blob: 29a62890b871fbe0190b6b79b323ab549594c93f [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 Neil658051b2018-09-10 12:26:21 -0700395 message, err := newMessage(gen, f, nil, mdescs.Get(i))
396 if err != nil {
397 return nil, err
398 }
399 f.Messages = append(f.Messages, message)
Damien Neilc7d07d92018-08-22 13:46:02 -0700400 }
Damien Neil46abb572018-09-07 12:45:37 -0700401 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
402 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
403 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700404 for _, message := range f.Messages {
405 message.init(gen)
406 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700407 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700408}
409
Damien Neil082ce922018-09-06 10:23:53 -0700410// goPackageOption interprets a file's go_package option.
411// If there is no go_package, it returns ("", "").
412// If there's a simple name, it returns (pkg, "").
413// If the option implies an import path, it returns (pkg, impPath).
414func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
415 opt := d.GetOptions().GetGoPackage()
416 if opt == "" {
417 return "", ""
418 }
419 // A semicolon-delimited suffix delimits the import path and package name.
420 if i := strings.Index(opt, ";"); i >= 0 {
421 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
422 }
423 // The presence of a slash implies there's an import path.
424 if i := strings.LastIndex(opt, "/"); i >= 0 {
425 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
426 }
427 return cleanPackageName(opt), ""
428}
429
Damien Neilc7d07d92018-08-22 13:46:02 -0700430// A Message describes a message.
431type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700432 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700433
434 GoIdent GoIdent // name of the generated Go type
Damien Neil658051b2018-09-10 12:26:21 -0700435 Fields []*Field // message field declarations
Damien Neilc7d07d92018-08-22 13:46:02 -0700436 Messages []*Message // nested message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700437 Enums []*Enum // nested enum declarations
Damien Neilcab8dfe2018-09-06 14:51:28 -0700438 Path []int32 // location path of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700439}
440
Damien Neil658051b2018-09-10 12:26:21 -0700441func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) (*Message, error) {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700442 var path []int32
443 if parent != nil {
444 path = pathAppend(parent.Path, messageMessageField, int32(desc.Index()))
445 } else {
446 path = []int32{fileMessageField, int32(desc.Index())}
447 }
Damien Neil46abb572018-09-07 12:45:37 -0700448 message := &Message{
Damien Neilabc6fc12018-08-23 14:39:30 -0700449 Desc: desc,
450 GoIdent: newGoIdent(f, desc),
Damien Neilcab8dfe2018-09-06 14:51:28 -0700451 Path: path,
Damien Neilc7d07d92018-08-22 13:46:02 -0700452 }
Damien Neil658051b2018-09-10 12:26:21 -0700453 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700454 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil658051b2018-09-10 12:26:21 -0700455 m, err := newMessage(gen, f, message, mdescs.Get(i))
456 if err != nil {
457 return nil, err
458 }
459 message.Messages = append(message.Messages, m)
Damien Neilc7d07d92018-08-22 13:46:02 -0700460 }
Damien Neil46abb572018-09-07 12:45:37 -0700461 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
462 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
463 }
Damien Neil658051b2018-09-10 12:26:21 -0700464 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
465 field, err := newField(gen, f, message, fdescs.Get(i))
466 if err != nil {
467 return nil, err
468 }
469 message.Fields = append(message.Fields, field)
470 }
471
472 // Field name conflict resolution.
473 //
474 // We assume well-known method names that may be attached to a generated
475 // message type, as well as a 'Get*' method for each field. For each
476 // field in turn, we add _s to its name until there are no conflicts.
477 //
478 // Any change to the following set of method names is a potential
479 // incompatible API change because it may change generated field names.
480 //
481 // TODO: If we ever support a 'go_name' option to set the Go name of a
482 // field, we should consider dropping this entirely. The conflict
483 // resolution algorithm is subtle and surprising (changing the order
484 // in which fields appear in the .proto source file can change the
485 // names of fields in generated code), and does not adapt well to
486 // adding new per-field methods such as setters.
487 usedNames := map[string]bool{
488 "Reset": true,
489 "String": true,
490 "ProtoMessage": true,
491 "Marshal": true,
492 "Unmarshal": true,
493 "ExtensionRangeArray": true,
494 "ExtensionMap": true,
495 "Descriptor": true,
496 }
497 makeNameUnique := func(name string) string {
498 for usedNames[name] || usedNames["Get"+name] {
499 name += "_"
500 }
501 usedNames[name] = true
502 usedNames["Get"+name] = true
503 return name
504 }
505 for _, field := range message.Fields {
506 field.GoIdent.GoName = makeNameUnique(field.GoIdent.GoName)
507 // TODO: If this is the first field of a oneof that we haven't seen
508 // before, generate the name for the oneof.
509 }
510
511 return message, nil
512}
513
Damien Neil0bd5a382018-09-13 15:07:10 -0700514func (message *Message) init(gen *Plugin) error {
515 for _, child := range message.Messages {
516 if err := child.init(gen); err != nil {
517 return err
518 }
519 }
520 for _, field := range message.Fields {
521 if err := field.init(gen); err != nil {
522 return err
523 }
524 }
525 return nil
526}
527
Damien Neil658051b2018-09-10 12:26:21 -0700528// A Field describes a message field.
529type Field struct {
530 Desc protoreflect.FieldDescriptor
531
532 // GoIdent is the base name of this field's Go fields and methods.
533 // For code generated by protoc-gen-go, this means a field named
534 // '{{GoIdent}}' and a getter method named 'Get{{GoIdent}}'.
535 GoIdent GoIdent
536
537 MessageType *Message // type for message or group fields; nil otherwise
538 EnumType *Enum // type for enum fields; nil otherwise
539 Path []int32 // location path of this field
540}
541
542func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) (*Field, error) {
543 field := &Field{
544 Desc: desc,
545 GoIdent: GoIdent{
546 GoName: camelCase(string(desc.Name())),
547 GoImportPath: f.GoImportPath,
548 },
549 Path: pathAppend(message.Path, messageFieldField, int32(desc.Index())),
550 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700551 return field, nil
552}
553
554func (field *Field) init(gen *Plugin) error {
555 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700556 switch desc.Kind() {
557 case protoreflect.MessageKind, protoreflect.GroupKind:
558 mname := desc.MessageType().FullName()
559 message, ok := gen.messagesByName[mname]
560 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700561 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700562 }
563 field.MessageType = message
564 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700565 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700566 enum, ok := gen.enumsByName[ename]
567 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700568 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700569 }
570 field.EnumType = enum
571 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700572 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700573}
574
575// An Enum describes an enum.
576type Enum struct {
577 Desc protoreflect.EnumDescriptor
578
579 GoIdent GoIdent // name of the generated Go type
580 Values []*EnumValue // enum values
581 Path []int32 // location path of this enum
582}
583
584func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
585 var path []int32
586 if parent != nil {
587 path = pathAppend(parent.Path, messageEnumField, int32(desc.Index()))
588 } else {
589 path = []int32{fileEnumField, int32(desc.Index())}
590 }
591 enum := &Enum{
592 Desc: desc,
593 GoIdent: newGoIdent(f, desc),
594 Path: path,
595 }
Damien Neil658051b2018-09-10 12:26:21 -0700596 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700597 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
598 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
599 }
600 return enum
601}
602
603// An EnumValue describes an enum value.
604type EnumValue struct {
605 Desc protoreflect.EnumValueDescriptor
606
607 GoIdent GoIdent // name of the generated Go type
608 Path []int32 // location path of this enum value
609}
610
611func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
612 // A top-level enum value's name is: EnumName_ValueName
613 // An enum value contained in a message is: MessageName_ValueName
614 //
615 // Enum value names are not camelcased.
616 parentIdent := enum.GoIdent
617 if message != nil {
618 parentIdent = message.GoIdent
619 }
620 name := parentIdent.GoName + "_" + string(desc.Name())
621 return &EnumValue{
622 Desc: desc,
623 GoIdent: GoIdent{
624 GoName: name,
625 GoImportPath: f.GoImportPath,
626 },
627 Path: pathAppend(enum.Path, enumValueField, int32(desc.Index())),
628 }
Damien Neil220c2022018-08-15 11:24:18 -0700629}
630
631// A GeneratedFile is a generated file.
632type GeneratedFile struct {
Damien Neild9016772018-08-23 14:39:30 -0700633 filename string
634 goImportPath GoImportPath
635 buf bytes.Buffer
636 packageNames map[GoImportPath]GoPackageName
637 usedPackageNames map[GoPackageName]bool
Damien Neil220c2022018-08-15 11:24:18 -0700638}
639
Damien Neild9016772018-08-23 14:39:30 -0700640// NewGeneratedFile creates a new generated file with the given filename
641// and import path.
642func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700643 g := &GeneratedFile{
Damien Neild9016772018-08-23 14:39:30 -0700644 filename: filename,
645 goImportPath: goImportPath,
646 packageNames: make(map[GoImportPath]GoPackageName),
647 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil220c2022018-08-15 11:24:18 -0700648 }
649 gen.genFiles = append(gen.genFiles, g)
650 return g
651}
652
653// P prints a line to the generated output. It converts each parameter to a
654// string following the same rules as fmt.Print. It never inserts spaces
655// between parameters.
656//
657// TODO: .meta file annotations.
658func (g *GeneratedFile) P(v ...interface{}) {
659 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700660 switch x := x.(type) {
661 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700662 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700663 default:
664 fmt.Fprint(&g.buf, x)
665 }
Damien Neil220c2022018-08-15 11:24:18 -0700666 }
667 fmt.Fprintln(&g.buf)
668}
669
Damien Neil46abb572018-09-07 12:45:37 -0700670// QualifiedGoIdent returns the string to use for a Go identifier.
671//
672// If the identifier is from a different Go package than the generated file,
673// the returned name will be qualified (package.name) and an import statement
674// for the identifier's package will be included in the file.
675func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
676 if ident.GoImportPath == g.goImportPath {
677 return ident.GoName
678 }
679 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
680 return string(packageName) + "." + ident.GoName
681 }
682 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
683 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
684 packageName = orig + GoPackageName(strconv.Itoa(i))
685 }
686 g.packageNames[ident.GoImportPath] = packageName
687 g.usedPackageNames[packageName] = true
688 return string(packageName) + "." + ident.GoName
689}
690
Damien Neil220c2022018-08-15 11:24:18 -0700691// Write implements io.Writer.
692func (g *GeneratedFile) Write(p []byte) (n int, err error) {
693 return g.buf.Write(p)
694}
695
696// Content returns the contents of the generated file.
Damien Neilc7d07d92018-08-22 13:46:02 -0700697func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700698 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700699 return g.buf.Bytes(), nil
700 }
701
702 // Reformat generated code.
703 original := g.buf.Bytes()
704 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700705 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700706 if err != nil {
707 // Print out the bad code with line numbers.
708 // This should never happen in practice, but it can while changing generated code
709 // so consider this a debugging aid.
710 var src bytes.Buffer
711 s := bufio.NewScanner(bytes.NewReader(original))
712 for line := 1; s.Scan(); line++ {
713 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
714 }
Damien Neild9016772018-08-23 14:39:30 -0700715 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700716 }
Damien Neild9016772018-08-23 14:39:30 -0700717
718 // Add imports.
719 var importPaths []string
720 for importPath := range g.packageNames {
721 importPaths = append(importPaths, string(importPath))
722 }
723 sort.Strings(importPaths)
724 for _, importPath := range importPaths {
Damien Neil1ec33152018-09-13 13:12:36 -0700725 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), importPath)
Damien Neild9016772018-08-23 14:39:30 -0700726 }
Damien Neil1ec33152018-09-13 13:12:36 -0700727 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700728
Damien Neilc7d07d92018-08-22 13:46:02 -0700729 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700730 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700731 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700732 }
Damien Neild9016772018-08-23 14:39:30 -0700733 // TODO: Annotations.
Damien Neilc7d07d92018-08-22 13:46:02 -0700734 return out.Bytes(), nil
735
Damien Neil220c2022018-08-15 11:24:18 -0700736}
Damien Neil082ce922018-09-06 10:23:53 -0700737
738type pathType int
739
740const (
741 pathTypeImport pathType = iota
742 pathTypeSourceRelative
743)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700744
745// The SourceCodeInfo message describes the location of elements of a parsed
746// .proto file by way of a "path", which is a sequence of integers that
747// describe the route from a FileDescriptorProto to the relevant submessage.
748// The path alternates between a field number of a repeated field, and an index
749// into that repeated field. The constants below define the field numbers that
750// are used.
751//
752// See descriptor.proto for more information about this.
753const (
754 // field numbers in FileDescriptorProto
755 filePackageField = 2 // package
756 fileMessageField = 4 // message_type
Damien Neil46abb572018-09-07 12:45:37 -0700757 fileEnumField = 5 // enum_type
Damien Neilcab8dfe2018-09-06 14:51:28 -0700758 // field numbers in DescriptorProto
759 messageFieldField = 2 // field
760 messageMessageField = 3 // nested_type
761 messageEnumField = 4 // enum_type
762 messageOneofField = 8 // oneof_decl
763 // field numbers in EnumDescriptorProto
764 enumValueField = 2 // value
765)
766
767// pathAppend appends elements to a location path.
768// It does not alias the original path.
769func pathAppend(path []int32, a ...int32) []int32 {
770 var n []int32
771 n = append(n, path...)
772 n = append(n, a...)
773 return n
774}