blob: c79b55ab20f5a015aa52df541916401c31ef1f5d [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
109func (m *messageReflectWrapper) pointer() pointer { return m.p }
110
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 }
145 if !isComposite(xt) {
146 return defaultValueOf(xt)
147 }
148 return frozenValueOf(xt.New())
149}
150func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
151 if *m == nil {
152 *m = make(map[int32]ExtensionField)
153 }
154 var x ExtensionField
155 x.SetType(xt)
156 x.SetEagerValue(xt.InterfaceOf(v))
157 (*m)[int32(xt.Number())] = x
158}
159func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
160 if !isComposite(xt) {
161 panic("invalid Mutable on field with non-composite type")
162 }
163 if x, ok := (*m)[int32(xt.Number())]; ok {
164 return xt.ValueOf(x.GetValue())
165 }
166 v := xt.New()
167 m.Set(xt, v)
168 return v
169}
170
171func isComposite(fd pref.FieldDescriptor) bool {
172 return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
173}
174
175// checkField verifies that the provided field descriptor is valid.
176// Exactly one of the returned values is populated.
177func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
178 if fi := mi.fields[fd.Number()]; fi != nil {
179 if fi.fieldDesc != fd {
180 panic("mismatching field descriptor")
181 }
182 return fi, nil
183 }
184 if fd.IsExtension() {
185 if fd.ContainingMessage().FullName() != mi.PBType.FullName() {
186 // TODO: Should this be exact containing message descriptor match?
187 panic("mismatching containing message")
188 }
189 if !mi.PBType.ExtensionRanges().Has(fd.Number()) {
190 panic("invalid extension field")
191 }
192 return nil, fd.(pref.ExtensionType)
193 }
194 panic("invalid field descriptor")
195}