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