protogen.go 43 KB

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