blob: b17d705bef1c95e08db981b0fd7abcd8d5da88a2 [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 Tsai08e00302018-11-26 22:32:06 -08005package legacy
Joe Tsai90fe9962018-10-18 11:06:29 -07006
7import (
8 "fmt"
Joe Tsai90fe9962018-10-18 11:06:29 -07009 "reflect"
Joe Tsai90fe9962018-10-18 11:06:29 -070010 "strings"
11 "sync"
12 "unicode"
13
Damien Neile89e6242019-05-13 23:55:40 -070014 ptag "google.golang.org/protobuf/internal/encoding/tag"
15 pimpl "google.golang.org/protobuf/internal/impl"
16 ptype "google.golang.org/protobuf/internal/prototype"
17 pref "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsaib2f66be2019-05-22 00:42:45 -040018 "google.golang.org/protobuf/reflect/prototype"
Joe Tsai90fe9962018-10-18 11:06:29 -070019)
20
Joe Tsai6dbffb72018-12-04 14:06:19 -080021// wrapMessage wraps v as a protoreflect.ProtoMessage,
Joe Tsaif0c01e42018-11-06 13:05:20 -080022// where v must be a *struct kind and not implement the v2 API already.
Joe Tsai6dbffb72018-12-04 14:06:19 -080023func wrapMessage(v reflect.Value) pref.ProtoMessage {
Joe Tsai4fe96632019-05-22 05:12:36 -040024 mt := loadMessageInfo(v.Type())
Joe Tsai08e00302018-11-26 22:32:06 -080025 return mt.MessageOf(v.Interface()).Interface()
Joe Tsaif0c01e42018-11-06 13:05:20 -080026}
27
Joe Tsai4fe96632019-05-22 05:12:36 -040028var messageTypeCache sync.Map // map[reflect.Type]*MessageInfo
Joe Tsaice6edd32018-10-19 16:27:46 -070029
Joe Tsai4fe96632019-05-22 05:12:36 -040030// loadMessageInfo dynamically loads a *MessageInfo for t,
Joe Tsaif0c01e42018-11-06 13:05:20 -080031// where t must be a *struct kind and not implement the v2 API already.
Joe Tsai4fe96632019-05-22 05:12:36 -040032func loadMessageInfo(t reflect.Type) *pimpl.MessageInfo {
33 // Fast-path: check if a MessageInfo is cached for this concrete type.
Joe Tsaif0c01e42018-11-06 13:05:20 -080034 if mt, ok := messageTypeCache.Load(t); ok {
Joe Tsai4fe96632019-05-22 05:12:36 -040035 return mt.(*pimpl.MessageInfo)
Joe Tsaice6edd32018-10-19 16:27:46 -070036 }
37
Joe Tsai4fe96632019-05-22 05:12:36 -040038 // Slow-path: derive message descriptor and initialize MessageInfo.
Joe Tsai35ec98f2019-03-25 14:41:32 -070039 md := LoadMessageDesc(t)
Joe Tsai4fe96632019-05-22 05:12:36 -040040 mt := new(pimpl.MessageInfo)
Damien Neil8012b442019-01-18 09:32:24 -080041 mt.GoType = t
Joe Tsaib2f66be2019-05-22 00:42:45 -040042 mt.PBType = &prototype.Message{
43 MessageDescriptor: md,
44 NewMessage: func() pref.Message {
45 return mt.MessageOf(reflect.New(t.Elem()).Interface())
46 },
47 }
Joe Tsaib9365042019-03-19 14:14:29 -070048 if mt, ok := messageTypeCache.LoadOrStore(t, mt); ok {
Joe Tsai4fe96632019-05-22 05:12:36 -040049 return mt.(*pimpl.MessageInfo)
Joe Tsaib9365042019-03-19 14:14:29 -070050 }
Joe Tsaif0c01e42018-11-06 13:05:20 -080051 return mt
Joe Tsaice6edd32018-10-19 16:27:46 -070052}
53
Joe Tsaib9365042019-03-19 14:14:29 -070054var messageDescLock sync.Mutex
Joe Tsai90fe9962018-10-18 11:06:29 -070055var messageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor
56
Joe Tsai35ec98f2019-03-25 14:41:32 -070057// LoadMessageDesc 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.
61func LoadMessageDesc(t reflect.Type) pref.MessageDescriptor {
Joe Tsai90fe9962018-10-18 11:06:29 -070062 return messageDescSet{}.Load(t)
63}
64
65type messageDescSet struct {
66 visited map[reflect.Type]*ptype.StandaloneMessage
67 descs []*ptype.StandaloneMessage
68 types []reflect.Type
69}
70
71func (ms messageDescSet) Load(t reflect.Type) pref.MessageDescriptor {
72 // Fast-path: check if a MessageDescriptor is cached for this concrete type.
73 if mi, ok := messageDescCache.Load(t); ok {
74 return mi.(pref.MessageDescriptor)
75 }
76
77 // Slow-path: initialize MessageDescriptor from the Go type.
Joe Tsaib9365042019-03-19 14:14:29 -070078 //
79 // Hold a global lock during message creation to ensure that each Go type
80 // maps to exactly one MessageDescriptor. After obtaining the lock, we must
81 // check again whether the message has already been handled.
82 messageDescLock.Lock()
83 defer messageDescLock.Unlock()
84 if mi, ok := messageDescCache.Load(t); ok {
85 return mi.(pref.MessageDescriptor)
86 }
Joe Tsai90fe9962018-10-18 11:06:29 -070087
88 // Processing t recursively populates descs and types with all sub-messages.
89 // The descriptor for the first type is guaranteed to be at the front.
90 ms.processMessage(t)
91
92 // Within a proto file it is possible for cyclic dependencies to exist
93 // between multiple message types. When these cases arise, the set of
94 // message descriptors must be created together.
95 mds, err := ptype.NewMessages(ms.descs)
96 if err != nil {
97 panic(err)
98 }
99 for i, md := range mds {
100 // Protobuf semantics represents map entries under-the-hood as
101 // pseudo-messages (has a descriptor, but no generated Go type).
102 // Avoid caching these fake messages.
103 if t := ms.types[i]; t.Kind() != reflect.Map {
104 messageDescCache.Store(t, md)
105 }
106 }
107 return mds[0]
108}
109
110func (ms *messageDescSet) processMessage(t reflect.Type) pref.MessageDescriptor {
111 // Fast-path: Obtain a placeholder if the message is already processed.
112 if m, ok := ms.visited[t]; ok {
113 return ptype.PlaceholderMessage(m.FullName)
114 }
115
116 // Slow-path: Walk over the struct fields to derive the message descriptor.
Joe Tsai6f9095c2018-11-10 14:12:21 -0800117 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct || t.Elem().PkgPath() == "" {
118 panic(fmt.Sprintf("got %v, want named *struct kind", t))
Joe Tsai90fe9962018-10-18 11:06:29 -0700119 }
120
121 // Derive name and syntax from the raw descriptor.
122 m := new(ptype.StandaloneMessage)
123 mv := reflect.New(t.Elem()).Interface()
124 if _, ok := mv.(pref.ProtoMessage); ok {
125 panic(fmt.Sprintf("%v already implements proto.Message", t))
126 }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800127 if md, ok := mv.(messageV1); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -0700128 b, idxs := md.Descriptor()
Damien Neil987d5702019-04-10 11:06:53 -0700129 fd := loadFileDesc(b)
Joe Tsai90fe9962018-10-18 11:06:29 -0700130
131 // Derive syntax.
132 switch fd.GetSyntax() {
133 case "proto2", "":
134 m.Syntax = pref.Proto2
135 case "proto3":
136 m.Syntax = pref.Proto3
137 }
138
139 // Derive full name.
140 md := fd.MessageType[idxs[0]]
141 m.FullName = pref.FullName(fd.GetPackage()).Append(pref.Name(md.GetName()))
142 for _, i := range idxs[1:] {
143 md = md.NestedType[i]
144 m.FullName = m.FullName.Append(pref.Name(md.GetName()))
145 }
146 } else {
Joe Tsai6dbffb72018-12-04 14:06:19 -0800147 // If the type does not implement messageV1, then the only way to
Joe Tsai90fe9962018-10-18 11:06:29 -0700148 // obtain the full name is through the registry. However, this is
149 // unreliable as some generated messages register with a fork of
150 // golang/protobuf, so the registry may not have this information.
151 m.FullName = deriveFullName(t.Elem())
152 m.Syntax = pref.Proto2
153
154 // Try to determine if the message is using proto3 by checking scalars.
155 for i := 0; i < t.Elem().NumField(); i++ {
156 f := t.Elem().Field(i)
157 if tag := f.Tag.Get("protobuf"); tag != "" {
158 switch f.Type.Kind() {
159 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
160 m.Syntax = pref.Proto3
161 }
162 for _, s := range strings.Split(tag, ",") {
163 if s == "proto3" {
164 m.Syntax = pref.Proto3
165 }
166 }
167 }
168 }
169 }
170 ms.visit(m, t)
171
172 // Obtain a list of oneof wrapper types.
173 var oneofWrappers []reflect.Type
174 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
175 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
176 for _, v := range vs.Interface().([]interface{}) {
177 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
178 }
179 }
Joe Tsai25cc69d2018-11-28 23:43:49 -0800180 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
181 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
182 for _, v := range vs.Interface().([]interface{}) {
183 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
184 }
185 }
Joe Tsai90fe9962018-10-18 11:06:29 -0700186
187 // Obtain a list of the extension ranges.
188 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
189 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
190 for i := 0; i < vs.Len(); i++ {
191 v := vs.Index(i)
192 m.ExtensionRanges = append(m.ExtensionRanges, [2]pref.FieldNumber{
193 pref.FieldNumber(v.FieldByName("Start").Int()),
194 pref.FieldNumber(v.FieldByName("End").Int() + 1),
195 })
196 }
197 }
198
199 // Derive the message fields by inspecting the struct fields.
200 for i := 0; i < t.Elem().NumField(); i++ {
201 f := t.Elem().Field(i)
202 if tag := f.Tag.Get("protobuf"); tag != "" {
203 tagKey := f.Tag.Get("protobuf_key")
204 tagVal := f.Tag.Get("protobuf_val")
205 m.Fields = append(m.Fields, ms.parseField(tag, tagKey, tagVal, f.Type, m))
206 }
207 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
208 name := pref.Name(tag)
209 m.Oneofs = append(m.Oneofs, ptype.Oneof{Name: name})
210 for _, t := range oneofWrappers {
211 if t.Implements(f.Type) {
212 f := t.Elem().Field(0)
213 if tag := f.Tag.Get("protobuf"); tag != "" {
214 ft := ms.parseField(tag, "", "", f.Type, m)
215 ft.OneofName = name
216 m.Fields = append(m.Fields, ft)
217 }
218 }
219 }
220 }
221 }
222
223 return ptype.PlaceholderMessage(m.FullName)
224}
225
Joe Tsai05828db2018-11-01 13:52:16 -0700226func (ms *messageDescSet) parseField(tag, tagKey, tagVal string, goType reflect.Type, parent *ptype.StandaloneMessage) ptype.Field {
227 t := goType
Joe Tsai90fe9962018-10-18 11:06:29 -0700228 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
229 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
230 if isOptional || isRepeated {
231 t = t.Elem()
232 }
Joe Tsai05828db2018-11-01 13:52:16 -0700233 f := ptag.Unmarshal(tag, t)
Joe Tsai90fe9962018-10-18 11:06:29 -0700234
235 // Populate EnumType and MessageType.
236 if f.EnumType == nil && f.Kind == pref.EnumKind {
Damien Neila8593ba2019-01-08 16:18:07 -0800237 if ev, ok := reflect.Zero(t).Interface().(pref.Enum); ok {
Joe Tsai0fc49f82019-05-01 12:29:25 -0700238 f.EnumType = ev.Descriptor()
Joe Tsai90fe9962018-10-18 11:06:29 -0700239 } else {
Joe Tsai35ec98f2019-03-25 14:41:32 -0700240 f.EnumType = LoadEnumDesc(t)
Joe Tsai90fe9962018-10-18 11:06:29 -0700241 }
242 }
243 if f.MessageType == nil && (f.Kind == pref.MessageKind || f.Kind == pref.GroupKind) {
244 if mv, ok := reflect.Zero(t).Interface().(pref.ProtoMessage); ok {
Joe Tsai0fc49f82019-05-01 12:29:25 -0700245 f.MessageType = mv.ProtoReflect().Descriptor()
Joe Tsai90fe9962018-10-18 11:06:29 -0700246 } else if t.Kind() == reflect.Map {
247 m := &ptype.StandaloneMessage{
Damien Neil232ea152018-12-10 15:14:36 -0800248 Syntax: parent.Syntax,
249 FullName: parent.FullName.Append(mapEntryName(f.Name)),
Damien Neil232ea152018-12-10 15:14:36 -0800250 IsMapEntry: true,
Joe Tsai90fe9962018-10-18 11:06:29 -0700251 Fields: []ptype.Field{
252 ms.parseField(tagKey, "", "", t.Key(), nil),
253 ms.parseField(tagVal, "", "", t.Elem(), nil),
254 },
255 }
256 ms.visit(m, t)
257 f.MessageType = ptype.PlaceholderMessage(m.FullName)
258 } else if mv, ok := messageDescCache.Load(t); ok {
259 f.MessageType = mv.(pref.MessageDescriptor)
260 } else {
261 f.MessageType = ms.processMessage(t)
262 }
263 }
264 return f
265}
266
267func (ms *messageDescSet) visit(m *ptype.StandaloneMessage, t reflect.Type) {
268 if ms.visited == nil {
269 ms.visited = make(map[reflect.Type]*ptype.StandaloneMessage)
270 }
271 if t.Kind() != reflect.Map {
272 ms.visited[t] = m
273 }
274 ms.descs = append(ms.descs, m)
275 ms.types = append(ms.types, t)
276}
277
278// deriveFullName derives a fully qualified protobuf name for the given Go type
279// The provided name is not guaranteed to be stable nor universally unique.
280// It should be sufficiently unique within a program.
281func deriveFullName(t reflect.Type) pref.FullName {
282 sanitize := func(r rune) rune {
283 switch {
284 case r == '/':
285 return '.'
286 case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9':
287 return r
288 default:
289 return '_'
290 }
291 }
292 prefix := strings.Map(sanitize, t.PkgPath())
293 suffix := strings.Map(sanitize, t.Name())
294 if suffix == "" {
295 suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer())
296 }
297
298 ss := append(strings.Split(prefix, "."), suffix)
299 for i, s := range ss {
300 if s == "" || ('0' <= s[0] && s[0] <= '9') {
301 ss[i] = "x" + s
302 }
303 }
304 return pref.FullName(strings.Join(ss, "."))
305}
306
307// mapEntryName derives the message name for a map field of a given name.
308// This is identical to MapEntryName from parser.cc in the protoc source.
309func mapEntryName(s pref.Name) pref.Name {
310 var b []byte
311 nextUpper := true
312 for i := 0; i < len(s); i++ {
313 if c := s[i]; c == '_' {
314 nextUpper = true
315 } else {
316 if nextUpper {
317 c = byte(unicode.ToUpper(rune(c)))
318 nextUpper = false
319 }
320 b = append(b, c)
321 }
322 }
323 return pref.Name(append(b, "Entry"...))
324}