blob: cdfccceb37a2770a67834a4f63135f63863b30d4 [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
Joe Tsaib6405bd2018-11-15 14:44:37 -0800382 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
383 GoPackageName GoPackageName // name of this file's Go package
384 GoImportPath GoImportPath // import path of this file's Go package
385 Messages []*Message // top-level message declarations
386 Enums []*Enum // top-level enum declarations
387 Extensions []*Extension // top-level extension declarations
388 Services []*Service // top-level service declarations
389 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700390
391 // GeneratedFilenamePrefix is used to construct filenames for generated
392 // files associated with this source file.
393 //
394 // For example, the source file "dir/foo.proto" might have a filename prefix
395 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
396 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700397
Joe Tsaie1f8d502018-11-26 18:55:29 -0800398 sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700399}
400
Joe Tsaie1f8d502018-11-26 18:55:29 -0800401func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
402 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700403 if err != nil {
404 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
405 }
406 if err := gen.fileReg.Register(desc); err != nil {
407 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
408 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700409 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700410 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700411 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700412 GoPackageName: packageName,
413 GoImportPath: importPath,
Joe Tsaie1f8d502018-11-26 18:55:29 -0800414 sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700415 }
Damien Neil082ce922018-09-06 10:23:53 -0700416
417 // Determine the prefix for generated Go files.
418 prefix := p.GetName()
419 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
420 prefix = prefix[:len(prefix)-len(ext)]
421 }
422 if gen.pathType == pathTypeImport {
423 // If paths=import (the default) and the file contains a go_package option
424 // with a full import path, the output filename is derived from the Go import
425 // path.
426 //
427 // Pass the paths=source_relative flag to always derive the output filename
428 // from the input filename instead.
429 if _, importPath := goPackageOption(p); importPath != "" {
430 prefix = path.Join(string(importPath), path.Base(prefix))
431 }
432 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800433 f.GoDescriptorIdent = GoIdent{
434 GoName: camelCase(cleanGoName(path.Base(prefix), true)) + "_ProtoFile",
435 GoImportPath: f.GoImportPath,
436 }
Damien Neil082ce922018-09-06 10:23:53 -0700437 f.GeneratedFilenamePrefix = prefix
438
Damien Neilba1159f2018-10-17 12:53:18 -0700439 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
440 key := newPathKey(loc.Path)
441 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
442 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700443 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700444 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700445 }
Damien Neil46abb572018-09-07 12:45:37 -0700446 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
447 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
448 }
Damien Neil993c04d2018-09-14 15:41:11 -0700449 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
450 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
451 }
Damien Neil2dc67182018-09-21 15:03:34 -0700452 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
453 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
454 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700455 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700456 if err := message.init(gen); err != nil {
457 return nil, err
458 }
459 }
460 for _, extension := range f.Extensions {
461 if err := extension.init(gen); err != nil {
462 return nil, err
463 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700464 }
Damien Neil2dc67182018-09-21 15:03:34 -0700465 for _, service := range f.Services {
466 for _, method := range service.Methods {
467 if err := method.init(gen); err != nil {
468 return nil, err
469 }
470 }
471 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700472 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700473}
474
Damien Neil162c1272018-10-04 12:42:37 -0700475func (f *File) location(path ...int32) Location {
476 return Location{
477 SourceFile: f.Desc.Path(),
478 Path: path,
479 }
480}
481
Damien Neil082ce922018-09-06 10:23:53 -0700482// goPackageOption interprets a file's go_package option.
483// If there is no go_package, it returns ("", "").
484// If there's a simple name, it returns (pkg, "").
485// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800486func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700487 opt := d.GetOptions().GetGoPackage()
488 if opt == "" {
489 return "", ""
490 }
491 // A semicolon-delimited suffix delimits the import path and package name.
492 if i := strings.Index(opt, ";"); i >= 0 {
493 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
494 }
495 // The presence of a slash implies there's an import path.
496 if i := strings.LastIndex(opt, "/"); i >= 0 {
497 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
498 }
499 return cleanPackageName(opt), ""
500}
501
Damien Neilc7d07d92018-08-22 13:46:02 -0700502// A Message describes a message.
503type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700504 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700505
Damien Neil993c04d2018-09-14 15:41:11 -0700506 GoIdent GoIdent // name of the generated Go type
507 Fields []*Field // message field declarations
508 Oneofs []*Oneof // oneof declarations
509 Messages []*Message // nested message declarations
510 Enums []*Enum // nested enum declarations
511 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700512 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700513}
514
Damien Neil1fa78d82018-09-13 13:12:36 -0700515func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700516 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700517 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700518 loc = parent.Location.appendPath(messageMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700519 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700520 loc = f.location(fileMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700521 }
Damien Neil46abb572018-09-07 12:45:37 -0700522 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700523 Desc: desc,
524 GoIdent: newGoIdent(f, desc),
525 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700526 }
Damien Neil658051b2018-09-10 12:26:21 -0700527 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700528 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700529 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700530 }
Damien Neil46abb572018-09-07 12:45:37 -0700531 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
532 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
533 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700534 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
535 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
536 }
Damien Neil658051b2018-09-10 12:26:21 -0700537 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700538 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700539 }
Damien Neil993c04d2018-09-14 15:41:11 -0700540 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
541 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
542 }
Damien Neil658051b2018-09-10 12:26:21 -0700543
544 // Field name conflict resolution.
545 //
546 // We assume well-known method names that may be attached to a generated
547 // message type, as well as a 'Get*' method for each field. For each
548 // field in turn, we add _s to its name until there are no conflicts.
549 //
550 // Any change to the following set of method names is a potential
551 // incompatible API change because it may change generated field names.
552 //
553 // TODO: If we ever support a 'go_name' option to set the Go name of a
554 // field, we should consider dropping this entirely. The conflict
555 // resolution algorithm is subtle and surprising (changing the order
556 // in which fields appear in the .proto source file can change the
557 // names of fields in generated code), and does not adapt well to
558 // adding new per-field methods such as setters.
559 usedNames := map[string]bool{
560 "Reset": true,
561 "String": true,
562 "ProtoMessage": true,
563 "Marshal": true,
564 "Unmarshal": true,
565 "ExtensionRangeArray": true,
566 "ExtensionMap": true,
567 "Descriptor": true,
568 }
569 makeNameUnique := func(name string) string {
570 for usedNames[name] || usedNames["Get"+name] {
571 name += "_"
572 }
573 usedNames[name] = true
574 usedNames["Get"+name] = true
575 return name
576 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700577 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700578 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700579 field.GoName = makeNameUnique(field.GoName)
580 if field.OneofType != nil {
581 if !seenOneofs[field.OneofType.Desc.Index()] {
582 // If this is a field in a oneof that we haven't seen before,
583 // make the name for that oneof unique as well.
584 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
585 seenOneofs[field.OneofType.Desc.Index()] = true
586 }
587 }
Damien Neil658051b2018-09-10 12:26:21 -0700588 }
589
Damien Neil1fa78d82018-09-13 13:12:36 -0700590 return message
Damien Neil658051b2018-09-10 12:26:21 -0700591}
592
Damien Neil0bd5a382018-09-13 15:07:10 -0700593func (message *Message) init(gen *Plugin) error {
594 for _, child := range message.Messages {
595 if err := child.init(gen); err != nil {
596 return err
597 }
598 }
599 for _, field := range message.Fields {
600 if err := field.init(gen); err != nil {
601 return err
602 }
603 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700604 for _, oneof := range message.Oneofs {
605 oneof.init(gen, message)
606 }
Damien Neil993c04d2018-09-14 15:41:11 -0700607 for _, extension := range message.Extensions {
608 if err := extension.init(gen); err != nil {
609 return err
610 }
611 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700612 return nil
613}
614
Damien Neil658051b2018-09-10 12:26:21 -0700615// A Field describes a message field.
616type Field struct {
617 Desc protoreflect.FieldDescriptor
618
Damien Neil1fa78d82018-09-13 13:12:36 -0700619 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700620 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700621 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
622 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700623
Damien Neil993c04d2018-09-14 15:41:11 -0700624 ParentMessage *Message // message in which this field is defined; nil if top-level extension
625 ExtendedType *Message // extended message for extension fields; nil otherwise
626 MessageType *Message // type for message or group fields; nil otherwise
627 EnumType *Enum // type for enum fields; nil otherwise
628 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700629 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700630}
631
Damien Neil1fa78d82018-09-13 13:12:36 -0700632func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700633 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700634 switch {
635 case desc.ExtendedType() != nil && message == nil:
Damien Neil162c1272018-10-04 12:42:37 -0700636 loc = f.location(fileExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700637 case desc.ExtendedType() != nil && message != nil:
Damien Neil162c1272018-10-04 12:42:37 -0700638 loc = message.Location.appendPath(messageExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700639 default:
Damien Neil162c1272018-10-04 12:42:37 -0700640 loc = message.Location.appendPath(messageFieldField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700641 }
Damien Neil658051b2018-09-10 12:26:21 -0700642 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700643 Desc: desc,
644 GoName: camelCase(string(desc.Name())),
645 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700646 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700647 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700648 if desc.OneofType() != nil {
649 field.OneofType = message.Oneofs[desc.OneofType().Index()]
650 }
651 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700652}
653
Damien Neil993c04d2018-09-14 15:41:11 -0700654// Extension is an alias of Field for documentation.
655type Extension = Field
656
Damien Neil0bd5a382018-09-13 15:07:10 -0700657func (field *Field) init(gen *Plugin) error {
658 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700659 switch desc.Kind() {
660 case protoreflect.MessageKind, protoreflect.GroupKind:
661 mname := desc.MessageType().FullName()
662 message, ok := gen.messagesByName[mname]
663 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700664 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700665 }
666 field.MessageType = message
667 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700668 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700669 enum, ok := gen.enumsByName[ename]
670 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700671 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700672 }
673 field.EnumType = enum
674 }
Damien Neil993c04d2018-09-14 15:41:11 -0700675 if desc.ExtendedType() != nil {
676 mname := desc.ExtendedType().FullName()
677 message, ok := gen.messagesByName[mname]
678 if !ok {
679 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
680 }
681 field.ExtendedType = message
682 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700683 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700684}
685
Damien Neil1fa78d82018-09-13 13:12:36 -0700686// A Oneof describes a oneof field.
687type Oneof struct {
688 Desc protoreflect.OneofDescriptor
689
Damien Neil993c04d2018-09-14 15:41:11 -0700690 GoName string // Go field name of this oneof
691 ParentMessage *Message // message in which this oneof occurs
692 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700693 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700694}
695
696func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
697 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700698 Desc: desc,
699 ParentMessage: message,
700 GoName: camelCase(string(desc.Name())),
Damien Neil162c1272018-10-04 12:42:37 -0700701 Location: message.Location.appendPath(messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700702 }
703}
704
705func (oneof *Oneof) init(gen *Plugin, parent *Message) {
706 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
707 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
708 }
709}
710
Damien Neil46abb572018-09-07 12:45:37 -0700711// An Enum describes an enum.
712type Enum struct {
713 Desc protoreflect.EnumDescriptor
714
Damien Neil162c1272018-10-04 12:42:37 -0700715 GoIdent GoIdent // name of the generated Go type
716 Values []*EnumValue // enum values
717 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700718}
719
720func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700721 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700722 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700723 loc = parent.Location.appendPath(messageEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700724 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700725 loc = f.location(fileEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700726 }
727 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700728 Desc: desc,
729 GoIdent: newGoIdent(f, desc),
730 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700731 }
Damien Neil658051b2018-09-10 12:26:21 -0700732 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700733 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
734 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
735 }
736 return enum
737}
738
739// An EnumValue describes an enum value.
740type EnumValue struct {
741 Desc protoreflect.EnumValueDescriptor
742
Damien Neil162c1272018-10-04 12:42:37 -0700743 GoIdent GoIdent // name of the generated Go type
744 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700745}
746
747func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
748 // A top-level enum value's name is: EnumName_ValueName
749 // An enum value contained in a message is: MessageName_ValueName
750 //
751 // Enum value names are not camelcased.
752 parentIdent := enum.GoIdent
753 if message != nil {
754 parentIdent = message.GoIdent
755 }
756 name := parentIdent.GoName + "_" + string(desc.Name())
757 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800758 Desc: desc,
759 GoIdent: f.GoImportPath.Ident(name),
Damien Neil162c1272018-10-04 12:42:37 -0700760 Location: enum.Location.appendPath(enumValueField, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700761 }
Damien Neil220c2022018-08-15 11:24:18 -0700762}
763
764// A GeneratedFile is a generated file.
765type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700766 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700767 filename string
768 goImportPath GoImportPath
769 buf bytes.Buffer
770 packageNames map[GoImportPath]GoPackageName
771 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700772 manualImports map[GoImportPath]bool
Damien Neil162c1272018-10-04 12:42:37 -0700773 annotations map[string][]Location
Damien Neil220c2022018-08-15 11:24:18 -0700774}
775
Damien Neild9016772018-08-23 14:39:30 -0700776// NewGeneratedFile creates a new generated file with the given filename
777// and import path.
778func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700779 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700780 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700781 filename: filename,
782 goImportPath: goImportPath,
783 packageNames: make(map[GoImportPath]GoPackageName),
784 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700785 manualImports: make(map[GoImportPath]bool),
Damien Neil162c1272018-10-04 12:42:37 -0700786 annotations: make(map[string][]Location),
Damien Neil220c2022018-08-15 11:24:18 -0700787 }
788 gen.genFiles = append(gen.genFiles, g)
789 return g
790}
791
Damien Neil2dc67182018-09-21 15:03:34 -0700792// A Service describes a service.
793type Service struct {
794 Desc protoreflect.ServiceDescriptor
795
Damien Neil162c1272018-10-04 12:42:37 -0700796 GoName string
797 Location Location // location of this service
798 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700799}
800
801func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
802 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700803 Desc: desc,
804 GoName: camelCase(string(desc.Name())),
805 Location: f.location(fileServiceField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700806 }
807 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
808 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
809 }
810 return service
811}
812
813// A Method describes a method in a service.
814type Method struct {
815 Desc protoreflect.MethodDescriptor
816
817 GoName string
818 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700819 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700820 InputType *Message
821 OutputType *Message
822}
823
824func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
825 method := &Method{
826 Desc: desc,
827 GoName: camelCase(string(desc.Name())),
828 ParentService: service,
Damien Neil162c1272018-10-04 12:42:37 -0700829 Location: service.Location.appendPath(serviceMethodField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700830 }
831 return method
832}
833
834func (method *Method) init(gen *Plugin) error {
835 desc := method.Desc
836
837 inName := desc.InputType().FullName()
838 in, ok := gen.messagesByName[inName]
839 if !ok {
840 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
841 }
842 method.InputType = in
843
844 outName := desc.OutputType().FullName()
845 out, ok := gen.messagesByName[outName]
846 if !ok {
847 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
848 }
849 method.OutputType = out
850
851 return nil
852}
853
Damien Neil220c2022018-08-15 11:24:18 -0700854// P prints a line to the generated output. It converts each parameter to a
855// string following the same rules as fmt.Print. It never inserts spaces
856// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700857func (g *GeneratedFile) P(v ...interface{}) {
858 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700859 switch x := x.(type) {
860 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700861 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700862 default:
863 fmt.Fprint(&g.buf, x)
864 }
Damien Neil220c2022018-08-15 11:24:18 -0700865 }
866 fmt.Fprintln(&g.buf)
867}
868
Damien Neilba1159f2018-10-17 12:53:18 -0700869// PrintLeadingComments writes the comment appearing before a location in
870// the .proto source to the generated file.
871//
872// It returns true if a comment was present at the location.
873func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
874 f := g.gen.filesByName[loc.SourceFile]
875 if f == nil {
876 return false
877 }
878 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
879 if infoLoc.LeadingComments == nil {
880 continue
881 }
882 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
883 g.buf.WriteString("//")
884 g.buf.WriteString(line)
885 g.buf.WriteString("\n")
886 }
887 return true
888 }
889 return false
890}
891
Damien Neil46abb572018-09-07 12:45:37 -0700892// QualifiedGoIdent returns the string to use for a Go identifier.
893//
894// If the identifier is from a different Go package than the generated file,
895// the returned name will be qualified (package.name) and an import statement
896// for the identifier's package will be included in the file.
897func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
898 if ident.GoImportPath == g.goImportPath {
899 return ident.GoName
900 }
901 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
902 return string(packageName) + "." + ident.GoName
903 }
904 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700905 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700906 packageName = orig + GoPackageName(strconv.Itoa(i))
907 }
908 g.packageNames[ident.GoImportPath] = packageName
909 g.usedPackageNames[packageName] = true
910 return string(packageName) + "." + ident.GoName
911}
912
Damien Neil2e0c3da2018-09-19 12:51:36 -0700913// Import ensures a package is imported by the generated file.
914//
915// Packages referenced by QualifiedGoIdent are automatically imported.
916// Explicitly importing a package with Import is generally only necessary
917// when the import will be blank (import _ "package").
918func (g *GeneratedFile) Import(importPath GoImportPath) {
919 g.manualImports[importPath] = true
920}
921
Damien Neil220c2022018-08-15 11:24:18 -0700922// Write implements io.Writer.
923func (g *GeneratedFile) Write(p []byte) (n int, err error) {
924 return g.buf.Write(p)
925}
926
Damien Neil162c1272018-10-04 12:42:37 -0700927// Annotate associates a symbol in a generated Go file with a location in a
928// source .proto file.
929//
930// The symbol may refer to a type, constant, variable, function, method, or
931// struct field. The "T.sel" syntax is used to identify the method or field
932// 'sel' on type 'T'.
933func (g *GeneratedFile) Annotate(symbol string, loc Location) {
934 g.annotations[symbol] = append(g.annotations[symbol], loc)
935}
936
937// content returns the contents of the generated file.
938func (g *GeneratedFile) content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700939 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700940 return g.buf.Bytes(), nil
941 }
942
943 // Reformat generated code.
944 original := g.buf.Bytes()
945 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700946 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700947 if err != nil {
948 // Print out the bad code with line numbers.
949 // This should never happen in practice, but it can while changing generated code
950 // so consider this a debugging aid.
951 var src bytes.Buffer
952 s := bufio.NewScanner(bytes.NewReader(original))
953 for line := 1; s.Scan(); line++ {
954 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
955 }
Damien Neild9016772018-08-23 14:39:30 -0700956 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700957 }
Damien Neild9016772018-08-23 14:39:30 -0700958
959 // Add imports.
960 var importPaths []string
961 for importPath := range g.packageNames {
962 importPaths = append(importPaths, string(importPath))
963 }
964 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700965 rewriteImport := func(importPath string) string {
966 if f := g.gen.opts.ImportRewriteFunc; f != nil {
967 return string(f(GoImportPath(importPath)))
968 }
969 return importPath
970 }
Damien Neild9016772018-08-23 14:39:30 -0700971 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700972 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700973 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700974 for importPath := range g.manualImports {
975 if _, ok := g.packageNames[importPath]; ok {
976 continue
977 }
Damien Neil329b75e2018-10-04 17:31:07 -0700978 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700979 }
Damien Neil1ec33152018-09-13 13:12:36 -0700980 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700981
Damien Neilc7d07d92018-08-22 13:46:02 -0700982 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700983 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700984 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700985 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700986 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -0700987}
Damien Neilc7d07d92018-08-22 13:46:02 -0700988
Damien Neil162c1272018-10-04 12:42:37 -0700989// metaFile returns the contents of the file's metadata file, which is a
990// text formatted string of the google.protobuf.GeneratedCodeInfo.
991func (g *GeneratedFile) metaFile(content []byte) (string, error) {
992 fset := token.NewFileSet()
993 astFile, err := parser.ParseFile(fset, "", content, 0)
994 if err != nil {
995 return "", err
996 }
Joe Tsaie1f8d502018-11-26 18:55:29 -0800997 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -0700998
999 seenAnnotations := make(map[string]bool)
1000 annotate := func(s string, ident *ast.Ident) {
1001 seenAnnotations[s] = true
1002 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001003 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Joe Tsai009e0672018-11-27 18:45:07 -08001004 SourceFile: scalar.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001005 Path: loc.Path,
Joe Tsai009e0672018-11-27 18:45:07 -08001006 Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
1007 End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001008 })
1009 }
1010 }
1011 for _, decl := range astFile.Decls {
1012 switch decl := decl.(type) {
1013 case *ast.GenDecl:
1014 for _, spec := range decl.Specs {
1015 switch spec := spec.(type) {
1016 case *ast.TypeSpec:
1017 annotate(spec.Name.Name, spec.Name)
1018 if st, ok := spec.Type.(*ast.StructType); ok {
1019 for _, field := range st.Fields.List {
1020 for _, name := range field.Names {
1021 annotate(spec.Name.Name+"."+name.Name, name)
1022 }
1023 }
1024 }
1025 case *ast.ValueSpec:
1026 for _, name := range spec.Names {
1027 annotate(name.Name, name)
1028 }
1029 }
1030 }
1031 case *ast.FuncDecl:
1032 if decl.Recv == nil {
1033 annotate(decl.Name.Name, decl.Name)
1034 } else {
1035 recv := decl.Recv.List[0].Type
1036 if s, ok := recv.(*ast.StarExpr); ok {
1037 recv = s.X
1038 }
1039 if id, ok := recv.(*ast.Ident); ok {
1040 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1041 }
1042 }
1043 }
1044 }
1045 for a := range g.annotations {
1046 if !seenAnnotations[a] {
1047 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1048 }
1049 }
1050
1051 return proto.CompactTextString(info), nil
Damien Neil220c2022018-08-15 11:24:18 -07001052}
Damien Neil082ce922018-09-06 10:23:53 -07001053
1054type pathType int
1055
1056const (
1057 pathTypeImport pathType = iota
1058 pathTypeSourceRelative
1059)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001060
1061// The SourceCodeInfo message describes the location of elements of a parsed
1062// .proto file by way of a "path", which is a sequence of integers that
1063// describe the route from a FileDescriptorProto to the relevant submessage.
1064// The path alternates between a field number of a repeated field, and an index
1065// into that repeated field. The constants below define the field numbers that
1066// are used.
1067//
1068// See descriptor.proto for more information about this.
1069const (
1070 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001071 filePackageField = 2 // package
1072 fileMessageField = 4 // message_type
1073 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -07001074 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -07001075 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -07001076 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001077 messageFieldField = 2 // field
1078 messageMessageField = 3 // nested_type
1079 messageEnumField = 4 // enum_type
1080 messageExtensionField = 6 // extension
1081 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -07001082 // field numbers in EnumDescriptorProto
1083 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -07001084 // field numbers in ServiceDescriptorProto
1085 serviceMethodField = 2 // method
1086 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -07001087)
1088
Damien Neil162c1272018-10-04 12:42:37 -07001089// A Location is a location in a .proto source file.
1090//
1091// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1092// for details.
1093type Location struct {
1094 SourceFile string
1095 Path []int32
1096}
1097
1098// appendPath add elements to a Location's path, returning a new Location.
1099func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001100 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001101 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001102 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001103 return Location{
1104 SourceFile: loc.SourceFile,
1105 Path: n,
1106 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001107}
Damien Neilba1159f2018-10-17 12:53:18 -07001108
1109// A pathKey is a representation of a location path suitable for use as a map key.
1110type pathKey struct {
1111 s string
1112}
1113
1114// newPathKey converts a location path to a pathKey.
1115func newPathKey(path []int32) pathKey {
1116 buf := make([]byte, 4*len(path))
1117 for i, x := range path {
1118 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1119 }
1120 return pathKey{string(buf)}
1121}