blob: 7552157b274bcc9978de40738115cf6a0adc12a6 [file] [log] [blame]
Joe Tsaifa02f4e2018-09-12 16:20:37 -07001// Copyright 2018 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 (
Joe Tsaic6b75612018-09-13 14:24:37 -07008 "fmt"
Joe Tsaifa02f4e2018-09-12 16:20:37 -07009 "reflect"
10 "strconv"
11 "strings"
Joe Tsaic6b75612018-09-13 14:24:37 -070012 "sync"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070013
Joe Tsai01ab2962018-09-21 17:44:00 -070014 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaic6b75612018-09-13 14:24:37 -070015 ptype "github.com/golang/protobuf/v2/reflect/prototype"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070016)
17
Joe Tsaic6b75612018-09-13 14:24:37 -070018// MessageType provides protobuf related functionality for a given Go type
19// that represents a message. A given instance of MessageType is tied to
20// exactly one Go type, which must be a pointer to a struct type.
21type MessageType struct {
22 // Desc is an optionally provided message descriptor. If nil, the descriptor
23 // is lazily derived from the Go type information of generated messages
24 // for the v1 API.
25 //
26 // Once set, this field must never be mutated.
27 Desc pref.MessageDescriptor
28
29 once sync.Once // protects all unexported fields
30
31 goType reflect.Type // pointer to struct
32 pbType pref.MessageType // only valid if goType does not implement proto.Message
33
Joe Tsaifa02f4e2018-09-12 16:20:37 -070034 // TODO: Split fields into dense and sparse maps similar to the current
35 // table-driven implementation in v1?
36 fields map[pref.FieldNumber]*fieldInfo
Joe Tsaibe5348c2018-10-23 18:31:18 -070037
38 unknownFields func(*messageDataType) pref.UnknownFields
39 extensionFields func(*messageDataType) pref.KnownFields
Joe Tsaifa02f4e2018-09-12 16:20:37 -070040}
41
Joe Tsaic6b75612018-09-13 14:24:37 -070042// init lazily initializes the MessageType upon first use and
43// also checks that the provided pointer p is of the correct Go type.
44//
45// It must be called at the start of every exported method.
46func (mi *MessageType) init(p interface{}) {
47 mi.once.Do(func() {
48 v := reflect.ValueOf(p)
49 t := v.Type()
50 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
51 panic(fmt.Sprintf("got %v, want *struct kind", t))
52 }
53 mi.goType = t
54
55 // Derive the message descriptor if unspecified.
56 md := mi.Desc
57 if md == nil {
58 // TODO: derive the message type from the Go struct type
59 }
60
61 // Initialize the Go message type wrapper if the Go type does not
62 // implement the proto.Message interface.
63 //
64 // Otherwise, we assume that the Go type manually implements the
65 // interface and is internally consistent such that:
66 // goType == reflect.New(goType.Elem()).Interface().(proto.Message).ProtoReflect().Type().GoType()
67 //
68 // Generated code ensures that this property holds.
69 if _, ok := p.(pref.ProtoMessage); !ok {
70 mi.pbType = ptype.NewGoMessage(&ptype.GoMessage{
71 MessageDescriptor: md,
72 New: func(pref.MessageType) pref.ProtoMessage {
73 p := reflect.New(t.Elem()).Interface()
74 return (*message)(mi.dataTypeOf(p))
75 },
76 })
77 }
78
Joe Tsaibe5348c2018-10-23 18:31:18 -070079 mi.generateKnownFieldFuncs(t.Elem(), md)
80 mi.generateUnknownFieldFuncs(t.Elem(), md)
81 mi.generateExtensionFieldFuncs(t.Elem(), md)
Joe Tsaic6b75612018-09-13 14:24:37 -070082 })
83
84 // TODO: Remove this check? This API is primarily used by generated code,
85 // and should not violate this assumption. Leave this check in for now to
86 // provide some sanity checks during development. This can be removed if
87 // it proves to be detrimental to performance.
88 if reflect.TypeOf(p) != mi.goType {
89 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.goType))
90 }
91}
92
Joe Tsaibe5348c2018-10-23 18:31:18 -070093// generateKnownFieldFuncs generates per-field functions for all operations
Joe Tsaifa02f4e2018-09-12 16:20:37 -070094// to be performed on each field. It takes in a reflect.Type representing the
95// Go struct, and a protoreflect.MessageDescriptor to match with the fields
96// in the struct.
97//
98// This code assumes that the struct is well-formed and panics if there are
99// any discrepancies.
Joe Tsaibe5348c2018-10-23 18:31:18 -0700100func (mi *MessageType) generateKnownFieldFuncs(t reflect.Type, md pref.MessageDescriptor) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700101 // Generate a mapping of field numbers and names to Go struct field or type.
102 fields := map[pref.FieldNumber]reflect.StructField{}
103 oneofs := map[pref.Name]reflect.StructField{}
104 oneofFields := map[pref.FieldNumber]reflect.Type{}
105 special := map[string]reflect.StructField{}
106fieldLoop:
107 for i := 0; i < t.NumField(); i++ {
108 f := t.Field(i)
109 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
110 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
111 n, _ := strconv.ParseUint(s, 10, 64)
112 fields[pref.FieldNumber(n)] = f
113 continue fieldLoop
114 }
115 }
116 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
117 oneofs[pref.Name(s)] = f
118 continue fieldLoop
119 }
120 switch f.Name {
121 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
122 special[f.Name] = f
123 continue fieldLoop
124 }
125 }
Joe Tsai2c870bb2018-10-17 11:46:52 -0700126 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -0700127 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700128 oneofLoop:
129 for _, v := range vs.Interface().([]interface{}) {
130 tf := reflect.TypeOf(v).Elem()
131 f := tf.Field(0)
132 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
133 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
134 n, _ := strconv.ParseUint(s, 10, 64)
135 oneofFields[pref.FieldNumber(n)] = tf
136 continue oneofLoop
137 }
138 }
139 }
140 }
141
142 mi.fields = map[pref.FieldNumber]*fieldInfo{}
143 for i := 0; i < md.Fields().Len(); i++ {
144 fd := md.Fields().Get(i)
145 fs := fields[fd.Number()]
146 var fi fieldInfo
147 switch {
148 case fd.IsWeak():
149 fi = fieldInfoForWeak(fd, special["XXX_weak"])
150 case fd.OneofType() != nil:
151 fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
152 case fd.IsMap():
153 fi = fieldInfoForMap(fd, fs)
154 case fd.Cardinality() == pref.Repeated:
155 fi = fieldInfoForVector(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700156 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700157 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700158 default:
159 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700160 }
161 mi.fields[fd.Number()] = &fi
162 }
163}
Joe Tsaic6b75612018-09-13 14:24:37 -0700164
Joe Tsaibe5348c2018-10-23 18:31:18 -0700165func (mi *MessageType) generateUnknownFieldFuncs(t reflect.Type, md pref.MessageDescriptor) {
166 // TODO
167 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
168 return emptyUnknownFields{}
169 }
170}
171
172func (mi *MessageType) generateExtensionFieldFuncs(t reflect.Type, md pref.MessageDescriptor) {
173 // TODO
174 mi.extensionFields = func(*messageDataType) pref.KnownFields {
175 return emptyExtensionFields{}
176 }
177}
178
Joe Tsaic6b75612018-09-13 14:24:37 -0700179func (mi *MessageType) MessageOf(p interface{}) pref.Message {
180 mi.init(p)
181 if m, ok := p.(pref.ProtoMessage); ok {
182 // We assume p properly implements protoreflect.Message.
183 // See the comment in MessageType.init regarding pbType.
184 return m.ProtoReflect()
185 }
186 return (*message)(mi.dataTypeOf(p))
187}
188
189func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
190 mi.init(p)
191 return (*knownFields)(mi.dataTypeOf(p))
192}
193
194func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
195 mi.init(p)
Joe Tsaibe5348c2018-10-23 18:31:18 -0700196 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700197}
198
199func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
200 return &messageDataType{pointerOfIface(&p), mi}
201}
202
203// messageDataType is a tuple of a pointer to the message data and
204// a pointer to the message type.
205//
206// TODO: Unfortunately, we need to close over a pointer and MessageType,
207// which incurs an an allocation. This pair is similar to a Go interface,
208// which is essentially a tuple of the same thing. We can make this efficient
209// with reflect.NamedOf (see https://golang.org/issues/16522).
210//
211// With that hypothetical API, we could dynamically create a new named type
212// that has the same underlying type as MessageType.goType, and
213// dynamically create methods that close over MessageType.
214// Since the new type would have the same underlying type, we could directly
215// convert between pointers of those types, giving us an efficient way to swap
216// out the method set.
217//
218// Barring the ability to dynamically create named types, the workaround is
219// 1. either to accept the cost of an allocation for this wrapper struct or
220// 2. generate more types and methods, at the expense of binary size increase.
221type messageDataType struct {
222 p pointer
223 mi *MessageType
224}
225
226type message messageDataType
227
228func (m *message) Type() pref.MessageType {
229 return m.mi.pbType
230}
231func (m *message) KnownFields() pref.KnownFields {
232 return (*knownFields)(m)
233}
234func (m *message) UnknownFields() pref.UnknownFields {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700235 return m.mi.unknownFields((*messageDataType)(m))
Joe Tsaic6b75612018-09-13 14:24:37 -0700236}
Joe Tsai91e14662018-09-13 13:24:35 -0700237func (m *message) Unwrap() interface{} { // TODO: unexport?
Joe Tsaic6b75612018-09-13 14:24:37 -0700238 return m.p.asType(m.mi.goType.Elem()).Interface()
239}
240func (m *message) Interface() pref.ProtoMessage {
241 return m
242}
243func (m *message) ProtoReflect() pref.Message {
244 return m
245}
246func (m *message) ProtoMutable() {}
247
248type knownFields messageDataType
249
Joe Tsaic6b75612018-09-13 14:24:37 -0700250func (fs *knownFields) Len() (cnt int) {
251 for _, fi := range fs.mi.fields {
252 if fi.has(fs.p) {
253 cnt++
254 }
255 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700256 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700257}
258func (fs *knownFields) Has(n pref.FieldNumber) bool {
259 if fi := fs.mi.fields[n]; fi != nil {
260 return fi.has(fs.p)
261 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700262 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700263}
264func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
265 if fi := fs.mi.fields[n]; fi != nil {
266 return fi.get(fs.p)
267 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700268 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700269}
270func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
271 if fi := fs.mi.fields[n]; fi != nil {
272 fi.set(fs.p, v)
273 return
274 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700275 fs.extensionFields().Set(n, v)
Joe Tsaic6b75612018-09-13 14:24:37 -0700276}
277func (fs *knownFields) Clear(n pref.FieldNumber) {
278 if fi := fs.mi.fields[n]; fi != nil {
279 fi.clear(fs.p)
280 return
281 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700282 fs.extensionFields().Clear(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700283}
284func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
285 if fi := fs.mi.fields[n]; fi != nil {
286 return fi.mutable(fs.p)
287 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700288 return fs.extensionFields().Mutable(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700289}
290func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
291 for n, fi := range fs.mi.fields {
292 if fi.has(fs.p) {
293 if !f(n, fi.get(fs.p)) {
294 return
295 }
296 }
297 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700298 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700299}
300func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700301 return fs.extensionFields().ExtensionTypes()
302}
303func (fs *knownFields) extensionFields() pref.KnownFields {
304 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700305}
306
Joe Tsaibe5348c2018-10-23 18:31:18 -0700307type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700308
Joe Tsaibe5348c2018-10-23 18:31:18 -0700309func (emptyUnknownFields) Len() int { return 0 }
310func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
311func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { /* noop */ }
312func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) {}
313func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700314
Joe Tsaibe5348c2018-10-23 18:31:18 -0700315type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700316
Joe Tsaibe5348c2018-10-23 18:31:18 -0700317func (emptyExtensionFields) Len() int { return 0 }
318func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
319func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
320func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("invalid field") }
321func (emptyExtensionFields) Clear(pref.FieldNumber) { panic("invalid field") }
322func (emptyExtensionFields) Mutable(pref.FieldNumber) pref.Mutable { panic("invalid field") }
323func (emptyExtensionFields) Range(f func(pref.FieldNumber, pref.Value) bool) {}
324func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
325
326type emptyExtensionTypes struct{}
327
328func (emptyExtensionTypes) Len() int { return 0 }
329func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
330func (emptyExtensionTypes) Remove(pref.ExtensionType) { panic("extensions not supported") }
331func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
332func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
333func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) {}