message.go 10 KB

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