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