blob: 005867c61c8814f86b416ba1248422bca4a111c8 [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
Joe Tsai05828db2018-11-01 13:52:16 -070014 ptag "github.com/golang/protobuf/v2/internal/encoding/tag"
Joe Tsai08e00302018-11-26 22:32:06 -080015 pimpl "github.com/golang/protobuf/v2/internal/impl"
Joe Tsai009e0672018-11-27 18:45:07 -080016 scalar "github.com/golang/protobuf/v2/internal/scalar"
Joe Tsai90fe9962018-10-18 11:06:29 -070017 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
18 ptype "github.com/golang/protobuf/v2/reflect/prototype"
Joe Tsaie1f8d502018-11-26 18:55:29 -080019
20 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Joe Tsai90fe9962018-10-18 11:06:29 -070021)
22
Joe Tsai6dbffb72018-12-04 14:06:19 -080023// wrapMessage wraps v as a protoreflect.ProtoMessage,
Joe Tsaif0c01e42018-11-06 13:05:20 -080024// where v must be a *struct kind and not implement the v2 API already.
Joe Tsai6dbffb72018-12-04 14:06:19 -080025func wrapMessage(v reflect.Value) pref.ProtoMessage {
26 mt := loadMessageType(v.Type())
Joe Tsai08e00302018-11-26 22:32:06 -080027 return mt.MessageOf(v.Interface()).Interface()
Joe Tsaif0c01e42018-11-06 13:05:20 -080028}
29
Joe Tsaice6edd32018-10-19 16:27:46 -070030var messageTypeCache sync.Map // map[reflect.Type]*MessageType
31
Joe Tsai6dbffb72018-12-04 14:06:19 -080032// loadMessageType dynamically loads a *MessageType for t,
Joe Tsaif0c01e42018-11-06 13:05:20 -080033// where t must be a *struct kind and not implement the v2 API already.
Joe Tsai6dbffb72018-12-04 14:06:19 -080034func loadMessageType(t reflect.Type) *pimpl.MessageType {
Joe Tsaice6edd32018-10-19 16:27:46 -070035 // Fast-path: check if a MessageType is cached for this concrete type.
Joe Tsaif0c01e42018-11-06 13:05:20 -080036 if mt, ok := messageTypeCache.Load(t); ok {
Joe Tsai08e00302018-11-26 22:32:06 -080037 return mt.(*pimpl.MessageType)
Joe Tsaice6edd32018-10-19 16:27:46 -070038 }
39
40 // Slow-path: derive message descriptor and initialize MessageType.
Joe Tsai6dbffb72018-12-04 14:06:19 -080041 md := loadMessageDesc(t)
Joe Tsai08e00302018-11-26 22:32:06 -080042 mt := new(pimpl.MessageType)
Joe Tsai3bc7d6f2019-01-09 02:57:13 -080043 mt.Type = ptype.GoMessage(md, func(pref.MessageType) pref.Message {
Joe Tsaif0c01e42018-11-06 13:05:20 -080044 p := reflect.New(t.Elem()).Interface()
Joe Tsai3bc7d6f2019-01-09 02:57:13 -080045 return mt.MessageOf(p)
Joe Tsaif0c01e42018-11-06 13:05:20 -080046 })
47 messageTypeCache.Store(t, mt)
48 return mt
Joe Tsaice6edd32018-10-19 16:27:46 -070049}
50
Joe Tsai90fe9962018-10-18 11:06:29 -070051var messageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor
52
Joe Tsai6dbffb72018-12-04 14:06:19 -080053// loadMessageDesc returns an MessageDescriptor derived from the Go type,
Joe Tsaice6edd32018-10-19 16:27:46 -070054// which must be a *struct kind and not implement the v2 API already.
Joe Tsai6dbffb72018-12-04 14:06:19 -080055func loadMessageDesc(t reflect.Type) pref.MessageDescriptor {
Joe Tsai90fe9962018-10-18 11:06:29 -070056 return messageDescSet{}.Load(t)
57}
58
59type messageDescSet struct {
60 visited map[reflect.Type]*ptype.StandaloneMessage
61 descs []*ptype.StandaloneMessage
62 types []reflect.Type
63}
64
65func (ms messageDescSet) Load(t reflect.Type) pref.MessageDescriptor {
66 // Fast-path: check if a MessageDescriptor is cached for this concrete type.
67 if mi, ok := messageDescCache.Load(t); ok {
68 return mi.(pref.MessageDescriptor)
69 }
70
71 // Slow-path: initialize MessageDescriptor from the Go type.
72
73 // Processing t recursively populates descs and types with all sub-messages.
74 // The descriptor for the first type is guaranteed to be at the front.
75 ms.processMessage(t)
76
77 // Within a proto file it is possible for cyclic dependencies to exist
78 // between multiple message types. When these cases arise, the set of
79 // message descriptors must be created together.
80 mds, err := ptype.NewMessages(ms.descs)
81 if err != nil {
82 panic(err)
83 }
84 for i, md := range mds {
85 // Protobuf semantics represents map entries under-the-hood as
86 // pseudo-messages (has a descriptor, but no generated Go type).
87 // Avoid caching these fake messages.
88 if t := ms.types[i]; t.Kind() != reflect.Map {
89 messageDescCache.Store(t, md)
90 }
91 }
92 return mds[0]
93}
94
95func (ms *messageDescSet) processMessage(t reflect.Type) pref.MessageDescriptor {
96 // Fast-path: Obtain a placeholder if the message is already processed.
97 if m, ok := ms.visited[t]; ok {
98 return ptype.PlaceholderMessage(m.FullName)
99 }
100
101 // Slow-path: Walk over the struct fields to derive the message descriptor.
Joe Tsai6f9095c2018-11-10 14:12:21 -0800102 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct || t.Elem().PkgPath() == "" {
103 panic(fmt.Sprintf("got %v, want named *struct kind", t))
Joe Tsai90fe9962018-10-18 11:06:29 -0700104 }
105
106 // Derive name and syntax from the raw descriptor.
107 m := new(ptype.StandaloneMessage)
108 mv := reflect.New(t.Elem()).Interface()
109 if _, ok := mv.(pref.ProtoMessage); ok {
110 panic(fmt.Sprintf("%v already implements proto.Message", t))
111 }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800112 if md, ok := mv.(messageV1); ok {
Joe Tsai90fe9962018-10-18 11:06:29 -0700113 b, idxs := md.Descriptor()
Joe Tsai6dbffb72018-12-04 14:06:19 -0800114 fd := loadFileDesc(b)
Joe Tsai90fe9962018-10-18 11:06:29 -0700115
116 // Derive syntax.
117 switch fd.GetSyntax() {
118 case "proto2", "":
119 m.Syntax = pref.Proto2
120 case "proto3":
121 m.Syntax = pref.Proto3
122 }
123
124 // Derive full name.
125 md := fd.MessageType[idxs[0]]
126 m.FullName = pref.FullName(fd.GetPackage()).Append(pref.Name(md.GetName()))
127 for _, i := range idxs[1:] {
128 md = md.NestedType[i]
129 m.FullName = m.FullName.Append(pref.Name(md.GetName()))
130 }
131 } else {
Joe Tsai6dbffb72018-12-04 14:06:19 -0800132 // If the type does not implement messageV1, then the only way to
Joe Tsai90fe9962018-10-18 11:06:29 -0700133 // obtain the full name is through the registry. However, this is
134 // unreliable as some generated messages register with a fork of
135 // golang/protobuf, so the registry may not have this information.
136 m.FullName = deriveFullName(t.Elem())
137 m.Syntax = pref.Proto2
138
139 // Try to determine if the message is using proto3 by checking scalars.
140 for i := 0; i < t.Elem().NumField(); i++ {
141 f := t.Elem().Field(i)
142 if tag := f.Tag.Get("protobuf"); tag != "" {
143 switch f.Type.Kind() {
144 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
145 m.Syntax = pref.Proto3
146 }
147 for _, s := range strings.Split(tag, ",") {
148 if s == "proto3" {
149 m.Syntax = pref.Proto3
150 }
151 }
152 }
153 }
154 }
155 ms.visit(m, t)
156
157 // Obtain a list of oneof wrapper types.
158 var oneofWrappers []reflect.Type
159 if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok {
160 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3]
161 for _, v := range vs.Interface().([]interface{}) {
162 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
163 }
164 }
Joe Tsai25cc69d2018-11-28 23:43:49 -0800165 if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok {
166 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
167 for _, v := range vs.Interface().([]interface{}) {
168 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
169 }
170 }
Joe Tsai90fe9962018-10-18 11:06:29 -0700171
172 // Obtain a list of the extension ranges.
173 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
174 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
175 for i := 0; i < vs.Len(); i++ {
176 v := vs.Index(i)
177 m.ExtensionRanges = append(m.ExtensionRanges, [2]pref.FieldNumber{
178 pref.FieldNumber(v.FieldByName("Start").Int()),
179 pref.FieldNumber(v.FieldByName("End").Int() + 1),
180 })
181 }
182 }
183
184 // Derive the message fields by inspecting the struct fields.
185 for i := 0; i < t.Elem().NumField(); i++ {
186 f := t.Elem().Field(i)
187 if tag := f.Tag.Get("protobuf"); tag != "" {
188 tagKey := f.Tag.Get("protobuf_key")
189 tagVal := f.Tag.Get("protobuf_val")
190 m.Fields = append(m.Fields, ms.parseField(tag, tagKey, tagVal, f.Type, m))
191 }
192 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
193 name := pref.Name(tag)
194 m.Oneofs = append(m.Oneofs, ptype.Oneof{Name: name})
195 for _, t := range oneofWrappers {
196 if t.Implements(f.Type) {
197 f := t.Elem().Field(0)
198 if tag := f.Tag.Get("protobuf"); tag != "" {
199 ft := ms.parseField(tag, "", "", f.Type, m)
200 ft.OneofName = name
201 m.Fields = append(m.Fields, ft)
202 }
203 }
204 }
205 }
206 }
207
208 return ptype.PlaceholderMessage(m.FullName)
209}
210
Joe Tsai05828db2018-11-01 13:52:16 -0700211func (ms *messageDescSet) parseField(tag, tagKey, tagVal string, goType reflect.Type, parent *ptype.StandaloneMessage) ptype.Field {
212 t := goType
Joe Tsai90fe9962018-10-18 11:06:29 -0700213 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
214 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
215 if isOptional || isRepeated {
216 t = t.Elem()
217 }
Joe Tsai05828db2018-11-01 13:52:16 -0700218 f := ptag.Unmarshal(tag, t)
Joe Tsai90fe9962018-10-18 11:06:29 -0700219
220 // Populate EnumType and MessageType.
221 if f.EnumType == nil && f.Kind == pref.EnumKind {
Damien Neila8593ba2019-01-08 16:18:07 -0800222 if ev, ok := reflect.Zero(t).Interface().(pref.Enum); ok {
223 f.EnumType = ev.Type()
Joe Tsai90fe9962018-10-18 11:06:29 -0700224 } else {
Joe Tsai6dbffb72018-12-04 14:06:19 -0800225 f.EnumType = loadEnumDesc(t)
Joe Tsai90fe9962018-10-18 11:06:29 -0700226 }
227 }
228 if f.MessageType == nil && (f.Kind == pref.MessageKind || f.Kind == pref.GroupKind) {
229 if mv, ok := reflect.Zero(t).Interface().(pref.ProtoMessage); ok {
230 f.MessageType = mv.ProtoReflect().Type()
231 } else if t.Kind() == reflect.Map {
232 m := &ptype.StandaloneMessage{
Damien Neil232ea152018-12-10 15:14:36 -0800233 Syntax: parent.Syntax,
234 FullName: parent.FullName.Append(mapEntryName(f.Name)),
235 Options: &descriptorpb.MessageOptions{MapEntry: scalar.Bool(true)},
236 IsMapEntry: true,
Joe Tsai90fe9962018-10-18 11:06:29 -0700237 Fields: []ptype.Field{
238 ms.parseField(tagKey, "", "", t.Key(), nil),
239 ms.parseField(tagVal, "", "", t.Elem(), nil),
240 },
241 }
242 ms.visit(m, t)
243 f.MessageType = ptype.PlaceholderMessage(m.FullName)
244 } else if mv, ok := messageDescCache.Load(t); ok {
245 f.MessageType = mv.(pref.MessageDescriptor)
246 } else {
247 f.MessageType = ms.processMessage(t)
248 }
249 }
250 return f
251}
252
253func (ms *messageDescSet) visit(m *ptype.StandaloneMessage, t reflect.Type) {
254 if ms.visited == nil {
255 ms.visited = make(map[reflect.Type]*ptype.StandaloneMessage)
256 }
257 if t.Kind() != reflect.Map {
258 ms.visited[t] = m
259 }
260 ms.descs = append(ms.descs, m)
261 ms.types = append(ms.types, t)
262}
263
264// deriveFullName derives a fully qualified protobuf name for the given Go type
265// The provided name is not guaranteed to be stable nor universally unique.
266// It should be sufficiently unique within a program.
267func deriveFullName(t reflect.Type) pref.FullName {
268 sanitize := func(r rune) rune {
269 switch {
270 case r == '/':
271 return '.'
272 case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9':
273 return r
274 default:
275 return '_'
276 }
277 }
278 prefix := strings.Map(sanitize, t.PkgPath())
279 suffix := strings.Map(sanitize, t.Name())
280 if suffix == "" {
281 suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer())
282 }
283
284 ss := append(strings.Split(prefix, "."), suffix)
285 for i, s := range ss {
286 if s == "" || ('0' <= s[0] && s[0] <= '9') {
287 ss[i] = "x" + s
288 }
289 }
290 return pref.FullName(strings.Join(ss, "."))
291}
292
293// mapEntryName derives the message name for a map field of a given name.
294// This is identical to MapEntryName from parser.cc in the protoc source.
295func mapEntryName(s pref.Name) pref.Name {
296 var b []byte
297 nextUpper := true
298 for i := 0; i < len(s); i++ {
299 if c := s[i]; c == '_' {
300 nextUpper = true
301 } else {
302 if nextUpper {
303 c = byte(unicode.ToUpper(rune(c)))
304 nextUpper = false
305 }
306 b = append(b, c)
307 }
308 }
309 return pref.Name(append(b, "Entry"...))
310}