blob: 699ac2c65f05a4c7b9b9dbdc2744a9941b9e0eed [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
15// MessageState is a data structure that is nested as the first field in a
16// concrete message. It provides a way to implement the ProtoReflect method
17// in an allocation-free way without needing to have a shadow Go type generated
18// for every message type. This technique only works using unsafe.
19//
20//
21// Example generated code:
22//
23// type M struct {
24// state protoimpl.MessageState
25//
26// Field1 int32
27// Field2 string
28// Field3 *BarMessage
29// ...
30// }
31//
32// func (m *M) ProtoReflect() protoreflect.Message {
33// mi := &file_fizz_buzz_proto_msgInfos[5]
34// if protoimpl.UnsafeEnabled && m != nil {
35// ms := protoimpl.X.MessageStateOf(Pointer(m))
36// if ms.LoadMessageInfo() == nil {
37// ms.StoreMessageInfo(mi)
38// }
39// return ms
40// }
41// return mi.MessageOf(m)
42// }
43//
44// The MessageState type holds a *MessageInfo, which must be atomically set to
45// the message info associated with a given message instance.
46// By unsafely converting a *M into a *MessageState, the MessageState object
47// has access to all the information needed to implement protobuf reflection.
48// It has access to the message info as its first field, and a pointer to the
49// MessageState is identical to a pointer to the concrete message value.
50//
51//
52// Requirements:
53// • The type M must implement protoreflect.ProtoMessage.
54// • The address of m must not be nil.
55// • The address of m and the address of m.state must be equal,
56// even though they are different Go types.
57type MessageState struct {
58 pragma.NoUnkeyedLiterals
59 pragma.DoNotCompare
60 pragma.DoNotCopy
61
62 mi *MessageInfo
63}
64
65type messageState MessageState
66
67var (
Damien Neil954bd922019-07-17 16:52:10 -070068 _ pref.Message = (*messageState)(nil)
69 _ Unwrapper = (*messageState)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -070070)
71
72// messageDataType is a tuple of a pointer to the message data and
73// a pointer to the message type. It is a generalized way of providing a
74// reflective view over a message instance. The disadvantage of this approach
75// is the need to allocate this tuple of 16B.
76type messageDataType struct {
77 p pointer
78 mi *MessageInfo
79}
80
81type (
Joe Tsai82760ce2019-06-20 03:09:57 -070082 messageReflectWrapper messageDataType
Joe Tsai0f81b382019-07-10 23:14:31 -070083 messageIfaceWrapper messageDataType
Joe Tsai82760ce2019-06-20 03:09:57 -070084)
85
86var (
87 _ pref.Message = (*messageReflectWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -070088 _ Unwrapper = (*messageReflectWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -070089 _ pref.ProtoMessage = (*messageIfaceWrapper)(nil)
Damien Neil954bd922019-07-17 16:52:10 -070090 _ Unwrapper = (*messageIfaceWrapper)(nil)
Joe Tsai82760ce2019-06-20 03:09:57 -070091)
92
93// MessageOf returns a reflective view over a message. The input must be a
94// pointer to a named Go struct. If the provided type has a ProtoReflect method,
95// it must be implemented by calling this method.
96func (mi *MessageInfo) MessageOf(m interface{}) pref.Message {
97 // TODO: Switch the input to be an opaque Pointer.
98 if reflect.TypeOf(m) != mi.GoType {
99 panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoType))
100 }
101 p := pointerOfIface(m)
102 if p.IsNil() {
103 return mi.nilMessage.Init(mi)
104 }
105 return &messageReflectWrapper{p, mi}
106}
107
Joe Tsai2aea6142019-07-31 12:27:30 -0700108func (m *messageReflectWrapper) pointer() pointer { return m.p }
109func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi }
Joe Tsai82760ce2019-06-20 03:09:57 -0700110
111func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
112 return (*messageReflectWrapper)(m)
113}
Joe Tsai82760ce2019-06-20 03:09:57 -0700114func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
115 return m.p.AsIfaceOf(m.mi.GoType.Elem())
116}
Joe Tsai82760ce2019-06-20 03:09:57 -0700117
118type extensionMap map[int32]ExtensionField
119
120func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
121 if m != nil {
122 for _, x := range *m {
123 xt := x.GetType()
124 if !f(xt, xt.ValueOf(x.GetValue())) {
125 return
126 }
127 }
128 }
129}
130func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
131 if m != nil {
132 _, ok = (*m)[int32(xt.Number())]
133 }
134 return ok
135}
136func (m *extensionMap) Clear(xt pref.ExtensionType) {
137 delete(*m, int32(xt.Number()))
138}
139func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
140 if m != nil {
141 if x, ok := (*m)[int32(xt.Number())]; ok {
142 return xt.ValueOf(x.GetValue())
143 }
144 }
Damien Neild4f08002019-08-07 12:21:41 -0700145 return xt.Zero()
Joe Tsai82760ce2019-06-20 03:09:57 -0700146}
147func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
148 if *m == nil {
149 *m = make(map[int32]ExtensionField)
150 }
151 var x ExtensionField
152 x.SetType(xt)
153 x.SetEagerValue(xt.InterfaceOf(v))
154 (*m)[int32(xt.Number())] = x
155}
156func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
157 if !isComposite(xt) {
158 panic("invalid Mutable on field with non-composite type")
159 }
160 if x, ok := (*m)[int32(xt.Number())]; ok {
161 return xt.ValueOf(x.GetValue())
162 }
163 v := xt.New()
164 m.Set(xt, v)
165 return v
166}
167
168func isComposite(fd pref.FieldDescriptor) bool {
169 return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
170}
171
172// checkField verifies that the provided field descriptor is valid.
173// Exactly one of the returned values is populated.
174func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
175 if fi := mi.fields[fd.Number()]; fi != nil {
176 if fi.fieldDesc != fd {
177 panic("mismatching field descriptor")
178 }
179 return fi, nil
180 }
181 if fd.IsExtension() {
182 if fd.ContainingMessage().FullName() != mi.PBType.FullName() {
183 // TODO: Should this be exact containing message descriptor match?
184 panic("mismatching containing message")
185 }
186 if !mi.PBType.ExtensionRanges().Has(fd.Number()) {
187 panic("invalid extension field")
188 }
189 return nil, fd.(pref.ExtensionType)
190 }
191 panic("invalid field descriptor")
192}