legacy_enum.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 impl
  5. import (
  6. "fmt"
  7. "reflect"
  8. "strings"
  9. "sync"
  10. "google.golang.org/protobuf/internal/filedesc"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. pref "google.golang.org/protobuf/reflect/protoreflect"
  13. )
  14. // legacyWrapEnum wraps v as a protoreflect.Enum,
  15. // where v must be a int32 kind and not implement the v2 API already.
  16. func legacyWrapEnum(v reflect.Value) pref.Enum {
  17. et := legacyLoadEnumType(v.Type())
  18. return et.New(pref.EnumNumber(v.Int()))
  19. }
  20. var legacyEnumTypeCache sync.Map // map[reflect.Type]protoreflect.EnumType
  21. // legacyLoadEnumType dynamically loads a protoreflect.EnumType for t,
  22. // where t must be an int32 kind and not implement the v2 API already.
  23. func legacyLoadEnumType(t reflect.Type) pref.EnumType {
  24. // Fast-path: check if a EnumType is cached for this concrete type.
  25. if et, ok := legacyEnumTypeCache.Load(t); ok {
  26. return et.(pref.EnumType)
  27. }
  28. // Slow-path: derive enum descriptor and initialize EnumType.
  29. var et pref.EnumType
  30. ed := LegacyLoadEnumDesc(t)
  31. et = &legacyEnumType{
  32. desc: ed,
  33. goType: t,
  34. }
  35. if et, ok := legacyEnumTypeCache.LoadOrStore(t, et); ok {
  36. return et.(pref.EnumType)
  37. }
  38. return et
  39. }
  40. type legacyEnumType struct {
  41. desc pref.EnumDescriptor
  42. goType reflect.Type
  43. m sync.Map // map[protoreflect.EnumNumber]proto.Enum
  44. }
  45. func (t *legacyEnumType) New(n pref.EnumNumber) pref.Enum {
  46. if e, ok := t.m.Load(n); ok {
  47. return e.(pref.Enum)
  48. }
  49. e := &legacyEnumWrapper{num: n, pbTyp: t, goTyp: t.goType}
  50. t.m.Store(n, e)
  51. return e
  52. }
  53. func (t *legacyEnumType) GoType() reflect.Type {
  54. return t.goType
  55. }
  56. func (t *legacyEnumType) Descriptor() pref.EnumDescriptor {
  57. return t.desc
  58. }
  59. type legacyEnumWrapper struct {
  60. num pref.EnumNumber
  61. pbTyp pref.EnumType
  62. goTyp reflect.Type
  63. }
  64. func (e *legacyEnumWrapper) Descriptor() pref.EnumDescriptor {
  65. return e.pbTyp.Descriptor()
  66. }
  67. func (e *legacyEnumWrapper) Type() pref.EnumType {
  68. return e.pbTyp
  69. }
  70. func (e *legacyEnumWrapper) Number() pref.EnumNumber {
  71. return e.num
  72. }
  73. func (e *legacyEnumWrapper) ProtoReflect() pref.Enum {
  74. return e
  75. }
  76. func (e *legacyEnumWrapper) ProtoUnwrap() interface{} {
  77. v := reflect.New(e.goTyp).Elem()
  78. v.SetInt(int64(e.num))
  79. return v.Interface()
  80. }
  81. var (
  82. _ pref.Enum = (*legacyEnumWrapper)(nil)
  83. _ Unwrapper = (*legacyEnumWrapper)(nil)
  84. )
  85. var legacyEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor
  86. // LegacyLoadEnumDesc returns an EnumDescriptor derived from the Go type,
  87. // which must be an int32 kind and not implement the v2 API already.
  88. //
  89. // This is exported for testing purposes.
  90. func LegacyLoadEnumDesc(t reflect.Type) pref.EnumDescriptor {
  91. // Fast-path: check if an EnumDescriptor is cached for this concrete type.
  92. if ed, ok := legacyEnumDescCache.Load(t); ok {
  93. return ed.(pref.EnumDescriptor)
  94. }
  95. // Slow-path: initialize EnumDescriptor from the raw descriptor.
  96. ev := reflect.Zero(t).Interface()
  97. if _, ok := ev.(pref.Enum); ok {
  98. panic(fmt.Sprintf("%v already implements proto.Enum", t))
  99. }
  100. edV1, ok := ev.(enumV1)
  101. if !ok {
  102. return aberrantLoadEnumDesc(t)
  103. }
  104. b, idxs := edV1.EnumDescriptor()
  105. var ed pref.EnumDescriptor
  106. if len(idxs) == 1 {
  107. ed = legacyLoadFileDesc(b).Enums().Get(idxs[0])
  108. } else {
  109. md := legacyLoadFileDesc(b).Messages().Get(idxs[0])
  110. for _, i := range idxs[1 : len(idxs)-1] {
  111. md = md.Messages().Get(i)
  112. }
  113. ed = md.Enums().Get(idxs[len(idxs)-1])
  114. }
  115. if ed, ok := legacyEnumDescCache.LoadOrStore(t, ed); ok {
  116. return ed.(protoreflect.EnumDescriptor)
  117. }
  118. return ed
  119. }
  120. var aberrantEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor
  121. // aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type,
  122. // which must not implement protoreflect.Enum or enumV1.
  123. //
  124. // If the type does not implement enumV1, then there is no reliable
  125. // way to derive the original protobuf type information.
  126. // We are unable to use the global enum registry since it is
  127. // unfortunately keyed by the protobuf full name, which we also do not know.
  128. // Thus, this produces some bogus enum descriptor based on the Go type name.
  129. func aberrantLoadEnumDesc(t reflect.Type) pref.EnumDescriptor {
  130. // Fast-path: check if an EnumDescriptor is cached for this concrete type.
  131. if ed, ok := aberrantEnumDescCache.Load(t); ok {
  132. return ed.(pref.EnumDescriptor)
  133. }
  134. // Slow-path: construct a bogus, but unique EnumDescriptor.
  135. ed := &filedesc.Enum{L2: new(filedesc.EnumL2)}
  136. ed.L0.FullName = aberrantDeriveFullName(t) // e.g., github_com.user.repo.MyEnum
  137. ed.L0.ParentFile = filedesc.SurrogateProto3
  138. ed.L2.Values.List = append(ed.L2.Values.List, filedesc.EnumValue{})
  139. // TODO: Use the presence of a UnmarshalJSON method to determine proto2?
  140. vd := &ed.L2.Values.List[0]
  141. vd.L0.FullName = ed.L0.FullName + "_UNKNOWN" // e.g., github_com.user.repo.MyEnum_UNKNOWN
  142. vd.L0.ParentFile = ed.L0.ParentFile
  143. vd.L0.Parent = ed
  144. // TODO: We could use the String method to obtain some enum value names by
  145. // starting at 0 and print the enum until it produces invalid identifiers.
  146. // An exhaustive query is clearly impractical, but can be best-effort.
  147. if ed, ok := aberrantEnumDescCache.LoadOrStore(t, ed); ok {
  148. return ed.(pref.EnumDescriptor)
  149. }
  150. return ed
  151. }
  152. // aberrantDeriveFullName derives a fully qualified protobuf name for the given Go type
  153. // The provided name is not guaranteed to be stable nor universally unique.
  154. // It should be sufficiently unique within a program.
  155. func aberrantDeriveFullName(t reflect.Type) pref.FullName {
  156. sanitize := func(r rune) rune {
  157. switch {
  158. case r == '/':
  159. return '.'
  160. case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9':
  161. return r
  162. default:
  163. return '_'
  164. }
  165. }
  166. prefix := strings.Map(sanitize, t.PkgPath())
  167. suffix := strings.Map(sanitize, t.Name())
  168. if suffix == "" {
  169. suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer())
  170. }
  171. ss := append(strings.Split(prefix, "."), suffix)
  172. for i, s := range ss {
  173. if s == "" || ('0' <= s[0] && s[0] <= '9') {
  174. ss[i] = "x" + s
  175. }
  176. }
  177. return pref.FullName(strings.Join(ss, "."))
  178. }