legacy_enum.go 6.5 KB

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