message.go 11 KB

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