-
Notifications
You must be signed in to change notification settings - Fork 808
/
generator.go
3444 lines (3172 loc) · 111 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
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
The code generator for the plugin for the Google protocol buffer compiler.
It generates Go code from the protocol buffer description files read by the
main routine.
*/
package generator
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"path"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/gogo/protobuf/gogoproto"
"github.com/gogo/protobuf/proto"
descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/gogo/protobuf/protoc-gen-gogo/generator/internal/remap"
plugin "github.com/gogo/protobuf/protoc-gen-gogo/plugin"
)
// generatedCodeVersion indicates a version of the generated code.
// It is incremented whenever an incompatibility between the generated code and
// proto package is introduced; the generated code references
// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
const generatedCodeVersion = 3
// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
type Plugin interface {
// Name identifies the plugin.
Name() string
// Init is called once after data structures are built but before
// code generation begins.
Init(g *Generator)
// Generate produces the code generated by the plugin for this file,
// except for the imports, by calling the generator's methods P, In, and Out.
Generate(file *FileDescriptor)
// GenerateImports produces the import declarations for this file.
// It is called after Generate.
GenerateImports(file *FileDescriptor)
}
type pluginSlice []Plugin
func (ps pluginSlice) Len() int {
return len(ps)
}
func (ps pluginSlice) Less(i, j int) bool {
return ps[i].Name() < ps[j].Name()
}
func (ps pluginSlice) Swap(i, j int) {
ps[i], ps[j] = ps[j], ps[i]
}
var plugins pluginSlice
// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
// It is typically called during initialization.
func RegisterPlugin(p Plugin) {
plugins = append(plugins, p)
}
// A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf".
type GoImportPath string
func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
// A GoPackageName is the name of a Go package. e.g., "protobuf".
type GoPackageName string
// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
// a pointer to the FileDescriptorProto that represents it. These types achieve that
// wrapping by placing each Proto inside a struct with the pointer to its File. The
// structs have the same names as their contents, with "Proto" removed.
// FileDescriptor is used to store the things that it points to.
// The file and package name method are common to messages and enums.
type common struct {
file *FileDescriptor // File this object comes from.
}
// GoImportPath is the import path of the Go package containing the type.
func (c *common) GoImportPath() GoImportPath {
return c.file.importPath
}
func (c *common) File() *FileDescriptor { return c.file }
func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
return file.GetSyntax() == "proto3"
}
func (c *common) proto3() bool { return fileIsProto3(c.file.FileDescriptorProto) }
// Descriptor represents a protocol buffer message.
type Descriptor struct {
common
*descriptor.DescriptorProto
parent *Descriptor // The containing message, if any.
nested []*Descriptor // Inner messages, if any.
enums []*EnumDescriptor // Inner enums, if any.
ext []*ExtensionDescriptor // Extensions, if any.
typename []string // Cached typename vector.
index int // The index into the container, whether the file or another message.
path string // The SourceCodeInfo path as comma-separated integers.
group bool
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (d *Descriptor) TypeName() []string {
if d.typename != nil {
return d.typename
}
n := 0
for parent := d; parent != nil; parent = parent.parent {
n++
}
s := make([]string, n)
for parent := d; parent != nil; parent = parent.parent {
n--
s[n] = parent.GetName()
}
d.typename = s
return s
}
func (d *Descriptor) allowOneof() bool {
return true
}
// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type EnumDescriptor struct {
common
*descriptor.EnumDescriptorProto
parent *Descriptor // The containing message, if any.
typename []string // Cached typename vector.
index int // The index into the container, whether the file or a message.
path string // The SourceCodeInfo path as comma-separated integers.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *EnumDescriptor) TypeName() (s []string) {
if e.typename != nil {
return e.typename
}
name := e.GetName()
if e.parent == nil {
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
e.typename = s
return s
}
// alias provides the TypeName corrected for the application of any naming
// extensions on the enum type. It should be used for generating references to
// the Go types and for calculating prefixes.
func (e *EnumDescriptor) alias() (s []string) {
s = e.TypeName()
if gogoproto.IsEnumCustomName(e.EnumDescriptorProto) {
s[len(s)-1] = gogoproto.GetEnumCustomName(e.EnumDescriptorProto)
}
return
}
// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
func (e *EnumDescriptor) prefix() string {
typeName := e.alias()
if e.parent == nil {
// If the enum is not part of a message, the prefix is just the type name.
return CamelCase(typeName[len(typeName)-1]) + "_"
}
return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
}
// The integer value of the named constant in this enumerated type.
func (e *EnumDescriptor) integerValueAsString(name string) string {
for _, c := range e.Value {
if c.GetName() == name {
return fmt.Sprint(c.GetNumber())
}
}
log.Fatal("cannot find value for enum constant")
return ""
}
// ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type ExtensionDescriptor struct {
common
*descriptor.FieldDescriptorProto
parent *Descriptor // The containing message, if any.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *ExtensionDescriptor) TypeName() (s []string) {
name := e.GetName()
if e.parent == nil {
// top-level extension
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
return s
}
// DescName returns the variable name used for the generated descriptor.
func (e *ExtensionDescriptor) DescName() string {
// The full type name.
typeName := e.TypeName()
// Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
for i, s := range typeName {
typeName[i] = CamelCase(s)
}
return "E_" + strings.Join(typeName, "_")
}
// ImportedDescriptor describes a type that has been publicly imported from another file.
type ImportedDescriptor struct {
common
o Object
}
func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
// FileDescriptor describes an protocol buffer descriptor file (.proto).
// It includes slices of all the messages and enums defined within it.
// Those slices are constructed by WrapTypes.
type FileDescriptor struct {
*descriptor.FileDescriptorProto
desc []*Descriptor // All the messages defined in this file.
enum []*EnumDescriptor // All the enums defined in this file.
ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
// Comments, stored as a map of path (comma-separated integers) to the comment.
comments map[string]*descriptor.SourceCodeInfo_Location
// The full list of symbols that are exported,
// as a map from the exported object to its symbols.
// This is used for supporting public imports.
exported map[Object][]symbol
importPath GoImportPath // Import path of this file's package.
packageName GoPackageName // Name of this file's Go package.
proto3 bool // whether to generate proto3 code for this file
}
// VarName is the variable name we'll use in the generated code to refer
// to the compressed bytes of this descriptor. It is not exported, so
// it is only valid inside the generated package.
func (d *FileDescriptor) VarName() string {
h := sha256.Sum256([]byte(d.GetName()))
return fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(h[:8]))
}
// goPackageOption interprets the file's go_package option.
// If there is no go_package, it returns ("", "", false).
// If there's a simple name, it returns ("", pkg, true).
// If the option implies an import path, it returns (impPath, pkg, true).
func (d *FileDescriptor) goPackageOption() (impPath GoImportPath, pkg GoPackageName, ok bool) {
opt := d.GetOptions().GetGoPackage()
if opt == "" {
return "", "", false
}
// A semicolon-delimited suffix delimits the import path and package name.
sc := strings.Index(opt, ";")
if sc >= 0 {
return GoImportPath(opt[:sc]), cleanPackageName(opt[sc+1:]), true
}
// The presence of a slash implies there's an import path.
slash := strings.LastIndex(opt, "/")
if slash >= 0 {
return GoImportPath(opt), cleanPackageName(opt[slash+1:]), true
}
return "", cleanPackageName(opt), true
}
// goFileName returns the output name for the generated Go file.
func (d *FileDescriptor) goFileName(pathType pathType) string {
name := *d.Name
if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
name = name[:len(name)-len(ext)]
}
name += ".pb.go"
if pathType == pathTypeSourceRelative {
return name
}
// Does the file have a "go_package" option?
// If it does, it may override the filename.
if impPath, _, ok := d.goPackageOption(); ok && impPath != "" {
// Replace the existing dirname with the declared import path.
_, name = path.Split(name)
name = path.Join(string(impPath), name)
return name
}
return name
}
func (d *FileDescriptor) addExport(obj Object, sym symbol) {
d.exported[obj] = append(d.exported[obj], sym)
}
// symbol is an interface representing an exported Go symbol.
type symbol interface {
// GenerateAlias should generate an appropriate alias
// for the symbol from the named package.
GenerateAlias(g *Generator, filename string, pkg GoPackageName)
}
type messageSymbol struct {
sym string
hasExtensions, isMessageSet bool
oneofTypes []string
}
type getterSymbol struct {
name string
typ string
typeName string // canonical name in proto world; empty for proto.Message and similar
genType bool // whether typ contains a generated type (message/group/enum)
}
func (ms *messageSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
g.P("// ", ms.sym, " from public import ", filename)
g.P("type ", ms.sym, " = ", pkg, ".", ms.sym)
for _, name := range ms.oneofTypes {
g.P("type ", name, " = ", pkg, ".", name)
}
}
type enumSymbol struct {
name string
proto3 bool // Whether this came from a proto3 file.
}
func (es enumSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
s := es.name
g.P("// ", s, " from public import ", filename)
g.P("type ", s, " = ", pkg, ".", s)
g.P("var ", s, "_name = ", pkg, ".", s, "_name")
g.P("var ", s, "_value = ", pkg, ".", s, "_value")
}
type constOrVarSymbol struct {
sym string
typ string // either "const" or "var"
cast string // if non-empty, a type cast is required (used for enums)
}
func (cs constOrVarSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
v := string(pkg) + "." + cs.sym
if cs.cast != "" {
v = cs.cast + "(" + v + ")"
}
g.P(cs.typ, " ", cs.sym, " = ", v)
}
// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
type Object interface {
GoImportPath() GoImportPath
TypeName() []string
File() *FileDescriptor
}
// Generator is the type whose methods generate the output, stored in the associated response structure.
type Generator struct {
*bytes.Buffer
Request *plugin.CodeGeneratorRequest // The input.
Response *plugin.CodeGeneratorResponse // The output.
Param map[string]string // Command-line parameters.
PackageImportPath string // Go import path of the package we're generating code for
ImportPrefix string // String to prefix to imported package file names.
ImportMap map[string]string // Mapping from .proto file name to import path
Pkg map[string]string // The names under which we import support packages
outputImportPath GoImportPath // Package we're generating code for.
allFiles []*FileDescriptor // All files in the tree
allFilesByName map[string]*FileDescriptor // All files by filename.
genFiles []*FileDescriptor // Those files we will generate output for.
file *FileDescriptor // The file we are compiling now.
packageNames map[GoImportPath]GoPackageName // Imported package names in the current file.
usedPackages map[GoImportPath]bool // Packages used in current file.
usedPackageNames map[GoPackageName]bool // Package names used in the current file.
addedImports map[GoImportPath]bool // Additional imports to emit.`
typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
init []string // Lines to emit in the init function.
indent string
pathType pathType // How to generate output filenames.
writeOutput bool
annotateCode bool // whether to store annotations
annotations []*descriptor.GeneratedCodeInfo_Annotation // annotations to store
customImports []string
writtenImports map[string]bool // For de-duplicating written imports
}
type pathType int
const (
pathTypeImport pathType = iota
pathTypeSourceRelative
)
// New creates a new generator and allocates the request and response protobufs.
func New() *Generator {
g := new(Generator)
g.Buffer = new(bytes.Buffer)
g.Request = new(plugin.CodeGeneratorRequest)
g.Response = new(plugin.CodeGeneratorResponse)
g.writtenImports = make(map[string]bool)
g.addedImports = make(map[GoImportPath]bool)
return g
}
// Error reports a problem, including an error, and exits the program.
func (g *Generator) Error(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("protoc-gen-gogo: error:", s)
os.Exit(1)
}
// Fail reports a problem and exits the program.
func (g *Generator) Fail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("protoc-gen-gogo: error:", s)
os.Exit(1)
}
// CommandLineParameters breaks the comma-separated list of key=value pairs
// in the parameter (a member of the request protobuf) into a key/value map.
// It then sets file name mappings defined by those entries.
func (g *Generator) CommandLineParameters(parameter string) {
g.Param = make(map[string]string)
for _, p := range strings.Split(parameter, ",") {
if i := strings.Index(p, "="); i < 0 {
g.Param[p] = ""
} else {
g.Param[p[0:i]] = p[i+1:]
}
}
g.ImportMap = make(map[string]string)
pluginList := "none" // Default list of plugin names to enable (empty means all).
for k, v := range g.Param {
switch k {
case "import_prefix":
g.ImportPrefix = v
case "import_path":
g.PackageImportPath = v
case "paths":
switch v {
case "import":
g.pathType = pathTypeImport
case "source_relative":
g.pathType = pathTypeSourceRelative
default:
g.Fail(fmt.Sprintf(`Unknown path type %q: want "import" or "source_relative".`, v))
}
case "plugins":
pluginList = v
case "annotate_code":
if v == "true" {
g.annotateCode = true
}
default:
if len(k) > 0 && k[0] == 'M' {
g.ImportMap[k[1:]] = v
}
}
}
if pluginList == "" {
return
}
if pluginList == "none" {
pluginList = ""
}
gogoPluginNames := []string{"unmarshal", "unsafeunmarshaler", "union", "stringer", "size", "protosizer", "populate", "marshalto", "unsafemarshaler", "gostring", "face", "equal", "enumstringer", "embedcheck", "description", "defaultcheck", "oneofcheck", "compare"}
pluginList = strings.Join(append(gogoPluginNames, pluginList), "+")
if pluginList != "" {
// Amend the set of plugins.
enabled := make(map[string]bool)
for _, name := range strings.Split(pluginList, "+") {
enabled[name] = true
}
var nplugins pluginSlice
for _, p := range plugins {
if enabled[p.Name()] {
nplugins = append(nplugins, p)
}
}
sort.Sort(nplugins)
plugins = nplugins
}
}
// DefaultPackageName returns the package name printed for the object.
// If its file is in a different package, it returns the package name we're using for this file, plus ".".
// Otherwise it returns the empty string.
func (g *Generator) DefaultPackageName(obj Object) string {
importPath := obj.GoImportPath()
if importPath == g.outputImportPath {
return ""
}
return string(g.GoPackageName(importPath)) + "."
}
// GoPackageName returns the name used for a package.
func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName {
if name, ok := g.packageNames[importPath]; ok {
return name
}
name := cleanPackageName(baseName(string(importPath)))
for i, orig := 1, name; g.usedPackageNames[name] || isGoPredeclaredIdentifier[string(name)]; i++ {
name = orig + GoPackageName(strconv.Itoa(i))
}
if g.packageNames == nil {
g.packageNames = make(map[GoImportPath]GoPackageName)
}
g.packageNames[importPath] = name
if g.usedPackageNames == nil {
g.usedPackageNames = make(map[GoPackageName]bool)
}
g.usedPackageNames[name] = true
return name
}
// AddImport adds a package to the generated file's import section.
// It returns the name used for the package.
func (g *Generator) AddImport(importPath GoImportPath) GoPackageName {
g.addedImports[importPath] = true
return g.GoPackageName(importPath)
}
var globalPackageNames = map[GoPackageName]bool{
"fmt": true,
"math": true,
"proto": true,
}
// Create and remember a guaranteed unique package name. Pkg is the candidate name.
// The FileDescriptor parameter is unused.
func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
name := cleanPackageName(pkg)
for i, orig := 1, name; globalPackageNames[name]; i++ {
name = orig + GoPackageName(strconv.Itoa(i))
}
globalPackageNames[name] = true
return string(name)
}
var isGoKeyword = map[string]bool{
"break": true,
"case": true,
"chan": true,
"const": true,
"continue": true,
"default": true,
"else": true,
"defer": true,
"fallthrough": true,
"for": true,
"func": true,
"go": true,
"goto": true,
"if": true,
"import": true,
"interface": true,
"map": true,
"package": true,
"range": true,
"return": true,
"select": true,
"struct": true,
"switch": true,
"type": true,
"var": true,
}
var isGoPredeclaredIdentifier = map[string]bool{
"append": true,
"bool": true,
"byte": true,
"cap": true,
"close": true,
"complex": true,
"complex128": true,
"complex64": true,
"copy": true,
"delete": true,
"error": true,
"false": true,
"float32": true,
"float64": true,
"imag": true,
"int": true,
"int16": true,
"int32": true,
"int64": true,
"int8": true,
"iota": true,
"len": true,
"make": true,
"new": true,
"nil": true,
"panic": true,
"print": true,
"println": true,
"real": true,
"recover": true,
"rune": true,
"string": true,
"true": true,
"uint": true,
"uint16": true,
"uint32": true,
"uint64": true,
"uint8": true,
"uintptr": true,
}
func cleanPackageName(name string) GoPackageName {
name = strings.Map(badToUnderscore, name)
// Identifier must not be keyword: insert _.
if isGoKeyword[name] {
name = "_" + name
}
// Identifier must not begin with digit: insert _.
if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
name = "_" + name
}
return GoPackageName(name)
}
// defaultGoPackage returns the package name to use,
// derived from the import path of the package we're building code for.
func (g *Generator) defaultGoPackage() GoPackageName {
p := g.PackageImportPath
if i := strings.LastIndex(p, "/"); i >= 0 {
p = p[i+1:]
}
return cleanPackageName(p)
}
// SetPackageNames sets the package name for this run.
// The package name must agree across all files being generated.
// It also defines unique package names for all imported files.
func (g *Generator) SetPackageNames() {
g.outputImportPath = g.genFiles[0].importPath
defaultPackageNames := make(map[GoImportPath]GoPackageName)
for _, f := range g.genFiles {
if _, p, ok := f.goPackageOption(); ok {
defaultPackageNames[f.importPath] = p
}
}
for _, f := range g.genFiles {
if _, p, ok := f.goPackageOption(); ok {
// Source file: option go_package = "quux/bar";
f.packageName = p
} else if p, ok := defaultPackageNames[f.importPath]; ok {
// A go_package option in another file in the same package.
//
// This is a poor choice in general, since every source file should
// contain a go_package option. Supported mainly for historical
// compatibility.
f.packageName = p
} else if p := g.defaultGoPackage(); p != "" {
// Command-line: import_path=quux/bar.
//
// The import_path flag sets a package name for files which don't
// contain a go_package option.
f.packageName = p
} else if p := f.GetPackage(); p != "" {
// Source file: package quux.bar;
f.packageName = cleanPackageName(p)
} else {
// Source filename.
f.packageName = cleanPackageName(baseName(f.GetName()))
}
}
// Check that all files have a consistent package name and import path.
for _, f := range g.genFiles[1:] {
if a, b := g.genFiles[0].importPath, f.importPath; a != b {
g.Fail(fmt.Sprintf("inconsistent package import paths: %v, %v", a, b))
}
if a, b := g.genFiles[0].packageName, f.packageName; a != b {
g.Fail(fmt.Sprintf("inconsistent package names: %v, %v", a, b))
}
}
// Names of support packages. These never vary (if there are conflicts,
// we rename the conflicting package), so this could be removed someday.
g.Pkg = map[string]string{
"fmt": "fmt",
"math": "math",
"proto": "proto",
"golang_proto": "golang_proto",
}
}
// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
// and FileDescriptorProtos into file-referenced objects within the Generator.
// It also creates the list of files to generate and so should be called before GenerateAllFiles.
func (g *Generator) WrapTypes() {
g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile))
g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles))
genFileNames := make(map[string]bool)
for _, n := range g.Request.FileToGenerate {
genFileNames[n] = true
}
for _, f := range g.Request.ProtoFile {
fd := &FileDescriptor{
FileDescriptorProto: f,
exported: make(map[Object][]symbol),
proto3: fileIsProto3(f),
}
// The import path may be set in a number of ways.
if substitution, ok := g.ImportMap[f.GetName()]; ok {
// Command-line: M=foo.proto=quux/bar.
//
// Explicit mapping of source file to import path.
fd.importPath = GoImportPath(substitution)
} else if genFileNames[f.GetName()] && g.PackageImportPath != "" {
// Command-line: import_path=quux/bar.
//
// The import_path flag sets the import path for every file that
// we generate code for.
fd.importPath = GoImportPath(g.PackageImportPath)
} else if p, _, _ := fd.goPackageOption(); p != "" {
// Source file: option go_package = "quux/bar";
//
// The go_package option sets the import path. Most users should use this.
fd.importPath = p
} else {
// Source filename.
//
// Last resort when nothing else is available.
fd.importPath = GoImportPath(path.Dir(f.GetName()))
}
// We must wrap the descriptors before we wrap the enums
fd.desc = wrapDescriptors(fd)
g.buildNestedDescriptors(fd.desc)
fd.enum = wrapEnumDescriptors(fd, fd.desc)
g.buildNestedEnums(fd.desc, fd.enum)
fd.ext = wrapExtensions(fd)
extractComments(fd)
g.allFiles = append(g.allFiles, fd)
g.allFilesByName[f.GetName()] = fd
}
for _, fd := range g.allFiles {
fd.imp = wrapImported(fd, g)
}
g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate))
for _, fileName := range g.Request.FileToGenerate {
fd := g.allFilesByName[fileName]
if fd == nil {
g.Fail("could not find file named", fileName)
}
g.genFiles = append(g.genFiles, fd)
}
}
// Scan the descriptors in this file. For each one, build the slice of nested descriptors
func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
for _, desc := range descs {
if len(desc.NestedType) != 0 {
for _, nest := range descs {
if nest.parent == desc {
desc.nested = append(desc.nested, nest)
}
}
if len(desc.nested) != len(desc.NestedType) {
g.Fail("internal error: nesting failure for", desc.GetName())
}
}
}
}
func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) {
for _, desc := range descs {
if len(desc.EnumType) != 0 {
for _, enum := range enums {
if enum.parent == desc {
desc.enums = append(desc.enums, enum)
}
}
if len(desc.enums) != len(desc.EnumType) {
g.Fail("internal error: enum nesting failure for", desc.GetName())
}
}
}
}
// Construct the Descriptor
func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *Descriptor {
d := &Descriptor{
common: common{file},
DescriptorProto: desc,
parent: parent,
index: index,
}
if parent == nil {
d.path = fmt.Sprintf("%d,%d", messagePath, index)
} else {
d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
}
// The only way to distinguish a group from a message is whether
// the containing message has a TYPE_GROUP field that matches.
if parent != nil {
parts := d.TypeName()
if file.Package != nil {
parts = append([]string{*file.Package}, parts...)
}
exp := "." + strings.Join(parts, ".")
for _, field := range parent.Field {
if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
d.group = true
break
}
}
}
for _, field := range desc.Extension {
d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d})
}
return d
}
// Return a slice of all the Descriptors defined within this file
func wrapDescriptors(file *FileDescriptor) []*Descriptor {
sl := make([]*Descriptor, 0, len(file.MessageType)+10)
for i, desc := range file.MessageType {
sl = wrapThisDescriptor(sl, desc, nil, file, i)
}
return sl
}
// Wrap this Descriptor, recursively
func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) []*Descriptor {
sl = append(sl, newDescriptor(desc, parent, file, index))
me := sl[len(sl)-1]
for i, nested := range desc.NestedType {
sl = wrapThisDescriptor(sl, nested, me, file, i)
}
return sl
}
// Construct the EnumDescriptor
func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *EnumDescriptor {
ed := &EnumDescriptor{
common: common{file},
EnumDescriptorProto: desc,
parent: parent,
index: index,
}
if parent == nil {
ed.path = fmt.Sprintf("%d,%d", enumPath, index)
} else {
ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
}
return ed
}
// Return a slice of all the EnumDescriptors defined within this file
func wrapEnumDescriptors(file *FileDescriptor, descs []*Descriptor) []*EnumDescriptor {
sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
// Top-level enums.
for i, enum := range file.EnumType {
sl = append(sl, newEnumDescriptor(enum, nil, file, i))
}
// Enums within messages. Enums within embedded messages appear in the outer-most message.
for _, nested := range descs {
for i, enum := range nested.EnumType {
sl = append(sl, newEnumDescriptor(enum, nested, file, i))
}
}
return sl
}
// Return a slice of all the top-level ExtensionDescriptors defined within this file.
func wrapExtensions(file *FileDescriptor) []*ExtensionDescriptor {
var sl []*ExtensionDescriptor
for _, field := range file.Extension {
sl = append(sl, &ExtensionDescriptor{common{file}, field, nil})
}
return sl
}
// Return a slice of all the types that are publicly imported into this file.
func wrapImported(file *FileDescriptor, g *Generator) (sl []*ImportedDescriptor) {
for _, index := range file.PublicDependency {
df := g.fileByName(file.Dependency[index])
for _, d := range df.desc {
if d.GetOptions().GetMapEntry() {
continue
}
sl = append(sl, &ImportedDescriptor{common{file}, d})
}
for _, e := range df.enum {
sl = append(sl, &ImportedDescriptor{common{file}, e})
}
for _, ext := range df.ext {
sl = append(sl, &ImportedDescriptor{common{file}, ext})
}
}
return
}
func extractComments(file *FileDescriptor) {
file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
for _, loc := range file.GetSourceCodeInfo().GetLocation() {
if loc.LeadingComments == nil {
continue
}
var p []string
for _, n := range loc.Path {
p = append(p, strconv.Itoa(int(n)))
}
file.comments[strings.Join(p, ",")] = loc
}
}