registry.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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 protoregistry provides data structures to register and lookup
  5. // protobuf descriptor types.
  6. //
  7. // The Files registry contains file descriptors and provides the ability
  8. // to iterate over the files or lookup a specific descriptor within the files.
  9. // Files only contains protobuf descriptors and has no understanding of Go
  10. // type information that may be associated with each descriptor.
  11. //
  12. // The Types registry contains descriptor types for which there is a known
  13. // Go type associated with that descriptor. It provides the ability to iterate
  14. // over the registered types or lookup a type by name.
  15. package protoregistry
  16. import (
  17. "fmt"
  18. "log"
  19. "strings"
  20. "sync"
  21. "google.golang.org/protobuf/internal/errors"
  22. "google.golang.org/protobuf/reflect/protoreflect"
  23. )
  24. // ignoreConflict reports whether to ignore a registration conflict
  25. // given the descriptor being registered and the error.
  26. // It is a variable so that the behavior is easily overridden in another file.
  27. var ignoreConflict = func(d protoreflect.Descriptor, err error) bool {
  28. log.Printf(""+
  29. "WARNING: %v\n"+
  30. "A future release will panic on registration conflicts.\n"+
  31. // TODO: Add a URL pointing to documentation on how to resolve conflicts.
  32. "\n", err)
  33. return true
  34. }
  35. var globalMutex sync.RWMutex
  36. // GlobalFiles is a global registry of file descriptors.
  37. var GlobalFiles *Files = new(Files)
  38. // GlobalTypes is the registry used by default for type lookups
  39. // unless a local registry is provided by the user.
  40. var GlobalTypes *Types = new(Types)
  41. // NotFound is a sentinel error value to indicate that the type was not found.
  42. var NotFound = errors.New("not found")
  43. // Files is a registry for looking up or iterating over files and the
  44. // descriptors contained within them.
  45. // The Find and Range methods are safe for concurrent use.
  46. type Files struct {
  47. // The map of descsByName contains:
  48. // EnumDescriptor
  49. // EnumValueDescriptor
  50. // MessageDescriptor
  51. // ExtensionDescriptor
  52. // ServiceDescriptor
  53. // *packageDescriptor
  54. //
  55. // Note that files are stored as a slice, since a package may contain
  56. // multiple files. Only top-level declarations are registered.
  57. // Note that enum values are in the top-level since that are in the same
  58. // scope as the parent enum.
  59. descsByName map[protoreflect.FullName]interface{}
  60. filesByPath map[string]protoreflect.FileDescriptor
  61. }
  62. type packageDescriptor struct {
  63. files []protoreflect.FileDescriptor
  64. }
  65. // NewFiles returns a registry initialized with the provided set of files.
  66. // Files with a namespace conflict with an pre-existing file are not registered.
  67. func NewFiles(files ...protoreflect.FileDescriptor) *Files {
  68. r := new(Files)
  69. r.Register(files...) // ignore errors; first takes precedence
  70. return r
  71. }
  72. // Register registers the provided list of file descriptors.
  73. //
  74. // If any descriptor within a file conflicts with the descriptor of any
  75. // previously registered file (e.g., two enums with the same full name),
  76. // then that file is not registered and an error is returned.
  77. //
  78. // It is permitted for multiple files to have the same file path.
  79. func (r *Files) Register(files ...protoreflect.FileDescriptor) error {
  80. if r == GlobalFiles {
  81. globalMutex.Lock()
  82. defer globalMutex.Unlock()
  83. }
  84. if r.descsByName == nil {
  85. r.descsByName = map[protoreflect.FullName]interface{}{
  86. "": &packageDescriptor{},
  87. }
  88. r.filesByPath = make(map[string]protoreflect.FileDescriptor)
  89. }
  90. var firstErr error
  91. for _, file := range files {
  92. if err := r.registerFile(file); err != nil && firstErr == nil {
  93. firstErr = err
  94. }
  95. }
  96. return firstErr
  97. }
  98. func (r *Files) registerFile(fd protoreflect.FileDescriptor) error {
  99. path := fd.Path()
  100. if prev := r.filesByPath[path]; prev != nil {
  101. err := errors.New("file %q is already registered", fd.Path())
  102. err = amendErrorWithCaller(err, prev, fd)
  103. if r == GlobalFiles && ignoreConflict(fd, err) {
  104. err = nil
  105. }
  106. return err
  107. }
  108. for name := fd.Package(); name != ""; name = name.Parent() {
  109. switch prev := r.descsByName[name]; prev.(type) {
  110. case nil, *packageDescriptor:
  111. default:
  112. err := errors.New("file %q has a package name conflict over %v", fd.Path(), name)
  113. err = amendErrorWithCaller(err, prev, fd)
  114. if r == GlobalFiles && ignoreConflict(fd, err) {
  115. err = nil
  116. }
  117. return err
  118. }
  119. }
  120. var err error
  121. var hasConflict bool
  122. rangeTopLevelDescriptors(fd, func(d protoreflect.Descriptor) {
  123. if prev := r.descsByName[d.FullName()]; prev != nil {
  124. hasConflict = true
  125. err = errors.New("file %q has a name conflict over %v", fd.Path(), d.FullName())
  126. err = amendErrorWithCaller(err, prev, fd)
  127. if r == GlobalFiles && ignoreConflict(d, err) {
  128. err = nil
  129. }
  130. }
  131. })
  132. if hasConflict {
  133. return err
  134. }
  135. for name := fd.Package(); name != ""; name = name.Parent() {
  136. if r.descsByName[name] == nil {
  137. r.descsByName[name] = &packageDescriptor{}
  138. }
  139. }
  140. p := r.descsByName[fd.Package()].(*packageDescriptor)
  141. p.files = append(p.files, fd)
  142. rangeTopLevelDescriptors(fd, func(d protoreflect.Descriptor) {
  143. r.descsByName[d.FullName()] = d
  144. })
  145. r.filesByPath[path] = fd
  146. return nil
  147. }
  148. // FindDescriptorByName looks up a descriptor by the full name.
  149. //
  150. // This returns (nil, NotFound) if not found.
  151. func (r *Files) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) {
  152. if r == nil {
  153. return nil, NotFound
  154. }
  155. if r == GlobalFiles {
  156. globalMutex.RLock()
  157. defer globalMutex.RUnlock()
  158. }
  159. prefix := name
  160. suffix := nameSuffix("")
  161. for prefix != "" {
  162. if d, ok := r.descsByName[prefix]; ok {
  163. switch d := d.(type) {
  164. case protoreflect.EnumDescriptor:
  165. if d.FullName() == name {
  166. return d, nil
  167. }
  168. case protoreflect.EnumValueDescriptor:
  169. if d.FullName() == name {
  170. return d, nil
  171. }
  172. case protoreflect.MessageDescriptor:
  173. if d.FullName() == name {
  174. return d, nil
  175. }
  176. if d := findDescriptorInMessage(d, suffix); d != nil && d.FullName() == name {
  177. return d, nil
  178. }
  179. case protoreflect.ExtensionDescriptor:
  180. if d.FullName() == name {
  181. return d, nil
  182. }
  183. case protoreflect.ServiceDescriptor:
  184. if d.FullName() == name {
  185. return d, nil
  186. }
  187. if d := d.Methods().ByName(suffix.Pop()); d != nil && d.FullName() == name {
  188. return d, nil
  189. }
  190. }
  191. return nil, NotFound
  192. }
  193. prefix = prefix.Parent()
  194. suffix = nameSuffix(name[len(prefix)+len("."):])
  195. }
  196. return nil, NotFound
  197. }
  198. func findDescriptorInMessage(md protoreflect.MessageDescriptor, suffix nameSuffix) protoreflect.Descriptor {
  199. name := suffix.Pop()
  200. if suffix == "" {
  201. if ed := md.Enums().ByName(name); ed != nil {
  202. return ed
  203. }
  204. for i := md.Enums().Len() - 1; i >= 0; i-- {
  205. if vd := md.Enums().Get(i).Values().ByName(name); vd != nil {
  206. return vd
  207. }
  208. }
  209. if xd := md.Extensions().ByName(name); xd != nil {
  210. return xd
  211. }
  212. if fd := md.Fields().ByName(name); fd != nil {
  213. return fd
  214. }
  215. if od := md.Oneofs().ByName(name); od != nil {
  216. return od
  217. }
  218. }
  219. if md := md.Messages().ByName(name); md != nil {
  220. if suffix == "" {
  221. return md
  222. }
  223. return findDescriptorInMessage(md, suffix)
  224. }
  225. return nil
  226. }
  227. type nameSuffix string
  228. func (s *nameSuffix) Pop() (name protoreflect.Name) {
  229. if i := strings.IndexByte(string(*s), '.'); i >= 0 {
  230. name, *s = protoreflect.Name((*s)[:i]), (*s)[i+1:]
  231. } else {
  232. name, *s = protoreflect.Name((*s)), ""
  233. }
  234. return name
  235. }
  236. // FindFileByPath looks up a file by the path.
  237. //
  238. // This returns (nil, NotFound) if not found.
  239. func (r *Files) FindFileByPath(path string) (protoreflect.FileDescriptor, error) {
  240. if r == nil {
  241. return nil, NotFound
  242. }
  243. if r == GlobalFiles {
  244. globalMutex.RLock()
  245. defer globalMutex.RUnlock()
  246. }
  247. if fd, ok := r.filesByPath[path]; ok {
  248. return fd, nil
  249. }
  250. return nil, NotFound
  251. }
  252. // NumFiles reports the number of registered files.
  253. func (r *Files) NumFiles() int {
  254. if r == nil {
  255. return 0
  256. }
  257. if r == GlobalFiles {
  258. globalMutex.RLock()
  259. defer globalMutex.RUnlock()
  260. }
  261. return len(r.filesByPath)
  262. }
  263. // RangeFiles iterates over all registered files.
  264. // The iteration order is undefined.
  265. func (r *Files) RangeFiles(f func(protoreflect.FileDescriptor) bool) {
  266. if r == nil {
  267. return
  268. }
  269. if r == GlobalFiles {
  270. globalMutex.RLock()
  271. defer globalMutex.RUnlock()
  272. }
  273. for _, file := range r.filesByPath {
  274. if !f(file) {
  275. return
  276. }
  277. }
  278. }
  279. // NumFilesByPackage reports the number of registered files in a proto package.
  280. func (r *Files) NumFilesByPackage(name protoreflect.FullName) int {
  281. if r == nil {
  282. return 0
  283. }
  284. if r == GlobalFiles {
  285. globalMutex.RLock()
  286. defer globalMutex.RUnlock()
  287. }
  288. p, ok := r.descsByName[name].(*packageDescriptor)
  289. if !ok {
  290. return 0
  291. }
  292. return len(p.files)
  293. }
  294. // RangeFilesByPackage iterates over all registered files in a give proto package.
  295. // The iteration order is undefined.
  296. func (r *Files) RangeFilesByPackage(name protoreflect.FullName, f func(protoreflect.FileDescriptor) bool) {
  297. if r == nil {
  298. return
  299. }
  300. if r == GlobalFiles {
  301. globalMutex.RLock()
  302. defer globalMutex.RUnlock()
  303. }
  304. p, ok := r.descsByName[name].(*packageDescriptor)
  305. if !ok {
  306. return
  307. }
  308. for _, file := range p.files {
  309. if !f(file) {
  310. return
  311. }
  312. }
  313. }
  314. // rangeTopLevelDescriptors iterates over all top-level descriptors in a file
  315. // which will be directly entered into the registry.
  316. func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) {
  317. eds := fd.Enums()
  318. for i := eds.Len() - 1; i >= 0; i-- {
  319. f(eds.Get(i))
  320. vds := eds.Get(i).Values()
  321. for i := vds.Len() - 1; i >= 0; i-- {
  322. f(vds.Get(i))
  323. }
  324. }
  325. mds := fd.Messages()
  326. for i := mds.Len() - 1; i >= 0; i-- {
  327. f(mds.Get(i))
  328. }
  329. xds := fd.Extensions()
  330. for i := xds.Len() - 1; i >= 0; i-- {
  331. f(xds.Get(i))
  332. }
  333. sds := fd.Services()
  334. for i := sds.Len() - 1; i >= 0; i-- {
  335. f(sds.Get(i))
  336. }
  337. }
  338. // A Type is a protoreflect.EnumType, protoreflect.MessageType, or protoreflect.ExtensionType.
  339. type Type interface{}
  340. // MessageTypeResolver is an interface for looking up messages.
  341. //
  342. // A compliant implementation must deterministically return the same type
  343. // if no error is encountered.
  344. //
  345. // The Types type implements this interface.
  346. type MessageTypeResolver interface {
  347. // FindMessageByName looks up a message by its full name.
  348. // E.g., "google.protobuf.Any"
  349. //
  350. // This return (nil, NotFound) if not found.
  351. FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error)
  352. // FindMessageByURL looks up a message by a URL identifier.
  353. // See documentation on google.protobuf.Any.type_url for the URL format.
  354. //
  355. // This returns (nil, NotFound) if not found.
  356. FindMessageByURL(url string) (protoreflect.MessageType, error)
  357. }
  358. // ExtensionTypeResolver is an interface for looking up extensions.
  359. //
  360. // A compliant implementation must deterministically return the same type
  361. // if no error is encountered.
  362. //
  363. // The Types type implements this interface.
  364. type ExtensionTypeResolver interface {
  365. // FindExtensionByName looks up a extension field by the field's full name.
  366. // Note that this is the full name of the field as determined by
  367. // where the extension is declared and is unrelated to the full name of the
  368. // message being extended.
  369. //
  370. // This returns (nil, NotFound) if not found.
  371. FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error)
  372. // FindExtensionByNumber looks up a extension field by the field number
  373. // within some parent message, identified by full name.
  374. //
  375. // This returns (nil, NotFound) if not found.
  376. FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)
  377. }
  378. var (
  379. _ MessageTypeResolver = (*Types)(nil)
  380. _ ExtensionTypeResolver = (*Types)(nil)
  381. )
  382. // Types is a registry for looking up or iterating over descriptor types.
  383. // The Find and Range methods are safe for concurrent use.
  384. type Types struct {
  385. // TODO: The syntax of the URL is ill-defined and the protobuf team recently
  386. // changed the documented semantics in a way that breaks prior usages.
  387. // I do not believe they can do this and need to sync up with the
  388. // protobuf team again to hash out what the proper syntax of the URL is.
  389. // TODO: Should we separate this out as a registry for each type?
  390. //
  391. // In Java, the extension and message registry are distinct classes.
  392. // Their extension registry has knowledge of distinct Java types,
  393. // while their message registry only contains descriptor information.
  394. //
  395. // In Go, we have always registered messages, enums, and extensions.
  396. // Messages and extensions are registered with Go information, while enums
  397. // are only registered with descriptor information. We cannot drop Go type
  398. // information for messages otherwise we would be unable to implement
  399. // portions of the v1 API such as ptypes.DynamicAny.
  400. //
  401. // There is no enum registry in Java. In v1, we used the enum registry
  402. // because enum types provided no reflective methods. The addition of
  403. // ProtoReflect removes that need.
  404. typesByName typesByName
  405. extensionsByMessage extensionsByMessage
  406. numEnums int
  407. numMessages int
  408. numExtensions int
  409. }
  410. type (
  411. typesByName map[protoreflect.FullName]Type
  412. extensionsByMessage map[protoreflect.FullName]extensionsByNumber
  413. extensionsByNumber map[protoreflect.FieldNumber]protoreflect.ExtensionType
  414. )
  415. // NewTypes returns a registry initialized with the provided set of types.
  416. // If there are conflicts, the first one takes precedence.
  417. func NewTypes(typs ...Type) *Types {
  418. r := new(Types)
  419. r.Register(typs...) // ignore errors; first takes precedence
  420. return r
  421. }
  422. // Register registers the provided list of descriptor types.
  423. //
  424. // If a registration conflict occurs for enum, message, or extension types
  425. // (e.g., two different types have the same full name),
  426. // then the first type takes precedence and an error is returned.
  427. func (r *Types) Register(typs ...Type) error {
  428. if r == GlobalTypes {
  429. globalMutex.Lock()
  430. defer globalMutex.Unlock()
  431. }
  432. var firstErr error
  433. typeLoop:
  434. for _, typ := range typs {
  435. switch typ.(type) {
  436. case protoreflect.EnumType, protoreflect.MessageType, protoreflect.ExtensionType:
  437. // Check for conflicts in typesByName.
  438. var desc protoreflect.Descriptor
  439. var pcnt *int
  440. switch t := typ.(type) {
  441. case protoreflect.EnumType:
  442. desc = t.Descriptor()
  443. pcnt = &r.numEnums
  444. case protoreflect.MessageType:
  445. desc = t.Descriptor()
  446. pcnt = &r.numMessages
  447. case protoreflect.ExtensionType:
  448. desc = t.TypeDescriptor()
  449. pcnt = &r.numExtensions
  450. default:
  451. panic(fmt.Sprintf("invalid type: %T", t))
  452. }
  453. name := desc.FullName()
  454. if prev := r.typesByName[name]; prev != nil {
  455. err := errors.New("%v %v is already registered", typeName(typ), name)
  456. err = amendErrorWithCaller(err, prev, typ)
  457. if r == GlobalTypes && ignoreConflict(desc, err) {
  458. err = nil
  459. }
  460. if firstErr == nil {
  461. firstErr = err
  462. }
  463. continue typeLoop
  464. }
  465. // Check for conflicts in extensionsByMessage.
  466. if xt, _ := typ.(protoreflect.ExtensionType); xt != nil {
  467. xd := xt.TypeDescriptor()
  468. field := xd.Number()
  469. message := xd.ContainingMessage().FullName()
  470. if prev := r.extensionsByMessage[message][field]; prev != nil {
  471. err := errors.New("extension number %d is already registered on message %v", field, message)
  472. err = amendErrorWithCaller(err, prev, typ)
  473. if r == GlobalTypes && ignoreConflict(xd, err) {
  474. err = nil
  475. }
  476. if firstErr == nil {
  477. firstErr = err
  478. }
  479. continue typeLoop
  480. }
  481. // Update extensionsByMessage.
  482. if r.extensionsByMessage == nil {
  483. r.extensionsByMessage = make(extensionsByMessage)
  484. }
  485. if r.extensionsByMessage[message] == nil {
  486. r.extensionsByMessage[message] = make(extensionsByNumber)
  487. }
  488. r.extensionsByMessage[message][field] = xt
  489. }
  490. // Update typesByName and the count.
  491. if r.typesByName == nil {
  492. r.typesByName = make(typesByName)
  493. }
  494. r.typesByName[name] = typ
  495. (*pcnt)++
  496. default:
  497. if firstErr == nil {
  498. firstErr = errors.New("invalid type: %v", typeName(typ))
  499. }
  500. }
  501. }
  502. return firstErr
  503. }
  504. // FindEnumByName looks up an enum by its full name.
  505. // E.g., "google.protobuf.Field.Kind".
  506. //
  507. // This returns (nil, NotFound) if not found.
  508. func (r *Types) FindEnumByName(enum protoreflect.FullName) (protoreflect.EnumType, error) {
  509. if r == nil {
  510. return nil, NotFound
  511. }
  512. if r == GlobalTypes {
  513. globalMutex.RLock()
  514. defer globalMutex.RUnlock()
  515. }
  516. if v := r.typesByName[enum]; v != nil {
  517. if et, _ := v.(protoreflect.EnumType); et != nil {
  518. return et, nil
  519. }
  520. return nil, errors.New("found wrong type: got %v, want enum", typeName(v))
  521. }
  522. return nil, NotFound
  523. }
  524. // FindMessageByName looks up a message by its full name.
  525. // E.g., "google.protobuf.Any"
  526. //
  527. // This return (nil, NotFound) if not found.
  528. func (r *Types) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
  529. // The full name by itself is a valid URL.
  530. return r.FindMessageByURL(string(message))
  531. }
  532. // FindMessageByURL looks up a message by a URL identifier.
  533. // See documentation on google.protobuf.Any.type_url for the URL format.
  534. //
  535. // This returns (nil, NotFound) if not found.
  536. func (r *Types) FindMessageByURL(url string) (protoreflect.MessageType, error) {
  537. if r == nil {
  538. return nil, NotFound
  539. }
  540. if r == GlobalTypes {
  541. globalMutex.RLock()
  542. defer globalMutex.RUnlock()
  543. }
  544. message := protoreflect.FullName(url)
  545. if i := strings.LastIndexByte(url, '/'); i >= 0 {
  546. message = message[i+len("/"):]
  547. }
  548. if v := r.typesByName[message]; v != nil {
  549. if mt, _ := v.(protoreflect.MessageType); mt != nil {
  550. return mt, nil
  551. }
  552. return nil, errors.New("found wrong type: got %v, want message", typeName(v))
  553. }
  554. return nil, NotFound
  555. }
  556. // FindExtensionByName looks up a extension field by the field's full name.
  557. // Note that this is the full name of the field as determined by
  558. // where the extension is declared and is unrelated to the full name of the
  559. // message being extended.
  560. //
  561. // This returns (nil, NotFound) if not found.
  562. func (r *Types) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
  563. if r == nil {
  564. return nil, NotFound
  565. }
  566. if r == GlobalTypes {
  567. globalMutex.RLock()
  568. defer globalMutex.RUnlock()
  569. }
  570. if v := r.typesByName[field]; v != nil {
  571. if xt, _ := v.(protoreflect.ExtensionType); xt != nil {
  572. return xt, nil
  573. }
  574. return nil, errors.New("found wrong type: got %v, want extension", typeName(v))
  575. }
  576. return nil, NotFound
  577. }
  578. // FindExtensionByNumber looks up a extension field by the field number
  579. // within some parent message, identified by full name.
  580. //
  581. // This returns (nil, NotFound) if not found.
  582. func (r *Types) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
  583. if r == nil {
  584. return nil, NotFound
  585. }
  586. if r == GlobalTypes {
  587. globalMutex.RLock()
  588. defer globalMutex.RUnlock()
  589. }
  590. if xt, ok := r.extensionsByMessage[message][field]; ok {
  591. return xt, nil
  592. }
  593. return nil, NotFound
  594. }
  595. // NumEnums reports the number of registered enums.
  596. func (r *Types) NumEnums() int {
  597. if r == nil {
  598. return 0
  599. }
  600. if r == GlobalTypes {
  601. globalMutex.RLock()
  602. defer globalMutex.RUnlock()
  603. }
  604. return r.numEnums
  605. }
  606. // RangeEnums iterates over all registered enums.
  607. // Iteration order is undefined.
  608. func (r *Types) RangeEnums(f func(protoreflect.EnumType) bool) {
  609. if r == nil {
  610. return
  611. }
  612. if r == GlobalTypes {
  613. globalMutex.RLock()
  614. defer globalMutex.RUnlock()
  615. }
  616. for _, typ := range r.typesByName {
  617. if et, ok := typ.(protoreflect.EnumType); ok {
  618. if !f(et) {
  619. return
  620. }
  621. }
  622. }
  623. }
  624. // NumMessages reports the number of registered messages.
  625. func (r *Types) NumMessages() int {
  626. if r == nil {
  627. return 0
  628. }
  629. if r == GlobalTypes {
  630. globalMutex.RLock()
  631. defer globalMutex.RUnlock()
  632. }
  633. return r.numMessages
  634. }
  635. // RangeMessages iterates over all registered messages.
  636. // Iteration order is undefined.
  637. func (r *Types) RangeMessages(f func(protoreflect.MessageType) bool) {
  638. if r == nil {
  639. return
  640. }
  641. if r == GlobalTypes {
  642. globalMutex.RLock()
  643. defer globalMutex.RUnlock()
  644. }
  645. for _, typ := range r.typesByName {
  646. if mt, ok := typ.(protoreflect.MessageType); ok {
  647. if !f(mt) {
  648. return
  649. }
  650. }
  651. }
  652. }
  653. // NumExtensions reports the number of registered extensions.
  654. func (r *Types) NumExtensions() int {
  655. if r == nil {
  656. return 0
  657. }
  658. if r == GlobalTypes {
  659. globalMutex.RLock()
  660. defer globalMutex.RUnlock()
  661. }
  662. return r.numExtensions
  663. }
  664. // RangeExtensions iterates over all registered extensions.
  665. // Iteration order is undefined.
  666. func (r *Types) RangeExtensions(f func(protoreflect.ExtensionType) bool) {
  667. if r == nil {
  668. return
  669. }
  670. if r == GlobalTypes {
  671. globalMutex.RLock()
  672. defer globalMutex.RUnlock()
  673. }
  674. for _, typ := range r.typesByName {
  675. if xt, ok := typ.(protoreflect.ExtensionType); ok {
  676. if !f(xt) {
  677. return
  678. }
  679. }
  680. }
  681. }
  682. // NumExtensionsByMessage reports the number of registered extensions for
  683. // a given message type.
  684. func (r *Types) NumExtensionsByMessage(message protoreflect.FullName) int {
  685. if r == nil {
  686. return 0
  687. }
  688. if r == GlobalTypes {
  689. globalMutex.RLock()
  690. defer globalMutex.RUnlock()
  691. }
  692. return len(r.extensionsByMessage[message])
  693. }
  694. // RangeExtensionsByMessage iterates over all registered extensions filtered
  695. // by a given message type. Iteration order is undefined.
  696. func (r *Types) RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) {
  697. if r == nil {
  698. return
  699. }
  700. if r == GlobalTypes {
  701. globalMutex.RLock()
  702. defer globalMutex.RUnlock()
  703. }
  704. for _, xt := range r.extensionsByMessage[message] {
  705. if !f(xt) {
  706. return
  707. }
  708. }
  709. }
  710. func typeName(t Type) string {
  711. switch t.(type) {
  712. case protoreflect.EnumType:
  713. return "enum"
  714. case protoreflect.MessageType:
  715. return "message"
  716. case protoreflect.ExtensionType:
  717. return "extension"
  718. default:
  719. return fmt.Sprintf("%T", t)
  720. }
  721. }
  722. func amendErrorWithCaller(err error, prev, curr interface{}) error {
  723. prevPkg := goPackage(prev)
  724. currPkg := goPackage(curr)
  725. if prevPkg == "" || currPkg == "" || prevPkg == currPkg {
  726. return err
  727. }
  728. return errors.New("%s\n\tpreviously from: %q\n\tcurrently from: %q", err, prevPkg, currPkg)
  729. }
  730. func goPackage(v interface{}) string {
  731. switch d := v.(type) {
  732. case protoreflect.EnumType:
  733. v = d.Descriptor()
  734. case protoreflect.MessageType:
  735. v = d.Descriptor()
  736. case protoreflect.ExtensionType:
  737. v = d.TypeDescriptor()
  738. }
  739. if d, ok := v.(protoreflect.Descriptor); ok {
  740. v = d.ParentFile()
  741. }
  742. if d, ok := v.(interface{ GoPackagePath() string }); ok {
  743. return d.GoPackagePath()
  744. }
  745. return ""
  746. }