blob: 2d6e53a0c455fb910032088095fa710757a1080b [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
136 // If possible, use the custom protobuf name specified on the type.
137 fn, ok := t.MethodByName("XXX_MessageName")
138 if !ok {
139 fn, ok = t.Elem().MethodByName("XXX_MessageName")
140 }
141 if ok {
142 v := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
143 if s := pref.FullName(v.String()); s.IsValid() {
144 md.L0.FullName = s
145 }
146 }
147
148 // Try to determine if the message is using proto3 by checking scalars.
149 for i := 0; i < t.Elem().NumField(); i++ {
150 f := t.Elem().Field(i)
151 if tag := f.Tag.Get("protobuf"); tag != "" {
152 switch f.Type.Kind() {
153 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
154 md.L0.ParentFile = filedesc.SurrogateProto3
155 }
156 for _, s := range strings.Split(tag, ",") {
157 if s == "proto3" {
158 md.L0.ParentFile = filedesc.SurrogateProto3
159 }
160 }
161 }
162 }
163
164 // Obtain a list of oneof wrapper types.
165 var oneofWrappers []reflect.Type
166 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
167 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
168 for _, v := range vs.Interface().([]interface{}) {
169 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
170 }
171 }
172 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
173 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
174 for _, v := range vs.Interface().([]interface{}) {
175 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
176 }
177 }
178
179 // Obtain a list of the extension ranges.
180 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
181 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
182 for i := 0; i < vs.Len(); i++ {
183 v := vs.Index(i)
184 md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{
185 pref.FieldNumber(v.FieldByName("Start").Int()),
186 pref.FieldNumber(v.FieldByName("End").Int() + 1),
187 })
188 md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil)
189 }
190 }
191
192 // Derive the message fields by inspecting the struct fields.
193 for i := 0; i < t.Elem().NumField(); i++ {
194 f := t.Elem().Field(i)
195 if tag := f.Tag.Get("protobuf"); tag != "" {
196 tagKey := f.Tag.Get("protobuf_key")
197 tagVal := f.Tag.Get("protobuf_val")
198 aberrantAppendField(md, f.Type, tag, tagKey, tagVal)
199 }
200 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
201 n := len(md.L2.Oneofs.List)
202 md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{})
203 od := &md.L2.Oneofs.List[n]
204 od.L0.FullName = md.FullName().Append(pref.Name(tag))
205 od.L0.ParentFile = md.L0.ParentFile
206 od.L0.Parent = md
207 od.L0.Index = n
208
209 for _, t := range oneofWrappers {
210 if t.Implements(f.Type) {
211 f := t.Elem().Field(0)
212 if tag := f.Tag.Get("protobuf"); tag != "" {
213 aberrantAppendField(md, f.Type, tag, "", "")
214 fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1]
215 fd.L1.ContainingOneof = od
216 od.L1.Fields.List = append(od.L1.Fields.List, fd)
217 }
218 }
219 }
220 }
221 }
222
223 // TODO: Use custom Marshal/Unmarshal methods for the fast-path?
224
225 return md
226}
227
228func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) {
229 t := goType
230 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
231 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
232 if isOptional || isRepeated {
233 t = t.Elem()
234 }
235 fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field)
236
237 // Append field descriptor to the message.
238 n := len(md.L2.Fields.List)
239 md.L2.Fields.List = append(md.L2.Fields.List, *fd)
240 fd = &md.L2.Fields.List[n]
241 fd.L0.FullName = md.FullName().Append(fd.Name())
242 fd.L0.ParentFile = md.L0.ParentFile
243 fd.L0.Parent = md
244 fd.L0.Index = n
245
246 if fd.L1.IsWeak || fd.L1.HasPacked {
247 fd.L1.Options = func() pref.ProtoMessage {
248 opts := descopts.Field.ProtoReflect().New()
249 if fd.L1.IsWeak {
250 opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOf(true))
251 }
252 if fd.L1.HasPacked {
253 opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOf(fd.L1.IsPacked))
254 }
255 return opts.Interface()
256 }
257 }
258
259 // Populate Enum and Message.
260 if fd.Enum() == nil && fd.Kind() == pref.EnumKind {
261 switch v := reflect.Zero(t).Interface().(type) {
262 case pref.Enum:
263 fd.L1.Enum = v.Descriptor()
264 default:
265 fd.L1.Enum = LegacyLoadEnumDesc(t)
266 }
267 }
268 if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) {
269 switch v := reflect.Zero(t).Interface().(type) {
270 case pref.ProtoMessage:
271 fd.L1.Message = v.ProtoReflect().Descriptor()
272 default:
273 if t.Kind() == reflect.Map {
274 n := len(md.L1.Messages.List)
275 md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)})
276 md2 := &md.L1.Messages.List[n]
277 md2.L0.FullName = md.FullName().Append(aberrantMapEntryName(fd.Name()))
278 md2.L0.ParentFile = md.L0.ParentFile
279 md2.L0.Parent = md
280 md2.L0.Index = n
281
282 md2.L2.IsMapEntry = true
283 md2.L2.Options = func() pref.ProtoMessage {
284 opts := descopts.Message.ProtoReflect().New()
285 opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOf(true))
286 return opts.Interface()
287 }
288
289 aberrantAppendField(md2, t.Key(), tagKey, "", "")
290 aberrantAppendField(md2, t.Elem(), tagVal, "", "")
291
292 fd.L1.Message = md2
293 break
294 }
295 fd.L1.Message = aberrantLoadMessageDesc(t, false)
296 }
297 }
298}
299
300type placeholderEnumValues struct {
301 protoreflect.EnumValueDescriptors
302}
303
304func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor {
305 return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n)))
306}
307
308// aberrantMapEntryName derives the name for a map entry message.
309// See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057
310func aberrantMapEntryName(s pref.Name) pref.Name {
311 var b []byte
312 upperNext := true
313 for _, c := range s {
314 switch {
315 case c == '_':
316 upperNext = true
317 case upperNext:
318 b = append(b, byte(unicode.ToUpper(c)))
319 upperNext = false
320 default:
321 b = append(b, byte(c))
322 }
323 }
324 b = append(b, "Entry"...)
325 return pref.Name(b)
326}