/
function.go
374 lines (324 loc) · 9.18 KB
/
function.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
package function
import (
"bytes"
"encoding/json"
"errors"
"reflect"
"runtime/debug"
"strings"
"fmt"
"github.com/TIBCOSoftware/flogo-lib/core/data"
"github.com/TIBCOSoftware/flogo-lib/core/mapper/exprmapper/funcexprtype"
"github.com/TIBCOSoftware/flogo-lib/core/mapper/exprmapper/ref"
"github.com/TIBCOSoftware/flogo-lib/logger"
)
var logrus = logger.GetLogger("function")
type Func interface {
Eval(inputScope, outputScope data.Scope) ([]interface{}, error)
String() string
}
type FunctionExp struct {
Name string `json:"name"`
Params []*Parameter `json:"params"`
}
type Parameter struct {
Function *FunctionExp `json:"function"`
Type funcexprtype.Type `json:"type"`
Value interface{} `json:"value"`
}
func (p *Parameter) UnmarshalJSON(paramData []byte) error {
ser := &struct {
Function *FunctionExp `json:"function"`
Type funcexprtype.Type `json:"type"`
Value interface{} `json:"value"`
}{}
if err := json.Unmarshal(paramData, ser); err != nil {
return err
}
p.Function = ser.Function
p.Type = ser.Type
v, err := ConvertToValue(ser.Value, ser.Type)
if err != nil {
return err
}
p.Value = v
return nil
}
func (p *Parameter) IsEmtpy() bool {
if p.Function != nil {
if p.Function.Name == "" && p.Type == 0 && p.Value == nil && len(p.Function.Params) <= 0 {
return true
}
} else {
if p.Type == 0 && p.Value == nil {
return true
}
}
return false
}
func (p *Parameter) IsFunction() bool {
return funcexprtype.FUNCTION == p.Type
}
func (f *FunctionExp) Eval() (interface{}, error) {
value, err := f.callFunction(nil, nil, nil)
if err != nil {
return nil, err
}
return convertType(value), err
}
func (f *FunctionExp) EvalWithScope(inputScope data.Scope, resolver data.Resolver) (interface{}, error) {
value, err := f.callFunction(nil, inputScope, resolver)
if err != nil {
logrus.Errorf("Execution failed for function [%s] error - %+v", f.Name, err.Error())
return nil, err
}
return convertType(value), err
}
func (f *FunctionExp) EvalWithData(data interface{}, inputScope data.Scope, resolver data.Resolver) (interface{}, error) {
value, err := f.callFunction(data, inputScope, resolver)
if err != nil {
return nil, err
}
return convertType(value), err
}
func HandleToSingleOutput(values interface{}) interface{} {
if values != nil {
switch t := values.(type) {
case []interface{}:
return t[0]
default:
return t
}
}
return nil
}
func convertType(value reflect.Value) interface{} {
return value.Interface()
}
func (f *FunctionExp) getRealFunction() (Function, error) {
return GetFunction(f.Name)
}
func (f *FunctionExp) getMethod() (reflect.Value, error) {
var ptr reflect.Value
s, err := f.getRealFunction()
if err != nil {
return reflect.Value{}, err
}
value := reflect.ValueOf(s)
if value.Type().Kind() == reflect.Ptr {
ptr = value
value = ptr.Elem()
} else {
ptr = reflect.New(reflect.TypeOf(s))
temp := ptr.Elem()
temp.Set(value)
}
method := value.MethodByName("Eval")
if !method.IsValid() {
method = ptr.MethodByName("Eval")
if !method.IsValid() {
logrus.Debug("invalid also, ", f.Name)
return reflect.Value{}, errors.New("Method invalid..")
}
}
return method, nil
}
func (f *FunctionExp) Tostring() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("function name [%s] ", f.Name))
for i, param := range f.Params {
if param != nil {
buffer.WriteString(fmt.Sprintf(" parameter [%d]'s type [%s] and value [%+v]", i, param.Type, param.Value))
}
}
return buffer.String()
}
func (f *FunctionExp) callFunction(fdata interface{}, inputScope data.Scope, resolver data.Resolver) (results reflect.Value, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
logrus.Debugf("StackTrace: %s", debug.Stack())
}
}()
method, err := f.getMethod()
if err != nil {
return reflect.Value{}, err
}
inputs := []reflect.Value{}
for i, p := range f.Params {
if p.IsFunction() {
result, err := p.Function.callFunction(fdata, inputScope, resolver)
if err != nil {
return reflect.Value{}, err
}
logrus.Debugf("function [%s] [%d]'s argument type [%s] and value [%+v]", f.Name, i, p.Type, result)
inputs = append(inputs, result)
} else {
if !p.IsEmtpy() {
if p.Type == funcexprtype.REF {
var field *ref.MappingRef
switch p.Value.(type) {
case string:
field = ref.NewMappingRef(p.Value.(string))
case *ref.MappingRef:
field = p.Value.(*ref.MappingRef)
}
if inputScope == nil {
p.Value = field.GetRef()
} else {
v, err := field.Eval(inputScope, resolver)
if err != nil {
return reflect.Value{}, err
}
p.Value = v
}
} else if p.Type == funcexprtype.ARRAYREF {
var field *ref.ArrayRef
switch p.Value.(type) {
case string:
field = ref.NewArrayRef(p.Value.(string))
case *ref.ArrayRef:
field = p.Value.(*ref.ArrayRef)
}
if inputScope == nil {
p.Value = field.GetRef()
} else {
if fdata == nil {
//Array mapping should not go here for today, take is as get current scope.
//TODO how to know it is array mapping or get current scope
ref := ref.NewMappingRef(field.GetRef())
v, err := ref.Eval(inputScope, resolver)
if err != nil {
return reflect.Value{}, err
}
p.Value = v
} else {
v, err := field.EvalFromData(fdata)
if err != nil {
return reflect.Value{}, err
}
p.Value = v
}
}
}
logrus.Debugf("function [%s] [%d]'s argument type [%s] and value [%+v]", f.Name, i, p.Type, p.Value)
if p.Value != nil {
inputs = append(inputs, reflect.ValueOf(p.Value))
} else {
t := method.Type().In(i)
funcStr := method.Type().String()
if strings.Contains(funcStr, "...") {
parameterNum := method.Type().NumIn()
if parameterNum > 1 {
//2. Variadic as latest parameter
//func(name string, id int, ids ...string)
if i == parameterNum-1 {
inputs = append(inputs, reflect.Zero(t.Elem()))
} else {
inputs = append(inputs, reflect.Zero(t))
}
} else {
//1. only one variadic parameter
//func(...string)
inputs = append(inputs, reflect.Zero(t.Elem()))
}
} else {
inputs = append(inputs, reflect.Zero(t))
}
}
}
}
}
logrus.Debugf("Input Parameters: %+v", inputs)
args, err := ensureArguments(method, inputs)
if err != nil {
return reflect.Value{}, fmt.Errorf("Function '%s' argument validation failed due to error %s", f.Name, err.Error())
}
values := method.Call(args)
return f.extractErrorFromValues(values)
}
func ensureArguments(method reflect.Value, in []reflect.Value) ([]reflect.Value, error) {
var retInputs []reflect.Value
methodType := method.Type()
n := method.Type().NumIn()
if methodType.IsVariadic() && n == 1 {
x := in[0]
elem := methodType.In(0).Elem()
if xt := x.Type(); !xt.AssignableTo(elem) {
v, err := convertArgs(elem, x)
if err != nil {
return nil, fmt.Errorf("argument type mismatch. Can not convert type %s to type %s. ", xt.String(), elem.String())
}
retInputs = append(retInputs, reflect.ValueOf(v))
} else {
retInputs = append(retInputs, x)
}
} else {
for i := 0; i < n; i++ {
if xt, targ := in[i].Type(), methodType.In(i); !xt.AssignableTo(targ) {
v, err := convertArgs(targ, in[i])
if err != nil {
return nil, fmt.Errorf("argument type mismatch. Can not convert type %s to type %s. ", xt.String(), targ.String())
}
retInputs = append(retInputs, reflect.ValueOf(v))
} else {
retInputs = append(retInputs, in[i])
}
}
}
if methodType.IsVariadic() {
m := len(in) - n
elem := methodType.In(n - 1).Elem()
for j := 0; j < m; j++ {
x := in[n+j]
if xt := x.Type(); !xt.AssignableTo(elem) {
v, err := convertArgs(elem, x)
if err != nil {
return nil, fmt.Errorf("argument type mismatch. Can not convert type %s to type %s. ", xt.String(), elem.String())
}
retInputs = append(retInputs, reflect.ValueOf(v))
} else {
retInputs = append(retInputs, x)
}
}
}
return retInputs, nil
}
func convertArgs(argType reflect.Type, in reflect.Value) (interface{}, error) {
var v interface{}
var err error
switch argType.Kind() {
case reflect.Bool:
v, err = data.CoerceToBoolean(in.Interface())
case reflect.Interface:
v, err = data.CoerceToAny(in.Interface())
case reflect.Int:
v, err = data.CoerceToInteger(in.Interface())
case reflect.Int64:
v, err = data.CoerceToLong(in.Interface())
case reflect.String:
v, err = data.CoerceToString(in.Interface())
case reflect.Float64:
v, err = data.CoerceToDouble(in.Interface())
default:
v = in.Interface()
}
return v, err
}
func (f *FunctionExp) extractErrorFromValues(values []reflect.Value) (reflect.Value, error) {
tempValues := []reflect.Value{}
var err error
for _, value := range values {
if value.Type().Name() == "error" {
if value.Interface() != nil {
err = value.Interface().(error)
}
} else {
tempValues = append(tempValues, value)
}
}
if len(tempValues) > 1 {
return tempValues[0], fmt.Errorf("Not support function multiple returns")
}
return tempValues[0], err
}