blob: f745a81ce56e30cd08d453ce3773f73052f03cf9 [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
93// aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type,
94// 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.
98//
99// The finalized flag determines whether the returned message descriptor must
100// be fully initialized.
Joe Tsai32e8a522019-07-02 10:51:24 -0700101func aberrantLoadMessageDesc(t reflect.Type) pref.MessageDescriptor {
102 aberrantMessageDescLock.Lock()
103 defer aberrantMessageDescLock.Unlock()
104 if aberrantMessageDescCache == nil {
105 aberrantMessageDescCache = make(map[reflect.Type]protoreflect.MessageDescriptor)
106 }
107 return aberrantLoadMessageDescReentrant(t)
108}
109func aberrantLoadMessageDescReentrant(t reflect.Type) pref.MessageDescriptor {
Joe Tsai851185d2019-07-01 13:45:52 -0700110 // Fast-path: check if an MessageDescriptor is cached for this concrete type.
Joe Tsai32e8a522019-07-02 10:51:24 -0700111 if md, ok := aberrantMessageDescCache[t]; ok {
112 return md
Joe Tsai851185d2019-07-01 13:45:52 -0700113 }
114
Joe Tsai851185d2019-07-01 13:45:52 -0700115 // Slow-path: construct a descriptor from the Go struct type (best-effort).
Joe Tsai32e8a522019-07-02 10:51:24 -0700116 // Cache the MessageDescriptor early on so that we can resolve internal
117 // cyclic references.
118 md := &filedesc.Message{L2: new(filedesc.MessageL2)}
Joe Tsai851185d2019-07-01 13:45:52 -0700119 md.L0.FullName = aberrantDeriveFullName(t.Elem())
120 md.L0.ParentFile = filedesc.SurrogateProto2
Joe Tsai32e8a522019-07-02 10:51:24 -0700121 aberrantMessageDescCache[t] = md
Joe Tsai851185d2019-07-01 13:45:52 -0700122
Joe Tsai851185d2019-07-01 13:45:52 -0700123 // Try to determine if the message is using proto3 by checking scalars.
124 for i := 0; i < t.Elem().NumField(); i++ {
125 f := t.Elem().Field(i)
126 if tag := f.Tag.Get("protobuf"); tag != "" {
127 switch f.Type.Kind() {
128 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
129 md.L0.ParentFile = filedesc.SurrogateProto3
130 }
131 for _, s := range strings.Split(tag, ",") {
132 if s == "proto3" {
133 md.L0.ParentFile = filedesc.SurrogateProto3
134 }
135 }
136 }
137 }
138
139 // Obtain a list of oneof wrapper types.
140 var oneofWrappers []reflect.Type
141 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
142 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
143 for _, v := range vs.Interface().([]interface{}) {
144 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
145 }
146 }
147 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
148 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
149 for _, v := range vs.Interface().([]interface{}) {
150 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
151 }
152 }
153
154 // Obtain a list of the extension ranges.
155 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
156 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
157 for i := 0; i < vs.Len(); i++ {
158 v := vs.Index(i)
159 md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{
160 pref.FieldNumber(v.FieldByName("Start").Int()),
161 pref.FieldNumber(v.FieldByName("End").Int() + 1),
162 })
163 md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil)
164 }
165 }
166
167 // Derive the message fields by inspecting the struct fields.
168 for i := 0; i < t.Elem().NumField(); i++ {
169 f := t.Elem().Field(i)
170 if tag := f.Tag.Get("protobuf"); tag != "" {
171 tagKey := f.Tag.Get("protobuf_key")
172 tagVal := f.Tag.Get("protobuf_val")
173 aberrantAppendField(md, f.Type, tag, tagKey, tagVal)
174 }
175 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
176 n := len(md.L2.Oneofs.List)
177 md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{})
178 od := &md.L2.Oneofs.List[n]
179 od.L0.FullName = md.FullName().Append(pref.Name(tag))
180 od.L0.ParentFile = md.L0.ParentFile
181 od.L0.Parent = md
182 od.L0.Index = n
183
184 for _, t := range oneofWrappers {
185 if t.Implements(f.Type) {
186 f := t.Elem().Field(0)
187 if tag := f.Tag.Get("protobuf"); tag != "" {
188 aberrantAppendField(md, f.Type, tag, "", "")
189 fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1]
190 fd.L1.ContainingOneof = od
191 od.L1.Fields.List = append(od.L1.Fields.List, fd)
192 }
193 }
194 }
195 }
196 }
197
198 // TODO: Use custom Marshal/Unmarshal methods for the fast-path?
199
200 return md
201}
202
203func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) {
204 t := goType
205 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
206 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
207 if isOptional || isRepeated {
208 t = t.Elem()
209 }
210 fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field)
211
212 // Append field descriptor to the message.
213 n := len(md.L2.Fields.List)
214 md.L2.Fields.List = append(md.L2.Fields.List, *fd)
215 fd = &md.L2.Fields.List[n]
216 fd.L0.FullName = md.FullName().Append(fd.Name())
217 fd.L0.ParentFile = md.L0.ParentFile
218 fd.L0.Parent = md
219 fd.L0.Index = n
220
221 if fd.L1.IsWeak || fd.L1.HasPacked {
222 fd.L1.Options = func() pref.ProtoMessage {
223 opts := descopts.Field.ProtoReflect().New()
224 if fd.L1.IsWeak {
225 opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOf(true))
226 }
227 if fd.L1.HasPacked {
228 opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOf(fd.L1.IsPacked))
229 }
230 return opts.Interface()
231 }
232 }
233
234 // Populate Enum and Message.
235 if fd.Enum() == nil && fd.Kind() == pref.EnumKind {
236 switch v := reflect.Zero(t).Interface().(type) {
237 case pref.Enum:
238 fd.L1.Enum = v.Descriptor()
239 default:
240 fd.L1.Enum = LegacyLoadEnumDesc(t)
241 }
242 }
243 if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) {
244 switch v := reflect.Zero(t).Interface().(type) {
245 case pref.ProtoMessage:
246 fd.L1.Message = v.ProtoReflect().Descriptor()
Joe Tsai32e8a522019-07-02 10:51:24 -0700247 case messageV1:
248 fd.L1.Message = LegacyLoadMessageDesc(t)
Joe Tsai851185d2019-07-01 13:45:52 -0700249 default:
250 if t.Kind() == reflect.Map {
251 n := len(md.L1.Messages.List)
252 md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)})
253 md2 := &md.L1.Messages.List[n]
254 md2.L0.FullName = md.FullName().Append(aberrantMapEntryName(fd.Name()))
255 md2.L0.ParentFile = md.L0.ParentFile
256 md2.L0.Parent = md
257 md2.L0.Index = n
258
259 md2.L2.IsMapEntry = true
260 md2.L2.Options = func() pref.ProtoMessage {
261 opts := descopts.Message.ProtoReflect().New()
262 opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOf(true))
263 return opts.Interface()
264 }
265
266 aberrantAppendField(md2, t.Key(), tagKey, "", "")
267 aberrantAppendField(md2, t.Elem(), tagVal, "", "")
268
269 fd.L1.Message = md2
270 break
271 }
Joe Tsai32e8a522019-07-02 10:51:24 -0700272 fd.L1.Message = aberrantLoadMessageDescReentrant(t)
Joe Tsai851185d2019-07-01 13:45:52 -0700273 }
274 }
275}
276
277type placeholderEnumValues struct {
278 protoreflect.EnumValueDescriptors
279}
280
281func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor {
282 return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n)))
283}
284
285// aberrantMapEntryName derives the name for a map entry message.
286// See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057
287func aberrantMapEntryName(s pref.Name) pref.Name {
288 var b []byte
289 upperNext := true
290 for _, c := range s {
291 switch {
292 case c == '_':
293 upperNext = true
294 case upperNext:
295 b = append(b, byte(unicode.ToUpper(c)))
296 upperNext = false
297 default:
298 b = append(b, byte(c))
299 }
300 }
301 b = append(b, "Entry"...)
302 return pref.Name(b)
303}