blob: 5cd2a807f8732ad25cd3cb97f5aa48f19ee01ae9 [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
Damien Neil658051b2018-09-10 12:26:21 -0700107 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700108 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700109 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700110 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700111 pathType pathType
112 genFiles []*GeneratedFile
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800113 opts Options
Damien Neil658051b2018-09-10 12:26:21 -0700114 err error
Damien Neil220c2022018-08-15 11:24:18 -0700115}
116
Damien Neil3cf6e622018-09-11 13:53:14 -0700117type Options struct {
118 // If ParamFunc is non-nil, it will be called with each unknown
119 // generator parameter.
120 //
121 // Plugins for protoc can accept parameters from the command line,
122 // passed in the --<lang>_out protoc, separated from the output
123 // directory with a colon; e.g.,
124 //
125 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
126 //
127 // Parameters passed in this fashion as a comma-separated list of
128 // key=value pairs will be passed to the ParamFunc.
129 //
130 // The (flag.FlagSet).Set method matches this function signature,
131 // so parameters can be converted into flags as in the following:
132 //
133 // var flags flag.FlagSet
134 // value := flags.Bool("param", false, "")
135 // opts := &protogen.Options{
136 // ParamFunc: flags.Set,
137 // }
138 // protogen.Run(opts, func(p *protogen.Plugin) error {
139 // if *value { ... }
140 // })
141 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700142
143 // ImportRewriteFunc is called with the import path of each package
144 // imported by a generated file. It returns the import path to use
145 // for this package.
146 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700147}
148
Damien Neil220c2022018-08-15 11:24:18 -0700149// New returns a new Plugin.
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800150func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
Damien Neil220c2022018-08-15 11:24:18 -0700151 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700152 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700153 FilesByPath: make(map[string]*File),
Damien Neilc8268852019-10-08 13:28:53 -0700154 fileReg: new(protoregistry.Files),
Damien Neil658051b2018-09-10 12:26:21 -0700155 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700156 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700157 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700158 }
159
Damien Neil082ce922018-09-06 10:23:53 -0700160 packageNames := make(map[string]GoPackageName) // filename -> package name
161 importPaths := make(map[string]GoImportPath) // filename -> import path
Joe Tsai3e802492019-09-07 13:06:27 -0700162 mfiles := make(map[string]bool) // filename set
Damien Neil082ce922018-09-06 10:23:53 -0700163 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700164 for _, param := range strings.Split(req.GetParameter(), ",") {
165 var value string
166 if i := strings.Index(param, "="); i >= 0 {
167 value = param[i+1:]
168 param = param[0:i]
169 }
170 switch param {
171 case "":
172 // Ignore.
Damien Neil220c2022018-08-15 11:24:18 -0700173 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700174 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700175 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700176 switch value {
177 case "import":
178 gen.pathType = pathTypeImport
179 case "source_relative":
180 gen.pathType = pathTypeSourceRelative
181 default:
182 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
183 }
Damien Neil220c2022018-08-15 11:24:18 -0700184 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700185 switch value {
186 case "true", "":
187 gen.annotateCode = true
188 case "false":
189 default:
190 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
191 }
Damien Neil220c2022018-08-15 11:24:18 -0700192 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700193 if param[0] == 'M' {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700194 if i := strings.Index(value, ";"); i >= 0 {
195 pkgName := GoPackageName(value[i+1:])
196 if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName {
197 return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName)
198 }
199 packageNames[param[1:]] = pkgName
200 value = value[:i]
201 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700202 importPaths[param[1:]] = GoImportPath(value)
Joe Tsai3e802492019-09-07 13:06:27 -0700203 mfiles[param[1:]] = true
Damien Neil3cf6e622018-09-11 13:53:14 -0700204 continue
Damien Neil220c2022018-08-15 11:24:18 -0700205 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700206 if opts.ParamFunc != nil {
207 if err := opts.ParamFunc(param, value); err != nil {
208 return nil, err
209 }
210 }
Damien Neil082ce922018-09-06 10:23:53 -0700211 }
212 }
213
214 // Figure out the import path and package name for each file.
215 //
216 // The rules here are complicated and have grown organically over time.
217 // Interactions between different ways of specifying package information
218 // may be surprising.
219 //
220 // The recommended approach is to include a go_package option in every
221 // .proto source file specifying the full import path of the Go package
222 // associated with this file.
223 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700224 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700225 //
226 // Build systems which want to exert full control over import paths may
227 // specify M<filename>=<import_path> flags.
228 //
229 // Other approaches are not recommend.
230 generatedFileNames := make(map[string]bool)
231 for _, name := range gen.Request.FileToGenerate {
232 generatedFileNames[name] = true
233 }
234 // We need to determine the import paths before the package names,
235 // because the Go package name for a file is sometimes derived from
236 // different file in the same package.
237 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
238 for _, fdesc := range gen.Request.ProtoFile {
239 filename := fdesc.GetName()
240 packageName, importPath := goPackageOption(fdesc)
241 switch {
242 case importPaths[filename] != "":
Damien Neilaadba562020-02-15 14:28:51 -0800243 // Command line: Mfoo.proto=quux/bar
Damien Neil082ce922018-09-06 10:23:53 -0700244 //
245 // Explicit mapping of source file to import path.
246 case generatedFileNames[filename] && packageImportPath != "":
247 // Command line: import_path=quux/bar
248 //
249 // The import_path flag sets the import path for every file that
250 // we generate code for.
251 importPaths[filename] = packageImportPath
252 case importPath != "":
253 // Source file: option go_package = "quux/bar";
254 //
255 // The go_package option sets the import path. Most users should use this.
256 importPaths[filename] = importPath
257 default:
258 // Source filename.
259 //
260 // Last resort when nothing else is available.
261 importPaths[filename] = GoImportPath(path.Dir(filename))
262 }
263 if packageName != "" {
264 packageNameForImportPath[importPaths[filename]] = packageName
265 }
266 }
267 for _, fdesc := range gen.Request.ProtoFile {
268 filename := fdesc.GetName()
Joe Tsai3e802492019-09-07 13:06:27 -0700269 packageName, importPath := goPackageOption(fdesc)
Damien Neil082ce922018-09-06 10:23:53 -0700270 defaultPackageName := packageNameForImportPath[importPaths[filename]]
271 switch {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700272 case packageNames[filename] != "":
273 // A package name specified by the "M" command-line argument.
Damien Neil082ce922018-09-06 10:23:53 -0700274 case packageName != "":
Joe Tsai3e802492019-09-07 13:06:27 -0700275 // TODO: For the "M" command-line argument, this means that the
276 // package name can be derived from the go_package option.
277 // Go package information should either consistently come from the
278 // command-line or the .proto source file, but not both.
279 // See how to make this consistent.
280
Damien Neil082ce922018-09-06 10:23:53 -0700281 // Source file: option go_package = "quux/bar";
282 packageNames[filename] = packageName
283 case defaultPackageName != "":
284 // A go_package option in another file in the same package.
285 //
286 // This is a poor choice in general, since every source file should
287 // contain a go_package option. Supported mainly for historical
288 // compatibility.
289 packageNames[filename] = defaultPackageName
290 case generatedFileNames[filename] && packageImportPath != "":
291 // Command line: import_path=quux/bar
292 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
293 case fdesc.GetPackage() != "":
294 // Source file: package quux.bar;
295 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
296 default:
297 // Source filename.
298 packageNames[filename] = cleanPackageName(baseName(filename))
299 }
Joe Tsai3e802492019-09-07 13:06:27 -0700300
301 goPkgOpt := string(importPaths[filename])
302 if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
303 goPkgOpt += ";" + string(packageNames[filename])
304 }
305 switch {
306 case packageImportPath != "":
307 // Command line: import_path=quux/bar
Damien Neile358d432020-03-06 13:58:41 -0800308 warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700309 "\toption go_package = %q;\n"+
310 "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800311 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700312 "\n", fdesc.GetName(), goPkgOpt)
313 case mfiles[filename]:
314 // Command line: M=foo.proto=quux/bar
315 case packageName != "" && importPath == "":
316 // Source file: option go_package = "quux";
Damien Neile358d432020-03-06 13:58:41 -0800317 warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700318 "\toption go_package = %q;\n"+
319 "A future release of protoc-gen-go will require the import path be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800320 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700321 "\n", fdesc.GetName(), goPkgOpt)
322 case packageName == "" && importPath == "":
323 // No Go package information provided.
Damien Neile358d432020-03-06 13:58:41 -0800324 warn("Missing 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700325 "\toption go_package = %q;\n"+
326 "A future release of protoc-gen-go will require this be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800327 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700328 "\n", fdesc.GetName(), goPkgOpt)
329 }
Damien Neil082ce922018-09-06 10:23:53 -0700330 }
331
332 // Consistency check: Every file with the same Go import path should have
333 // the same Go package name.
334 packageFiles := make(map[GoImportPath][]string)
335 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700336 if _, ok := packageNames[filename]; !ok {
337 // Skip files mentioned in a M<file>=<import_path> parameter
338 // but which do not appear in the CodeGeneratorRequest.
339 continue
340 }
Damien Neil082ce922018-09-06 10:23:53 -0700341 packageFiles[importPath] = append(packageFiles[importPath], filename)
342 }
343 for importPath, filenames := range packageFiles {
344 for i := 1; i < len(filenames); i++ {
345 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
346 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
347 importPath, a, filenames[0], b, filenames[i])
348 }
Damien Neil220c2022018-08-15 11:24:18 -0700349 }
350 }
351
352 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700353 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700354 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700355 return nil, fmt.Errorf("duplicate file name: %q", filename)
356 }
357 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700358 if err != nil {
359 return nil, err
360 }
Damien Neil220c2022018-08-15 11:24:18 -0700361 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700362 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700363 }
Damien Neil082ce922018-09-06 10:23:53 -0700364 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700365 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700366 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700367 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700368 }
369 f.Generate = true
370 }
371 return gen, nil
372}
373
374// Error records an error in code generation. The generator will report the
375// error back to protoc and will not produce output.
376func (gen *Plugin) Error(err error) {
377 if gen.err == nil {
378 gen.err = err
379 }
380}
381
382// Response returns the generator output.
383func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
384 resp := &pluginpb.CodeGeneratorResponse{}
385 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700386 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700387 return resp
388 }
Damien Neil162c1272018-10-04 12:42:37 -0700389 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800390 if g.skip {
391 continue
392 }
393 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700394 if err != nil {
395 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700396 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700397 }
398 }
Damien Neil220c2022018-08-15 11:24:18 -0700399 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700400 Name: proto.String(g.filename),
401 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700402 })
Damien Neil162c1272018-10-04 12:42:37 -0700403 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
404 meta, err := g.metaFile(content)
405 if err != nil {
406 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700407 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700408 }
409 }
410 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700411 Name: proto.String(g.filename + ".meta"),
412 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700413 })
414 }
Damien Neil220c2022018-08-15 11:24:18 -0700415 }
416 return resp
417}
418
Damien Neilc7d07d92018-08-22 13:46:02 -0700419// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700420type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700421 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800422 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700423
Joe Tsaib6405bd2018-11-15 14:44:37 -0800424 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
425 GoPackageName GoPackageName // name of this file's Go package
426 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700427
428 Enums []*Enum // top-level enum declarations
429 Messages []*Message // top-level message declarations
430 Extensions []*Extension // top-level extension declarations
431 Services []*Service // top-level service declarations
432
433 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700434
435 // GeneratedFilenamePrefix is used to construct filenames for generated
436 // files associated with this source file.
437 //
438 // For example, the source file "dir/foo.proto" might have a filename prefix
439 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
440 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700441
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700442 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700443}
444
Joe Tsaie1f8d502018-11-26 18:55:29 -0800445func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
446 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700447 if err != nil {
448 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
449 }
Damien Neilc8268852019-10-08 13:28:53 -0700450 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700451 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
452 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700453 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700454 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700455 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700456 GoPackageName: packageName,
457 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700458 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700459 }
Damien Neil082ce922018-09-06 10:23:53 -0700460
461 // Determine the prefix for generated Go files.
462 prefix := p.GetName()
463 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
464 prefix = prefix[:len(prefix)-len(ext)]
465 }
Damien Neilaadba562020-02-15 14:28:51 -0800466 switch gen.pathType {
467 case pathTypeLegacy:
468 // The default is to derive the output filename from the Go import path
469 // if the file contains a go_package option,or from the input filename instead.
Damien Neil082ce922018-09-06 10:23:53 -0700470 if _, importPath := goPackageOption(p); importPath != "" {
471 prefix = path.Join(string(importPath), path.Base(prefix))
472 }
Damien Neilaadba562020-02-15 14:28:51 -0800473 case pathTypeImport:
474 // If paths=import, the output filename is derived from the Go import path.
475 prefix = path.Join(string(f.GoImportPath), path.Base(prefix))
476 case pathTypeSourceRelative:
477 // If paths=source_relative, the output filename is derived from
478 // the input filename.
Damien Neil082ce922018-09-06 10:23:53 -0700479 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800480 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700481 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800482 GoImportPath: f.GoImportPath,
483 }
Damien Neil082ce922018-09-06 10:23:53 -0700484 f.GeneratedFilenamePrefix = prefix
485
Damien Neilba1159f2018-10-17 12:53:18 -0700486 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700487 // Descriptors declarations are guaranteed to have unique comment sets.
488 // Other locations may not be unique, but we don't use them.
489 var leadingDetached []Comments
490 for _, s := range loc.GetLeadingDetachedComments() {
491 leadingDetached = append(leadingDetached, Comments(s))
492 }
493 f.comments[newPathKey(loc.Path)] = CommentSet{
494 LeadingDetached: leadingDetached,
495 Leading: Comments(loc.GetLeadingComments()),
496 Trailing: Comments(loc.GetTrailingComments()),
497 }
Damien Neilba1159f2018-10-17 12:53:18 -0700498 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700499 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
500 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700501 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700502 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
503 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700504 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700505 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
506 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700507 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700508 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
509 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700510 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700511 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700512 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700513 return nil, err
514 }
515 }
516 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700517 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700518 return nil, err
519 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700520 }
Damien Neil2dc67182018-09-21 15:03:34 -0700521 for _, service := range f.Services {
522 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700523 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700524 return nil, err
525 }
526 }
527 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700528 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700529}
530
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900531func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700532 return Location{
533 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900534 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700535 }
536}
537
Damien Neil082ce922018-09-06 10:23:53 -0700538// goPackageOption interprets a file's go_package option.
539// If there is no go_package, it returns ("", "").
540// If there's a simple name, it returns (pkg, "").
541// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800542func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700543 opt := d.GetOptions().GetGoPackage()
544 if opt == "" {
545 return "", ""
546 }
Joe Tsai3e802492019-09-07 13:06:27 -0700547 rawPkg, impPath := goPackageOptionRaw(opt)
548 pkg = cleanPackageName(rawPkg)
549 if string(pkg) != rawPkg && impPath != "" {
Damien Neile358d432020-03-06 13:58:41 -0800550 warn("Malformed 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700551 "\toption go_package = %q;\n"+
552 "A future release of protoc-gen-go will reject this.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800553 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700554 "\n", d.GetName(), string(impPath)+";"+string(pkg))
555 }
556 return pkg, impPath
557}
558func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700559 // A semicolon-delimited suffix delimits the import path and package name.
560 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700561 return opt[i+1:], GoImportPath(opt[:i])
Damien Neil082ce922018-09-06 10:23:53 -0700562 }
563 // The presence of a slash implies there's an import path.
564 if i := strings.LastIndex(opt, "/"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700565 return opt[i+1:], GoImportPath(opt)
Damien Neil082ce922018-09-06 10:23:53 -0700566 }
Joe Tsai3e802492019-09-07 13:06:27 -0700567 return opt, ""
Damien Neil082ce922018-09-06 10:23:53 -0700568}
569
Joe Tsai7762ec22019-08-20 20:10:23 -0700570// An Enum describes an enum.
571type Enum struct {
572 Desc protoreflect.EnumDescriptor
573
574 GoIdent GoIdent // name of the generated Go type
575
576 Values []*EnumValue // enum value declarations
577
578 Location Location // location of this enum
579 Comments CommentSet // comments associated with this enum
580}
581
582func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
583 var loc Location
584 if parent != nil {
585 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
586 } else {
587 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
588 }
589 enum := &Enum{
590 Desc: desc,
591 GoIdent: newGoIdent(f, desc),
592 Location: loc,
593 Comments: f.comments[newPathKey(loc.Path)],
594 }
595 gen.enumsByName[desc.FullName()] = enum
596 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
597 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
598 }
599 return enum
600}
601
602// An EnumValue describes an enum value.
603type EnumValue struct {
604 Desc protoreflect.EnumValueDescriptor
605
606 GoIdent GoIdent // name of the generated Go declaration
607
Joe Tsai4df99fd2019-08-20 22:26:16 -0700608 Parent *Enum // enum in which this value is declared
609
Joe Tsai7762ec22019-08-20 20:10:23 -0700610 Location Location // location of this enum value
611 Comments CommentSet // comments associated with this enum value
612}
613
614func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
615 // A top-level enum value's name is: EnumName_ValueName
616 // An enum value contained in a message is: MessageName_ValueName
617 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700618 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700619 parentIdent := enum.GoIdent
620 if message != nil {
621 parentIdent = message.GoIdent
622 }
623 name := parentIdent.GoName + "_" + string(desc.Name())
624 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
625 return &EnumValue{
626 Desc: desc,
627 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700628 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700629 Location: loc,
630 Comments: f.comments[newPathKey(loc.Path)],
631 }
632}
633
Damien Neilc7d07d92018-08-22 13:46:02 -0700634// A Message describes a message.
635type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700636 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700637
Joe Tsai7762ec22019-08-20 20:10:23 -0700638 GoIdent GoIdent // name of the generated Go type
639
640 Fields []*Field // message field declarations
641 Oneofs []*Oneof // message oneof declarations
642
Damien Neil993c04d2018-09-14 15:41:11 -0700643 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700644 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700645 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700646
647 Location Location // location of this message
648 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700649}
650
Damien Neil1fa78d82018-09-13 13:12:36 -0700651func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700652 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700653 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700654 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700655 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700656 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700657 }
Damien Neil46abb572018-09-07 12:45:37 -0700658 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700659 Desc: desc,
660 GoIdent: newGoIdent(f, desc),
661 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700662 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700663 }
Damien Neil658051b2018-09-10 12:26:21 -0700664 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700665 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
666 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700667 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700668 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
669 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700670 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700671 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
672 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700673 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700674 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
675 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700676 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700677 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
678 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
679 }
680
681 // Resolve local references between fields and oneofs.
682 for _, field := range message.Fields {
683 if od := field.Desc.ContainingOneof(); od != nil {
684 oneof := message.Oneofs[od.Index()]
685 field.Oneof = oneof
686 oneof.Fields = append(oneof.Fields, field)
687 }
Damien Neil993c04d2018-09-14 15:41:11 -0700688 }
Damien Neil658051b2018-09-10 12:26:21 -0700689
690 // Field name conflict resolution.
691 //
692 // We assume well-known method names that may be attached to a generated
693 // message type, as well as a 'Get*' method for each field. For each
694 // field in turn, we add _s to its name until there are no conflicts.
695 //
696 // Any change to the following set of method names is a potential
697 // incompatible API change because it may change generated field names.
698 //
699 // TODO: If we ever support a 'go_name' option to set the Go name of a
700 // field, we should consider dropping this entirely. The conflict
701 // resolution algorithm is subtle and surprising (changing the order
702 // in which fields appear in the .proto source file can change the
703 // names of fields in generated code), and does not adapt well to
704 // adding new per-field methods such as setters.
705 usedNames := map[string]bool{
706 "Reset": true,
707 "String": true,
708 "ProtoMessage": true,
709 "Marshal": true,
710 "Unmarshal": true,
711 "ExtensionRangeArray": true,
712 "ExtensionMap": true,
713 "Descriptor": true,
714 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800715 makeNameUnique := func(name string, hasGetter bool) string {
716 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700717 name += "_"
718 }
719 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800720 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700721 return name
722 }
723 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800724 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700725 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
726 if field.Oneof != nil && field.Oneof.Fields[0] == field {
727 // Make the name for a oneof unique as well. For historical reasons,
728 // this assumes that a getter method is not generated for oneofs.
729 // This is incorrect, but fixing it breaks existing code.
730 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
731 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
732 }
733 }
734
735 // Oneof field name conflict resolution.
736 //
737 // This conflict resolution is incomplete as it does not consider collisions
738 // with other oneof field types, but fixing it breaks existing code.
739 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700740 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700741 Loop:
742 for {
743 for _, nestedMessage := range message.Messages {
744 if nestedMessage.GoIdent == field.GoIdent {
745 field.GoIdent.GoName += "_"
746 continue Loop
747 }
748 }
749 for _, nestedEnum := range message.Enums {
750 if nestedEnum.GoIdent == field.GoIdent {
751 field.GoIdent.GoName += "_"
752 continue Loop
753 }
754 }
755 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700756 }
757 }
Damien Neil658051b2018-09-10 12:26:21 -0700758 }
759
Damien Neil1fa78d82018-09-13 13:12:36 -0700760 return message
Damien Neil658051b2018-09-10 12:26:21 -0700761}
762
Joe Tsai7762ec22019-08-20 20:10:23 -0700763func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700764 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700765 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700766 return err
767 }
768 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700769 for _, message := range message.Messages {
770 if err := message.resolveDependencies(gen); err != nil {
771 return err
772 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700773 }
Damien Neil993c04d2018-09-14 15:41:11 -0700774 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700775 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700776 return err
777 }
778 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700779 return nil
780}
781
Damien Neil658051b2018-09-10 12:26:21 -0700782// A Field describes a message field.
783type Field struct {
784 Desc protoreflect.FieldDescriptor
785
Damien Neil1fa78d82018-09-13 13:12:36 -0700786 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700787 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700788 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700789 GoName string // e.g., "FieldName"
790
791 // GoIdent is the base name of a top-level declaration for this field.
792 // For code generated by protoc-gen-go, this means a wrapper type named
793 // '{{GoIdent}}' for members fields of a oneof, and a variable named
794 // 'E_{{GoIdent}}' for extension fields.
795 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700796
Joe Tsai7762ec22019-08-20 20:10:23 -0700797 Parent *Message // message in which this field is declared; nil if top-level extension
798 Oneof *Oneof // containing oneof; nil if not part of a oneof
799 Extendee *Message // extended message for extension fields; nil otherwise
800
801 Enum *Enum // type for enum fields; nil otherwise
802 Message *Message // type for message or group fields; nil otherwise
803
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700804 Location Location // location of this field
805 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700806}
807
Damien Neil1fa78d82018-09-13 13:12:36 -0700808func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700809 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700810 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700811 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700812 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700813 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700814 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700815 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700816 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700817 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700818 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700819 var parentPrefix string
820 if message != nil {
821 parentPrefix = message.GoIdent.GoName + "_"
822 }
Damien Neil658051b2018-09-10 12:26:21 -0700823 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700824 Desc: desc,
825 GoName: camelCased,
826 GoIdent: GoIdent{
827 GoImportPath: f.GoImportPath,
828 GoName: parentPrefix + camelCased,
829 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700830 Parent: message,
831 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700832 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700833 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700834 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700835}
836
Joe Tsai7762ec22019-08-20 20:10:23 -0700837func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700838 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700839 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700840 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700841 name := field.Desc.Enum().FullName()
842 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700843 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700844 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700845 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700846 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700847 case protoreflect.MessageKind, protoreflect.GroupKind:
848 name := desc.Message().FullName()
849 message, ok := gen.messagesByName[name]
850 if !ok {
851 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
852 }
853 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700854 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700855 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700856 name := desc.ContainingMessage().FullName()
857 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700858 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700859 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700860 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700861 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700862 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700863 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700864}
865
Joe Tsai7762ec22019-08-20 20:10:23 -0700866// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700867type Oneof struct {
868 Desc protoreflect.OneofDescriptor
869
Joe Tsaief6e5242019-08-21 00:55:36 -0700870 // GoName is the base name of this oneof's Go field and methods.
871 // For code generated by protoc-gen-go, this means a field named
872 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
873 GoName string // e.g., "OneofName"
874
875 // GoIdent is the base name of a top-level declaration for this oneof.
876 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700877
878 Parent *Message // message in which this oneof is declared
879
Joe Tsaid24bc722019-04-15 23:39:09 -0700880 Fields []*Field // fields that are part of this oneof
881
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700882 Location Location // location of this oneof
883 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700884}
885
886func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700887 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Joe Tsai2e7817f2019-08-23 12:18:57 -0700888 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700889 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700890 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700891 Desc: desc,
892 Parent: message,
893 GoName: camelCased,
894 GoIdent: GoIdent{
895 GoImportPath: f.GoImportPath,
896 GoName: parentPrefix + camelCased,
897 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700898 Location: loc,
899 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700900 }
901}
902
Joe Tsai7762ec22019-08-20 20:10:23 -0700903// Extension is an alias of Field for documentation.
904type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700905
Damien Neil2dc67182018-09-21 15:03:34 -0700906// A Service describes a service.
907type Service struct {
908 Desc protoreflect.ServiceDescriptor
909
Joe Tsai7762ec22019-08-20 20:10:23 -0700910 GoName string
911
912 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700913
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700914 Location Location // location of this service
915 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700916}
917
918func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700919 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700920 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700921 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700922 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700923 Location: loc,
924 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700925 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700926 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
927 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700928 }
929 return service
930}
931
932// A Method describes a method in a service.
933type Method struct {
934 Desc protoreflect.MethodDescriptor
935
Joe Tsaid24bc722019-04-15 23:39:09 -0700936 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700937
938 Parent *Service // service in which this method is declared
939
Joe Tsaid24bc722019-04-15 23:39:09 -0700940 Input *Message
941 Output *Message
942
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700943 Location Location // location of this method
944 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700945}
946
947func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700948 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700949 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700950 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700951 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700952 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700953 Location: loc,
954 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700955 }
956 return method
957}
958
Joe Tsai7762ec22019-08-20 20:10:23 -0700959func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700960 desc := method.Desc
961
Joe Tsaid24bc722019-04-15 23:39:09 -0700962 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700963 in, ok := gen.messagesByName[inName]
964 if !ok {
965 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
966 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700967 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700968
Joe Tsaid24bc722019-04-15 23:39:09 -0700969 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700970 out, ok := gen.messagesByName[outName]
971 if !ok {
972 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
973 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700974 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700975
976 return nil
977}
978
Damien Neil7bf3ce22018-12-21 15:54:06 -0800979// A GeneratedFile is a generated file.
980type GeneratedFile struct {
981 gen *Plugin
982 skip bool
983 filename string
984 goImportPath GoImportPath
985 buf bytes.Buffer
986 packageNames map[GoImportPath]GoPackageName
987 usedPackageNames map[GoPackageName]bool
988 manualImports map[GoImportPath]bool
989 annotations map[string][]Location
990}
991
992// NewGeneratedFile creates a new generated file with the given filename
993// and import path.
994func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
995 g := &GeneratedFile{
996 gen: gen,
997 filename: filename,
998 goImportPath: goImportPath,
999 packageNames: make(map[GoImportPath]GoPackageName),
1000 usedPackageNames: make(map[GoPackageName]bool),
1001 manualImports: make(map[GoImportPath]bool),
1002 annotations: make(map[string][]Location),
1003 }
Joe Tsai124c8122019-01-14 11:48:43 -08001004
1005 // All predeclared identifiers in Go are already used.
1006 for _, s := range types.Universe.Names() {
1007 g.usedPackageNames[GoPackageName(s)] = true
1008 }
1009
Damien Neil7bf3ce22018-12-21 15:54:06 -08001010 gen.genFiles = append(gen.genFiles, g)
1011 return g
1012}
1013
Damien Neil220c2022018-08-15 11:24:18 -07001014// P prints a line to the generated output. It converts each parameter to a
1015// string following the same rules as fmt.Print. It never inserts spaces
1016// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -07001017func (g *GeneratedFile) P(v ...interface{}) {
1018 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -07001019 switch x := x.(type) {
1020 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -07001021 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -07001022 default:
1023 fmt.Fprint(&g.buf, x)
1024 }
Damien Neil220c2022018-08-15 11:24:18 -07001025 }
1026 fmt.Fprintln(&g.buf)
1027}
1028
Damien Neil46abb572018-09-07 12:45:37 -07001029// QualifiedGoIdent returns the string to use for a Go identifier.
1030//
1031// If the identifier is from a different Go package than the generated file,
1032// the returned name will be qualified (package.name) and an import statement
1033// for the identifier's package will be included in the file.
1034func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
1035 if ident.GoImportPath == g.goImportPath {
1036 return ident.GoName
1037 }
1038 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
1039 return string(packageName) + "." + ident.GoName
1040 }
1041 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -08001042 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -07001043 packageName = orig + GoPackageName(strconv.Itoa(i))
1044 }
1045 g.packageNames[ident.GoImportPath] = packageName
1046 g.usedPackageNames[packageName] = true
1047 return string(packageName) + "." + ident.GoName
1048}
1049
Damien Neil2e0c3da2018-09-19 12:51:36 -07001050// Import ensures a package is imported by the generated file.
1051//
1052// Packages referenced by QualifiedGoIdent are automatically imported.
1053// Explicitly importing a package with Import is generally only necessary
1054// when the import will be blank (import _ "package").
1055func (g *GeneratedFile) Import(importPath GoImportPath) {
1056 g.manualImports[importPath] = true
1057}
1058
Damien Neil220c2022018-08-15 11:24:18 -07001059// Write implements io.Writer.
1060func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1061 return g.buf.Write(p)
1062}
1063
Damien Neil7bf3ce22018-12-21 15:54:06 -08001064// Skip removes the generated file from the plugin output.
1065func (g *GeneratedFile) Skip() {
1066 g.skip = true
1067}
1068
Damien Neil162c1272018-10-04 12:42:37 -07001069// Annotate associates a symbol in a generated Go file with a location in a
1070// source .proto file.
1071//
1072// The symbol may refer to a type, constant, variable, function, method, or
1073// struct field. The "T.sel" syntax is used to identify the method or field
1074// 'sel' on type 'T'.
1075func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1076 g.annotations[symbol] = append(g.annotations[symbol], loc)
1077}
1078
Damien Neil7bf3ce22018-12-21 15:54:06 -08001079// Content returns the contents of the generated file.
1080func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001081 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001082 return g.buf.Bytes(), nil
1083 }
1084
1085 // Reformat generated code.
1086 original := g.buf.Bytes()
1087 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001088 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001089 if err != nil {
1090 // Print out the bad code with line numbers.
1091 // This should never happen in practice, but it can while changing generated code
1092 // so consider this a debugging aid.
1093 var src bytes.Buffer
1094 s := bufio.NewScanner(bytes.NewReader(original))
1095 for line := 1; s.Scan(); line++ {
1096 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1097 }
Damien Neild9016772018-08-23 14:39:30 -07001098 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001099 }
Damien Neild9016772018-08-23 14:39:30 -07001100
Joe Tsaibeda4042019-03-10 16:40:48 -07001101 // Collect a sorted list of all imports.
1102 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001103 rewriteImport := func(importPath string) string {
1104 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1105 return string(f(GoImportPath(importPath)))
1106 }
1107 return importPath
1108 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001109 for importPath := range g.packageNames {
1110 pkgName := string(g.packageNames[GoImportPath(importPath)])
1111 pkgPath := rewriteImport(string(importPath))
1112 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001113 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001114 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001115 if _, ok := g.packageNames[importPath]; !ok {
1116 pkgPath := rewriteImport(string(importPath))
1117 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001118 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001119 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001120 sort.Slice(importPaths, func(i, j int) bool {
1121 return importPaths[i][1] < importPaths[j][1]
1122 })
1123
1124 // Modify the AST to include a new import block.
1125 if len(importPaths) > 0 {
1126 // Insert block after package statement or
1127 // possible comment attached to the end of the package statement.
1128 pos := file.Package
1129 tokFile := fset.File(file.Package)
1130 pkgLine := tokFile.Line(file.Package)
1131 for _, c := range file.Comments {
1132 if tokFile.Line(c.Pos()) > pkgLine {
1133 break
1134 }
1135 pos = c.End()
1136 }
1137
1138 // Construct the import block.
1139 impDecl := &ast.GenDecl{
1140 Tok: token.IMPORT,
1141 TokPos: pos,
1142 Lparen: pos,
1143 Rparen: pos,
1144 }
1145 for _, importPath := range importPaths {
1146 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1147 Name: &ast.Ident{
1148 Name: importPath[0],
1149 NamePos: pos,
1150 },
1151 Path: &ast.BasicLit{
1152 Kind: token.STRING,
1153 Value: strconv.Quote(importPath[1]),
1154 ValuePos: pos,
1155 },
1156 EndPos: pos,
1157 })
1158 }
1159 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1160 }
Damien Neild9016772018-08-23 14:39:30 -07001161
Damien Neilc7d07d92018-08-22 13:46:02 -07001162 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001163 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001164 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001165 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001166 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001167}
Damien Neilc7d07d92018-08-22 13:46:02 -07001168
Damien Neil162c1272018-10-04 12:42:37 -07001169// metaFile returns the contents of the file's metadata file, which is a
1170// text formatted string of the google.protobuf.GeneratedCodeInfo.
1171func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1172 fset := token.NewFileSet()
1173 astFile, err := parser.ParseFile(fset, "", content, 0)
1174 if err != nil {
1175 return "", err
1176 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001177 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001178
1179 seenAnnotations := make(map[string]bool)
1180 annotate := func(s string, ident *ast.Ident) {
1181 seenAnnotations[s] = true
1182 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001183 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001184 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001185 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001186 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1187 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001188 })
1189 }
1190 }
1191 for _, decl := range astFile.Decls {
1192 switch decl := decl.(type) {
1193 case *ast.GenDecl:
1194 for _, spec := range decl.Specs {
1195 switch spec := spec.(type) {
1196 case *ast.TypeSpec:
1197 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001198 switch st := spec.Type.(type) {
1199 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001200 for _, field := range st.Fields.List {
1201 for _, name := range field.Names {
1202 annotate(spec.Name.Name+"."+name.Name, name)
1203 }
1204 }
Damien Neilae2a5612018-12-12 08:54:57 -08001205 case *ast.InterfaceType:
1206 for _, field := range st.Methods.List {
1207 for _, name := range field.Names {
1208 annotate(spec.Name.Name+"."+name.Name, name)
1209 }
1210 }
Damien Neil162c1272018-10-04 12:42:37 -07001211 }
1212 case *ast.ValueSpec:
1213 for _, name := range spec.Names {
1214 annotate(name.Name, name)
1215 }
1216 }
1217 }
1218 case *ast.FuncDecl:
1219 if decl.Recv == nil {
1220 annotate(decl.Name.Name, decl.Name)
1221 } else {
1222 recv := decl.Recv.List[0].Type
1223 if s, ok := recv.(*ast.StarExpr); ok {
1224 recv = s.X
1225 }
1226 if id, ok := recv.(*ast.Ident); ok {
1227 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1228 }
1229 }
1230 }
1231 }
1232 for a := range g.annotations {
1233 if !seenAnnotations[a] {
1234 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1235 }
1236 }
1237
Damien Neil5c5b5312019-05-14 12:44:37 -07001238 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001239 if err != nil {
1240 return "", err
1241 }
1242 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001243}
Damien Neil082ce922018-09-06 10:23:53 -07001244
Joe Tsai2e7817f2019-08-23 12:18:57 -07001245// A GoIdent is a Go identifier, consisting of a name and import path.
1246// The name is a single identifier and may not be a dot-qualified selector.
1247type GoIdent struct {
1248 GoName string
1249 GoImportPath GoImportPath
1250}
1251
1252func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1253
1254// newGoIdent returns the Go identifier for a descriptor.
1255func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1256 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1257 return GoIdent{
1258 GoName: strs.GoCamelCase(name),
1259 GoImportPath: f.GoImportPath,
1260 }
1261}
1262
1263// A GoImportPath is the import path of a Go package.
1264// For example: "google.golang.org/protobuf/compiler/protogen"
1265type GoImportPath string
1266
1267func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1268
1269// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1270func (p GoImportPath) Ident(s string) GoIdent {
1271 return GoIdent{GoName: s, GoImportPath: p}
1272}
1273
1274// A GoPackageName is the name of a Go package. e.g., "protobuf".
1275type GoPackageName string
1276
1277// cleanPackageName converts a string to a valid Go package name.
1278func cleanPackageName(name string) GoPackageName {
1279 return GoPackageName(strs.GoSanitized(name))
1280}
1281
1282// baseName returns the last path element of the name, with the last dotted suffix removed.
1283func baseName(name string) string {
1284 // First, find the last element
1285 if i := strings.LastIndex(name, "/"); i >= 0 {
1286 name = name[i+1:]
1287 }
1288 // Now drop the suffix
1289 if i := strings.LastIndex(name, "."); i >= 0 {
1290 name = name[:i]
1291 }
1292 return name
1293}
1294
Damien Neil082ce922018-09-06 10:23:53 -07001295type pathType int
1296
1297const (
Damien Neilaadba562020-02-15 14:28:51 -08001298 pathTypeLegacy pathType = iota
1299 pathTypeImport
Damien Neil082ce922018-09-06 10:23:53 -07001300 pathTypeSourceRelative
1301)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001302
Damien Neil162c1272018-10-04 12:42:37 -07001303// A Location is a location in a .proto source file.
1304//
1305// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1306// for details.
1307type Location struct {
1308 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001309 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001310}
1311
1312// appendPath add elements to a Location's path, returning a new Location.
1313func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001314 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001315 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001316 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001317 return Location{
1318 SourceFile: loc.SourceFile,
1319 Path: n,
1320 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001321}
Damien Neilba1159f2018-10-17 12:53:18 -07001322
1323// A pathKey is a representation of a location path suitable for use as a map key.
1324type pathKey struct {
1325 s string
1326}
1327
1328// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001329func newPathKey(idxPath []int32) pathKey {
1330 buf := make([]byte, 4*len(idxPath))
1331 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001332 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1333 }
1334 return pathKey{string(buf)}
1335}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001336
1337// CommentSet is a set of leading and trailing comments associated
1338// with a .proto descriptor declaration.
1339type CommentSet struct {
1340 LeadingDetached []Comments
1341 Leading Comments
1342 Trailing Comments
1343}
1344
1345// Comments is a comments string as provided by protoc.
1346type Comments string
1347
1348// String formats the comments by inserting // to the start of each line,
1349// ensuring that there is a trailing newline.
1350// An empty comment is formatted as an empty string.
1351func (c Comments) String() string {
1352 if c == "" {
1353 return ""
1354 }
1355 var b []byte
1356 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1357 b = append(b, "//"...)
1358 b = append(b, line...)
1359 b = append(b, "\n"...)
1360 }
1361 return string(b)
1362}
Damien Neile358d432020-03-06 13:58:41 -08001363
1364var warnings = true
1365
1366func warn(format string, a ...interface{}) {
1367 if warnings {
1368 log.Printf("WARNING: "+format, a...)
1369 }
1370}