blob: 0c88c832af5dcc51f8b96bd0373da93af144087a [file] [log] [blame]
Joe Tsai08e00302018-11-26 22:32:06 -08001// 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
5package legacy
6
7import (
8 "fmt"
9 "reflect"
Joe Tsai62517cc2018-12-04 14:00:01 -080010 "sync"
Joe Tsai08e00302018-11-26 22:32:06 -080011
12 papi "github.com/golang/protobuf/protoapi"
13 ptag "github.com/golang/protobuf/v2/internal/encoding/tag"
14 pimpl "github.com/golang/protobuf/v2/internal/impl"
Joe Tsai990b9f52019-03-13 12:56:39 -070015 ptype "github.com/golang/protobuf/v2/internal/prototype"
Joe Tsaib3960a72018-12-05 10:35:35 -080016 pfmt "github.com/golang/protobuf/v2/internal/typefmt"
Joe Tsai08e00302018-11-26 22:32:06 -080017 pvalue "github.com/golang/protobuf/v2/internal/value"
18 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
Joe Tsai08e00302018-11-26 22:32:06 -080019)
20
Joe Tsai62517cc2018-12-04 14:00:01 -080021// extensionDescKey is a comparable version of protoapi.ExtensionDesc
22// suitable for use as a key in a map.
23type extensionDescKey struct {
24 typeV2 pref.ExtensionType
25 extendedType reflect.Type
26 extensionType reflect.Type
27 field int32
28 name string
29 tag string
30 filename string
31}
32
33func extensionDescKeyOf(d *papi.ExtensionDesc) extensionDescKey {
34 return extensionDescKey{
35 d.Type,
36 reflect.TypeOf(d.ExtendedType),
37 reflect.TypeOf(d.ExtensionType),
38 d.Field, d.Name, d.Tag, d.Filename,
39 }
40}
41
42var (
43 extensionTypeCache sync.Map // map[extensionDescKey]protoreflect.ExtensionType
44 extensionDescCache sync.Map // map[protoreflect.ExtensionType]*protoapi.ExtensionDesc
45)
46
Joe Tsai6dbffb72018-12-04 14:06:19 -080047// extensionDescFromType converts a v2 protoreflect.ExtensionType to a
Joe Tsai62517cc2018-12-04 14:00:01 -080048// v1 protoapi.ExtensionDesc. The returned ExtensionDesc must not be mutated.
Joe Tsai6dbffb72018-12-04 14:06:19 -080049func extensionDescFromType(t pref.ExtensionType) *papi.ExtensionDesc {
Joe Tsaiafb455e2019-03-14 16:08:22 -070050 // Fast-path: check whether an extension desc is already nested within.
51 if t, ok := t.(interface{ ProtoLegacyExtensionDesc() *papi.ExtensionDesc }); ok {
52 if d := t.ProtoLegacyExtensionDesc(); d != nil {
53 return d
54 }
55 }
56
Joe Tsai62517cc2018-12-04 14:00:01 -080057 // Fast-path: check the cache for whether this ExtensionType has already
58 // been converted to a legacy descriptor.
59 if d, ok := extensionDescCache.Load(t); ok {
60 return d.(*papi.ExtensionDesc)
Joe Tsai08e00302018-11-26 22:32:06 -080061 }
62
63 // Determine the parent type if possible.
64 var parent papi.Message
65 if mt, ok := t.ExtendedType().(pref.MessageType); ok {
66 // Create a new parent message and unwrap it if possible.
Joe Tsai3bc7d6f2019-01-09 02:57:13 -080067 mv := mt.New().Interface()
Joe Tsai08e00302018-11-26 22:32:06 -080068 t := reflect.TypeOf(mv)
69 if mv, ok := mv.(pvalue.Unwrapper); ok {
70 t = reflect.TypeOf(mv.ProtoUnwrap())
71 }
72
73 // Check whether the message implements the legacy v1 Message interface.
74 mz := reflect.Zero(t).Interface()
75 if mz, ok := mz.(papi.Message); ok {
76 parent = mz
77 }
78 }
79
80 // Determine the v1 extension type, which is unfortunately not the same as
81 // the v2 ExtensionType.GoType.
82 extType := t.GoType()
83 switch extType.Kind() {
84 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
85 extType = reflect.PtrTo(extType) // T -> *T for singular scalar fields
86 case reflect.Ptr:
87 if extType.Elem().Kind() == reflect.Slice {
88 extType = extType.Elem() // *[]T -> []T for repeated fields
89 }
90 }
91
92 // Reconstruct the legacy enum full name, which is an odd mixture of the
93 // proto package name with the Go type name.
94 var enumName string
95 if t.Kind() == pref.EnumKind {
96 // Derive Go type name.
97 // For legacy enums, unwrap the wrapper to get the underlying Go type.
98 et := t.EnumType().(pref.EnumType)
99 var ev interface{} = et.New(0)
100 if u, ok := ev.(pvalue.Unwrapper); ok {
101 ev = u.ProtoUnwrap()
102 }
103 enumName = reflect.TypeOf(ev).Name()
104
105 // Derive the proto package name.
106 // For legacy enums, obtain the proto package from the raw descriptor.
107 var protoPkg string
108 if fd := parentFileDescriptor(et); fd != nil {
109 protoPkg = string(fd.Package())
110 }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800111 if ed, ok := ev.(enumV1); ok && protoPkg == "" {
Joe Tsai08e00302018-11-26 22:32:06 -0800112 b, _ := ed.EnumDescriptor()
Joe Tsai6dbffb72018-12-04 14:06:19 -0800113 protoPkg = loadFileDesc(b).GetPackage()
Joe Tsai08e00302018-11-26 22:32:06 -0800114 }
115
116 if protoPkg != "" {
117 enumName = protoPkg + "." + enumName
118 }
119 }
120
121 // Derive the proto file that the extension was declared within.
122 var filename string
123 if fd := parentFileDescriptor(t); fd != nil {
124 filename = fd.Path()
125 }
126
127 // Construct and return a v1 ExtensionDesc.
Joe Tsai62517cc2018-12-04 14:00:01 -0800128 d := &papi.ExtensionDesc{
Joe Tsai08e00302018-11-26 22:32:06 -0800129 Type: t,
130 ExtendedType: parent,
131 ExtensionType: reflect.Zero(extType).Interface(),
132 Field: int32(t.Number()),
133 Name: string(t.FullName()),
134 Tag: ptag.Marshal(t, enumName),
135 Filename: filename,
136 }
Joe Tsaib9365042019-03-19 14:14:29 -0700137 if d, ok := extensionDescCache.LoadOrStore(t, d); ok {
138 return d.(*papi.ExtensionDesc)
139 }
Joe Tsai62517cc2018-12-04 14:00:01 -0800140 return d
Joe Tsai08e00302018-11-26 22:32:06 -0800141}
142
Joe Tsai6dbffb72018-12-04 14:06:19 -0800143// extensionTypeFromDesc converts a v1 protoapi.ExtensionDesc to a
Joe Tsai62517cc2018-12-04 14:00:01 -0800144// v2 protoreflect.ExtensionType. The returned descriptor type takes ownership
145// of the input extension desc. The input must not be mutated so long as the
146// returned type is still in use.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800147func extensionTypeFromDesc(d *papi.ExtensionDesc) pref.ExtensionType {
Joe Tsai62517cc2018-12-04 14:00:01 -0800148 // Fast-path: check whether an extension type is already nested within.
Joe Tsai08e00302018-11-26 22:32:06 -0800149 if d.Type != nil {
Joe Tsai62517cc2018-12-04 14:00:01 -0800150 return d.Type
151 }
152
153 // Fast-path: check the cache for whether this ExtensionType has already
154 // been converted from a legacy descriptor.
155 dk := extensionDescKeyOf(d)
156 if t, ok := extensionTypeCache.Load(dk); ok {
157 return t.(pref.ExtensionType)
Joe Tsai08e00302018-11-26 22:32:06 -0800158 }
159
160 // Derive basic field information from the struct tag.
161 t := reflect.TypeOf(d.ExtensionType)
162 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
163 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
164 if isOptional || isRepeated {
165 t = t.Elem()
166 }
167 f := ptag.Unmarshal(d.Tag, t)
168
169 // Construct a v2 ExtensionType.
170 conv := pvalue.NewLegacyConverter(t, f.Kind, Export{})
171 xd, err := ptype.NewExtension(&ptype.StandaloneExtension{
172 FullName: pref.FullName(d.Name),
173 Number: pref.FieldNumber(d.Field),
174 Cardinality: f.Cardinality,
175 Kind: f.Kind,
176 Default: f.Default,
177 Options: f.Options,
178 EnumType: conv.EnumType,
179 MessageType: conv.MessageType,
Herbie Ong2b0bba82018-12-20 12:56:42 -0800180 ExtendedType: pimpl.Export{}.MessageTypeOf(d.ExtendedType),
Joe Tsai08e00302018-11-26 22:32:06 -0800181 })
182 if err != nil {
183 panic(err)
184 }
Herbie Ong2b0bba82018-12-20 12:56:42 -0800185 var zv interface{}
186 switch xd.Kind() {
187 case pref.EnumKind, pref.MessageKind, pref.GroupKind:
188 zv = reflect.Zero(t).Interface()
189 }
190 xt := pimpl.Export{}.ExtensionTypeOf(xd, zv)
Joe Tsai08e00302018-11-26 22:32:06 -0800191
Joe Tsai62517cc2018-12-04 14:00:01 -0800192 // Cache the conversion for both directions.
Joe Tsaib9365042019-03-19 14:14:29 -0700193 extensionDescCache.LoadOrStore(xt, d)
194 if xt, ok := extensionTypeCache.LoadOrStore(dk, xt); ok {
195 return xt.(pref.ExtensionType)
196 }
Joe Tsai62517cc2018-12-04 14:00:01 -0800197 return xt
Joe Tsai08e00302018-11-26 22:32:06 -0800198}
199
Joe Tsai6dbffb72018-12-04 14:06:19 -0800200// extensionTypeOf returns a protoreflect.ExtensionType where the GoType
Joe Tsai08e00302018-11-26 22:32:06 -0800201// is the underlying v1 Go type instead of the wrapper types used to present
202// v1 Go types as if they satisfied the v2 API.
203//
204// This function is only valid if xd.Kind is an enum or message.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800205func extensionTypeOf(xd pref.ExtensionDescriptor, t reflect.Type) pref.ExtensionType {
Joe Tsai08e00302018-11-26 22:32:06 -0800206 // Step 1: Create an ExtensionType where GoType is the wrapper type.
207 conv := pvalue.NewLegacyConverter(t, xd.Kind(), Export{})
208 xt := ptype.GoExtension(xd, conv.EnumType, conv.MessageType)
209
210 // Step 2: Wrap ExtensionType such that GoType presents the legacy Go type.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800211 xt2 := &extensionType{ExtensionType: xt}
Joe Tsai08e00302018-11-26 22:32:06 -0800212 if xd.Cardinality() != pref.Repeated {
213 xt2.typ = t
Joe Tsaid18bd312019-01-09 03:23:55 -0800214 xt2.new = func() pref.Value {
215 return xt.New()
Joe Tsai08e00302018-11-26 22:32:06 -0800216 }
217 xt2.valueOf = func(v interface{}) pref.Value {
218 if reflect.TypeOf(v) != xt2.typ {
219 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
220 }
221 if xd.Kind() == pref.EnumKind {
222 return xt.ValueOf(Export{}.EnumOf(v))
223 } else {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700224 return xt.ValueOf(Export{}.MessageOf(v).Interface())
Joe Tsai08e00302018-11-26 22:32:06 -0800225 }
226 }
227 xt2.interfaceOf = func(v pref.Value) interface{} {
228 return xt.InterfaceOf(v).(pvalue.Unwrapper).ProtoUnwrap()
229 }
230 } else {
231 xt2.typ = reflect.PtrTo(reflect.SliceOf(t))
Joe Tsaid18bd312019-01-09 03:23:55 -0800232 xt2.new = func() pref.Value {
233 v := reflect.New(xt2.typ.Elem()).Interface()
234 return pref.ValueOf(pvalue.ListOf(v, conv))
Joe Tsai08e00302018-11-26 22:32:06 -0800235 }
236 xt2.valueOf = func(v interface{}) pref.Value {
237 if reflect.TypeOf(v) != xt2.typ {
238 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
239 }
240 return pref.ValueOf(pvalue.ListOf(v, conv))
241 }
242 xt2.interfaceOf = func(pv pref.Value) interface{} {
243 v := pv.List().(pvalue.Unwrapper).ProtoUnwrap()
244 if reflect.TypeOf(v) != xt2.typ {
245 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
246 }
247 return v
248 }
249 }
250 return xt2
251}
252
Joe Tsai6dbffb72018-12-04 14:06:19 -0800253type extensionType struct {
Joe Tsai08e00302018-11-26 22:32:06 -0800254 pref.ExtensionType
255 typ reflect.Type
Joe Tsaid18bd312019-01-09 03:23:55 -0800256 new func() pref.Value
Joe Tsai08e00302018-11-26 22:32:06 -0800257 valueOf func(interface{}) pref.Value
258 interfaceOf func(pref.Value) interface{}
259}
260
Joe Tsai6dbffb72018-12-04 14:06:19 -0800261func (x *extensionType) GoType() reflect.Type { return x.typ }
Joe Tsaid18bd312019-01-09 03:23:55 -0800262func (x *extensionType) New() pref.Value { return x.new() }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800263func (x *extensionType) ValueOf(v interface{}) pref.Value { return x.valueOf(v) }
264func (x *extensionType) InterfaceOf(v pref.Value) interface{} { return x.interfaceOf(v) }
Joe Tsaib3960a72018-12-05 10:35:35 -0800265func (x *extensionType) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, x) }