blob: ab889cce541da9f6b8310460804c092c591e7677 [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 Tsaic6b75612018-09-13 14:24:37 -070015 ptype "github.com/golang/protobuf/v2/reflect/prototype"
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 {
22 // Desc is an optionally provided message descriptor. If nil, the descriptor
23 // is lazily derived from the Go type information of generated messages
24 // for the v1 API.
25 //
26 // Once set, this field must never be mutated.
27 Desc pref.MessageDescriptor
28
29 once sync.Once // protects all unexported fields
30
31 goType reflect.Type // pointer to struct
32 pbType pref.MessageType // only valid if goType does not implement proto.Message
33
Joe Tsaifa02f4e2018-09-12 16:20:37 -070034 // TODO: Split fields into dense and sparse maps similar to the current
35 // table-driven implementation in v1?
36 fields map[pref.FieldNumber]*fieldInfo
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
Joe Tsaic6b75612018-09-13 14:24:37 -070042// init lazily initializes the MessageType upon first use and
43// also checks that the provided pointer p is of the correct Go type.
44//
45// It must be called at the start of every exported method.
46func (mi *MessageType) init(p interface{}) {
47 mi.once.Do(func() {
48 v := reflect.ValueOf(p)
49 t := v.Type()
50 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
51 panic(fmt.Sprintf("got %v, want *struct kind", t))
52 }
53 mi.goType = t
54
55 // Derive the message descriptor if unspecified.
Joe Tsai95b02902018-10-31 18:23:42 -070056 if mi.Desc == nil {
57 mi.Desc = loadMessageDesc(t)
Joe Tsaic6b75612018-09-13 14:24:37 -070058 }
59
60 // Initialize the Go message type wrapper if the Go type does not
61 // implement the proto.Message interface.
62 //
63 // Otherwise, we assume that the Go type manually implements the
64 // interface and is internally consistent such that:
65 // goType == reflect.New(goType.Elem()).Interface().(proto.Message).ProtoReflect().Type().GoType()
66 //
67 // Generated code ensures that this property holds.
68 if _, ok := p.(pref.ProtoMessage); !ok {
Joe Tsai1c40f492018-11-09 17:02:57 -080069 mi.pbType = ptype.GoMessage(mi.Desc, func(pref.MessageType) pref.ProtoMessage {
70 p := reflect.New(t.Elem()).Interface()
Joe Tsai6f9095c2018-11-10 14:12:21 -080071 return (*legacyMessageWrapper)(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -070072 })
73 }
74
Joe Tsai95b02902018-10-31 18:23:42 -070075 mi.makeKnownFieldsFunc(t.Elem())
76 mi.makeUnknownFieldsFunc(t.Elem())
77 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070078 })
79
80 // TODO: Remove this check? This API is primarily used by generated code,
81 // and should not violate this assumption. Leave this check in for now to
82 // provide some sanity checks during development. This can be removed if
83 // it proves to be detrimental to performance.
84 if reflect.TypeOf(p) != mi.goType {
85 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.goType))
86 }
87}
88
Joe Tsai95b02902018-10-31 18:23:42 -070089// makeKnownFieldsFunc generates per-field functions for all operations
Joe Tsaifa02f4e2018-09-12 16:20:37 -070090// to be performed on each field. It takes in a reflect.Type representing the
91// Go struct, and a protoreflect.MessageDescriptor to match with the fields
92// in the struct.
93//
94// This code assumes that the struct is well-formed and panics if there are
95// any discrepancies.
Joe Tsai95b02902018-10-31 18:23:42 -070096func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -070097 // Generate a mapping of field numbers and names to Go struct field or type.
98 fields := map[pref.FieldNumber]reflect.StructField{}
99 oneofs := map[pref.Name]reflect.StructField{}
100 oneofFields := map[pref.FieldNumber]reflect.Type{}
101 special := map[string]reflect.StructField{}
102fieldLoop:
103 for i := 0; i < t.NumField(); i++ {
104 f := t.Field(i)
105 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
106 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
107 n, _ := strconv.ParseUint(s, 10, 64)
108 fields[pref.FieldNumber(n)] = f
109 continue fieldLoop
110 }
111 }
112 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
113 oneofs[pref.Name(s)] = f
114 continue fieldLoop
115 }
116 switch f.Name {
117 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
118 special[f.Name] = f
119 continue fieldLoop
120 }
121 }
Joe Tsai2c870bb2018-10-17 11:46:52 -0700122 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -0700123 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700124 oneofLoop:
125 for _, v := range vs.Interface().([]interface{}) {
126 tf := reflect.TypeOf(v).Elem()
127 f := tf.Field(0)
128 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
129 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
130 n, _ := strconv.ParseUint(s, 10, 64)
131 oneofFields[pref.FieldNumber(n)] = tf
132 continue oneofLoop
133 }
134 }
135 }
136 }
137
138 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Joe Tsai95b02902018-10-31 18:23:42 -0700139 for i := 0; i < mi.Desc.Fields().Len(); i++ {
140 fd := mi.Desc.Fields().Get(i)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700141 fs := fields[fd.Number()]
142 var fi fieldInfo
143 switch {
144 case fd.IsWeak():
145 fi = fieldInfoForWeak(fd, special["XXX_weak"])
146 case fd.OneofType() != nil:
147 fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
148 case fd.IsMap():
149 fi = fieldInfoForMap(fd, fs)
150 case fd.Cardinality() == pref.Repeated:
151 fi = fieldInfoForVector(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700152 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700153 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700154 default:
155 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700156 }
157 mi.fields[fd.Number()] = &fi
158 }
159}
Joe Tsaic6b75612018-09-13 14:24:37 -0700160
Joe Tsai95b02902018-10-31 18:23:42 -0700161func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
162 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700163 mi.unknownFields = f
164 return
165 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700166 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
167 return emptyUnknownFields{}
168 }
169}
170
Joe Tsai95b02902018-10-31 18:23:42 -0700171func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700172 // TODO
173 mi.extensionFields = func(*messageDataType) pref.KnownFields {
174 return emptyExtensionFields{}
175 }
176}
177
Joe Tsaic6b75612018-09-13 14:24:37 -0700178func (mi *MessageType) MessageOf(p interface{}) pref.Message {
179 mi.init(p)
180 if m, ok := p.(pref.ProtoMessage); ok {
181 // We assume p properly implements protoreflect.Message.
182 // See the comment in MessageType.init regarding pbType.
183 return m.ProtoReflect()
184 }
Joe Tsai6f9095c2018-11-10 14:12:21 -0800185 return (*legacyMessageWrapper)(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700186}
187
188func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
189 mi.init(p)
190 return (*knownFields)(mi.dataTypeOf(p))
191}
192
193func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
194 mi.init(p)
Joe Tsaibe5348c2018-10-23 18:31:18 -0700195 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700196}
197
198func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
199 return &messageDataType{pointerOfIface(&p), mi}
200}
201
202// messageDataType is a tuple of a pointer to the message data and
203// a pointer to the message type.
204//
205// TODO: Unfortunately, we need to close over a pointer and MessageType,
206// which incurs an an allocation. This pair is similar to a Go interface,
207// which is essentially a tuple of the same thing. We can make this efficient
208// with reflect.NamedOf (see https://golang.org/issues/16522).
209//
210// With that hypothetical API, we could dynamically create a new named type
211// that has the same underlying type as MessageType.goType, and
212// dynamically create methods that close over MessageType.
213// Since the new type would have the same underlying type, we could directly
214// convert between pointers of those types, giving us an efficient way to swap
215// out the method set.
216//
217// Barring the ability to dynamically create named types, the workaround is
218// 1. either to accept the cost of an allocation for this wrapper struct or
219// 2. generate more types and methods, at the expense of binary size increase.
220type messageDataType struct {
221 p pointer
222 mi *MessageType
223}
224
Joe Tsaic6b75612018-09-13 14:24:37 -0700225type knownFields messageDataType
226
Joe Tsaic6b75612018-09-13 14:24:37 -0700227func (fs *knownFields) Len() (cnt int) {
228 for _, fi := range fs.mi.fields {
229 if fi.has(fs.p) {
230 cnt++
231 }
232 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700233 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700234}
235func (fs *knownFields) Has(n pref.FieldNumber) bool {
236 if fi := fs.mi.fields[n]; fi != nil {
237 return fi.has(fs.p)
238 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700239 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700240}
241func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
242 if fi := fs.mi.fields[n]; fi != nil {
243 return fi.get(fs.p)
244 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700245 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700246}
247func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
248 if fi := fs.mi.fields[n]; fi != nil {
249 fi.set(fs.p, v)
250 return
251 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700252 fs.extensionFields().Set(n, v)
Joe Tsaic6b75612018-09-13 14:24:37 -0700253}
254func (fs *knownFields) Clear(n pref.FieldNumber) {
255 if fi := fs.mi.fields[n]; fi != nil {
256 fi.clear(fs.p)
257 return
258 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700259 fs.extensionFields().Clear(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700260}
261func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
262 if fi := fs.mi.fields[n]; fi != nil {
263 return fi.mutable(fs.p)
264 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700265 return fs.extensionFields().Mutable(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700266}
267func (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}
277func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700278 return fs.extensionFields().ExtensionTypes()
279}
280func (fs *knownFields) extensionFields() pref.KnownFields {
281 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700282}
283
Joe Tsaibe5348c2018-10-23 18:31:18 -0700284type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700285
Joe Tsaibe5348c2018-10-23 18:31:18 -0700286func (emptyUnknownFields) Len() int { return 0 }
287func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800288func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
289func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700290func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700291
Joe Tsaibe5348c2018-10-23 18:31:18 -0700292type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700293
Joe Tsaibe5348c2018-10-23 18:31:18 -0700294func (emptyExtensionFields) Len() int { return 0 }
295func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
296func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800297func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
298func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
299func (emptyExtensionFields) Mutable(pref.FieldNumber) pref.Mutable { panic("extensions not supported") }
300func (emptyExtensionFields) Range(f func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700301func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
302
303type emptyExtensionTypes struct{}
304
305func (emptyExtensionTypes) Len() int { return 0 }
306func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800307func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700308func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
309func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800310func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }