blob: c406b3d7d570bfeda34adafd85c25d7b6b5ac260 [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 {
69 mi.pbType = ptype.NewGoMessage(&ptype.GoMessage{
Joe Tsai95b02902018-10-31 18:23:42 -070070 MessageDescriptor: mi.Desc,
Joe Tsaic6b75612018-09-13 14:24:37 -070071 New: func(pref.MessageType) pref.ProtoMessage {
72 p := reflect.New(t.Elem()).Interface()
73 return (*message)(mi.dataTypeOf(p))
74 },
75 })
76 }
77
Joe Tsai95b02902018-10-31 18:23:42 -070078 mi.makeKnownFieldsFunc(t.Elem())
79 mi.makeUnknownFieldsFunc(t.Elem())
80 mi.makeExtensionFieldsFunc(t.Elem())
Joe Tsaic6b75612018-09-13 14:24:37 -070081 })
82
83 // TODO: Remove this check? This API is primarily used by generated code,
84 // and should not violate this assumption. Leave this check in for now to
85 // provide some sanity checks during development. This can be removed if
86 // it proves to be detrimental to performance.
87 if reflect.TypeOf(p) != mi.goType {
88 panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.goType))
89 }
90}
91
Joe Tsai95b02902018-10-31 18:23:42 -070092// makeKnownFieldsFunc generates per-field functions for all operations
Joe Tsaifa02f4e2018-09-12 16:20:37 -070093// to be performed on each field. It takes in a reflect.Type representing the
94// Go struct, and a protoreflect.MessageDescriptor to match with the fields
95// in the struct.
96//
97// This code assumes that the struct is well-formed and panics if there are
98// any discrepancies.
Joe Tsai95b02902018-10-31 18:23:42 -070099func (mi *MessageType) makeKnownFieldsFunc(t reflect.Type) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700100 // Generate a mapping of field numbers and names to Go struct field or type.
101 fields := map[pref.FieldNumber]reflect.StructField{}
102 oneofs := map[pref.Name]reflect.StructField{}
103 oneofFields := map[pref.FieldNumber]reflect.Type{}
104 special := map[string]reflect.StructField{}
105fieldLoop:
106 for i := 0; i < t.NumField(); i++ {
107 f := t.Field(i)
108 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
109 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
110 n, _ := strconv.ParseUint(s, 10, 64)
111 fields[pref.FieldNumber(n)] = f
112 continue fieldLoop
113 }
114 }
115 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
116 oneofs[pref.Name(s)] = f
117 continue fieldLoop
118 }
119 switch f.Name {
120 case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions":
121 special[f.Name] = f
122 continue fieldLoop
123 }
124 }
Joe Tsai2c870bb2018-10-17 11:46:52 -0700125 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -0700126 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700127 oneofLoop:
128 for _, v := range vs.Interface().([]interface{}) {
129 tf := reflect.TypeOf(v).Elem()
130 f := tf.Field(0)
131 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
132 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
133 n, _ := strconv.ParseUint(s, 10, 64)
134 oneofFields[pref.FieldNumber(n)] = tf
135 continue oneofLoop
136 }
137 }
138 }
139 }
140
141 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Joe Tsai95b02902018-10-31 18:23:42 -0700142 for i := 0; i < mi.Desc.Fields().Len(); i++ {
143 fd := mi.Desc.Fields().Get(i)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700144 fs := fields[fd.Number()]
145 var fi fieldInfo
146 switch {
147 case fd.IsWeak():
148 fi = fieldInfoForWeak(fd, special["XXX_weak"])
149 case fd.OneofType() != nil:
150 fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()])
151 case fd.IsMap():
152 fi = fieldInfoForMap(fd, fs)
153 case fd.Cardinality() == pref.Repeated:
154 fi = fieldInfoForVector(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700155 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700156 fi = fieldInfoForMessage(fd, fs)
Joe Tsaic6b75612018-09-13 14:24:37 -0700157 default:
158 fi = fieldInfoForScalar(fd, fs)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700159 }
160 mi.fields[fd.Number()] = &fi
161 }
162}
Joe Tsaic6b75612018-09-13 14:24:37 -0700163
Joe Tsai95b02902018-10-31 18:23:42 -0700164func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
165 if f := makeLegacyUnknownFieldsFunc(t); f != nil {
Joe Tsaie2afdc22018-10-25 14:06:56 -0700166 mi.unknownFields = f
167 return
168 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700169 mi.unknownFields = func(*messageDataType) pref.UnknownFields {
170 return emptyUnknownFields{}
171 }
172}
173
Joe Tsai95b02902018-10-31 18:23:42 -0700174func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700175 // TODO
176 mi.extensionFields = func(*messageDataType) pref.KnownFields {
177 return emptyExtensionFields{}
178 }
179}
180
Joe Tsaic6b75612018-09-13 14:24:37 -0700181func (mi *MessageType) MessageOf(p interface{}) pref.Message {
182 mi.init(p)
183 if m, ok := p.(pref.ProtoMessage); ok {
184 // We assume p properly implements protoreflect.Message.
185 // See the comment in MessageType.init regarding pbType.
186 return m.ProtoReflect()
187 }
188 return (*message)(mi.dataTypeOf(p))
189}
190
191func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields {
192 mi.init(p)
193 return (*knownFields)(mi.dataTypeOf(p))
194}
195
196func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields {
197 mi.init(p)
Joe Tsaibe5348c2018-10-23 18:31:18 -0700198 return mi.unknownFields(mi.dataTypeOf(p))
Joe Tsaic6b75612018-09-13 14:24:37 -0700199}
200
201func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
202 return &messageDataType{pointerOfIface(&p), mi}
203}
204
205// messageDataType is a tuple of a pointer to the message data and
206// a pointer to the message type.
207//
208// TODO: Unfortunately, we need to close over a pointer and MessageType,
209// which incurs an an allocation. This pair is similar to a Go interface,
210// which is essentially a tuple of the same thing. We can make this efficient
211// with reflect.NamedOf (see https://golang.org/issues/16522).
212//
213// With that hypothetical API, we could dynamically create a new named type
214// that has the same underlying type as MessageType.goType, and
215// dynamically create methods that close over MessageType.
216// Since the new type would have the same underlying type, we could directly
217// convert between pointers of those types, giving us an efficient way to swap
218// out the method set.
219//
220// Barring the ability to dynamically create named types, the workaround is
221// 1. either to accept the cost of an allocation for this wrapper struct or
222// 2. generate more types and methods, at the expense of binary size increase.
223type messageDataType struct {
224 p pointer
225 mi *MessageType
226}
227
228type message messageDataType
229
230func (m *message) Type() pref.MessageType {
231 return m.mi.pbType
232}
233func (m *message) KnownFields() pref.KnownFields {
234 return (*knownFields)(m)
235}
236func (m *message) UnknownFields() pref.UnknownFields {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700237 return m.mi.unknownFields((*messageDataType)(m))
Joe Tsaic6b75612018-09-13 14:24:37 -0700238}
Joe Tsai91e14662018-09-13 13:24:35 -0700239func (m *message) Unwrap() interface{} { // TODO: unexport?
Joe Tsaic6b75612018-09-13 14:24:37 -0700240 return m.p.asType(m.mi.goType.Elem()).Interface()
241}
242func (m *message) Interface() pref.ProtoMessage {
243 return m
244}
245func (m *message) ProtoReflect() pref.Message {
246 return m
247}
248func (m *message) ProtoMutable() {}
249
250type knownFields messageDataType
251
Joe Tsaic6b75612018-09-13 14:24:37 -0700252func (fs *knownFields) Len() (cnt int) {
253 for _, fi := range fs.mi.fields {
254 if fi.has(fs.p) {
255 cnt++
256 }
257 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700258 return cnt + fs.extensionFields().Len()
Joe Tsaic6b75612018-09-13 14:24:37 -0700259}
260func (fs *knownFields) Has(n pref.FieldNumber) bool {
261 if fi := fs.mi.fields[n]; fi != nil {
262 return fi.has(fs.p)
263 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700264 return fs.extensionFields().Has(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700265}
266func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
267 if fi := fs.mi.fields[n]; fi != nil {
268 return fi.get(fs.p)
269 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700270 return fs.extensionFields().Get(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700271}
272func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
273 if fi := fs.mi.fields[n]; fi != nil {
274 fi.set(fs.p, v)
275 return
276 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700277 fs.extensionFields().Set(n, v)
Joe Tsaic6b75612018-09-13 14:24:37 -0700278}
279func (fs *knownFields) Clear(n pref.FieldNumber) {
280 if fi := fs.mi.fields[n]; fi != nil {
281 fi.clear(fs.p)
282 return
283 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700284 fs.extensionFields().Clear(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700285}
286func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable {
287 if fi := fs.mi.fields[n]; fi != nil {
288 return fi.mutable(fs.p)
289 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700290 return fs.extensionFields().Mutable(n)
Joe Tsaic6b75612018-09-13 14:24:37 -0700291}
292func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
293 for n, fi := range fs.mi.fields {
294 if fi.has(fs.p) {
295 if !f(n, fi.get(fs.p)) {
296 return
297 }
298 }
299 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700300 fs.extensionFields().Range(f)
Joe Tsaic6b75612018-09-13 14:24:37 -0700301}
302func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
Joe Tsaibe5348c2018-10-23 18:31:18 -0700303 return fs.extensionFields().ExtensionTypes()
304}
305func (fs *knownFields) extensionFields() pref.KnownFields {
306 return fs.mi.extensionFields((*messageDataType)(fs))
Joe Tsaic6b75612018-09-13 14:24:37 -0700307}
308
Joe Tsaibe5348c2018-10-23 18:31:18 -0700309type emptyUnknownFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700310
Joe Tsaibe5348c2018-10-23 18:31:18 -0700311func (emptyUnknownFields) Len() int { return 0 }
312func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800313func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
314func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700315func (emptyUnknownFields) IsSupported() bool { return false }
Joe Tsaic6b75612018-09-13 14:24:37 -0700316
Joe Tsaibe5348c2018-10-23 18:31:18 -0700317type emptyExtensionFields struct{}
Joe Tsaic6b75612018-09-13 14:24:37 -0700318
Joe Tsaibe5348c2018-10-23 18:31:18 -0700319func (emptyExtensionFields) Len() int { return 0 }
320func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
321func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800322func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
323func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
324func (emptyExtensionFields) Mutable(pref.FieldNumber) pref.Mutable { panic("extensions not supported") }
325func (emptyExtensionFields) Range(f func(pref.FieldNumber, pref.Value) bool) { return }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700326func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
327
328type emptyExtensionTypes struct{}
329
330func (emptyExtensionTypes) Len() int { return 0 }
331func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800332func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
Joe Tsaibe5348c2018-10-23 18:31:18 -0700333func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
334func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
Joe Tsai34eb7ef2018-11-07 16:39:49 -0800335func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }