blob: a61baa0d91da2aa837f9417bf117bc5c77126ce9 [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"
Damien Neilba1159f2018-10-17 12:53:18 -070016 "encoding/binary"
Damien Neil220c2022018-08-15 11:24:18 -070017 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070018 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070019 "go/parser"
20 "go/printer"
21 "go/token"
Joe Tsai124c8122019-01-14 11:48:43 -080022 "go/types"
Damien Neil220c2022018-08-15 11:24:18 -070023 "io/ioutil"
24 "os"
Damien Neil082ce922018-09-06 10:23:53 -070025 "path"
Damien Neil220c2022018-08-15 11:24:18 -070026 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070027 "sort"
28 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070029 "strings"
30
31 "github.com/golang/protobuf/proto"
Joe Tsai1af1de02019-03-01 16:12:32 -080032 "github.com/golang/protobuf/v2/internal/descfield"
Joe Tsai009e0672018-11-27 18:45:07 -080033 "github.com/golang/protobuf/v2/internal/scalar"
Joe Tsaie1f8d502018-11-26 18:55:29 -080034 "github.com/golang/protobuf/v2/reflect/protodesc"
Joe Tsai01ab2962018-09-21 17:44:00 -070035 "github.com/golang/protobuf/v2/reflect/protoreflect"
36 "github.com/golang/protobuf/v2/reflect/protoregistry"
Damien Neild9016772018-08-23 14:39:30 -070037 "golang.org/x/tools/go/ast/astutil"
Joe Tsaie1f8d502018-11-26 18:55:29 -080038
39 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
40 pluginpb "github.com/golang/protobuf/v2/types/plugin"
Damien Neil220c2022018-08-15 11:24:18 -070041)
42
43// Run executes a function as a protoc plugin.
44//
45// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
46// function, and writes a CodeGeneratorResponse message to os.Stdout.
47//
48// If a failure occurs while reading or writing, Run prints an error to
49// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070050//
51// Passing a nil options is equivalent to passing a zero-valued one.
52func Run(opts *Options, f func(*Plugin) error) {
53 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070054 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
55 os.Exit(1)
56 }
57}
58
Damien Neil3cf6e622018-09-11 13:53:14 -070059func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070060 if len(os.Args) > 1 {
61 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
62 }
Damien Neil220c2022018-08-15 11:24:18 -070063 in, err := ioutil.ReadAll(os.Stdin)
64 if err != nil {
65 return err
66 }
67 req := &pluginpb.CodeGeneratorRequest{}
68 if err := proto.Unmarshal(in, req); err != nil {
69 return err
70 }
Damien Neil3cf6e622018-09-11 13:53:14 -070071 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070072 if err != nil {
73 return err
74 }
75 if err := f(gen); err != nil {
76 // Errors from the plugin function are reported by setting the
77 // error field in the CodeGeneratorResponse.
78 //
79 // In contrast, errors that indicate a problem in protoc
80 // itself (unparsable input, I/O errors, etc.) are reported
81 // to stderr.
82 gen.Error(err)
83 }
84 resp := gen.Response()
85 out, err := proto.Marshal(resp)
86 if err != nil {
87 return err
88 }
89 if _, err := os.Stdout.Write(out); err != nil {
90 return err
91 }
92 return nil
93}
94
95// A Plugin is a protoc plugin invocation.
96type Plugin struct {
97 // Request is the CodeGeneratorRequest provided by protoc.
98 Request *pluginpb.CodeGeneratorRequest
99
100 // Files is the set of files to generate and everything they import.
101 // Files appear in topological order, so each file appears before any
102 // file that imports it.
103 Files []*File
104 filesByName map[string]*File
105
Damien Neil658051b2018-09-10 12:26:21 -0700106 fileReg *protoregistry.Files
107 messagesByName map[protoreflect.FullName]*Message
108 enumsByName map[protoreflect.FullName]*Enum
Damien Neil162c1272018-10-04 12:42:37 -0700109 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700110 pathType pathType
111 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700112 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700113 err error
Damien Neil220c2022018-08-15 11:24:18 -0700114}
115
Damien Neil3cf6e622018-09-11 13:53:14 -0700116// Options are optional parameters to New.
117type Options struct {
118 // If ParamFunc is non-nil, it will be called with each unknown
119 // generator parameter.
120 //
121 // Plugins for protoc can accept parameters from the command line,
122 // passed in the --<lang>_out protoc, separated from the output
123 // directory with a colon; e.g.,
124 //
125 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
126 //
127 // Parameters passed in this fashion as a comma-separated list of
128 // key=value pairs will be passed to the ParamFunc.
129 //
130 // The (flag.FlagSet).Set method matches this function signature,
131 // so parameters can be converted into flags as in the following:
132 //
133 // var flags flag.FlagSet
134 // value := flags.Bool("param", false, "")
135 // opts := &protogen.Options{
136 // ParamFunc: flags.Set,
137 // }
138 // protogen.Run(opts, func(p *protogen.Plugin) error {
139 // if *value { ... }
140 // })
141 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700142
143 // ImportRewriteFunc is called with the import path of each package
144 // imported by a generated file. It returns the import path to use
145 // for this package.
146 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700147}
148
Damien Neil220c2022018-08-15 11:24:18 -0700149// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700150//
151// Passing a nil Options is equivalent to passing a zero-valued one.
152func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
153 if opts == nil {
154 opts = &Options{}
155 }
Damien Neil220c2022018-08-15 11:24:18 -0700156 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700157 Request: req,
158 filesByName: make(map[string]*File),
159 fileReg: protoregistry.NewFiles(),
160 messagesByName: make(map[protoreflect.FullName]*Message),
161 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700162 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700163 }
164
Damien Neil082ce922018-09-06 10:23:53 -0700165 packageNames := make(map[string]GoPackageName) // filename -> package name
166 importPaths := make(map[string]GoImportPath) // filename -> import path
167 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700168 for _, param := range strings.Split(req.GetParameter(), ",") {
169 var value string
170 if i := strings.Index(param, "="); i >= 0 {
171 value = param[i+1:]
172 param = param[0:i]
173 }
174 switch param {
175 case "":
176 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700177 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700178 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700179 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700180 switch value {
181 case "import":
182 gen.pathType = pathTypeImport
183 case "source_relative":
184 gen.pathType = pathTypeSourceRelative
185 default:
186 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
187 }
Damien Neil220c2022018-08-15 11:24:18 -0700188 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700189 switch value {
190 case "true", "":
191 gen.annotateCode = true
192 case "false":
193 default:
194 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
195 }
Damien Neil220c2022018-08-15 11:24:18 -0700196 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700197 if param[0] == 'M' {
198 importPaths[param[1:]] = GoImportPath(value)
199 continue
Damien Neil220c2022018-08-15 11:24:18 -0700200 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700201 if opts.ParamFunc != nil {
202 if err := opts.ParamFunc(param, value); err != nil {
203 return nil, err
204 }
205 }
Damien Neil082ce922018-09-06 10:23:53 -0700206 }
207 }
208
209 // Figure out the import path and package name for each file.
210 //
211 // The rules here are complicated and have grown organically over time.
212 // Interactions between different ways of specifying package information
213 // may be surprising.
214 //
215 // The recommended approach is to include a go_package option in every
216 // .proto source file specifying the full import path of the Go package
217 // associated with this file.
218 //
219 // option go_package = "github.com/golang/protobuf/ptypes/any";
220 //
221 // Build systems which want to exert full control over import paths may
222 // specify M<filename>=<import_path> flags.
223 //
224 // Other approaches are not recommend.
225 generatedFileNames := make(map[string]bool)
226 for _, name := range gen.Request.FileToGenerate {
227 generatedFileNames[name] = true
228 }
229 // We need to determine the import paths before the package names,
230 // because the Go package name for a file is sometimes derived from
231 // different file in the same package.
232 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
233 for _, fdesc := range gen.Request.ProtoFile {
234 filename := fdesc.GetName()
235 packageName, importPath := goPackageOption(fdesc)
236 switch {
237 case importPaths[filename] != "":
238 // Command line: M=foo.proto=quux/bar
239 //
240 // Explicit mapping of source file to import path.
241 case generatedFileNames[filename] && packageImportPath != "":
242 // Command line: import_path=quux/bar
243 //
244 // The import_path flag sets the import path for every file that
245 // we generate code for.
246 importPaths[filename] = packageImportPath
247 case importPath != "":
248 // Source file: option go_package = "quux/bar";
249 //
250 // The go_package option sets the import path. Most users should use this.
251 importPaths[filename] = importPath
252 default:
253 // Source filename.
254 //
255 // Last resort when nothing else is available.
256 importPaths[filename] = GoImportPath(path.Dir(filename))
257 }
258 if packageName != "" {
259 packageNameForImportPath[importPaths[filename]] = packageName
260 }
261 }
262 for _, fdesc := range gen.Request.ProtoFile {
263 filename := fdesc.GetName()
264 packageName, _ := goPackageOption(fdesc)
265 defaultPackageName := packageNameForImportPath[importPaths[filename]]
266 switch {
267 case packageName != "":
268 // Source file: option go_package = "quux/bar";
269 packageNames[filename] = packageName
270 case defaultPackageName != "":
271 // A go_package option in another file in the same package.
272 //
273 // This is a poor choice in general, since every source file should
274 // contain a go_package option. Supported mainly for historical
275 // compatibility.
276 packageNames[filename] = defaultPackageName
277 case generatedFileNames[filename] && packageImportPath != "":
278 // Command line: import_path=quux/bar
279 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
280 case fdesc.GetPackage() != "":
281 // Source file: package quux.bar;
282 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
283 default:
284 // Source filename.
285 packageNames[filename] = cleanPackageName(baseName(filename))
286 }
287 }
288
289 // Consistency check: Every file with the same Go import path should have
290 // the same Go package name.
291 packageFiles := make(map[GoImportPath][]string)
292 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700293 if _, ok := packageNames[filename]; !ok {
294 // Skip files mentioned in a M<file>=<import_path> parameter
295 // but which do not appear in the CodeGeneratorRequest.
296 continue
297 }
Damien Neil082ce922018-09-06 10:23:53 -0700298 packageFiles[importPath] = append(packageFiles[importPath], filename)
299 }
300 for importPath, filenames := range packageFiles {
301 for i := 1; i < len(filenames); i++ {
302 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
303 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
304 importPath, a, filenames[0], b, filenames[i])
305 }
Damien Neil220c2022018-08-15 11:24:18 -0700306 }
307 }
308
309 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700310 filename := fdesc.GetName()
311 if gen.filesByName[filename] != nil {
312 return nil, fmt.Errorf("duplicate file name: %q", filename)
313 }
314 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700315 if err != nil {
316 return nil, err
317 }
Damien Neil220c2022018-08-15 11:24:18 -0700318 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700319 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700320 }
Damien Neil082ce922018-09-06 10:23:53 -0700321 for _, filename := range gen.Request.FileToGenerate {
322 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700323 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700324 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700325 }
326 f.Generate = true
327 }
328 return gen, nil
329}
330
331// Error records an error in code generation. The generator will report the
332// error back to protoc and will not produce output.
333func (gen *Plugin) Error(err error) {
334 if gen.err == nil {
335 gen.err = err
336 }
337}
338
339// Response returns the generator output.
340func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
341 resp := &pluginpb.CodeGeneratorResponse{}
342 if gen.err != nil {
Joe Tsai009e0672018-11-27 18:45:07 -0800343 resp.Error = scalar.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700344 return resp
345 }
Damien Neil162c1272018-10-04 12:42:37 -0700346 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800347 if g.skip {
348 continue
349 }
350 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700351 if err != nil {
352 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800353 Error: scalar.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700354 }
355 }
Damien Neil220c2022018-08-15 11:24:18 -0700356 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800357 Name: scalar.String(g.filename),
358 Content: scalar.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700359 })
Damien Neil162c1272018-10-04 12:42:37 -0700360 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
361 meta, err := g.metaFile(content)
362 if err != nil {
363 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800364 Error: scalar.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700365 }
366 }
367 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800368 Name: scalar.String(g.filename + ".meta"),
369 Content: scalar.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700370 })
371 }
Damien Neil220c2022018-08-15 11:24:18 -0700372 }
373 return resp
374}
375
376// FileByName returns the file with the given name.
377func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
378 f, ok = gen.filesByName[name]
379 return f, ok
380}
381
Damien Neilc7d07d92018-08-22 13:46:02 -0700382// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700383type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700384 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800385 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700386
Joe Tsaib6405bd2018-11-15 14:44:37 -0800387 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
388 GoPackageName GoPackageName // name of this file's Go package
389 GoImportPath GoImportPath // import path of this file's Go package
390 Messages []*Message // top-level message declarations
391 Enums []*Enum // top-level enum declarations
392 Extensions []*Extension // top-level extension declarations
393 Services []*Service // top-level service declarations
394 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700395
396 // GeneratedFilenamePrefix is used to construct filenames for generated
397 // files associated with this source file.
398 //
399 // For example, the source file "dir/foo.proto" might have a filename prefix
400 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
401 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700402
Joe Tsaie1f8d502018-11-26 18:55:29 -0800403 sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700404}
405
Joe Tsaie1f8d502018-11-26 18:55:29 -0800406func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
407 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700408 if err != nil {
409 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
410 }
411 if err := gen.fileReg.Register(desc); err != nil {
412 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
413 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700414 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700415 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700416 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700417 GoPackageName: packageName,
418 GoImportPath: importPath,
Joe Tsaie1f8d502018-11-26 18:55:29 -0800419 sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700420 }
Damien Neil082ce922018-09-06 10:23:53 -0700421
422 // Determine the prefix for generated Go files.
423 prefix := p.GetName()
424 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
425 prefix = prefix[:len(prefix)-len(ext)]
426 }
427 if gen.pathType == pathTypeImport {
428 // If paths=import (the default) and the file contains a go_package option
429 // with a full import path, the output filename is derived from the Go import
430 // path.
431 //
432 // Pass the paths=source_relative flag to always derive the output filename
433 // from the input filename instead.
434 if _, importPath := goPackageOption(p); importPath != "" {
435 prefix = path.Join(string(importPath), path.Base(prefix))
436 }
437 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800438 f.GoDescriptorIdent = GoIdent{
Joe Tsai40692112019-02-27 20:25:51 -0800439 GoName: "File_" + cleanGoName(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800440 GoImportPath: f.GoImportPath,
441 }
Damien Neil082ce922018-09-06 10:23:53 -0700442 f.GeneratedFilenamePrefix = prefix
443
Damien Neilba1159f2018-10-17 12:53:18 -0700444 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
445 key := newPathKey(loc.Path)
446 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
447 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700448 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700449 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700450 }
Damien Neil46abb572018-09-07 12:45:37 -0700451 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
452 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
453 }
Damien Neil993c04d2018-09-14 15:41:11 -0700454 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
455 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
456 }
Damien Neil2dc67182018-09-21 15:03:34 -0700457 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
458 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
459 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700460 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700461 if err := message.init(gen); err != nil {
462 return nil, err
463 }
464 }
465 for _, extension := range f.Extensions {
466 if err := extension.init(gen); err != nil {
467 return nil, err
468 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700469 }
Damien Neil2dc67182018-09-21 15:03:34 -0700470 for _, service := range f.Services {
471 for _, method := range service.Methods {
472 if err := method.init(gen); err != nil {
473 return nil, err
474 }
475 }
476 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700477 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700478}
479
Damien Neil162c1272018-10-04 12:42:37 -0700480func (f *File) location(path ...int32) Location {
481 return Location{
482 SourceFile: f.Desc.Path(),
483 Path: path,
484 }
485}
486
Damien Neil082ce922018-09-06 10:23:53 -0700487// goPackageOption interprets a file's go_package option.
488// If there is no go_package, it returns ("", "").
489// If there's a simple name, it returns (pkg, "").
490// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800491func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700492 opt := d.GetOptions().GetGoPackage()
493 if opt == "" {
494 return "", ""
495 }
496 // A semicolon-delimited suffix delimits the import path and package name.
497 if i := strings.Index(opt, ";"); i >= 0 {
498 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
499 }
500 // The presence of a slash implies there's an import path.
501 if i := strings.LastIndex(opt, "/"); i >= 0 {
502 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
503 }
504 return cleanPackageName(opt), ""
505}
506
Damien Neilc7d07d92018-08-22 13:46:02 -0700507// A Message describes a message.
508type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700509 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700510
Damien Neil993c04d2018-09-14 15:41:11 -0700511 GoIdent GoIdent // name of the generated Go type
512 Fields []*Field // message field declarations
513 Oneofs []*Oneof // oneof declarations
514 Messages []*Message // nested message declarations
515 Enums []*Enum // nested enum declarations
516 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700517 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700518}
519
Damien Neil1fa78d82018-09-13 13:12:36 -0700520func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700521 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700522 if parent != nil {
Joe Tsai1af1de02019-03-01 16:12:32 -0800523 loc = parent.Location.appendPath(descfield.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700524 } else {
Joe Tsai1af1de02019-03-01 16:12:32 -0800525 loc = f.location(descfield.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700526 }
Damien Neil46abb572018-09-07 12:45:37 -0700527 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700528 Desc: desc,
529 GoIdent: newGoIdent(f, desc),
530 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700531 }
Damien Neil658051b2018-09-10 12:26:21 -0700532 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700533 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700534 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700535 }
Damien Neil46abb572018-09-07 12:45:37 -0700536 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
537 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
538 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700539 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
540 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
541 }
Damien Neil658051b2018-09-10 12:26:21 -0700542 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700543 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700544 }
Damien Neil993c04d2018-09-14 15:41:11 -0700545 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
546 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
547 }
Damien Neil658051b2018-09-10 12:26:21 -0700548
549 // Field name conflict resolution.
550 //
551 // We assume well-known method names that may be attached to a generated
552 // message type, as well as a 'Get*' method for each field. For each
553 // field in turn, we add _s to its name until there are no conflicts.
554 //
555 // Any change to the following set of method names is a potential
556 // incompatible API change because it may change generated field names.
557 //
558 // TODO: If we ever support a 'go_name' option to set the Go name of a
559 // field, we should consider dropping this entirely. The conflict
560 // resolution algorithm is subtle and surprising (changing the order
561 // in which fields appear in the .proto source file can change the
562 // names of fields in generated code), and does not adapt well to
563 // adding new per-field methods such as setters.
564 usedNames := map[string]bool{
565 "Reset": true,
566 "String": true,
567 "ProtoMessage": true,
568 "Marshal": true,
569 "Unmarshal": true,
570 "ExtensionRangeArray": true,
571 "ExtensionMap": true,
572 "Descriptor": true,
573 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800574 makeNameUnique := func(name string, hasGetter bool) string {
575 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700576 name += "_"
577 }
578 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800579 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700580 return name
581 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700583 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800584 field.GoName = makeNameUnique(field.GoName, true)
Damien Neil1fa78d82018-09-13 13:12:36 -0700585 if field.OneofType != nil {
586 if !seenOneofs[field.OneofType.Desc.Index()] {
587 // If this is a field in a oneof that we haven't seen before,
588 // make the name for that oneof unique as well.
Joe Tsaid6966a42019-01-08 10:59:34 -0800589 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName, false)
Damien Neil1fa78d82018-09-13 13:12:36 -0700590 seenOneofs[field.OneofType.Desc.Index()] = true
591 }
592 }
Damien Neil658051b2018-09-10 12:26:21 -0700593 }
594
Damien Neil1fa78d82018-09-13 13:12:36 -0700595 return message
Damien Neil658051b2018-09-10 12:26:21 -0700596}
597
Damien Neil0bd5a382018-09-13 15:07:10 -0700598func (message *Message) init(gen *Plugin) error {
599 for _, child := range message.Messages {
600 if err := child.init(gen); err != nil {
601 return err
602 }
603 }
604 for _, field := range message.Fields {
605 if err := field.init(gen); err != nil {
606 return err
607 }
608 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700609 for _, oneof := range message.Oneofs {
610 oneof.init(gen, message)
611 }
Damien Neil993c04d2018-09-14 15:41:11 -0700612 for _, extension := range message.Extensions {
613 if err := extension.init(gen); err != nil {
614 return err
615 }
616 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700617 return nil
618}
619
Damien Neil658051b2018-09-10 12:26:21 -0700620// A Field describes a message field.
621type Field struct {
622 Desc protoreflect.FieldDescriptor
623
Damien Neil1fa78d82018-09-13 13:12:36 -0700624 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700625 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700626 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
627 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700628
Damien Neil993c04d2018-09-14 15:41:11 -0700629 ParentMessage *Message // message in which this field is defined; nil if top-level extension
630 ExtendedType *Message // extended message for extension fields; nil otherwise
631 MessageType *Message // type for message or group fields; nil otherwise
632 EnumType *Enum // type for enum fields; nil otherwise
633 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700634 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700635}
636
Damien Neil1fa78d82018-09-13 13:12:36 -0700637func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700638 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700639 switch {
640 case desc.ExtendedType() != nil && message == nil:
Joe Tsai1af1de02019-03-01 16:12:32 -0800641 loc = f.location(descfield.FileDescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700642 case desc.ExtendedType() != nil && message != nil:
Joe Tsai1af1de02019-03-01 16:12:32 -0800643 loc = message.Location.appendPath(descfield.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700644 default:
Joe Tsai1af1de02019-03-01 16:12:32 -0800645 loc = message.Location.appendPath(descfield.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700646 }
Damien Neil658051b2018-09-10 12:26:21 -0700647 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700648 Desc: desc,
649 GoName: camelCase(string(desc.Name())),
650 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700651 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700652 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700653 if desc.OneofType() != nil {
654 field.OneofType = message.Oneofs[desc.OneofType().Index()]
655 }
656 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700657}
658
Damien Neil993c04d2018-09-14 15:41:11 -0700659// Extension is an alias of Field for documentation.
660type Extension = Field
661
Damien Neil0bd5a382018-09-13 15:07:10 -0700662func (field *Field) init(gen *Plugin) error {
663 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700664 switch desc.Kind() {
665 case protoreflect.MessageKind, protoreflect.GroupKind:
666 mname := desc.MessageType().FullName()
667 message, ok := gen.messagesByName[mname]
668 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700669 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700670 }
671 field.MessageType = message
672 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700673 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700674 enum, ok := gen.enumsByName[ename]
675 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700676 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700677 }
678 field.EnumType = enum
679 }
Damien Neil993c04d2018-09-14 15:41:11 -0700680 if desc.ExtendedType() != nil {
681 mname := desc.ExtendedType().FullName()
682 message, ok := gen.messagesByName[mname]
683 if !ok {
684 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
685 }
686 field.ExtendedType = message
687 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700688 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700689}
690
Damien Neil1fa78d82018-09-13 13:12:36 -0700691// A Oneof describes a oneof field.
692type Oneof struct {
693 Desc protoreflect.OneofDescriptor
694
Damien Neil993c04d2018-09-14 15:41:11 -0700695 GoName string // Go field name of this oneof
696 ParentMessage *Message // message in which this oneof occurs
697 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700698 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700699}
700
701func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
702 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700703 Desc: desc,
704 ParentMessage: message,
705 GoName: camelCase(string(desc.Name())),
Joe Tsai1af1de02019-03-01 16:12:32 -0800706 Location: message.Location.appendPath(descfield.DescriptorProto_OneofDecl, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700707 }
708}
709
710func (oneof *Oneof) init(gen *Plugin, parent *Message) {
711 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
712 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
713 }
714}
715
Damien Neil46abb572018-09-07 12:45:37 -0700716// An Enum describes an enum.
717type Enum struct {
718 Desc protoreflect.EnumDescriptor
719
Damien Neil162c1272018-10-04 12:42:37 -0700720 GoIdent GoIdent // name of the generated Go type
721 Values []*EnumValue // enum values
722 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700723}
724
725func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700726 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700727 if parent != nil {
Joe Tsai1af1de02019-03-01 16:12:32 -0800728 loc = parent.Location.appendPath(descfield.DescriptorProto_EnumType, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700729 } else {
Joe Tsai1af1de02019-03-01 16:12:32 -0800730 loc = f.location(descfield.FileDescriptorProto_EnumType, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700731 }
732 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700733 Desc: desc,
734 GoIdent: newGoIdent(f, desc),
735 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700736 }
Damien Neil658051b2018-09-10 12:26:21 -0700737 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700738 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
739 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
740 }
741 return enum
742}
743
744// An EnumValue describes an enum value.
745type EnumValue struct {
746 Desc protoreflect.EnumValueDescriptor
747
Damien Neil162c1272018-10-04 12:42:37 -0700748 GoIdent GoIdent // name of the generated Go type
749 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700750}
751
752func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
753 // A top-level enum value's name is: EnumName_ValueName
754 // An enum value contained in a message is: MessageName_ValueName
755 //
756 // Enum value names are not camelcased.
757 parentIdent := enum.GoIdent
758 if message != nil {
759 parentIdent = message.GoIdent
760 }
761 name := parentIdent.GoName + "_" + string(desc.Name())
762 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800763 Desc: desc,
764 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai1af1de02019-03-01 16:12:32 -0800765 Location: enum.Location.appendPath(descfield.EnumDescriptorProto_Value, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700766 }
Damien Neil220c2022018-08-15 11:24:18 -0700767}
768
Damien Neil2dc67182018-09-21 15:03:34 -0700769// A Service describes a service.
770type Service struct {
771 Desc protoreflect.ServiceDescriptor
772
Damien Neil162c1272018-10-04 12:42:37 -0700773 GoName string
774 Location Location // location of this service
775 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700776}
777
778func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
779 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700780 Desc: desc,
781 GoName: camelCase(string(desc.Name())),
Joe Tsai1af1de02019-03-01 16:12:32 -0800782 Location: f.location(descfield.FileDescriptorProto_Service, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700783 }
784 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
785 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
786 }
787 return service
788}
789
790// A Method describes a method in a service.
791type Method struct {
792 Desc protoreflect.MethodDescriptor
793
794 GoName string
795 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700796 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700797 InputType *Message
798 OutputType *Message
799}
800
801func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
802 method := &Method{
803 Desc: desc,
804 GoName: camelCase(string(desc.Name())),
805 ParentService: service,
Joe Tsai1af1de02019-03-01 16:12:32 -0800806 Location: service.Location.appendPath(descfield.ServiceDescriptorProto_Method, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700807 }
808 return method
809}
810
811func (method *Method) init(gen *Plugin) error {
812 desc := method.Desc
813
814 inName := desc.InputType().FullName()
815 in, ok := gen.messagesByName[inName]
816 if !ok {
817 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
818 }
819 method.InputType = in
820
821 outName := desc.OutputType().FullName()
822 out, ok := gen.messagesByName[outName]
823 if !ok {
824 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
825 }
826 method.OutputType = out
827
828 return nil
829}
830
Damien Neil7bf3ce22018-12-21 15:54:06 -0800831// A GeneratedFile is a generated file.
832type GeneratedFile struct {
833 gen *Plugin
834 skip bool
835 filename string
836 goImportPath GoImportPath
837 buf bytes.Buffer
838 packageNames map[GoImportPath]GoPackageName
839 usedPackageNames map[GoPackageName]bool
840 manualImports map[GoImportPath]bool
841 annotations map[string][]Location
842}
843
844// NewGeneratedFile creates a new generated file with the given filename
845// and import path.
846func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
847 g := &GeneratedFile{
848 gen: gen,
849 filename: filename,
850 goImportPath: goImportPath,
851 packageNames: make(map[GoImportPath]GoPackageName),
852 usedPackageNames: make(map[GoPackageName]bool),
853 manualImports: make(map[GoImportPath]bool),
854 annotations: make(map[string][]Location),
855 }
Joe Tsai124c8122019-01-14 11:48:43 -0800856
857 // All predeclared identifiers in Go are already used.
858 for _, s := range types.Universe.Names() {
859 g.usedPackageNames[GoPackageName(s)] = true
860 }
861
Damien Neil7bf3ce22018-12-21 15:54:06 -0800862 gen.genFiles = append(gen.genFiles, g)
863 return g
864}
865
Damien Neil220c2022018-08-15 11:24:18 -0700866// P prints a line to the generated output. It converts each parameter to a
867// string following the same rules as fmt.Print. It never inserts spaces
868// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700869func (g *GeneratedFile) P(v ...interface{}) {
870 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700871 switch x := x.(type) {
872 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700873 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700874 default:
875 fmt.Fprint(&g.buf, x)
876 }
Damien Neil220c2022018-08-15 11:24:18 -0700877 }
878 fmt.Fprintln(&g.buf)
879}
880
Damien Neilba1159f2018-10-17 12:53:18 -0700881// PrintLeadingComments writes the comment appearing before a location in
882// the .proto source to the generated file.
883//
884// It returns true if a comment was present at the location.
885func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
886 f := g.gen.filesByName[loc.SourceFile]
887 if f == nil {
888 return false
889 }
890 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
891 if infoLoc.LeadingComments == nil {
892 continue
893 }
894 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
895 g.buf.WriteString("//")
896 g.buf.WriteString(line)
897 g.buf.WriteString("\n")
898 }
899 return true
900 }
901 return false
902}
903
Damien Neil46abb572018-09-07 12:45:37 -0700904// QualifiedGoIdent returns the string to use for a Go identifier.
905//
906// If the identifier is from a different Go package than the generated file,
907// the returned name will be qualified (package.name) and an import statement
908// for the identifier's package will be included in the file.
909func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
910 if ident.GoImportPath == g.goImportPath {
911 return ident.GoName
912 }
913 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
914 return string(packageName) + "." + ident.GoName
915 }
916 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -0800917 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700918 packageName = orig + GoPackageName(strconv.Itoa(i))
919 }
920 g.packageNames[ident.GoImportPath] = packageName
921 g.usedPackageNames[packageName] = true
922 return string(packageName) + "." + ident.GoName
923}
924
Damien Neil2e0c3da2018-09-19 12:51:36 -0700925// Import ensures a package is imported by the generated file.
926//
927// Packages referenced by QualifiedGoIdent are automatically imported.
928// Explicitly importing a package with Import is generally only necessary
929// when the import will be blank (import _ "package").
930func (g *GeneratedFile) Import(importPath GoImportPath) {
931 g.manualImports[importPath] = true
932}
933
Damien Neil220c2022018-08-15 11:24:18 -0700934// Write implements io.Writer.
935func (g *GeneratedFile) Write(p []byte) (n int, err error) {
936 return g.buf.Write(p)
937}
938
Damien Neil7bf3ce22018-12-21 15:54:06 -0800939// Skip removes the generated file from the plugin output.
940func (g *GeneratedFile) Skip() {
941 g.skip = true
942}
943
Damien Neil162c1272018-10-04 12:42:37 -0700944// Annotate associates a symbol in a generated Go file with a location in a
945// source .proto file.
946//
947// The symbol may refer to a type, constant, variable, function, method, or
948// struct field. The "T.sel" syntax is used to identify the method or field
949// 'sel' on type 'T'.
950func (g *GeneratedFile) Annotate(symbol string, loc Location) {
951 g.annotations[symbol] = append(g.annotations[symbol], loc)
952}
953
Damien Neil7bf3ce22018-12-21 15:54:06 -0800954// Content returns the contents of the generated file.
955func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700956 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700957 return g.buf.Bytes(), nil
958 }
959
960 // Reformat generated code.
961 original := g.buf.Bytes()
962 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700963 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700964 if err != nil {
965 // Print out the bad code with line numbers.
966 // This should never happen in practice, but it can while changing generated code
967 // so consider this a debugging aid.
968 var src bytes.Buffer
969 s := bufio.NewScanner(bytes.NewReader(original))
970 for line := 1; s.Scan(); line++ {
971 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
972 }
Damien Neild9016772018-08-23 14:39:30 -0700973 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700974 }
Damien Neild9016772018-08-23 14:39:30 -0700975
976 // Add imports.
977 var importPaths []string
978 for importPath := range g.packageNames {
979 importPaths = append(importPaths, string(importPath))
980 }
981 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700982 rewriteImport := func(importPath string) string {
983 if f := g.gen.opts.ImportRewriteFunc; f != nil {
984 return string(f(GoImportPath(importPath)))
985 }
986 return importPath
987 }
Damien Neild9016772018-08-23 14:39:30 -0700988 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700989 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700990 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700991 for importPath := range g.manualImports {
992 if _, ok := g.packageNames[importPath]; ok {
993 continue
994 }
Damien Neil329b75e2018-10-04 17:31:07 -0700995 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700996 }
Damien Neil1ec33152018-09-13 13:12:36 -0700997 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700998
Damien Neilc7d07d92018-08-22 13:46:02 -0700999 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001000 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001001 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001002 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001003 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001004}
Damien Neilc7d07d92018-08-22 13:46:02 -07001005
Damien Neil162c1272018-10-04 12:42:37 -07001006// metaFile returns the contents of the file's metadata file, which is a
1007// text formatted string of the google.protobuf.GeneratedCodeInfo.
1008func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1009 fset := token.NewFileSet()
1010 astFile, err := parser.ParseFile(fset, "", content, 0)
1011 if err != nil {
1012 return "", err
1013 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001014 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001015
1016 seenAnnotations := make(map[string]bool)
1017 annotate := func(s string, ident *ast.Ident) {
1018 seenAnnotations[s] = true
1019 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001020 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Joe Tsai009e0672018-11-27 18:45:07 -08001021 SourceFile: scalar.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001022 Path: loc.Path,
Joe Tsai009e0672018-11-27 18:45:07 -08001023 Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
1024 End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001025 })
1026 }
1027 }
1028 for _, decl := range astFile.Decls {
1029 switch decl := decl.(type) {
1030 case *ast.GenDecl:
1031 for _, spec := range decl.Specs {
1032 switch spec := spec.(type) {
1033 case *ast.TypeSpec:
1034 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001035 switch st := spec.Type.(type) {
1036 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001037 for _, field := range st.Fields.List {
1038 for _, name := range field.Names {
1039 annotate(spec.Name.Name+"."+name.Name, name)
1040 }
1041 }
Damien Neilae2a5612018-12-12 08:54:57 -08001042 case *ast.InterfaceType:
1043 for _, field := range st.Methods.List {
1044 for _, name := range field.Names {
1045 annotate(spec.Name.Name+"."+name.Name, name)
1046 }
1047 }
Damien Neil162c1272018-10-04 12:42:37 -07001048 }
1049 case *ast.ValueSpec:
1050 for _, name := range spec.Names {
1051 annotate(name.Name, name)
1052 }
1053 }
1054 }
1055 case *ast.FuncDecl:
1056 if decl.Recv == nil {
1057 annotate(decl.Name.Name, decl.Name)
1058 } else {
1059 recv := decl.Recv.List[0].Type
1060 if s, ok := recv.(*ast.StarExpr); ok {
1061 recv = s.X
1062 }
1063 if id, ok := recv.(*ast.Ident); ok {
1064 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1065 }
1066 }
1067 }
1068 }
1069 for a := range g.annotations {
1070 if !seenAnnotations[a] {
1071 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1072 }
1073 }
1074
Joe Tsai19058432019-02-27 21:46:29 -08001075 return strings.TrimSpace(proto.CompactTextString(info)), nil
Damien Neil220c2022018-08-15 11:24:18 -07001076}
Damien Neil082ce922018-09-06 10:23:53 -07001077
1078type pathType int
1079
1080const (
1081 pathTypeImport pathType = iota
1082 pathTypeSourceRelative
1083)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001084
Damien Neil162c1272018-10-04 12:42:37 -07001085// A Location is a location in a .proto source file.
1086//
1087// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1088// for details.
1089type Location struct {
1090 SourceFile string
1091 Path []int32
1092}
1093
1094// appendPath add elements to a Location's path, returning a new Location.
1095func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001096 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001097 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001098 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001099 return Location{
1100 SourceFile: loc.SourceFile,
1101 Path: n,
1102 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001103}
Damien Neilba1159f2018-10-17 12:53:18 -07001104
1105// A pathKey is a representation of a location path suitable for use as a map key.
1106type pathKey struct {
1107 s string
1108}
1109
1110// newPathKey converts a location path to a pathKey.
1111func newPathKey(path []int32) pathKey {
1112 buf := make([]byte, 4*len(path))
1113 for i, x := range path {
1114 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1115 }
1116 return pathKey{string(buf)}
1117}