convert.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 value provides functionality for wrapping Go values to implement
  5. // protoreflect values.
  6. package value
  7. import (
  8. "fmt"
  9. "reflect"
  10. pref "google.golang.org/protobuf/reflect/protoreflect"
  11. piface "google.golang.org/protobuf/runtime/protoiface"
  12. )
  13. // Unwrapper unwraps the value to the underlying value.
  14. // This is implemented by List and Map.
  15. type Unwrapper interface {
  16. ProtoUnwrap() interface{}
  17. }
  18. var (
  19. boolType = reflect.TypeOf(bool(false))
  20. int32Type = reflect.TypeOf(int32(0))
  21. int64Type = reflect.TypeOf(int64(0))
  22. uint32Type = reflect.TypeOf(uint32(0))
  23. uint64Type = reflect.TypeOf(uint64(0))
  24. float32Type = reflect.TypeOf(float32(0))
  25. float64Type = reflect.TypeOf(float64(0))
  26. stringType = reflect.TypeOf(string(""))
  27. bytesType = reflect.TypeOf([]byte(nil))
  28. enumIfaceV2 = reflect.TypeOf((*pref.Enum)(nil)).Elem()
  29. messageIfaceV1 = reflect.TypeOf((*piface.MessageV1)(nil)).Elem()
  30. messageIfaceV2 = reflect.TypeOf((*pref.ProtoMessage)(nil)).Elem()
  31. byteType = reflect.TypeOf(byte(0))
  32. )
  33. // NewConverter matches a Go type with a protobuf kind and returns a Converter
  34. // that converts between the two. NewConverter panics if it unable to provide a
  35. // conversion between the two. The Converter methods also panic when they are
  36. // called on incorrect Go types.
  37. //
  38. // This matcher deliberately supports a wider range of Go types than what
  39. // protoc-gen-go historically generated to be able to automatically wrap some
  40. // v1 messages generated by other forks of protoc-gen-go.
  41. func NewConverter(t reflect.Type, k pref.Kind) Converter {
  42. return NewLegacyConverter(t, k, nil)
  43. }
  44. // LegacyWrapper is a set of wrapper methods that wraps legacy v1 Go types
  45. // to implement the v2 reflection APIs.
  46. type (
  47. LegacyWrapper interface {
  48. EnumOf(interface{}) LegacyEnum
  49. EnumTypeOf(interface{}) pref.EnumType
  50. EnumDescriptorOf(interface{}) pref.EnumDescriptor
  51. MessageOf(interface{}) LegacyMessage
  52. MessageTypeOf(interface{}) pref.MessageType
  53. MessageDescriptorOf(interface{}) pref.MessageDescriptor
  54. // TODO: Remove these eventually.
  55. // See the TODOs in internal/impl/legacy_extension.go.
  56. ExtensionDescFromType(pref.ExtensionType) *piface.ExtensionDescV1
  57. ExtensionTypeFromDesc(*piface.ExtensionDescV1) pref.ExtensionType
  58. }
  59. LegacyEnum = interface {
  60. pref.Enum
  61. ProtoUnwrap() interface{}
  62. }
  63. LegacyMessage = interface {
  64. pref.Message
  65. ProtoUnwrap() interface{}
  66. }
  67. )
  68. // NewLegacyConverter is identical to NewConverter,
  69. // but supports wrapping legacy v1 messages to implement the v2 message API
  70. // using the provided LegacyWrapper.
  71. func NewLegacyConverter(t reflect.Type, k pref.Kind, w LegacyWrapper) Converter {
  72. switch k {
  73. case pref.BoolKind:
  74. if t.Kind() == reflect.Bool {
  75. return makeScalarConverter(t, boolType)
  76. }
  77. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  78. if t.Kind() == reflect.Int32 {
  79. return makeScalarConverter(t, int32Type)
  80. }
  81. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  82. if t.Kind() == reflect.Int64 {
  83. return makeScalarConverter(t, int64Type)
  84. }
  85. case pref.Uint32Kind, pref.Fixed32Kind:
  86. if t.Kind() == reflect.Uint32 {
  87. return makeScalarConverter(t, uint32Type)
  88. }
  89. case pref.Uint64Kind, pref.Fixed64Kind:
  90. if t.Kind() == reflect.Uint64 {
  91. return makeScalarConverter(t, uint64Type)
  92. }
  93. case pref.FloatKind:
  94. if t.Kind() == reflect.Float32 {
  95. return makeScalarConverter(t, float32Type)
  96. }
  97. case pref.DoubleKind:
  98. if t.Kind() == reflect.Float64 {
  99. return makeScalarConverter(t, float64Type)
  100. }
  101. case pref.StringKind:
  102. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  103. return makeScalarConverter(t, stringType)
  104. }
  105. case pref.BytesKind:
  106. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  107. return makeScalarConverter(t, bytesType)
  108. }
  109. case pref.EnumKind:
  110. // Handle enums, which must be a named int32 type.
  111. if t.PkgPath() != "" && t.Kind() == reflect.Int32 {
  112. var et pref.EnumType
  113. if t.Implements(enumIfaceV2) {
  114. et = &enumType{reflect.Zero(t).Interface().(pref.Enum).Descriptor(), t}
  115. } else {
  116. et = w.EnumTypeOf(reflect.Zero(t).Interface())
  117. }
  118. return Converter{
  119. PBValueOf: func(v reflect.Value) pref.Value {
  120. if v.Type() != t {
  121. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  122. }
  123. return pref.ValueOf(pref.EnumNumber(v.Int()))
  124. },
  125. GoValueOf: func(v pref.Value) reflect.Value {
  126. return reflect.ValueOf(v.Enum()).Convert(t)
  127. },
  128. EnumType: et,
  129. IsLegacy: !t.Implements(enumIfaceV2),
  130. }
  131. }
  132. case pref.MessageKind, pref.GroupKind:
  133. // Handle v2 messages, which must satisfy the proto.Message interface.
  134. if t.Kind() == reflect.Ptr && t.Implements(messageIfaceV2) {
  135. md := reflect.Zero(t).Interface().(pref.ProtoMessage).ProtoReflect().Descriptor()
  136. mt := &messageType{md, t}
  137. return Converter{
  138. PBValueOf: func(v reflect.Value) pref.Value {
  139. if v.Type() != t {
  140. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  141. }
  142. return pref.ValueOf(v.Interface().(pref.ProtoMessage).ProtoReflect())
  143. },
  144. GoValueOf: func(v pref.Value) reflect.Value {
  145. rv := reflect.ValueOf(v.Message().Interface())
  146. if rv.Type() != t {
  147. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  148. }
  149. return rv
  150. },
  151. MessageType: mt,
  152. }
  153. }
  154. // Handle v1 messages, which we need to wrap as a v2 message.
  155. if w != nil && t.Kind() == reflect.Ptr && t.Implements(messageIfaceV1) {
  156. mt := w.MessageTypeOf(reflect.Zero(t).Interface())
  157. return Converter{
  158. PBValueOf: func(v reflect.Value) pref.Value {
  159. if v.Type() != t {
  160. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  161. }
  162. return pref.ValueOf(w.MessageOf(v.Interface()))
  163. },
  164. GoValueOf: func(v pref.Value) reflect.Value {
  165. rv := reflect.ValueOf(v.Message().(Unwrapper).ProtoUnwrap())
  166. if rv.Type() != t {
  167. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  168. }
  169. return rv
  170. },
  171. MessageType: mt,
  172. IsLegacy: true,
  173. }
  174. }
  175. }
  176. panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
  177. }
  178. func makeScalarConverter(goType, pbType reflect.Type) Converter {
  179. return Converter{
  180. PBValueOf: func(v reflect.Value) pref.Value {
  181. if v.Type() != goType {
  182. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), goType))
  183. }
  184. if goType.Kind() == reflect.String && pbType.Kind() == reflect.Slice && v.Len() == 0 {
  185. return pref.ValueOf([]byte(nil)) // ensure empty string is []byte(nil)
  186. }
  187. return pref.ValueOf(v.Convert(pbType).Interface())
  188. },
  189. GoValueOf: func(v pref.Value) reflect.Value {
  190. rv := reflect.ValueOf(v.Interface())
  191. if rv.Type() != pbType {
  192. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), pbType))
  193. }
  194. if pbType.Kind() == reflect.String && goType.Kind() == reflect.Slice && rv.Len() == 0 {
  195. return reflect.Zero(goType) // ensure empty string is []byte(nil)
  196. }
  197. return rv.Convert(goType)
  198. },
  199. }
  200. }
  201. // Converter provides functions for converting to/from Go reflect.Value types
  202. // and protobuf protoreflect.Value types.
  203. type Converter struct {
  204. PBValueOf func(reflect.Value) pref.Value
  205. GoValueOf func(pref.Value) reflect.Value
  206. EnumType pref.EnumType
  207. MessageType pref.MessageType
  208. IsLegacy bool
  209. }
  210. // TODO: This needs to be centralized in a package.
  211. type enumType struct {
  212. // TODO: Remove me as an embedded field.
  213. pref.EnumDescriptor
  214. typ reflect.Type // must implement protoreflect.Enum
  215. }
  216. func (t *enumType) Descriptor() pref.EnumDescriptor { return t.EnumDescriptor }
  217. func (t *enumType) GoType() reflect.Type { return t.typ }
  218. func (t *enumType) New(n pref.EnumNumber) pref.Enum {
  219. return reflect.ValueOf(n).Convert(t.typ).Interface().(pref.Enum)
  220. }
  221. // TODO: This needs to be centralized in a package.
  222. type messageType struct {
  223. // TODO: Remove me as an embedded field.
  224. pref.MessageDescriptor
  225. typ reflect.Type // must implement protoreflect.ProtoMessage
  226. }
  227. func (t *messageType) Descriptor() pref.MessageDescriptor { return t.MessageDescriptor }
  228. func (t *messageType) GoType() reflect.Type { return t.typ }
  229. func (t *messageType) New() pref.Message {
  230. return reflect.New(t.typ.Elem()).Interface().(pref.ProtoMessage).ProtoReflect()
  231. }