blob: b01622b2a85838578f433bb1300cfb2644e98821 [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()
122 if !f(xt.Descriptor(), xt.ValueOf(x.GetValue())) {
123 return
124 }
125 }
126 }
127}
128func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
129 if m != nil {
130 _, ok = (*m)[int32(xt.Descriptor().Number())]
131 }
132 return ok
133}
134func (m *extensionMap) Clear(xt pref.ExtensionType) {
135 delete(*m, int32(xt.Descriptor().Number()))
136}
137func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
138 xd := xt.Descriptor()
139 if m != nil {
140 if x, ok := (*m)[int32(xd.Number())]; ok {
141 return xt.ValueOf(x.GetValue())
142 }
143 }
144 return xt.Zero()
145}
146func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
147 if *m == nil {
148 *m = make(map[int32]ExtensionField)
149 }
150 var x ExtensionField
151 x.SetType(xt)
152 x.SetEagerValue(xt.InterfaceOf(v))
153 (*m)[int32(xt.Descriptor().Number())] = x
154}
155func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
156 xd := xt.Descriptor()
157 if xd.Kind() != pref.MessageKind && xd.Kind() != pref.GroupKind && !xd.IsList() && !xd.IsMap() {
158 panic("invalid Mutable on field with non-composite type")
159 }
160 if x, ok := (*m)[int32(xd.Number())]; ok {
161 return xt.ValueOf(x.GetValue())
162 }
163 v := xt.New()
164 m.Set(xt, v)
165 return v
166}
167
Joe Tsai82760ce2019-06-20 03:09:57 -0700168// MessageState is a data structure that is nested as the first field in a
169// concrete message. It provides a way to implement the ProtoReflect method
170// in an allocation-free way without needing to have a shadow Go type generated
171// for every message type. This technique only works using unsafe.
172//
173//
174// Example generated code:
175//
176// type M struct {
177// state protoimpl.MessageState
178//
179// Field1 int32
180// Field2 string
181// Field3 *BarMessage
182// ...
183// }
184//
185// func (m *M) ProtoReflect() protoreflect.Message {
186// mi := &file_fizz_buzz_proto_msgInfos[5]
187// if protoimpl.UnsafeEnabled && m != nil {
188// ms := protoimpl.X.MessageStateOf(Pointer(m))
189// if ms.LoadMessageInfo() == nil {
190// ms.StoreMessageInfo(mi)
191// }
192// return ms
193// }
194// return mi.MessageOf(m)
195// }
196//
197// The MessageState type holds a *MessageInfo, which must be atomically set to
198// the message info associated with a given message instance.
199// By unsafely converting a *M into a *MessageState, the MessageState object
200// has access to all the information needed to implement protobuf reflection.
201// It has access to the message info as its first field, and a pointer to the
202// MessageState is identical to a pointer to the concrete message value.
203//
204//
205// Requirements:
206// • The type M must implement protoreflect.ProtoMessage.
207// • The address of m must not be nil.
208// • The address of m and the address of m.state must be equal,
209// even though they are different Go types.
210type MessageState struct {
211 pragma.NoUnkeyedLiterals
212 pragma.DoNotCompare
213 pragma.DoNotCopy
214
215 mi *MessageInfo
216}
217
218type messageState MessageState
219
220var (
Damien Neil954bd922019-07-17 16:52:10 -0700221 _ pref.Message = (*messageState)(nil)
222 _ Unwrapper = (*messageState)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700223)
224
225// messageDataType is a tuple of a pointer to the message data and
226// a pointer to the message type. It is a generalized way of providing a
227// reflective view over a message instance. The disadvantage of this approach
228// is the need to allocate this tuple of 16B.
229type messageDataType struct {
230 p pointer
231 mi *MessageInfo
232}
233
234type (
Joe Tsai82760ce2019-06-20 03:09:57 -0700235 messageReflectWrapper messageDataType
Joe Tsai0f81b382019-07-10 23:14:31 -0700236 messageIfaceWrapper messageDataType
Joe Tsai82760ce2019-06-20 03:09:57 -0700237)
238
239var (
240 _ pref.Message = (*messageReflectWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -0700241 _ Unwrapper = (*messageReflectWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700242 _ pref.ProtoMessage = (*messageIfaceWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -0700243 _ Unwrapper = (*messageIfaceWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -0700244)
245
246// MessageOf returns a reflective view over a message. The input must be a
247// pointer to a named Go struct. If the provided type has a ProtoReflect method,
248// it must be implemented by calling this method.
249func (mi *MessageInfo) MessageOf(m interface{}) pref.Message {
250 // TODO: Switch the input to be an opaque Pointer.
Damien Neil16163b42019-08-06 15:43:25 -0700251 if reflect.TypeOf(m) != mi.GoReflectType {
252 panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoReflectType))
Joe Tsai82760ce2019-06-20 03:09:57 -0700253 }
254 p := pointerOfIface(m)
255 if p.IsNil() {
256 return mi.nilMessage.Init(mi)
257 }
258 return &messageReflectWrapper{p, mi}
259}
260
Joe Tsai2aea6142019-07-31 12:27:30 -0700261func (m *messageReflectWrapper) pointer() pointer { return m.p }
262func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi }
Joe Tsai82760ce2019-06-20 03:09:57 -0700263
264func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
265 return (*messageReflectWrapper)(m)
266}
Joe Tsai82760ce2019-06-20 03:09:57 -0700267func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
Damien Neil16163b42019-08-06 15:43:25 -0700268 return m.p.AsIfaceOf(m.mi.GoReflectType.Elem())
Joe Tsai82760ce2019-06-20 03:09:57 -0700269}
Joe Tsai82760ce2019-06-20 03:09:57 -0700270
Joe Tsai82760ce2019-06-20 03:09:57 -0700271// checkField verifies that the provided field descriptor is valid.
272// Exactly one of the returned values is populated.
273func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
274 if fi := mi.fields[fd.Number()]; fi != nil {
275 if fi.fieldDesc != fd {
276 panic("mismatching field descriptor")
277 }
278 return fi, nil
279 }
280 if fd.IsExtension() {
Damien Neil16163b42019-08-06 15:43:25 -0700281 if fd.ContainingMessage().FullName() != mi.Desc.FullName() {
Joe Tsai82760ce2019-06-20 03:09:57 -0700282 // TODO: Should this be exact containing message descriptor match?
283 panic("mismatching containing message")
284 }
Damien Neil16163b42019-08-06 15:43:25 -0700285 if !mi.Desc.ExtensionRanges().Has(fd.Number()) {
Joe Tsai82760ce2019-06-20 03:09:57 -0700286 panic("invalid extension field")
287 }
Damien Neil92f76182019-08-02 16:58:08 -0700288 xtd, ok := fd.(pref.ExtensionTypeDescriptor)
289 if !ok {
290 panic("extension descriptor does not implement ExtensionTypeDescriptor")
291 }
292 return nil, xtd.Type()
Joe Tsai82760ce2019-06-20 03:09:57 -0700293 }
294 panic("invalid field descriptor")
295}