desc.go 27 KB

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