generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
schema.go
1598 lines (1457 loc) 路 47.1 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package compile
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"path"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"unicode"
"unicode/utf8"
"github.com/alecthomas/types/optional"
"golang.org/x/exp/maps"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/packages"
"github.com/TBD54566975/ftl/backend/schema"
"github.com/TBD54566975/ftl/backend/schema/strcase"
"github.com/TBD54566975/ftl/internal/errors"
"github.com/TBD54566975/ftl/internal/goast"
)
var (
fset = token.NewFileSet()
contextIfaceType = once(func() *types.Interface {
return mustLoadRef("context", "Context").Type().Underlying().(*types.Interface) //nolint:forcetypeassert
})
errorIFaceType = once(func() *types.Interface {
return mustLoadRef("builtin", "error").Type().Underlying().(*types.Interface) //nolint:forcetypeassert
})
ftlCallFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.Call"
ftlFSMFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.FSM"
ftlTransitionFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.Transition"
ftlStartFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.Start"
ftlConfigFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.Config"
ftlSecretFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.Secret" //nolint:gosec
ftlPostgresDBFuncPath = "github.com/TBD54566975/ftl/go-runtime/ftl.PostgresDatabase"
ftlUnitTypePath = "github.com/TBD54566975/ftl/go-runtime/ftl.Unit"
ftlOptionTypePath = "github.com/TBD54566975/ftl/go-runtime/ftl.Option"
aliasFieldTag = "json"
)
// NativeNames is a map of top-level declarations to their native Go names.
type NativeNames map[schema.Node]string
// enumInterfaces is a map of type enum names to the interface that variants must conform to.
type enumInterfaces map[string]*types.Interface
func noEndColumnErrorf(pos token.Pos, format string, args ...interface{}) *schema.Error {
return tokenErrorf(pos, "", format, args...)
}
func tokenErrorf(pos token.Pos, tokenText string, format string, args ...interface{}) *schema.Error {
goPos := goPosToSchemaPos(pos)
endColumn := goPos.Column
if len(tokenText) > 0 {
endColumn += utf8.RuneCountInString(tokenText)
}
return schema.Errorf(goPosToSchemaPos(pos), endColumn, format, args...)
}
func errorf(node ast.Node, format string, args ...interface{}) *schema.Error {
pos, endCol := goNodePosToSchemaPos(node)
return schema.Errorf(pos, endCol, format, args...)
}
func tokenWrapf(pos token.Pos, tokenText string, err error, format string, args ...interface{}) *schema.Error {
goPos := goPosToSchemaPos(pos)
endColumn := goPos.Column
if len(tokenText) > 0 {
endColumn += utf8.RuneCountInString(tokenText)
}
return schema.Wrapf(goPos, endColumn, err, format, args...)
}
func wrapf(node ast.Node, err error, format string, args ...interface{}) *schema.Error {
pos, endCol := goNodePosToSchemaPos(node)
return schema.Wrapf(pos, endCol, err, format, args...)
}
type errorSet map[string]*schema.Error
func (e errorSet) add(err *schema.Error) {
e[err.Error()] = err
}
func (e errorSet) addAll(errs ...*schema.Error) {
for _, err := range errs {
e.add(err)
}
}
type ParseResult struct {
Module *schema.Module
NativeNames NativeNames
// Errors contains schema validation errors encountered during parsing.
Errors []*schema.Error
}
// ExtractModuleSchema statically parses Go FTL module source into a schema.Module.
func ExtractModuleSchema(dir string, sch *schema.Schema) (optional.Option[ParseResult], error) {
pkgs, err := packages.Load(&packages.Config{
Dir: dir,
Fset: fset,
Mode: packages.NeedName | packages.NeedFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports,
}, "./...")
if err != nil {
return optional.None[ParseResult](), err
}
if len(pkgs) == 0 {
return optional.None[ParseResult](), fmt.Errorf("no packages found in %q, does \"go mod tidy\" need to be run?", dir)
}
// Find module name
module := &schema.Module{}
merr := []error{}
schemaErrs := []*schema.Error{}
nativeNames := NativeNames{}
for _, pkg := range pkgs {
moduleName, ok := ftlModuleFromGoModule(pkg.PkgPath).Get()
if !ok {
return optional.None[ParseResult](), fmt.Errorf("package %q is not in the ftl namespace", pkg.PkgPath)
}
if len(strings.Split(pkg.PkgPath, "/")) > 2 {
// skip subpackages of a module
continue
}
module.Name = moduleName
if len(pkg.Errors) > 0 {
for _, perr := range pkg.Errors {
merr = append(merr, perr)
}
}
pctx := newParseContext(pkg, pkgs, module, sch)
err := extractTypeDecls(pctx)
if err != nil {
return optional.None[ParseResult](), err
}
for _, file := range pkg.Syntax {
err := goast.Visit(file, func(node ast.Node, next func() error) (err error) {
switch node := node.(type) {
case *ast.CallExpr:
visitCallExpr(pctx, node)
case *ast.File:
visitFile(pctx, node)
case *ast.FuncDecl:
verb := visitFuncDecl(pctx, node)
pctx.activeVerb = verb
err = next()
if err != nil {
return err
}
pctx.activeVerb = nil
return nil
case *ast.GenDecl:
visitGenDecl(pctx, node)
default:
}
return next()
})
if err != nil {
return optional.None[ParseResult](), err
}
}
for decl, nativeName := range pctx.nativeNames {
nativeNames[decl] = nativeName
}
if len(pctx.errors) > 0 {
schemaErrs = append(schemaErrs, maps.Values(pctx.errors)...)
}
}
if len(schemaErrs) > 0 {
schema.SortErrorsByPosition(schemaErrs)
return optional.Some(ParseResult{Errors: schemaErrs}), nil
}
if len(merr) > 0 {
return optional.None[ParseResult](), errors.Join(merr...)
}
return optional.Some(ParseResult{
NativeNames: nativeNames,
Module: module,
}), schema.ValidateModule(module)
}
// extractTypeDecls traverses the package's AST and extracts type declarations (type aliases and enums)
//
// This allows us to know if a type is a type alias or an enum regardless of ordering when visiting each ast node.
// - The Decls get added to the pctx's module, nativeNames and enumInterfaces.
// - We only want to do a simple pass, so we do not resolve references to other types. This means the TypeAlias and Enum decls have Type = nil
// - This get's filled in with the next pass
func extractTypeDecls(pctx *parseContext) error {
for _, file := range pctx.pkg.Syntax {
err := goast.Visit(file, func(aNode ast.Node, next func() error) (err error) {
node, ok := aNode.(*ast.GenDecl)
if !ok || node.Tok != token.TYPE {
return next()
}
extractTypeDeclsForNode(pctx, node)
return next()
})
if err != nil {
return err
}
}
return nil
}
func extractTypeDeclsForNode(pctx *parseContext, node *ast.GenDecl) {
directives, parseErr := parseDirectives(node, fset, node.Doc)
if parseErr != nil {
// errors collected when visiting all nodes in the next pass
return
}
foundDeclType := optional.None[string]()
for _, dir := range directives {
if len(node.Specs) != 1 {
// errors handled on next pass
continue
}
t, ok := node.Specs[0].(*ast.TypeSpec)
if !ok {
continue
}
aType := pctx.pkg.Types.Scope().Lookup(t.Name.Name)
nativeName := aType.Pkg().Name() + "." + aType.Name()
switch dir := dir.(type) {
case *directiveEnum:
typ := pctx.pkg.TypesInfo.TypeOf(t.Type)
switch typ.Underlying().(type) {
case *types.Basic:
enum := &schema.Enum{
Pos: goPosToSchemaPos(node.Pos()),
Comments: visitComments(node.Doc),
Name: strcase.ToUpperCamel(t.Name.Name),
Type: nil, //TODO: explain
Export: dir.IsExported(),
}
pctx.module.Decls = append(pctx.module.Decls, enum)
pctx.nativeNames[enum] = nativeName
case *types.Interface:
enum := &schema.Enum{
Pos: goPosToSchemaPos(node.Pos()),
Comments: visitComments(node.Doc),
Name: strcase.ToUpperCamel(t.Name.Name),
Export: dir.IsExported(),
}
if typ, ok := typ.(*types.Interface); ok {
pctx.nativeNames[enum] = nativeName
pctx.module.Decls = append(pctx.module.Decls, enum)
pctx.enumInterfaces[t.Name.Name] = typ
} else {
pctx.errors.add(errorf(node, "expected interface for type enum but got %q", typ))
}
}
foundDeclType = optional.Some("enum")
case *directiveTypeAlias:
alias := &schema.TypeAlias{
Pos: goPosToSchemaPos(node.Pos()),
Comments: visitComments(node.Doc),
Name: strcase.ToUpperCamel(t.Name.Name),
Export: dir.IsExported(),
Type: nil, //TODO: explain
}
pctx.module.Decls = append(pctx.module.Decls, alias)
pctx.nativeNames[alias] = nativeName
foundDeclType = optional.Some("type alias")
case *directiveData, *directiveIngress, *directiveVerb, *directiveCronJob:
continue
}
if foundDeclType, ok := foundDeclType.Get(); ok {
if len(directives) > 1 {
pctx.errors.add(errorf(node, "only one directive expected for %v", foundDeclType))
}
break
}
}
}
func visitCallExpr(pctx *parseContext, node *ast.CallExpr) {
_, fn := deref[*types.Func](pctx.pkg, node.Fun)
if fn == nil {
return
}
switch fn.FullName() {
case ftlCallFuncPath:
parseCall(pctx, node)
case ftlConfigFuncPath, ftlSecretFuncPath:
// Secret/config declaration: ftl.Config[<type>](<name>)
parseConfigDecl(pctx, node, fn)
case ftlFSMFuncPath:
parseFSMDecl(pctx, node)
case ftlPostgresDBFuncPath:
parseDatabaseDecl(pctx, node, schema.PostgresDatabaseType)
}
}
func parseCall(pctx *parseContext, node *ast.CallExpr) {
if pctx.activeVerb == nil {
return
}
if len(node.Args) != 3 {
pctx.errors.add(errorf(node, "call must have exactly three arguments"))
return
}
ref := parseVerbRef(pctx, node.Args[1])
if ref == nil {
ref = parseSelectorRef(node.Args[1])
var suffix string
if pctx.schema.ResolveRef(ref) != nil {
suffix = ", does it need to be exported?"
}
if sel, ok := node.Args[1].(*ast.SelectorExpr); ok {
pctx.errors.add(errorf(node.Args[1], "call first argument must be a function but is an unresolved reference to %s.%s%s", sel.X, sel.Sel, suffix))
}
pctx.errors.add(errorf(node.Args[1], "call first argument must be a function in an ftl module%s", suffix))
return
}
pctx.activeVerb.AddCall(ref)
}
func parseSelectorRef(node ast.Expr) *schema.Ref {
sel, ok := node.(*ast.SelectorExpr)
if !ok {
return nil
}
ident, ok := sel.X.(*ast.Ident)
if !ok {
return nil
}
return &schema.Ref{
Pos: goPosToSchemaPos(node.Pos()),
Module: ident.Name,
Name: strcase.ToLowerCamel(sel.Sel.Name),
}
}
func parseVerbRef(pctx *parseContext, node ast.Expr) *schema.Ref {
_, verbFn := deref[*types.Func](pctx.pkg, node)
if verbFn == nil {
return nil
}
moduleName, ok := ftlModuleFromGoModule(verbFn.Pkg().Path()).Get()
if !ok {
return nil
}
return &schema.Ref{
Pos: goPosToSchemaPos(node.Pos()),
Module: moduleName,
Name: strcase.ToLowerCamel(verbFn.Name()),
}
}
func parseFSMDecl(pctx *parseContext, node *ast.CallExpr) {
var literal *ast.BasicLit
if len(node.Args) > 0 {
literal, _ = node.Args[0].(*ast.BasicLit)
}
if literal == nil || literal.Kind != token.STRING {
pctx.errors.add(errorf(node, "first argument to an FSM declaration must be the name as a string literal"))
return
}
name, err := strconv.Unquote(literal.Value)
if err != nil {
panic(err) // Should never happen
}
if !schema.ValidateName(name) {
pctx.errors.add(errorf(node, "FSM names must be valid identifiers"))
}
fsm := &schema.FSM{
Pos: goPosToSchemaPos(node.Pos()),
Name: name,
}
pctx.module.Decls = append(pctx.module.Decls, fsm)
for _, arg := range node.Args[1:] {
call, ok := arg.(*ast.CallExpr)
if !ok {
pctx.errors.add(errorf(arg, "expected call to Start or Transition"))
continue
}
_, fn := deref[*types.Func](pctx.pkg, call.Fun)
if fn == nil {
pctx.errors.add(errorf(call, "expected call to Start or Transition"))
continue
}
parseFSMTransition(pctx, call, fn, fsm)
}
}
// Parse a Start or Transition call in an FSM declaration and add it to the FSM.
func parseFSMTransition(pctx *parseContext, node *ast.CallExpr, fn *types.Func, fsm *schema.FSM) {
refs := make([]*schema.Ref, len(node.Args))
for i, arg := range node.Args {
ref := parseVerbRef(pctx, arg)
if ref == nil {
pctx.errors.add(errorf(arg, "expected a reference to a sink"))
return
}
refs[i] = ref
}
switch fn.FullName() {
case ftlStartFuncPath:
if len(refs) != 1 {
pctx.errors.add(errorf(node, "expected one reference to a sink"))
return
}
fsm.Start = append(fsm.Start, refs...)
case ftlTransitionFuncPath:
if len(refs) != 2 {
pctx.errors.add(errorf(node, "expected two references to sinks"))
return
}
fsm.Transitions = append(fsm.Transitions, &schema.FSMTransition{
Pos: goPosToSchemaPos(node.Pos()),
From: refs[0],
To: refs[1],
})
default:
pctx.errors.add(errorf(node, "expected call to Start or Transition"))
}
}
func parseConfigDecl(pctx *parseContext, node *ast.CallExpr, fn *types.Func) {
var literal *ast.BasicLit
if len(node.Args) > 0 {
literal, _ = node.Args[0].(*ast.BasicLit)
}
if literal == nil || literal.Kind != token.STRING {
pctx.errors.add(errorf(node, "first argument to config and secret declarations must be the name as a string literal"))
return
}
name, err := strconv.Unquote(literal.Value)
if err != nil {
panic(err) // Should never happen
}
if !schema.ValidateName(name) {
pctx.errors.add(errorf(node, "config and secret names must be valid identifiers"))
}
index := node.Fun.(*ast.IndexExpr) //nolint:forcetypeassert
// Type parameter
tp := pctx.pkg.TypesInfo.Types[index.Index].Type
st, ok := visitType(pctx, index.Index.Pos(), tp, false).Get()
if !ok {
pctx.errors.add(errorf(index.Index, "unsupported type %q", tp))
return
}
// Add the declaration to the module.
var decl schema.Decl
if fn.FullName() == ftlConfigFuncPath {
decl = &schema.Config{
Pos: goPosToSchemaPos(node.Pos()),
Name: name,
Type: st,
}
} else {
decl = &schema.Secret{
Pos: goPosToSchemaPos(node.Pos()),
Name: name,
Type: st,
}
}
// Check for duplicates
_, endCol := goNodePosToSchemaPos(node)
for _, d := range pctx.module.Decls {
switch fn.FullName() {
case ftlConfigFuncPath:
c, ok := d.(*schema.Config)
if ok && c.Name == name && c.Type.String() == st.String() {
pctx.errors.add(errorf(node, "duplicate config declaration at %d:%d-%d", c.Pos.Line, c.Pos.Column, endCol))
return
}
case ftlSecretFuncPath:
s, ok := d.(*schema.Secret)
if ok && s.Name == name && s.Type.String() == st.String() {
pctx.errors.add(errorf(node, "duplicate secret declaration at %d:%d-%d", s.Pos.Line, s.Pos.Column, endCol))
return
}
default:
}
}
pctx.module.Decls = append(pctx.module.Decls, decl)
}
func parseDatabaseDecl(pctx *parseContext, node *ast.CallExpr, dbType string) {
var name string
if len(node.Args) == 1 {
if literal, ok := node.Args[0].(*ast.BasicLit); ok && literal.Kind == token.STRING {
var err error
name, err = strconv.Unquote(literal.Value)
if err != nil {
pctx.errors.add(wrapf(node, err, ""))
return
}
}
}
if name == "" {
pctx.errors.add(errorf(node, "config and secret declarations must have a single string literal argument"))
return
}
// Check for duplicates
_, endCol := goNodePosToSchemaPos(node)
for _, d := range pctx.module.Decls {
db, ok := d.(*schema.Database)
if ok && db.Name == name {
pctx.errors.add(errorf(node, "duplicate database declaration at %d:%d-%d", db.Pos.Line, db.Pos.Column, endCol))
return
}
}
decl := &schema.Database{
Pos: goPosToSchemaPos(node.Pos()),
Name: name,
Type: dbType,
}
pctx.module.Decls = append(pctx.module.Decls, decl)
}
func visitFile(pctx *parseContext, node *ast.File) {
if node.Doc == nil {
return
}
pctx.module.Comments = visitComments(node.Doc)
}
func isType[T types.Type](t types.Type) bool {
if _, ok := t.(*types.Named); ok {
t = t.Underlying()
}
_, ok := t.(T)
return ok
}
func checkSignature(pctx *parseContext, node *ast.FuncDecl, sig *types.Signature) (req, resp optional.Option[*types.Var]) {
params := sig.Params()
results := sig.Results()
if params.Len() > 2 {
pctx.errors.add(errorf(node, "must have at most two parameters (context.Context, struct)"))
}
if params.Len() == 0 {
pctx.errors.add(errorf(node, "first parameter must be context.Context"))
} else if !types.AssertableTo(contextIfaceType(), params.At(0).Type()) {
pctx.errors.add(tokenErrorf(params.At(0).Pos(), params.At(0).Name(), "first parameter must be of type context.Context but is %s", params.At(0).Type()))
}
if params.Len() == 2 {
if !isType[*types.Struct](params.At(1).Type()) {
pctx.errors.add(tokenErrorf(params.At(1).Pos(), params.At(1).Name(), "second parameter must be a struct but is %s", params.At(1).Type()))
}
if params.At(1).Type().String() == ftlUnitTypePath {
pctx.errors.add(tokenErrorf(params.At(1).Pos(), params.At(1).Name(), "second parameter must not be ftl.Unit"))
}
req = optional.Some(params.At(1))
}
if results.Len() > 2 {
pctx.errors.add(errorf(node, "must have at most two results (struct, error)"))
}
if results.Len() == 0 {
pctx.errors.add(errorf(node, "must at least return an error"))
} else if !types.AssertableTo(errorIFaceType(), results.At(results.Len()-1).Type()) {
pctx.errors.add(tokenErrorf(results.At(results.Len()-1).Pos(), results.At(results.Len()-1).Name(), "must return an error but is %s", results.At(0).Type()))
}
if results.Len() == 2 {
if !isType[*types.Struct](results.At(0).Type()) {
pctx.errors.add(tokenErrorf(results.At(0).Pos(), results.At(0).Name(), "first result must be a struct but is %s", results.At(0).Type()))
}
if results.At(1).Type().String() == ftlUnitTypePath {
pctx.errors.add(tokenErrorf(results.At(1).Pos(), results.At(1).Name(), "second result must not be ftl.Unit"))
}
resp = optional.Some(results.At(0))
}
return req, resp
}
func goPosToSchemaPos(pos token.Pos) schema.Position {
p := fset.Position(pos)
return schema.Position{Filename: p.Filename, Line: p.Line, Column: p.Column, Offset: p.Offset}
}
func goNodePosToSchemaPos(node ast.Node) (schema.Position, int) {
p := fset.Position(node.Pos())
return schema.Position{Filename: p.Filename, Line: p.Line, Column: p.Column, Offset: p.Offset}, fset.Position(node.End()).Column
}
func visitGenDecl(pctx *parseContext, node *ast.GenDecl) {
switch node.Tok {
case token.TYPE:
directives, err := parseDirectives(node, fset, node.Doc)
if err != nil {
pctx.errors.add(err)
}
maybeVisitTypeEnumVariant(pctx, node, directives)
if node.Doc == nil {
return
}
for _, dir := range directives {
switch dir.(type) {
case *directiveVerb, *directiveData, *directiveEnum, *directiveTypeAlias:
if len(node.Specs) != 1 {
pctx.errors.add(errorf(node, "error parsing ftl directive: expected "+
"exactly one type declaration"))
return
}
if pctx.module.Name == "" {
pctx.module.Name = pctx.pkg.Name
} else if pctx.module.Name != pctx.pkg.Name && strings.TrimPrefix(pctx.pkg.Name, "ftl/") != pctx.module.Name {
pctx.errors.add(errorf(node, "ftl directive must be in the module package"))
return
}
if t, ok := node.Specs[0].(*ast.TypeSpec); ok {
isExported := false
if exportableDir, ok := dir.(exportable); ok {
isExported = exportableDir.IsExported()
}
// We have already collected enum and type alias declarations in extractTypeDecls
// On this second pass we can visit deeper and pull out the type information
typ := pctx.pkg.TypesInfo.TypeOf(t.Type)
if _, ok := dir.(*directiveEnum); ok {
enumOption, enumInterface := pctx.getEnumForTypeName(t.Name.Name)
enum, ok := enumOption.Get()
if !ok {
// This case can be reached if a type is both an enum and a typealias.
// Error is already reported in extractTypeDecls
return
}
switch typ.Underlying().(type) {
case *types.Basic:
if sType, ok := visitType(pctx, node.Pos(), typ, isExported).Get(); ok {
enum.Type = sType
} else {
pctx.errors.add(errorf(node, "unsupported type %q for value enum",
pctx.pkg.TypesInfo.TypeOf(t.Type).Underlying()))
}
case *types.Interface:
if !enumInterface.Ok() {
pctx.errors.add(errorf(node, "could not find interface for type enum"))
}
}
} else if _, ok := dir.(*directiveTypeAlias); ok {
decl, ok := pctx.getDeclForTypeName(t.Name.Name)
if !ok {
pctx.errors.add(errorf(node, "could not find type alias declaration for %q", t.Name.Name))
return
}
typeAlias, ok := decl.(*schema.TypeAlias)
if !ok {
// This case can be reached if a type is both an enum and a typealias.
// Error is already reported in extractTypeDecls
return
}
if sType, ok := visitType(pctx, node.Pos(), typ, isExported).Get(); ok {
typeAlias.Type = sType
} else {
pctx.errors.add(errorf(node, "unsupported type %q for type alias", typ.Underlying()))
}
} else {
visitType(pctx, node.Pos(), pctx.pkg.TypesInfo.Defs[t.Name].Type(), isExported)
}
}
case *directiveIngress, *directiveCronJob:
}
}
return
case token.CONST:
var typ ast.Expr
for i, s := range node.Specs {
v, ok := s.(*ast.ValueSpec)
if !ok {
continue
}
// In an iota enum, only the first value has a type.
// Hydrate this to subsequent values so we can associate them with the enum.
if i == 0 && isIotaEnum(v) {
typ = v.Type
} else if v.Type == nil {
v.Type = typ
}
visitValueSpec(pctx, v)
}
return
default:
return
}
}
func maybeVisitTypeEnumVariant(pctx *parseContext, node *ast.GenDecl, directives []directive) {
if len(node.Specs) != 1 {
return
}
// `type NAME TYPE` e.g. type Scalar string
t, ok := node.Specs[0].(*ast.TypeSpec)
if !ok {
return
}
typ := pctx.pkg.TypesInfo.TypeOf(t.Type)
if typeInterface, ok := typ.Underlying().(*types.Interface); ok {
// Type enums should not count as variants of themselves
pctx.enumInterfaces[t.Name.Name] = typeInterface
return
}
enumVariant := &schema.EnumVariant{
Pos: goPosToSchemaPos(node.Pos()),
Comments: visitComments(node.Doc),
Name: strcase.ToUpperCamel(t.Name.Name),
}
matchedEnumNames := []string{}
// iterate in a predictable way to make sure we are not flipflopping between builds of which type enum counts as first
allEnumNames := maps.Keys(pctx.enumInterfaces)
slices.Sort(allEnumNames)
for _, enumName := range allEnumNames {
interfaceNode := pctx.enumInterfaces[enumName]
// If the type declared is an enum variant, then it must implement
// the interface of a type enum
named, ok := pctx.pkg.Types.Scope().Lookup(t.Name.Name).Type().(*types.Named)
if !ok {
continue
}
if !types.Implements(named, interfaceNode) {
continue
}
enumOption, _ := pctx.getEnumForTypeName(enumName)
enum, ok := enumOption.Get()
if !ok {
pctx.errors.add(errorf(node, "could not find enum called %s", enumName))
continue
}
matchedEnumNames = append(matchedEnumNames, enumName)
if len(matchedEnumNames) > 1 {
continue
}
if enum.VariantForName(enumVariant.Name).Ok() {
continue
}
// If any directives on this node are exported, then the
// enum variant node is considered exported. Also, if the
// parent enum itself is exported, then all its variants
// should transitively also be exported.
isExported := enum.IsExported()
for _, dir := range directives {
if exportableDir, ok := dir.(exportable); ok {
if enum.Export && !exportableDir.IsExported() {
pctx.errors.add(errorf(node, "parent enum %q is exported, but directive %q on %q is not: all variants of exported enums that have a directive must be explicitly exported as well", enumName, exportableDir, t.Name.Name))
}
isExported = exportableDir.IsExported()
}
}
vType, ok := visitTypeValue(pctx, named, t.Type, nil, isExported).Get()
if !ok {
pctx.errors.add(errorf(node, "unsupported type %q for type enum variant", named))
continue
}
enumVariant.Value = vType
enum.Variants = append(enum.Variants, enumVariant)
pctx.nativeNames[enumVariant] = named.Obj().Pkg().Name() + "." + named.Obj().Name()
}
if len(matchedEnumNames) > 1 {
slices.Sort(matchedEnumNames)
pctx.errors.add(errorf(node, "type can not be a variant of more than 1 type enums (%s)", strings.Join(matchedEnumNames, ", ")))
}
}
func visitTypeValue(pctx *parseContext, named *types.Named, tnode ast.Expr, index types.Type, isExported bool) optional.Option[*schema.TypeValue] {
switch typ := tnode.(type) {
// Selector expression e.g. ftl.Unit, ftl.Option, foo.Bar
case *ast.SelectorExpr:
var ident *ast.Ident
var ok bool
if ident, ok = typ.X.(*ast.Ident); !ok {
return optional.None[*schema.TypeValue]()
}
for _, im := range maps.Values(pctx.pkg.Imports) {
if im.Name != ident.Name {
continue
}
switch im.ID + "." + typ.Sel.Name {
case "time.Time":
return optional.Some(&schema.TypeValue{
Pos: goPosToSchemaPos(tnode.Pos()),
Value: &schema.Time{},
})
case ftlUnitTypePath:
return optional.Some(&schema.TypeValue{
Pos: goPosToSchemaPos(tnode.Pos()),
Value: &schema.Unit{},
})
case ftlOptionTypePath:
if index == nil {
return optional.None[*schema.TypeValue]()
}
if vt, ok := visitType(pctx, tnode.Pos(), index, isExported).Get(); ok {
return optional.Some(&schema.TypeValue{
Pos: goPosToSchemaPos(tnode.Pos()),
Value: &schema.Optional{
Pos: goPosToSchemaPos(tnode.Pos()),
Type: vt,
},
})
}
default: // Data ref
externalModuleName, ok := ftlModuleFromGoModule(im.ID).Get()
if !ok {
pctx.errors.add(errorf(tnode, "package %q is not in the ftl namespace", im.ID))
return optional.None[*schema.TypeValue]()
}
return optional.Some(&schema.TypeValue{
Pos: goPosToSchemaPos(tnode.Pos()),
Value: &schema.Ref{
Pos: goPosToSchemaPos(tnode.Pos()),
Module: externalModuleName,
Name: typ.Sel.Name,
},
})
}
}
case *ast.IndexExpr: // Generic type, e.g. ftl.Option[string]
if se, ok := typ.X.(*ast.SelectorExpr); ok {
return visitTypeValue(pctx, named, se, pctx.pkg.TypesInfo.TypeOf(typ.Index), isExported)
}
default:
if typ, ok := visitType(pctx, tnode.Pos(), named, isExported).Get(); ok {
return optional.Some(&schema.TypeValue{Value: typ})
} else {
pctx.errors.add(errorf(tnode, "unsupported type %q for type enum variant", named))
}
}
return optional.None[*schema.TypeValue]()
}
func visitValueSpec(pctx *parseContext, node *ast.ValueSpec) {
var enum *schema.Enum
i, ok := node.Type.(*ast.Ident)
if !ok {
return
}
enumOption, enumInterface := pctx.getEnumForTypeName(i.Name)
enum, ok = enumOption.Get()
if !ok {
return
}
if enumInterface.Ok() {
pctx.errors.add(errorf(node, "cannot attach enum value to %s because it a type enum", enum.Name))
return
}
maybeErrorOnInvalidEnumMixing(pctx, node, enum.Name)
c, ok := pctx.pkg.TypesInfo.Defs[node.Names[0]].(*types.Const)
if !ok {
pctx.errors.add(errorf(node, "could not extract enum %s: expected exactly one variant name", enum.Name))
return
}
if value, ok := visitConst(pctx, c).Get(); ok {
variant := &schema.EnumVariant{
Pos: goPosToSchemaPos(c.Pos()),
Comments: visitComments(node.Doc),
Name: strcase.ToUpperCamel(c.Id()),
Value: value,
}
enum.Variants = append(enum.Variants, variant)
} else {
pctx.errors.add(errorf(node, "unsupported type %q for enum variant %q", c.Type(), c.Name()))
}
}
// maybeErrorOnInvalidEnumMixing ensures value enums are not set as variants of type enums.
// How this gets parsed:
//
// //ftl:enum
// type TypeEnum interface { typeEnum() }
//
// type BadValueEnum int
//
// // This line causes BadValueEnum to be parsed as a TypeEnum variant. At this point, we
// // cannot determine if BadValueEnum is intended to be a value enum, so we must treat it
// // as any other type enum variant.
// func (BadValueEnum) typeEnum() {}
//
// // This line will error because this is where we find out that BadValueEnum is intended
// // to be a value enum, but value enums cannot be variants of type enums. BadValueEnum
// // is not in pctx.enums.
// const A BadValueEnum = 1
func maybeErrorOnInvalidEnumMixing(pctx *parseContext, node *ast.ValueSpec, enumName string) {
for _, decl := range pctx.module.Decls {
enum, ok := decl.(*schema.Enum)
if !ok {
continue
}
for _, variant := range enum.Variants {
if variant.Name == enumName {
pctx.errors.add(errorf(node, "cannot attach enum value to %s because it is a variant of type enum %s, not a value enum", enumName, enum.Name))
}
}
}
}
func visitFuncDecl(pctx *parseContext, node *ast.FuncDecl) (verb *schema.Verb) {
if node.Doc == nil {
return nil
}
directives, err := parseDirectives(node, fset, node.Doc)
if err != nil {
pctx.errors.add(err)
}
var metadata []schema.Metadata
isVerb := false
isExported := false
for _, dir := range directives {
switch dir := dir.(type) {
case *directiveVerb:
isVerb = true
isExported = dir.Export
if pctx.module.Name == "" {
pctx.module.Name = pctx.pkg.Name
} else if pctx.module.Name != pctx.pkg.Name {
pctx.errors.add(errorf(node, "function verb directive must be in the module package"))
}
case *directiveIngress:
isVerb = true
isExported = true
typ := dir.Type
if typ == "" {
typ = "http"
}
metadata = append(metadata, &schema.MetadataIngress{
Pos: dir.Pos,
Type: typ,
Method: dir.Method,
Path: dir.Path,
})
case *directiveCronJob:
isVerb = true
isExported = false
metadata = append(metadata, &schema.MetadataCronJob{
Pos: dir.Pos,
Cron: dir.Cron,
})
case *directiveData, *directiveEnum, *directiveTypeAlias:
pctx.errors.add(errorf(node, "unexpected directive %T", dir))
}
}
if !isVerb {
return nil
}
for _, name := range pctx.nativeNames {
if name == node.Name.Name {
pctx.errors.add(noEndColumnErrorf(node.Pos(), "duplicate verb name %q", node.Name.Name))
return nil
}
}
fnt := pctx.pkg.TypesInfo.Defs[node.Name].(*types.Func) //nolint:forcetypeassert