message.go 12 KB

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