desc.go 22 KB

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