blob: 0ad54205b5abc17a43aa4821b2edd0a9c92aa0a4 [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"
Joe Tsai01ab2962018-09-21 17:44:00 -070032 "github.com/golang/protobuf/v2/reflect/protoreflect"
33 "github.com/golang/protobuf/v2/reflect/protoregistry"
34 "github.com/golang/protobuf/v2/reflect/prototype"
Damien Neild9016772018-08-23 14:39:30 -070035 "golang.org/x/tools/go/ast/astutil"
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
Damien Neil1fa8ab02018-09-27 15:51:05 -0700103 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700104 err error
Damien Neil220c2022018-08-15 11:24:18 -0700105}
106
Damien Neil3cf6e622018-09-11 13:53:14 -0700107// Options are optional parameters to New.
108type Options struct {
109 // If ParamFunc is non-nil, it will be called with each unknown
110 // generator parameter.
111 //
112 // Plugins for protoc can accept parameters from the command line,
113 // passed in the --<lang>_out protoc, separated from the output
114 // directory with a colon; e.g.,
115 //
116 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
117 //
118 // Parameters passed in this fashion as a comma-separated list of
119 // key=value pairs will be passed to the ParamFunc.
120 //
121 // The (flag.FlagSet).Set method matches this function signature,
122 // so parameters can be converted into flags as in the following:
123 //
124 // var flags flag.FlagSet
125 // value := flags.Bool("param", false, "")
126 // opts := &protogen.Options{
127 // ParamFunc: flags.Set,
128 // }
129 // protogen.Run(opts, func(p *protogen.Plugin) error {
130 // if *value { ... }
131 // })
132 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700133
134 // ImportRewriteFunc is called with the import path of each package
135 // imported by a generated file. It returns the import path to use
136 // for this package.
137 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700138}
139
Damien Neil220c2022018-08-15 11:24:18 -0700140// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700141//
142// Passing a nil Options is equivalent to passing a zero-valued one.
143func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
144 if opts == nil {
145 opts = &Options{}
146 }
Damien Neil220c2022018-08-15 11:24:18 -0700147 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700148 Request: req,
149 filesByName: make(map[string]*File),
150 fileReg: protoregistry.NewFiles(),
151 messagesByName: make(map[protoreflect.FullName]*Message),
152 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700153 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700154 }
155
Damien Neil082ce922018-09-06 10:23:53 -0700156 packageNames := make(map[string]GoPackageName) // filename -> package name
157 importPaths := make(map[string]GoImportPath) // filename -> import path
158 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700159 for _, param := range strings.Split(req.GetParameter(), ",") {
160 var value string
161 if i := strings.Index(param, "="); i >= 0 {
162 value = param[i+1:]
163 param = param[0:i]
164 }
165 switch param {
166 case "":
167 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700168 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700169 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700170 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700171 switch value {
172 case "import":
173 gen.pathType = pathTypeImport
174 case "source_relative":
175 gen.pathType = pathTypeSourceRelative
176 default:
177 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
178 }
Damien Neil220c2022018-08-15 11:24:18 -0700179 case "annotate_code":
180 // TODO
181 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700182 if param[0] == 'M' {
183 importPaths[param[1:]] = GoImportPath(value)
184 continue
Damien Neil220c2022018-08-15 11:24:18 -0700185 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700186 if opts.ParamFunc != nil {
187 if err := opts.ParamFunc(param, value); err != nil {
188 return nil, err
189 }
190 }
Damien Neil082ce922018-09-06 10:23:53 -0700191 }
192 }
193
194 // Figure out the import path and package name for each file.
195 //
196 // The rules here are complicated and have grown organically over time.
197 // Interactions between different ways of specifying package information
198 // may be surprising.
199 //
200 // The recommended approach is to include a go_package option in every
201 // .proto source file specifying the full import path of the Go package
202 // associated with this file.
203 //
204 // option go_package = "github.com/golang/protobuf/ptypes/any";
205 //
206 // Build systems which want to exert full control over import paths may
207 // specify M<filename>=<import_path> flags.
208 //
209 // Other approaches are not recommend.
210 generatedFileNames := make(map[string]bool)
211 for _, name := range gen.Request.FileToGenerate {
212 generatedFileNames[name] = true
213 }
214 // We need to determine the import paths before the package names,
215 // because the Go package name for a file is sometimes derived from
216 // different file in the same package.
217 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
218 for _, fdesc := range gen.Request.ProtoFile {
219 filename := fdesc.GetName()
220 packageName, importPath := goPackageOption(fdesc)
221 switch {
222 case importPaths[filename] != "":
223 // Command line: M=foo.proto=quux/bar
224 //
225 // Explicit mapping of source file to import path.
226 case generatedFileNames[filename] && packageImportPath != "":
227 // Command line: import_path=quux/bar
228 //
229 // The import_path flag sets the import path for every file that
230 // we generate code for.
231 importPaths[filename] = packageImportPath
232 case importPath != "":
233 // Source file: option go_package = "quux/bar";
234 //
235 // The go_package option sets the import path. Most users should use this.
236 importPaths[filename] = importPath
237 default:
238 // Source filename.
239 //
240 // Last resort when nothing else is available.
241 importPaths[filename] = GoImportPath(path.Dir(filename))
242 }
243 if packageName != "" {
244 packageNameForImportPath[importPaths[filename]] = packageName
245 }
246 }
247 for _, fdesc := range gen.Request.ProtoFile {
248 filename := fdesc.GetName()
249 packageName, _ := goPackageOption(fdesc)
250 defaultPackageName := packageNameForImportPath[importPaths[filename]]
251 switch {
252 case packageName != "":
253 // Source file: option go_package = "quux/bar";
254 packageNames[filename] = packageName
255 case defaultPackageName != "":
256 // A go_package option in another file in the same package.
257 //
258 // This is a poor choice in general, since every source file should
259 // contain a go_package option. Supported mainly for historical
260 // compatibility.
261 packageNames[filename] = defaultPackageName
262 case generatedFileNames[filename] && packageImportPath != "":
263 // Command line: import_path=quux/bar
264 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
265 case fdesc.GetPackage() != "":
266 // Source file: package quux.bar;
267 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
268 default:
269 // Source filename.
270 packageNames[filename] = cleanPackageName(baseName(filename))
271 }
272 }
273
274 // Consistency check: Every file with the same Go import path should have
275 // the same Go package name.
276 packageFiles := make(map[GoImportPath][]string)
277 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700278 if _, ok := packageNames[filename]; !ok {
279 // Skip files mentioned in a M<file>=<import_path> parameter
280 // but which do not appear in the CodeGeneratorRequest.
281 continue
282 }
Damien Neil082ce922018-09-06 10:23:53 -0700283 packageFiles[importPath] = append(packageFiles[importPath], filename)
284 }
285 for importPath, filenames := range packageFiles {
286 for i := 1; i < len(filenames); i++ {
287 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
288 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
289 importPath, a, filenames[0], b, filenames[i])
290 }
Damien Neil220c2022018-08-15 11:24:18 -0700291 }
292 }
293
294 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700295 filename := fdesc.GetName()
296 if gen.filesByName[filename] != nil {
297 return nil, fmt.Errorf("duplicate file name: %q", filename)
298 }
299 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700300 if err != nil {
301 return nil, err
302 }
Damien Neil220c2022018-08-15 11:24:18 -0700303 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700304 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700305 }
Damien Neil082ce922018-09-06 10:23:53 -0700306 for _, filename := range gen.Request.FileToGenerate {
307 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700308 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700309 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700310 }
311 f.Generate = true
312 }
313 return gen, nil
314}
315
316// Error records an error in code generation. The generator will report the
317// error back to protoc and will not produce output.
318func (gen *Plugin) Error(err error) {
319 if gen.err == nil {
320 gen.err = err
321 }
322}
323
324// Response returns the generator output.
325func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
326 resp := &pluginpb.CodeGeneratorResponse{}
327 if gen.err != nil {
328 resp.Error = proto.String(gen.err.Error())
329 return resp
330 }
331 for _, gf := range gen.genFiles {
Damien Neilc7d07d92018-08-22 13:46:02 -0700332 content, err := gf.Content()
333 if err != nil {
334 return &pluginpb.CodeGeneratorResponse{
335 Error: proto.String(err.Error()),
336 }
337 }
Damien Neil220c2022018-08-15 11:24:18 -0700338 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neild9016772018-08-23 14:39:30 -0700339 Name: proto.String(gf.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700340 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700341 })
342 }
343 return resp
344}
345
346// FileByName returns the file with the given name.
347func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
348 f, ok = gen.filesByName[name]
349 return f, ok
350}
351
Damien Neilc7d07d92018-08-22 13:46:02 -0700352// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700353type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700354 Desc protoreflect.FileDescriptor
355 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700356
Damien Neil082ce922018-09-06 10:23:53 -0700357 GoPackageName GoPackageName // name of this file's Go package
358 GoImportPath GoImportPath // import path of this file's Go package
359 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700360 Enums []*Enum // top-level enum declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700361 Extensions []*Extension // top-level extension declarations
Damien Neil2dc67182018-09-21 15:03:34 -0700362 Services []*Service // top-level service declarations
Damien Neil082ce922018-09-06 10:23:53 -0700363 Generate bool // true if we should generate code for this file
364
365 // GeneratedFilenamePrefix is used to construct filenames for generated
366 // files associated with this source file.
367 //
368 // For example, the source file "dir/foo.proto" might have a filename prefix
369 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
370 GeneratedFilenamePrefix string
Damien Neil220c2022018-08-15 11:24:18 -0700371}
372
Damien Neil082ce922018-09-06 10:23:53 -0700373func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700374 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
375 if err != nil {
376 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
377 }
378 if err := gen.fileReg.Register(desc); err != nil {
379 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
380 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700381 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700382 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700383 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700384 GoPackageName: packageName,
385 GoImportPath: importPath,
Damien Neil220c2022018-08-15 11:24:18 -0700386 }
Damien Neil082ce922018-09-06 10:23:53 -0700387
388 // Determine the prefix for generated Go files.
389 prefix := p.GetName()
390 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
391 prefix = prefix[:len(prefix)-len(ext)]
392 }
393 if gen.pathType == pathTypeImport {
394 // If paths=import (the default) and the file contains a go_package option
395 // with a full import path, the output filename is derived from the Go import
396 // path.
397 //
398 // Pass the paths=source_relative flag to always derive the output filename
399 // from the input filename instead.
400 if _, importPath := goPackageOption(p); importPath != "" {
401 prefix = path.Join(string(importPath), path.Base(prefix))
402 }
403 }
404 f.GeneratedFilenamePrefix = prefix
405
Damien Neilabc6fc12018-08-23 14:39:30 -0700406 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700407 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700408 }
Damien Neil46abb572018-09-07 12:45:37 -0700409 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
410 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
411 }
Damien Neil993c04d2018-09-14 15:41:11 -0700412 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
413 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
414 }
Damien Neil2dc67182018-09-21 15:03:34 -0700415 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
416 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
417 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700418 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700419 if err := message.init(gen); err != nil {
420 return nil, err
421 }
422 }
423 for _, extension := range f.Extensions {
424 if err := extension.init(gen); err != nil {
425 return nil, err
426 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700427 }
Damien Neil2dc67182018-09-21 15:03:34 -0700428 for _, service := range f.Services {
429 for _, method := range service.Methods {
430 if err := method.init(gen); err != nil {
431 return nil, err
432 }
433 }
434 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700435 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700436}
437
Damien Neil082ce922018-09-06 10:23:53 -0700438// goPackageOption interprets a file's go_package option.
439// If there is no go_package, it returns ("", "").
440// If there's a simple name, it returns (pkg, "").
441// If the option implies an import path, it returns (pkg, impPath).
442func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
443 opt := d.GetOptions().GetGoPackage()
444 if opt == "" {
445 return "", ""
446 }
447 // A semicolon-delimited suffix delimits the import path and package name.
448 if i := strings.Index(opt, ";"); i >= 0 {
449 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
450 }
451 // The presence of a slash implies there's an import path.
452 if i := strings.LastIndex(opt, "/"); i >= 0 {
453 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
454 }
455 return cleanPackageName(opt), ""
456}
457
Damien Neilc7d07d92018-08-22 13:46:02 -0700458// A Message describes a message.
459type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700460 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700461
Damien Neil993c04d2018-09-14 15:41:11 -0700462 GoIdent GoIdent // name of the generated Go type
463 Fields []*Field // message field declarations
464 Oneofs []*Oneof // oneof declarations
465 Messages []*Message // nested message declarations
466 Enums []*Enum // nested enum declarations
467 Extensions []*Extension // nested extension declarations
468 Path []int32 // location path of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700469}
470
Damien Neil1fa78d82018-09-13 13:12:36 -0700471func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700472 var path []int32
473 if parent != nil {
474 path = pathAppend(parent.Path, messageMessageField, int32(desc.Index()))
475 } else {
476 path = []int32{fileMessageField, int32(desc.Index())}
477 }
Damien Neil46abb572018-09-07 12:45:37 -0700478 message := &Message{
Damien Neilabc6fc12018-08-23 14:39:30 -0700479 Desc: desc,
480 GoIdent: newGoIdent(f, desc),
Damien Neilcab8dfe2018-09-06 14:51:28 -0700481 Path: path,
Damien Neilc7d07d92018-08-22 13:46:02 -0700482 }
Damien Neil658051b2018-09-10 12:26:21 -0700483 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700484 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700485 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700486 }
Damien Neil46abb572018-09-07 12:45:37 -0700487 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
488 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
489 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700490 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
491 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
492 }
Damien Neil658051b2018-09-10 12:26:21 -0700493 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700494 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700495 }
Damien Neil993c04d2018-09-14 15:41:11 -0700496 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
497 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
498 }
Damien Neil658051b2018-09-10 12:26:21 -0700499
500 // Field name conflict resolution.
501 //
502 // We assume well-known method names that may be attached to a generated
503 // message type, as well as a 'Get*' method for each field. For each
504 // field in turn, we add _s to its name until there are no conflicts.
505 //
506 // Any change to the following set of method names is a potential
507 // incompatible API change because it may change generated field names.
508 //
509 // TODO: If we ever support a 'go_name' option to set the Go name of a
510 // field, we should consider dropping this entirely. The conflict
511 // resolution algorithm is subtle and surprising (changing the order
512 // in which fields appear in the .proto source file can change the
513 // names of fields in generated code), and does not adapt well to
514 // adding new per-field methods such as setters.
515 usedNames := map[string]bool{
516 "Reset": true,
517 "String": true,
518 "ProtoMessage": true,
519 "Marshal": true,
520 "Unmarshal": true,
521 "ExtensionRangeArray": true,
522 "ExtensionMap": true,
523 "Descriptor": true,
524 }
525 makeNameUnique := func(name string) string {
526 for usedNames[name] || usedNames["Get"+name] {
527 name += "_"
528 }
529 usedNames[name] = true
530 usedNames["Get"+name] = true
531 return name
532 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700533 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700534 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700535 field.GoName = makeNameUnique(field.GoName)
536 if field.OneofType != nil {
537 if !seenOneofs[field.OneofType.Desc.Index()] {
538 // If this is a field in a oneof that we haven't seen before,
539 // make the name for that oneof unique as well.
540 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
541 seenOneofs[field.OneofType.Desc.Index()] = true
542 }
543 }
Damien Neil658051b2018-09-10 12:26:21 -0700544 }
545
Damien Neil1fa78d82018-09-13 13:12:36 -0700546 return message
Damien Neil658051b2018-09-10 12:26:21 -0700547}
548
Damien Neil0bd5a382018-09-13 15:07:10 -0700549func (message *Message) init(gen *Plugin) error {
550 for _, child := range message.Messages {
551 if err := child.init(gen); err != nil {
552 return err
553 }
554 }
555 for _, field := range message.Fields {
556 if err := field.init(gen); err != nil {
557 return err
558 }
559 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700560 for _, oneof := range message.Oneofs {
561 oneof.init(gen, message)
562 }
Damien Neil993c04d2018-09-14 15:41:11 -0700563 for _, extension := range message.Extensions {
564 if err := extension.init(gen); err != nil {
565 return err
566 }
567 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700568 return nil
569}
570
Damien Neil658051b2018-09-10 12:26:21 -0700571// A Field describes a message field.
572type Field struct {
573 Desc protoreflect.FieldDescriptor
574
Damien Neil1fa78d82018-09-13 13:12:36 -0700575 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700576 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700577 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
578 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700579
Damien Neil993c04d2018-09-14 15:41:11 -0700580 ParentMessage *Message // message in which this field is defined; nil if top-level extension
581 ExtendedType *Message // extended message for extension fields; nil otherwise
582 MessageType *Message // type for message or group fields; nil otherwise
583 EnumType *Enum // type for enum fields; nil otherwise
584 OneofType *Oneof // containing oneof; nil if not part of a oneof
585 Path []int32 // location path of this field
Damien Neil658051b2018-09-10 12:26:21 -0700586}
587
Damien Neil1fa78d82018-09-13 13:12:36 -0700588func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil993c04d2018-09-14 15:41:11 -0700589 var path []int32
590 switch {
591 case desc.ExtendedType() != nil && message == nil:
592 path = []int32{fileExtensionField, int32(desc.Index())}
593 case desc.ExtendedType() != nil && message != nil:
594 path = pathAppend(message.Path, messageExtensionField, int32(desc.Index()))
595 default:
596 path = pathAppend(message.Path, messageFieldField, int32(desc.Index()))
597 }
Damien Neil658051b2018-09-10 12:26:21 -0700598 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700599 Desc: desc,
600 GoName: camelCase(string(desc.Name())),
601 ParentMessage: message,
602 Path: path,
Damien Neil658051b2018-09-10 12:26:21 -0700603 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 if desc.OneofType() != nil {
605 field.OneofType = message.Oneofs[desc.OneofType().Index()]
606 }
607 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700608}
609
Damien Neil993c04d2018-09-14 15:41:11 -0700610// Extension is an alias of Field for documentation.
611type Extension = Field
612
Damien Neil0bd5a382018-09-13 15:07:10 -0700613func (field *Field) init(gen *Plugin) error {
614 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700615 switch desc.Kind() {
616 case protoreflect.MessageKind, protoreflect.GroupKind:
617 mname := desc.MessageType().FullName()
618 message, ok := gen.messagesByName[mname]
619 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700620 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700621 }
622 field.MessageType = message
623 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700624 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700625 enum, ok := gen.enumsByName[ename]
626 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700627 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700628 }
629 field.EnumType = enum
630 }
Damien Neil993c04d2018-09-14 15:41:11 -0700631 if desc.ExtendedType() != nil {
632 mname := desc.ExtendedType().FullName()
633 message, ok := gen.messagesByName[mname]
634 if !ok {
635 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
636 }
637 field.ExtendedType = message
638 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700639 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700640}
641
Damien Neil1fa78d82018-09-13 13:12:36 -0700642// A Oneof describes a oneof field.
643type Oneof struct {
644 Desc protoreflect.OneofDescriptor
645
Damien Neil993c04d2018-09-14 15:41:11 -0700646 GoName string // Go field name of this oneof
647 ParentMessage *Message // message in which this oneof occurs
648 Fields []*Field // fields that are part of this oneof
649 Path []int32 // location path of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700650}
651
652func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
653 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700654 Desc: desc,
655 ParentMessage: message,
656 GoName: camelCase(string(desc.Name())),
657 Path: pathAppend(message.Path, messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700658 }
659}
660
661func (oneof *Oneof) init(gen *Plugin, parent *Message) {
662 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
663 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
664 }
665}
666
Damien Neil46abb572018-09-07 12:45:37 -0700667// An Enum describes an enum.
668type Enum struct {
669 Desc protoreflect.EnumDescriptor
670
671 GoIdent GoIdent // name of the generated Go type
672 Values []*EnumValue // enum values
673 Path []int32 // location path of this enum
674}
675
676func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
677 var path []int32
678 if parent != nil {
679 path = pathAppend(parent.Path, messageEnumField, int32(desc.Index()))
680 } else {
681 path = []int32{fileEnumField, int32(desc.Index())}
682 }
683 enum := &Enum{
684 Desc: desc,
685 GoIdent: newGoIdent(f, desc),
686 Path: path,
687 }
Damien Neil658051b2018-09-10 12:26:21 -0700688 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700689 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
690 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
691 }
692 return enum
693}
694
695// An EnumValue describes an enum value.
696type EnumValue struct {
697 Desc protoreflect.EnumValueDescriptor
698
699 GoIdent GoIdent // name of the generated Go type
700 Path []int32 // location path of this enum value
701}
702
703func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
704 // A top-level enum value's name is: EnumName_ValueName
705 // An enum value contained in a message is: MessageName_ValueName
706 //
707 // Enum value names are not camelcased.
708 parentIdent := enum.GoIdent
709 if message != nil {
710 parentIdent = message.GoIdent
711 }
712 name := parentIdent.GoName + "_" + string(desc.Name())
713 return &EnumValue{
714 Desc: desc,
715 GoIdent: GoIdent{
716 GoName: name,
717 GoImportPath: f.GoImportPath,
718 },
719 Path: pathAppend(enum.Path, enumValueField, int32(desc.Index())),
720 }
Damien Neil220c2022018-08-15 11:24:18 -0700721}
722
723// A GeneratedFile is a generated file.
724type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700725 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700726 filename string
727 goImportPath GoImportPath
728 buf bytes.Buffer
729 packageNames map[GoImportPath]GoPackageName
730 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700731 manualImports map[GoImportPath]bool
Damien Neil220c2022018-08-15 11:24:18 -0700732}
733
Damien Neild9016772018-08-23 14:39:30 -0700734// NewGeneratedFile creates a new generated file with the given filename
735// and import path.
736func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700737 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700738 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700739 filename: filename,
740 goImportPath: goImportPath,
741 packageNames: make(map[GoImportPath]GoPackageName),
742 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700743 manualImports: make(map[GoImportPath]bool),
Damien Neil220c2022018-08-15 11:24:18 -0700744 }
745 gen.genFiles = append(gen.genFiles, g)
746 return g
747}
748
Damien Neil2dc67182018-09-21 15:03:34 -0700749// A Service describes a service.
750type Service struct {
751 Desc protoreflect.ServiceDescriptor
752
753 GoName string
754 Path []int32 // location path of this service
755 Methods []*Method // service method definitions
756}
757
758func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
759 service := &Service{
760 Desc: desc,
761 GoName: camelCase(string(desc.Name())),
762 Path: []int32{fileServiceField, int32(desc.Index())},
763 }
764 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
765 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
766 }
767 return service
768}
769
770// A Method describes a method in a service.
771type Method struct {
772 Desc protoreflect.MethodDescriptor
773
774 GoName string
775 ParentService *Service
776 Path []int32 // location path of this method
777 InputType *Message
778 OutputType *Message
779}
780
781func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
782 method := &Method{
783 Desc: desc,
784 GoName: camelCase(string(desc.Name())),
785 ParentService: service,
786 Path: pathAppend(service.Path, serviceMethodField, int32(desc.Index())),
787 }
788 return method
789}
790
791func (method *Method) init(gen *Plugin) error {
792 desc := method.Desc
793
794 inName := desc.InputType().FullName()
795 in, ok := gen.messagesByName[inName]
796 if !ok {
797 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
798 }
799 method.InputType = in
800
801 outName := desc.OutputType().FullName()
802 out, ok := gen.messagesByName[outName]
803 if !ok {
804 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
805 }
806 method.OutputType = out
807
808 return nil
809}
810
Damien Neil220c2022018-08-15 11:24:18 -0700811// P prints a line to the generated output. It converts each parameter to a
812// string following the same rules as fmt.Print. It never inserts spaces
813// between parameters.
814//
815// TODO: .meta file annotations.
816func (g *GeneratedFile) P(v ...interface{}) {
817 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700818 switch x := x.(type) {
819 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700820 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700821 default:
822 fmt.Fprint(&g.buf, x)
823 }
Damien Neil220c2022018-08-15 11:24:18 -0700824 }
825 fmt.Fprintln(&g.buf)
826}
827
Damien Neil46abb572018-09-07 12:45:37 -0700828// QualifiedGoIdent returns the string to use for a Go identifier.
829//
830// If the identifier is from a different Go package than the generated file,
831// the returned name will be qualified (package.name) and an import statement
832// for the identifier's package will be included in the file.
833func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
834 if ident.GoImportPath == g.goImportPath {
835 return ident.GoName
836 }
837 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
838 return string(packageName) + "." + ident.GoName
839 }
840 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700841 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700842 packageName = orig + GoPackageName(strconv.Itoa(i))
843 }
844 g.packageNames[ident.GoImportPath] = packageName
845 g.usedPackageNames[packageName] = true
846 return string(packageName) + "." + ident.GoName
847}
848
Damien Neil2e0c3da2018-09-19 12:51:36 -0700849// Import ensures a package is imported by the generated file.
850//
851// Packages referenced by QualifiedGoIdent are automatically imported.
852// Explicitly importing a package with Import is generally only necessary
853// when the import will be blank (import _ "package").
854func (g *GeneratedFile) Import(importPath GoImportPath) {
855 g.manualImports[importPath] = true
856}
857
Damien Neil220c2022018-08-15 11:24:18 -0700858// Write implements io.Writer.
859func (g *GeneratedFile) Write(p []byte) (n int, err error) {
860 return g.buf.Write(p)
861}
862
863// Content returns the contents of the generated file.
Damien Neilc7d07d92018-08-22 13:46:02 -0700864func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700865 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700866 return g.buf.Bytes(), nil
867 }
868
869 // Reformat generated code.
870 original := g.buf.Bytes()
871 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700872 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700873 if err != nil {
874 // Print out the bad code with line numbers.
875 // This should never happen in practice, but it can while changing generated code
876 // so consider this a debugging aid.
877 var src bytes.Buffer
878 s := bufio.NewScanner(bytes.NewReader(original))
879 for line := 1; s.Scan(); line++ {
880 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
881 }
Damien Neild9016772018-08-23 14:39:30 -0700882 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700883 }
Damien Neild9016772018-08-23 14:39:30 -0700884
885 // Add imports.
886 var importPaths []string
887 for importPath := range g.packageNames {
888 importPaths = append(importPaths, string(importPath))
889 }
890 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700891 rewriteImport := func(importPath string) string {
892 if f := g.gen.opts.ImportRewriteFunc; f != nil {
893 return string(f(GoImportPath(importPath)))
894 }
895 return importPath
896 }
Damien Neild9016772018-08-23 14:39:30 -0700897 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700898 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700899 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700900 for importPath := range g.manualImports {
901 if _, ok := g.packageNames[importPath]; ok {
902 continue
903 }
Damien Neil329b75e2018-10-04 17:31:07 -0700904 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700905 }
Damien Neil1ec33152018-09-13 13:12:36 -0700906 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700907
Damien Neilc7d07d92018-08-22 13:46:02 -0700908 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700909 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700910 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700911 }
Damien Neild9016772018-08-23 14:39:30 -0700912 // TODO: Annotations.
Damien Neilc7d07d92018-08-22 13:46:02 -0700913 return out.Bytes(), nil
914
Damien Neil220c2022018-08-15 11:24:18 -0700915}
Damien Neil082ce922018-09-06 10:23:53 -0700916
917type pathType int
918
919const (
920 pathTypeImport pathType = iota
921 pathTypeSourceRelative
922)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700923
924// The SourceCodeInfo message describes the location of elements of a parsed
925// .proto file by way of a "path", which is a sequence of integers that
926// describe the route from a FileDescriptorProto to the relevant submessage.
927// The path alternates between a field number of a repeated field, and an index
928// into that repeated field. The constants below define the field numbers that
929// are used.
930//
931// See descriptor.proto for more information about this.
932const (
933 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -0700934 filePackageField = 2 // package
935 fileMessageField = 4 // message_type
936 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -0700937 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -0700938 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -0700939 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -0700940 messageFieldField = 2 // field
941 messageMessageField = 3 // nested_type
942 messageEnumField = 4 // enum_type
943 messageExtensionField = 6 // extension
944 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -0700945 // field numbers in EnumDescriptorProto
946 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -0700947 // field numbers in ServiceDescriptorProto
948 serviceMethodField = 2 // method
949 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -0700950)
951
952// pathAppend appends elements to a location path.
953// It does not alias the original path.
954func pathAppend(path []int32, a ...int32) []int32 {
955 var n []int32
956 n = append(n, path...)
957 n = append(n, a...)
958 return n
959}