protogen.go 39 KB

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