/
embeds.go
361 lines (341 loc) · 10.5 KB
/
embeds.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
// Copyright (c) 2018, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package kit
import (
"log"
"reflect"
"strings"
)
// This file contains helpful functions for dealing with embedded structs, in
// the reflect system
// FlatFieldsTypeFunc calls a function on all the primary fields of a given
// struct type, including those on anonymous embedded structs that this struct
// has, passing the current (embedded) type and StructField -- effectively
// flattens the reflect field list -- if fun returns false then iteration
// stops -- overall rval is false if iteration was stopped or there was an
// error (logged), true otherwise
func FlatFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool {
typ = NonPtrType(typ)
if typ.Kind() != reflect.Struct {
log.Printf("kit.FlatFieldsTypeFunc: Must call on a struct type, not: %v\n", typ)
return false
}
rval := true
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.Type.Kind() == reflect.Struct && f.Anonymous {
rval = FlatFieldsTypeFunc(f.Type, fun) // no err here
if !rval {
break
}
} else {
rval = fun(typ, f)
if !rval {
break
}
}
}
return rval
}
// AllFieldsTypeFunc calls a function on all the fields of a given struct type,
// including those on *any* embedded structs that this struct has -- if fun
// returns false then iteration stops -- overall rval is false if iteration
// was stopped or there was an error (logged), true otherwise.
func AllFieldsTypeFunc(typ reflect.Type, fun func(typ reflect.Type, field reflect.StructField) bool) bool {
typ = NonPtrType(typ)
if typ.Kind() != reflect.Struct {
log.Printf("kit.AllFieldsTypeFunc: Must call on a struct type, not: %v\n", typ)
return false
}
rval := true
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.Type.Kind() == reflect.Struct {
rval = AllFieldsTypeFunc(f.Type, fun) // no err here
if !rval {
break
}
} else {
rval = fun(typ, f)
if !rval {
break
}
}
}
return rval
}
// FlatFieldsValueFunc calls a function on all the primary fields of a
// given struct value (must pass a pointer to the struct) including those on
// anonymous embedded structs that this struct has, passing the current
// (embedded) type and StructField -- effectively flattens the reflect field
// list
func FlatFieldsValueFunc(stru any, fun func(stru any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool) bool {
vv := reflect.ValueOf(stru)
if stru == nil || vv.Kind() != reflect.Ptr {
log.Printf("kit.FlatFieldsValueFunc: must pass a non-nil pointer to the struct: %v\n", stru)
return false
}
v := NonPtrValue(vv)
if !v.IsValid() {
return true
}
typ := v.Type()
if typ.Kind() != reflect.Struct {
// log.Printf("kit.FlatFieldsValueFunc: non-pointer type is not a struct: %v\n", typ.String())
return false
}
rval := true
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
vf := v.Field(i)
if !vf.CanInterface() {
continue
}
vfi := vf.Interface()
if vfi == stru {
continue
}
if f.Type.Kind() == reflect.Struct && f.Anonymous {
// key to take addr here so next level is addressable
rval = FlatFieldsValueFunc(PtrValue(vf).Interface(), fun)
if !rval {
break
}
} else {
rval = fun(vfi, typ, f, vf)
if !rval {
break
}
}
}
return rval
}
// FlatFields returns a slice list of all the StructField type information for
// fields of given type and any embedded types -- returns nil on error
// (logged)
func FlatFields(typ reflect.Type) []reflect.StructField {
ff := make([]reflect.StructField, 0)
falseErr := FlatFieldsTypeFunc(typ, func(typ reflect.Type, field reflect.StructField) bool {
ff = append(ff, field)
return true
})
if falseErr == false {
return nil
}
return ff
}
// AllFields returns a slice list of all the StructField type information for
// all elemental fields of given type and all embedded types -- returns nil on
// error (logged)
func AllFields(typ reflect.Type) []reflect.StructField {
ff := make([]reflect.StructField, 0)
falseErr := AllFieldsTypeFunc(typ, func(typ reflect.Type, field reflect.StructField) bool {
ff = append(ff, field)
return true
})
if falseErr == false {
return nil
}
return ff
}
// AllFieldsN returns number of elemental fields in given type
func AllFieldsN(typ reflect.Type) int {
n := 0
falseErr := AllFieldsTypeFunc(typ, func(typ reflect.Type, field reflect.StructField) bool {
n++
return true
})
if falseErr == false {
return 0
}
return n
}
// FlatFieldsVals returns a slice list of all the field reflect.Value's for
// fields of given struct (must pass a pointer to the struct) and any of its
// embedded structs -- returns nil on error (logged)
func FlatFieldVals(stru any) []reflect.Value {
ff := make([]reflect.Value, 0)
falseErr := FlatFieldsValueFunc(stru, func(stru any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool {
ff = append(ff, fieldVal)
return true
})
if falseErr == false {
return nil
}
return ff
}
// FlatFieldInterfaces returns a slice list of all the field interface{}
// values *as pointers to the field value* (i.e., calling Addr() on the Field
// Value) for fields of given struct (must pass a pointer to the struct) and
// any of its embedded structs -- returns nil on error (logged)
func FlatFieldInterfaces(stru any) []any {
ff := make([]any, 0)
falseErr := FlatFieldsValueFunc(stru, func(stru any, typ reflect.Type, field reflect.StructField, fieldVal reflect.Value) bool {
ff = append(ff, PtrValue(fieldVal).Interface())
return true
})
if falseErr == false {
return nil
}
return ff
}
// FlatFieldByName returns field in type or embedded structs within type, by
// name -- native function already does flat version, so this is just for
// reference and consistency
func FlatFieldByName(typ reflect.Type, nm string) (reflect.StructField, bool) {
return typ.FieldByName(nm)
}
// FieldByPath returns field in type or embedded structs within type, by a
// dot-separated path -- finds field by name for each level of the path, and
// recurses.
func FieldByPath(typ reflect.Type, path string) (reflect.StructField, bool) {
pels := strings.Split(path, ".")
ctyp := typ
plen := len(pels)
for i, pe := range pels {
fld, ok := ctyp.FieldByName(pe)
if !ok {
log.Printf("kit.FieldByPath: field: %v not found in type: %v, starting from path: %v, in type: %v\n", pe, ctyp.String(), path, typ.String())
return fld, false
}
if i == plen-1 {
return fld, true
}
ctyp = fld.Type
}
return reflect.StructField{}, false
}
// FieldValueByPath returns field interface in type or embedded structs within
// type, by a dot-separated path -- finds field by name for each level of the
// path, and recurses.
func FieldValueByPath(stru any, path string) (reflect.Value, bool) {
pels := strings.Split(path, ".")
sval := reflect.ValueOf(stru)
cval := sval
typ := sval.Type()
ctyp := typ
plen := len(pels)
for i, pe := range pels {
_, ok := ctyp.FieldByName(pe)
if !ok {
log.Printf("kit.FieldValueByPath: field: %v not found in type: %v, starting from path: %v, in type: %v\n", pe, cval.Type().String(), path, typ.String())
return cval, false
}
fval := cval.FieldByName(pe)
if i == plen-1 {
return fval, true
}
cval = fval
ctyp = fval.Type()
}
return reflect.Value{}, false
}
// FlatFieldTag returns given tag value in field in type or embedded structs
// within type, by name -- empty string if not set or field not found
func FlatFieldTag(typ reflect.Type, nm, tag string) string {
fld, ok := typ.FieldByName(nm)
if !ok {
return ""
}
return fld.Tag.Get(tag)
}
// FlatFieldValueByName finds field in object and embedded objects, by name,
// returning reflect.Value of field -- native version of Value function
// already does flat find, so this just provides a convenient wrapper
func FlatFieldValueByName(stru any, nm string) reflect.Value {
vv := reflect.ValueOf(stru)
if stru == nil || vv.Kind() != reflect.Ptr {
log.Printf("kit.FlatFieldsValueFunc: must pass a non-nil pointer to the struct: %v\n", stru)
return reflect.Value{}
}
v := NonPtrValue(vv)
return v.FieldByName(nm)
}
// FlatFieldInterfaceByName finds field in object and embedded objects, by
// name, returning interface{} to pointer of field, or nil if not found
func FlatFieldInterfaceByName(stru any, nm string) any {
ff := FlatFieldValueByName(stru, nm)
if !ff.IsValid() {
return nil
}
return PtrValue(ff).Interface()
}
// TypeEmbeds checks if given type embeds another type, at any level of
// recursive embedding (including being the type itself)
func TypeEmbeds(typ, embed reflect.Type) bool {
typ = NonPtrType(typ)
embed = NonPtrType(embed)
if typ == embed {
return true
}
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.Type.Kind() == reflect.Struct && f.Anonymous {
// fmt.Printf("typ %v anon struct %v\n", typ.Name(), f.Name)
if f.Type == embed {
return true
}
return TypeEmbeds(f.Type, embed)
}
}
return false
}
// Embed returns the embedded struct of given type within given struct
func Embed(stru any, embed reflect.Type) any {
if IfaceIsNil(stru) {
return nil
}
v := NonPtrValue(reflect.ValueOf(stru))
typ := v.Type()
if typ == embed {
return PtrValue(v).Interface()
}
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.Type.Kind() == reflect.Struct && f.Anonymous { // anon only avail on StructField fm typ
vf := v.Field(i)
vfpi := PtrValue(vf).Interface()
if f.Type == embed {
return vfpi
}
rv := Embed(vfpi, embed)
if rv != nil {
return rv
}
}
}
return nil
}
// EmbedImplements checks if given type implements given interface, or
// it embeds a type that does so -- must pass a type constructed like this:
// reflect.TypeOf((*gi.Node2D)(nil)).Elem() or just reflect.TypeOf(ki.BaseIface())
func EmbedImplements(typ, iface reflect.Type) bool {
if iface.Kind() != reflect.Interface {
log.Printf("kit.TypeRegistry EmbedImplements -- type is not an interface: %v\n", iface)
return false
}
if typ.Implements(iface) {
return true
}
if reflect.PtrTo(typ).Implements(iface) { // typically need the pointer type to impl
return true
}
typ = NonPtrType(typ)
if typ.Implements(iface) { // try it all possible ways..
return true
}
if typ.Kind() != reflect.Struct {
return false
}
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if f.Type.Kind() == reflect.Struct && f.Anonymous {
rv := EmbedImplements(f.Type, iface)
if rv {
return true
}
}
}
return false
}