protogen.go 40 KB

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