-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgenerate_generator.go
1052 lines (910 loc) · 30.5 KB
/
generate_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
package internal
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"go/types"
"io"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"unicode"
"github.com/samber/lo"
"golang.org/x/tools/go/packages"
"github.com/go-kod/kod/internal/callgraph"
"github.com/go-kod/kod/internal/version"
)
const (
generatedCodeFile = "kod_gen.go"
Usage = `Generate code for a Kod application.
Usage:
kod generate [packages]
Description:
"kod generate" generates code for the Kod applications in the
provided packages. For example, "kod generate . ./foo" will generate code
for the Kod applications in the current directory and in the ./foo
directory. For every package, the generated code is placed in a kod_gen.go
file in the package's directory. For example, "kod generate . ./foo" will
create ./kod_gen.go and ./foo/kod_gen.go.
You specify packages for "kod 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 "kod generate" directly, you can place a line of the
following form in one of the .go files in the package:
//go:generate kod generate
and then use the normal "go generate" command.
Examples:
# Generate code for the package in the current directory.
kod generate
# Same as "kod generate".
kod generate .
# Generate code for the package in the ./foo directory.
kod generate ./foo
# Generate code for all packages in all subdirectories of current directory.
kod 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 Kod 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: parseNonKodGenFile,
BuildFlags: []string{"--tags=ignoreKodGen"},
}
pkgList, err := packages.Load(cfg, pkgs...)
if err != nil {
return fmt.Errorf("packages.Load: %w", err)
}
var errs []error
for _, pkg := range pkgList {
g, err := newGenerator(opt, pkg, fset)
if err != nil {
errs = append(errs, err)
continue
}
if err := g.generate(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// parseNonKodGenFile parses a Go file, except for kod_gen.go files whose
// contents are ignored since those contents may reference types that no longer
// exist.
func parseNonKodGenFile(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 {
opt Options
pkg *packages.Package
tset *typeSet
fileset *token.FileSet
components []*component
}
// 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/go-kod/kod/kod.go"
// with much shorter filenames like "./kod.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) (*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
// kod.AutoMarshal struct.
tset := newTypeSet(pkg)
// Find and process all seen.
seen := map[string]*component{}
components := []*component{}
for _, file := range pkg.Syntax {
filename := fset.Position(file.Package).Filename
if filepath.Base(filename) == generatedCodeFile {
// Ignore kod_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 kod.Implements[T].
//
// 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 := seen[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
}
seen[c.fullIntfName()] = c
components = append(components, c)
}
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
// slices.Reverse(components)
return &generator{
opt: opt,
pkg: pkg,
tset: tset,
fileset: fset,
components: components,
}, nil
}
// findComponents returns the components in the provided file. For example,
// findComponents will find and return the following component.
//
// type something struct {
// kod.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, tset, ts)
if err != nil {
errs = append(errs, err)
continue
}
if component != nil {
components = append(components, component)
}
}
}
return components, 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, 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 kod.Implements[T] or kod.WithRouter[T] embedded fields.
var intf *types.Named // The component interface type
var isMain bool // Is intf kod.Main?
// var typ componentType // ComponentType
var refs []*types.Named // T for which kod.Ref[T] exists 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 isKodRef(t) {
// The field f has type kod.Ref[T].
arg := t.(*types.Named).TypeArgs().At(0)
if isKodMain(arg) {
return nil, errorf(pkg.Fset, f.Pos(),
"components cannot contain a reference to kod.Main")
}
named, ok := arg.(*types.Named)
if !ok {
return nil, errorf(pkg.Fset, f.Pos(),
"kod.Ref argument %s is not a named type.",
formatType(pkg, arg))
}
refs = append(refs, named)
}
if len(f.Names) != 0 {
// Ignore unembedded fields.
//
// TODO: Warn the user about unembedded
// kod.Implements, kod.WithConfig, or kod.WithRouter?
continue
}
switch {
// The field f is an embedded kod.Implements[T].
case isKodImplements(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(),
"kod.Implements argument %s is not a named type.",
formatType(pkg, arg))
}
// typ = getComponentType(arg)
isMain = isKodMain(arg)
if !isMain && named.Obj().Pkg() != pkg.Types {
return nil, errorf(pkg.Fset, f.Pos(),
"kod.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 `kod.Implements[%s]` instead of `kod.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(),
"kod.Implements argument %s is not an interface.",
formatType(pkg, named))
}
intf = named
}
}
if intf == nil {
// TODO: Warn the user if they embed kod.WithRouter or
// kod.WithConfig but don't embed kod.Implements.
return nil, nil
}
// Check 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 kod.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
}
// 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,
isMain: isMain,
refs: refs,
}
return comp, nil
}
// component represents a Kod 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 {
// kod.Implements[Adder]
// kod.WithRouter[router]
// }
// type router struct{}
type component struct {
intf *types.Named // component interface
impl *types.Named // component implementation
isMain bool // intf is kod.Main
refs []*types.Named // List of T where a kod.Ref[T] field is 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()
}
func (c *component) fullMethodNameVar(methodName string) string {
return fmt.Sprintf("%s_%s_FullMethodName", c.intfName(), methodName)
}
// 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)
}
// fullIntfName returns the full package-prefixed component interface name.
func (c *component) fullFullMethodName(methodName string) string {
return c.fullIntfName() + "." + methodName
}
// 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, _ *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 Kod 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 Kod component %q has incorrect %s types. %w",
// m.Name(), formatType(pkg, t.Params()), formatType(pkg, t.Results()),
// intf.Obj().Name(), bad, err)
// }
// do no process kod.Main
if isKodMain(intf) {
continue
}
// // do no process kod.Controller or kod.Component
// if typ == ComponentTypeController || typ == ComponentTypeComponent {
// continue
// }
// // Method must have one parameter at least.
// if t.Params().Len() == 0 {
// errs = append(errs, bad("argument", "The method must have one parameter at least."))
// continue
// }
// // First argument must be context.Context.
// if !isContext(t.Params().At(0).Type()) {
// errs = append(errs, bad("argument", "The first argument must have type context.Context."))
// }
// // do no process kod.Controller or kod.Component
// if typ == ComponentTypeRepository {
// continue
// }
// // Method must have two parameters at most.
// if t.Params().Len() > 2 {
// errs = append(errs, bad("argument", "The method must have two parameters at most."))
// continue
// }
// // Second argument must be a pointer to a struct
// if t.Params().Len() == 2 && !isPointerToStruct(t.Params().At(1).Type()) {
// errs = append(errs, bad("argument", "The second argument must be a pointer to a struct."))
// }
// // Result must have two values at most.
// if t.Results().Len() > 2 {
// errs = append(errs, bad("return", "The method must return two values at most."))
// continue
// }
// // First result must be a pointer to a struct.
// if t.Results().Len() == 2 && !isPointerToStruct(t.Results().At(0).Type()) {
// errs = append(errs, bad("return", "The first return must be a pointer to a struct."))
// }
// // Last result must be error.
// if t.Results().Len() == 1 && t.Results().At(t.Results().Len()-1).Type().String() != "error" {
// // TODO: If the function doesn't return anything, don't
// // print t.Results.
// errs = append(errs, bad("return", "The last return must have type error."))
// }
// if t.Results().Len() == 0 {
// errs = append(errs, bad("return", "The last return must have type error."))
// }
}
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, _ *typeSet, impl *types.Named) error {
for i := 0; i < impl.NumMethods(); i++ {
m := impl.Method(i)
if m.Name() != "Init" {
continue
}
// TODO: 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.`,
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
}
type printFn func(format string, args ...interface{})
// TODO: Have generate return an error.
func (g *generator) generate() error {
if len(g.components) == 0 {
// There's nothing to generate.
return nil
}
// 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.generateVersionCheck(fn)
g.generateInstanceChecks(fn)
g.generateLocalStubs(fn)
}
// 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
{
fn := func(format string, args ...interface{}) {
fmt.Fprintln(&header, fmt.Sprintf(format, args...))
}
g.generateImports(fn)
g.generateFullMethodNames(fn)
}
// Create a generated file.
filename := filepath.Join(g.pkgDir(), generatedCodeFile)
dst := NewWriter(filename)
defer dst.Cleanup()
fmtAndWrite := func(buf bytes.Buffer) error {
// Format the code.
b := buf.Bytes()
formatted, err := format.Source(b)
if err != nil {
fmt.Println(string(b))
return fmt.Errorf("format.Source: %w", err)
}
b = formatted
// Write to dst.
_, err = io.Copy(dst, bytes.NewReader(b))
return err
}
if err := fmtAndWrite(header); err != nil {
return err
}
if err := fmtAndWrite(body); err != nil {
return err
}
return dst.Close()
}
// pkgDir returns the directory of the package.
func (g *generator) pkgDir() string {
if len(g.pkg.Syntax) == 0 {
panic(fmt.Errorf("package %v has no source files", g.pkg))
}
f := g.pkg.Syntax[0]
fname := g.fileset.Position(f.Package).Filename
return filepath.Dir(fname)
}
// componentRef returns the string to use to refer to the interface
// implemented by a component in generated code.
func (g *generator) componentRef(comp *component) string {
if comp.isMain {
return g.kod().qualify("Main")
}
return comp.intfName() // We already checked that interface is in the same package.
}
// generateImports generates code to import all the dependencies.
func (g *generator) generateImports(p printFn) {
p(`// Code generated by "kod generate". DO NOT EDIT.`)
p("//go:build !ignoreKodGen")
p("")
p("package %s", g.pkg.Name)
p("")
p(`import (`)
for _, imp := range g.tset.imports() {
if imp.alias == "" {
p(` %s`, strconv.Quote(imp.path))
} else {
p(` %s %s`, imp.alias, strconv.Quote(imp.path))
}
}
p(`)`)
}
func (g *generator) generateFullMethodNames(p printFn) {
if len(g.components) == 0 {
return
}
p(``)
p(`// Full method names for components.`)
p(`const (`)
for _, comp := range g.components {
for _, m := range comp.methods() {
if g.getFirstArgTypeString(m) != "context.Context" {
continue
}
p(`// %s is the full name of the method [%s.%s].`, comp.fullMethodNameVar(m.Name()), comp.implName(), m.Name())
p(`%s = %q`, comp.fullMethodNameVar(m.Name()), comp.fullFullMethodName(m.Name()))
}
}
p(`)`)
}
func (g *generator) generateVersionCheck(p printFn) {
// selfVersion := version.SelfVersion()
p(``)
p(`// CodeGen version check.`)
p("var _ kod.CodeGenLatestVersion = kod.CodeGenVersion[[%d][%d]struct{}](%s)",
version.CodeGenMajor, version.CodeGenMinor,
fmt.Sprintf("`"+`
ERROR: You generated this file with 'kod generate' (codegen
version %s). The generated code is incompatible with the version of the
github.com/go-kod/kod module that you're using. The kod module
version can be found in your go.mod file or by running the following command.
go list -m github.com/go-kod/kod
We recommend updating the kod module and the 'kod generate' command by
running the following.
go get github.com/go-kod/kod@latest
go install github.com/go-kod/kod/cmd/kod@latest
Then, re-run 'kod generate' and re-build your code. If the problem persists,
please file an issue at https://github.com/go-kod/kod/issues.
`+"`", version.CodeGenSemVersion))
}
// generateInstanceChecks generates code that checks that every component
// implementation type implements kod.InstanceOf[T] for the appropriate T.
func (g *generator) generateInstanceChecks(p printFn) {
// If someone deletes a kod.Implements annotation and forgets to re-run
// `kod generate`, these checks will fail to build. Similarly, if a user
// changes the interface in a kod.Implements and forgets to re-run
// `kod generate`, these checks will fail to build.
p(``)
p(`// kod.InstanceOf checks.`)
for _, c := range g.components {
// e.g., var _ kod.InstanceOf[Odd] = &odd{}
p(`var _ %s[%s] = (*%s)(nil)`, g.kod().qualify("InstanceOf"), g.tset.genTypeString(c.intf), g.tset.genTypeString(c.impl))
}
}
// generateRegisteredComponents generates code that registers the components with Kod.
func (g *generator) generateRegisteredComponents(p printFn) {
if len(g.components) == 0 {
return
}
p(``)
p(`func init() {`)
for _, comp := range g.components {
name := comp.intfName()
myName := comp.fullIntfName()
localStubFn := fmt.Sprintf(`func(ctx context.Context, info *kod.LocalStubFnInfo) any {
return %s_local_stub{
impl: info.Impl.(%s),
interceptor: info.Interceptor,
} }`,
notExported(name), g.componentRef(comp))
refNames := make([]string, 0, len(comp.refs))
for _, ref := range comp.refs {
refNames = append(refNames, callgraph.MakeEdgeString(comp.fullIntfName(), fullName(ref)))
}
reflect := g.tset.importPackage("reflect", "reflect")
p(` %s(&%s{`, g.codegen().qualify("Register"), g.codegen().qualify("Registration"))
p(` Name: %q,`, myName)
// To get a reflect.Type for an interface, we have to first get a type
// of its pointer and then resolve the underlying type. See:
// https://pkg.go.dev/reflect#example-TypeOf
p(` Interface: %s((*%s)(nil)).Elem(),`, reflect.qualify("TypeOf"), g.componentRef(comp))
p(` Impl: %s(%s{}),`, reflect.qualify("TypeOf"), comp.implName())
p(" Refs: `%s`,", strings.Join(refNames, ",\n"))
if !comp.isMain {
p(` LocalStubFn: %s,`, localStubFn)
} else {
p(` LocalStubFn: nil,`)
}
p(` })`)
}
p(`}`)
}
// kod imports and returns the kod package.
func (g *generator) kod() importPkg {
return g.tset.importPackage(kodPackagePath, "kod")
}
// kod imports and returns the kod package.
func (g *generator) interceptor() importPkg {
return g.tset.importPackage("github.com/go-kod/kod/interceptor", "interceptor")
}
// codegen imports and returns the codegen package.
func (g *generator) codegen() importPkg {
path := kodPackagePath
return g.tset.importPackage(path, "kod")
}
// formatType pretty prints the provided type, encountered in the provided
// currentPackage.
func formatType(currentPackage *packages.Package, t types.Type) string {
qualifier := func(pkg *types.Package) string {
if pkg == currentPackage.Types {
return ""
}
return pkg.Name()
}
return types.TypeString(t, qualifier)
}
// generateLocalStubs generates code that creates stubs for the local components.
func (g *generator) generateLocalStubs(p printFn) {
p(``)
p(``)
p(`// Local stub implementations.`)
var b strings.Builder
for _, comp := range g.components {
if comp.isMain {
continue
}
g.tset.importPackage("context", "context")
g.interceptor()
stub := notExported(comp.intfName()) + "_local_stub"
p(`// %s is a local stub implementation of [%s].`, stub, g.tset.genTypeString(comp.intf))
p(`type %s struct{`, stub)
p(` impl %s`, g.componentRef(comp))
p(` interceptor interceptor.Interceptor`)
p(`}`)
p(``)
p(`// Check that [%s] implements the [%s] interface.`, stub, g.tset.genTypeString(comp.intf))
p(`var _ %s = (*%s)(nil)`, g.tset.genTypeString(comp.intf), stub)
p(``)
for _, m := range comp.methods() {
mt := m.Type().(*types.Signature)
firstArgTypeString := g.getFirstArgTypeString(m)
p(``)
p(`// %s wraps the method [%s.%s].`, m.Name(), comp.implName(), m.Name())
p(`func (s %s) %s(%s) (%s) {`, stub, m.Name(), g.args(mt), g.returns(mt))
// If the first argument is not context.Context, then we don't support interceptors.
if firstArgTypeString != "context.Context" {
p(`// Because the first argument is not context.Context, so interceptors are not supported.`)
p(` %s s.impl.%s(%s)
return
}`, g.returnsList(mt), m.Name(), g.argList(comp, mt))
continue
}
p(`
if s.interceptor == nil {
%s s.impl.%s(%s)
return
}
`, g.returnsList(mt), m.Name(), g.argList(comp, mt))
p(`call := func(ctx context.Context, info interceptor.CallInfo, req, res []any) (err error) {`)
p(` %s s.impl.%s(%s)
%sreturn
}
`, g.returnsList(mt), m.Name(), g.argList(comp, mt), g.setReturnsList(mt))
p(`info := interceptor.CallInfo {
Impl: s.impl,
FullMethod: %s,
}
`, comp.fullMethodNameVar(m.Name()))
p(`%s = s.interceptor(ctx, info, []any{%s}, []any{%s}, call)`,
lo.If(haveError(mt), "err").Else("_"),
g.argsReflectList(mt), g.returnsReflectList(mt))
// Call the local method.
b.Reset()
if mt.Results().Len() > 0 {
p(` return`)
}
p(`}`)
}
}
}
func (g *generator) getFirstArgTypeString(m *types.Func) string {
mt := m.Type().(*types.Signature)
if mt.Params().Len() > 0 {
return g.tset.genTypeString(mt.Params().At(0).Type())
}
return ""
}
func (g *generator) setReturnsList(sig *types.Signature) string {
var returns strings.Builder
for i := 0; i < sig.Results().Len(); i++ {
rt := sig.Results().At(i).Type()
if g.tset.genTypeString(rt) == "error" {
// fmt.Fprintf(&returns, "res[%d] = err\n", i)
continue
}
fmt.Fprintf(&returns, "res[%d] = r%d\n", i, i)
}
return returns.String()
}
func (g *generator) argList(_ *component, sig *types.Signature) string {
if sig.Params().Len() == 0 {
return ""
}
var b strings.Builder
if haveContext(sig) {
fmt.Fprintf(&b, "ctx")
} else {
fmt.Fprintf(&b, "a0")
}
for i := 1; i < sig.Params().Len(); i++ {
if sig.Variadic() && i == sig.Params().Len()-1 {
fmt.Fprintf(&b, ", a%d...", i)
} else {
fmt.Fprintf(&b, ", a%d", i)
}
}
return b.String()
}
func (g *generator) argsReflectList(sig *types.Signature) string {
if sig.Params().Len() == 0 {
return ""
}
var b strings.Builder
for i := 0; i < sig.Params().Len(); i++ {
// filter context.Context
if g.tset.genTypeString(sig.Params().At(i).Type()) == "context.Context" {
continue
}
if sig.Variadic() {
fmt.Fprintf(&b, "a%d...", i)
} else {
fmt.Fprintf(&b, "a%d", i)
}
if i != sig.Params().Len()-1 {
fmt.Fprintf(&b, ",")
}
}
return b.String()
}
// args returns a textual representation of the arguments of the provided
// signature. The first argument must be a context.Context. The returned code
// names the first argument ctx and all subsequent arguments a0, a1, and so on.
func (g *generator) args(sig *types.Signature) string {
if sig.Params().Len() == 0 {
return ""
}
var args strings.Builder
for i := 0; i < sig.Params().Len(); i++ { // Skip initial context.Context
at := sig.Params().At(i).Type()
if !sig.Variadic() || i != sig.Params().Len()-1 {
if g.tset.genTypeString(at) == "context.Context" {
fmt.Fprintf(&args, ",ctx context.Context")
continue
}
fmt.Fprintf(&args, ", a%d %s", i, g.tset.genTypeString(at))
continue
}
// For variadic functions, the final argument is guaranteed to be a
// slice. Instead of passing an argument of type []t, we pass ...t.
subtype := at.(*types.Slice).Elem()
if g.tset.genTypeString(subtype) == "context.Context" {
fmt.Fprintf(&args, ",ctx ...context.Context")
continue
}
fmt.Fprintf(&args, ", a%d ...%s", i, g.tset.genTypeString(subtype))
}
return args.String()[1:]
}
// returns will return a textual representation of the returns of the provided
// signature. The last return must be an error. The returned code names the
// returns r0, r1, and so on. The returned error is called err.
func (g *generator) returns(sig *types.Signature) string {
var returns strings.Builder
for i := 0; i < sig.Results().Len(); i++ {
rt := sig.Results().At(i).Type()
if g.tset.genTypeString(rt) == "error" {
fmt.Fprintf(&returns, "err error")
continue
}
fmt.Fprintf(&returns, "r%d %s, ", i, g.tset.genTypeString(rt))
}
return returns.String()
}
func (g *generator) returnsList(sig *types.Signature) string {
var returns strings.Builder
for i := 0; i < sig.Results().Len(); i++ {
rt := sig.Results().At(i).Type()
if g.tset.genTypeString(rt) == "error" {
fmt.Fprintf(&returns, "err")
continue
}
fmt.Fprintf(&returns, "r%d", i)
if i != sig.Results().Len()-1 {
fmt.Fprintf(&returns, ", ")