Debian Codegraph @

cmd/protoc-gen-yarpc/generator/generator.go

raw symbols SCIP
1 // Protocol Buffers for Go with Gadgets
2 //
3 // Copyright (c) 2013, The GoGo Authors. All rights reserved.
4 // http://github.com/gogo/protobuf
5 //
6 // Go support for Protocol Buffers - Google's data interchange format
7 //
8 // Copyright 2010 The Go Authors. All rights reserved.
9 // https://github.com/golang/protobuf
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // * Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 // * Redistributions in binary form must reproduce the above
18 // copyright notice, this list of conditions and the following disclaimer
19 // in the documentation and/or other materials provided with the
20 // distribution.
21 // * Neither the name of Google Inc. nor the names of its
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
37 /*
38 The code generator for the plugin for the Google protocol buffer compiler.
39 It generates Go code from the protocol buffer description files read by the
40 main routine.
41 */
42 package generator
43
44 import (
45 "bytes"
46 "fmt"
47 "log"
48 "os"
49 "path"
50 "strconv"
51 "strings"
52 "unicode"
53 "unicode/utf8"
54
55 "github.com/gogo/protobuf/gogoproto"
56 "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
57 plugin "github.com/gogo/protobuf/protoc-gen-gogo/plugin"
58 )
59
60 // generatedCodeVersion indicates a version of the generated code.
61 // It is incremented whenever an incompatibility between the generated code and
62 // proto package is introduced; the generated code references
63 // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
64 const generatedCodeVersion = 2
65
66 // A Plugin provides functionality to add to the output during Go code generation,
67 // such as to produce RPC stubs.
68 type Plugin interface {
69 // Name identifies the plugin.
70 Name() string
71 // Init is called once after data structures are built but before
72 // code generation begins.
73 Init(g *Generator)
74 // Generate produces the code generated by the plugin for this file,
75 // except for the imports, by calling the generator's methods P, In, and Out.
76 Generate(file *FileDescriptor)
77 // GenerateImports produces the import declarations for this file.
78 // It is called after Generate.
79 GenerateImports(file *FileDescriptor)
80 }
81
82 // Each type we import as a protocol buffer (other than FileDescriptorProto) needs
83 // a pointer to the FileDescriptorProto that represents it. These types achieve that
84 // wrapping by placing each Proto inside a struct with the pointer to its File. The
85 // structs have the same names as their contents, with "Proto" removed.
86 // FileDescriptor is used to store the things that it points to.
87
88 // The file and package name method are common to messages and enums.
89 type common struct {
90 file *descriptor.FileDescriptorProto // File this object comes from.
91 }
92
93 // PackageName is name in the package clause in the generated file.
94 func (c *common) PackageName() string { return uniquePackageOf(c.file) }
95
96 func (c *common) File() *descriptor.FileDescriptorProto { return c.file }
97
98 func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
99 return file.GetSyntax() == "proto3"
100 }
101
102 func (c *common) proto3() bool { return fileIsProto3(c.file) }
103
104 // Descriptor represents a protocol buffer message.
105 type Descriptor struct {
106 common
107 *descriptor.DescriptorProto
108 parent *Descriptor // The containing message, if any.
109 nested []*Descriptor // Inner messages, if any.
110 enums []*EnumDescriptor // Inner enums, if any.
111 ext []*ExtensionDescriptor // Extensions, if any.
112 typename []string // Cached typename vector.
113 index int // The index into the container, whether the file or another message.
114 path string // The SourceCodeInfo path as comma-separated integers.
115 group bool
116 }
117
118 // TypeName returns the elements of the dotted type name.
119 // The package name is not part of this name.
120 func (d *Descriptor) TypeName() []string {
121 if d.typename != nil {
122 return d.typename
123 }
124 n := 0
125 for parent := d; parent != nil; parent = parent.parent {
126 n++
127 }
128 s := make([]string, n, n)
129 for parent := d; parent != nil; parent = parent.parent {
130 n--
131 s[n] = parent.GetName()
132 }
133 d.typename = s
134 return s
135 }
136
137 func (d *Descriptor) allowOneof() bool {
138 return true
139 }
140
141 // EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
142 // Otherwise it will be the descriptor of the message in which it is defined.
143 type EnumDescriptor struct {
144 common
145 *descriptor.EnumDescriptorProto
146 parent *Descriptor // The containing message, if any.
147 typename []string // Cached typename vector.
148 index int // The index into the container, whether the file or a message.
149 path string // The SourceCodeInfo path as comma-separated integers.
150 }
151
152 // TypeName returns the elements of the dotted type name.
153 // The package name is not part of this name.
154 func (e *EnumDescriptor) TypeName() (s []string) {
155 if e.typename != nil {
156 return e.typename
157 }
158 name := e.GetName()
159 if e.parent == nil {
160 s = make([]string, 1)
161 } else {
162 pname := e.parent.TypeName()
163 s = make([]string, len(pname)+1)
164 copy(s, pname)
165 }
166 s[len(s)-1] = name
167 e.typename = s
168 return s
169 }
170
171 // alias provides the TypeName corrected for the application of any naming
172 // extensions on the enum type. It should be used for generating references to
173 // the Go types and for calculating prefixes.
174 func (e *EnumDescriptor) alias() (s []string) {
175 s = e.TypeName()
176 if gogoproto.IsEnumCustomName(e.EnumDescriptorProto) {
177 s[len(s)-1] = gogoproto.GetEnumCustomName(e.EnumDescriptorProto)
178 }
179
180 return
181 }
182
183 // Everything but the last element of the full type name, CamelCased.
184 // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
185 func (e *EnumDescriptor) prefix() string {
186 typeName := e.alias()
187 if e.parent == nil {
188 // If the enum is not part of a message, the prefix is just the type name.
189 return CamelCase(typeName[len(typeName)-1]) + "_"
190 }
191 return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
192 }
193
194 // The integer value of the named constant in this enumerated type.
195 func (e *EnumDescriptor) integerValueAsString(name string) string {
196 for _, c := range e.Value {
197 if c.GetName() == name {
198 return fmt.Sprint(c.GetNumber())
199 }
200 }
201 log.Fatal("cannot find value for enum constant")
202 return ""
203 }
204
205 // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
206 // Otherwise it will be the descriptor of the message in which it is defined.
207 type ExtensionDescriptor struct {
208 common
209 *descriptor.FieldDescriptorProto
210 parent *Descriptor // The containing message, if any.
211 }
212
213 // TypeName returns the elements of the dotted type name.
214 // The package name is not part of this name.
215 func (e *ExtensionDescriptor) TypeName() (s []string) {
216 name := e.GetName()
217 if e.parent == nil {
218 // top-level extension
219 s = make([]string, 1)
220 } else {
221 pname := e.parent.TypeName()
222 s = make([]string, len(pname)+1)
223 copy(s, pname)
224 }
225 s[len(s)-1] = name
226 return s
227 }
228
229 // DescName returns the variable name used for the generated descriptor.
230 func (e *ExtensionDescriptor) DescName() string {
231 // The full type name.
232 typeName := e.TypeName()
233 // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
234 for i, s := range typeName {
235 typeName[i] = CamelCase(s)
236 }
237 return "E_" + strings.Join(typeName, "_")
238 }
239
240 // ImportedDescriptor describes a type that has been publicly imported from another file.
241 type ImportedDescriptor struct {
242 common
243 o Object
244 }
245
246 func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
247
248 // FileDescriptor describes an protocol buffer descriptor file (.proto).
249 // It includes slices of all the messages and enums defined within it.
250 // Those slices are constructed by WrapTypes.
251 type FileDescriptor struct {
252 *descriptor.FileDescriptorProto
253 desc []*Descriptor // All the messages defined in this file.
254 enum []*EnumDescriptor // All the enums defined in this file.
255 ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
256 imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
257
258 // Comments, stored as a map of path (comma-separated integers) to the comment.
259 comments map[string]*descriptor.SourceCodeInfo_Location
260
261 // The full list of symbols that are exported,
262 // as a map from the exported object to its symbols.
263 // This is used for supporting public imports.
264 exported map[Object][]symbol
265
266 index int // The index of this file in the list of files to generate code for
267
268 proto3 bool // whether to generate proto3 code for this file
269
270 suffix string // filename suffix
271 }
272
273 // PackageName is the package name we'll use in the generated code to refer to this file.
274 func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
275
276 // VarName is the variable name we'll use in the generated code to refer
277 // to the compressed bytes of this descriptor. It is not exported, so
278 // it is only valid inside the generated package.
279 func (d *FileDescriptor) VarName() string { return fmt.Sprintf("fileDescriptor%v", FileName(d)) }
280
281 // goPackageOption interprets the file's go_package option.
282 // If there is no go_package, it returns ("", "", false).
283 // If there's a simple name, it returns ("", pkg, true).
284 // If the option implies an import path, it returns (impPath, pkg, true).
285 func (d *FileDescriptor) goPackageOption() (impPath, pkg string, ok bool) {
286 pkg = d.GetOptions().GetGoPackage()
287 if pkg == "" {
288 return
289 }
290 ok = true
291 // The presence of a slash implies there's an import path.
292 slash := strings.LastIndex(pkg, "/")
293 if slash < 0 {
294 return
295 }
296 impPath, pkg = pkg, pkg[slash+1:]
297 // A semicolon-delimited suffix overrides the package name.
298 sc := strings.IndexByte(impPath, ';')
299 if sc < 0 {
300 return
301 }
302 impPath, pkg = impPath[:sc], impPath[sc+1:]
303 return
304 }
305
306 // goPackageName returns the Go package name to use in the
307 // generated Go file. The result explicit reports whether the name
308 // came from an option go_package statement. If explicit is false,
309 // the name was derived from the protocol buffer's package statement
310 // or the input file name.
311 func (d *FileDescriptor) goPackageName() (name string, explicit bool) {
312 // Does the file have a "go_package" option?
313 if _, pkg, ok := d.goPackageOption(); ok {
314 return pkg, true
315 }
316
317 // Does the file have a package clause?
318 if pkg := d.GetPackage(); pkg != "" {
319 return pkg, false
320 }
321 // Use the file base name.
322 return baseName(d.GetName()), false
323 }
324
325 // goFileName returns the output name for the generated Go file.
326 func (d *FileDescriptor) goFileName() string {
327 name := *d.Name
328 if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
329 name = name[:len(name)-len(ext)]
330 }
331 name += d.suffix
332
333 // Does the file have a "go_package" option?
334 // If it does, it may override the filename.
335 if impPath, _, ok := d.goPackageOption(); ok && impPath != "" {
336 // Replace the existing dirname with the declared import path.
337 _, name = path.Split(name)
338 name = path.Join(impPath, name)
339 return name
340 }
341
342 return name
343 }
344
345 func (d *FileDescriptor) addExport(obj Object, sym symbol) {
346 d.exported[obj] = append(d.exported[obj], sym)
347 }
348
349 // symbol is an interface representing an exported Go symbol.
350 type symbol interface {
351 // GenerateAlias should generate an appropriate alias
352 // for the symbol from the named package.
353 GenerateAlias(g *Generator, pkg string)
354 }
355
356 // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
357 type Object interface {
358 PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
359 TypeName() []string
360 File() *descriptor.FileDescriptorProto
361 }
362
363 // Each package name we generate must be unique. The package we're generating
364 // gets its own name but every other package must have a unique name that does
365 // not conflict in the code we generate. These names are chosen globally (although
366 // they don't have to be, it simplifies things to do them globally).
367 func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
368 s, ok := uniquePackageName[fd]
369 if !ok {
370 log.Fatal("internal error: no package name defined for " + fd.GetName())
371 }
372 return s
373 }
374
375 // Generator is the type whose methods generate the output, stored in the associated response structure.
376 type Generator struct {
377 *bytes.Buffer
378
379 Request *plugin.CodeGeneratorRequest // The input.
380 Response *plugin.CodeGeneratorResponse // The output.
381 Suffix string // Filename suffix
382
383 Param map[string]string // Command-line parameters.
384 PackageImportPath string // Go import path of the package we're generating code for
385 ImportPrefix string // String to prefix to imported package file names.
386 ImportMap map[string]string // Mapping from .proto file name to import path
387
388 Pkg map[string]string // The names under which we import support packages
389
390 packageName string // What we're calling ourselves.
391 allFiles []*FileDescriptor // All files in the tree
392 allFilesByName map[string]*FileDescriptor // All files by filename.
393 genFiles []*FileDescriptor // Those files we will generate output for.
394 file *FileDescriptor // The file we are compiling now.
395 usedPackages map[string]bool // Names of packages used in current file.
396 typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
397 init []string // Lines to emit in the init function.
398 indent string
399 writeOutput bool
400
401 customImports []string
402 writtenImports map[string]bool // For de-duplicating written imports
403 }
404
405 // New creates a new generator and allocates the request and response protobufs.
406 func New() *Generator {
407 g := new(Generator)
408 g.Buffer = new(bytes.Buffer)
409 g.Request = new(plugin.CodeGeneratorRequest)
410 g.Response = new(plugin.CodeGeneratorResponse)
411 g.Suffix = ".pb.go"
412 g.writtenImports = make(map[string]bool)
413 uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
414 pkgNamesInUse = make(map[string][]*FileDescriptor)
415 return g
416 }
417
418 // Error reports a problem, including an error, and exits the program.
419 func (g *Generator) Error(err error, msgs ...string) {
420 s := strings.Join(msgs, " ") + ":" + err.Error()
421 log.Print("protoc-gen-yarpc: error:", s)
422 os.Exit(1)
423 }
424
425 // Fail reports a problem and exits the program.
426 func (g *Generator) Fail(msgs ...string) {
427 s := strings.Join(msgs, " ")
428 log.Print("protoc-gen-yarpc: error:", s)
429 os.Exit(1)
430 }
431
432 // CommandLineParameters breaks the comma-separated list of key=value pairs
433 // in the parameter (a member of the request protobuf) into a key/value map.
434 // It then sets file name mappings defined by those entries.
435 func (g *Generator) CommandLineParameters(parameter string) {
436 g.Param = make(map[string]string)
437 for _, p := range strings.Split(parameter, ",") {
438 if i := strings.Index(p, "="); i < 0 {
439 g.Param[p] = ""
440 } else {
441 g.Param[p[0:i]] = p[i+1:]
442 }
443 }
444
445 g.ImportMap = make(map[string]string)
446 for k, v := range g.Param {
447 switch k {
448 case "import_prefix":
449 g.ImportPrefix = v
450 case "import_path":
451 g.PackageImportPath = v
452 default:
453 if len(k) > 0 && k[0] == 'M' {
454 g.ImportMap[k[1:]] = v
455 }
456 }
457 }
458 }
459
460 // DefaultPackageName returns the package name printed for the object.
461 // If its file is in a different package, it returns the package name we're using for this file, plus ".".
462 // Otherwise it returns the empty string.
463 func (g *Generator) DefaultPackageName(obj Object) string {
464 pkg := obj.PackageName()
465 if pkg == g.packageName {
466 return ""
467 }
468 return pkg + "."
469 }
470
471 // For each input file, the unique package name to use, underscored.
472 var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
473
474 // Package names already registered. Key is the name from the .proto file;
475 // value is the name that appears in the generated code.
476 var pkgNamesInUse = make(map[string][]*FileDescriptor)
477
478 // Create and remember a guaranteed unique package name for this file descriptor.
479 // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
480 // has no file descriptor.
481 func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
482 // Convert dots to underscores before finding a unique alias.
483 pkg = strings.Map(badToUnderscore, pkg)
484
485 var i = -1
486 var ptr *FileDescriptor = nil
487 for i, ptr = range pkgNamesInUse[pkg] {
488 if ptr == f {
489 if i == 0 {
490 return pkg
491 }
492 return pkg + strconv.Itoa(i)
493 }
494 }
495
496 pkgNamesInUse[pkg] = append(pkgNamesInUse[pkg], f)
497 i += 1
498
499 if i > 0 {
500 pkg = pkg + strconv.Itoa(i)
501 }
502
503 if f != nil {
504 uniquePackageName[f.FileDescriptorProto] = pkg
505 }
506 return pkg
507 }
508
509 var isGoKeyword = map[string]bool{
510 "break": true,
511 "case": true,
512 "chan": true,
513 "const": true,
514 "continue": true,
515 "default": true,
516 "else": true,
517 "defer": true,
518 "fallthrough": true,
519 "for": true,
520 "func": true,
521 "go": true,
522 "goto": true,
523 "if": true,
524 "import": true,
525 "interface": true,
526 "map": true,
527 "package": true,
528 "range": true,
529 "return": true,
530 "select": true,
531 "struct": true,
532 "switch": true,
533 "type": true,
534 "var": true,
535 }
536
537 // defaultGoPackage returns the package name to use,
538 // derived from the import path of the package we're building code for.
539 func (g *Generator) defaultGoPackage() string {
540 p := g.PackageImportPath
541 if i := strings.LastIndex(p, "/"); i >= 0 {
542 p = p[i+1:]
543 }
544 if p == "" {
545 return ""
546 }
547
548 p = strings.Map(badToUnderscore, p)
549 // Identifier must not be keyword: insert _.
550 if isGoKeyword[p] {
551 p = "_" + p
552 }
553 // Identifier must not begin with digit: insert _.
554 if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) {
555 p = "_" + p
556 }
557 return p
558 }
559
560 // SetPackageNames sets the package name for this run.
561 // The package name must agree across all files being generated.
562 // It also defines unique package names for all imported files.
563 func (g *Generator) SetPackageNames() {
564 // Register the name for this package. It will be the first name
565 // registered so is guaranteed to be unmodified.
566 pkg, explicit := g.genFiles[0].goPackageName()
567
568 // Check all files for an explicit go_package option.
569 for _, f := range g.genFiles {
570 thisPkg, thisExplicit := f.goPackageName()
571 if thisExplicit {
572 if !explicit {
573 // Let this file's go_package option serve for all input files.
574 pkg, explicit = thisPkg, true
575 } else if thisPkg != pkg {
576 g.Fail("inconsistent package names:", thisPkg, pkg)
577 }
578 }
579 }
580
581 // If we don't have an explicit go_package option but we have an
582 // import path, use that.
583 if !explicit {
584 p := g.defaultGoPackage()
585 if p != "" {
586 pkg, explicit = p, true
587 }
588 }
589
590 // If there was no go_package and no import path to use,
591 // double-check that all the inputs have the same implicit
592 // Go package name.
593 if !explicit {
594 for _, f := range g.genFiles {
595 thisPkg, _ := f.goPackageName()
596 if thisPkg != pkg {
597 g.Fail("inconsistent package names:", thisPkg, pkg)
598 }
599 }
600 }
601
602 g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
603
604 // Register the support package names. They might collide with the
605 // name of a package we import.
606 g.Pkg = map[string]string{
607 "fmt": RegisterUniquePackageName("fmt", nil),
608 "math": RegisterUniquePackageName("math", nil),
609 "proto": RegisterUniquePackageName("proto", nil),
610 "golang_proto": RegisterUniquePackageName("golang_proto", nil),
611 }
612
613 AllFiles:
614 for _, f := range g.allFiles {
615 for _, genf := range g.genFiles {
616 if f == genf {
617 // In this package already.
618 uniquePackageName[f.FileDescriptorProto] = g.packageName
619 continue AllFiles
620 }
621 }
622 // The file is a dependency, so we want to ignore its go_package option
623 // because that is only relevant for its specific generated output.
624 pkg := f.GetPackage()
625 if pkg == "" {
626 pkg = baseName(*f.Name)
627 }
628 RegisterUniquePackageName(pkg, f)
629 }
630 }
631
632 // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
633 // and FileDescriptorProtos into file-referenced objects within the Generator.
634 // It also creates the list of files to generate and so should be called before GenerateAllFiles.
635 func (g *Generator) WrapTypes() {
636 g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile))
637 g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles))
638 for _, f := range g.Request.ProtoFile {
639 // We must wrap the descriptors before we wrap the enums
640 descs := wrapDescriptors(f)
641 g.buildNestedDescriptors(descs)
642 enums := wrapEnumDescriptors(f, descs)
643 g.buildNestedEnums(descs, enums)
644 exts := wrapExtensions(f)
645 fd := &FileDescriptor{
646 FileDescriptorProto: f,
647 desc: descs,
648 enum: enums,
649 ext: exts,
650 exported: make(map[Object][]symbol),
651 proto3: fileIsProto3(f),
652 suffix: g.Suffix,
653 }
654 extractComments(fd)
655 g.allFiles = append(g.allFiles, fd)
656 g.allFilesByName[f.GetName()] = fd
657 }
658 for _, fd := range g.allFiles {
659 fd.imp = wrapImported(fd.FileDescriptorProto, g)
660 }
661
662 g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate))
663 for _, fileName := range g.Request.FileToGenerate {
664 fd := g.allFilesByName[fileName]
665 if fd == nil {
666 g.Fail("could not find file named", fileName)
667 }
668 fd.index = len(g.genFiles)
669 g.genFiles = append(g.genFiles, fd)
670 }
671 }
672
673 // Scan the descriptors in this file. For each one, build the slice of nested descriptors
674 func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
675 for _, desc := range descs {
676 if len(desc.NestedType) != 0 {
677 for _, nest := range descs {
678 if nest.parent == desc {
679 desc.nested = append(desc.nested, nest)
680 }
681 }
682 if len(desc.nested) != len(desc.NestedType) {
683 g.Fail("internal error: nesting failure for", desc.GetName())
684 }
685 }
686 }
687 }
688
689 func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) {
690 for _, desc := range descs {
691 if len(desc.EnumType) != 0 {
692 for _, enum := range enums {
693 if enum.parent == desc {
694 desc.enums = append(desc.enums, enum)
695 }
696 }
697 if len(desc.enums) != len(desc.EnumType) {
698 g.Fail("internal error: enum nesting failure for", desc.GetName())
699 }
700 }
701 }
702 }
703
704 // Construct the Descriptor
705 func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor {
706 d := &Descriptor{
707 common: common{file},
708 DescriptorProto: desc,
709 parent: parent,
710 index: index,
711 }
712 if parent == nil {
713 d.path = fmt.Sprintf("%d,%d", messagePath, index)
714 } else {
715 d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
716 }
717
718 // The only way to distinguish a group from a message is whether
719 // the containing message has a TYPE_GROUP field that matches.
720 if parent != nil {
721 parts := d.TypeName()
722 if file.Package != nil {
723 parts = append([]string{*file.Package}, parts...)
724 }
725 exp := "." + strings.Join(parts, ".")
726 for _, field := range parent.Field {
727 if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
728 d.group = true
729 break
730 }
731 }
732 }
733
734 for _, field := range desc.Extension {
735 d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d})
736 }
737
738 return d
739 }
740
741 // Return a slice of all the Descriptors defined within this file
742 func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
743 sl := make([]*Descriptor, 0, len(file.MessageType)+10)
744 for i, desc := range file.MessageType {
745 sl = wrapThisDescriptor(sl, desc, nil, file, i)
746 }
747 return sl
748 }
749
750 // Wrap this Descriptor, recursively
751 func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor {
752 sl = append(sl, newDescriptor(desc, parent, file, index))
753 me := sl[len(sl)-1]
754 for i, nested := range desc.NestedType {
755 sl = wrapThisDescriptor(sl, nested, me, file, i)
756 }
757 return sl
758 }
759
760 // Construct the EnumDescriptor
761 func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor {
762 ed := &EnumDescriptor{
763 common: common{file},
764 EnumDescriptorProto: desc,
765 parent: parent,
766 index: index,
767 }
768 if parent == nil {
769 ed.path = fmt.Sprintf("%d,%d", enumPath, index)
770 } else {
771 ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
772 }
773 return ed
774 }
775
776 // Return a slice of all the EnumDescriptors defined within this file
777 func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
778 sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
779 // Top-level enums.
780 for i, enum := range file.EnumType {
781 sl = append(sl, newEnumDescriptor(enum, nil, file, i))
782 }
783 // Enums within messages. Enums within embedded messages appear in the outer-most message.
784 for _, nested := range descs {
785 for i, enum := range nested.EnumType {
786 sl = append(sl, newEnumDescriptor(enum, nested, file, i))
787 }
788 }
789 return sl
790 }
791
792 // Return a slice of all the top-level ExtensionDescriptors defined within this file.
793 func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor {
794 var sl []*ExtensionDescriptor
795 for _, field := range file.Extension {
796 sl = append(sl, &ExtensionDescriptor{common{file}, field, nil})
797 }
798 return sl
799 }
800
801 // Return a slice of all the types that are publicly imported into this file.
802 func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) {
803 for _, index := range file.PublicDependency {
804 df := g.fileByName(file.Dependency[index])
805 for _, d := range df.desc {
806 if d.GetOptions().GetMapEntry() {
807 continue
808 }
809 sl = append(sl, &ImportedDescriptor{common{file}, d})
810 }
811 for _, e := range df.enum {
812 sl = append(sl, &ImportedDescriptor{common{file}, e})
813 }
814 for _, ext := range df.ext {
815 sl = append(sl, &ImportedDescriptor{common{file}, ext})
816 }
817 }
818 return
819 }
820
821 func extractComments(file *FileDescriptor) {
822 file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
823 for _, loc := range file.GetSourceCodeInfo().GetLocation() {
824 if loc.LeadingComments == nil {
825 continue
826 }
827 var p []string
828 for _, n := range loc.Path {
829 p = append(p, strconv.Itoa(int(n)))
830 }
831 file.comments[strings.Join(p, ",")] = loc
832 }
833 }
834
835 // BuildTypeNameMap builds the map from fully qualified type names to objects.
836 // The key names for the map come from the input data, which puts a period at the beginning.
837 // It should be called after SetPackageNames and before GenerateAllFiles.
838 func (g *Generator) BuildTypeNameMap() {
839 g.typeNameToObject = make(map[string]Object)
840 for _, f := range g.allFiles {
841 // The names in this loop are defined by the proto world, not us, so the
842 // package name may be empty. If so, the dotted package name of X will
843 // be ".X"; otherwise it will be ".pkg.X".
844 dottedPkg := "." + f.GetPackage()
845 if dottedPkg != "." {
846 dottedPkg += "."
847 }
848 for _, enum := range f.enum {
849 name := dottedPkg + dottedSlice(enum.TypeName())
850 g.typeNameToObject[name] = enum
851 }
852 for _, desc := range f.desc {
853 name := dottedPkg + dottedSlice(desc.TypeName())
854 g.typeNameToObject[name] = desc
855 }
856 }
857 }
858
859 // ObjectNamed, given a fully-qualified input type name as it appears in the input data,
860 // returns the descriptor for the message or enum with that name.
861 func (g *Generator) ObjectNamed(typeName string) Object {
862 o, ok := g.typeNameToObject[typeName]
863 if !ok {
864 g.Fail("can't find object with type", typeName)
865 }
866
867 // If the file of this object isn't a direct dependency of the current file,
868 // or in the current file, then this object has been publicly imported into
869 // a dependency of the current file.
870 // We should return the ImportedDescriptor object for it instead.
871 direct := *o.File().Name == *g.file.Name
872 if !direct {
873 for _, dep := range g.file.Dependency {
874 if *g.fileByName(dep).Name == *o.File().Name {
875 direct = true
876 break
877 }
878 }
879 }
880 if !direct {
881 found := false
882 Loop:
883 for _, dep := range g.file.Dependency {
884 df := g.fileByName(*g.fileByName(dep).Name)
885 for _, td := range df.imp {
886 if td.o == o {
887 // Found it!
888 o = td
889 found = true
890 break Loop
891 }
892 }
893 }
894 if !found {
895 log.Printf("protoc-gen-yarpc: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
896 }
897 }
898
899 return o
900 }
901
902 // P prints the arguments to the generated output. It handles strings and int32s, plus
903 // handling indirections because they may be *string, etc.
904 func (g *Generator) P(str ...interface{}) {
905 if !g.writeOutput {
906 return
907 }
908 g.WriteString(g.indent)
909 for _, v := range str {
910 switch s := v.(type) {
911 case string:
912 g.WriteString(s)
913 case *string:
914 g.WriteString(*s)
915 case bool:
916 fmt.Fprintf(g, "%t", s)
917 case *bool:
918 fmt.Fprintf(g, "%t", *s)
919 case int:
920 fmt.Fprintf(g, "%d", s)
921 case *int32:
922 fmt.Fprintf(g, "%d", *s)
923 case *int64:
924 fmt.Fprintf(g, "%d", *s)
925 case float64:
926 fmt.Fprintf(g, "%g", s)
927 case *float64:
928 fmt.Fprintf(g, "%g", *s)
929 default:
930 g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
931 }
932 }
933 g.WriteByte('\n')
934 }
935
936 // addInitf stores the given statement to be printed inside the file's init function.
937 // The statement is given as a format specifier and arguments.
938 func (g *Generator) addInitf(stmt string, a ...interface{}) {
939 g.init = append(g.init, fmt.Sprintf(stmt, a...))
940 }
941
942 func (g *Generator) PrintImport(alias, pkg string) {
943 statement := "import " + alias + " " + strconv.Quote(pkg)
944 if g.writtenImports[statement] {
945 return
946 }
947 g.P(statement)
948 g.writtenImports[statement] = true
949 }
950
951 // In Indents the output one tab stop.
952 func (g *Generator) In() { g.indent += "\t" }
953
954 // Out unindents the output one tab stop.
955 func (g *Generator) Out() {
956 if len(g.indent) > 0 {
957 g.indent = g.indent[1:]
958 }
959 }
960
961 // FileOf return the FileDescriptor for this FileDescriptorProto.
962 func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
963 for _, file := range g.allFiles {
964 if file.FileDescriptorProto == fd {
965 return file
966 }
967 }
968 g.Fail("could not find file in table:", fd.GetName())
969 return nil
970 }
971
972 // Generate the header, including package definition
973 func (g *Generator) generateHeader() {
974 g.P("// Code generated by protoc-gen-yarpc. DO NOT EDIT.")
975 g.P("// source: ", *g.file.Name)
976 g.P()
977
978 name := g.file.PackageName()
979
980 if g.file.index == 0 {
981 // Generate package docs for the first file in the package.
982 g.P("/*")
983 g.P("Package ", name, " is a generated protocol buffer package.")
984 g.P()
985 if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok {
986 // not using g.PrintComments because this is a /* */ comment block.
987 text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
988 for _, line := range strings.Split(text, "\n") {
989 line = strings.TrimPrefix(line, " ")
990 // ensure we don't escape from the block comment
991 line = strings.Replace(line, "*/", "* /", -1)
992 g.P(line)
993 }
994 g.P()
995 }
996 var topMsgs []string
997 g.P("It is generated from these files:")
998 for _, f := range g.genFiles {
999 g.P("\t", f.Name)
1000 for _, msg := range f.desc {
1001 if msg.parent != nil {
1002 continue
1003 }
1004 topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName()))
1005 }
1006 }
1007 g.P()
1008 g.P("It has these top-level messages:")
1009 for _, msg := range topMsgs {
1010 g.P("\t", msg)
1011 }
1012 g.P("*/")
1013 }
1014
1015 g.P("package ", name)
1016 g.P()
1017 }
1018
1019 // PrintComments prints any comments from the source .proto file.
1020 // The path is a comma-separated list of integers.
1021 // It returns an indication of whether any comments were printed.
1022 // See descriptor.proto for its format.
1023 func (g *Generator) PrintComments(path string) bool {
1024 if !g.writeOutput {
1025 return false
1026 }
1027 if loc, ok := g.file.comments[path]; ok {
1028 text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
1029 for _, line := range strings.Split(text, "\n") {
1030 g.P("// ", strings.TrimPrefix(line, " "))
1031 }
1032 return true
1033 }
1034 return false
1035 }
1036
1037 // Comments returns any comments from the source .proto file and empty string if comments not found.
1038 // The path is a comma-separated list of intergers.
1039 // See descriptor.proto for its format.
1040 func (g *Generator) Comments(path string) string {
1041 loc, ok := g.file.comments[path]
1042 if !ok {
1043 return ""
1044 }
1045 text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
1046 return text
1047 }
1048
1049 func (g *Generator) fileByName(filename string) *FileDescriptor {
1050 return g.allFilesByName[filename]
1051 }
1052
1053 // weak returns whether the ith import of the current file is a weak import.
1054 func (g *Generator) weak(i int32) bool {
1055 for _, j := range g.file.WeakDependency {
1056 if j == i {
1057 return true
1058 }
1059 }
1060 return false
1061 }
1062
1063 // Generate the imports
1064 func (g *Generator) generateImports() {
1065 // We almost always need a proto import. Rather than computing when we
1066 // do, which is tricky when there's a plugin, just import it and
1067 // reference it later. The same argument applies to the fmt and math packages.
1068 if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) {
1069 g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/gogo/protobuf/proto")
1070 if gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) {
1071 g.PrintImport(g.Pkg["golang_proto"], g.ImportPrefix+"github.com/golang/protobuf/proto")
1072 }
1073 } else {
1074 g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/golang/protobuf/proto")
1075 }
1076 g.PrintImport(g.Pkg["fmt"], "fmt")
1077 g.PrintImport(g.Pkg["math"], "math")
1078
1079 for i, s := range g.file.Dependency {
1080 fd := g.fileByName(s)
1081 // Do not import our own package.
1082 if fd.PackageName() == g.packageName {
1083 continue
1084 }
1085 filename := fd.goFileName()
1086 // By default, import path is the dirname of the Go filename.
1087 importPath := path.Dir(filename)
1088 if substitution, ok := g.ImportMap[s]; ok {
1089 importPath = substitution
1090 }
1091 importPath = g.ImportPrefix + importPath
1092 // Skip weak imports.
1093 if g.weak(int32(i)) {
1094 g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath))
1095 continue
1096 }
1097 // We need to import all the dependencies, even if we don't reference them,
1098 // because other code and tools depend on having the full transitive closure
1099 // of protocol buffer types in the binary.
1100 if _, ok := g.usedPackages[fd.PackageName()]; ok {
1101 g.PrintImport(fd.PackageName(), importPath)
1102 } else {
1103 g.P("import _ ", strconv.Quote(importPath))
1104 }
1105 }
1106 g.P()
1107 for _, s := range g.customImports {
1108 s1 := strings.Map(badToUnderscore, s)
1109 g.PrintImport(s1, s)
1110 }
1111 g.P()
1112 g.P("// Reference imports to suppress errors if they are not otherwise used.")
1113 g.P("var _ = ", g.Pkg["proto"], ".Marshal")
1114 if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) && gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) {
1115 g.P("var _ = ", g.Pkg["golang_proto"], ".Marshal")
1116 }
1117 g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
1118 g.P("var _ = ", g.Pkg["math"], ".Inf")
1119 for _, cimport := range g.customImports {
1120 if cimport == "time" {
1121 g.P("var _ = time.Kitchen")
1122 break
1123 }
1124 }
1125 g.P()
1126 }
1127
1128 func (g *Generator) generateImported(id *ImportedDescriptor) {
1129 // Don't generate public import symbols for files that we are generating
1130 // code for, since those symbols will already be in this package.
1131 // We can't simply avoid creating the ImportedDescriptor objects,
1132 // because g.genFiles isn't populated at that stage.
1133 tn := id.TypeName()
1134 sn := tn[len(tn)-1]
1135 df := g.FileOf(id.o.File())
1136 filename := *df.Name
1137 for _, fd := range g.genFiles {
1138 if *fd.Name == filename {
1139 g.P("// Ignoring public import of ", sn, " from ", filename)
1140 g.P()
1141 return
1142 }
1143 }
1144 g.P("// ", sn, " from public import ", filename)
1145 g.usedPackages[df.PackageName()] = true
1146
1147 for _, sym := range df.exported[id.o] {
1148 sym.GenerateAlias(g, df.PackageName())
1149 }
1150
1151 g.P()
1152 }
1153
1154 // The tag is a string like "varint,2,opt,name=fieldname,def=7" that
1155 // identifies details of the field for the protocol buffer marshaling and unmarshaling
1156 // code. The fields are:
1157 // wire encoding
1158 // protocol tag number
1159 // opt,req,rep for optional, required, or repeated
1160 // packed whether the encoding is "packed" (optional; repeated primitives only)
1161 // name= the original declared name
1162 // enum= the name of the enum type if it is an enum-typed field.
1163 // proto3 if this field is in a proto3 message
1164 // def= string representation of the default value, if any.
1165 // The default value must be in a representation that can be used at run-time
1166 // to generate the default value. Thus bools become 0 and 1, for instance.
1167 func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string {
1168 optrepreq := ""
1169 switch {
1170 case isOptional(field):
1171 optrepreq = "opt"
1172 case isRequired(field):
1173 optrepreq = "req"
1174 case isRepeated(field):
1175 optrepreq = "rep"
1176 }
1177 var defaultValue string
1178 if dv := field.DefaultValue; dv != nil { // set means an explicit default
1179 defaultValue = *dv
1180 // Some types need tweaking.
1181 switch *field.Type {
1182 case descriptor.FieldDescriptorProto_TYPE_BOOL:
1183 if defaultValue == "true" {
1184 defaultValue = "1"
1185 } else {
1186 defaultValue = "0"
1187 }
1188 case descriptor.FieldDescriptorProto_TYPE_STRING,
1189 descriptor.FieldDescriptorProto_TYPE_BYTES:
1190 // Nothing to do. Quoting is done for the whole tag.
1191 case descriptor.FieldDescriptorProto_TYPE_ENUM:
1192 // For enums we need to provide the integer constant.
1193 obj := g.ObjectNamed(field.GetTypeName())
1194 if id, ok := obj.(*ImportedDescriptor); ok {
1195 // It is an enum that was publicly imported.
1196 // We need the underlying type.
1197 obj = id.o
1198 }
1199 enum, ok := obj.(*EnumDescriptor)
1200 if !ok {
1201 log.Printf("obj is a %T", obj)
1202 if id, ok := obj.(*ImportedDescriptor); ok {
1203 log.Printf("id.o is a %T", id.o)
1204 }
1205 g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
1206 }
1207 defaultValue = enum.integerValueAsString(defaultValue)
1208 }
1209 defaultValue = ",def=" + defaultValue
1210 }
1211 enum := ""
1212 if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
1213 // We avoid using obj.PackageName(), because we want to use the
1214 // original (proto-world) package name.
1215 obj := g.ObjectNamed(field.GetTypeName())
1216 if id, ok := obj.(*ImportedDescriptor); ok {
1217 obj = id.o
1218 }
1219 enum = ",enum="
1220 if pkg := obj.File().GetPackage(); pkg != "" {
1221 enum += pkg + "."
1222 }
1223 enum += CamelCaseSlice(obj.TypeName())
1224 }
1225 packed := ""
1226 if (field.Options != nil && field.Options.GetPacked()) ||
1227 // Per https://developers.google.com/protocol-buffers/docs/proto3#simple:
1228 // "In proto3, repeated fields of scalar numeric types use packed encoding by default."
1229 (message.proto3() && (field.Options == nil || field.Options.Packed == nil) &&
1230 isRepeated(field) && IsScalar(field)) {
1231 packed = ",packed"
1232 }
1233 fieldName := field.GetName()
1234 name := fieldName
1235 if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
1236 // We must use the type name for groups instead of
1237 // the field name to preserve capitalization.
1238 // type_name in FieldDescriptorProto is fully-qualified,
1239 // but we only want the local part.
1240 name = *field.TypeName
1241 if i := strings.LastIndex(name, "."); i >= 0 {
1242 name = name[i+1:]
1243 }
1244 }
1245 if json := field.GetJsonName(); json != "" && json != name {
1246 // TODO: escaping might be needed, in which case
1247 // perhaps this should be in its own "json" tag.
1248 name += ",json=" + json
1249 }
1250 name = ",name=" + name
1251
1252 embed := ""
1253 if gogoproto.IsEmbed(field) {
1254 embed = ",embedded=" + fieldName
1255 }
1256
1257 ctype := ""
1258 if gogoproto.IsCustomType(field) {
1259 ctype = ",customtype=" + gogoproto.GetCustomType(field)
1260 }
1261
1262 casttype := ""
1263 if gogoproto.IsCastType(field) {
1264 casttype = ",casttype=" + gogoproto.GetCastType(field)
1265 }
1266
1267 castkey := ""
1268 if gogoproto.IsCastKey(field) {
1269 castkey = ",castkey=" + gogoproto.GetCastKey(field)
1270 }
1271
1272 castvalue := ""
1273 if gogoproto.IsCastValue(field) {
1274 castvalue = ",castvalue=" + gogoproto.GetCastValue(field)
1275 // record the original message type for jsonpb reconstruction
1276 desc := g.ObjectNamed(field.GetTypeName())
1277 if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
1278 valueField := d.Field[1]
1279 if valueField.IsMessage() {
1280 castvalue += ",castvaluetype=" + strings.TrimPrefix(valueField.GetTypeName(), ".")
1281 }
1282 }
1283 }
1284
1285 if message.proto3() {
1286 // We only need the extra tag for []byte fields;
1287 // no need to add noise for the others.
1288 if *field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE &&
1289 *field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP &&
1290 !field.IsRepeated() {
1291 name += ",proto3"
1292 }
1293 }
1294 oneof := ""
1295 if field.OneofIndex != nil {
1296 oneof = ",oneof"
1297 }
1298 stdtime := ""
1299 if gogoproto.IsStdTime(field) {
1300 stdtime = ",stdtime"
1301 }
1302 stdduration := ""
1303 if gogoproto.IsStdDuration(field) {
1304 stdduration = ",stdduration"
1305 }
1306 return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s%s%s%s%s%s%s%s",
1307 wiretype,
1308 field.GetNumber(),
1309 optrepreq,
1310 packed,
1311 name,
1312 enum,
1313 oneof,
1314 defaultValue,
1315 embed,
1316 ctype,
1317 casttype,
1318 castkey,
1319 castvalue,
1320 stdtime,
1321 stdduration))
1322 }
1323
1324 func needsStar(field *descriptor.FieldDescriptorProto, proto3 bool, allowOneOf bool) bool {
1325 if isRepeated(field) &&
1326 (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE || gogoproto.IsCustomType(field)) &&
1327 (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) {
1328 return false
1329 }
1330 if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES && !gogoproto.IsCustomType(field) {
1331 return false
1332 }
1333 if !gogoproto.IsNullable(field) {
1334 return false
1335 }
1336 if field.OneofIndex != nil && allowOneOf &&
1337 (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE) &&
1338 (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) {
1339 return false
1340 }
1341 if proto3 &&
1342 (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE) &&
1343 (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) &&
1344 !gogoproto.IsCustomType(field) {
1345 return false
1346 }
1347 return true
1348 }
1349
1350 // TypeName is the printed name appropriate for an item. If the object is in the current file,
1351 // TypeName drops the package name and underscores the rest.
1352 // Otherwise the object is from another package; and the result is the underscored
1353 // package name followed by the item name.
1354 // The result always has an initial capital.
1355 func (g *Generator) TypeName(obj Object) string {
1356 return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
1357 }
1358
1359 // TypeNameWithPackage is like TypeName, but always includes the package
1360 // name even if the object is in our own package.
1361 func (g *Generator) TypeNameWithPackage(obj Object) string {
1362 return obj.PackageName() + CamelCaseSlice(obj.TypeName())
1363 }
1364
1365 // GoType returns a string representing the type name, and the wire type
1366 func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
1367 // TODO: Options.
1368 switch *field.Type {
1369 case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
1370 typ, wire = "float64", "fixed64"
1371 case descriptor.FieldDescriptorProto_TYPE_FLOAT:
1372 typ, wire = "float32", "fixed32"
1373 case descriptor.FieldDescriptorProto_TYPE_INT64:
1374 typ, wire = "int64", "varint"
1375 case descriptor.FieldDescriptorProto_TYPE_UINT64:
1376 typ, wire = "uint64", "varint"
1377 case descriptor.FieldDescriptorProto_TYPE_INT32:
1378 typ, wire = "int32", "varint"
1379 case descriptor.FieldDescriptorProto_TYPE_UINT32:
1380 typ, wire = "uint32", "varint"
1381 case descriptor.FieldDescriptorProto_TYPE_FIXED64:
1382 typ, wire = "uint64", "fixed64"
1383 case descriptor.FieldDescriptorProto_TYPE_FIXED32:
1384 typ, wire = "uint32", "fixed32"
1385 case descriptor.FieldDescriptorProto_TYPE_BOOL:
1386 typ, wire = "bool", "varint"
1387 case descriptor.FieldDescriptorProto_TYPE_STRING:
1388 typ, wire = "string", "bytes"
1389 case descriptor.FieldDescriptorProto_TYPE_GROUP:
1390 desc := g.ObjectNamed(field.GetTypeName())
1391 typ, wire = g.TypeName(desc), "group"
1392 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
1393 desc := g.ObjectNamed(field.GetTypeName())
1394 typ, wire = g.TypeName(desc), "bytes"
1395 case descriptor.FieldDescriptorProto_TYPE_BYTES:
1396 typ, wire = "[]byte", "bytes"
1397 case descriptor.FieldDescriptorProto_TYPE_ENUM:
1398 desc := g.ObjectNamed(field.GetTypeName())
1399 typ, wire = g.TypeName(desc), "varint"
1400 case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
1401 typ, wire = "int32", "fixed32"
1402 case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
1403 typ, wire = "int64", "fixed64"
1404 case descriptor.FieldDescriptorProto_TYPE_SINT32:
1405 typ, wire = "int32", "zigzag32"
1406 case descriptor.FieldDescriptorProto_TYPE_SINT64:
1407 typ, wire = "int64", "zigzag64"
1408 default:
1409 g.Fail("unknown type for", field.GetName())
1410 }
1411 switch {
1412 case gogoproto.IsCustomType(field) && gogoproto.IsCastType(field):
1413 g.Fail(field.GetName() + " cannot be custom type and cast type")
1414 case gogoproto.IsCustomType(field):
1415 var packageName string
1416 var err error
1417 packageName, typ, err = getCustomType(field)
1418 if err != nil {
1419 g.Fail(err.Error())
1420 }
1421 if len(packageName) > 0 {
1422 g.customImports = append(g.customImports, packageName)
1423 }
1424 case gogoproto.IsCastType(field):
1425 var packageName string
1426 var err error
1427 packageName, typ, err = getCastType(field)
1428 if err != nil {
1429 g.Fail(err.Error())
1430 }
1431 if len(packageName) > 0 {
1432 g.customImports = append(g.customImports, packageName)
1433 }
1434 case gogoproto.IsStdTime(field):
1435 g.customImports = append(g.customImports, "time")
1436 typ = "time.Time"
1437 case gogoproto.IsStdDuration(field):
1438 g.customImports = append(g.customImports, "time")
1439 typ = "time.Duration"
1440 }
1441 if needsStar(field, g.file.proto3 && field.Extendee == nil, message != nil && message.allowOneof()) {
1442 typ = "*" + typ
1443 }
1444 if isRepeated(field) {
1445 typ = "[]" + typ
1446 }
1447 return
1448 }
1449
1450 // GoMapDescriptor is a full description of the map output struct.
1451 type GoMapDescriptor struct {
1452 GoType string
1453
1454 KeyField *descriptor.FieldDescriptorProto
1455 KeyAliasField *descriptor.FieldDescriptorProto
1456 KeyTag string
1457
1458 ValueField *descriptor.FieldDescriptorProto
1459 ValueAliasField *descriptor.FieldDescriptorProto
1460 ValueTag string
1461 }
1462
1463 func (g *Generator) GoMapType(d *Descriptor, field *descriptor.FieldDescriptorProto) *GoMapDescriptor {
1464 if d == nil {
1465 byName := g.ObjectNamed(field.GetTypeName())
1466 desc, ok := byName.(*Descriptor)
1467 if byName == nil || !ok || !desc.GetOptions().GetMapEntry() {
1468 g.Fail(fmt.Sprintf("field %s is not a map", field.GetTypeName()))
1469 return nil
1470 }
1471 d = desc
1472 }
1473
1474 m := &GoMapDescriptor{
1475 KeyField: d.Field[0],
1476 ValueField: d.Field[1],
1477 }
1478
1479 // Figure out the Go types and tags for the key and value types.
1480 m.KeyAliasField, m.ValueAliasField = g.GetMapKeyField(field, m.KeyField), g.GetMapValueField(field, m.ValueField)
1481 keyType, keyWire := g.GoType(d, m.KeyAliasField)
1482 valType, valWire := g.GoType(d, m.ValueAliasField)
1483
1484 m.KeyTag, m.ValueTag = g.goTag(d, m.KeyField, keyWire), g.goTag(d, m.ValueField, valWire)
1485
1486 if gogoproto.IsCastType(field) {
1487 var packageName string
1488 var err error
1489 packageName, typ, err := getCastType(field)
1490 if err != nil {
1491 g.Fail(err.Error())
1492 }
1493 if len(packageName) > 0 {
1494 g.customImports = append(g.customImports, packageName)
1495 }
1496 m.GoType = typ
1497 return m
1498 }
1499
1500 // We don't use stars, except for message-typed values.
1501 // Message and enum types are the only two possibly foreign types used in maps,
1502 // so record their use. They are not permitted as map keys.
1503 keyType = strings.TrimPrefix(keyType, "*")
1504 switch *m.ValueAliasField.Type {
1505 case descriptor.FieldDescriptorProto_TYPE_ENUM:
1506 valType = strings.TrimPrefix(valType, "*")
1507 g.RecordTypeUse(m.ValueAliasField.GetTypeName())
1508 case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
1509 if !gogoproto.IsNullable(m.ValueAliasField) {
1510 valType = strings.TrimPrefix(valType, "*")
1511 }
1512 if !gogoproto.IsStdTime(field) && !gogoproto.IsStdDuration(field) {
1513 g.RecordTypeUse(m.ValueAliasField.GetTypeName())
1514 }
1515 default:
1516 if gogoproto.IsCustomType(m.ValueAliasField) {
1517 if !gogoproto.IsNullable(m.ValueAliasField) {
1518 valType = strings.TrimPrefix(valType, "*")
1519 }
1520 g.RecordTypeUse(m.ValueAliasField.GetTypeName())
1521 } else {
1522 valType = strings.TrimPrefix(valType, "*")
1523 }
1524 }
1525
1526 m.GoType = fmt.Sprintf("map[%s]%s", keyType, valType)
1527 return m
1528 }
1529
1530 func (g *Generator) RecordTypeUse(t string) {
1531 if obj, ok := g.typeNameToObject[t]; ok {
1532 // Call ObjectNamed to get the true object to record the use.
1533 obj = g.ObjectNamed(t)
1534 g.usedPackages[obj.PackageName()] = true
1535 }
1536 }
1537
1538 // Method names that may be generated. Fields with these names get an
1539 // underscore appended. Any change to this set is a potential incompatible
1540 // API change because it changes generated field names.
1541 var methodNames = [...]string{
1542 "Reset",
1543 "String",
1544 "ProtoMessage",
1545 "Marshal",
1546 "Unmarshal",
1547 "ExtensionRangeArray",
1548 "ExtensionMap",
1549 "Descriptor",
1550 "MarshalTo",
1551 "Equal",
1552 "VerboseEqual",
1553 "GoString",
1554 "ProtoSize",
1555 }
1556
1557 func (g *Generator) generateInitFunction() {
1558 if len(g.init) == 0 {
1559 return
1560 }
1561 g.P("func init() {")
1562 g.In()
1563 for _, l := range g.init {
1564 g.P(l)
1565 }
1566 g.Out()
1567 g.P("}")
1568 g.init = nil
1569 }
1570
1571 // And now lots of helper functions.
1572
1573 // Is c an ASCII lower-case letter?
1574 func isASCIILower(c byte) bool {
1575 return 'a' <= c && c <= 'z'
1576 }
1577
1578 // Is c an ASCII digit?
1579 func isASCIIDigit(c byte) bool {
1580 return '0' <= c && c <= '9'
1581 }
1582
1583 // CamelCase returns the CamelCased name.
1584 // If there is an interior underscore followed by a lower case letter,
1585 // drop the underscore and convert the letter to upper case.
1586 // There is a remote possibility of this rewrite causing a name collision,
1587 // but it's so remote we're prepared to pretend it's nonexistent - since the
1588 // C++ generator lowercases names, it's extremely unlikely to have two fields
1589 // with different capitalizations.
1590 // In short, _my_field_name_2 becomes XMyFieldName_2.
1591 func CamelCase(s string) string {
1592 if s == "" {
1593 return ""
1594 }
1595 t := make([]byte, 0, 32)
1596 i := 0
1597 if s[0] == '_' {
1598 // Need a capital letter; drop the '_'.
1599 t = append(t, 'X')
1600 i++
1601 }
1602 // Invariant: if the next letter is lower case, it must be converted
1603 // to upper case.
1604 // That is, we process a word at a time, where words are marked by _ or
1605 // upper case letter. Digits are treated as words.
1606 for ; i < len(s); i++ {
1607 c := s[i]
1608 if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
1609 continue // Skip the underscore in s.
1610 }
1611 if isASCIIDigit(c) {
1612 t = append(t, c)
1613 continue
1614 }
1615 // Assume we have a letter now - if not, it's a bogus identifier.
1616 // The next word is a sequence of characters that must start upper case.
1617 if isASCIILower(c) {
1618 c ^= ' ' // Make it a capital letter.
1619 }
1620 t = append(t, c) // Guaranteed not lower case.
1621 // Accept lower case sequence that follows.
1622 for i+1 < len(s) && isASCIILower(s[i+1]) {
1623 i++
1624 t = append(t, s[i])
1625 }
1626 }
1627 return string(t)
1628 }
1629
1630 // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
1631 // be joined with "_".
1632 func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
1633
1634 // dottedSlice turns a sliced name into a dotted name.
1635 func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
1636
1637 // Is this field optional?
1638 func isOptional(field *descriptor.FieldDescriptorProto) bool {
1639 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
1640 }
1641
1642 // Is this field required?
1643 func isRequired(field *descriptor.FieldDescriptorProto) bool {
1644 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
1645 }
1646
1647 // Is this field repeated?
1648 func isRepeated(field *descriptor.FieldDescriptorProto) bool {
1649 return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
1650 }
1651
1652 // Is this field a scalar numeric type?
1653 func IsScalar(field *descriptor.FieldDescriptorProto) bool {
1654 if field.Type == nil {
1655 return false
1656 }
1657 switch *field.Type {
1658 case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
1659 descriptor.FieldDescriptorProto_TYPE_FLOAT,
1660 descriptor.FieldDescriptorProto_TYPE_INT64,
1661 descriptor.FieldDescriptorProto_TYPE_UINT64,
1662 descriptor.FieldDescriptorProto_TYPE_INT32,
1663 descriptor.FieldDescriptorProto_TYPE_FIXED64,
1664 descriptor.FieldDescriptorProto_TYPE_FIXED32,
1665 descriptor.FieldDescriptorProto_TYPE_BOOL,
1666 descriptor.FieldDescriptorProto_TYPE_UINT32,
1667 descriptor.FieldDescriptorProto_TYPE_ENUM,
1668 descriptor.FieldDescriptorProto_TYPE_SFIXED32,
1669 descriptor.FieldDescriptorProto_TYPE_SFIXED64,
1670 descriptor.FieldDescriptorProto_TYPE_SINT32,
1671 descriptor.FieldDescriptorProto_TYPE_SINT64:
1672 return true
1673 default:
1674 return false
1675 }
1676 }
1677
1678 // badToUnderscore is the mapping function used to generate Go names from package names,
1679 // which can be dotted in the input .proto file. It replaces non-identifier characters such as
1680 // dot or dash with underscore.
1681 func badToUnderscore(r rune) rune {
1682 if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
1683 return r
1684 }
1685 return '_'
1686 }
1687
1688 // baseName returns the last path element of the name, with the last dotted suffix removed.
1689 func baseName(name string) string {
1690 // First, find the last element
1691 if i := strings.LastIndex(name, "/"); i >= 0 {
1692 name = name[i+1:]
1693 }
1694 // Now drop the suffix
1695 if i := strings.LastIndex(name, "."); i >= 0 {
1696 name = name[0:i]
1697 }
1698 return name
1699 }
1700
1701 // The SourceCodeInfo message describes the location of elements of a parsed
1702 // .proto file by way of a "path", which is a sequence of integers that
1703 // describe the route from a FileDescriptorProto to the relevant submessage.
1704 // The path alternates between a field number of a repeated field, and an index
1705 // into that repeated field. The constants below define the field numbers that
1706 // are used.
1707 //
1708 // See descriptor.proto for more information about this.
1709 const (
1710 // tag numbers in FileDescriptorProto
1711 packagePath = 2 // package
1712 messagePath = 4 // message_type
1713 enumPath = 5 // enum_type
1714 // tag numbers in DescriptorProto
1715 messageFieldPath = 2 // field
1716 messageMessagePath = 3 // nested_type
1717 messageEnumPath = 4 // enum_type
1718 messageOneofPath = 8 // oneof_decl
1719 // tag numbers in EnumDescriptorProto
1720 enumValuePath = 2 // value
1721 )