blob: c719e47cd567c30b3a3378b27fd3f8d685b80d96 [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 Tsai08e00302018-11-26 22:32:06 -080014 pvalue "github.com/golang/protobuf/v2/internal/value"
Joe Tsai01ab2962018-09-21 17:44:00 -070015 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
Damien Neil0d3e8cc2019-04-01 13:31:55 -070016 piface "github.com/golang/protobuf/v2/runtime/protoiface"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070017)
18
Joe Tsaic6b75612018-09-13 14:24:37 -070019// MessageType provides protobuf related functionality for a given Go type
20// that represents a message. A given instance of MessageType is tied to
21// exactly one Go type, which must be a pointer to a struct type.
22type MessageType struct {
Damien Neil8012b442019-01-18 09:32:24 -080023 // GoType is the underlying message Go type and must be populated.
Joe Tsaic6b75612018-09-13 14:24:37 -070024 // Once set, this field must never be mutated.
Damien Neil8012b442019-01-18 09:32:24 -080025 GoType reflect.Type // pointer to struct
26
27 // PBType is the underlying message descriptor type and must be populated.
28 // Once set, this field must never be mutated.
29 PBType pref.MessageType
Joe Tsaic6b75612018-09-13 14:24:37 -070030
31 once sync.Once // protects all unexported fields
32
Joe Tsaifa02f4e2018-09-12 16:20:37 -070033 // TODO: Split fields into dense and sparse maps similar to the current
34 // table-driven implementation in v1?
35 fields map[pref.FieldNumber]*fieldInfo
Joe Tsai4ec39c72019-04-03 13:40:53 -070036 oneofs map[pref.Name]*oneofInfo
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
Damien Neil8012b442019-01-18 09:32:24 -080042func (mi *MessageType) init() {
Joe Tsaic6b75612018-09-13 14:24:37 -070043 mi.once.Do(func() {
Damien Neil8012b442019-01-18 09:32:24 -080044 t := mi.GoType
Joe Tsaic6b75612018-09-13 14:24:37 -070045 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
46 panic(fmt.Sprintf("got %v, want *struct kind", t))
47 }
Joe Tsaic6b75612018-09-13 14:24:37 -070048
Joe Tsai95b02902018-10-31 18:23:42 -070049 mi.makeKnownFieldsFunc(t.Elem())
50 mi.makeUnknownFieldsFunc(t.Elem())
51 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070052 })
Joe Tsaic6b75612018-09-13 14:24:37 -070053}
54
Joe Tsaif0c01e42018-11-06 13:05:20 -080055// makeKnownFieldsFunc generates functions for operations that can be performed
56// on each protobuf message field. It takes in a reflect.Type representing the
57// Go struct and matches message fields with struct fields.
Joe Tsaifa02f4e2018-09-12 16:20:37 -070058//
59// This code assumes that the struct is well-formed and panics if there are
60// any discrepancies.
Joe Tsai95b02902018-10-31 18:23:42 -070061func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070062 // Generate a mapping of field numbers and names to Go struct field or type.
Joe Tsai4ec39c72019-04-03 13:40:53 -070063 var (
64 fieldsByNumber = map[pref.FieldNumber]reflect.StructField{}
65 oneofsByName = map[pref.Name]reflect.StructField{}
66 oneofWrappersByType = map[reflect.Type]pref.FieldNumber{}
67 oneofWrappersByNumber = map[pref.FieldNumber]reflect.Type{}
68 specialByName = map[string]reflect.StructField{}
69 )
Joe Tsaifa02f4e2018-09-12 16:20:37 -070070fieldLoop:
71 for i := 0; i < t.NumField(); i++ {
72 f := t.Field(i)
73 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
74 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
75 n, _ := strconv.ParseUint(s, 10, 64)
Joe Tsai4ec39c72019-04-03 13:40:53 -070076 fieldsByNumber[pref.FieldNumber(n)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -070077 continue fieldLoop
78 }
79 }
80 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
Joe Tsai4ec39c72019-04-03 13:40:53 -070081 oneofsByName[pref.Name(s)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -070082 continue fieldLoop
83 }
84 switch f.Name {
85 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
Joe Tsai4ec39c72019-04-03 13:40:53 -070086 specialByName[f.Name] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -070087 continue fieldLoop
88 }
89 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -080090 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -070091 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -080092 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
93 }
94 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
95 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
96 }
97 for _, v := range oneofWrappers {
98 tf := reflect.TypeOf(v).Elem()
99 f := tf.Field(0)
100 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
101 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
102 n, _ := strconv.ParseUint(s, 10, 64)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700103 oneofWrappersByType[tf] = pref.FieldNumber(n)
104 oneofWrappersByNumber[pref.FieldNumber(n)] = tf
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800105 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700106 }
107 }
108 }
109
110 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neil8012b442019-01-18 09:32:24 -0800111 for i := 0; i < mi.PBType.Fields().Len(); i++ {
112 fd := mi.PBType.Fields().Get(i)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700113 fs := fieldsByNumber[fd.Number()]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700114 var fi fieldInfo
115 switch {
116 case fd.IsWeak():
Joe Tsai4ec39c72019-04-03 13:40:53 -0700117 fi = fieldInfoForWeak(fd, specialByName["XXX_weak"])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700118 case fd.OneofType() != nil:
Joe Tsai4ec39c72019-04-03 13:40:53 -0700119 fi = fieldInfoForOneof(fd, oneofsByName[fd.OneofType().Name()], oneofWrappersByNumber[fd.Number()])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700120 case fd.IsMap():
121 fi = fieldInfoForMap(fd, fs)
122 case fd.Cardinality() == pref.Repeated:
Joe Tsai4b7aff62018-11-14 14:05:19 -0800123 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700124 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700125 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700126 default:
127 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700128 }
129 mi.fields[fd.Number()] = &fi
130 }
Joe Tsai4ec39c72019-04-03 13:40:53 -0700131
132 mi.oneofs = map[pref.Name]*oneofInfo{}
133 for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
134 od := mi.PBType.Oneofs().Get(i)
135 mi.oneofs[od.Name()] = makeOneofInfo(od, oneofsByName[od.Name()], oneofWrappersByType)
136 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700137}
Joe Tsaic6b75612018-09-13 14:24:37 -0700138
Joe Tsai95b02902018-10-31 18:23:42 -0700139func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
140 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700141 mi.unknownFields = f
142 return
143 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700144 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
145 return emptyUnknownFields{}
146 }
147}
148
Joe Tsai95b02902018-10-31 18:23:42 -0700149func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800150 if f := makeLegacyExtensionFieldsFunc(t); f != nil {
151 mi.extensionFields = f
152 return
153 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700154 mi.extensionFields = func(*messageDataType) pref.KnownFields {
155 return emptyExtensionFields{}
156 }
157}
158
Joe Tsai08e00302018-11-26 22:32:06 -0800159func (mi *MessageType) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700160 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800161}
162
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700163func (mi *MessageType) Methods() *piface.Methods {
164 return nil
165}
166
Joe Tsaic6b75612018-09-13 14:24:37 -0700167func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800168 // TODO: Remove this check? This API is primarily used by generated code,
169 // and should not violate this assumption. Leave this check in for now to
170 // provide some sanity checks during development. This can be removed if
171 // it proves to be detrimental to performance.
172 if reflect.TypeOf(p) != mi.GoType {
173 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
174 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800175 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700176}
177
178// messageDataType is a tuple of a pointer to the message data and
179// a pointer to the message type.
180//
181// TODO: Unfortunately, we need to close over a pointer and MessageType,
182// which incurs an an allocation. This pair is similar to a Go interface,
183// which is essentially a tuple of the same thing. We can make this efficient
184// with reflect.NamedOf (see https://golang.org/issues/16522).
185//
186// With that hypothetical API, we could dynamically create a new named type
Damien Neil8012b442019-01-18 09:32:24 -0800187// that has the same underlying type as MessageType.GoType, and
Joe Tsaic6b75612018-09-13 14:24:37 -0700188// dynamically create methods that close over MessageType.
189// Since the new type would have the same underlying type, we could directly
190// convert between pointers of those types, giving us an efficient way to swap
191// out the method set.
192//
193// Barring the ability to dynamically create named types, the workaround is
194// 1. either to accept the cost of an allocation for this wrapper struct or
195// 2. generate more types and methods, at the expense of binary size increase.
196type messageDataType struct {
197 p pointer
198 mi *MessageType
199}
200
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700201type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800202
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700203func (m *messageReflectWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800204 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800205}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700206func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800207 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800208 return (*knownFields)(m)
209}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700210func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800211 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800212 return m.mi.unknownFields((*messageDataType)(m))
213}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700214func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800215 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
216 return m
217 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700218 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800219}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700220func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800221 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800222}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700223func (m *messageReflectWrapper) ProtoMutable() {}
Joe Tsai08e00302018-11-26 22:32:06 -0800224
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700225var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
226
227type messageIfaceWrapper messageDataType
228
229func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
230 return (*messageReflectWrapper)(m)
231}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700232func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
233 return m.mi.Methods()
234}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700235func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
236 return m.p.AsIfaceOf(m.mi.GoType.Elem())
237}
Joe Tsai08e00302018-11-26 22:32:06 -0800238
Joe Tsaic6b75612018-09-13 14:24:37 -0700239type knownFields messageDataType
240
Joe Tsaic6b75612018-09-13 14:24:37 -0700241func (fs *knownFields) Len() (cnt int) {
242 for _, fi := range fs.mi.fields {
243 if fi.has(fs.p) {
244 cnt++
245 }
246 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700247 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700248}
249func (fs *knownFields) Has(n pref.FieldNumber) bool {
250 if fi := fs.mi.fields[n]; fi != nil {
251 return fi.has(fs.p)
252 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700253 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700254}
255func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
256 if fi := fs.mi.fields[n]; fi != nil {
257 return fi.get(fs.p)
258 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700259 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700260}
261func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
262 if fi := fs.mi.fields[n]; fi != nil {
263 fi.set(fs.p, v)
264 return
265 }
Damien Neil8012b442019-01-18 09:32:24 -0800266 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800267 fs.extensionFields().Set(n, v)
268 return
269 }
270 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700271}
272func (fs *knownFields) Clear(n pref.FieldNumber) {
273 if fi := fs.mi.fields[n]; fi != nil {
274 fi.clear(fs.p)
275 return
276 }
Damien Neil8012b442019-01-18 09:32:24 -0800277 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800278 fs.extensionFields().Clear(n)
279 return
280 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700281}
Joe Tsai4ec39c72019-04-03 13:40:53 -0700282func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
283 if oi := fs.mi.oneofs[s]; oi != nil {
284 return oi.which(fs.p)
285 }
286 return 0
287}
Joe Tsaic6b75612018-09-13 14:24:37 -0700288func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
289 for n, fi := range fs.mi.fields {
290 if fi.has(fs.p) {
291 if !f(n, fi.get(fs.p)) {
292 return
293 }
294 }
295 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700296 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700297}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800298func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800299 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800300 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800301 }
Damien Neil8012b442019-01-18 09:32:24 -0800302 if fs.mi.PBType.ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800303 return fs.extensionFields().NewMessage(n)
304 }
305 panic(fmt.Sprintf("invalid field: %d", n))
306}
Joe Tsaic6b75612018-09-13 14:24:37 -0700307func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700308 return fs.extensionFields().ExtensionTypes()
309}
310func (fs *knownFields) extensionFields() pref.KnownFields {
311 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700312}
313
Joe Tsaibe5348c2018-10-23 18:31:18 -0700314type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700315
Joe Tsaibe5348c2018-10-23 18:31:18 -0700316func (emptyUnknownFields) Len() int { return 0 }
317func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800318func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
319func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700320func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700321
Joe Tsaibe5348c2018-10-23 18:31:18 -0700322type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700323
Joe Tsaif0c01e42018-11-06 13:05:20 -0800324func (emptyExtensionFields) Len() int { return 0 }
325func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
326func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
327func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
328func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsai4ec39c72019-04-03 13:40:53 -0700329func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800330func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800331func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800332 panic("extensions not supported")
333}
334func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700335
336type emptyExtensionTypes struct{}
337
338func (emptyExtensionTypes) Len() int { return 0 }
339func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800340func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700341func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
342func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800343func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }