blob: dbf98167d6c714fba697c5b8cf692a5ed4deca0c [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"
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 {
Damien Neil8012b442019-01-18 09:32:24 -080022 // GoType is the underlying message Go type and must be populated.
Joe Tsaic6b75612018-09-13 14:24:37 -070023 // Once set, this field must never be mutated.
Damien Neil8012b442019-01-18 09:32:24 -080024 GoType reflect.Type // pointer to struct
25
26 // PBType is the underlying message descriptor type and must be populated.
27 // Once set, this field must never be mutated.
28 PBType pref.MessageType
Joe Tsaic6b75612018-09-13 14:24:37 -070029
30 once sync.Once // protects all unexported fields
31
Joe Tsaifa02f4e2018-09-12 16:20:37 -070032 // TODO: Split fields into dense and sparse maps similar to the current
33 // table-driven implementation in v1?
34 fields map[pref.FieldNumber]*fieldInfo
Joe Tsaibe5348c2018-10-23 18:31:18 -070035
36 unknownFields func(*messageDataType) pref.UnknownFields
37 extensionFields func(*messageDataType) pref.KnownFields
Joe Tsaifa02f4e2018-09-12 16:20:37 -070038}
39
Damien Neil8012b442019-01-18 09:32:24 -080040func (mi *MessageType) init() {
Joe Tsaic6b75612018-09-13 14:24:37 -070041 mi.once.Do(func() {
Damien Neil8012b442019-01-18 09:32:24 -080042 t := mi.GoType
Joe Tsaic6b75612018-09-13 14:24:37 -070043 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
44 panic(fmt.Sprintf("got %v, want *struct kind", t))
45 }
Joe Tsaic6b75612018-09-13 14:24:37 -070046
Joe Tsai95b02902018-10-31 18:23:42 -070047 mi.makeKnownFieldsFunc(t.Elem())
48 mi.makeUnknownFieldsFunc(t.Elem())
49 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070050 })
Joe Tsaic6b75612018-09-13 14:24:37 -070051}
52
Joe Tsaif0c01e42018-11-06 13:05:20 -080053// makeKnownFieldsFunc generates functions for operations that can be performed
54// on each protobuf message field. It takes in a reflect.Type representing the
55// Go struct and matches message fields with struct fields.
Joe Tsaifa02f4e2018-09-12 16:20:37 -070056//
57// This code assumes that the struct is well-formed and panics if there are
58// any discrepancies.
Joe Tsai95b02902018-10-31 18:23:42 -070059func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070060 // Generate a mapping of field numbers and names to Go struct field or type.
61 fields := map[pref.FieldNumber]reflect.StructField{}
62 oneofs := map[pref.Name]reflect.StructField{}
63 oneofFields := map[pref.FieldNumber]reflect.Type{}
64 special := map[string]reflect.StructField{}
65fieldLoop:
66 for i := 0; i < t.NumField(); i++ {
67 f := t.Field(i)
68 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
69 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
70 n, _ := strconv.ParseUint(s, 10, 64)
71 fields[pref.FieldNumber(n)] = f
72 continue fieldLoop
73 }
74 }
75 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
76 oneofs[pref.Name(s)] = f
77 continue fieldLoop
78 }
79 switch f.Name {
80 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
81 special[f.Name] = f
82 continue fieldLoop
83 }
84 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -080085 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -070086 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -080087 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
88 }
89 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
90 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
91 }
92 for _, v := range oneofWrappers {
93 tf := reflect.TypeOf(v).Elem()
94 f := tf.Field(0)
95 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
96 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
97 n, _ := strconv.ParseUint(s, 10, 64)
98 oneofFields[pref.FieldNumber(n)] = tf
99 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700100 }
101 }
102 }
103
104 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neil8012b442019-01-18 09:32:24 -0800105 for i := 0; i < mi.PBType.Fields().Len(); i++ {
106 fd := mi.PBType.Fields().Get(i)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700107 fs := fields[fd.Number()]
108 var fi fieldInfo
109 switch {
110 case fd.IsWeak():
111 fi = fieldInfoForWeak(fd, special["XXX_weak"])
112 case fd.OneofType() != nil:
113 fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
114 case fd.IsMap():
115 fi = fieldInfoForMap(fd, fs)
116 case fd.Cardinality() == pref.Repeated:
Joe Tsai4b7aff62018-11-14 14:05:19 -0800117 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700118 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700119 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700120 default:
121 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700122 }
123 mi.fields[fd.Number()] = &fi
124 }
125}
Joe Tsaic6b75612018-09-13 14:24:37 -0700126
Joe Tsai95b02902018-10-31 18:23:42 -0700127func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
128 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700129 mi.unknownFields = f
130 return
131 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700132 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
133 return emptyUnknownFields{}
134 }
135}
136
Joe Tsai95b02902018-10-31 18:23:42 -0700137func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800138 if f := makeLegacyExtensionFieldsFunc(t); f != nil {
139 mi.extensionFields = f
140 return
141 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700142 mi.extensionFields = func(*messageDataType) pref.KnownFields {
143 return emptyExtensionFields{}
144 }
145}
146
Joe Tsai08e00302018-11-26 22:32:06 -0800147func (mi *MessageType) MessageOf(p interface{}) pref.Message {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700148 return (*messageReflectWrapper)(mi.dataTypeOf(p))
Joe Tsai08e00302018-11-26 22:32:06 -0800149}
150
Joe Tsaic6b75612018-09-13 14:24:37 -0700151func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800152 // TODO: Remove this check? This API is primarily used by generated code,
153 // and should not violate this assumption. Leave this check in for now to
154 // provide some sanity checks during development. This can be removed if
155 // it proves to be detrimental to performance.
156 if reflect.TypeOf(p) != mi.GoType {
157 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
158 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800159 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700160}
161
162// messageDataType is a tuple of a pointer to the message data and
163// a pointer to the message type.
164//
165// TODO: Unfortunately, we need to close over a pointer and MessageType,
166// which incurs an an allocation. This pair is similar to a Go interface,
167// which is essentially a tuple of the same thing. We can make this efficient
168// with reflect.NamedOf (see https://golang.org/issues/16522).
169//
170// With that hypothetical API, we could dynamically create a new named type
Damien Neil8012b442019-01-18 09:32:24 -0800171// that has the same underlying type as MessageType.GoType, and
Joe Tsaic6b75612018-09-13 14:24:37 -0700172// dynamically create methods that close over MessageType.
173// Since the new type would have the same underlying type, we could directly
174// convert between pointers of those types, giving us an efficient way to swap
175// out the method set.
176//
177// Barring the ability to dynamically create named types, the workaround is
178// 1. either to accept the cost of an allocation for this wrapper struct or
179// 2. generate more types and methods, at the expense of binary size increase.
180type messageDataType struct {
181 p pointer
182 mi *MessageType
183}
184
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700185type messageReflectWrapper messageDataType
Joe Tsai08e00302018-11-26 22:32:06 -0800186
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700187func (m *messageReflectWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800188 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800189}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700190func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800191 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800192 return (*knownFields)(m)
193}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700194func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800195 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800196 return m.mi.unknownFields((*messageDataType)(m))
197}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700198func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
Joe Tsai08e00302018-11-26 22:32:06 -0800199 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
200 return m
201 }
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700202 return (*messageIfaceWrapper)(m)
Joe Tsai08e00302018-11-26 22:32:06 -0800203}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700204func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800205 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800206}
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700207func (m *messageReflectWrapper) ProtoMutable() {}
Joe Tsai08e00302018-11-26 22:32:06 -0800208
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700209var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
210
211type messageIfaceWrapper messageDataType
212
213func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
214 return (*messageReflectWrapper)(m)
215}
216func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
217 return m.p.AsIfaceOf(m.mi.GoType.Elem())
218}
Joe Tsai08e00302018-11-26 22:32:06 -0800219
Joe Tsaic6b75612018-09-13 14:24:37 -0700220type knownFields messageDataType
221
Joe Tsaic6b75612018-09-13 14:24:37 -0700222func (fs *knownFields) Len() (cnt int) {
223 for _, fi := range fs.mi.fields {
224 if fi.has(fs.p) {
225 cnt++
226 }
227 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700228 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700229}
230func (fs *knownFields) Has(n pref.FieldNumber) bool {
231 if fi := fs.mi.fields[n]; fi != nil {
232 return fi.has(fs.p)
233 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700234 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700235}
236func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
237 if fi := fs.mi.fields[n]; fi != nil {
238 return fi.get(fs.p)
239 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700240 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700241}
242func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
243 if fi := fs.mi.fields[n]; fi != nil {
244 fi.set(fs.p, v)
245 return
246 }
Damien Neil8012b442019-01-18 09:32:24 -0800247 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800248 fs.extensionFields().Set(n, v)
249 return
250 }
251 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700252}
253func (fs *knownFields) Clear(n pref.FieldNumber) {
254 if fi := fs.mi.fields[n]; fi != nil {
255 fi.clear(fs.p)
256 return
257 }
Damien Neil8012b442019-01-18 09:32:24 -0800258 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800259 fs.extensionFields().Clear(n)
260 return
261 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700262}
Joe Tsaic6b75612018-09-13 14:24:37 -0700263func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
264 for n, fi := range fs.mi.fields {
265 if fi.has(fs.p) {
266 if !f(n, fi.get(fs.p)) {
267 return
268 }
269 }
270 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700271 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700272}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800273func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800274 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800275 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800276 }
Damien Neil8012b442019-01-18 09:32:24 -0800277 if fs.mi.PBType.ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800278 return fs.extensionFields().NewMessage(n)
279 }
280 panic(fmt.Sprintf("invalid field: %d", n))
281}
Joe Tsaic6b75612018-09-13 14:24:37 -0700282func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700283 return fs.extensionFields().ExtensionTypes()
284}
285func (fs *knownFields) extensionFields() pref.KnownFields {
286 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700287}
288
Joe Tsaibe5348c2018-10-23 18:31:18 -0700289type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700290
Joe Tsaibe5348c2018-10-23 18:31:18 -0700291func (emptyUnknownFields) Len() int { return 0 }
292func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800293func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
294func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700295func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700296
Joe Tsaibe5348c2018-10-23 18:31:18 -0700297type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700298
Joe Tsaif0c01e42018-11-06 13:05:20 -0800299func (emptyExtensionFields) Len() int { return 0 }
300func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
301func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
302func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
303func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsaif0c01e42018-11-06 13:05:20 -0800304func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800305func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800306 panic("extensions not supported")
307}
308func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700309
310type emptyExtensionTypes struct{}
311
312func (emptyExtensionTypes) Len() int { return 0 }
313func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800314func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700315func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
316func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800317func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }