-
Notifications
You must be signed in to change notification settings - Fork 42
/
generic_func.go
534 lines (465 loc) · 12.9 KB
/
generic_func.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package udf
import (
"errors"
"fmt"
"math"
"reflect"
"time"
"gopkg.in/sensorbee/sensorbee.v0/core"
"gopkg.in/sensorbee/sensorbee.v0/data"
)
// ConvertGeneric creates a new UDF from various form of functions. Arguments
// of the function don't have to be tuple types, but some standard types are
// allowed. The UDF returned provide a weak type conversion, that is it uses
// data.To{Type} function to convert values. Therefore, a string may be
// passed as an integer or vice versa. If the function wants to provide
// strict type conversion, generate UDF by Func function.
//
// Acceptable types:
// - bool
// - standard integers
// - standard floats
// - string
// - time.Time
// - data.Bool, data.Int, data.Float, data.String, data.Blob,
// data.Timestamp, data.Array, data.Map, data.Value
// - a slice of types above
func ConvertGeneric(function interface{}) (UDF, error) {
t := reflect.TypeOf(function)
if t.Kind() != reflect.Func {
return nil, errors.New("the argument must be a function")
}
numArgs := t.NumIn()
if genericFuncHasContext(t) {
numArgs--
}
return convertGenericAggregate(function, make([]bool, numArgs), false)
}
// MustConvertGeneric is like ConvertGeneric, but panics on errors.
func MustConvertGeneric(function interface{}) UDF {
f, err := ConvertGeneric(function)
if err != nil {
panic(err)
}
return f
}
// ConvertGenericAggregate creates a new aggregate UDF from various form of
// functions. aggParams argument is used to indicate which arguments of the
// function are aggregation parameter.
// receives aggregation parameter.
// Supported and acceptable types are the same as ConvertGeneric.
func ConvertGenericAggregate(function interface{}, aggParams []bool) (UDF, error) {
return convertGenericAggregate(function, aggParams, true)
}
func convertGenericAggregate(function interface{}, aggParams []bool, isAggregate bool) (UDF, error) {
t := reflect.TypeOf(function)
if t.Kind() != reflect.Func {
return nil, errors.New("the argument must be a function")
}
copiedParams := make([]bool, len(aggParams))
copy(copiedParams, aggParams)
g := &genericFunc{
function: reflect.ValueOf(function),
hasContext: genericFuncHasContext(t),
variadic: t.IsVariadic(),
arity: t.NumIn(),
aggregationParameter: copiedParams,
}
if g.hasContext {
g.arity--
}
if isAggregate {
if g.arity == 0 {
return nil, errors.New("UDAF must have at least one argument")
}
hasTrue := false
for _, b := range aggParams {
if b {
hasTrue = true
break
}
}
if !hasTrue {
return nil, errors.New("the function doesn't have an aggregation parameter")
}
}
if g.arity != len(aggParams) {
return nil, errors.New("the aggParams must have the same number of arguments of the function")
}
for i := 0; i < g.arity; i++ {
if !aggParams[i] {
continue
}
in := i
if g.hasContext {
in++
}
if t.In(in).Kind() != reflect.Slice {
return nil, fmt.Errorf("the %v-th parameter for aggregation must be slice", i+1)
}
}
if hasError, err := checkGenericFuncReturnTypes(t); err != nil {
return nil, err
} else {
g.hasError = hasError
}
if convs, err := createGenericConverters(t, t.NumIn()-g.arity); err != nil {
return nil, err
} else {
g.converters = convs
}
return g, nil
}
// MustConvertGenericAggregate is like ConvertGenericAggregate,
// but panics on errors.
func MustConvertGenericAggregate(function interface{}, aggParams []bool) UDF {
f, err := ConvertGenericAggregate(function, aggParams)
if err != nil {
panic(err)
}
return f
}
func checkGenericFuncReturnTypes(t reflect.Type) (bool, error) {
hasError := false
switch n := t.NumOut(); n {
case 2:
if !t.Out(1).Implements(reflect.TypeOf(func(error) {}).In(0)) {
return false, fmt.Errorf("the second return value must be an error: %v", t.Out(1))
}
hasError = true
fallthrough
case 1:
out := t.Out(0)
if out.Kind() == reflect.Interface {
// data.Value is the only interface which is accepted.
if !out.Implements(reflect.TypeOf(data.NewValue).Out(0)) {
return false, fmt.Errorf("the return value isn't convertible to data.Value")
}
}
if _, err := data.NewValue(reflect.Zero(out).Interface()); err != nil {
return false, fmt.Errorf("the return value isn't convertible to data.Value")
}
default:
return false, fmt.Errorf("the number of return values must be 1 or 2: %v", n)
}
return hasError, nil
}
func genericFuncHasContext(t reflect.Type) bool {
if t.NumIn() == 0 {
return false
}
c := t.In(0)
return reflect.TypeOf(&core.Context{}).AssignableTo(c)
}
func createGenericConverters(t reflect.Type, argStart int) ([]argumentConverter, error) {
variadic := t.IsVariadic()
convs := make([]argumentConverter, 0, t.NumIn()-argStart)
for i := argStart; i < t.NumIn(); i++ {
arg := t.In(i)
if i == t.NumIn()-1 && variadic {
arg = arg.Elem()
}
c, err := genericFuncArgumentConverter(arg)
if err != nil {
return nil, err
}
convs = append(convs, c)
}
return convs, nil
}
type argumentConverter func(data.Value) (interface{}, error)
func genericFuncArgumentConverter(t reflect.Type) (argumentConverter, error) {
// TODO: this function is too long.
switch t.Kind() {
case reflect.Bool:
return func(v data.Value) (interface{}, error) {
return data.ToBool(v)
}, nil
case reflect.Int:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < -1^int64(^uint(0)>>1) {
return nil, fmt.Errorf("%v is too small for int", i)
} else if i > int64(^uint(0)>>1) {
return nil, fmt.Errorf("%v is too big for int", i)
}
return int(i), nil
}, nil
case reflect.Int8:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < math.MinInt8 {
return nil, fmt.Errorf("%v is too small for int8", i)
} else if i > math.MaxInt8 {
return nil, fmt.Errorf("%v is too big for int8", i)
}
return int8(i), nil
}, nil
case reflect.Int16:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < math.MinInt16 {
return nil, fmt.Errorf("%v is too small for int16", i)
} else if i > math.MaxInt16 {
return nil, fmt.Errorf("%v is too big for int16", i)
}
return int16(i), nil
}, nil
case reflect.Int32:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < math.MinInt32 {
return nil, fmt.Errorf("%v is too small for int32", i)
} else if i > math.MaxInt32 {
return nil, fmt.Errorf("%v is too big for int32", i)
}
return int32(i), nil
}, nil
case reflect.Int64:
return func(v data.Value) (interface{}, error) {
return data.ToInt(v)
}, nil
case reflect.Uint:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < 0 {
return nil, fmt.Errorf("%v is too small for uint", i)
} else if i > int64(^uint(0)>>1) {
return nil, fmt.Errorf("%v is too big for uint", i)
}
return uint(i), nil
}, nil
case reflect.Uint8:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < 0 {
return nil, fmt.Errorf("%v is too small for uint8", i)
} else if i > math.MaxUint8 {
return nil, fmt.Errorf("%v is too big for uint8", i)
}
return uint8(i), nil
}, nil
case reflect.Uint16:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < 0 {
return nil, fmt.Errorf("%v is too small for uint16", i)
} else if i > math.MaxUint16 {
return nil, fmt.Errorf("%v is too big for uint16", i)
}
return uint16(i), nil
}, nil
case reflect.Uint32:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < 0 {
return nil, fmt.Errorf("%v is too small for uint32", i)
} else if i > math.MaxUint32 {
return nil, fmt.Errorf("%v is too big for uint32", i)
}
return uint32(i), nil
}, nil
case reflect.Uint64:
return func(v data.Value) (interface{}, error) {
i, err := data.ToInt(v)
if err != nil {
return nil, err
}
if i < 0 {
return nil, fmt.Errorf("%v is too small for uint64", i)
}
return uint64(i), nil
}, nil
case reflect.Float32:
return func(v data.Value) (interface{}, error) {
f, err := data.ToFloat(v)
if err != nil {
return nil, err
}
return float32(f), err
}, nil
case reflect.Float64:
return func(v data.Value) (interface{}, error) {
return data.ToFloat(v)
}, nil
case reflect.String:
return func(v data.Value) (interface{}, error) {
return data.ToString(v)
}, nil
case reflect.Slice:
elemType := t.Elem()
if elemType.Kind() == reflect.Uint8 {
// process this as a blob
return func(v data.Value) (interface{}, error) {
// This function explicitly returns nil to avoid returning
// nils having non-empty type information for later nil
// equality checks.
res, err := data.ToBlob(v)
if err != nil {
return nil, err
}
if res == nil {
return nil, err
}
return res, nil
}, nil
}
c, err := genericFuncArgumentConverter(elemType)
if err != nil {
return nil, err
}
return func(v data.Value) (interface{}, error) {
a, err := data.AsArray(v)
if err != nil {
return nil, err
}
res := reflect.MakeSlice(t, 0, len(a))
for _, elem := range a {
e, err := c(elem)
if err != nil {
return nil, err
}
res = reflect.Append(res, reflect.ValueOf(e))
}
return res.Interface(), nil // res will never be nil.
}, nil
default:
switch reflect.Zero(t).Interface().(type) {
case data.Map:
return func(v data.Value) (interface{}, error) {
res, err := data.AsMap(v)
if err != nil {
return nil, err
}
if res == nil {
return nil, err
}
return res, nil
}, nil
case time.Time:
return func(v data.Value) (interface{}, error) {
return data.ToTimestamp(v)
}, nil
default:
if t.Implements(reflect.TypeOf(data.NewValue).Out(0)) { // data.Value
// Zero(interface) returns nil and type assertion doesn't work for it.
return func(v data.Value) (interface{}, error) {
if v == nil {
return nil, nil // Erase type information (data.Value) from nil
}
return v, nil
}, nil
}
// other tuple types are covered in Kind() switch above
return nil, fmt.Errorf("unsupported type: %v", t)
}
}
}
type genericFunc struct {
function reflect.Value
hasContext bool
hasError bool
variadic bool
// arity is the number of arguments. If the function is variadic, arity
// counts the last variadic parameter. For example, if the function is
// func(int, float, ...string), arity is 3. It doesn't count Context.
arity int
// aggregationParameter have the same length as the number of arguments
// excluding the *core.Context.
// The values are returned by IsAggregationParameter method.
// If the aggregationParameter[n] boolean value is true, the n-th function
// argument receives aggregation parameter.
aggregationParameter []bool
converters []argumentConverter
}
func (g *genericFunc) Call(ctx *core.Context, args ...data.Value) (data.Value, error) {
out, err := g.call(ctx, args...)
if err != nil {
return nil, err
}
if g.hasError {
if !out[1].IsNil() {
return nil, out[1].Interface().(error)
}
}
return data.NewValue(out[0].Interface())
}
func (g *genericFunc) call(ctx *core.Context, args ...data.Value) ([]reflect.Value, error) {
if len(args) < g.arity {
if g.variadic && len(args) == g.arity-1 {
// having no variadic parameter is ok.
} else {
return nil, fmt.Errorf("insufficient number of argumetns")
}
} else if len(args) != g.arity && !g.variadic {
return nil, fmt.Errorf("too many arguments")
}
in := make([]reflect.Value, 0, len(args)+1) // +1 for context
if g.hasContext {
in = append(in, reflect.ValueOf(ctx))
}
variadicBegin := g.arity
if g.variadic {
variadicBegin--
}
for i := 0; i < variadicBegin; i++ {
v, err := g.converters[i](args[i])
if err != nil {
return nil, err
}
in = append(in, reflect.ValueOf(v))
}
for i := variadicBegin; i < len(args); i++ {
v, err := g.converters[len(g.converters)-1](args[i])
if err != nil {
return nil, err
}
in = append(in, reflect.ValueOf(v))
}
return g.function.Call(in), nil
}
func (g *genericFunc) Accept(arity int) bool {
if arity < g.arity {
if g.variadic && arity == g.arity-1 {
// having no variadic parameter is ok.
} else {
return false
}
} else if arity != g.arity && !g.variadic {
return false
}
return true
}
func (g *genericFunc) IsAggregationParameter(k int) bool {
if len(g.aggregationParameter) <= k {
if g.variadic {
return g.aggregationParameter[len(g.aggregationParameter)-1]
}
return false
}
return g.aggregationParameter[k]
}