legacy_enum.go 6.7 KB

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