blob: 95a499fc2fe705f11e768cc1b3e210c20c6c1241 [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"
Damien Neil220c2022018-08-15 11:24:18 -070022 "io/ioutil"
23 "os"
Damien Neil082ce922018-09-06 10:23:53 -070024 "path"
Damien Neil220c2022018-08-15 11:24:18 -070025 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070026 "sort"
27 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070028 "strings"
29
30 "github.com/golang/protobuf/proto"
Joe Tsai009e0672018-11-27 18:45:07 -080031 "github.com/golang/protobuf/v2/internal/scalar"
Joe Tsaie1f8d502018-11-26 18:55:29 -080032 "github.com/golang/protobuf/v2/reflect/protodesc"
Joe Tsai01ab2962018-09-21 17:44:00 -070033 "github.com/golang/protobuf/v2/reflect/protoreflect"
34 "github.com/golang/protobuf/v2/reflect/protoregistry"
Damien Neild9016772018-08-23 14:39:30 -070035 "golang.org/x/tools/go/ast/astutil"
Joe Tsaie1f8d502018-11-26 18:55:29 -080036
37 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
38 pluginpb "github.com/golang/protobuf/v2/types/plugin"
Damien Neil220c2022018-08-15 11:24:18 -070039)
40
41// Run executes a function as a protoc plugin.
42//
43// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
44// function, and writes a CodeGeneratorResponse message to os.Stdout.
45//
46// If a failure occurs while reading or writing, Run prints an error to
47// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070048//
49// Passing a nil options is equivalent to passing a zero-valued one.
50func Run(opts *Options, f func(*Plugin) error) {
51 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070052 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
53 os.Exit(1)
54 }
55}
56
Damien Neil3cf6e622018-09-11 13:53:14 -070057func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070058 if len(os.Args) > 1 {
59 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
60 }
Damien Neil220c2022018-08-15 11:24:18 -070061 in, err := ioutil.ReadAll(os.Stdin)
62 if err != nil {
63 return err
64 }
65 req := &pluginpb.CodeGeneratorRequest{}
66 if err := proto.Unmarshal(in, req); err != nil {
67 return err
68 }
Damien Neil3cf6e622018-09-11 13:53:14 -070069 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070070 if err != nil {
71 return err
72 }
73 if err := f(gen); err != nil {
74 // Errors from the plugin function are reported by setting the
75 // error field in the CodeGeneratorResponse.
76 //
77 // In contrast, errors that indicate a problem in protoc
78 // itself (unparsable input, I/O errors, etc.) are reported
79 // to stderr.
80 gen.Error(err)
81 }
82 resp := gen.Response()
83 out, err := proto.Marshal(resp)
84 if err != nil {
85 return err
86 }
87 if _, err := os.Stdout.Write(out); err != nil {
88 return err
89 }
90 return nil
91}
92
93// A Plugin is a protoc plugin invocation.
94type Plugin struct {
95 // Request is the CodeGeneratorRequest provided by protoc.
96 Request *pluginpb.CodeGeneratorRequest
97
98 // Files is the set of files to generate and everything they import.
99 // Files appear in topological order, so each file appears before any
100 // file that imports it.
101 Files []*File
102 filesByName map[string]*File
103
Damien Neil658051b2018-09-10 12:26:21 -0700104 fileReg *protoregistry.Files
105 messagesByName map[protoreflect.FullName]*Message
106 enumsByName map[protoreflect.FullName]*Enum
Damien Neil162c1272018-10-04 12:42:37 -0700107 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700108 pathType pathType
109 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700110 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700111 err error
Damien Neil220c2022018-08-15 11:24:18 -0700112}
113
Damien Neil3cf6e622018-09-11 13:53:14 -0700114// Options are optional parameters to New.
115type Options struct {
116 // If ParamFunc is non-nil, it will be called with each unknown
117 // generator parameter.
118 //
119 // Plugins for protoc can accept parameters from the command line,
120 // passed in the --<lang>_out protoc, separated from the output
121 // directory with a colon; e.g.,
122 //
123 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
124 //
125 // Parameters passed in this fashion as a comma-separated list of
126 // key=value pairs will be passed to the ParamFunc.
127 //
128 // The (flag.FlagSet).Set method matches this function signature,
129 // so parameters can be converted into flags as in the following:
130 //
131 // var flags flag.FlagSet
132 // value := flags.Bool("param", false, "")
133 // opts := &protogen.Options{
134 // ParamFunc: flags.Set,
135 // }
136 // protogen.Run(opts, func(p *protogen.Plugin) error {
137 // if *value { ... }
138 // })
139 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700140
141 // ImportRewriteFunc is called with the import path of each package
142 // imported by a generated file. It returns the import path to use
143 // for this package.
144 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700145}
146
Damien Neil220c2022018-08-15 11:24:18 -0700147// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700148//
149// Passing a nil Options is equivalent to passing a zero-valued one.
150func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
151 if opts == nil {
152 opts = &Options{}
153 }
Damien Neil220c2022018-08-15 11:24:18 -0700154 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700155 Request: req,
156 filesByName: make(map[string]*File),
157 fileReg: protoregistry.NewFiles(),
158 messagesByName: make(map[protoreflect.FullName]*Message),
159 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700160 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700161 }
162
Damien Neil082ce922018-09-06 10:23:53 -0700163 packageNames := make(map[string]GoPackageName) // filename -> package name
164 importPaths := make(map[string]GoImportPath) // filename -> import path
165 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700166 for _, param := range strings.Split(req.GetParameter(), ",") {
167 var value string
168 if i := strings.Index(param, "="); i >= 0 {
169 value = param[i+1:]
170 param = param[0:i]
171 }
172 switch param {
173 case "":
174 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700175 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700176 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700177 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700178 switch value {
179 case "import":
180 gen.pathType = pathTypeImport
181 case "source_relative":
182 gen.pathType = pathTypeSourceRelative
183 default:
184 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
185 }
Damien Neil220c2022018-08-15 11:24:18 -0700186 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700187 switch value {
188 case "true", "":
189 gen.annotateCode = true
190 case "false":
191 default:
192 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
193 }
Damien Neil220c2022018-08-15 11:24:18 -0700194 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700195 if param[0] == 'M' {
196 importPaths[param[1:]] = GoImportPath(value)
197 continue
Damien Neil220c2022018-08-15 11:24:18 -0700198 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700199 if opts.ParamFunc != nil {
200 if err := opts.ParamFunc(param, value); err != nil {
201 return nil, err
202 }
203 }
Damien Neil082ce922018-09-06 10:23:53 -0700204 }
205 }
206
207 // Figure out the import path and package name for each file.
208 //
209 // The rules here are complicated and have grown organically over time.
210 // Interactions between different ways of specifying package information
211 // may be surprising.
212 //
213 // The recommended approach is to include a go_package option in every
214 // .proto source file specifying the full import path of the Go package
215 // associated with this file.
216 //
217 // option go_package = "github.com/golang/protobuf/ptypes/any";
218 //
219 // Build systems which want to exert full control over import paths may
220 // specify M<filename>=<import_path> flags.
221 //
222 // Other approaches are not recommend.
223 generatedFileNames := make(map[string]bool)
224 for _, name := range gen.Request.FileToGenerate {
225 generatedFileNames[name] = true
226 }
227 // We need to determine the import paths before the package names,
228 // because the Go package name for a file is sometimes derived from
229 // different file in the same package.
230 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
231 for _, fdesc := range gen.Request.ProtoFile {
232 filename := fdesc.GetName()
233 packageName, importPath := goPackageOption(fdesc)
234 switch {
235 case importPaths[filename] != "":
236 // Command line: M=foo.proto=quux/bar
237 //
238 // Explicit mapping of source file to import path.
239 case generatedFileNames[filename] && packageImportPath != "":
240 // Command line: import_path=quux/bar
241 //
242 // The import_path flag sets the import path for every file that
243 // we generate code for.
244 importPaths[filename] = packageImportPath
245 case importPath != "":
246 // Source file: option go_package = "quux/bar";
247 //
248 // The go_package option sets the import path. Most users should use this.
249 importPaths[filename] = importPath
250 default:
251 // Source filename.
252 //
253 // Last resort when nothing else is available.
254 importPaths[filename] = GoImportPath(path.Dir(filename))
255 }
256 if packageName != "" {
257 packageNameForImportPath[importPaths[filename]] = packageName
258 }
259 }
260 for _, fdesc := range gen.Request.ProtoFile {
261 filename := fdesc.GetName()
262 packageName, _ := goPackageOption(fdesc)
263 defaultPackageName := packageNameForImportPath[importPaths[filename]]
264 switch {
265 case packageName != "":
266 // Source file: option go_package = "quux/bar";
267 packageNames[filename] = packageName
268 case defaultPackageName != "":
269 // A go_package option in another file in the same package.
270 //
271 // This is a poor choice in general, since every source file should
272 // contain a go_package option. Supported mainly for historical
273 // compatibility.
274 packageNames[filename] = defaultPackageName
275 case generatedFileNames[filename] && packageImportPath != "":
276 // Command line: import_path=quux/bar
277 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
278 case fdesc.GetPackage() != "":
279 // Source file: package quux.bar;
280 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
281 default:
282 // Source filename.
283 packageNames[filename] = cleanPackageName(baseName(filename))
284 }
285 }
286
287 // Consistency check: Every file with the same Go import path should have
288 // the same Go package name.
289 packageFiles := make(map[GoImportPath][]string)
290 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700291 if _, ok := packageNames[filename]; !ok {
292 // Skip files mentioned in a M<file>=<import_path> parameter
293 // but which do not appear in the CodeGeneratorRequest.
294 continue
295 }
Damien Neil082ce922018-09-06 10:23:53 -0700296 packageFiles[importPath] = append(packageFiles[importPath], filename)
297 }
298 for importPath, filenames := range packageFiles {
299 for i := 1; i < len(filenames); i++ {
300 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
301 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
302 importPath, a, filenames[0], b, filenames[i])
303 }
Damien Neil220c2022018-08-15 11:24:18 -0700304 }
305 }
306
307 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700308 filename := fdesc.GetName()
309 if gen.filesByName[filename] != nil {
310 return nil, fmt.Errorf("duplicate file name: %q", filename)
311 }
312 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700313 if err != nil {
314 return nil, err
315 }
Damien Neil220c2022018-08-15 11:24:18 -0700316 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700317 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700318 }
Damien Neil082ce922018-09-06 10:23:53 -0700319 for _, filename := range gen.Request.FileToGenerate {
320 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700321 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700322 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700323 }
324 f.Generate = true
325 }
326 return gen, nil
327}
328
329// Error records an error in code generation. The generator will report the
330// error back to protoc and will not produce output.
331func (gen *Plugin) Error(err error) {
332 if gen.err == nil {
333 gen.err = err
334 }
335}
336
337// Response returns the generator output.
338func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
339 resp := &pluginpb.CodeGeneratorResponse{}
340 if gen.err != nil {
Joe Tsai009e0672018-11-27 18:45:07 -0800341 resp.Error = scalar.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700342 return resp
343 }
Damien Neil162c1272018-10-04 12:42:37 -0700344 for _, g := range gen.genFiles {
345 content, err := g.content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700346 if err != nil {
347 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800348 Error: scalar.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700349 }
350 }
Damien Neil220c2022018-08-15 11:24:18 -0700351 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800352 Name: scalar.String(g.filename),
353 Content: scalar.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700354 })
Damien Neil162c1272018-10-04 12:42:37 -0700355 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
356 meta, err := g.metaFile(content)
357 if err != nil {
358 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800359 Error: scalar.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700360 }
361 }
362 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800363 Name: scalar.String(g.filename + ".meta"),
364 Content: scalar.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700365 })
366 }
Damien Neil220c2022018-08-15 11:24:18 -0700367 }
368 return resp
369}
370
371// FileByName returns the file with the given name.
372func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
373 f, ok = gen.filesByName[name]
374 return f, ok
375}
376
Damien Neilc7d07d92018-08-22 13:46:02 -0700377// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700378type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700379 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800380 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700381
Damien Neil082ce922018-09-06 10:23:53 -0700382 GoPackageName GoPackageName // name of this file's Go package
383 GoImportPath GoImportPath // import path of this file's Go package
384 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700385 Enums []*Enum // top-level enum declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700386 Extensions []*Extension // top-level extension declarations
Damien Neil2dc67182018-09-21 15:03:34 -0700387 Services []*Service // top-level service declarations
Damien Neil082ce922018-09-06 10:23:53 -0700388 Generate bool // true if we should generate code for this file
389
390 // GeneratedFilenamePrefix is used to construct filenames for generated
391 // files associated with this source file.
392 //
393 // For example, the source file "dir/foo.proto" might have a filename prefix
394 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
395 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700396
Joe Tsaie1f8d502018-11-26 18:55:29 -0800397 sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700398}
399
Joe Tsaie1f8d502018-11-26 18:55:29 -0800400func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
401 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700402 if err != nil {
403 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
404 }
405 if err := gen.fileReg.Register(desc); err != nil {
406 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
407 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700408 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700409 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700410 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700411 GoPackageName: packageName,
412 GoImportPath: importPath,
Joe Tsaie1f8d502018-11-26 18:55:29 -0800413 sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700414 }
Damien Neil082ce922018-09-06 10:23:53 -0700415
416 // Determine the prefix for generated Go files.
417 prefix := p.GetName()
418 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
419 prefix = prefix[:len(prefix)-len(ext)]
420 }
421 if gen.pathType == pathTypeImport {
422 // If paths=import (the default) and the file contains a go_package option
423 // with a full import path, the output filename is derived from the Go import
424 // path.
425 //
426 // Pass the paths=source_relative flag to always derive the output filename
427 // from the input filename instead.
428 if _, importPath := goPackageOption(p); importPath != "" {
429 prefix = path.Join(string(importPath), path.Base(prefix))
430 }
431 }
432 f.GeneratedFilenamePrefix = prefix
433
Damien Neilba1159f2018-10-17 12:53:18 -0700434 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
435 key := newPathKey(loc.Path)
436 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
437 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700438 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700439 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700440 }
Damien Neil46abb572018-09-07 12:45:37 -0700441 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
442 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
443 }
Damien Neil993c04d2018-09-14 15:41:11 -0700444 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
445 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
446 }
Damien Neil2dc67182018-09-21 15:03:34 -0700447 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
448 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
449 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700450 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700451 if err := message.init(gen); err != nil {
452 return nil, err
453 }
454 }
455 for _, extension := range f.Extensions {
456 if err := extension.init(gen); err != nil {
457 return nil, err
458 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700459 }
Damien Neil2dc67182018-09-21 15:03:34 -0700460 for _, service := range f.Services {
461 for _, method := range service.Methods {
462 if err := method.init(gen); err != nil {
463 return nil, err
464 }
465 }
466 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700467 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700468}
469
Damien Neil162c1272018-10-04 12:42:37 -0700470func (f *File) location(path ...int32) Location {
471 return Location{
472 SourceFile: f.Desc.Path(),
473 Path: path,
474 }
475}
476
Damien Neil082ce922018-09-06 10:23:53 -0700477// goPackageOption interprets a file's go_package option.
478// If there is no go_package, it returns ("", "").
479// If there's a simple name, it returns (pkg, "").
480// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800481func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700482 opt := d.GetOptions().GetGoPackage()
483 if opt == "" {
484 return "", ""
485 }
486 // A semicolon-delimited suffix delimits the import path and package name.
487 if i := strings.Index(opt, ";"); i >= 0 {
488 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
489 }
490 // The presence of a slash implies there's an import path.
491 if i := strings.LastIndex(opt, "/"); i >= 0 {
492 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
493 }
494 return cleanPackageName(opt), ""
495}
496
Damien Neilc7d07d92018-08-22 13:46:02 -0700497// A Message describes a message.
498type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700499 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700500
Damien Neil993c04d2018-09-14 15:41:11 -0700501 GoIdent GoIdent // name of the generated Go type
502 Fields []*Field // message field declarations
503 Oneofs []*Oneof // oneof declarations
504 Messages []*Message // nested message declarations
505 Enums []*Enum // nested enum declarations
506 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700507 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700508}
509
Damien Neil1fa78d82018-09-13 13:12:36 -0700510func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700511 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700512 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700513 loc = parent.Location.appendPath(messageMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700514 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700515 loc = f.location(fileMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700516 }
Damien Neil46abb572018-09-07 12:45:37 -0700517 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700518 Desc: desc,
519 GoIdent: newGoIdent(f, desc),
520 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700521 }
Damien Neil658051b2018-09-10 12:26:21 -0700522 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700523 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700524 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700525 }
Damien Neil46abb572018-09-07 12:45:37 -0700526 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
527 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
528 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700529 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
530 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
531 }
Damien Neil658051b2018-09-10 12:26:21 -0700532 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700533 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700534 }
Damien Neil993c04d2018-09-14 15:41:11 -0700535 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
536 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
537 }
Damien Neil658051b2018-09-10 12:26:21 -0700538
539 // Field name conflict resolution.
540 //
541 // We assume well-known method names that may be attached to a generated
542 // message type, as well as a 'Get*' method for each field. For each
543 // field in turn, we add _s to its name until there are no conflicts.
544 //
545 // Any change to the following set of method names is a potential
546 // incompatible API change because it may change generated field names.
547 //
548 // TODO: If we ever support a 'go_name' option to set the Go name of a
549 // field, we should consider dropping this entirely. The conflict
550 // resolution algorithm is subtle and surprising (changing the order
551 // in which fields appear in the .proto source file can change the
552 // names of fields in generated code), and does not adapt well to
553 // adding new per-field methods such as setters.
554 usedNames := map[string]bool{
555 "Reset": true,
556 "String": true,
557 "ProtoMessage": true,
558 "Marshal": true,
559 "Unmarshal": true,
560 "ExtensionRangeArray": true,
561 "ExtensionMap": true,
562 "Descriptor": true,
563 }
564 makeNameUnique := func(name string) string {
565 for usedNames[name] || usedNames["Get"+name] {
566 name += "_"
567 }
568 usedNames[name] = true
569 usedNames["Get"+name] = true
570 return name
571 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700572 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700573 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700574 field.GoName = makeNameUnique(field.GoName)
575 if field.OneofType != nil {
576 if !seenOneofs[field.OneofType.Desc.Index()] {
577 // If this is a field in a oneof that we haven't seen before,
578 // make the name for that oneof unique as well.
579 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
580 seenOneofs[field.OneofType.Desc.Index()] = true
581 }
582 }
Damien Neil658051b2018-09-10 12:26:21 -0700583 }
584
Damien Neil1fa78d82018-09-13 13:12:36 -0700585 return message
Damien Neil658051b2018-09-10 12:26:21 -0700586}
587
Damien Neil0bd5a382018-09-13 15:07:10 -0700588func (message *Message) init(gen *Plugin) error {
589 for _, child := range message.Messages {
590 if err := child.init(gen); err != nil {
591 return err
592 }
593 }
594 for _, field := range message.Fields {
595 if err := field.init(gen); err != nil {
596 return err
597 }
598 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700599 for _, oneof := range message.Oneofs {
600 oneof.init(gen, message)
601 }
Damien Neil993c04d2018-09-14 15:41:11 -0700602 for _, extension := range message.Extensions {
603 if err := extension.init(gen); err != nil {
604 return err
605 }
606 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700607 return nil
608}
609
Damien Neil658051b2018-09-10 12:26:21 -0700610// A Field describes a message field.
611type Field struct {
612 Desc protoreflect.FieldDescriptor
613
Damien Neil1fa78d82018-09-13 13:12:36 -0700614 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700615 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700616 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
617 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700618
Damien Neil993c04d2018-09-14 15:41:11 -0700619 ParentMessage *Message // message in which this field is defined; nil if top-level extension
620 ExtendedType *Message // extended message for extension fields; nil otherwise
621 MessageType *Message // type for message or group fields; nil otherwise
622 EnumType *Enum // type for enum fields; nil otherwise
623 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700624 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700625}
626
Damien Neil1fa78d82018-09-13 13:12:36 -0700627func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700628 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700629 switch {
630 case desc.ExtendedType() != nil && message == nil:
Damien Neil162c1272018-10-04 12:42:37 -0700631 loc = f.location(fileExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700632 case desc.ExtendedType() != nil && message != nil:
Damien Neil162c1272018-10-04 12:42:37 -0700633 loc = message.Location.appendPath(messageExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700634 default:
Damien Neil162c1272018-10-04 12:42:37 -0700635 loc = message.Location.appendPath(messageFieldField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700636 }
Damien Neil658051b2018-09-10 12:26:21 -0700637 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700638 Desc: desc,
639 GoName: camelCase(string(desc.Name())),
640 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700641 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700642 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700643 if desc.OneofType() != nil {
644 field.OneofType = message.Oneofs[desc.OneofType().Index()]
645 }
646 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700647}
648
Damien Neil993c04d2018-09-14 15:41:11 -0700649// Extension is an alias of Field for documentation.
650type Extension = Field
651
Damien Neil0bd5a382018-09-13 15:07:10 -0700652func (field *Field) init(gen *Plugin) error {
653 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700654 switch desc.Kind() {
655 case protoreflect.MessageKind, protoreflect.GroupKind:
656 mname := desc.MessageType().FullName()
657 message, ok := gen.messagesByName[mname]
658 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700659 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700660 }
661 field.MessageType = message
662 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700663 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700664 enum, ok := gen.enumsByName[ename]
665 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700666 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700667 }
668 field.EnumType = enum
669 }
Damien Neil993c04d2018-09-14 15:41:11 -0700670 if desc.ExtendedType() != nil {
671 mname := desc.ExtendedType().FullName()
672 message, ok := gen.messagesByName[mname]
673 if !ok {
674 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
675 }
676 field.ExtendedType = message
677 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700678 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700679}
680
Damien Neil1fa78d82018-09-13 13:12:36 -0700681// A Oneof describes a oneof field.
682type Oneof struct {
683 Desc protoreflect.OneofDescriptor
684
Damien Neil993c04d2018-09-14 15:41:11 -0700685 GoName string // Go field name of this oneof
686 ParentMessage *Message // message in which this oneof occurs
687 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700688 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700689}
690
691func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
692 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700693 Desc: desc,
694 ParentMessage: message,
695 GoName: camelCase(string(desc.Name())),
Damien Neil162c1272018-10-04 12:42:37 -0700696 Location: message.Location.appendPath(messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700697 }
698}
699
700func (oneof *Oneof) init(gen *Plugin, parent *Message) {
701 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
702 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
703 }
704}
705
Damien Neil46abb572018-09-07 12:45:37 -0700706// An Enum describes an enum.
707type Enum struct {
708 Desc protoreflect.EnumDescriptor
709
Damien Neil162c1272018-10-04 12:42:37 -0700710 GoIdent GoIdent // name of the generated Go type
711 Values []*EnumValue // enum values
712 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700713}
714
715func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700716 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700717 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700718 loc = parent.Location.appendPath(messageEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700719 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700720 loc = f.location(fileEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700721 }
722 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700723 Desc: desc,
724 GoIdent: newGoIdent(f, desc),
725 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700726 }
Damien Neil658051b2018-09-10 12:26:21 -0700727 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700728 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
729 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
730 }
731 return enum
732}
733
734// An EnumValue describes an enum value.
735type EnumValue struct {
736 Desc protoreflect.EnumValueDescriptor
737
Damien Neil162c1272018-10-04 12:42:37 -0700738 GoIdent GoIdent // name of the generated Go type
739 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700740}
741
742func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
743 // A top-level enum value's name is: EnumName_ValueName
744 // An enum value contained in a message is: MessageName_ValueName
745 //
746 // Enum value names are not camelcased.
747 parentIdent := enum.GoIdent
748 if message != nil {
749 parentIdent = message.GoIdent
750 }
751 name := parentIdent.GoName + "_" + string(desc.Name())
752 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800753 Desc: desc,
754 GoIdent: f.GoImportPath.Ident(name),
Damien Neil162c1272018-10-04 12:42:37 -0700755 Location: enum.Location.appendPath(enumValueField, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700756 }
Damien Neil220c2022018-08-15 11:24:18 -0700757}
758
759// A GeneratedFile is a generated file.
760type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700761 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700762 filename string
763 goImportPath GoImportPath
764 buf bytes.Buffer
765 packageNames map[GoImportPath]GoPackageName
766 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700767 manualImports map[GoImportPath]bool
Damien Neil162c1272018-10-04 12:42:37 -0700768 annotations map[string][]Location
Damien Neil220c2022018-08-15 11:24:18 -0700769}
770
Damien Neild9016772018-08-23 14:39:30 -0700771// NewGeneratedFile creates a new generated file with the given filename
772// and import path.
773func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700774 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700775 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700776 filename: filename,
777 goImportPath: goImportPath,
778 packageNames: make(map[GoImportPath]GoPackageName),
779 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700780 manualImports: make(map[GoImportPath]bool),
Damien Neil162c1272018-10-04 12:42:37 -0700781 annotations: make(map[string][]Location),
Damien Neil220c2022018-08-15 11:24:18 -0700782 }
783 gen.genFiles = append(gen.genFiles, g)
784 return g
785}
786
Damien Neil2dc67182018-09-21 15:03:34 -0700787// A Service describes a service.
788type Service struct {
789 Desc protoreflect.ServiceDescriptor
790
Damien Neil162c1272018-10-04 12:42:37 -0700791 GoName string
792 Location Location // location of this service
793 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700794}
795
796func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
797 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700798 Desc: desc,
799 GoName: camelCase(string(desc.Name())),
800 Location: f.location(fileServiceField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700801 }
802 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
803 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
804 }
805 return service
806}
807
808// A Method describes a method in a service.
809type Method struct {
810 Desc protoreflect.MethodDescriptor
811
812 GoName string
813 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700814 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700815 InputType *Message
816 OutputType *Message
817}
818
819func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
820 method := &Method{
821 Desc: desc,
822 GoName: camelCase(string(desc.Name())),
823 ParentService: service,
Damien Neil162c1272018-10-04 12:42:37 -0700824 Location: service.Location.appendPath(serviceMethodField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700825 }
826 return method
827}
828
829func (method *Method) init(gen *Plugin) error {
830 desc := method.Desc
831
832 inName := desc.InputType().FullName()
833 in, ok := gen.messagesByName[inName]
834 if !ok {
835 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
836 }
837 method.InputType = in
838
839 outName := desc.OutputType().FullName()
840 out, ok := gen.messagesByName[outName]
841 if !ok {
842 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
843 }
844 method.OutputType = out
845
846 return nil
847}
848
Damien Neil220c2022018-08-15 11:24:18 -0700849// P prints a line to the generated output. It converts each parameter to a
850// string following the same rules as fmt.Print. It never inserts spaces
851// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700852func (g *GeneratedFile) P(v ...interface{}) {
853 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700854 switch x := x.(type) {
855 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700856 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700857 default:
858 fmt.Fprint(&g.buf, x)
859 }
Damien Neil220c2022018-08-15 11:24:18 -0700860 }
861 fmt.Fprintln(&g.buf)
862}
863
Damien Neilba1159f2018-10-17 12:53:18 -0700864// PrintLeadingComments writes the comment appearing before a location in
865// the .proto source to the generated file.
866//
867// It returns true if a comment was present at the location.
868func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
869 f := g.gen.filesByName[loc.SourceFile]
870 if f == nil {
871 return false
872 }
873 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
874 if infoLoc.LeadingComments == nil {
875 continue
876 }
877 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
878 g.buf.WriteString("//")
879 g.buf.WriteString(line)
880 g.buf.WriteString("\n")
881 }
882 return true
883 }
884 return false
885}
886
Damien Neil46abb572018-09-07 12:45:37 -0700887// QualifiedGoIdent returns the string to use for a Go identifier.
888//
889// If the identifier is from a different Go package than the generated file,
890// the returned name will be qualified (package.name) and an import statement
891// for the identifier's package will be included in the file.
892func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
893 if ident.GoImportPath == g.goImportPath {
894 return ident.GoName
895 }
896 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
897 return string(packageName) + "." + ident.GoName
898 }
899 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700900 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700901 packageName = orig + GoPackageName(strconv.Itoa(i))
902 }
903 g.packageNames[ident.GoImportPath] = packageName
904 g.usedPackageNames[packageName] = true
905 return string(packageName) + "." + ident.GoName
906}
907
Damien Neil2e0c3da2018-09-19 12:51:36 -0700908// Import ensures a package is imported by the generated file.
909//
910// Packages referenced by QualifiedGoIdent are automatically imported.
911// Explicitly importing a package with Import is generally only necessary
912// when the import will be blank (import _ "package").
913func (g *GeneratedFile) Import(importPath GoImportPath) {
914 g.manualImports[importPath] = true
915}
916
Damien Neil220c2022018-08-15 11:24:18 -0700917// Write implements io.Writer.
918func (g *GeneratedFile) Write(p []byte) (n int, err error) {
919 return g.buf.Write(p)
920}
921
Damien Neil162c1272018-10-04 12:42:37 -0700922// Annotate associates a symbol in a generated Go file with a location in a
923// source .proto file.
924//
925// The symbol may refer to a type, constant, variable, function, method, or
926// struct field. The "T.sel" syntax is used to identify the method or field
927// 'sel' on type 'T'.
928func (g *GeneratedFile) Annotate(symbol string, loc Location) {
929 g.annotations[symbol] = append(g.annotations[symbol], loc)
930}
931
932// content returns the contents of the generated file.
933func (g *GeneratedFile) content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700934 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700935 return g.buf.Bytes(), nil
936 }
937
938 // Reformat generated code.
939 original := g.buf.Bytes()
940 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700941 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700942 if err != nil {
943 // Print out the bad code with line numbers.
944 // This should never happen in practice, but it can while changing generated code
945 // so consider this a debugging aid.
946 var src bytes.Buffer
947 s := bufio.NewScanner(bytes.NewReader(original))
948 for line := 1; s.Scan(); line++ {
949 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
950 }
Damien Neild9016772018-08-23 14:39:30 -0700951 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700952 }
Damien Neild9016772018-08-23 14:39:30 -0700953
954 // Add imports.
955 var importPaths []string
956 for importPath := range g.packageNames {
957 importPaths = append(importPaths, string(importPath))
958 }
959 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700960 rewriteImport := func(importPath string) string {
961 if f := g.gen.opts.ImportRewriteFunc; f != nil {
962 return string(f(GoImportPath(importPath)))
963 }
964 return importPath
965 }
Damien Neild9016772018-08-23 14:39:30 -0700966 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700967 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700968 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700969 for importPath := range g.manualImports {
970 if _, ok := g.packageNames[importPath]; ok {
971 continue
972 }
Damien Neil329b75e2018-10-04 17:31:07 -0700973 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700974 }
Damien Neil1ec33152018-09-13 13:12:36 -0700975 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700976
Damien Neilc7d07d92018-08-22 13:46:02 -0700977 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700978 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700979 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700980 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700981 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -0700982}
Damien Neilc7d07d92018-08-22 13:46:02 -0700983
Damien Neil162c1272018-10-04 12:42:37 -0700984// metaFile returns the contents of the file's metadata file, which is a
985// text formatted string of the google.protobuf.GeneratedCodeInfo.
986func (g *GeneratedFile) metaFile(content []byte) (string, error) {
987 fset := token.NewFileSet()
988 astFile, err := parser.ParseFile(fset, "", content, 0)
989 if err != nil {
990 return "", err
991 }
Joe Tsaie1f8d502018-11-26 18:55:29 -0800992 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -0700993
994 seenAnnotations := make(map[string]bool)
995 annotate := func(s string, ident *ast.Ident) {
996 seenAnnotations[s] = true
997 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800998 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Joe Tsai009e0672018-11-27 18:45:07 -0800999 SourceFile: scalar.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001000 Path: loc.Path,
Joe Tsai009e0672018-11-27 18:45:07 -08001001 Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
1002 End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001003 })
1004 }
1005 }
1006 for _, decl := range astFile.Decls {
1007 switch decl := decl.(type) {
1008 case *ast.GenDecl:
1009 for _, spec := range decl.Specs {
1010 switch spec := spec.(type) {
1011 case *ast.TypeSpec:
1012 annotate(spec.Name.Name, spec.Name)
1013 if st, ok := spec.Type.(*ast.StructType); ok {
1014 for _, field := range st.Fields.List {
1015 for _, name := range field.Names {
1016 annotate(spec.Name.Name+"."+name.Name, name)
1017 }
1018 }
1019 }
1020 case *ast.ValueSpec:
1021 for _, name := range spec.Names {
1022 annotate(name.Name, name)
1023 }
1024 }
1025 }
1026 case *ast.FuncDecl:
1027 if decl.Recv == nil {
1028 annotate(decl.Name.Name, decl.Name)
1029 } else {
1030 recv := decl.Recv.List[0].Type
1031 if s, ok := recv.(*ast.StarExpr); ok {
1032 recv = s.X
1033 }
1034 if id, ok := recv.(*ast.Ident); ok {
1035 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1036 }
1037 }
1038 }
1039 }
1040 for a := range g.annotations {
1041 if !seenAnnotations[a] {
1042 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1043 }
1044 }
1045
1046 return proto.CompactTextString(info), nil
Damien Neil220c2022018-08-15 11:24:18 -07001047}
Damien Neil082ce922018-09-06 10:23:53 -07001048
1049type pathType int
1050
1051const (
1052 pathTypeImport pathType = iota
1053 pathTypeSourceRelative
1054)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001055
1056// The SourceCodeInfo message describes the location of elements of a parsed
1057// .proto file by way of a "path", which is a sequence of integers that
1058// describe the route from a FileDescriptorProto to the relevant submessage.
1059// The path alternates between a field number of a repeated field, and an index
1060// into that repeated field. The constants below define the field numbers that
1061// are used.
1062//
1063// See descriptor.proto for more information about this.
1064const (
1065 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001066 filePackageField = 2 // package
1067 fileMessageField = 4 // message_type
1068 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -07001069 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -07001070 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -07001071 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001072 messageFieldField = 2 // field
1073 messageMessageField = 3 // nested_type
1074 messageEnumField = 4 // enum_type
1075 messageExtensionField = 6 // extension
1076 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -07001077 // field numbers in EnumDescriptorProto
1078 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -07001079 // field numbers in ServiceDescriptorProto
1080 serviceMethodField = 2 // method
1081 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -07001082)
1083
Damien Neil162c1272018-10-04 12:42:37 -07001084// A Location is a location in a .proto source file.
1085//
1086// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1087// for details.
1088type Location struct {
1089 SourceFile string
1090 Path []int32
1091}
1092
1093// appendPath add elements to a Location's path, returning a new Location.
1094func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001095 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001096 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001097 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001098 return Location{
1099 SourceFile: loc.SourceFile,
1100 Path: n,
1101 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001102}
Damien Neilba1159f2018-10-17 12:53:18 -07001103
1104// A pathKey is a representation of a location path suitable for use as a map key.
1105type pathKey struct {
1106 s string
1107}
1108
1109// newPathKey converts a location path to a pathKey.
1110func newPathKey(path []int32) pathKey {
1111 buf := make([]byte, 4*len(path))
1112 for i, x := range path {
1113 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1114 }
1115 return pathKey{string(buf)}
1116}