legacy_enum.go 5.9 KB

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