legacy_enum.go 6.0 KB

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