forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.go
434 lines (400 loc) · 11.9 KB
/
reflect.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package ravendb
import (
"fmt"
"reflect"
"strings"
)
// functionality related to reflection
func isPtrStruct(t reflect.Type) (reflect.Type, bool) {
if t.Kind() == reflect.Ptr && t.Elem() != nil && t.Elem().Kind() == reflect.Struct {
return t, true
}
return nil, false
}
func isPtrMapStringToPtrStruct(tp reflect.Type) (reflect.Type, bool) {
if tp.Kind() != reflect.Ptr {
return nil, false
}
tp = tp.Elem()
if tp.Kind() != reflect.Map {
return nil, false
}
if tp.Key().Kind() != reflect.String {
return nil, false
}
return isPtrStruct(tp.Elem())
}
func isMapStringToPtrStruct(tp reflect.Type) (reflect.Type, bool) {
if tp.Kind() != reflect.Map {
return nil, false
}
if tp.Key().Kind() != reflect.String {
return nil, false
}
return isPtrStruct(tp.Elem())
}
// Go port of com.google.common.base.Defaults to make porting Java easier
func getDefaultValueForType(clazz reflect.Type) interface{} {
rv := reflect.Zero(clazz)
return rv.Interface()
}
// GetFullTypeName returns fully qualified (including package) name of the type,
// after traversing pointers.
// e.g. for struct Foo in main package, the type of Foo and *Foo is main.Foo
func getFullTypeName(v interface{}) string {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
typ := rv.Type()
return typ.String()
}
// getShortTypeName returns a short (not including package) name of the type,
// after traversing pointers.
// e.g. for struct Foo, the type of Foo and *Foo is "Foo"
// Note: this emulates Java's operator over-loading to support
// DefaultGetCollectionName.
func getShortTypeNameForEntityOrType(v interface{}) string {
if typ, ok := v.(reflect.Type); ok {
return getShortTypeNameForType(typ)
}
return getShortTypeNameForEntity(v)
}
func getShortTypeNameForEntity(v interface{}) string {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
typ := rv.Type()
return getShortTypeNameForType(typ)
}
func getShortTypeNameForType(typ reflect.Type) string {
// for *Foo and **Foo the name we want to return is Foo
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
return typ.Name()
}
// identity property is field of type string with name ID
func getIdentityProperty(typ reflect.Type) string {
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
return ""
}
field, ok := typ.FieldByName("ID")
if !ok || field.Type.Kind() != reflect.String {
return ""
}
return "ID"
}
func isTypePrimitive(t reflect.Type) bool {
kind := t.Kind()
switch kind {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8,
reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64, reflect.String:
return true
case reflect.Ptr:
return false
// TODO: not all of those we should support
case reflect.Array, reflect.Interface, reflect.Map, reflect.Slice, reflect.Struct:
panic("NYI")
}
return false
}
func getStructTypeOfReflectValue(rv reflect.Value) (reflect.Type, bool) {
if rv.Type().Kind() == reflect.Ptr {
rv = rv.Elem()
}
typ := rv.Type()
if typ.Kind() == reflect.Struct {
return typ, true
}
return typ, false
}
func getStructTypeOfValue(v interface{}) (reflect.Type, bool) {
rv := reflect.ValueOf(v)
return getStructTypeOfReflectValue(rv)
}
// if typ is ptr-to-struct, return as is
// if typ is ptr-to-ptr-to-struct, returns ptr-to-struct
// otherwise returns nil
func fixUpStructType(typ reflect.Type) reflect.Type {
if typ.Kind() != reflect.Ptr {
return nil
}
subtype := typ.Elem()
if subtype.Kind() == reflect.Struct {
return typ
}
if subtype.Kind() != reflect.Ptr {
return nil
}
if subtype.Elem().Kind() == reflect.Struct {
return subtype
}
return nil
}
func convertFloat64ToType(v float64, typ reflect.Type) interface{} {
switch typ.Kind() {
case reflect.Float32:
return float32(v)
case reflect.Float64:
return v
case reflect.Int:
return int(v)
case reflect.Int8:
return int8(v)
case reflect.Int16:
return int16(v)
case reflect.Int32:
return int32(v)
case reflect.Int64:
return int64(v)
case reflect.Uint:
return uint(v)
case reflect.Uint8:
return uint8(v)
case reflect.Uint16:
return uint16(v)
case reflect.Uint32:
return uint32(v)
case reflect.Uint64:
return uint64(v)
}
panicIf(true, "don't know how to convert value of type %T to reflect type %s", v, typ.Name())
return int(0)
}
func treeToValue(typ reflect.Type, js interface{}) (interface{}, error) {
// TODO: should also handle primitive types
switch v := js.(type) {
case string:
if typ.Kind() == reflect.String {
return js, nil
}
panicIf(true, "don't know how to convert value of type %T to reflect type %s", js, typ.Name())
case float64:
return convertFloat64ToType(v, typ), nil
case bool:
panicIf(true, "don't know how to convert value of type %T to reflect type %s", js, typ.Name())
case []interface{}:
panicIf(true, "don't know how to convert value of type %T to reflect type %s", js, typ.Name())
case map[string]interface{}:
return makeStructFromJSONMap(typ, v)
}
panicIf(true, "don't know how to convert value of type %v to reflect type %s", js, typ.Name())
return nil, fmt.Errorf("don't know how to convert value of type %v to reflect type %s", js, typ.Name())
}
// get name of struct field for json serialization
// empty string means we should skip this field
func getJSONFieldName(field reflect.StructField) string {
// skip unexported fields
if field.PkgPath != "" {
return ""
}
tag := field.Tag.Get("json")
// if no tag, use field name
if tag == "" {
return field.Name
}
// skip if explicitly marked as non-json serializable
// TODO: write tests for this
if tag == "-" {
return ""
}
// this could be "name,omitempty" etc.; extract just the name
if idx := strings.IndexByte(tag, ','); idx != -1 {
name := tag[:idx-1]
// if it's sth. like ",omitempty", use field name
// TODO: write tests for this
if name == "" {
return field.Name
}
return name
}
return tag
}
// FieldsFor returns names of all fields for the value of a struct type.
// They can be used in e.g. DocumentQuery.SelectFields:
// fields := ravendb.FieldsFor(&MyType{})
// q = q.SelectFields(fields...)
func FieldsFor(s interface{}) []string {
v := reflect.ValueOf(s)
// if pointer get the underlying element≤
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
panicIf(v.Kind() != reflect.Struct, "argument must be struct, we got %T", s)
t := v.Type()
var res []string
for i := 0; i < t.NumField(); i++ {
if name := getJSONFieldName(t.Field(i)); name != "" {
res = append(res, name)
}
}
return res
}
// given js value (most likely as map[string]interface{}) decode into res
func decodeJSONAsStruct(js interface{}, res interface{}) error {
d, err := jsonMarshal(js)
if err != nil {
return err
}
return jsonUnmarshal(d, res)
}
// given a json represented as map and type of a struct
func makeStructFromJSONMap(typ reflect.Type, js map[string]interface{}) (interface{}, error) {
if typ == reflect.TypeOf(map[string]interface{}{}) {
return js, nil
}
typ2 := fixUpStructType(typ)
if typ2 == nil {
return nil, newIllegalArgumentError("typ should be *<type> or *(*<type> but is %s", typ.String())
}
typ = typ2
// reflect.New() creates a pointer to type. if typ is already a pointer,
// we undo one level
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
rvNew := reflect.New(typ)
d, err := jsonMarshal(js)
if err != nil {
return nil, err
}
v := rvNew.Interface()
err = jsonUnmarshal(d, v)
if err != nil {
return nil, err
}
return v, nil
}
func dbglog(format string, args ...interface{}) string {
s := fmt.Sprintf(format, args...)
fmt.Println(s)
return s
}
// corresponds to ObjectMapper.convertValue()
// val is coming from JSON, so it can be string, bool, float64, []interface{}
// or map[string]interface{}
// TODO: not sure about nil
// for simple types (int, bool, string) it should be just pass-through
// for structs decode map[string]interface{} => struct using MakeStructFromJSONMap
func convertValue(val interface{}, clazz reflect.Type) (interface{}, error) {
// TODO: implement every possible type. Need more comprehensive tests
// to exercise those code paths
switch clazz.Kind() {
case reflect.String:
switch v := val.(type) {
case string:
return v, nil
default:
panicIf(true, "%s", dbglog("converting of type %T to string NYI", val))
}
case reflect.Int:
switch v := val.(type) {
case int:
return v, nil
case float64:
res := int(v)
return res, nil
default:
panicIf(true, "%s", dbglog("converting of type %T to reflect.Int NYI", val))
}
case reflect.Ptr:
clazz2 := clazz.Elem()
switch clazz2.Kind() {
case reflect.Struct:
valIn, ok := val.(map[string]interface{})
if !ok {
return nil, newRavenError("can't convert value of type '%s' to a struct", val)
}
v, err := makeStructFromJSONMap(clazz, valIn)
return v, err
default:
panicIf(true, "%s", dbglog("converting to pointer of '%s' NYI", clazz.Kind().String()))
}
default:
panicIf(true, "%s", dbglog("converting to %s NYI", clazz.Kind().String()))
}
return nil, newNotImplementedError("convertValue: NYI")
}
// m is a single-element map[string]*struct
// returns single map value
func getSingleMapValue(results interface{}) (interface{}, error) {
m := reflect.ValueOf(results)
if m.Type().Kind() != reflect.Map {
return nil, fmt.Errorf("results should be a map[string]*struct, is %s. tp: %s", m.Type().String(), m.Type().String())
}
mapKeyType := m.Type().Key()
if mapKeyType != stringType {
return nil, fmt.Errorf("results should be a map[string]*struct, is %s. tp: %s", m.Type().String(), m.Type().String())
}
mapElemPtrType := m.Type().Elem()
if mapElemPtrType.Kind() != reflect.Ptr {
return nil, fmt.Errorf("results should be a map[string]*struct, is %s. tp: %s", m.Type().String(), m.Type().String())
}
mapElemType := mapElemPtrType.Elem()
if mapElemType.Kind() != reflect.Struct {
return nil, fmt.Errorf("results should be a map[string]*struct, is %s. tp: %s", m.Type().String(), m.Type().String())
}
keys := m.MapKeys()
if len(keys) == 0 {
return nil, nil
}
if len(keys) != 1 {
return nil, fmt.Errorf("expected results to have only one element, has %d", len(keys))
}
v := m.MapIndex(keys[0])
return v.Interface(), nil
}
func checkIsPtrSlice(v interface{}, argName string) error {
if v == nil {
return newIllegalArgumentError("%s can't be nil", argName)
}
tp := reflect.TypeOf(v)
if tp.Kind() == reflect.Slice {
// more specific error message for common error of passing
// []<type> instead of *[]<type>
return newIllegalArgumentError("%s can't be of type %T, try *%T", argName, v, v)
}
if tp.Kind() != reflect.Ptr {
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
if tp.Elem().Kind() != reflect.Slice {
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
return nil
}
func checkIsPtrPtrStruct(v interface{}, argName string) error {
if v == nil {
return newIllegalArgumentError("%s can't be nil", argName)
}
tp := reflect.TypeOf(v)
if tp.Kind() == reflect.Struct {
// possibly a common mistake, so try to provide a helpful error message
typeGot := fmt.Sprintf("%T", v)
typeExpect := "**" + typeGot
return newIllegalArgumentError("%s can't be of type %s, try passing %s", argName, typeGot, typeExpect)
}
if tp.Kind() != reflect.Ptr {
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
if tp.Elem().Kind() == reflect.Struct {
// possibly a common mistake, so try to provide a helpful error message
typeGot := fmt.Sprintf("%T", v)
typeExpect := "*" + typeGot
return newIllegalArgumentError("%s can't be of type %s, try passing %s", argName, typeGot, typeExpect)
}
if tp.Elem().Kind() != reflect.Ptr {
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
// we only allow pointer to struct
if tp.Elem().Elem().Kind() == reflect.Struct {
return nil
}
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}