blob: ee8d0f740fca0e3cdf083f503c2ac145b1906b70 [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' {
194 importPaths[param[1:]] = GoImportPath(value)
Joe Tsai3e802492019-09-07 13:06:27 -0700195 mfiles[param[1:]] = true
Damien Neil3cf6e622018-09-11 13:53:14 -0700196 continue
Damien Neil220c2022018-08-15 11:24:18 -0700197 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700198 if opts.ParamFunc != nil {
199 if err := opts.ParamFunc(param, value); err != nil {
200 return nil, err
201 }
202 }
Damien Neil082ce922018-09-06 10:23:53 -0700203 }
204 }
205
206 // Figure out the import path and package name for each file.
207 //
208 // The rules here are complicated and have grown organically over time.
209 // Interactions between different ways of specifying package information
210 // may be surprising.
211 //
212 // The recommended approach is to include a go_package option in every
213 // .proto source file specifying the full import path of the Go package
214 // associated with this file.
215 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700216 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700217 //
218 // Build systems which want to exert full control over import paths may
219 // specify M<filename>=<import_path> flags.
220 //
221 // Other approaches are not recommend.
222 generatedFileNames := make(map[string]bool)
223 for _, name := range gen.Request.FileToGenerate {
224 generatedFileNames[name] = true
225 }
226 // We need to determine the import paths before the package names,
227 // because the Go package name for a file is sometimes derived from
228 // different file in the same package.
229 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
230 for _, fdesc := range gen.Request.ProtoFile {
231 filename := fdesc.GetName()
232 packageName, importPath := goPackageOption(fdesc)
233 switch {
234 case importPaths[filename] != "":
235 // Command line: M=foo.proto=quux/bar
236 //
237 // Explicit mapping of source file to import path.
238 case generatedFileNames[filename] && packageImportPath != "":
239 // Command line: import_path=quux/bar
240 //
241 // The import_path flag sets the import path for every file that
242 // we generate code for.
243 importPaths[filename] = packageImportPath
244 case importPath != "":
245 // Source file: option go_package = "quux/bar";
246 //
247 // The go_package option sets the import path. Most users should use this.
248 importPaths[filename] = importPath
249 default:
250 // Source filename.
251 //
252 // Last resort when nothing else is available.
253 importPaths[filename] = GoImportPath(path.Dir(filename))
254 }
255 if packageName != "" {
256 packageNameForImportPath[importPaths[filename]] = packageName
257 }
258 }
259 for _, fdesc := range gen.Request.ProtoFile {
260 filename := fdesc.GetName()
Joe Tsai3e802492019-09-07 13:06:27 -0700261 packageName, importPath := goPackageOption(fdesc)
Damien Neil082ce922018-09-06 10:23:53 -0700262 defaultPackageName := packageNameForImportPath[importPaths[filename]]
263 switch {
264 case packageName != "":
Joe Tsai3e802492019-09-07 13:06:27 -0700265 // TODO: For the "M" command-line argument, this means that the
266 // package name can be derived from the go_package option.
267 // Go package information should either consistently come from the
268 // command-line or the .proto source file, but not both.
269 // See how to make this consistent.
270
Damien Neil082ce922018-09-06 10:23:53 -0700271 // Source file: option go_package = "quux/bar";
272 packageNames[filename] = packageName
273 case defaultPackageName != "":
274 // A go_package option in another file in the same package.
275 //
276 // This is a poor choice in general, since every source file should
277 // contain a go_package option. Supported mainly for historical
278 // compatibility.
279 packageNames[filename] = defaultPackageName
280 case generatedFileNames[filename] && packageImportPath != "":
281 // Command line: import_path=quux/bar
282 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
283 case fdesc.GetPackage() != "":
284 // Source file: package quux.bar;
285 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
286 default:
287 // Source filename.
288 packageNames[filename] = cleanPackageName(baseName(filename))
289 }
Joe Tsai3e802492019-09-07 13:06:27 -0700290
291 goPkgOpt := string(importPaths[filename])
292 if path.Base(string(goPkgOpt)) != string(packageNames[filename]) {
293 goPkgOpt += ";" + string(packageNames[filename])
294 }
295 switch {
296 case packageImportPath != "":
297 // Command line: import_path=quux/bar
Damien Neile358d432020-03-06 13:58:41 -0800298 warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700299 "\toption go_package = %q;\n"+
300 "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800301 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700302 "\n", fdesc.GetName(), goPkgOpt)
303 case mfiles[filename]:
304 // Command line: M=foo.proto=quux/bar
305 case packageName != "" && importPath == "":
306 // Source file: option go_package = "quux";
Damien Neile358d432020-03-06 13:58:41 -0800307 warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700308 "\toption go_package = %q;\n"+
309 "A future release of protoc-gen-go will require the import path be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800310 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700311 "\n", fdesc.GetName(), goPkgOpt)
312 case packageName == "" && importPath == "":
313 // No Go package information provided.
Damien Neile358d432020-03-06 13:58:41 -0800314 warn("Missing 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700315 "\toption go_package = %q;\n"+
316 "A future release of protoc-gen-go will require this be specified.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800317 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700318 "\n", fdesc.GetName(), goPkgOpt)
319 }
Damien Neil082ce922018-09-06 10:23:53 -0700320 }
321
322 // Consistency check: Every file with the same Go import path should have
323 // the same Go package name.
324 packageFiles := make(map[GoImportPath][]string)
325 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700326 if _, ok := packageNames[filename]; !ok {
327 // Skip files mentioned in a M<file>=<import_path> parameter
328 // but which do not appear in the CodeGeneratorRequest.
329 continue
330 }
Damien Neil082ce922018-09-06 10:23:53 -0700331 packageFiles[importPath] = append(packageFiles[importPath], filename)
332 }
333 for importPath, filenames := range packageFiles {
334 for i := 1; i < len(filenames); i++ {
335 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
336 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
337 importPath, a, filenames[0], b, filenames[i])
338 }
Damien Neil220c2022018-08-15 11:24:18 -0700339 }
340 }
341
342 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700343 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700344 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700345 return nil, fmt.Errorf("duplicate file name: %q", filename)
346 }
347 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700348 if err != nil {
349 return nil, err
350 }
Damien Neil220c2022018-08-15 11:24:18 -0700351 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700352 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700353 }
Damien Neil082ce922018-09-06 10:23:53 -0700354 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700355 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700356 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700357 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700358 }
359 f.Generate = true
360 }
361 return gen, nil
362}
363
364// Error records an error in code generation. The generator will report the
365// error back to protoc and will not produce output.
366func (gen *Plugin) Error(err error) {
367 if gen.err == nil {
368 gen.err = err
369 }
370}
371
372// Response returns the generator output.
373func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
374 resp := &pluginpb.CodeGeneratorResponse{}
375 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700376 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700377 return resp
378 }
Damien Neil162c1272018-10-04 12:42:37 -0700379 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800380 if g.skip {
381 continue
382 }
383 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700384 if err != nil {
385 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700386 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700387 }
388 }
Damien Neil220c2022018-08-15 11:24:18 -0700389 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700390 Name: proto.String(g.filename),
391 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700392 })
Damien Neil162c1272018-10-04 12:42:37 -0700393 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
394 meta, err := g.metaFile(content)
395 if err != nil {
396 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700397 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700398 }
399 }
400 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neila8a2cea2019-07-10 16:17:16 -0700401 Name: proto.String(g.filename + ".meta"),
402 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700403 })
404 }
Damien Neil220c2022018-08-15 11:24:18 -0700405 }
406 return resp
407}
408
Damien Neilc7d07d92018-08-22 13:46:02 -0700409// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700410type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700411 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800412 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700413
Joe Tsaib6405bd2018-11-15 14:44:37 -0800414 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
415 GoPackageName GoPackageName // name of this file's Go package
416 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700417
418 Enums []*Enum // top-level enum declarations
419 Messages []*Message // top-level message declarations
420 Extensions []*Extension // top-level extension declarations
421 Services []*Service // top-level service declarations
422
423 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700424
425 // GeneratedFilenamePrefix is used to construct filenames for generated
426 // files associated with this source file.
427 //
428 // For example, the source file "dir/foo.proto" might have a filename prefix
429 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
430 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700431
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700432 comments map[pathKey]CommentSet
Damien Neil220c2022018-08-15 11:24:18 -0700433}
434
Joe Tsaie1f8d502018-11-26 18:55:29 -0800435func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
436 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700437 if err != nil {
438 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
439 }
Damien Neilc8268852019-10-08 13:28:53 -0700440 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700441 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
442 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700443 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700444 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700445 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700446 GoPackageName: packageName,
447 GoImportPath: importPath,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700448 comments: make(map[pathKey]CommentSet),
Damien Neil220c2022018-08-15 11:24:18 -0700449 }
Damien Neil082ce922018-09-06 10:23:53 -0700450
451 // Determine the prefix for generated Go files.
452 prefix := p.GetName()
453 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
454 prefix = prefix[:len(prefix)-len(ext)]
455 }
456 if gen.pathType == pathTypeImport {
457 // If paths=import (the default) and the file contains a go_package option
458 // with a full import path, the output filename is derived from the Go import
459 // path.
460 //
461 // Pass the paths=source_relative flag to always derive the output filename
462 // from the input filename instead.
463 if _, importPath := goPackageOption(p); importPath != "" {
464 prefix = path.Join(string(importPath), path.Base(prefix))
465 }
466 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800467 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700468 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800469 GoImportPath: f.GoImportPath,
470 }
Damien Neil082ce922018-09-06 10:23:53 -0700471 f.GeneratedFilenamePrefix = prefix
472
Damien Neilba1159f2018-10-17 12:53:18 -0700473 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700474 // Descriptors declarations are guaranteed to have unique comment sets.
475 // Other locations may not be unique, but we don't use them.
476 var leadingDetached []Comments
477 for _, s := range loc.GetLeadingDetachedComments() {
478 leadingDetached = append(leadingDetached, Comments(s))
479 }
480 f.comments[newPathKey(loc.Path)] = CommentSet{
481 LeadingDetached: leadingDetached,
482 Leading: Comments(loc.GetLeadingComments()),
483 Trailing: Comments(loc.GetTrailingComments()),
484 }
Damien Neilba1159f2018-10-17 12:53:18 -0700485 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700486 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
487 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700488 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700489 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
490 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700491 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700492 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
493 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700494 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700495 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
496 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700497 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700498 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700499 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700500 return nil, err
501 }
502 }
503 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700504 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700505 return nil, err
506 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700507 }
Damien Neil2dc67182018-09-21 15:03:34 -0700508 for _, service := range f.Services {
509 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700510 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700511 return nil, err
512 }
513 }
514 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700515 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700516}
517
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900518func (f *File) location(idxPath ...int32) Location {
Damien Neil162c1272018-10-04 12:42:37 -0700519 return Location{
520 SourceFile: f.Desc.Path(),
Koichi Shiraishiea2076d2019-05-24 18:24:29 +0900521 Path: idxPath,
Damien Neil162c1272018-10-04 12:42:37 -0700522 }
523}
524
Damien Neil082ce922018-09-06 10:23:53 -0700525// goPackageOption interprets a file's go_package option.
526// If there is no go_package, it returns ("", "").
527// If there's a simple name, it returns (pkg, "").
528// If the option implies an import path, it returns (pkg, impPath).
Joe Tsaie1f8d502018-11-26 18:55:29 -0800529func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700530 opt := d.GetOptions().GetGoPackage()
531 if opt == "" {
532 return "", ""
533 }
Joe Tsai3e802492019-09-07 13:06:27 -0700534 rawPkg, impPath := goPackageOptionRaw(opt)
535 pkg = cleanPackageName(rawPkg)
536 if string(pkg) != rawPkg && impPath != "" {
Damien Neile358d432020-03-06 13:58:41 -0800537 warn("Malformed 'go_package' option in %q, please specify:\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700538 "\toption go_package = %q;\n"+
539 "A future release of protoc-gen-go will reject this.\n"+
Joe Tsai222a0002020-02-24 11:21:30 -0800540 "See "+goPackageDocURL+" for more information.\n"+
Joe Tsai3e802492019-09-07 13:06:27 -0700541 "\n", d.GetName(), string(impPath)+";"+string(pkg))
542 }
543 return pkg, impPath
544}
545func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) {
Damien Neil082ce922018-09-06 10:23:53 -0700546 // A semicolon-delimited suffix delimits the import path and package name.
547 if i := strings.Index(opt, ";"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700548 return opt[i+1:], GoImportPath(opt[:i])
Damien Neil082ce922018-09-06 10:23:53 -0700549 }
550 // The presence of a slash implies there's an import path.
551 if i := strings.LastIndex(opt, "/"); i >= 0 {
Joe Tsai3e802492019-09-07 13:06:27 -0700552 return opt[i+1:], GoImportPath(opt)
Damien Neil082ce922018-09-06 10:23:53 -0700553 }
Joe Tsai3e802492019-09-07 13:06:27 -0700554 return opt, ""
Damien Neil082ce922018-09-06 10:23:53 -0700555}
556
Joe Tsai7762ec22019-08-20 20:10:23 -0700557// An Enum describes an enum.
558type Enum struct {
559 Desc protoreflect.EnumDescriptor
560
561 GoIdent GoIdent // name of the generated Go type
562
563 Values []*EnumValue // enum value declarations
564
565 Location Location // location of this enum
566 Comments CommentSet // comments associated with this enum
567}
568
569func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
570 var loc Location
571 if parent != nil {
572 loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
573 } else {
574 loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
575 }
576 enum := &Enum{
577 Desc: desc,
578 GoIdent: newGoIdent(f, desc),
579 Location: loc,
580 Comments: f.comments[newPathKey(loc.Path)],
581 }
582 gen.enumsByName[desc.FullName()] = enum
583 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
584 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
585 }
586 return enum
587}
588
589// An EnumValue describes an enum value.
590type EnumValue struct {
591 Desc protoreflect.EnumValueDescriptor
592
593 GoIdent GoIdent // name of the generated Go declaration
594
Joe Tsai4df99fd2019-08-20 22:26:16 -0700595 Parent *Enum // enum in which this value is declared
596
Joe Tsai7762ec22019-08-20 20:10:23 -0700597 Location Location // location of this enum value
598 Comments CommentSet // comments associated with this enum value
599}
600
601func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
602 // A top-level enum value's name is: EnumName_ValueName
603 // An enum value contained in a message is: MessageName_ValueName
604 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700605 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700606 parentIdent := enum.GoIdent
607 if message != nil {
608 parentIdent = message.GoIdent
609 }
610 name := parentIdent.GoName + "_" + string(desc.Name())
611 loc := enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index()))
612 return &EnumValue{
613 Desc: desc,
614 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700615 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700616 Location: loc,
617 Comments: f.comments[newPathKey(loc.Path)],
618 }
619}
620
Damien Neilc7d07d92018-08-22 13:46:02 -0700621// A Message describes a message.
622type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700623 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700624
Joe Tsai7762ec22019-08-20 20:10:23 -0700625 GoIdent GoIdent // name of the generated Go type
626
627 Fields []*Field // message field declarations
628 Oneofs []*Oneof // message oneof declarations
629
Damien Neil993c04d2018-09-14 15:41:11 -0700630 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700631 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700632 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700633
634 Location Location // location of this message
635 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700636}
637
Damien Neil1fa78d82018-09-13 13:12:36 -0700638func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700639 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700640 if parent != nil {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700641 loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700642 } else {
Joe Tsaica46d8c2019-03-20 16:51:09 -0700643 loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700644 }
Damien Neil46abb572018-09-07 12:45:37 -0700645 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700646 Desc: desc,
647 GoIdent: newGoIdent(f, desc),
648 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700649 Comments: f.comments[newPathKey(loc.Path)],
Damien Neilc7d07d92018-08-22 13:46:02 -0700650 }
Damien Neil658051b2018-09-10 12:26:21 -0700651 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700652 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
653 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700654 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700655 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
656 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700657 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700658 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
659 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700660 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700661 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
662 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700663 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700664 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
665 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
666 }
667
668 // Resolve local references between fields and oneofs.
669 for _, field := range message.Fields {
670 if od := field.Desc.ContainingOneof(); od != nil {
671 oneof := message.Oneofs[od.Index()]
672 field.Oneof = oneof
673 oneof.Fields = append(oneof.Fields, field)
674 }
Damien Neil993c04d2018-09-14 15:41:11 -0700675 }
Damien Neil658051b2018-09-10 12:26:21 -0700676
677 // Field name conflict resolution.
678 //
679 // We assume well-known method names that may be attached to a generated
680 // message type, as well as a 'Get*' method for each field. For each
681 // field in turn, we add _s to its name until there are no conflicts.
682 //
683 // Any change to the following set of method names is a potential
684 // incompatible API change because it may change generated field names.
685 //
686 // TODO: If we ever support a 'go_name' option to set the Go name of a
687 // field, we should consider dropping this entirely. The conflict
688 // resolution algorithm is subtle and surprising (changing the order
689 // in which fields appear in the .proto source file can change the
690 // names of fields in generated code), and does not adapt well to
691 // adding new per-field methods such as setters.
692 usedNames := map[string]bool{
693 "Reset": true,
694 "String": true,
695 "ProtoMessage": true,
696 "Marshal": true,
697 "Unmarshal": true,
698 "ExtensionRangeArray": true,
699 "ExtensionMap": true,
700 "Descriptor": true,
701 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800702 makeNameUnique := func(name string, hasGetter bool) string {
703 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700704 name += "_"
705 }
706 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800707 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700708 return name
709 }
710 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800711 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700712 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
713 if field.Oneof != nil && field.Oneof.Fields[0] == field {
714 // Make the name for a oneof unique as well. For historical reasons,
715 // this assumes that a getter method is not generated for oneofs.
716 // This is incorrect, but fixing it breaks existing code.
717 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
718 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
719 }
720 }
721
722 // Oneof field name conflict resolution.
723 //
724 // This conflict resolution is incomplete as it does not consider collisions
725 // with other oneof field types, but fixing it breaks existing code.
726 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700727 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700728 Loop:
729 for {
730 for _, nestedMessage := range message.Messages {
731 if nestedMessage.GoIdent == field.GoIdent {
732 field.GoIdent.GoName += "_"
733 continue Loop
734 }
735 }
736 for _, nestedEnum := range message.Enums {
737 if nestedEnum.GoIdent == field.GoIdent {
738 field.GoIdent.GoName += "_"
739 continue Loop
740 }
741 }
742 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700743 }
744 }
Damien Neil658051b2018-09-10 12:26:21 -0700745 }
746
Damien Neil1fa78d82018-09-13 13:12:36 -0700747 return message
Damien Neil658051b2018-09-10 12:26:21 -0700748}
749
Joe Tsai7762ec22019-08-20 20:10:23 -0700750func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700751 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700752 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700753 return err
754 }
755 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700756 for _, message := range message.Messages {
757 if err := message.resolveDependencies(gen); err != nil {
758 return err
759 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700760 }
Damien Neil993c04d2018-09-14 15:41:11 -0700761 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700762 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700763 return err
764 }
765 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700766 return nil
767}
768
Damien Neil658051b2018-09-10 12:26:21 -0700769// A Field describes a message field.
770type Field struct {
771 Desc protoreflect.FieldDescriptor
772
Damien Neil1fa78d82018-09-13 13:12:36 -0700773 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700774 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700775 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700776 GoName string // e.g., "FieldName"
777
778 // GoIdent is the base name of a top-level declaration for this field.
779 // For code generated by protoc-gen-go, this means a wrapper type named
780 // '{{GoIdent}}' for members fields of a oneof, and a variable named
781 // 'E_{{GoIdent}}' for extension fields.
782 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700783
Joe Tsai7762ec22019-08-20 20:10:23 -0700784 Parent *Message // message in which this field is declared; nil if top-level extension
785 Oneof *Oneof // containing oneof; nil if not part of a oneof
786 Extendee *Message // extended message for extension fields; nil otherwise
787
788 Enum *Enum // type for enum fields; nil otherwise
789 Message *Message // type for message or group fields; nil otherwise
790
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700791 Location Location // location of this field
792 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700793}
794
Damien Neil1fa78d82018-09-13 13:12:36 -0700795func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700796 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700797 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700798 case desc.IsExtension() && message == nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700799 loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
Joe Tsaiac31a352019-05-13 14:32:56 -0700800 case desc.IsExtension() && message != nil:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700801 loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700802 default:
Joe Tsaica46d8c2019-03-20 16:51:09 -0700803 loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700804 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700805 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700806 var parentPrefix string
807 if message != nil {
808 parentPrefix = message.GoIdent.GoName + "_"
809 }
Damien Neil658051b2018-09-10 12:26:21 -0700810 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700811 Desc: desc,
812 GoName: camelCased,
813 GoIdent: GoIdent{
814 GoImportPath: f.GoImportPath,
815 GoName: parentPrefix + camelCased,
816 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700817 Parent: message,
818 Location: loc,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700819 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil658051b2018-09-10 12:26:21 -0700820 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700821 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700822}
823
Joe Tsai7762ec22019-08-20 20:10:23 -0700824func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700825 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700826 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700827 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700828 name := field.Desc.Enum().FullName()
829 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700830 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700831 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700832 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700833 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700834 case protoreflect.MessageKind, protoreflect.GroupKind:
835 name := desc.Message().FullName()
836 message, ok := gen.messagesByName[name]
837 if !ok {
838 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
839 }
840 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700841 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700842 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700843 name := desc.ContainingMessage().FullName()
844 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700845 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700846 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700847 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700848 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700849 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700850 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700851}
852
Joe Tsai7762ec22019-08-20 20:10:23 -0700853// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700854type Oneof struct {
855 Desc protoreflect.OneofDescriptor
856
Joe Tsaief6e5242019-08-21 00:55:36 -0700857 // GoName is the base name of this oneof's Go field and methods.
858 // For code generated by protoc-gen-go, this means a field named
859 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
860 GoName string // e.g., "OneofName"
861
862 // GoIdent is the base name of a top-level declaration for this oneof.
863 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700864
865 Parent *Message // message in which this oneof is declared
866
Joe Tsaid24bc722019-04-15 23:39:09 -0700867 Fields []*Field // fields that are part of this oneof
868
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700869 Location Location // location of this oneof
870 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700871}
872
873func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700874 loc := message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index()))
Joe Tsai2e7817f2019-08-23 12:18:57 -0700875 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700876 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700877 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700878 Desc: desc,
879 Parent: message,
880 GoName: camelCased,
881 GoIdent: GoIdent{
882 GoImportPath: f.GoImportPath,
883 GoName: parentPrefix + camelCased,
884 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700885 Location: loc,
886 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil1fa78d82018-09-13 13:12:36 -0700887 }
888}
889
Joe Tsai7762ec22019-08-20 20:10:23 -0700890// Extension is an alias of Field for documentation.
891type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700892
Damien Neil2dc67182018-09-21 15:03:34 -0700893// A Service describes a service.
894type Service struct {
895 Desc protoreflect.ServiceDescriptor
896
Joe Tsai7762ec22019-08-20 20:10:23 -0700897 GoName string
898
899 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700900
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700901 Location Location // location of this service
902 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700903}
904
905func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700906 loc := f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700907 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700908 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700909 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700910 Location: loc,
911 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700912 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700913 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
914 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700915 }
916 return service
917}
918
919// A Method describes a method in a service.
920type Method struct {
921 Desc protoreflect.MethodDescriptor
922
Joe Tsaid24bc722019-04-15 23:39:09 -0700923 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700924
925 Parent *Service // service in which this method is declared
926
Joe Tsaid24bc722019-04-15 23:39:09 -0700927 Input *Message
928 Output *Message
929
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700930 Location Location // location of this method
931 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700932}
933
934func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700935 loc := service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index()))
Damien Neil2dc67182018-09-21 15:03:34 -0700936 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700937 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700938 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700939 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700940 Location: loc,
941 Comments: f.comments[newPathKey(loc.Path)],
Damien Neil2dc67182018-09-21 15:03:34 -0700942 }
943 return method
944}
945
Joe Tsai7762ec22019-08-20 20:10:23 -0700946func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700947 desc := method.Desc
948
Joe Tsaid24bc722019-04-15 23:39:09 -0700949 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700950 in, ok := gen.messagesByName[inName]
951 if !ok {
952 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
953 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700954 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700955
Joe Tsaid24bc722019-04-15 23:39:09 -0700956 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700957 out, ok := gen.messagesByName[outName]
958 if !ok {
959 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
960 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700961 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700962
963 return nil
964}
965
Damien Neil7bf3ce22018-12-21 15:54:06 -0800966// A GeneratedFile is a generated file.
967type GeneratedFile struct {
968 gen *Plugin
969 skip bool
970 filename string
971 goImportPath GoImportPath
972 buf bytes.Buffer
973 packageNames map[GoImportPath]GoPackageName
974 usedPackageNames map[GoPackageName]bool
975 manualImports map[GoImportPath]bool
976 annotations map[string][]Location
977}
978
979// NewGeneratedFile creates a new generated file with the given filename
980// and import path.
981func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
982 g := &GeneratedFile{
983 gen: gen,
984 filename: filename,
985 goImportPath: goImportPath,
986 packageNames: make(map[GoImportPath]GoPackageName),
987 usedPackageNames: make(map[GoPackageName]bool),
988 manualImports: make(map[GoImportPath]bool),
989 annotations: make(map[string][]Location),
990 }
Joe Tsai124c8122019-01-14 11:48:43 -0800991
992 // All predeclared identifiers in Go are already used.
993 for _, s := range types.Universe.Names() {
994 g.usedPackageNames[GoPackageName(s)] = true
995 }
996
Damien Neil7bf3ce22018-12-21 15:54:06 -0800997 gen.genFiles = append(gen.genFiles, g)
998 return g
999}
1000
Damien Neil220c2022018-08-15 11:24:18 -07001001// P prints a line to the generated output. It converts each parameter to a
1002// string following the same rules as fmt.Print. It never inserts spaces
1003// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -07001004func (g *GeneratedFile) P(v ...interface{}) {
1005 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -07001006 switch x := x.(type) {
1007 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -07001008 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -07001009 default:
1010 fmt.Fprint(&g.buf, x)
1011 }
Damien Neil220c2022018-08-15 11:24:18 -07001012 }
1013 fmt.Fprintln(&g.buf)
1014}
1015
Damien Neil46abb572018-09-07 12:45:37 -07001016// QualifiedGoIdent returns the string to use for a Go identifier.
1017//
1018// If the identifier is from a different Go package than the generated file,
1019// the returned name will be qualified (package.name) and an import statement
1020// for the identifier's package will be included in the file.
1021func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
1022 if ident.GoImportPath == g.goImportPath {
1023 return ident.GoName
1024 }
1025 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
1026 return string(packageName) + "." + ident.GoName
1027 }
1028 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -08001029 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -07001030 packageName = orig + GoPackageName(strconv.Itoa(i))
1031 }
1032 g.packageNames[ident.GoImportPath] = packageName
1033 g.usedPackageNames[packageName] = true
1034 return string(packageName) + "." + ident.GoName
1035}
1036
Damien Neil2e0c3da2018-09-19 12:51:36 -07001037// Import ensures a package is imported by the generated file.
1038//
1039// Packages referenced by QualifiedGoIdent are automatically imported.
1040// Explicitly importing a package with Import is generally only necessary
1041// when the import will be blank (import _ "package").
1042func (g *GeneratedFile) Import(importPath GoImportPath) {
1043 g.manualImports[importPath] = true
1044}
1045
Damien Neil220c2022018-08-15 11:24:18 -07001046// Write implements io.Writer.
1047func (g *GeneratedFile) Write(p []byte) (n int, err error) {
1048 return g.buf.Write(p)
1049}
1050
Damien Neil7bf3ce22018-12-21 15:54:06 -08001051// Skip removes the generated file from the plugin output.
1052func (g *GeneratedFile) Skip() {
1053 g.skip = true
1054}
1055
Damien Neil162c1272018-10-04 12:42:37 -07001056// Annotate associates a symbol in a generated Go file with a location in a
1057// source .proto file.
1058//
1059// The symbol may refer to a type, constant, variable, function, method, or
1060// struct field. The "T.sel" syntax is used to identify the method or field
1061// 'sel' on type 'T'.
1062func (g *GeneratedFile) Annotate(symbol string, loc Location) {
1063 g.annotations[symbol] = append(g.annotations[symbol], loc)
1064}
1065
Damien Neil7bf3ce22018-12-21 15:54:06 -08001066// Content returns the contents of the generated file.
1067func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001068 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001069 return g.buf.Bytes(), nil
1070 }
1071
1072 // Reformat generated code.
1073 original := g.buf.Bytes()
1074 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001075 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001076 if err != nil {
1077 // Print out the bad code with line numbers.
1078 // This should never happen in practice, but it can while changing generated code
1079 // so consider this a debugging aid.
1080 var src bytes.Buffer
1081 s := bufio.NewScanner(bytes.NewReader(original))
1082 for line := 1; s.Scan(); line++ {
1083 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1084 }
Damien Neild9016772018-08-23 14:39:30 -07001085 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001086 }
Damien Neild9016772018-08-23 14:39:30 -07001087
Joe Tsaibeda4042019-03-10 16:40:48 -07001088 // Collect a sorted list of all imports.
1089 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001090 rewriteImport := func(importPath string) string {
1091 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1092 return string(f(GoImportPath(importPath)))
1093 }
1094 return importPath
1095 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001096 for importPath := range g.packageNames {
1097 pkgName := string(g.packageNames[GoImportPath(importPath)])
1098 pkgPath := rewriteImport(string(importPath))
1099 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001100 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001101 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001102 if _, ok := g.packageNames[importPath]; !ok {
1103 pkgPath := rewriteImport(string(importPath))
1104 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001105 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001106 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001107 sort.Slice(importPaths, func(i, j int) bool {
1108 return importPaths[i][1] < importPaths[j][1]
1109 })
1110
1111 // Modify the AST to include a new import block.
1112 if len(importPaths) > 0 {
1113 // Insert block after package statement or
1114 // possible comment attached to the end of the package statement.
1115 pos := file.Package
1116 tokFile := fset.File(file.Package)
1117 pkgLine := tokFile.Line(file.Package)
1118 for _, c := range file.Comments {
1119 if tokFile.Line(c.Pos()) > pkgLine {
1120 break
1121 }
1122 pos = c.End()
1123 }
1124
1125 // Construct the import block.
1126 impDecl := &ast.GenDecl{
1127 Tok: token.IMPORT,
1128 TokPos: pos,
1129 Lparen: pos,
1130 Rparen: pos,
1131 }
1132 for _, importPath := range importPaths {
1133 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1134 Name: &ast.Ident{
1135 Name: importPath[0],
1136 NamePos: pos,
1137 },
1138 Path: &ast.BasicLit{
1139 Kind: token.STRING,
1140 Value: strconv.Quote(importPath[1]),
1141 ValuePos: pos,
1142 },
1143 EndPos: pos,
1144 })
1145 }
1146 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1147 }
Damien Neild9016772018-08-23 14:39:30 -07001148
Damien Neilc7d07d92018-08-22 13:46:02 -07001149 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001150 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001151 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001152 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001153 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001154}
Damien Neilc7d07d92018-08-22 13:46:02 -07001155
Damien Neil162c1272018-10-04 12:42:37 -07001156// metaFile returns the contents of the file's metadata file, which is a
1157// text formatted string of the google.protobuf.GeneratedCodeInfo.
1158func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1159 fset := token.NewFileSet()
1160 astFile, err := parser.ParseFile(fset, "", content, 0)
1161 if err != nil {
1162 return "", err
1163 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001164 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001165
1166 seenAnnotations := make(map[string]bool)
1167 annotate := func(s string, ident *ast.Ident) {
1168 seenAnnotations[s] = true
1169 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001170 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001171 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001172 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001173 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1174 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001175 })
1176 }
1177 }
1178 for _, decl := range astFile.Decls {
1179 switch decl := decl.(type) {
1180 case *ast.GenDecl:
1181 for _, spec := range decl.Specs {
1182 switch spec := spec.(type) {
1183 case *ast.TypeSpec:
1184 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001185 switch st := spec.Type.(type) {
1186 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001187 for _, field := range st.Fields.List {
1188 for _, name := range field.Names {
1189 annotate(spec.Name.Name+"."+name.Name, name)
1190 }
1191 }
Damien Neilae2a5612018-12-12 08:54:57 -08001192 case *ast.InterfaceType:
1193 for _, field := range st.Methods.List {
1194 for _, name := range field.Names {
1195 annotate(spec.Name.Name+"."+name.Name, name)
1196 }
1197 }
Damien Neil162c1272018-10-04 12:42:37 -07001198 }
1199 case *ast.ValueSpec:
1200 for _, name := range spec.Names {
1201 annotate(name.Name, name)
1202 }
1203 }
1204 }
1205 case *ast.FuncDecl:
1206 if decl.Recv == nil {
1207 annotate(decl.Name.Name, decl.Name)
1208 } else {
1209 recv := decl.Recv.List[0].Type
1210 if s, ok := recv.(*ast.StarExpr); ok {
1211 recv = s.X
1212 }
1213 if id, ok := recv.(*ast.Ident); ok {
1214 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1215 }
1216 }
1217 }
1218 }
1219 for a := range g.annotations {
1220 if !seenAnnotations[a] {
1221 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1222 }
1223 }
1224
Damien Neil5c5b5312019-05-14 12:44:37 -07001225 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001226 if err != nil {
1227 return "", err
1228 }
1229 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001230}
Damien Neil082ce922018-09-06 10:23:53 -07001231
Joe Tsai2e7817f2019-08-23 12:18:57 -07001232// A GoIdent is a Go identifier, consisting of a name and import path.
1233// The name is a single identifier and may not be a dot-qualified selector.
1234type GoIdent struct {
1235 GoName string
1236 GoImportPath GoImportPath
1237}
1238
1239func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1240
1241// newGoIdent returns the Go identifier for a descriptor.
1242func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1243 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1244 return GoIdent{
1245 GoName: strs.GoCamelCase(name),
1246 GoImportPath: f.GoImportPath,
1247 }
1248}
1249
1250// A GoImportPath is the import path of a Go package.
1251// For example: "google.golang.org/protobuf/compiler/protogen"
1252type GoImportPath string
1253
1254func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1255
1256// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1257func (p GoImportPath) Ident(s string) GoIdent {
1258 return GoIdent{GoName: s, GoImportPath: p}
1259}
1260
1261// A GoPackageName is the name of a Go package. e.g., "protobuf".
1262type GoPackageName string
1263
1264// cleanPackageName converts a string to a valid Go package name.
1265func cleanPackageName(name string) GoPackageName {
1266 return GoPackageName(strs.GoSanitized(name))
1267}
1268
1269// baseName returns the last path element of the name, with the last dotted suffix removed.
1270func baseName(name string) string {
1271 // First, find the last element
1272 if i := strings.LastIndex(name, "/"); i >= 0 {
1273 name = name[i+1:]
1274 }
1275 // Now drop the suffix
1276 if i := strings.LastIndex(name, "."); i >= 0 {
1277 name = name[:i]
1278 }
1279 return name
1280}
1281
Damien Neil082ce922018-09-06 10:23:53 -07001282type pathType int
1283
1284const (
1285 pathTypeImport pathType = iota
1286 pathTypeSourceRelative
1287)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001288
Damien Neil162c1272018-10-04 12:42:37 -07001289// A Location is a location in a .proto source file.
1290//
1291// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1292// for details.
1293type Location struct {
1294 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001295 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001296}
1297
1298// appendPath add elements to a Location's path, returning a new Location.
1299func (loc Location) appendPath(a ...int32) Location {
Joe Tsai691d8562019-07-12 17:16:36 -07001300 var n protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001301 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001302 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001303 return Location{
1304 SourceFile: loc.SourceFile,
1305 Path: n,
1306 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001307}
Damien Neilba1159f2018-10-17 12:53:18 -07001308
1309// A pathKey is a representation of a location path suitable for use as a map key.
1310type pathKey struct {
1311 s string
1312}
1313
1314// newPathKey converts a location path to a pathKey.
Koichi Shiraishiea2076d2019-05-24 18:24:29 +09001315func newPathKey(idxPath []int32) pathKey {
1316 buf := make([]byte, 4*len(idxPath))
1317 for i, x := range idxPath {
Damien Neilba1159f2018-10-17 12:53:18 -07001318 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1319 }
1320 return pathKey{string(buf)}
1321}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001322
1323// CommentSet is a set of leading and trailing comments associated
1324// with a .proto descriptor declaration.
1325type CommentSet struct {
1326 LeadingDetached []Comments
1327 Leading Comments
1328 Trailing Comments
1329}
1330
1331// Comments is a comments string as provided by protoc.
1332type Comments string
1333
1334// String formats the comments by inserting // to the start of each line,
1335// ensuring that there is a trailing newline.
1336// An empty comment is formatted as an empty string.
1337func (c Comments) String() string {
1338 if c == "" {
1339 return ""
1340 }
1341 var b []byte
1342 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1343 b = append(b, "//"...)
1344 b = append(b, line...)
1345 b = append(b, "\n"...)
1346 }
1347 return string(b)
1348}
Damien Neile358d432020-03-06 13:58:41 -08001349
1350var warnings = true
1351
1352func warn(format string, a ...interface{}) {
1353 if warnings {
1354 log.Printf("WARNING: "+format, a...)
1355 }
1356}