-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
2774 lines (2497 loc) · 88.8 KB
/
generator.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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generate
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"go/types"
"io"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"github.com/TiagoMalhadas/xcweaver/internal/files"
"github.com/TiagoMalhadas/xcweaver/internal/tool"
"github.com/TiagoMalhadas/xcweaver/runtime/codegen"
"github.com/TiagoMalhadas/xcweaver/runtime/colors"
"github.com/TiagoMalhadas/xcweaver/runtime/version"
"golang.org/x/exp/maps"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/typeutil"
)
// TODO(rgrandl): Modify the generator code to use only the types package. Right
// now we are doing code generation relying both on the types and ast packages,
// which can be confusing and also we might do unnecessary work.
const (
generatedCodeFile = "weaver_gen.go"
Usage = `Generate code for a XCWeaver application.
Usage:
xcweaver generate [packages]
Description:
"xcweaver generate" generates code for the XCWeaver applications in the
provided packages. For example, "xcweaver generate . ./foo" will generate code
for the XCWeaver applications in the current directory and in the ./foo
directory. For every package, the generated code is placed in a weaver_gen.go
file in the package's directory. For example, "xcweaver generate . ./foo" will
create ./weaver_gen.go and ./foo/weaver_gen.go.
You specify packages for "xcweaver generate" in the same way you specify
packages for go build, go test, go vet, etc. See "go help packages" for more
information.
Rather than invoking "xcweaver generate" directly, you can place a line of the
following form in one of the .go files in the package:
//go:generate xcweaver generate
and then use the normal "go generate" command.
Examples:
# Generate code for the package in the current directory.
xcweaver generate
# Same as "xcweaver generate".
xcweaver generate .
# Generate code for the package in the ./foo directory.
xcweaver generate ./foo
# Generate code for all packages in all subdirectories of current directory.
xcweaver generate ./...`
)
// Options controls the operation of Generate.
type Options struct {
// If non-nil, use the specified function to report warnings.
Warn func(error)
}
// Generate generates Service Weaver code for the specified packages.
// The list of supplied packages are treated similarly to the arguments
// passed to "go build" (see "go help packages" for details).
func Generate(dir string, pkgs []string, opt Options) error {
if opt.Warn == nil {
opt.Warn = func(err error) { fmt.Fprintln(os.Stderr, err) }
}
fset := token.NewFileSet()
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedSyntax | packages.NeedImports | packages.NeedTypes | packages.NeedTypesInfo,
Dir: dir,
Fset: fset,
ParseFile: parseNonWeaverGenFile,
BuildFlags: []string{"--tags=ignoreWeaverGen"},
}
pkgList, err := packages.Load(cfg, pkgs...)
if err != nil {
return fmt.Errorf("packages.Load: %w", err)
}
var automarshals typeutil.Map
var errs []error
for _, pkg := range pkgList {
g, err := newGenerator(opt, pkg, fset, &automarshals)
if err != nil {
errs = append(errs, err)
continue
}
if err := g.generate(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// parseNonWeaverGenFile parses a Go file, except for weaver_gen.go files whose
// contents are ignored since those contents may reference types that no longer
// exist.
func parseNonWeaverGenFile(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
if filepath.Base(filename) == generatedCodeFile {
return parser.ParseFile(fset, filename, src, parser.PackageClauseOnly)
}
return parser.ParseFile(fset, filename, src, parser.ParseComments|parser.DeclarationErrors)
}
type generator struct {
pkg *packages.Package
tset *typeSet
fileset *token.FileSet
components []*component
sizeFuncNeeded typeutil.Map // types that need a serviceweaver_size_* function
generated typeutil.Map // memo cache for generateEncDecMethodsFor
}
// errorf is like fmt.Errorf but prefixes the error with the provided position.
func errorf(fset *token.FileSet, pos token.Pos, format string, args ...interface{}) error {
// Rewrite the position's filename relative to the current directory. This
// replaces long filenames like "/home/foo/TiagoMalhadas/xcweaver/weaver.go"
// with much shorter filenames like "./weaver.go".
position := fset.Position(pos)
if cwd, err := filepath.Abs("."); err == nil {
if filename, err := filepath.Rel(cwd, position.Filename); err == nil {
position.Filename = filename
}
}
prefix := position.String()
if colors.Enabled() {
// Color the filename red when colors are enabled.
prefix = fmt.Sprintf("%s%v%s", colors.Color256(160), position, colors.Reset)
}
return fmt.Errorf("%s: %w", prefix, fmt.Errorf(format, args...))
}
func newGenerator(opt Options, pkg *packages.Package, fset *token.FileSet, automarshals *typeutil.Map) (*generator, error) {
// Abort if there were any errors loading the package.
var errs []error
for _, err := range pkg.Errors {
errs = append(errs, err)
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
// Search every file in the package for types that embed the
// weaver.AutoMarshal struct.
tset := newTypeSet(pkg, automarshals, &typeutil.Map{})
for _, file := range pkg.Syntax {
filename := fset.Position(file.Package).Filename
if filepath.Base(filename) == generatedCodeFile {
// Ignore weaver_gen.go files.
continue
}
ts, err := findAutoMarshals(pkg, file)
if err != nil {
errs = append(errs, err)
continue
}
for _, t := range ts {
tset.automarshalCandidates.Set(t, struct{}{})
}
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
// Just because a type embeds weaver.AutoMarshal doesn't mean we can
// automatically marshal it. Some types, like `struct { x chan int }`, are
// just not serializable. Here, we check that every type that embeds
// weaver.AutoMarshal is actually serializable.
for _, t := range tset.automarshalCandidates.Keys() {
n := t.(*types.Named)
if err := errors.Join(tset.checkSerializable(n)...); err != nil {
errs = append(errs, errorf(fset, n.Obj().Pos(), "type %v is not serializable\n%w", t, err))
continue
}
tset.automarshals.Set(t, struct{}{})
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
// Find and process all components.
components := map[string]*component{}
for _, file := range pkg.Syntax {
filename := fset.Position(file.Package).Filename
if filepath.Base(filename) == generatedCodeFile {
// Ignore weaver_gen.go files.
continue
}
fileComponents, err := findComponents(opt, pkg, file, tset)
if err != nil {
errs = append(errs, err)
continue
}
for _, c := range fileComponents {
// Check for component duplicates, two components that embed the
// same weaver.Implements[T].
//
// TODO(mwhittaker): This code relies on the fact that a component
// interface and component implementation have to be in the same
// package. If we lift this requirement, then this code will break.
if existing, ok := components[c.fullIntfName()]; ok {
errs = append(errs, errorf(pkg.Fset, c.impl.Obj().Pos(),
"Duplicate implementation for component %s, other declaration: %v",
c.fullIntfName(), fset.Position(existing.impl.Obj().Pos())))
continue
}
components[c.fullIntfName()] = c
}
}
// Find method attributes.
for _, file := range pkg.Syntax {
filename := fset.Position(file.Package).Filename
if filepath.Base(filename) == generatedCodeFile {
// Ignore weaver_gen.go files.
continue
}
if err := findMethodAttributes(pkg, file, components); err != nil {
errs = append(errs, err)
}
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
return &generator{
pkg: pkg,
tset: tset,
fileset: fset,
components: maps.Values(components),
}, nil
}
// findComponents returns the components in the provided file. For example,
// findComponents will find and return the following component.
//
// type something struct {
// weaver.Implements[SomeComponentType]
// ...
// }
func findComponents(opt Options, pkg *packages.Package, f *ast.File, tset *typeSet) ([]*component, error) {
var components []*component
var errs []error
for _, d := range f.Decls {
gendecl, ok := d.(*ast.GenDecl)
if !ok || gendecl.Tok != token.TYPE {
continue
}
for _, spec := range gendecl.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
component, err := extractComponent(opt, pkg, f, tset, ts)
if err != nil {
errs = append(errs, err)
continue
}
if component != nil {
components = append(components, component)
}
}
}
return components, errors.Join(errs...)
}
func findMethodAttributes(pkg *packages.Package, f *ast.File, components map[string]*component) error {
// Look for declarations of the form:
// var _ weaver.NotRetriable = Component.Method
var errs []error
for _, decl := range f.Decls {
gendecl, ok := decl.(*ast.GenDecl)
if !ok || gendecl.Tok != token.VAR {
continue
}
for _, spec := range gendecl.Specs {
valspec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
typeAndValue, ok := pkg.TypesInfo.Types[valspec.Type]
if !ok {
continue
}
t := typeAndValue.Type
if !isWeaverNotRetriable(t) {
continue
}
for _, val := range valspec.Values {
// We allow non-blank vars for uniformity.
comp, method, ok := findComponentMethod(pkg, components, val)
if !ok {
errs = append(errs, errorf(pkg.Fset, valspec.Pos(), "xcweaver.NonRetriable should only be assigned a value that identifies a method of a component implemented by this package"))
continue
}
if comp.noretry == nil {
comp.noretry = map[string]struct{}{}
}
comp.noretry[method] = struct{}{}
}
}
}
return errors.Join(errs...)
}
// findComponentMethod returns the component and method if val is an expression of
// the form C.M where C is a component listed in components and C has a method named M.
func findComponentMethod(pkg *packages.Package, components map[string]*component, val ast.Expr) (*component, string, bool) {
sel, ok := val.(*ast.SelectorExpr)
if !ok {
return nil, "", false
}
ctypeval, ok := pkg.TypesInfo.Types[sel.X]
if !ok {
return nil, "", false
}
ctype, ok := ctypeval.Type.(*types.Named)
if !ok {
return nil, "", false
}
cname := fullName(ctype)
c, ok := components[cname]
if !ok {
return nil, "", false
}
method := sel.Sel.Name
for _, m := range c.methods() {
if m.Name() == method {
return c, method, true
}
}
return nil, "", false
}
// findAutoMarshals returns the types in the provided file which embed the
// weaver.AutoMarshal struct.
func findAutoMarshals(pkg *packages.Package, f *ast.File) ([]*types.Named, error) {
var automarshals []*types.Named
var errs []error
for _, decl := range f.Decls {
gendecl, ok := decl.(*ast.GenDecl)
if !ok || gendecl.Tok != token.TYPE {
// This is not a type declaration.
continue
}
// Recall that a type declaration can have multiple type specs. We have
// to iterate over all of them. For example:
//
// type (
// a struct{} // Spec 1
// b struct{} // Spec 2
// )
for _, spec := range gendecl.Specs {
typespec, ok := spec.(*ast.TypeSpec)
if !ok {
panic(errorf(pkg.Fset, spec.Pos(), "type declaration has non-TypeSpec spec: %v", spec))
}
// Extract the type's name.
def, ok := pkg.TypesInfo.Defs[typespec.Name]
if !ok {
panic(errorf(pkg.Fset, spec.Pos(), "name %v not found", typespec.Name))
}
n, ok := def.Type().(*types.Named)
if !ok {
// For type aliases like `type Int = int`, Int has type int and
// not type Named. We ignore these.
continue
}
// Check if the type of the expression is struct.
t, ok := pkg.TypesInfo.Types[typespec.Type].Type.(*types.Struct)
if !ok {
continue
}
// Check for an embedded weaver.AutoMarshal field.
automarshal := false
for i := 0; i < t.NumFields(); i++ {
f := t.Field(i)
if f.Embedded() && isWeaverAutoMarshal(f.Type()) {
automarshal = true
break
}
}
if !automarshal {
continue
}
// Ignore generic types. Generic types don't play well with
// embedded AutoMarshals. For example, consider the following type
// declaration:
//
// type Register[A any] struct {
// weaver.AutoMarshal
// a A
// }
//
// Is Register[A] serializable? It depends on A. Plus, we cannot
// really generate WeaverMarshal and WeaverUnmarshal methods for
// specific instantiations of Register[A]. Because of these
// complications, we ignore generic types.
//
// TODO(mwhittaker): Handle generics somehow?
if n.TypeParams() != nil { // generics have non-nil TypeParams()
errs = append(errs, errorf(pkg.Fset, spec.Pos(),
"generic struct %v cannot embed xcweaver.AutoMarshal. See serviceweaver.dev/docs.html#serializable-types for more information.",
formatType(pkg, n)))
continue
}
automarshals = append(automarshals, n)
}
}
return automarshals, errors.Join(errs...)
}
// extractComponent attempts to extract a component from the provided TypeSpec.
// It returns a nil component if the TypeSpec doesn't define a component.
func extractComponent(opt Options, pkg *packages.Package, file *ast.File, tset *typeSet, spec *ast.TypeSpec) (*component, error) {
// Check that the type spec is of the form `type t struct {...}`.
s, ok := spec.Type.(*ast.StructType)
if !ok {
// This type declaration does not involve a struct. For example, it
// might look like `type t int`. These non-struct type declarations
// cannot be components.
return nil, nil
}
def, ok := pkg.TypesInfo.Defs[spec.Name]
if !ok {
panic(errorf(pkg.Fset, spec.Pos(), "name %v not found", spec.Name))
}
impl, ok := def.Type().(*types.Named)
if !ok {
// For type aliases like `type t = struct{}`, t has type *types.Struct
// and not type *types.Named. We ignore these.
return nil, nil
}
// Find any weaver.Implements[T] or weaver.WithRouter[T] embedded fields.
var intf *types.Named // The component interface type
var router *types.Named // Router type (if any)
var isMain bool // Is intf weaver.Main?
var refs []*types.Named // T for which weaver.Ref[T] exists in struct
var listeners []string // Names of all listener fields declared in struct
var antipodeAgents []string // Names of all listener fields declared in struct
for _, f := range s.Fields.List {
typeAndValue, ok := pkg.TypesInfo.Types[f.Type]
if !ok {
panic(errorf(pkg.Fset, f.Pos(), "type %v not found", f.Type))
}
t := typeAndValue.Type
if isWeaverRef(t) {
// The field f has type weaver.Ref[T].
arg := t.(*types.Named).TypeArgs().At(0)
if isWeaverMain(arg) {
return nil, errorf(pkg.Fset, f.Pos(),
"components cannot contain a reference to xcweaver.Main")
}
named, ok := arg.(*types.Named)
if !ok {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.Ref argument %s is not a named type.",
formatType(pkg, arg))
}
refs = append(refs, named)
} else if isWeaverListener(t) {
lis, err := getListenerNamesFromStructField(pkg, f)
if err != nil {
return nil, err
}
listeners = append(listeners, lis...)
} else if isWeaverAntipodeAgent(t) {
antipode, err := getAntipodeAgentNamesFromStructField(pkg, f)
if err != nil {
return nil, err
}
antipodeAgents = append(antipodeAgents, antipode...)
}
if len(f.Names) != 0 {
// Ignore unembedded fields.
//
// TODO(mwhittaker): Warn the user about unembedded
// weaver.Implements, weaver.WithConfig, or weaver.WithRouter?
continue
}
switch {
// The field f is an embedded weaver.Implements[T].
case isWeaverImplements(t):
// Check that T is a named interface type inside the package.
arg := t.(*types.Named).TypeArgs().At(0)
named, ok := arg.(*types.Named)
if !ok {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.Implements argument %s is not a named type.",
formatType(pkg, arg))
}
isMain = isWeaverMain(arg)
if !isMain && named.Obj().Pkg() != pkg.Types {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.Implements argument %s is a type outside the current package. A component interface and implementation must be in the same package. If you can't move them into the same package, you can add `type %s %v` to the implementation's package and embed `xcweaver.Implements[%s]` instead of `xcweaver.Implements[%s]`.",
formatType(pkg, named), named.Obj().Name(), formatType(pkg, named), named.Obj().Name(), formatType(pkg, named))
}
if _, ok := named.Underlying().(*types.Interface); !ok {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.Implements argument %s is not an interface.",
formatType(pkg, named))
}
intf = named
// The field f is an embedded weaver.WithRouter[T].
case isWeaverWithRouter(t):
// Check that T is a named type inside the package.
arg := t.(*types.Named).TypeArgs().At(0)
named, ok := arg.(*types.Named)
if !ok {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.WithRouter argument %s is not a named type.",
formatType(pkg, arg))
}
if named.Obj().Pkg() != pkg.Types {
return nil, errorf(pkg.Fset, f.Pos(),
"xcweaver.WithRouter argument %s is a type outside the current package.",
formatType(pkg, named))
}
router = named
}
}
if intf == nil {
// TODO(mwhittaker): Warn the user if they embed weaver.WithRouter or
// weaver.WithConfig but don't embed weaver.Implements.
return nil, nil
}
// Check that that the component implementation implements the component
// interface.
if !types.Implements(types.NewPointer(impl), intf.Underlying().(*types.Interface)) {
return nil, errorf(pkg.Fset, spec.Pos(),
"type %s embeds xcweaver.Implements[%s] but does not implement interface %s.",
formatType(pkg, impl), formatType(pkg, intf), formatType(pkg, intf))
}
// Disallow generic component implementations.
if spec.TypeParams != nil && spec.TypeParams.NumFields() != 0 {
return nil, errorf(pkg.Fset, spec.Pos(),
"component implementation %s is generic. Component implements cannot be generic.",
formatType(pkg, impl))
}
// Validate the component's methods.
if err := validateMethods(pkg, tset, intf); err != nil {
return nil, err
}
// Check that listener names are unique.
seenLis := map[string]struct{}{}
for _, lis := range listeners {
if _, ok := seenLis[lis]; ok {
return nil, errorf(pkg.Fset, spec.Pos(),
"component implementation %s declares multiple listeners with name %s. Please disambiguate.", formatType(pkg, impl), lis)
}
seenLis[lis] = struct{}{}
}
// Check that antipode agent names are unique.
seenAntipodeAgents := map[string]struct{}{}
for _, antipodeAgent := range antipodeAgents {
if _, ok := seenAntipodeAgents[antipodeAgent]; ok {
return nil, errorf(pkg.Fset, spec.Pos(),
"component implementation %s declares multiple antipode agents with name %s. Please disambiguate.", formatType(pkg, impl), antipodeAgent)
}
seenAntipodeAgents[antipodeAgent] = struct{}{}
}
// Warn the user if the component has a mistyped Init method. Init methods
// are supposed to have type "func(context.Context) error", but it's easy
// to forget to add a context.Context argument or error return. Without
// this warning, the component's Init method will be silently ignored. This
// can be very frustrating to debug.
if err := checkMistypedInit(pkg, tset, impl); err != nil {
opt.Warn(err)
}
comp := &component{
intf: intf,
impl: impl,
router: router,
isMain: isMain,
refs: refs,
listeners: listeners,
antipodeAgents: antipodeAgents,
}
// Find routing information if needed.
if comp.router != nil {
var err error
comp.routingKey, comp.routedMethods, err = routerMethods(pkg, intf, router)
if err != nil {
return nil, errorf(pkg.Fset, spec.Pos(), "%w", err)
}
}
return comp, nil
}
// getListenerNamesFromStructField extracts listener names from the given
// weaver.Listener field in the component implementation struct.
func getListenerNamesFromStructField(pkg *packages.Package, f *ast.Field) ([]string, error) {
// Try to get the listener name from the struct tag.
if f.Tag != nil {
tag := reflect.StructTag(strings.TrimPrefix(
strings.TrimSuffix(f.Tag.Value, "`"), "`"))
if len(f.Names) > 1 {
return nil, errorf(pkg.Fset, f.Pos(),
"Tag %s repeated for multiple fields", tag)
}
if name, ok := tag.Lookup("xcweaver"); ok {
if !token.IsIdentifier(name) {
return nil, errorf(pkg.Fset, f.Pos(),
"Listener tag %s is not a valid Go identifier", tag)
}
return []string{name}, nil
}
// fallthrough
}
// Get the listener name(s) from the struct field name(s).
if f.Names == nil { // embedded field
return []string{"Listener"}, nil
}
var ret []string
for _, fname := range f.Names {
ret = append(ret, fname.Name)
}
return ret, nil
}
// getAntipodeAgentNamesFromStructField extracts antipode agents names from the given
// weaver.Antipode[T] field in the component implementation struct.
func getAntipodeAgentNamesFromStructField(pkg *packages.Package, f *ast.Field) ([]string, error) {
// Try to get the antipode agent name from the struct tag.
if f.Tag != nil {
tag := reflect.StructTag(strings.TrimPrefix(
strings.TrimSuffix(f.Tag.Value, "`"), "`"))
if len(f.Names) > 1 {
return nil, errorf(pkg.Fset, f.Pos(),
"Tag %s repeated for multiple fields", tag)
}
if name, ok := tag.Lookup("xcweaver"); ok {
if !token.IsIdentifier(name) {
return nil, errorf(pkg.Fset, f.Pos(),
"Listener tag %s is not a valid Go identifier", tag)
}
return []string{name}, nil
}
// fallthrough
}
// Get the antipode agent name(s) from the struct field name(s).
if f.Names == nil { // embedded field
return []string{"Antipode"}, nil
}
var ret []string
for _, fname := range f.Names {
ret = append(ret, fname.Name)
}
return ret, nil
}
// component represents a Service Weaver component.
//
// A component is divided into an interface and implementation. For example, in
// the following code, Adder is the component interface, and adder is the
// component implementation. router is the router type.
//
// type Adder interface{}
// type adder struct {
// weaver.Implements[Adder]
// weaver.WithRouter[router]
// }
// type router struct{}
type component struct {
intf *types.Named // component interface
impl *types.Named // component implementation
router *types.Named // router, or nil if there is no router
routingKey types.Type // routing key, or nil if there is no router
routedMethods map[string]bool // the set of methods with a routing function
isMain bool // intf is weaver.Main
refs []*types.Named // List of T where a weaver.Ref[T] field is in impl struct
listeners []string // Names of listener fields declared in impl struct
noretry map[string]struct{} // Methods that should not be retried
antipodeAgents []string // Names of antipode agent fields declared in impl struct
}
func fullName(t *types.Named) string {
return path.Join(t.Obj().Pkg().Path(), t.Obj().Name())
}
// intfName returns the component interface name.
func (c *component) intfName() string {
return c.intf.Obj().Name()
}
// implName returns the component implementation name.
func (c *component) implName() string {
return c.impl.Obj().Name()
}
// fullIntfName returns the full package-prefixed component interface name.
func (c *component) fullIntfName() string {
return fullName(c.intf)
}
// methods returns the component interface's methods.
func (c *component) methods() []*types.Func {
underlying := c.intf.Underlying().(*types.Interface)
methods := make([]*types.Func, underlying.NumMethods())
for i := 0; i < underlying.NumMethods(); i++ {
methods[i] = underlying.Method(i)
}
// Sort the component's methods deterministically. This allows a developer
// to re-order the interface methods without the generated code changing.
sort.Slice(methods, func(i, j int) bool {
return methods[i].Name() < methods[j].Name()
})
return methods
}
// validateMethods validates that the provided component's methods are all
// valid component methods.
func validateMethods(pkg *packages.Package, tset *typeSet, intf *types.Named) error {
var errs []error
underlying := intf.Underlying().(*types.Interface)
for i := 0; i < underlying.NumMethods(); i++ {
m := underlying.Method(i)
t, ok := m.Type().(*types.Signature)
if !ok {
panic(errorf(pkg.Fset, m.Pos(), "method %s doesn't have a signature", m.Name()))
}
// Disallow unexported methods.
if !m.Exported() {
errs = append(errs, errorf(pkg.Fset, m.Pos(),
"Method `%s%s %s` of XCWeaver component %q is unexported. Every method in a component interface must be exported.",
m.Name(), formatType(pkg, t.Params()), formatType(pkg, t.Results()), intf.Obj().Name()))
continue
}
// bad is a helper function for producing helpful error messages.
bad := func(bad, format string, arg ...any) error {
err := fmt.Errorf(format, arg...)
return errorf(
pkg.Fset, m.Pos(),
"Method `%s%s %s` of XCWeaver component %q has incorrect %s types. %w",
m.Name(), formatType(pkg, t.Params()), formatType(pkg, t.Results()), intf.Obj().Name(), bad, err)
}
// First argument must be context.Context.
if t.Params().Len() < 1 || !isContext(t.Params().At(0).Type()) {
errs = append(errs, bad("argument", "The first argument must have type context.Context."))
}
// All arguments but context.Context must be serializable.
for i := 1; i < t.Params().Len(); i++ {
arg := t.Params().At(i)
if err := errors.Join(tset.checkSerializable(arg.Type())...); err != nil {
// TODO(mwhittaker): Print a link to documentation on which types are serializable.
errs = append(errs, bad("argument",
"Argument %d has type %s, which is not serializable. All arguments, besides the initial context.Context, must be serializable.\n%w",
i, formatType(pkg, arg.Type()), err))
}
}
// Last result must be error.
if t.Results().Len() < 1 || t.Results().At(t.Results().Len()-1).Type().String() != "error" {
// TODO(mwhittaker): If the function doesn't return anything, don't
// print t.Results.
errs = append(errs, bad("return", "The last return must have type error."))
}
// All results but error must be serializable.
for i := 0; i < t.Results().Len()-1; i++ {
res := t.Results().At(i)
if err := errors.Join(tset.checkSerializable(res.Type())...); err != nil {
// TODO(mwhittaker): Print a link to documentation on which types are serializable.
errs = append(errs, bad("return",
"Return %d has type %v, which is not serializable. All returns, besides the final error, must be serializable.\n%w",
i, formatType(pkg, res.Type()), err))
}
}
}
return errors.Join(errs...)
}
// checkMistypedInit returns an error if the provided component implementation
// has an Init method that does not have type "func(context.Context) error".
func checkMistypedInit(pkg *packages.Package, tset *typeSet, impl *types.Named) error {
for i := 0; i < impl.NumMethods(); i++ {
m := impl.Method(i)
if m.Name() != "Init" {
continue
}
// TODO(mwhittaker): Highlight the warning yellow instead of red.
sig := m.Type().(*types.Signature)
err := errorf(pkg.Fset, m.Pos(),
`WARNING: Component %v's Init method has type "%v", not type "func(context.Context) error". It will be ignored. See https://serviceweaver.dev/docs.html#components-implementation for more information.`,
impl.Obj().Name(), sig)
// Check Init's parameters.
if sig.Params().Len() != 1 || !isContext(sig.Params().At(0).Type()) {
return err
}
// Check Init's returns.
if sig.Results().Len() != 1 || sig.Results().At(0).Type().String() != "error" {
return err
}
return nil
}
return nil
}
// routerMethods returns the routing key and the set of routed methods for comp.
//
// A developer can annotate a Service Weaver component with a router, like this:
//
// type foo struct {
// weaver.Implements[Foo]
// weaver.WithRouter[fooRouter]
// ...
// }
// func (*foo) A(context.Context) error {...}
// func (*foo) B(context.Context, int) error {...}
// func (*foo) C(context.Context, int) error {...}
//
// type fooRouter struct{}
// func (fooRouter) A(context.Context) int {...}
// func (fooRouter) B(context.Context, int) int {...}
func routerMethods(pkg *packages.Package, intf, router *types.Named) (types.Type, map[string]bool, error) {
underlying := intf.Underlying().(*types.Interface)
componentMethods := map[string]*types.Signature{}
for i := 0; i < underlying.NumMethods(); i++ {
m := underlying.Method(i)
componentMethods[m.Name()] = m.Type().(*types.Signature)
}
// Verify that every router method corresponds to a component method. This
// is so we avoid errors where one has been renamed but not the other.
// Also check that they all have the same return type.
var routingKey types.Type
routedMethods := map[string]bool{}
for i, n := 0, router.NumMethods(); i < n; i++ {
m := router.Method(i)
pos := m.Origin().Pos()
componentMethod, ok := componentMethods[m.Name()]
if !ok {
return nil, nil, errorf(pkg.Fset, pos,
"Routing function %q does not match any method of %q.",
m.Name(), intf.Obj().Name())
}
mt := m.Type().(*types.Signature)
// Router method args must match component method args.
if !types.Identical(mt.Params(), componentMethod.Params()) {
return nil, nil, errorf(pkg.Fset, pos,
"Component %q method arguments %s do not match router method arguments %s",
intf.Obj().Name(), formatType(pkg, componentMethod.Params()), formatType(pkg, mt.Params()))
}
// All router methods must have the same routable return type.
if mt.Results().Len() != 1 {
return nil, nil, errorf(pkg.Fset, pos,
"Routing function %q must return exactly one value (it returns %d)",
m.Name(), mt.Results().Len())
}
ret := mt.Results().At(0).Type()
if i == 0 {
if !isValidRouterType(ret) {
return nil, nil, errorf(pkg.Fset, pos,
"Router method %q has invalid routing key type %q. A routing key type should be an integer, float, string, or a struct with every field being an integer, float, or string.",
m.Name(), formatType(pkg, ret))
}
routingKey = ret
} else if !types.Identical(ret, routingKey) {
return nil, nil, errorf(pkg.Fset, pos,
"Return type of %q (%s) does not match previously seen routing key type (%s)",
m.Name(), formatType(pkg, ret), formatType(pkg, routingKey))
}
routedMethods[m.Name()] = true
}
if routingKey == nil {
return nil, nil, errorf(pkg.Fset, router.Obj().Pos(),
"No routing methods found on declarated router type (%s) for component %q",
router.Obj().Name(), intf.Obj().Name())
}
return routingKey, routedMethods, nil
}
type printFn func(format string, args ...interface{})
// TODO(mwhittaker): Have generate return an error.
func (g *generator) generate() error {
if len(g.components)+g.tset.automarshalCandidates.Len() == 0 {
// There's nothing to generate.
return nil
}
// Process components in deterministic order.
sort.Slice(g.components, func(i, j int) bool {
return g.components[i].intfName() < g.components[j].intfName()
})
// Generate the file body.
var body bytes.Buffer
{
fn := func(format string, args ...interface{}) {
fmt.Fprintln(&body, fmt.Sprintf(format, args...))
}
g.generateRegisteredComponents(fn)
g.generateInstanceChecks(fn)
g.generateRouterChecks(fn)
g.generateLocalStubs(fn)
g.generateClientStubs(fn)
if err := g.generateVersionCheck(fn); err != nil {
return err
}
g.generateServerStubs(fn)
g.generateReflectStubs(fn)
g.generateAutoMarshalMethods(fn)
g.generateRouterMethods(fn)
g.generateEncDecMethods(fn)
// append the size methods
if g.sizeFuncNeeded.Len() > 0 {
fn(`// Size implementations.`)
fn(``)
keys := g.sizeFuncNeeded.Keys()
sort.Slice(keys, func(i, j int) bool {
x, y := keys[i], keys[j]
return x.String() < y.String()
})
for _, t := range keys {
g.generateSizeFunction(fn, t)
}
}
}
// Generate the file header. This should be done at the very end to ensure
// that all types added to the body have been imported.
var header bytes.Buffer