-
Notifications
You must be signed in to change notification settings - Fork 242
/
conversions.go
354 lines (304 loc) · 9.43 KB
/
conversions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package kernel
import (
"reflect"
"time"
"github.com/aws/jsii-runtime-go/internal/api"
)
var (
anyType = reflect.TypeOf((*interface{})(nil)).Elem()
)
// CastAndSetToPtr accepts a pointer to any type and attempts to cast the value
// argument to be the same type. Then it sets the value of the pointer element
// to be the newly cast data. This is used to cast payloads from JSII to
// expected return types for Get and Invoke functions.
func (c *Client) CastAndSetToPtr(ptr interface{}, data interface{}) {
ptrVal := reflect.ValueOf(ptr).Elem()
dataVal := reflect.ValueOf(data)
c.castAndSetToPtr(ptrVal, dataVal)
}
// castAndSetToPtr is the same as CastAndSetToPtr except it operates on the
// reflect.Value representation of the pointer and data.
func (c *Client) castAndSetToPtr(ptr reflect.Value, data reflect.Value) {
if !data.IsValid() {
// data will not be valid if was made from a nil value, as there would
// not have been enough type information available to build a valid
// reflect.Value. In such cases, we must craft the correctly-typed zero
// value ourselves.
data = reflect.Zero(ptr.Type())
} else if ptr.Kind() == reflect.Ptr && ptr.IsNil() {
// if ptr is a Pointer type and data is valid, initialize a non-nil pointer
// type. Otherwise inner value is not-settable upon recursion. See third
// law of reflection.
// https://blog.golang.org/laws-of-reflection
ptr.Set(reflect.New(ptr.Type().Elem()))
c.castAndSetToPtr(ptr.Elem(), data)
return
} else if data.Kind() == reflect.Interface && !data.IsNil() {
// If data is a non-nil interface, unwrap it to get it's dynamic value
// type sorted out, so that further calls in this method don't have to
// worry about this edge-case when reasoning on kinds.
data = reflect.ValueOf(data.Interface())
}
if ref, isRef := castValToRef(data); isRef {
// If return data is a jsii struct passed by reference, de-reference it all.
if fields, _, isStruct := c.Types().StructFields(ptr.Type()); isStruct {
for _, field := range fields {
got, err := c.Get(GetProps{
Property: field.Tag.Get("json"),
ObjRef: ref,
})
if err != nil {
panic(err)
}
fieldVal := ptr.FieldByIndex(field.Index)
c.castAndSetToPtr(fieldVal, reflect.ValueOf(got.Value))
}
return
}
// If it's currently tracked, return the current instance
if object, ok := c.objects.GetObjectAs(ref.InstanceID, ptr.Type()); ok {
ptr.Set(object)
return
}
// If return data is jsii object references, add to objects table.
if err := c.Types().InitJsiiProxy(ptr); err == nil {
if err = c.RegisterInstance(ptr, ref); err != nil {
panic(err)
}
} else {
panic(err)
}
return
}
if enumref, isEnum := castValToEnumRef(data); isEnum {
member, err := c.Types().EnumMemberForEnumRef(enumref)
if err != nil {
panic(err)
}
ptr.Set(reflect.ValueOf(member))
return
}
if date, isDate := castValToDate(data); isDate {
ptr.Set(reflect.ValueOf(date))
return
}
// maps
if m, isMap := c.castValToMap(data, ptr.Type()); isMap {
ptr.Set(m)
return
}
// arrays
if data.Kind() == reflect.Slice {
len := data.Len()
var slice reflect.Value
if ptr.Kind() == reflect.Slice {
slice = reflect.MakeSlice(ptr.Type(), len, len)
} else {
slice = reflect.MakeSlice(reflect.SliceOf(anyType), len, len)
}
// If return type is a slice, recursively cast elements
for i := 0; i < len; i++ {
c.castAndSetToPtr(slice.Index(i), data.Index(i))
}
ptr.Set(slice)
return
}
ptr.Set(data)
}
// Accepts pointers to structs that implement interfaces and searches for an
// existing object reference in the kernel. If it exists, it casts it to an
// objref for the runtime. Recursively casts types that may contain nested
// object references.
func (c *Client) CastPtrToRef(dataVal reflect.Value) interface{} {
if !dataVal.IsValid() {
// dataVal is a 0-value, meaning we have no value available... We return
// this to JavaScript as a "null" value.
return nil
}
if (dataVal.Kind() == reflect.Interface || dataVal.Kind() == reflect.Ptr) && dataVal.IsNil() {
return nil
}
// In case we got a time.Time value (or pointer to one).
if wireDate, isDate := castPtrToDate(dataVal); isDate {
return wireDate
}
switch dataVal.Kind() {
case reflect.Map:
result := api.WireMap{MapData: make(map[string]interface{})}
iter := dataVal.MapRange()
for iter.Next() {
key := iter.Key().String()
val := iter.Value()
result.MapData[key] = c.CastPtrToRef(val)
}
return result
case reflect.Interface, reflect.Ptr:
if valref, valHasRef := c.FindObjectRef(dataVal); valHasRef {
return valref
}
// In case we got a pointer to a map, slice, enum, ...
if elem := reflect.Indirect(dataVal.Elem()); elem.Kind() != reflect.Struct {
return c.CastPtrToRef(elem)
}
if dataVal.Elem().Kind() == reflect.Struct {
elemVal := dataVal.Elem()
if fields, fqn, isStruct := c.Types().StructFields(elemVal.Type()); isStruct {
data := make(map[string]interface{})
for _, field := range fields {
fieldVal := elemVal.FieldByIndex(field.Index)
if (fieldVal.Kind() == reflect.Ptr || fieldVal.Kind() == reflect.Interface) && fieldVal.IsNil() {
continue
}
key := field.Tag.Get("json")
data[key] = c.CastPtrToRef(fieldVal)
}
return api.WireStruct{
StructDescriptor: api.StructDescriptor{
FQN: fqn,
Fields: data,
},
}
}
}
if ref, err := c.ManageObject(dataVal); err != nil {
panic(err)
} else {
return ref
}
case reflect.Slice:
refs := make([]interface{}, dataVal.Len())
for i := 0; i < dataVal.Len(); i++ {
refs[i] = c.CastPtrToRef(dataVal.Index(i))
}
return refs
case reflect.String:
if enumRef, isEnumRef := c.Types().TryRenderEnumRef(dataVal); isEnumRef {
return enumRef
}
}
return dataVal.Interface()
}
// castPtrToDate obtains an api.WireDate from the provided reflect.Value if it
// represents a time.Time or *time.Time value. It accepts both a pointer and
// direct value as a convenience (when passing time.Time through an interface{}
// parameter, having to unwrap it as a pointer is annoying and unneeded).
func castPtrToDate(data reflect.Value) (wireDate api.WireDate, ok bool) {
var timestamp *time.Time
if timestamp, ok = data.Interface().(*time.Time); !ok {
var val time.Time
if val, ok = data.Interface().(time.Time); ok {
timestamp = &val
}
}
if ok {
wireDate.Timestamp = timestamp.Format(time.RFC3339Nano)
}
return
}
func castValToRef(data reflect.Value) (ref api.ObjectRef, ok bool) {
if data.Kind() == reflect.Map {
for _, k := range data.MapKeys() {
// Finding values type requires extracting from reflect.Value
// otherwise .Kind() returns `interface{}`
v := reflect.ValueOf(data.MapIndex(k).Interface())
if k.Kind() != reflect.String {
continue
}
switch k.String() {
case "$jsii.byref":
if v.Kind() != reflect.String {
ok = false
return
}
ref.InstanceID = v.String()
ok = true
case "$jsii.interfaces":
if v.Kind() != reflect.Slice {
continue
}
ifaces := make([]api.FQN, v.Len())
for i := 0; i < v.Len(); i++ {
e := reflect.ValueOf(v.Index(i).Interface())
if e.Kind() != reflect.String {
ok = false
return
}
ifaces[i] = api.FQN(e.String())
}
ref.Interfaces = ifaces
}
}
}
return ref, ok
}
// TODO: This should return a time.Time instead
func castValToDate(data reflect.Value) (date time.Time, ok bool) {
if data.Kind() == reflect.Map {
for _, k := range data.MapKeys() {
v := reflect.ValueOf(data.MapIndex(k).Interface())
if k.Kind() == reflect.String && k.String() == "$jsii.date" && v.Kind() == reflect.String {
var err error
date, err = time.Parse(time.RFC3339Nano, v.String())
ok = (err == nil)
break
}
}
}
return
}
func castValToEnumRef(data reflect.Value) (enum api.EnumRef, ok bool) {
ok = false
if data.Kind() == reflect.Map {
for _, k := range data.MapKeys() {
// Finding values type requires extracting from reflect.Value
// otherwise .Kind() returns `interface{}`
v := reflect.ValueOf(data.MapIndex(k).Interface())
if k.Kind() == reflect.String && k.String() == "$jsii.enum" && v.Kind() == reflect.String {
enum.MemberFQN = v.String()
ok = true
break
}
}
}
return
}
// castValToMap attempts converting the provided jsii wire value to a
// go map. This recognizes the "$jsii.map" object and does the necessary
// recursive value conversion.
func (c *Client) castValToMap(data reflect.Value, mapType reflect.Type) (m reflect.Value, ok bool) {
ok = false
if data.Kind() != reflect.Map || data.Type().Key().Kind() != reflect.String {
return
}
if mapType.Kind() == reflect.Map && mapType.Key().Kind() != reflect.String {
return
}
if mapType == anyType {
mapType = reflect.TypeOf((map[string]interface{})(nil))
}
dataIter := data.MapRange()
for dataIter.Next() {
key := dataIter.Key().String()
if key != "$jsii.map" {
continue
}
// Finding value type requries extracting from reflect.Value
// otherwise .Kind() returns `interface{}`
val := reflect.ValueOf(dataIter.Value().Interface())
if val.Kind() != reflect.Map {
return
}
ok = true
m = reflect.MakeMap(mapType)
iter := val.MapRange()
for iter.Next() {
val := iter.Value()
// Note: reflect.New(t) returns a pointer to a newly allocated t
convertedVal := reflect.New(mapType.Elem()).Elem()
c.castAndSetToPtr(convertedVal, val)
m.SetMapIndex(iter.Key(), convertedVal)
}
return
}
return
}