blob: 162670224052b0432a684e21af51b525486328cb [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 Tsai62517cc2018-12-04 14:00:01 -080050 // Fast-path: check the cache for whether this ExtensionType has already
51 // been converted to a legacy descriptor.
52 if d, ok := extensionDescCache.Load(t); ok {
53 return d.(*papi.ExtensionDesc)
Joe Tsai08e00302018-11-26 22:32:06 -080054 }
55
56 // Determine the parent type if possible.
57 var parent papi.Message
58 if mt, ok := t.ExtendedType().(pref.MessageType); ok {
59 // Create a new parent message and unwrap it if possible.
Joe Tsai3bc7d6f2019-01-09 02:57:13 -080060 mv := mt.New().Interface()
Joe Tsai08e00302018-11-26 22:32:06 -080061 t := reflect.TypeOf(mv)
62 if mv, ok := mv.(pvalue.Unwrapper); ok {
63 t = reflect.TypeOf(mv.ProtoUnwrap())
64 }
65
66 // Check whether the message implements the legacy v1 Message interface.
67 mz := reflect.Zero(t).Interface()
68 if mz, ok := mz.(papi.Message); ok {
69 parent = mz
70 }
71 }
72
73 // Determine the v1 extension type, which is unfortunately not the same as
74 // the v2 ExtensionType.GoType.
75 extType := t.GoType()
76 switch extType.Kind() {
77 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
78 extType = reflect.PtrTo(extType) // T -> *T for singular scalar fields
79 case reflect.Ptr:
80 if extType.Elem().Kind() == reflect.Slice {
81 extType = extType.Elem() // *[]T -> []T for repeated fields
82 }
83 }
84
85 // Reconstruct the legacy enum full name, which is an odd mixture of the
86 // proto package name with the Go type name.
87 var enumName string
88 if t.Kind() == pref.EnumKind {
89 // Derive Go type name.
90 // For legacy enums, unwrap the wrapper to get the underlying Go type.
91 et := t.EnumType().(pref.EnumType)
92 var ev interface{} = et.New(0)
93 if u, ok := ev.(pvalue.Unwrapper); ok {
94 ev = u.ProtoUnwrap()
95 }
96 enumName = reflect.TypeOf(ev).Name()
97
98 // Derive the proto package name.
99 // For legacy enums, obtain the proto package from the raw descriptor.
100 var protoPkg string
101 if fd := parentFileDescriptor(et); fd != nil {
102 protoPkg = string(fd.Package())
103 }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800104 if ed, ok := ev.(enumV1); ok && protoPkg == "" {
Joe Tsai08e00302018-11-26 22:32:06 -0800105 b, _ := ed.EnumDescriptor()
Joe Tsai6dbffb72018-12-04 14:06:19 -0800106 protoPkg = loadFileDesc(b).GetPackage()
Joe Tsai08e00302018-11-26 22:32:06 -0800107 }
108
109 if protoPkg != "" {
110 enumName = protoPkg + "." + enumName
111 }
112 }
113
114 // Derive the proto file that the extension was declared within.
115 var filename string
116 if fd := parentFileDescriptor(t); fd != nil {
117 filename = fd.Path()
118 }
119
120 // Construct and return a v1 ExtensionDesc.
Joe Tsai62517cc2018-12-04 14:00:01 -0800121 d := &papi.ExtensionDesc{
Joe Tsai08e00302018-11-26 22:32:06 -0800122 Type: t,
123 ExtendedType: parent,
124 ExtensionType: reflect.Zero(extType).Interface(),
125 Field: int32(t.Number()),
126 Name: string(t.FullName()),
127 Tag: ptag.Marshal(t, enumName),
128 Filename: filename,
129 }
Joe Tsai62517cc2018-12-04 14:00:01 -0800130 extensionDescCache.Store(t, d)
131 return d
Joe Tsai08e00302018-11-26 22:32:06 -0800132}
133
Joe Tsai6dbffb72018-12-04 14:06:19 -0800134// extensionTypeFromDesc converts a v1 protoapi.ExtensionDesc to a
Joe Tsai62517cc2018-12-04 14:00:01 -0800135// v2 protoreflect.ExtensionType. The returned descriptor type takes ownership
136// of the input extension desc. The input must not be mutated so long as the
137// returned type is still in use.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800138func extensionTypeFromDesc(d *papi.ExtensionDesc) pref.ExtensionType {
Joe Tsai62517cc2018-12-04 14:00:01 -0800139 // Fast-path: check whether an extension type is already nested within.
Joe Tsai08e00302018-11-26 22:32:06 -0800140 if d.Type != nil {
Joe Tsai6dbffb72018-12-04 14:06:19 -0800141 // Cache descriptor for future extensionDescFromType operation.
Joe Tsai62517cc2018-12-04 14:00:01 -0800142 // This assumes that there is only one legacy protoapi.ExtensionDesc
143 // that wraps any given specific protoreflect.ExtensionType.
144 extensionDescCache.LoadOrStore(d.Type, d)
145 return d.Type
146 }
147
148 // Fast-path: check the cache for whether this ExtensionType has already
149 // been converted from a legacy descriptor.
150 dk := extensionDescKeyOf(d)
151 if t, ok := extensionTypeCache.Load(dk); ok {
152 return t.(pref.ExtensionType)
Joe Tsai08e00302018-11-26 22:32:06 -0800153 }
154
155 // Derive basic field information from the struct tag.
156 t := reflect.TypeOf(d.ExtensionType)
157 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
158 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
159 if isOptional || isRepeated {
160 t = t.Elem()
161 }
162 f := ptag.Unmarshal(d.Tag, t)
163
164 // Construct a v2 ExtensionType.
165 conv := pvalue.NewLegacyConverter(t, f.Kind, Export{})
166 xd, err := ptype.NewExtension(&ptype.StandaloneExtension{
167 FullName: pref.FullName(d.Name),
168 Number: pref.FieldNumber(d.Field),
169 Cardinality: f.Cardinality,
170 Kind: f.Kind,
171 Default: f.Default,
172 Options: f.Options,
173 EnumType: conv.EnumType,
174 MessageType: conv.MessageType,
Herbie Ong2b0bba82018-12-20 12:56:42 -0800175 ExtendedType: pimpl.Export{}.MessageTypeOf(d.ExtendedType),
Joe Tsai08e00302018-11-26 22:32:06 -0800176 })
177 if err != nil {
178 panic(err)
179 }
Herbie Ong2b0bba82018-12-20 12:56:42 -0800180 var zv interface{}
181 switch xd.Kind() {
182 case pref.EnumKind, pref.MessageKind, pref.GroupKind:
183 zv = reflect.Zero(t).Interface()
184 }
185 xt := pimpl.Export{}.ExtensionTypeOf(xd, zv)
Joe Tsai08e00302018-11-26 22:32:06 -0800186
Joe Tsai62517cc2018-12-04 14:00:01 -0800187 // Cache the conversion for both directions.
188 extensionDescCache.Store(xt, d)
189 extensionTypeCache.Store(dk, xt)
190 return xt
Joe Tsai08e00302018-11-26 22:32:06 -0800191}
192
Joe Tsai6dbffb72018-12-04 14:06:19 -0800193// extensionTypeOf returns a protoreflect.ExtensionType where the GoType
Joe Tsai08e00302018-11-26 22:32:06 -0800194// is the underlying v1 Go type instead of the wrapper types used to present
195// v1 Go types as if they satisfied the v2 API.
196//
197// This function is only valid if xd.Kind is an enum or message.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800198func extensionTypeOf(xd pref.ExtensionDescriptor, t reflect.Type) pref.ExtensionType {
Joe Tsai08e00302018-11-26 22:32:06 -0800199 // Step 1: Create an ExtensionType where GoType is the wrapper type.
200 conv := pvalue.NewLegacyConverter(t, xd.Kind(), Export{})
201 xt := ptype.GoExtension(xd, conv.EnumType, conv.MessageType)
202
203 // Step 2: Wrap ExtensionType such that GoType presents the legacy Go type.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800204 xt2 := &extensionType{ExtensionType: xt}
Joe Tsai08e00302018-11-26 22:32:06 -0800205 if xd.Cardinality() != pref.Repeated {
206 xt2.typ = t
Joe Tsaid18bd312019-01-09 03:23:55 -0800207 xt2.new = func() pref.Value {
208 return xt.New()
Joe Tsai08e00302018-11-26 22:32:06 -0800209 }
210 xt2.valueOf = func(v interface{}) pref.Value {
211 if reflect.TypeOf(v) != xt2.typ {
212 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
213 }
214 if xd.Kind() == pref.EnumKind {
215 return xt.ValueOf(Export{}.EnumOf(v))
216 } else {
Joe Tsai22b1ebd2019-03-11 13:45:14 -0700217 return xt.ValueOf(Export{}.MessageOf(v).Interface())
Joe Tsai08e00302018-11-26 22:32:06 -0800218 }
219 }
220 xt2.interfaceOf = func(v pref.Value) interface{} {
221 return xt.InterfaceOf(v).(pvalue.Unwrapper).ProtoUnwrap()
222 }
223 } else {
224 xt2.typ = reflect.PtrTo(reflect.SliceOf(t))
Joe Tsaid18bd312019-01-09 03:23:55 -0800225 xt2.new = func() pref.Value {
226 v := reflect.New(xt2.typ.Elem()).Interface()
227 return pref.ValueOf(pvalue.ListOf(v, conv))
Joe Tsai08e00302018-11-26 22:32:06 -0800228 }
229 xt2.valueOf = func(v interface{}) pref.Value {
230 if reflect.TypeOf(v) != xt2.typ {
231 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
232 }
233 return pref.ValueOf(pvalue.ListOf(v, conv))
234 }
235 xt2.interfaceOf = func(pv pref.Value) interface{} {
236 v := pv.List().(pvalue.Unwrapper).ProtoUnwrap()
237 if reflect.TypeOf(v) != xt2.typ {
238 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
239 }
240 return v
241 }
242 }
243 return xt2
244}
245
Joe Tsai6dbffb72018-12-04 14:06:19 -0800246type extensionType struct {
Joe Tsai08e00302018-11-26 22:32:06 -0800247 pref.ExtensionType
248 typ reflect.Type
Joe Tsaid18bd312019-01-09 03:23:55 -0800249 new func() pref.Value
Joe Tsai08e00302018-11-26 22:32:06 -0800250 valueOf func(interface{}) pref.Value
251 interfaceOf func(pref.Value) interface{}
252}
253
Joe Tsai6dbffb72018-12-04 14:06:19 -0800254func (x *extensionType) GoType() reflect.Type { return x.typ }
Joe Tsaid18bd312019-01-09 03:23:55 -0800255func (x *extensionType) New() pref.Value { return x.new() }
Joe Tsai6dbffb72018-12-04 14:06:19 -0800256func (x *extensionType) ValueOf(v interface{}) pref.Value { return x.valueOf(v) }
257func (x *extensionType) InterfaceOf(v pref.Value) interface{} { return x.interfaceOf(v) }
Joe Tsaib3960a72018-12-05 10:35:35 -0800258func (x *extensionType) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, x) }