blob: 9be2d77314fc7870fd42cde08612795ac78b4cfb [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//
7// Plugins for protoc, the Protocol Buffers Compiler, are programs which read
8// a CodeGeneratorRequest protocol buffer from standard input and write a
9// CodeGeneratorResponse protocol buffer to standard output. This package
10// provides support for writing plugins which generate Go code.
11package 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"
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
30 "github.com/golang/protobuf/proto"
31 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
32 pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
Joe Tsai01ab2962018-09-21 17:44:00 -070033 "github.com/golang/protobuf/v2/reflect/protoreflect"
34 "github.com/golang/protobuf/v2/reflect/protoregistry"
35 "github.com/golang/protobuf/v2/reflect/prototype"
Damien Neild9016772018-08-23 14:39:30 -070036 "golang.org/x/tools/go/ast/astutil"
Damien Neil220c2022018-08-15 11:24:18 -070037)
38
39// Run executes a function as a protoc plugin.
40//
41// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
42// function, and writes a CodeGeneratorResponse message to os.Stdout.
43//
44// If a failure occurs while reading or writing, Run prints an error to
45// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070046//
47// Passing a nil options is equivalent to passing a zero-valued one.
48func Run(opts *Options, f func(*Plugin) error) {
49 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070050 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
51 os.Exit(1)
52 }
53}
54
Damien Neil3cf6e622018-09-11 13:53:14 -070055func run(opts *Options, f func(*Plugin) error) error {
Damien Neild277b522018-10-04 15:30:51 -070056 if len(os.Args) > 1 {
57 return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
58 }
Damien Neil220c2022018-08-15 11:24:18 -070059 in, err := ioutil.ReadAll(os.Stdin)
60 if err != nil {
61 return err
62 }
63 req := &pluginpb.CodeGeneratorRequest{}
64 if err := proto.Unmarshal(in, req); err != nil {
65 return err
66 }
Damien Neil3cf6e622018-09-11 13:53:14 -070067 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070068 if err != nil {
69 return err
70 }
71 if err := f(gen); err != nil {
72 // Errors from the plugin function are reported by setting the
73 // error field in the CodeGeneratorResponse.
74 //
75 // In contrast, errors that indicate a problem in protoc
76 // itself (unparsable input, I/O errors, etc.) are reported
77 // to stderr.
78 gen.Error(err)
79 }
80 resp := gen.Response()
81 out, err := proto.Marshal(resp)
82 if err != nil {
83 return err
84 }
85 if _, err := os.Stdout.Write(out); err != nil {
86 return err
87 }
88 return nil
89}
90
91// A Plugin is a protoc plugin invocation.
92type Plugin struct {
93 // Request is the CodeGeneratorRequest provided by protoc.
94 Request *pluginpb.CodeGeneratorRequest
95
96 // Files is the set of files to generate and everything they import.
97 // Files appear in topological order, so each file appears before any
98 // file that imports it.
99 Files []*File
100 filesByName map[string]*File
101
Damien Neil658051b2018-09-10 12:26:21 -0700102 fileReg *protoregistry.Files
103 messagesByName map[protoreflect.FullName]*Message
104 enumsByName map[protoreflect.FullName]*Enum
Damien Neil162c1272018-10-04 12:42:37 -0700105 annotateCode bool
Damien Neil658051b2018-09-10 12:26:21 -0700106 pathType pathType
107 genFiles []*GeneratedFile
Damien Neil1fa8ab02018-09-27 15:51:05 -0700108 opts *Options
Damien Neil658051b2018-09-10 12:26:21 -0700109 err error
Damien Neil220c2022018-08-15 11:24:18 -0700110}
111
Damien Neil3cf6e622018-09-11 13:53:14 -0700112// Options are optional parameters to New.
113type Options struct {
114 // If ParamFunc is non-nil, it will be called with each unknown
115 // generator parameter.
116 //
117 // Plugins for protoc can accept parameters from the command line,
118 // passed in the --<lang>_out protoc, separated from the output
119 // directory with a colon; e.g.,
120 //
121 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
122 //
123 // Parameters passed in this fashion as a comma-separated list of
124 // key=value pairs will be passed to the ParamFunc.
125 //
126 // The (flag.FlagSet).Set method matches this function signature,
127 // so parameters can be converted into flags as in the following:
128 //
129 // var flags flag.FlagSet
130 // value := flags.Bool("param", false, "")
131 // opts := &protogen.Options{
132 // ParamFunc: flags.Set,
133 // }
134 // protogen.Run(opts, func(p *protogen.Plugin) error {
135 // if *value { ... }
136 // })
137 ParamFunc func(name, value string) error
Damien Neil1fa8ab02018-09-27 15:51:05 -0700138
139 // ImportRewriteFunc is called with the import path of each package
140 // imported by a generated file. It returns the import path to use
141 // for this package.
142 ImportRewriteFunc func(GoImportPath) GoImportPath
Damien Neil3cf6e622018-09-11 13:53:14 -0700143}
144
Damien Neil220c2022018-08-15 11:24:18 -0700145// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700146//
147// Passing a nil Options is equivalent to passing a zero-valued one.
148func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
149 if opts == nil {
150 opts = &Options{}
151 }
Damien Neil220c2022018-08-15 11:24:18 -0700152 gen := &Plugin{
Damien Neil658051b2018-09-10 12:26:21 -0700153 Request: req,
154 filesByName: make(map[string]*File),
155 fileReg: protoregistry.NewFiles(),
156 messagesByName: make(map[protoreflect.FullName]*Message),
157 enumsByName: make(map[protoreflect.FullName]*Enum),
Damien Neil1fa8ab02018-09-27 15:51:05 -0700158 opts: opts,
Damien Neil220c2022018-08-15 11:24:18 -0700159 }
160
Damien Neil082ce922018-09-06 10:23:53 -0700161 packageNames := make(map[string]GoPackageName) // filename -> package name
162 importPaths := make(map[string]GoImportPath) // filename -> import path
163 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)
195 continue
Damien Neil220c2022018-08-15 11:24:18 -0700196 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700197 if opts.ParamFunc != nil {
198 if err := opts.ParamFunc(param, value); err != nil {
199 return nil, err
200 }
201 }
Damien Neil082ce922018-09-06 10:23:53 -0700202 }
203 }
204
205 // Figure out the import path and package name for each file.
206 //
207 // The rules here are complicated and have grown organically over time.
208 // Interactions between different ways of specifying package information
209 // may be surprising.
210 //
211 // The recommended approach is to include a go_package option in every
212 // .proto source file specifying the full import path of the Go package
213 // associated with this file.
214 //
215 // option go_package = "github.com/golang/protobuf/ptypes/any";
216 //
217 // Build systems which want to exert full control over import paths may
218 // specify M<filename>=<import_path> flags.
219 //
220 // Other approaches are not recommend.
221 generatedFileNames := make(map[string]bool)
222 for _, name := range gen.Request.FileToGenerate {
223 generatedFileNames[name] = true
224 }
225 // We need to determine the import paths before the package names,
226 // because the Go package name for a file is sometimes derived from
227 // different file in the same package.
228 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
229 for _, fdesc := range gen.Request.ProtoFile {
230 filename := fdesc.GetName()
231 packageName, importPath := goPackageOption(fdesc)
232 switch {
233 case importPaths[filename] != "":
234 // Command line: M=foo.proto=quux/bar
235 //
236 // Explicit mapping of source file to import path.
237 case generatedFileNames[filename] && packageImportPath != "":
238 // Command line: import_path=quux/bar
239 //
240 // The import_path flag sets the import path for every file that
241 // we generate code for.
242 importPaths[filename] = packageImportPath
243 case importPath != "":
244 // Source file: option go_package = "quux/bar";
245 //
246 // The go_package option sets the import path. Most users should use this.
247 importPaths[filename] = importPath
248 default:
249 // Source filename.
250 //
251 // Last resort when nothing else is available.
252 importPaths[filename] = GoImportPath(path.Dir(filename))
253 }
254 if packageName != "" {
255 packageNameForImportPath[importPaths[filename]] = packageName
256 }
257 }
258 for _, fdesc := range gen.Request.ProtoFile {
259 filename := fdesc.GetName()
260 packageName, _ := goPackageOption(fdesc)
261 defaultPackageName := packageNameForImportPath[importPaths[filename]]
262 switch {
263 case packageName != "":
264 // Source file: option go_package = "quux/bar";
265 packageNames[filename] = packageName
266 case defaultPackageName != "":
267 // A go_package option in another file in the same package.
268 //
269 // This is a poor choice in general, since every source file should
270 // contain a go_package option. Supported mainly for historical
271 // compatibility.
272 packageNames[filename] = defaultPackageName
273 case generatedFileNames[filename] && packageImportPath != "":
274 // Command line: import_path=quux/bar
275 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
276 case fdesc.GetPackage() != "":
277 // Source file: package quux.bar;
278 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
279 default:
280 // Source filename.
281 packageNames[filename] = cleanPackageName(baseName(filename))
282 }
283 }
284
285 // Consistency check: Every file with the same Go import path should have
286 // the same Go package name.
287 packageFiles := make(map[GoImportPath][]string)
288 for filename, importPath := range importPaths {
Damien Neilbbbd38f2018-10-08 16:36:49 -0700289 if _, ok := packageNames[filename]; !ok {
290 // Skip files mentioned in a M<file>=<import_path> parameter
291 // but which do not appear in the CodeGeneratorRequest.
292 continue
293 }
Damien Neil082ce922018-09-06 10:23:53 -0700294 packageFiles[importPath] = append(packageFiles[importPath], filename)
295 }
296 for importPath, filenames := range packageFiles {
297 for i := 1; i < len(filenames); i++ {
298 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
299 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
300 importPath, a, filenames[0], b, filenames[i])
301 }
Damien Neil220c2022018-08-15 11:24:18 -0700302 }
303 }
304
305 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700306 filename := fdesc.GetName()
307 if gen.filesByName[filename] != nil {
308 return nil, fmt.Errorf("duplicate file name: %q", filename)
309 }
310 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700311 if err != nil {
312 return nil, err
313 }
Damien Neil220c2022018-08-15 11:24:18 -0700314 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700315 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700316 }
Damien Neil082ce922018-09-06 10:23:53 -0700317 for _, filename := range gen.Request.FileToGenerate {
318 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700319 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700320 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700321 }
322 f.Generate = true
323 }
324 return gen, nil
325}
326
327// Error records an error in code generation. The generator will report the
328// error back to protoc and will not produce output.
329func (gen *Plugin) Error(err error) {
330 if gen.err == nil {
331 gen.err = err
332 }
333}
334
335// Response returns the generator output.
336func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
337 resp := &pluginpb.CodeGeneratorResponse{}
338 if gen.err != nil {
339 resp.Error = proto.String(gen.err.Error())
340 return resp
341 }
Damien Neil162c1272018-10-04 12:42:37 -0700342 for _, g := range gen.genFiles {
343 content, err := g.content()
Damien Neilc7d07d92018-08-22 13:46:02 -0700344 if err != nil {
345 return &pluginpb.CodeGeneratorResponse{
346 Error: proto.String(err.Error()),
347 }
348 }
Damien Neil220c2022018-08-15 11:24:18 -0700349 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neil162c1272018-10-04 12:42:37 -0700350 Name: proto.String(g.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700351 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700352 })
Damien Neil162c1272018-10-04 12:42:37 -0700353 if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
354 meta, err := g.metaFile(content)
355 if err != nil {
356 return &pluginpb.CodeGeneratorResponse{
357 Error: proto.String(err.Error()),
358 }
359 }
360 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
361 Name: proto.String(g.filename + ".meta"),
362 Content: proto.String(meta),
363 })
364 }
Damien Neil220c2022018-08-15 11:24:18 -0700365 }
366 return resp
367}
368
369// FileByName returns the file with the given name.
370func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
371 f, ok = gen.filesByName[name]
372 return f, ok
373}
374
Damien Neilc7d07d92018-08-22 13:46:02 -0700375// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700376type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700377 Desc protoreflect.FileDescriptor
378 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700379
Damien Neil082ce922018-09-06 10:23:53 -0700380 GoPackageName GoPackageName // name of this file's Go package
381 GoImportPath GoImportPath // import path of this file's Go package
382 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700383 Enums []*Enum // top-level enum declarations
Damien Neil993c04d2018-09-14 15:41:11 -0700384 Extensions []*Extension // top-level extension declarations
Damien Neil2dc67182018-09-21 15:03:34 -0700385 Services []*Service // top-level service declarations
Damien Neil082ce922018-09-06 10:23:53 -0700386 Generate bool // true if we should generate code for this file
387
388 // GeneratedFilenamePrefix is used to construct filenames for generated
389 // files associated with this source file.
390 //
391 // For example, the source file "dir/foo.proto" might have a filename prefix
392 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
393 GeneratedFilenamePrefix string
Damien Neilba1159f2018-10-17 12:53:18 -0700394
395 sourceInfo map[pathKey][]*descpb.SourceCodeInfo_Location
Damien Neil220c2022018-08-15 11:24:18 -0700396}
397
Damien Neil082ce922018-09-06 10:23:53 -0700398func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700399 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
400 if err != nil {
401 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
402 }
403 if err := gen.fileReg.Register(desc); err != nil {
404 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
405 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700406 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700407 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700408 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700409 GoPackageName: packageName,
410 GoImportPath: importPath,
Damien Neilba1159f2018-10-17 12:53:18 -0700411 sourceInfo: make(map[pathKey][]*descpb.SourceCodeInfo_Location),
Damien Neil220c2022018-08-15 11:24:18 -0700412 }
Damien Neil082ce922018-09-06 10:23:53 -0700413
414 // Determine the prefix for generated Go files.
415 prefix := p.GetName()
416 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
417 prefix = prefix[:len(prefix)-len(ext)]
418 }
419 if gen.pathType == pathTypeImport {
420 // If paths=import (the default) and the file contains a go_package option
421 // with a full import path, the output filename is derived from the Go import
422 // path.
423 //
424 // Pass the paths=source_relative flag to always derive the output filename
425 // from the input filename instead.
426 if _, importPath := goPackageOption(p); importPath != "" {
427 prefix = path.Join(string(importPath), path.Base(prefix))
428 }
429 }
430 f.GeneratedFilenamePrefix = prefix
431
Damien Neilba1159f2018-10-17 12:53:18 -0700432 for _, loc := range p.GetSourceCodeInfo().GetLocation() {
433 key := newPathKey(loc.Path)
434 f.sourceInfo[key] = append(f.sourceInfo[key], loc)
435 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700436 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700437 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700438 }
Damien Neil46abb572018-09-07 12:45:37 -0700439 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
440 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
441 }
Damien Neil993c04d2018-09-14 15:41:11 -0700442 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
443 f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
444 }
Damien Neil2dc67182018-09-21 15:03:34 -0700445 for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
446 f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
447 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700448 for _, message := range f.Messages {
Damien Neil993c04d2018-09-14 15:41:11 -0700449 if err := message.init(gen); err != nil {
450 return nil, err
451 }
452 }
453 for _, extension := range f.Extensions {
454 if err := extension.init(gen); err != nil {
455 return nil, err
456 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700457 }
Damien Neil2dc67182018-09-21 15:03:34 -0700458 for _, service := range f.Services {
459 for _, method := range service.Methods {
460 if err := method.init(gen); err != nil {
461 return nil, err
462 }
463 }
464 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700465 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700466}
467
Damien Neil162c1272018-10-04 12:42:37 -0700468func (f *File) location(path ...int32) Location {
469 return Location{
470 SourceFile: f.Desc.Path(),
471 Path: path,
472 }
473}
474
Damien Neil082ce922018-09-06 10:23:53 -0700475// goPackageOption interprets a file's go_package option.
476// If there is no go_package, it returns ("", "").
477// If there's a simple name, it returns (pkg, "").
478// If the option implies an import path, it returns (pkg, impPath).
479func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
480 opt := d.GetOptions().GetGoPackage()
481 if opt == "" {
482 return "", ""
483 }
484 // A semicolon-delimited suffix delimits the import path and package name.
485 if i := strings.Index(opt, ";"); i >= 0 {
486 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
487 }
488 // The presence of a slash implies there's an import path.
489 if i := strings.LastIndex(opt, "/"); i >= 0 {
490 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
491 }
492 return cleanPackageName(opt), ""
493}
494
Damien Neilc7d07d92018-08-22 13:46:02 -0700495// A Message describes a message.
496type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700497 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700498
Damien Neil993c04d2018-09-14 15:41:11 -0700499 GoIdent GoIdent // name of the generated Go type
500 Fields []*Field // message field declarations
501 Oneofs []*Oneof // oneof declarations
502 Messages []*Message // nested message declarations
503 Enums []*Enum // nested enum declarations
504 Extensions []*Extension // nested extension declarations
Damien Neil162c1272018-10-04 12:42:37 -0700505 Location Location // location of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700506}
507
Damien Neil1fa78d82018-09-13 13:12:36 -0700508func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
Damien Neil162c1272018-10-04 12:42:37 -0700509 var loc Location
Damien Neilcab8dfe2018-09-06 14:51:28 -0700510 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700511 loc = parent.Location.appendPath(messageMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700512 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700513 loc = f.location(fileMessageField, int32(desc.Index()))
Damien Neilcab8dfe2018-09-06 14:51:28 -0700514 }
Damien Neil46abb572018-09-07 12:45:37 -0700515 message := &Message{
Damien Neil162c1272018-10-04 12:42:37 -0700516 Desc: desc,
517 GoIdent: newGoIdent(f, desc),
518 Location: loc,
Damien Neilc7d07d92018-08-22 13:46:02 -0700519 }
Damien Neil658051b2018-09-10 12:26:21 -0700520 gen.messagesByName[desc.FullName()] = message
Damien Neilabc6fc12018-08-23 14:39:30 -0700521 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700522 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700523 }
Damien Neil46abb572018-09-07 12:45:37 -0700524 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
525 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
526 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700527 for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
528 message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
529 }
Damien Neil658051b2018-09-10 12:26:21 -0700530 for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
Damien Neil1fa78d82018-09-13 13:12:36 -0700531 message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
Damien Neil658051b2018-09-10 12:26:21 -0700532 }
Damien Neil993c04d2018-09-14 15:41:11 -0700533 for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
534 message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
535 }
Damien Neil658051b2018-09-10 12:26:21 -0700536
537 // Field name conflict resolution.
538 //
539 // We assume well-known method names that may be attached to a generated
540 // message type, as well as a 'Get*' method for each field. For each
541 // field in turn, we add _s to its name until there are no conflicts.
542 //
543 // Any change to the following set of method names is a potential
544 // incompatible API change because it may change generated field names.
545 //
546 // TODO: If we ever support a 'go_name' option to set the Go name of a
547 // field, we should consider dropping this entirely. The conflict
548 // resolution algorithm is subtle and surprising (changing the order
549 // in which fields appear in the .proto source file can change the
550 // names of fields in generated code), and does not adapt well to
551 // adding new per-field methods such as setters.
552 usedNames := map[string]bool{
553 "Reset": true,
554 "String": true,
555 "ProtoMessage": true,
556 "Marshal": true,
557 "Unmarshal": true,
558 "ExtensionRangeArray": true,
559 "ExtensionMap": true,
560 "Descriptor": true,
561 }
562 makeNameUnique := func(name string) string {
563 for usedNames[name] || usedNames["Get"+name] {
564 name += "_"
565 }
566 usedNames[name] = true
567 usedNames["Get"+name] = true
568 return name
569 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700570 seenOneofs := make(map[int]bool)
Damien Neil658051b2018-09-10 12:26:21 -0700571 for _, field := range message.Fields {
Damien Neil1fa78d82018-09-13 13:12:36 -0700572 field.GoName = makeNameUnique(field.GoName)
573 if field.OneofType != nil {
574 if !seenOneofs[field.OneofType.Desc.Index()] {
575 // If this is a field in a oneof that we haven't seen before,
576 // make the name for that oneof unique as well.
577 field.OneofType.GoName = makeNameUnique(field.OneofType.GoName)
578 seenOneofs[field.OneofType.Desc.Index()] = true
579 }
580 }
Damien Neil658051b2018-09-10 12:26:21 -0700581 }
582
Damien Neil1fa78d82018-09-13 13:12:36 -0700583 return message
Damien Neil658051b2018-09-10 12:26:21 -0700584}
585
Damien Neil0bd5a382018-09-13 15:07:10 -0700586func (message *Message) init(gen *Plugin) error {
587 for _, child := range message.Messages {
588 if err := child.init(gen); err != nil {
589 return err
590 }
591 }
592 for _, field := range message.Fields {
593 if err := field.init(gen); err != nil {
594 return err
595 }
596 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700597 for _, oneof := range message.Oneofs {
598 oneof.init(gen, message)
599 }
Damien Neil993c04d2018-09-14 15:41:11 -0700600 for _, extension := range message.Extensions {
601 if err := extension.init(gen); err != nil {
602 return err
603 }
604 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700605 return nil
606}
607
Damien Neil658051b2018-09-10 12:26:21 -0700608// A Field describes a message field.
609type Field struct {
610 Desc protoreflect.FieldDescriptor
611
Damien Neil1fa78d82018-09-13 13:12:36 -0700612 // GoName is the base name of this field's Go field and methods.
Damien Neil658051b2018-09-10 12:26:21 -0700613 // For code generated by protoc-gen-go, this means a field named
Damien Neil1fa78d82018-09-13 13:12:36 -0700614 // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
615 GoName string
Damien Neil658051b2018-09-10 12:26:21 -0700616
Damien Neil993c04d2018-09-14 15:41:11 -0700617 ParentMessage *Message // message in which this field is defined; nil if top-level extension
618 ExtendedType *Message // extended message for extension fields; nil otherwise
619 MessageType *Message // type for message or group fields; nil otherwise
620 EnumType *Enum // type for enum fields; nil otherwise
621 OneofType *Oneof // containing oneof; nil if not part of a oneof
Damien Neil162c1272018-10-04 12:42:37 -0700622 Location Location // location of this field
Damien Neil658051b2018-09-10 12:26:21 -0700623}
624
Damien Neil1fa78d82018-09-13 13:12:36 -0700625func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
Damien Neil162c1272018-10-04 12:42:37 -0700626 var loc Location
Damien Neil993c04d2018-09-14 15:41:11 -0700627 switch {
628 case desc.ExtendedType() != nil && message == nil:
Damien Neil162c1272018-10-04 12:42:37 -0700629 loc = f.location(fileExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700630 case desc.ExtendedType() != nil && message != nil:
Damien Neil162c1272018-10-04 12:42:37 -0700631 loc = message.Location.appendPath(messageExtensionField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700632 default:
Damien Neil162c1272018-10-04 12:42:37 -0700633 loc = message.Location.appendPath(messageFieldField, int32(desc.Index()))
Damien Neil993c04d2018-09-14 15:41:11 -0700634 }
Damien Neil658051b2018-09-10 12:26:21 -0700635 field := &Field{
Damien Neil993c04d2018-09-14 15:41:11 -0700636 Desc: desc,
637 GoName: camelCase(string(desc.Name())),
638 ParentMessage: message,
Damien Neil162c1272018-10-04 12:42:37 -0700639 Location: loc,
Damien Neil658051b2018-09-10 12:26:21 -0700640 }
Damien Neil1fa78d82018-09-13 13:12:36 -0700641 if desc.OneofType() != nil {
642 field.OneofType = message.Oneofs[desc.OneofType().Index()]
643 }
644 return field
Damien Neil0bd5a382018-09-13 15:07:10 -0700645}
646
Damien Neil993c04d2018-09-14 15:41:11 -0700647// Extension is an alias of Field for documentation.
648type Extension = Field
649
Damien Neil0bd5a382018-09-13 15:07:10 -0700650func (field *Field) init(gen *Plugin) error {
651 desc := field.Desc
Damien Neil658051b2018-09-10 12:26:21 -0700652 switch desc.Kind() {
653 case protoreflect.MessageKind, protoreflect.GroupKind:
654 mname := desc.MessageType().FullName()
655 message, ok := gen.messagesByName[mname]
656 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700657 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
Damien Neil658051b2018-09-10 12:26:21 -0700658 }
659 field.MessageType = message
660 case protoreflect.EnumKind:
Damien Neil0bd5a382018-09-13 15:07:10 -0700661 ename := field.Desc.EnumType().FullName()
Damien Neil658051b2018-09-10 12:26:21 -0700662 enum, ok := gen.enumsByName[ename]
663 if !ok {
Damien Neil0bd5a382018-09-13 15:07:10 -0700664 return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
Damien Neil658051b2018-09-10 12:26:21 -0700665 }
666 field.EnumType = enum
667 }
Damien Neil993c04d2018-09-14 15:41:11 -0700668 if desc.ExtendedType() != nil {
669 mname := desc.ExtendedType().FullName()
670 message, ok := gen.messagesByName[mname]
671 if !ok {
672 return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
673 }
674 field.ExtendedType = message
675 }
Damien Neil0bd5a382018-09-13 15:07:10 -0700676 return nil
Damien Neil46abb572018-09-07 12:45:37 -0700677}
678
Damien Neil1fa78d82018-09-13 13:12:36 -0700679// A Oneof describes a oneof field.
680type Oneof struct {
681 Desc protoreflect.OneofDescriptor
682
Damien Neil993c04d2018-09-14 15:41:11 -0700683 GoName string // Go field name of this oneof
684 ParentMessage *Message // message in which this oneof occurs
685 Fields []*Field // fields that are part of this oneof
Damien Neil162c1272018-10-04 12:42:37 -0700686 Location Location // location of this oneof
Damien Neil1fa78d82018-09-13 13:12:36 -0700687}
688
689func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
690 return &Oneof{
Damien Neil993c04d2018-09-14 15:41:11 -0700691 Desc: desc,
692 ParentMessage: message,
693 GoName: camelCase(string(desc.Name())),
Damien Neil162c1272018-10-04 12:42:37 -0700694 Location: message.Location.appendPath(messageOneofField, int32(desc.Index())),
Damien Neil1fa78d82018-09-13 13:12:36 -0700695 }
696}
697
698func (oneof *Oneof) init(gen *Plugin, parent *Message) {
699 for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
700 oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
701 }
702}
703
Damien Neil46abb572018-09-07 12:45:37 -0700704// An Enum describes an enum.
705type Enum struct {
706 Desc protoreflect.EnumDescriptor
707
Damien Neil162c1272018-10-04 12:42:37 -0700708 GoIdent GoIdent // name of the generated Go type
709 Values []*EnumValue // enum values
710 Location Location // location of this enum
Damien Neil46abb572018-09-07 12:45:37 -0700711}
712
713func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
Damien Neil162c1272018-10-04 12:42:37 -0700714 var loc Location
Damien Neil46abb572018-09-07 12:45:37 -0700715 if parent != nil {
Damien Neil162c1272018-10-04 12:42:37 -0700716 loc = parent.Location.appendPath(messageEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700717 } else {
Damien Neil162c1272018-10-04 12:42:37 -0700718 loc = f.location(fileEnumField, int32(desc.Index()))
Damien Neil46abb572018-09-07 12:45:37 -0700719 }
720 enum := &Enum{
Damien Neil162c1272018-10-04 12:42:37 -0700721 Desc: desc,
722 GoIdent: newGoIdent(f, desc),
723 Location: loc,
Damien Neil46abb572018-09-07 12:45:37 -0700724 }
Damien Neil658051b2018-09-10 12:26:21 -0700725 gen.enumsByName[desc.FullName()] = enum
Damien Neil46abb572018-09-07 12:45:37 -0700726 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
727 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
728 }
729 return enum
730}
731
732// An EnumValue describes an enum value.
733type EnumValue struct {
734 Desc protoreflect.EnumValueDescriptor
735
Damien Neil162c1272018-10-04 12:42:37 -0700736 GoIdent GoIdent // name of the generated Go type
737 Location Location // location of this enum value
Damien Neil46abb572018-09-07 12:45:37 -0700738}
739
740func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
741 // A top-level enum value's name is: EnumName_ValueName
742 // An enum value contained in a message is: MessageName_ValueName
743 //
744 // Enum value names are not camelcased.
745 parentIdent := enum.GoIdent
746 if message != nil {
747 parentIdent = message.GoIdent
748 }
749 name := parentIdent.GoName + "_" + string(desc.Name())
750 return &EnumValue{
Joe Tsaic1c17aa2018-11-16 11:14:14 -0800751 Desc: desc,
752 GoIdent: f.GoImportPath.Ident(name),
Damien Neil162c1272018-10-04 12:42:37 -0700753 Location: enum.Location.appendPath(enumValueField, int32(desc.Index())),
Damien Neil46abb572018-09-07 12:45:37 -0700754 }
Damien Neil220c2022018-08-15 11:24:18 -0700755}
756
757// A GeneratedFile is a generated file.
758type GeneratedFile struct {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700759 gen *Plugin
Damien Neild9016772018-08-23 14:39:30 -0700760 filename string
761 goImportPath GoImportPath
762 buf bytes.Buffer
763 packageNames map[GoImportPath]GoPackageName
764 usedPackageNames map[GoPackageName]bool
Damien Neil2e0c3da2018-09-19 12:51:36 -0700765 manualImports map[GoImportPath]bool
Damien Neil162c1272018-10-04 12:42:37 -0700766 annotations map[string][]Location
Damien Neil220c2022018-08-15 11:24:18 -0700767}
768
Damien Neild9016772018-08-23 14:39:30 -0700769// NewGeneratedFile creates a new generated file with the given filename
770// and import path.
771func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700772 g := &GeneratedFile{
Damien Neil1fa8ab02018-09-27 15:51:05 -0700773 gen: gen,
Damien Neild9016772018-08-23 14:39:30 -0700774 filename: filename,
775 goImportPath: goImportPath,
776 packageNames: make(map[GoImportPath]GoPackageName),
777 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil2e0c3da2018-09-19 12:51:36 -0700778 manualImports: make(map[GoImportPath]bool),
Damien Neil162c1272018-10-04 12:42:37 -0700779 annotations: make(map[string][]Location),
Damien Neil220c2022018-08-15 11:24:18 -0700780 }
781 gen.genFiles = append(gen.genFiles, g)
782 return g
783}
784
Damien Neil2dc67182018-09-21 15:03:34 -0700785// A Service describes a service.
786type Service struct {
787 Desc protoreflect.ServiceDescriptor
788
Damien Neil162c1272018-10-04 12:42:37 -0700789 GoName string
790 Location Location // location of this service
791 Methods []*Method // service method definitions
Damien Neil2dc67182018-09-21 15:03:34 -0700792}
793
794func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
795 service := &Service{
Damien Neil162c1272018-10-04 12:42:37 -0700796 Desc: desc,
797 GoName: camelCase(string(desc.Name())),
798 Location: f.location(fileServiceField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700799 }
800 for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
801 service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
802 }
803 return service
804}
805
806// A Method describes a method in a service.
807type Method struct {
808 Desc protoreflect.MethodDescriptor
809
810 GoName string
811 ParentService *Service
Damien Neil162c1272018-10-04 12:42:37 -0700812 Location Location // location of this method
Damien Neil2dc67182018-09-21 15:03:34 -0700813 InputType *Message
814 OutputType *Message
815}
816
817func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
818 method := &Method{
819 Desc: desc,
820 GoName: camelCase(string(desc.Name())),
821 ParentService: service,
Damien Neil162c1272018-10-04 12:42:37 -0700822 Location: service.Location.appendPath(serviceMethodField, int32(desc.Index())),
Damien Neil2dc67182018-09-21 15:03:34 -0700823 }
824 return method
825}
826
827func (method *Method) init(gen *Plugin) error {
828 desc := method.Desc
829
830 inName := desc.InputType().FullName()
831 in, ok := gen.messagesByName[inName]
832 if !ok {
833 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
834 }
835 method.InputType = in
836
837 outName := desc.OutputType().FullName()
838 out, ok := gen.messagesByName[outName]
839 if !ok {
840 return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
841 }
842 method.OutputType = out
843
844 return nil
845}
846
Damien Neil220c2022018-08-15 11:24:18 -0700847// P prints a line to the generated output. It converts each parameter to a
848// string following the same rules as fmt.Print. It never inserts spaces
849// between parameters.
Damien Neil220c2022018-08-15 11:24:18 -0700850func (g *GeneratedFile) P(v ...interface{}) {
851 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700852 switch x := x.(type) {
853 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700854 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700855 default:
856 fmt.Fprint(&g.buf, x)
857 }
Damien Neil220c2022018-08-15 11:24:18 -0700858 }
859 fmt.Fprintln(&g.buf)
860}
861
Damien Neilba1159f2018-10-17 12:53:18 -0700862// PrintLeadingComments writes the comment appearing before a location in
863// the .proto source to the generated file.
864//
865// It returns true if a comment was present at the location.
866func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
867 f := g.gen.filesByName[loc.SourceFile]
868 if f == nil {
869 return false
870 }
871 for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
872 if infoLoc.LeadingComments == nil {
873 continue
874 }
875 for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
876 g.buf.WriteString("//")
877 g.buf.WriteString(line)
878 g.buf.WriteString("\n")
879 }
880 return true
881 }
882 return false
883}
884
Damien Neil46abb572018-09-07 12:45:37 -0700885// QualifiedGoIdent returns the string to use for a Go identifier.
886//
887// If the identifier is from a different Go package than the generated file,
888// the returned name will be qualified (package.name) and an import statement
889// for the identifier's package will be included in the file.
890func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
891 if ident.GoImportPath == g.goImportPath {
892 return ident.GoName
893 }
894 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
895 return string(packageName) + "." + ident.GoName
896 }
897 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
Damien Neil87214662018-10-05 11:23:35 -0700898 for i, orig := 1, packageName; g.usedPackageNames[packageName] || isGoPredeclaredIdentifier[string(packageName)]; i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700899 packageName = orig + GoPackageName(strconv.Itoa(i))
900 }
901 g.packageNames[ident.GoImportPath] = packageName
902 g.usedPackageNames[packageName] = true
903 return string(packageName) + "." + ident.GoName
904}
905
Damien Neil2e0c3da2018-09-19 12:51:36 -0700906// Import ensures a package is imported by the generated file.
907//
908// Packages referenced by QualifiedGoIdent are automatically imported.
909// Explicitly importing a package with Import is generally only necessary
910// when the import will be blank (import _ "package").
911func (g *GeneratedFile) Import(importPath GoImportPath) {
912 g.manualImports[importPath] = true
913}
914
Damien Neil220c2022018-08-15 11:24:18 -0700915// Write implements io.Writer.
916func (g *GeneratedFile) Write(p []byte) (n int, err error) {
917 return g.buf.Write(p)
918}
919
Damien Neil162c1272018-10-04 12:42:37 -0700920// Annotate associates a symbol in a generated Go file with a location in a
921// source .proto file.
922//
923// The symbol may refer to a type, constant, variable, function, method, or
924// struct field. The "T.sel" syntax is used to identify the method or field
925// 'sel' on type 'T'.
926func (g *GeneratedFile) Annotate(symbol string, loc Location) {
927 g.annotations[symbol] = append(g.annotations[symbol], loc)
928}
929
930// content returns the contents of the generated file.
931func (g *GeneratedFile) content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700932 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700933 return g.buf.Bytes(), nil
934 }
935
936 // Reformat generated code.
937 original := g.buf.Bytes()
938 fset := token.NewFileSet()
Damien Neil1ec33152018-09-13 13:12:36 -0700939 file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
Damien Neilc7d07d92018-08-22 13:46:02 -0700940 if err != nil {
941 // Print out the bad code with line numbers.
942 // This should never happen in practice, but it can while changing generated code
943 // so consider this a debugging aid.
944 var src bytes.Buffer
945 s := bufio.NewScanner(bytes.NewReader(original))
946 for line := 1; s.Scan(); line++ {
947 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
948 }
Damien Neild9016772018-08-23 14:39:30 -0700949 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700950 }
Damien Neild9016772018-08-23 14:39:30 -0700951
952 // Add imports.
953 var importPaths []string
954 for importPath := range g.packageNames {
955 importPaths = append(importPaths, string(importPath))
956 }
957 sort.Strings(importPaths)
Damien Neil1fa8ab02018-09-27 15:51:05 -0700958 rewriteImport := func(importPath string) string {
959 if f := g.gen.opts.ImportRewriteFunc; f != nil {
960 return string(f(GoImportPath(importPath)))
961 }
962 return importPath
963 }
Damien Neild9016772018-08-23 14:39:30 -0700964 for _, importPath := range importPaths {
Damien Neil1fa8ab02018-09-27 15:51:05 -0700965 astutil.AddNamedImport(fset, file, string(g.packageNames[GoImportPath(importPath)]), rewriteImport(importPath))
Damien Neild9016772018-08-23 14:39:30 -0700966 }
Damien Neil2e0c3da2018-09-19 12:51:36 -0700967 for importPath := range g.manualImports {
968 if _, ok := g.packageNames[importPath]; ok {
969 continue
970 }
Damien Neil329b75e2018-10-04 17:31:07 -0700971 astutil.AddNamedImport(fset, file, "_", rewriteImport(string(importPath)))
Damien Neil2e0c3da2018-09-19 12:51:36 -0700972 }
Damien Neil1ec33152018-09-13 13:12:36 -0700973 ast.SortImports(fset, file)
Damien Neild9016772018-08-23 14:39:30 -0700974
Damien Neilc7d07d92018-08-22 13:46:02 -0700975 var out bytes.Buffer
Damien Neil1ec33152018-09-13 13:12:36 -0700976 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700977 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700978 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700979 return out.Bytes(), nil
Damien Neil162c1272018-10-04 12:42:37 -0700980}
Damien Neilc7d07d92018-08-22 13:46:02 -0700981
Damien Neil162c1272018-10-04 12:42:37 -0700982// metaFile returns the contents of the file's metadata file, which is a
983// text formatted string of the google.protobuf.GeneratedCodeInfo.
984func (g *GeneratedFile) metaFile(content []byte) (string, error) {
985 fset := token.NewFileSet()
986 astFile, err := parser.ParseFile(fset, "", content, 0)
987 if err != nil {
988 return "", err
989 }
990 info := &descpb.GeneratedCodeInfo{}
991
992 seenAnnotations := make(map[string]bool)
993 annotate := func(s string, ident *ast.Ident) {
994 seenAnnotations[s] = true
995 for _, loc := range g.annotations[s] {
996 info.Annotation = append(info.Annotation, &descpb.GeneratedCodeInfo_Annotation{
997 SourceFile: proto.String(loc.SourceFile),
998 Path: loc.Path,
999 Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)),
1000 End: proto.Int32(int32(fset.Position(ident.End()).Offset)),
1001 })
1002 }
1003 }
1004 for _, decl := range astFile.Decls {
1005 switch decl := decl.(type) {
1006 case *ast.GenDecl:
1007 for _, spec := range decl.Specs {
1008 switch spec := spec.(type) {
1009 case *ast.TypeSpec:
1010 annotate(spec.Name.Name, spec.Name)
1011 if st, ok := spec.Type.(*ast.StructType); ok {
1012 for _, field := range st.Fields.List {
1013 for _, name := range field.Names {
1014 annotate(spec.Name.Name+"."+name.Name, name)
1015 }
1016 }
1017 }
1018 case *ast.ValueSpec:
1019 for _, name := range spec.Names {
1020 annotate(name.Name, name)
1021 }
1022 }
1023 }
1024 case *ast.FuncDecl:
1025 if decl.Recv == nil {
1026 annotate(decl.Name.Name, decl.Name)
1027 } else {
1028 recv := decl.Recv.List[0].Type
1029 if s, ok := recv.(*ast.StarExpr); ok {
1030 recv = s.X
1031 }
1032 if id, ok := recv.(*ast.Ident); ok {
1033 annotate(id.Name+"."+decl.Name.Name, decl.Name)
1034 }
1035 }
1036 }
1037 }
1038 for a := range g.annotations {
1039 if !seenAnnotations[a] {
1040 return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
1041 }
1042 }
1043
1044 return proto.CompactTextString(info), nil
Damien Neil220c2022018-08-15 11:24:18 -07001045}
Damien Neil082ce922018-09-06 10:23:53 -07001046
1047type pathType int
1048
1049const (
1050 pathTypeImport pathType = iota
1051 pathTypeSourceRelative
1052)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001053
1054// The SourceCodeInfo message describes the location of elements of a parsed
1055// .proto file by way of a "path", which is a sequence of integers that
1056// describe the route from a FileDescriptorProto to the relevant submessage.
1057// The path alternates between a field number of a repeated field, and an index
1058// into that repeated field. The constants below define the field numbers that
1059// are used.
1060//
1061// See descriptor.proto for more information about this.
1062const (
1063 // field numbers in FileDescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001064 filePackageField = 2 // package
1065 fileMessageField = 4 // message_type
1066 fileEnumField = 5 // enum_type
Damien Neil2dc67182018-09-21 15:03:34 -07001067 fileServiceField = 6 // service
Damien Neil993c04d2018-09-14 15:41:11 -07001068 fileExtensionField = 7 // extension
Damien Neilcab8dfe2018-09-06 14:51:28 -07001069 // field numbers in DescriptorProto
Damien Neil993c04d2018-09-14 15:41:11 -07001070 messageFieldField = 2 // field
1071 messageMessageField = 3 // nested_type
1072 messageEnumField = 4 // enum_type
1073 messageExtensionField = 6 // extension
1074 messageOneofField = 8 // oneof_decl
Damien Neilcab8dfe2018-09-06 14:51:28 -07001075 // field numbers in EnumDescriptorProto
1076 enumValueField = 2 // value
Damien Neil2dc67182018-09-21 15:03:34 -07001077 // field numbers in ServiceDescriptorProto
1078 serviceMethodField = 2 // method
1079 serviceStreamField = 4 // stream
Damien Neilcab8dfe2018-09-06 14:51:28 -07001080)
1081
Damien Neil162c1272018-10-04 12:42:37 -07001082// A Location is a location in a .proto source file.
1083//
1084// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
1085// for details.
1086type Location struct {
1087 SourceFile string
1088 Path []int32
1089}
1090
1091// appendPath add elements to a Location's path, returning a new Location.
1092func (loc Location) appendPath(a ...int32) Location {
Damien Neilcab8dfe2018-09-06 14:51:28 -07001093 var n []int32
Damien Neil162c1272018-10-04 12:42:37 -07001094 n = append(n, loc.Path...)
Damien Neilcab8dfe2018-09-06 14:51:28 -07001095 n = append(n, a...)
Damien Neil162c1272018-10-04 12:42:37 -07001096 return Location{
1097 SourceFile: loc.SourceFile,
1098 Path: n,
1099 }
Damien Neilcab8dfe2018-09-06 14:51:28 -07001100}
Damien Neilba1159f2018-10-17 12:53:18 -07001101
1102// A pathKey is a representation of a location path suitable for use as a map key.
1103type pathKey struct {
1104 s string
1105}
1106
1107// newPathKey converts a location path to a pathKey.
1108func newPathKey(path []int32) pathKey {
1109 buf := make([]byte, 4*len(path))
1110 for i, x := range path {
1111 binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
1112 }
1113 return pathKey{string(buf)}
1114}