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