blob: ee4c73588846bedf77ff205b7a3b46ffc9af00cb [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"
16 "fmt"
Damien Neilc7d07d92018-08-22 13:46:02 -070017 "go/parser"
18 "go/printer"
19 "go/token"
Damien Neil220c2022018-08-15 11:24:18 -070020 "io/ioutil"
21 "os"
Damien Neil082ce922018-09-06 10:23:53 -070022 "path"
Damien Neil220c2022018-08-15 11:24:18 -070023 "path/filepath"
Damien Neild9016772018-08-23 14:39:30 -070024 "sort"
25 "strconv"
Damien Neil220c2022018-08-15 11:24:18 -070026 "strings"
27
28 "github.com/golang/protobuf/proto"
29 descpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
30 pluginpb "github.com/golang/protobuf/protoc-gen-go/plugin"
Damien Neild9016772018-08-23 14:39:30 -070031 "golang.org/x/tools/go/ast/astutil"
Damien Neilabc6fc12018-08-23 14:39:30 -070032 "google.golang.org/proto/reflect/protoreflect"
33 "google.golang.org/proto/reflect/protoregistry"
34 "google.golang.org/proto/reflect/prototype"
Damien Neil220c2022018-08-15 11:24:18 -070035)
36
37// Run executes a function as a protoc plugin.
38//
39// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
40// function, and writes a CodeGeneratorResponse message to os.Stdout.
41//
42// If a failure occurs while reading or writing, Run prints an error to
43// os.Stderr and calls os.Exit(1).
Damien Neil3cf6e622018-09-11 13:53:14 -070044//
45// Passing a nil options is equivalent to passing a zero-valued one.
46func Run(opts *Options, f func(*Plugin) error) {
47 if err := run(opts, f); err != nil {
Damien Neil220c2022018-08-15 11:24:18 -070048 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
49 os.Exit(1)
50 }
51}
52
Damien Neil3cf6e622018-09-11 13:53:14 -070053func run(opts *Options, f func(*Plugin) error) error {
Damien Neil220c2022018-08-15 11:24:18 -070054 in, err := ioutil.ReadAll(os.Stdin)
55 if err != nil {
56 return err
57 }
58 req := &pluginpb.CodeGeneratorRequest{}
59 if err := proto.Unmarshal(in, req); err != nil {
60 return err
61 }
Damien Neil3cf6e622018-09-11 13:53:14 -070062 gen, err := New(req, opts)
Damien Neil220c2022018-08-15 11:24:18 -070063 if err != nil {
64 return err
65 }
66 if err := f(gen); err != nil {
67 // Errors from the plugin function are reported by setting the
68 // error field in the CodeGeneratorResponse.
69 //
70 // In contrast, errors that indicate a problem in protoc
71 // itself (unparsable input, I/O errors, etc.) are reported
72 // to stderr.
73 gen.Error(err)
74 }
75 resp := gen.Response()
76 out, err := proto.Marshal(resp)
77 if err != nil {
78 return err
79 }
80 if _, err := os.Stdout.Write(out); err != nil {
81 return err
82 }
83 return nil
84}
85
86// A Plugin is a protoc plugin invocation.
87type Plugin struct {
88 // Request is the CodeGeneratorRequest provided by protoc.
89 Request *pluginpb.CodeGeneratorRequest
90
91 // Files is the set of files to generate and everything they import.
92 // Files appear in topological order, so each file appears before any
93 // file that imports it.
94 Files []*File
95 filesByName map[string]*File
96
Damien Neil082ce922018-09-06 10:23:53 -070097 fileReg *protoregistry.Files
98 pathType pathType
Damien Neil220c2022018-08-15 11:24:18 -070099 genFiles []*GeneratedFile
100 err error
101}
102
Damien Neil3cf6e622018-09-11 13:53:14 -0700103// Options are optional parameters to New.
104type Options struct {
105 // If ParamFunc is non-nil, it will be called with each unknown
106 // generator parameter.
107 //
108 // Plugins for protoc can accept parameters from the command line,
109 // passed in the --<lang>_out protoc, separated from the output
110 // directory with a colon; e.g.,
111 //
112 // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
113 //
114 // Parameters passed in this fashion as a comma-separated list of
115 // key=value pairs will be passed to the ParamFunc.
116 //
117 // The (flag.FlagSet).Set method matches this function signature,
118 // so parameters can be converted into flags as in the following:
119 //
120 // var flags flag.FlagSet
121 // value := flags.Bool("param", false, "")
122 // opts := &protogen.Options{
123 // ParamFunc: flags.Set,
124 // }
125 // protogen.Run(opts, func(p *protogen.Plugin) error {
126 // if *value { ... }
127 // })
128 ParamFunc func(name, value string) error
129}
130
Damien Neil220c2022018-08-15 11:24:18 -0700131// New returns a new Plugin.
Damien Neil3cf6e622018-09-11 13:53:14 -0700132//
133// Passing a nil Options is equivalent to passing a zero-valued one.
134func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
135 if opts == nil {
136 opts = &Options{}
137 }
Damien Neil220c2022018-08-15 11:24:18 -0700138 gen := &Plugin{
139 Request: req,
140 filesByName: make(map[string]*File),
Damien Neilabc6fc12018-08-23 14:39:30 -0700141 fileReg: protoregistry.NewFiles(),
Damien Neil220c2022018-08-15 11:24:18 -0700142 }
143
Damien Neil082ce922018-09-06 10:23:53 -0700144 packageNames := make(map[string]GoPackageName) // filename -> package name
145 importPaths := make(map[string]GoImportPath) // filename -> import path
146 var packageImportPath GoImportPath
Damien Neil220c2022018-08-15 11:24:18 -0700147 for _, param := range strings.Split(req.GetParameter(), ",") {
148 var value string
149 if i := strings.Index(param, "="); i >= 0 {
150 value = param[i+1:]
151 param = param[0:i]
152 }
153 switch param {
154 case "":
155 // Ignore.
156 case "import_prefix":
157 // TODO
158 case "import_path":
Damien Neil082ce922018-09-06 10:23:53 -0700159 packageImportPath = GoImportPath(value)
Damien Neil220c2022018-08-15 11:24:18 -0700160 case "paths":
Damien Neil082ce922018-09-06 10:23:53 -0700161 switch value {
162 case "import":
163 gen.pathType = pathTypeImport
164 case "source_relative":
165 gen.pathType = pathTypeSourceRelative
166 default:
167 return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
168 }
Damien Neil220c2022018-08-15 11:24:18 -0700169 case "annotate_code":
170 // TODO
171 default:
Damien Neil3cf6e622018-09-11 13:53:14 -0700172 if param[0] == 'M' {
173 importPaths[param[1:]] = GoImportPath(value)
174 continue
Damien Neil220c2022018-08-15 11:24:18 -0700175 }
Damien Neil3cf6e622018-09-11 13:53:14 -0700176 if opts.ParamFunc != nil {
177 if err := opts.ParamFunc(param, value); err != nil {
178 return nil, err
179 }
180 }
Damien Neil082ce922018-09-06 10:23:53 -0700181 }
182 }
183
184 // Figure out the import path and package name for each file.
185 //
186 // The rules here are complicated and have grown organically over time.
187 // Interactions between different ways of specifying package information
188 // may be surprising.
189 //
190 // The recommended approach is to include a go_package option in every
191 // .proto source file specifying the full import path of the Go package
192 // associated with this file.
193 //
194 // option go_package = "github.com/golang/protobuf/ptypes/any";
195 //
196 // Build systems which want to exert full control over import paths may
197 // specify M<filename>=<import_path> flags.
198 //
199 // Other approaches are not recommend.
200 generatedFileNames := make(map[string]bool)
201 for _, name := range gen.Request.FileToGenerate {
202 generatedFileNames[name] = true
203 }
204 // We need to determine the import paths before the package names,
205 // because the Go package name for a file is sometimes derived from
206 // different file in the same package.
207 packageNameForImportPath := make(map[GoImportPath]GoPackageName)
208 for _, fdesc := range gen.Request.ProtoFile {
209 filename := fdesc.GetName()
210 packageName, importPath := goPackageOption(fdesc)
211 switch {
212 case importPaths[filename] != "":
213 // Command line: M=foo.proto=quux/bar
214 //
215 // Explicit mapping of source file to import path.
216 case generatedFileNames[filename] && packageImportPath != "":
217 // Command line: import_path=quux/bar
218 //
219 // The import_path flag sets the import path for every file that
220 // we generate code for.
221 importPaths[filename] = packageImportPath
222 case importPath != "":
223 // Source file: option go_package = "quux/bar";
224 //
225 // The go_package option sets the import path. Most users should use this.
226 importPaths[filename] = importPath
227 default:
228 // Source filename.
229 //
230 // Last resort when nothing else is available.
231 importPaths[filename] = GoImportPath(path.Dir(filename))
232 }
233 if packageName != "" {
234 packageNameForImportPath[importPaths[filename]] = packageName
235 }
236 }
237 for _, fdesc := range gen.Request.ProtoFile {
238 filename := fdesc.GetName()
239 packageName, _ := goPackageOption(fdesc)
240 defaultPackageName := packageNameForImportPath[importPaths[filename]]
241 switch {
242 case packageName != "":
243 // Source file: option go_package = "quux/bar";
244 packageNames[filename] = packageName
245 case defaultPackageName != "":
246 // A go_package option in another file in the same package.
247 //
248 // This is a poor choice in general, since every source file should
249 // contain a go_package option. Supported mainly for historical
250 // compatibility.
251 packageNames[filename] = defaultPackageName
252 case generatedFileNames[filename] && packageImportPath != "":
253 // Command line: import_path=quux/bar
254 packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
255 case fdesc.GetPackage() != "":
256 // Source file: package quux.bar;
257 packageNames[filename] = cleanPackageName(fdesc.GetPackage())
258 default:
259 // Source filename.
260 packageNames[filename] = cleanPackageName(baseName(filename))
261 }
262 }
263
264 // Consistency check: Every file with the same Go import path should have
265 // the same Go package name.
266 packageFiles := make(map[GoImportPath][]string)
267 for filename, importPath := range importPaths {
268 packageFiles[importPath] = append(packageFiles[importPath], filename)
269 }
270 for importPath, filenames := range packageFiles {
271 for i := 1; i < len(filenames); i++ {
272 if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
273 return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
274 importPath, a, filenames[0], b, filenames[i])
275 }
Damien Neil220c2022018-08-15 11:24:18 -0700276 }
277 }
278
279 for _, fdesc := range gen.Request.ProtoFile {
Damien Neil082ce922018-09-06 10:23:53 -0700280 filename := fdesc.GetName()
281 if gen.filesByName[filename] != nil {
282 return nil, fmt.Errorf("duplicate file name: %q", filename)
283 }
284 f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
Damien Neilabc6fc12018-08-23 14:39:30 -0700285 if err != nil {
286 return nil, err
287 }
Damien Neil220c2022018-08-15 11:24:18 -0700288 gen.Files = append(gen.Files, f)
Damien Neil082ce922018-09-06 10:23:53 -0700289 gen.filesByName[filename] = f
Damien Neil220c2022018-08-15 11:24:18 -0700290 }
Damien Neil082ce922018-09-06 10:23:53 -0700291 for _, filename := range gen.Request.FileToGenerate {
292 f, ok := gen.FileByName(filename)
Damien Neil220c2022018-08-15 11:24:18 -0700293 if !ok {
Damien Neil082ce922018-09-06 10:23:53 -0700294 return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
Damien Neil220c2022018-08-15 11:24:18 -0700295 }
296 f.Generate = true
297 }
298 return gen, nil
299}
300
301// Error records an error in code generation. The generator will report the
302// error back to protoc and will not produce output.
303func (gen *Plugin) Error(err error) {
304 if gen.err == nil {
305 gen.err = err
306 }
307}
308
309// Response returns the generator output.
310func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
311 resp := &pluginpb.CodeGeneratorResponse{}
312 if gen.err != nil {
313 resp.Error = proto.String(gen.err.Error())
314 return resp
315 }
316 for _, gf := range gen.genFiles {
Damien Neilc7d07d92018-08-22 13:46:02 -0700317 content, err := gf.Content()
318 if err != nil {
319 return &pluginpb.CodeGeneratorResponse{
320 Error: proto.String(err.Error()),
321 }
322 }
Damien Neil220c2022018-08-15 11:24:18 -0700323 resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Damien Neild9016772018-08-23 14:39:30 -0700324 Name: proto.String(gf.filename),
Damien Neilc7d07d92018-08-22 13:46:02 -0700325 Content: proto.String(string(content)),
Damien Neil220c2022018-08-15 11:24:18 -0700326 })
327 }
328 return resp
329}
330
331// FileByName returns the file with the given name.
332func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
333 f, ok = gen.filesByName[name]
334 return f, ok
335}
336
Damien Neilc7d07d92018-08-22 13:46:02 -0700337// A File describes a .proto source file.
Damien Neil220c2022018-08-15 11:24:18 -0700338type File struct {
Damien Neil7779e052018-09-07 14:14:06 -0700339 Desc protoreflect.FileDescriptor
340 Proto *descpb.FileDescriptorProto
Damien Neil220c2022018-08-15 11:24:18 -0700341
Damien Neil082ce922018-09-06 10:23:53 -0700342 GoPackageName GoPackageName // name of this file's Go package
343 GoImportPath GoImportPath // import path of this file's Go package
344 Messages []*Message // top-level message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700345 Enums []*Enum // top-level enum declarations
Damien Neil082ce922018-09-06 10:23:53 -0700346 Generate bool // true if we should generate code for this file
347
348 // GeneratedFilenamePrefix is used to construct filenames for generated
349 // files associated with this source file.
350 //
351 // For example, the source file "dir/foo.proto" might have a filename prefix
352 // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
353 GeneratedFilenamePrefix string
Damien Neil220c2022018-08-15 11:24:18 -0700354}
355
Damien Neil082ce922018-09-06 10:23:53 -0700356func newFile(gen *Plugin, p *descpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
Damien Neilabc6fc12018-08-23 14:39:30 -0700357 desc, err := prototype.NewFileFromDescriptorProto(p, gen.fileReg)
358 if err != nil {
359 return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
360 }
361 if err := gen.fileReg.Register(desc); err != nil {
362 return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
363 }
Damien Neilc7d07d92018-08-22 13:46:02 -0700364 f := &File{
Damien Neil082ce922018-09-06 10:23:53 -0700365 Desc: desc,
Damien Neil7779e052018-09-07 14:14:06 -0700366 Proto: p,
Damien Neil082ce922018-09-06 10:23:53 -0700367 GoPackageName: packageName,
368 GoImportPath: importPath,
Damien Neil220c2022018-08-15 11:24:18 -0700369 }
Damien Neil082ce922018-09-06 10:23:53 -0700370
371 // Determine the prefix for generated Go files.
372 prefix := p.GetName()
373 if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
374 prefix = prefix[:len(prefix)-len(ext)]
375 }
376 if gen.pathType == pathTypeImport {
377 // If paths=import (the default) and the file contains a go_package option
378 // with a full import path, the output filename is derived from the Go import
379 // path.
380 //
381 // Pass the paths=source_relative flag to always derive the output filename
382 // from the input filename instead.
383 if _, importPath := goPackageOption(p); importPath != "" {
384 prefix = path.Join(string(importPath), path.Base(prefix))
385 }
386 }
387 f.GeneratedFilenamePrefix = prefix
388
Damien Neilabc6fc12018-08-23 14:39:30 -0700389 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neilcab8dfe2018-09-06 14:51:28 -0700390 f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700391 }
Damien Neil46abb572018-09-07 12:45:37 -0700392 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
393 f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
394 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700395 return f, nil
Damien Neilc7d07d92018-08-22 13:46:02 -0700396}
397
Damien Neil082ce922018-09-06 10:23:53 -0700398// goPackageOption interprets a file's go_package option.
399// If there is no go_package, it returns ("", "").
400// If there's a simple name, it returns (pkg, "").
401// If the option implies an import path, it returns (pkg, impPath).
402func goPackageOption(d *descpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
403 opt := d.GetOptions().GetGoPackage()
404 if opt == "" {
405 return "", ""
406 }
407 // A semicolon-delimited suffix delimits the import path and package name.
408 if i := strings.Index(opt, ";"); i >= 0 {
409 return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
410 }
411 // The presence of a slash implies there's an import path.
412 if i := strings.LastIndex(opt, "/"); i >= 0 {
413 return cleanPackageName(opt[i+1:]), GoImportPath(opt)
414 }
415 return cleanPackageName(opt), ""
416}
417
Damien Neilc7d07d92018-08-22 13:46:02 -0700418// A Message describes a message.
419type Message struct {
Damien Neilabc6fc12018-08-23 14:39:30 -0700420 Desc protoreflect.MessageDescriptor
Damien Neilc7d07d92018-08-22 13:46:02 -0700421
422 GoIdent GoIdent // name of the generated Go type
423 Messages []*Message // nested message declarations
Damien Neil46abb572018-09-07 12:45:37 -0700424 Enums []*Enum // nested enum declarations
Damien Neilcab8dfe2018-09-06 14:51:28 -0700425 Path []int32 // location path of this message
Damien Neilc7d07d92018-08-22 13:46:02 -0700426}
427
Damien Neilcab8dfe2018-09-06 14:51:28 -0700428func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
429 var path []int32
430 if parent != nil {
431 path = pathAppend(parent.Path, messageMessageField, int32(desc.Index()))
432 } else {
433 path = []int32{fileMessageField, int32(desc.Index())}
434 }
Damien Neil46abb572018-09-07 12:45:37 -0700435 message := &Message{
Damien Neilabc6fc12018-08-23 14:39:30 -0700436 Desc: desc,
437 GoIdent: newGoIdent(f, desc),
Damien Neilcab8dfe2018-09-06 14:51:28 -0700438 Path: path,
Damien Neilc7d07d92018-08-22 13:46:02 -0700439 }
Damien Neilabc6fc12018-08-23 14:39:30 -0700440 for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
Damien Neil46abb572018-09-07 12:45:37 -0700441 message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
Damien Neilc7d07d92018-08-22 13:46:02 -0700442 }
Damien Neil46abb572018-09-07 12:45:37 -0700443 for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
444 message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
445 }
446 return message
447}
448
449// An Enum describes an enum.
450type Enum struct {
451 Desc protoreflect.EnumDescriptor
452
453 GoIdent GoIdent // name of the generated Go type
454 Values []*EnumValue // enum values
455 Path []int32 // location path of this enum
456}
457
458func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
459 var path []int32
460 if parent != nil {
461 path = pathAppend(parent.Path, messageEnumField, int32(desc.Index()))
462 } else {
463 path = []int32{fileEnumField, int32(desc.Index())}
464 }
465 enum := &Enum{
466 Desc: desc,
467 GoIdent: newGoIdent(f, desc),
468 Path: path,
469 }
470 for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
471 enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
472 }
473 return enum
474}
475
476// An EnumValue describes an enum value.
477type EnumValue struct {
478 Desc protoreflect.EnumValueDescriptor
479
480 GoIdent GoIdent // name of the generated Go type
481 Path []int32 // location path of this enum value
482}
483
484func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
485 // A top-level enum value's name is: EnumName_ValueName
486 // An enum value contained in a message is: MessageName_ValueName
487 //
488 // Enum value names are not camelcased.
489 parentIdent := enum.GoIdent
490 if message != nil {
491 parentIdent = message.GoIdent
492 }
493 name := parentIdent.GoName + "_" + string(desc.Name())
494 return &EnumValue{
495 Desc: desc,
496 GoIdent: GoIdent{
497 GoName: name,
498 GoImportPath: f.GoImportPath,
499 },
500 Path: pathAppend(enum.Path, enumValueField, int32(desc.Index())),
501 }
Damien Neil220c2022018-08-15 11:24:18 -0700502}
503
504// A GeneratedFile is a generated file.
505type GeneratedFile struct {
Damien Neild9016772018-08-23 14:39:30 -0700506 filename string
507 goImportPath GoImportPath
508 buf bytes.Buffer
509 packageNames map[GoImportPath]GoPackageName
510 usedPackageNames map[GoPackageName]bool
Damien Neil220c2022018-08-15 11:24:18 -0700511}
512
Damien Neild9016772018-08-23 14:39:30 -0700513// NewGeneratedFile creates a new generated file with the given filename
514// and import path.
515func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
Damien Neil220c2022018-08-15 11:24:18 -0700516 g := &GeneratedFile{
Damien Neild9016772018-08-23 14:39:30 -0700517 filename: filename,
518 goImportPath: goImportPath,
519 packageNames: make(map[GoImportPath]GoPackageName),
520 usedPackageNames: make(map[GoPackageName]bool),
Damien Neil220c2022018-08-15 11:24:18 -0700521 }
522 gen.genFiles = append(gen.genFiles, g)
523 return g
524}
525
526// P prints a line to the generated output. It converts each parameter to a
527// string following the same rules as fmt.Print. It never inserts spaces
528// between parameters.
529//
530// TODO: .meta file annotations.
531func (g *GeneratedFile) P(v ...interface{}) {
532 for _, x := range v {
Damien Neild9016772018-08-23 14:39:30 -0700533 switch x := x.(type) {
534 case GoIdent:
Damien Neil46abb572018-09-07 12:45:37 -0700535 fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
Damien Neild9016772018-08-23 14:39:30 -0700536 default:
537 fmt.Fprint(&g.buf, x)
538 }
Damien Neil220c2022018-08-15 11:24:18 -0700539 }
540 fmt.Fprintln(&g.buf)
541}
542
Damien Neil46abb572018-09-07 12:45:37 -0700543// QualifiedGoIdent returns the string to use for a Go identifier.
544//
545// If the identifier is from a different Go package than the generated file,
546// the returned name will be qualified (package.name) and an import statement
547// for the identifier's package will be included in the file.
548func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
549 if ident.GoImportPath == g.goImportPath {
550 return ident.GoName
551 }
552 if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
553 return string(packageName) + "." + ident.GoName
554 }
555 packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
556 for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
557 packageName = orig + GoPackageName(strconv.Itoa(i))
558 }
559 g.packageNames[ident.GoImportPath] = packageName
560 g.usedPackageNames[packageName] = true
561 return string(packageName) + "." + ident.GoName
562}
563
Damien Neild9016772018-08-23 14:39:30 -0700564func (g *GeneratedFile) goPackageName(importPath GoImportPath) GoPackageName {
565 if name, ok := g.packageNames[importPath]; ok {
566 return name
567 }
568 name := cleanPackageName(baseName(string(importPath)))
569 for i, orig := 1, name; g.usedPackageNames[name]; i++ {
570 name = orig + GoPackageName(strconv.Itoa(i))
571 }
572 g.packageNames[importPath] = name
573 g.usedPackageNames[name] = true
574 return name
575}
576
Damien Neil220c2022018-08-15 11:24:18 -0700577// Write implements io.Writer.
578func (g *GeneratedFile) Write(p []byte) (n int, err error) {
579 return g.buf.Write(p)
580}
581
582// Content returns the contents of the generated file.
Damien Neilc7d07d92018-08-22 13:46:02 -0700583func (g *GeneratedFile) Content() ([]byte, error) {
Damien Neild9016772018-08-23 14:39:30 -0700584 if !strings.HasSuffix(g.filename, ".go") {
Damien Neilc7d07d92018-08-22 13:46:02 -0700585 return g.buf.Bytes(), nil
586 }
587
588 // Reformat generated code.
589 original := g.buf.Bytes()
590 fset := token.NewFileSet()
591 ast, err := parser.ParseFile(fset, "", original, parser.ParseComments)
592 if err != nil {
593 // Print out the bad code with line numbers.
594 // This should never happen in practice, but it can while changing generated code
595 // so consider this a debugging aid.
596 var src bytes.Buffer
597 s := bufio.NewScanner(bytes.NewReader(original))
598 for line := 1; s.Scan(); line++ {
599 fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
600 }
Damien Neild9016772018-08-23 14:39:30 -0700601 return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
Damien Neilc7d07d92018-08-22 13:46:02 -0700602 }
Damien Neild9016772018-08-23 14:39:30 -0700603
604 // Add imports.
605 var importPaths []string
606 for importPath := range g.packageNames {
607 importPaths = append(importPaths, string(importPath))
608 }
609 sort.Strings(importPaths)
610 for _, importPath := range importPaths {
611 astutil.AddNamedImport(fset, ast, string(g.packageNames[GoImportPath(importPath)]), importPath)
612 }
613
Damien Neilc7d07d92018-08-22 13:46:02 -0700614 var out bytes.Buffer
615 if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, ast); err != nil {
Damien Neild9016772018-08-23 14:39:30 -0700616 return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
Damien Neilc7d07d92018-08-22 13:46:02 -0700617 }
Damien Neild9016772018-08-23 14:39:30 -0700618 // TODO: Annotations.
Damien Neilc7d07d92018-08-22 13:46:02 -0700619 return out.Bytes(), nil
620
Damien Neil220c2022018-08-15 11:24:18 -0700621}
Damien Neil082ce922018-09-06 10:23:53 -0700622
623type pathType int
624
625const (
626 pathTypeImport pathType = iota
627 pathTypeSourceRelative
628)
Damien Neilcab8dfe2018-09-06 14:51:28 -0700629
630// The SourceCodeInfo message describes the location of elements of a parsed
631// .proto file by way of a "path", which is a sequence of integers that
632// describe the route from a FileDescriptorProto to the relevant submessage.
633// The path alternates between a field number of a repeated field, and an index
634// into that repeated field. The constants below define the field numbers that
635// are used.
636//
637// See descriptor.proto for more information about this.
638const (
639 // field numbers in FileDescriptorProto
640 filePackageField = 2 // package
641 fileMessageField = 4 // message_type
Damien Neil46abb572018-09-07 12:45:37 -0700642 fileEnumField = 5 // enum_type
Damien Neilcab8dfe2018-09-06 14:51:28 -0700643 // field numbers in DescriptorProto
644 messageFieldField = 2 // field
645 messageMessageField = 3 // nested_type
646 messageEnumField = 4 // enum_type
647 messageOneofField = 8 // oneof_decl
648 // field numbers in EnumDescriptorProto
649 enumValueField = 2 // value
650)
651
652// pathAppend appends elements to a location path.
653// It does not alias the original path.
654func pathAppend(path []int32, a ...int32) []int32 {
655 var n []int32
656 n = append(n, path...)
657 n = append(n, a...)
658 return n
659}