/
gen.go
1123 lines (1017 loc) · 40.1 KB
/
gen.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 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package golang implements Go code generation from compiled VDL packages.
package golang
import (
"bytes"
"flag"
"fmt"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"text/template"
"v.io/v23/vdl"
"v.io/x/ref/lib/vdl/compile"
"v.io/x/ref/lib/vdl/parse"
"v.io/x/ref/lib/vdl/vdlutil"
)
type goData struct {
Package *compile.Package
Env *compile.Env
Imports goImports
VDLConfigName string
createdTargets map[*vdl.Type]bool // set of types whose Targets have already been created
anonTargets map[*vdl.Type]int // tracks unnamed target numbers
anonReaders map[*vdl.Type]int // tracks unnamed decoder numbers
anonWriters map[*vdl.Type]int // tracks unnamed encoder numbers
typeOfs map[*vdl.Type]int // tracks vdl.TypeOf var numbers
vdlTypeDefintions string // the code to define all vdl types + methods.
collectImports bool // is this the import collecting pass instead of normal generation
importMap importMap
}
var skipGoMethods = flag.Bool("skip-go-methods", false, "Skip go generation of VDL{Read,Write,Zero} methods.")
// testingMode is only set to true in tests, to make testing simpler.
var testingMode = false
// Reference a package in the generator.
// If goData's collectImports mode is set, empty imports will be generated and the set of
// imported packages will be collected. If collectImports is unset, the list of imported
// packages will be used to return a valid import.
func (data *goData) Pkg(genPkgPath string) string {
if testingMode {
return path.Base(genPkgPath) + "."
}
if data.collectImports {
data.importMap.AddPackage(genPkgPath, data.pkgName(genPkgPath))
return ""
}
// Special-case to avoid adding package qualifiers if we're generating code
// for that package.
if data.Package.GenPath == genPkgPath {
return ""
}
if local := data.Imports.LookupLocal(genPkgPath); local != "" {
return local + "."
}
data.Env.Errors.Errorf("%s: unknown generated package %q", data.Package.Name, genPkgPath)
return ""
}
// Reference a package as forced "_" in the generator.
// During the import pass mode, this is used to collect dependencies on wiretypes
// that must have their native conversions registered.
func (data *goData) AddForcedPkg(genPkgPath string) {
if data.collectImports {
data.importMap.AddForcedPackage(genPkgPath)
}
}
func (data *goData) pkgName(genPkgPath string) string {
// For user imports, ResolvePackageGenPath should resolve to a
// valid package.
if pkg := data.Env.ResolvePackageGenPath(genPkgPath); pkg != nil {
return pkg.Name
}
// For system imports, e.g., v.io/v23/vdl just use the basename.
return path.Base(genPkgPath)
}
func (data *goData) CtxVar(name string) string {
return name + " *" + data.Pkg("v.io/v23/context") + "T"
}
func (data *goData) OptsVar(name string) string {
return name + " ..." + data.Pkg("v.io/v23/rpc") + "CallOpt"
}
func (data *goData) SkipGenZeroReadWrite(def *compile.TypeDef) bool {
switch {
case *skipGoMethods:
return true
case data.Package.Path == "v.io/v23/vdl/vdltest" && strings.HasPrefix(def.Name, "X"):
// Don't generate VDL{IsZero,Read,Write} for vdltest types that start with
// X. This is hard-coded to make it easy to generate test cases.
return true
}
return false
}
func (data *goData) TypeOf(tt *vdl.Type) string {
if builtin := builtInTypeVars[tt]; builtin != "" {
return data.Pkg("v.io/v23/vdl") + builtin
}
// Keep track of all other types, so we can define the vars later.
id := data.typeOfs[tt]
if id == 0 {
id = len(data.typeOfs) + 1
data.typeOfs[tt] = id
}
return typeOfVarName(tt, id)
}
func typeOfVarName(tt *vdl.Type, id int) string {
return fmt.Sprintf("vdlType%s%d", tt.Kind().CamelCase(), id)
}
func (data *goData) idToTypeOfs() map[int]*vdl.Type {
// Create a reverse typeOfs map, so that we dump the vars in order.
idToType := make(map[int]*vdl.Type, len(data.typeOfs))
for tt, id := range data.typeOfs {
idToType[id] = tt
}
return idToType
}
func (data *goData) DeclareTypeOfVars() string {
idToType := data.idToTypeOfs()
if len(idToType) == 0 {
return ""
}
s := `
// Hold type definitions in package-level variables, for better performance.
// Declare and initialize with default values here so that the initializeVDL
// method will be considered ready to initialize before any of the type
// definitions that appear below.
//
//nolint:unused
var (`
for id := 1; id <= len(idToType); id++ {
tt := idToType[id]
s += fmt.Sprintf(`
%[1]s *%[2]sType = nil`, typeOfVarName(tt, id), data.Pkg("v.io/v23/vdl"))
}
return s + `
)`
}
// DefineTypeOfVars defines the vars holding type definitions. They are
// declared as unexported package-level vars, and defined separately in the
// initializeVDL func, to ensure they are initialized as early as possible.
func (data *goData) DefineTypeOfVars() string {
idToType := data.idToTypeOfs()
if len(idToType) == 0 {
return ""
}
s := `
// Initialize type definitions.`
for id := 1; id <= len(idToType); id++ {
// We need to generate a Go expression of type *vdl.Type that represents the
// type. Since the rest of our logic can already generate the Go code for
// any value, we just wrap it in vdl.TypeOf to produce the final result.
//
// This may seem like a strange roundtrip, but results in less generator and
// generated code.
//
// There's no need to convert the value to its native representation, since
// it'll just be converted back in vdl.TypeOf.
tt := idToType[id]
typeOf := data.InitializationExpression(tt)
s += fmt.Sprintf(`
%[1]s = %[2]s`, typeOfVarName(tt, id), typeOf)
}
return s
}
// InitializationExpression returns an expression for initializing the value
// of the specified type. It is called by DefineTypeOfVars above and is required
// by the code generator in order to generate initialization values for fields
// in package level variables without relying on initialization order.
func (data *goData) InitializationExpression(tt *vdl.Type) string {
if builtin, ok := builtInTypeVars[tt]; ok {
return "vdl." + builtin
}
typeOf := typeGoWire(data, tt)
if tt.Kind() != vdl.Optional {
typeOf = "*" + typeOf
}
typeOf = "((" + typeOf + ")(nil))"
if tt.CanBeOptional() && tt.Kind() != vdl.Optional {
typeOf += ".Elem()"
}
return fmt.Sprintf(`%[1]sTypeOf%[2]s`, data.Pkg("v.io/v23/vdl"), typeOf)
}
// Run the code to define the methods so as to generate the
// type variables that need to be initialized ahead of actually
// writing that code.
func (data *goData) InitializeTypeDefinitions() {
defs := strings.Builder{}
for _, def := range data.Package.TypeDefs() {
defs.WriteString(defineType(data, def))
defs.WriteRune('\n')
if !data.SkipGenZeroReadWrite(def) {
defs.WriteString(defineIsZero(data, def))
defs.WriteString(defineWrite(data, def))
defs.WriteString(defineRead(data, def))
}
}
data.vdlTypeDefintions = defs.String()
}
// VDLTypeDefinitions returns the code for all VDL method definitions.
func (data *goData) VDLTypeDefinitions() string {
return data.vdlTypeDefintions
}
var builtInTypeVars = map[*vdl.Type]string{
vdl.AnyType: "AnyType",
vdl.BoolType: "BoolType",
vdl.ByteType: "ByteType",
vdl.Uint16Type: "Uint16Type",
vdl.Uint32Type: "Uint32Type",
vdl.Uint64Type: "Uint64Type",
vdl.Int8Type: "Int8Type",
vdl.Int16Type: "Int16Type",
vdl.Int32Type: "Int32Type",
vdl.Int64Type: "Int64Type",
vdl.Float32Type: "Float32Type",
vdl.Float64Type: "Float64Type",
vdl.StringType: "StringType",
vdl.TypeObjectType: "TypeObjectType",
vdl.ErrorType: "ErrorType",
}
// Generate takes a populated compile.Package and returns a byte slice
// containing the generated Go source code.
func Generate(pkg *compile.Package, env *compile.Env) []byte {
validateGoConfig(pkg, env)
data := &goData{
Package: pkg,
Env: env,
collectImports: true,
importMap: importMap{},
createdTargets: make(map[*vdl.Type]bool),
anonTargets: make(map[*vdl.Type]int),
anonReaders: make(map[*vdl.Type]int),
anonWriters: make(map[*vdl.Type]int),
typeOfs: make(map[*vdl.Type]int),
}
data.InitializeTypeDefinitions()
// The implementation uses the template mechanism from text/template and
// executes the template against the goData instance.
// First pass: run the templates to collect imports.
var buf bytes.Buffer
if err := goTemplate.Execute(&buf, data); err != nil {
// We shouldn't see an error; it means our template is buggy.
panic(fmt.Errorf("vdl: couldn't execute template: %v", err))
}
// Remove self and built-in package dependencies. Every package can use
// itself and the built-in package, so we don't need to record this.
data.importMap.DeletePackage(pkg)
data.importMap.DeletePackage(compile.BuiltInPackage)
// Sort the imports.
data.Imports = goImports(data.importMap.Sort())
// Second pass: re-run the templates with the final imports to generate the
// output file.
data.collectImports = false
data.createdTargets = make(map[*vdl.Type]bool)
data.anonTargets = make(map[*vdl.Type]int)
data.anonReaders = make(map[*vdl.Type]int)
data.anonWriters = make(map[*vdl.Type]int)
data.typeOfs = make(map[*vdl.Type]int)
data.InitializeTypeDefinitions()
buf.Reset()
if err := goTemplate.Execute(&buf, data); err != nil {
// We shouldn't see an error; it means our template is buggy.
panic(fmt.Errorf("vdl: couldn't execute template: %v", err))
}
// Use goimports to format the generated source and imports.
pretty, err := runner(buf.Bytes(), filepath.Join(runtime.GOROOT(), "bin", "gofmt"), "-s")
if err != nil {
// We shouldn't see an error; it means we generated invalid code.
fmt.Printf("%s", buf.Bytes())
panic(fmt.Errorf("vdl: generated invalid Go code for %v: %v", pkg.Path, err))
}
// Use goimports to format the generated source and imports.
pretty, err = runner(pretty, "goimports")
if err != nil {
// We shouldn't see an error; it means we generated invalid code.
fmt.Printf("%s", pretty)
panic(fmt.Errorf("vdl: generated invalid Go code for %v: %v", pkg.Path, err))
}
return pretty
}
func runner(buf []byte, binary string, args ...string) ([]byte, error) {
cmd := exec.Command(binary, args...)
cmd.Stdin = bytes.NewBuffer(buf)
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to run %v: %v", strings.Join(cmd.Args, " "), err)
}
return output, nil
}
var goTemplate *template.Template
// The template mechanism is great at high-level formatting and simple
// substitution, but is bad at more complicated logic. We define some functions
// that we can use in the template so that when things get complicated we back
// off to a regular function.
func init() {
funcMap := template.FuncMap{
"firstRuneToExport": vdlutil.FirstRuneToExportCase,
"firstRuneToUpper": vdlutil.FirstRuneToUpper,
"firstRuneToLower": vdlutil.FirstRuneToLower,
"vdlZeroValue": vdl.ZeroValue,
"errorName": errorName,
"errorComment": errorComment,
"nativeType": nativeType,
"hasNativeTypes": hasNativeTypes,
"noCustomNative": noCustomNative,
"typeHasNoCustomNative": typeHasNoCustomNative,
"typeGo": typeGo,
"defineConst": defineConst,
"genValueOf": genValueOf,
"embedGo": embedGo,
"isStreamingMethod": isStreamingMethod,
"hasStreamingMethods": hasStreamingMethods,
"docBreak": docBreak,
"quoteStripDoc": parse.QuoteStripDoc,
"argNames": argNames,
"argTypes": argTypes,
"argNameTypes": argNameTypes,
"argParens": argParens,
"uniqueName": uniqueName,
"uniqueNameImpl": uniqueNameImpl,
"serverCallVar": serverCallVar,
"serverCallStubVar": serverCallStubVar,
"outArgsClient": outArgsClient,
"clientStubImpl": clientStubImpl,
"clientFinishImpl": clientFinishImpl,
"serverStubImpl": serverStubImpl,
"reInitStreamValue": reInitStreamValue,
"callVerror": callVerror,
"paramNamedResults": paramNamedResults,
}
goTemplate = template.Must(template.New("genGo").Funcs(funcMap).Parse(genGo))
}
func errorName(def *compile.ErrorDef) string {
switch {
case def.Exported:
return "Err" + def.Name
default:
return "err" + vdlutil.FirstRuneToUpper(def.Name)
}
}
func errorComment(def *compile.ErrorDef) string {
parts := strings.Fields(def.Doc)
errName := errorName(def)
// Make sure the comment starts with Err<name>....
if len(parts) > 0 && "Err"+parts[1] == errName {
return strings.Replace(def.Doc, parts[1], "Err"+parts[1], 1)
}
return def.Doc
}
func isStreamingMethod(method *compile.Method) bool {
return method.InStream != nil || method.OutStream != nil
}
func hasStreamingMethods(methods []*compile.Method) bool {
for _, method := range methods {
if isStreamingMethod(method) {
return true
}
}
return false
}
// docBreak adds a "//\n" break to separate previous comment lines and doc. If
// doc is empty it returns the empty string.
func docBreak(doc string) string {
if doc == "" {
return ""
}
return "//\n" + doc
}
// argTypes returns a comma-separated list of each type from args.
func argTypes(first, last string, data *goData, args []*compile.Field) string {
var result []string
if first != "" {
result = append(result, first)
}
for _, arg := range args {
result = append(result, typeGo(data, arg.Type))
}
if last != "" {
result = append(result, last)
}
return strings.Join(result, ", ")
}
// argNames returns a comma-separated list of each name from args. If argPrefix
// is empty, the name specified in args is used; otherwise the name is prefixD,
// where D is the position of the argument.
func argNames(boxPrefix, argPrefix, first, second, last string, args []*compile.Field) string {
var result []string
if first != "" {
result = append(result, first)
}
if second != "" {
result = append(result, second)
}
for ix, arg := range args {
name := arg.Name
if argPrefix != "" {
name = fmt.Sprintf("%s%d", argPrefix, ix)
}
if arg.Type == vdl.ErrorType {
// TODO(toddw): Also need to box user-defined external interfaces. Or can
// we remove this special-case now?
name = boxPrefix + name
}
result = append(result, name)
}
if last != "" {
result = append(result, last)
}
return strings.Join(result, ", ")
}
// argNameTypes returns a comma-separated list of "name type" from args. If
// argPrefix is empty, the name specified in args is used; otherwise the name is
// prefixD, where D is the position of the argument. If argPrefix is empty and
// no names are specified in args, no names will be output.
func argNameTypes(argPrefix, first, second, last string, data *goData, args []*compile.Field) string {
noNames := argPrefix == "" && !hasArgNames(args)
var result []string
if first != "" {
result = append(result, maybeStripArgName(first, noNames))
}
if second != "" {
result = append(result, maybeStripArgName(second, noNames))
}
for ax, arg := range args {
var name string
switch {
case noNames:
break
case argPrefix == "":
name = arg.Name + " "
default:
name = fmt.Sprintf("%s%d ", argPrefix, ax)
}
result = append(result, name+typeGo(data, arg.Type))
}
if last != "" {
result = append(result, maybeStripArgName(last, noNames))
}
return strings.Join(result, ", ")
}
func hasArgNames(args []*compile.Field) bool {
// VDL guarantees that either all args are named, or none of them are.
return len(args) > 0 && args[0].Name != ""
}
// maybeStripArgName strips away the first space-terminated token from arg, only
// if strip is true.
func maybeStripArgName(arg string, strip bool) string {
if index := strings.Index(arg, " "); index != -1 && strip {
return arg[index+1:]
}
return arg
}
// paramNamedResults returns a comma-separated list of "name type" from args
// in the order (first, second, args*, last)
func paramNamedResults(first, second, last string, data *goData, args []*compile.Field) string {
var result []string
if first != "" {
result = append(result, first)
}
if second != "" {
result = append(result, second)
}
for _, arg := range args {
result = append(result, arg.Name+" "+typeGo(data, arg.Type))
}
if last != "" {
result = append(result, last)
}
return strings.Join(result, ", ")
}
// argParens takes a list of 0 or more arguments, and adds parens only when
// necessary; if args contains any commas or spaces, we must add parens.
func argParens(argList string) string {
if strings.ContainsAny(argList, ", ") {
return "(" + argList + ")"
}
return argList
}
// uniqueName returns a unique name based on the interface, method and suffix.
func uniqueName(iface *compile.Interface, method *compile.Method, suffix string) string {
return iface.Name + method.Name + suffix
}
// uniqueNameImpl returns uniqueName with an "impl" prefix.
func uniqueNameImpl(iface *compile.Interface, method *compile.Method, suffix string) string {
return "impl" + uniqueName(iface, method, suffix)
}
// The first arg of every server method is a context; the type is either a typed
// context for streams, or rpc.ServerCall for non-streams.
func serverCallVar(name string, data *goData, iface *compile.Interface, method *compile.Method) string {
if isStreamingMethod(method) {
return name + " " + uniqueName(iface, method, "ServerCall")
}
return name + " " + data.Pkg("v.io/v23/rpc") + "ServerCall"
}
// The first arg of every server stub method is a context; the type is either a
// typed context stub for streams, or rpc.ServerCall for non-streams.
func serverCallStubVar(name string, data *goData, iface *compile.Interface, method *compile.Method) string {
if isStreamingMethod(method) {
return name + " *" + uniqueName(iface, method, "ServerCallStub")
}
return name + " " + data.Pkg("v.io/v23/rpc") + "ServerCall"
}
// outArgsClient returns the out args of an interface method on the client,
// wrapped in parens if necessary. The client side always returns a final
// error, in addition to the regular out-args.
func outArgsClient(argPrefix string, errName string, data *goData, iface *compile.Interface, method *compile.Method) string {
first, args := "", method.OutArgs
if isStreamingMethod(method) {
first, args = "ocall "+uniqueName(iface, method, "ClientCall"), nil
}
return argParens(argNameTypes(argPrefix, first, "", errName+" error", data, args))
}
// clientStubImpl returns the interface method client stub implementation.
func clientStubImpl(data *goData, iface *compile.Interface, method *compile.Method) string {
var buf bytes.Buffer
inargs := "nil"
if len(method.InArgs) > 0 {
inargs = "[]interface{}{" + argNames("&", "i", "", "", "", method.InArgs) + "}"
}
switch {
case isStreamingMethod(method):
fmt.Fprint(&buf, "\tvar call "+data.Pkg("v.io/v23/rpc")+"ClientCall\n")
fmt.Fprintf(&buf, "\tif call, err = "+data.Pkg("v.io/v23")+"GetClient(ctx).StartCall(ctx, c.name, %q, %s, opts...); err != nil {\n\t\treturn\n\t}\n", method.Name, inargs)
fmt.Fprintf(&buf, "ocall = &%s{ClientCall: call}\n", uniqueNameImpl(iface, method, "ClientCall"))
default:
outargs := "nil"
if len(method.OutArgs) > 0 {
outargs = "[]interface{}{" + argNames("", "&o", "", "", "", method.OutArgs) + "}"
}
fmt.Fprintf(&buf, "\terr = "+data.Pkg("v.io/v23")+"GetClient(ctx).Call(ctx, c.name, %q, %s, %s, opts...)\n", method.Name, inargs, outargs)
}
fmt.Fprint(&buf, "\treturn")
return buf.String() // the caller writes the trailing newline
}
// clientFinishImpl returns the client finish implementation for method.
func clientFinishImpl(varname string, method *compile.Method) string {
outargs := argNames("", "&o", "", "", "", method.OutArgs)
return fmt.Sprintf("\terr = %s.Finish(%s)", varname, outargs)
}
// serverStubImpl returns the interface method server stub implementation.
func serverStubImpl(data *goData, iface *compile.Interface, method *compile.Method) string {
var buf bytes.Buffer
inargs := argNames("", "i", "ctx", "call", "", method.InArgs)
fmt.Fprintf(&buf, "\treturn s.impl.%s(%s)", method.Name, inargs)
return buf.String() // the caller writes the trailing newline
}
func reInitStreamValue(data *goData, t *vdl.Type, name string) string {
switch t.Kind() {
case vdl.Struct:
return name + " = " + typeGo(data, t) + "{}\n"
case vdl.Any:
return name + " = nil\n"
}
return ""
}
func callVerror(data *goData, call string) string {
if data.Package.Name == "verror" {
return call
}
return "verror." + call
}
// The template that we execute against a goData instance to generate our
// code. Most of this is fairly straightforward substitution and ranges; more
// complicated logic is delegated to the helper functions above.
//
// We try to generate code that has somewhat reasonable formatting, and leave
// the fine-tuning to the go/format package. Note that go/format won't fix
// some instances of spurious newlines, so we try to keep it reasonable.
const genGo = `
{{$data := .}}
{{$pkg := $data.Package}}
{{$pkg.FileDoc}}
// This file was auto-generated by the vanadium vdl tool.
// Package: {{$pkg.Name}}
{{$pkg.Doc}}//
//nolint:revive
package {{$pkg.Name}}
{{if $data.Imports}}
import (
{{range $imp := $data.Imports}}
{{if $imp.Name}}{{$imp.Name}} {{end}}"{{$imp.Path}}"{{end}}
){{end}}
var initializeVDLCalled = false
var _ = initializeVDL() // Must be first; see initializeVDL comments for details.
{{if $pkg.TypeDefs}}
{{$data.DeclareTypeOfVars}}
// Type definitions
// ================
{{$data.VDLTypeDefinitions}}
{{if hasNativeTypes $data}}
// Type-check native conversion functions.
var (
{{range $wire, $native := $pkg.Config.Go.WireToNativeTypes}}{{if noCustomNative $native}}{{$nat := nativeType $data $native $pkg}}
_ func({{$wire}}, *{{$nat}}) error = {{$wire}}ToNative
_ func(*{{$wire}}, {{$nat}}) error = {{$wire}}FromNative{{end}}{{end}}
)
{{end}}
{{end}}
{{if $pkg.ConstDefs}}
// Const definitions
// =================
{{range $cdef := $pkg.ConstDefs}}
{{defineConst $data $cdef}}{{end}}
{{end}}
{{if $pkg.ErrorDefs}}
// Error definitions
// =================
var (
{{range $edef := $pkg.ErrorDefs}}
{{errorComment $edef}}{{errorName $edef}} = {{$data.Pkg "v.io/v23/verror"}}NewIDAction("{{$edef.ID}}", {{$data.Pkg "v.io/v23/verror"}}{{$edef.RetryCode}}){{end}}
)
{{range $edef := $pkg.ErrorDefs}}
{{$errName := errorName $edef}}
{{$newErr := print (firstRuneToExport "New" $edef.Exported) (firstRuneToUpper $errName)}}
{{$errorf := print (firstRuneToExport "Errorf" $edef.Exported) (firstRuneToUpper $edef.Name)}}
{{$message := print (firstRuneToExport "Message" $edef.Exported) (firstRuneToUpper $edef.Name)}}
// {{$errorf}} calls {{$errName}}.Errorf with the supplied arguments.
func {{$errorf}}(ctx {{(print "*" ($data.Pkg "v.io/v23/context") "T")}}, format string, {{argNameTypes "" "" "" "" $data $edef.Params}}) error {
return {{$errName}}.Errorf({{argNames "" "" "ctx" "format" "" $edef.Params}})
}
// {{$message}} calls {{$errName}}.Message with the supplied arguments.
func {{$message}}(ctx {{(print "*" ($data.Pkg "v.io/v23/context") "T")}}, message string, {{argNameTypes "" "" "" "" $data $edef.Params}}) error {
return {{$errName}}.Message({{argNames "" "" "ctx" "message" "" $edef.Params}})
}
{{$params := print (firstRuneToExport "Params" $edef.Exported) (firstRuneToUpper $errName)}}
// {{$params}} extracts the expected parameters from the error's ParameterList.
func {{$params}}(argumentError error) ({{paramNamedResults "verrorComponent string" "verrorOperation string" "returnErr error" $data $edef.Params}}) {
params := {{callVerror $data "Params(argumentError)"}}
if params == nil {
returnErr = fmt.Errorf("no parameters found in: %T: %v", argumentError, argumentError)
return
}
iter := ¶mListIterator{params: params, max: len(params)}
if verrorComponent, verrorOperation, returnErr = iter.preamble(); returnErr != nil {
return
}
{{if $edef.Params}}
var (
tmp interface{}
ok bool
)
{{range $edef.Params}}tmp, returnErr = iter.next()
if {{.Name}}, ok = tmp.({{typeGo $data .Type}}); !ok {
if returnErr != nil {
return
}
returnErr = fmt.Errorf("parameter list contains the wrong type for return value {{.Name}}, has %T and not {{typeGo $data .Type}}", tmp)
return
}
{{end}}{{end}}
return
}
{{end}}
{{end}}
{{if $pkg.ErrorDefs}}
type paramListIterator struct {
err error
idx, max int
params []interface{}
}
func (pl *paramListIterator) next() (interface{}, error) {
if pl.err != nil {
return nil, pl.err
}
if pl.idx+1 > pl.max {
pl.err = fmt.Errorf("too few parameters: have %v", pl.max)
return nil, pl.err
}
pl.idx++
return pl.params[pl.idx-1], nil
}
func (pl *paramListIterator) preamble() (component, operation string, err error) {
var tmp interface{}
if tmp, err = pl.next(); err != nil {
return
}
var ok bool
if component, ok = tmp.(string); !ok {
return "", "", fmt.Errorf("ParamList[0]: component name is not a string: %T", tmp)
}
if tmp, err = pl.next(); err != nil {
return
}
if operation, ok = tmp.(string); !ok {
return "", "", fmt.Errorf("ParamList[1]: operation name is not a string: %T", tmp)
}
return
}
{{end}}
{{if $pkg.Interfaces}}
// Interface definitions
// =====================
{{range $iface := $pkg.Interfaces}}
{{$ifaceStreaming := hasStreamingMethods $iface.AllMethods}}
{{$rpc_ := $data.Pkg "v.io/v23/rpc"}}
// {{$iface.Name}}ClientMethods is the client interface
// containing {{$iface.Name}} methods.
{{docBreak $iface.Doc}}type {{$iface.Name}}ClientMethods interface { {{range $embed := $iface.Embeds}}
{{$embed.Doc}}{{embedGo $data $embed}}ClientMethods{{$embed.DocSuffix}}{{end}}{{range $method := $iface.Methods}}
{{$method.Doc}}{{$method.Name}}({{argNameTypes "" ($data.CtxVar "_") "" ($data.OptsVar "_") $data $method.InArgs}}) {{outArgsClient "" "_" $data $iface $method}}{{$method.DocSuffix}}{{end}}
}
// {{$iface.Name}}ClientStub embeds {{$iface.Name}}ClientMethods and is a
// placeholder for additional management operations.
type {{$iface.Name}}ClientStub interface {
{{$iface.Name}}ClientMethods
}
// {{$iface.Name}}Client returns a client stub for {{$iface.Name}}.
func {{$iface.Name}}Client(name string) {{$iface.Name}}ClientStub {
return impl{{$iface.Name}}ClientStub{name{{range $embed := $iface.Embeds}}, {{embedGo $data $embed}}Client(name){{end}} }
}
type impl{{$iface.Name}}ClientStub struct {
name string
{{range $embed := $iface.Embeds}}
{{embedGo $data $embed}}ClientStub{{end}}
}
{{range $method := $iface.Methods}}
func (c impl{{$iface.Name}}ClientStub) {{$method.Name}}({{argNameTypes "i" ($data.CtxVar "ctx") "" ($data.OptsVar "opts") $data $method.InArgs}}) {{outArgsClient "o" "err" $data $iface $method}} {
{{clientStubImpl $data $iface $method}}
}
{{end}}
{{range $method := $iface.Methods}}{{if isStreamingMethod $method}}
{{$clientStream := uniqueName $iface $method "ClientStream"}}
{{$clientCall := uniqueName $iface $method "ClientCall"}}
{{$clientCallImpl := uniqueNameImpl $iface $method "ClientCall"}}
{{$clientRecvImpl := uniqueNameImpl $iface $method "ClientCallRecv"}}
{{$clientSendImpl := uniqueNameImpl $iface $method "ClientCallSend"}}
// {{$clientStream}} is the client stream for {{$iface.Name}}.{{$method.Name}}.
type {{$clientStream}} interface { {{if $method.OutStream}}
// RecvStream returns the receiver side of the {{$iface.Name}}.{{$method.Name}} client stream.
RecvStream() interface {
// Advance stages an item so that it may be retrieved via Value. Returns
// true iff there is an item to retrieve. Advance must be called before
// Value is called. May block if an item is not available.
Advance() bool
// Value returns the item that was staged by Advance. May panic if Advance
// returned false or was not called. Never blocks.
Value() {{typeGo $data $method.OutStream}}
// Err returns any error encountered by Advance. Never blocks.
Err() error
} {{end}}{{if $method.InStream}}
// SendStream returns the send side of the {{$iface.Name}}.{{$method.Name}} client stream.
SendStream() interface {
// Send places the item onto the output stream. Returns errors
// encountered while sending, or if Send is called after Close or
// the stream has been canceled. Blocks if there is no buffer
// space; will unblock when buffer space is available or after
// the stream has been canceled.
Send(item {{typeGo $data $method.InStream}}) error
// Close indicates to the server that no more items will be sent;
// server Recv calls will receive io.EOF after all sent items.
// This is an optional call - e.g. a client might call Close if it
// needs to continue receiving items from the server after it's
// done sending. Returns errors encountered while closing, or if
// Close is called after the stream has been canceled. Like Send,
// blocks if there is no buffer space available.
Close() error
} {{end}}
}
// {{$clientCall}} represents the call returned from {{$iface.Name}}.{{$method.Name}}.
type {{$clientCall}} interface {
{{$clientStream}} {{if $method.InStream}}
// Finish performs the equivalent of SendStream().Close, then blocks until
// the server is done, and returns the positional return values for the call.{{else}}
// Finish blocks until the server is done, and returns the positional return
// values for call.{{end}}
//
// Finish returns immediately if the call has been canceled; depending on the
// timing the output could either be an error signaling cancelation, or the
// valid positional return values from the server.
//
// Calling Finish is mandatory for releasing stream resources, unless the call
// has been canceled or any of the other methods return an error. Finish should
// be called at most once.
Finish() {{argParens (argNameTypes "" "" "" "_ error" $data $method.OutArgs)}}
}
type {{$clientCallImpl}} struct {
{{$rpc_}}ClientCall{{if $method.OutStream}}
valRecv {{typeGo $data $method.OutStream}}
errRecv error{{end}}
}
{{if $method.OutStream}}func (c *{{$clientCallImpl}}) RecvStream() interface {
Advance() bool
Value() {{typeGo $data $method.OutStream}}
Err() error
} {
return {{$clientRecvImpl}}{c}
}
type {{$clientRecvImpl}} struct {
c *{{$clientCallImpl}}
}
func (c {{$clientRecvImpl}}) Advance() bool {
{{reInitStreamValue $data $method.OutStream "c.c.valRecv"}}c.c.errRecv = c.c.Recv(&c.c.valRecv)
return c.c.errRecv == nil
}
func (c {{$clientRecvImpl}}) Value() {{typeGo $data $method.OutStream}} {
return c.c.valRecv
}
func (c {{$clientRecvImpl}}) Err() error {
if c.c.errRecv == {{$data.Pkg "io"}}EOF {
return nil
}
return c.c.errRecv
}
{{end}}{{if $method.InStream}}func (c *{{$clientCallImpl}}) SendStream() interface {
Send(item {{typeGo $data $method.InStream}}) error
Close() error
} {
return {{$clientSendImpl}}{c}
}
type {{$clientSendImpl}} struct {
c *{{$clientCallImpl}}
}
func (c {{$clientSendImpl}}) Send(item {{typeGo $data $method.InStream}}) error {
return c.c.Send(item)
}
func (c {{$clientSendImpl}}) Close() error {
return c.c.CloseSend()
}
{{end}}func (c *{{$clientCallImpl}}) Finish() {{argParens (argNameTypes "o" "" "" "err error" $data $method.OutArgs)}} {
{{clientFinishImpl "c.ClientCall" $method}}
return
}
{{end}}
{{end}}
// {{$iface.Name}}ServerMethods is the interface a server writer
// implements for {{$iface.Name}}.
{{docBreak $iface.Doc}}type {{$iface.Name}}ServerMethods interface { {{range $embed := $iface.Embeds}}
{{$embed.Doc}}{{embedGo $data $embed}}ServerMethods{{$embed.DocSuffix}}{{end}}{{range $method := $iface.Methods}}
{{$method.Doc}}{{$method.Name}}({{argNameTypes "" ($data.CtxVar "_") (serverCallVar "_" $data $iface $method) "" $data $method.InArgs}}) {{argParens (argNameTypes "" "" "" "_ error" $data $method.OutArgs)}}{{$method.DocSuffix}}{{end}}
}
// {{$iface.Name}}ServerStubMethods is the server interface containing
// {{$iface.Name}} methods, as expected by rpc.Server.{{if $ifaceStreaming}}
// The only difference between this interface and {{$iface.Name}}ServerMethods
// is the streaming methods.{{else}}
// There is no difference between this interface and {{$iface.Name}}ServerMethods
// since there are no streaming methods.{{end}}
type {{$iface.Name}}ServerStubMethods {{if $ifaceStreaming}}interface { {{range $embed := $iface.Embeds}}
{{$embed.Doc}}{{embedGo $data $embed}}ServerStubMethods{{$embed.DocSuffix}}{{end}}{{range $method := $iface.Methods}}
{{$method.Doc}}{{$method.Name}}({{argNameTypes "" ($data.CtxVar "_") (serverCallStubVar "_" $data $iface $method) "" $data $method.InArgs}}) {{argParens (argNameTypes "" "" "" "_ error" $data $method.OutArgs)}}{{$method.DocSuffix}}{{end}}
}
{{else}}{{$iface.Name}}ServerMethods
{{end}}
// {{$iface.Name}}ServerStub adds universal methods to {{$iface.Name}}ServerStubMethods.
type {{$iface.Name}}ServerStub interface {
{{$iface.Name}}ServerStubMethods
// DescribeInterfaces the {{$iface.Name}} interfaces.
Describe__() []{{$rpc_}}InterfaceDesc
}
// {{$iface.Name}}Server returns a server stub for {{$iface.Name}}.
// It converts an implementation of {{$iface.Name}}ServerMethods into
// an object that may be used by rpc.Server.
func {{$iface.Name}}Server(impl {{$iface.Name}}ServerMethods) {{$iface.Name}}ServerStub {
stub := impl{{$iface.Name}}ServerStub{
impl: impl,{{range $embed := $iface.Embeds}}
{{$embed.Name}}ServerStub: {{embedGo $data $embed}}Server(impl),{{end}}
}
// Initialize GlobState; always check the stub itself first, to handle the
// case where the user has the Glob method defined in their VDL source.
if gs := {{$rpc_}}NewGlobState(stub); gs != nil {
stub.gs = gs
} else if gs := {{$rpc_}}NewGlobState(impl); gs != nil {
stub.gs = gs
}
return stub
}
type impl{{$iface.Name}}ServerStub struct {
impl {{$iface.Name}}ServerMethods{{range $embed := $iface.Embeds}}
{{embedGo $data $embed}}ServerStub{{end}}
gs *{{$rpc_}}GlobState
}
{{range $method := $iface.Methods}}
func (s impl{{$iface.Name}}ServerStub) {{$method.Name}}({{argNameTypes "i" ($data.CtxVar "ctx") (serverCallStubVar "call" $data $iface $method) "" $data $method.InArgs}}) {{argParens (argTypes "" "error" $data $method.OutArgs)}} {
{{serverStubImpl $data $iface $method}}
}
{{end}}
func (s impl{{$iface.Name}}ServerStub) Globber() *{{$rpc_}}GlobState {
return s.gs
}
func (s impl{{$iface.Name}}ServerStub) Describe__() []{{$rpc_}}InterfaceDesc {
return []{{$rpc_}}InterfaceDesc{ {{$iface.Name}}Desc{{range $embed := $iface.TransitiveEmbeds}}, {{embedGo $data $embed}}Desc{{end}} }
}
// {{$iface.Name}}Desc describes the {{$iface.Name}} interface.
var {{$iface.Name}}Desc {{$rpc_}}InterfaceDesc = desc{{$iface.Name}}
// desc{{$iface.Name}} hides the desc to keep godoc clean.
var desc{{$iface.Name}} = {{$rpc_}}InterfaceDesc{ {{if $iface.Name}}
Name: "{{$iface.Name}}",{{end}}{{if $iface.File.Package.Path}}
PkgPath: "{{$iface.File.Package.Path}}",{{end}}{{if $iface.Doc}}
Doc: {{quoteStripDoc $iface.Doc}},{{end}}{{if $iface.Embeds}}
Embeds: []{{$rpc_}}EmbedDesc{ {{range $embed := $iface.Embeds}}
{ Name: "{{$embed.Name}}", PkgPath: "{{$embed.File.Package.Path}}", Doc: {{quoteStripDoc $embed.Doc}} },{{end}}
},{{end}}{{if $iface.Methods}}
Methods: []{{$rpc_}}MethodDesc{ {{range $method := $iface.Methods}}
{ {{if $method.Name}}
Name: "{{$method.Name}}",{{end}}{{if $method.Doc}}
Doc: {{quoteStripDoc $method.Doc}},{{end}}{{if $method.InArgs}}
InArgs: []{{$rpc_}}ArgDesc{ {{range $arg := $method.InArgs}}
{ Name: "{{$arg.Name}}", Doc: {{quoteStripDoc $arg.Doc}} }, // {{typeGo $data $arg.Type}}{{end}}
},{{end}}{{if $method.OutArgs}}
OutArgs: []{{$rpc_}}ArgDesc{ {{range $arg := $method.OutArgs}}
{ Name: "{{$arg.Name}}", Doc: {{quoteStripDoc $arg.Doc}} }, // {{typeGo $data $arg.Type}}{{end}}
},{{end}}{{if $method.Tags}}
Tags: []*{{$data.Pkg "v.io/v23/vdl"}}Value{ {{range $tag := $method.Tags}}{{genValueOf $data $tag}} ,{{end}} },{{end}}
},{{end}}
},{{end}}
}