message.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. "strconv"
  9. "strings"
  10. "sync"
  11. pvalue "github.com/golang/protobuf/v2/internal/value"
  12. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  13. piface "github.com/golang/protobuf/v2/runtime/protoiface"
  14. )
  15. // MessageType provides protobuf related functionality for a given Go type
  16. // that represents a message. A given instance of MessageType is tied to
  17. // exactly one Go type, which must be a pointer to a struct type.
  18. type MessageType struct {
  19. // GoType is the underlying message Go type and must be populated.
  20. // Once set, this field must never be mutated.
  21. GoType reflect.Type // pointer to struct
  22. // PBType is the underlying message descriptor type and must be populated.
  23. // Once set, this field must never be mutated.
  24. PBType pref.MessageType
  25. once sync.Once // protects all unexported fields
  26. // TODO: Split fields into dense and sparse maps similar to the current
  27. // table-driven implementation in v1?
  28. fields map[pref.FieldNumber]*fieldInfo
  29. unknownFields func(*messageDataType) pref.UnknownFields
  30. extensionFields func(*messageDataType) pref.KnownFields
  31. }
  32. func (mi *MessageType) init() {
  33. mi.once.Do(func() {
  34. t := mi.GoType
  35. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  36. panic(fmt.Sprintf("got %v, want *struct kind", t))
  37. }
  38. mi.makeKnownFieldsFunc(t.Elem())
  39. mi.makeUnknownFieldsFunc(t.Elem())
  40. mi.makeExtensionFieldsFunc(t.Elem())
  41. })
  42. }
  43. // makeKnownFieldsFunc generates functions for operations that can be performed
  44. // on each protobuf message field. It takes in a reflect.Type representing the
  45. // Go struct and matches message fields with struct fields.
  46. //
  47. // This code assumes that the struct is well-formed and panics if there are
  48. // any discrepancies.
  49. func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
  50. // Generate a mapping of field numbers and names to Go struct field or type.
  51. fields := map[pref.FieldNumber]reflect.StructField{}
  52. oneofs := map[pref.Name]reflect.StructField{}
  53. oneofFields := map[pref.FieldNumber]reflect.Type{}
  54. special := map[string]reflect.StructField{}
  55. fieldLoop:
  56. for i := 0; i < t.NumField(); i++ {
  57. f := t.Field(i)
  58. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  59. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  60. n, _ := strconv.ParseUint(s, 10, 64)
  61. fields[pref.FieldNumber(n)] = f
  62. continue fieldLoop
  63. }
  64. }
  65. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  66. oneofs[pref.Name(s)] = f
  67. continue fieldLoop
  68. }
  69. switch f.Name {
  70. case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
  71. special[f.Name] = f
  72. continue fieldLoop
  73. }
  74. }
  75. var oneofWrappers []interface{}
  76. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  77. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  78. }
  79. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  80. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  81. }
  82. for _, v := range oneofWrappers {
  83. tf := reflect.TypeOf(v).Elem()
  84. f := tf.Field(0)
  85. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  86. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  87. n, _ := strconv.ParseUint(s, 10, 64)
  88. oneofFields[pref.FieldNumber(n)] = tf
  89. break
  90. }
  91. }
  92. }
  93. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  94. for i := 0; i < mi.PBType.Fields().Len(); i++ {
  95. fd := mi.PBType.Fields().Get(i)
  96. fs := fields[fd.Number()]
  97. var fi fieldInfo
  98. switch {
  99. case fd.IsWeak():
  100. fi = fieldInfoForWeak(fd, special["XXX_weak"])
  101. case fd.OneofType() != nil:
  102. fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
  103. case fd.IsMap():
  104. fi = fieldInfoForMap(fd, fs)
  105. case fd.Cardinality() == pref.Repeated:
  106. fi = fieldInfoForList(fd, fs)
  107. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  108. fi = fieldInfoForMessage(fd, fs)
  109. default:
  110. fi = fieldInfoForScalar(fd, fs)
  111. }
  112. mi.fields[fd.Number()] = &fi
  113. }
  114. }
  115. func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
  116. if f := makeLegacyUnknownFieldsFunc(t); f != nil {
  117. mi.unknownFields = f
  118. return
  119. }
  120. mi.unknownFields = func(*messageDataType) pref.UnknownFields {
  121. return emptyUnknownFields{}
  122. }
  123. }
  124. func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
  125. if f := makeLegacyExtensionFieldsFunc(t); f != nil {
  126. mi.extensionFields = f
  127. return
  128. }
  129. mi.extensionFields = func(*messageDataType) pref.KnownFields {
  130. return emptyExtensionFields{}
  131. }
  132. }
  133. func (mi *MessageType) MessageOf(p interface{}) pref.Message {
  134. return (*messageReflectWrapper)(mi.dataTypeOf(p))
  135. }
  136. func (mi *MessageType) Methods() *piface.Methods {
  137. return nil
  138. }
  139. func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
  140. // TODO: Remove this check? This API is primarily used by generated code,
  141. // and should not violate this assumption. Leave this check in for now to
  142. // provide some sanity checks during development. This can be removed if
  143. // it proves to be detrimental to performance.
  144. if reflect.TypeOf(p) != mi.GoType {
  145. panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
  146. }
  147. return &messageDataType{pointerOfIface(p), mi}
  148. }
  149. // messageDataType is a tuple of a pointer to the message data and
  150. // a pointer to the message type.
  151. //
  152. // TODO: Unfortunately, we need to close over a pointer and MessageType,
  153. // which incurs an an allocation. This pair is similar to a Go interface,
  154. // which is essentially a tuple of the same thing. We can make this efficient
  155. // with reflect.NamedOf (see https://golang.org/issues/16522).
  156. //
  157. // With that hypothetical API, we could dynamically create a new named type
  158. // that has the same underlying type as MessageType.GoType, and
  159. // dynamically create methods that close over MessageType.
  160. // Since the new type would have the same underlying type, we could directly
  161. // convert between pointers of those types, giving us an efficient way to swap
  162. // out the method set.
  163. //
  164. // Barring the ability to dynamically create named types, the workaround is
  165. // 1. either to accept the cost of an allocation for this wrapper struct or
  166. // 2. generate more types and methods, at the expense of binary size increase.
  167. type messageDataType struct {
  168. p pointer
  169. mi *MessageType
  170. }
  171. type messageReflectWrapper messageDataType
  172. func (m *messageReflectWrapper) Type() pref.MessageType {
  173. return m.mi.PBType
  174. }
  175. func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
  176. m.mi.init()
  177. return (*knownFields)(m)
  178. }
  179. func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
  180. m.mi.init()
  181. return m.mi.unknownFields((*messageDataType)(m))
  182. }
  183. func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
  184. if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
  185. return m
  186. }
  187. return (*messageIfaceWrapper)(m)
  188. }
  189. func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
  190. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  191. }
  192. func (m *messageReflectWrapper) ProtoMutable() {}
  193. var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
  194. type messageIfaceWrapper messageDataType
  195. func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
  196. return (*messageReflectWrapper)(m)
  197. }
  198. func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
  199. return m.mi.Methods()
  200. }
  201. func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
  202. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  203. }
  204. type knownFields messageDataType
  205. func (fs *knownFields) Len() (cnt int) {
  206. for _, fi := range fs.mi.fields {
  207. if fi.has(fs.p) {
  208. cnt++
  209. }
  210. }
  211. return cnt + fs.extensionFields().Len()
  212. }
  213. func (fs *knownFields) Has(n pref.FieldNumber) bool {
  214. if fi := fs.mi.fields[n]; fi != nil {
  215. return fi.has(fs.p)
  216. }
  217. return fs.extensionFields().Has(n)
  218. }
  219. func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
  220. if fi := fs.mi.fields[n]; fi != nil {
  221. return fi.get(fs.p)
  222. }
  223. return fs.extensionFields().Get(n)
  224. }
  225. func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
  226. if fi := fs.mi.fields[n]; fi != nil {
  227. fi.set(fs.p, v)
  228. return
  229. }
  230. if fs.mi.PBType.ExtensionRanges().Has(n) {
  231. fs.extensionFields().Set(n, v)
  232. return
  233. }
  234. panic(fmt.Sprintf("invalid field: %d", n))
  235. }
  236. func (fs *knownFields) Clear(n pref.FieldNumber) {
  237. if fi := fs.mi.fields[n]; fi != nil {
  238. fi.clear(fs.p)
  239. return
  240. }
  241. if fs.mi.PBType.ExtensionRanges().Has(n) {
  242. fs.extensionFields().Clear(n)
  243. return
  244. }
  245. }
  246. func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
  247. for n, fi := range fs.mi.fields {
  248. if fi.has(fs.p) {
  249. if !f(n, fi.get(fs.p)) {
  250. return
  251. }
  252. }
  253. }
  254. fs.extensionFields().Range(f)
  255. }
  256. func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
  257. if fi := fs.mi.fields[n]; fi != nil {
  258. return fi.newMessage()
  259. }
  260. if fs.mi.PBType.ExtensionRanges().Has(n) {
  261. return fs.extensionFields().NewMessage(n)
  262. }
  263. panic(fmt.Sprintf("invalid field: %d", n))
  264. }
  265. func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
  266. return fs.extensionFields().ExtensionTypes()
  267. }
  268. func (fs *knownFields) extensionFields() pref.KnownFields {
  269. return fs.mi.extensionFields((*messageDataType)(fs))
  270. }
  271. type emptyUnknownFields struct{}
  272. func (emptyUnknownFields) Len() int { return 0 }
  273. func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
  274. func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
  275. func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
  276. func (emptyUnknownFields) IsSupported() bool { return false }
  277. type emptyExtensionFields struct{}
  278. func (emptyExtensionFields) Len() int { return 0 }
  279. func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
  280. func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
  281. func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
  282. func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
  283. func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
  284. func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
  285. panic("extensions not supported")
  286. }
  287. func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
  288. type emptyExtensionTypes struct{}
  289. func (emptyExtensionTypes) Len() int { return 0 }
  290. func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
  291. func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
  292. func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
  293. func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
  294. func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }