blob: 469b255d10264fe570dcf2f3ebb02188bb444f62 [file] [log] [blame]
Joe Tsai82760ce2019-06-20 03:09:57 -07001// Copyright 2019 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
5package impl
6
7import (
8 "fmt"
9 "reflect"
10
11 "google.golang.org/protobuf/internal/pragma"
Joe Tsai82760ce2019-06-20 03:09:57 -070012 pref "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai82760ce2019-06-20 03:09:57 -070013)
14
Joe Tsai0484b1a2019-08-13 15:36:08 -070015type reflectMessageInfo struct {
16 fields map[pref.FieldNumber]*fieldInfo
17 oneofs map[pref.Name]*oneofInfo
18
19 getUnknown func(pointer) pref.RawFields
20 setUnknown func(pointer, pref.RawFields)
21 extensionMap func(pointer) *extensionMap
22
23 nilMessage atomicNilMessage
24}
25
26// makeReflectFuncs generates the set of functions to support reflection.
27func (mi *MessageInfo) makeReflectFuncs(t reflect.Type, si structInfo) {
28 mi.makeKnownFieldsFunc(si)
29 mi.makeUnknownFieldsFunc(t, si)
30 mi.makeExtensionFieldsFunc(t, si)
31}
32
33// makeKnownFieldsFunc generates functions for operations that can be performed
34// on each protobuf message field. It takes in a reflect.Type representing the
35// Go struct and matches message fields with struct fields.
36//
37// This code assumes that the struct is well-formed and panics if there are
38// any discrepancies.
39func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
40 mi.fields = map[pref.FieldNumber]*fieldInfo{}
41 md := mi.Desc
42 for i := 0; i < md.Fields().Len(); i++ {
43 fd := md.Fields().Get(i)
44 fs := si.fieldsByNumber[fd.Number()]
45 var fi fieldInfo
46 switch {
47 case fd.ContainingOneof() != nil:
48 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()])
49 case fd.IsMap():
50 fi = fieldInfoForMap(fd, fs, mi.Exporter)
51 case fd.IsList():
52 fi = fieldInfoForList(fd, fs, mi.Exporter)
53 case fd.IsWeak():
54 fi = fieldInfoForWeakMessage(fd, si.weakOffset)
55 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
56 fi = fieldInfoForMessage(fd, fs, mi.Exporter)
57 default:
58 fi = fieldInfoForScalar(fd, fs, mi.Exporter)
59 }
60 mi.fields[fd.Number()] = &fi
61 }
62
63 mi.oneofs = map[pref.Name]*oneofInfo{}
64 for i := 0; i < md.Oneofs().Len(); i++ {
65 od := md.Oneofs().Get(i)
66 mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], mi.Exporter, si.oneofWrappersByType)
67 }
68}
69
70func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) {
71 mi.getUnknown = func(pointer) pref.RawFields { return nil }
72 mi.setUnknown = func(pointer, pref.RawFields) { return }
73 if si.unknownOffset.IsValid() {
74 mi.getUnknown = func(p pointer) pref.RawFields {
75 if p.IsNil() {
76 return nil
77 }
78 rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
79 return pref.RawFields(*rv.Interface().(*[]byte))
80 }
81 mi.setUnknown = func(p pointer, b pref.RawFields) {
82 if p.IsNil() {
83 panic("invalid SetUnknown on nil Message")
84 }
85 rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
86 *rv.Interface().(*[]byte) = []byte(b)
87 }
88 } else {
89 mi.getUnknown = func(pointer) pref.RawFields {
90 return nil
91 }
92 mi.setUnknown = func(p pointer, _ pref.RawFields) {
93 if p.IsNil() {
94 panic("invalid SetUnknown on nil Message")
95 }
96 }
97 }
98}
99
100func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) {
101 if si.extensionOffset.IsValid() {
102 mi.extensionMap = func(p pointer) *extensionMap {
103 if p.IsNil() {
104 return (*extensionMap)(nil)
105 }
106 v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType)
107 return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
108 }
109 } else {
110 mi.extensionMap = func(pointer) *extensionMap {
111 return (*extensionMap)(nil)
112 }
113 }
114}
115
116type extensionMap map[int32]ExtensionField
117
118func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
119 if m != nil {
120 for _, x := range *m {
121 xt := x.GetType()
Damien Neil68b81c32019-08-22 11:41:32 -0700122 if !f(xt.TypeDescriptor(), x.Value()) {
Joe Tsai0484b1a2019-08-13 15:36:08 -0700123 return
124 }
125 }
126 }
127}
128func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
129 if m != nil {
Damien Neil79bfdbe2019-08-28 11:08:22 -0700130 _, ok = (*m)[int32(xt.TypeDescriptor().Number())]
Joe Tsai0484b1a2019-08-13 15:36:08 -0700131 }
132 return ok
133}
134func (m *extensionMap) Clear(xt pref.ExtensionType) {
Damien Neil79bfdbe2019-08-28 11:08:22 -0700135 delete(*m, int32(xt.TypeDescriptor().Number()))
Joe Tsai0484b1a2019-08-13 15:36:08 -0700136}
137func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
Damien Neil79bfdbe2019-08-28 11:08:22 -0700138 xd := xt.TypeDescriptor()
Joe Tsai0484b1a2019-08-13 15:36:08 -0700139 if m != nil {
140 if x, ok := (*m)[int32(xd.Number())]; ok {
Damien Neil68b81c32019-08-22 11:41:32 -0700141 return x.Value()
Joe Tsai0484b1a2019-08-13 15:36:08 -0700142 }
143 }
144 return xt.Zero()
145}
146func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
Damien Neil68b81c32019-08-22 11:41:32 -0700147 if !xt.IsValidValue(v) {
148 panic(fmt.Errorf("%v: assigning invalid value", xt.TypeDescriptor().FullName()))
149 }
Joe Tsai0484b1a2019-08-13 15:36:08 -0700150 if *m == nil {
151 *m = make(map[int32]ExtensionField)
152 }
153 var x ExtensionField
Damien Neil68b81c32019-08-22 11:41:32 -0700154 x.Set(xt, v)
Damien Neil79bfdbe2019-08-28 11:08:22 -0700155 (*m)[int32(xt.TypeDescriptor().Number())] = x
Joe Tsai0484b1a2019-08-13 15:36:08 -0700156}
157func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
Damien Neil79bfdbe2019-08-28 11:08:22 -0700158 xd := xt.TypeDescriptor()
Joe Tsai0484b1a2019-08-13 15:36:08 -0700159 if xd.Kind() != pref.MessageKind && xd.Kind() != pref.GroupKind && !xd.IsList() && !xd.IsMap() {
160 panic("invalid Mutable on field with non-composite type")
161 }
162 if x, ok := (*m)[int32(xd.Number())]; ok {
Damien Neil68b81c32019-08-22 11:41:32 -0700163 return x.Value()
Joe Tsai0484b1a2019-08-13 15:36:08 -0700164 }
165 v := xt.New()
166 m.Set(xt, v)
167 return v
168}
169
Joe Tsai82760ce2019-06-20 03:09:57 -0700170// MessageState is a data structure that is nested as the first field in a
171// concrete message. It provides a way to implement the ProtoReflect method
172// in an allocation-free way without needing to have a shadow Go type generated
173// for every message type. This technique only works using unsafe.
174//
175//
176// Example generated code:
177//
178// type M struct {
179// state protoimpl.MessageState
180//
181// Field1 int32
182// Field2 string
183// Field3 *BarMessage
184// ...
185// }
186//
187// func (m *M) ProtoReflect() protoreflect.Message {
188// mi := &file_fizz_buzz_proto_msgInfos[5]
189// if protoimpl.UnsafeEnabled && m != nil {
190// ms := protoimpl.X.MessageStateOf(Pointer(m))
191// if ms.LoadMessageInfo() == nil {
192// ms.StoreMessageInfo(mi)
193// }
194// return ms
195// }
196// return mi.MessageOf(m)
197// }
198//
199// The MessageState type holds a *MessageInfo, which must be atomically set to
200// the message info associated with a given message instance.
201// By unsafely converting a *M into a *MessageState, the MessageState object
202// has access to all the information needed to implement protobuf reflection.
203// It has access to the message info as its first field, and a pointer to the
204// MessageState is identical to a pointer to the concrete message value.
205//
206//
207// Requirements:
208// • The type M must implement protoreflect.ProtoMessage.
209// • The address of m must not be nil.
210// • The address of m and the address of m.state must be equal,
211// even though they are different Go types.
212type MessageState struct {
213 pragma.NoUnkeyedLiterals
214 pragma.DoNotCompare
215 pragma.DoNotCopy
216
217 mi *MessageInfo
218}
219
220type messageState MessageState
221
222var (
Damien Neil954bd922019-07-17 16:52:10 -0700223 _ pref.Message = (*messageState)(nil)
224 _ Unwrapper = (*messageState)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700225)
226
227// messageDataType is a tuple of a pointer to the message data and
228// a pointer to the message type. It is a generalized way of providing a
229// reflective view over a message instance. The disadvantage of this approach
230// is the need to allocate this tuple of 16B.
231type messageDataType struct {
232 p pointer
233 mi *MessageInfo
234}
235
236type (
Joe Tsai82760ce2019-06-20 03:09:57 -0700237 messageReflectWrapper messageDataType
Joe Tsai0f81b382019-07-10 23:14:31 -0700238 messageIfaceWrapper messageDataType
Joe Tsai82760ce2019-06-20 03:09:57 -0700239)
240
241var (
242 _ pref.Message = (*messageReflectWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -0700243 _ Unwrapper = (*messageReflectWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700244 _ pref.ProtoMessage = (*messageIfaceWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -0700245 _ Unwrapper = (*messageIfaceWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700246)
247
248// MessageOf returns a reflective view over a message. The input must be a
249// pointer to a named Go struct. If the provided type has a ProtoReflect method,
250// it must be implemented by calling this method.
251func (mi *MessageInfo) MessageOf(m interface{}) pref.Message {
252 // TODO: Switch the input to be an opaque Pointer.
Damien Neil16163b42019-08-06 15:43:25 -0700253 if reflect.TypeOf(m) != mi.GoReflectType {
254 panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoReflectType))
Joe Tsai82760ce2019-06-20 03:09:57 -0700255 }
256 p := pointerOfIface(m)
257 if p.IsNil() {
258 return mi.nilMessage.Init(mi)
259 }
260 return &messageReflectWrapper{p, mi}
261}
262
Joe Tsai2aea6142019-07-31 12:27:30 -0700263func (m *messageReflectWrapper) pointer() pointer { return m.p }
264func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi }
Joe Tsai82760ce2019-06-20 03:09:57 -0700265
266func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
267 return (*messageReflectWrapper)(m)
268}
Joe Tsai82760ce2019-06-20 03:09:57 -0700269func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
Damien Neil16163b42019-08-06 15:43:25 -0700270 return m.p.AsIfaceOf(m.mi.GoReflectType.Elem())
Joe Tsai82760ce2019-06-20 03:09:57 -0700271}
Joe Tsai82760ce2019-06-20 03:09:57 -0700272
Joe Tsai82760ce2019-06-20 03:09:57 -0700273// checkField verifies that the provided field descriptor is valid.
274// Exactly one of the returned values is populated.
275func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
276 if fi := mi.fields[fd.Number()]; fi != nil {
277 if fi.fieldDesc != fd {
278 panic("mismatching field descriptor")
279 }
280 return fi, nil
281 }
282 if fd.IsExtension() {
Damien Neil16163b42019-08-06 15:43:25 -0700283 if fd.ContainingMessage().FullName() != mi.Desc.FullName() {
Joe Tsai82760ce2019-06-20 03:09:57 -0700284 // TODO: Should this be exact containing message descriptor match?
285 panic("mismatching containing message")
286 }
Damien Neil16163b42019-08-06 15:43:25 -0700287 if !mi.Desc.ExtensionRanges().Has(fd.Number()) {
Joe Tsai82760ce2019-06-20 03:09:57 -0700288 panic("invalid extension field")
289 }
Damien Neil92f76182019-08-02 16:58:08 -0700290 xtd, ok := fd.(pref.ExtensionTypeDescriptor)
291 if !ok {
292 panic("extension descriptor does not implement ExtensionTypeDescriptor")
293 }
294 return nil, xtd.Type()
Joe Tsai82760ce2019-06-20 03:09:57 -0700295 }
296 panic("invalid field descriptor")
297}