blob: fd3732fb783a09f4a53583085511e97e133d0cc8 [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 Tsai90fe9962018-10-18 11:06:29 -070062 // Fast-path: check if a MessageDescriptor is cached for this concrete type.
Joe Tsai21ade492019-05-22 13:42:54 -040063 if mi, ok := legacyMessageDescCache.Load(t); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -070064 return mi.(pref.MessageDescriptor)
65 }
66
Joe Tsaid8881392019-06-06 13:01:53 -070067 // Slow-path: initialize MessageDescriptor from the raw descriptor.
Joe Tsai90fe9962018-10-18 11:06:29 -070068 mv := reflect.New(t.Elem()).Interface()
69 if _, ok := mv.(pref.ProtoMessage); ok {
70 panic(fmt.Sprintf("%v already implements proto.Message", t))
71 }
Joe Tsaid8881392019-06-06 13:01:53 -070072 mdV1, ok := mv.(messageV1)
73 if !ok {
Joe Tsai32e8a522019-07-02 10:51:24 -070074 return aberrantLoadMessageDesc(t)
Joe Tsaid8881392019-06-06 13:01:53 -070075 }
76 b, idxs := mdV1.Descriptor()
Joe Tsai90fe9962018-10-18 11:06:29 -070077
Joe Tsaid8881392019-06-06 13:01:53 -070078 md := legacyLoadFileDesc(b).Messages().Get(idxs[0])
79 for _, i := range idxs[1:] {
80 md = md.Messages().Get(i)
Joe Tsai90fe9962018-10-18 11:06:29 -070081 }
Joe Tsaid8881392019-06-06 13:01:53 -070082 if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok {
83 return md.(protoreflect.MessageDescriptor)
Joe Tsai90fe9962018-10-18 11:06:29 -070084 }
Joe Tsaid8881392019-06-06 13:01:53 -070085 return md
Joe Tsai90fe9962018-10-18 11:06:29 -070086}
Joe Tsai851185d2019-07-01 13:45:52 -070087
Joe Tsai32e8a522019-07-02 10:51:24 -070088var (
89 aberrantMessageDescLock sync.Mutex
90 aberrantMessageDescCache map[reflect.Type]protoreflect.MessageDescriptor
91)
Joe Tsai851185d2019-07-01 13:45:52 -070092
Joe Tsaia8044502019-07-06 17:38:44 -070093// aberrantLoadMessageDesc returns an EnumDescriptor derived from the Go type,
Joe Tsai851185d2019-07-01 13:45:52 -070094// which must not implement protoreflect.ProtoMessage or messageV1.
95//
96// This is a best-effort derivation of the message descriptor using the protobuf
97// tags on the struct fields.
Joe Tsai32e8a522019-07-02 10:51:24 -070098func aberrantLoadMessageDesc(t reflect.Type) pref.MessageDescriptor {
99 aberrantMessageDescLock.Lock()
100 defer aberrantMessageDescLock.Unlock()
101 if aberrantMessageDescCache == nil {
102 aberrantMessageDescCache = make(map[reflect.Type]protoreflect.MessageDescriptor)
103 }
104 return aberrantLoadMessageDescReentrant(t)
105}
106func aberrantLoadMessageDescReentrant(t reflect.Type) pref.MessageDescriptor {
Joe Tsai851185d2019-07-01 13:45:52 -0700107 // Fast-path: check if an MessageDescriptor is cached for this concrete type.
Joe Tsai32e8a522019-07-02 10:51:24 -0700108 if md, ok := aberrantMessageDescCache[t]; ok {
109 return md
Joe Tsai851185d2019-07-01 13:45:52 -0700110 }
111
Joe Tsai851185d2019-07-01 13:45:52 -0700112 // Slow-path: construct a descriptor from the Go struct type (best-effort).
Joe Tsai32e8a522019-07-02 10:51:24 -0700113 // Cache the MessageDescriptor early on so that we can resolve internal
114 // cyclic references.
115 md := &filedesc.Message{L2: new(filedesc.MessageL2)}
Joe Tsai851185d2019-07-01 13:45:52 -0700116 md.L0.FullName = aberrantDeriveFullName(t.Elem())
117 md.L0.ParentFile = filedesc.SurrogateProto2
Joe Tsai32e8a522019-07-02 10:51:24 -0700118 aberrantMessageDescCache[t] = md
Joe Tsai851185d2019-07-01 13:45:52 -0700119
Joe Tsai851185d2019-07-01 13:45:52 -0700120 // Try to determine if the message is using proto3 by checking scalars.
121 for i := 0; i < t.Elem().NumField(); i++ {
122 f := t.Elem().Field(i)
123 if tag := f.Tag.Get("protobuf"); tag != "" {
124 switch f.Type.Kind() {
125 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
126 md.L0.ParentFile = filedesc.SurrogateProto3
127 }
128 for _, s := range strings.Split(tag, ",") {
129 if s == "proto3" {
130 md.L0.ParentFile = filedesc.SurrogateProto3
131 }
132 }
133 }
134 }
135
136 // Obtain a list of oneof wrapper types.
137 var oneofWrappers []reflect.Type
138 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
139 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
140 for _, v := range vs.Interface().([]interface{}) {
141 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
142 }
143 }
144 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
145 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
146 for _, v := range vs.Interface().([]interface{}) {
147 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
148 }
149 }
150
151 // Obtain a list of the extension ranges.
152 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
153 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
154 for i := 0; i < vs.Len(); i++ {
155 v := vs.Index(i)
156 md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{
157 pref.FieldNumber(v.FieldByName("Start").Int()),
158 pref.FieldNumber(v.FieldByName("End").Int() + 1),
159 })
160 md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil)
161 }
162 }
163
164 // Derive the message fields by inspecting the struct fields.
165 for i := 0; i < t.Elem().NumField(); i++ {
166 f := t.Elem().Field(i)
167 if tag := f.Tag.Get("protobuf"); tag != "" {
168 tagKey := f.Tag.Get("protobuf_key")
169 tagVal := f.Tag.Get("protobuf_val")
170 aberrantAppendField(md, f.Type, tag, tagKey, tagVal)
171 }
172 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
173 n := len(md.L2.Oneofs.List)
174 md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{})
175 od := &md.L2.Oneofs.List[n]
176 od.L0.FullName = md.FullName().Append(pref.Name(tag))
177 od.L0.ParentFile = md.L0.ParentFile
178 od.L0.Parent = md
179 od.L0.Index = n
180
181 for _, t := range oneofWrappers {
182 if t.Implements(f.Type) {
183 f := t.Elem().Field(0)
184 if tag := f.Tag.Get("protobuf"); tag != "" {
185 aberrantAppendField(md, f.Type, tag, "", "")
186 fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1]
187 fd.L1.ContainingOneof = od
188 od.L1.Fields.List = append(od.L1.Fields.List, fd)
189 }
190 }
191 }
192 }
193 }
194
195 // TODO: Use custom Marshal/Unmarshal methods for the fast-path?
196
197 return md
198}
199
200func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) {
201 t := goType
202 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
203 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
204 if isOptional || isRepeated {
205 t = t.Elem()
206 }
207 fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field)
208
209 // Append field descriptor to the message.
210 n := len(md.L2.Fields.List)
211 md.L2.Fields.List = append(md.L2.Fields.List, *fd)
212 fd = &md.L2.Fields.List[n]
213 fd.L0.FullName = md.FullName().Append(fd.Name())
214 fd.L0.ParentFile = md.L0.ParentFile
215 fd.L0.Parent = md
216 fd.L0.Index = n
217
218 if fd.L1.IsWeak || fd.L1.HasPacked {
219 fd.L1.Options = func() pref.ProtoMessage {
220 opts := descopts.Field.ProtoReflect().New()
221 if fd.L1.IsWeak {
222 opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOf(true))
223 }
224 if fd.L1.HasPacked {
225 opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOf(fd.L1.IsPacked))
226 }
227 return opts.Interface()
228 }
229 }
230
231 // Populate Enum and Message.
232 if fd.Enum() == nil && fd.Kind() == pref.EnumKind {
233 switch v := reflect.Zero(t).Interface().(type) {
234 case pref.Enum:
235 fd.L1.Enum = v.Descriptor()
236 default:
237 fd.L1.Enum = LegacyLoadEnumDesc(t)
238 }
239 }
240 if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) {
241 switch v := reflect.Zero(t).Interface().(type) {
242 case pref.ProtoMessage:
243 fd.L1.Message = v.ProtoReflect().Descriptor()
Joe Tsai32e8a522019-07-02 10:51:24 -0700244 case messageV1:
245 fd.L1.Message = LegacyLoadMessageDesc(t)
Joe Tsai851185d2019-07-01 13:45:52 -0700246 default:
247 if t.Kind() == reflect.Map {
248 n := len(md.L1.Messages.List)
249 md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)})
250 md2 := &md.L1.Messages.List[n]
251 md2.L0.FullName = md.FullName().Append(aberrantMapEntryName(fd.Name()))
252 md2.L0.ParentFile = md.L0.ParentFile
253 md2.L0.Parent = md
254 md2.L0.Index = n
255
256 md2.L2.IsMapEntry = true
257 md2.L2.Options = func() pref.ProtoMessage {
258 opts := descopts.Message.ProtoReflect().New()
259 opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOf(true))
260 return opts.Interface()
261 }
262
263 aberrantAppendField(md2, t.Key(), tagKey, "", "")
264 aberrantAppendField(md2, t.Elem(), tagVal, "", "")
265
266 fd.L1.Message = md2
267 break
268 }
Joe Tsai32e8a522019-07-02 10:51:24 -0700269 fd.L1.Message = aberrantLoadMessageDescReentrant(t)
Joe Tsai851185d2019-07-01 13:45:52 -0700270 }
271 }
272}
273
274type placeholderEnumValues struct {
275 protoreflect.EnumValueDescriptors
276}
277
278func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor {
279 return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n)))
280}
281
282// aberrantMapEntryName derives the name for a map entry message.
283// See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057
284func aberrantMapEntryName(s pref.Name) pref.Name {
285 var b []byte
286 upperNext := true
287 for _, c := range s {
288 switch {
289 case c == '_':
290 upperNext = true
291 case upperNext:
292 b = append(b, byte(unicode.ToUpper(c)))
293 upperNext = false
294 default:
295 b = append(b, byte(c))
296 }
297 }
298 b = append(b, "Entry"...)
299 return pref.Name(b)
300}