blob: 76964eb922c5c52c725f078626dc7b68ec1c45d3 [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 {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800345 if g.skip {
346 continue
347 }
348 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700349 if err != nil {
350 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800351 Error: scalar.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700352 }
353 }
Damien Neil220c2022018-08-15 11:24:18 -0700354 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800355 Name: scalar.String(g.filename),
356 Content: scalar.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700357 })
Damien Neil162c1272018-10-04 12:42:37 -0700358 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
359 meta, err := g.metaFile(content)
360 if err != nil {
361 return &pluginpb.CodeGeneratorResponse{
Joe Tsai009e0672018-11-27 18:45:07 -0800362 Error: scalar.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700363 }
364 }
365 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Joe Tsai009e0672018-11-27 18:45:07 -0800366 Name: scalar.String(g.filename + ".meta"),
367 Content: scalar.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700368 })
369 }
Damien Neil220c2022018-08-15 11:24:18 -0700370 }
371 return resp
372}
373
374// FileByName returns the file with the given name.
375func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
376 f, ok = gen.filesByName[name]
377 return f, ok
378}
379
Damien Neilc7d07d92018-08-22 13:46:02 -0700380// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700381type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700382 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800383 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700384
Joe Tsaib6405bd2018-11-15 14:44:37 -0800385 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
386 GoPackageName GoPackageName // name of this file's Go package
387 GoImportPath GoImportPath // import path of this file's Go package
388 Messages []*Message // top-level message declarations
389 Enums []*Enum // top-level enum declarations
390 Extensions []*Extension // top-level extension declarations
391 Services []*Service // top-level service declarations
392 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700393
394 // GeneratedFilenamePrefix is used to construct filenames for generated
395 // files associated with this source file.
396 //
397 // For example, the source file "dir/foo.proto" might have a filename prefix
398 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
399 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700400
Joe Tsaie1f8d502018-11-26 18:55:29 -0800401 sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700402}
403
Joe Tsaie1f8d502018-11-26 18:55:29 -0800404func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
405 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700406 if err != nil {
407 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
408 }
409 if err := gen.fileReg.Register(desc); err != nil {
410 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
411 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700412 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700413 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700414 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700415 GoPackageName: packageName,
416 GoImportPath: importPath,
Joe Tsaie1f8d502018-11-26 18:55:29 -0800417 sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700418 }
Damien Neil082ce922018-09-06 10:23:53 -0700419
420 // Determine the prefix for generated Go files.
421 prefix := p.GetName()
422 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
423 prefix = prefix[:len(prefix)-len(ext)]
424 }
425 if gen.pathType == pathTypeImport {
426 // If paths=import (the default) and the file contains a go_package option
427 // with a full import path, the output filename is derived from the Go import
428 // path.
429 //
430 // Pass the paths=source_relative flag to always derive the output filename
431 // from the input filename instead.
432 if _, importPath := goPackageOption(p); importPath != "" {
433 prefix = path.Join(string(importPath), path.Base(prefix))
434 }
435 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800436 f.GoDescriptorIdent = GoIdent{
437 GoName: camelCase(cleanGoName(path.Base(prefix), true)) + "_ProtoFile",
438 GoImportPath: f.GoImportPath,
439 }
Damien Neil082ce922018-09-06 10:23:53 -0700440 f.GeneratedFilenamePrefix = prefix
441
Damien Neilba1159f2018-10-17 12:53:18 -0700442 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
443 key := newPathKey(loc.Path)
444 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
445 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700446 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700447 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700448 }
Damien Neil46abb572018-09-07 12:45:37 -0700449 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
450 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
451 }
Damien Neil993c04d2018-09-14 15:41:11 -0700452 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
453 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
454 }
Damien Neil2dc67182018-09-21 15:03:34 -0700455 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
456 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
457 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700458 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700459 if err := message.init(gen); err != nil {
460 return nil, err
461 }
462 }
463 for _, extension := range f.Extensions {
464 if err := extension.init(gen); err != nil {
465 return nil, err
466 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700467 }
Damien Neil2dc67182018-09-21 15:03:34 -0700468 for _, service := range f.Services {
469 for _, method := range service.Methods {
470 if err := method.init(gen); err != nil {
471 return nil, err
472 }
473 }
474 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700475 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700476}
477
Damien Neil162c1272018-10-04 12:42:37 -0700478func (f *File) location(path ...int32) Location {
479 return Location{
480 SourceFile: f.Desc.Path(),
481 Path: path,
482 }
483}
484
Damien Neil082ce922018-09-06 10:23:53 -0700485// goPackageOption interprets a file's go_package option.
486// If there is no go_package, it returns ("", "").
487// If there's a simple name, it returns (pkg, "").
488// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800489func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700490 opt := d.GetOptions().GetGoPackage()
491 if opt == "" {
492 return "", ""
493 }
494 // A semicolon-delimited suffix delimits the import path and package name.
495 if i := strings.Index(opt, ";"); i >= 0 {
496 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
497 }
498 // The presence of a slash implies there's an import path.
499 if i := strings.LastIndex(opt, "/"); i >= 0 {
500 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
501 }
502 return cleanPackageName(opt), ""
503}
504
Damien Neilc7d07d92018-08-22 13:46:02 -0700505// A Message describes a message.
506type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700507 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700508
Damien Neil993c04d2018-09-14 15:41:11 -0700509 GoIdent GoIdent // name of the generated Go type
510 Fields []*Field // message field declarations
511 Oneofs []*Oneof // oneof declarations
512 Messages []*Message // nested message declarations
513 Enums []*Enum // nested enum declarations
514 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700515 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700516}
517
Damien Neil1fa78d82018-09-13 13:12:36 -0700518func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700519 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700520 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700521 loc = parent.Location.appendPath(messageMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700522 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700523 loc = f.location(fileMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700524 }
Damien Neil46abb572018-09-07 12:45:37 -0700525 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700526 Desc: desc,
527 GoIdent: newGoIdent(f, desc),
528 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700529 }
Damien Neil658051b2018-09-10 12:26:21 -0700530 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700531 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700532 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700533 }
Damien Neil46abb572018-09-07 12:45:37 -0700534 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
535 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
536 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700537 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
538 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
539 }
Damien Neil658051b2018-09-10 12:26:21 -0700540 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700541 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700542 }
Damien Neil993c04d2018-09-14 15:41:11 -0700543 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
544 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
545 }
Damien Neil658051b2018-09-10 12:26:21 -0700546
547 // Field name conflict resolution.
548 //
549 // We assume well-known method names that may be attached to a generated
550 // message type, as well as a 'Get*' method for each field. For each
551 // field in turn, we add _s to its name until there are no conflicts.
552 //
553 // Any change to the following set of method names is a potential
554 // incompatible API change because it may change generated field names.
555 //
556 // TODO: If we ever support a 'go_name' option to set the Go name of a
557 // field, we should consider dropping this entirely. The conflict
558 // resolution algorithm is subtle and surprising (changing the order
559 // in which fields appear in the .proto source file can change the
560 // names of fields in generated code), and does not adapt well to
561 // adding new per-field methods such as setters.
562 usedNames := map[string]bool{
563 "Reset": true,
564 "String": true,
565 "ProtoMessage": true,
566 "Marshal": true,
567 "Unmarshal": true,
568 "ExtensionRangeArray": true,
569 "ExtensionMap": true,
570 "Descriptor": true,
571 }
572 makeNameUnique := func(name string) string {
573 for usedNames[name] || usedNames["Get"+name] {
574 name += "_"
575 }
576 usedNames[name] = true
577 usedNames["Get"+name] = true
578 return name
579 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700580 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700581 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700582 field.GoName = makeNameUnique(field.GoName)
583 if field.OneofType != nil {
584 if !seenOneofs[field.OneofType.Desc.Index()] {
585 // If this is a field in a oneof that we haven't seen before,
586 // make the name for that oneof unique as well.
587 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
588 seenOneofs[field.OneofType.Desc.Index()] = true
589 }
590 }
Damien Neil658051b2018-09-10 12:26:21 -0700591 }
592
Damien Neil1fa78d82018-09-13 13:12:36 -0700593 return message
Damien Neil658051b2018-09-10 12:26:21 -0700594}
595
Damien Neil0bd5a382018-09-13 15:07:10 -0700596func (message *Message) init(gen *Plugin) error {
597 for _, child := range message.Messages {
598 if err := child.init(gen); err != nil {
599 return err
600 }
601 }
602 for _, field := range message.Fields {
603 if err := field.init(gen); err != nil {
604 return err
605 }
606 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700607 for _, oneof := range message.Oneofs {
608 oneof.init(gen, message)
609 }
Damien Neil993c04d2018-09-14 15:41:11 -0700610 for _, extension := range message.Extensions {
611 if err := extension.init(gen); err != nil {
612 return err
613 }
614 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700615 return nil
616}
617
Damien Neil658051b2018-09-10 12:26:21 -0700618// A Field describes a message field.
619type Field struct {
620 Desc protoreflect.FieldDescriptor
621
Damien Neil1fa78d82018-09-13 13:12:36 -0700622 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700623 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700624 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
625 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700626
Damien Neil993c04d2018-09-14 15:41:11 -0700627 ParentMessage *Message // message in which this field is defined; nil if top-level extension
628 ExtendedType *Message // extended message for extension fields; nil otherwise
629 MessageType *Message // type for message or group fields; nil otherwise
630 EnumType *Enum // type for enum fields; nil otherwise
631 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700632 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700633}
634
Damien Neil1fa78d82018-09-13 13:12:36 -0700635func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700636 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700637 switch {
638 case desc.ExtendedType() != nil && message == nil:
Damien Neil162c1272018-10-04 12:42:37 -0700639 loc = f.location(fileExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700640 case desc.ExtendedType() != nil && message != nil:
Damien Neil162c1272018-10-04 12:42:37 -0700641 loc = message.Location.appendPath(messageExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700642 default:
Damien Neil162c1272018-10-04 12:42:37 -0700643 loc = message.Location.appendPath(messageFieldField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700644 }
Damien Neil658051b2018-09-10 12:26:21 -0700645 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700646 Desc: desc,
647 GoName: camelCase(string(desc.Name())),
648 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700649 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700650 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700651 if desc.OneofType() != nil {
652 field.OneofType = message.Oneofs[desc.OneofType().Index()]
653 }
654 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700655}
656
Damien Neil993c04d2018-09-14 15:41:11 -0700657// Extension is an alias of Field for documentation.
658type Extension = Field
659
Damien Neil0bd5a382018-09-13 15:07:10 -0700660func (field *Field) init(gen *Plugin) error {
661 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700662 switch desc.Kind() {
663 case protoreflect.MessageKind, protoreflect.GroupKind:
664 mname := desc.MessageType().FullName()
665 message, ok := gen.messagesByName[mname]
666 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700667 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700668 }
669 field.MessageType = message
670 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700671 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700672 enum, ok := gen.enumsByName[ename]
673 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700674 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700675 }
676 field.EnumType = enum
677 }
Damien Neil993c04d2018-09-14 15:41:11 -0700678 if desc.ExtendedType() != nil {
679 mname := desc.ExtendedType().FullName()
680 message, ok := gen.messagesByName[mname]
681 if !ok {
682 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
683 }
684 field.ExtendedType = message
685 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700686 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700687}
688
Damien Neil1fa78d82018-09-13 13:12:36 -0700689// A Oneof describes a oneof field.
690type Oneof struct {
691 Desc protoreflect.OneofDescriptor
692
Damien Neil993c04d2018-09-14 15:41:11 -0700693 GoName string // Go field name of this oneof
694 ParentMessage *Message // message in which this oneof occurs
695 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700696 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700697}
698
699func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
700 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700701 Desc: desc,
702 ParentMessage: message,
703 GoName: camelCase(string(desc.Name())),
Damien Neil162c1272018-10-04 12:42:37 -0700704 Location: message.Location.appendPath(messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700705 }
706}
707
708func (oneof *Oneof) init(gen *Plugin, parent *Message) {
709 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
710 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
711 }
712}
713
Damien Neil46abb572018-09-07 12:45:37 -0700714// An Enum describes an enum.
715type Enum struct {
716 Desc protoreflect.EnumDescriptor
717
Damien Neil162c1272018-10-04 12:42:37 -0700718 GoIdent GoIdent // name of the generated Go type
719 Values []*EnumValue // enum values
720 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700721}
722
723func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700724 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700725 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700726 loc = parent.Location.appendPath(messageEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700727 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700728 loc = f.location(fileEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700729 }
730 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700731 Desc: desc,
732 GoIdent: newGoIdent(f, desc),
733 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700734 }
Damien Neil658051b2018-09-10 12:26:21 -0700735 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700736 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
737 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
738 }
739 return enum
740}
741
742// An EnumValue describes an enum value.
743type EnumValue struct {
744 Desc protoreflect.EnumValueDescriptor
745
Damien Neil162c1272018-10-04 12:42:37 -0700746 GoIdent GoIdent // name of the generated Go type
747 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700748}
749
750func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
751 // A top-level enum value's name is: EnumName_ValueName
752 // An enum value contained in a message is: MessageName_ValueName
753 //
754 // Enum value names are not camelcased.
755 parentIdent := enum.GoIdent
756 if message != nil {
757 parentIdent = message.GoIdent
758 }
759 name := parentIdent.GoName + "_" + string(desc.Name())
760 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800761 Desc: desc,
762 GoIdent: f.GoImportPath.Ident(name),
Damien Neil162c1272018-10-04 12:42:37 -0700763 Location: enum.Location.appendPath(enumValueField, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700764 }
Damien Neil220c2022018-08-15 11:24:18 -0700765}
766
Damien Neil2dc67182018-09-21 15:03:34 -0700767// A Service describes a service.
768type Service struct {
769 Desc protoreflect.ServiceDescriptor
770
Damien Neil162c1272018-10-04 12:42:37 -0700771 GoName string
772 Location Location // location of this service
773 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700774}
775
776func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
777 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700778 Desc: desc,
779 GoName: camelCase(string(desc.Name())),
780 Location: f.location(fileServiceField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700781 }
782 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
783 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
784 }
785 return service
786}
787
788// A Method describes a method in a service.
789type Method struct {
790 Desc protoreflect.MethodDescriptor
791
792 GoName string
793 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700794 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700795 InputType *Message
796 OutputType *Message
797}
798
799func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
800 method := &Method{
801 Desc: desc,
802 GoName: camelCase(string(desc.Name())),
803 ParentService: service,
Damien Neil162c1272018-10-04 12:42:37 -0700804 Location: service.Location.appendPath(serviceMethodField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700805 }
806 return method
807}
808
809func (method *Method) init(gen *Plugin) error {
810 desc := method.Desc
811
812 inName := desc.InputType().FullName()
813 in, ok := gen.messagesByName[inName]
814 if !ok {
815 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
816 }
817 method.InputType = in
818
819 outName := desc.OutputType().FullName()
820 out, ok := gen.messagesByName[outName]
821 if !ok {
822 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
823 }
824 method.OutputType = out
825
826 return nil
827}
828
Damien Neil7bf3ce22018-12-21 15:54:06 -0800829// A GeneratedFile is a generated file.
830type GeneratedFile struct {
831 gen *Plugin
832 skip bool
833 filename string
834 goImportPath GoImportPath
835 buf bytes.Buffer
836 packageNames map[GoImportPath]GoPackageName
837 usedPackageNames map[GoPackageName]bool
838 manualImports map[GoImportPath]bool
839 annotations map[string][]Location
840}
841
842// NewGeneratedFile creates a new generated file with the given filename
843// and import path.
844func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
845 g := &GeneratedFile{
846 gen: gen,
847 filename: filename,
848 goImportPath: goImportPath,
849 packageNames: make(map[GoImportPath]GoPackageName),
850 usedPackageNames: make(map[GoPackageName]bool),
851 manualImports: make(map[GoImportPath]bool),
852 annotations: make(map[string][]Location),
853 }
854 gen.genFiles = append(gen.genFiles, g)
855 return g
856}
857
Damien Neil220c2022018-08-15 11:24:18 -0700858// P prints a line to the generated output. It converts each parameter to a
859// string following the same rules as fmt.Print. It never inserts spaces
860// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700861func (g *GeneratedFile) P(v ...interface{}) {
862 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700863 switch x := x.(type) {
864 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700865 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700866 default:
867 fmt.Fprint(&g.buf, x)
868 }
Damien Neil220c2022018-08-15 11:24:18 -0700869 }
870 fmt.Fprintln(&g.buf)
871}
872
Damien Neilba1159f2018-10-17 12:53:18 -0700873// PrintLeadingComments writes the comment appearing before a location in
874// the .proto source to the generated file.
875//
876// It returns true if a comment was present at the location.
877func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
878 f := g.gen.filesByName[loc.SourceFile]
879 if f == nil {
880 return false
881 }
882 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
883 if infoLoc.LeadingComments == nil {
884 continue
885 }
886 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
887 g.buf.WriteString("//")
888 g.buf.WriteString(line)
889 g.buf.WriteString("\n")
890 }
891 return true
892 }
893 return false
894}
895
Damien Neil46abb572018-09-07 12:45:37 -0700896// QualifiedGoIdent returns the string to use for a Go identifier.
897//
898// If the identifier is from a different Go package than the generated file,
899// the returned name will be qualified (package.name) and an import statement
900// for the identifier's package will be included in the file.
901func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
902 if ident.GoImportPath == g.goImportPath {
903 return ident.GoName
904 }
905 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
906 return string(packageName) + "." + ident.GoName
907 }
908 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700909 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700910 packageName = orig + GoPackageName(strconv.Itoa(i))
911 }
912 g.packageNames[ident.GoImportPath] = packageName
913 g.usedPackageNames[packageName] = true
914 return string(packageName) + "." + ident.GoName
915}
916
Damien Neil2e0c3da2018-09-19 12:51:36 -0700917// Import ensures a package is imported by the generated file.
918//
919// Packages referenced by QualifiedGoIdent are automatically imported.
920// Explicitly importing a package with Import is generally only necessary
921// when the import will be blank (import _ "package").
922func (g *GeneratedFile) Import(importPath GoImportPath) {
923 g.manualImports[importPath] = true
924}
925
Damien Neil220c2022018-08-15 11:24:18 -0700926// Write implements io.Writer.
927func (g *GeneratedFile) Write(p []byte) (n int, err error) {
928 return g.buf.Write(p)
929}
930
Damien Neil7bf3ce22018-12-21 15:54:06 -0800931// Skip removes the generated file from the plugin output.
932func (g *GeneratedFile) Skip() {
933 g.skip = true
934}
935
Damien Neil162c1272018-10-04 12:42:37 -0700936// Annotate associates a symbol in a generated Go file with a location in a
937// source .proto file.
938//
939// The symbol may refer to a type, constant, variable, function, method, or
940// struct field. The "T.sel" syntax is used to identify the method or field
941// 'sel' on type 'T'.
942func (g *GeneratedFile) Annotate(symbol string, loc Location) {
943 g.annotations[symbol] = append(g.annotations[symbol], loc)
944}
945
Damien Neil7bf3ce22018-12-21 15:54:06 -0800946// Content returns the contents of the generated file.
947func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700948 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700949 return g.buf.Bytes(), nil
950 }
951
952 // Reformat generated code.
953 original := g.buf.Bytes()
954 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700955 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700956 if err != nil {
957 // Print out the bad code with line numbers.
958 // This should never happen in practice, but it can while changing generated code
959 // so consider this a debugging aid.
960 var src bytes.Buffer
961 s := bufio.NewScanner(bytes.NewReader(original))
962 for line := 1; s.Scan(); line++ {
963 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
964 }
Damien Neild9016772018-08-23 14:39:30 -0700965 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700966 }
Damien Neild9016772018-08-23 14:39:30 -0700967
968 // Add imports.
969 var importPaths []string
970 for importPath := range g.packageNames {
971 importPaths = append(importPaths, string(importPath))
972 }
973 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700974 rewriteImport := func(importPath string) string {
975 if f := g.gen.opts.ImportRewriteFunc; f != nil {
976 return string(f(GoImportPath(importPath)))
977 }
978 return importPath
979 }
Damien Neild9016772018-08-23 14:39:30 -0700980 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700981 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700982 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700983 for importPath := range g.manualImports {
984 if _, ok := g.packageNames[importPath]; ok {
985 continue
986 }
Damien Neil329b75e2018-10-04 17:31:07 -0700987 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700988 }
Damien Neil1ec33152018-09-13 13:12:36 -0700989 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700990
Damien Neilc7d07d92018-08-22 13:46:02 -0700991 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700992 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700993 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700994 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700995 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -0700996}
Damien Neilc7d07d92018-08-22 13:46:02 -0700997
Damien Neil162c1272018-10-04 12:42:37 -0700998// metaFile returns the contents of the file's metadata file, which is a
999// text formatted string of the google.protobuf.GeneratedCodeInfo.
1000func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1001 fset := token.NewFileSet()
1002 astFile, err := parser.ParseFile(fset, "", content, 0)
1003 if err != nil {
1004 return "", err
1005 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001006 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001007
1008 seenAnnotations := make(map[string]bool)
1009 annotate := func(s string, ident *ast.Ident) {
1010 seenAnnotations[s] = true
1011 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001012 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Joe Tsai009e0672018-11-27 18:45:07 -08001013 SourceFile: scalar.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001014 Path: loc.Path,
Joe Tsai009e0672018-11-27 18:45:07 -08001015 Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
1016 End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001017 })
1018 }
1019 }
1020 for _, decl := range astFile.Decls {
1021 switch decl := decl.(type) {
1022 case *ast.GenDecl:
1023 for _, spec := range decl.Specs {
1024 switch spec := spec.(type) {
1025 case *ast.TypeSpec:
1026 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001027 switch st := spec.Type.(type) {
1028 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001029 for _, field := range st.Fields.List {
1030 for _, name := range field.Names {
1031 annotate(spec.Name.Name+"."+name.Name, name)
1032 }
1033 }
Damien Neilae2a5612018-12-12 08:54:57 -08001034 case *ast.InterfaceType:
1035 for _, field := range st.Methods.List {
1036 for _, name := range field.Names {
1037 annotate(spec.Name.Name+"."+name.Name, name)
1038 }
1039 }
Damien Neil162c1272018-10-04 12:42:37 -07001040 }
1041 case *ast.ValueSpec:
1042 for _, name := range spec.Names {
1043 annotate(name.Name, name)
1044 }
1045 }
1046 }
1047 case *ast.FuncDecl:
1048 if decl.Recv == nil {
1049 annotate(decl.Name.Name, decl.Name)
1050 } else {
1051 recv := decl.Recv.List[0].Type
1052 if s, ok := recv.(*ast.StarExpr); ok {
1053 recv = s.X
1054 }
1055 if id, ok := recv.(*ast.Ident); ok {
1056 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1057 }
1058 }
1059 }
1060 }
1061 for a := range g.annotations {
1062 if !seenAnnotations[a] {
1063 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1064 }
1065 }
1066
1067 return proto.CompactTextString(info), nil
Damien Neil220c2022018-08-15 11:24:18 -07001068}
Damien Neil082ce922018-09-06 10:23:53 -07001069
1070type pathType int
1071
1072const (
1073 pathTypeImport pathType = iota
1074 pathTypeSourceRelative
1075)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001076
1077// The SourceCodeInfo message describes the location of elements of a parsed
1078// .proto file by way of a "path", which is a sequence of integers that
1079// describe the route from a FileDescriptorProto to the relevant submessage.
1080// The path alternates between a field number of a repeated field, and an index
1081// into that repeated field. The constants below define the field numbers that
1082// are used.
1083//
1084// See descriptor.proto for more information about this.
1085const (
1086 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001087 filePackageField = 2 // package
1088 fileMessageField = 4 // message_type
1089 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -07001090 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -07001091 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -07001092 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001093 messageFieldField = 2 // field
1094 messageMessageField = 3 // nested_type
1095 messageEnumField = 4 // enum_type
1096 messageExtensionField = 6 // extension
1097 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -07001098 // field numbers in EnumDescriptorProto
1099 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -07001100 // field numbers in ServiceDescriptorProto
1101 serviceMethodField = 2 // method
1102 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -07001103)
1104
Damien Neil162c1272018-10-04 12:42:37 -07001105// A Location is a location in a .proto source file.
1106//
1107// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1108// for details.
1109type Location struct {
1110 SourceFile string
1111 Path []int32
1112}
1113
1114// appendPath add elements to a Location's path, returning a new Location.
1115func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001116 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001117 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001118 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001119 return Location{
1120 SourceFile: loc.SourceFile,
1121 Path: n,
1122 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001123}
Damien Neilba1159f2018-10-17 12:53:18 -07001124
1125// A pathKey is a representation of a location path suitable for use as a map key.
1126type pathKey struct {
1127 s string
1128}
1129
1130// newPathKey converts a location path to a pathKey.
1131func newPathKey(path []int32) pathKey {
1132 buf := make([]byte, 4*len(path))
1133 for i, x := range path {
1134 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1135 }
1136 return pathKey{string(buf)}
1137}