-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.go
More file actions
113 lines (102 loc) · 2.53 KB
/
methods.go
File metadata and controls
113 lines (102 loc) · 2.53 KB
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
package dscope
import (
"errors"
"fmt"
"reflect"
)
func Methods(objects ...any) (ret []any) {
visitedTypes := make(map[reflect.Type]bool)
var extend func(reflect.Value)
extend = func(v reflect.Value) {
if !v.IsValid() {
panic(errors.Join(
fmt.Errorf("invalid value"),
ErrBadArgument,
))
}
// nil interface
if v.Kind() == reflect.Interface && v.IsNil() {
panic(errors.Join(
fmt.Errorf("invalid value: nil interface %v", v.Type()),
ErrBadArgument,
))
}
t := v.Type()
if visitedTypes[t] {
return
}
visitedTypes[t] = true
if t.Kind() == reflect.Pointer && v.IsNil() {
// If it's a pointer chain eventually to an interface that's nil, we can't construct.
base := t
for base.Kind() == reflect.Pointer {
base = base.Elem()
}
if base.Kind() == reflect.Interface {
panic(errors.Join(
fmt.Errorf("invalid value: nil pointer to interface %v", t),
ErrBadArgument,
))
}
// Construct concrete object for typed nil pointers like (*MyStruct)(nil)
v = reflect.New(t.Elem())
}
// method sets
for i := range v.NumMethod() {
ret = append(ret, v.Method(i).Interface())
}
// from fields
for t.Kind() == reflect.Pointer {
// deref
t = t.Elem()
if v.IsNil() {
// Allocate new instance for nil pointers to avoid panic on Elem()
v = reflect.New(t).Elem()
} else {
v = v.Elem()
}
if t.Kind() == reflect.Pointer {
// Collect methods from intermediate pointers (e.g. *T when we started with **T)
for i := range v.NumMethod() {
ret = append(ret, v.Method(i).Interface())
}
}
}
if t.Kind() == reflect.Struct {
for i := range t.NumField() {
field := t.Field(i)
if field.PkgPath != "" {
continue
}
if field.Type.Implements(isModuleType) {
fv := v.Field(i)
if fv.Kind() == reflect.Struct {
if fv.CanAddr() {
extend(fv.Addr())
} else {
// For non-addressable struct fields (e.g. when the parent is passed by value),
// we create an addressable copy to ensure methods with pointer receivers are found.
ptr := reflect.New(fv.Type())
ptr.Elem().Set(fv)
extend(ptr)
}
} else {
extend(fv)
}
}
}
}
}
for _, object := range objects {
v := reflect.ValueOf(object)
if v.IsValid() && v.Kind() == reflect.Struct {
// For root structs passed by value, create an addressable copy
// to ensure pointer receiver methods are discovered.
ptr := reflect.New(v.Type())
ptr.Elem().Set(v)
v = ptr
}
extend(v)
}
return
}