blob: c0b1029f5aea7fb5242d8a346321f90d635f9490 [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 Tsai01ab2962018-09-21 17:44:00 -070014 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070015)
16
Joe Tsaif0c01e42018-11-06 13:05:20 -080017// MessageOf returns the protoreflect.Message interface over p.
18// If p already implements proto.Message, then it directly calls the
19// ProtoReflect method, otherwise it wraps the legacy v1 message to implement
20// the v2 reflective interface.
21func MessageOf(p interface{}) pref.Message {
22 if m, ok := p.(pref.ProtoMessage); ok {
23 return m.ProtoReflect()
24 }
25 return legacyWrapMessage(reflect.ValueOf(p)).ProtoReflect()
26}
27
Joe Tsaic6b75612018-09-13 14:24:37 -070028// MessageType provides protobuf related functionality for a given Go type
29// that represents a message. A given instance of MessageType is tied to
30// exactly one Go type, which must be a pointer to a struct type.
31type MessageType struct {
Joe Tsaif0c01e42018-11-06 13:05:20 -080032 // Type is the underlying message type and must be populated.
Joe Tsaic6b75612018-09-13 14:24:37 -070033 // Once set, this field must never be mutated.
Joe Tsaif0c01e42018-11-06 13:05:20 -080034 Type pref.MessageType
Joe Tsaic6b75612018-09-13 14:24:37 -070035
36 once sync.Once // protects all unexported fields
37
Joe Tsaif0c01e42018-11-06 13:05:20 -080038 goType reflect.Type // pointer to struct
Joe Tsaic6b75612018-09-13 14:24:37 -070039
Joe Tsaifa02f4e2018-09-12 16:20:37 -070040 // TODO: Split fields into dense and sparse maps similar to the current
41 // table-driven implementation in v1?
42 fields map[pref.FieldNumber]*fieldInfo
Joe Tsaibe5348c2018-10-23 18:31:18 -070043
44 unknownFields func(*messageDataType) pref.UnknownFields
45 extensionFields func(*messageDataType) pref.KnownFields
Joe Tsaifa02f4e2018-09-12 16:20:37 -070046}
47
Joe Tsaic6b75612018-09-13 14:24:37 -070048// init lazily initializes the MessageType upon first use and
49// also checks that the provided pointer p is of the correct Go type.
50//
51// It must be called at the start of every exported method.
52func (mi *MessageType) init(p interface{}) {
53 mi.once.Do(func() {
Joe Tsaif0c01e42018-11-06 13:05:20 -080054 t := reflect.TypeOf(p)
Joe Tsaic6b75612018-09-13 14:24:37 -070055 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
56 panic(fmt.Sprintf("got %v, want *struct kind", t))
57 }
58 mi.goType = t
59
Joe Tsai95b02902018-10-31 18:23:42 -070060 mi.makeKnownFieldsFunc(t.Elem())
61 mi.makeUnknownFieldsFunc(t.Elem())
62 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070063 })
64
65 // TODO: Remove this check? This API is primarily used by generated code,
66 // and should not violate this assumption. Leave this check in for now to
67 // provide some sanity checks during development. This can be removed if
68 // it proves to be detrimental to performance.
69 if reflect.TypeOf(p) != mi.goType {
70 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.goType))
71 }
72}
73
Joe Tsaif0c01e42018-11-06 13:05:20 -080074// makeKnownFieldsFunc generates functions for operations that can be performed
75// on each protobuf message field. It takes in a reflect.Type representing the
76// Go struct and matches message fields with struct fields.
Joe Tsaifa02f4e2018-09-12 16:20:37 -070077//
78// This code assumes that the struct is well-formed and panics if there are
79// any discrepancies.
Joe Tsai95b02902018-10-31 18:23:42 -070080func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070081 // Generate a mapping of field numbers and names to Go struct field or type.
82 fields := map[pref.FieldNumber]reflect.StructField{}
83 oneofs := map[pref.Name]reflect.StructField{}
84 oneofFields := map[pref.FieldNumber]reflect.Type{}
85 special := map[string]reflect.StructField{}
86fieldLoop:
87 for i := 0; i < t.NumField(); i++ {
88 f := t.Field(i)
89 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
90 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
91 n, _ := strconv.ParseUint(s, 10, 64)
92 fields[pref.FieldNumber(n)] = f
93 continue fieldLoop
94 }
95 }
96 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
97 oneofs[pref.Name(s)] = f
98 continue fieldLoop
99 }
100 switch f.Name {
101 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
102 special[f.Name] = f
103 continue fieldLoop
104 }
105 }
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800106 var oneofWrappers []interface{}
Joe Tsai2c870bb2018-10-17 11:46:52 -0700107 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800108 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
109 }
110 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
111 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
112 }
113 for _, v := range oneofWrappers {
114 tf := reflect.TypeOf(v).Elem()
115 f := tf.Field(0)
116 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
117 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
118 n, _ := strconv.ParseUint(s, 10, 64)
119 oneofFields[pref.FieldNumber(n)] = tf
120 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700121 }
122 }
123 }
124
125 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Joe Tsaif0c01e42018-11-06 13:05:20 -0800126 for i := 0; i < mi.Type.Fields().Len(); i++ {
127 fd := mi.Type.Fields().Get(i)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700128 fs := fields[fd.Number()]
129 var fi fieldInfo
130 switch {
131 case fd.IsWeak():
132 fi = fieldInfoForWeak(fd, special["XXX_weak"])
133 case fd.OneofType() != nil:
134 fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
135 case fd.IsMap():
136 fi = fieldInfoForMap(fd, fs)
137 case fd.Cardinality() == pref.Repeated:
Joe Tsai4b7aff62018-11-14 14:05:19 -0800138 fi = fieldInfoForList(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700139 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700140 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700141 default:
142 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700143 }
144 mi.fields[fd.Number()] = &fi
145 }
146}
Joe Tsaic6b75612018-09-13 14:24:37 -0700147
Joe Tsai95b02902018-10-31 18:23:42 -0700148func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
149 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700150 mi.unknownFields = f
151 return
152 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700153 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
154 return emptyUnknownFields{}
155 }
156}
157
Joe Tsai95b02902018-10-31 18:23:42 -0700158func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800159 if f := makeLegacyExtensionFieldsFunc(t); f != nil {
160 mi.extensionFields = f
161 return
162 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700163 mi.extensionFields = func(*messageDataType) pref.KnownFields {
164 return emptyExtensionFields{}
165 }
166}
167
Joe Tsaic6b75612018-09-13 14:24:37 -0700168func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
Joe Tsaic6b75612018-09-13 14:24:37 -0700169 return (*knownFields)(mi.dataTypeOf(p))
170}
171
172func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700173 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700174}
175
176func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
Joe Tsaif0c01e42018-11-06 13:05:20 -0800177 mi.init(p)
Joe Tsaic6b75612018-09-13 14:24:37 -0700178 return &messageDataType{pointerOfIface(&p), mi}
179}
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
190// that has the same underlying type as MessageType.goType, and
191// 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 Tsaic6b75612018-09-13 14:24:37 -0700204type knownFields messageDataType
205
Joe Tsaic6b75612018-09-13 14:24:37 -0700206func (fs *knownFields) Len() (cnt int) {
207 for _, fi := range fs.mi.fields {
208 if fi.has(fs.p) {
209 cnt++
210 }
211 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700212 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700213}
214func (fs *knownFields) Has(n pref.FieldNumber) bool {
215 if fi := fs.mi.fields[n]; fi != nil {
216 return fi.has(fs.p)
217 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700218 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700219}
220func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
221 if fi := fs.mi.fields[n]; fi != nil {
222 return fi.get(fs.p)
223 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700224 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700225}
226func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
227 if fi := fs.mi.fields[n]; fi != nil {
228 fi.set(fs.p, v)
229 return
230 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800231 if fs.mi.Type.ExtensionRanges().Has(n) {
232 fs.extensionFields().Set(n, v)
233 return
234 }
235 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700236}
237func (fs *knownFields) Clear(n pref.FieldNumber) {
238 if fi := fs.mi.fields[n]; fi != nil {
239 fi.clear(fs.p)
240 return
241 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800242 if fs.mi.Type.ExtensionRanges().Has(n) {
243 fs.extensionFields().Clear(n)
244 return
245 }
Joe Tsaic6b75612018-09-13 14:24:37 -0700246}
247func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
248 if fi := fs.mi.fields[n]; fi != nil {
249 return fi.mutable(fs.p)
250 }
Joe Tsaif0c01e42018-11-06 13:05:20 -0800251 if fs.mi.Type.ExtensionRanges().Has(n) {
252 return fs.extensionFields().Mutable(n)
253 }
254 panic(fmt.Sprintf("invalid field: %d", n))
Joe Tsaic6b75612018-09-13 14:24:37 -0700255}
256func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
257 for n, fi := range fs.mi.fields {
258 if fi.has(fs.p) {
259 if !f(n, fi.get(fs.p)) {
260 return
261 }
262 }
263 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700264 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700265}
266func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700267 return fs.extensionFields().ExtensionTypes()
268}
269func (fs *knownFields) extensionFields() pref.KnownFields {
270 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700271}
272
Joe Tsaibe5348c2018-10-23 18:31:18 -0700273type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700274
Joe Tsaibe5348c2018-10-23 18:31:18 -0700275func (emptyUnknownFields) Len() int { return 0 }
276func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800277func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
278func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700279func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700280
Joe Tsaibe5348c2018-10-23 18:31:18 -0700281type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700282
Joe Tsaif0c01e42018-11-06 13:05:20 -0800283func (emptyExtensionFields) Len() int { return 0 }
284func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
285func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
286func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
287func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
288func (emptyExtensionFields) Mutable(pref.FieldNumber) pref.Mutable { panic("extensions not supported") }
289func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
290func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700291
292type emptyExtensionTypes struct{}
293
294func (emptyExtensionTypes) Len() int { return 0 }
295func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800296func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700297func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
298func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800299func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }