protogen.go 35 KB

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