blob: 3be898d73ee506e2e2ff3407bac61154fccb184a [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package protogen provides support for writing protoc plugins.
6//
7// Plugins for protoc, the Protocol Buffers Compiler, are programs which read
8// a CodeGeneratorRequest protocol buffer from standard input and write a
9// CodeGeneratorResponse protocol buffer to standard output. This package
10// provides support for writing plugins which generate Go code.
11package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
Damien Neilba1159f2018-10-17 12:53:18 -070016 "encoding/binary"
Damien Neil220c2022018-08-15 11:24:18 -070017 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070018 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070019 "go/parser"
20 "go/printer"
21 "go/token"
Joe Tsai124c8122019-01-14 11:48:43 -080022 "go/types"
Damien Neil220c2022018-08-15 11:24:18 -070023 "io/ioutil"
24 "os"
Damien Neil082ce922018-09-06 10:23:53 -070025 "path"
Damien Neil220c2022018-08-15 11:24:18 -070026 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070027 "sort"
28 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070029 "strings"
30
Damien Neil5c5b5312019-05-14 12:44:37 -070031 "google.golang.org/protobuf/encoding/prototext"
Damien Neile89e6242019-05-13 23:55:40 -070032 "google.golang.org/protobuf/internal/fieldnum"
Joe Tsai2e7817f2019-08-23 12:18:57 -070033 "google.golang.org/protobuf/internal/strs"
Damien Neile89e6242019-05-13 23:55:40 -070034 "google.golang.org/protobuf/proto"
35 "google.golang.org/protobuf/reflect/protodesc"
36 "google.golang.org/protobuf/reflect/protoreflect"
37 "google.golang.org/protobuf/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080038
Joe Tsaia95b29f2019-05-16 12:47:20 -070039 "google.golang.org/protobuf/types/descriptorpb"
40 "google.golang.org/protobuf/types/pluginpb"
Damien Neil220c2022018-08-15 11:24:18 -070041)
42
43// Run executes a function as a protoc plugin.
44//
45// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
46// function, and writes a CodeGeneratorResponse message to os.Stdout.
47//
48// If a failure occurs while reading or writing, Run prints an error to
49// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070050//
51// Passing a nil options is equivalent to passing a zero-valued one.
52func Run(opts *Options, f func(*Plugin) error) {
53 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070054 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
55 os.Exit(1)
56 }
57}
58
Damien Neil3cf6e622018-09-11 13:53:14 -070059func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070060 if len(os.Args) > 1 {
61 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
62 }
Damien Neil220c2022018-08-15 11:24:18 -070063 in, err := ioutil.ReadAll(os.Stdin)
64 if err != nil {
65 return err
66 }
67 req := &pluginpb.CodeGeneratorRequest{}
68 if err := proto.Unmarshal(in, req); err != nil {
69 return err
70 }
Damien Neil3cf6e622018-09-11 13:53:14 -070071 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070072 if err != nil {
73 return err
74 }
75 if err := f(gen); err != nil {
76 // Errors from the plugin function are reported by setting the
77 // error field in the CodeGeneratorResponse.
78 //
79 // In contrast, errors that indicate a problem in protoc
80 // itself (unparsable input, I/O errors, etc.) are reported
81 // to stderr.
82 gen.Error(err)
83 }
84 resp := gen.Response()
85 out, err := proto.Marshal(resp)
86 if err != nil {
87 return err
88 }
89 if _, err := os.Stdout.Write(out); err != nil {
90 return err
91 }
92 return nil
93}
94
95// A Plugin is a protoc plugin invocation.
96type Plugin struct {
97 // Request is the CodeGeneratorRequest provided by protoc.
98 Request *pluginpb.CodeGeneratorRequest
99
100 // Files is the set of files to generate and everything they import.
101 // Files appear in topological order, so each file appears before any
102 // file that imports it.
103 Files []*File
Joe Tsai2cec4842019-08-20 20:14:19 -0700104 FilesByPath map[string]*File
Damien Neil220c2022018-08-15 11:24:18 -0700105
Damien Neil658051b2018-09-10 12:26:21 -0700106 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700107 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700108 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700109 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700110 pathType pathType
111 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700112 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700113 err error
Damien Neil220c2022018-08-15 11:24:18 -0700114}
115
Damien Neil3cf6e622018-09-11 13:53:14 -0700116// Options are optional parameters to New.
117type Options struct {
118 // If ParamFunc is non-nil, it will be called with each unknown
119 // generator parameter.
120 //
121 // Plugins for protoc can accept parameters from the command line,
122 // passed in the --<lang>_out protoc, separated from the output
123 // directory with a colon; e.g.,
124 //
125 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
126 //
127 // Parameters passed in this fashion as a comma-separated list of
128 // key=value pairs will be passed to the ParamFunc.
129 //
130 // The (flag.FlagSet).Set method matches this function signature,
131 // so parameters can be converted into flags as in the following:
132 //
133 // var flags flag.FlagSet
134 // value := flags.Bool("param", false, "")
135 // opts := &protogen.Options{
136 // ParamFunc: flags.Set,
137 // }
138 // protogen.Run(opts, func(p *protogen.Plugin) error {
139 // if *value { ... }
140 // })
141 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700142
143 // ImportRewriteFunc is called with the import path of each package
144 // imported by a generated file. It returns the import path to use
145 // for this package.
146 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700147}
148
Damien Neil220c2022018-08-15 11:24:18 -0700149// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700150//
151// Passing a nil Options is equivalent to passing a zero-valued one.
152func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
153 if opts == nil {
154 opts = &Options{}
155 }
Damien Neil220c2022018-08-15 11:24:18 -0700156 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700157 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700158 FilesByPath: make(map[string]*File),
Damien Neil658051b2018-09-10 12:26:21 -0700159 fileReg: protoregistry.NewFiles(),
Damien Neil658051b2018-09-10 12:26:21 -0700160 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700161 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700162 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700163 }
164
Damien Neil082ce922018-09-06 10:23:53 -0700165 packageNames := make(map[string]GoPackageName) // filename -> package name
166 importPaths := make(map[string]GoImportPath) // filename -> import path
167 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700168 for _, param := range strings.Split(req.GetParameter(), ",") {
169 var value string
170 if i := strings.Index(param, "="); i >= 0 {
171 value = param[i+1:]
172 param = param[0:i]
173 }
174 switch param {
175 case "":
176 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700177 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700178 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700179 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700180 switch value {
181 case "import":
182 gen.pathType = pathTypeImport
183 case "source_relative":
184 gen.pathType = pathTypeSourceRelative
185 default:
186 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
187 }
Damien Neil220c2022018-08-15 11:24:18 -0700188 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700189 switch value {
190 case "true", "":
191 gen.annotateCode = true
192 case "false":
193 default:
194 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
195 }
Damien Neil220c2022018-08-15 11:24:18 -0700196 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700197 if param[0] == 'M' {
198 importPaths[param[1:]] = GoImportPath(value)
199 continue
Damien Neil220c2022018-08-15 11:24:18 -0700200 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700201 if opts.ParamFunc != nil {
202 if err := opts.ParamFunc(param, value); err != nil {
203 return nil, err
204 }
205 }
Damien Neil082ce922018-09-06 10:23:53 -0700206 }
207 }
208
209 // Figure out the import path and package name for each file.
210 //
211 // The rules here are complicated and have grown organically over time.
212 // Interactions between different ways of specifying package information
213 // may be surprising.
214 //
215 // The recommended approach is to include a go_package option in every
216 // .proto source file specifying the full import path of the Go package
217 // associated with this file.
218 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700219 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700220 //
221 // Build systems which want to exert full control over import paths may
222 // specify M<filename>=<import_path> flags.
223 //
224 // Other approaches are not recommend.
225 generatedFileNames := make(map[string]bool)
226 for _, name := range gen.Request.FileToGenerate {
227 generatedFileNames[name] = true
228 }
229 // We need to determine the import paths before the package names,
230 // because the Go package name for a file is sometimes derived from
231 // different file in the same package.
232 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
233 for _, fdesc := range gen.Request.ProtoFile {
234 filename := fdesc.GetName()
235 packageName, importPath := goPackageOption(fdesc)
236 switch {
237 case importPaths[filename] != "":
238 // Command line: M=foo.proto=quux/bar
239 //
240 // Explicit mapping of source file to import path.
241 case generatedFileNames[filename] && packageImportPath != "":
242 // Command line: import_path=quux/bar
243 //
244 // The import_path flag sets the import path for every file that
245 // we generate code for.
246 importPaths[filename] = packageImportPath
247 case importPath != "":
248 // Source file: option go_package = "quux/bar";
249 //
250 // The go_package option sets the import path. Most users should use this.
251 importPaths[filename] = importPath
252 default:
253 // Source filename.
254 //
255 // Last resort when nothing else is available.
256 importPaths[filename] = GoImportPath(path.Dir(filename))
257 }
258 if packageName != "" {
259 packageNameForImportPath[importPaths[filename]] = packageName
260 }
261 }
262 for _, fdesc := range gen.Request.ProtoFile {
263 filename := fdesc.GetName()
264 packageName, _ := goPackageOption(fdesc)
265 defaultPackageName := packageNameForImportPath[importPaths[filename]]
266 switch {
267 case packageName != "":
268 // Source file: option go_package = "quux/bar";
269 packageNames[filename] = packageName
270 case defaultPackageName != "":
271 // A go_package option in another file in the same package.
272 //
273 // This is a poor choice in general, since every source file should
274 // contain a go_package option. Supported mainly for historical
275 // compatibility.
276 packageNames[filename] = defaultPackageName
277 case generatedFileNames[filename] && packageImportPath != "":
278 // Command line: import_path=quux/bar
279 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
280 case fdesc.GetPackage() != "":
281 // Source file: package quux.bar;
282 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
283 default:
284 // Source filename.
285 packageNames[filename] = cleanPackageName(baseName(filename))
286 }
287 }
288
289 // Consistency check: Every file with the same Go import path should have
290 // the same Go package name.
291 packageFiles := make(map[GoImportPath][]string)
292 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700293 if _, ok := packageNames[filename]; !ok {
294 // Skip files mentioned in a M<file>=<import_path> parameter
295 // but which do not appear in the CodeGeneratorRequest.
296 continue
297 }
Damien Neil082ce922018-09-06 10:23:53 -0700298 packageFiles[importPath] = append(packageFiles[importPath], filename)
299 }
300 for importPath, filenames := range packageFiles {
301 for i := 1; i < len(filenames); i++ {
302 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
303 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
304 importPath, a, filenames[0], b, filenames[i])
305 }
Damien Neil220c2022018-08-15 11:24:18 -0700306 }
307 }
308
309 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700310 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700311 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700312 return nil, fmt.Errorf("duplicate file name: %q", filename)
313 }
314 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700315 if err != nil {
316 return nil, err
317 }
Damien Neil220c2022018-08-15 11:24:18 -0700318 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700319 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700320 }
Damien Neil082ce922018-09-06 10:23:53 -0700321 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700322 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700323 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700324 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700325 }
326 f.Generate = true
327 }
328 return gen, nil
329}
330
331// Error records an error in code generation. The generator will report the
332// error back to protoc and will not produce output.
333func (gen *Plugin) Error(err error) {
334 if gen.err == nil {
335 gen.err = err
336 }
337}
338
339// Response returns the generator output.
340func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
341 resp := &pluginpb.CodeGeneratorResponse{}
342 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700343 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700344 return resp
345 }
Damien Neil162c1272018-10-04 12:42:37 -0700346 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800347 if g.skip {
348 continue
349 }
350 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700351 if err != nil {
352 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700353 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700354 }
355 }
Damien Neil220c2022018-08-15 11:24:18 -0700356 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700357 Name: proto.String(g.filename),
358 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700359 })
Damien Neil162c1272018-10-04 12:42:37 -0700360 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
361 meta, err := g.metaFile(content)
362 if err != nil {
363 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700364 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700365 }
366 }
367 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700368 Name: proto.String(g.filename + ".meta"),
369 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700370 })
371 }
Damien Neil220c2022018-08-15 11:24:18 -0700372 }
373 return resp
374}
375
Damien Neilc7d07d92018-08-22 13:46:02 -0700376// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700377type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700378 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800379 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700380
Joe Tsaib6405bd2018-11-15 14:44:37 -0800381 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
382 GoPackageName GoPackageName // name of this file's Go package
383 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700384
385 Enums []*Enum // top-level enum declarations
386 Messages []*Message // top-level message declarations
387 Extensions []*Extension // top-level extension declarations
388 Services []*Service // top-level service declarations
389
390 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700391
392 // GeneratedFilenamePrefix is used to construct filenames for generated
393 // files associated with this source file.
394 //
395 // For example, the source file "dir/foo.proto" might have a filename prefix
396 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
397 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700398
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700399 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700400}
401
Joe Tsaie1f8d502018-11-26 18:55:29 -0800402func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
403 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700404 if err != nil {
405 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
406 }
407 if err := gen.fileReg.Register(desc); err != nil {
408 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
409 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700410 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700411 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700412 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700413 GoPackageName: packageName,
414 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700415 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700416 }
Damien Neil082ce922018-09-06 10:23:53 -0700417
418 // Determine the prefix for generated Go files.
419 prefix := p.GetName()
420 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
421 prefix = prefix[:len(prefix)-len(ext)]
422 }
423 if gen.pathType == pathTypeImport {
424 // If paths=import (the default) and the file contains a go_package option
425 // with a full import path, the output filename is derived from the Go import
426 // path.
427 //
428 // Pass the paths=source_relative flag to always derive the output filename
429 // from the input filename instead.
430 if _, importPath := goPackageOption(p); importPath != "" {
431 prefix = path.Join(string(importPath), path.Base(prefix))
432 }
433 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800434 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700435 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800436 GoImportPath: f.GoImportPath,
437 }
Damien Neil082ce922018-09-06 10:23:53 -0700438 f.GeneratedFilenamePrefix = prefix
439
Damien Neilba1159f2018-10-17 12:53:18 -0700440 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700441 // Descriptors declarations are guaranteed to have unique comment sets.
442 // Other locations may not be unique, but we don't use them.
443 var leadingDetached []Comments
444 for _, s := range loc.GetLeadingDetachedComments() {
445 leadingDetached = append(leadingDetached, Comments(s))
446 }
447 f.comments[newPathKey(loc.Path)] = CommentSet{
448 LeadingDetached: leadingDetached,
449 Leading: Comments(loc.GetLeadingComments()),
450 Trailing: Comments(loc.GetTrailingComments()),
451 }
Damien Neilba1159f2018-10-17 12:53:18 -0700452 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700453 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
454 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700455 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700456 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
457 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700458 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700459 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
460 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700461 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700462 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
463 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700464 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700465 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700466 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700467 return nil, err
468 }
469 }
470 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700471 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700472 return nil, err
473 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700474 }
Damien Neil2dc67182018-09-21 15:03:34 -0700475 for _, service := range f.Services {
476 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700477 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700478 return nil, err
479 }
480 }
481 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700482 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700483}
484
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900485func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700486 return Location{
487 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900488 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700489 }
490}
491
Damien Neil082ce922018-09-06 10:23:53 -0700492// goPackageOption interprets a file's go_package option.
493// If there is no go_package, it returns ("", "").
494// If there's a simple name, it returns (pkg, "").
495// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800496func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700497 opt := d.GetOptions().GetGoPackage()
498 if opt == "" {
499 return "", ""
500 }
501 // A semicolon-delimited suffix delimits the import path and package name.
502 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai2e7817f2019-08-23 12:18:57 -0700503 // TODO: The package name is explicitly provided by the .proto file.
504 // Rather than sanitizing it, we should pass it verbatim.
Damien Neil082ce922018-09-06 10:23:53 -0700505 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
506 }
507 // The presence of a slash implies there's an import path.
508 if i := strings.LastIndex(opt, "/"); i >= 0 {
509 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
510 }
511 return cleanPackageName(opt), ""
512}
513
Joe Tsai7762ec22019-08-20 20:10:23 -0700514// An Enum describes an enum.
515type Enum struct {
516 Desc protoreflect.EnumDescriptor
517
518 GoIdent GoIdent // name of the generated Go type
519
520 Values []*EnumValue // enum value declarations
521
522 Location Location // location of this enum
523 Comments CommentSet // comments associated with this enum
524}
525
526func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
527 var loc Location
528 if parent != nil {
529 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
530 } else {
531 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
532 }
533 enum := &Enum{
534 Desc: desc,
535 GoIdent: newGoIdent(f, desc),
536 Location: loc,
537 Comments: f.comments[newPathKey(loc.Path)],
538 }
539 gen.enumsByName[desc.FullName()] = enum
540 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
541 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
542 }
543 return enum
544}
545
546// An EnumValue describes an enum value.
547type EnumValue struct {
548 Desc protoreflect.EnumValueDescriptor
549
550 GoIdent GoIdent // name of the generated Go declaration
551
Joe Tsai4df99fd2019-08-20 22:26:16 -0700552 Parent *Enum // enum in which this value is declared
553
Joe Tsai7762ec22019-08-20 20:10:23 -0700554 Location Location // location of this enum value
555 Comments CommentSet // comments associated with this enum value
556}
557
558func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
559 // A top-level enum value's name is: EnumName_ValueName
560 // An enum value contained in a message is: MessageName_ValueName
561 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700562 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700563 parentIdent := enum.GoIdent
564 if message != nil {
565 parentIdent = message.GoIdent
566 }
567 name := parentIdent.GoName + "_" + string(desc.Name())
568 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
569 return &EnumValue{
570 Desc: desc,
571 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700572 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700573 Location: loc,
574 Comments: f.comments[newPathKey(loc.Path)],
575 }
576}
577
Damien Neilc7d07d92018-08-22 13:46:02 -0700578// A Message describes a message.
579type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700580 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700581
Joe Tsai7762ec22019-08-20 20:10:23 -0700582 GoIdent GoIdent // name of the generated Go type
583
584 Fields []*Field // message field declarations
585 Oneofs []*Oneof // message oneof declarations
586
Damien Neil993c04d2018-09-14 15:41:11 -0700587 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700588 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700589 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700590
591 Location Location // location of this message
592 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700593}
594
Damien Neil1fa78d82018-09-13 13:12:36 -0700595func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700596 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700597 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700598 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700599 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700600 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700601 }
Damien Neil46abb572018-09-07 12:45:37 -0700602 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700603 Desc: desc,
604 GoIdent: newGoIdent(f, desc),
605 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700606 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700607 }
Damien Neil658051b2018-09-10 12:26:21 -0700608 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700609 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
610 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700611 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700612 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
613 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700614 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700615 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
616 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700617 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700618 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
619 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700620 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700621 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
622 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
623 }
624
625 // Resolve local references between fields and oneofs.
626 for _, field := range message.Fields {
627 if od := field.Desc.ContainingOneof(); od != nil {
628 oneof := message.Oneofs[od.Index()]
629 field.Oneof = oneof
630 oneof.Fields = append(oneof.Fields, field)
631 }
Damien Neil993c04d2018-09-14 15:41:11 -0700632 }
Damien Neil658051b2018-09-10 12:26:21 -0700633
634 // Field name conflict resolution.
635 //
636 // We assume well-known method names that may be attached to a generated
637 // message type, as well as a 'Get*' method for each field. For each
638 // field in turn, we add _s to its name until there are no conflicts.
639 //
640 // Any change to the following set of method names is a potential
641 // incompatible API change because it may change generated field names.
642 //
643 // TODO: If we ever support a 'go_name' option to set the Go name of a
644 // field, we should consider dropping this entirely. The conflict
645 // resolution algorithm is subtle and surprising (changing the order
646 // in which fields appear in the .proto source file can change the
647 // names of fields in generated code), and does not adapt well to
648 // adding new per-field methods such as setters.
649 usedNames := map[string]bool{
650 "Reset": true,
651 "String": true,
652 "ProtoMessage": true,
653 "Marshal": true,
654 "Unmarshal": true,
655 "ExtensionRangeArray": true,
656 "ExtensionMap": true,
657 "Descriptor": true,
658 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800659 makeNameUnique := func(name string, hasGetter bool) string {
660 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700661 name += "_"
662 }
663 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800664 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700665 return name
666 }
667 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800668 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700669 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
670 if field.Oneof != nil && field.Oneof.Fields[0] == field {
671 // Make the name for a oneof unique as well. For historical reasons,
672 // this assumes that a getter method is not generated for oneofs.
673 // This is incorrect, but fixing it breaks existing code.
674 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
675 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
676 }
677 }
678
679 // Oneof field name conflict resolution.
680 //
681 // This conflict resolution is incomplete as it does not consider collisions
682 // with other oneof field types, but fixing it breaks existing code.
683 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700684 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700685 Loop:
686 for {
687 for _, nestedMessage := range message.Messages {
688 if nestedMessage.GoIdent == field.GoIdent {
689 field.GoIdent.GoName += "_"
690 continue Loop
691 }
692 }
693 for _, nestedEnum := range message.Enums {
694 if nestedEnum.GoIdent == field.GoIdent {
695 field.GoIdent.GoName += "_"
696 continue Loop
697 }
698 }
699 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700700 }
701 }
Damien Neil658051b2018-09-10 12:26:21 -0700702 }
703
Damien Neil1fa78d82018-09-13 13:12:36 -0700704 return message
Damien Neil658051b2018-09-10 12:26:21 -0700705}
706
Joe Tsai7762ec22019-08-20 20:10:23 -0700707func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700708 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700709 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700710 return err
711 }
712 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700713 for _, message := range message.Messages {
714 if err := message.resolveDependencies(gen); err != nil {
715 return err
716 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700717 }
Damien Neil993c04d2018-09-14 15:41:11 -0700718 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700719 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700720 return err
721 }
722 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700723 return nil
724}
725
Damien Neil658051b2018-09-10 12:26:21 -0700726// A Field describes a message field.
727type Field struct {
728 Desc protoreflect.FieldDescriptor
729
Damien Neil1fa78d82018-09-13 13:12:36 -0700730 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700731 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700732 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700733 GoName string // e.g., "FieldName"
734
735 // GoIdent is the base name of a top-level declaration for this field.
736 // For code generated by protoc-gen-go, this means a wrapper type named
737 // '{{GoIdent}}' for members fields of a oneof, and a variable named
738 // 'E_{{GoIdent}}' for extension fields.
739 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700740
Joe Tsai7762ec22019-08-20 20:10:23 -0700741 Parent *Message // message in which this field is declared; nil if top-level extension
742 Oneof *Oneof // containing oneof; nil if not part of a oneof
743 Extendee *Message // extended message for extension fields; nil otherwise
744
745 Enum *Enum // type for enum fields; nil otherwise
746 Message *Message // type for message or group fields; nil otherwise
747
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700748 Location Location // location of this field
749 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700750}
751
Damien Neil1fa78d82018-09-13 13:12:36 -0700752func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700753 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700754 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700755 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700756 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700757 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700758 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700759 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700760 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700761 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700762 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700763 var parentPrefix string
764 if message != nil {
765 parentPrefix = message.GoIdent.GoName + "_"
766 }
Damien Neil658051b2018-09-10 12:26:21 -0700767 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700768 Desc: desc,
769 GoName: camelCased,
770 GoIdent: GoIdent{
771 GoImportPath: f.GoImportPath,
772 GoName: parentPrefix + camelCased,
773 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700774 Parent: message,
775 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700776 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700777 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700778 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700779}
780
Joe Tsai7762ec22019-08-20 20:10:23 -0700781func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700782 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700783 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700784 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700785 name := field.Desc.Enum().FullName()
786 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700787 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700788 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700789 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700790 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700791 case protoreflect.MessageKind, protoreflect.GroupKind:
792 name := desc.Message().FullName()
793 message, ok := gen.messagesByName[name]
794 if !ok {
795 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
796 }
797 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700798 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700799 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700800 name := desc.ContainingMessage().FullName()
801 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700802 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700803 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700804 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700805 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700806 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700807 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700808}
809
Joe Tsai7762ec22019-08-20 20:10:23 -0700810// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700811type Oneof struct {
812 Desc protoreflect.OneofDescriptor
813
Joe Tsaief6e5242019-08-21 00:55:36 -0700814 // GoName is the base name of this oneof's Go field and methods.
815 // For code generated by protoc-gen-go, this means a field named
816 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
817 GoName string // e.g., "OneofName"
818
819 // GoIdent is the base name of a top-level declaration for this oneof.
820 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700821
822 Parent *Message // message in which this oneof is declared
823
Joe Tsaid24bc722019-04-15 23:39:09 -0700824 Fields []*Field // fields that are part of this oneof
825
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700826 Location Location // location of this oneof
827 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700828}
829
830func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700831 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Joe Tsai2e7817f2019-08-23 12:18:57 -0700832 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700833 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700834 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700835 Desc: desc,
836 Parent: message,
837 GoName: camelCased,
838 GoIdent: GoIdent{
839 GoImportPath: f.GoImportPath,
840 GoName: parentPrefix + camelCased,
841 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700842 Location: loc,
843 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700844 }
845}
846
Joe Tsai7762ec22019-08-20 20:10:23 -0700847// Extension is an alias of Field for documentation.
848type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700849
Damien Neil2dc67182018-09-21 15:03:34 -0700850// A Service describes a service.
851type Service struct {
852 Desc protoreflect.ServiceDescriptor
853
Joe Tsai7762ec22019-08-20 20:10:23 -0700854 GoName string
855
856 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700857
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700858 Location Location // location of this service
859 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700860}
861
862func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700863 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700864 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700865 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700866 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700867 Location: loc,
868 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700869 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700870 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
871 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700872 }
873 return service
874}
875
876// A Method describes a method in a service.
877type Method struct {
878 Desc protoreflect.MethodDescriptor
879
Joe Tsaid24bc722019-04-15 23:39:09 -0700880 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700881
882 Parent *Service // service in which this method is declared
883
Joe Tsaid24bc722019-04-15 23:39:09 -0700884 Input *Message
885 Output *Message
886
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700887 Location Location // location of this method
888 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700889}
890
891func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700892 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700893 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700894 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700895 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700896 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700897 Location: loc,
898 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700899 }
900 return method
901}
902
Joe Tsai7762ec22019-08-20 20:10:23 -0700903func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700904 desc := method.Desc
905
Joe Tsaid24bc722019-04-15 23:39:09 -0700906 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700907 in, ok := gen.messagesByName[inName]
908 if !ok {
909 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
910 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700911 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700912
Joe Tsaid24bc722019-04-15 23:39:09 -0700913 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700914 out, ok := gen.messagesByName[outName]
915 if !ok {
916 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
917 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700918 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700919
920 return nil
921}
922
Damien Neil7bf3ce22018-12-21 15:54:06 -0800923// A GeneratedFile is a generated file.
924type GeneratedFile struct {
925 gen *Plugin
926 skip bool
927 filename string
928 goImportPath GoImportPath
929 buf bytes.Buffer
930 packageNames map[GoImportPath]GoPackageName
931 usedPackageNames map[GoPackageName]bool
932 manualImports map[GoImportPath]bool
933 annotations map[string][]Location
934}
935
936// NewGeneratedFile creates a new generated file with the given filename
937// and import path.
938func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
939 g := &GeneratedFile{
940 gen: gen,
941 filename: filename,
942 goImportPath: goImportPath,
943 packageNames: make(map[GoImportPath]GoPackageName),
944 usedPackageNames: make(map[GoPackageName]bool),
945 manualImports: make(map[GoImportPath]bool),
946 annotations: make(map[string][]Location),
947 }
Joe Tsai124c8122019-01-14 11:48:43 -0800948
949 // All predeclared identifiers in Go are already used.
950 for _, s := range types.Universe.Names() {
951 g.usedPackageNames[GoPackageName(s)] = true
952 }
953
Damien Neil7bf3ce22018-12-21 15:54:06 -0800954 gen.genFiles = append(gen.genFiles, g)
955 return g
956}
957
Damien Neil220c2022018-08-15 11:24:18 -0700958// P prints a line to the generated output. It converts each parameter to a
959// string following the same rules as fmt.Print. It never inserts spaces
960// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700961func (g *GeneratedFile) P(v ...interface{}) {
962 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700963 switch x := x.(type) {
964 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700965 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700966 default:
967 fmt.Fprint(&g.buf, x)
968 }
Damien Neil220c2022018-08-15 11:24:18 -0700969 }
970 fmt.Fprintln(&g.buf)
971}
972
Damien Neil46abb572018-09-07 12:45:37 -0700973// QualifiedGoIdent returns the string to use for a Go identifier.
974//
975// If the identifier is from a different Go package than the generated file,
976// the returned name will be qualified (package.name) and an import statement
977// for the identifier's package will be included in the file.
978func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
979 if ident.GoImportPath == g.goImportPath {
980 return ident.GoName
981 }
982 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
983 return string(packageName) + "." + ident.GoName
984 }
985 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -0800986 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700987 packageName = orig + GoPackageName(strconv.Itoa(i))
988 }
989 g.packageNames[ident.GoImportPath] = packageName
990 g.usedPackageNames[packageName] = true
991 return string(packageName) + "." + ident.GoName
992}
993
Damien Neil2e0c3da2018-09-19 12:51:36 -0700994// Import ensures a package is imported by the generated file.
995//
996// Packages referenced by QualifiedGoIdent are automatically imported.
997// Explicitly importing a package with Import is generally only necessary
998// when the import will be blank (import _ "package").
999func (g *GeneratedFile) Import(importPath GoImportPath) {
1000 g.manualImports[importPath] = true
1001}
1002
Damien Neil220c2022018-08-15 11:24:18 -07001003// Write implements io.Writer.
1004func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1005 return g.buf.Write(p)
1006}
1007
Damien Neil7bf3ce22018-12-21 15:54:06 -08001008// Skip removes the generated file from the plugin output.
1009func (g *GeneratedFile) Skip() {
1010 g.skip = true
1011}
1012
Damien Neil162c1272018-10-04 12:42:37 -07001013// Annotate associates a symbol in a generated Go file with a location in a
1014// source .proto file.
1015//
1016// The symbol may refer to a type, constant, variable, function, method, or
1017// struct field. The "T.sel" syntax is used to identify the method or field
1018// 'sel' on type 'T'.
1019func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1020 g.annotations[symbol] = append(g.annotations[symbol], loc)
1021}
1022
Damien Neil7bf3ce22018-12-21 15:54:06 -08001023// Content returns the contents of the generated file.
1024func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001025 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001026 return g.buf.Bytes(), nil
1027 }
1028
1029 // Reformat generated code.
1030 original := g.buf.Bytes()
1031 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001032 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001033 if err != nil {
1034 // Print out the bad code with line numbers.
1035 // This should never happen in practice, but it can while changing generated code
1036 // so consider this a debugging aid.
1037 var src bytes.Buffer
1038 s := bufio.NewScanner(bytes.NewReader(original))
1039 for line := 1; s.Scan(); line++ {
1040 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1041 }
Damien Neild9016772018-08-23 14:39:30 -07001042 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001043 }
Damien Neild9016772018-08-23 14:39:30 -07001044
Joe Tsaibeda4042019-03-10 16:40:48 -07001045 // Collect a sorted list of all imports.
1046 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001047 rewriteImport := func(importPath string) string {
1048 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1049 return string(f(GoImportPath(importPath)))
1050 }
1051 return importPath
1052 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001053 for importPath := range g.packageNames {
1054 pkgName := string(g.packageNames[GoImportPath(importPath)])
1055 pkgPath := rewriteImport(string(importPath))
1056 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001057 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001058 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001059 if _, ok := g.packageNames[importPath]; !ok {
1060 pkgPath := rewriteImport(string(importPath))
1061 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001062 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001063 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001064 sort.Slice(importPaths, func(i, j int) bool {
1065 return importPaths[i][1] < importPaths[j][1]
1066 })
1067
1068 // Modify the AST to include a new import block.
1069 if len(importPaths) > 0 {
1070 // Insert block after package statement or
1071 // possible comment attached to the end of the package statement.
1072 pos := file.Package
1073 tokFile := fset.File(file.Package)
1074 pkgLine := tokFile.Line(file.Package)
1075 for _, c := range file.Comments {
1076 if tokFile.Line(c.Pos()) > pkgLine {
1077 break
1078 }
1079 pos = c.End()
1080 }
1081
1082 // Construct the import block.
1083 impDecl := &ast.GenDecl{
1084 Tok: token.IMPORT,
1085 TokPos: pos,
1086 Lparen: pos,
1087 Rparen: pos,
1088 }
1089 for _, importPath := range importPaths {
1090 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1091 Name: &ast.Ident{
1092 Name: importPath[0],
1093 NamePos: pos,
1094 },
1095 Path: &ast.BasicLit{
1096 Kind: token.STRING,
1097 Value: strconv.Quote(importPath[1]),
1098 ValuePos: pos,
1099 },
1100 EndPos: pos,
1101 })
1102 }
1103 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1104 }
Damien Neild9016772018-08-23 14:39:30 -07001105
Damien Neilc7d07d92018-08-22 13:46:02 -07001106 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001107 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001108 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001109 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001110 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001111}
Damien Neilc7d07d92018-08-22 13:46:02 -07001112
Damien Neil162c1272018-10-04 12:42:37 -07001113// metaFile returns the contents of the file's metadata file, which is a
1114// text formatted string of the google.protobuf.GeneratedCodeInfo.
1115func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1116 fset := token.NewFileSet()
1117 astFile, err := parser.ParseFile(fset, "", content, 0)
1118 if err != nil {
1119 return "", err
1120 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001121 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001122
1123 seenAnnotations := make(map[string]bool)
1124 annotate := func(s string, ident *ast.Ident) {
1125 seenAnnotations[s] = true
1126 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001127 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001128 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001129 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001130 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1131 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001132 })
1133 }
1134 }
1135 for _, decl := range astFile.Decls {
1136 switch decl := decl.(type) {
1137 case *ast.GenDecl:
1138 for _, spec := range decl.Specs {
1139 switch spec := spec.(type) {
1140 case *ast.TypeSpec:
1141 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001142 switch st := spec.Type.(type) {
1143 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001144 for _, field := range st.Fields.List {
1145 for _, name := range field.Names {
1146 annotate(spec.Name.Name+"."+name.Name, name)
1147 }
1148 }
Damien Neilae2a5612018-12-12 08:54:57 -08001149 case *ast.InterfaceType:
1150 for _, field := range st.Methods.List {
1151 for _, name := range field.Names {
1152 annotate(spec.Name.Name+"."+name.Name, name)
1153 }
1154 }
Damien Neil162c1272018-10-04 12:42:37 -07001155 }
1156 case *ast.ValueSpec:
1157 for _, name := range spec.Names {
1158 annotate(name.Name, name)
1159 }
1160 }
1161 }
1162 case *ast.FuncDecl:
1163 if decl.Recv == nil {
1164 annotate(decl.Name.Name, decl.Name)
1165 } else {
1166 recv := decl.Recv.List[0].Type
1167 if s, ok := recv.(*ast.StarExpr); ok {
1168 recv = s.X
1169 }
1170 if id, ok := recv.(*ast.Ident); ok {
1171 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1172 }
1173 }
1174 }
1175 }
1176 for a := range g.annotations {
1177 if !seenAnnotations[a] {
1178 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1179 }
1180 }
1181
Damien Neil5c5b5312019-05-14 12:44:37 -07001182 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001183 if err != nil {
1184 return "", err
1185 }
1186 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001187}
Damien Neil082ce922018-09-06 10:23:53 -07001188
Joe Tsai2e7817f2019-08-23 12:18:57 -07001189// A GoIdent is a Go identifier, consisting of a name and import path.
1190// The name is a single identifier and may not be a dot-qualified selector.
1191type GoIdent struct {
1192 GoName string
1193 GoImportPath GoImportPath
1194}
1195
1196func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1197
1198// newGoIdent returns the Go identifier for a descriptor.
1199func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1200 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1201 return GoIdent{
1202 GoName: strs.GoCamelCase(name),
1203 GoImportPath: f.GoImportPath,
1204 }
1205}
1206
1207// A GoImportPath is the import path of a Go package.
1208// For example: "google.golang.org/protobuf/compiler/protogen"
1209type GoImportPath string
1210
1211func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1212
1213// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1214func (p GoImportPath) Ident(s string) GoIdent {
1215 return GoIdent{GoName: s, GoImportPath: p}
1216}
1217
1218// A GoPackageName is the name of a Go package. e.g., "protobuf".
1219type GoPackageName string
1220
1221// cleanPackageName converts a string to a valid Go package name.
1222func cleanPackageName(name string) GoPackageName {
1223 return GoPackageName(strs.GoSanitized(name))
1224}
1225
1226// baseName returns the last path element of the name, with the last dotted suffix removed.
1227func baseName(name string) string {
1228 // First, find the last element
1229 if i := strings.LastIndex(name, "/"); i >= 0 {
1230 name = name[i+1:]
1231 }
1232 // Now drop the suffix
1233 if i := strings.LastIndex(name, "."); i >= 0 {
1234 name = name[:i]
1235 }
1236 return name
1237}
1238
Damien Neil082ce922018-09-06 10:23:53 -07001239type pathType int
1240
1241const (
1242 pathTypeImport pathType = iota
1243 pathTypeSourceRelative
1244)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001245
Damien Neil162c1272018-10-04 12:42:37 -07001246// A Location is a location in a .proto source file.
1247//
1248// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1249// for details.
1250type Location struct {
1251 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001252 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001253}
1254
1255// appendPath add elements to a Location's path, returning a new Location.
1256func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001257 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001258 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001259 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001260 return Location{
1261 SourceFile: loc.SourceFile,
1262 Path: n,
1263 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001264}
Damien Neilba1159f2018-10-17 12:53:18 -07001265
1266// A pathKey is a representation of a location path suitable for use as a map key.
1267type pathKey struct {
1268 s string
1269}
1270
1271// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001272func newPathKey(idxPath []int32) pathKey {
1273 buf := make([]byte, 4*len(idxPath))
1274 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001275 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1276 }
1277 return pathKey{string(buf)}
1278}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001279
1280// CommentSet is a set of leading and trailing comments associated
1281// with a .proto descriptor declaration.
1282type CommentSet struct {
1283 LeadingDetached []Comments
1284 Leading Comments
1285 Trailing Comments
1286}
1287
1288// Comments is a comments string as provided by protoc.
1289type Comments string
1290
1291// String formats the comments by inserting // to the start of each line,
1292// ensuring that there is a trailing newline.
1293// An empty comment is formatted as an empty string.
1294func (c Comments) String() string {
1295 if c == "" {
1296 return ""
1297 }
1298 var b []byte
1299 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1300 b = append(b, "//"...)
1301 b = append(b, line...)
1302 b = append(b, "\n"...)
1303 }
1304 return string(b)
1305}