message.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. }
  31. // init lazily initializes the MessageType upon first use and
  32. // also checks that the provided pointer p is of the correct Go type.
  33. //
  34. // It must be called at the start of every exported method.
  35. func (mi *MessageType) init(p interface{}) {
  36. mi.once.Do(func() {
  37. v := reflect.ValueOf(p)
  38. t := v.Type()
  39. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  40. panic(fmt.Sprintf("got %v, want *struct kind", t))
  41. }
  42. mi.goType = t
  43. // Derive the message descriptor if unspecified.
  44. md := mi.Desc
  45. if md == nil {
  46. // TODO: derive the message type from the Go struct type
  47. }
  48. // Initialize the Go message type wrapper if the Go type does not
  49. // implement the proto.Message interface.
  50. //
  51. // Otherwise, we assume that the Go type manually implements the
  52. // interface and is internally consistent such that:
  53. // goType == reflect.New(goType.Elem()).Interface().(proto.Message).ProtoReflect().Type().GoType()
  54. //
  55. // Generated code ensures that this property holds.
  56. if _, ok := p.(pref.ProtoMessage); !ok {
  57. mi.pbType = ptype.NewGoMessage(&ptype.GoMessage{
  58. MessageDescriptor: md,
  59. New: func(pref.MessageType) pref.ProtoMessage {
  60. p := reflect.New(t.Elem()).Interface()
  61. return (*message)(mi.dataTypeOf(p))
  62. },
  63. })
  64. }
  65. mi.generateFieldFuncs(t.Elem(), md)
  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. // generateFieldFuncs generates per-field functions for all common 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) generateFieldFuncs(t reflect.Type, md pref.MessageDescriptor) {
  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 := t.MethodByName("XXX_OneofFuncs"); ok {
  109. vs := fn.Func.Call([]reflect.Value{reflect.New(fn.Type.In(0)).Elem()})[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 < md.Fields().Len(); i++ {
  125. fd := md.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) MessageOf(p interface{}) pref.Message {
  146. mi.init(p)
  147. if m, ok := p.(pref.ProtoMessage); ok {
  148. // We assume p properly implements protoreflect.Message.
  149. // See the comment in MessageType.init regarding pbType.
  150. return m.ProtoReflect()
  151. }
  152. return (*message)(mi.dataTypeOf(p))
  153. }
  154. func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
  155. mi.init(p)
  156. return (*knownFields)(mi.dataTypeOf(p))
  157. }
  158. func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
  159. mi.init(p)
  160. return (*unknownFields)(mi.dataTypeOf(p))
  161. }
  162. func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
  163. return &messageDataType{pointerOfIface(&p), mi}
  164. }
  165. // messageDataType is a tuple of a pointer to the message data and
  166. // a pointer to the message type.
  167. //
  168. // TODO: Unfortunately, we need to close over a pointer and MessageType,
  169. // which incurs an an allocation. This pair is similar to a Go interface,
  170. // which is essentially a tuple of the same thing. We can make this efficient
  171. // with reflect.NamedOf (see https://golang.org/issues/16522).
  172. //
  173. // With that hypothetical API, we could dynamically create a new named type
  174. // that has the same underlying type as MessageType.goType, and
  175. // dynamically create methods that close over MessageType.
  176. // Since the new type would have the same underlying type, we could directly
  177. // convert between pointers of those types, giving us an efficient way to swap
  178. // out the method set.
  179. //
  180. // Barring the ability to dynamically create named types, the workaround is
  181. // 1. either to accept the cost of an allocation for this wrapper struct or
  182. // 2. generate more types and methods, at the expense of binary size increase.
  183. type messageDataType struct {
  184. p pointer
  185. mi *MessageType
  186. }
  187. type message messageDataType
  188. func (m *message) Type() pref.MessageType {
  189. return m.mi.pbType
  190. }
  191. func (m *message) KnownFields() pref.KnownFields {
  192. return (*knownFields)(m)
  193. }
  194. func (m *message) UnknownFields() pref.UnknownFields {
  195. return (*unknownFields)(m)
  196. }
  197. func (m *message) Unwrap() interface{} {
  198. return m.p.asType(m.mi.goType.Elem()).Interface()
  199. }
  200. func (m *message) Interface() pref.ProtoMessage {
  201. return m
  202. }
  203. func (m *message) ProtoReflect() pref.Message {
  204. return m
  205. }
  206. func (m *message) ProtoMutable() {}
  207. type knownFields messageDataType
  208. func (fs *knownFields) List() (nums []pref.FieldNumber) {
  209. for n, fi := range fs.mi.fields {
  210. if fi.has(fs.p) {
  211. nums = append(nums, n)
  212. }
  213. }
  214. // TODO: Handle extension fields.
  215. return nums
  216. }
  217. func (fs *knownFields) Len() (cnt int) {
  218. for _, fi := range fs.mi.fields {
  219. if fi.has(fs.p) {
  220. cnt++
  221. }
  222. }
  223. // TODO: Handle extension fields.
  224. return cnt
  225. }
  226. func (fs *knownFields) Has(n pref.FieldNumber) bool {
  227. if fi := fs.mi.fields[n]; fi != nil {
  228. return fi.has(fs.p)
  229. }
  230. // TODO: Handle extension fields.
  231. return false
  232. }
  233. func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
  234. if fi := fs.mi.fields[n]; fi != nil {
  235. return fi.get(fs.p)
  236. }
  237. // TODO: Handle extension fields.
  238. return pref.Value{}
  239. }
  240. func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
  241. if fi := fs.mi.fields[n]; fi != nil {
  242. fi.set(fs.p, v)
  243. return
  244. }
  245. // TODO: Handle extension fields.
  246. panic("invalid field")
  247. }
  248. func (fs *knownFields) Clear(n pref.FieldNumber) {
  249. if fi := fs.mi.fields[n]; fi != nil {
  250. fi.clear(fs.p)
  251. return
  252. }
  253. // TODO: Handle extension fields.
  254. panic("invalid field")
  255. }
  256. func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
  257. if fi := fs.mi.fields[n]; fi != nil {
  258. return fi.mutable(fs.p)
  259. }
  260. // TODO: Handle extension fields.
  261. panic("invalid field")
  262. }
  263. func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
  264. for n, fi := range fs.mi.fields {
  265. if fi.has(fs.p) {
  266. if !f(n, fi.get(fs.p)) {
  267. return
  268. }
  269. }
  270. }
  271. // TODO: Handle extension fields.
  272. }
  273. func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
  274. return (*extensionFieldTypes)(fs)
  275. }
  276. type extensionFieldTypes messageDataType // TODO
  277. func (fs *extensionFieldTypes) List() []pref.ExtensionType { return nil }
  278. func (fs *extensionFieldTypes) Len() int { return 0 }
  279. func (fs *extensionFieldTypes) Register(pref.ExtensionType) { return }
  280. func (fs *extensionFieldTypes) Remove(pref.ExtensionType) { return }
  281. func (fs *extensionFieldTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
  282. func (fs *extensionFieldTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
  283. func (fs *extensionFieldTypes) Range(f func(pref.ExtensionType) bool) { return }
  284. type unknownFields messageDataType // TODO
  285. func (fs *unknownFields) List() []pref.FieldNumber { return nil }
  286. func (fs *unknownFields) Len() int { return 0 }
  287. func (fs *unknownFields) Get(n pref.FieldNumber) pref.RawFields { return nil }
  288. func (fs *unknownFields) Set(n pref.FieldNumber, b pref.RawFields) { return }
  289. func (fs *unknownFields) Range(f func(pref.FieldNumber, pref.RawFields) bool) { return }
  290. func (fs *unknownFields) IsSupported() bool { return false }