-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.go
More file actions
83 lines (71 loc) · 1.68 KB
/
functions.go
File metadata and controls
83 lines (71 loc) · 1.68 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
// Copyright (c) 2017, Paessler AG <support@paessler.com>
// All rights reserved.
package goeval
import (
"fmt"
"reflect"
)
type function func(arguments ...any) (any, error)
func toFunc(f any) function {
if f, ok := f.(func(arguments ...any) (any, error)); ok {
return f
}
fun := reflect.ValueOf(f)
t := fun.Type()
return func(args ...any) (any, error) {
var v any
in, err := createCallArguments(t, args)
if err != nil {
return nil, err
}
out := fun.Call(in)
r := make([]any, len(out))
for i, e := range out {
r[i] = e.Interface()
}
err = nil
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
if len(r) > 0 && t.Out(len(r)-1).Implements(errorInterface) {
if r[len(r)-1] != nil {
err = r[len(r)-1].(error)
}
r = r[0 : len(r)-1]
}
switch len(r) {
case 0:
v = nil
case 1:
v = r[0]
default:
v = r
}
return v, err
}
}
func createCallArguments(t reflect.Type, args []any) ([]reflect.Value, error) {
variadic := t.IsVariadic()
numIn := t.NumIn()
if (!variadic && len(args) != numIn) || (variadic && len(args) < numIn-1) {
return nil, fmt.Errorf("invalid number of parameters")
}
in := make([]reflect.Value, len(args))
var inType reflect.Type
for i, arg := range args {
if !variadic || i < numIn-1 {
inType = t.In(i)
} else if i == numIn-1 {
inType = t.In(numIn - 1).Elem()
}
argVal := reflect.ValueOf(arg)
if arg == nil || !argVal.Type().AssignableTo(inType) {
val, ok := reflectConvertTo(inType.Kind(), arg)
if !ok {
return nil, fmt.Errorf("expected type %s for parameter %d but got %T",
inType.String(), i, arg)
}
argVal = reflect.ValueOf(val)
}
in[i] = argVal
}
return in, nil
}