protogen.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. // 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. // Package protogen provides support for writing protoc plugins.
  5. //
  6. // Plugins for protoc, the Protocol Buffers Compiler, are programs which read
  7. // a CodeGeneratorRequest protocol buffer from standard input and write a
  8. // CodeGeneratorResponse protocol buffer to standard output. This package
  9. // provides support for writing plugins which generate Go code.
  10. package protogen
  11. import (
  12. "bufio"
  13. "bytes"
  14. "encoding/binary"
  15. "fmt"
  16. "go/ast"
  17. "go/parser"
  18. "go/printer"
  19. "go/token"
  20. "go/types"
  21. "io/ioutil"
  22. "os"
  23. "path"
  24. "path/filepath"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "google.golang.org/protobuf/encoding/prototext"
  29. "google.golang.org/protobuf/internal/fieldnum"
  30. "google.golang.org/protobuf/internal/scalar"
  31. "google.golang.org/protobuf/proto"
  32. "google.golang.org/protobuf/reflect/protodesc"
  33. "google.golang.org/protobuf/reflect/protoreflect"
  34. "google.golang.org/protobuf/reflect/protoregistry"
  35. "google.golang.org/protobuf/types/descriptorpb"
  36. "google.golang.org/protobuf/types/pluginpb"
  37. )
  38. // Run executes a function as a protoc plugin.
  39. //
  40. // It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin
  41. // function, and writes a CodeGeneratorResponse message to os.Stdout.
  42. //
  43. // If a failure occurs while reading or writing, Run prints an error to
  44. // os.Stderr and calls os.Exit(1).
  45. //
  46. // Passing a nil options is equivalent to passing a zero-valued one.
  47. func Run(opts *Options, f func(*Plugin) error) {
  48. if err := run(opts, f); err != nil {
  49. fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
  50. os.Exit(1)
  51. }
  52. }
  53. func run(opts *Options, f func(*Plugin) error) error {
  54. if len(os.Args) > 1 {
  55. return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
  56. }
  57. in, err := ioutil.ReadAll(os.Stdin)
  58. if err != nil {
  59. return err
  60. }
  61. req := &pluginpb.CodeGeneratorRequest{}
  62. if err := proto.Unmarshal(in, req); err != nil {
  63. return err
  64. }
  65. gen, err := New(req, opts)
  66. if err != nil {
  67. return err
  68. }
  69. if err := f(gen); err != nil {
  70. // Errors from the plugin function are reported by setting the
  71. // error field in the CodeGeneratorResponse.
  72. //
  73. // In contrast, errors that indicate a problem in protoc
  74. // itself (unparsable input, I/O errors, etc.) are reported
  75. // to stderr.
  76. gen.Error(err)
  77. }
  78. resp := gen.Response()
  79. out, err := proto.Marshal(resp)
  80. if err != nil {
  81. return err
  82. }
  83. if _, err := os.Stdout.Write(out); err != nil {
  84. return err
  85. }
  86. return nil
  87. }
  88. // A Plugin is a protoc plugin invocation.
  89. type Plugin struct {
  90. // Request is the CodeGeneratorRequest provided by protoc.
  91. Request *pluginpb.CodeGeneratorRequest
  92. // Files is the set of files to generate and everything they import.
  93. // Files appear in topological order, so each file appears before any
  94. // file that imports it.
  95. Files []*File
  96. filesByName map[string]*File
  97. fileReg *protoregistry.Files
  98. messagesByName map[protoreflect.FullName]*Message
  99. enumsByName map[protoreflect.FullName]*Enum
  100. annotateCode bool
  101. pathType pathType
  102. genFiles []*GeneratedFile
  103. opts *Options
  104. err error
  105. }
  106. // Options are optional parameters to New.
  107. type Options struct {
  108. // If ParamFunc is non-nil, it will be called with each unknown
  109. // generator parameter.
  110. //
  111. // Plugins for protoc can accept parameters from the command line,
  112. // passed in the --<lang>_out protoc, separated from the output
  113. // directory with a colon; e.g.,
  114. //
  115. // --go_out=<param1>=<value1>,<param2>=<value2>:<output_directory>
  116. //
  117. // Parameters passed in this fashion as a comma-separated list of
  118. // key=value pairs will be passed to the ParamFunc.
  119. //
  120. // The (flag.FlagSet).Set method matches this function signature,
  121. // so parameters can be converted into flags as in the following:
  122. //
  123. // var flags flag.FlagSet
  124. // value := flags.Bool("param", false, "")
  125. // opts := &protogen.Options{
  126. // ParamFunc: flags.Set,
  127. // }
  128. // protogen.Run(opts, func(p *protogen.Plugin) error {
  129. // if *value { ... }
  130. // })
  131. ParamFunc func(name, value string) error
  132. // ImportRewriteFunc is called with the import path of each package
  133. // imported by a generated file. It returns the import path to use
  134. // for this package.
  135. ImportRewriteFunc func(GoImportPath) GoImportPath
  136. }
  137. // New returns a new Plugin.
  138. //
  139. // Passing a nil Options is equivalent to passing a zero-valued one.
  140. func New(req *pluginpb.CodeGeneratorRequest, opts *Options) (*Plugin, error) {
  141. if opts == nil {
  142. opts = &Options{}
  143. }
  144. gen := &Plugin{
  145. Request: req,
  146. filesByName: make(map[string]*File),
  147. fileReg: protoregistry.NewFiles(),
  148. messagesByName: make(map[protoreflect.FullName]*Message),
  149. enumsByName: make(map[protoreflect.FullName]*Enum),
  150. opts: opts,
  151. }
  152. packageNames := make(map[string]GoPackageName) // filename -> package name
  153. importPaths := make(map[string]GoImportPath) // filename -> import path
  154. var packageImportPath GoImportPath
  155. for _, param := range strings.Split(req.GetParameter(), ",") {
  156. var value string
  157. if i := strings.Index(param, "="); i >= 0 {
  158. value = param[i+1:]
  159. param = param[0:i]
  160. }
  161. switch param {
  162. case "":
  163. // Ignore.
  164. case "import_path":
  165. packageImportPath = GoImportPath(value)
  166. case "paths":
  167. switch value {
  168. case "import":
  169. gen.pathType = pathTypeImport
  170. case "source_relative":
  171. gen.pathType = pathTypeSourceRelative
  172. default:
  173. return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value)
  174. }
  175. case "annotate_code":
  176. switch value {
  177. case "true", "":
  178. gen.annotateCode = true
  179. case "false":
  180. default:
  181. return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param)
  182. }
  183. default:
  184. if param[0] == 'M' {
  185. importPaths[param[1:]] = GoImportPath(value)
  186. continue
  187. }
  188. if opts.ParamFunc != nil {
  189. if err := opts.ParamFunc(param, value); err != nil {
  190. return nil, err
  191. }
  192. }
  193. }
  194. }
  195. // Figure out the import path and package name for each file.
  196. //
  197. // The rules here are complicated and have grown organically over time.
  198. // Interactions between different ways of specifying package information
  199. // may be surprising.
  200. //
  201. // The recommended approach is to include a go_package option in every
  202. // .proto source file specifying the full import path of the Go package
  203. // associated with this file.
  204. //
  205. // option go_package = "github.com/golang/protobuf/ptypes/any";
  206. //
  207. // Build systems which want to exert full control over import paths may
  208. // specify M<filename>=<import_path> flags.
  209. //
  210. // Other approaches are not recommend.
  211. generatedFileNames := make(map[string]bool)
  212. for _, name := range gen.Request.FileToGenerate {
  213. generatedFileNames[name] = true
  214. }
  215. // We need to determine the import paths before the package names,
  216. // because the Go package name for a file is sometimes derived from
  217. // different file in the same package.
  218. packageNameForImportPath := make(map[GoImportPath]GoPackageName)
  219. for _, fdesc := range gen.Request.ProtoFile {
  220. filename := fdesc.GetName()
  221. packageName, importPath := goPackageOption(fdesc)
  222. switch {
  223. case importPaths[filename] != "":
  224. // Command line: M=foo.proto=quux/bar
  225. //
  226. // Explicit mapping of source file to import path.
  227. case generatedFileNames[filename] && packageImportPath != "":
  228. // Command line: import_path=quux/bar
  229. //
  230. // The import_path flag sets the import path for every file that
  231. // we generate code for.
  232. importPaths[filename] = packageImportPath
  233. case importPath != "":
  234. // Source file: option go_package = "quux/bar";
  235. //
  236. // The go_package option sets the import path. Most users should use this.
  237. importPaths[filename] = importPath
  238. default:
  239. // Source filename.
  240. //
  241. // Last resort when nothing else is available.
  242. importPaths[filename] = GoImportPath(path.Dir(filename))
  243. }
  244. if packageName != "" {
  245. packageNameForImportPath[importPaths[filename]] = packageName
  246. }
  247. }
  248. for _, fdesc := range gen.Request.ProtoFile {
  249. filename := fdesc.GetName()
  250. packageName, _ := goPackageOption(fdesc)
  251. defaultPackageName := packageNameForImportPath[importPaths[filename]]
  252. switch {
  253. case packageName != "":
  254. // Source file: option go_package = "quux/bar";
  255. packageNames[filename] = packageName
  256. case defaultPackageName != "":
  257. // A go_package option in another file in the same package.
  258. //
  259. // This is a poor choice in general, since every source file should
  260. // contain a go_package option. Supported mainly for historical
  261. // compatibility.
  262. packageNames[filename] = defaultPackageName
  263. case generatedFileNames[filename] && packageImportPath != "":
  264. // Command line: import_path=quux/bar
  265. packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath)))
  266. case fdesc.GetPackage() != "":
  267. // Source file: package quux.bar;
  268. packageNames[filename] = cleanPackageName(fdesc.GetPackage())
  269. default:
  270. // Source filename.
  271. packageNames[filename] = cleanPackageName(baseName(filename))
  272. }
  273. }
  274. // Consistency check: Every file with the same Go import path should have
  275. // the same Go package name.
  276. packageFiles := make(map[GoImportPath][]string)
  277. for filename, importPath := range importPaths {
  278. if _, ok := packageNames[filename]; !ok {
  279. // Skip files mentioned in a M<file>=<import_path> parameter
  280. // but which do not appear in the CodeGeneratorRequest.
  281. continue
  282. }
  283. packageFiles[importPath] = append(packageFiles[importPath], filename)
  284. }
  285. for importPath, filenames := range packageFiles {
  286. for i := 1; i < len(filenames); i++ {
  287. if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b {
  288. return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)",
  289. importPath, a, filenames[0], b, filenames[i])
  290. }
  291. }
  292. }
  293. for _, fdesc := range gen.Request.ProtoFile {
  294. filename := fdesc.GetName()
  295. if gen.filesByName[filename] != nil {
  296. return nil, fmt.Errorf("duplicate file name: %q", filename)
  297. }
  298. f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename])
  299. if err != nil {
  300. return nil, err
  301. }
  302. gen.Files = append(gen.Files, f)
  303. gen.filesByName[filename] = f
  304. }
  305. for _, filename := range gen.Request.FileToGenerate {
  306. f, ok := gen.FileByName(filename)
  307. if !ok {
  308. return nil, fmt.Errorf("no descriptor for generated file: %v", filename)
  309. }
  310. f.Generate = true
  311. }
  312. return gen, nil
  313. }
  314. // Error records an error in code generation. The generator will report the
  315. // error back to protoc and will not produce output.
  316. func (gen *Plugin) Error(err error) {
  317. if gen.err == nil {
  318. gen.err = err
  319. }
  320. }
  321. // Response returns the generator output.
  322. func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse {
  323. resp := &pluginpb.CodeGeneratorResponse{}
  324. if gen.err != nil {
  325. resp.Error = scalar.String(gen.err.Error())
  326. return resp
  327. }
  328. for _, g := range gen.genFiles {
  329. if g.skip {
  330. continue
  331. }
  332. content, err := g.Content()
  333. if err != nil {
  334. return &pluginpb.CodeGeneratorResponse{
  335. Error: scalar.String(err.Error()),
  336. }
  337. }
  338. resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
  339. Name: scalar.String(g.filename),
  340. Content: scalar.String(string(content)),
  341. })
  342. if gen.annotateCode && strings.HasSuffix(g.filename, ".go") {
  343. meta, err := g.metaFile(content)
  344. if err != nil {
  345. return &pluginpb.CodeGeneratorResponse{
  346. Error: scalar.String(err.Error()),
  347. }
  348. }
  349. resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
  350. Name: scalar.String(g.filename + ".meta"),
  351. Content: scalar.String(meta),
  352. })
  353. }
  354. }
  355. return resp
  356. }
  357. // FileByName returns the file with the given name.
  358. func (gen *Plugin) FileByName(name string) (f *File, ok bool) {
  359. f, ok = gen.filesByName[name]
  360. return f, ok
  361. }
  362. // A File describes a .proto source file.
  363. type File struct {
  364. Desc protoreflect.FileDescriptor
  365. Proto *descriptorpb.FileDescriptorProto
  366. GoDescriptorIdent GoIdent // name of Go variable for the file descriptor
  367. GoPackageName GoPackageName // name of this file's Go package
  368. GoImportPath GoImportPath // import path of this file's Go package
  369. Messages []*Message // top-level message declarations
  370. Enums []*Enum // top-level enum declarations
  371. Extensions []*Extension // top-level extension declarations
  372. Services []*Service // top-level service declarations
  373. Generate bool // true if we should generate code for this file
  374. // GeneratedFilenamePrefix is used to construct filenames for generated
  375. // files associated with this source file.
  376. //
  377. // For example, the source file "dir/foo.proto" might have a filename prefix
  378. // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go".
  379. GeneratedFilenamePrefix string
  380. sourceInfo map[pathKey][]*descriptorpb.SourceCodeInfo_Location
  381. }
  382. func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) {
  383. desc, err := protodesc.NewFile(p, gen.fileReg)
  384. if err != nil {
  385. return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err)
  386. }
  387. if err := gen.fileReg.Register(desc); err != nil {
  388. return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err)
  389. }
  390. f := &File{
  391. Desc: desc,
  392. Proto: p,
  393. GoPackageName: packageName,
  394. GoImportPath: importPath,
  395. sourceInfo: make(map[pathKey][]*descriptorpb.SourceCodeInfo_Location),
  396. }
  397. // Determine the prefix for generated Go files.
  398. prefix := p.GetName()
  399. if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" {
  400. prefix = prefix[:len(prefix)-len(ext)]
  401. }
  402. if gen.pathType == pathTypeImport {
  403. // If paths=import (the default) and the file contains a go_package option
  404. // with a full import path, the output filename is derived from the Go import
  405. // path.
  406. //
  407. // Pass the paths=source_relative flag to always derive the output filename
  408. // from the input filename instead.
  409. if _, importPath := goPackageOption(p); importPath != "" {
  410. prefix = path.Join(string(importPath), path.Base(prefix))
  411. }
  412. }
  413. f.GoDescriptorIdent = GoIdent{
  414. GoName: "File_" + cleanGoName(p.GetName()),
  415. GoImportPath: f.GoImportPath,
  416. }
  417. f.GeneratedFilenamePrefix = prefix
  418. for _, loc := range p.GetSourceCodeInfo().GetLocation() {
  419. key := newPathKey(loc.Path)
  420. f.sourceInfo[key] = append(f.sourceInfo[key], loc)
  421. }
  422. for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
  423. f.Messages = append(f.Messages, newMessage(gen, f, nil, mdescs.Get(i)))
  424. }
  425. for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
  426. f.Enums = append(f.Enums, newEnum(gen, f, nil, edescs.Get(i)))
  427. }
  428. for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
  429. f.Extensions = append(f.Extensions, newField(gen, f, nil, extdescs.Get(i)))
  430. }
  431. for i, sdescs := 0, desc.Services(); i < sdescs.Len(); i++ {
  432. f.Services = append(f.Services, newService(gen, f, sdescs.Get(i)))
  433. }
  434. for _, message := range f.Messages {
  435. if err := message.init(gen); err != nil {
  436. return nil, err
  437. }
  438. }
  439. for _, extension := range f.Extensions {
  440. if err := extension.init(gen); err != nil {
  441. return nil, err
  442. }
  443. }
  444. for _, service := range f.Services {
  445. for _, method := range service.Methods {
  446. if err := method.init(gen); err != nil {
  447. return nil, err
  448. }
  449. }
  450. }
  451. return f, nil
  452. }
  453. func (f *File) location(idxPath ...int32) Location {
  454. return Location{
  455. SourceFile: f.Desc.Path(),
  456. Path: idxPath,
  457. }
  458. }
  459. // goPackageOption interprets a file's go_package option.
  460. // If there is no go_package, it returns ("", "").
  461. // If there's a simple name, it returns (pkg, "").
  462. // If the option implies an import path, it returns (pkg, impPath).
  463. func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) {
  464. opt := d.GetOptions().GetGoPackage()
  465. if opt == "" {
  466. return "", ""
  467. }
  468. // A semicolon-delimited suffix delimits the import path and package name.
  469. if i := strings.Index(opt, ";"); i >= 0 {
  470. return cleanPackageName(opt[i+1:]), GoImportPath(opt[:i])
  471. }
  472. // The presence of a slash implies there's an import path.
  473. if i := strings.LastIndex(opt, "/"); i >= 0 {
  474. return cleanPackageName(opt[i+1:]), GoImportPath(opt)
  475. }
  476. return cleanPackageName(opt), ""
  477. }
  478. // A Message describes a message.
  479. type Message struct {
  480. Desc protoreflect.MessageDescriptor
  481. GoIdent GoIdent // name of the generated Go type
  482. Fields []*Field // message field declarations
  483. Oneofs []*Oneof // oneof declarations
  484. Messages []*Message // nested message declarations
  485. Enums []*Enum // nested enum declarations
  486. Extensions []*Extension // nested extension declarations
  487. Location Location // location of this message
  488. }
  489. func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message {
  490. var loc Location
  491. if parent != nil {
  492. loc = parent.Location.appendPath(fieldnum.DescriptorProto_NestedType, int32(desc.Index()))
  493. } else {
  494. loc = f.location(fieldnum.FileDescriptorProto_MessageType, int32(desc.Index()))
  495. }
  496. message := &Message{
  497. Desc: desc,
  498. GoIdent: newGoIdent(f, desc),
  499. Location: loc,
  500. }
  501. gen.messagesByName[desc.FullName()] = message
  502. for i, mdescs := 0, desc.Messages(); i < mdescs.Len(); i++ {
  503. message.Messages = append(message.Messages, newMessage(gen, f, message, mdescs.Get(i)))
  504. }
  505. for i, edescs := 0, desc.Enums(); i < edescs.Len(); i++ {
  506. message.Enums = append(message.Enums, newEnum(gen, f, message, edescs.Get(i)))
  507. }
  508. for i, odescs := 0, desc.Oneofs(); i < odescs.Len(); i++ {
  509. message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, odescs.Get(i)))
  510. }
  511. for i, fdescs := 0, desc.Fields(); i < fdescs.Len(); i++ {
  512. message.Fields = append(message.Fields, newField(gen, f, message, fdescs.Get(i)))
  513. }
  514. for i, extdescs := 0, desc.Extensions(); i < extdescs.Len(); i++ {
  515. message.Extensions = append(message.Extensions, newField(gen, f, message, extdescs.Get(i)))
  516. }
  517. // Field name conflict resolution.
  518. //
  519. // We assume well-known method names that may be attached to a generated
  520. // message type, as well as a 'Get*' method for each field. For each
  521. // field in turn, we add _s to its name until there are no conflicts.
  522. //
  523. // Any change to the following set of method names is a potential
  524. // incompatible API change because it may change generated field names.
  525. //
  526. // TODO: If we ever support a 'go_name' option to set the Go name of a
  527. // field, we should consider dropping this entirely. The conflict
  528. // resolution algorithm is subtle and surprising (changing the order
  529. // in which fields appear in the .proto source file can change the
  530. // names of fields in generated code), and does not adapt well to
  531. // adding new per-field methods such as setters.
  532. usedNames := map[string]bool{
  533. "Reset": true,
  534. "String": true,
  535. "ProtoMessage": true,
  536. "Marshal": true,
  537. "Unmarshal": true,
  538. "ExtensionRangeArray": true,
  539. "ExtensionMap": true,
  540. "Descriptor": true,
  541. }
  542. makeNameUnique := func(name string, hasGetter bool) string {
  543. for usedNames[name] || (hasGetter && usedNames["Get"+name]) {
  544. name += "_"
  545. }
  546. usedNames[name] = true
  547. usedNames["Get"+name] = hasGetter
  548. return name
  549. }
  550. seenOneofs := make(map[int]bool)
  551. for _, field := range message.Fields {
  552. field.GoName = makeNameUnique(field.GoName, true)
  553. if field.Oneof != nil {
  554. if !seenOneofs[field.Oneof.Desc.Index()] {
  555. // If this is a field in a oneof that we haven't seen before,
  556. // make the name for that oneof unique as well.
  557. field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false)
  558. seenOneofs[field.Oneof.Desc.Index()] = true
  559. }
  560. }
  561. }
  562. return message
  563. }
  564. func (message *Message) init(gen *Plugin) error {
  565. for _, child := range message.Messages {
  566. if err := child.init(gen); err != nil {
  567. return err
  568. }
  569. }
  570. for _, field := range message.Fields {
  571. if err := field.init(gen); err != nil {
  572. return err
  573. }
  574. }
  575. for _, oneof := range message.Oneofs {
  576. oneof.init(gen, message)
  577. }
  578. for _, extension := range message.Extensions {
  579. if err := extension.init(gen); err != nil {
  580. return err
  581. }
  582. }
  583. return nil
  584. }
  585. // A Field describes a message field.
  586. type Field struct {
  587. Desc protoreflect.FieldDescriptor
  588. // GoName is the base name of this field's Go field and methods.
  589. // For code generated by protoc-gen-go, this means a field named
  590. // '{{GoName}}' and a getter method named 'Get{{GoName}}'.
  591. GoName string
  592. Parent *Message // message in which this field is defined; nil if top-level extension
  593. Oneof *Oneof // containing oneof; nil if not part of a oneof
  594. Extendee *Message // extended message for extension fields; nil otherwise
  595. Enum *Enum // type for enum fields; nil otherwise
  596. Message *Message // type for message or group fields; nil otherwise
  597. Location Location // location of this field
  598. }
  599. func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field {
  600. var loc Location
  601. switch {
  602. case desc.IsExtension() && message == nil:
  603. loc = f.location(fieldnum.FileDescriptorProto_Extension, int32(desc.Index()))
  604. case desc.IsExtension() && message != nil:
  605. loc = message.Location.appendPath(fieldnum.DescriptorProto_Extension, int32(desc.Index()))
  606. default:
  607. loc = message.Location.appendPath(fieldnum.DescriptorProto_Field, int32(desc.Index()))
  608. }
  609. field := &Field{
  610. Desc: desc,
  611. GoName: camelCase(string(desc.Name())),
  612. Parent: message,
  613. Location: loc,
  614. }
  615. if desc.ContainingOneof() != nil {
  616. field.Oneof = message.Oneofs[desc.ContainingOneof().Index()]
  617. }
  618. return field
  619. }
  620. // Extension is an alias of Field for documentation.
  621. type Extension = Field
  622. func (field *Field) init(gen *Plugin) error {
  623. desc := field.Desc
  624. switch desc.Kind() {
  625. case protoreflect.MessageKind, protoreflect.GroupKind:
  626. mname := desc.Message().FullName()
  627. message, ok := gen.messagesByName[mname]
  628. if !ok {
  629. return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
  630. }
  631. field.Message = message
  632. case protoreflect.EnumKind:
  633. ename := field.Desc.Enum().FullName()
  634. enum, ok := gen.enumsByName[ename]
  635. if !ok {
  636. return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), ename)
  637. }
  638. field.Enum = enum
  639. }
  640. if desc.IsExtension() {
  641. mname := desc.ContainingMessage().FullName()
  642. message, ok := gen.messagesByName[mname]
  643. if !ok {
  644. return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), mname)
  645. }
  646. field.Extendee = message
  647. }
  648. return nil
  649. }
  650. // A Oneof describes a oneof field.
  651. type Oneof struct {
  652. Desc protoreflect.OneofDescriptor
  653. GoName string // Go field name of this oneof
  654. Parent *Message // message in which this oneof occurs
  655. Fields []*Field // fields that are part of this oneof
  656. Location Location // location of this oneof
  657. }
  658. func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof {
  659. return &Oneof{
  660. Desc: desc,
  661. Parent: message,
  662. GoName: camelCase(string(desc.Name())),
  663. Location: message.Location.appendPath(fieldnum.DescriptorProto_OneofDecl, int32(desc.Index())),
  664. }
  665. }
  666. func (oneof *Oneof) init(gen *Plugin, parent *Message) {
  667. for i, fdescs := 0, oneof.Desc.Fields(); i < fdescs.Len(); i++ {
  668. oneof.Fields = append(oneof.Fields, parent.Fields[fdescs.Get(i).Index()])
  669. }
  670. }
  671. // An Enum describes an enum.
  672. type Enum struct {
  673. Desc protoreflect.EnumDescriptor
  674. GoIdent GoIdent // name of the generated Go type
  675. Values []*EnumValue // enum values
  676. Location Location // location of this enum
  677. }
  678. func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum {
  679. var loc Location
  680. if parent != nil {
  681. loc = parent.Location.appendPath(fieldnum.DescriptorProto_EnumType, int32(desc.Index()))
  682. } else {
  683. loc = f.location(fieldnum.FileDescriptorProto_EnumType, int32(desc.Index()))
  684. }
  685. enum := &Enum{
  686. Desc: desc,
  687. GoIdent: newGoIdent(f, desc),
  688. Location: loc,
  689. }
  690. gen.enumsByName[desc.FullName()] = enum
  691. for i, evdescs := 0, enum.Desc.Values(); i < evdescs.Len(); i++ {
  692. enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, evdescs.Get(i)))
  693. }
  694. return enum
  695. }
  696. // An EnumValue describes an enum value.
  697. type EnumValue struct {
  698. Desc protoreflect.EnumValueDescriptor
  699. GoIdent GoIdent // name of the generated Go type
  700. Location Location // location of this enum value
  701. }
  702. func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue {
  703. // A top-level enum value's name is: EnumName_ValueName
  704. // An enum value contained in a message is: MessageName_ValueName
  705. //
  706. // Enum value names are not camelcased.
  707. parentIdent := enum.GoIdent
  708. if message != nil {
  709. parentIdent = message.GoIdent
  710. }
  711. name := parentIdent.GoName + "_" + string(desc.Name())
  712. return &EnumValue{
  713. Desc: desc,
  714. GoIdent: f.GoImportPath.Ident(name),
  715. Location: enum.Location.appendPath(fieldnum.EnumDescriptorProto_Value, int32(desc.Index())),
  716. }
  717. }
  718. // A Service describes a service.
  719. type Service struct {
  720. Desc protoreflect.ServiceDescriptor
  721. GoName string
  722. Methods []*Method // service method definitions
  723. Location Location // location of this service
  724. }
  725. func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service {
  726. service := &Service{
  727. Desc: desc,
  728. GoName: camelCase(string(desc.Name())),
  729. Location: f.location(fieldnum.FileDescriptorProto_Service, int32(desc.Index())),
  730. }
  731. for i, mdescs := 0, desc.Methods(); i < mdescs.Len(); i++ {
  732. service.Methods = append(service.Methods, newMethod(gen, f, service, mdescs.Get(i)))
  733. }
  734. return service
  735. }
  736. // A Method describes a method in a service.
  737. type Method struct {
  738. Desc protoreflect.MethodDescriptor
  739. GoName string
  740. Parent *Service
  741. Input *Message
  742. Output *Message
  743. Location Location // location of this method
  744. }
  745. func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method {
  746. method := &Method{
  747. Desc: desc,
  748. GoName: camelCase(string(desc.Name())),
  749. Parent: service,
  750. Location: service.Location.appendPath(fieldnum.ServiceDescriptorProto_Method, int32(desc.Index())),
  751. }
  752. return method
  753. }
  754. func (method *Method) init(gen *Plugin) error {
  755. desc := method.Desc
  756. inName := desc.Input().FullName()
  757. in, ok := gen.messagesByName[inName]
  758. if !ok {
  759. return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName)
  760. }
  761. method.Input = in
  762. outName := desc.Output().FullName()
  763. out, ok := gen.messagesByName[outName]
  764. if !ok {
  765. return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName)
  766. }
  767. method.Output = out
  768. return nil
  769. }
  770. // A GeneratedFile is a generated file.
  771. type GeneratedFile struct {
  772. gen *Plugin
  773. skip bool
  774. filename string
  775. goImportPath GoImportPath
  776. buf bytes.Buffer
  777. packageNames map[GoImportPath]GoPackageName
  778. usedPackageNames map[GoPackageName]bool
  779. manualImports map[GoImportPath]bool
  780. annotations map[string][]Location
  781. }
  782. // NewGeneratedFile creates a new generated file with the given filename
  783. // and import path.
  784. func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile {
  785. g := &GeneratedFile{
  786. gen: gen,
  787. filename: filename,
  788. goImportPath: goImportPath,
  789. packageNames: make(map[GoImportPath]GoPackageName),
  790. usedPackageNames: make(map[GoPackageName]bool),
  791. manualImports: make(map[GoImportPath]bool),
  792. annotations: make(map[string][]Location),
  793. }
  794. // All predeclared identifiers in Go are already used.
  795. for _, s := range types.Universe.Names() {
  796. g.usedPackageNames[GoPackageName(s)] = true
  797. }
  798. gen.genFiles = append(gen.genFiles, g)
  799. return g
  800. }
  801. // P prints a line to the generated output. It converts each parameter to a
  802. // string following the same rules as fmt.Print. It never inserts spaces
  803. // between parameters.
  804. func (g *GeneratedFile) P(v ...interface{}) {
  805. for _, x := range v {
  806. switch x := x.(type) {
  807. case GoIdent:
  808. fmt.Fprint(&g.buf, g.QualifiedGoIdent(x))
  809. default:
  810. fmt.Fprint(&g.buf, x)
  811. }
  812. }
  813. fmt.Fprintln(&g.buf)
  814. }
  815. // PrintLeadingComments writes the comment appearing before a location in
  816. // the .proto source to the generated file.
  817. //
  818. // It returns true if a comment was present at the location.
  819. func (g *GeneratedFile) PrintLeadingComments(loc Location) (hasComment bool) {
  820. f := g.gen.filesByName[loc.SourceFile]
  821. if f == nil {
  822. return false
  823. }
  824. for _, infoLoc := range f.sourceInfo[newPathKey(loc.Path)] {
  825. if infoLoc.LeadingComments == nil {
  826. continue
  827. }
  828. for _, line := range strings.Split(strings.TrimSuffix(infoLoc.GetLeadingComments(), "\n"), "\n") {
  829. g.buf.WriteString("//")
  830. g.buf.WriteString(line)
  831. g.buf.WriteString("\n")
  832. }
  833. return true
  834. }
  835. return false
  836. }
  837. // QualifiedGoIdent returns the string to use for a Go identifier.
  838. //
  839. // If the identifier is from a different Go package than the generated file,
  840. // the returned name will be qualified (package.name) and an import statement
  841. // for the identifier's package will be included in the file.
  842. func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string {
  843. if ident.GoImportPath == g.goImportPath {
  844. return ident.GoName
  845. }
  846. if packageName, ok := g.packageNames[ident.GoImportPath]; ok {
  847. return string(packageName) + "." + ident.GoName
  848. }
  849. packageName := cleanPackageName(baseName(string(ident.GoImportPath)))
  850. for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ {
  851. packageName = orig + GoPackageName(strconv.Itoa(i))
  852. }
  853. g.packageNames[ident.GoImportPath] = packageName
  854. g.usedPackageNames[packageName] = true
  855. return string(packageName) + "." + ident.GoName
  856. }
  857. // Import ensures a package is imported by the generated file.
  858. //
  859. // Packages referenced by QualifiedGoIdent are automatically imported.
  860. // Explicitly importing a package with Import is generally only necessary
  861. // when the import will be blank (import _ "package").
  862. func (g *GeneratedFile) Import(importPath GoImportPath) {
  863. g.manualImports[importPath] = true
  864. }
  865. // Write implements io.Writer.
  866. func (g *GeneratedFile) Write(p []byte) (n int, err error) {
  867. return g.buf.Write(p)
  868. }
  869. // Skip removes the generated file from the plugin output.
  870. func (g *GeneratedFile) Skip() {
  871. g.skip = true
  872. }
  873. // Annotate associates a symbol in a generated Go file with a location in a
  874. // source .proto file.
  875. //
  876. // The symbol may refer to a type, constant, variable, function, method, or
  877. // struct field. The "T.sel" syntax is used to identify the method or field
  878. // 'sel' on type 'T'.
  879. func (g *GeneratedFile) Annotate(symbol string, loc Location) {
  880. g.annotations[symbol] = append(g.annotations[symbol], loc)
  881. }
  882. // Content returns the contents of the generated file.
  883. func (g *GeneratedFile) Content() ([]byte, error) {
  884. if !strings.HasSuffix(g.filename, ".go") {
  885. return g.buf.Bytes(), nil
  886. }
  887. // Reformat generated code.
  888. original := g.buf.Bytes()
  889. fset := token.NewFileSet()
  890. file, err := parser.ParseFile(fset, "", original, parser.ParseComments)
  891. if err != nil {
  892. // Print out the bad code with line numbers.
  893. // This should never happen in practice, but it can while changing generated code
  894. // so consider this a debugging aid.
  895. var src bytes.Buffer
  896. s := bufio.NewScanner(bytes.NewReader(original))
  897. for line := 1; s.Scan(); line++ {
  898. fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
  899. }
  900. return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String())
  901. }
  902. // Collect a sorted list of all imports.
  903. var importPaths [][2]string
  904. rewriteImport := func(importPath string) string {
  905. if f := g.gen.opts.ImportRewriteFunc; f != nil {
  906. return string(f(GoImportPath(importPath)))
  907. }
  908. return importPath
  909. }
  910. for importPath := range g.packageNames {
  911. pkgName := string(g.packageNames[GoImportPath(importPath)])
  912. pkgPath := rewriteImport(string(importPath))
  913. importPaths = append(importPaths, [2]string{pkgName, pkgPath})
  914. }
  915. for importPath := range g.manualImports {
  916. if _, ok := g.packageNames[importPath]; !ok {
  917. pkgPath := rewriteImport(string(importPath))
  918. importPaths = append(importPaths, [2]string{"_", pkgPath})
  919. }
  920. }
  921. sort.Slice(importPaths, func(i, j int) bool {
  922. return importPaths[i][1] < importPaths[j][1]
  923. })
  924. // Modify the AST to include a new import block.
  925. if len(importPaths) > 0 {
  926. // Insert block after package statement or
  927. // possible comment attached to the end of the package statement.
  928. pos := file.Package
  929. tokFile := fset.File(file.Package)
  930. pkgLine := tokFile.Line(file.Package)
  931. for _, c := range file.Comments {
  932. if tokFile.Line(c.Pos()) > pkgLine {
  933. break
  934. }
  935. pos = c.End()
  936. }
  937. // Construct the import block.
  938. impDecl := &ast.GenDecl{
  939. Tok: token.IMPORT,
  940. TokPos: pos,
  941. Lparen: pos,
  942. Rparen: pos,
  943. }
  944. for _, importPath := range importPaths {
  945. impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{
  946. Name: &ast.Ident{
  947. Name: importPath[0],
  948. NamePos: pos,
  949. },
  950. Path: &ast.BasicLit{
  951. Kind: token.STRING,
  952. Value: strconv.Quote(importPath[1]),
  953. ValuePos: pos,
  954. },
  955. EndPos: pos,
  956. })
  957. }
  958. file.Decls = append([]ast.Decl{impDecl}, file.Decls...)
  959. }
  960. var out bytes.Buffer
  961. if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil {
  962. return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err)
  963. }
  964. return out.Bytes(), nil
  965. }
  966. // metaFile returns the contents of the file's metadata file, which is a
  967. // text formatted string of the google.protobuf.GeneratedCodeInfo.
  968. func (g *GeneratedFile) metaFile(content []byte) (string, error) {
  969. fset := token.NewFileSet()
  970. astFile, err := parser.ParseFile(fset, "", content, 0)
  971. if err != nil {
  972. return "", err
  973. }
  974. info := &descriptorpb.GeneratedCodeInfo{}
  975. seenAnnotations := make(map[string]bool)
  976. annotate := func(s string, ident *ast.Ident) {
  977. seenAnnotations[s] = true
  978. for _, loc := range g.annotations[s] {
  979. info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{
  980. SourceFile: scalar.String(loc.SourceFile),
  981. Path: loc.Path,
  982. Begin: scalar.Int32(int32(fset.Position(ident.Pos()).Offset)),
  983. End: scalar.Int32(int32(fset.Position(ident.End()).Offset)),
  984. })
  985. }
  986. }
  987. for _, decl := range astFile.Decls {
  988. switch decl := decl.(type) {
  989. case *ast.GenDecl:
  990. for _, spec := range decl.Specs {
  991. switch spec := spec.(type) {
  992. case *ast.TypeSpec:
  993. annotate(spec.Name.Name, spec.Name)
  994. switch st := spec.Type.(type) {
  995. case *ast.StructType:
  996. for _, field := range st.Fields.List {
  997. for _, name := range field.Names {
  998. annotate(spec.Name.Name+"."+name.Name, name)
  999. }
  1000. }
  1001. case *ast.InterfaceType:
  1002. for _, field := range st.Methods.List {
  1003. for _, name := range field.Names {
  1004. annotate(spec.Name.Name+"."+name.Name, name)
  1005. }
  1006. }
  1007. }
  1008. case *ast.ValueSpec:
  1009. for _, name := range spec.Names {
  1010. annotate(name.Name, name)
  1011. }
  1012. }
  1013. }
  1014. case *ast.FuncDecl:
  1015. if decl.Recv == nil {
  1016. annotate(decl.Name.Name, decl.Name)
  1017. } else {
  1018. recv := decl.Recv.List[0].Type
  1019. if s, ok := recv.(*ast.StarExpr); ok {
  1020. recv = s.X
  1021. }
  1022. if id, ok := recv.(*ast.Ident); ok {
  1023. annotate(id.Name+"."+decl.Name.Name, decl.Name)
  1024. }
  1025. }
  1026. }
  1027. }
  1028. for a := range g.annotations {
  1029. if !seenAnnotations[a] {
  1030. return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a)
  1031. }
  1032. }
  1033. b, err := prototext.Marshal(info)
  1034. if err != nil {
  1035. return "", err
  1036. }
  1037. return string(b), nil
  1038. }
  1039. type pathType int
  1040. const (
  1041. pathTypeImport pathType = iota
  1042. pathTypeSourceRelative
  1043. )
  1044. // A Location is a location in a .proto source file.
  1045. //
  1046. // See the google.protobuf.SourceCodeInfo documentation in descriptor.proto
  1047. // for details.
  1048. type Location struct {
  1049. SourceFile string
  1050. Path []int32
  1051. }
  1052. // appendPath add elements to a Location's path, returning a new Location.
  1053. func (loc Location) appendPath(a ...int32) Location {
  1054. var n []int32
  1055. n = append(n, loc.Path...)
  1056. n = append(n, a...)
  1057. return Location{
  1058. SourceFile: loc.SourceFile,
  1059. Path: n,
  1060. }
  1061. }
  1062. // A pathKey is a representation of a location path suitable for use as a map key.
  1063. type pathKey struct {
  1064. s string
  1065. }
  1066. // newPathKey converts a location path to a pathKey.
  1067. func newPathKey(idxPath []int32) pathKey {
  1068. buf := make([]byte, 4*len(idxPath))
  1069. for i, x := range idxPath {
  1070. binary.LittleEndian.PutUint32(buf[i*4:], uint32(x))
  1071. }
  1072. return pathKey{string(buf)}
  1073. }