message.go 11 KB

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