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