blob: c380a03a18c98ff96cd0357bceca88f0f7788fb0 [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//
Joe Tsai04f03cb2020-02-14 12:40:48 -08007// Plugins for protoc, the Protocol Buffer compiler,
8// are programs which read a CodeGeneratorRequest message from standard input
9// and write a CodeGeneratorResponse message to standard output.
10// This package provides support for writing plugins which generate Go code.
Damien Neil220c2022018-08-15 11:24:18 -070011package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
16 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070017 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070018 "go/parser"
19 "go/printer"
20 "go/token"
Joe Tsai124c8122019-01-14 11:48:43 -080021 "go/types"
Damien Neil220c2022018-08-15 11:24:18 -070022 "io/ioutil"
Joe Tsai3e802492019-09-07 13:06:27 -070023 "log"
Damien Neil220c2022018-08-15 11:24:18 -070024 "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"
Joe Tsaie0b77db2020-05-26 11:21:59 -070032 "google.golang.org/protobuf/internal/genid"
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
Joe Tsai222a0002020-02-24 11:21:30 -080043const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package"
44
Damien Neil220c2022018-08-15 11:24:18 -070045// Run executes a function as a protoc plugin.
46//
47// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
48// function, and writes a CodeGeneratorResponse message to os.Stdout.
49//
50// If a failure occurs while reading or writing, Run prints an error to
51// os.Stderr and calls os.Exit(1).
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080052func (opts Options) Run(f func(*Plugin) error) {
Damien Neil3cf6e622018-09-11 13:53:14 -070053 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
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080059func 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 }
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080071 gen, err := opts.New(req)
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
Joe Tsai387873d2020-04-28 14:44:38 -0700106 // SupportedFeatures is the set of protobuf language features supported by
107 // this generator plugin. See the documentation for
108 // google.protobuf.CodeGeneratorResponse.supported_features for details.
109 SupportedFeatures uint64
110
Damien Neil658051b2018-09-10 12:26:21 -0700111 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700112 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700113 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700114 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700115 pathType pathType
Damien Neilffbc5fd2020-02-12 23:38:30 -0800116 module string
Damien Neil658051b2018-09-10 12:26:21 -0700117 genFiles []*GeneratedFile
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800118 opts Options
Damien Neil658051b2018-09-10 12:26:21 -0700119 err error
Damien Neil220c2022018-08-15 11:24:18 -0700120}
121
Damien Neil3cf6e622018-09-11 13:53:14 -0700122type Options struct {
123 // If ParamFunc is non-nil, it will be called with each unknown
124 // generator parameter.
125 //
126 // Plugins for protoc can accept parameters from the command line,
127 // passed in the --<lang>_out protoc, separated from the output
128 // directory with a colon; e.g.,
129 //
130 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
131 //
132 // Parameters passed in this fashion as a comma-separated list of
133 // key=value pairs will be passed to the ParamFunc.
134 //
135 // The (flag.FlagSet).Set method matches this function signature,
136 // so parameters can be converted into flags as in the following:
137 //
138 // var flags flag.FlagSet
139 // value := flags.Bool("param", false, "")
140 // opts := &protogen.Options{
141 // ParamFunc: flags.Set,
142 // }
143 // protogen.Run(opts, func(p *protogen.Plugin) error {
144 // if *value { ... }
145 // })
146 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700147
148 // ImportRewriteFunc is called with the import path of each package
149 // imported by a generated file. It returns the import path to use
150 // for this package.
151 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700152}
153
Damien Neil220c2022018-08-15 11:24:18 -0700154// New returns a new Plugin.
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800155func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
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 Neilc8268852019-10-08 13:28:53 -0700159 fileReg: new(protoregistry.Files),
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
Joe Tsai3e802492019-09-07 13:06:27 -0700167 mfiles := make(map[string]bool) // filename set
Damien Neil082ce922018-09-06 10:23:53 -0700168 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700169 for _, param := range strings.Split(req.GetParameter(), ",") {
170 var value string
171 if i := strings.Index(param, "="); i >= 0 {
172 value = param[i+1:]
173 param = param[0:i]
174 }
175 switch param {
176 case "":
177 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700178 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700179 packageImportPath = GoImportPath(value)
Damien Neilffbc5fd2020-02-12 23:38:30 -0800180 case "module":
181 gen.module = value
Damien Neil220c2022018-08-15 11:24:18 -0700182 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700183 switch value {
184 case "import":
185 gen.pathType = pathTypeImport
186 case "source_relative":
187 gen.pathType = pathTypeSourceRelative
188 default:
189 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
190 }
Damien Neil220c2022018-08-15 11:24:18 -0700191 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700192 switch value {
193 case "true", "":
194 gen.annotateCode = true
195 case "false":
196 default:
197 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
198 }
Damien Neil220c2022018-08-15 11:24:18 -0700199 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700200 if param[0] == 'M' {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700201 if i := strings.Index(value, ";"); i >= 0 {
202 pkgName := GoPackageName(value[i+1:])
203 if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName {
204 return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName)
205 }
206 packageNames[param[1:]] = pkgName
207 value = value[:i]
208 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700209 importPaths[param[1:]] = GoImportPath(value)
Joe Tsai3e802492019-09-07 13:06:27 -0700210 mfiles[param[1:]] = true
Damien Neil3cf6e622018-09-11 13:53:14 -0700211 continue
Damien Neil220c2022018-08-15 11:24:18 -0700212 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700213 if opts.ParamFunc != nil {
214 if err := opts.ParamFunc(param, value); err != nil {
215 return nil, err
216 }
217 }
Damien Neil082ce922018-09-06 10:23:53 -0700218 }
219 }
Damien Neilffbc5fd2020-02-12 23:38:30 -0800220 if gen.module != "" {
221 // When the module= option is provided, we strip the module name
222 // prefix from generated files. This only makes sense if generated
223 // filenames are based on the import path, so default to paths=import
224 // and complain if source_relative was selected manually.
225 switch gen.pathType {
226 case pathTypeLegacy:
227 gen.pathType = pathTypeImport
228 case pathTypeSourceRelative:
229 return nil, fmt.Errorf("cannot use module= with paths=source_relative")
230 }
231 }
Damien Neil082ce922018-09-06 10:23:53 -0700232
233 // Figure out the import path and package name for each file.
234 //
235 // The rules here are complicated and have grown organically over time.
236 // Interactions between different ways of specifying package information
237 // may be surprising.
238 //
239 // The recommended approach is to include a go_package option in every
240 // .proto source file specifying the full import path of the Go package
241 // associated with this file.
242 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700243 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700244 //
245 // Build systems which want to exert full control over import paths may
246 // specify M<filename>=<import_path> flags.
247 //
248 // Other approaches are not recommend.
249 generatedFileNames := make(map[string]bool)
250 for _, name := range gen.Request.FileToGenerate {
251 generatedFileNames[name] = true
252 }
253 // We need to determine the import paths before the package names,
254 // because the Go package name for a file is sometimes derived from
255 // different file in the same package.
256 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
257 for _, fdesc := range gen.Request.ProtoFile {
258 filename := fdesc.GetName()
259 packageName, importPath := goPackageOption(fdesc)
260 switch {
261 case importPaths[filename] != "":
Damien Neilaadba562020-02-15 14:28:51 -0800262 // Command line: Mfoo.proto=quux/bar
Damien Neil082ce922018-09-06 10:23:53 -0700263 //
264 // Explicit mapping of source file to import path.
265 case generatedFileNames[filename] && packageImportPath != "":
266 // Command line: import_path=quux/bar
267 //
268 // The import_path flag sets the import path for every file that
269 // we generate code for.
270 importPaths[filename] = packageImportPath
271 case importPath != "":
272 // Source file: option go_package = "quux/bar";
273 //
274 // The go_package option sets the import path. Most users should use this.
275 importPaths[filename] = importPath
276 default:
277 // Source filename.
278 //
279 // Last resort when nothing else is available.
280 importPaths[filename] = GoImportPath(path.Dir(filename))
281 }
282 if packageName != "" {
283 packageNameForImportPath[importPaths[filename]] = packageName
284 }
285 }
286 for _, fdesc := range gen.Request.ProtoFile {
287 filename := fdesc.GetName()
Joe Tsai3e802492019-09-07 13:06:27 -0700288 packageName, importPath := goPackageOption(fdesc)
Damien Neil082ce922018-09-06 10:23:53 -0700289 defaultPackageName := packageNameForImportPath[importPaths[filename]]
290 switch {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700291 case packageNames[filename] != "":
292 // A package name specified by the "M" command-line argument.
Damien Neil082ce922018-09-06 10:23:53 -0700293 case packageName != "":
Joe Tsai3e802492019-09-07 13:06:27 -0700294 // TODO: For the "M" command-line argument, this means that the
295 // package name can be derived from the go_package option.
296 // Go package information should either consistently come from the
297 // command-line or the .proto source file, but not both.
298 // See how to make this consistent.
299
Damien Neil082ce922018-09-06 10:23:53 -0700300 // Source file: option go_package = "quux/bar";
301 packageNames[filename] = packageName
302 case defaultPackageName != "":
303 // A go_package option in another file in the same package.
304 //
305 // This is a poor choice in general, since every source file should
306 // contain a go_package option. Supported mainly for historical
307 // compatibility.
308 packageNames[filename] = defaultPackageName
309 case generatedFileNames[filename] && packageImportPath != "":
310 // Command line: import_path=quux/bar
311 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
312 case fdesc.GetPackage() != "":
313 // Source file: package quux.bar;
314 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
315 default:
316 // Source filename.
317 packageNames[filename] = cleanPackageName(baseName(filename))
318 }
Joe Tsai3e802492019-09-07 13:06:27 -0700319
320 goPkgOpt := string(importPaths[filename])
321 if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
322 goPkgOpt += ";" + string(packageNames[filename])
323 }
324 switch {
325 case packageImportPath != "":
326 // Command line: import_path=quux/bar
Damien Neile358d432020-03-06 13:58:41 -0800327 warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700328 "\toption go_package = %q;\n"+
329 "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800330 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700331 "\n", fdesc.GetName(), goPkgOpt)
332 case mfiles[filename]:
333 // Command line: M=foo.proto=quux/bar
334 case packageName != "" && importPath == "":
335 // Source file: option go_package = "quux";
Damien Neile358d432020-03-06 13:58:41 -0800336 warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700337 "\toption go_package = %q;\n"+
338 "A future release of protoc-gen-go will require the import path be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800339 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700340 "\n", fdesc.GetName(), goPkgOpt)
341 case packageName == "" && importPath == "":
342 // No Go package information provided.
Joe Tsaice5d8312020-05-05 12:01:13 -0700343 dotIdx := strings.Index(goPkgOpt, ".") // heuristic for top-level domain
344 slashIdx := strings.Index(goPkgOpt, "/") // heuristic for multi-segment path
345 if isFull := 0 <= dotIdx && dotIdx <= slashIdx; isFull {
346 warn("Missing 'go_package' option in %q, please specify:\n"+
347 "\toption go_package = %q;\n"+
348 "A future release of protoc-gen-go will require this be specified.\n"+
349 "See "+goPackageDocURL+" for more information.\n"+
350 "\n", fdesc.GetName(), goPkgOpt)
351 } else {
352 warn("Missing 'go_package' option in %q,\n"+
353 "please specify it with the full Go package path as\n"+
354 "a future release of protoc-gen-go will require this be specified.\n"+
355 "See "+goPackageDocURL+" for more information.\n"+
356 "\n", fdesc.GetName())
357 }
Joe Tsai3e802492019-09-07 13:06:27 -0700358 }
Damien Neil082ce922018-09-06 10:23:53 -0700359 }
360
361 // Consistency check: Every file with the same Go import path should have
362 // the same Go package name.
363 packageFiles := make(map[GoImportPath][]string)
364 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700365 if _, ok := packageNames[filename]; !ok {
366 // Skip files mentioned in a M<file>=<import_path> parameter
367 // but which do not appear in the CodeGeneratorRequest.
368 continue
369 }
Damien Neil082ce922018-09-06 10:23:53 -0700370 packageFiles[importPath] = append(packageFiles[importPath], filename)
371 }
372 for importPath, filenames := range packageFiles {
373 for i := 1; i < len(filenames); i++ {
374 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
375 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
376 importPath, a, filenames[0], b, filenames[i])
377 }
Damien Neil220c2022018-08-15 11:24:18 -0700378 }
379 }
380
381 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700382 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700383 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700384 return nil, fmt.Errorf("duplicate file name: %q", filename)
385 }
386 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700387 if err != nil {
388 return nil, err
389 }
Damien Neil220c2022018-08-15 11:24:18 -0700390 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700391 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700392 }
Damien Neil082ce922018-09-06 10:23:53 -0700393 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700394 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700395 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700396 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700397 }
398 f.Generate = true
399 }
400 return gen, nil
401}
402
403// Error records an error in code generation. The generator will report the
404// error back to protoc and will not produce output.
405func (gen *Plugin) Error(err error) {
406 if gen.err == nil {
407 gen.err = err
408 }
409}
410
411// Response returns the generator output.
412func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
413 resp := &pluginpb.CodeGeneratorResponse{}
414 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700415 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700416 return resp
417 }
Damien Neil162c1272018-10-04 12:42:37 -0700418 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800419 if g.skip {
420 continue
421 }
422 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700423 if err != nil {
424 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700425 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700426 }
427 }
Damien Neilffbc5fd2020-02-12 23:38:30 -0800428 filename := g.filename
429 if gen.module != "" {
430 trim := gen.module + "/"
431 if !strings.HasPrefix(filename, trim) {
432 return &pluginpb.CodeGeneratorResponse{
433 Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)),
434 }
435 }
436 filename = strings.TrimPrefix(filename, trim)
437 }
Damien Neil220c2022018-08-15 11:24:18 -0700438 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800439 Name: proto.String(filename),
Damien Neila8a2cea2019-07-10 16:17:16 -0700440 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700441 })
Damien Neil162c1272018-10-04 12:42:37 -0700442 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
443 meta, err := g.metaFile(content)
444 if err != nil {
445 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700446 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700447 }
448 }
449 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800450 Name: proto.String(filename + ".meta"),
Damien Neila8a2cea2019-07-10 16:17:16 -0700451 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700452 })
453 }
Damien Neil220c2022018-08-15 11:24:18 -0700454 }
Joe Tsai387873d2020-04-28 14:44:38 -0700455 if gen.SupportedFeatures > 0 {
456 resp.SupportedFeatures = proto.Uint64(gen.SupportedFeatures)
457 }
Damien Neil220c2022018-08-15 11:24:18 -0700458 return resp
459}
460
Damien Neilc7d07d92018-08-22 13:46:02 -0700461// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700462type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700463 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800464 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700465
Joe Tsaib6405bd2018-11-15 14:44:37 -0800466 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
467 GoPackageName GoPackageName // name of this file's Go package
468 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700469
470 Enums []*Enum // top-level enum declarations
471 Messages []*Message // top-level message declarations
472 Extensions []*Extension // top-level extension declarations
473 Services []*Service // top-level service declarations
474
475 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700476
477 // GeneratedFilenamePrefix is used to construct filenames for generated
478 // files associated with this source file.
479 //
480 // For example, the source file "dir/foo.proto" might have a filename prefix
481 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
482 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700483
Joe Tsai42cc4c52020-06-16 08:48:38 -0700484 location Location
Damien Neil220c2022018-08-15 11:24:18 -0700485}
486
Joe Tsaie1f8d502018-11-26 18:55:29 -0800487func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
488 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700489 if err != nil {
490 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
491 }
Damien Neilc8268852019-10-08 13:28:53 -0700492 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700493 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
494 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700495 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700496 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700497 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700498 GoPackageName: packageName,
499 GoImportPath: importPath,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700500 location: Location{SourceFile: desc.Path()},
Damien Neil220c2022018-08-15 11:24:18 -0700501 }
Damien Neil082ce922018-09-06 10:23:53 -0700502
503 // Determine the prefix for generated Go files.
504 prefix := p.GetName()
505 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
506 prefix = prefix[:len(prefix)-len(ext)]
507 }
Damien Neilaadba562020-02-15 14:28:51 -0800508 switch gen.pathType {
509 case pathTypeLegacy:
510 // The default is to derive the output filename from the Go import path
511 // if the file contains a go_package option,or from the input filename instead.
Damien Neil082ce922018-09-06 10:23:53 -0700512 if _, importPath := goPackageOption(p); importPath != "" {
513 prefix = path.Join(string(importPath), path.Base(prefix))
514 }
Damien Neilaadba562020-02-15 14:28:51 -0800515 case pathTypeImport:
516 // If paths=import, the output filename is derived from the Go import path.
517 prefix = path.Join(string(f.GoImportPath), path.Base(prefix))
518 case pathTypeSourceRelative:
519 // If paths=source_relative, the output filename is derived from
520 // the input filename.
Damien Neil082ce922018-09-06 10:23:53 -0700521 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800522 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700523 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800524 GoImportPath: f.GoImportPath,
525 }
Damien Neil082ce922018-09-06 10:23:53 -0700526 f.GeneratedFilenamePrefix = prefix
527
Joe Tsai7762ec22019-08-20 20:10:23 -0700528 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
529 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700530 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700531 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
532 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700533 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700534 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
535 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700536 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700537 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
538 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700539 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700540 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700541 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700542 return nil, err
543 }
544 }
545 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700546 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700547 return nil, err
548 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700549 }
Damien Neil2dc67182018-09-21 15:03:34 -0700550 for _, service := range f.Services {
551 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700552 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700553 return nil, err
554 }
555 }
556 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700557 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700558}
559
Damien Neil082ce922018-09-06 10:23:53 -0700560// goPackageOption interprets a file's go_package option.
561// If there is no go_package, it returns ("", "").
562// If there's a simple name, it returns (pkg, "").
563// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800564func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700565 opt := d.GetOptions().GetGoPackage()
566 if opt == "" {
567 return "", ""
568 }
Joe Tsai3e802492019-09-07 13:06:27 -0700569 rawPkg, impPath := goPackageOptionRaw(opt)
570 pkg = cleanPackageName(rawPkg)
571 if string(pkg) != rawPkg && impPath != "" {
Damien Neile358d432020-03-06 13:58:41 -0800572 warn("Malformed 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700573 "\toption go_package = %q;\n"+
574 "A future release of protoc-gen-go will reject this.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800575 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700576 "\n", d.GetName(), string(impPath)+";"+string(pkg))
577 }
578 return pkg, impPath
579}
580func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700581 // A semicolon-delimited suffix delimits the import path and package name.
582 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700583 return opt[i+1:], GoImportPath(opt[:i])
Damien Neil082ce922018-09-06 10:23:53 -0700584 }
585 // The presence of a slash implies there's an import path.
586 if i := strings.LastIndex(opt, "/"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700587 return opt[i+1:], GoImportPath(opt)
Damien Neil082ce922018-09-06 10:23:53 -0700588 }
Joe Tsai3e802492019-09-07 13:06:27 -0700589 return opt, ""
Damien Neil082ce922018-09-06 10:23:53 -0700590}
591
Joe Tsai7762ec22019-08-20 20:10:23 -0700592// An Enum describes an enum.
593type Enum struct {
594 Desc protoreflect.EnumDescriptor
595
596 GoIdent GoIdent // name of the generated Go type
597
598 Values []*EnumValue // enum value declarations
599
600 Location Location // location of this enum
601 Comments CommentSet // comments associated with this enum
602}
603
604func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
605 var loc Location
606 if parent != nil {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700607 loc = parent.Location.appendPath(genid.DescriptorProto_EnumType_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700608 } else {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700609 loc = f.location.appendPath(genid.FileDescriptorProto_EnumType_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700610 }
611 enum := &Enum{
612 Desc: desc,
613 GoIdent: newGoIdent(f, desc),
614 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700615 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Joe Tsai7762ec22019-08-20 20:10:23 -0700616 }
617 gen.enumsByName[desc.FullName()] = enum
618 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
619 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
620 }
621 return enum
622}
623
624// An EnumValue describes an enum value.
625type EnumValue struct {
626 Desc protoreflect.EnumValueDescriptor
627
628 GoIdent GoIdent // name of the generated Go declaration
629
Joe Tsai4df99fd2019-08-20 22:26:16 -0700630 Parent *Enum // enum in which this value is declared
631
Joe Tsai7762ec22019-08-20 20:10:23 -0700632 Location Location // location of this enum value
633 Comments CommentSet // comments associated with this enum value
634}
635
636func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
637 // A top-level enum value's name is: EnumName_ValueName
638 // An enum value contained in a message is: MessageName_ValueName
639 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700640 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700641 parentIdent := enum.GoIdent
642 if message != nil {
643 parentIdent = message.GoIdent
644 }
645 name := parentIdent.GoName + "_" + string(desc.Name())
Joe Tsai42cc4c52020-06-16 08:48:38 -0700646 loc := enum.Location.appendPath(genid.EnumDescriptorProto_Value_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700647 return &EnumValue{
648 Desc: desc,
649 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700650 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700651 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700652 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Joe Tsai7762ec22019-08-20 20:10:23 -0700653 }
654}
655
Damien Neilc7d07d92018-08-22 13:46:02 -0700656// A Message describes a message.
657type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700658 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700659
Joe Tsai7762ec22019-08-20 20:10:23 -0700660 GoIdent GoIdent // name of the generated Go type
661
662 Fields []*Field // message field declarations
663 Oneofs []*Oneof // message oneof declarations
664
Damien Neil993c04d2018-09-14 15:41:11 -0700665 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700666 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700667 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700668
669 Location Location // location of this message
670 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700671}
672
Damien Neil1fa78d82018-09-13 13:12:36 -0700673func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700674 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700675 if parent != nil {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700676 loc = parent.Location.appendPath(genid.DescriptorProto_NestedType_field_number, desc.Index())
Damien Neilcab8dfe2018-09-06 14:51:28 -0700677 } else {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700678 loc = f.location.appendPath(genid.FileDescriptorProto_MessageType_field_number, desc.Index())
Damien Neilcab8dfe2018-09-06 14:51:28 -0700679 }
Damien Neil46abb572018-09-07 12:45:37 -0700680 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700681 Desc: desc,
682 GoIdent: newGoIdent(f, desc),
683 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700684 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neilc7d07d92018-08-22 13:46:02 -0700685 }
Damien Neil658051b2018-09-10 12:26:21 -0700686 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700687 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
688 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700689 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700690 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
691 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700692 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700693 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
694 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700695 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700696 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
697 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700698 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700699 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
700 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
701 }
702
703 // Resolve local references between fields and oneofs.
704 for _, field := range message.Fields {
705 if od := field.Desc.ContainingOneof(); od != nil {
706 oneof := message.Oneofs[od.Index()]
707 field.Oneof = oneof
708 oneof.Fields = append(oneof.Fields, field)
709 }
Damien Neil993c04d2018-09-14 15:41:11 -0700710 }
Damien Neil658051b2018-09-10 12:26:21 -0700711
712 // Field name conflict resolution.
713 //
714 // We assume well-known method names that may be attached to a generated
715 // message type, as well as a 'Get*' method for each field. For each
716 // field in turn, we add _s to its name until there are no conflicts.
717 //
718 // Any change to the following set of method names is a potential
719 // incompatible API change because it may change generated field names.
720 //
721 // TODO: If we ever support a 'go_name' option to set the Go name of a
722 // field, we should consider dropping this entirely. The conflict
723 // resolution algorithm is subtle and surprising (changing the order
724 // in which fields appear in the .proto source file can change the
725 // names of fields in generated code), and does not adapt well to
726 // adding new per-field methods such as setters.
727 usedNames := map[string]bool{
728 "Reset": true,
729 "String": true,
730 "ProtoMessage": true,
731 "Marshal": true,
732 "Unmarshal": true,
733 "ExtensionRangeArray": true,
734 "ExtensionMap": true,
735 "Descriptor": true,
736 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800737 makeNameUnique := func(name string, hasGetter bool) string {
738 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700739 name += "_"
740 }
741 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800742 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700743 return name
744 }
745 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800746 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700747 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
748 if field.Oneof != nil && field.Oneof.Fields[0] == field {
749 // Make the name for a oneof unique as well. For historical reasons,
750 // this assumes that a getter method is not generated for oneofs.
751 // This is incorrect, but fixing it breaks existing code.
752 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
753 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
754 }
755 }
756
757 // Oneof field name conflict resolution.
758 //
759 // This conflict resolution is incomplete as it does not consider collisions
760 // with other oneof field types, but fixing it breaks existing code.
761 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700762 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700763 Loop:
764 for {
765 for _, nestedMessage := range message.Messages {
766 if nestedMessage.GoIdent == field.GoIdent {
767 field.GoIdent.GoName += "_"
768 continue Loop
769 }
770 }
771 for _, nestedEnum := range message.Enums {
772 if nestedEnum.GoIdent == field.GoIdent {
773 field.GoIdent.GoName += "_"
774 continue Loop
775 }
776 }
777 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700778 }
779 }
Damien Neil658051b2018-09-10 12:26:21 -0700780 }
781
Damien Neil1fa78d82018-09-13 13:12:36 -0700782 return message
Damien Neil658051b2018-09-10 12:26:21 -0700783}
784
Joe Tsai7762ec22019-08-20 20:10:23 -0700785func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700786 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700787 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700788 return err
789 }
790 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700791 for _, message := range message.Messages {
792 if err := message.resolveDependencies(gen); err != nil {
793 return err
794 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700795 }
Damien Neil993c04d2018-09-14 15:41:11 -0700796 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700797 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700798 return err
799 }
800 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700801 return nil
802}
803
Damien Neil658051b2018-09-10 12:26:21 -0700804// A Field describes a message field.
805type Field struct {
806 Desc protoreflect.FieldDescriptor
807
Damien Neil1fa78d82018-09-13 13:12:36 -0700808 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700809 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700810 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700811 GoName string // e.g., "FieldName"
812
813 // GoIdent is the base name of a top-level declaration for this field.
814 // For code generated by protoc-gen-go, this means a wrapper type named
815 // '{{GoIdent}}' for members fields of a oneof, and a variable named
816 // 'E_{{GoIdent}}' for extension fields.
817 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700818
Joe Tsai7762ec22019-08-20 20:10:23 -0700819 Parent *Message // message in which this field is declared; nil if top-level extension
820 Oneof *Oneof // containing oneof; nil if not part of a oneof
821 Extendee *Message // extended message for extension fields; nil otherwise
822
823 Enum *Enum // type for enum fields; nil otherwise
824 Message *Message // type for message or group fields; nil otherwise
825
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700826 Location Location // location of this field
827 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700828}
829
Damien Neil1fa78d82018-09-13 13:12:36 -0700830func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700831 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700832 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700833 case desc.IsExtension() && message == nil:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700834 loc = f.location.appendPath(genid.FileDescriptorProto_Extension_field_number, desc.Index())
Joe Tsaiac31a352019-05-13 14:32:56 -0700835 case desc.IsExtension() && message != nil:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700836 loc = message.Location.appendPath(genid.DescriptorProto_Extension_field_number, desc.Index())
Damien Neil993c04d2018-09-14 15:41:11 -0700837 default:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700838 loc = message.Location.appendPath(genid.DescriptorProto_Field_field_number, desc.Index())
Damien Neil993c04d2018-09-14 15:41:11 -0700839 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700840 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700841 var parentPrefix string
842 if message != nil {
843 parentPrefix = message.GoIdent.GoName + "_"
844 }
Damien Neil658051b2018-09-10 12:26:21 -0700845 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700846 Desc: desc,
847 GoName: camelCased,
848 GoIdent: GoIdent{
849 GoImportPath: f.GoImportPath,
850 GoName: parentPrefix + camelCased,
851 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700852 Parent: message,
853 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700854 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil658051b2018-09-10 12:26:21 -0700855 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700856 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700857}
858
Joe Tsai7762ec22019-08-20 20:10:23 -0700859func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700860 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700861 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700862 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700863 name := field.Desc.Enum().FullName()
864 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700865 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700866 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700867 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700868 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700869 case protoreflect.MessageKind, protoreflect.GroupKind:
870 name := desc.Message().FullName()
871 message, ok := gen.messagesByName[name]
872 if !ok {
873 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
874 }
875 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700876 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700877 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700878 name := desc.ContainingMessage().FullName()
879 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700880 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700881 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700882 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700883 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700884 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700885 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700886}
887
Joe Tsai7762ec22019-08-20 20:10:23 -0700888// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700889type Oneof struct {
890 Desc protoreflect.OneofDescriptor
891
Joe Tsaief6e5242019-08-21 00:55:36 -0700892 // GoName is the base name of this oneof's Go field and methods.
893 // For code generated by protoc-gen-go, this means a field named
894 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
895 GoName string // e.g., "OneofName"
896
897 // GoIdent is the base name of a top-level declaration for this oneof.
898 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700899
900 Parent *Message // message in which this oneof is declared
901
Joe Tsaid24bc722019-04-15 23:39:09 -0700902 Fields []*Field // fields that are part of this oneof
903
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700904 Location Location // location of this oneof
905 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700906}
907
908func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700909 loc := message.Location.appendPath(genid.DescriptorProto_OneofDecl_field_number, desc.Index())
Joe Tsai2e7817f2019-08-23 12:18:57 -0700910 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700911 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700912 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700913 Desc: desc,
914 Parent: message,
915 GoName: camelCased,
916 GoIdent: GoIdent{
917 GoImportPath: f.GoImportPath,
918 GoName: parentPrefix + camelCased,
919 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700920 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700921 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil1fa78d82018-09-13 13:12:36 -0700922 }
923}
924
Joe Tsai7762ec22019-08-20 20:10:23 -0700925// Extension is an alias of Field for documentation.
926type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700927
Damien Neil2dc67182018-09-21 15:03:34 -0700928// A Service describes a service.
929type Service struct {
930 Desc protoreflect.ServiceDescriptor
931
Joe Tsai7762ec22019-08-20 20:10:23 -0700932 GoName string
933
934 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700935
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700936 Location Location // location of this service
937 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700938}
939
940func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700941 loc := f.location.appendPath(genid.FileDescriptorProto_Service_field_number, desc.Index())
Damien Neil2dc67182018-09-21 15:03:34 -0700942 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700943 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700944 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700945 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700946 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil2dc67182018-09-21 15:03:34 -0700947 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700948 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
949 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700950 }
951 return service
952}
953
954// A Method describes a method in a service.
955type Method struct {
956 Desc protoreflect.MethodDescriptor
957
Joe Tsaid24bc722019-04-15 23:39:09 -0700958 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700959
960 Parent *Service // service in which this method is declared
961
Joe Tsaid24bc722019-04-15 23:39:09 -0700962 Input *Message
963 Output *Message
964
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700965 Location Location // location of this method
966 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700967}
968
969func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700970 loc := service.Location.appendPath(genid.ServiceDescriptorProto_Method_field_number, desc.Index())
Damien Neil2dc67182018-09-21 15:03:34 -0700971 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700972 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700973 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700974 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700975 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700976 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil2dc67182018-09-21 15:03:34 -0700977 }
978 return method
979}
980
Joe Tsai7762ec22019-08-20 20:10:23 -0700981func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700982 desc := method.Desc
983
Joe Tsaid24bc722019-04-15 23:39:09 -0700984 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700985 in, ok := gen.messagesByName[inName]
986 if !ok {
987 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
988 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700989 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700990
Joe Tsaid24bc722019-04-15 23:39:09 -0700991 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700992 out, ok := gen.messagesByName[outName]
993 if !ok {
994 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
995 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700996 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700997
998 return nil
999}
1000
Damien Neil7bf3ce22018-12-21 15:54:06 -08001001// A GeneratedFile is a generated file.
1002type GeneratedFile struct {
1003 gen *Plugin
1004 skip bool
1005 filename string
1006 goImportPath GoImportPath
1007 buf bytes.Buffer
1008 packageNames map[GoImportPath]GoPackageName
1009 usedPackageNames map[GoPackageName]bool
1010 manualImports map[GoImportPath]bool
1011 annotations map[string][]Location
1012}
1013
1014// NewGeneratedFile creates a new generated file with the given filename
1015// and import path.
1016func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
1017 g := &GeneratedFile{
1018 gen: gen,
1019 filename: filename,
1020 goImportPath: goImportPath,
1021 packageNames: make(map[GoImportPath]GoPackageName),
1022 usedPackageNames: make(map[GoPackageName]bool),
1023 manualImports: make(map[GoImportPath]bool),
1024 annotations: make(map[string][]Location),
1025 }
Joe Tsai124c8122019-01-14 11:48:43 -08001026
1027 // All predeclared identifiers in Go are already used.
1028 for _, s := range types.Universe.Names() {
1029 g.usedPackageNames[GoPackageName(s)] = true
1030 }
1031
Damien Neil7bf3ce22018-12-21 15:54:06 -08001032 gen.genFiles = append(gen.genFiles, g)
1033 return g
1034}
1035
Damien Neil220c2022018-08-15 11:24:18 -07001036// P prints a line to the generated output. It converts each parameter to a
1037// string following the same rules as fmt.Print. It never inserts spaces
1038// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -07001039func (g *GeneratedFile) P(v ...interface{}) {
1040 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -07001041 switch x := x.(type) {
1042 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -07001043 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -07001044 default:
1045 fmt.Fprint(&g.buf, x)
1046 }
Damien Neil220c2022018-08-15 11:24:18 -07001047 }
1048 fmt.Fprintln(&g.buf)
1049}
1050
Damien Neil46abb572018-09-07 12:45:37 -07001051// QualifiedGoIdent returns the string to use for a Go identifier.
1052//
1053// If the identifier is from a different Go package than the generated file,
1054// the returned name will be qualified (package.name) and an import statement
1055// for the identifier's package will be included in the file.
1056func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
1057 if ident.GoImportPath == g.goImportPath {
1058 return ident.GoName
1059 }
1060 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
1061 return string(packageName) + "." + ident.GoName
1062 }
1063 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -08001064 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -07001065 packageName = orig + GoPackageName(strconv.Itoa(i))
1066 }
1067 g.packageNames[ident.GoImportPath] = packageName
1068 g.usedPackageNames[packageName] = true
1069 return string(packageName) + "." + ident.GoName
1070}
1071
Damien Neil2e0c3da2018-09-19 12:51:36 -07001072// Import ensures a package is imported by the generated file.
1073//
1074// Packages referenced by QualifiedGoIdent are automatically imported.
1075// Explicitly importing a package with Import is generally only necessary
1076// when the import will be blank (import _ "package").
1077func (g *GeneratedFile) Import(importPath GoImportPath) {
1078 g.manualImports[importPath] = true
1079}
1080
Damien Neil220c2022018-08-15 11:24:18 -07001081// Write implements io.Writer.
1082func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1083 return g.buf.Write(p)
1084}
1085
Damien Neil7bf3ce22018-12-21 15:54:06 -08001086// Skip removes the generated file from the plugin output.
1087func (g *GeneratedFile) Skip() {
1088 g.skip = true
1089}
1090
Oscar Söderlund8525b202020-05-06 06:04:40 +02001091// Unskip reverts a previous call to Skip, re-including the generated file in
1092// the plugin output.
1093func (g *GeneratedFile) Unskip() {
1094 g.skip = false
1095}
1096
Damien Neil162c1272018-10-04 12:42:37 -07001097// Annotate associates a symbol in a generated Go file with a location in a
1098// source .proto file.
1099//
1100// The symbol may refer to a type, constant, variable, function, method, or
1101// struct field. The "T.sel" syntax is used to identify the method or field
1102// 'sel' on type 'T'.
1103func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1104 g.annotations[symbol] = append(g.annotations[symbol], loc)
1105}
1106
Damien Neil7bf3ce22018-12-21 15:54:06 -08001107// Content returns the contents of the generated file.
1108func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001109 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001110 return g.buf.Bytes(), nil
1111 }
1112
1113 // Reformat generated code.
1114 original := g.buf.Bytes()
1115 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001116 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001117 if err != nil {
1118 // Print out the bad code with line numbers.
1119 // This should never happen in practice, but it can while changing generated code
1120 // so consider this a debugging aid.
1121 var src bytes.Buffer
1122 s := bufio.NewScanner(bytes.NewReader(original))
1123 for line := 1; s.Scan(); line++ {
1124 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1125 }
Damien Neild9016772018-08-23 14:39:30 -07001126 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001127 }
Damien Neild9016772018-08-23 14:39:30 -07001128
Joe Tsaibeda4042019-03-10 16:40:48 -07001129 // Collect a sorted list of all imports.
1130 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001131 rewriteImport := func(importPath string) string {
1132 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1133 return string(f(GoImportPath(importPath)))
1134 }
1135 return importPath
1136 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001137 for importPath := range g.packageNames {
1138 pkgName := string(g.packageNames[GoImportPath(importPath)])
1139 pkgPath := rewriteImport(string(importPath))
1140 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001141 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001142 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001143 if _, ok := g.packageNames[importPath]; !ok {
1144 pkgPath := rewriteImport(string(importPath))
1145 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001146 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001147 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001148 sort.Slice(importPaths, func(i, j int) bool {
1149 return importPaths[i][1] < importPaths[j][1]
1150 })
1151
1152 // Modify the AST to include a new import block.
1153 if len(importPaths) > 0 {
1154 // Insert block after package statement or
1155 // possible comment attached to the end of the package statement.
1156 pos := file.Package
1157 tokFile := fset.File(file.Package)
1158 pkgLine := tokFile.Line(file.Package)
1159 for _, c := range file.Comments {
1160 if tokFile.Line(c.Pos()) > pkgLine {
1161 break
1162 }
1163 pos = c.End()
1164 }
1165
1166 // Construct the import block.
1167 impDecl := &ast.GenDecl{
1168 Tok: token.IMPORT,
1169 TokPos: pos,
1170 Lparen: pos,
1171 Rparen: pos,
1172 }
1173 for _, importPath := range importPaths {
1174 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1175 Name: &ast.Ident{
1176 Name: importPath[0],
1177 NamePos: pos,
1178 },
1179 Path: &ast.BasicLit{
1180 Kind: token.STRING,
1181 Value: strconv.Quote(importPath[1]),
1182 ValuePos: pos,
1183 },
1184 EndPos: pos,
1185 })
1186 }
1187 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1188 }
Damien Neild9016772018-08-23 14:39:30 -07001189
Damien Neilc7d07d92018-08-22 13:46:02 -07001190 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001191 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001192 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001193 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001194 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001195}
Damien Neilc7d07d92018-08-22 13:46:02 -07001196
Damien Neil162c1272018-10-04 12:42:37 -07001197// metaFile returns the contents of the file's metadata file, which is a
1198// text formatted string of the google.protobuf.GeneratedCodeInfo.
1199func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1200 fset := token.NewFileSet()
1201 astFile, err := parser.ParseFile(fset, "", content, 0)
1202 if err != nil {
1203 return "", err
1204 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001205 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001206
1207 seenAnnotations := make(map[string]bool)
1208 annotate := func(s string, ident *ast.Ident) {
1209 seenAnnotations[s] = true
1210 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001211 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001212 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001213 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001214 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1215 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001216 })
1217 }
1218 }
1219 for _, decl := range astFile.Decls {
1220 switch decl := decl.(type) {
1221 case *ast.GenDecl:
1222 for _, spec := range decl.Specs {
1223 switch spec := spec.(type) {
1224 case *ast.TypeSpec:
1225 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001226 switch st := spec.Type.(type) {
1227 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001228 for _, field := range st.Fields.List {
1229 for _, name := range field.Names {
1230 annotate(spec.Name.Name+"."+name.Name, name)
1231 }
1232 }
Damien Neilae2a5612018-12-12 08:54:57 -08001233 case *ast.InterfaceType:
1234 for _, field := range st.Methods.List {
1235 for _, name := range field.Names {
1236 annotate(spec.Name.Name+"."+name.Name, name)
1237 }
1238 }
Damien Neil162c1272018-10-04 12:42:37 -07001239 }
1240 case *ast.ValueSpec:
1241 for _, name := range spec.Names {
1242 annotate(name.Name, name)
1243 }
1244 }
1245 }
1246 case *ast.FuncDecl:
1247 if decl.Recv == nil {
1248 annotate(decl.Name.Name, decl.Name)
1249 } else {
1250 recv := decl.Recv.List[0].Type
1251 if s, ok := recv.(*ast.StarExpr); ok {
1252 recv = s.X
1253 }
1254 if id, ok := recv.(*ast.Ident); ok {
1255 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1256 }
1257 }
1258 }
1259 }
1260 for a := range g.annotations {
1261 if !seenAnnotations[a] {
1262 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1263 }
1264 }
1265
Damien Neil5c5b5312019-05-14 12:44:37 -07001266 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001267 if err != nil {
1268 return "", err
1269 }
1270 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001271}
Damien Neil082ce922018-09-06 10:23:53 -07001272
Joe Tsai2e7817f2019-08-23 12:18:57 -07001273// A GoIdent is a Go identifier, consisting of a name and import path.
1274// The name is a single identifier and may not be a dot-qualified selector.
1275type GoIdent struct {
1276 GoName string
1277 GoImportPath GoImportPath
1278}
1279
1280func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1281
1282// newGoIdent returns the Go identifier for a descriptor.
1283func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1284 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1285 return GoIdent{
1286 GoName: strs.GoCamelCase(name),
1287 GoImportPath: f.GoImportPath,
1288 }
1289}
1290
1291// A GoImportPath is the import path of a Go package.
1292// For example: "google.golang.org/protobuf/compiler/protogen"
1293type GoImportPath string
1294
1295func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1296
1297// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1298func (p GoImportPath) Ident(s string) GoIdent {
1299 return GoIdent{GoName: s, GoImportPath: p}
1300}
1301
1302// A GoPackageName is the name of a Go package. e.g., "protobuf".
1303type GoPackageName string
1304
1305// cleanPackageName converts a string to a valid Go package name.
1306func cleanPackageName(name string) GoPackageName {
1307 return GoPackageName(strs.GoSanitized(name))
1308}
1309
1310// baseName returns the last path element of the name, with the last dotted suffix removed.
1311func baseName(name string) string {
1312 // First, find the last element
1313 if i := strings.LastIndex(name, "/"); i >= 0 {
1314 name = name[i+1:]
1315 }
1316 // Now drop the suffix
1317 if i := strings.LastIndex(name, "."); i >= 0 {
1318 name = name[:i]
1319 }
1320 return name
1321}
1322
Damien Neil082ce922018-09-06 10:23:53 -07001323type pathType int
1324
1325const (
Damien Neilaadba562020-02-15 14:28:51 -08001326 pathTypeLegacy pathType = iota
1327 pathTypeImport
Damien Neil082ce922018-09-06 10:23:53 -07001328 pathTypeSourceRelative
1329)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001330
Damien Neil162c1272018-10-04 12:42:37 -07001331// A Location is a location in a .proto source file.
1332//
1333// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1334// for details.
1335type Location struct {
1336 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001337 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001338}
1339
1340// appendPath add elements to a Location's path, returning a new Location.
Joe Tsai42cc4c52020-06-16 08:48:38 -07001341func (loc Location) appendPath(num protoreflect.FieldNumber, idx int) Location {
1342 loc.Path = append(protoreflect.SourcePath(nil), loc.Path...) // make copy
1343 loc.Path = append(loc.Path, int32(num), int32(idx))
1344 return loc
Damien Neilba1159f2018-10-17 12:53:18 -07001345}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001346
1347// CommentSet is a set of leading and trailing comments associated
1348// with a .proto descriptor declaration.
1349type CommentSet struct {
1350 LeadingDetached []Comments
1351 Leading Comments
1352 Trailing Comments
1353}
1354
Joe Tsai42cc4c52020-06-16 08:48:38 -07001355func makeCommentSet(loc protoreflect.SourceLocation) CommentSet {
1356 var leadingDetached []Comments
1357 for _, s := range loc.LeadingDetachedComments {
1358 leadingDetached = append(leadingDetached, Comments(s))
1359 }
1360 return CommentSet{
1361 LeadingDetached: leadingDetached,
1362 Leading: Comments(loc.LeadingComments),
1363 Trailing: Comments(loc.TrailingComments),
1364 }
1365}
1366
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001367// Comments is a comments string as provided by protoc.
1368type Comments string
1369
1370// String formats the comments by inserting // to the start of each line,
1371// ensuring that there is a trailing newline.
1372// An empty comment is formatted as an empty string.
1373func (c Comments) String() string {
1374 if c == "" {
1375 return ""
1376 }
1377 var b []byte
1378 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1379 b = append(b, "//"...)
1380 b = append(b, line...)
1381 b = append(b, "\n"...)
1382 }
1383 return string(b)
1384}
Damien Neile358d432020-03-06 13:58:41 -08001385
1386var warnings = true
1387
1388func warn(format string, a ...interface{}) {
1389 if warnings {
1390 log.Printf("WARNING: "+format, a...)
1391 }
1392}