blob: 99c8e0c6ebe3e9c38e3f53e82ec4029b9ca781c1 [file] [log] [blame]
Joe Tsai90fe9962018-10-18 11:06:29 -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
Joe Tsai21ade492019-05-22 13:42:54 -04005package impl
Joe Tsai90fe9962018-10-18 11:06:29 -07006
7import (
8 "fmt"
Joe Tsai90fe9962018-10-18 11:06:29 -07009 "reflect"
Joe Tsai851185d2019-07-01 13:45:52 -070010 "strings"
Joe Tsai90fe9962018-10-18 11:06:29 -070011 "sync"
Joe Tsai851185d2019-07-01 13:45:52 -070012 "unicode"
Joe Tsai90fe9962018-10-18 11:06:29 -070013
Joe Tsai851185d2019-07-01 13:45:52 -070014 "google.golang.org/protobuf/internal/descopts"
15 ptag "google.golang.org/protobuf/internal/encoding/tag"
16 "google.golang.org/protobuf/internal/filedesc"
Joe Tsaid8881392019-06-06 13:01:53 -070017 "google.golang.org/protobuf/reflect/protoreflect"
Damien Neile89e6242019-05-13 23:55:40 -070018 pref "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsaib2f66be2019-05-22 00:42:45 -040019 "google.golang.org/protobuf/reflect/prototype"
Joe Tsai90fe9962018-10-18 11:06:29 -070020)
21
Joe Tsai21ade492019-05-22 13:42:54 -040022// legacyWrapMessage wraps v as a protoreflect.ProtoMessage,
Joe Tsaif0c01e42018-11-06 13:05:20 -080023// where v must be a *struct kind and not implement the v2 API already.
Joe Tsai21ade492019-05-22 13:42:54 -040024func legacyWrapMessage(v reflect.Value) pref.ProtoMessage {
25 mt := legacyLoadMessageInfo(v.Type())
Joe Tsai08e00302018-11-26 22:32:06 -080026 return mt.MessageOf(v.Interface()).Interface()
Joe Tsaif0c01e42018-11-06 13:05:20 -080027}
28
Joe Tsai21ade492019-05-22 13:42:54 -040029var legacyMessageTypeCache sync.Map // map[reflect.Type]*MessageInfo
Joe Tsaice6edd32018-10-19 16:27:46 -070030
Joe Tsai21ade492019-05-22 13:42:54 -040031// legacyLoadMessageInfo dynamically loads a *MessageInfo for t,
Joe Tsaif0c01e42018-11-06 13:05:20 -080032// where t must be a *struct kind and not implement the v2 API already.
Joe Tsai21ade492019-05-22 13:42:54 -040033func legacyLoadMessageInfo(t reflect.Type) *MessageInfo {
Joe Tsai4fe96632019-05-22 05:12:36 -040034 // Fast-path: check if a MessageInfo is cached for this concrete type.
Joe Tsai21ade492019-05-22 13:42:54 -040035 if mt, ok := legacyMessageTypeCache.Load(t); ok {
36 return mt.(*MessageInfo)
Joe Tsaice6edd32018-10-19 16:27:46 -070037 }
38
Joe Tsai4fe96632019-05-22 05:12:36 -040039 // Slow-path: derive message descriptor and initialize MessageInfo.
Joe Tsai21ade492019-05-22 13:42:54 -040040 md := LegacyLoadMessageDesc(t)
41 mt := new(MessageInfo)
Damien Neil8012b442019-01-18 09:32:24 -080042 mt.GoType = t
Joe Tsaib2f66be2019-05-22 00:42:45 -040043 mt.PBType = &prototype.Message{
44 MessageDescriptor: md,
45 NewMessage: func() pref.Message {
46 return mt.MessageOf(reflect.New(t.Elem()).Interface())
47 },
48 }
Joe Tsai21ade492019-05-22 13:42:54 -040049 if mt, ok := legacyMessageTypeCache.LoadOrStore(t, mt); ok {
50 return mt.(*MessageInfo)
Joe Tsaib9365042019-03-19 14:14:29 -070051 }
Joe Tsaif0c01e42018-11-06 13:05:20 -080052 return mt
Joe Tsaice6edd32018-10-19 16:27:46 -070053}
54
Joe Tsaid8881392019-06-06 13:01:53 -070055var legacyMessageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor
Joe Tsai90fe9962018-10-18 11:06:29 -070056
Joe Tsai21ade492019-05-22 13:42:54 -040057// LegacyLoadMessageDesc returns an MessageDescriptor derived from the Go type,
Joe Tsaice6edd32018-10-19 16:27:46 -070058// which must be a *struct kind and not implement the v2 API already.
Joe Tsai35ec98f2019-03-25 14:41:32 -070059//
60// This is exported for testing purposes.
Joe Tsai21ade492019-05-22 13:42:54 -040061func LegacyLoadMessageDesc(t reflect.Type) pref.MessageDescriptor {
Joe Tsai851185d2019-07-01 13:45:52 -070062 return legacyLoadMessageDesc(t, true)
63}
64func legacyLoadMessageDesc(t reflect.Type, finalized bool) pref.MessageDescriptor {
Joe Tsai90fe9962018-10-18 11:06:29 -070065 // Fast-path: check if a MessageDescriptor is cached for this concrete type.
Joe Tsai21ade492019-05-22 13:42:54 -040066 if mi, ok := legacyMessageDescCache.Load(t); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -070067 return mi.(pref.MessageDescriptor)
68 }
69
Joe Tsaid8881392019-06-06 13:01:53 -070070 // Slow-path: initialize MessageDescriptor from the raw descriptor.
Joe Tsai90fe9962018-10-18 11:06:29 -070071 mv := reflect.New(t.Elem()).Interface()
72 if _, ok := mv.(pref.ProtoMessage); ok {
73 panic(fmt.Sprintf("%v already implements proto.Message", t))
74 }
Joe Tsaid8881392019-06-06 13:01:53 -070075 mdV1, ok := mv.(messageV1)
76 if !ok {
Joe Tsai851185d2019-07-01 13:45:52 -070077 return aberrantLoadMessageDesc(t, finalized)
Joe Tsaid8881392019-06-06 13:01:53 -070078 }
79 b, idxs := mdV1.Descriptor()
Joe Tsai90fe9962018-10-18 11:06:29 -070080
Joe Tsaid8881392019-06-06 13:01:53 -070081 md := legacyLoadFileDesc(b).Messages().Get(idxs[0])
82 for _, i := range idxs[1:] {
83 md = md.Messages().Get(i)
Joe Tsai90fe9962018-10-18 11:06:29 -070084 }
Joe Tsaid8881392019-06-06 13:01:53 -070085 if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok {
86 return md.(protoreflect.MessageDescriptor)
Joe Tsai90fe9962018-10-18 11:06:29 -070087 }
Joe Tsaid8881392019-06-06 13:01:53 -070088 return md
Joe Tsai90fe9962018-10-18 11:06:29 -070089}
Joe Tsai851185d2019-07-01 13:45:52 -070090
91var aberrantMessageDescCache sync.Map // map[reflect.Type]aberrantMessageDesc
92
93// aberrantMessageDesc is a tuple containing a MessageDescriptor and a channel
94// to signal whether the descriptor is initialized. For external lookups,
95// we must ensure that the descriptor is fully initialized. For internal lookups
96// to resolve cycles, we only need to obtain the descriptor reference.
97type aberrantMessageDesc struct {
98 desc protoreflect.MessageDescriptor
99 done chan struct{} // closed when desc is fully initialized
100}
101
102// aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type,
103// which must not implement protoreflect.ProtoMessage or messageV1.
104//
105// This is a best-effort derivation of the message descriptor using the protobuf
106// tags on the struct fields.
107//
108// The finalized flag determines whether the returned message descriptor must
109// be fully initialized.
110func aberrantLoadMessageDesc(t reflect.Type, finalized bool) pref.MessageDescriptor {
111 // Fast-path: check if an MessageDescriptor is cached for this concrete type.
112 if mdi, ok := aberrantMessageDescCache.Load(t); ok {
113 if finalized {
114 <-mdi.(aberrantMessageDesc).done
115 }
116 return mdi.(aberrantMessageDesc).desc
117 }
118
119 // Medium-path: create an initial descriptor and cache it immediately,
120 // so that cyclic references can be resolved. Each descriptor is paired
121 // with a channel to signal when the descriptor is fully initialized.
122 md := &filedesc.Message{L2: new(filedesc.MessageL2)}
123 mdi := aberrantMessageDesc{desc: md, done: make(chan struct{})}
124 if mdi, ok := aberrantMessageDescCache.LoadOrStore(t, mdi); ok {
125 if finalized {
126 <-mdi.(aberrantMessageDesc).done
127 }
128 return mdi.(aberrantMessageDesc).desc
129 }
130 defer func() { close(mdi.done) }()
131
132 // Slow-path: construct a descriptor from the Go struct type (best-effort).
133 md.L0.FullName = aberrantDeriveFullName(t.Elem())
134 md.L0.ParentFile = filedesc.SurrogateProto2
135
Joe Tsai851185d2019-07-01 13:45:52 -0700136 // Try to determine if the message is using proto3 by checking scalars.
137 for i := 0; i < t.Elem().NumField(); i++ {
138 f := t.Elem().Field(i)
139 if tag := f.Tag.Get("protobuf"); tag != "" {
140 switch f.Type.Kind() {
141 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
142 md.L0.ParentFile = filedesc.SurrogateProto3
143 }
144 for _, s := range strings.Split(tag, ",") {
145 if s == "proto3" {
146 md.L0.ParentFile = filedesc.SurrogateProto3
147 }
148 }
149 }
150 }
151
152 // Obtain a list of oneof wrapper types.
153 var oneofWrappers []reflect.Type
154 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
155 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
156 for _, v := range vs.Interface().([]interface{}) {
157 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
158 }
159 }
160 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
161 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
162 for _, v := range vs.Interface().([]interface{}) {
163 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
164 }
165 }
166
167 // Obtain a list of the extension ranges.
168 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
169 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
170 for i := 0; i < vs.Len(); i++ {
171 v := vs.Index(i)
172 md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{
173 pref.FieldNumber(v.FieldByName("Start").Int()),
174 pref.FieldNumber(v.FieldByName("End").Int() + 1),
175 })
176 md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil)
177 }
178 }
179
180 // Derive the message fields by inspecting the struct fields.
181 for i := 0; i < t.Elem().NumField(); i++ {
182 f := t.Elem().Field(i)
183 if tag := f.Tag.Get("protobuf"); tag != "" {
184 tagKey := f.Tag.Get("protobuf_key")
185 tagVal := f.Tag.Get("protobuf_val")
186 aberrantAppendField(md, f.Type, tag, tagKey, tagVal)
187 }
188 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
189 n := len(md.L2.Oneofs.List)
190 md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{})
191 od := &md.L2.Oneofs.List[n]
192 od.L0.FullName = md.FullName().Append(pref.Name(tag))
193 od.L0.ParentFile = md.L0.ParentFile
194 od.L0.Parent = md
195 od.L0.Index = n
196
197 for _, t := range oneofWrappers {
198 if t.Implements(f.Type) {
199 f := t.Elem().Field(0)
200 if tag := f.Tag.Get("protobuf"); tag != "" {
201 aberrantAppendField(md, f.Type, tag, "", "")
202 fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1]
203 fd.L1.ContainingOneof = od
204 od.L1.Fields.List = append(od.L1.Fields.List, fd)
205 }
206 }
207 }
208 }
209 }
210
211 // TODO: Use custom Marshal/Unmarshal methods for the fast-path?
212
213 return md
214}
215
216func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) {
217 t := goType
218 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
219 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
220 if isOptional || isRepeated {
221 t = t.Elem()
222 }
223 fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field)
224
225 // Append field descriptor to the message.
226 n := len(md.L2.Fields.List)
227 md.L2.Fields.List = append(md.L2.Fields.List, *fd)
228 fd = &md.L2.Fields.List[n]
229 fd.L0.FullName = md.FullName().Append(fd.Name())
230 fd.L0.ParentFile = md.L0.ParentFile
231 fd.L0.Parent = md
232 fd.L0.Index = n
233
234 if fd.L1.IsWeak || fd.L1.HasPacked {
235 fd.L1.Options = func() pref.ProtoMessage {
236 opts := descopts.Field.ProtoReflect().New()
237 if fd.L1.IsWeak {
238 opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOf(true))
239 }
240 if fd.L1.HasPacked {
241 opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOf(fd.L1.IsPacked))
242 }
243 return opts.Interface()
244 }
245 }
246
247 // Populate Enum and Message.
248 if fd.Enum() == nil && fd.Kind() == pref.EnumKind {
249 switch v := reflect.Zero(t).Interface().(type) {
250 case pref.Enum:
251 fd.L1.Enum = v.Descriptor()
252 default:
253 fd.L1.Enum = LegacyLoadEnumDesc(t)
254 }
255 }
256 if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) {
257 switch v := reflect.Zero(t).Interface().(type) {
258 case pref.ProtoMessage:
259 fd.L1.Message = v.ProtoReflect().Descriptor()
260 default:
261 if t.Kind() == reflect.Map {
262 n := len(md.L1.Messages.List)
263 md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)})
264 md2 := &md.L1.Messages.List[n]
265 md2.L0.FullName = md.FullName().Append(aberrantMapEntryName(fd.Name()))
266 md2.L0.ParentFile = md.L0.ParentFile
267 md2.L0.Parent = md
268 md2.L0.Index = n
269
270 md2.L2.IsMapEntry = true
271 md2.L2.Options = func() pref.ProtoMessage {
272 opts := descopts.Message.ProtoReflect().New()
273 opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOf(true))
274 return opts.Interface()
275 }
276
277 aberrantAppendField(md2, t.Key(), tagKey, "", "")
278 aberrantAppendField(md2, t.Elem(), tagVal, "", "")
279
280 fd.L1.Message = md2
281 break
282 }
283 fd.L1.Message = aberrantLoadMessageDesc(t, false)
284 }
285 }
286}
287
288type placeholderEnumValues struct {
289 protoreflect.EnumValueDescriptors
290}
291
292func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor {
293 return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n)))
294}
295
296// aberrantMapEntryName derives the name for a map entry message.
297// See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057
298func aberrantMapEntryName(s pref.Name) pref.Name {
299 var b []byte
300 upperNext := true
301 for _, c := range s {
302 switch {
303 case c == '_':
304 upperNext = true
305 case upperNext:
306 b = append(b, byte(unicode.ToUpper(c)))
307 upperNext = false
308 default:
309 b = append(b, byte(c))
310 }
311 }
312 b = append(b, "Entry"...)
313 return pref.Name(b)
314}