blob: 81e53f8a2e9e492ecbdad464cb41c393a1e3bffc [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 Neild277b522018-10-04 15:30:51 -070055 if len(os.Args) > 1 {
56 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
57 }
Damien Neil220c2022018-08-15 11:24:18 -070058 in, err := ioutil.ReadAll(os.Stdin)
59 if err != nil {
60 return err
61 }
62 req := &pluginpb.CodeGeneratorRequest{}
63 if err := proto.Unmarshal(in, req); err != nil {
64 return err
65 }
Damien Neil3cf6e622018-09-11 13:53:14 -070066 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070067 if err != nil {
68 return err
69 }
70 if err := f(gen); err != nil {
71 // Errors from the plugin function are reported by setting the
72 // error field in the CodeGeneratorResponse.
73 //
74 // In contrast, errors that indicate a problem in protoc
75 // itself (unparsable input, I/O errors, etc.) are reported
76 // to stderr.
77 gen.Error(err)
78 }
79 resp := gen.Response()
80 out, err := proto.Marshal(resp)
81 if err != nil {
82 return err
83 }
84 if _, err := os.Stdout.Write(out); err != nil {
85 return err
86 }
87 return nil
88}
89
90// A Plugin is a protoc plugin invocation.
91type Plugin struct {
92 // Request is the CodeGeneratorRequest provided by protoc.
93 Request *pluginpb.CodeGeneratorRequest
94
95 // Files is the set of files to generate and everything they import.
96 // Files appear in topological order, so each file appears before any
97 // file that imports it.
98 Files []*File
99 filesByName map[string]*File
100
Damien Neil658051b2018-09-10 12:26:21 -0700101 fileReg *protoregistry.Files
102 messagesByName map[protoreflect.FullName]*Message
103 enumsByName map[protoreflect.FullName]*Enum
104 pathType pathType
105 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700106 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700107 err error
Damien Neil220c2022018-08-15 11:24:18 -0700108}
109
Damien Neil3cf6e622018-09-11 13:53:14 -0700110// Options are optional parameters to New.
111type Options struct {
112 // If ParamFunc is non-nil, it will be called with each unknown
113 // generator parameter.
114 //
115 // Plugins for protoc can accept parameters from the command line,
116 // passed in the --<lang>_out protoc, separated from the output
117 // directory with a colon; e.g.,
118 //
119 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
120 //
121 // Parameters passed in this fashion as a comma-separated list of
122 // key=value pairs will be passed to the ParamFunc.
123 //
124 // The (flag.FlagSet).Set method matches this function signature,
125 // so parameters can be converted into flags as in the following:
126 //
127 // var flags flag.FlagSet
128 // value := flags.Bool("param", false, "")
129 // opts := &protogen.Options{
130 // ParamFunc: flags.Set,
131 // }
132 // protogen.Run(opts, func(p *protogen.Plugin) error {
133 // if *value { ... }
134 // })
135 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700136
137 // ImportRewriteFunc is called with the import path of each package
138 // imported by a generated file. It returns the import path to use
139 // for this package.
140 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700141}
142
Damien Neil220c2022018-08-15 11:24:18 -0700143// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700144//
145// Passing a nil Options is equivalent to passing a zero-valued one.
146func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
147 if opts == nil {
148 opts = &Options{}
149 }
Damien Neil220c2022018-08-15 11:24:18 -0700150 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700151 Request: req,
152 filesByName: make(map[string]*File),
153 fileReg: protoregistry.NewFiles(),
154 messagesByName: make(map[protoreflect.FullName]*Message),
155 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700156 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700157 }
158
Damien Neil082ce922018-09-06 10:23:53 -0700159 packageNames := make(map[string]GoPackageName) // filename -> package name
160 importPaths := make(map[string]GoImportPath) // filename -> import path
161 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700162 for _, param := range strings.Split(req.GetParameter(), ",") {
163 var value string
164 if i := strings.Index(param, "="); i >= 0 {
165 value = param[i+1:]
166 param = param[0:i]
167 }
168 switch param {
169 case "":
170 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700171 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700172 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700173 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700174 switch value {
175 case "import":
176 gen.pathType = pathTypeImport
177 case "source_relative":
178 gen.pathType = pathTypeSourceRelative
179 default:
180 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
181 }
Damien Neil220c2022018-08-15 11:24:18 -0700182 case "annotate_code":
183 // TODO
184 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700185 if param[0] == 'M' {
186 importPaths[param[1:]] = GoImportPath(value)
187 continue
Damien Neil220c2022018-08-15 11:24:18 -0700188 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700189 if opts.ParamFunc != nil {
190 if err := opts.ParamFunc(param, value); err != nil {
191 return nil, err
192 }
193 }
Damien Neil082ce922018-09-06 10:23:53 -0700194 }
195 }
196
197 // Figure out the import path and package name for each file.
198 //
199 // The rules here are complicated and have grown organically over time.
200 // Interactions between different ways of specifying package information
201 // may be surprising.
202 //
203 // The recommended approach is to include a go_package option in every
204 // .proto source file specifying the full import path of the Go package
205 // associated with this file.
206 //
207 // option go_package = "github.com/golang/protobuf/ptypes/any";
208 //
209 // Build systems which want to exert full control over import paths may
210 // specify M<filename>=<import_path> flags.
211 //
212 // Other approaches are not recommend.
213 generatedFileNames := make(map[string]bool)
214 for _, name := range gen.Request.FileToGenerate {
215 generatedFileNames[name] = true
216 }
217 // We need to determine the import paths before the package names,
218 // because the Go package name for a file is sometimes derived from
219 // different file in the same package.
220 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
221 for _, fdesc := range gen.Request.ProtoFile {
222 filename := fdesc.GetName()
223 packageName, importPath := goPackageOption(fdesc)
224 switch {
225 case importPaths[filename] != "":
226 // Command line: M=foo.proto=quux/bar
227 //
228 // Explicit mapping of source file to import path.
229 case generatedFileNames[filename] && packageImportPath != "":
230 // Command line: import_path=quux/bar
231 //
232 // The import_path flag sets the import path for every file that
233 // we generate code for.
234 importPaths[filename] = packageImportPath
235 case importPath != "":
236 // Source file: option go_package = "quux/bar";
237 //
238 // The go_package option sets the import path. Most users should use this.
239 importPaths[filename] = importPath
240 default:
241 // Source filename.
242 //
243 // Last resort when nothing else is available.
244 importPaths[filename] = GoImportPath(path.Dir(filename))
245 }
246 if packageName != "" {
247 packageNameForImportPath[importPaths[filename]] = packageName
248 }
249 }
250 for _, fdesc := range gen.Request.ProtoFile {
251 filename := fdesc.GetName()
252 packageName, _ := goPackageOption(fdesc)
253 defaultPackageName := packageNameForImportPath[importPaths[filename]]
254 switch {
255 case packageName != "":
256 // Source file: option go_package = "quux/bar";
257 packageNames[filename] = packageName
258 case defaultPackageName != "":
259 // A go_package option in another file in the same package.
260 //
261 // This is a poor choice in general, since every source file should
262 // contain a go_package option. Supported mainly for historical
263 // compatibility.
264 packageNames[filename] = defaultPackageName
265 case generatedFileNames[filename] && packageImportPath != "":
266 // Command line: import_path=quux/bar
267 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
268 case fdesc.GetPackage() != "":
269 // Source file: package quux.bar;
270 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
271 default:
272 // Source filename.
273 packageNames[filename] = cleanPackageName(baseName(filename))
274 }
275 }
276
277 // Consistency check: Every file with the same Go import path should have
278 // the same Go package name.
279 packageFiles := make(map[GoImportPath][]string)
280 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700281 if _, ok := packageNames[filename]; !ok {
282 // Skip files mentioned in a M<file>=<import_path> parameter
283 // but which do not appear in the CodeGeneratorRequest.
284 continue
285 }
Damien Neil082ce922018-09-06 10:23:53 -0700286 packageFiles[importPath] = append(packageFiles[importPath], filename)
287 }
288 for importPath, filenames := range packageFiles {
289 for i := 1; i < len(filenames); i++ {
290 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
291 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
292 importPath, a, filenames[0], b, filenames[i])
293 }
Damien Neil220c2022018-08-15 11:24:18 -0700294 }
295 }
296
297 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700298 filename := fdesc.GetName()
299 if gen.filesByName[filename] != nil {
300 return nil, fmt.Errorf("duplicate file name: %q", filename)
301 }
302 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700303 if err != nil {
304 return nil, err
305 }
Damien Neil220c2022018-08-15 11:24:18 -0700306 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700307 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700308 }
Damien Neil082ce922018-09-06 10:23:53 -0700309 for _, filename := range gen.Request.FileToGenerate {
310 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700311 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700312 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700313 }
314 f.Generate = true
315 }
316 return gen, nil
317}
318
319// Error records an error in code generation. The generator will report the
320// error back to protoc and will not produce output.
321func (gen *Plugin) Error(err error) {
322 if gen.err == nil {
323 gen.err = err
324 }
325}
326
327// Response returns the generator output.
328func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
329 resp := &pluginpb.CodeGeneratorResponse{}
330 if gen.err != nil {
331 resp.Error = proto.String(gen.err.Error())
332 return resp
333 }
334 for _, gf := range gen.genFiles {
Damien Neilc7d07d92018-08-22 13:46:02 -0700335 content, err := gf.Content()
336 if err != nil {
337 return &pluginpb.CodeGeneratorResponse{
338 Error: proto.String(err.Error()),
339 }
340 }
Damien Neil220c2022018-08-15 11:24:18 -0700341 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neild9016772018-08-23 14:39:30 -0700342 Name: proto.String(gf.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700343 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700344 })
345 }
346 return resp
347}
348
349// FileByName returns the file with the given name.
350func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
351 f, ok = gen.filesByName[name]
352 return f, ok
353}
354
Damien Neilc7d07d92018-08-22 13:46:02 -0700355// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700356type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700357 Desc protoreflect.FileDescriptor
358 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700359
Damien Neil082ce922018-09-06 10:23:53 -0700360 GoPackageName GoPackageName // name of this file's Go package
361 GoImportPath GoImportPath // import path of this file's Go package
362 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700363 Enums []*Enum // top-level enum declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700364 Extensions []*Extension // top-level extension declarations
Damien Neil2dc67182018-09-21 15:03:34 -0700365 Services []*Service // top-level service declarations
Damien Neil082ce922018-09-06 10:23:53 -0700366 Generate bool // true if we should generate code for this file
367
368 // GeneratedFilenamePrefix is used to construct filenames for generated
369 // files associated with this source file.
370 //
371 // For example, the source file "dir/foo.proto" might have a filename prefix
372 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
373 GeneratedFilenamePrefix string
Damien Neil220c2022018-08-15 11:24:18 -0700374}
375
Damien Neil082ce922018-09-06 10:23:53 -0700376func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700377 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
378 if err != nil {
379 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
380 }
381 if err := gen.fileReg.Register(desc); err != nil {
382 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
383 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700384 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700385 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700386 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700387 GoPackageName: packageName,
388 GoImportPath: importPath,
Damien Neil220c2022018-08-15 11:24:18 -0700389 }
Damien Neil082ce922018-09-06 10:23:53 -0700390
391 // Determine the prefix for generated Go files.
392 prefix := p.GetName()
393 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
394 prefix = prefix[:len(prefix)-len(ext)]
395 }
396 if gen.pathType == pathTypeImport {
397 // If paths=import (the default) and the file contains a go_package option
398 // with a full import path, the output filename is derived from the Go import
399 // path.
400 //
401 // Pass the paths=source_relative flag to always derive the output filename
402 // from the input filename instead.
403 if _, importPath := goPackageOption(p); importPath != "" {
404 prefix = path.Join(string(importPath), path.Base(prefix))
405 }
406 }
407 f.GeneratedFilenamePrefix = prefix
408
Damien Neilabc6fc12018-08-23 14:39:30 -0700409 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700410 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700411 }
Damien Neil46abb572018-09-07 12:45:37 -0700412 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
413 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
414 }
Damien Neil993c04d2018-09-14 15:41:11 -0700415 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
416 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
417 }
Damien Neil2dc67182018-09-21 15:03:34 -0700418 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
419 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
420 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700421 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700422 if err := message.init(gen); err != nil {
423 return nil, err
424 }
425 }
426 for _, extension := range f.Extensions {
427 if err := extension.init(gen); err != nil {
428 return nil, err
429 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700430 }
Damien Neil2dc67182018-09-21 15:03:34 -0700431 for _, service := range f.Services {
432 for _, method := range service.Methods {
433 if err := method.init(gen); err != nil {
434 return nil, err
435 }
436 }
437 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700438 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700439}
440
Damien Neil082ce922018-09-06 10:23:53 -0700441// goPackageOption interprets a file's go_package option.
442// If there is no go_package, it returns ("", "").
443// If there's a simple name, it returns (pkg, "").
444// If the option implies an import path, it returns (pkg, impPath).
445func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
446 opt := d.GetOptions().GetGoPackage()
447 if opt == "" {
448 return "", ""
449 }
450 // A semicolon-delimited suffix delimits the import path and package name.
451 if i := strings.Index(opt, ";"); i >= 0 {
452 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
453 }
454 // The presence of a slash implies there's an import path.
455 if i := strings.LastIndex(opt, "/"); i >= 0 {
456 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
457 }
458 return cleanPackageName(opt), ""
459}
460
Damien Neilc7d07d92018-08-22 13:46:02 -0700461// A Message describes a message.
462type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700463 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700464
Damien Neil993c04d2018-09-14 15:41:11 -0700465 GoIdent GoIdent // name of the generated Go type
466 Fields []*Field // message field declarations
467 Oneofs []*Oneof // oneof declarations
468 Messages []*Message // nested message declarations
469 Enums []*Enum // nested enum declarations
470 Extensions []*Extension // nested extension declarations
471 Path []int32 // location path of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700472}
473
Damien Neil1fa78d82018-09-13 13:12:36 -0700474func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700475 var path []int32
476 if parent != nil {
477 path = pathAppend(parent.Path, messageMessageField, int32(desc.Index()))
478 } else {
479 path = []int32{fileMessageField, int32(desc.Index())}
480 }
Damien Neil46abb572018-09-07 12:45:37 -0700481 message := &Message{
Damien Neilabc6fc12018-08-23 14:39:30 -0700482 Desc: desc,
483 GoIdent: newGoIdent(f, desc),
Damien Neilcab8dfe2018-09-06 14:51:28 -0700484 Path: path,
Damien Neilc7d07d92018-08-22 13:46:02 -0700485 }
Damien Neil658051b2018-09-10 12:26:21 -0700486 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700487 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700488 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700489 }
Damien Neil46abb572018-09-07 12:45:37 -0700490 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
491 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
492 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700493 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
494 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
495 }
Damien Neil658051b2018-09-10 12:26:21 -0700496 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700497 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700498 }
Damien Neil993c04d2018-09-14 15:41:11 -0700499 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
500 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
501 }
Damien Neil658051b2018-09-10 12:26:21 -0700502
503 // Field name conflict resolution.
504 //
505 // We assume well-known method names that may be attached to a generated
506 // message type, as well as a 'Get*' method for each field. For each
507 // field in turn, we add _s to its name until there are no conflicts.
508 //
509 // Any change to the following set of method names is a potential
510 // incompatible API change because it may change generated field names.
511 //
512 // TODO: If we ever support a 'go_name' option to set the Go name of a
513 // field, we should consider dropping this entirely. The conflict
514 // resolution algorithm is subtle and surprising (changing the order
515 // in which fields appear in the .proto source file can change the
516 // names of fields in generated code), and does not adapt well to
517 // adding new per-field methods such as setters.
518 usedNames := map[string]bool{
519 "Reset": true,
520 "String": true,
521 "ProtoMessage": true,
522 "Marshal": true,
523 "Unmarshal": true,
524 "ExtensionRangeArray": true,
525 "ExtensionMap": true,
526 "Descriptor": true,
527 }
528 makeNameUnique := func(name string) string {
529 for usedNames[name] || usedNames["Get"+name] {
530 name += "_"
531 }
532 usedNames[name] = true
533 usedNames["Get"+name] = true
534 return name
535 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700536 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700537 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700538 field.GoName = makeNameUnique(field.GoName)
539 if field.OneofType != nil {
540 if !seenOneofs[field.OneofType.Desc.Index()] {
541 // If this is a field in a oneof that we haven't seen before,
542 // make the name for that oneof unique as well.
543 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
544 seenOneofs[field.OneofType.Desc.Index()] = true
545 }
546 }
Damien Neil658051b2018-09-10 12:26:21 -0700547 }
548
Damien Neil1fa78d82018-09-13 13:12:36 -0700549 return message
Damien Neil658051b2018-09-10 12:26:21 -0700550}
551
Damien Neil0bd5a382018-09-13 15:07:10 -0700552func (message *Message) init(gen *Plugin) error {
553 for _, child := range message.Messages {
554 if err := child.init(gen); err != nil {
555 return err
556 }
557 }
558 for _, field := range message.Fields {
559 if err := field.init(gen); err != nil {
560 return err
561 }
562 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700563 for _, oneof := range message.Oneofs {
564 oneof.init(gen, message)
565 }
Damien Neil993c04d2018-09-14 15:41:11 -0700566 for _, extension := range message.Extensions {
567 if err := extension.init(gen); err != nil {
568 return err
569 }
570 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700571 return nil
572}
573
Damien Neil658051b2018-09-10 12:26:21 -0700574// A Field describes a message field.
575type Field struct {
576 Desc protoreflect.FieldDescriptor
577
Damien Neil1fa78d82018-09-13 13:12:36 -0700578 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700579 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700580 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
581 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700582
Damien Neil993c04d2018-09-14 15:41:11 -0700583 ParentMessage *Message // message in which this field is defined; nil if top-level extension
584 ExtendedType *Message // extended message for extension fields; nil otherwise
585 MessageType *Message // type for message or group fields; nil otherwise
586 EnumType *Enum // type for enum fields; nil otherwise
587 OneofType *Oneof // containing oneof; nil if not part of a oneof
588 Path []int32 // location path of this field
Damien Neil658051b2018-09-10 12:26:21 -0700589}
590
Damien Neil1fa78d82018-09-13 13:12:36 -0700591func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil993c04d2018-09-14 15:41:11 -0700592 var path []int32
593 switch {
594 case desc.ExtendedType() != nil && message == nil:
595 path = []int32{fileExtensionField, int32(desc.Index())}
596 case desc.ExtendedType() != nil && message != nil:
597 path = pathAppend(message.Path, messageExtensionField, int32(desc.Index()))
598 default:
599 path = pathAppend(message.Path, messageFieldField, int32(desc.Index()))
600 }
Damien Neil658051b2018-09-10 12:26:21 -0700601 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700602 Desc: desc,
603 GoName: camelCase(string(desc.Name())),
604 ParentMessage: message,
605 Path: path,
Damien Neil658051b2018-09-10 12:26:21 -0700606 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700607 if desc.OneofType() != nil {
608 field.OneofType = message.Oneofs[desc.OneofType().Index()]
609 }
610 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700611}
612
Damien Neil993c04d2018-09-14 15:41:11 -0700613// Extension is an alias of Field for documentation.
614type Extension = Field
615
Damien Neil0bd5a382018-09-13 15:07:10 -0700616func (field *Field) init(gen *Plugin) error {
617 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700618 switch desc.Kind() {
619 case protoreflect.MessageKind, protoreflect.GroupKind:
620 mname := desc.MessageType().FullName()
621 message, ok := gen.messagesByName[mname]
622 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700623 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700624 }
625 field.MessageType = message
626 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700627 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700628 enum, ok := gen.enumsByName[ename]
629 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700630 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700631 }
632 field.EnumType = enum
633 }
Damien Neil993c04d2018-09-14 15:41:11 -0700634 if desc.ExtendedType() != nil {
635 mname := desc.ExtendedType().FullName()
636 message, ok := gen.messagesByName[mname]
637 if !ok {
638 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
639 }
640 field.ExtendedType = message
641 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700642 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700643}
644
Damien Neil1fa78d82018-09-13 13:12:36 -0700645// A Oneof describes a oneof field.
646type Oneof struct {
647 Desc protoreflect.OneofDescriptor
648
Damien Neil993c04d2018-09-14 15:41:11 -0700649 GoName string // Go field name of this oneof
650 ParentMessage *Message // message in which this oneof occurs
651 Fields []*Field // fields that are part of this oneof
652 Path []int32 // location path of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700653}
654
655func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
656 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700657 Desc: desc,
658 ParentMessage: message,
659 GoName: camelCase(string(desc.Name())),
660 Path: pathAppend(message.Path, messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700661 }
662}
663
664func (oneof *Oneof) init(gen *Plugin, parent *Message) {
665 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
666 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
667 }
668}
669
Damien Neil46abb572018-09-07 12:45:37 -0700670// An Enum describes an enum.
671type Enum struct {
672 Desc protoreflect.EnumDescriptor
673
674 GoIdent GoIdent // name of the generated Go type
675 Values []*EnumValue // enum values
676 Path []int32 // location path of this enum
677}
678
679func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
680 var path []int32
681 if parent != nil {
682 path = pathAppend(parent.Path, messageEnumField, int32(desc.Index()))
683 } else {
684 path = []int32{fileEnumField, int32(desc.Index())}
685 }
686 enum := &Enum{
687 Desc: desc,
688 GoIdent: newGoIdent(f, desc),
689 Path: path,
690 }
Damien Neil658051b2018-09-10 12:26:21 -0700691 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700692 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
693 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
694 }
695 return enum
696}
697
698// An EnumValue describes an enum value.
699type EnumValue struct {
700 Desc protoreflect.EnumValueDescriptor
701
702 GoIdent GoIdent // name of the generated Go type
703 Path []int32 // location path of this enum value
704}
705
706func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
707 // A top-level enum value's name is: EnumName_ValueName
708 // An enum value contained in a message is: MessageName_ValueName
709 //
710 // Enum value names are not camelcased.
711 parentIdent := enum.GoIdent
712 if message != nil {
713 parentIdent = message.GoIdent
714 }
715 name := parentIdent.GoName + "_" + string(desc.Name())
716 return &EnumValue{
717 Desc: desc,
718 GoIdent: GoIdent{
719 GoName: name,
720 GoImportPath: f.GoImportPath,
721 },
722 Path: pathAppend(enum.Path, enumValueField, int32(desc.Index())),
723 }
Damien Neil220c2022018-08-15 11:24:18 -0700724}
725
726// A GeneratedFile is a generated file.
727type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700728 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700729 filename string
730 goImportPath GoImportPath
731 buf bytes.Buffer
732 packageNames map[GoImportPath]GoPackageName
733 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700734 manualImports map[GoImportPath]bool
Damien Neil220c2022018-08-15 11:24:18 -0700735}
736
Damien Neild9016772018-08-23 14:39:30 -0700737// NewGeneratedFile creates a new generated file with the given filename
738// and import path.
739func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700740 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700741 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700742 filename: filename,
743 goImportPath: goImportPath,
744 packageNames: make(map[GoImportPath]GoPackageName),
745 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700746 manualImports: make(map[GoImportPath]bool),
Damien Neil220c2022018-08-15 11:24:18 -0700747 }
748 gen.genFiles = append(gen.genFiles, g)
749 return g
750}
751
Damien Neil2dc67182018-09-21 15:03:34 -0700752// A Service describes a service.
753type Service struct {
754 Desc protoreflect.ServiceDescriptor
755
756 GoName string
757 Path []int32 // location path of this service
758 Methods []*Method // service method definitions
759}
760
761func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
762 service := &Service{
763 Desc: desc,
764 GoName: camelCase(string(desc.Name())),
765 Path: []int32{fileServiceField, int32(desc.Index())},
766 }
767 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
768 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
769 }
770 return service
771}
772
773// A Method describes a method in a service.
774type Method struct {
775 Desc protoreflect.MethodDescriptor
776
777 GoName string
778 ParentService *Service
779 Path []int32 // location path of this method
780 InputType *Message
781 OutputType *Message
782}
783
784func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
785 method := &Method{
786 Desc: desc,
787 GoName: camelCase(string(desc.Name())),
788 ParentService: service,
789 Path: pathAppend(service.Path, serviceMethodField, int32(desc.Index())),
790 }
791 return method
792}
793
794func (method *Method) init(gen *Plugin) error {
795 desc := method.Desc
796
797 inName := desc.InputType().FullName()
798 in, ok := gen.messagesByName[inName]
799 if !ok {
800 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
801 }
802 method.InputType = in
803
804 outName := desc.OutputType().FullName()
805 out, ok := gen.messagesByName[outName]
806 if !ok {
807 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
808 }
809 method.OutputType = out
810
811 return nil
812}
813
Damien Neil220c2022018-08-15 11:24:18 -0700814// P prints a line to the generated output. It converts each parameter to a
815// string following the same rules as fmt.Print. It never inserts spaces
816// between parameters.
817//
818// TODO: .meta file annotations.
819func (g *GeneratedFile) P(v ...interface{}) {
820 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700821 switch x := x.(type) {
822 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700823 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700824 default:
825 fmt.Fprint(&g.buf, x)
826 }
Damien Neil220c2022018-08-15 11:24:18 -0700827 }
828 fmt.Fprintln(&g.buf)
829}
830
Damien Neil46abb572018-09-07 12:45:37 -0700831// QualifiedGoIdent returns the string to use for a Go identifier.
832//
833// If the identifier is from a different Go package than the generated file,
834// the returned name will be qualified (package.name) and an import statement
835// for the identifier's package will be included in the file.
836func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
837 if ident.GoImportPath == g.goImportPath {
838 return ident.GoName
839 }
840 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
841 return string(packageName) + "." + ident.GoName
842 }
843 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700844 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700845 packageName = orig + GoPackageName(strconv.Itoa(i))
846 }
847 g.packageNames[ident.GoImportPath] = packageName
848 g.usedPackageNames[packageName] = true
849 return string(packageName) + "." + ident.GoName
850}
851
Damien Neil2e0c3da2018-09-19 12:51:36 -0700852// Import ensures a package is imported by the generated file.
853//
854// Packages referenced by QualifiedGoIdent are automatically imported.
855// Explicitly importing a package with Import is generally only necessary
856// when the import will be blank (import _ "package").
857func (g *GeneratedFile) Import(importPath GoImportPath) {
858 g.manualImports[importPath] = true
859}
860
Damien Neil220c2022018-08-15 11:24:18 -0700861// Write implements io.Writer.
862func (g *GeneratedFile) Write(p []byte) (n int, err error) {
863 return g.buf.Write(p)
864}
865
866// Content returns the contents of the generated file.
Damien Neilc7d07d92018-08-22 13:46:02 -0700867func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700868 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700869 return g.buf.Bytes(), nil
870 }
871
872 // Reformat generated code.
873 original := g.buf.Bytes()
874 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700875 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700876 if err != nil {
877 // Print out the bad code with line numbers.
878 // This should never happen in practice, but it can while changing generated code
879 // so consider this a debugging aid.
880 var src bytes.Buffer
881 s := bufio.NewScanner(bytes.NewReader(original))
882 for line := 1; s.Scan(); line++ {
883 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
884 }
Damien Neild9016772018-08-23 14:39:30 -0700885 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700886 }
Damien Neild9016772018-08-23 14:39:30 -0700887
888 // Add imports.
889 var importPaths []string
890 for importPath := range g.packageNames {
891 importPaths = append(importPaths, string(importPath))
892 }
893 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700894 rewriteImport := func(importPath string) string {
895 if f := g.gen.opts.ImportRewriteFunc; f != nil {
896 return string(f(GoImportPath(importPath)))
897 }
898 return importPath
899 }
Damien Neild9016772018-08-23 14:39:30 -0700900 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700901 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700902 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700903 for importPath := range g.manualImports {
904 if _, ok := g.packageNames[importPath]; ok {
905 continue
906 }
Damien Neil329b75e2018-10-04 17:31:07 -0700907 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700908 }
Damien Neil1ec33152018-09-13 13:12:36 -0700909 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700910
Damien Neilc7d07d92018-08-22 13:46:02 -0700911 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700912 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700913 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700914 }
Damien Neild9016772018-08-23 14:39:30 -0700915 // TODO: Annotations.
Damien Neilc7d07d92018-08-22 13:46:02 -0700916 return out.Bytes(), nil
917
Damien Neil220c2022018-08-15 11:24:18 -0700918}
Damien Neil082ce922018-09-06 10:23:53 -0700919
920type pathType int
921
922const (
923 pathTypeImport pathType = iota
924 pathTypeSourceRelative
925)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700926
927// The SourceCodeInfo message describes the location of elements of a parsed
928// .proto file by way of a "path", which is a sequence of integers that
929// describe the route from a FileDescriptorProto to the relevant submessage.
930// The path alternates between a field number of a repeated field, and an index
931// into that repeated field. The constants below define the field numbers that
932// are used.
933//
934// See descriptor.proto for more information about this.
935const (
936 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -0700937 filePackageField = 2 // package
938 fileMessageField = 4 // message_type
939 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -0700940 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -0700941 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -0700942 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -0700943 messageFieldField = 2 // field
944 messageMessageField = 3 // nested_type
945 messageEnumField = 4 // enum_type
946 messageExtensionField = 6 // extension
947 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -0700948 // field numbers in EnumDescriptorProto
949 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -0700950 // field numbers in ServiceDescriptorProto
951 serviceMethodField = 2 // method
952 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -0700953)
954
955// pathAppend appends elements to a location path.
956// It does not alias the original path.
957func pathAppend(path []int32, a ...int32) []int32 {
958 var n []int32
959 n = append(n, path...)
960 n = append(n, a...)
961 return n
962}