blob: ae31fd28e0f781c3a1ef9ef7dbaac8977e503609 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package protogen provides support for writing protoc plugins.
6//
7// Plugins for protoc, the Protocol Buffers Compiler, are programs which read
8// a CodeGeneratorRequest protocol buffer from standard input and write a
9// CodeGeneratorResponse protocol buffer to standard output. This package
10// provides support for writing plugins which generate Go code.
11package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
16 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070017 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070018 "go/parser"
19 "go/printer"
20 "go/token"
Damien Neil220c2022018-08-15 11:24:18 -070021 "io/ioutil"
22 "os"
Damien Neil082ce922018-09-06 10:23:53 -070023 "path"
Damien Neil220c2022018-08-15 11:24:18 -070024 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070025 "sort"
26 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070027 "strings"
28
29 "github.com/golang/protobuf/proto"
30 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
31 pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
Damien Neild9016772018-08-23 14:39:30 -070032 "golang.org/x/tools/go/ast/astutil"
Damien Neilabc6fc12018-08-23 14:39:30 -070033 "google.golang.org/proto/reflect/protoreflect"
34 "google.golang.org/proto/reflect/protoregistry"
35 "google.golang.org/proto/reflect/prototype"
Damien Neil220c2022018-08-15 11:24:18 -070036)
37
38// Run executes a function as a protoc plugin.
39//
40// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
41// function, and writes a CodeGeneratorResponse message to os.Stdout.
42//
43// If a failure occurs while reading or writing, Run prints an error to
44// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070045//
46// Passing a nil options is equivalent to passing a zero-valued one.
47func Run(opts *Options, f func(*Plugin) error) {
48 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070049 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
50 os.Exit(1)
51 }
52}
53
Damien Neil3cf6e622018-09-11 13:53:14 -070054func run(opts *Options, f func(*Plugin) error) error {
Damien Neil220c2022018-08-15 11:24:18 -070055 in, err := ioutil.ReadAll(os.Stdin)
56 if err != nil {
57 return err
58 }
59 req := &pluginpb.CodeGeneratorRequest{}
60 if err := proto.Unmarshal(in, req); err != nil {
61 return err
62 }
Damien Neil3cf6e622018-09-11 13:53:14 -070063 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070064 if err != nil {
65 return err
66 }
67 if err := f(gen); err != nil {
68 // Errors from the plugin function are reported by setting the
69 // error field in the CodeGeneratorResponse.
70 //
71 // In contrast, errors that indicate a problem in protoc
72 // itself (unparsable input, I/O errors, etc.) are reported
73 // to stderr.
74 gen.Error(err)
75 }
76 resp := gen.Response()
77 out, err := proto.Marshal(resp)
78 if err != nil {
79 return err
80 }
81 if _, err := os.Stdout.Write(out); err != nil {
82 return err
83 }
84 return nil
85}
86
87// A Plugin is a protoc plugin invocation.
88type Plugin struct {
89 // Request is the CodeGeneratorRequest provided by protoc.
90 Request *pluginpb.CodeGeneratorRequest
91
92 // Files is the set of files to generate and everything they import.
93 // Files appear in topological order, so each file appears before any
94 // file that imports it.
95 Files []*File
96 filesByName map[string]*File
97
Damien Neil658051b2018-09-10 12:26:21 -070098 fileReg *protoregistry.Files
99 messagesByName map[protoreflect.FullName]*Message
100 enumsByName map[protoreflect.FullName]*Enum
101 pathType pathType
102 genFiles []*GeneratedFile
103 err error
Damien Neil220c2022018-08-15 11:24:18 -0700104}
105
Damien Neil3cf6e622018-09-11 13:53:14 -0700106// Options are optional parameters to New.
107type Options struct {
108 // If ParamFunc is non-nil, it will be called with each unknown
109 // generator parameter.
110 //
111 // Plugins for protoc can accept parameters from the command line,
112 // passed in the --<lang>_out protoc, separated from the output
113 // directory with a colon; e.g.,
114 //
115 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
116 //
117 // Parameters passed in this fashion as a comma-separated list of
118 // key=value pairs will be passed to the ParamFunc.
119 //
120 // The (flag.FlagSet).Set method matches this function signature,
121 // so parameters can be converted into flags as in the following:
122 //
123 // var flags flag.FlagSet
124 // value := flags.Bool("param", false, "")
125 // opts := &protogen.Options{
126 // ParamFunc: flags.Set,
127 // }
128 // protogen.Run(opts, func(p *protogen.Plugin) error {
129 // if *value { ... }
130 // })
131 ParamFunc func(name, value string) error
132}
133
Damien Neil220c2022018-08-15 11:24:18 -0700134// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700135//
136// Passing a nil Options is equivalent to passing a zero-valued one.
137func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
138 if opts == nil {
139 opts = &Options{}
140 }
Damien Neil220c2022018-08-15 11:24:18 -0700141 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700142 Request: req,
143 filesByName: make(map[string]*File),
144 fileReg: protoregistry.NewFiles(),
145 messagesByName: make(map[protoreflect.FullName]*Message),
146 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil220c2022018-08-15 11:24:18 -0700147 }
148
Damien Neil082ce922018-09-06 10:23:53 -0700149 packageNames := make(map[string]GoPackageName) // filename -> package name
150 importPaths := make(map[string]GoImportPath) // filename -> import path
151 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700152 for _, param := range strings.Split(req.GetParameter(), ",") {
153 var value string
154 if i := strings.Index(param, "="); i >= 0 {
155 value = param[i+1:]
156 param = param[0:i]
157 }
158 switch param {
159 case "":
160 // Ignore.
161 case "import_prefix":
162 // TODO
163 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700164 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700165 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700166 switch value {
167 case "import":
168 gen.pathType = pathTypeImport
169 case "source_relative":
170 gen.pathType = pathTypeSourceRelative
171 default:
172 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
173 }
Damien Neil220c2022018-08-15 11:24:18 -0700174 case "annotate_code":
175 // TODO
176 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700177 if param[0] == 'M' {
178 importPaths[param[1:]] = GoImportPath(value)
179 continue
Damien Neil220c2022018-08-15 11:24:18 -0700180 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700181 if opts.ParamFunc != nil {
182 if err := opts.ParamFunc(param, value); err != nil {
183 return nil, err
184 }
185 }
Damien Neil082ce922018-09-06 10:23:53 -0700186 }
187 }
188
189 // Figure out the import path and package name for each file.
190 //
191 // The rules here are complicated and have grown organically over time.
192 // Interactions between different ways of specifying package information
193 // may be surprising.
194 //
195 // The recommended approach is to include a go_package option in every
196 // .proto source file specifying the full import path of the Go package
197 // associated with this file.
198 //
199 // option go_package = "github.com/golang/protobuf/ptypes/any";
200 //
201 // Build systems which want to exert full control over import paths may
202 // specify M<filename>=<import_path> flags.
203 //
204 // Other approaches are not recommend.
205 generatedFileNames := make(map[string]bool)
206 for _, name := range gen.Request.FileToGenerate {
207 generatedFileNames[name] = true
208 }
209 // We need to determine the import paths before the package names,
210 // because the Go package name for a file is sometimes derived from
211 // different file in the same package.
212 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
213 for _, fdesc := range gen.Request.ProtoFile {
214 filename := fdesc.GetName()
215 packageName, importPath := goPackageOption(fdesc)
216 switch {
217 case importPaths[filename] != "":
218 // Command line: M=foo.proto=quux/bar
219 //
220 // Explicit mapping of source file to import path.
221 case generatedFileNames[filename] && packageImportPath != "":
222 // Command line: import_path=quux/bar
223 //
224 // The import_path flag sets the import path for every file that
225 // we generate code for.
226 importPaths[filename] = packageImportPath
227 case importPath != "":
228 // Source file: option go_package = "quux/bar";
229 //
230 // The go_package option sets the import path. Most users should use this.
231 importPaths[filename] = importPath
232 default:
233 // Source filename.
234 //
235 // Last resort when nothing else is available.
236 importPaths[filename] = GoImportPath(path.Dir(filename))
237 }
238 if packageName != "" {
239 packageNameForImportPath[importPaths[filename]] = packageName
240 }
241 }
242 for _, fdesc := range gen.Request.ProtoFile {
243 filename := fdesc.GetName()
244 packageName, _ := goPackageOption(fdesc)
245 defaultPackageName := packageNameForImportPath[importPaths[filename]]
246 switch {
247 case packageName != "":
248 // Source file: option go_package = "quux/bar";
249 packageNames[filename] = packageName
250 case defaultPackageName != "":
251 // A go_package option in another file in the same package.
252 //
253 // This is a poor choice in general, since every source file should
254 // contain a go_package option. Supported mainly for historical
255 // compatibility.
256 packageNames[filename] = defaultPackageName
257 case generatedFileNames[filename] && packageImportPath != "":
258 // Command line: import_path=quux/bar
259 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
260 case fdesc.GetPackage() != "":
261 // Source file: package quux.bar;
262 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
263 default:
264 // Source filename.
265 packageNames[filename] = cleanPackageName(baseName(filename))
266 }
267 }
268
269 // Consistency check: Every file with the same Go import path should have
270 // the same Go package name.
271 packageFiles := make(map[GoImportPath][]string)
272 for filename, importPath := range importPaths {
273 packageFiles[importPath] = append(packageFiles[importPath], filename)
274 }
275 for importPath, filenames := range packageFiles {
276 for i := 1; i < len(filenames); i++ {
277 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
278 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
279 importPath, a, filenames[0], b, filenames[i])
280 }
Damien Neil220c2022018-08-15 11:24:18 -0700281 }
282 }
283
284 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700285 filename := fdesc.GetName()
286 if gen.filesByName[filename] != nil {
287 return nil, fmt.Errorf("duplicate file name: %q", filename)
288 }
289 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700290 if err != nil {
291 return nil, err
292 }
Damien Neil220c2022018-08-15 11:24:18 -0700293 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700294 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700295 }
Damien Neil082ce922018-09-06 10:23:53 -0700296 for _, filename := range gen.Request.FileToGenerate {
297 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700298 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700299 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700300 }
301 f.Generate = true
302 }
303 return gen, nil
304}
305
306// Error records an error in code generation. The generator will report the
307// error back to protoc and will not produce output.
308func (gen *Plugin) Error(err error) {
309 if gen.err == nil {
310 gen.err = err
311 }
312}
313
314// Response returns the generator output.
315func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
316 resp := &pluginpb.CodeGeneratorResponse{}
317 if gen.err != nil {
318 resp.Error = proto.String(gen.err.Error())
319 return resp
320 }
321 for _, gf := range gen.genFiles {
Damien Neilc7d07d92018-08-22 13:46:02 -0700322 content, err := gf.Content()
323 if err != nil {
324 return &pluginpb.CodeGeneratorResponse{
325 Error: proto.String(err.Error()),
326 }
327 }
Damien Neil220c2022018-08-15 11:24:18 -0700328 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neild9016772018-08-23 14:39:30 -0700329 Name: proto.String(gf.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700330 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700331 })
332 }
333 return resp
334}
335
336// FileByName returns the file with the given name.
337func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
338 f, ok = gen.filesByName[name]
339 return f, ok
340}
341
Damien Neilc7d07d92018-08-22 13:46:02 -0700342// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700343type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700344 Desc protoreflect.FileDescriptor
345 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700346
Damien Neil082ce922018-09-06 10:23:53 -0700347 GoPackageName GoPackageName // name of this file's Go package
348 GoImportPath GoImportPath // import path of this file's Go package
349 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700350 Enums []*Enum // top-level enum declarations
Damien Neil082ce922018-09-06 10:23:53 -0700351 Generate bool // true if we should generate code for this file
352
353 // GeneratedFilenamePrefix is used to construct filenames for generated
354 // files associated with this source file.
355 //
356 // For example, the source file "dir/foo.proto" might have a filename prefix
357 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
358 GeneratedFilenamePrefix string
Damien Neil220c2022018-08-15 11:24:18 -0700359}
360
Damien Neil082ce922018-09-06 10:23:53 -0700361func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700362 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
363 if err != nil {
364 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
365 }
366 if err := gen.fileReg.Register(desc); err != nil {
367 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
368 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700369 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700370 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700371 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700372 GoPackageName: packageName,
373 GoImportPath: importPath,
Damien Neil220c2022018-08-15 11:24:18 -0700374 }
Damien Neil082ce922018-09-06 10:23:53 -0700375
376 // Determine the prefix for generated Go files.
377 prefix := p.GetName()
378 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
379 prefix = prefix[:len(prefix)-len(ext)]
380 }
381 if gen.pathType == pathTypeImport {
382 // If paths=import (the default) and the file contains a go_package option
383 // with a full import path, the output filename is derived from the Go import
384 // path.
385 //
386 // Pass the paths=source_relative flag to always derive the output filename
387 // from the input filename instead.
388 if _, importPath := goPackageOption(p); importPath != "" {
389 prefix = path.Join(string(importPath), path.Base(prefix))
390 }
391 }
392 f.GeneratedFilenamePrefix = prefix
393
Damien Neilabc6fc12018-08-23 14:39:30 -0700394 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700395 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700396 }
Damien Neil46abb572018-09-07 12:45:37 -0700397 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
398 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
399 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700400 for _, message := range f.Messages {
401 message.init(gen)
402 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700403 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700404}
405
Damien Neil082ce922018-09-06 10:23:53 -0700406// goPackageOption interprets a file's go_package option.
407// If there is no go_package, it returns ("", "").
408// If there's a simple name, it returns (pkg, "").
409// If the option implies an import path, it returns (pkg, impPath).
410func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
411 opt := d.GetOptions().GetGoPackage()
412 if opt == "" {
413 return "", ""
414 }
415 // A semicolon-delimited suffix delimits the import path and package name.
416 if i := strings.Index(opt, ";"); i >= 0 {
417 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
418 }
419 // The presence of a slash implies there's an import path.
420 if i := strings.LastIndex(opt, "/"); i >= 0 {
421 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
422 }
423 return cleanPackageName(opt), ""
424}
425
Damien Neilc7d07d92018-08-22 13:46:02 -0700426// A Message describes a message.
427type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700428 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700429
430 GoIdent GoIdent // name of the generated Go type
Damien Neil658051b2018-09-10 12:26:21 -0700431 Fields []*Field // message field declarations
Damien Neil1fa78d82018-09-13 13:12:36 -0700432 Oneofs []*Oneof // oneof declarations
Damien Neilc7d07d92018-08-22 13:46:02 -0700433 Messages []*Message // nested message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700434 Enums []*Enum // nested enum declarations
Damien Neilcab8dfe2018-09-06 14:51:28 -0700435 Path []int32 // location path of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700436}
437
Damien Neil1fa78d82018-09-13 13:12:36 -0700438func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700439 var path []int32
440 if parent != nil {
441 path = pathAppend(parent.Path, messageMessageField, int32(desc.Index()))
442 } else {
443 path = []int32{fileMessageField, int32(desc.Index())}
444 }
Damien Neil46abb572018-09-07 12:45:37 -0700445 message := &Message{
Damien Neilabc6fc12018-08-23 14:39:30 -0700446 Desc: desc,
447 GoIdent: newGoIdent(f, desc),
Damien Neilcab8dfe2018-09-06 14:51:28 -0700448 Path: path,
Damien Neilc7d07d92018-08-22 13:46:02 -0700449 }
Damien Neil658051b2018-09-10 12:26:21 -0700450 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700451 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700452 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700453 }
Damien Neil46abb572018-09-07 12:45:37 -0700454 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
455 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
456 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700457 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
458 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
459 }
Damien Neil658051b2018-09-10 12:26:21 -0700460 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700461 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700462 }
463
464 // Field name conflict resolution.
465 //
466 // We assume well-known method names that may be attached to a generated
467 // message type, as well as a 'Get*' method for each field. For each
468 // field in turn, we add _s to its name until there are no conflicts.
469 //
470 // Any change to the following set of method names is a potential
471 // incompatible API change because it may change generated field names.
472 //
473 // TODO: If we ever support a 'go_name' option to set the Go name of a
474 // field, we should consider dropping this entirely. The conflict
475 // resolution algorithm is subtle and surprising (changing the order
476 // in which fields appear in the .proto source file can change the
477 // names of fields in generated code), and does not adapt well to
478 // adding new per-field methods such as setters.
479 usedNames := map[string]bool{
480 "Reset": true,
481 "String": true,
482 "ProtoMessage": true,
483 "Marshal": true,
484 "Unmarshal": true,
485 "ExtensionRangeArray": true,
486 "ExtensionMap": true,
487 "Descriptor": true,
488 }
489 makeNameUnique := func(name string) string {
490 for usedNames[name] || usedNames["Get"+name] {
491 name += "_"
492 }
493 usedNames[name] = true
494 usedNames["Get"+name] = true
495 return name
496 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700497 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700498 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700499 field.GoName = makeNameUnique(field.GoName)
500 if field.OneofType != nil {
501 if !seenOneofs[field.OneofType.Desc.Index()] {
502 // If this is a field in a oneof that we haven't seen before,
503 // make the name for that oneof unique as well.
504 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
505 seenOneofs[field.OneofType.Desc.Index()] = true
506 }
507 }
Damien Neil658051b2018-09-10 12:26:21 -0700508 }
509
Damien Neil1fa78d82018-09-13 13:12:36 -0700510 return message
Damien Neil658051b2018-09-10 12:26:21 -0700511}
512
Damien Neil0bd5a382018-09-13 15:07:10 -0700513func (message *Message) init(gen *Plugin) error {
514 for _, child := range message.Messages {
515 if err := child.init(gen); err != nil {
516 return err
517 }
518 }
519 for _, field := range message.Fields {
520 if err := field.init(gen); err != nil {
521 return err
522 }
523 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700524 for _, oneof := range message.Oneofs {
525 oneof.init(gen, message)
526 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700527 return nil
528}
529
Damien Neil658051b2018-09-10 12:26:21 -0700530// A Field describes a message field.
531type Field struct {
532 Desc protoreflect.FieldDescriptor
533
Damien Neil1fa78d82018-09-13 13:12:36 -0700534 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700535 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700536 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
537 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700538
Damien Neil1fa78d82018-09-13 13:12:36 -0700539 ContainingType *Message // message in which this field occurs
540 MessageType *Message // type for message or group fields; nil otherwise
541 EnumType *Enum // type for enum fields; nil otherwise
542 OneofType *Oneof // containing oneof; nil if not part of a oneof
543 Path []int32 // location path of this field
Damien Neil658051b2018-09-10 12:26:21 -0700544}
545
Damien Neil1fa78d82018-09-13 13:12:36 -0700546func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil658051b2018-09-10 12:26:21 -0700547 field := &Field{
Damien Neil1fa78d82018-09-13 13:12:36 -0700548 Desc: desc,
549 GoName: camelCase(string(desc.Name())),
550 ContainingType: message,
551 Path: pathAppend(message.Path, messageFieldField, int32(desc.Index())),
Damien Neil658051b2018-09-10 12:26:21 -0700552 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700553 if desc.OneofType() != nil {
554 field.OneofType = message.Oneofs[desc.OneofType().Index()]
555 }
556 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700557}
558
559func (field *Field) init(gen *Plugin) error {
560 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700561 switch desc.Kind() {
562 case protoreflect.MessageKind, protoreflect.GroupKind:
563 mname := desc.MessageType().FullName()
564 message, ok := gen.messagesByName[mname]
565 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700566 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700567 }
568 field.MessageType = message
569 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700570 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700571 enum, ok := gen.enumsByName[ename]
572 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700573 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700574 }
575 field.EnumType = enum
576 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700577 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700578}
579
Damien Neil1fa78d82018-09-13 13:12:36 -0700580// A Oneof describes a oneof field.
581type Oneof struct {
582 Desc protoreflect.OneofDescriptor
583
584 GoName string // Go field name of this oneof
585 ContainingType *Message // message in which this oneof occurs
586 Fields []*Field // fields that are part of this oneof
587 Path []int32 // location path of this oneof
588}
589
590func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
591 return &Oneof{
592 Desc: desc,
593 ContainingType: message,
594 GoName: camelCase(string(desc.Name())),
595 Path: pathAppend(message.Path, messageOneofField, int32(desc.Index())),
596 }
597}
598
599func (oneof *Oneof) init(gen *Plugin, parent *Message) {
600 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
601 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
602 }
603}
604
Damien Neil46abb572018-09-07 12:45:37 -0700605// An Enum describes an enum.
606type Enum struct {
607 Desc protoreflect.EnumDescriptor
608
609 GoIdent GoIdent // name of the generated Go type
610 Values []*EnumValue // enum values
611 Path []int32 // location path of this enum
612}
613
614func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
615 var path []int32
616 if parent != nil {
617 path = pathAppend(parent.Path, messageEnumField, int32(desc.Index()))
618 } else {
619 path = []int32{fileEnumField, int32(desc.Index())}
620 }
621 enum := &Enum{
622 Desc: desc,
623 GoIdent: newGoIdent(f, desc),
624 Path: path,
625 }
Damien Neil658051b2018-09-10 12:26:21 -0700626 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700627 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
628 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
629 }
630 return enum
631}
632
633// An EnumValue describes an enum value.
634type EnumValue struct {
635 Desc protoreflect.EnumValueDescriptor
636
637 GoIdent GoIdent // name of the generated Go type
638 Path []int32 // location path of this enum value
639}
640
641func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
642 // A top-level enum value's name is: EnumName_ValueName
643 // An enum value contained in a message is: MessageName_ValueName
644 //
645 // Enum value names are not camelcased.
646 parentIdent := enum.GoIdent
647 if message != nil {
648 parentIdent = message.GoIdent
649 }
650 name := parentIdent.GoName + "_" + string(desc.Name())
651 return &EnumValue{
652 Desc: desc,
653 GoIdent: GoIdent{
654 GoName: name,
655 GoImportPath: f.GoImportPath,
656 },
657 Path: pathAppend(enum.Path, enumValueField, int32(desc.Index())),
658 }
Damien Neil220c2022018-08-15 11:24:18 -0700659}
660
661// A GeneratedFile is a generated file.
662type GeneratedFile struct {
Damien Neild9016772018-08-23 14:39:30 -0700663 filename string
664 goImportPath GoImportPath
665 buf bytes.Buffer
666 packageNames map[GoImportPath]GoPackageName
667 usedPackageNames map[GoPackageName]bool
Damien Neil220c2022018-08-15 11:24:18 -0700668}
669
Damien Neild9016772018-08-23 14:39:30 -0700670// NewGeneratedFile creates a new generated file with the given filename
671// and import path.
672func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700673 g := &GeneratedFile{
Damien Neild9016772018-08-23 14:39:30 -0700674 filename: filename,
675 goImportPath: goImportPath,
676 packageNames: make(map[GoImportPath]GoPackageName),
677 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil220c2022018-08-15 11:24:18 -0700678 }
679 gen.genFiles = append(gen.genFiles, g)
680 return g
681}
682
683// P prints a line to the generated output. It converts each parameter to a
684// string following the same rules as fmt.Print. It never inserts spaces
685// between parameters.
686//
687// TODO: .meta file annotations.
688func (g *GeneratedFile) P(v ...interface{}) {
689 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700690 switch x := x.(type) {
691 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700692 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700693 default:
694 fmt.Fprint(&g.buf, x)
695 }
Damien Neil220c2022018-08-15 11:24:18 -0700696 }
697 fmt.Fprintln(&g.buf)
698}
699
Damien Neil46abb572018-09-07 12:45:37 -0700700// QualifiedGoIdent returns the string to use for a Go identifier.
701//
702// If the identifier is from a different Go package than the generated file,
703// the returned name will be qualified (package.name) and an import statement
704// for the identifier's package will be included in the file.
705func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
706 if ident.GoImportPath == g.goImportPath {
707 return ident.GoName
708 }
709 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
710 return string(packageName) + "." + ident.GoName
711 }
712 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
713 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
714 packageName = orig + GoPackageName(strconv.Itoa(i))
715 }
716 g.packageNames[ident.GoImportPath] = packageName
717 g.usedPackageNames[packageName] = true
718 return string(packageName) + "." + ident.GoName
719}
720
Damien Neil220c2022018-08-15 11:24:18 -0700721// Write implements io.Writer.
722func (g *GeneratedFile) Write(p []byte) (n int, err error) {
723 return g.buf.Write(p)
724}
725
726// Content returns the contents of the generated file.
Damien Neilc7d07d92018-08-22 13:46:02 -0700727func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700728 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700729 return g.buf.Bytes(), nil
730 }
731
732 // Reformat generated code.
733 original := g.buf.Bytes()
734 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700735 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700736 if err != nil {
737 // Print out the bad code with line numbers.
738 // This should never happen in practice, but it can while changing generated code
739 // so consider this a debugging aid.
740 var src bytes.Buffer
741 s := bufio.NewScanner(bytes.NewReader(original))
742 for line := 1; s.Scan(); line++ {
743 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
744 }
Damien Neild9016772018-08-23 14:39:30 -0700745 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700746 }
Damien Neild9016772018-08-23 14:39:30 -0700747
748 // Add imports.
749 var importPaths []string
750 for importPath := range g.packageNames {
751 importPaths = append(importPaths, string(importPath))
752 }
753 sort.Strings(importPaths)
754 for _, importPath := range importPaths {
Damien Neil1ec33152018-09-13 13:12:36 -0700755 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), importPath)
Damien Neild9016772018-08-23 14:39:30 -0700756 }
Damien Neil1ec33152018-09-13 13:12:36 -0700757 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700758
Damien Neilc7d07d92018-08-22 13:46:02 -0700759 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700760 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700761 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700762 }
Damien Neild9016772018-08-23 14:39:30 -0700763 // TODO: Annotations.
Damien Neilc7d07d92018-08-22 13:46:02 -0700764 return out.Bytes(), nil
765
Damien Neil220c2022018-08-15 11:24:18 -0700766}
Damien Neil082ce922018-09-06 10:23:53 -0700767
768type pathType int
769
770const (
771 pathTypeImport pathType = iota
772 pathTypeSourceRelative
773)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700774
775// The SourceCodeInfo message describes the location of elements of a parsed
776// .proto file by way of a "path", which is a sequence of integers that
777// describe the route from a FileDescriptorProto to the relevant submessage.
778// The path alternates between a field number of a repeated field, and an index
779// into that repeated field. The constants below define the field numbers that
780// are used.
781//
782// See descriptor.proto for more information about this.
783const (
784 // field numbers in FileDescriptorProto
785 filePackageField = 2 // package
786 fileMessageField = 4 // message_type
Damien Neil46abb572018-09-07 12:45:37 -0700787 fileEnumField = 5 // enum_type
Damien Neilcab8dfe2018-09-06 14:51:28 -0700788 // field numbers in DescriptorProto
789 messageFieldField = 2 // field
790 messageMessageField = 3 // nested_type
791 messageEnumField = 4 // enum_type
792 messageOneofField = 8 // oneof_decl
793 // field numbers in EnumDescriptorProto
794 enumValueField = 2 // value
795)
796
797// pathAppend appends elements to a location path.
798// It does not alias the original path.
799func pathAppend(path []int32, a ...int32) []int32 {
800 var n []int32
801 n = append(n, path...)
802 n = append(n, a...)
803 return n
804}