This repository has been archived by the owner on May 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreflect.go
322 lines (259 loc) · 6.97 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
package sabre
import (
"fmt"
"reflect"
"strings"
)
var (
scopeType = reflect.TypeOf((*Scope)(nil)).Elem()
errorType = reflect.TypeOf((*error)(nil)).Elem()
)
// ValueOf converts a Go value to sabre Value type. If 'v' is already a Value
// type, it is returned as is. Primitive Go values like string, rune, int, float,
// bool are converted to the right sabre Value types. Functions are converted to
// the wrapper 'Fn' type. Value of type 'reflect.Type' will be wrapped as 'Type'
// which enables initializing a value of that type when invoked. All other types
// will be wrapped using 'Any' type.
func ValueOf(v interface{}) Value {
if v == nil {
return Nil{}
}
if val, isValue := v.(Value); isValue {
return val
}
if rt, ok := v.(reflect.Type); ok {
return Type{T: rt}
}
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Func:
return reflectFn(rv)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Int64(rv.Int())
case reflect.Float32, reflect.Float64:
return Float64(rv.Float())
case reflect.String:
return String(rv.String())
case reflect.Uint8:
return Character(rv.Uint())
case reflect.Bool:
return Bool(rv.Bool())
default:
// TODO: handle array & slice as list/vector.
return Any{V: rv}
}
}
// Any can be used to wrap arbitrary Go value into Sabre scope.
type Any struct{ V reflect.Value }
// Eval returns itself.
func (any Any) Eval(_ Scope) (Value, error) { return any, nil }
func (any Any) String() string { return fmt.Sprintf("Any{%v}", any.V) }
// Type represents the type value of a given value. Type also implements
// Value type.
type Type struct{ T reflect.Type }
// Eval returns the type value itself.
func (t Type) Eval(_ Scope) (Value, error) { return t, nil }
func (t Type) String() string { return fmt.Sprintf("%v", t.T) }
// Invoke creates zero value of the given type.
func (t Type) Invoke(scope Scope, args ...Value) (Value, error) {
if isKind(t.T, reflect.Interface, reflect.Chan, reflect.Func) {
return nil, fmt.Errorf("type '%s' cannot be initialized", t.T)
}
argVals, err := evalValueList(scope, args)
if err != nil {
return nil, err
}
switch t.T {
case reflect.TypeOf((*List)(nil)):
return &List{Values: argVals}, nil
case reflect.TypeOf(Vector{}):
return Vector{Values: argVals}, nil
case reflect.TypeOf(Set{}):
return Set{Values: Values(argVals).Uniq()}, nil
}
likeSeq := isKind(t.T, reflect.Slice, reflect.Array)
if likeSeq {
return Values(argVals), nil
}
return ValueOf(reflect.New(t.T).Elem().Interface()), nil
}
// reflectFn creates a wrapper Fn for the given Go function value using
// reflection.
func reflectFn(rv reflect.Value) *Fn {
fw := wrapFunc(rv)
return &Fn{
Args: fw.argNames(),
Variadic: rv.Type().IsVariadic(),
Func: func(scope Scope, args []Value) (_ Value, err error) {
defer func() {
if v := recover(); v != nil {
err = fmt.Errorf("panic: %v", v)
}
}()
args, err = evalValueList(scope, args)
if err != nil {
return nil, err
}
return fw.Call(scope, args...)
},
}
}
func wrapFunc(rv reflect.Value) *funcWrapper {
rt := rv.Type()
minArgs := rt.NumIn()
if rt.IsVariadic() {
minArgs = minArgs - 1
}
passScope := (minArgs > 0) && (rt.In(0) == scopeType)
lastOutIdx := rt.NumOut() - 1
returnsErr := lastOutIdx >= 0 && rt.Out(lastOutIdx) == errorType
if returnsErr {
lastOutIdx-- // ignore error value from return values
}
return &funcWrapper{
rv: rv,
rt: rt,
minArgs: minArgs,
passScope: passScope,
returnsErr: returnsErr,
lastOutIdx: lastOutIdx,
}
}
type funcWrapper struct {
rv reflect.Value
rt reflect.Type
passScope bool
minArgs int
returnsErr bool
lastOutIdx int
}
func (fw *funcWrapper) Call(scope Scope, vals ...Value) (Value, error) {
args := reflectValues(vals)
if fw.passScope {
args = append([]reflect.Value{reflect.ValueOf(scope)}, args...)
}
if err := fw.checkArgCount(len(args)); err != nil {
return nil, err
}
args, err := fw.convertTypes(args...)
if err != nil {
return nil, err
}
return fw.wrapReturns(fw.rv.Call(args)...)
}
func (fw *funcWrapper) argNames() []string {
cleanArgName := func(t reflect.Type) string {
return strings.Replace(t.String(), "sabre.", "", -1)
}
var argNames []string
i := 0
for ; i < fw.minArgs; i++ {
argNames = append(argNames, cleanArgName(fw.rt.In(i)))
}
if fw.rt.IsVariadic() {
argNames = append(argNames, cleanArgName(fw.rt.In(i).Elem()))
}
return argNames
}
func (fw *funcWrapper) convertTypes(args ...reflect.Value) ([]reflect.Value, error) {
var vals []reflect.Value
for i := 0; i < fw.rt.NumIn(); i++ {
if fw.rt.IsVariadic() && i == fw.rt.NumIn()-1 {
c, err := convertArgsTo(fw.rt.In(i).Elem(), args[i:]...)
if err != nil {
return nil, err
}
vals = append(vals, c...)
break
}
c, err := convertArgsTo(fw.rt.In(i), args[i])
if err != nil {
return nil, err
}
vals = append(vals, c...)
}
return vals, nil
}
func (fw *funcWrapper) checkArgCount(count int) error {
if count != fw.minArgs {
if fw.rt.IsVariadic() && count < fw.minArgs {
return fmt.Errorf(
"call requires at-least %d argument(s), got %d",
fw.minArgs, count,
)
} else if !fw.rt.IsVariadic() && count > fw.minArgs {
return fmt.Errorf(
"call requires exactly %d argument(s), got %d",
fw.minArgs, count,
)
}
}
return nil
}
func (fw *funcWrapper) wrapReturns(vals ...reflect.Value) (Value, error) {
if fw.rt.NumOut() == 0 {
return Nil{}, nil
}
if fw.returnsErr {
errIndex := fw.lastOutIdx + 1
if !vals[errIndex].IsNil() {
return nil, vals[errIndex].Interface().(error)
}
if fw.rt.NumOut() == 1 {
return Nil{}, nil
}
}
wrapped := sabreValues(vals[0 : fw.lastOutIdx+1])
if len(wrapped) == 1 {
return wrapped[0], nil
}
return Values(wrapped), nil
}
func convertArgsTo(expected reflect.Type, args ...reflect.Value) ([]reflect.Value, error) {
var converted []reflect.Value
for _, arg := range args {
actual := arg.Type()
switch {
case isAssignable(actual, expected):
converted = append(converted, arg)
case actual.ConvertibleTo(expected):
converted = append(converted, arg.Convert(expected))
default:
return args, fmt.Errorf(
"value of type '%s' cannot be converted to '%s'",
actual, expected,
)
}
}
return converted, nil
}
func isAssignable(from, to reflect.Type) bool {
return (from == to) || from.AssignableTo(to) ||
(to.Kind() == reflect.Interface && from.Implements(to))
}
func reflectValues(args []Value) []reflect.Value {
var rvs []reflect.Value
for _, arg := range args {
if any, ok := arg.(Any); ok {
rvs = append(rvs, any.V)
} else {
rvs = append(rvs, reflect.ValueOf(arg))
}
}
return rvs
}
func sabreValues(rvs []reflect.Value) []Value {
var vals []Value
for _, arg := range rvs {
vals = append(vals, ValueOf(arg.Interface()))
}
return vals
}
func isKind(rt reflect.Type, kinds ...reflect.Kind) bool {
for _, k := range kinds {
if k == rt.Kind() {
return true
}
}
return false
}