desc.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. // Copyright 2019 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 filedesc
  5. import (
  6. "bytes"
  7. "fmt"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "google.golang.org/protobuf/internal/descfmt"
  12. "google.golang.org/protobuf/internal/descopts"
  13. "google.golang.org/protobuf/internal/encoding/defval"
  14. "google.golang.org/protobuf/internal/encoding/messageset"
  15. "google.golang.org/protobuf/internal/genid"
  16. "google.golang.org/protobuf/internal/pragma"
  17. "google.golang.org/protobuf/internal/strs"
  18. "google.golang.org/protobuf/reflect/protoreflect"
  19. "google.golang.org/protobuf/reflect/protoregistry"
  20. )
  21. // Edition is an Enum for proto2.Edition
  22. type Edition int32
  23. // These values align with the value of Enum in descriptor.proto which allows
  24. // direct conversion between the proto enum and this enum.
  25. const (
  26. EditionUnknown Edition = 0
  27. EditionProto2 Edition = 998
  28. EditionProto3 Edition = 999
  29. Edition2023 Edition = 1000
  30. EditionUnsupported Edition = 100000
  31. )
  32. // The types in this file may have a suffix:
  33. // • L0: Contains fields common to all descriptors (except File) and
  34. // must be initialized up front.
  35. // • L1: Contains fields specific to a descriptor and
  36. // must be initialized up front. If the associated proto uses Editions, the
  37. // Editions features must always be resolved. If not explicitly set, the
  38. // appropriate default must be resolved and set.
  39. // • L2: Contains fields that are lazily initialized when constructing
  40. // from the raw file descriptor. When constructing as a literal, the L2
  41. // fields must be initialized up front.
  42. //
  43. // The types are exported so that packages like reflect/protodesc can
  44. // directly construct descriptors.
  45. type (
  46. File struct {
  47. fileRaw
  48. L1 FileL1
  49. once uint32 // atomically set if L2 is valid
  50. mu sync.Mutex // protects L2
  51. L2 *FileL2
  52. }
  53. FileL1 struct {
  54. Syntax protoreflect.Syntax
  55. Edition Edition // Only used if Syntax == Editions
  56. Path string
  57. Package protoreflect.FullName
  58. Enums Enums
  59. Messages Messages
  60. Extensions Extensions
  61. Services Services
  62. EditionFeatures EditionFeatures
  63. }
  64. FileL2 struct {
  65. Options func() protoreflect.ProtoMessage
  66. Imports FileImports
  67. Locations SourceLocations
  68. }
  69. EditionFeatures struct {
  70. // IsFieldPresence is true if field_presence is EXPLICIT
  71. // https://protobuf.dev/editions/features/#field_presence
  72. IsFieldPresence bool
  73. // IsFieldPresence is true if field_presence is LEGACY_REQUIRED
  74. // https://protobuf.dev/editions/features/#field_presence
  75. IsLegacyRequired bool
  76. // IsOpenEnum is true if enum_type is OPEN
  77. // https://protobuf.dev/editions/features/#enum_type
  78. IsOpenEnum bool
  79. // IsPacked is true if repeated_field_encoding is PACKED
  80. // https://protobuf.dev/editions/features/#repeated_field_encoding
  81. IsPacked bool
  82. // IsUTF8Validated is true if utf_validation is VERIFY
  83. // https://protobuf.dev/editions/features/#utf8_validation
  84. IsUTF8Validated bool
  85. // IsDelimitedEncoded is true if message_encoding is DELIMITED
  86. // https://protobuf.dev/editions/features/#message_encoding
  87. IsDelimitedEncoded bool
  88. // IsJSONCompliant is true if json_format is ALLOW
  89. // https://protobuf.dev/editions/features/#json_format
  90. IsJSONCompliant bool
  91. // GenerateLegacyUnmarshalJSON determines if the plugin generates the
  92. // UnmarshalJSON([]byte) error method for enums.
  93. GenerateLegacyUnmarshalJSON bool
  94. }
  95. )
  96. func (fd *File) ParentFile() protoreflect.FileDescriptor { return fd }
  97. func (fd *File) Parent() protoreflect.Descriptor { return nil }
  98. func (fd *File) Index() int { return 0 }
  99. func (fd *File) Syntax() protoreflect.Syntax { return fd.L1.Syntax }
  100. // Not exported and just used to reconstruct the original FileDescriptor proto
  101. func (fd *File) Edition() int32 { return int32(fd.L1.Edition) }
  102. func (fd *File) Name() protoreflect.Name { return fd.L1.Package.Name() }
  103. func (fd *File) FullName() protoreflect.FullName { return fd.L1.Package }
  104. func (fd *File) IsPlaceholder() bool { return false }
  105. func (fd *File) Options() protoreflect.ProtoMessage {
  106. if f := fd.lazyInit().Options; f != nil {
  107. return f()
  108. }
  109. return descopts.File
  110. }
  111. func (fd *File) Path() string { return fd.L1.Path }
  112. func (fd *File) Package() protoreflect.FullName { return fd.L1.Package }
  113. func (fd *File) Imports() protoreflect.FileImports { return &fd.lazyInit().Imports }
  114. func (fd *File) Enums() protoreflect.EnumDescriptors { return &fd.L1.Enums }
  115. func (fd *File) Messages() protoreflect.MessageDescriptors { return &fd.L1.Messages }
  116. func (fd *File) Extensions() protoreflect.ExtensionDescriptors { return &fd.L1.Extensions }
  117. func (fd *File) Services() protoreflect.ServiceDescriptors { return &fd.L1.Services }
  118. func (fd *File) SourceLocations() protoreflect.SourceLocations { return &fd.lazyInit().Locations }
  119. func (fd *File) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) }
  120. func (fd *File) ProtoType(protoreflect.FileDescriptor) {}
  121. func (fd *File) ProtoInternal(pragma.DoNotImplement) {}
  122. func (fd *File) lazyInit() *FileL2 {
  123. if atomic.LoadUint32(&fd.once) == 0 {
  124. fd.lazyInitOnce()
  125. }
  126. return fd.L2
  127. }
  128. func (fd *File) lazyInitOnce() {
  129. fd.mu.Lock()
  130. if fd.L2 == nil {
  131. fd.lazyRawInit() // recursively initializes all L2 structures
  132. }
  133. atomic.StoreUint32(&fd.once, 1)
  134. fd.mu.Unlock()
  135. }
  136. // GoPackagePath is a pseudo-internal API for determining the Go package path
  137. // that this file descriptor is declared in.
  138. //
  139. // WARNING: This method is exempt from the compatibility promise and may be
  140. // removed in the future without warning.
  141. func (fd *File) GoPackagePath() string {
  142. return fd.builder.GoPackagePath
  143. }
  144. type (
  145. Enum struct {
  146. Base
  147. L1 EnumL1
  148. L2 *EnumL2 // protected by fileDesc.once
  149. }
  150. EnumL1 struct {
  151. eagerValues bool // controls whether EnumL2.Values is already populated
  152. EditionFeatures EditionFeatures
  153. }
  154. EnumL2 struct {
  155. Options func() protoreflect.ProtoMessage
  156. Values EnumValues
  157. ReservedNames Names
  158. ReservedRanges EnumRanges
  159. }
  160. EnumValue struct {
  161. Base
  162. L1 EnumValueL1
  163. }
  164. EnumValueL1 struct {
  165. Options func() protoreflect.ProtoMessage
  166. Number protoreflect.EnumNumber
  167. }
  168. )
  169. func (ed *Enum) Options() protoreflect.ProtoMessage {
  170. if f := ed.lazyInit().Options; f != nil {
  171. return f()
  172. }
  173. return descopts.Enum
  174. }
  175. func (ed *Enum) Values() protoreflect.EnumValueDescriptors {
  176. if ed.L1.eagerValues {
  177. return &ed.L2.Values
  178. }
  179. return &ed.lazyInit().Values
  180. }
  181. func (ed *Enum) ReservedNames() protoreflect.Names { return &ed.lazyInit().ReservedNames }
  182. func (ed *Enum) ReservedRanges() protoreflect.EnumRanges { return &ed.lazyInit().ReservedRanges }
  183. func (ed *Enum) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) }
  184. func (ed *Enum) ProtoType(protoreflect.EnumDescriptor) {}
  185. func (ed *Enum) lazyInit() *EnumL2 {
  186. ed.L0.ParentFile.lazyInit() // implicitly initializes L2
  187. return ed.L2
  188. }
  189. func (ed *Enum) IsClosed() bool {
  190. return !ed.L1.EditionFeatures.IsOpenEnum
  191. }
  192. func (ed *EnumValue) Options() protoreflect.ProtoMessage {
  193. if f := ed.L1.Options; f != nil {
  194. return f()
  195. }
  196. return descopts.EnumValue
  197. }
  198. func (ed *EnumValue) Number() protoreflect.EnumNumber { return ed.L1.Number }
  199. func (ed *EnumValue) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) }
  200. func (ed *EnumValue) ProtoType(protoreflect.EnumValueDescriptor) {}
  201. type (
  202. Message struct {
  203. Base
  204. L1 MessageL1
  205. L2 *MessageL2 // protected by fileDesc.once
  206. }
  207. MessageL1 struct {
  208. Enums Enums
  209. Messages Messages
  210. Extensions Extensions
  211. IsMapEntry bool // promoted from google.protobuf.MessageOptions
  212. IsMessageSet bool // promoted from google.protobuf.MessageOptions
  213. EditionFeatures EditionFeatures
  214. }
  215. MessageL2 struct {
  216. Options func() protoreflect.ProtoMessage
  217. Fields Fields
  218. Oneofs Oneofs
  219. ReservedNames Names
  220. ReservedRanges FieldRanges
  221. RequiredNumbers FieldNumbers // must be consistent with Fields.Cardinality
  222. ExtensionRanges FieldRanges
  223. ExtensionRangeOptions []func() protoreflect.ProtoMessage // must be same length as ExtensionRanges
  224. }
  225. Field struct {
  226. Base
  227. L1 FieldL1
  228. }
  229. FieldL1 struct {
  230. Options func() protoreflect.ProtoMessage
  231. Number protoreflect.FieldNumber
  232. Cardinality protoreflect.Cardinality // must be consistent with Message.RequiredNumbers
  233. Kind protoreflect.Kind
  234. StringName stringName
  235. IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto
  236. IsWeak bool // promoted from google.protobuf.FieldOptions
  237. Default defaultValue
  238. ContainingOneof protoreflect.OneofDescriptor // must be consistent with Message.Oneofs.Fields
  239. Enum protoreflect.EnumDescriptor
  240. Message protoreflect.MessageDescriptor
  241. EditionFeatures EditionFeatures
  242. }
  243. Oneof struct {
  244. Base
  245. L1 OneofL1
  246. }
  247. OneofL1 struct {
  248. Options func() protoreflect.ProtoMessage
  249. Fields OneofFields // must be consistent with Message.Fields.ContainingOneof
  250. EditionFeatures EditionFeatures
  251. }
  252. )
  253. func (md *Message) Options() protoreflect.ProtoMessage {
  254. if f := md.lazyInit().Options; f != nil {
  255. return f()
  256. }
  257. return descopts.Message
  258. }
  259. func (md *Message) IsMapEntry() bool { return md.L1.IsMapEntry }
  260. func (md *Message) Fields() protoreflect.FieldDescriptors { return &md.lazyInit().Fields }
  261. func (md *Message) Oneofs() protoreflect.OneofDescriptors { return &md.lazyInit().Oneofs }
  262. func (md *Message) ReservedNames() protoreflect.Names { return &md.lazyInit().ReservedNames }
  263. func (md *Message) ReservedRanges() protoreflect.FieldRanges { return &md.lazyInit().ReservedRanges }
  264. func (md *Message) RequiredNumbers() protoreflect.FieldNumbers { return &md.lazyInit().RequiredNumbers }
  265. func (md *Message) ExtensionRanges() protoreflect.FieldRanges { return &md.lazyInit().ExtensionRanges }
  266. func (md *Message) ExtensionRangeOptions(i int) protoreflect.ProtoMessage {
  267. if f := md.lazyInit().ExtensionRangeOptions[i]; f != nil {
  268. return f()
  269. }
  270. return descopts.ExtensionRange
  271. }
  272. func (md *Message) Enums() protoreflect.EnumDescriptors { return &md.L1.Enums }
  273. func (md *Message) Messages() protoreflect.MessageDescriptors { return &md.L1.Messages }
  274. func (md *Message) Extensions() protoreflect.ExtensionDescriptors { return &md.L1.Extensions }
  275. func (md *Message) ProtoType(protoreflect.MessageDescriptor) {}
  276. func (md *Message) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) }
  277. func (md *Message) lazyInit() *MessageL2 {
  278. md.L0.ParentFile.lazyInit() // implicitly initializes L2
  279. return md.L2
  280. }
  281. // IsMessageSet is a pseudo-internal API for checking whether a message
  282. // should serialize in the proto1 message format.
  283. //
  284. // WARNING: This method is exempt from the compatibility promise and may be
  285. // removed in the future without warning.
  286. func (md *Message) IsMessageSet() bool {
  287. return md.L1.IsMessageSet
  288. }
  289. func (fd *Field) Options() protoreflect.ProtoMessage {
  290. if f := fd.L1.Options; f != nil {
  291. return f()
  292. }
  293. return descopts.Field
  294. }
  295. func (fd *Field) Number() protoreflect.FieldNumber { return fd.L1.Number }
  296. func (fd *Field) Cardinality() protoreflect.Cardinality { return fd.L1.Cardinality }
  297. func (fd *Field) Kind() protoreflect.Kind {
  298. return fd.L1.Kind
  299. }
  300. func (fd *Field) HasJSONName() bool { return fd.L1.StringName.hasJSON }
  301. func (fd *Field) JSONName() string { return fd.L1.StringName.getJSON(fd) }
  302. func (fd *Field) TextName() string { return fd.L1.StringName.getText(fd) }
  303. func (fd *Field) HasPresence() bool {
  304. if fd.L1.Cardinality == protoreflect.Repeated {
  305. return false
  306. }
  307. return fd.IsExtension() || fd.L1.EditionFeatures.IsFieldPresence || fd.L1.Message != nil || fd.L1.ContainingOneof != nil
  308. }
  309. func (fd *Field) HasOptionalKeyword() bool {
  310. return (fd.L0.ParentFile.L1.Syntax == protoreflect.Proto2 && fd.L1.Cardinality == protoreflect.Optional && fd.L1.ContainingOneof == nil) || fd.L1.IsProto3Optional
  311. }
  312. func (fd *Field) IsPacked() bool {
  313. if fd.L1.Cardinality != protoreflect.Repeated {
  314. return false
  315. }
  316. switch fd.L1.Kind {
  317. case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind:
  318. return false
  319. }
  320. return fd.L1.EditionFeatures.IsPacked
  321. }
  322. func (fd *Field) IsExtension() bool { return false }
  323. func (fd *Field) IsWeak() bool { return fd.L1.IsWeak }
  324. func (fd *Field) IsList() bool { return fd.Cardinality() == protoreflect.Repeated && !fd.IsMap() }
  325. func (fd *Field) IsMap() bool { return fd.Message() != nil && fd.Message().IsMapEntry() }
  326. func (fd *Field) MapKey() protoreflect.FieldDescriptor {
  327. if !fd.IsMap() {
  328. return nil
  329. }
  330. return fd.Message().Fields().ByNumber(genid.MapEntry_Key_field_number)
  331. }
  332. func (fd *Field) MapValue() protoreflect.FieldDescriptor {
  333. if !fd.IsMap() {
  334. return nil
  335. }
  336. return fd.Message().Fields().ByNumber(genid.MapEntry_Value_field_number)
  337. }
  338. func (fd *Field) HasDefault() bool { return fd.L1.Default.has }
  339. func (fd *Field) Default() protoreflect.Value { return fd.L1.Default.get(fd) }
  340. func (fd *Field) DefaultEnumValue() protoreflect.EnumValueDescriptor { return fd.L1.Default.enum }
  341. func (fd *Field) ContainingOneof() protoreflect.OneofDescriptor { return fd.L1.ContainingOneof }
  342. func (fd *Field) ContainingMessage() protoreflect.MessageDescriptor {
  343. return fd.L0.Parent.(protoreflect.MessageDescriptor)
  344. }
  345. func (fd *Field) Enum() protoreflect.EnumDescriptor {
  346. return fd.L1.Enum
  347. }
  348. func (fd *Field) Message() protoreflect.MessageDescriptor {
  349. if fd.L1.IsWeak {
  350. if d, _ := protoregistry.GlobalFiles.FindDescriptorByName(fd.L1.Message.FullName()); d != nil {
  351. return d.(protoreflect.MessageDescriptor)
  352. }
  353. }
  354. return fd.L1.Message
  355. }
  356. func (fd *Field) IsMapEntry() bool {
  357. parent, ok := fd.L0.Parent.(protoreflect.MessageDescriptor)
  358. return ok && parent.IsMapEntry()
  359. }
  360. func (fd *Field) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) }
  361. func (fd *Field) ProtoType(protoreflect.FieldDescriptor) {}
  362. // EnforceUTF8 is a pseudo-internal API to determine whether to enforce UTF-8
  363. // validation for the string field. This exists for Google-internal use only
  364. // since proto3 did not enforce UTF-8 validity prior to the open-source release.
  365. // If this method does not exist, the default is to enforce valid UTF-8.
  366. //
  367. // WARNING: This method is exempt from the compatibility promise and may be
  368. // removed in the future without warning.
  369. func (fd *Field) EnforceUTF8() bool {
  370. return fd.L1.EditionFeatures.IsUTF8Validated
  371. }
  372. func (od *Oneof) IsSynthetic() bool {
  373. return od.L0.ParentFile.L1.Syntax == protoreflect.Proto3 && len(od.L1.Fields.List) == 1 && od.L1.Fields.List[0].HasOptionalKeyword()
  374. }
  375. func (od *Oneof) Options() protoreflect.ProtoMessage {
  376. if f := od.L1.Options; f != nil {
  377. return f()
  378. }
  379. return descopts.Oneof
  380. }
  381. func (od *Oneof) Fields() protoreflect.FieldDescriptors { return &od.L1.Fields }
  382. func (od *Oneof) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, od) }
  383. func (od *Oneof) ProtoType(protoreflect.OneofDescriptor) {}
  384. type (
  385. Extension struct {
  386. Base
  387. L1 ExtensionL1
  388. L2 *ExtensionL2 // protected by fileDesc.once
  389. }
  390. ExtensionL1 struct {
  391. Number protoreflect.FieldNumber
  392. Extendee protoreflect.MessageDescriptor
  393. Cardinality protoreflect.Cardinality
  394. Kind protoreflect.Kind
  395. EditionFeatures EditionFeatures
  396. }
  397. ExtensionL2 struct {
  398. Options func() protoreflect.ProtoMessage
  399. StringName stringName
  400. IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto
  401. Default defaultValue
  402. Enum protoreflect.EnumDescriptor
  403. Message protoreflect.MessageDescriptor
  404. }
  405. )
  406. func (xd *Extension) Options() protoreflect.ProtoMessage {
  407. if f := xd.lazyInit().Options; f != nil {
  408. return f()
  409. }
  410. return descopts.Field
  411. }
  412. func (xd *Extension) Number() protoreflect.FieldNumber { return xd.L1.Number }
  413. func (xd *Extension) Cardinality() protoreflect.Cardinality { return xd.L1.Cardinality }
  414. func (xd *Extension) Kind() protoreflect.Kind { return xd.L1.Kind }
  415. func (xd *Extension) HasJSONName() bool { return xd.lazyInit().StringName.hasJSON }
  416. func (xd *Extension) JSONName() string { return xd.lazyInit().StringName.getJSON(xd) }
  417. func (xd *Extension) TextName() string { return xd.lazyInit().StringName.getText(xd) }
  418. func (xd *Extension) HasPresence() bool { return xd.L1.Cardinality != protoreflect.Repeated }
  419. func (xd *Extension) HasOptionalKeyword() bool {
  420. return (xd.L0.ParentFile.L1.Syntax == protoreflect.Proto2 && xd.L1.Cardinality == protoreflect.Optional) || xd.lazyInit().IsProto3Optional
  421. }
  422. func (xd *Extension) IsPacked() bool {
  423. if xd.L1.Cardinality != protoreflect.Repeated {
  424. return false
  425. }
  426. switch xd.L1.Kind {
  427. case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind:
  428. return false
  429. }
  430. return xd.L1.EditionFeatures.IsPacked
  431. }
  432. func (xd *Extension) IsExtension() bool { return true }
  433. func (xd *Extension) IsWeak() bool { return false }
  434. func (xd *Extension) IsList() bool { return xd.Cardinality() == protoreflect.Repeated }
  435. func (xd *Extension) IsMap() bool { return false }
  436. func (xd *Extension) MapKey() protoreflect.FieldDescriptor { return nil }
  437. func (xd *Extension) MapValue() protoreflect.FieldDescriptor { return nil }
  438. func (xd *Extension) HasDefault() bool { return xd.lazyInit().Default.has }
  439. func (xd *Extension) Default() protoreflect.Value { return xd.lazyInit().Default.get(xd) }
  440. func (xd *Extension) DefaultEnumValue() protoreflect.EnumValueDescriptor {
  441. return xd.lazyInit().Default.enum
  442. }
  443. func (xd *Extension) ContainingOneof() protoreflect.OneofDescriptor { return nil }
  444. func (xd *Extension) ContainingMessage() protoreflect.MessageDescriptor { return xd.L1.Extendee }
  445. func (xd *Extension) Enum() protoreflect.EnumDescriptor { return xd.lazyInit().Enum }
  446. func (xd *Extension) Message() protoreflect.MessageDescriptor { return xd.lazyInit().Message }
  447. func (xd *Extension) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, xd) }
  448. func (xd *Extension) ProtoType(protoreflect.FieldDescriptor) {}
  449. func (xd *Extension) ProtoInternal(pragma.DoNotImplement) {}
  450. func (xd *Extension) lazyInit() *ExtensionL2 {
  451. xd.L0.ParentFile.lazyInit() // implicitly initializes L2
  452. return xd.L2
  453. }
  454. type (
  455. Service struct {
  456. Base
  457. L1 ServiceL1
  458. L2 *ServiceL2 // protected by fileDesc.once
  459. }
  460. ServiceL1 struct{}
  461. ServiceL2 struct {
  462. Options func() protoreflect.ProtoMessage
  463. Methods Methods
  464. }
  465. Method struct {
  466. Base
  467. L1 MethodL1
  468. }
  469. MethodL1 struct {
  470. Options func() protoreflect.ProtoMessage
  471. Input protoreflect.MessageDescriptor
  472. Output protoreflect.MessageDescriptor
  473. IsStreamingClient bool
  474. IsStreamingServer bool
  475. }
  476. )
  477. func (sd *Service) Options() protoreflect.ProtoMessage {
  478. if f := sd.lazyInit().Options; f != nil {
  479. return f()
  480. }
  481. return descopts.Service
  482. }
  483. func (sd *Service) Methods() protoreflect.MethodDescriptors { return &sd.lazyInit().Methods }
  484. func (sd *Service) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, sd) }
  485. func (sd *Service) ProtoType(protoreflect.ServiceDescriptor) {}
  486. func (sd *Service) ProtoInternal(pragma.DoNotImplement) {}
  487. func (sd *Service) lazyInit() *ServiceL2 {
  488. sd.L0.ParentFile.lazyInit() // implicitly initializes L2
  489. return sd.L2
  490. }
  491. func (md *Method) Options() protoreflect.ProtoMessage {
  492. if f := md.L1.Options; f != nil {
  493. return f()
  494. }
  495. return descopts.Method
  496. }
  497. func (md *Method) Input() protoreflect.MessageDescriptor { return md.L1.Input }
  498. func (md *Method) Output() protoreflect.MessageDescriptor { return md.L1.Output }
  499. func (md *Method) IsStreamingClient() bool { return md.L1.IsStreamingClient }
  500. func (md *Method) IsStreamingServer() bool { return md.L1.IsStreamingServer }
  501. func (md *Method) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) }
  502. func (md *Method) ProtoType(protoreflect.MethodDescriptor) {}
  503. func (md *Method) ProtoInternal(pragma.DoNotImplement) {}
  504. // Surrogate files are can be used to create standalone descriptors
  505. // where the syntax is only information derived from the parent file.
  506. var (
  507. SurrogateProto2 = &File{L1: FileL1{Syntax: protoreflect.Proto2}, L2: &FileL2{}}
  508. SurrogateProto3 = &File{L1: FileL1{Syntax: protoreflect.Proto3}, L2: &FileL2{}}
  509. SurrogateEdition2023 = &File{L1: FileL1{Syntax: protoreflect.Editions, Edition: Edition2023}, L2: &FileL2{}}
  510. )
  511. type (
  512. Base struct {
  513. L0 BaseL0
  514. }
  515. BaseL0 struct {
  516. FullName protoreflect.FullName // must be populated
  517. ParentFile *File // must be populated
  518. Parent protoreflect.Descriptor
  519. Index int
  520. }
  521. )
  522. func (d *Base) Name() protoreflect.Name { return d.L0.FullName.Name() }
  523. func (d *Base) FullName() protoreflect.FullName { return d.L0.FullName }
  524. func (d *Base) ParentFile() protoreflect.FileDescriptor {
  525. if d.L0.ParentFile == SurrogateProto2 || d.L0.ParentFile == SurrogateProto3 {
  526. return nil // surrogate files are not real parents
  527. }
  528. return d.L0.ParentFile
  529. }
  530. func (d *Base) Parent() protoreflect.Descriptor { return d.L0.Parent }
  531. func (d *Base) Index() int { return d.L0.Index }
  532. func (d *Base) Syntax() protoreflect.Syntax { return d.L0.ParentFile.Syntax() }
  533. func (d *Base) IsPlaceholder() bool { return false }
  534. func (d *Base) ProtoInternal(pragma.DoNotImplement) {}
  535. type stringName struct {
  536. hasJSON bool
  537. once sync.Once
  538. nameJSON string
  539. nameText string
  540. }
  541. // InitJSON initializes the name. It is exported for use by other internal packages.
  542. func (s *stringName) InitJSON(name string) {
  543. s.hasJSON = true
  544. s.nameJSON = name
  545. }
  546. // Returns true if this field is structured like the synthetic field of a proto2
  547. // group. This allows us to expand our treatment of delimited fields without
  548. // breaking proto2 files that have been upgraded to editions.
  549. func isGroupLike(fd protoreflect.FieldDescriptor) bool {
  550. // Groups are always group types.
  551. if fd.Kind() != protoreflect.GroupKind {
  552. return false
  553. }
  554. // Group fields are always the lowercase type name.
  555. if strings.ToLower(string(fd.Message().Name())) != string(fd.Name()) {
  556. return false
  557. }
  558. // Groups could only be defined in the same file they're used.
  559. if fd.Message().ParentFile() != fd.ParentFile() {
  560. return false
  561. }
  562. // Group messages are always defined in the same scope as the field. File
  563. // level extensions will compare NULL == NULL here, which is why the file
  564. // comparison above is necessary to ensure both come from the same file.
  565. if fd.IsExtension() {
  566. return fd.Parent() == fd.Message().Parent()
  567. }
  568. return fd.ContainingMessage() == fd.Message().Parent()
  569. }
  570. func (s *stringName) lazyInit(fd protoreflect.FieldDescriptor) *stringName {
  571. s.once.Do(func() {
  572. if fd.IsExtension() {
  573. // For extensions, JSON and text are formatted the same way.
  574. var name string
  575. if messageset.IsMessageSetExtension(fd) {
  576. name = string("[" + fd.FullName().Parent() + "]")
  577. } else {
  578. name = string("[" + fd.FullName() + "]")
  579. }
  580. s.nameJSON = name
  581. s.nameText = name
  582. } else {
  583. // Format the JSON name.
  584. if !s.hasJSON {
  585. s.nameJSON = strs.JSONCamelCase(string(fd.Name()))
  586. }
  587. // Format the text name.
  588. s.nameText = string(fd.Name())
  589. if isGroupLike(fd) {
  590. s.nameText = string(fd.Message().Name())
  591. }
  592. }
  593. })
  594. return s
  595. }
  596. func (s *stringName) getJSON(fd protoreflect.FieldDescriptor) string { return s.lazyInit(fd).nameJSON }
  597. func (s *stringName) getText(fd protoreflect.FieldDescriptor) string { return s.lazyInit(fd).nameText }
  598. func DefaultValue(v protoreflect.Value, ev protoreflect.EnumValueDescriptor) defaultValue {
  599. dv := defaultValue{has: v.IsValid(), val: v, enum: ev}
  600. if b, ok := v.Interface().([]byte); ok {
  601. // Store a copy of the default bytes, so that we can detect
  602. // accidental mutations of the original value.
  603. dv.bytes = append([]byte(nil), b...)
  604. }
  605. return dv
  606. }
  607. func unmarshalDefault(b []byte, k protoreflect.Kind, pf *File, ed protoreflect.EnumDescriptor) defaultValue {
  608. var evs protoreflect.EnumValueDescriptors
  609. if k == protoreflect.EnumKind {
  610. // If the enum is declared within the same file, be careful not to
  611. // blindly call the Values method, lest we bind ourselves in a deadlock.
  612. if e, ok := ed.(*Enum); ok && e.L0.ParentFile == pf {
  613. evs = &e.L2.Values
  614. } else {
  615. evs = ed.Values()
  616. }
  617. // If we are unable to resolve the enum dependency, use a placeholder
  618. // enum value since we will not be able to parse the default value.
  619. if ed.IsPlaceholder() && protoreflect.Name(b).IsValid() {
  620. v := protoreflect.ValueOfEnum(0)
  621. ev := PlaceholderEnumValue(ed.FullName().Parent().Append(protoreflect.Name(b)))
  622. return DefaultValue(v, ev)
  623. }
  624. }
  625. v, ev, err := defval.Unmarshal(string(b), k, evs, defval.Descriptor)
  626. if err != nil {
  627. panic(err)
  628. }
  629. return DefaultValue(v, ev)
  630. }
  631. type defaultValue struct {
  632. has bool
  633. val protoreflect.Value
  634. enum protoreflect.EnumValueDescriptor
  635. bytes []byte
  636. }
  637. func (dv *defaultValue) get(fd protoreflect.FieldDescriptor) protoreflect.Value {
  638. // Return the zero value as the default if unpopulated.
  639. if !dv.has {
  640. if fd.Cardinality() == protoreflect.Repeated {
  641. return protoreflect.Value{}
  642. }
  643. switch fd.Kind() {
  644. case protoreflect.BoolKind:
  645. return protoreflect.ValueOfBool(false)
  646. case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
  647. return protoreflect.ValueOfInt32(0)
  648. case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
  649. return protoreflect.ValueOfInt64(0)
  650. case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
  651. return protoreflect.ValueOfUint32(0)
  652. case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
  653. return protoreflect.ValueOfUint64(0)
  654. case protoreflect.FloatKind:
  655. return protoreflect.ValueOfFloat32(0)
  656. case protoreflect.DoubleKind:
  657. return protoreflect.ValueOfFloat64(0)
  658. case protoreflect.StringKind:
  659. return protoreflect.ValueOfString("")
  660. case protoreflect.BytesKind:
  661. return protoreflect.ValueOfBytes(nil)
  662. case protoreflect.EnumKind:
  663. if evs := fd.Enum().Values(); evs.Len() > 0 {
  664. return protoreflect.ValueOfEnum(evs.Get(0).Number())
  665. }
  666. return protoreflect.ValueOfEnum(0)
  667. }
  668. }
  669. if len(dv.bytes) > 0 && !bytes.Equal(dv.bytes, dv.val.Bytes()) {
  670. // TODO: Avoid panic if we're running with the race detector
  671. // and instead spawn a goroutine that periodically resets
  672. // this value back to the original to induce a race.
  673. panic(fmt.Sprintf("detected mutation on the default bytes for %v", fd.FullName()))
  674. }
  675. return dv.val
  676. }