blob: 29d95e6e1d32433e8981677c4b6ff925e7823bf3 [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 {
Joe Tsaid24bc722019-04-15 23:39:09 -0700116 case fd.Oneof() != nil:
117 fi = fieldInfoForOneof(fd, oneofsByName[fd.Oneof().Name()], oneofWrappersByNumber[fd.Number()])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700118 case fd.IsMap():
119 fi = fieldInfoForMap(fd, fs)
120 case fd.Cardinality() == pref.Repeated:
Joe Tsai4b7aff62018-11-14 14:05:19 -0800121 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700122 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700123 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700124 default:
125 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700126 }
127 mi.fields[fd.Number()] = &fi
128 }
Joe Tsai4ec39c72019-04-03 13:40:53 -0700129
130 mi.oneofs = map[pref.Name]*oneofInfo{}
131 for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
132 od := mi.PBType.Oneofs().Get(i)
133 mi.oneofs[od.Name()] = makeOneofInfo(od, oneofsByName[od.Name()], oneofWrappersByType)
134 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700135}
Joe Tsaic6b75612018-09-13 14:24:37 -0700136
Joe Tsai95b02902018-10-31 18:23:42 -0700137func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
138 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700139 mi.unknownFields = f
140 return
141 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700142 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
143 return emptyUnknownFields{}
144 }
145}
146
Joe Tsai95b02902018-10-31 18:23:42 -0700147func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800148 if f := makeLegacyExtensionFieldsFunc(t); f != nil {
149 mi.extensionFields = f
150 return
151 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700152 mi.extensionFields = func(*messageDataType) pref.KnownFields {
153 return emptyExtensionFields{}
154 }
155}
156
Joe Tsai08e00302018-11-26 22:32:06 -0800157func (mi *MessageType) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700158 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800159}
160
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700161func (mi *MessageType) Methods() *piface.Methods {
162 return nil
163}
164
Joe Tsaic6b75612018-09-13 14:24:37 -0700165func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800166 // TODO: Remove this check? This API is primarily used by generated code,
167 // and should not violate this assumption. Leave this check in for now to
168 // provide some sanity checks during development. This can be removed if
169 // it proves to be detrimental to performance.
170 if reflect.TypeOf(p) != mi.GoType {
171 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
172 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800173 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700174}
175
176// messageDataType is a tuple of a pointer to the message data and
177// a pointer to the message type.
178//
179// TODO: Unfortunately, we need to close over a pointer and MessageType,
180// which incurs an an allocation. This pair is similar to a Go interface,
181// which is essentially a tuple of the same thing. We can make this efficient
182// with reflect.NamedOf (see https://golang.org/issues/16522).
183//
184// With that hypothetical API, we could dynamically create a new named type
Damien Neil8012b442019-01-18 09:32:24 -0800185// that has the same underlying type as MessageType.GoType, and
Joe Tsaic6b75612018-09-13 14:24:37 -0700186// dynamically create methods that close over MessageType.
187// Since the new type would have the same underlying type, we could directly
188// convert between pointers of those types, giving us an efficient way to swap
189// out the method set.
190//
191// Barring the ability to dynamically create named types, the workaround is
192// 1. either to accept the cost of an allocation for this wrapper struct or
193// 2. generate more types and methods, at the expense of binary size increase.
194type messageDataType struct {
195 p pointer
196 mi *MessageType
197}
198
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700199type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800200
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700201func (m *messageReflectWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800202 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800203}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700204func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800205 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800206 return (*knownFields)(m)
207}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700208func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800209 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800210 return m.mi.unknownFields((*messageDataType)(m))
211}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700212func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800213 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
214 return m
215 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700216 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800217}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700218func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800219 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800220}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700221func (m *messageReflectWrapper) ProtoMutable() {}
Joe Tsai08e00302018-11-26 22:32:06 -0800222
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700223var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
224
225type messageIfaceWrapper messageDataType
226
227func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
228 return (*messageReflectWrapper)(m)
229}
Damien Neil0d3e8cc2019-04-01 13:31:55 -0700230func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
231 return m.mi.Methods()
232}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700233func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
234 return m.p.AsIfaceOf(m.mi.GoType.Elem())
235}
Joe Tsai08e00302018-11-26 22:32:06 -0800236
Joe Tsaic6b75612018-09-13 14:24:37 -0700237type knownFields messageDataType
238
Joe Tsaic6b75612018-09-13 14:24:37 -0700239func (fs *knownFields) Len() (cnt int) {
240 for _, fi := range fs.mi.fields {
241 if fi.has(fs.p) {
242 cnt++
243 }
244 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700245 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700246}
247func (fs *knownFields) Has(n pref.FieldNumber) bool {
248 if fi := fs.mi.fields[n]; fi != nil {
249 return fi.has(fs.p)
250 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700251 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700252}
253func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
254 if fi := fs.mi.fields[n]; fi != nil {
255 return fi.get(fs.p)
256 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700257 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700258}
259func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
260 if fi := fs.mi.fields[n]; fi != nil {
261 fi.set(fs.p, v)
262 return
263 }
Damien Neil8012b442019-01-18 09:32:24 -0800264 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800265 fs.extensionFields().Set(n, v)
266 return
267 }
268 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700269}
270func (fs *knownFields) Clear(n pref.FieldNumber) {
271 if fi := fs.mi.fields[n]; fi != nil {
272 fi.clear(fs.p)
273 return
274 }
Damien Neil8012b442019-01-18 09:32:24 -0800275 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800276 fs.extensionFields().Clear(n)
277 return
278 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700279}
Joe Tsai4ec39c72019-04-03 13:40:53 -0700280func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
281 if oi := fs.mi.oneofs[s]; oi != nil {
282 return oi.which(fs.p)
283 }
284 return 0
285}
Joe Tsaic6b75612018-09-13 14:24:37 -0700286func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
287 for n, fi := range fs.mi.fields {
288 if fi.has(fs.p) {
289 if !f(n, fi.get(fs.p)) {
290 return
291 }
292 }
293 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700294 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700295}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800296func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800297 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800298 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800299 }
Damien Neil8012b442019-01-18 09:32:24 -0800300 if fs.mi.PBType.ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800301 return fs.extensionFields().NewMessage(n)
302 }
303 panic(fmt.Sprintf("invalid field: %d", n))
304}
Joe Tsaic6b75612018-09-13 14:24:37 -0700305func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700306 return fs.extensionFields().ExtensionTypes()
307}
308func (fs *knownFields) extensionFields() pref.KnownFields {
309 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700310}
311
Joe Tsaibe5348c2018-10-23 18:31:18 -0700312type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700313
Joe Tsaibe5348c2018-10-23 18:31:18 -0700314func (emptyUnknownFields) Len() int { return 0 }
315func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800316func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
317func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700318func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700319
Joe Tsaibe5348c2018-10-23 18:31:18 -0700320type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700321
Joe Tsaif0c01e42018-11-06 13:05:20 -0800322func (emptyExtensionFields) Len() int { return 0 }
323func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
324func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
325func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
326func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsai4ec39c72019-04-03 13:40:53 -0700327func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800328func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800329func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800330 panic("extensions not supported")
331}
332func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700333
334type emptyExtensionTypes struct{}
335
336func (emptyExtensionTypes) Len() int { return 0 }
337func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800338func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700339func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
340func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800341func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }