blob: 0620d3ab3dcce8e6a7c5d958f4b54c16a667d207 [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"
Damien Neile89e6242019-05-13 23:55:40 -070033 "google.golang.org/protobuf/proto"
34 "google.golang.org/protobuf/reflect/protodesc"
35 "google.golang.org/protobuf/reflect/protoreflect"
36 "google.golang.org/protobuf/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080037
Joe Tsaia95b29f2019-05-16 12:47:20 -070038 "google.golang.org/protobuf/types/descriptorpb"
39 "google.golang.org/protobuf/types/pluginpb"
Damien Neil220c2022018-08-15 11:24:18 -070040)
41
42// Run executes a function as a protoc plugin.
43//
44// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
45// function, and writes a CodeGeneratorResponse message to os.Stdout.
46//
47// If a failure occurs while reading or writing, Run prints an error to
48// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070049//
50// Passing a nil options is equivalent to passing a zero-valued one.
51func Run(opts *Options, f func(*Plugin) error) {
52 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070053 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
54 os.Exit(1)
55 }
56}
57
Damien Neil3cf6e622018-09-11 13:53:14 -070058func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070059 if len(os.Args) > 1 {
60 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
61 }
Damien Neil220c2022018-08-15 11:24:18 -070062 in, err := ioutil.ReadAll(os.Stdin)
63 if err != nil {
64 return err
65 }
66 req := &pluginpb.CodeGeneratorRequest{}
67 if err := proto.Unmarshal(in, req); err != nil {
68 return err
69 }
Damien Neil3cf6e622018-09-11 13:53:14 -070070 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070071 if err != nil {
72 return err
73 }
74 if err := f(gen); err != nil {
75 // Errors from the plugin function are reported by setting the
76 // error field in the CodeGeneratorResponse.
77 //
78 // In contrast, errors that indicate a problem in protoc
79 // itself (unparsable input, I/O errors, etc.) are reported
80 // to stderr.
81 gen.Error(err)
82 }
83 resp := gen.Response()
84 out, err := proto.Marshal(resp)
85 if err != nil {
86 return err
87 }
88 if _, err := os.Stdout.Write(out); err != nil {
89 return err
90 }
91 return nil
92}
93
94// A Plugin is a protoc plugin invocation.
95type Plugin struct {
96 // Request is the CodeGeneratorRequest provided by protoc.
97 Request *pluginpb.CodeGeneratorRequest
98
99 // Files is the set of files to generate and everything they import.
100 // Files appear in topological order, so each file appears before any
101 // file that imports it.
102 Files []*File
Joe Tsai2cec4842019-08-20 20:14:19 -0700103 FilesByPath map[string]*File
Damien Neil220c2022018-08-15 11:24:18 -0700104
Damien Neil658051b2018-09-10 12:26:21 -0700105 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700106 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700107 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700108 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700109 pathType pathType
110 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700111 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700112 err error
Damien Neil220c2022018-08-15 11:24:18 -0700113}
114
Damien Neil3cf6e622018-09-11 13:53:14 -0700115// Options are optional parameters to New.
116type Options struct {
117 // If ParamFunc is non-nil, it will be called with each unknown
118 // generator parameter.
119 //
120 // Plugins for protoc can accept parameters from the command line,
121 // passed in the --<lang>_out protoc, separated from the output
122 // directory with a colon; e.g.,
123 //
124 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
125 //
126 // Parameters passed in this fashion as a comma-separated list of
127 // key=value pairs will be passed to the ParamFunc.
128 //
129 // The (flag.FlagSet).Set method matches this function signature,
130 // so parameters can be converted into flags as in the following:
131 //
132 // var flags flag.FlagSet
133 // value := flags.Bool("param", false, "")
134 // opts := &protogen.Options{
135 // ParamFunc: flags.Set,
136 // }
137 // protogen.Run(opts, func(p *protogen.Plugin) error {
138 // if *value { ... }
139 // })
140 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700141
142 // ImportRewriteFunc is called with the import path of each package
143 // imported by a generated file. It returns the import path to use
144 // for this package.
145 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700146}
147
Damien Neil220c2022018-08-15 11:24:18 -0700148// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700149//
150// Passing a nil Options is equivalent to passing a zero-valued one.
151func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
152 if opts == nil {
153 opts = &Options{}
154 }
Damien Neil220c2022018-08-15 11:24:18 -0700155 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700156 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700157 FilesByPath: make(map[string]*File),
Damien Neil658051b2018-09-10 12:26:21 -0700158 fileReg: protoregistry.NewFiles(),
Damien Neil658051b2018-09-10 12:26:21 -0700159 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700160 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700161 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700162 }
163
Damien Neil082ce922018-09-06 10:23:53 -0700164 packageNames := make(map[string]GoPackageName) // filename -> package name
165 importPaths := make(map[string]GoImportPath) // filename -> import path
166 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700167 for _, param := range strings.Split(req.GetParameter(), ",") {
168 var value string
169 if i := strings.Index(param, "="); i >= 0 {
170 value = param[i+1:]
171 param = param[0:i]
172 }
173 switch param {
174 case "":
175 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700176 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700177 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700178 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700179 switch value {
180 case "import":
181 gen.pathType = pathTypeImport
182 case "source_relative":
183 gen.pathType = pathTypeSourceRelative
184 default:
185 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
186 }
Damien Neil220c2022018-08-15 11:24:18 -0700187 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700188 switch value {
189 case "true", "":
190 gen.annotateCode = true
191 case "false":
192 default:
193 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
194 }
Damien Neil220c2022018-08-15 11:24:18 -0700195 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700196 if param[0] == 'M' {
197 importPaths[param[1:]] = GoImportPath(value)
198 continue
Damien Neil220c2022018-08-15 11:24:18 -0700199 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700200 if opts.ParamFunc != nil {
201 if err := opts.ParamFunc(param, value); err != nil {
202 return nil, err
203 }
204 }
Damien Neil082ce922018-09-06 10:23:53 -0700205 }
206 }
207
208 // Figure out the import path and package name for each file.
209 //
210 // The rules here are complicated and have grown organically over time.
211 // Interactions between different ways of specifying package information
212 // may be surprising.
213 //
214 // The recommended approach is to include a go_package option in every
215 // .proto source file specifying the full import path of the Go package
216 // associated with this file.
217 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700218 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700219 //
220 // Build systems which want to exert full control over import paths may
221 // specify M<filename>=<import_path> flags.
222 //
223 // Other approaches are not recommend.
224 generatedFileNames := make(map[string]bool)
225 for _, name := range gen.Request.FileToGenerate {
226 generatedFileNames[name] = true
227 }
228 // We need to determine the import paths before the package names,
229 // because the Go package name for a file is sometimes derived from
230 // different file in the same package.
231 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
232 for _, fdesc := range gen.Request.ProtoFile {
233 filename := fdesc.GetName()
234 packageName, importPath := goPackageOption(fdesc)
235 switch {
236 case importPaths[filename] != "":
237 // Command line: M=foo.proto=quux/bar
238 //
239 // Explicit mapping of source file to import path.
240 case generatedFileNames[filename] && packageImportPath != "":
241 // Command line: import_path=quux/bar
242 //
243 // The import_path flag sets the import path for every file that
244 // we generate code for.
245 importPaths[filename] = packageImportPath
246 case importPath != "":
247 // Source file: option go_package = "quux/bar";
248 //
249 // The go_package option sets the import path. Most users should use this.
250 importPaths[filename] = importPath
251 default:
252 // Source filename.
253 //
254 // Last resort when nothing else is available.
255 importPaths[filename] = GoImportPath(path.Dir(filename))
256 }
257 if packageName != "" {
258 packageNameForImportPath[importPaths[filename]] = packageName
259 }
260 }
261 for _, fdesc := range gen.Request.ProtoFile {
262 filename := fdesc.GetName()
263 packageName, _ := goPackageOption(fdesc)
264 defaultPackageName := packageNameForImportPath[importPaths[filename]]
265 switch {
266 case packageName != "":
267 // Source file: option go_package = "quux/bar";
268 packageNames[filename] = packageName
269 case defaultPackageName != "":
270 // A go_package option in another file in the same package.
271 //
272 // This is a poor choice in general, since every source file should
273 // contain a go_package option. Supported mainly for historical
274 // compatibility.
275 packageNames[filename] = defaultPackageName
276 case generatedFileNames[filename] && packageImportPath != "":
277 // Command line: import_path=quux/bar
278 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
279 case fdesc.GetPackage() != "":
280 // Source file: package quux.bar;
281 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
282 default:
283 // Source filename.
284 packageNames[filename] = cleanPackageName(baseName(filename))
285 }
286 }
287
288 // Consistency check: Every file with the same Go import path should have
289 // the same Go package name.
290 packageFiles := make(map[GoImportPath][]string)
291 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700292 if _, ok := packageNames[filename]; !ok {
293 // Skip files mentioned in a M<file>=<import_path> parameter
294 // but which do not appear in the CodeGeneratorRequest.
295 continue
296 }
Damien Neil082ce922018-09-06 10:23:53 -0700297 packageFiles[importPath] = append(packageFiles[importPath], filename)
298 }
299 for importPath, filenames := range packageFiles {
300 for i := 1; i < len(filenames); i++ {
301 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
302 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
303 importPath, a, filenames[0], b, filenames[i])
304 }
Damien Neil220c2022018-08-15 11:24:18 -0700305 }
306 }
307
308 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700309 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700310 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700311 return nil, fmt.Errorf("duplicate file name: %q", filename)
312 }
313 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700314 if err != nil {
315 return nil, err
316 }
Damien Neil220c2022018-08-15 11:24:18 -0700317 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700318 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700319 }
Damien Neil082ce922018-09-06 10:23:53 -0700320 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700321 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700322 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700323 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700324 }
325 f.Generate = true
326 }
327 return gen, nil
328}
329
330// Error records an error in code generation. The generator will report the
331// error back to protoc and will not produce output.
332func (gen *Plugin) Error(err error) {
333 if gen.err == nil {
334 gen.err = err
335 }
336}
337
338// Response returns the generator output.
339func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
340 resp := &pluginpb.CodeGeneratorResponse{}
341 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700342 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700343 return resp
344 }
Damien Neil162c1272018-10-04 12:42:37 -0700345 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800346 if g.skip {
347 continue
348 }
349 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700350 if err != nil {
351 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700352 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700353 }
354 }
Damien Neil220c2022018-08-15 11:24:18 -0700355 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700356 Name: proto.String(g.filename),
357 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700358 })
Damien Neil162c1272018-10-04 12:42:37 -0700359 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
360 meta, err := g.metaFile(content)
361 if err != nil {
362 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700363 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700364 }
365 }
366 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700367 Name: proto.String(g.filename + ".meta"),
368 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700369 })
370 }
Damien Neil220c2022018-08-15 11:24:18 -0700371 }
372 return resp
373}
374
Damien Neilc7d07d92018-08-22 13:46:02 -0700375// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700376type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700377 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800378 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700379
Joe Tsaib6405bd2018-11-15 14:44:37 -0800380 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
381 GoPackageName GoPackageName // name of this file's Go package
382 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700383
384 Enums []*Enum // top-level enum declarations
385 Messages []*Message // top-level message declarations
386 Extensions []*Extension // top-level extension declarations
387 Services []*Service // top-level service declarations
388
389 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700390
391 // GeneratedFilenamePrefix is used to construct filenames for generated
392 // files associated with this source file.
393 //
394 // For example, the source file "dir/foo.proto" might have a filename prefix
395 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
396 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700397
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700398 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700399}
400
Joe Tsaie1f8d502018-11-26 18:55:29 -0800401func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
402 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700403 if err != nil {
404 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
405 }
406 if err := gen.fileReg.Register(desc); err != nil {
407 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
408 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700409 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700410 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700411 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700412 GoPackageName: packageName,
413 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700414 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700415 }
Damien Neil082ce922018-09-06 10:23:53 -0700416
417 // Determine the prefix for generated Go files.
418 prefix := p.GetName()
419 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
420 prefix = prefix[:len(prefix)-len(ext)]
421 }
422 if gen.pathType == pathTypeImport {
423 // If paths=import (the default) and the file contains a go_package option
424 // with a full import path, the output filename is derived from the Go import
425 // path.
426 //
427 // Pass the paths=source_relative flag to always derive the output filename
428 // from the input filename instead.
429 if _, importPath := goPackageOption(p); importPath != "" {
430 prefix = path.Join(string(importPath), path.Base(prefix))
431 }
432 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800433 f.GoDescriptorIdent = GoIdent{
Joe Tsai40692112019-02-27 20:25:51 -0800434 GoName: "File_" + cleanGoName(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800435 GoImportPath: f.GoImportPath,
436 }
Damien Neil082ce922018-09-06 10:23:53 -0700437 f.GeneratedFilenamePrefix = prefix
438
Damien Neilba1159f2018-10-17 12:53:18 -0700439 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700440 // Descriptors declarations are guaranteed to have unique comment sets.
441 // Other locations may not be unique, but we don't use them.
442 var leadingDetached []Comments
443 for _, s := range loc.GetLeadingDetachedComments() {
444 leadingDetached = append(leadingDetached, Comments(s))
445 }
446 f.comments[newPathKey(loc.Path)] = CommentSet{
447 LeadingDetached: leadingDetached,
448 Leading: Comments(loc.GetLeadingComments()),
449 Trailing: Comments(loc.GetTrailingComments()),
450 }
Damien Neilba1159f2018-10-17 12:53:18 -0700451 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700452 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
453 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700454 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700455 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
456 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700457 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700458 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
459 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700460 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700461 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
462 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700463 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700464 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700465 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700466 return nil, err
467 }
468 }
469 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700470 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700471 return nil, err
472 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700473 }
Damien Neil2dc67182018-09-21 15:03:34 -0700474 for _, service := range f.Services {
475 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700476 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700477 return nil, err
478 }
479 }
480 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700481 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700482}
483
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900484func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700485 return Location{
486 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900487 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700488 }
489}
490
Damien Neil082ce922018-09-06 10:23:53 -0700491// goPackageOption interprets a file's go_package option.
492// If there is no go_package, it returns ("", "").
493// If there's a simple name, it returns (pkg, "").
494// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800495func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700496 opt := d.GetOptions().GetGoPackage()
497 if opt == "" {
498 return "", ""
499 }
500 // A semicolon-delimited suffix delimits the import path and package name.
501 if i := strings.Index(opt, ";"); i >= 0 {
502 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
503 }
504 // The presence of a slash implies there's an import path.
505 if i := strings.LastIndex(opt, "/"); i >= 0 {
506 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
507 }
508 return cleanPackageName(opt), ""
509}
510
Joe Tsai7762ec22019-08-20 20:10:23 -0700511// An Enum describes an enum.
512type Enum struct {
513 Desc protoreflect.EnumDescriptor
514
515 GoIdent GoIdent // name of the generated Go type
516
517 Values []*EnumValue // enum value declarations
518
519 Location Location // location of this enum
520 Comments CommentSet // comments associated with this enum
521}
522
523func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
524 var loc Location
525 if parent != nil {
526 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
527 } else {
528 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
529 }
530 enum := &Enum{
531 Desc: desc,
532 GoIdent: newGoIdent(f, desc),
533 Location: loc,
534 Comments: f.comments[newPathKey(loc.Path)],
535 }
536 gen.enumsByName[desc.FullName()] = enum
537 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
538 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
539 }
540 return enum
541}
542
543// An EnumValue describes an enum value.
544type EnumValue struct {
545 Desc protoreflect.EnumValueDescriptor
546
547 GoIdent GoIdent // name of the generated Go declaration
548
Joe Tsai4df99fd2019-08-20 22:26:16 -0700549 Parent *Enum // enum in which this value is declared
550
Joe Tsai7762ec22019-08-20 20:10:23 -0700551 Location Location // location of this enum value
552 Comments CommentSet // comments associated with this enum value
553}
554
555func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
556 // A top-level enum value's name is: EnumName_ValueName
557 // An enum value contained in a message is: MessageName_ValueName
558 //
559 // Enum value names are not camelcased.
560 parentIdent := enum.GoIdent
561 if message != nil {
562 parentIdent = message.GoIdent
563 }
564 name := parentIdent.GoName + "_" + string(desc.Name())
565 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
566 return &EnumValue{
567 Desc: desc,
568 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700569 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700570 Location: loc,
571 Comments: f.comments[newPathKey(loc.Path)],
572 }
573}
574
Damien Neilc7d07d92018-08-22 13:46:02 -0700575// A Message describes a message.
576type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700577 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700578
Joe Tsai7762ec22019-08-20 20:10:23 -0700579 GoIdent GoIdent // name of the generated Go type
580
581 Fields []*Field // message field declarations
582 Oneofs []*Oneof // message oneof declarations
583
Damien Neil993c04d2018-09-14 15:41:11 -0700584 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700585 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700586 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700587
588 Location Location // location of this message
589 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700590}
591
Damien Neil1fa78d82018-09-13 13:12:36 -0700592func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700593 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700594 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700595 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700596 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700597 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700598 }
Damien Neil46abb572018-09-07 12:45:37 -0700599 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700600 Desc: desc,
601 GoIdent: newGoIdent(f, desc),
602 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700603 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700604 }
Damien Neil658051b2018-09-10 12:26:21 -0700605 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700606 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
607 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700608 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700609 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
610 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700611 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700612 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
613 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700614 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700615 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
616 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700617 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700618 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
619 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
620 }
621
622 // Resolve local references between fields and oneofs.
623 for _, field := range message.Fields {
624 if od := field.Desc.ContainingOneof(); od != nil {
625 oneof := message.Oneofs[od.Index()]
626 field.Oneof = oneof
627 oneof.Fields = append(oneof.Fields, field)
628 }
Damien Neil993c04d2018-09-14 15:41:11 -0700629 }
Damien Neil658051b2018-09-10 12:26:21 -0700630
631 // Field name conflict resolution.
632 //
633 // We assume well-known method names that may be attached to a generated
634 // message type, as well as a 'Get*' method for each field. For each
635 // field in turn, we add _s to its name until there are no conflicts.
636 //
637 // Any change to the following set of method names is a potential
638 // incompatible API change because it may change generated field names.
639 //
640 // TODO: If we ever support a 'go_name' option to set the Go name of a
641 // field, we should consider dropping this entirely. The conflict
642 // resolution algorithm is subtle and surprising (changing the order
643 // in which fields appear in the .proto source file can change the
644 // names of fields in generated code), and does not adapt well to
645 // adding new per-field methods such as setters.
646 usedNames := map[string]bool{
647 "Reset": true,
648 "String": true,
649 "ProtoMessage": true,
650 "Marshal": true,
651 "Unmarshal": true,
652 "ExtensionRangeArray": true,
653 "ExtensionMap": true,
654 "Descriptor": true,
655 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800656 makeNameUnique := func(name string, hasGetter bool) string {
657 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700658 name += "_"
659 }
660 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800661 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700662 return name
663 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700664 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700665 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800666 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaid24bc722019-04-15 23:39:09 -0700667 if field.Oneof != nil {
668 if !seenOneofs[field.Oneof.Desc.Index()] {
Damien Neil1fa78d82018-09-13 13:12:36 -0700669 // If this is a field in a oneof that we haven't seen before,
670 // make the name for that oneof unique as well.
Joe Tsaid24bc722019-04-15 23:39:09 -0700671 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
672 seenOneofs[field.Oneof.Desc.Index()] = true
Damien Neil1fa78d82018-09-13 13:12:36 -0700673 }
674 }
Damien Neil658051b2018-09-10 12:26:21 -0700675 }
676
Damien Neil1fa78d82018-09-13 13:12:36 -0700677 return message
Damien Neil658051b2018-09-10 12:26:21 -0700678}
679
Joe Tsai7762ec22019-08-20 20:10:23 -0700680func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700681 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700682 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700683 return err
684 }
685 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700686 for _, message := range message.Messages {
687 if err := message.resolveDependencies(gen); err != nil {
688 return err
689 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700690 }
Damien Neil993c04d2018-09-14 15:41:11 -0700691 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700692 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700693 return err
694 }
695 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700696 return nil
697}
698
Damien Neil658051b2018-09-10 12:26:21 -0700699// A Field describes a message field.
700type Field struct {
701 Desc protoreflect.FieldDescriptor
702
Damien Neil1fa78d82018-09-13 13:12:36 -0700703 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700704 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700705 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
706 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700707
Joe Tsai7762ec22019-08-20 20:10:23 -0700708 Parent *Message // message in which this field is declared; nil if top-level extension
709 Oneof *Oneof // containing oneof; nil if not part of a oneof
710 Extendee *Message // extended message for extension fields; nil otherwise
711
712 Enum *Enum // type for enum fields; nil otherwise
713 Message *Message // type for message or group fields; nil otherwise
714
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700715 Location Location // location of this field
716 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700717}
718
Damien Neil1fa78d82018-09-13 13:12:36 -0700719func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700720 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700721 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700722 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700723 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700724 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700725 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700726 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700727 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700728 }
Damien Neil658051b2018-09-10 12:26:21 -0700729 field := &Field{
Joe Tsaid24bc722019-04-15 23:39:09 -0700730 Desc: desc,
731 GoName: camelCase(string(desc.Name())),
732 Parent: message,
733 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700734 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700735 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700736 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700737}
738
Joe Tsai7762ec22019-08-20 20:10:23 -0700739func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700740 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700741 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700742 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700743 name := field.Desc.Enum().FullName()
744 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700745 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700746 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700747 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700748 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700749 case protoreflect.MessageKind, protoreflect.GroupKind:
750 name := desc.Message().FullName()
751 message, ok := gen.messagesByName[name]
752 if !ok {
753 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
754 }
755 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700756 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700757 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700758 name := desc.ContainingMessage().FullName()
759 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700760 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700761 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700762 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700763 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700764 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700765 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700766}
767
Joe Tsai7762ec22019-08-20 20:10:23 -0700768// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700769type Oneof struct {
770 Desc protoreflect.OneofDescriptor
771
Joe Tsai7762ec22019-08-20 20:10:23 -0700772 GoName string // Go field name of this oneof
773
774 Parent *Message // message in which this oneof is declared
775
Joe Tsaid24bc722019-04-15 23:39:09 -0700776 Fields []*Field // fields that are part of this oneof
777
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700778 Location Location // location of this oneof
779 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700780}
781
782func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700783 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Damien Neil1fa78d82018-09-13 13:12:36 -0700784 return &Oneof{
Joe Tsaid24bc722019-04-15 23:39:09 -0700785 Desc: desc,
786 Parent: message,
787 GoName: camelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700788 Location: loc,
789 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700790 }
791}
792
Joe Tsai7762ec22019-08-20 20:10:23 -0700793// Extension is an alias of Field for documentation.
794type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700795
Damien Neil2dc67182018-09-21 15:03:34 -0700796// A Service describes a service.
797type Service struct {
798 Desc protoreflect.ServiceDescriptor
799
Joe Tsai7762ec22019-08-20 20:10:23 -0700800 GoName string
801
802 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700803
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700804 Location Location // location of this service
805 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700806}
807
808func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700809 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700810 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700811 Desc: desc,
812 GoName: camelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700813 Location: loc,
814 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700815 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700816 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
817 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700818 }
819 return service
820}
821
822// A Method describes a method in a service.
823type Method struct {
824 Desc protoreflect.MethodDescriptor
825
Joe Tsaid24bc722019-04-15 23:39:09 -0700826 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700827
828 Parent *Service // service in which this method is declared
829
Joe Tsaid24bc722019-04-15 23:39:09 -0700830 Input *Message
831 Output *Message
832
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700833 Location Location // location of this method
834 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700835}
836
837func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700838 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700839 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700840 Desc: desc,
841 GoName: camelCase(string(desc.Name())),
842 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700843 Location: loc,
844 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700845 }
846 return method
847}
848
Joe Tsai7762ec22019-08-20 20:10:23 -0700849func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700850 desc := method.Desc
851
Joe Tsaid24bc722019-04-15 23:39:09 -0700852 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700853 in, ok := gen.messagesByName[inName]
854 if !ok {
855 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
856 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700857 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700858
Joe Tsaid24bc722019-04-15 23:39:09 -0700859 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700860 out, ok := gen.messagesByName[outName]
861 if !ok {
862 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
863 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700864 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700865
866 return nil
867}
868
Damien Neil7bf3ce22018-12-21 15:54:06 -0800869// A GeneratedFile is a generated file.
870type GeneratedFile struct {
871 gen *Plugin
872 skip bool
873 filename string
874 goImportPath GoImportPath
875 buf bytes.Buffer
876 packageNames map[GoImportPath]GoPackageName
877 usedPackageNames map[GoPackageName]bool
878 manualImports map[GoImportPath]bool
879 annotations map[string][]Location
880}
881
882// NewGeneratedFile creates a new generated file with the given filename
883// and import path.
884func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
885 g := &GeneratedFile{
886 gen: gen,
887 filename: filename,
888 goImportPath: goImportPath,
889 packageNames: make(map[GoImportPath]GoPackageName),
890 usedPackageNames: make(map[GoPackageName]bool),
891 manualImports: make(map[GoImportPath]bool),
892 annotations: make(map[string][]Location),
893 }
Joe Tsai124c8122019-01-14 11:48:43 -0800894
895 // All predeclared identifiers in Go are already used.
896 for _, s := range types.Universe.Names() {
897 g.usedPackageNames[GoPackageName(s)] = true
898 }
899
Damien Neil7bf3ce22018-12-21 15:54:06 -0800900 gen.genFiles = append(gen.genFiles, g)
901 return g
902}
903
Damien Neil220c2022018-08-15 11:24:18 -0700904// P prints a line to the generated output. It converts each parameter to a
905// string following the same rules as fmt.Print. It never inserts spaces
906// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700907func (g *GeneratedFile) P(v ...interface{}) {
908 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700909 switch x := x.(type) {
910 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700911 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700912 default:
913 fmt.Fprint(&g.buf, x)
914 }
Damien Neil220c2022018-08-15 11:24:18 -0700915 }
916 fmt.Fprintln(&g.buf)
917}
918
Damien Neil46abb572018-09-07 12:45:37 -0700919// QualifiedGoIdent returns the string to use for a Go identifier.
920//
921// If the identifier is from a different Go package than the generated file,
922// the returned name will be qualified (package.name) and an import statement
923// for the identifier's package will be included in the file.
924func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
925 if ident.GoImportPath == g.goImportPath {
926 return ident.GoName
927 }
928 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
929 return string(packageName) + "." + ident.GoName
930 }
931 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -0800932 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700933 packageName = orig + GoPackageName(strconv.Itoa(i))
934 }
935 g.packageNames[ident.GoImportPath] = packageName
936 g.usedPackageNames[packageName] = true
937 return string(packageName) + "." + ident.GoName
938}
939
Damien Neil2e0c3da2018-09-19 12:51:36 -0700940// Import ensures a package is imported by the generated file.
941//
942// Packages referenced by QualifiedGoIdent are automatically imported.
943// Explicitly importing a package with Import is generally only necessary
944// when the import will be blank (import _ "package").
945func (g *GeneratedFile) Import(importPath GoImportPath) {
946 g.manualImports[importPath] = true
947}
948
Damien Neil220c2022018-08-15 11:24:18 -0700949// Write implements io.Writer.
950func (g *GeneratedFile) Write(p []byte) (n int, err error) {
951 return g.buf.Write(p)
952}
953
Damien Neil7bf3ce22018-12-21 15:54:06 -0800954// Skip removes the generated file from the plugin output.
955func (g *GeneratedFile) Skip() {
956 g.skip = true
957}
958
Damien Neil162c1272018-10-04 12:42:37 -0700959// Annotate associates a symbol in a generated Go file with a location in a
960// source .proto file.
961//
962// The symbol may refer to a type, constant, variable, function, method, or
963// struct field. The "T.sel" syntax is used to identify the method or field
964// 'sel' on type 'T'.
965func (g *GeneratedFile) Annotate(symbol string, loc Location) {
966 g.annotations[symbol] = append(g.annotations[symbol], loc)
967}
968
Damien Neil7bf3ce22018-12-21 15:54:06 -0800969// Content returns the contents of the generated file.
970func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700971 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700972 return g.buf.Bytes(), nil
973 }
974
975 // Reformat generated code.
976 original := g.buf.Bytes()
977 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700978 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700979 if err != nil {
980 // Print out the bad code with line numbers.
981 // This should never happen in practice, but it can while changing generated code
982 // so consider this a debugging aid.
983 var src bytes.Buffer
984 s := bufio.NewScanner(bytes.NewReader(original))
985 for line := 1; s.Scan(); line++ {
986 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
987 }
Damien Neild9016772018-08-23 14:39:30 -0700988 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700989 }
Damien Neild9016772018-08-23 14:39:30 -0700990
Joe Tsaibeda4042019-03-10 16:40:48 -0700991 // Collect a sorted list of all imports.
992 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -0700993 rewriteImport := func(importPath string) string {
994 if f := g.gen.opts.ImportRewriteFunc; f != nil {
995 return string(f(GoImportPath(importPath)))
996 }
997 return importPath
998 }
Joe Tsaibeda4042019-03-10 16:40:48 -0700999 for importPath := range g.packageNames {
1000 pkgName := string(g.packageNames[GoImportPath(importPath)])
1001 pkgPath := rewriteImport(string(importPath))
1002 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001003 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001004 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001005 if _, ok := g.packageNames[importPath]; !ok {
1006 pkgPath := rewriteImport(string(importPath))
1007 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001008 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001009 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001010 sort.Slice(importPaths, func(i, j int) bool {
1011 return importPaths[i][1] < importPaths[j][1]
1012 })
1013
1014 // Modify the AST to include a new import block.
1015 if len(importPaths) > 0 {
1016 // Insert block after package statement or
1017 // possible comment attached to the end of the package statement.
1018 pos := file.Package
1019 tokFile := fset.File(file.Package)
1020 pkgLine := tokFile.Line(file.Package)
1021 for _, c := range file.Comments {
1022 if tokFile.Line(c.Pos()) > pkgLine {
1023 break
1024 }
1025 pos = c.End()
1026 }
1027
1028 // Construct the import block.
1029 impDecl := &ast.GenDecl{
1030 Tok: token.IMPORT,
1031 TokPos: pos,
1032 Lparen: pos,
1033 Rparen: pos,
1034 }
1035 for _, importPath := range importPaths {
1036 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1037 Name: &ast.Ident{
1038 Name: importPath[0],
1039 NamePos: pos,
1040 },
1041 Path: &ast.BasicLit{
1042 Kind: token.STRING,
1043 Value: strconv.Quote(importPath[1]),
1044 ValuePos: pos,
1045 },
1046 EndPos: pos,
1047 })
1048 }
1049 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1050 }
Damien Neild9016772018-08-23 14:39:30 -07001051
Damien Neilc7d07d92018-08-22 13:46:02 -07001052 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001053 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001054 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001055 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001056 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001057}
Damien Neilc7d07d92018-08-22 13:46:02 -07001058
Damien Neil162c1272018-10-04 12:42:37 -07001059// metaFile returns the contents of the file's metadata file, which is a
1060// text formatted string of the google.protobuf.GeneratedCodeInfo.
1061func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1062 fset := token.NewFileSet()
1063 astFile, err := parser.ParseFile(fset, "", content, 0)
1064 if err != nil {
1065 return "", err
1066 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001067 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001068
1069 seenAnnotations := make(map[string]bool)
1070 annotate := func(s string, ident *ast.Ident) {
1071 seenAnnotations[s] = true
1072 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001073 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001074 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001075 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001076 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1077 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001078 })
1079 }
1080 }
1081 for _, decl := range astFile.Decls {
1082 switch decl := decl.(type) {
1083 case *ast.GenDecl:
1084 for _, spec := range decl.Specs {
1085 switch spec := spec.(type) {
1086 case *ast.TypeSpec:
1087 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001088 switch st := spec.Type.(type) {
1089 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001090 for _, field := range st.Fields.List {
1091 for _, name := range field.Names {
1092 annotate(spec.Name.Name+"."+name.Name, name)
1093 }
1094 }
Damien Neilae2a5612018-12-12 08:54:57 -08001095 case *ast.InterfaceType:
1096 for _, field := range st.Methods.List {
1097 for _, name := range field.Names {
1098 annotate(spec.Name.Name+"."+name.Name, name)
1099 }
1100 }
Damien Neil162c1272018-10-04 12:42:37 -07001101 }
1102 case *ast.ValueSpec:
1103 for _, name := range spec.Names {
1104 annotate(name.Name, name)
1105 }
1106 }
1107 }
1108 case *ast.FuncDecl:
1109 if decl.Recv == nil {
1110 annotate(decl.Name.Name, decl.Name)
1111 } else {
1112 recv := decl.Recv.List[0].Type
1113 if s, ok := recv.(*ast.StarExpr); ok {
1114 recv = s.X
1115 }
1116 if id, ok := recv.(*ast.Ident); ok {
1117 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1118 }
1119 }
1120 }
1121 }
1122 for a := range g.annotations {
1123 if !seenAnnotations[a] {
1124 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1125 }
1126 }
1127
Damien Neil5c5b5312019-05-14 12:44:37 -07001128 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001129 if err != nil {
1130 return "", err
1131 }
1132 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001133}
Damien Neil082ce922018-09-06 10:23:53 -07001134
1135type pathType int
1136
1137const (
1138 pathTypeImport pathType = iota
1139 pathTypeSourceRelative
1140)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001141
Damien Neil162c1272018-10-04 12:42:37 -07001142// A Location is a location in a .proto source file.
1143//
1144// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1145// for details.
1146type Location struct {
1147 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001148 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001149}
1150
1151// appendPath add elements to a Location's path, returning a new Location.
1152func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001153 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001154 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001155 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001156 return Location{
1157 SourceFile: loc.SourceFile,
1158 Path: n,
1159 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001160}
Damien Neilba1159f2018-10-17 12:53:18 -07001161
1162// A pathKey is a representation of a location path suitable for use as a map key.
1163type pathKey struct {
1164 s string
1165}
1166
1167// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001168func newPathKey(idxPath []int32) pathKey {
1169 buf := make([]byte, 4*len(idxPath))
1170 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001171 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1172 }
1173 return pathKey{string(buf)}
1174}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001175
1176// CommentSet is a set of leading and trailing comments associated
1177// with a .proto descriptor declaration.
1178type CommentSet struct {
1179 LeadingDetached []Comments
1180 Leading Comments
1181 Trailing Comments
1182}
1183
1184// Comments is a comments string as provided by protoc.
1185type Comments string
1186
1187// String formats the comments by inserting // to the start of each line,
1188// ensuring that there is a trailing newline.
1189// An empty comment is formatted as an empty string.
1190func (c Comments) String() string {
1191 if c == "" {
1192 return ""
1193 }
1194 var b []byte
1195 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1196 b = append(b, "//"...)
1197 b = append(b, line...)
1198 b = append(b, "\n"...)
1199 }
1200 return string(b)
1201}