blob: e3b9e7fcd9a042fcb2354505f5c5bc0fe327371f [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"
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"
Joe Tsai3e802492019-09-07 13:06:27 -070024 "log"
Damien Neil220c2022018-08-15 11:24:18 -070025 "os"
Damien Neil082ce922018-09-06 10:23:53 -070026 "path"
Damien Neil220c2022018-08-15 11:24:18 -070027 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070028 "sort"
29 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070030 "strings"
31
Damien Neil5c5b5312019-05-14 12:44:37 -070032 "google.golang.org/protobuf/encoding/prototext"
Damien Neile89e6242019-05-13 23:55:40 -070033 "google.golang.org/protobuf/internal/fieldnum"
Joe Tsai2e7817f2019-08-23 12:18:57 -070034 "google.golang.org/protobuf/internal/strs"
Damien Neile89e6242019-05-13 23:55:40 -070035 "google.golang.org/protobuf/proto"
36 "google.golang.org/protobuf/reflect/protodesc"
37 "google.golang.org/protobuf/reflect/protoreflect"
38 "google.golang.org/protobuf/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080039
Joe Tsaia95b29f2019-05-16 12:47:20 -070040 "google.golang.org/protobuf/types/descriptorpb"
41 "google.golang.org/protobuf/types/pluginpb"
Damien Neil220c2022018-08-15 11:24:18 -070042)
43
Joe Tsai222a0002020-02-24 11:21:30 -080044const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package"
45
Damien Neil220c2022018-08-15 11:24:18 -070046// Run executes a function as a protoc plugin.
47//
48// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
49// function, and writes a CodeGeneratorResponse message to os.Stdout.
50//
51// If a failure occurs while reading or writing, Run prints an error to
52// os.Stderr and calls os.Exit(1).
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080053func (opts Options) Run(f func(*Plugin) error) {
Damien Neil3cf6e622018-09-11 13:53:14 -070054 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070055 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
56 os.Exit(1)
57 }
58}
59
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080060func run(opts Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070061 if len(os.Args) > 1 {
62 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
63 }
Damien Neil220c2022018-08-15 11:24:18 -070064 in, err := ioutil.ReadAll(os.Stdin)
65 if err != nil {
66 return err
67 }
68 req := &pluginpb.CodeGeneratorRequest{}
69 if err := proto.Unmarshal(in, req); err != nil {
70 return err
71 }
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080072 gen, err := opts.New(req)
Damien Neil220c2022018-08-15 11:24:18 -070073 if err != nil {
74 return err
75 }
76 if err := f(gen); err != nil {
77 // Errors from the plugin function are reported by setting the
78 // error field in the CodeGeneratorResponse.
79 //
80 // In contrast, errors that indicate a problem in protoc
81 // itself (unparsable input, I/O errors, etc.) are reported
82 // to stderr.
83 gen.Error(err)
84 }
85 resp := gen.Response()
86 out, err := proto.Marshal(resp)
87 if err != nil {
88 return err
89 }
90 if _, err := os.Stdout.Write(out); err != nil {
91 return err
92 }
93 return nil
94}
95
96// A Plugin is a protoc plugin invocation.
97type Plugin struct {
98 // Request is the CodeGeneratorRequest provided by protoc.
99 Request *pluginpb.CodeGeneratorRequest
100
101 // Files is the set of files to generate and everything they import.
102 // Files appear in topological order, so each file appears before any
103 // file that imports it.
104 Files []*File
Joe Tsai2cec4842019-08-20 20:14:19 -0700105 FilesByPath map[string]*File
Damien Neil220c2022018-08-15 11:24:18 -0700106
Joe Tsai387873d2020-04-28 14:44:38 -0700107 // SupportedFeatures is the set of protobuf language features supported by
108 // this generator plugin. See the documentation for
109 // google.protobuf.CodeGeneratorResponse.supported_features for details.
110 SupportedFeatures uint64
111
Damien Neil658051b2018-09-10 12:26:21 -0700112 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700113 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700114 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700115 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700116 pathType pathType
Damien Neilffbc5fd2020-02-12 23:38:30 -0800117 module string
Damien Neil658051b2018-09-10 12:26:21 -0700118 genFiles []*GeneratedFile
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800119 opts Options
Damien Neil658051b2018-09-10 12:26:21 -0700120 err error
Damien Neil220c2022018-08-15 11:24:18 -0700121}
122
Damien Neil3cf6e622018-09-11 13:53:14 -0700123type Options struct {
124 // If ParamFunc is non-nil, it will be called with each unknown
125 // generator parameter.
126 //
127 // Plugins for protoc can accept parameters from the command line,
128 // passed in the --<lang>_out protoc, separated from the output
129 // directory with a colon; e.g.,
130 //
131 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
132 //
133 // Parameters passed in this fashion as a comma-separated list of
134 // key=value pairs will be passed to the ParamFunc.
135 //
136 // The (flag.FlagSet).Set method matches this function signature,
137 // so parameters can be converted into flags as in the following:
138 //
139 // var flags flag.FlagSet
140 // value := flags.Bool("param", false, "")
141 // opts := &protogen.Options{
142 // ParamFunc: flags.Set,
143 // }
144 // protogen.Run(opts, func(p *protogen.Plugin) error {
145 // if *value { ... }
146 // })
147 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700148
149 // ImportRewriteFunc is called with the import path of each package
150 // imported by a generated file. It returns the import path to use
151 // for this package.
152 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700153}
154
Damien Neil220c2022018-08-15 11:24:18 -0700155// New returns a new Plugin.
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800156func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
Damien Neil220c2022018-08-15 11:24:18 -0700157 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700158 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700159 FilesByPath: make(map[string]*File),
Damien Neilc8268852019-10-08 13:28:53 -0700160 fileReg: new(protoregistry.Files),
Damien Neil658051b2018-09-10 12:26:21 -0700161 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700162 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700163 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700164 }
165
Damien Neil082ce922018-09-06 10:23:53 -0700166 packageNames := make(map[string]GoPackageName) // filename -> package name
167 importPaths := make(map[string]GoImportPath) // filename -> import path
Joe Tsai3e802492019-09-07 13:06:27 -0700168 mfiles := make(map[string]bool) // filename set
Damien Neil082ce922018-09-06 10:23:53 -0700169 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700170 for _, param := range strings.Split(req.GetParameter(), ",") {
171 var value string
172 if i := strings.Index(param, "="); i >= 0 {
173 value = param[i+1:]
174 param = param[0:i]
175 }
176 switch param {
177 case "":
178 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700179 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700180 packageImportPath = GoImportPath(value)
Damien Neilffbc5fd2020-02-12 23:38:30 -0800181 case "module":
182 gen.module = value
Damien Neil220c2022018-08-15 11:24:18 -0700183 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700184 switch value {
185 case "import":
186 gen.pathType = pathTypeImport
187 case "source_relative":
188 gen.pathType = pathTypeSourceRelative
189 default:
190 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
191 }
Damien Neil220c2022018-08-15 11:24:18 -0700192 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700193 switch value {
194 case "true", "":
195 gen.annotateCode = true
196 case "false":
197 default:
198 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
199 }
Damien Neil220c2022018-08-15 11:24:18 -0700200 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700201 if param[0] == 'M' {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700202 if i := strings.Index(value, ";"); i >= 0 {
203 pkgName := GoPackageName(value[i+1:])
204 if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName {
205 return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName)
206 }
207 packageNames[param[1:]] = pkgName
208 value = value[:i]
209 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700210 importPaths[param[1:]] = GoImportPath(value)
Joe Tsai3e802492019-09-07 13:06:27 -0700211 mfiles[param[1:]] = true
Damien Neil3cf6e622018-09-11 13:53:14 -0700212 continue
Damien Neil220c2022018-08-15 11:24:18 -0700213 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700214 if opts.ParamFunc != nil {
215 if err := opts.ParamFunc(param, value); err != nil {
216 return nil, err
217 }
218 }
Damien Neil082ce922018-09-06 10:23:53 -0700219 }
220 }
Damien Neilffbc5fd2020-02-12 23:38:30 -0800221 if gen.module != "" {
222 // When the module= option is provided, we strip the module name
223 // prefix from generated files. This only makes sense if generated
224 // filenames are based on the import path, so default to paths=import
225 // and complain if source_relative was selected manually.
226 switch gen.pathType {
227 case pathTypeLegacy:
228 gen.pathType = pathTypeImport
229 case pathTypeSourceRelative:
230 return nil, fmt.Errorf("cannot use module= with paths=source_relative")
231 }
232 }
Damien Neil082ce922018-09-06 10:23:53 -0700233
234 // Figure out the import path and package name for each file.
235 //
236 // The rules here are complicated and have grown organically over time.
237 // Interactions between different ways of specifying package information
238 // may be surprising.
239 //
240 // The recommended approach is to include a go_package option in every
241 // .proto source file specifying the full import path of the Go package
242 // associated with this file.
243 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700244 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700245 //
246 // Build systems which want to exert full control over import paths may
247 // specify M<filename>=<import_path> flags.
248 //
249 // Other approaches are not recommend.
250 generatedFileNames := make(map[string]bool)
251 for _, name := range gen.Request.FileToGenerate {
252 generatedFileNames[name] = true
253 }
254 // We need to determine the import paths before the package names,
255 // because the Go package name for a file is sometimes derived from
256 // different file in the same package.
257 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
258 for _, fdesc := range gen.Request.ProtoFile {
259 filename := fdesc.GetName()
260 packageName, importPath := goPackageOption(fdesc)
261 switch {
262 case importPaths[filename] != "":
Damien Neilaadba562020-02-15 14:28:51 -0800263 // Command line: Mfoo.proto=quux/bar
Damien Neil082ce922018-09-06 10:23:53 -0700264 //
265 // Explicit mapping of source file to import path.
266 case generatedFileNames[filename] && packageImportPath != "":
267 // Command line: import_path=quux/bar
268 //
269 // The import_path flag sets the import path for every file that
270 // we generate code for.
271 importPaths[filename] = packageImportPath
272 case importPath != "":
273 // Source file: option go_package = "quux/bar";
274 //
275 // The go_package option sets the import path. Most users should use this.
276 importPaths[filename] = importPath
277 default:
278 // Source filename.
279 //
280 // Last resort when nothing else is available.
281 importPaths[filename] = GoImportPath(path.Dir(filename))
282 }
283 if packageName != "" {
284 packageNameForImportPath[importPaths[filename]] = packageName
285 }
286 }
287 for _, fdesc := range gen.Request.ProtoFile {
288 filename := fdesc.GetName()
Joe Tsai3e802492019-09-07 13:06:27 -0700289 packageName, importPath := goPackageOption(fdesc)
Damien Neil082ce922018-09-06 10:23:53 -0700290 defaultPackageName := packageNameForImportPath[importPaths[filename]]
291 switch {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700292 case packageNames[filename] != "":
293 // A package name specified by the "M" command-line argument.
Damien Neil082ce922018-09-06 10:23:53 -0700294 case packageName != "":
Joe Tsai3e802492019-09-07 13:06:27 -0700295 // TODO: For the "M" command-line argument, this means that the
296 // package name can be derived from the go_package option.
297 // Go package information should either consistently come from the
298 // command-line or the .proto source file, but not both.
299 // See how to make this consistent.
300
Damien Neil082ce922018-09-06 10:23:53 -0700301 // Source file: option go_package = "quux/bar";
302 packageNames[filename] = packageName
303 case defaultPackageName != "":
304 // A go_package option in another file in the same package.
305 //
306 // This is a poor choice in general, since every source file should
307 // contain a go_package option. Supported mainly for historical
308 // compatibility.
309 packageNames[filename] = defaultPackageName
310 case generatedFileNames[filename] && packageImportPath != "":
311 // Command line: import_path=quux/bar
312 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
313 case fdesc.GetPackage() != "":
314 // Source file: package quux.bar;
315 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
316 default:
317 // Source filename.
318 packageNames[filename] = cleanPackageName(baseName(filename))
319 }
Joe Tsai3e802492019-09-07 13:06:27 -0700320
321 goPkgOpt := string(importPaths[filename])
322 if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
323 goPkgOpt += ";" + string(packageNames[filename])
324 }
325 switch {
326 case packageImportPath != "":
327 // Command line: import_path=quux/bar
Damien Neile358d432020-03-06 13:58:41 -0800328 warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700329 "\toption go_package = %q;\n"+
330 "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800331 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700332 "\n", fdesc.GetName(), goPkgOpt)
333 case mfiles[filename]:
334 // Command line: M=foo.proto=quux/bar
335 case packageName != "" && importPath == "":
336 // Source file: option go_package = "quux";
Damien Neile358d432020-03-06 13:58:41 -0800337 warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700338 "\toption go_package = %q;\n"+
339 "A future release of protoc-gen-go will require the import path be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800340 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700341 "\n", fdesc.GetName(), goPkgOpt)
342 case packageName == "" && importPath == "":
343 // No Go package information provided.
Damien Neile358d432020-03-06 13:58:41 -0800344 warn("Missing 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700345 "\toption go_package = %q;\n"+
346 "A future release of protoc-gen-go will require this be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800347 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700348 "\n", fdesc.GetName(), goPkgOpt)
349 }
Damien Neil082ce922018-09-06 10:23:53 -0700350 }
351
352 // Consistency check: Every file with the same Go import path should have
353 // the same Go package name.
354 packageFiles := make(map[GoImportPath][]string)
355 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700356 if _, ok := packageNames[filename]; !ok {
357 // Skip files mentioned in a M<file>=<import_path> parameter
358 // but which do not appear in the CodeGeneratorRequest.
359 continue
360 }
Damien Neil082ce922018-09-06 10:23:53 -0700361 packageFiles[importPath] = append(packageFiles[importPath], filename)
362 }
363 for importPath, filenames := range packageFiles {
364 for i := 1; i < len(filenames); i++ {
365 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
366 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
367 importPath, a, filenames[0], b, filenames[i])
368 }
Damien Neil220c2022018-08-15 11:24:18 -0700369 }
370 }
371
372 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700373 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700374 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700375 return nil, fmt.Errorf("duplicate file name: %q", filename)
376 }
377 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700378 if err != nil {
379 return nil, err
380 }
Damien Neil220c2022018-08-15 11:24:18 -0700381 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700382 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700383 }
Damien Neil082ce922018-09-06 10:23:53 -0700384 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700385 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700386 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700387 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700388 }
389 f.Generate = true
390 }
391 return gen, nil
392}
393
394// Error records an error in code generation. The generator will report the
395// error back to protoc and will not produce output.
396func (gen *Plugin) Error(err error) {
397 if gen.err == nil {
398 gen.err = err
399 }
400}
401
402// Response returns the generator output.
403func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
404 resp := &pluginpb.CodeGeneratorResponse{}
405 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700406 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700407 return resp
408 }
Damien Neil162c1272018-10-04 12:42:37 -0700409 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800410 if g.skip {
411 continue
412 }
413 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700414 if err != nil {
415 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700416 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700417 }
418 }
Damien Neilffbc5fd2020-02-12 23:38:30 -0800419 filename := g.filename
420 if gen.module != "" {
421 trim := gen.module + "/"
422 if !strings.HasPrefix(filename, trim) {
423 return &pluginpb.CodeGeneratorResponse{
424 Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)),
425 }
426 }
427 filename = strings.TrimPrefix(filename, trim)
428 }
Damien Neil220c2022018-08-15 11:24:18 -0700429 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800430 Name: proto.String(filename),
Damien Neila8a2cea2019-07-10 16:17:16 -0700431 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700432 })
Damien Neil162c1272018-10-04 12:42:37 -0700433 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
434 meta, err := g.metaFile(content)
435 if err != nil {
436 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700437 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700438 }
439 }
440 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800441 Name: proto.String(filename + ".meta"),
Damien Neila8a2cea2019-07-10 16:17:16 -0700442 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700443 })
444 }
Damien Neil220c2022018-08-15 11:24:18 -0700445 }
Joe Tsai387873d2020-04-28 14:44:38 -0700446 if gen.SupportedFeatures > 0 {
447 resp.SupportedFeatures = proto.Uint64(gen.SupportedFeatures)
448 }
Damien Neil220c2022018-08-15 11:24:18 -0700449 return resp
450}
451
Damien Neilc7d07d92018-08-22 13:46:02 -0700452// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700453type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700454 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800455 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700456
Joe Tsaib6405bd2018-11-15 14:44:37 -0800457 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
458 GoPackageName GoPackageName // name of this file's Go package
459 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700460
461 Enums []*Enum // top-level enum declarations
462 Messages []*Message // top-level message declarations
463 Extensions []*Extension // top-level extension declarations
464 Services []*Service // top-level service declarations
465
466 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700467
468 // GeneratedFilenamePrefix is used to construct filenames for generated
469 // files associated with this source file.
470 //
471 // For example, the source file "dir/foo.proto" might have a filename prefix
472 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
473 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700474
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700475 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700476}
477
Joe Tsaie1f8d502018-11-26 18:55:29 -0800478func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
479 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700480 if err != nil {
481 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
482 }
Damien Neilc8268852019-10-08 13:28:53 -0700483 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700484 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
485 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700486 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700487 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700488 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700489 GoPackageName: packageName,
490 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700491 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700492 }
Damien Neil082ce922018-09-06 10:23:53 -0700493
494 // Determine the prefix for generated Go files.
495 prefix := p.GetName()
496 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
497 prefix = prefix[:len(prefix)-len(ext)]
498 }
Damien Neilaadba562020-02-15 14:28:51 -0800499 switch gen.pathType {
500 case pathTypeLegacy:
501 // The default is to derive the output filename from the Go import path
502 // if the file contains a go_package option,or from the input filename instead.
Damien Neil082ce922018-09-06 10:23:53 -0700503 if _, importPath := goPackageOption(p); importPath != "" {
504 prefix = path.Join(string(importPath), path.Base(prefix))
505 }
Damien Neilaadba562020-02-15 14:28:51 -0800506 case pathTypeImport:
507 // If paths=import, the output filename is derived from the Go import path.
508 prefix = path.Join(string(f.GoImportPath), path.Base(prefix))
509 case pathTypeSourceRelative:
510 // If paths=source_relative, the output filename is derived from
511 // the input filename.
Damien Neil082ce922018-09-06 10:23:53 -0700512 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800513 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700514 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800515 GoImportPath: f.GoImportPath,
516 }
Damien Neil082ce922018-09-06 10:23:53 -0700517 f.GeneratedFilenamePrefix = prefix
518
Damien Neilba1159f2018-10-17 12:53:18 -0700519 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700520 // Descriptors declarations are guaranteed to have unique comment sets.
521 // Other locations may not be unique, but we don't use them.
522 var leadingDetached []Comments
523 for _, s := range loc.GetLeadingDetachedComments() {
524 leadingDetached = append(leadingDetached, Comments(s))
525 }
526 f.comments[newPathKey(loc.Path)] = CommentSet{
527 LeadingDetached: leadingDetached,
528 Leading: Comments(loc.GetLeadingComments()),
529 Trailing: Comments(loc.GetTrailingComments()),
530 }
Damien Neilba1159f2018-10-17 12:53:18 -0700531 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700532 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
533 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700534 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700535 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
536 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700537 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700538 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
539 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700540 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700541 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
542 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700543 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700544 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700545 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700546 return nil, err
547 }
548 }
549 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700550 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700551 return nil, err
552 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700553 }
Damien Neil2dc67182018-09-21 15:03:34 -0700554 for _, service := range f.Services {
555 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700556 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700557 return nil, err
558 }
559 }
560 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700561 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700562}
563
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900564func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700565 return Location{
566 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900567 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700568 }
569}
570
Damien Neil082ce922018-09-06 10:23:53 -0700571// goPackageOption interprets a file's go_package option.
572// If there is no go_package, it returns ("", "").
573// If there's a simple name, it returns (pkg, "").
574// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800575func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700576 opt := d.GetOptions().GetGoPackage()
577 if opt == "" {
578 return "", ""
579 }
Joe Tsai3e802492019-09-07 13:06:27 -0700580 rawPkg, impPath := goPackageOptionRaw(opt)
581 pkg = cleanPackageName(rawPkg)
582 if string(pkg) != rawPkg && impPath != "" {
Damien Neile358d432020-03-06 13:58:41 -0800583 warn("Malformed 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700584 "\toption go_package = %q;\n"+
585 "A future release of protoc-gen-go will reject this.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800586 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700587 "\n", d.GetName(), string(impPath)+";"+string(pkg))
588 }
589 return pkg, impPath
590}
591func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700592 // A semicolon-delimited suffix delimits the import path and package name.
593 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700594 return opt[i+1:], GoImportPath(opt[:i])
Damien Neil082ce922018-09-06 10:23:53 -0700595 }
596 // The presence of a slash implies there's an import path.
597 if i := strings.LastIndex(opt, "/"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700598 return opt[i+1:], GoImportPath(opt)
Damien Neil082ce922018-09-06 10:23:53 -0700599 }
Joe Tsai3e802492019-09-07 13:06:27 -0700600 return opt, ""
Damien Neil082ce922018-09-06 10:23:53 -0700601}
602
Joe Tsai7762ec22019-08-20 20:10:23 -0700603// An Enum describes an enum.
604type Enum struct {
605 Desc protoreflect.EnumDescriptor
606
607 GoIdent GoIdent // name of the generated Go type
608
609 Values []*EnumValue // enum value declarations
610
611 Location Location // location of this enum
612 Comments CommentSet // comments associated with this enum
613}
614
615func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
616 var loc Location
617 if parent != nil {
618 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
619 } else {
620 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
621 }
622 enum := &Enum{
623 Desc: desc,
624 GoIdent: newGoIdent(f, desc),
625 Location: loc,
626 Comments: f.comments[newPathKey(loc.Path)],
627 }
628 gen.enumsByName[desc.FullName()] = enum
629 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
630 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
631 }
632 return enum
633}
634
635// An EnumValue describes an enum value.
636type EnumValue struct {
637 Desc protoreflect.EnumValueDescriptor
638
639 GoIdent GoIdent // name of the generated Go declaration
640
Joe Tsai4df99fd2019-08-20 22:26:16 -0700641 Parent *Enum // enum in which this value is declared
642
Joe Tsai7762ec22019-08-20 20:10:23 -0700643 Location Location // location of this enum value
644 Comments CommentSet // comments associated with this enum value
645}
646
647func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
648 // A top-level enum value's name is: EnumName_ValueName
649 // An enum value contained in a message is: MessageName_ValueName
650 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700651 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700652 parentIdent := enum.GoIdent
653 if message != nil {
654 parentIdent = message.GoIdent
655 }
656 name := parentIdent.GoName + "_" + string(desc.Name())
657 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
658 return &EnumValue{
659 Desc: desc,
660 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700661 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700662 Location: loc,
663 Comments: f.comments[newPathKey(loc.Path)],
664 }
665}
666
Damien Neilc7d07d92018-08-22 13:46:02 -0700667// A Message describes a message.
668type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700669 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700670
Joe Tsai7762ec22019-08-20 20:10:23 -0700671 GoIdent GoIdent // name of the generated Go type
672
673 Fields []*Field // message field declarations
674 Oneofs []*Oneof // message oneof declarations
675
Damien Neil993c04d2018-09-14 15:41:11 -0700676 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700677 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700678 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700679
680 Location Location // location of this message
681 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700682}
683
Damien Neil1fa78d82018-09-13 13:12:36 -0700684func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700685 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700686 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700687 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700688 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700689 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700690 }
Damien Neil46abb572018-09-07 12:45:37 -0700691 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700692 Desc: desc,
693 GoIdent: newGoIdent(f, desc),
694 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700695 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700696 }
Damien Neil658051b2018-09-10 12:26:21 -0700697 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700698 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
699 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700700 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700701 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
702 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700703 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700704 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
705 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700706 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700707 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
708 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700709 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700710 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
711 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
712 }
713
714 // Resolve local references between fields and oneofs.
715 for _, field := range message.Fields {
716 if od := field.Desc.ContainingOneof(); od != nil {
717 oneof := message.Oneofs[od.Index()]
718 field.Oneof = oneof
719 oneof.Fields = append(oneof.Fields, field)
720 }
Damien Neil993c04d2018-09-14 15:41:11 -0700721 }
Damien Neil658051b2018-09-10 12:26:21 -0700722
723 // Field name conflict resolution.
724 //
725 // We assume well-known method names that may be attached to a generated
726 // message type, as well as a 'Get*' method for each field. For each
727 // field in turn, we add _s to its name until there are no conflicts.
728 //
729 // Any change to the following set of method names is a potential
730 // incompatible API change because it may change generated field names.
731 //
732 // TODO: If we ever support a 'go_name' option to set the Go name of a
733 // field, we should consider dropping this entirely. The conflict
734 // resolution algorithm is subtle and surprising (changing the order
735 // in which fields appear in the .proto source file can change the
736 // names of fields in generated code), and does not adapt well to
737 // adding new per-field methods such as setters.
738 usedNames := map[string]bool{
739 "Reset": true,
740 "String": true,
741 "ProtoMessage": true,
742 "Marshal": true,
743 "Unmarshal": true,
744 "ExtensionRangeArray": true,
745 "ExtensionMap": true,
746 "Descriptor": true,
747 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800748 makeNameUnique := func(name string, hasGetter bool) string {
749 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700750 name += "_"
751 }
752 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800753 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700754 return name
755 }
756 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800757 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700758 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
759 if field.Oneof != nil && field.Oneof.Fields[0] == field {
760 // Make the name for a oneof unique as well. For historical reasons,
761 // this assumes that a getter method is not generated for oneofs.
762 // This is incorrect, but fixing it breaks existing code.
763 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
764 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
765 }
766 }
767
768 // Oneof field name conflict resolution.
769 //
770 // This conflict resolution is incomplete as it does not consider collisions
771 // with other oneof field types, but fixing it breaks existing code.
772 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700773 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700774 Loop:
775 for {
776 for _, nestedMessage := range message.Messages {
777 if nestedMessage.GoIdent == field.GoIdent {
778 field.GoIdent.GoName += "_"
779 continue Loop
780 }
781 }
782 for _, nestedEnum := range message.Enums {
783 if nestedEnum.GoIdent == field.GoIdent {
784 field.GoIdent.GoName += "_"
785 continue Loop
786 }
787 }
788 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700789 }
790 }
Damien Neil658051b2018-09-10 12:26:21 -0700791 }
792
Damien Neil1fa78d82018-09-13 13:12:36 -0700793 return message
Damien Neil658051b2018-09-10 12:26:21 -0700794}
795
Joe Tsai7762ec22019-08-20 20:10:23 -0700796func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700797 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700798 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700799 return err
800 }
801 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700802 for _, message := range message.Messages {
803 if err := message.resolveDependencies(gen); err != nil {
804 return err
805 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700806 }
Damien Neil993c04d2018-09-14 15:41:11 -0700807 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700808 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700809 return err
810 }
811 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700812 return nil
813}
814
Damien Neil658051b2018-09-10 12:26:21 -0700815// A Field describes a message field.
816type Field struct {
817 Desc protoreflect.FieldDescriptor
818
Damien Neil1fa78d82018-09-13 13:12:36 -0700819 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700820 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700821 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700822 GoName string // e.g., "FieldName"
823
824 // GoIdent is the base name of a top-level declaration for this field.
825 // For code generated by protoc-gen-go, this means a wrapper type named
826 // '{{GoIdent}}' for members fields of a oneof, and a variable named
827 // 'E_{{GoIdent}}' for extension fields.
828 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700829
Joe Tsai7762ec22019-08-20 20:10:23 -0700830 Parent *Message // message in which this field is declared; nil if top-level extension
831 Oneof *Oneof // containing oneof; nil if not part of a oneof
832 Extendee *Message // extended message for extension fields; nil otherwise
833
834 Enum *Enum // type for enum fields; nil otherwise
835 Message *Message // type for message or group fields; nil otherwise
836
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700837 Location Location // location of this field
838 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700839}
840
Damien Neil1fa78d82018-09-13 13:12:36 -0700841func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700842 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700843 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700844 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700845 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700846 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700847 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700848 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700849 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700850 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700851 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700852 var parentPrefix string
853 if message != nil {
854 parentPrefix = message.GoIdent.GoName + "_"
855 }
Damien Neil658051b2018-09-10 12:26:21 -0700856 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700857 Desc: desc,
858 GoName: camelCased,
859 GoIdent: GoIdent{
860 GoImportPath: f.GoImportPath,
861 GoName: parentPrefix + camelCased,
862 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700863 Parent: message,
864 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700865 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700866 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700867 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700868}
869
Joe Tsai7762ec22019-08-20 20:10:23 -0700870func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700871 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700872 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700873 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700874 name := field.Desc.Enum().FullName()
875 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700876 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700877 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700878 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700879 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700880 case protoreflect.MessageKind, protoreflect.GroupKind:
881 name := desc.Message().FullName()
882 message, ok := gen.messagesByName[name]
883 if !ok {
884 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
885 }
886 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700887 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700888 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700889 name := desc.ContainingMessage().FullName()
890 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700891 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700892 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700893 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700894 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700895 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700896 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700897}
898
Joe Tsai7762ec22019-08-20 20:10:23 -0700899// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700900type Oneof struct {
901 Desc protoreflect.OneofDescriptor
902
Joe Tsaief6e5242019-08-21 00:55:36 -0700903 // GoName is the base name of this oneof's Go field and methods.
904 // For code generated by protoc-gen-go, this means a field named
905 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
906 GoName string // e.g., "OneofName"
907
908 // GoIdent is the base name of a top-level declaration for this oneof.
909 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700910
911 Parent *Message // message in which this oneof is declared
912
Joe Tsaid24bc722019-04-15 23:39:09 -0700913 Fields []*Field // fields that are part of this oneof
914
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700915 Location Location // location of this oneof
916 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700917}
918
919func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700920 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Joe Tsai2e7817f2019-08-23 12:18:57 -0700921 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700922 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700923 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700924 Desc: desc,
925 Parent: message,
926 GoName: camelCased,
927 GoIdent: GoIdent{
928 GoImportPath: f.GoImportPath,
929 GoName: parentPrefix + camelCased,
930 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700931 Location: loc,
932 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700933 }
934}
935
Joe Tsai7762ec22019-08-20 20:10:23 -0700936// Extension is an alias of Field for documentation.
937type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700938
Damien Neil2dc67182018-09-21 15:03:34 -0700939// A Service describes a service.
940type Service struct {
941 Desc protoreflect.ServiceDescriptor
942
Joe Tsai7762ec22019-08-20 20:10:23 -0700943 GoName string
944
945 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700946
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700947 Location Location // location of this service
948 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700949}
950
951func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700952 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700953 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700954 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700955 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700956 Location: loc,
957 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700958 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700959 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
960 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700961 }
962 return service
963}
964
965// A Method describes a method in a service.
966type Method struct {
967 Desc protoreflect.MethodDescriptor
968
Joe Tsaid24bc722019-04-15 23:39:09 -0700969 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700970
971 Parent *Service // service in which this method is declared
972
Joe Tsaid24bc722019-04-15 23:39:09 -0700973 Input *Message
974 Output *Message
975
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700976 Location Location // location of this method
977 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700978}
979
980func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700981 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700982 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700983 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700984 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700985 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700986 Location: loc,
987 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700988 }
989 return method
990}
991
Joe Tsai7762ec22019-08-20 20:10:23 -0700992func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700993 desc := method.Desc
994
Joe Tsaid24bc722019-04-15 23:39:09 -0700995 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700996 in, ok := gen.messagesByName[inName]
997 if !ok {
998 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
999 }
Joe Tsaid24bc722019-04-15 23:39:09 -07001000 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -07001001
Joe Tsaid24bc722019-04-15 23:39:09 -07001002 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -07001003 out, ok := gen.messagesByName[outName]
1004 if !ok {
1005 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
1006 }
Joe Tsaid24bc722019-04-15 23:39:09 -07001007 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -07001008
1009 return nil
1010}
1011
Damien Neil7bf3ce22018-12-21 15:54:06 -08001012// A GeneratedFile is a generated file.
1013type GeneratedFile struct {
1014 gen *Plugin
1015 skip bool
1016 filename string
1017 goImportPath GoImportPath
1018 buf bytes.Buffer
1019 packageNames map[GoImportPath]GoPackageName
1020 usedPackageNames map[GoPackageName]bool
1021 manualImports map[GoImportPath]bool
1022 annotations map[string][]Location
1023}
1024
1025// NewGeneratedFile creates a new generated file with the given filename
1026// and import path.
1027func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
1028 g := &GeneratedFile{
1029 gen: gen,
1030 filename: filename,
1031 goImportPath: goImportPath,
1032 packageNames: make(map[GoImportPath]GoPackageName),
1033 usedPackageNames: make(map[GoPackageName]bool),
1034 manualImports: make(map[GoImportPath]bool),
1035 annotations: make(map[string][]Location),
1036 }
Joe Tsai124c8122019-01-14 11:48:43 -08001037
1038 // All predeclared identifiers in Go are already used.
1039 for _, s := range types.Universe.Names() {
1040 g.usedPackageNames[GoPackageName(s)] = true
1041 }
1042
Damien Neil7bf3ce22018-12-21 15:54:06 -08001043 gen.genFiles = append(gen.genFiles, g)
1044 return g
1045}
1046
Damien Neil220c2022018-08-15 11:24:18 -07001047// P prints a line to the generated output. It converts each parameter to a
1048// string following the same rules as fmt.Print. It never inserts spaces
1049// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -07001050func (g *GeneratedFile) P(v ...interface{}) {
1051 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -07001052 switch x := x.(type) {
1053 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -07001054 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -07001055 default:
1056 fmt.Fprint(&g.buf, x)
1057 }
Damien Neil220c2022018-08-15 11:24:18 -07001058 }
1059 fmt.Fprintln(&g.buf)
1060}
1061
Damien Neil46abb572018-09-07 12:45:37 -07001062// QualifiedGoIdent returns the string to use for a Go identifier.
1063//
1064// If the identifier is from a different Go package than the generated file,
1065// the returned name will be qualified (package.name) and an import statement
1066// for the identifier's package will be included in the file.
1067func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
1068 if ident.GoImportPath == g.goImportPath {
1069 return ident.GoName
1070 }
1071 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
1072 return string(packageName) + "." + ident.GoName
1073 }
1074 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -08001075 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -07001076 packageName = orig + GoPackageName(strconv.Itoa(i))
1077 }
1078 g.packageNames[ident.GoImportPath] = packageName
1079 g.usedPackageNames[packageName] = true
1080 return string(packageName) + "." + ident.GoName
1081}
1082
Damien Neil2e0c3da2018-09-19 12:51:36 -07001083// Import ensures a package is imported by the generated file.
1084//
1085// Packages referenced by QualifiedGoIdent are automatically imported.
1086// Explicitly importing a package with Import is generally only necessary
1087// when the import will be blank (import _ "package").
1088func (g *GeneratedFile) Import(importPath GoImportPath) {
1089 g.manualImports[importPath] = true
1090}
1091
Damien Neil220c2022018-08-15 11:24:18 -07001092// Write implements io.Writer.
1093func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1094 return g.buf.Write(p)
1095}
1096
Damien Neil7bf3ce22018-12-21 15:54:06 -08001097// Skip removes the generated file from the plugin output.
1098func (g *GeneratedFile) Skip() {
1099 g.skip = true
1100}
1101
Damien Neil162c1272018-10-04 12:42:37 -07001102// Annotate associates a symbol in a generated Go file with a location in a
1103// source .proto file.
1104//
1105// The symbol may refer to a type, constant, variable, function, method, or
1106// struct field. The "T.sel" syntax is used to identify the method or field
1107// 'sel' on type 'T'.
1108func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1109 g.annotations[symbol] = append(g.annotations[symbol], loc)
1110}
1111
Damien Neil7bf3ce22018-12-21 15:54:06 -08001112// Content returns the contents of the generated file.
1113func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001114 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001115 return g.buf.Bytes(), nil
1116 }
1117
1118 // Reformat generated code.
1119 original := g.buf.Bytes()
1120 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001121 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001122 if err != nil {
1123 // Print out the bad code with line numbers.
1124 // This should never happen in practice, but it can while changing generated code
1125 // so consider this a debugging aid.
1126 var src bytes.Buffer
1127 s := bufio.NewScanner(bytes.NewReader(original))
1128 for line := 1; s.Scan(); line++ {
1129 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1130 }
Damien Neild9016772018-08-23 14:39:30 -07001131 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001132 }
Damien Neild9016772018-08-23 14:39:30 -07001133
Joe Tsaibeda4042019-03-10 16:40:48 -07001134 // Collect a sorted list of all imports.
1135 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001136 rewriteImport := func(importPath string) string {
1137 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1138 return string(f(GoImportPath(importPath)))
1139 }
1140 return importPath
1141 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001142 for importPath := range g.packageNames {
1143 pkgName := string(g.packageNames[GoImportPath(importPath)])
1144 pkgPath := rewriteImport(string(importPath))
1145 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001146 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001147 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001148 if _, ok := g.packageNames[importPath]; !ok {
1149 pkgPath := rewriteImport(string(importPath))
1150 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001151 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001152 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001153 sort.Slice(importPaths, func(i, j int) bool {
1154 return importPaths[i][1] < importPaths[j][1]
1155 })
1156
1157 // Modify the AST to include a new import block.
1158 if len(importPaths) > 0 {
1159 // Insert block after package statement or
1160 // possible comment attached to the end of the package statement.
1161 pos := file.Package
1162 tokFile := fset.File(file.Package)
1163 pkgLine := tokFile.Line(file.Package)
1164 for _, c := range file.Comments {
1165 if tokFile.Line(c.Pos()) > pkgLine {
1166 break
1167 }
1168 pos = c.End()
1169 }
1170
1171 // Construct the import block.
1172 impDecl := &ast.GenDecl{
1173 Tok: token.IMPORT,
1174 TokPos: pos,
1175 Lparen: pos,
1176 Rparen: pos,
1177 }
1178 for _, importPath := range importPaths {
1179 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1180 Name: &ast.Ident{
1181 Name: importPath[0],
1182 NamePos: pos,
1183 },
1184 Path: &ast.BasicLit{
1185 Kind: token.STRING,
1186 Value: strconv.Quote(importPath[1]),
1187 ValuePos: pos,
1188 },
1189 EndPos: pos,
1190 })
1191 }
1192 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1193 }
Damien Neild9016772018-08-23 14:39:30 -07001194
Damien Neilc7d07d92018-08-22 13:46:02 -07001195 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001196 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001197 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001198 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001199 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001200}
Damien Neilc7d07d92018-08-22 13:46:02 -07001201
Damien Neil162c1272018-10-04 12:42:37 -07001202// metaFile returns the contents of the file's metadata file, which is a
1203// text formatted string of the google.protobuf.GeneratedCodeInfo.
1204func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1205 fset := token.NewFileSet()
1206 astFile, err := parser.ParseFile(fset, "", content, 0)
1207 if err != nil {
1208 return "", err
1209 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001210 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001211
1212 seenAnnotations := make(map[string]bool)
1213 annotate := func(s string, ident *ast.Ident) {
1214 seenAnnotations[s] = true
1215 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001216 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001217 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001218 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001219 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1220 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001221 })
1222 }
1223 }
1224 for _, decl := range astFile.Decls {
1225 switch decl := decl.(type) {
1226 case *ast.GenDecl:
1227 for _, spec := range decl.Specs {
1228 switch spec := spec.(type) {
1229 case *ast.TypeSpec:
1230 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001231 switch st := spec.Type.(type) {
1232 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001233 for _, field := range st.Fields.List {
1234 for _, name := range field.Names {
1235 annotate(spec.Name.Name+"."+name.Name, name)
1236 }
1237 }
Damien Neilae2a5612018-12-12 08:54:57 -08001238 case *ast.InterfaceType:
1239 for _, field := range st.Methods.List {
1240 for _, name := range field.Names {
1241 annotate(spec.Name.Name+"."+name.Name, name)
1242 }
1243 }
Damien Neil162c1272018-10-04 12:42:37 -07001244 }
1245 case *ast.ValueSpec:
1246 for _, name := range spec.Names {
1247 annotate(name.Name, name)
1248 }
1249 }
1250 }
1251 case *ast.FuncDecl:
1252 if decl.Recv == nil {
1253 annotate(decl.Name.Name, decl.Name)
1254 } else {
1255 recv := decl.Recv.List[0].Type
1256 if s, ok := recv.(*ast.StarExpr); ok {
1257 recv = s.X
1258 }
1259 if id, ok := recv.(*ast.Ident); ok {
1260 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1261 }
1262 }
1263 }
1264 }
1265 for a := range g.annotations {
1266 if !seenAnnotations[a] {
1267 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1268 }
1269 }
1270
Damien Neil5c5b5312019-05-14 12:44:37 -07001271 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001272 if err != nil {
1273 return "", err
1274 }
1275 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001276}
Damien Neil082ce922018-09-06 10:23:53 -07001277
Joe Tsai2e7817f2019-08-23 12:18:57 -07001278// A GoIdent is a Go identifier, consisting of a name and import path.
1279// The name is a single identifier and may not be a dot-qualified selector.
1280type GoIdent struct {
1281 GoName string
1282 GoImportPath GoImportPath
1283}
1284
1285func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1286
1287// newGoIdent returns the Go identifier for a descriptor.
1288func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1289 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1290 return GoIdent{
1291 GoName: strs.GoCamelCase(name),
1292 GoImportPath: f.GoImportPath,
1293 }
1294}
1295
1296// A GoImportPath is the import path of a Go package.
1297// For example: "google.golang.org/protobuf/compiler/protogen"
1298type GoImportPath string
1299
1300func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1301
1302// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1303func (p GoImportPath) Ident(s string) GoIdent {
1304 return GoIdent{GoName: s, GoImportPath: p}
1305}
1306
1307// A GoPackageName is the name of a Go package. e.g., "protobuf".
1308type GoPackageName string
1309
1310// cleanPackageName converts a string to a valid Go package name.
1311func cleanPackageName(name string) GoPackageName {
1312 return GoPackageName(strs.GoSanitized(name))
1313}
1314
1315// baseName returns the last path element of the name, with the last dotted suffix removed.
1316func baseName(name string) string {
1317 // First, find the last element
1318 if i := strings.LastIndex(name, "/"); i >= 0 {
1319 name = name[i+1:]
1320 }
1321 // Now drop the suffix
1322 if i := strings.LastIndex(name, "."); i >= 0 {
1323 name = name[:i]
1324 }
1325 return name
1326}
1327
Damien Neil082ce922018-09-06 10:23:53 -07001328type pathType int
1329
1330const (
Damien Neilaadba562020-02-15 14:28:51 -08001331 pathTypeLegacy pathType = iota
1332 pathTypeImport
Damien Neil082ce922018-09-06 10:23:53 -07001333 pathTypeSourceRelative
1334)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001335
Damien Neil162c1272018-10-04 12:42:37 -07001336// A Location is a location in a .proto source file.
1337//
1338// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1339// for details.
1340type Location struct {
1341 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001342 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001343}
1344
1345// appendPath add elements to a Location's path, returning a new Location.
1346func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001347 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001348 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001349 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001350 return Location{
1351 SourceFile: loc.SourceFile,
1352 Path: n,
1353 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001354}
Damien Neilba1159f2018-10-17 12:53:18 -07001355
1356// A pathKey is a representation of a location path suitable for use as a map key.
1357type pathKey struct {
1358 s string
1359}
1360
1361// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001362func newPathKey(idxPath []int32) pathKey {
1363 buf := make([]byte, 4*len(idxPath))
1364 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001365 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1366 }
1367 return pathKey{string(buf)}
1368}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001369
1370// CommentSet is a set of leading and trailing comments associated
1371// with a .proto descriptor declaration.
1372type CommentSet struct {
1373 LeadingDetached []Comments
1374 Leading Comments
1375 Trailing Comments
1376}
1377
1378// Comments is a comments string as provided by protoc.
1379type Comments string
1380
1381// String formats the comments by inserting // to the start of each line,
1382// ensuring that there is a trailing newline.
1383// An empty comment is formatted as an empty string.
1384func (c Comments) String() string {
1385 if c == "" {
1386 return ""
1387 }
1388 var b []byte
1389 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1390 b = append(b, "//"...)
1391 b = append(b, line...)
1392 b = append(b, "\n"...)
1393 }
1394 return string(b)
1395}
Damien Neile358d432020-03-06 13:58:41 -08001396
1397var warnings = true
1398
1399func warn(format string, a ...interface{}) {
1400 if warnings {
1401 log.Printf("WARNING: "+format, a...)
1402 }
1403}