-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinterpreter_test.go
More file actions
835 lines (790 loc) · 27.1 KB
/
interpreter_test.go
File metadata and controls
835 lines (790 loc) · 27.1 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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
package mexpr
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func TestInterpreter(t *testing.T) {
type test struct {
expr string
input string
inputParsed any
skipTC bool
unordered bool
opts []InterpreterOption
err string
output any
}
cases := []test{
// Add/sub
{expr: "1 + 2 - 3", output: 0.0},
{expr: "-1 + +3", output: 2.0},
{expr: "-1 + -3 - -4", output: 0.0},
{expr: `0.5 + 0.2`, output: 0.7},
{expr: `.5 + .2`, output: 0.7},
{expr: `1_000_000 + 1`, output: 1000001.0},
// Mul/div
{expr: "4 * 5 / 10", output: 2.0},
{expr: `19 % x`, input: `{"x": 5}`, output: 4.0},
// Power
{expr: "2^3", output: 8.0},
{expr: "2^3^2", output: 512.0},
{expr: "16^.5", output: 4.0},
// Parentheses
{expr: "((1 + (2)) * 3)", output: 9.0},
// Comparison
{expr: "1 < 2", output: true},
{expr: "1 > 2", output: false},
{expr: "1 > 1", output: false},
{expr: "1 >= 1", output: true},
{expr: "1 < 1", output: false},
{expr: "1 <= 1", output: true},
{expr: "1 == 1", output: true},
{expr: "1 == 2", output: false},
{expr: "1 != 1", output: false},
{expr: "1 != 2", output: true},
{expr: "x.length == 3", input: `{"x": "abc"}`, output: true},
{expr: `19 % 5 == 4`, output: true},
{expr: `foo == 1`, input: `{"foo": []}`, output: false},
{expr: `foo == 1`, input: `{"foo": {}}`, output: false},
// Boolean comparisons
{expr: "1 < 2 and 1 > 2", output: false},
{expr: "1 < 2 and 2 > 1", output: true},
{expr: "1 < 2 or 1 > 2", output: true},
{expr: "1 < 2 or 2 > 1", output: true},
{expr: `1 and "a"`, output: true},
{expr: `0 and missing`, input: `{}`, skipTC: true, opts: []InterpreterOption{StrictMode}, output: false},
{expr: `1 or missing`, input: `{}`, skipTC: true, opts: []InterpreterOption{StrictMode}, output: true},
// Negation
{expr: "not (1 < 2)", output: false},
{expr: "not (1 < 2) and (3 < 4)", output: false},
{expr: "not foo.bar", input: `{"foo": {"bar": true}}`, output: false},
{expr: "not foo[0].bar", input: `{"foo": [{"bar": true}]}`, output: false},
// Strings
{expr: `"foo" == "foo"`, output: true},
{expr: `"foo" == "bar"`, output: false},
{expr: `"foo\"bar"`, output: `foo"bar`},
{expr: `"foo`, err: "unterminated string"},
{expr: `"foo" + "bar" == "foobar"`, output: true},
{expr: `foo + "a"`, input: `{"foo": 1}`, output: "1a"},
{expr: `foo + bar`, input: `{"foo": "id", "bar": 1}`, output: "id1"},
{expr: `foo[0]`, input: `{"foo": "hello"}`, output: "h"},
{expr: `foo[-1]`, input: `{"foo": "hello"}`, output: "o"},
{expr: `foo[0:-3]`, input: `{"foo": "hello"}`, output: "hel"},
{expr: `"é".length`, output: 1},
{expr: `foo[0]`, input: `{"foo": "éclair"}`, output: "é"},
{expr: `foo[1:2]`, input: `{"foo": "héllo"}`, output: "él"},
// Unquoted strings
{expr: `"foo" == foo`, skipTC: true, output: false},
{expr: `"foo" == foo`, opts: []InterpreterOption{UnquotedStrings}, output: true},
{expr: `"foo" == bar`, opts: []InterpreterOption{UnquotedStrings}, output: false},
{expr: `foo == foo`, opts: []InterpreterOption{UnquotedStrings}, output: true},
{expr: `foo == foo`, opts: []InterpreterOption{UnquotedStrings, StrictMode}, output: true},
{expr: `foo + 1`, opts: []InterpreterOption{UnquotedStrings}, output: "foo1"},
{expr: `@.foo + 1`, opts: []InterpreterOption{UnquotedStrings}, err: "cannot operate on incompatible types"},
{expr: `@.foo + 1`, opts: []InterpreterOption{UnquotedStrings, StrictMode}, err: "cannot get foo"},
{expr: `foo.bar == bar`, opts: []InterpreterOption{UnquotedStrings}, output: false},
{expr: `foo.bar == bar`, skipTC: true, opts: []InterpreterOption{UnquotedStrings}, input: `{"foo": {}}`, output: false},
{expr: `foo.bar == baz`, opts: []InterpreterOption{UnquotedStrings}, input: `{"foo": {"bar": "baz"}}`, output: true},
{expr: `(items where foo).length == 1`, input: `{"items": [{"foo": 1}, {"bar": 2}, {"baz": 3}]}`, opts: []InterpreterOption{UnquotedStrings}, output: true},
{expr: `(items where @.foo).length == 1`, input: `{"items": [{"foo": 1}, {"bar": 2}, {"baz": 3}]}`, opts: []InterpreterOption{UnquotedStrings}, output: true},
{expr: `(items where foo in id).length == 1`, input: `{"items": [{"id": "foo123"}, {"id": "bar456"}, {"id": "baz789"}]}`, opts: []InterpreterOption{UnquotedStrings}, output: true},
// Identifier / fields
{expr: "foo", input: `{"foo": 1.0}`, output: 1.0},
{expr: "foo.bar.baz", input: `{"foo": {"bar": {"baz": 1.0}}}`, output: 1.0},
{expr: `foo == "foo"`, input: `{"foo": "foo"}`, output: true},
{expr: `foo.in.not`, input: `{"foo": {"in": {"not": 1}}}`, output: 1.0},
{expr: `@`, input: `{"hello": "world"}`, output: map[string]any{"hello": "world"}},
{expr: `hello.@`, input: `{"hello": "world"}`, output: "world"},
// Arrays
{expr: "foo[0]", input: `{"foo": [1, 2]}`, output: 1.0},
{expr: "foo[-1]", input: `{"foo": [1, 2]}`, output: 2.0},
{expr: "foo[:1]", input: `{"foo": [1, 2, 3]}`, output: []any{1.0, 2.0}},
{expr: "foo[:]", input: `{"foo": [1, 2, 3]}`, output: []any{1.0, 2.0, 3.0}},
{expr: "foo[2:]", input: `{"foo": [1, 2, 3]}`, output: []any{3.0}},
{expr: "foo[:-1]", input: `{"foo": [1, 2, 3]}`, output: []any{1.0, 2.0, 3.0}},
{expr: "foo[1 + 2 / 2]", input: `{"foo": [1, 2, 3]}`, output: 3.0},
{expr: "foo[1:1 + 2]", input: `{"foo": [1, 2, 3, 4]}`, output: []any{2.0, 3.0, 4.0}},
{expr: "foo[foo[0]:bar.baz * 1^2]", input: `{"foo": [1, 2, 3, 4], "bar": {"baz": 3}}`, output: []any{2.0, 3.0, 4.0}},
{expr: "foo + bar", input: `{"foo": [1, 2], "bar": [3, 4]}`, output: []any{1.0, 2.0, 3.0, 4.0}},
{expr: "foo[bar]", input: `{"foo": [1, 2, 3], "bar": [0, 1]}`, output: []any{1.0, 2.0}},
// In
{expr: `"foo" in "foobar"`, output: true},
{expr: `"foo" in bar`, input: `{"bar": ["foo", "other"]}`, output: true},
{expr: `123 in 12345`, output: true},
{expr: `1 in "best 1"`, output: true},
{expr: `1 < 2 in "this is true"`, output: true},
{expr: `1 < 2 in "this is false"`, output: false},
{expr: `"bar" in foo`, input: `{"foo": {"bar": 1}}`, output: true},
{expr: `"bar" in foo`, input: `{"foo": {"bar": null}}`, output: true},
// Contains
{expr: `"foobar" contains "foo"`, output: true},
{expr: `"foobar" contains "baz"`, output: false},
{expr: `labels contains "foo"`, input: `{"labels": ["foo", "bar"]}`, output: true},
{expr: `foo contains "bar"`, input: `{"foo": {"bar": null}}`, output: true},
// Starts / ends with
{expr: `"foo" startsWith "f"`, output: true},
{expr: `"foo" startsWith "o"`, output: false},
{expr: `foo startsWith "f"`, input: `{"foo": "foo"}`, output: true},
{expr: `name startsWith "/groups/" + group`, input: `{"name": "/groups/foo/bar", "group": "foo"}`, output: true},
{expr: `"foo" endsWith "f"`, output: false},
{expr: `"foo" endsWith "o"`, output: true},
{expr: `"id1" endsWith 1`, output: true},
// Before / after
{expr: `start before end`, input: `{"start": "2022-01-01T12:00:00Z", "end": "2022-01-01T23:59:59Z"}`, output: true},
{expr: `start before end`, input: `{"start": "2022-01-01T12:00:00", "end": "2022-01-01T23:59:59"}`, output: true},
{expr: `start before end`, input: `{"start": "2022-01-01", "end": "2022-01-02"}`, output: true},
{expr: `start after end`, input: `{"start": "2022-01-01T12:00:00Z", "end": "2022-01-01T23:59:59Z"}`, output: false},
// Length
{expr: `"foo".length`, output: 3},
{expr: `str.length`, input: `{"str": "abcdef"}`, output: 6},
{expr: `arr.length`, input: `{"arr": [1, 2]}`, output: 2},
// Lower/Upper
{expr: `"foo".upper`, output: "FOO"},
{expr: `str.lower`, input: `{"str": "ABCD"}`, output: "abcd"},
{expr: `str.lower == abcd`, input: `{"str": "ABCD"}`, opts: []InterpreterOption{UnquotedStrings}, skipTC: true, output: true},
// Where
{expr: `items where id > 3`, input: `{"items": [{"id": 1}, {"id": 3}, {"id": 5}, {"id": 7}]}`, output: []any{map[string]any{"id": 5.0}, map[string]any{"id": 7.0}}},
{expr: `items where id > 3 where labels contains "foo"`, input: `{"items": [{"id": 1, "labels": ["foo"]}, {"id": 3}, {"id": 5, "labels": ["foo"]}, {"id": 7}]}`, output: []any{map[string]any{"id": 5.0, "labels": []any{"foo"}}}},
{expr: `(items where id > 3).length == 2`, input: `{"items": [{"id": 1}, {"id": 3}, {"id": 5}, {"id": 7}]}`, output: true},
{expr: `not (items where id > 3)`, input: `{"items": [{"id": 1}, {"id": 3}, {"id": 5}, {"id": 7}]}`, output: false},
{expr: `items where id > 3`, input: `{}`, skipTC: true, output: nil},
{expr: `foo where method == "GET"`, input: `{"foo": {"op1": {"method": "GET", "path": "/op1"}, "op2": {"method": "PUT", "path": "/op2"}, "op3": {"method": "DELETE", "path": "/op3"}}}`, output: []any{map[string]any{"method": "GET", "path": "/op1"}}},
{expr: `foo where method == "GET"`, inputParsed: map[any]any{"foo": map[any]any{"op1": map[any]any{"method": "GET", "path": "/op1"}, "op2": map[any]any{"method": "PUT", "path": "/op2"}, "op3": map[any]any{"method": "DELETE", "path": "/op3"}}}, output: []any{map[any]any{"method": "GET", "path": "/op1"}}},
{expr: `items where id > 0`, input: `{"items": [{"id": 1}, "x", {"id": 2}]}`, output: []any{map[string]any{"id": 1.0}, map[string]any{"id": 2.0}}},
{expr: `foo where id > 0`, input: `{"foo": {"a": "x", "b": {"id": 1}, "c": {"id": 2}}}`, unordered: true, output: []any{map[string]any{"id": 1.0}, map[string]any{"id": 2.0}}},
{expr: `items where id > 3`, input: `{"items": []}`, output: []any{}},
{expr: `items where id > 3`, input: `{"items": 1}`, skipTC: true, output: []any{}},
// Order of operations
{expr: "1 + 2 + 3", output: 6.0},
{expr: "1 + 2 * 3", output: 7.0},
{expr: "(1 + 2) * 3", output: 9.0},
{expr: "6 / 3 + 2 * 5", output: 12.0},
// failure
{expr: "foo + 1", input: `{}`, err: "no property foo"},
{expr: "6 -", err: "incomplete expression"},
{expr: `foo.bar + "baz"`, input: `{"foo": 1}`, err: "no property bar"},
{expr: `foo + 1`, input: `{"foo": [1, 2]}`, err: "cannot operate on incompatible types"},
{expr: `foo > 1`, input: `{"foo": []}`, err: "cannot compare array[unknown] with number"},
{expr: `foo[1-]`, input: `{"foo": "hello"}`, err: "unexpected right-bracket"},
{expr: `not (1- <= 5)`, err: "missing right operand"},
{expr: `(1 >=)`, err: "unexpected right-paren"},
{expr: `foo[foo[0] != bar]`, input: `{"foo": [1, 2, 3], "bar": true}`, err: "array index must be number or slice"},
{expr: `1 < "foo"`, err: "unable to convert to number"},
{expr: `1 <`, err: "incomplete expression"},
{expr: `1 +`, err: "incomplete expression"},
{expr: `1 ]`, err: "expected eof but found right-bracket"},
{expr: `0.5 + 1"`, err: "unterminated string"},
{expr: `0.5 > "some kind of string"`, err: "unable to convert to number"},
{expr: `foo beginswith "bar"`, input: `{"foo": "bar"}`, err: "expected eof"},
{expr: `1 / (foo * 1)`, input: `{"foo": 0}`, err: "cannot divide by zero"},
{expr: `1 before "2020-01-01"`, err: "unable to convert 1 to date or time"},
{expr: `"2020-01-01" after "invalid"`, err: "unable to convert invalid to date or time"},
{expr: `a[2:0]`, input: `{"a": [0, 1, 2]}`, err: "slice start cannot be greater than end"},
{expr: `a[2:0]`, input: `{"a": "hello"}`, err: "slice start cannot be greater than end"},
{expr: `a[0][-7]`, input: `{"a": [[]]}`, skipTC: true, err: "invalid index"},
{expr: `a[0]`, input: `{"a": []}`, skipTC: true, err: "invalid index"},
}
for _, tc := range cases {
t.Run(tc.expr, func(t *testing.T) {
var input any
if tc.inputParsed != nil {
input = tc.inputParsed
} else if tc.input != "" {
if err := json.Unmarshal([]byte(tc.input), &input); err != nil {
t.Fatal(err)
}
}
types := input
if tc.skipTC {
// Skip type check
types = nil
}
ast, err := Parse(tc.expr, types, tc.opts...)
if ast != nil {
t.Log("graph G {\n" + ast.Dot("") + "\n}")
}
if tc.err != "" {
if err != nil {
if strings.Contains(err.Error(), tc.err) {
return
}
t.Fatal(err.Pretty(tc.expr))
}
} else {
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
}
result, err := Run(ast, input, tc.opts...)
if tc.err != "" {
if err == nil {
t.Fatal("expected error but found none")
}
if strings.Contains(err.Error(), tc.err) {
return
}
t.Fatal(err.Pretty(tc.expr))
} else {
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if tc.unordered {
expectedSlice, ok := tc.output.([]any)
if !ok {
t.Fatalf("unordered test expected []any output, got %T", tc.output)
}
resultSlice, ok := result.([]any)
if !ok {
t.Fatalf("unordered test expected []any result, got %T", result)
}
if len(expectedSlice) != len(resultSlice) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
used := make([]bool, len(resultSlice))
for _, expected := range expectedSlice {
matched := false
for idx, actual := range resultSlice {
if used[idx] {
continue
}
if reflect.DeepEqual(expected, actual) {
used[idx] = true
matched = true
break
}
}
if !matched {
t.Fatalf("expected %v but found %v", tc.output, result)
}
}
return
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
}
})
}
}
func TestTypedFunctions(t *testing.T) {
input := map[string]any{
"add": func(a, b int) int { return a + b },
"ratio": func(a int, b float64) float64 { return float64(a) / b },
"isAdmin": func(role string) bool { return role == "admin" },
"concat": func(left, right string) string { return left + right },
"toggle": func(v bool) bool { return !v },
"uintAdd": func(a uint, b uint8) uint64 { return uint64(a + uint(b)) },
"id": func() int { return 123 },
"name": func() string { return "MEXPR" },
"enabled": func() bool { return true },
"a": 2,
"b": 3,
"enabled2": false,
"role": "admin",
"prefix": "m",
"suffix": "expr",
}
type test struct {
expr string
output any
err string
}
cases := []test{
{expr: "add(a, b)", output: 5},
{expr: "ratio(9, 2) > 4", output: true},
{expr: `isAdmin(role)`, output: true},
{expr: `concat(prefix, suffix) == "mexpr"`, output: true},
{expr: "toggle(enabled2)", output: true},
{expr: "uintAdd(a, b) == 5", output: true},
{expr: "id + 1", output: 124.0},
{expr: "name.lower == \"mexpr\"", output: true},
{expr: "name.length == 5", output: true},
{expr: "enabled and a > 1", output: true},
{expr: "add(1.9, 2.1)", output: 3},
{expr: "add(a)", err: "expects 2 parameter"},
{expr: "isAdmin(a)", err: "expects string but found number"},
{expr: "toggle(a)", err: "expects boolean but found number"},
{expr: "missing()", err: "function missing not found"},
}
for _, tc := range cases {
t.Run(tc.expr, func(t *testing.T) {
ast, err := Parse(tc.expr, input)
if tc.err != "" {
if err == nil {
t.Fatal("expected error but found none")
}
if !strings.Contains(err.Error(), tc.err) {
t.Fatal(err.Pretty(tc.expr))
}
return
}
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, input, StrictMode)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestTypedSlices(t *testing.T) {
input := map[string]any{
"ints": []int{1, 2, 3},
"floats": []float64{1.5, 2.5, 3.5},
"strings": []string{"alpha", "beta", "gamma"},
"bounds": []int{0, 1},
}
cases := []struct {
expr string
output any
}{
{expr: "ints[1]", output: 2},
{expr: "ints[1:]", output: []int{2, 3}},
{expr: "ints[bounds]", output: []int{1, 2}},
{expr: "ints + ints", output: []int{1, 2, 3, 1, 2, 3}},
{expr: `2 in ints`, output: true},
{expr: `strings contains "beta"`, output: true},
{expr: `strings[1]`, output: "beta"},
{expr: `floats.length`, output: 3},
}
for _, tc := range cases {
t.Run(tc.expr, func(t *testing.T) {
ast, err := Parse(tc.expr, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestReflectionBackedSlices(t *testing.T) {
input := map[string]any{
"uints": []uint{1, 2, 3},
"emptyUints": []uint{},
}
cases := []struct {
expr string
output any
}{
{expr: "uints[1]", output: uint(2)},
{expr: "uints[:1]", output: []uint{1, 2}},
{expr: "uints[1:2]", output: []uint{2, 3}},
{expr: "uints + uints", output: []any{uint(1), uint(2), uint(3), uint(1), uint(2), uint(3)}},
{expr: `2 in uints`, output: true},
{expr: `uints.length`, output: 3},
{expr: `uints and 1`, output: true},
{expr: `emptyUints or 1`, output: true},
}
for _, tc := range cases {
t.Run(tc.expr, func(t *testing.T) {
ast, err := Parse(tc.expr, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestTruthinessConversions(t *testing.T) {
cases := []struct {
name string
expr string
input map[string]any
output any
}{
{name: "int64 true", expr: "value and 1", input: map[string]any{"value": int64(2)}, output: true},
{name: "int64 false", expr: "value or 0", input: map[string]any{"value": int64(-1)}, output: false},
{name: "uint8 true", expr: "value and 1", input: map[string]any{"value": uint8(1)}, output: true},
{name: "float32 false", expr: "value or 0", input: map[string]any{"value": float32(0)}, output: false},
{name: "bytes true", expr: "value and 1", input: map[string]any{"value": []byte("x")}, output: true},
{name: "bytes false", expr: "value or 0", input: map[string]any{"value": []byte{}}, output: false},
{name: "map any true", expr: "value and 1", input: map[string]any{"value": map[any]any{"k": 1}}, output: true},
{name: "map any false", expr: "value or 0", input: map[string]any{"value": map[any]any{}}, output: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ast, err := Parse(tc.expr, tc.input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, tc.input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestAdditionalNumericConversions(t *testing.T) {
cases := []struct {
name string
expr string
input map[string]any
output any
}{
{name: "int8 and uint16", expr: "a + b", input: map[string]any{"a": int8(2), "b": uint16(3)}, output: 5.0},
{name: "float32 and literal", expr: "a + 2", input: map[string]any{"a": float32(1.5)}, output: 3.5},
{name: "numeric equality", expr: "a == b", input: map[string]any{"a": int16(1), "b": uint8(1)}, output: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ast, err := Parse(tc.expr, tc.input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, tc.input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestReflectionBackedArrays(t *testing.T) {
input := map[string]any{
"arr": [3]uint{1, 2, 3},
"tail": [2]uint{4, 5},
}
cases := []struct {
expr string
output any
}{
{expr: "arr[1]", output: uint(2)},
{expr: "arr[:1]", output: []uint{1, 2}},
{expr: "arr + tail", output: []any{uint(1), uint(2), uint(3), uint(4), uint(5)}},
{expr: "2 in arr", output: true},
}
for _, tc := range cases {
t.Run(tc.expr, func(t *testing.T) {
ast, err := Parse(tc.expr, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
result, err := Run(ast, input)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
if !reflect.DeepEqual(tc.output, result) {
t.Fatalf("expected %v but found %v", tc.output, result)
}
})
}
}
func TestEmptyArrayTypeCheck(t *testing.T) {
ast, err := Parse(`items where id > 3`, map[string]any{"items": []any{}})
if err != nil {
t.Fatal(err.Pretty(`items where id > 3`))
}
result, err := Run(ast, map[string]any{"items": []any{}})
if err != nil {
t.Fatal(err.Pretty(`items where id > 3`))
}
if !reflect.DeepEqual([]any{}, result) {
t.Fatalf("expected empty result, got %v", result)
}
}
func TestEmptyObjectTypeCheck(t *testing.T) {
ast, err := Parse(`items where id > 3`, map[string]any{"items": map[string]any{}})
if err != nil {
t.Fatal(err.Pretty(`items where id > 3`))
}
result, err := Run(ast, map[string]any{"items": map[string]any{}})
if err != nil {
t.Fatal(err.Pretty(`items where id > 3`))
}
if !reflect.DeepEqual([]any{}, result) {
t.Fatalf("expected empty result, got %v", result)
}
}
func TestWhereRequiresArrayOrObject(t *testing.T) {
_, err := Parse(`items where id > 3`, map[string]any{"items": 1})
if err == nil {
t.Fatal("expected error")
}
if err.Error() != "where clause requires an array or object, but found number" {
t.Fatalf("unexpected error: %v", err)
}
}
func TestNestedNumericEquality(t *testing.T) {
result, err := Eval("a == b", map[string]any{
"a": []int{1},
"b": []float64{1},
})
if err != nil {
t.Fatal(err)
}
if result != true {
t.Fatalf("expected true but found %v", result)
}
}
func TestTypedFunctionsMapAny(t *testing.T) {
input := map[any]any{
"upper": func(s string) string { return strings.ToUpper(s) },
"value": "mexpr",
}
ast, err := Parse("upper(value)", input)
if err != nil {
t.Fatal(err.Pretty("upper(value)"))
}
result, err := Run(ast, input, StrictMode)
if err != nil {
t.Fatal(err.Pretty("upper(value)"))
}
if result != "MEXPR" {
t.Fatalf("expected MEXPR but found %v", result)
}
}
func TestTypedFunctionsUnsupportedSignatures(t *testing.T) {
type test struct {
name string
expr string
input map[string]any
err string
}
cases := []test{
{
name: "variadic",
expr: "join(a)",
input: map[string]any{
"join": func(values ...string) string { return strings.Join(values, ",") },
"a": "x",
},
err: "unsupported function type for join",
},
{
name: "multiple returns",
expr: "pair(a)",
input: map[string]any{
"pair": func(v string) (string, string) { return v, v },
"a": "x",
},
err: "unsupported function type for pair",
},
{
name: "non scalar param",
expr: "sum(items)",
input: map[string]any{
"sum": func(values []int) int { return len(values) },
"items": []any{1, 2},
},
err: "unsupported function type for sum",
},
{
name: "non scalar return",
expr: "items()",
input: map[string]any{
"items": func() []string { return []string{"a"} },
},
err: "unsupported function type for items",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := Parse(tc.expr, tc.input)
if err == nil {
t.Fatal("expected error but found none")
}
if !strings.Contains(err.Error(), tc.err) {
t.Fatal(err.Pretty(tc.expr))
}
})
}
}
func TestTypeCheckFunctions(t *testing.T) {
type test struct {
name string
expr string
input any
err string
}
cases := []test{
{
name: "typed function call",
expr: "add(a, b)",
input: map[string]any{
"add": func(a, b int) int { return a + b },
"a": 2,
"b": 3,
},
},
{
name: "lazy numeric value",
expr: "id + 1",
input: map[string]any{
"id": func() int { return 123 },
},
},
{
name: "lazy string pseudo property",
expr: "name.upper == \"MEXPR\"",
input: map[string]any{
"name": func() string { return "mexpr" },
},
},
{
name: "arity mismatch",
expr: "add(a)",
input: map[string]any{
"add": func(a, b int) int { return a + b },
"a": 2,
},
err: "expects 2 parameter(s), got 1",
},
{
name: "argument type mismatch",
expr: "toggle(a)",
input: map[string]any{
"toggle": func(v bool) bool { return !v },
"a": 2,
},
err: "expects boolean but found number",
},
{
name: "missing function",
expr: "missing()",
input: map[string]any{},
err: "function missing not found",
},
{
name: "unsupported signature",
expr: "items()",
input: map[string]any{
"items": func() []string { return []string{"a"} },
},
err: "unsupported function type for items",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ast, err := Parse(tc.expr, nil)
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
err = TypeCheck(ast, tc.input)
if tc.err != "" {
if err == nil {
t.Fatal("expected error but found none")
}
if !strings.Contains(err.Error(), tc.err) {
t.Fatal(err.Pretty(tc.expr))
}
return
}
if err != nil {
t.Fatal(err.Pretty(tc.expr))
}
})
}
}
func FuzzMexpr(f *testing.F) {
f.Fuzz(func(t *testing.T, s string) {
Eval(s, nil)
Eval(s, map[string]any{
"b": true,
"i": 5,
"f": 1.0,
"s": "Hello",
"a": []any{false, 1, "a"},
"o": map[any]any{
"prop": 123,
},
})
})
}
func Benchmark(b *testing.B) {
benchmarks := []struct {
name string
mexpr string
expr string
result any
}{
{"field", `baz`, `baz`, "value"},
{"comparison", `foo.bar > 1000`, `foo.bar > 1000`, true},
{"logical", `1 > 2 or 3 > 4`, `1 > 2 or 3 > 4`, false},
{"math", `foo.bar + 1`, `foo.bar + 1`, 1000000001.0},
{"string", `baz startsWith "va"`, `baz startsWith "va"`, true},
{"index", `arr[1]`, `arr[1]`, 2},
{
name: "complex",
mexpr: `foo.bar / (1 * 1024 * 1024) >= 1.0 and "v" in baz and baz.length > 3 and arr[2:].length == 1`,
expr: `foo.bar / (1 * 1024 * 1024) >= 1.0 and baz contains "v" and len(baz) > 3 and len(arr[2:]) == 1`,
result: true,
},
}
var r any
input := map[string]any{
"foo": map[string]any{
"bar": 1000000000.0,
},
"baz": "value",
"arr": []any{1, 2, 3},
}
for _, bm := range benchmarks {
b.Run("mexpr-"+bm.name+"-slow", func(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
ast, _ := Parse(bm.mexpr, input)
r, _ = Run(ast, input, StrictMode)
}
if !reflect.DeepEqual(bm.result, r) {
b.Fatalf("expected %v but found %v", bm.result, r)
}
})
// b.Run(" expr-"+bm.name+"-slow", func(b *testing.B) {
// b.ReportAllocs()
// for n := 0; n < b.N; n++ {
// r, _ = expr.Eval(bm.expr, input)
// }
// assert.Equal(b, bm.result, r)
// })
}
for _, bm := range benchmarks {
b.Run("mexpr-"+bm.name+"-cached", func(b *testing.B) {
b.ReportAllocs()
ast, err := Parse(bm.mexpr, input)
if err != nil {
b.Fatal(err)
}
i := NewInterpreter(ast)
b.ResetTimer()
for n := 0; n < b.N; n++ {
r, _ = i.Run(input)
}
if !reflect.DeepEqual(bm.result, r) {
b.Fatalf("expected %v but found %v", bm.result, r)
}
})
// b.Run(" expr-"+bm.name+"-cached", func(b *testing.B) {
// b.ReportAllocs()
// program, err := expr.Compile(bm.expr)
// assert.NoError(b, err)
// b.ResetTimer()
// for n := 0; n < b.N; n++ {
// r, _ = expr.Run(program, input)
// }
// assert.Equal(b, bm.result, r)
// })
}
}