blob: 22f663edfa217944e80bdc7e8e8a13a732ea2b93 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package protogen provides support for writing protoc plugins.
6//
7// Plugins for protoc, the Protocol Buffers Compiler, are programs which read
8// a CodeGeneratorRequest protocol buffer from standard input and write a
9// CodeGeneratorResponse protocol buffer to standard output. This package
10// provides support for writing plugins which generate Go code.
11package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
16 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070017 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070018 "go/parser"
19 "go/printer"
20 "go/token"
Damien Neil220c2022018-08-15 11:24:18 -070021 "io/ioutil"
22 "os"
Damien Neil082ce922018-09-06 10:23:53 -070023 "path"
Damien Neil220c2022018-08-15 11:24:18 -070024 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070025 "sort"
26 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070027 "strings"
28
29 "github.com/golang/protobuf/proto"
30 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
31 pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
Joe Tsai01ab2962018-09-21 17:44:00 -070032 "github.com/golang/protobuf/v2/reflect/protoreflect"
33 "github.com/golang/protobuf/v2/reflect/protoregistry"
34 "github.com/golang/protobuf/v2/reflect/prototype"
Damien Neild9016772018-08-23 14:39:30 -070035 "golang.org/x/tools/go/ast/astutil"
Damien Neil220c2022018-08-15 11:24:18 -070036)
37
38// Run executes a function as a protoc plugin.
39//
40// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
41// function, and writes a CodeGeneratorResponse message to os.Stdout.
42//
43// If a failure occurs while reading or writing, Run prints an error to
44// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070045//
46// Passing a nil options is equivalent to passing a zero-valued one.
47func Run(opts *Options, f func(*Plugin) error) {
48 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070049 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
50 os.Exit(1)
51 }
52}
53
Damien Neil3cf6e622018-09-11 13:53:14 -070054func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070055 if len(os.Args) > 1 {
56 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
57 }
Damien Neil220c2022018-08-15 11:24:18 -070058 in, err := ioutil.ReadAll(os.Stdin)
59 if err != nil {
60 return err
61 }
62 req := &pluginpb.CodeGeneratorRequest{}
63 if err := proto.Unmarshal(in, req); err != nil {
64 return err
65 }
Damien Neil3cf6e622018-09-11 13:53:14 -070066 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070067 if err != nil {
68 return err
69 }
70 if err := f(gen); err != nil {
71 // Errors from the plugin function are reported by setting the
72 // error field in the CodeGeneratorResponse.
73 //
74 // In contrast, errors that indicate a problem in protoc
75 // itself (unparsable input, I/O errors, etc.) are reported
76 // to stderr.
77 gen.Error(err)
78 }
79 resp := gen.Response()
80 out, err := proto.Marshal(resp)
81 if err != nil {
82 return err
83 }
84 if _, err := os.Stdout.Write(out); err != nil {
85 return err
86 }
87 return nil
88}
89
90// A Plugin is a protoc plugin invocation.
91type Plugin struct {
92 // Request is the CodeGeneratorRequest provided by protoc.
93 Request *pluginpb.CodeGeneratorRequest
94
95 // Files is the set of files to generate and everything they import.
96 // Files appear in topological order, so each file appears before any
97 // file that imports it.
98 Files []*File
99 filesByName map[string]*File
100
Damien Neil658051b2018-09-10 12:26:21 -0700101 fileReg *protoregistry.Files
102 messagesByName map[protoreflect.FullName]*Message
103 enumsByName map[protoreflect.FullName]*Enum
Damien Neil162c1272018-10-04 12:42:37 -0700104 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700105 pathType pathType
106 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700107 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700108 err error
Damien Neil220c2022018-08-15 11:24:18 -0700109}
110
Damien Neil3cf6e622018-09-11 13:53:14 -0700111// Options are optional parameters to New.
112type Options struct {
113 // If ParamFunc is non-nil, it will be called with each unknown
114 // generator parameter.
115 //
116 // Plugins for protoc can accept parameters from the command line,
117 // passed in the --<lang>_out protoc, separated from the output
118 // directory with a colon; e.g.,
119 //
120 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
121 //
122 // Parameters passed in this fashion as a comma-separated list of
123 // key=value pairs will be passed to the ParamFunc.
124 //
125 // The (flag.FlagSet).Set method matches this function signature,
126 // so parameters can be converted into flags as in the following:
127 //
128 // var flags flag.FlagSet
129 // value := flags.Bool("param", false, "")
130 // opts := &protogen.Options{
131 // ParamFunc: flags.Set,
132 // }
133 // protogen.Run(opts, func(p *protogen.Plugin) error {
134 // if *value { ... }
135 // })
136 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700137
138 // ImportRewriteFunc is called with the import path of each package
139 // imported by a generated file. It returns the import path to use
140 // for this package.
141 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700142}
143
Damien Neil220c2022018-08-15 11:24:18 -0700144// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700145//
146// Passing a nil Options is equivalent to passing a zero-valued one.
147func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
148 if opts == nil {
149 opts = &Options{}
150 }
Damien Neil220c2022018-08-15 11:24:18 -0700151 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700152 Request: req,
153 filesByName: make(map[string]*File),
154 fileReg: protoregistry.NewFiles(),
155 messagesByName: make(map[protoreflect.FullName]*Message),
156 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700157 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700158 }
159
Damien Neil082ce922018-09-06 10:23:53 -0700160 packageNames := make(map[string]GoPackageName) // filename -> package name
161 importPaths := make(map[string]GoImportPath) // filename -> import path
162 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700163 for _, param := range strings.Split(req.GetParameter(), ",") {
164 var value string
165 if i := strings.Index(param, "="); i >= 0 {
166 value = param[i+1:]
167 param = param[0:i]
168 }
169 switch param {
170 case "":
171 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700172 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700173 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700174 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700175 switch value {
176 case "import":
177 gen.pathType = pathTypeImport
178 case "source_relative":
179 gen.pathType = pathTypeSourceRelative
180 default:
181 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
182 }
Damien Neil220c2022018-08-15 11:24:18 -0700183 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700184 switch value {
185 case "true", "":
186 gen.annotateCode = true
187 case "false":
188 default:
189 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
190 }
Damien Neil220c2022018-08-15 11:24:18 -0700191 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700192 if param[0] == 'M' {
193 importPaths[param[1:]] = GoImportPath(value)
194 continue
Damien Neil220c2022018-08-15 11:24:18 -0700195 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700196 if opts.ParamFunc != nil {
197 if err := opts.ParamFunc(param, value); err != nil {
198 return nil, err
199 }
200 }
Damien Neil082ce922018-09-06 10:23:53 -0700201 }
202 }
203
204 // Figure out the import path and package name for each file.
205 //
206 // The rules here are complicated and have grown organically over time.
207 // Interactions between different ways of specifying package information
208 // may be surprising.
209 //
210 // The recommended approach is to include a go_package option in every
211 // .proto source file specifying the full import path of the Go package
212 // associated with this file.
213 //
214 // option go_package = "github.com/golang/protobuf/ptypes/any";
215 //
216 // Build systems which want to exert full control over import paths may
217 // specify M<filename>=<import_path> flags.
218 //
219 // Other approaches are not recommend.
220 generatedFileNames := make(map[string]bool)
221 for _, name := range gen.Request.FileToGenerate {
222 generatedFileNames[name] = true
223 }
224 // We need to determine the import paths before the package names,
225 // because the Go package name for a file is sometimes derived from
226 // different file in the same package.
227 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
228 for _, fdesc := range gen.Request.ProtoFile {
229 filename := fdesc.GetName()
230 packageName, importPath := goPackageOption(fdesc)
231 switch {
232 case importPaths[filename] != "":
233 // Command line: M=foo.proto=quux/bar
234 //
235 // Explicit mapping of source file to import path.
236 case generatedFileNames[filename] && packageImportPath != "":
237 // Command line: import_path=quux/bar
238 //
239 // The import_path flag sets the import path for every file that
240 // we generate code for.
241 importPaths[filename] = packageImportPath
242 case importPath != "":
243 // Source file: option go_package = "quux/bar";
244 //
245 // The go_package option sets the import path. Most users should use this.
246 importPaths[filename] = importPath
247 default:
248 // Source filename.
249 //
250 // Last resort when nothing else is available.
251 importPaths[filename] = GoImportPath(path.Dir(filename))
252 }
253 if packageName != "" {
254 packageNameForImportPath[importPaths[filename]] = packageName
255 }
256 }
257 for _, fdesc := range gen.Request.ProtoFile {
258 filename := fdesc.GetName()
259 packageName, _ := goPackageOption(fdesc)
260 defaultPackageName := packageNameForImportPath[importPaths[filename]]
261 switch {
262 case packageName != "":
263 // Source file: option go_package = "quux/bar";
264 packageNames[filename] = packageName
265 case defaultPackageName != "":
266 // A go_package option in another file in the same package.
267 //
268 // This is a poor choice in general, since every source file should
269 // contain a go_package option. Supported mainly for historical
270 // compatibility.
271 packageNames[filename] = defaultPackageName
272 case generatedFileNames[filename] && packageImportPath != "":
273 // Command line: import_path=quux/bar
274 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
275 case fdesc.GetPackage() != "":
276 // Source file: package quux.bar;
277 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
278 default:
279 // Source filename.
280 packageNames[filename] = cleanPackageName(baseName(filename))
281 }
282 }
283
284 // Consistency check: Every file with the same Go import path should have
285 // the same Go package name.
286 packageFiles := make(map[GoImportPath][]string)
287 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700288 if _, ok := packageNames[filename]; !ok {
289 // Skip files mentioned in a M<file>=<import_path> parameter
290 // but which do not appear in the CodeGeneratorRequest.
291 continue
292 }
Damien Neil082ce922018-09-06 10:23:53 -0700293 packageFiles[importPath] = append(packageFiles[importPath], filename)
294 }
295 for importPath, filenames := range packageFiles {
296 for i := 1; i < len(filenames); i++ {
297 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
298 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
299 importPath, a, filenames[0], b, filenames[i])
300 }
Damien Neil220c2022018-08-15 11:24:18 -0700301 }
302 }
303
304 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700305 filename := fdesc.GetName()
306 if gen.filesByName[filename] != nil {
307 return nil, fmt.Errorf("duplicate file name: %q", filename)
308 }
309 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700310 if err != nil {
311 return nil, err
312 }
Damien Neil220c2022018-08-15 11:24:18 -0700313 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700314 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700315 }
Damien Neil082ce922018-09-06 10:23:53 -0700316 for _, filename := range gen.Request.FileToGenerate {
317 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700318 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700319 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700320 }
321 f.Generate = true
322 }
323 return gen, nil
324}
325
326// Error records an error in code generation. The generator will report the
327// error back to protoc and will not produce output.
328func (gen *Plugin) Error(err error) {
329 if gen.err == nil {
330 gen.err = err
331 }
332}
333
334// Response returns the generator output.
335func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
336 resp := &pluginpb.CodeGeneratorResponse{}
337 if gen.err != nil {
338 resp.Error = proto.String(gen.err.Error())
339 return resp
340 }
Damien Neil162c1272018-10-04 12:42:37 -0700341 for _, g := range gen.genFiles {
342 content, err := g.content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700343 if err != nil {
344 return &pluginpb.CodeGeneratorResponse{
345 Error: proto.String(err.Error()),
346 }
347 }
Damien Neil220c2022018-08-15 11:24:18 -0700348 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neil162c1272018-10-04 12:42:37 -0700349 Name: proto.String(g.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700350 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700351 })
Damien Neil162c1272018-10-04 12:42:37 -0700352 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
353 meta, err := g.metaFile(content)
354 if err != nil {
355 return &pluginpb.CodeGeneratorResponse{
356 Error: proto.String(err.Error()),
357 }
358 }
359 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
360 Name: proto.String(g.filename + ".meta"),
361 Content: proto.String(meta),
362 })
363 }
Damien Neil220c2022018-08-15 11:24:18 -0700364 }
365 return resp
366}
367
368// FileByName returns the file with the given name.
369func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
370 f, ok = gen.filesByName[name]
371 return f, ok
372}
373
Damien Neilc7d07d92018-08-22 13:46:02 -0700374// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700375type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700376 Desc protoreflect.FileDescriptor
377 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700378
Damien Neil082ce922018-09-06 10:23:53 -0700379 GoPackageName GoPackageName // name of this file's Go package
380 GoImportPath GoImportPath // import path of this file's Go package
381 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700382 Enums []*Enum // top-level enum declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700383 Extensions []*Extension // top-level extension declarations
Damien Neil2dc67182018-09-21 15:03:34 -0700384 Services []*Service // top-level service declarations
Damien Neil082ce922018-09-06 10:23:53 -0700385 Generate bool // true if we should generate code for this file
386
387 // GeneratedFilenamePrefix is used to construct filenames for generated
388 // files associated with this source file.
389 //
390 // For example, the source file "dir/foo.proto" might have a filename prefix
391 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
392 GeneratedFilenamePrefix string
Damien Neil220c2022018-08-15 11:24:18 -0700393}
394
Damien Neil082ce922018-09-06 10:23:53 -0700395func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700396 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
397 if err != nil {
398 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
399 }
400 if err := gen.fileReg.Register(desc); err != nil {
401 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
402 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700403 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700404 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700405 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700406 GoPackageName: packageName,
407 GoImportPath: importPath,
Damien Neil220c2022018-08-15 11:24:18 -0700408 }
Damien Neil082ce922018-09-06 10:23:53 -0700409
410 // Determine the prefix for generated Go files.
411 prefix := p.GetName()
412 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
413 prefix = prefix[:len(prefix)-len(ext)]
414 }
415 if gen.pathType == pathTypeImport {
416 // If paths=import (the default) and the file contains a go_package option
417 // with a full import path, the output filename is derived from the Go import
418 // path.
419 //
420 // Pass the paths=source_relative flag to always derive the output filename
421 // from the input filename instead.
422 if _, importPath := goPackageOption(p); importPath != "" {
423 prefix = path.Join(string(importPath), path.Base(prefix))
424 }
425 }
426 f.GeneratedFilenamePrefix = prefix
427
Damien Neilabc6fc12018-08-23 14:39:30 -0700428 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700429 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700430 }
Damien Neil46abb572018-09-07 12:45:37 -0700431 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
432 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
433 }
Damien Neil993c04d2018-09-14 15:41:11 -0700434 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
435 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
436 }
Damien Neil2dc67182018-09-21 15:03:34 -0700437 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
438 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
439 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700440 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700441 if err := message.init(gen); err != nil {
442 return nil, err
443 }
444 }
445 for _, extension := range f.Extensions {
446 if err := extension.init(gen); err != nil {
447 return nil, err
448 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700449 }
Damien Neil2dc67182018-09-21 15:03:34 -0700450 for _, service := range f.Services {
451 for _, method := range service.Methods {
452 if err := method.init(gen); err != nil {
453 return nil, err
454 }
455 }
456 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700457 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700458}
459
Damien Neil162c1272018-10-04 12:42:37 -0700460func (f *File) location(path ...int32) Location {
461 return Location{
462 SourceFile: f.Desc.Path(),
463 Path: path,
464 }
465}
466
Damien Neil082ce922018-09-06 10:23:53 -0700467// goPackageOption interprets a file's go_package option.
468// If there is no go_package, it returns ("", "").
469// If there's a simple name, it returns (pkg, "").
470// If the option implies an import path, it returns (pkg, impPath).
471func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
472 opt := d.GetOptions().GetGoPackage()
473 if opt == "" {
474 return "", ""
475 }
476 // A semicolon-delimited suffix delimits the import path and package name.
477 if i := strings.Index(opt, ";"); i >= 0 {
478 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
479 }
480 // The presence of a slash implies there's an import path.
481 if i := strings.LastIndex(opt, "/"); i >= 0 {
482 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
483 }
484 return cleanPackageName(opt), ""
485}
486
Damien Neilc7d07d92018-08-22 13:46:02 -0700487// A Message describes a message.
488type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700489 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700490
Damien Neil993c04d2018-09-14 15:41:11 -0700491 GoIdent GoIdent // name of the generated Go type
492 Fields []*Field // message field declarations
493 Oneofs []*Oneof // oneof declarations
494 Messages []*Message // nested message declarations
495 Enums []*Enum // nested enum declarations
496 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700497 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700498}
499
Damien Neil1fa78d82018-09-13 13:12:36 -0700500func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700501 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700502 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700503 loc = parent.Location.appendPath(messageMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700504 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700505 loc = f.location(fileMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700506 }
Damien Neil46abb572018-09-07 12:45:37 -0700507 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700508 Desc: desc,
509 GoIdent: newGoIdent(f, desc),
510 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700511 }
Damien Neil658051b2018-09-10 12:26:21 -0700512 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700513 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700514 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700515 }
Damien Neil46abb572018-09-07 12:45:37 -0700516 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
517 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
518 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700519 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
520 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
521 }
Damien Neil658051b2018-09-10 12:26:21 -0700522 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700523 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700524 }
Damien Neil993c04d2018-09-14 15:41:11 -0700525 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
526 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
527 }
Damien Neil658051b2018-09-10 12:26:21 -0700528
529 // Field name conflict resolution.
530 //
531 // We assume well-known method names that may be attached to a generated
532 // message type, as well as a 'Get*' method for each field. For each
533 // field in turn, we add _s to its name until there are no conflicts.
534 //
535 // Any change to the following set of method names is a potential
536 // incompatible API change because it may change generated field names.
537 //
538 // TODO: If we ever support a 'go_name' option to set the Go name of a
539 // field, we should consider dropping this entirely. The conflict
540 // resolution algorithm is subtle and surprising (changing the order
541 // in which fields appear in the .proto source file can change the
542 // names of fields in generated code), and does not adapt well to
543 // adding new per-field methods such as setters.
544 usedNames := map[string]bool{
545 "Reset": true,
546 "String": true,
547 "ProtoMessage": true,
548 "Marshal": true,
549 "Unmarshal": true,
550 "ExtensionRangeArray": true,
551 "ExtensionMap": true,
552 "Descriptor": true,
553 }
554 makeNameUnique := func(name string) string {
555 for usedNames[name] || usedNames["Get"+name] {
556 name += "_"
557 }
558 usedNames[name] = true
559 usedNames["Get"+name] = true
560 return name
561 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700562 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700563 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700564 field.GoName = makeNameUnique(field.GoName)
565 if field.OneofType != nil {
566 if !seenOneofs[field.OneofType.Desc.Index()] {
567 // If this is a field in a oneof that we haven't seen before,
568 // make the name for that oneof unique as well.
569 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
570 seenOneofs[field.OneofType.Desc.Index()] = true
571 }
572 }
Damien Neil658051b2018-09-10 12:26:21 -0700573 }
574
Damien Neil1fa78d82018-09-13 13:12:36 -0700575 return message
Damien Neil658051b2018-09-10 12:26:21 -0700576}
577
Damien Neil0bd5a382018-09-13 15:07:10 -0700578func (message *Message) init(gen *Plugin) error {
579 for _, child := range message.Messages {
580 if err := child.init(gen); err != nil {
581 return err
582 }
583 }
584 for _, field := range message.Fields {
585 if err := field.init(gen); err != nil {
586 return err
587 }
588 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700589 for _, oneof := range message.Oneofs {
590 oneof.init(gen, message)
591 }
Damien Neil993c04d2018-09-14 15:41:11 -0700592 for _, extension := range message.Extensions {
593 if err := extension.init(gen); err != nil {
594 return err
595 }
596 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700597 return nil
598}
599
Damien Neil658051b2018-09-10 12:26:21 -0700600// A Field describes a message field.
601type Field struct {
602 Desc protoreflect.FieldDescriptor
603
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700605 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700606 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
607 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700608
Damien Neil993c04d2018-09-14 15:41:11 -0700609 ParentMessage *Message // message in which this field is defined; nil if top-level extension
610 ExtendedType *Message // extended message for extension fields; nil otherwise
611 MessageType *Message // type for message or group fields; nil otherwise
612 EnumType *Enum // type for enum fields; nil otherwise
613 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700614 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700615}
616
Damien Neil1fa78d82018-09-13 13:12:36 -0700617func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700618 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700619 switch {
620 case desc.ExtendedType() != nil && message == nil:
Damien Neil162c1272018-10-04 12:42:37 -0700621 loc = f.location(fileExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700622 case desc.ExtendedType() != nil && message != nil:
Damien Neil162c1272018-10-04 12:42:37 -0700623 loc = message.Location.appendPath(messageExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700624 default:
Damien Neil162c1272018-10-04 12:42:37 -0700625 loc = message.Location.appendPath(messageFieldField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700626 }
Damien Neil658051b2018-09-10 12:26:21 -0700627 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700628 Desc: desc,
629 GoName: camelCase(string(desc.Name())),
630 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700631 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700632 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700633 if desc.OneofType() != nil {
634 field.OneofType = message.Oneofs[desc.OneofType().Index()]
635 }
636 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700637}
638
Damien Neil993c04d2018-09-14 15:41:11 -0700639// Extension is an alias of Field for documentation.
640type Extension = Field
641
Damien Neil0bd5a382018-09-13 15:07:10 -0700642func (field *Field) init(gen *Plugin) error {
643 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700644 switch desc.Kind() {
645 case protoreflect.MessageKind, protoreflect.GroupKind:
646 mname := desc.MessageType().FullName()
647 message, ok := gen.messagesByName[mname]
648 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700649 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700650 }
651 field.MessageType = message
652 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700653 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700654 enum, ok := gen.enumsByName[ename]
655 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700656 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700657 }
658 field.EnumType = enum
659 }
Damien Neil993c04d2018-09-14 15:41:11 -0700660 if desc.ExtendedType() != nil {
661 mname := desc.ExtendedType().FullName()
662 message, ok := gen.messagesByName[mname]
663 if !ok {
664 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
665 }
666 field.ExtendedType = message
667 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700668 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700669}
670
Damien Neil1fa78d82018-09-13 13:12:36 -0700671// A Oneof describes a oneof field.
672type Oneof struct {
673 Desc protoreflect.OneofDescriptor
674
Damien Neil993c04d2018-09-14 15:41:11 -0700675 GoName string // Go field name of this oneof
676 ParentMessage *Message // message in which this oneof occurs
677 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700678 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700679}
680
681func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
682 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700683 Desc: desc,
684 ParentMessage: message,
685 GoName: camelCase(string(desc.Name())),
Damien Neil162c1272018-10-04 12:42:37 -0700686 Location: message.Location.appendPath(messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700687 }
688}
689
690func (oneof *Oneof) init(gen *Plugin, parent *Message) {
691 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
692 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
693 }
694}
695
Damien Neil46abb572018-09-07 12:45:37 -0700696// An Enum describes an enum.
697type Enum struct {
698 Desc protoreflect.EnumDescriptor
699
Damien Neil162c1272018-10-04 12:42:37 -0700700 GoIdent GoIdent // name of the generated Go type
701 Values []*EnumValue // enum values
702 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700703}
704
705func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700706 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700707 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700708 loc = parent.Location.appendPath(messageEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700709 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700710 loc = f.location(fileEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700711 }
712 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700713 Desc: desc,
714 GoIdent: newGoIdent(f, desc),
715 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700716 }
Damien Neil658051b2018-09-10 12:26:21 -0700717 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700718 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
719 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
720 }
721 return enum
722}
723
724// An EnumValue describes an enum value.
725type EnumValue struct {
726 Desc protoreflect.EnumValueDescriptor
727
Damien Neil162c1272018-10-04 12:42:37 -0700728 GoIdent GoIdent // name of the generated Go type
729 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700730}
731
732func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
733 // A top-level enum value's name is: EnumName_ValueName
734 // An enum value contained in a message is: MessageName_ValueName
735 //
736 // Enum value names are not camelcased.
737 parentIdent := enum.GoIdent
738 if message != nil {
739 parentIdent = message.GoIdent
740 }
741 name := parentIdent.GoName + "_" + string(desc.Name())
742 return &EnumValue{
743 Desc: desc,
744 GoIdent: GoIdent{
745 GoName: name,
746 GoImportPath: f.GoImportPath,
747 },
Damien Neil162c1272018-10-04 12:42:37 -0700748 Location: enum.Location.appendPath(enumValueField, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700749 }
Damien Neil220c2022018-08-15 11:24:18 -0700750}
751
752// A GeneratedFile is a generated file.
753type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700754 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700755 filename string
756 goImportPath GoImportPath
757 buf bytes.Buffer
758 packageNames map[GoImportPath]GoPackageName
759 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700760 manualImports map[GoImportPath]bool
Damien Neil162c1272018-10-04 12:42:37 -0700761 annotations map[string][]Location
Damien Neil220c2022018-08-15 11:24:18 -0700762}
763
Damien Neild9016772018-08-23 14:39:30 -0700764// NewGeneratedFile creates a new generated file with the given filename
765// and import path.
766func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700767 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700768 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700769 filename: filename,
770 goImportPath: goImportPath,
771 packageNames: make(map[GoImportPath]GoPackageName),
772 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700773 manualImports: make(map[GoImportPath]bool),
Damien Neil162c1272018-10-04 12:42:37 -0700774 annotations: make(map[string][]Location),
Damien Neil220c2022018-08-15 11:24:18 -0700775 }
776 gen.genFiles = append(gen.genFiles, g)
777 return g
778}
779
Damien Neil2dc67182018-09-21 15:03:34 -0700780// A Service describes a service.
781type Service struct {
782 Desc protoreflect.ServiceDescriptor
783
Damien Neil162c1272018-10-04 12:42:37 -0700784 GoName string
785 Location Location // location of this service
786 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700787}
788
789func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
790 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700791 Desc: desc,
792 GoName: camelCase(string(desc.Name())),
793 Location: f.location(fileServiceField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700794 }
795 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
796 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
797 }
798 return service
799}
800
801// A Method describes a method in a service.
802type Method struct {
803 Desc protoreflect.MethodDescriptor
804
805 GoName string
806 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700807 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700808 InputType *Message
809 OutputType *Message
810}
811
812func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
813 method := &Method{
814 Desc: desc,
815 GoName: camelCase(string(desc.Name())),
816 ParentService: service,
Damien Neil162c1272018-10-04 12:42:37 -0700817 Location: service.Location.appendPath(serviceMethodField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700818 }
819 return method
820}
821
822func (method *Method) init(gen *Plugin) error {
823 desc := method.Desc
824
825 inName := desc.InputType().FullName()
826 in, ok := gen.messagesByName[inName]
827 if !ok {
828 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
829 }
830 method.InputType = in
831
832 outName := desc.OutputType().FullName()
833 out, ok := gen.messagesByName[outName]
834 if !ok {
835 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
836 }
837 method.OutputType = out
838
839 return nil
840}
841
Damien Neil220c2022018-08-15 11:24:18 -0700842// P prints a line to the generated output. It converts each parameter to a
843// string following the same rules as fmt.Print. It never inserts spaces
844// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700845func (g *GeneratedFile) P(v ...interface{}) {
846 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700847 switch x := x.(type) {
848 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700849 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700850 default:
851 fmt.Fprint(&g.buf, x)
852 }
Damien Neil220c2022018-08-15 11:24:18 -0700853 }
854 fmt.Fprintln(&g.buf)
855}
856
Damien Neil46abb572018-09-07 12:45:37 -0700857// QualifiedGoIdent returns the string to use for a Go identifier.
858//
859// If the identifier is from a different Go package than the generated file,
860// the returned name will be qualified (package.name) and an import statement
861// for the identifier's package will be included in the file.
862func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
863 if ident.GoImportPath == g.goImportPath {
864 return ident.GoName
865 }
866 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
867 return string(packageName) + "." + ident.GoName
868 }
869 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700870 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700871 packageName = orig + GoPackageName(strconv.Itoa(i))
872 }
873 g.packageNames[ident.GoImportPath] = packageName
874 g.usedPackageNames[packageName] = true
875 return string(packageName) + "." + ident.GoName
876}
877
Damien Neil2e0c3da2018-09-19 12:51:36 -0700878// Import ensures a package is imported by the generated file.
879//
880// Packages referenced by QualifiedGoIdent are automatically imported.
881// Explicitly importing a package with Import is generally only necessary
882// when the import will be blank (import _ "package").
883func (g *GeneratedFile) Import(importPath GoImportPath) {
884 g.manualImports[importPath] = true
885}
886
Damien Neil220c2022018-08-15 11:24:18 -0700887// Write implements io.Writer.
888func (g *GeneratedFile) Write(p []byte) (n int, err error) {
889 return g.buf.Write(p)
890}
891
Damien Neil162c1272018-10-04 12:42:37 -0700892// Annotate associates a symbol in a generated Go file with a location in a
893// source .proto file.
894//
895// The symbol may refer to a type, constant, variable, function, method, or
896// struct field. The "T.sel" syntax is used to identify the method or field
897// 'sel' on type 'T'.
898func (g *GeneratedFile) Annotate(symbol string, loc Location) {
899 g.annotations[symbol] = append(g.annotations[symbol], loc)
900}
901
902// content returns the contents of the generated file.
903func (g *GeneratedFile) content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700904 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700905 return g.buf.Bytes(), nil
906 }
907
908 // Reformat generated code.
909 original := g.buf.Bytes()
910 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700911 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700912 if err != nil {
913 // Print out the bad code with line numbers.
914 // This should never happen in practice, but it can while changing generated code
915 // so consider this a debugging aid.
916 var src bytes.Buffer
917 s := bufio.NewScanner(bytes.NewReader(original))
918 for line := 1; s.Scan(); line++ {
919 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
920 }
Damien Neild9016772018-08-23 14:39:30 -0700921 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700922 }
Damien Neild9016772018-08-23 14:39:30 -0700923
924 // Add imports.
925 var importPaths []string
926 for importPath := range g.packageNames {
927 importPaths = append(importPaths, string(importPath))
928 }
929 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700930 rewriteImport := func(importPath string) string {
931 if f := g.gen.opts.ImportRewriteFunc; f != nil {
932 return string(f(GoImportPath(importPath)))
933 }
934 return importPath
935 }
Damien Neild9016772018-08-23 14:39:30 -0700936 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700937 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700938 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700939 for importPath := range g.manualImports {
940 if _, ok := g.packageNames[importPath]; ok {
941 continue
942 }
Damien Neil329b75e2018-10-04 17:31:07 -0700943 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700944 }
Damien Neil1ec33152018-09-13 13:12:36 -0700945 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700946
Damien Neilc7d07d92018-08-22 13:46:02 -0700947 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700948 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700949 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700950 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700951 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -0700952}
Damien Neilc7d07d92018-08-22 13:46:02 -0700953
Damien Neil162c1272018-10-04 12:42:37 -0700954// metaFile returns the contents of the file's metadata file, which is a
955// text formatted string of the google.protobuf.GeneratedCodeInfo.
956func (g *GeneratedFile) metaFile(content []byte) (string, error) {
957 fset := token.NewFileSet()
958 astFile, err := parser.ParseFile(fset, "", content, 0)
959 if err != nil {
960 return "", err
961 }
962 info := &descpb.GeneratedCodeInfo{}
963
964 seenAnnotations := make(map[string]bool)
965 annotate := func(s string, ident *ast.Ident) {
966 seenAnnotations[s] = true
967 for _, loc := range g.annotations[s] {
968 info.Annotation = append(info.Annotation, &descpb.GeneratedCodeInfo_Annotation{
969 SourceFile: proto.String(loc.SourceFile),
970 Path: loc.Path,
971 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
972 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
973 })
974 }
975 }
976 for _, decl := range astFile.Decls {
977 switch decl := decl.(type) {
978 case *ast.GenDecl:
979 for _, spec := range decl.Specs {
980 switch spec := spec.(type) {
981 case *ast.TypeSpec:
982 annotate(spec.Name.Name, spec.Name)
983 if st, ok := spec.Type.(*ast.StructType); ok {
984 for _, field := range st.Fields.List {
985 for _, name := range field.Names {
986 annotate(spec.Name.Name+"."+name.Name, name)
987 }
988 }
989 }
990 case *ast.ValueSpec:
991 for _, name := range spec.Names {
992 annotate(name.Name, name)
993 }
994 }
995 }
996 case *ast.FuncDecl:
997 if decl.Recv == nil {
998 annotate(decl.Name.Name, decl.Name)
999 } else {
1000 recv := decl.Recv.List[0].Type
1001 if s, ok := recv.(*ast.StarExpr); ok {
1002 recv = s.X
1003 }
1004 if id, ok := recv.(*ast.Ident); ok {
1005 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1006 }
1007 }
1008 }
1009 }
1010 for a := range g.annotations {
1011 if !seenAnnotations[a] {
1012 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1013 }
1014 }
1015
1016 return proto.CompactTextString(info), nil
Damien Neil220c2022018-08-15 11:24:18 -07001017}
Damien Neil082ce922018-09-06 10:23:53 -07001018
1019type pathType int
1020
1021const (
1022 pathTypeImport pathType = iota
1023 pathTypeSourceRelative
1024)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001025
1026// The SourceCodeInfo message describes the location of elements of a parsed
1027// .proto file by way of a "path", which is a sequence of integers that
1028// describe the route from a FileDescriptorProto to the relevant submessage.
1029// The path alternates between a field number of a repeated field, and an index
1030// into that repeated field. The constants below define the field numbers that
1031// are used.
1032//
1033// See descriptor.proto for more information about this.
1034const (
1035 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001036 filePackageField = 2 // package
1037 fileMessageField = 4 // message_type
1038 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -07001039 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -07001040 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -07001041 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001042 messageFieldField = 2 // field
1043 messageMessageField = 3 // nested_type
1044 messageEnumField = 4 // enum_type
1045 messageExtensionField = 6 // extension
1046 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -07001047 // field numbers in EnumDescriptorProto
1048 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -07001049 // field numbers in ServiceDescriptorProto
1050 serviceMethodField = 2 // method
1051 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -07001052)
1053
Damien Neil162c1272018-10-04 12:42:37 -07001054// A Location is a location in a .proto source file.
1055//
1056// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1057// for details.
1058type Location struct {
1059 SourceFile string
1060 Path []int32
1061}
1062
1063// appendPath add elements to a Location's path, returning a new Location.
1064func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001065 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001066 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001067 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001068 return Location{
1069 SourceFile: loc.SourceFile,
1070 Path: n,
1071 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001072}