blob: 2b0a9ca3d129c0ce1fc8cb98364cdec0f27b3812 [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) {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700166 if f := generateLegacyUnknownFieldFuncs(t, md); f != nil {
167 mi.unknownFields = f
168 return
169 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700170 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
171 return emptyUnknownFields{}
172 }
173}
174
175func (mi *MessageType) generateExtensionFieldFuncs(t reflect.Type, md pref.MessageDescriptor) {
176 // TODO
177 mi.extensionFields = func(*messageDataType) pref.KnownFields {
178 return emptyExtensionFields{}
179 }
180}
181
Joe Tsaic6b75612018-09-13 14:24:37 -0700182func (mi *MessageType) MessageOf(p interface{}) pref.Message {
183 mi.init(p)
184 if m, ok := p.(pref.ProtoMessage); ok {
185 // We assume p properly implements protoreflect.Message.
186 // See the comment in MessageType.init regarding pbType.
187 return m.ProtoReflect()
188 }
189 return (*message)(mi.dataTypeOf(p))
190}
191
192func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
193 mi.init(p)
194 return (*knownFields)(mi.dataTypeOf(p))
195}
196
197func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
198 mi.init(p)
Joe Tsaibe5348c2018-10-23 18:31:18 -0700199 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700200}
201
202func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
203 return &messageDataType{pointerOfIface(&p), mi}
204}
205
206// messageDataType is a tuple of a pointer to the message data and
207// a pointer to the message type.
208//
209// TODO: Unfortunately, we need to close over a pointer and MessageType,
210// which incurs an an allocation. This pair is similar to a Go interface,
211// which is essentially a tuple of the same thing. We can make this efficient
212// with reflect.NamedOf (see https://golang.org/issues/16522).
213//
214// With that hypothetical API, we could dynamically create a new named type
215// that has the same underlying type as MessageType.goType, and
216// dynamically create methods that close over MessageType.
217// Since the new type would have the same underlying type, we could directly
218// convert between pointers of those types, giving us an efficient way to swap
219// out the method set.
220//
221// Barring the ability to dynamically create named types, the workaround is
222// 1. either to accept the cost of an allocation for this wrapper struct or
223// 2. generate more types and methods, at the expense of binary size increase.
224type messageDataType struct {
225 p pointer
226 mi *MessageType
227}
228
229type message messageDataType
230
231func (m *message) Type() pref.MessageType {
232 return m.mi.pbType
233}
234func (m *message) KnownFields() pref.KnownFields {
235 return (*knownFields)(m)
236}
237func (m *message) UnknownFields() pref.UnknownFields {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700238 return m.mi.unknownFields((*messageDataType)(m))
Joe Tsaic6b75612018-09-13 14:24:37 -0700239}
Joe Tsai91e14662018-09-13 13:24:35 -0700240func (m *message) Unwrap() interface{} { // TODO: unexport?
Joe Tsaic6b75612018-09-13 14:24:37 -0700241 return m.p.asType(m.mi.goType.Elem()).Interface()
242}
243func (m *message) Interface() pref.ProtoMessage {
244 return m
245}
246func (m *message) ProtoReflect() pref.Message {
247 return m
248}
249func (m *message) ProtoMutable() {}
250
251type knownFields messageDataType
252
Joe Tsaic6b75612018-09-13 14:24:37 -0700253func (fs *knownFields) Len() (cnt int) {
254 for _, fi := range fs.mi.fields {
255 if fi.has(fs.p) {
256 cnt++
257 }
258 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700259 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700260}
261func (fs *knownFields) Has(n pref.FieldNumber) bool {
262 if fi := fs.mi.fields[n]; fi != nil {
263 return fi.has(fs.p)
264 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700265 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700266}
267func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
268 if fi := fs.mi.fields[n]; fi != nil {
269 return fi.get(fs.p)
270 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700271 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700272}
273func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
274 if fi := fs.mi.fields[n]; fi != nil {
275 fi.set(fs.p, v)
276 return
277 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700278 fs.extensionFields().Set(n, v)
Joe Tsaic6b75612018-09-13 14:24:37 -0700279}
280func (fs *knownFields) Clear(n pref.FieldNumber) {
281 if fi := fs.mi.fields[n]; fi != nil {
282 fi.clear(fs.p)
283 return
284 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700285 fs.extensionFields().Clear(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700286}
287func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
288 if fi := fs.mi.fields[n]; fi != nil {
289 return fi.mutable(fs.p)
290 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700291 return fs.extensionFields().Mutable(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700292}
293func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
294 for n, fi := range fs.mi.fields {
295 if fi.has(fs.p) {
296 if !f(n, fi.get(fs.p)) {
297 return
298 }
299 }
300 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700301 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700302}
303func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700304 return fs.extensionFields().ExtensionTypes()
305}
306func (fs *knownFields) extensionFields() pref.KnownFields {
307 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700308}
309
Joe Tsaibe5348c2018-10-23 18:31:18 -0700310type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700311
Joe Tsaibe5348c2018-10-23 18:31:18 -0700312func (emptyUnknownFields) Len() int { return 0 }
313func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
314func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { /* noop */ }
315func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) {}
316func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700317
Joe Tsaibe5348c2018-10-23 18:31:18 -0700318type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700319
Joe Tsaibe5348c2018-10-23 18:31:18 -0700320func (emptyExtensionFields) Len() int { return 0 }
321func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
322func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
323func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("invalid field") }
324func (emptyExtensionFields) Clear(pref.FieldNumber) { panic("invalid field") }
325func (emptyExtensionFields) Mutable(pref.FieldNumber) pref.Mutable { panic("invalid field") }
326func (emptyExtensionFields) Range(f func(pref.FieldNumber, pref.Value) bool) {}
327func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
328
329type emptyExtensionTypes struct{}
330
331func (emptyExtensionTypes) Len() int { return 0 }
332func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
333func (emptyExtensionTypes) Remove(pref.ExtensionType) { panic("extensions not supported") }
334func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
335func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
336func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) {}