blob: cf1e8090f69093a141c2eb6871fdf76b1bbf987a [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"
Joe Tsaie1f8d502018-11-26 18:55:29 -080037
38 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
39 pluginpb "github.com/golang/protobuf/v2/types/plugin"
Damien Neil220c2022018-08-15 11:24:18 -070040)
41
42// Run executes a function as a protoc plugin.
43//
44// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
45// function, and writes a CodeGeneratorResponse message to os.Stdout.
46//
47// If a failure occurs while reading or writing, Run prints an error to
48// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070049//
50// Passing a nil options is equivalent to passing a zero-valued one.
51func Run(opts *Options, f func(*Plugin) error) {
52 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070053 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
54 os.Exit(1)
55 }
56}
57
Damien Neil3cf6e622018-09-11 13:53:14 -070058func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070059 if len(os.Args) > 1 {
60 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
61 }
Damien Neil220c2022018-08-15 11:24:18 -070062 in, err := ioutil.ReadAll(os.Stdin)
63 if err != nil {
64 return err
65 }
66 req := &pluginpb.CodeGeneratorRequest{}
67 if err := proto.Unmarshal(in, req); err != nil {
68 return err
69 }
Damien Neil3cf6e622018-09-11 13:53:14 -070070 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070071 if err != nil {
72 return err
73 }
74 if err := f(gen); err != nil {
75 // Errors from the plugin function are reported by setting the
76 // error field in the CodeGeneratorResponse.
77 //
78 // In contrast, errors that indicate a problem in protoc
79 // itself (unparsable input, I/O errors, etc.) are reported
80 // to stderr.
81 gen.Error(err)
82 }
83 resp := gen.Response()
84 out, err := proto.Marshal(resp)
85 if err != nil {
86 return err
87 }
88 if _, err := os.Stdout.Write(out); err != nil {
89 return err
90 }
91 return nil
92}
93
94// A Plugin is a protoc plugin invocation.
95type Plugin struct {
96 // Request is the CodeGeneratorRequest provided by protoc.
97 Request *pluginpb.CodeGeneratorRequest
98
99 // Files is the set of files to generate and everything they import.
100 // Files appear in topological order, so each file appears before any
101 // file that imports it.
102 Files []*File
103 filesByName map[string]*File
104
Damien Neil658051b2018-09-10 12:26:21 -0700105 fileReg *protoregistry.Files
106 messagesByName map[protoreflect.FullName]*Message
107 enumsByName map[protoreflect.FullName]*Enum
Damien Neil162c1272018-10-04 12:42:37 -0700108 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700109 pathType pathType
110 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700111 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700112 err error
Damien Neil220c2022018-08-15 11:24:18 -0700113}
114
Damien Neil3cf6e622018-09-11 13:53:14 -0700115// Options are optional parameters to New.
116type Options struct {
117 // If ParamFunc is non-nil, it will be called with each unknown
118 // generator parameter.
119 //
120 // Plugins for protoc can accept parameters from the command line,
121 // passed in the --<lang>_out protoc, separated from the output
122 // directory with a colon; e.g.,
123 //
124 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
125 //
126 // Parameters passed in this fashion as a comma-separated list of
127 // key=value pairs will be passed to the ParamFunc.
128 //
129 // The (flag.FlagSet).Set method matches this function signature,
130 // so parameters can be converted into flags as in the following:
131 //
132 // var flags flag.FlagSet
133 // value := flags.Bool("param", false, "")
134 // opts := &protogen.Options{
135 // ParamFunc: flags.Set,
136 // }
137 // protogen.Run(opts, func(p *protogen.Plugin) error {
138 // if *value { ... }
139 // })
140 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700141
142 // ImportRewriteFunc is called with the import path of each package
143 // imported by a generated file. It returns the import path to use
144 // for this package.
145 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700146}
147
Damien Neil220c2022018-08-15 11:24:18 -0700148// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700149//
150// Passing a nil Options is equivalent to passing a zero-valued one.
151func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
152 if opts == nil {
153 opts = &Options{}
154 }
Damien Neil220c2022018-08-15 11:24:18 -0700155 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700156 Request: req,
157 filesByName: make(map[string]*File),
158 fileReg: protoregistry.NewFiles(),
159 messagesByName: make(map[protoreflect.FullName]*Message),
160 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700161 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700162 }
163
Damien Neil082ce922018-09-06 10:23:53 -0700164 packageNames := make(map[string]GoPackageName) // filename -> package name
165 importPaths := make(map[string]GoImportPath) // filename -> import path
166 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700167 for _, param := range strings.Split(req.GetParameter(), ",") {
168 var value string
169 if i := strings.Index(param, "="); i >= 0 {
170 value = param[i+1:]
171 param = param[0:i]
172 }
173 switch param {
174 case "":
175 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700176 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700177 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700178 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700179 switch value {
180 case "import":
181 gen.pathType = pathTypeImport
182 case "source_relative":
183 gen.pathType = pathTypeSourceRelative
184 default:
185 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
186 }
Damien Neil220c2022018-08-15 11:24:18 -0700187 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700188 switch value {
189 case "true", "":
190 gen.annotateCode = true
191 case "false":
192 default:
193 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
194 }
Damien Neil220c2022018-08-15 11:24:18 -0700195 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700196 if param[0] == 'M' {
197 importPaths[param[1:]] = GoImportPath(value)
198 continue
Damien Neil220c2022018-08-15 11:24:18 -0700199 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700200 if opts.ParamFunc != nil {
201 if err := opts.ParamFunc(param, value); err != nil {
202 return nil, err
203 }
204 }
Damien Neil082ce922018-09-06 10:23:53 -0700205 }
206 }
207
208 // Figure out the import path and package name for each file.
209 //
210 // The rules here are complicated and have grown organically over time.
211 // Interactions between different ways of specifying package information
212 // may be surprising.
213 //
214 // The recommended approach is to include a go_package option in every
215 // .proto source file specifying the full import path of the Go package
216 // associated with this file.
217 //
218 // option go_package = "github.com/golang/protobuf/ptypes/any";
219 //
220 // Build systems which want to exert full control over import paths may
221 // specify M<filename>=<import_path> flags.
222 //
223 // Other approaches are not recommend.
224 generatedFileNames := make(map[string]bool)
225 for _, name := range gen.Request.FileToGenerate {
226 generatedFileNames[name] = true
227 }
228 // We need to determine the import paths before the package names,
229 // because the Go package name for a file is sometimes derived from
230 // different file in the same package.
231 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
232 for _, fdesc := range gen.Request.ProtoFile {
233 filename := fdesc.GetName()
234 packageName, importPath := goPackageOption(fdesc)
235 switch {
236 case importPaths[filename] != "":
237 // Command line: M=foo.proto=quux/bar
238 //
239 // Explicit mapping of source file to import path.
240 case generatedFileNames[filename] && packageImportPath != "":
241 // Command line: import_path=quux/bar
242 //
243 // The import_path flag sets the import path for every file that
244 // we generate code for.
245 importPaths[filename] = packageImportPath
246 case importPath != "":
247 // Source file: option go_package = "quux/bar";
248 //
249 // The go_package option sets the import path. Most users should use this.
250 importPaths[filename] = importPath
251 default:
252 // Source filename.
253 //
254 // Last resort when nothing else is available.
255 importPaths[filename] = GoImportPath(path.Dir(filename))
256 }
257 if packageName != "" {
258 packageNameForImportPath[importPaths[filename]] = packageName
259 }
260 }
261 for _, fdesc := range gen.Request.ProtoFile {
262 filename := fdesc.GetName()
263 packageName, _ := goPackageOption(fdesc)
264 defaultPackageName := packageNameForImportPath[importPaths[filename]]
265 switch {
266 case packageName != "":
267 // Source file: option go_package = "quux/bar";
268 packageNames[filename] = packageName
269 case defaultPackageName != "":
270 // A go_package option in another file in the same package.
271 //
272 // This is a poor choice in general, since every source file should
273 // contain a go_package option. Supported mainly for historical
274 // compatibility.
275 packageNames[filename] = defaultPackageName
276 case generatedFileNames[filename] && packageImportPath != "":
277 // Command line: import_path=quux/bar
278 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
279 case fdesc.GetPackage() != "":
280 // Source file: package quux.bar;
281 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
282 default:
283 // Source filename.
284 packageNames[filename] = cleanPackageName(baseName(filename))
285 }
286 }
287
288 // Consistency check: Every file with the same Go import path should have
289 // the same Go package name.
290 packageFiles := make(map[GoImportPath][]string)
291 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700292 if _, ok := packageNames[filename]; !ok {
293 // Skip files mentioned in a M<file>=<import_path> parameter
294 // but which do not appear in the CodeGeneratorRequest.
295 continue
296 }
Damien Neil082ce922018-09-06 10:23:53 -0700297 packageFiles[importPath] = append(packageFiles[importPath], filename)
298 }
299 for importPath, filenames := range packageFiles {
300 for i := 1; i < len(filenames); i++ {
301 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
302 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
303 importPath, a, filenames[0], b, filenames[i])
304 }
Damien Neil220c2022018-08-15 11:24:18 -0700305 }
306 }
307
308 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700309 filename := fdesc.GetName()
310 if gen.filesByName[filename] != nil {
311 return nil, fmt.Errorf("duplicate file name: %q", filename)
312 }
313 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700314 if err != nil {
315 return nil, err
316 }
Damien Neil220c2022018-08-15 11:24:18 -0700317 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700318 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700319 }
Damien Neil082ce922018-09-06 10:23:53 -0700320 for _, filename := range gen.Request.FileToGenerate {
321 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700322 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700323 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700324 }
325 f.Generate = true
326 }
327 return gen, nil
328}
329
330// Error records an error in code generation. The generator will report the
331// error back to protoc and will not produce output.
332func (gen *Plugin) Error(err error) {
333 if gen.err == nil {
334 gen.err = err
335 }
336}
337
338// Response returns the generator output.
339func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
340 resp := &pluginpb.CodeGeneratorResponse{}
341 if gen.err != nil {
Joe Tsai009e0672018-11-27 18:45:07 -0800342 resp.Error = scalar.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700343 return resp
344 }
Damien Neil162c1272018-10-04 12:42:37 -0700345 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800346 if g.skip {
347 continue
348 }
349 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700350 if err != nil {
351 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800352 Error: scalar.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700353 }
354 }
Damien Neil220c2022018-08-15 11:24:18 -0700355 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800356 Name: scalar.String(g.filename),
357 Content: scalar.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700358 })
Damien Neil162c1272018-10-04 12:42:37 -0700359 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
360 meta, err := g.metaFile(content)
361 if err != nil {
362 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800363 Error: scalar.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700364 }
365 }
366 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800367 Name: scalar.String(g.filename + ".meta"),
368 Content: scalar.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700369 })
370 }
Damien Neil220c2022018-08-15 11:24:18 -0700371 }
372 return resp
373}
374
375// FileByName returns the file with the given name.
376func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
377 f, ok = gen.filesByName[name]
378 return f, ok
379}
380
Damien Neilc7d07d92018-08-22 13:46:02 -0700381// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700382type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700383 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800384 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700385
Joe Tsaib6405bd2018-11-15 14:44:37 -0800386 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
387 GoPackageName GoPackageName // name of this file's Go package
388 GoImportPath GoImportPath // import path of this file's Go package
389 Messages []*Message // top-level message declarations
390 Enums []*Enum // top-level enum declarations
391 Extensions []*Extension // top-level extension declarations
392 Services []*Service // top-level service declarations
393 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700394
395 // GeneratedFilenamePrefix is used to construct filenames for generated
396 // files associated with this source file.
397 //
398 // For example, the source file "dir/foo.proto" might have a filename prefix
399 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
400 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700401
Joe Tsaie1f8d502018-11-26 18:55:29 -0800402 sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700403}
404
Joe Tsaie1f8d502018-11-26 18:55:29 -0800405func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
406 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700407 if err != nil {
408 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
409 }
410 if err := gen.fileReg.Register(desc); err != nil {
411 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
412 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700413 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700414 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700415 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700416 GoPackageName: packageName,
417 GoImportPath: importPath,
Joe Tsaie1f8d502018-11-26 18:55:29 -0800418 sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700419 }
Damien Neil082ce922018-09-06 10:23:53 -0700420
421 // Determine the prefix for generated Go files.
422 prefix := p.GetName()
423 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
424 prefix = prefix[:len(prefix)-len(ext)]
425 }
426 if gen.pathType == pathTypeImport {
427 // If paths=import (the default) and the file contains a go_package option
428 // with a full import path, the output filename is derived from the Go import
429 // path.
430 //
431 // Pass the paths=source_relative flag to always derive the output filename
432 // from the input filename instead.
433 if _, importPath := goPackageOption(p); importPath != "" {
434 prefix = path.Join(string(importPath), path.Base(prefix))
435 }
436 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800437 f.GoDescriptorIdent = GoIdent{
Joe Tsai40692112019-02-27 20:25:51 -0800438 GoName: "File_" + cleanGoName(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800439 GoImportPath: f.GoImportPath,
440 }
Damien Neil082ce922018-09-06 10:23:53 -0700441 f.GeneratedFilenamePrefix = prefix
442
Damien Neilba1159f2018-10-17 12:53:18 -0700443 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
444 key := newPathKey(loc.Path)
445 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
446 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700447 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700448 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700449 }
Damien Neil46abb572018-09-07 12:45:37 -0700450 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
451 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
452 }
Damien Neil993c04d2018-09-14 15:41:11 -0700453 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
454 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
455 }
Damien Neil2dc67182018-09-21 15:03:34 -0700456 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
457 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
458 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700459 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700460 if err := message.init(gen); err != nil {
461 return nil, err
462 }
463 }
464 for _, extension := range f.Extensions {
465 if err := extension.init(gen); err != nil {
466 return nil, err
467 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700468 }
Damien Neil2dc67182018-09-21 15:03:34 -0700469 for _, service := range f.Services {
470 for _, method := range service.Methods {
471 if err := method.init(gen); err != nil {
472 return nil, err
473 }
474 }
475 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700476 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700477}
478
Damien Neil162c1272018-10-04 12:42:37 -0700479func (f *File) location(path ...int32) Location {
480 return Location{
481 SourceFile: f.Desc.Path(),
482 Path: path,
483 }
484}
485
Damien Neil082ce922018-09-06 10:23:53 -0700486// goPackageOption interprets a file's go_package option.
487// If there is no go_package, it returns ("", "").
488// If there's a simple name, it returns (pkg, "").
489// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800490func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700491 opt := d.GetOptions().GetGoPackage()
492 if opt == "" {
493 return "", ""
494 }
495 // A semicolon-delimited suffix delimits the import path and package name.
496 if i := strings.Index(opt, ";"); i >= 0 {
497 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
498 }
499 // The presence of a slash implies there's an import path.
500 if i := strings.LastIndex(opt, "/"); i >= 0 {
501 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
502 }
503 return cleanPackageName(opt), ""
504}
505
Damien Neilc7d07d92018-08-22 13:46:02 -0700506// A Message describes a message.
507type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700508 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700509
Damien Neil993c04d2018-09-14 15:41:11 -0700510 GoIdent GoIdent // name of the generated Go type
511 Fields []*Field // message field declarations
512 Oneofs []*Oneof // oneof declarations
513 Messages []*Message // nested message declarations
514 Enums []*Enum // nested enum declarations
515 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700516 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700517}
518
Damien Neil1fa78d82018-09-13 13:12:36 -0700519func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700520 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700521 if parent != nil {
Joe Tsai1af1de02019-03-01 16:12:32 -0800522 loc = parent.Location.appendPath(descfield.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700523 } else {
Joe Tsai1af1de02019-03-01 16:12:32 -0800524 loc = f.location(descfield.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700525 }
Damien Neil46abb572018-09-07 12:45:37 -0700526 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700527 Desc: desc,
528 GoIdent: newGoIdent(f, desc),
529 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700530 }
Damien Neil658051b2018-09-10 12:26:21 -0700531 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700532 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700533 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700534 }
Damien Neil46abb572018-09-07 12:45:37 -0700535 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
536 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
537 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700538 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
539 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
540 }
Damien Neil658051b2018-09-10 12:26:21 -0700541 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700542 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700543 }
Damien Neil993c04d2018-09-14 15:41:11 -0700544 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
545 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
546 }
Damien Neil658051b2018-09-10 12:26:21 -0700547
548 // Field name conflict resolution.
549 //
550 // We assume well-known method names that may be attached to a generated
551 // message type, as well as a 'Get*' method for each field. For each
552 // field in turn, we add _s to its name until there are no conflicts.
553 //
554 // Any change to the following set of method names is a potential
555 // incompatible API change because it may change generated field names.
556 //
557 // TODO: If we ever support a 'go_name' option to set the Go name of a
558 // field, we should consider dropping this entirely. The conflict
559 // resolution algorithm is subtle and surprising (changing the order
560 // in which fields appear in the .proto source file can change the
561 // names of fields in generated code), and does not adapt well to
562 // adding new per-field methods such as setters.
563 usedNames := map[string]bool{
564 "Reset": true,
565 "String": true,
566 "ProtoMessage": true,
567 "Marshal": true,
568 "Unmarshal": true,
569 "ExtensionRangeArray": true,
570 "ExtensionMap": true,
571 "Descriptor": true,
572 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800573 makeNameUnique := func(name string, hasGetter bool) string {
574 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700575 name += "_"
576 }
577 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800578 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700579 return name
580 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700581 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700582 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800583 field.GoName = makeNameUnique(field.GoName, true)
Damien Neil1fa78d82018-09-13 13:12:36 -0700584 if field.OneofType != nil {
585 if !seenOneofs[field.OneofType.Desc.Index()] {
586 // If this is a field in a oneof that we haven't seen before,
587 // make the name for that oneof unique as well.
Joe Tsaid6966a42019-01-08 10:59:34 -0800588 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName, false)
Damien Neil1fa78d82018-09-13 13:12:36 -0700589 seenOneofs[field.OneofType.Desc.Index()] = true
590 }
591 }
Damien Neil658051b2018-09-10 12:26:21 -0700592 }
593
Damien Neil1fa78d82018-09-13 13:12:36 -0700594 return message
Damien Neil658051b2018-09-10 12:26:21 -0700595}
596
Damien Neil0bd5a382018-09-13 15:07:10 -0700597func (message *Message) init(gen *Plugin) error {
598 for _, child := range message.Messages {
599 if err := child.init(gen); err != nil {
600 return err
601 }
602 }
603 for _, field := range message.Fields {
604 if err := field.init(gen); err != nil {
605 return err
606 }
607 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700608 for _, oneof := range message.Oneofs {
609 oneof.init(gen, message)
610 }
Damien Neil993c04d2018-09-14 15:41:11 -0700611 for _, extension := range message.Extensions {
612 if err := extension.init(gen); err != nil {
613 return err
614 }
615 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700616 return nil
617}
618
Damien Neil658051b2018-09-10 12:26:21 -0700619// A Field describes a message field.
620type Field struct {
621 Desc protoreflect.FieldDescriptor
622
Damien Neil1fa78d82018-09-13 13:12:36 -0700623 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700624 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700625 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
626 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700627
Damien Neil993c04d2018-09-14 15:41:11 -0700628 ParentMessage *Message // message in which this field is defined; nil if top-level extension
629 ExtendedType *Message // extended message for extension fields; nil otherwise
630 MessageType *Message // type for message or group fields; nil otherwise
631 EnumType *Enum // type for enum fields; nil otherwise
632 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700633 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700634}
635
Damien Neil1fa78d82018-09-13 13:12:36 -0700636func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700637 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700638 switch {
639 case desc.ExtendedType() != nil && message == nil:
Joe Tsai1af1de02019-03-01 16:12:32 -0800640 loc = f.location(descfield.FileDescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700641 case desc.ExtendedType() != nil && message != nil:
Joe Tsai1af1de02019-03-01 16:12:32 -0800642 loc = message.Location.appendPath(descfield.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700643 default:
Joe Tsai1af1de02019-03-01 16:12:32 -0800644 loc = message.Location.appendPath(descfield.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700645 }
Damien Neil658051b2018-09-10 12:26:21 -0700646 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700647 Desc: desc,
648 GoName: camelCase(string(desc.Name())),
649 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700650 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700651 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700652 if desc.OneofType() != nil {
653 field.OneofType = message.Oneofs[desc.OneofType().Index()]
654 }
655 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700656}
657
Damien Neil993c04d2018-09-14 15:41:11 -0700658// Extension is an alias of Field for documentation.
659type Extension = Field
660
Damien Neil0bd5a382018-09-13 15:07:10 -0700661func (field *Field) init(gen *Plugin) error {
662 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700663 switch desc.Kind() {
664 case protoreflect.MessageKind, protoreflect.GroupKind:
665 mname := desc.MessageType().FullName()
666 message, ok := gen.messagesByName[mname]
667 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700668 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700669 }
670 field.MessageType = message
671 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700672 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700673 enum, ok := gen.enumsByName[ename]
674 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700675 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700676 }
677 field.EnumType = enum
678 }
Damien Neil993c04d2018-09-14 15:41:11 -0700679 if desc.ExtendedType() != nil {
680 mname := desc.ExtendedType().FullName()
681 message, ok := gen.messagesByName[mname]
682 if !ok {
683 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
684 }
685 field.ExtendedType = message
686 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700687 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700688}
689
Damien Neil1fa78d82018-09-13 13:12:36 -0700690// A Oneof describes a oneof field.
691type Oneof struct {
692 Desc protoreflect.OneofDescriptor
693
Damien Neil993c04d2018-09-14 15:41:11 -0700694 GoName string // Go field name of this oneof
695 ParentMessage *Message // message in which this oneof occurs
696 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700697 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700698}
699
700func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
701 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700702 Desc: desc,
703 ParentMessage: message,
704 GoName: camelCase(string(desc.Name())),
Joe Tsai1af1de02019-03-01 16:12:32 -0800705 Location: message.Location.appendPath(descfield.DescriptorProto_OneofDecl, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700706 }
707}
708
709func (oneof *Oneof) init(gen *Plugin, parent *Message) {
710 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
711 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
712 }
713}
714
Damien Neil46abb572018-09-07 12:45:37 -0700715// An Enum describes an enum.
716type Enum struct {
717 Desc protoreflect.EnumDescriptor
718
Damien Neil162c1272018-10-04 12:42:37 -0700719 GoIdent GoIdent // name of the generated Go type
720 Values []*EnumValue // enum values
721 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700722}
723
724func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700725 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700726 if parent != nil {
Joe Tsai1af1de02019-03-01 16:12:32 -0800727 loc = parent.Location.appendPath(descfield.DescriptorProto_EnumType, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700728 } else {
Joe Tsai1af1de02019-03-01 16:12:32 -0800729 loc = f.location(descfield.FileDescriptorProto_EnumType, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700730 }
731 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700732 Desc: desc,
733 GoIdent: newGoIdent(f, desc),
734 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700735 }
Damien Neil658051b2018-09-10 12:26:21 -0700736 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700737 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
738 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
739 }
740 return enum
741}
742
743// An EnumValue describes an enum value.
744type EnumValue struct {
745 Desc protoreflect.EnumValueDescriptor
746
Damien Neil162c1272018-10-04 12:42:37 -0700747 GoIdent GoIdent // name of the generated Go type
748 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700749}
750
751func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
752 // A top-level enum value's name is: EnumName_ValueName
753 // An enum value contained in a message is: MessageName_ValueName
754 //
755 // Enum value names are not camelcased.
756 parentIdent := enum.GoIdent
757 if message != nil {
758 parentIdent = message.GoIdent
759 }
760 name := parentIdent.GoName + "_" + string(desc.Name())
761 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800762 Desc: desc,
763 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai1af1de02019-03-01 16:12:32 -0800764 Location: enum.Location.appendPath(descfield.EnumDescriptorProto_Value, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700765 }
Damien Neil220c2022018-08-15 11:24:18 -0700766}
767
Damien Neil2dc67182018-09-21 15:03:34 -0700768// A Service describes a service.
769type Service struct {
770 Desc protoreflect.ServiceDescriptor
771
Damien Neil162c1272018-10-04 12:42:37 -0700772 GoName string
773 Location Location // location of this service
774 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700775}
776
777func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
778 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700779 Desc: desc,
780 GoName: camelCase(string(desc.Name())),
Joe Tsai1af1de02019-03-01 16:12:32 -0800781 Location: f.location(descfield.FileDescriptorProto_Service, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700782 }
783 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
784 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
785 }
786 return service
787}
788
789// A Method describes a method in a service.
790type Method struct {
791 Desc protoreflect.MethodDescriptor
792
793 GoName string
794 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700795 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700796 InputType *Message
797 OutputType *Message
798}
799
800func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
801 method := &Method{
802 Desc: desc,
803 GoName: camelCase(string(desc.Name())),
804 ParentService: service,
Joe Tsai1af1de02019-03-01 16:12:32 -0800805 Location: service.Location.appendPath(descfield.ServiceDescriptorProto_Method, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700806 }
807 return method
808}
809
810func (method *Method) init(gen *Plugin) error {
811 desc := method.Desc
812
813 inName := desc.InputType().FullName()
814 in, ok := gen.messagesByName[inName]
815 if !ok {
816 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
817 }
818 method.InputType = in
819
820 outName := desc.OutputType().FullName()
821 out, ok := gen.messagesByName[outName]
822 if !ok {
823 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
824 }
825 method.OutputType = out
826
827 return nil
828}
829
Damien Neil7bf3ce22018-12-21 15:54:06 -0800830// A GeneratedFile is a generated file.
831type GeneratedFile struct {
832 gen *Plugin
833 skip bool
834 filename string
835 goImportPath GoImportPath
836 buf bytes.Buffer
837 packageNames map[GoImportPath]GoPackageName
838 usedPackageNames map[GoPackageName]bool
839 manualImports map[GoImportPath]bool
840 annotations map[string][]Location
841}
842
843// NewGeneratedFile creates a new generated file with the given filename
844// and import path.
845func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
846 g := &GeneratedFile{
847 gen: gen,
848 filename: filename,
849 goImportPath: goImportPath,
850 packageNames: make(map[GoImportPath]GoPackageName),
851 usedPackageNames: make(map[GoPackageName]bool),
852 manualImports: make(map[GoImportPath]bool),
853 annotations: make(map[string][]Location),
854 }
Joe Tsai124c8122019-01-14 11:48:43 -0800855
856 // All predeclared identifiers in Go are already used.
857 for _, s := range types.Universe.Names() {
858 g.usedPackageNames[GoPackageName(s)] = true
859 }
860
Damien Neil7bf3ce22018-12-21 15:54:06 -0800861 gen.genFiles = append(gen.genFiles, g)
862 return g
863}
864
Damien Neil220c2022018-08-15 11:24:18 -0700865// P prints a line to the generated output. It converts each parameter to a
866// string following the same rules as fmt.Print. It never inserts spaces
867// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700868func (g *GeneratedFile) P(v ...interface{}) {
869 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700870 switch x := x.(type) {
871 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700872 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700873 default:
874 fmt.Fprint(&g.buf, x)
875 }
Damien Neil220c2022018-08-15 11:24:18 -0700876 }
877 fmt.Fprintln(&g.buf)
878}
879
Damien Neilba1159f2018-10-17 12:53:18 -0700880// PrintLeadingComments writes the comment appearing before a location in
881// the .proto source to the generated file.
882//
883// It returns true if a comment was present at the location.
884func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
885 f := g.gen.filesByName[loc.SourceFile]
886 if f == nil {
887 return false
888 }
889 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
890 if infoLoc.LeadingComments == nil {
891 continue
892 }
893 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
894 g.buf.WriteString("//")
895 g.buf.WriteString(line)
896 g.buf.WriteString("\n")
897 }
898 return true
899 }
900 return false
901}
902
Damien Neil46abb572018-09-07 12:45:37 -0700903// QualifiedGoIdent returns the string to use for a Go identifier.
904//
905// If the identifier is from a different Go package than the generated file,
906// the returned name will be qualified (package.name) and an import statement
907// for the identifier's package will be included in the file.
908func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
909 if ident.GoImportPath == g.goImportPath {
910 return ident.GoName
911 }
912 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
913 return string(packageName) + "." + ident.GoName
914 }
915 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -0800916 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700917 packageName = orig + GoPackageName(strconv.Itoa(i))
918 }
919 g.packageNames[ident.GoImportPath] = packageName
920 g.usedPackageNames[packageName] = true
921 return string(packageName) + "." + ident.GoName
922}
923
Damien Neil2e0c3da2018-09-19 12:51:36 -0700924// Import ensures a package is imported by the generated file.
925//
926// Packages referenced by QualifiedGoIdent are automatically imported.
927// Explicitly importing a package with Import is generally only necessary
928// when the import will be blank (import _ "package").
929func (g *GeneratedFile) Import(importPath GoImportPath) {
930 g.manualImports[importPath] = true
931}
932
Damien Neil220c2022018-08-15 11:24:18 -0700933// Write implements io.Writer.
934func (g *GeneratedFile) Write(p []byte) (n int, err error) {
935 return g.buf.Write(p)
936}
937
Damien Neil7bf3ce22018-12-21 15:54:06 -0800938// Skip removes the generated file from the plugin output.
939func (g *GeneratedFile) Skip() {
940 g.skip = true
941}
942
Damien Neil162c1272018-10-04 12:42:37 -0700943// Annotate associates a symbol in a generated Go file with a location in a
944// source .proto file.
945//
946// The symbol may refer to a type, constant, variable, function, method, or
947// struct field. The "T.sel" syntax is used to identify the method or field
948// 'sel' on type 'T'.
949func (g *GeneratedFile) Annotate(symbol string, loc Location) {
950 g.annotations[symbol] = append(g.annotations[symbol], loc)
951}
952
Damien Neil7bf3ce22018-12-21 15:54:06 -0800953// Content returns the contents of the generated file.
954func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700955 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700956 return g.buf.Bytes(), nil
957 }
958
959 // Reformat generated code.
960 original := g.buf.Bytes()
961 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700962 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700963 if err != nil {
964 // Print out the bad code with line numbers.
965 // This should never happen in practice, but it can while changing generated code
966 // so consider this a debugging aid.
967 var src bytes.Buffer
968 s := bufio.NewScanner(bytes.NewReader(original))
969 for line := 1; s.Scan(); line++ {
970 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
971 }
Damien Neild9016772018-08-23 14:39:30 -0700972 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700973 }
Damien Neild9016772018-08-23 14:39:30 -0700974
Joe Tsaibeda4042019-03-10 16:40:48 -0700975 // Collect a sorted list of all imports.
976 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -0700977 rewriteImport := func(importPath string) string {
978 if f := g.gen.opts.ImportRewriteFunc; f != nil {
979 return string(f(GoImportPath(importPath)))
980 }
981 return importPath
982 }
Joe Tsaibeda4042019-03-10 16:40:48 -0700983 for importPath := range g.packageNames {
984 pkgName := string(g.packageNames[GoImportPath(importPath)])
985 pkgPath := rewriteImport(string(importPath))
986 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -0700987 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700988 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -0700989 if _, ok := g.packageNames[importPath]; !ok {
990 pkgPath := rewriteImport(string(importPath))
991 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -0700992 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700993 }
Joe Tsaibeda4042019-03-10 16:40:48 -0700994 sort.Slice(importPaths, func(i, j int) bool {
995 return importPaths[i][1] < importPaths[j][1]
996 })
997
998 // Modify the AST to include a new import block.
999 if len(importPaths) > 0 {
1000 // Insert block after package statement or
1001 // possible comment attached to the end of the package statement.
1002 pos := file.Package
1003 tokFile := fset.File(file.Package)
1004 pkgLine := tokFile.Line(file.Package)
1005 for _, c := range file.Comments {
1006 if tokFile.Line(c.Pos()) > pkgLine {
1007 break
1008 }
1009 pos = c.End()
1010 }
1011
1012 // Construct the import block.
1013 impDecl := &ast.GenDecl{
1014 Tok: token.IMPORT,
1015 TokPos: pos,
1016 Lparen: pos,
1017 Rparen: pos,
1018 }
1019 for _, importPath := range importPaths {
1020 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1021 Name: &ast.Ident{
1022 Name: importPath[0],
1023 NamePos: pos,
1024 },
1025 Path: &ast.BasicLit{
1026 Kind: token.STRING,
1027 Value: strconv.Quote(importPath[1]),
1028 ValuePos: pos,
1029 },
1030 EndPos: pos,
1031 })
1032 }
1033 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1034 }
Damien Neild9016772018-08-23 14:39:30 -07001035
Damien Neilc7d07d92018-08-22 13:46:02 -07001036 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001037 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001038 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001039 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001040 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001041}
Damien Neilc7d07d92018-08-22 13:46:02 -07001042
Damien Neil162c1272018-10-04 12:42:37 -07001043// metaFile returns the contents of the file's metadata file, which is a
1044// text formatted string of the google.protobuf.GeneratedCodeInfo.
1045func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1046 fset := token.NewFileSet()
1047 astFile, err := parser.ParseFile(fset, "", content, 0)
1048 if err != nil {
1049 return "", err
1050 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001051 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001052
1053 seenAnnotations := make(map[string]bool)
1054 annotate := func(s string, ident *ast.Ident) {
1055 seenAnnotations[s] = true
1056 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001057 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Joe Tsai009e0672018-11-27 18:45:07 -08001058 SourceFile: scalar.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001059 Path: loc.Path,
Joe Tsai009e0672018-11-27 18:45:07 -08001060 Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
1061 End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001062 })
1063 }
1064 }
1065 for _, decl := range astFile.Decls {
1066 switch decl := decl.(type) {
1067 case *ast.GenDecl:
1068 for _, spec := range decl.Specs {
1069 switch spec := spec.(type) {
1070 case *ast.TypeSpec:
1071 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001072 switch st := spec.Type.(type) {
1073 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001074 for _, field := range st.Fields.List {
1075 for _, name := range field.Names {
1076 annotate(spec.Name.Name+"."+name.Name, name)
1077 }
1078 }
Damien Neilae2a5612018-12-12 08:54:57 -08001079 case *ast.InterfaceType:
1080 for _, field := range st.Methods.List {
1081 for _, name := range field.Names {
1082 annotate(spec.Name.Name+"."+name.Name, name)
1083 }
1084 }
Damien Neil162c1272018-10-04 12:42:37 -07001085 }
1086 case *ast.ValueSpec:
1087 for _, name := range spec.Names {
1088 annotate(name.Name, name)
1089 }
1090 }
1091 }
1092 case *ast.FuncDecl:
1093 if decl.Recv == nil {
1094 annotate(decl.Name.Name, decl.Name)
1095 } else {
1096 recv := decl.Recv.List[0].Type
1097 if s, ok := recv.(*ast.StarExpr); ok {
1098 recv = s.X
1099 }
1100 if id, ok := recv.(*ast.Ident); ok {
1101 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1102 }
1103 }
1104 }
1105 }
1106 for a := range g.annotations {
1107 if !seenAnnotations[a] {
1108 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1109 }
1110 }
1111
Joe Tsai19058432019-02-27 21:46:29 -08001112 return strings.TrimSpace(proto.CompactTextString(info)), nil
Damien Neil220c2022018-08-15 11:24:18 -07001113}
Damien Neil082ce922018-09-06 10:23:53 -07001114
1115type pathType int
1116
1117const (
1118 pathTypeImport pathType = iota
1119 pathTypeSourceRelative
1120)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001121
Damien Neil162c1272018-10-04 12:42:37 -07001122// A Location is a location in a .proto source file.
1123//
1124// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1125// for details.
1126type Location struct {
1127 SourceFile string
1128 Path []int32
1129}
1130
1131// appendPath add elements to a Location's path, returning a new Location.
1132func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001133 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001134 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001135 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001136 return Location{
1137 SourceFile: loc.SourceFile,
1138 Path: n,
1139 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001140}
Damien Neilba1159f2018-10-17 12:53:18 -07001141
1142// A pathKey is a representation of a location path suitable for use as a map key.
1143type pathKey struct {
1144 s string
1145}
1146
1147// newPathKey converts a location path to a pathKey.
1148func newPathKey(path []int32) pathKey {
1149 buf := make([]byte, 4*len(path))
1150 for i, x := range path {
1151 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1152 }
1153 return pathKey{string(buf)}
1154}