blob: 96efec9090254bc821b939b96b0a3aeb1ecd16ef [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
Damien Neile89e6242019-05-13 23:55:40 -070014 pvalue "google.golang.org/protobuf/internal/value"
15 pref "google.golang.org/protobuf/reflect/protoreflect"
16 piface "google.golang.org/protobuf/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{}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700116 for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
117 fd := mi.PBType.Descriptor().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 Tsaiac31a352019-05-13 14:32:56 -0700121 case fd.ContainingOneof() != nil:
122 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], si.oneofWrappersByNumber[fd.Number()])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700123 case fd.IsMap():
124 fi = fieldInfoForMap(fd, fs)
Joe Tsaiac31a352019-05-13 14:32:56 -0700125 case fd.IsList():
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{}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700136 for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
137 od := mi.PBType.Descriptor().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 Tsai0fc49f82019-05-01 12:29:25 -0700206// TODO: Remove this.
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700207func (m *messageReflectWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800208 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800209}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700210func (m *messageReflectWrapper) Descriptor() pref.MessageDescriptor {
211 return m.mi.PBType.Descriptor()
212}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700213func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800214 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800215 return (*knownFields)(m)
216}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700217func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800218 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800219 return m.mi.unknownFields((*messageDataType)(m))
220}
Joe Tsai0fc49f82019-05-01 12:29:25 -0700221func (m *messageReflectWrapper) New() pref.Message {
222 return m.mi.PBType.New()
223}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700224func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800225 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
226 return m
227 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700228 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800229}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700230func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800231 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800232}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700233func (m *messageReflectWrapper) ProtoMutable() {}
Joe Tsai08e00302018-11-26 22:32:06 -0800234
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700235var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
236
237type messageIfaceWrapper messageDataType
238
239func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
240 return (*messageReflectWrapper)(m)
241}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700242func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
243 return m.mi.Methods()
244}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700245func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
246 return m.p.AsIfaceOf(m.mi.GoType.Elem())
247}
Joe Tsai08e00302018-11-26 22:32:06 -0800248
Joe Tsaic6b75612018-09-13 14:24:37 -0700249type knownFields messageDataType
250
Joe Tsaic6b75612018-09-13 14:24:37 -0700251func (fs *knownFields) Len() (cnt int) {
252 for _, fi := range fs.mi.fields {
253 if fi.has(fs.p) {
254 cnt++
255 }
256 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700257 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700258}
259func (fs *knownFields) Has(n pref.FieldNumber) bool {
260 if fi := fs.mi.fields[n]; fi != nil {
261 return fi.has(fs.p)
262 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700263 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700264}
265func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
266 if fi := fs.mi.fields[n]; fi != nil {
267 return fi.get(fs.p)
268 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700269 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700270}
271func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
272 if fi := fs.mi.fields[n]; fi != nil {
273 fi.set(fs.p, v)
274 return
275 }
Joe Tsai0fc49f82019-05-01 12:29:25 -0700276 if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800277 fs.extensionFields().Set(n, v)
278 return
279 }
280 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700281}
282func (fs *knownFields) Clear(n pref.FieldNumber) {
283 if fi := fs.mi.fields[n]; fi != nil {
284 fi.clear(fs.p)
285 return
286 }
Joe Tsai0fc49f82019-05-01 12:29:25 -0700287 if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800288 fs.extensionFields().Clear(n)
289 return
290 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700291}
Joe Tsai4ec39c72019-04-03 13:40:53 -0700292func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
293 if oi := fs.mi.oneofs[s]; oi != nil {
294 return oi.which(fs.p)
295 }
296 return 0
297}
Joe Tsaic6b75612018-09-13 14:24:37 -0700298func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
299 for n, fi := range fs.mi.fields {
300 if fi.has(fs.p) {
301 if !f(n, fi.get(fs.p)) {
302 return
303 }
304 }
305 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700306 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700307}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800308func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800309 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800310 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800311 }
Joe Tsai0fc49f82019-05-01 12:29:25 -0700312 if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800313 return fs.extensionFields().NewMessage(n)
314 }
315 panic(fmt.Sprintf("invalid field: %d", n))
316}
Joe Tsaic6b75612018-09-13 14:24:37 -0700317func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700318 return fs.extensionFields().ExtensionTypes()
319}
320func (fs *knownFields) extensionFields() pref.KnownFields {
321 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700322}
323
Joe Tsaibe5348c2018-10-23 18:31:18 -0700324type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700325
Joe Tsaibe5348c2018-10-23 18:31:18 -0700326func (emptyUnknownFields) Len() int { return 0 }
327func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800328func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
329func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700330func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700331
Joe Tsaibe5348c2018-10-23 18:31:18 -0700332type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700333
Joe Tsaif0c01e42018-11-06 13:05:20 -0800334func (emptyExtensionFields) Len() int { return 0 }
335func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
336func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
337func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
338func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsai4ec39c72019-04-03 13:40:53 -0700339func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800340func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800341func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800342 panic("extensions not supported")
343}
344func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700345
346type emptyExtensionTypes struct{}
347
348func (emptyExtensionTypes) Len() int { return 0 }
349func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800350func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700351func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
352func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800353func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }