blob: 8879015b27c5278de44aa8e445a186978aeaf041 [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
Damien Neil3eaddf02019-05-09 11:33:55 -070049 si := mi.makeStructInfo(t.Elem())
50 mi.makeKnownFieldsFunc(si)
Joe Tsai95b02902018-10-31 18:23:42 -070051 mi.makeUnknownFieldsFunc(t.Elem())
52 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070053 })
Joe Tsaic6b75612018-09-13 14:24:37 -070054}
55
Damien Neil3eaddf02019-05-09 11:33:55 -070056type structInfo struct {
57 fieldsByNumber map[pref.FieldNumber]reflect.StructField
58 oneofsByName map[pref.Name]reflect.StructField
59 oneofWrappersByType map[reflect.Type]pref.FieldNumber
60 oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
61}
62
63func (mi *MessageType) makeStructInfo(t reflect.Type) structInfo {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070064 // Generate a mapping of field numbers and names to Go struct field or type.
Damien Neil3eaddf02019-05-09 11:33:55 -070065 si := structInfo{
66 fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
67 oneofsByName: map[pref.Name]reflect.StructField{},
68 oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
69 oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
70 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -070071fieldLoop:
72 for i := 0; i < t.NumField(); i++ {
73 f := t.Field(i)
74 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
75 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
76 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -070077 si.fieldsByNumber[pref.FieldNumber(n)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -070078 continue fieldLoop
79 }
80 }
81 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
Damien Neil3eaddf02019-05-09 11:33:55 -070082 si.oneofsByName[pref.Name(s)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -070083 continue fieldLoop
84 }
85 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -080086 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -070087 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -080088 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
89 }
90 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
91 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
92 }
93 for _, v := range oneofWrappers {
94 tf := reflect.TypeOf(v).Elem()
95 f := tf.Field(0)
96 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
97 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
98 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -070099 si.oneofWrappersByType[tf] = pref.FieldNumber(n)
100 si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800101 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700102 }
103 }
104 }
Damien Neil3eaddf02019-05-09 11:33:55 -0700105 return si
106}
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700107
Damien Neil3eaddf02019-05-09 11:33:55 -0700108// makeKnownFieldsFunc generates functions for operations that can be performed
109// on each protobuf message field. It takes in a reflect.Type representing the
110// Go struct and matches message fields with struct fields.
111//
112// This code assumes that the struct is well-formed and panics if there are
113// any discrepancies.
114func (mi *MessageType) makeKnownFieldsFunc(si structInfo) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700115 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neil8012b442019-01-18 09:32:24 -0800116 for i := 0; i < mi.PBType.Fields().Len(); i++ {
117 fd := mi.PBType.Fields().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700118 fs := si.fieldsByNumber[fd.Number()]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700119 var fi fieldInfo
120 switch {
Joe Tsaid24bc722019-04-15 23:39:09 -0700121 case fd.Oneof() != nil:
Damien Neil3eaddf02019-05-09 11:33:55 -0700122 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.Oneof().Name()], si.oneofWrappersByNumber[fd.Number()])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700123 case fd.IsMap():
124 fi = fieldInfoForMap(fd, fs)
125 case fd.Cardinality() == pref.Repeated:
Joe Tsai4b7aff62018-11-14 14:05:19 -0800126 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700127 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700128 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700129 default:
130 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700131 }
132 mi.fields[fd.Number()] = &fi
133 }
Joe Tsai4ec39c72019-04-03 13:40:53 -0700134
135 mi.oneofs = map[pref.Name]*oneofInfo{}
136 for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
137 od := mi.PBType.Oneofs().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700138 mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], si.oneofWrappersByType)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700139 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700140}
Joe Tsaic6b75612018-09-13 14:24:37 -0700141
Joe Tsai95b02902018-10-31 18:23:42 -0700142func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
143 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700144 mi.unknownFields = f
145 return
146 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700147 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
148 return emptyUnknownFields{}
149 }
150}
151
Joe Tsai95b02902018-10-31 18:23:42 -0700152func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800153 if f := makeLegacyExtensionFieldsFunc(t); f != nil {
154 mi.extensionFields = f
155 return
156 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700157 mi.extensionFields = func(*messageDataType) pref.KnownFields {
158 return emptyExtensionFields{}
159 }
160}
161
Joe Tsai08e00302018-11-26 22:32:06 -0800162func (mi *MessageType) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700163 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800164}
165
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700166func (mi *MessageType) Methods() *piface.Methods {
167 return nil
168}
169
Joe Tsaic6b75612018-09-13 14:24:37 -0700170func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800171 // TODO: Remove this check? This API is primarily used by generated code,
172 // and should not violate this assumption. Leave this check in for now to
173 // provide some sanity checks during development. This can be removed if
174 // it proves to be detrimental to performance.
175 if reflect.TypeOf(p) != mi.GoType {
176 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
177 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800178 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700179}
180
181// messageDataType is a tuple of a pointer to the message data and
182// a pointer to the message type.
183//
184// TODO: Unfortunately, we need to close over a pointer and MessageType,
185// which incurs an an allocation. This pair is similar to a Go interface,
186// which is essentially a tuple of the same thing. We can make this efficient
187// with reflect.NamedOf (see https://golang.org/issues/16522).
188//
189// With that hypothetical API, we could dynamically create a new named type
Damien Neil8012b442019-01-18 09:32:24 -0800190// that has the same underlying type as MessageType.GoType, and
Joe Tsaic6b75612018-09-13 14:24:37 -0700191// dynamically create methods that close over MessageType.
192// Since the new type would have the same underlying type, we could directly
193// convert between pointers of those types, giving us an efficient way to swap
194// out the method set.
195//
196// Barring the ability to dynamically create named types, the workaround is
197// 1. either to accept the cost of an allocation for this wrapper struct or
198// 2. generate more types and methods, at the expense of binary size increase.
199type messageDataType struct {
200 p pointer
201 mi *MessageType
202}
203
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700204type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800205
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700206func (m *messageReflectWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800207 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800208}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700209func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800210 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800211 return (*knownFields)(m)
212}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700213func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800214 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800215 return m.mi.unknownFields((*messageDataType)(m))
216}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700217func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800218 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
219 return m
220 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700221 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800222}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700223func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800224 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800225}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700226func (m *messageReflectWrapper) ProtoMutable() {}
Joe Tsai08e00302018-11-26 22:32:06 -0800227
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700228var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
229
230type messageIfaceWrapper messageDataType
231
232func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
233 return (*messageReflectWrapper)(m)
234}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700235func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
236 return m.mi.Methods()
237}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700238func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
239 return m.p.AsIfaceOf(m.mi.GoType.Elem())
240}
Joe Tsai08e00302018-11-26 22:32:06 -0800241
Joe Tsaic6b75612018-09-13 14:24:37 -0700242type knownFields messageDataType
243
Joe Tsaic6b75612018-09-13 14:24:37 -0700244func (fs *knownFields) Len() (cnt int) {
245 for _, fi := range fs.mi.fields {
246 if fi.has(fs.p) {
247 cnt++
248 }
249 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700250 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700251}
252func (fs *knownFields) Has(n pref.FieldNumber) bool {
253 if fi := fs.mi.fields[n]; fi != nil {
254 return fi.has(fs.p)
255 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700256 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700257}
258func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
259 if fi := fs.mi.fields[n]; fi != nil {
260 return fi.get(fs.p)
261 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700262 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700263}
264func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
265 if fi := fs.mi.fields[n]; fi != nil {
266 fi.set(fs.p, v)
267 return
268 }
Damien Neil8012b442019-01-18 09:32:24 -0800269 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800270 fs.extensionFields().Set(n, v)
271 return
272 }
273 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700274}
275func (fs *knownFields) Clear(n pref.FieldNumber) {
276 if fi := fs.mi.fields[n]; fi != nil {
277 fi.clear(fs.p)
278 return
279 }
Damien Neil8012b442019-01-18 09:32:24 -0800280 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800281 fs.extensionFields().Clear(n)
282 return
283 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700284}
Joe Tsai4ec39c72019-04-03 13:40:53 -0700285func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
286 if oi := fs.mi.oneofs[s]; oi != nil {
287 return oi.which(fs.p)
288 }
289 return 0
290}
Joe Tsaic6b75612018-09-13 14:24:37 -0700291func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
292 for n, fi := range fs.mi.fields {
293 if fi.has(fs.p) {
294 if !f(n, fi.get(fs.p)) {
295 return
296 }
297 }
298 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700299 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700300}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800301func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800302 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800303 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800304 }
Damien Neil8012b442019-01-18 09:32:24 -0800305 if fs.mi.PBType.ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800306 return fs.extensionFields().NewMessage(n)
307 }
308 panic(fmt.Sprintf("invalid field: %d", n))
309}
Joe Tsaic6b75612018-09-13 14:24:37 -0700310func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700311 return fs.extensionFields().ExtensionTypes()
312}
313func (fs *knownFields) extensionFields() pref.KnownFields {
314 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700315}
316
Joe Tsaibe5348c2018-10-23 18:31:18 -0700317type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700318
Joe Tsaibe5348c2018-10-23 18:31:18 -0700319func (emptyUnknownFields) Len() int { return 0 }
320func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800321func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
322func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700323func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700324
Joe Tsaibe5348c2018-10-23 18:31:18 -0700325type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700326
Joe Tsaif0c01e42018-11-06 13:05:20 -0800327func (emptyExtensionFields) Len() int { return 0 }
328func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
329func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
330func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
331func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsai4ec39c72019-04-03 13:40:53 -0700332func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800333func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800334func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800335 panic("extensions not supported")
336}
337func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700338
339type emptyExtensionTypes struct{}
340
341func (emptyExtensionTypes) Len() int { return 0 }
342func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800343func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700344func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
345func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800346func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }