blob: 2ee676fbb9be40df76edcac1ce4c0be5c853ce78 [file] [log] [blame]
Damien Neil220c2022018-08-15 11:24:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package protogen provides support for writing protoc plugins.
6//
Joe Tsai04f03cb2020-02-14 12:40:48 -08007// Plugins for protoc, the Protocol Buffer compiler,
8// are programs which read a CodeGeneratorRequest message from standard input
9// and write a CodeGeneratorResponse message to standard output.
10// This package provides support for writing plugins which generate Go code.
Damien Neil220c2022018-08-15 11:24:18 -070011package protogen
12
13import (
Damien Neilc7d07d92018-08-22 13:46:02 -070014 "bufio"
Damien Neil220c2022018-08-15 11:24:18 -070015 "bytes"
16 "fmt"
Damien Neil1ec33152018-09-13 13:12:36 -070017 "go/ast"
Damien Neilc7d07d92018-08-22 13:46:02 -070018 "go/parser"
19 "go/printer"
20 "go/token"
Joe Tsai124c8122019-01-14 11:48:43 -080021 "go/types"
Damien Neil220c2022018-08-15 11:24:18 -070022 "io/ioutil"
23 "os"
Damien Neil082ce922018-09-06 10:23:53 -070024 "path"
Damien Neil220c2022018-08-15 11:24:18 -070025 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070026 "sort"
27 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070028 "strings"
29
Damien Neil5c5b5312019-05-14 12:44:37 -070030 "google.golang.org/protobuf/encoding/prototext"
Joe Tsaie0b77db2020-05-26 11:21:59 -070031 "google.golang.org/protobuf/internal/genid"
Joe Tsai2e7817f2019-08-23 12:18:57 -070032 "google.golang.org/protobuf/internal/strs"
Damien Neile89e6242019-05-13 23:55:40 -070033 "google.golang.org/protobuf/proto"
34 "google.golang.org/protobuf/reflect/protodesc"
35 "google.golang.org/protobuf/reflect/protoreflect"
36 "google.golang.org/protobuf/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080037
Joe Tsaia95b29f2019-05-16 12:47:20 -070038 "google.golang.org/protobuf/types/descriptorpb"
39 "google.golang.org/protobuf/types/pluginpb"
Damien Neil220c2022018-08-15 11:24:18 -070040)
41
Joe Tsai222a0002020-02-24 11:21:30 -080042const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package"
43
Damien Neil220c2022018-08-15 11:24:18 -070044// Run executes a function as a protoc plugin.
45//
46// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
47// function, and writes a CodeGeneratorResponse message to os.Stdout.
48//
49// If a failure occurs while reading or writing, Run prints an error to
50// os.Stderr and calls os.Exit(1).
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080051func (opts Options) Run(f func(*Plugin) error) {
Damien Neil3cf6e622018-09-11 13:53:14 -070052 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070053 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
54 os.Exit(1)
55 }
56}
57
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080058func run(opts Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070059 if len(os.Args) > 1 {
60 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
61 }
Damien Neil220c2022018-08-15 11:24:18 -070062 in, err := ioutil.ReadAll(os.Stdin)
63 if err != nil {
64 return err
65 }
66 req := &pluginpb.CodeGeneratorRequest{}
67 if err := proto.Unmarshal(in, req); err != nil {
68 return err
69 }
Joe Tsaiab0ca4f2020-02-27 14:47:29 -080070 gen, err := opts.New(req)
Damien Neil220c2022018-08-15 11:24:18 -070071 if err != nil {
72 return err
73 }
74 if err := f(gen); err != nil {
75 // Errors from the plugin function are reported by setting the
76 // error field in the CodeGeneratorResponse.
77 //
78 // In contrast, errors that indicate a problem in protoc
79 // itself (unparsable input, I/O errors, etc.) are reported
80 // to stderr.
81 gen.Error(err)
82 }
83 resp := gen.Response()
84 out, err := proto.Marshal(resp)
85 if err != nil {
86 return err
87 }
88 if _, err := os.Stdout.Write(out); err != nil {
89 return err
90 }
91 return nil
92}
93
94// A Plugin is a protoc plugin invocation.
95type Plugin struct {
96 // Request is the CodeGeneratorRequest provided by protoc.
97 Request *pluginpb.CodeGeneratorRequest
98
99 // Files is the set of files to generate and everything they import.
100 // Files appear in topological order, so each file appears before any
101 // file that imports it.
102 Files []*File
Joe Tsai2cec4842019-08-20 20:14:19 -0700103 FilesByPath map[string]*File
Damien Neil220c2022018-08-15 11:24:18 -0700104
Joe Tsai387873d2020-04-28 14:44:38 -0700105 // SupportedFeatures is the set of protobuf language features supported by
106 // this generator plugin. See the documentation for
107 // google.protobuf.CodeGeneratorResponse.supported_features for details.
108 SupportedFeatures uint64
109
Damien Neil658051b2018-09-10 12:26:21 -0700110 fileReg *protoregistry.Files
Damien Neil658051b2018-09-10 12:26:21 -0700111 enumsByName map[protoreflect.FullName]*Enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700112 messagesByName map[protoreflect.FullName]*Message
Damien Neil162c1272018-10-04 12:42:37 -0700113 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700114 pathType pathType
Damien Neilffbc5fd2020-02-12 23:38:30 -0800115 module string
Damien Neil658051b2018-09-10 12:26:21 -0700116 genFiles []*GeneratedFile
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800117 opts Options
Damien Neil658051b2018-09-10 12:26:21 -0700118 err error
Damien Neil220c2022018-08-15 11:24:18 -0700119}
120
Damien Neil3cf6e622018-09-11 13:53:14 -0700121type Options struct {
122 // If ParamFunc is non-nil, it will be called with each unknown
123 // generator parameter.
124 //
125 // Plugins for protoc can accept parameters from the command line,
126 // passed in the --<lang>_out protoc, separated from the output
127 // directory with a colon; e.g.,
128 //
129 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
130 //
131 // Parameters passed in this fashion as a comma-separated list of
132 // key=value pairs will be passed to the ParamFunc.
133 //
134 // The (flag.FlagSet).Set method matches this function signature,
135 // so parameters can be converted into flags as in the following:
136 //
137 // var flags flag.FlagSet
138 // value := flags.Bool("param", false, "")
139 // opts := &protogen.Options{
140 // ParamFunc: flags.Set,
141 // }
142 // protogen.Run(opts, func(p *protogen.Plugin) error {
143 // if *value { ... }
144 // })
145 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700146
147 // ImportRewriteFunc is called with the import path of each package
148 // imported by a generated file. It returns the import path to use
149 // for this package.
150 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700151}
152
Damien Neil220c2022018-08-15 11:24:18 -0700153// New returns a new Plugin.
Joe Tsaiab0ca4f2020-02-27 14:47:29 -0800154func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) {
Damien Neil220c2022018-08-15 11:24:18 -0700155 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700156 Request: req,
Joe Tsai2cec4842019-08-20 20:14:19 -0700157 FilesByPath: make(map[string]*File),
Damien Neilc8268852019-10-08 13:28:53 -0700158 fileReg: new(protoregistry.Files),
Damien Neil658051b2018-09-10 12:26:21 -0700159 enumsByName: make(map[protoreflect.FullName]*Enum),
Joe Tsai7762ec22019-08-20 20:10:23 -0700160 messagesByName: make(map[protoreflect.FullName]*Message),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700161 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700162 }
163
Damien Neil082ce922018-09-06 10:23:53 -0700164 packageNames := make(map[string]GoPackageName) // filename -> package name
165 importPaths := make(map[string]GoImportPath) // filename -> import path
Damien Neil220c2022018-08-15 11:24:18 -0700166 for _, param := range strings.Split(req.GetParameter(), ",") {
167 var value string
168 if i := strings.Index(param, "="); i >= 0 {
169 value = param[i+1:]
170 param = param[0:i]
171 }
172 switch param {
173 case "":
174 // Ignore.
Damien Neilffbc5fd2020-02-12 23:38:30 -0800175 case "module":
176 gen.module = value
Damien Neil220c2022018-08-15 11:24:18 -0700177 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700178 switch value {
179 case "import":
180 gen.pathType = pathTypeImport
181 case "source_relative":
182 gen.pathType = pathTypeSourceRelative
183 default:
184 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
185 }
Damien Neil220c2022018-08-15 11:24:18 -0700186 case "annotate_code":
Damien Neil162c1272018-10-04 12:42:37 -0700187 switch value {
188 case "true", "":
189 gen.annotateCode = true
190 case "false":
191 default:
192 return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
193 }
Damien Neil220c2022018-08-15 11:24:18 -0700194 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700195 if param[0] == 'M' {
Joe Tsai8b366e82021-03-16 03:20:52 -0700196 impPath, pkgName := splitImportPathAndPackageName(value)
197 if pkgName != "" {
Joe Tsai6ad8e632020-03-18 00:59:09 -0700198 packageNames[param[1:]] = pkgName
Joe Tsai6ad8e632020-03-18 00:59:09 -0700199 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700200 if impPath != "" {
201 importPaths[param[1:]] = impPath
202 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700203 continue
Damien Neil220c2022018-08-15 11:24:18 -0700204 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700205 if opts.ParamFunc != nil {
206 if err := opts.ParamFunc(param, value); err != nil {
207 return nil, err
208 }
209 }
Damien Neil082ce922018-09-06 10:23:53 -0700210 }
211 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700212 // When the module= option is provided, we strip the module name
213 // prefix from generated files. This only makes sense if generated
214 // filenames are based on the import path.
215 if gen.module != "" && gen.pathType == pathTypeSourceRelative {
216 return nil, fmt.Errorf("cannot use module= with paths=source_relative")
Damien Neilffbc5fd2020-02-12 23:38:30 -0800217 }
Damien Neil082ce922018-09-06 10:23:53 -0700218
219 // Figure out the import path and package name for each file.
220 //
221 // The rules here are complicated and have grown organically over time.
222 // Interactions between different ways of specifying package information
223 // may be surprising.
224 //
225 // The recommended approach is to include a go_package option in every
226 // .proto source file specifying the full import path of the Go package
227 // associated with this file.
228 //
Joe Tsai8d30bbe2019-05-16 15:53:25 -0700229 // option go_package = "google.golang.org/protobuf/types/known/anypb";
Damien Neil082ce922018-09-06 10:23:53 -0700230 //
Joe Tsai8b366e82021-03-16 03:20:52 -0700231 // Alternatively, build systems which want to exert full control over
232 // import paths may specify M<filename>=<import_path> flags.
Damien Neil082ce922018-09-06 10:23:53 -0700233 for _, fdesc := range gen.Request.ProtoFile {
Joe Tsai8b366e82021-03-16 03:20:52 -0700234 // The "M" command-line flags take precedence over
235 // the "go_package" option in the .proto source file.
Damien Neil082ce922018-09-06 10:23:53 -0700236 filename := fdesc.GetName()
Joe Tsai8b366e82021-03-16 03:20:52 -0700237 impPath, pkgName := splitImportPathAndPackageName(fdesc.GetOptions().GetGoPackage())
238 if importPaths[filename] == "" && impPath != "" {
239 importPaths[filename] = impPath
Damien Neil082ce922018-09-06 10:23:53 -0700240 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700241 if packageNames[filename] == "" && pkgName != "" {
242 packageNames[filename] = pkgName
Joe Tsai3e802492019-09-07 13:06:27 -0700243 }
244 switch {
Joe Tsai8b366e82021-03-16 03:20:52 -0700245 case importPaths[filename] == "":
246 // The import path must be specified one way or another.
247 return nil, fmt.Errorf(
248 "unable to determine Go import path for %q\n\n"+
249 "Please specify either:\n"+
250 "\t• a \"go_package\" option in the .proto source file, or\n"+
251 "\t• a \"M\" argument on the command line.\n\n"+
252 "See %v for more information.\n",
253 fdesc.GetName(), goPackageDocURL)
Joe Tsai4c193d12021-05-04 11:03:42 -0700254 case !strings.Contains(string(importPaths[filename]), ".") &&
255 !strings.Contains(string(importPaths[filename]), "/"):
256 // Check that import paths contain at least a dot or slash to avoid
257 // a common mistake where import path is confused with package name.
Joe Tsai8b366e82021-03-16 03:20:52 -0700258 return nil, fmt.Errorf(
259 "invalid Go import path %q for %q\n\n"+
Joe Tsai4c193d12021-05-04 11:03:42 -0700260 "The import path must contain at least one period ('.') or forward slash ('/') character.\n\n"+
Joe Tsai8b366e82021-03-16 03:20:52 -0700261 "See %v for more information.\n",
262 string(importPaths[filename]), fdesc.GetName(), goPackageDocURL)
263 case packageNames[filename] == "":
264 // If the package name is not explicitly specified,
265 // then derive a reasonable package name from the import path.
266 //
267 // NOTE: The package name is derived first from the import path in
268 // the "go_package" option (if present) before trying the "M" flag.
269 // The inverted order for this is because the primary use of the "M"
270 // flag is by build systems that have full control over the
271 // import paths all packages, where it is generally expected that
272 // the Go package name still be identical for the Go toolchain and
273 // for custom build systems like Bazel.
274 if impPath == "" {
275 impPath = importPaths[filename]
Joe Tsaice5d8312020-05-05 12:01:13 -0700276 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700277 packageNames[filename] = cleanPackageName(path.Base(string(impPath)))
Joe Tsai3e802492019-09-07 13:06:27 -0700278 }
Damien Neil082ce922018-09-06 10:23:53 -0700279 }
280
281 // Consistency check: Every file with the same Go import path should have
282 // the same Go package name.
283 packageFiles := make(map[GoImportPath][]string)
284 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700285 if _, ok := packageNames[filename]; !ok {
286 // Skip files mentioned in a M<file>=<import_path> parameter
287 // but which do not appear in the CodeGeneratorRequest.
288 continue
289 }
Damien Neil082ce922018-09-06 10:23:53 -0700290 packageFiles[importPath] = append(packageFiles[importPath], filename)
291 }
292 for importPath, filenames := range packageFiles {
293 for i := 1; i < len(filenames); i++ {
294 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
295 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
296 importPath, a, filenames[0], b, filenames[i])
297 }
Damien Neil220c2022018-08-15 11:24:18 -0700298 }
299 }
300
301 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700302 filename := fdesc.GetName()
Joe Tsai2cec4842019-08-20 20:14:19 -0700303 if gen.FilesByPath[filename] != nil {
Damien Neil082ce922018-09-06 10:23:53 -0700304 return nil, fmt.Errorf("duplicate file name: %q", filename)
305 }
306 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700307 if err != nil {
308 return nil, err
309 }
Damien Neil220c2022018-08-15 11:24:18 -0700310 gen.Files = append(gen.Files, f)
Joe Tsai2cec4842019-08-20 20:14:19 -0700311 gen.FilesByPath[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700312 }
Damien Neil082ce922018-09-06 10:23:53 -0700313 for _, filename := range gen.Request.FileToGenerate {
Joe Tsai2cec4842019-08-20 20:14:19 -0700314 f, ok := gen.FilesByPath[filename]
Damien Neil220c2022018-08-15 11:24:18 -0700315 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700316 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700317 }
318 f.Generate = true
319 }
320 return gen, nil
321}
322
323// Error records an error in code generation. The generator will report the
324// error back to protoc and will not produce output.
325func (gen *Plugin) Error(err error) {
326 if gen.err == nil {
327 gen.err = err
328 }
329}
330
331// Response returns the generator output.
332func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
333 resp := &pluginpb.CodeGeneratorResponse{}
334 if gen.err != nil {
Damien Neila8a2cea2019-07-10 16:17:16 -0700335 resp.Error = proto.String(gen.err.Error())
Damien Neil220c2022018-08-15 11:24:18 -0700336 return resp
337 }
Damien Neil162c1272018-10-04 12:42:37 -0700338 for _, g := range gen.genFiles {
Damien Neil7bf3ce22018-12-21 15:54:06 -0800339 if g.skip {
340 continue
341 }
342 content, err := g.Content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700343 if err != nil {
344 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700345 Error: proto.String(err.Error()),
Damien Neilc7d07d92018-08-22 13:46:02 -0700346 }
347 }
Damien Neilffbc5fd2020-02-12 23:38:30 -0800348 filename := g.filename
349 if gen.module != "" {
350 trim := gen.module + "/"
351 if !strings.HasPrefix(filename, trim) {
352 return &pluginpb.CodeGeneratorResponse{
353 Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)),
354 }
355 }
356 filename = strings.TrimPrefix(filename, trim)
357 }
Damien Neil220c2022018-08-15 11:24:18 -0700358 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800359 Name: proto.String(filename),
Damien Neila8a2cea2019-07-10 16:17:16 -0700360 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700361 })
Damien Neil162c1272018-10-04 12:42:37 -0700362 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
363 meta, err := g.metaFile(content)
364 if err != nil {
365 return &pluginpb.CodeGeneratorResponse{
Damien Neila8a2cea2019-07-10 16:17:16 -0700366 Error: proto.String(err.Error()),
Damien Neil162c1272018-10-04 12:42:37 -0700367 }
368 }
369 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neilffbc5fd2020-02-12 23:38:30 -0800370 Name: proto.String(filename + ".meta"),
Damien Neila8a2cea2019-07-10 16:17:16 -0700371 Content: proto.String(meta),
Damien Neil162c1272018-10-04 12:42:37 -0700372 })
373 }
Damien Neil220c2022018-08-15 11:24:18 -0700374 }
Joe Tsai387873d2020-04-28 14:44:38 -0700375 if gen.SupportedFeatures > 0 {
376 resp.SupportedFeatures = proto.Uint64(gen.SupportedFeatures)
377 }
Damien Neil220c2022018-08-15 11:24:18 -0700378 return resp
379}
380
Damien Neilc7d07d92018-08-22 13:46:02 -0700381// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700382type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700383 Desc protoreflect.FileDescriptor
Joe Tsaie1f8d502018-11-26 18:55:29 -0800384 Proto *descriptorpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700385
Joe Tsaib6405bd2018-11-15 14:44:37 -0800386 GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
387 GoPackageName GoPackageName // name of this file's Go package
388 GoImportPath GoImportPath // import path of this file's Go package
Joe Tsai7762ec22019-08-20 20:10:23 -0700389
390 Enums []*Enum // top-level enum declarations
391 Messages []*Message // top-level message declarations
392 Extensions []*Extension // top-level extension declarations
393 Services []*Service // top-level service declarations
394
395 Generate bool // true if we should generate code for this file
Damien Neil082ce922018-09-06 10:23:53 -0700396
397 // GeneratedFilenamePrefix is used to construct filenames for generated
398 // files associated with this source file.
399 //
400 // For example, the source file "dir/foo.proto" might have a filename prefix
401 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
402 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700403
Joe Tsai42cc4c52020-06-16 08:48:38 -0700404 location Location
Damien Neil220c2022018-08-15 11:24:18 -0700405}
406
Joe Tsaie1f8d502018-11-26 18:55:29 -0800407func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
408 desc, err := protodesc.NewFile(p, gen.fileReg)
Damien Neilabc6fc12018-08-23 14:39:30 -0700409 if err != nil {
410 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
411 }
Damien Neilc8268852019-10-08 13:28:53 -0700412 if err := gen.fileReg.RegisterFile(desc); err != nil {
Damien Neilabc6fc12018-08-23 14:39:30 -0700413 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
414 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700415 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700416 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700417 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700418 GoPackageName: packageName,
419 GoImportPath: importPath,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700420 location: Location{SourceFile: desc.Path()},
Damien Neil220c2022018-08-15 11:24:18 -0700421 }
Damien Neil082ce922018-09-06 10:23:53 -0700422
423 // Determine the prefix for generated Go files.
424 prefix := p.GetName()
425 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
426 prefix = prefix[:len(prefix)-len(ext)]
427 }
Damien Neilaadba562020-02-15 14:28:51 -0800428 switch gen.pathType {
Damien Neilaadba562020-02-15 14:28:51 -0800429 case pathTypeImport:
430 // If paths=import, the output filename is derived from the Go import path.
431 prefix = path.Join(string(f.GoImportPath), path.Base(prefix))
432 case pathTypeSourceRelative:
433 // If paths=source_relative, the output filename is derived from
434 // the input filename.
Damien Neil082ce922018-09-06 10:23:53 -0700435 }
Joe Tsaib6405bd2018-11-15 14:44:37 -0800436 f.GoDescriptorIdent = GoIdent{
Joe Tsai2e7817f2019-08-23 12:18:57 -0700437 GoName: "File_" + strs.GoSanitized(p.GetName()),
Joe Tsaib6405bd2018-11-15 14:44:37 -0800438 GoImportPath: f.GoImportPath,
439 }
Damien Neil082ce922018-09-06 10:23:53 -0700440 f.GeneratedFilenamePrefix = prefix
441
Joe Tsai7762ec22019-08-20 20:10:23 -0700442 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
443 f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700444 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700445 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
446 f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700447 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700448 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
449 f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i)))
Damien Neil993c04d2018-09-14 15:41:11 -0700450 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700451 for i, sds := 0, desc.Services(); i < sds.Len(); i++ {
452 f.Services = append(f.Services, newService(gen, f, sds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700453 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700454 for _, message := range f.Messages {
Joe Tsai7762ec22019-08-20 20:10:23 -0700455 if err := message.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700456 return nil, err
457 }
458 }
459 for _, extension := range f.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700460 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700461 return nil, err
462 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700463 }
Damien Neil2dc67182018-09-21 15:03:34 -0700464 for _, service := range f.Services {
465 for _, method := range service.Methods {
Joe Tsai7762ec22019-08-20 20:10:23 -0700466 if err := method.resolveDependencies(gen); err != nil {
Damien Neil2dc67182018-09-21 15:03:34 -0700467 return nil, err
468 }
469 }
470 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700471 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700472}
473
Joe Tsai8b366e82021-03-16 03:20:52 -0700474// splitImportPathAndPackageName splits off the optional Go package name
475// from the Go import path when seperated by a ';' delimiter.
476func splitImportPathAndPackageName(s string) (GoImportPath, GoPackageName) {
477 if i := strings.Index(s, ";"); i >= 0 {
478 return GoImportPath(s[:i]), GoPackageName(s[i+1:])
Damien Neil082ce922018-09-06 10:23:53 -0700479 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700480 return GoImportPath(s), ""
Damien Neil082ce922018-09-06 10:23:53 -0700481}
482
Joe Tsai7762ec22019-08-20 20:10:23 -0700483// An Enum describes an enum.
484type Enum struct {
485 Desc protoreflect.EnumDescriptor
486
487 GoIdent GoIdent // name of the generated Go type
488
489 Values []*EnumValue // enum value declarations
490
491 Location Location // location of this enum
492 Comments CommentSet // comments associated with this enum
493}
494
495func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
496 var loc Location
497 if parent != nil {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700498 loc = parent.Location.appendPath(genid.DescriptorProto_EnumType_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700499 } else {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700500 loc = f.location.appendPath(genid.FileDescriptorProto_EnumType_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700501 }
502 enum := &Enum{
503 Desc: desc,
504 GoIdent: newGoIdent(f, desc),
505 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700506 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Joe Tsai7762ec22019-08-20 20:10:23 -0700507 }
508 gen.enumsByName[desc.FullName()] = enum
509 for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ {
510 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i)))
511 }
512 return enum
513}
514
515// An EnumValue describes an enum value.
516type EnumValue struct {
517 Desc protoreflect.EnumValueDescriptor
518
519 GoIdent GoIdent // name of the generated Go declaration
520
Joe Tsai4df99fd2019-08-20 22:26:16 -0700521 Parent *Enum // enum in which this value is declared
522
Joe Tsai7762ec22019-08-20 20:10:23 -0700523 Location Location // location of this enum value
524 Comments CommentSet // comments associated with this enum value
525}
526
527func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
528 // A top-level enum value's name is: EnumName_ValueName
529 // An enum value contained in a message is: MessageName_ValueName
530 //
Joe Tsaief6e5242019-08-21 00:55:36 -0700531 // For historical reasons, enum value names are not camel-cased.
Joe Tsai7762ec22019-08-20 20:10:23 -0700532 parentIdent := enum.GoIdent
533 if message != nil {
534 parentIdent = message.GoIdent
535 }
536 name := parentIdent.GoName + "_" + string(desc.Name())
Joe Tsai42cc4c52020-06-16 08:48:38 -0700537 loc := enum.Location.appendPath(genid.EnumDescriptorProto_Value_field_number, desc.Index())
Joe Tsai7762ec22019-08-20 20:10:23 -0700538 return &EnumValue{
539 Desc: desc,
540 GoIdent: f.GoImportPath.Ident(name),
Joe Tsai4df99fd2019-08-20 22:26:16 -0700541 Parent: enum,
Joe Tsai7762ec22019-08-20 20:10:23 -0700542 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700543 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Joe Tsai7762ec22019-08-20 20:10:23 -0700544 }
545}
546
Damien Neilc7d07d92018-08-22 13:46:02 -0700547// A Message describes a message.
548type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700549 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700550
Joe Tsai7762ec22019-08-20 20:10:23 -0700551 GoIdent GoIdent // name of the generated Go type
552
553 Fields []*Field // message field declarations
554 Oneofs []*Oneof // message oneof declarations
555
Damien Neil993c04d2018-09-14 15:41:11 -0700556 Enums []*Enum // nested enum declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700557 Messages []*Message // nested message declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700558 Extensions []*Extension // nested extension declarations
Joe Tsai7762ec22019-08-20 20:10:23 -0700559
560 Location Location // location of this message
561 Comments CommentSet // comments associated with this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700562}
563
Damien Neil1fa78d82018-09-13 13:12:36 -0700564func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700565 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700566 if parent != nil {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700567 loc = parent.Location.appendPath(genid.DescriptorProto_NestedType_field_number, desc.Index())
Damien Neilcab8dfe2018-09-06 14:51:28 -0700568 } else {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700569 loc = f.location.appendPath(genid.FileDescriptorProto_MessageType_field_number, desc.Index())
Damien Neilcab8dfe2018-09-06 14:51:28 -0700570 }
Damien Neil46abb572018-09-07 12:45:37 -0700571 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700572 Desc: desc,
573 GoIdent: newGoIdent(f, desc),
574 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700575 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neilc7d07d92018-08-22 13:46:02 -0700576 }
Damien Neil658051b2018-09-10 12:26:21 -0700577 gen.messagesByName[desc.FullName()] = message
Joe Tsai7762ec22019-08-20 20:10:23 -0700578 for i, eds := 0, desc.Enums(); i < eds.Len(); i++ {
579 message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700580 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700581 for i, mds := 0, desc.Messages(); i < mds.Len(); i++ {
582 message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i)))
Damien Neil46abb572018-09-07 12:45:37 -0700583 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700584 for i, fds := 0, desc.Fields(); i < fds.Len(); i++ {
585 message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i)))
Damien Neil1fa78d82018-09-13 13:12:36 -0700586 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700587 for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ {
588 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700589 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700590 for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ {
591 message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i)))
592 }
593
594 // Resolve local references between fields and oneofs.
595 for _, field := range message.Fields {
596 if od := field.Desc.ContainingOneof(); od != nil {
597 oneof := message.Oneofs[od.Index()]
598 field.Oneof = oneof
599 oneof.Fields = append(oneof.Fields, field)
600 }
Damien Neil993c04d2018-09-14 15:41:11 -0700601 }
Damien Neil658051b2018-09-10 12:26:21 -0700602
603 // Field name conflict resolution.
604 //
605 // We assume well-known method names that may be attached to a generated
606 // message type, as well as a 'Get*' method for each field. For each
607 // field in turn, we add _s to its name until there are no conflicts.
608 //
609 // Any change to the following set of method names is a potential
610 // incompatible API change because it may change generated field names.
611 //
612 // TODO: If we ever support a 'go_name' option to set the Go name of a
613 // field, we should consider dropping this entirely. The conflict
614 // resolution algorithm is subtle and surprising (changing the order
615 // in which fields appear in the .proto source file can change the
616 // names of fields in generated code), and does not adapt well to
617 // adding new per-field methods such as setters.
618 usedNames := map[string]bool{
619 "Reset": true,
620 "String": true,
621 "ProtoMessage": true,
622 "Marshal": true,
623 "Unmarshal": true,
624 "ExtensionRangeArray": true,
625 "ExtensionMap": true,
626 "Descriptor": true,
627 }
Joe Tsaid6966a42019-01-08 10:59:34 -0800628 makeNameUnique := func(name string, hasGetter bool) string {
629 for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
Damien Neil658051b2018-09-10 12:26:21 -0700630 name += "_"
631 }
632 usedNames[name] = true
Joe Tsaid6966a42019-01-08 10:59:34 -0800633 usedNames["Get"+name] = hasGetter
Damien Neil658051b2018-09-10 12:26:21 -0700634 return name
635 }
636 for _, field := range message.Fields {
Joe Tsaid6966a42019-01-08 10:59:34 -0800637 field.GoName = makeNameUnique(field.GoName, true)
Joe Tsaief6e5242019-08-21 00:55:36 -0700638 field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName
639 if field.Oneof != nil && field.Oneof.Fields[0] == field {
640 // Make the name for a oneof unique as well. For historical reasons,
641 // this assumes that a getter method is not generated for oneofs.
642 // This is incorrect, but fixing it breaks existing code.
643 field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
644 field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName
645 }
646 }
647
648 // Oneof field name conflict resolution.
649 //
650 // This conflict resolution is incomplete as it does not consider collisions
651 // with other oneof field types, but fixing it breaks existing code.
652 for _, field := range message.Fields {
Joe Tsaid24bc722019-04-15 23:39:09 -0700653 if field.Oneof != nil {
Joe Tsaief6e5242019-08-21 00:55:36 -0700654 Loop:
655 for {
656 for _, nestedMessage := range message.Messages {
657 if nestedMessage.GoIdent == field.GoIdent {
658 field.GoIdent.GoName += "_"
659 continue Loop
660 }
661 }
662 for _, nestedEnum := range message.Enums {
663 if nestedEnum.GoIdent == field.GoIdent {
664 field.GoIdent.GoName += "_"
665 continue Loop
666 }
667 }
668 break Loop
Damien Neil1fa78d82018-09-13 13:12:36 -0700669 }
670 }
Damien Neil658051b2018-09-10 12:26:21 -0700671 }
672
Damien Neil1fa78d82018-09-13 13:12:36 -0700673 return message
Damien Neil658051b2018-09-10 12:26:21 -0700674}
675
Joe Tsai7762ec22019-08-20 20:10:23 -0700676func (message *Message) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700677 for _, field := range message.Fields {
Joe Tsai7762ec22019-08-20 20:10:23 -0700678 if err := field.resolveDependencies(gen); err != nil {
Damien Neil0bd5a382018-09-13 15:07:10 -0700679 return err
680 }
681 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700682 for _, message := range message.Messages {
683 if err := message.resolveDependencies(gen); err != nil {
684 return err
685 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700686 }
Damien Neil993c04d2018-09-14 15:41:11 -0700687 for _, extension := range message.Extensions {
Joe Tsai7762ec22019-08-20 20:10:23 -0700688 if err := extension.resolveDependencies(gen); err != nil {
Damien Neil993c04d2018-09-14 15:41:11 -0700689 return err
690 }
691 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700692 return nil
693}
694
Damien Neil658051b2018-09-10 12:26:21 -0700695// A Field describes a message field.
696type Field struct {
697 Desc protoreflect.FieldDescriptor
698
Damien Neil1fa78d82018-09-13 13:12:36 -0700699 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700700 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700701 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
Joe Tsaief6e5242019-08-21 00:55:36 -0700702 GoName string // e.g., "FieldName"
703
704 // GoIdent is the base name of a top-level declaration for this field.
705 // For code generated by protoc-gen-go, this means a wrapper type named
706 // '{{GoIdent}}' for members fields of a oneof, and a variable named
707 // 'E_{{GoIdent}}' for extension fields.
708 GoIdent GoIdent // e.g., "MessageName_FieldName"
Damien Neil658051b2018-09-10 12:26:21 -0700709
Joe Tsai7762ec22019-08-20 20:10:23 -0700710 Parent *Message // message in which this field is declared; nil if top-level extension
711 Oneof *Oneof // containing oneof; nil if not part of a oneof
712 Extendee *Message // extended message for extension fields; nil otherwise
713
714 Enum *Enum // type for enum fields; nil otherwise
715 Message *Message // type for message or group fields; nil otherwise
716
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700717 Location Location // location of this field
718 Comments CommentSet // comments associated with this field
Damien Neil658051b2018-09-10 12:26:21 -0700719}
720
Damien Neil1fa78d82018-09-13 13:12:36 -0700721func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700722 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700723 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700724 case desc.IsExtension() && message == nil:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700725 loc = f.location.appendPath(genid.FileDescriptorProto_Extension_field_number, desc.Index())
Joe Tsaiac31a352019-05-13 14:32:56 -0700726 case desc.IsExtension() && message != nil:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700727 loc = message.Location.appendPath(genid.DescriptorProto_Extension_field_number, desc.Index())
Damien Neil993c04d2018-09-14 15:41:11 -0700728 default:
Joe Tsai42cc4c52020-06-16 08:48:38 -0700729 loc = message.Location.appendPath(genid.DescriptorProto_Field_field_number, desc.Index())
Damien Neil993c04d2018-09-14 15:41:11 -0700730 }
Joe Tsai2e7817f2019-08-23 12:18:57 -0700731 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700732 var parentPrefix string
733 if message != nil {
734 parentPrefix = message.GoIdent.GoName + "_"
735 }
Damien Neil658051b2018-09-10 12:26:21 -0700736 field := &Field{
Joe Tsaief6e5242019-08-21 00:55:36 -0700737 Desc: desc,
738 GoName: camelCased,
739 GoIdent: GoIdent{
740 GoImportPath: f.GoImportPath,
741 GoName: parentPrefix + camelCased,
742 },
Joe Tsaid24bc722019-04-15 23:39:09 -0700743 Parent: message,
744 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700745 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil658051b2018-09-10 12:26:21 -0700746 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700747 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700748}
749
Joe Tsai7762ec22019-08-20 20:10:23 -0700750func (field *Field) resolveDependencies(gen *Plugin) error {
Damien Neil0bd5a382018-09-13 15:07:10 -0700751 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700752 switch desc.Kind() {
Damien Neil658051b2018-09-10 12:26:21 -0700753 case protoreflect.EnumKind:
Joe Tsai7762ec22019-08-20 20:10:23 -0700754 name := field.Desc.Enum().FullName()
755 enum, ok := gen.enumsByName[name]
Damien Neil658051b2018-09-10 12:26:21 -0700756 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700757 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name)
Damien Neil658051b2018-09-10 12:26:21 -0700758 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700759 field.Enum = enum
Joe Tsai7762ec22019-08-20 20:10:23 -0700760 case protoreflect.MessageKind, protoreflect.GroupKind:
761 name := desc.Message().FullName()
762 message, ok := gen.messagesByName[name]
763 if !ok {
764 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
765 }
766 field.Message = message
Damien Neil658051b2018-09-10 12:26:21 -0700767 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700768 if desc.IsExtension() {
Joe Tsai7762ec22019-08-20 20:10:23 -0700769 name := desc.ContainingMessage().FullName()
770 message, ok := gen.messagesByName[name]
Damien Neil993c04d2018-09-14 15:41:11 -0700771 if !ok {
Joe Tsai7762ec22019-08-20 20:10:23 -0700772 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name)
Damien Neil993c04d2018-09-14 15:41:11 -0700773 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700774 field.Extendee = message
Damien Neil993c04d2018-09-14 15:41:11 -0700775 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700776 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700777}
778
Joe Tsai7762ec22019-08-20 20:10:23 -0700779// A Oneof describes a message oneof.
Damien Neil1fa78d82018-09-13 13:12:36 -0700780type Oneof struct {
781 Desc protoreflect.OneofDescriptor
782
Joe Tsaief6e5242019-08-21 00:55:36 -0700783 // GoName is the base name of this oneof's Go field and methods.
784 // For code generated by protoc-gen-go, this means a field named
785 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
786 GoName string // e.g., "OneofName"
787
788 // GoIdent is the base name of a top-level declaration for this oneof.
789 GoIdent GoIdent // e.g., "MessageName_OneofName"
Joe Tsai7762ec22019-08-20 20:10:23 -0700790
791 Parent *Message // message in which this oneof is declared
792
Joe Tsaid24bc722019-04-15 23:39:09 -0700793 Fields []*Field // fields that are part of this oneof
794
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700795 Location Location // location of this oneof
796 Comments CommentSet // comments associated with this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700797}
798
799func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700800 loc := message.Location.appendPath(genid.DescriptorProto_OneofDecl_field_number, desc.Index())
Joe Tsai2e7817f2019-08-23 12:18:57 -0700801 camelCased := strs.GoCamelCase(string(desc.Name()))
Joe Tsaief6e5242019-08-21 00:55:36 -0700802 parentPrefix := message.GoIdent.GoName + "_"
Damien Neil1fa78d82018-09-13 13:12:36 -0700803 return &Oneof{
Joe Tsaief6e5242019-08-21 00:55:36 -0700804 Desc: desc,
805 Parent: message,
806 GoName: camelCased,
807 GoIdent: GoIdent{
808 GoImportPath: f.GoImportPath,
809 GoName: parentPrefix + camelCased,
810 },
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700811 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700812 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil1fa78d82018-09-13 13:12:36 -0700813 }
814}
815
Joe Tsai7762ec22019-08-20 20:10:23 -0700816// Extension is an alias of Field for documentation.
817type Extension = Field
Damien Neil220c2022018-08-15 11:24:18 -0700818
Damien Neil2dc67182018-09-21 15:03:34 -0700819// A Service describes a service.
820type Service struct {
821 Desc protoreflect.ServiceDescriptor
822
Joe Tsai7762ec22019-08-20 20:10:23 -0700823 GoName string
824
825 Methods []*Method // service method declarations
Joe Tsaid24bc722019-04-15 23:39:09 -0700826
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700827 Location Location // location of this service
828 Comments CommentSet // comments associated with this service
Damien Neil2dc67182018-09-21 15:03:34 -0700829}
830
831func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700832 loc := f.location.appendPath(genid.FileDescriptorProto_Service_field_number, desc.Index())
Damien Neil2dc67182018-09-21 15:03:34 -0700833 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700834 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700835 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700836 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700837 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil2dc67182018-09-21 15:03:34 -0700838 }
Joe Tsai7762ec22019-08-20 20:10:23 -0700839 for i, mds := 0, desc.Methods(); i < mds.Len(); i++ {
840 service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i)))
Damien Neil2dc67182018-09-21 15:03:34 -0700841 }
842 return service
843}
844
845// A Method describes a method in a service.
846type Method struct {
847 Desc protoreflect.MethodDescriptor
848
Joe Tsaid24bc722019-04-15 23:39:09 -0700849 GoName string
Joe Tsai7762ec22019-08-20 20:10:23 -0700850
851 Parent *Service // service in which this method is declared
852
Joe Tsaid24bc722019-04-15 23:39:09 -0700853 Input *Message
854 Output *Message
855
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700856 Location Location // location of this method
857 Comments CommentSet // comments associated with this method
Damien Neil2dc67182018-09-21 15:03:34 -0700858}
859
860func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
Joe Tsai42cc4c52020-06-16 08:48:38 -0700861 loc := service.Location.appendPath(genid.ServiceDescriptorProto_Method_field_number, desc.Index())
Damien Neil2dc67182018-09-21 15:03:34 -0700862 method := &Method{
Joe Tsaid24bc722019-04-15 23:39:09 -0700863 Desc: desc,
Joe Tsai2e7817f2019-08-23 12:18:57 -0700864 GoName: strs.GoCamelCase(string(desc.Name())),
Joe Tsaid24bc722019-04-15 23:39:09 -0700865 Parent: service,
Joe Tsai70fdd5d2019-08-06 01:15:18 -0700866 Location: loc,
Joe Tsai42cc4c52020-06-16 08:48:38 -0700867 Comments: makeCommentSet(f.Desc.SourceLocations().ByDescriptor(desc)),
Damien Neil2dc67182018-09-21 15:03:34 -0700868 }
869 return method
870}
871
Joe Tsai7762ec22019-08-20 20:10:23 -0700872func (method *Method) resolveDependencies(gen *Plugin) error {
Damien Neil2dc67182018-09-21 15:03:34 -0700873 desc := method.Desc
874
Joe Tsaid24bc722019-04-15 23:39:09 -0700875 inName := desc.Input().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700876 in, ok := gen.messagesByName[inName]
877 if !ok {
878 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
879 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700880 method.Input = in
Damien Neil2dc67182018-09-21 15:03:34 -0700881
Joe Tsaid24bc722019-04-15 23:39:09 -0700882 outName := desc.Output().FullName()
Damien Neil2dc67182018-09-21 15:03:34 -0700883 out, ok := gen.messagesByName[outName]
884 if !ok {
885 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
886 }
Joe Tsaid24bc722019-04-15 23:39:09 -0700887 method.Output = out
Damien Neil2dc67182018-09-21 15:03:34 -0700888
889 return nil
890}
891
Damien Neil7bf3ce22018-12-21 15:54:06 -0800892// A GeneratedFile is a generated file.
893type GeneratedFile struct {
894 gen *Plugin
895 skip bool
896 filename string
897 goImportPath GoImportPath
898 buf bytes.Buffer
899 packageNames map[GoImportPath]GoPackageName
900 usedPackageNames map[GoPackageName]bool
901 manualImports map[GoImportPath]bool
902 annotations map[string][]Location
903}
904
905// NewGeneratedFile creates a new generated file with the given filename
906// and import path.
907func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
908 g := &GeneratedFile{
909 gen: gen,
910 filename: filename,
911 goImportPath: goImportPath,
912 packageNames: make(map[GoImportPath]GoPackageName),
913 usedPackageNames: make(map[GoPackageName]bool),
914 manualImports: make(map[GoImportPath]bool),
915 annotations: make(map[string][]Location),
916 }
Joe Tsai124c8122019-01-14 11:48:43 -0800917
918 // All predeclared identifiers in Go are already used.
919 for _, s := range types.Universe.Names() {
920 g.usedPackageNames[GoPackageName(s)] = true
921 }
922
Damien Neil7bf3ce22018-12-21 15:54:06 -0800923 gen.genFiles = append(gen.genFiles, g)
924 return g
925}
926
Damien Neil220c2022018-08-15 11:24:18 -0700927// P prints a line to the generated output. It converts each parameter to a
928// string following the same rules as fmt.Print. It never inserts spaces
929// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700930func (g *GeneratedFile) P(v ...interface{}) {
931 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700932 switch x := x.(type) {
933 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700934 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700935 default:
936 fmt.Fprint(&g.buf, x)
937 }
Damien Neil220c2022018-08-15 11:24:18 -0700938 }
939 fmt.Fprintln(&g.buf)
940}
941
Damien Neil46abb572018-09-07 12:45:37 -0700942// QualifiedGoIdent returns the string to use for a Go identifier.
943//
944// If the identifier is from a different Go package than the generated file,
945// the returned name will be qualified (package.name) and an import statement
946// for the identifier's package will be included in the file.
947func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
948 if ident.GoImportPath == g.goImportPath {
949 return ident.GoName
950 }
951 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
952 return string(packageName) + "." + ident.GoName
953 }
Joe Tsai8b366e82021-03-16 03:20:52 -0700954 packageName := cleanPackageName(path.Base(string(ident.GoImportPath)))
Joe Tsai124c8122019-01-14 11:48:43 -0800955 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700956 packageName = orig + GoPackageName(strconv.Itoa(i))
957 }
958 g.packageNames[ident.GoImportPath] = packageName
959 g.usedPackageNames[packageName] = true
960 return string(packageName) + "." + ident.GoName
961}
962
Damien Neil2e0c3da2018-09-19 12:51:36 -0700963// Import ensures a package is imported by the generated file.
964//
965// Packages referenced by QualifiedGoIdent are automatically imported.
966// Explicitly importing a package with Import is generally only necessary
967// when the import will be blank (import _ "package").
968func (g *GeneratedFile) Import(importPath GoImportPath) {
969 g.manualImports[importPath] = true
970}
971
Damien Neil220c2022018-08-15 11:24:18 -0700972// Write implements io.Writer.
973func (g *GeneratedFile) Write(p []byte) (n int, err error) {
974 return g.buf.Write(p)
975}
976
Damien Neil7bf3ce22018-12-21 15:54:06 -0800977// Skip removes the generated file from the plugin output.
978func (g *GeneratedFile) Skip() {
979 g.skip = true
980}
981
Oscar Söderlund8525b202020-05-06 06:04:40 +0200982// Unskip reverts a previous call to Skip, re-including the generated file in
983// the plugin output.
984func (g *GeneratedFile) Unskip() {
985 g.skip = false
986}
987
Damien Neil162c1272018-10-04 12:42:37 -0700988// Annotate associates a symbol in a generated Go file with a location in a
989// source .proto file.
990//
991// The symbol may refer to a type, constant, variable, function, method, or
992// struct field. The "T.sel" syntax is used to identify the method or field
993// 'sel' on type 'T'.
994func (g *GeneratedFile) Annotate(symbol string, loc Location) {
995 g.annotations[symbol] = append(g.annotations[symbol], loc)
996}
997
Damien Neil7bf3ce22018-12-21 15:54:06 -0800998// Content returns the contents of the generated file.
999func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -07001000 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -07001001 return g.buf.Bytes(), nil
1002 }
1003
1004 // Reformat generated code.
1005 original := g.buf.Bytes()
1006 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -07001007 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -07001008 if err != nil {
1009 // Print out the bad code with line numbers.
1010 // This should never happen in practice, but it can while changing generated code
1011 // so consider this a debugging aid.
1012 var src bytes.Buffer
1013 s := bufio.NewScanner(bytes.NewReader(original))
1014 for line := 1; s.Scan(); line++ {
1015 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
1016 }
Damien Neild9016772018-08-23 14:39:30 -07001017 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -07001018 }
Damien Neild9016772018-08-23 14:39:30 -07001019
Joe Tsaibeda4042019-03-10 16:40:48 -07001020 // Collect a sorted list of all imports.
1021 var importPaths [][2]string
Damien Neil1fa8ab02018-09-27 15:51:05 -07001022 rewriteImport := func(importPath string) string {
1023 if f := g.gen.opts.ImportRewriteFunc; f != nil {
1024 return string(f(GoImportPath(importPath)))
1025 }
1026 return importPath
1027 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001028 for importPath := range g.packageNames {
1029 pkgName := string(g.packageNames[GoImportPath(importPath)])
1030 pkgPath := rewriteImport(string(importPath))
1031 importPaths = append(importPaths, [2]string{pkgName, pkgPath})
Damien Neild9016772018-08-23 14:39:30 -07001032 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001033 for importPath := range g.manualImports {
Joe Tsaibeda4042019-03-10 16:40:48 -07001034 if _, ok := g.packageNames[importPath]; !ok {
1035 pkgPath := rewriteImport(string(importPath))
1036 importPaths = append(importPaths, [2]string{"_", pkgPath})
Damien Neil2e0c3da2018-09-19 12:51:36 -07001037 }
Damien Neil2e0c3da2018-09-19 12:51:36 -07001038 }
Joe Tsaibeda4042019-03-10 16:40:48 -07001039 sort.Slice(importPaths, func(i, j int) bool {
1040 return importPaths[i][1] < importPaths[j][1]
1041 })
1042
1043 // Modify the AST to include a new import block.
1044 if len(importPaths) > 0 {
1045 // Insert block after package statement or
1046 // possible comment attached to the end of the package statement.
1047 pos := file.Package
1048 tokFile := fset.File(file.Package)
1049 pkgLine := tokFile.Line(file.Package)
1050 for _, c := range file.Comments {
1051 if tokFile.Line(c.Pos()) > pkgLine {
1052 break
1053 }
1054 pos = c.End()
1055 }
1056
1057 // Construct the import block.
1058 impDecl := &ast.GenDecl{
1059 Tok: token.IMPORT,
1060 TokPos: pos,
1061 Lparen: pos,
1062 Rparen: pos,
1063 }
1064 for _, importPath := range importPaths {
1065 impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
1066 Name: &ast.Ident{
1067 Name: importPath[0],
1068 NamePos: pos,
1069 },
1070 Path: &ast.BasicLit{
1071 Kind: token.STRING,
1072 Value: strconv.Quote(importPath[1]),
1073 ValuePos: pos,
1074 },
1075 EndPos: pos,
1076 })
1077 }
1078 file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
1079 }
Damien Neild9016772018-08-23 14:39:30 -07001080
Damien Neilc7d07d92018-08-22 13:46:02 -07001081 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -07001082 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -07001083 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -07001084 }
Damien Neilc7d07d92018-08-22 13:46:02 -07001085 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -07001086}
Damien Neilc7d07d92018-08-22 13:46:02 -07001087
Damien Neil162c1272018-10-04 12:42:37 -07001088// metaFile returns the contents of the file's metadata file, which is a
1089// text formatted string of the google.protobuf.GeneratedCodeInfo.
1090func (g *GeneratedFile) metaFile(content []byte) (string, error) {
1091 fset := token.NewFileSet()
1092 astFile, err := parser.ParseFile(fset, "", content, 0)
1093 if err != nil {
1094 return "", err
1095 }
Joe Tsaie1f8d502018-11-26 18:55:29 -08001096 info := &descriptorpb.GeneratedCodeInfo{}
Damien Neil162c1272018-10-04 12:42:37 -07001097
1098 seenAnnotations := make(map[string]bool)
1099 annotate := func(s string, ident *ast.Ident) {
1100 seenAnnotations[s] = true
1101 for _, loc := range g.annotations[s] {
Joe Tsaie1f8d502018-11-26 18:55:29 -08001102 info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
Damien Neila8a2cea2019-07-10 16:17:16 -07001103 SourceFile: proto.String(loc.SourceFile),
Damien Neil162c1272018-10-04 12:42:37 -07001104 Path: loc.Path,
Damien Neila8a2cea2019-07-10 16:17:16 -07001105 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1106 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
Damien Neil162c1272018-10-04 12:42:37 -07001107 })
1108 }
1109 }
1110 for _, decl := range astFile.Decls {
1111 switch decl := decl.(type) {
1112 case *ast.GenDecl:
1113 for _, spec := range decl.Specs {
1114 switch spec := spec.(type) {
1115 case *ast.TypeSpec:
1116 annotate(spec.Name.Name, spec.Name)
Damien Neilae2a5612018-12-12 08:54:57 -08001117 switch st := spec.Type.(type) {
1118 case *ast.StructType:
Damien Neil162c1272018-10-04 12:42:37 -07001119 for _, field := range st.Fields.List {
1120 for _, name := range field.Names {
1121 annotate(spec.Name.Name+"."+name.Name, name)
1122 }
1123 }
Damien Neilae2a5612018-12-12 08:54:57 -08001124 case *ast.InterfaceType:
1125 for _, field := range st.Methods.List {
1126 for _, name := range field.Names {
1127 annotate(spec.Name.Name+"."+name.Name, name)
1128 }
1129 }
Damien Neil162c1272018-10-04 12:42:37 -07001130 }
1131 case *ast.ValueSpec:
1132 for _, name := range spec.Names {
1133 annotate(name.Name, name)
1134 }
1135 }
1136 }
1137 case *ast.FuncDecl:
1138 if decl.Recv == nil {
1139 annotate(decl.Name.Name, decl.Name)
1140 } else {
1141 recv := decl.Recv.List[0].Type
1142 if s, ok := recv.(*ast.StarExpr); ok {
1143 recv = s.X
1144 }
1145 if id, ok := recv.(*ast.Ident); ok {
1146 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1147 }
1148 }
1149 }
1150 }
1151 for a := range g.annotations {
1152 if !seenAnnotations[a] {
1153 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1154 }
1155 }
1156
Damien Neil5c5b5312019-05-14 12:44:37 -07001157 b, err := prototext.Marshal(info)
Joe Tsaif31bf262019-03-18 14:54:34 -07001158 if err != nil {
1159 return "", err
1160 }
1161 return string(b), nil
Damien Neil220c2022018-08-15 11:24:18 -07001162}
Damien Neil082ce922018-09-06 10:23:53 -07001163
Joe Tsai2e7817f2019-08-23 12:18:57 -07001164// A GoIdent is a Go identifier, consisting of a name and import path.
1165// The name is a single identifier and may not be a dot-qualified selector.
1166type GoIdent struct {
1167 GoName string
1168 GoImportPath GoImportPath
1169}
1170
1171func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) }
1172
1173// newGoIdent returns the Go identifier for a descriptor.
1174func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent {
1175 name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".")
1176 return GoIdent{
1177 GoName: strs.GoCamelCase(name),
1178 GoImportPath: f.GoImportPath,
1179 }
1180}
1181
1182// A GoImportPath is the import path of a Go package.
1183// For example: "google.golang.org/protobuf/compiler/protogen"
1184type GoImportPath string
1185
1186func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
1187
1188// Ident returns a GoIdent with s as the GoName and p as the GoImportPath.
1189func (p GoImportPath) Ident(s string) GoIdent {
1190 return GoIdent{GoName: s, GoImportPath: p}
1191}
1192
1193// A GoPackageName is the name of a Go package. e.g., "protobuf".
1194type GoPackageName string
1195
1196// cleanPackageName converts a string to a valid Go package name.
1197func cleanPackageName(name string) GoPackageName {
1198 return GoPackageName(strs.GoSanitized(name))
1199}
1200
Damien Neil082ce922018-09-06 10:23:53 -07001201type pathType int
1202
1203const (
Joe Tsai8b366e82021-03-16 03:20:52 -07001204 pathTypeImport pathType = iota
Damien Neil082ce922018-09-06 10:23:53 -07001205 pathTypeSourceRelative
1206)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001207
Damien Neil162c1272018-10-04 12:42:37 -07001208// A Location is a location in a .proto source file.
1209//
1210// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1211// for details.
1212type Location struct {
1213 SourceFile string
Joe Tsai691d8562019-07-12 17:16:36 -07001214 Path protoreflect.SourcePath
Damien Neil162c1272018-10-04 12:42:37 -07001215}
1216
1217// appendPath add elements to a Location's path, returning a new Location.
Joe Tsai42cc4c52020-06-16 08:48:38 -07001218func (loc Location) appendPath(num protoreflect.FieldNumber, idx int) Location {
1219 loc.Path = append(protoreflect.SourcePath(nil), loc.Path...) // make copy
1220 loc.Path = append(loc.Path, int32(num), int32(idx))
1221 return loc
Damien Neilba1159f2018-10-17 12:53:18 -07001222}
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001223
1224// CommentSet is a set of leading and trailing comments associated
1225// with a .proto descriptor declaration.
1226type CommentSet struct {
1227 LeadingDetached []Comments
1228 Leading Comments
1229 Trailing Comments
1230}
1231
Joe Tsai42cc4c52020-06-16 08:48:38 -07001232func makeCommentSet(loc protoreflect.SourceLocation) CommentSet {
1233 var leadingDetached []Comments
1234 for _, s := range loc.LeadingDetachedComments {
1235 leadingDetached = append(leadingDetached, Comments(s))
1236 }
1237 return CommentSet{
1238 LeadingDetached: leadingDetached,
1239 Leading: Comments(loc.LeadingComments),
1240 Trailing: Comments(loc.TrailingComments),
1241 }
1242}
1243
Joe Tsai70fdd5d2019-08-06 01:15:18 -07001244// Comments is a comments string as provided by protoc.
1245type Comments string
1246
1247// String formats the comments by inserting // to the start of each line,
1248// ensuring that there is a trailing newline.
1249// An empty comment is formatted as an empty string.
1250func (c Comments) String() string {
1251 if c == "" {
1252 return ""
1253 }
1254 var b []byte
1255 for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") {
1256 b = append(b, "//"...)
1257 b = append(b, line...)
1258 b = append(b, "\n"...)
1259 }
1260 return string(b)
1261}