blob: c6663a37e46e62027a42a0cd9df1d3606f8c7eb7 [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 {
148 return (*messageWrapper)(mi.dataTypeOf(p))
149}
150
Joe Tsaic6b75612018-09-13 14:24:37 -0700151func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800152 mi.init()
Joe Tsaic6b75612018-09-13 14:24:37 -0700153 return (*knownFields)(mi.dataTypeOf(p))
154}
155
156func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800157 mi.init()
Joe Tsaibe5348c2018-10-23 18:31:18 -0700158 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700159}
160
161func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Damien Neil8012b442019-01-18 09:32:24 -0800162 // TODO: Remove this check? This API is primarily used by generated code,
163 // and should not violate this assumption. Leave this check in for now to
164 // provide some sanity checks during development. This can be removed if
165 // it proves to be detrimental to performance.
166 if reflect.TypeOf(p) != mi.GoType {
167 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
168 }
Joe Tsai6cf80c42018-12-01 04:57:09 -0800169 return &messageDataType{pointerOfIface(p), mi}
Joe Tsaic6b75612018-09-13 14:24:37 -0700170}
171
172// messageDataType is a tuple of a pointer to the message data and
173// a pointer to the message type.
174//
175// TODO: Unfortunately, we need to close over a pointer and MessageType,
176// which incurs an an allocation. This pair is similar to a Go interface,
177// which is essentially a tuple of the same thing. We can make this efficient
178// with reflect.NamedOf (see https://golang.org/issues/16522).
179//
180// With that hypothetical API, we could dynamically create a new named type
Damien Neil8012b442019-01-18 09:32:24 -0800181// that has the same underlying type as MessageType.GoType, and
Joe Tsaic6b75612018-09-13 14:24:37 -0700182// dynamically create methods that close over MessageType.
183// Since the new type would have the same underlying type, we could directly
184// convert between pointers of those types, giving us an efficient way to swap
185// out the method set.
186//
187// Barring the ability to dynamically create named types, the workaround is
188// 1. either to accept the cost of an allocation for this wrapper struct or
189// 2. generate more types and methods, at the expense of binary size increase.
190type messageDataType struct {
191 p pointer
192 mi *MessageType
193}
194
Joe Tsai08e00302018-11-26 22:32:06 -0800195type messageWrapper messageDataType
196
197func (m *messageWrapper) Type() pref.MessageType {
Damien Neil8012b442019-01-18 09:32:24 -0800198 return m.mi.PBType
Joe Tsai08e00302018-11-26 22:32:06 -0800199}
200func (m *messageWrapper) KnownFields() pref.KnownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800201 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800202 return (*knownFields)(m)
203}
204func (m *messageWrapper) UnknownFields() pref.UnknownFields {
Damien Neil8012b442019-01-18 09:32:24 -0800205 m.mi.init()
Joe Tsai08e00302018-11-26 22:32:06 -0800206 return m.mi.unknownFields((*messageDataType)(m))
207}
208func (m *messageWrapper) Interface() pref.ProtoMessage {
209 if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
210 return m
211 }
212 return m
213}
214func (m *messageWrapper) ProtoReflect() pref.Message {
215 return m
216}
217func (m *messageWrapper) ProtoUnwrap() interface{} {
Damien Neil8012b442019-01-18 09:32:24 -0800218 return m.p.AsIfaceOf(m.mi.GoType.Elem())
Joe Tsai08e00302018-11-26 22:32:06 -0800219}
220func (m *messageWrapper) ProtoMutable() {}
221
222var _ pvalue.Unwrapper = (*messageWrapper)(nil)
223
Joe Tsaic6b75612018-09-13 14:24:37 -0700224type knownFields messageDataType
225
Joe Tsaic6b75612018-09-13 14:24:37 -0700226func (fs *knownFields) Len() (cnt int) {
227 for _, fi := range fs.mi.fields {
228 if fi.has(fs.p) {
229 cnt++
230 }
231 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700232 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700233}
234func (fs *knownFields) Has(n pref.FieldNumber) bool {
235 if fi := fs.mi.fields[n]; fi != nil {
236 return fi.has(fs.p)
237 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700238 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700239}
240func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
241 if fi := fs.mi.fields[n]; fi != nil {
242 return fi.get(fs.p)
243 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700244 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700245}
246func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
247 if fi := fs.mi.fields[n]; fi != nil {
248 fi.set(fs.p, v)
249 return
250 }
Damien Neil8012b442019-01-18 09:32:24 -0800251 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800252 fs.extensionFields().Set(n, v)
253 return
254 }
255 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700256}
257func (fs *knownFields) Clear(n pref.FieldNumber) {
258 if fi := fs.mi.fields[n]; fi != nil {
259 fi.clear(fs.p)
260 return
261 }
Damien Neil8012b442019-01-18 09:32:24 -0800262 if fs.mi.PBType.ExtensionRanges().Has(n) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800263 fs.extensionFields().Clear(n)
264 return
265 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700266}
Joe Tsaic6b75612018-09-13 14:24:37 -0700267func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
268 for n, fi := range fs.mi.fields {
269 if fi.has(fs.p) {
270 if !f(n, fi.get(fs.p)) {
271 return
272 }
273 }
274 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700275 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700276}
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800277func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800278 if fi := fs.mi.fields[n]; fi != nil {
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800279 return fi.newMessage()
Damien Neil97e7f572018-12-07 14:28:33 -0800280 }
Damien Neil8012b442019-01-18 09:32:24 -0800281 if fs.mi.PBType.ExtensionRanges().Has(n) {
Damien Neil97e7f572018-12-07 14:28:33 -0800282 return fs.extensionFields().NewMessage(n)
283 }
284 panic(fmt.Sprintf("invalid field: %d", n))
285}
Joe Tsaic6b75612018-09-13 14:24:37 -0700286func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700287 return fs.extensionFields().ExtensionTypes()
288}
289func (fs *knownFields) extensionFields() pref.KnownFields {
290 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700291}
292
Joe Tsaibe5348c2018-10-23 18:31:18 -0700293type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700294
Joe Tsaibe5348c2018-10-23 18:31:18 -0700295func (emptyUnknownFields) Len() int { return 0 }
296func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800297func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
298func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700299func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700300
Joe Tsaibe5348c2018-10-23 18:31:18 -0700301type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700302
Joe Tsaif0c01e42018-11-06 13:05:20 -0800303func (emptyExtensionFields) Len() int { return 0 }
304func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
305func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
306func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
307func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
Joe Tsaif0c01e42018-11-06 13:05:20 -0800308func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800309func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
Damien Neil97e7f572018-12-07 14:28:33 -0800310 panic("extensions not supported")
311}
312func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700313
314type emptyExtensionTypes struct{}
315
316func (emptyExtensionTypes) Len() int { return 0 }
317func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800318func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700319func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
320func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800321func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }