blob: 4a074d2480a49ef584248daff80a298f4ca8dffd [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 Tsaib3960a72018-12-05 10:35:35 -080015 pfmt "github.com/golang/protobuf/v2/internal/typefmt"
Joe Tsai08e00302018-11-26 22:32:06 -080016 pvalue "github.com/golang/protobuf/v2/internal/value"
17 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
18 ptype "github.com/golang/protobuf/v2/reflect/prototype"
19)
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.
60 mv := mt.New()
61 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,
175 ExtendedType: Export{}.MessageTypeOf(d.ExtendedType),
176 })
177 if err != nil {
178 panic(err)
179 }
180 xt := pimpl.Export{}.ExtensionTypeOf(xd, reflect.Zero(t).Interface())
Joe Tsai08e00302018-11-26 22:32:06 -0800181
Joe Tsai62517cc2018-12-04 14:00:01 -0800182 // Cache the conversion for both directions.
183 extensionDescCache.Store(xt, d)
184 extensionTypeCache.Store(dk, xt)
185 return xt
Joe Tsai08e00302018-11-26 22:32:06 -0800186}
187
Joe Tsai6dbffb72018-12-04 14:06:19 -0800188// extensionTypeOf returns a protoreflect.ExtensionType where the GoType
Joe Tsai08e00302018-11-26 22:32:06 -0800189// is the underlying v1 Go type instead of the wrapper types used to present
190// v1 Go types as if they satisfied the v2 API.
191//
192// This function is only valid if xd.Kind is an enum or message.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800193func extensionTypeOf(xd pref.ExtensionDescriptor, t reflect.Type) pref.ExtensionType {
Joe Tsai08e00302018-11-26 22:32:06 -0800194 // Step 1: Create an ExtensionType where GoType is the wrapper type.
195 conv := pvalue.NewLegacyConverter(t, xd.Kind(), Export{})
196 xt := ptype.GoExtension(xd, conv.EnumType, conv.MessageType)
197
198 // Step 2: Wrap ExtensionType such that GoType presents the legacy Go type.
Joe Tsai6dbffb72018-12-04 14:06:19 -0800199 xt2 := &extensionType{ExtensionType: xt}
Joe Tsai08e00302018-11-26 22:32:06 -0800200 if xd.Cardinality() != pref.Repeated {
201 xt2.typ = t
202 xt2.new = func() interface{} {
203 return xt.New().(pvalue.Unwrapper).ProtoUnwrap()
204 }
205 xt2.valueOf = func(v interface{}) pref.Value {
206 if reflect.TypeOf(v) != xt2.typ {
207 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
208 }
209 if xd.Kind() == pref.EnumKind {
210 return xt.ValueOf(Export{}.EnumOf(v))
211 } else {
212 return xt.ValueOf(Export{}.MessageOf(v))
213 }
214 }
215 xt2.interfaceOf = func(v pref.Value) interface{} {
216 return xt.InterfaceOf(v).(pvalue.Unwrapper).ProtoUnwrap()
217 }
218 } else {
219 xt2.typ = reflect.PtrTo(reflect.SliceOf(t))
220 xt2.new = func() interface{} {
221 return reflect.New(xt2.typ.Elem()).Interface()
222 }
223 xt2.valueOf = func(v interface{}) pref.Value {
224 if reflect.TypeOf(v) != xt2.typ {
225 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
226 }
227 return pref.ValueOf(pvalue.ListOf(v, conv))
228 }
229 xt2.interfaceOf = func(pv pref.Value) interface{} {
230 v := pv.List().(pvalue.Unwrapper).ProtoUnwrap()
231 if reflect.TypeOf(v) != xt2.typ {
232 panic(fmt.Sprintf("invalid type: got %T, want %v", v, xt2.typ))
233 }
234 return v
235 }
236 }
237 return xt2
238}
239
Joe Tsai6dbffb72018-12-04 14:06:19 -0800240type extensionType struct {
Joe Tsai08e00302018-11-26 22:32:06 -0800241 pref.ExtensionType
242 typ reflect.Type
243 new func() interface{}
244 valueOf func(interface{}) pref.Value
245 interfaceOf func(pref.Value) interface{}
246}
247
Joe Tsai6dbffb72018-12-04 14:06:19 -0800248func (x *extensionType) GoType() reflect.Type { return x.typ }
249func (x *extensionType) New() interface{} { return x.new() }
250func (x *extensionType) ValueOf(v interface{}) pref.Value { return x.valueOf(v) }
251func (x *extensionType) InterfaceOf(v pref.Value) interface{} { return x.interfaceOf(v) }
Joe Tsaib3960a72018-12-05 10:35:35 -0800252func (x *extensionType) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, x) }