message.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.Oneof() != nil:
  105. fi = fieldInfoForOneof(fd, oneofsByName[fd.Oneof().Name()], oneofWrappersByNumber[fd.Number()])
  106. case fd.IsMap():
  107. fi = fieldInfoForMap(fd, fs)
  108. case fd.Cardinality() == pref.Repeated:
  109. fi = fieldInfoForList(fd, fs)
  110. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  111. fi = fieldInfoForMessage(fd, fs)
  112. default:
  113. fi = fieldInfoForScalar(fd, fs)
  114. }
  115. mi.fields[fd.Number()] = &fi
  116. }
  117. mi.oneofs = map[pref.Name]*oneofInfo{}
  118. for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
  119. od := mi.PBType.Oneofs().Get(i)
  120. mi.oneofs[od.Name()] = makeOneofInfo(od, oneofsByName[od.Name()], oneofWrappersByType)
  121. }
  122. }
  123. func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
  124. if f := makeLegacyUnknownFieldsFunc(t); f != nil {
  125. mi.unknownFields = f
  126. return
  127. }
  128. mi.unknownFields = func(*messageDataType) pref.UnknownFields {
  129. return emptyUnknownFields{}
  130. }
  131. }
  132. func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
  133. if f := makeLegacyExtensionFieldsFunc(t); f != nil {
  134. mi.extensionFields = f
  135. return
  136. }
  137. mi.extensionFields = func(*messageDataType) pref.KnownFields {
  138. return emptyExtensionFields{}
  139. }
  140. }
  141. func (mi *MessageType) MessageOf(p interface{}) pref.Message {
  142. return (*messageReflectWrapper)(mi.dataTypeOf(p))
  143. }
  144. func (mi *MessageType) Methods() *piface.Methods {
  145. return nil
  146. }
  147. func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
  148. // TODO: Remove this check? This API is primarily used by generated code,
  149. // and should not violate this assumption. Leave this check in for now to
  150. // provide some sanity checks during development. This can be removed if
  151. // it proves to be detrimental to performance.
  152. if reflect.TypeOf(p) != mi.GoType {
  153. panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
  154. }
  155. return &messageDataType{pointerOfIface(p), mi}
  156. }
  157. // messageDataType is a tuple of a pointer to the message data and
  158. // a pointer to the message type.
  159. //
  160. // TODO: Unfortunately, we need to close over a pointer and MessageType,
  161. // which incurs an an allocation. This pair is similar to a Go interface,
  162. // which is essentially a tuple of the same thing. We can make this efficient
  163. // with reflect.NamedOf (see https://golang.org/issues/16522).
  164. //
  165. // With that hypothetical API, we could dynamically create a new named type
  166. // that has the same underlying type as MessageType.GoType, and
  167. // dynamically create methods that close over MessageType.
  168. // Since the new type would have the same underlying type, we could directly
  169. // convert between pointers of those types, giving us an efficient way to swap
  170. // out the method set.
  171. //
  172. // Barring the ability to dynamically create named types, the workaround is
  173. // 1. either to accept the cost of an allocation for this wrapper struct or
  174. // 2. generate more types and methods, at the expense of binary size increase.
  175. type messageDataType struct {
  176. p pointer
  177. mi *MessageType
  178. }
  179. type messageReflectWrapper messageDataType
  180. func (m *messageReflectWrapper) Type() pref.MessageType {
  181. return m.mi.PBType
  182. }
  183. func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
  184. m.mi.init()
  185. return (*knownFields)(m)
  186. }
  187. func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
  188. m.mi.init()
  189. return m.mi.unknownFields((*messageDataType)(m))
  190. }
  191. func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
  192. if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
  193. return m
  194. }
  195. return (*messageIfaceWrapper)(m)
  196. }
  197. func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
  198. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  199. }
  200. func (m *messageReflectWrapper) ProtoMutable() {}
  201. var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
  202. type messageIfaceWrapper messageDataType
  203. func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
  204. return (*messageReflectWrapper)(m)
  205. }
  206. func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
  207. return m.mi.Methods()
  208. }
  209. func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
  210. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  211. }
  212. type knownFields messageDataType
  213. func (fs *knownFields) Len() (cnt int) {
  214. for _, fi := range fs.mi.fields {
  215. if fi.has(fs.p) {
  216. cnt++
  217. }
  218. }
  219. return cnt + fs.extensionFields().Len()
  220. }
  221. func (fs *knownFields) Has(n pref.FieldNumber) bool {
  222. if fi := fs.mi.fields[n]; fi != nil {
  223. return fi.has(fs.p)
  224. }
  225. return fs.extensionFields().Has(n)
  226. }
  227. func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
  228. if fi := fs.mi.fields[n]; fi != nil {
  229. return fi.get(fs.p)
  230. }
  231. return fs.extensionFields().Get(n)
  232. }
  233. func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
  234. if fi := fs.mi.fields[n]; fi != nil {
  235. fi.set(fs.p, v)
  236. return
  237. }
  238. if fs.mi.PBType.ExtensionRanges().Has(n) {
  239. fs.extensionFields().Set(n, v)
  240. return
  241. }
  242. panic(fmt.Sprintf("invalid field: %d", n))
  243. }
  244. func (fs *knownFields) Clear(n pref.FieldNumber) {
  245. if fi := fs.mi.fields[n]; fi != nil {
  246. fi.clear(fs.p)
  247. return
  248. }
  249. if fs.mi.PBType.ExtensionRanges().Has(n) {
  250. fs.extensionFields().Clear(n)
  251. return
  252. }
  253. }
  254. func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
  255. if oi := fs.mi.oneofs[s]; oi != nil {
  256. return oi.which(fs.p)
  257. }
  258. return 0
  259. }
  260. func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
  261. for n, fi := range fs.mi.fields {
  262. if fi.has(fs.p) {
  263. if !f(n, fi.get(fs.p)) {
  264. return
  265. }
  266. }
  267. }
  268. fs.extensionFields().Range(f)
  269. }
  270. func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
  271. if fi := fs.mi.fields[n]; fi != nil {
  272. return fi.newMessage()
  273. }
  274. if fs.mi.PBType.ExtensionRanges().Has(n) {
  275. return fs.extensionFields().NewMessage(n)
  276. }
  277. panic(fmt.Sprintf("invalid field: %d", n))
  278. }
  279. func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
  280. return fs.extensionFields().ExtensionTypes()
  281. }
  282. func (fs *knownFields) extensionFields() pref.KnownFields {
  283. return fs.mi.extensionFields((*messageDataType)(fs))
  284. }
  285. type emptyUnknownFields struct{}
  286. func (emptyUnknownFields) Len() int { return 0 }
  287. func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
  288. func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
  289. func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
  290. func (emptyUnknownFields) IsSupported() bool { return false }
  291. type emptyExtensionFields struct{}
  292. func (emptyExtensionFields) Len() int { return 0 }
  293. func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
  294. func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
  295. func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
  296. func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
  297. func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
  298. func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
  299. func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
  300. panic("extensions not supported")
  301. }
  302. func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
  303. type emptyExtensionTypes struct{}
  304. func (emptyExtensionTypes) Len() int { return 0 }
  305. func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
  306. func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
  307. func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
  308. func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
  309. func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }