-
Notifications
You must be signed in to change notification settings - Fork 0
/
opFunction.go
636 lines (538 loc) · 15.1 KB
/
opFunction.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package mpath
import (
"encoding/json"
"fmt"
"strconv"
"strings"
sc "text/scanner"
"cuelang.org/go/cue"
"github.com/shopspring/decimal"
)
// Functions can only be part of an opPath
type opFunction struct {
IsInvalid bool
FunctionType FT_FunctionType
Params FunctionParameterTypes
opCommon
}
func (x *opFunction) Validate(rootValue cue.Value, cuePath CuePath, previousType InputOrOutput, blockedRootFields []string) (part *Function, returnedType InputOrOutput, returnsKnownValues bool, err error) {
cuePathValue, err := findValueAtPath(rootValue, cuePath)
if err != nil {
return &Function{
functionFields: functionFields{
String: x.UserString(),
HasError: HasError{
Error: strPtr(err.Error()),
},
},
}, returnedType, false, nil
}
part = &Function{
functionFields: functionFields{
String: x.UserString(),
FunctionName: (*string)(&x.FunctionType),
Available: &Available{},
},
}
if x.IsInvalid {
errMessage := fmt.Sprintf("invalid operation type '%s'", x.FunctionType)
part.Error = &errMessage
}
// Find the function descriptor
fd, ok := funcMap[x.FunctionType]
if !ok {
errMessage := "unknown function"
part.Error = &errMessage
return
}
if fd.ValidOn.IOType != IOOT_Variadic && fd.ValidOn.Type != PT_Any && fd.ValidOn.Type != previousType.Type {
errMessage := fmt.Sprintf("cannot use this function on type %s; can use on %s", previousType.Type, fd.ValidOn.Type)
part.Error = &errMessage
}
if fd.ValidOn.Type != PT_Any && fd.ValidOn.IOType != previousType.IOType {
errMessage := fmt.Sprintf("cannot use this function on type %s; can use on %s", previousType.IOType, fd.ValidOn.IOType)
if part.Error != nil {
errMessage = fmt.Sprintf("%s; %s", *part.Error, errMessage)
}
part.Error = &errMessage
}
returnedType = fd.Returns
part.Type = fd.Returns
var variadicType *PT_ParameterType
var variadicPosition int
part.FunctionParameters = []*FunctionParameter{}
for i, p := range x.Params {
param := &FunctionParameter{
String: p.String(),
}
part.FunctionParameters = append(part.FunctionParameters, param)
paramReturns := p.IsFuncParam()
paramReturns.CueExpr = paramReturns.Type.CueExpr()
switch t := p.(type) {
case *FP_Path:
var pathOp *Path
pathOp, _ = t.Value.Validate(rootValue, cuePath, blockedRootFields)
param.Part = pathOp
if pathOp.Error != nil {
param.Error = pathOp.Error
continue
}
pathOp.String = p.String()
if len(pathOp.Parts) == 0 {
errMessage := "no parts returned for path"
param.Error = &errMessage
continue
}
paramReturns = pathOp.ReturnType()
case *FP_LogicalOperation:
var logOp *LogicalOperation
logOp = t.Value.Validate(rootValue, cuePath, blockedRootFields)
param.Part = logOp
if logOp.Error != nil {
param.Error = logOp.Error
continue
}
logOp.String = p.String()
if len(logOp.Parts) == 0 {
errMessage := "no parts returned for path"
param.Error = &errMessage
continue
}
paramReturns = logOp.ReturnType()
}
pos := i
if variadicType != nil {
pos = variadicPosition
}
//get the parameter at this position
pd, err := fd.GetParamAtPosition(pos)
if err != nil {
errMessage := err.Error()
param.Error = &errMessage
continue
}
if variadicType == nil && pd.IOType == IOOT_Variadic {
vpt := paramReturns.Type
variadicType = &vpt
variadicPosition = i
}
if variadicType != nil {
param.IsVariadicOfParameterAtPosition = &variadicPosition
}
param.Type = paramReturns
switch pd.IOType {
case IOOT_Single:
if paramReturns.IOType != IOOT_Single {
errMessage := fmt.Sprintf("incorrect parameter type: expected single value, got %s", paramReturns.IOType)
param.Error = &errMessage
}
continue
case IOOT_Array:
if paramReturns.IOType != IOOT_Array {
errMessage := fmt.Sprintf("incorrect parameter type: expected array value, got %s", paramReturns.IOType)
param.Error = &errMessage
}
continue
case IOOT_Variadic:
// Do nothing, this can accept either a single or an array value
}
if pd.Type != PT_Any && pd.Type != paramReturns.Type {
// This means that the parameter does not accept "Any" type and the returned type is wrong for the expected input
errMessage := fmt.Sprintf("incorrect parameter type: wanted '%s'; got '%s'", pd.Type, paramReturns.Type)
param.Error = &errMessage
}
}
explanation := fd.explanationFunc(*part)
part.FunctionExplanation = &explanation
var k cue.Kind
k, _ = getUnderlyingKind(cuePathValue)
if fd.Returns.Type == PT_Any {
switch k {
// Primative Kinds:
case cue.BoolKind:
returnedType.Type = PT_Boolean
case cue.StringKind:
returnedType.Type = PT_String
case cue.NumberKind, cue.IntKind, cue.FloatKind:
returnedType.Type = PT_Number
case cue.StructKind:
returnedType.Type = PT_Object
case cue.ListKind:
returnedType.Type = PT_Any //todo: can I use the underlying type?
}
}
part.Type = returnedType
part.Type.CueExpr = fd.Returns.Type.CueExpr()
returnsKnownValues = fd.ReturnsKnownValues
if fd.ReturnsKnownValues && previousType.IOType == IOOT_Array && k == cue.StructKind {
cuePathValue, _ = getUnderlyingValue(cuePathValue)
// We can find available fields
returnedType.Type = PT_Object
returnedType.CueExpr = getExpr(cuePathValue)
part.Type = returnedType
part.Available.Fields, err = getAvailableFieldsForValue(cuePathValue, blockedRootFields)
if err != nil {
errMessage := fmt.Sprintf("failed to get available fields: %v", err)
if part.Error != nil {
errMessage = *part.Error + "; " + errMessage
}
part.Error = &errMessage
}
}
part.Available.Functions = append(part.Available.Functions, getAvailableFunctionsForKind(returnedType)...)
return
}
func (x *opFunction) Type() OT_OpType { return OT_Function }
func (x *opFunction) Sprint(depth int) (out string) {
paramsAsStrings := []string{}
for _, p := range x.Params {
paramsAsStrings = append(paramsAsStrings, p.String())
}
return fmt.Sprintf("%s(%s)", ft_GetName(x.FunctionType), strings.Join(paramsAsStrings, ","))
}
func (x *opFunction) Do(currentData, originalData any) (dataToUse any, err error) {
var rtParams FunctionParameterTypes
// get the pathParams and put them in the appropriate bucket
for _, param := range x.Params {
var ppOp Operation
switch t := param.(type) {
case *FP_Number, *FP_String, *FP_Bool:
rtParams = append(rtParams, t)
continue
case *FP_Path:
ppOp = t.Value
case *FP_LogicalOperation:
ppOp = t.Value
}
res, err := ppOp.Do(currentData, originalData)
if err != nil {
return nil, fmt.Errorf("issue with path parameter: %w", err)
}
switch resType := res.(type) {
case decimal.Decimal:
rtParams = append(rtParams, &FP_Number{resType})
case string:
rtParams = append(rtParams, &FP_String{resType})
case bool:
rtParams = append(rtParams, &FP_Bool{resType})
case []decimal.Decimal:
for _, rt := range resType {
rtParams = append(rtParams, &FP_Number{rt})
}
case []string:
for _, rt := range resType {
rtParams = append(rtParams, &FP_String{rt})
}
case []bool:
for _, rt := range resType {
rtParams = append(rtParams, &FP_Bool{rt})
}
case []float64:
for _, asFloat := range resType {
rtParams = append(rtParams, &FP_Number{decimal.NewFromFloat(asFloat)})
}
case []int:
for _, asInt := range resType {
rtParams = append(rtParams, &FP_Number{decimal.NewFromInt(int64(asInt))})
}
case []any:
for _, pv := range resType {
switch pvType := pv.(type) {
case float64:
rtParams = append(rtParams, &FP_Number{decimal.NewFromFloat(pvType)})
case int:
rtParams = append(rtParams, &FP_Number{decimal.NewFromInt(int64(pvType))})
case decimal.Decimal:
rtParams = append(rtParams, &FP_Number{pvType})
case string:
rtParams = append(rtParams, &FP_String{pvType})
case bool:
rtParams = append(rtParams, &FP_Bool{pvType})
default:
return nil, fmt.Errorf("unhandled param path type: %T", pv)
}
}
default:
return nil, fmt.Errorf("unhandled param path type: %T", resType)
}
}
currentData = convertToDecimalIfNumber(currentData)
funcToRun, ok := funcMap[x.FunctionType]
if !ok {
return nil, fmt.Errorf("unrecognised function")
}
return funcToRun.fn(rtParams, currentData)
}
func (x *opFunction) Parse(s *scanner, r rune) (nextR rune, err error) {
if s.sx.Peek() != '(' {
return r, erInvalid(s, '(')
}
x.FunctionType, err = ft_GetByName(s.TokenText())
if err != nil {
x.IsInvalid = true
x.FunctionType = FT_FunctionType(s.TokenText())
// return r, erAt(s, err.Error())
}
x.userString += string(x.FunctionType)
r = s.Scan()
x.userString += string(r)
for {
if r == sc.EOF {
break
}
switch r {
case ',':
x.userString += string(r)
// This is the separator, we can move on
r = s.Scan()
continue
case ')':
x.userString += string(r)
// This is the end of the function
return s.Scan(), nil
case '$', '@':
// This is a path
if r, err = x.addOpToParamsAndParse(s, r); err != nil {
return r, err
}
continue
case '{':
// This is a logical operation
if r, err = x.addLogicalOperationToParamsAndParse(s, r); err != nil {
return r, err
}
continue
case sc.String, sc.RawString, sc.Char:
tt := s.TokenText()
x.userString += string(tt)
if len(tt) >= 2 && strings.HasPrefix(tt, `"`) && strings.HasSuffix(tt, `"`) {
tt = tt[1 : len(tt)-1]
}
tt = unescape(tt)
x.Params = append(x.Params, &FP_String{tt})
case sc.Float, sc.Int:
// tt := s.TokenText()
// x.userString += string(tt)
// f, err := strconv.ParseFloat(tt, 64)
// if err != nil {
// // This should not be possible, but handle it just in case
// return r, erAt(s, "couldn't convert number as string '%s' to number", s.TokenText())
// }
// x.Params = append(x.Params, &FP_Number{decimal.NewFromFloat(f)})
r, err = dealWithNumbers(s, x, r)
if err != nil {
return r, erInvalid(s)
}
case sc.Ident:
//must be bool
tt := s.TokenText()
switch tt {
case "true":
x.userString += tt
x.Params = append(x.Params, &FP_Bool{true})
case "false":
x.userString += tt
x.Params = append(x.Params, &FP_Bool{false})
default:
r, err = dealWithNumbers(s, x, r)
if err != nil {
return r, erInvalid(s)
}
}
}
r = s.Scan()
}
return
}
func unescape(s string) string {
replacements := map[string]string{
"\\\"": "\"",
"\\a": "\a",
"\\b": "\b",
"\\f": "\f",
"\\n": "\n",
"\\r": "\r",
"\\t": "\t",
"\\v": "\v",
}
for old, new := range replacements {
s = strings.Replace(s, old, new, -1)
}
return s
}
func escape(s string) string {
replacements := map[string]string{
"\"": "\\\"",
"\a": "\\a",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\v": "\\v",
}
for old, new := range replacements {
s = strings.Replace(s, old, new, -1)
}
return s
}
func isRuneInString(c rune, s string) bool {
for _, sr := range s {
if c == sr {
return true
}
}
return false
}
func dealWithNumbers(s *scanner, x *opFunction, r rune) (rune, error) {
tt := s.TokenText()
// peek the scanner to see if the next character is a dot
if pk := s.sx.Peek(); pk == '.' {
// this should be a decimal
s.Scan() // scan the dot
pk = s.sx.Peek()
if isRuneInString(pk, "0123456789") {
s.Scan() // move to the next token, should be the remainder of the number
ttk := s.TokenText()
tt += "." + ttk
}
}
x.userString += string(tt)
f, err := strconv.ParseFloat(tt, 64)
if err != nil {
// This should not be possible, but handle it just in case
return r, erAt(s, "couldn't convert number as string '%s' to number", s.TokenText())
}
x.Params = append(x.Params, &FP_Number{decimal.NewFromFloat(f)})
return r, nil
}
func (x *opFunction) addOpToParamsAndParse(s *scanner, r rune) (nextR rune, err error) {
op := &opPath{}
x.Params = append(x.Params, &FP_Path{op})
nextR, err = op.Parse(s, r)
x.userString += op.UserString()
return
}
func (x *opFunction) addLogicalOperationToParamsAndParse(s *scanner, r rune) (nextR rune, err error) {
op := &opLogicalOperation{}
x.Params = append(x.Params, &FP_LogicalOperation{op})
nextR, err = op.Parse(s, r)
x.userString += op.UserString()
return
}
type FunctionParameterTypes []FunctionParameterType
func (x FunctionParameterTypes) Numbers() (out []*FP_Number) {
for _, fp := range x {
switch t := fp.(type) {
case *FP_Number:
out = append(out, t)
}
}
return
}
func (x FunctionParameterTypes) Strings() (out []*FP_String) {
for _, fp := range x {
switch t := fp.(type) {
case *FP_String:
out = append(out, t)
}
}
return
}
func (x FunctionParameterTypes) Bools() (out []*FP_Bool) {
for _, fp := range x {
switch t := fp.(type) {
case *FP_Bool:
out = append(out, t)
}
}
return
}
func (x FunctionParameterTypes) Paths() (out []*FP_Path) {
for _, fp := range x {
switch t := fp.(type) {
case *FP_Path:
out = append(out, t)
}
}
return
}
type FunctionParameterType interface {
IsFuncParam() (returns InputOrOutput)
String() string
GetValue() any
}
func functionParameterMarshalJSON(value any, typeName string) ([]byte, error) {
return json.Marshal(struct {
Type string `json:"_type"`
Value any `json:"Value"`
}{
Type: typeName,
Value: value,
})
}
type FP_Number struct {
Value decimal.Decimal
}
func (p FP_Number) String() string {
return p.Value.String()
}
func (x *FP_Number) IsFuncParam() (returns InputOrOutput) {
return inputOrOutput(PT_Number, IOOT_Single)
}
func (x *FP_Number) GetValue() any { return x.Value }
func (x *FP_Number) MarshalJSON() ([]byte, error) {
return functionParameterMarshalJSON(x.Value, "Number")
}
type FP_String struct {
Value string
}
func (p FP_String) String() string {
return fmt.Sprintf(`"%s"`, escape(p.Value))
}
func (x *FP_String) IsFuncParam() (returns InputOrOutput) {
return inputOrOutput(PT_String, IOOT_Single)
}
func (x *FP_String) GetValue() any { return x.Value }
func (x *FP_String) MarshalJSON() ([]byte, error) {
return functionParameterMarshalJSON(x.Value, "String")
}
type FP_Bool struct {
Value bool
}
func (p FP_Bool) String() string {
return fmt.Sprint(p.Value)
}
func (x *FP_Bool) IsFuncParam() (returns InputOrOutput) {
return inputOrOutput(PT_Boolean, IOOT_Single)
}
func (x *FP_Bool) GetValue() any { return x.Value }
func (x *FP_Bool) MarshalJSON() ([]byte, error) {
return functionParameterMarshalJSON(x.Value, "Bool")
}
type FP_Path struct {
Value *opPath
}
func (p FP_Path) String() string {
return p.Value.UserString()
}
func (x *FP_Path) IsFuncParam() (returns InputOrOutput) {
return inputOrOutput(PT_Any, IOOT_Single)
}
func (x *FP_Path) GetValue() any { return x.Value }
func (x *FP_Path) MarshalJSON() ([]byte, error) {
return functionParameterMarshalJSON(x.Value, "Path")
}
type FP_LogicalOperation struct {
Value *opLogicalOperation
}
func (p FP_LogicalOperation) String() string {
return p.Value.UserString()
}
func (x *FP_LogicalOperation) IsFuncParam() (returns InputOrOutput) {
return inputOrOutput(PT_Any, IOOT_Single)
}
func (x *FP_LogicalOperation) GetValue() any { return x.Value }
func (x *FP_LogicalOperation) MarshalJSON() ([]byte, error) {
return functionParameterMarshalJSON(x.Value, "LogicalOperation")
}