protogen.go 42 KB

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