-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.go
More file actions
1233 lines (1188 loc) · 37.6 KB
/
program.go
File metadata and controls
1233 lines (1188 loc) · 37.6 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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package expr
import (
"context"
"fmt"
"go/ast"
"go/token"
"math"
"reflect"
"strconv"
)
// Program is a compiled expression. Programs are immutable and safe for
// concurrent evaluation across goroutines.
type Program struct {
source string
root ast.Expr
funcs map[string]any
prepared map[string]*preparedFunc
fieldTags *structTagConfig
// callCache maps CallExpr nodes to a pre-resolved preparedFunc for
// the common case of a bare-identifier call target that resolves to
// a registered function and is not shadowed by the runtime env.
// Populated during compile(). Absent entries fall through to the
// normal runtime resolution path.
callCache map[*ast.CallExpr]*preparedFunc
// litCache maps BasicLit nodes to their pre-parsed value so
// evalLiteral is a single map lookup instead of repeating
// strconv work on every Run.
litCache map[*ast.BasicLit]any
}
// compile walks the root AST once to populate the lookup caches used
// during Run and to fold constant subtrees. Pre-resolving what we can
// at Compile time keeps the hot path allocation-free and
// reflection-free for common shapes.
func (p *Program) compile() {
p.callCache = map[*ast.CallExpr]*preparedFunc{}
p.litCache = map[*ast.BasicLit]any{}
p.root = p.prewalk(p.root)
}
// constValue reports the pre-computed value of a folded/literal node,
// if any. It recognizes BasicLit (via litCache) and the three
// keyword-backed idents true/false/nil.
func (p *Program) constValue(node ast.Expr) (any, bool) {
switch n := node.(type) {
case *ast.BasicLit:
if v, ok := p.litCache[n]; ok {
return v, true
}
case *ast.Ident:
switch n.Name {
case "true":
return true, true
case "false":
return false, true
case "nil":
return nil, true
}
}
return nil, false
}
// wrapConst turns a folded value into an ast.Expr that eval can see
// as a constant. BasicLit-backed kinds populate litCache so eval
// skips the strconv re-parse. Bools and nil use the keyword idents.
func (p *Program) wrapConst(v any) (ast.Expr, bool) {
switch x := v.(type) {
case bool:
if x {
return &ast.Ident{Name: "true"}, true
}
return &ast.Ident{Name: "false"}, true
case nil:
return &ast.Ident{Name: "nil"}, true
case int64:
lit := &ast.BasicLit{Kind: token.INT, Value: strconv.FormatInt(x, 10)}
p.litCache[lit] = x
return lit, true
case float64:
if math.IsNaN(x) || math.IsInf(x, 0) {
return nil, false
}
lit := &ast.BasicLit{Kind: token.FLOAT, Value: strconv.FormatFloat(x, 'g', -1, 64)}
p.litCache[lit] = x
return lit, true
case string:
lit := &ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(x)}
p.litCache[lit] = x
return lit, true
}
return nil, false
}
func (p *Program) prewalk(node ast.Expr) ast.Expr {
switch n := node.(type) {
case *ast.BasicLit:
if v, err := evalLiteral(n); err == nil {
p.litCache[n] = v
}
return n
case *ast.ParenExpr:
n.X = p.prewalk(n.X)
// Unwrap parens around constants so constValue sees them.
if _, ok := p.constValue(n.X); ok {
return n.X
}
return n
case *ast.UnaryExpr:
n.X = p.prewalk(n.X)
if xv, ok := p.constValue(n.X); ok {
if v, err := applyUnary(n.Op, xv); err == nil {
if wrapped, ok := p.wrapConst(v); ok {
return wrapped
}
}
}
return n
case *ast.BinaryExpr:
n.X = p.prewalk(n.X)
n.Y = p.prewalk(n.Y)
// Skip logical ops: their short-circuit semantics are visible
// to side-effects, and the LAND/LOR path in evalBinary is
// fast enough that folding a pure-literal `true && false`
// isn't worth a second code path.
if n.Op != token.LAND && n.Op != token.LOR {
if xv, ok := p.constValue(n.X); ok {
if yv, ok2 := p.constValue(n.Y); ok2 {
if v, err := applyBinary(n.Op, xv, yv); err == nil {
if wrapped, ok := p.wrapConst(v); ok {
return wrapped
}
}
}
}
}
return n
case *ast.SelectorExpr:
n.X = p.prewalk(n.X)
return n
case *ast.IndexExpr:
n.X = p.prewalk(n.X)
n.Index = p.prewalk(n.Index)
return n
case *ast.CallExpr:
// Only cache bare-identifier call targets that resolve to a
// registered, prepared function AND are not higher-order
// special forms. The form dispatcher needs the raw CallExpr.
// Keyword sentinels (`__expr_if__`, etc.) are translated back
// to their user-visible names so the prepared lookup keys on
// what the user actually wrote.
if ident, ok := n.Fun.(*ast.Ident); ok {
if _, isForm := higherOrderForms[ident.Name]; !isForm {
name := displayIdent(ident.Name)
if pf, ok := p.prepared[name]; ok && (pf.native != nil || pf.fv.IsValid()) {
p.callCache[n] = pf
}
}
}
for i, a := range n.Args {
n.Args[i] = p.prewalk(a)
}
return n
case *ast.CompositeLit:
for i, e := range n.Elts {
if kv, ok := e.(*ast.KeyValueExpr); ok {
kv.Key = p.prewalk(kv.Key)
kv.Value = p.prewalk(kv.Value)
} else {
n.Elts[i] = p.prewalk(e)
}
}
return n
}
return node
}
// applyUnary is the constant-folding helper for unary ops. It mirrors
// the runtime evalUnary logic but works on already-evaluated values
// so the fold pass never re-enters the main evaluator.
func applyUnary(op token.Token, v any) (any, error) {
switch op {
case token.NOT:
return !isTruthy(v), nil
case token.SUB:
if i, ok := toInt64(v); ok {
if i == math.MinInt64 {
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
}
return -i, nil
}
if f, ok := toFloat64(v); ok {
return -f, nil
}
return nil, fmt.Errorf("%w: cannot negate %T", ErrEvaluate, v)
case token.ADD:
if _, ok := toInt64(v); ok {
return v, nil
}
if _, ok := toFloat64(v); ok {
return v, nil
}
return nil, fmt.Errorf("%w: cannot apply unary + to %T", ErrEvaluate, v)
}
return nil, fmt.Errorf("%w: unsupported unary operator %v", ErrEvaluate, op)
}
var _ runner = (*Program)(nil)
// Source returns the original expression text.
func (p *Program) Source() string { return p.source }
// Run evaluates the program against env. env may be a map[string]any, a
// struct, or a pointer to a struct — identifier lookups resolve to map
// keys, struct fields, or bound methods (in that order of preference).
// Identifiers not found in env are then looked up against the functions
// registered via [WithFunctions] / [WithBuiltins]. The literals true,
// false, and nil are recognized directly. Any unsupported syntax node
// (slice expressions, type assertions, function literals, channel
// operations, etc.) returns an error wrapping ErrEvaluate.
//
// Env values that are themselves Go functions are callable from the
// expression: `f(x)` first looks up `f` in env, and if it finds a
// function value it is invoked through the same reflect-based dispatch
// used for [WithFunctions]-registered functions. Prefer registering
// functions via Options when possible — those go through a
// faster prepared path and participate in "did you mean…" diagnostics
// — but putting callables in env is a useful escape hatch for
// per-request closures or hosts that want to rebind helpers on every
// Run.
//
// expr checks ctx.Err() at the top of every AST node, so any
// pure-expression evaluation exits within one node of cancellation.
// Registered functions whose first parameter is context.Context receive
// ctx automatically; well-behaved callees can then cancel their own
// work. expr does not forcibly terminate user code that ignores ctx
// — Go provides no mechanism to kill a goroutine, and recovering from a
// blocked callee would leak it. Passing a nil ctx falls back to
// context.Background.
func (p *Program) Run(ctx context.Context, env any) (any, error) {
if ctx == nil {
ctx = context.Background()
}
return p.eval(ctx, p.root, env, 0)
}
func (p *Program) eval(ctx context.Context, node ast.Expr, env any, depth int) (any, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if depth >= MaxEvalDepth {
return nil, fmt.Errorf("%w: expression nested too deeply (limit %d)", ErrEvaluate, MaxEvalDepth)
}
depth++
switch n := node.(type) {
case *ast.BasicLit:
if v, ok := p.litCache[n]; ok {
return v, nil
}
return evalLiteral(n)
case *ast.Ident:
return evalIdent(n, env, p.funcs, p.fieldTags)
case *ast.ParenExpr:
return p.eval(ctx, n.X, env, depth)
case *ast.UnaryExpr:
return p.evalUnary(ctx, n, env, depth)
case *ast.BinaryExpr:
return p.evalBinary(ctx, n, env, depth)
case *ast.SelectorExpr:
return p.evalSelector(ctx, n, env, depth)
case *ast.IndexExpr:
return p.evalIndex(ctx, n, env, depth)
case *ast.CallExpr:
return p.evalCall(ctx, n, env, depth)
case *ast.CompositeLit:
return p.evalCompositeLit(ctx, n, env, depth)
}
return nil, fmt.Errorf("%w: unsupported syntax %T", ErrEvaluate, node)
}
// evalCompositeLit evaluates the two composite-literal shapes expr
// accepts: `[]any{...}` and `map[string]any{...}`. These are what the
// jsonlit rewrite produces for bare `[...]` and `{...}` literals, and
// they are also accepted directly in source.
//
// Other type forms (fixed-size arrays, typed slices like `[]int{}`,
// maps with non-string keys, struct literals, etc.) are rejected —
// expr is untyped at the value level, so widening the accepted set
// would not change what the evaluator can represent.
func (p *Program) evalCompositeLit(ctx context.Context, n *ast.CompositeLit, env any, depth int) (any, error) {
switch typ := n.Type.(type) {
case *ast.ArrayType:
if typ.Len != nil {
return nil, fmt.Errorf("%w: fixed-size array literals are not supported", ErrEvaluate)
}
if ident, ok := typ.Elt.(*ast.Ident); !ok || ident.Name != "any" {
return nil, fmt.Errorf("%w: only []any slice literals are supported", ErrEvaluate)
}
out := make([]any, len(n.Elts))
for i, elt := range n.Elts {
if _, isKV := elt.(*ast.KeyValueExpr); isKV {
return nil, fmt.Errorf("%w: keyed elements are not supported in []any literals", ErrEvaluate)
}
v, err := p.eval(ctx, elt, env, depth)
if err != nil {
return nil, err
}
out[i] = v
}
return out, nil
case *ast.MapType:
kIdent, kOk := typ.Key.(*ast.Ident)
vIdent, vOk := typ.Value.(*ast.Ident)
if !kOk || !vOk || kIdent.Name != "string" || vIdent.Name != "any" {
return nil, fmt.Errorf("%w: only map[string]any literals are supported", ErrEvaluate)
}
out := make(map[string]any, len(n.Elts))
for _, elt := range n.Elts {
kv, ok := elt.(*ast.KeyValueExpr)
if !ok {
return nil, fmt.Errorf("%w: map[string]any literal elements must be key:value pairs", ErrEvaluate)
}
k, err := p.eval(ctx, kv.Key, env, depth)
if err != nil {
return nil, err
}
ks, ok := k.(string)
if !ok {
return nil, fmt.Errorf("%w: map literal key must be string, got %T", ErrEvaluate, k)
}
v, err := p.eval(ctx, kv.Value, env, depth)
if err != nil {
return nil, err
}
out[ks] = v
}
return out, nil
case nil:
return nil, fmt.Errorf("%w: untyped composite literals are not supported", ErrEvaluate)
}
return nil, fmt.Errorf("%w: unsupported composite literal type %T", ErrEvaluate, n.Type)
}
func evalLiteral(n *ast.BasicLit) (any, error) {
switch n.Kind {
case token.INT:
i, err := strconv.ParseInt(n.Value, 0, 64)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrEvaluate, err)
}
return i, nil
case token.FLOAT:
f, err := strconv.ParseFloat(n.Value, 64)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrEvaluate, err)
}
return f, nil
case token.STRING:
s, err := strconv.Unquote(n.Value)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrEvaluate, err)
}
return s, nil
case token.CHAR:
s, err := strconv.Unquote(n.Value)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrEvaluate, err)
}
runes := []rune(s)
if len(runes) != 1 {
return nil, fmt.Errorf("%w: invalid char literal %q", ErrEvaluate, n.Value)
}
return int64(runes[0]), nil
}
return nil, fmt.Errorf("%w: unsupported literal kind %v", ErrEvaluate, n.Kind)
}
func evalIdent(n *ast.Ident, env any, funcs map[string]any, fieldTags *structTagConfig) (any, error) {
switch n.Name {
case "true":
return true, nil
case "false":
return false, nil
case "nil":
return nil, nil
}
// Keyword sentinels (`__expr_if__`, ...) lookup under their
// user-visible name so env entries and registered functions
// match what the user actually wrote.
name := displayIdent(n.Name)
if v, ok, err := lookupEnv(env, name, fieldTags); err != nil {
return nil, err
} else if ok {
return v, nil
}
if fn, ok := funcs[name]; ok {
return fn, nil
}
return nil, fmt.Errorf("%w: undefined identifier %q%s",
ErrEvaluate, name, identHint(env, funcs, name, fieldTags))
}
// lookupEnv resolves a top-level identifier against env. env may be a
// map[string]any, any map with string keys, a struct, a pointer to a
// struct, or an *itEnv wrapping one of the above. For structs, configured
// field tags participate in field lookup, and fields are preferred over
// methods when both match. Methods are returned as bound function values
// so they can be invoked by a CallExpr node. An itEnv binds `it` and
// `index` ahead of anything in its parent.
func lookupEnv(env any, name string, fieldTags *structTagConfig) (any, bool, error) {
if env == nil {
return nil, false, nil
}
if it, ok := env.(*itEnv); ok {
switch name {
case "it":
return it.it, true, nil
case "index":
return it.index, true, nil
}
return lookupEnv(it.parent, name, fieldTags)
}
if m, ok := env.(map[string]any); ok {
v, ok := m[name]
return v, ok, nil
}
rv := reflect.ValueOf(env)
// Check methods on the original (possibly pointer) value first so
// pointer-receiver methods are visible — but prefer struct fields if
// both exist with the same name.
orig := rv
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
return nil, false, nil
}
rv = rv.Elem()
}
switch rv.Kind() {
case reflect.Struct:
fv, ok, err := structFieldByName(rv, name, fieldTags)
if err != nil {
return nil, false, err
}
if ok && fv.CanInterface() {
return fv.Interface(), true, nil
}
if mv := orig.MethodByName(name); mv.IsValid() {
return methodCallable(name, mv), true, nil
}
case reflect.Map:
if rv.Type().Key().Kind() == reflect.String {
mv := rv.MapIndex(mapStringKey(rv.Type().Key(), name))
if mv.IsValid() {
return mv.Interface(), true, nil
}
}
}
return nil, false, nil
}
func (p *Program) evalUnary(ctx context.Context, n *ast.UnaryExpr, env any, depth int) (any, error) {
v, err := p.eval(ctx, n.X, env, depth)
if err != nil {
return nil, err
}
switch n.Op {
case token.NOT:
return !isTruthy(v), nil
case token.SUB:
if i, ok := toInt64(v); ok {
if i == math.MinInt64 {
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
}
return -i, nil
}
if f, ok := toFloat64(v); ok {
return -f, nil
}
return nil, fmt.Errorf("%w: cannot negate %T", ErrEvaluate, v)
case token.ADD:
if _, ok := toInt64(v); ok {
return v, nil
}
if _, ok := toFloat64(v); ok {
return v, nil
}
return nil, fmt.Errorf("%w: cannot apply unary + to %T", ErrEvaluate, v)
}
return nil, fmt.Errorf("%w: unsupported unary operator %v", ErrEvaluate, n.Op)
}
func (p *Program) evalBinary(ctx context.Context, n *ast.BinaryExpr, env any, depth int) (any, error) {
// Short-circuit logical operators: right-hand side is not evaluated
// when the left-hand side is sufficient to determine the result.
// Both operators return the deciding operand (matching Python
// `and`/`or`, JS `||`/`&&`), not a coerced bool. This composes with
// truthiness for idioms like `name || "(none)"` and `xs || []`.
if n.Op == token.LAND || n.Op == token.LOR {
lhs, err := p.eval(ctx, n.X, env, depth)
if err != nil {
return nil, err
}
lt := isTruthy(lhs)
if n.Op == token.LAND && !lt {
return lhs, nil
}
if n.Op == token.LOR && lt {
return lhs, nil
}
return p.eval(ctx, n.Y, env, depth)
}
lhs, err := p.eval(ctx, n.X, env, depth)
if err != nil {
return nil, err
}
rhs, err := p.eval(ctx, n.Y, env, depth)
if err != nil {
return nil, err
}
return applyBinary(n.Op, lhs, rhs)
}
func applyBinary(op token.Token, lhs, rhs any) (any, error) {
// String concatenation and comparison.
if ls, lok := asString(lhs); lok {
if rs, rok := asString(rhs); rok {
return applyStringBinary(op, ls, rs)
}
}
// Equality across arbitrary comparable types.
if op == token.EQL || op == token.NEQ {
if eq, ok := looseEqual(lhs, rhs); ok {
if op == token.NEQ {
return !eq, nil
}
return eq, nil
}
}
// Numeric operations: stay in int64 when both sides are integral,
// promote to float64 otherwise.
li, liOk := toInt64(lhs)
ri, riOk := toInt64(rhs)
if liOk && riOk {
switch op {
case token.ADD:
if v, ok := checkedAddInt64(li, ri); ok {
return v, nil
}
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
case token.SUB:
if v, ok := checkedSubInt64(li, ri); ok {
return v, nil
}
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
case token.MUL:
if v, ok := checkedMulInt64(li, ri); ok {
return v, nil
}
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
case token.QUO:
if ri == 0 {
return nil, fmt.Errorf("%w: division by zero", ErrEvaluate)
}
if li == math.MinInt64 && ri == -1 {
return nil, fmt.Errorf("%w: integer overflow", ErrEvaluate)
}
return li / ri, nil
case token.REM:
if ri == 0 {
return nil, fmt.Errorf("%w: modulo by zero", ErrEvaluate)
}
return li % ri, nil
case token.LSS:
return li < ri, nil
case token.GTR:
return li > ri, nil
case token.LEQ:
return li <= ri, nil
case token.GEQ:
return li >= ri, nil
}
}
lf, lfOk := toFloat64(lhs)
rf, rfOk := toFloat64(rhs)
if lfOk && rfOk {
switch op {
case token.ADD:
return lf + rf, nil
case token.SUB:
return lf - rf, nil
case token.MUL:
return lf * rf, nil
case token.QUO:
if rf == 0 {
return nil, fmt.Errorf("%w: division by zero", ErrEvaluate)
}
return lf / rf, nil
case token.REM:
if rf == 0 {
return nil, fmt.Errorf("%w: modulo by zero", ErrEvaluate)
}
return math.Mod(lf, rf), nil
case token.LSS:
return lf < rf, nil
case token.GTR:
return lf > rf, nil
case token.LEQ:
return lf <= rf, nil
case token.GEQ:
return lf >= rf, nil
}
}
return nil, fmt.Errorf("%w: operator %v not supported for %T and %T", ErrEvaluate, op, lhs, rhs)
}
func applyStringBinary(op token.Token, lhs, rhs string) (any, error) {
switch op {
case token.ADD:
return lhs + rhs, nil
case token.EQL:
return lhs == rhs, nil
case token.NEQ:
return lhs != rhs, nil
case token.LSS:
return lhs < rhs, nil
case token.GTR:
return lhs > rhs, nil
case token.LEQ:
return lhs <= rhs, nil
case token.GEQ:
return lhs >= rhs, nil
}
return nil, fmt.Errorf("%w: operator %v not supported for string and string", ErrEvaluate, op)
}
func checkedAddInt64(a, b int64) (int64, bool) {
if (b > 0 && a > math.MaxInt64-b) || (b < 0 && a < math.MinInt64-b) {
return 0, false
}
return a + b, true
}
func checkedSubInt64(a, b int64) (int64, bool) {
if (b < 0 && a > math.MaxInt64+b) || (b > 0 && a < math.MinInt64+b) {
return 0, false
}
return a - b, true
}
func checkedMulInt64(a, b int64) (int64, bool) {
if a == 0 || b == 0 {
return 0, true
}
if (a == math.MinInt64 && b == -1) || (b == math.MinInt64 && a == -1) {
return 0, false
}
v := a * b
if v/b != a {
return 0, false
}
return v, true
}
func (p *Program) evalSelector(ctx context.Context, n *ast.SelectorExpr, env any, depth int) (any, error) {
// Fast path: an ident-rooted selector chain (a.b.c.d) can be walked
// entirely through reflect.Value, materializing only the leaf via
// Interface(). The general path below boxes every intermediate
// result through any, which copies struct field data — a 10 MiB
// embedded array gets memcpy'd on each access. The fast path skips
// plain map[string]any roots because the type-asserted map lookup
// in selectField is already faster than reflect MapIndex.
if v, ok, err := evalSelectorChainRV(n, env, depth, p.fieldTags); ok {
return v, err
}
recv, err := p.eval(ctx, n.X, env, depth)
if err != nil {
return nil, err
}
return selectField(recv, n.Sel.Name, p.fieldTags)
}
// evalSelectorChainRV walks an ident-rooted selector chain in reflect
// space. ok is true when the fast path was taken (regardless of error);
// when false the caller must use the general path. The fast path
// declines for non-ident roots, for plain map[string]any envs (the
// general path is faster there), and for itEnv lookups of `it`/`index`
// whose values do not benefit.
func evalSelectorChainRV(n *ast.SelectorExpr, env any, depth int, fieldTags *structTagConfig) (any, bool, error) {
if _, isMap := env.(map[string]any); isMap {
return nil, false, nil
}
// Collect chain names leaf-first and find the root.
var names []string
cur := ast.Expr(n)
for {
sel, isSel := cur.(*ast.SelectorExpr)
if !isSel {
break
}
names = append(names, sel.Sel.Name)
cur = sel.X
}
ident, ok := cur.(*ast.Ident)
if !ok {
return nil, false, nil
}
if depth+len(names) > MaxEvalDepth {
return nil, true, fmt.Errorf("%w: expression nested too deeply (limit %d)", ErrEvaluate, MaxEvalDepth)
}
switch ident.Name {
case "true", "false", "nil":
return nil, false, nil
}
rv, ok, err := lookupEnvRV(env, ident.Name, fieldTags)
if err != nil {
return nil, true, err
}
if !ok {
return nil, false, nil
}
for i := len(names) - 1; i >= 0; i-- {
next, err := selectFieldRV(rv, displayIdent(names[i]), fieldTags)
if err != nil {
return nil, true, err
}
rv = next
}
if !rv.IsValid() {
return nil, true, nil
}
if !rv.CanInterface() {
return nil, true, fmt.Errorf("%w: field %q not accessible",
ErrEvaluate, displayIdent(names[0]))
}
return rv.Interface(), true, nil
}
// lookupEnvRV mirrors lookupEnv but returns a reflect.Value so callers
// can chain field accesses without boxing intermediate struct values.
// Map and itEnv lookups still go through any internally because their
// stored values already live behind interfaces.
func lookupEnvRV(env any, name string, fieldTags *structTagConfig) (reflect.Value, bool, error) {
if env == nil {
return reflect.Value{}, false, nil
}
if it, ok := env.(*itEnv); ok {
switch name {
case "it":
return reflect.ValueOf(it.it), true, nil
case "index":
return reflect.ValueOf(it.index), true, nil
}
return lookupEnvRV(it.parent, name, fieldTags)
}
if m, ok := env.(map[string]any); ok {
v, ok := m[name]
if !ok {
return reflect.Value{}, false, nil
}
return reflect.ValueOf(v), true, nil
}
rv := reflect.ValueOf(env)
orig := rv
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
return reflect.Value{}, false, nil
}
rv = rv.Elem()
}
switch rv.Kind() {
case reflect.Struct:
fv, ok, err := structFieldByName(rv, name, fieldTags)
if err != nil {
return reflect.Value{}, false, err
}
if ok && fv.CanInterface() {
return fv, true, nil
}
if mv := orig.MethodByName(name); mv.IsValid() {
return reflect.ValueOf(methodCallable(name, mv)), true, nil
}
case reflect.Map:
if rv.Type().Key().Kind() == reflect.String {
mv := rv.MapIndex(mapStringKey(rv.Type().Key(), name))
if mv.IsValid() {
return mv, true, nil
}
}
}
return reflect.Value{}, false, nil
}
// selectFieldRV reads a field/key from rv without boxing the parent
// through any. It mirrors selectField's behavior on structs and
// string-keyed maps, transparently dereffing pointers and unwrapping
// interface values. Errors are produced lazily — the cold path may
// call Interface() to build a "did you mean" hint.
func selectFieldRV(rv reflect.Value, name string, fieldTags *structTagConfig) (reflect.Value, error) {
for rv.Kind() == reflect.Interface && !rv.IsNil() {
rv = rv.Elem()
}
if !rv.IsValid() {
return reflect.Value{}, fmt.Errorf("%w: cannot access %q on nil", ErrEvaluate, name)
}
if rv.Kind() == reflect.Pointer {
if rv.IsNil() {
return reflect.Value{}, fmt.Errorf("%w: cannot access %q on nil pointer", ErrEvaluate, name)
}
rv = rv.Elem()
}
switch rv.Kind() {
case reflect.Struct:
fv, ok, err := structFieldByName(rv, name, fieldTags)
if err != nil {
return reflect.Value{}, err
}
if !ok || !fv.IsValid() || !fv.CanInterface() {
return reflect.Value{}, fmt.Errorf("%w: field %q not found on %v%s",
ErrEvaluate, name, rv.Type(), fieldHint(rv.Interface(), name, fieldTags))
}
return fv, nil
case reflect.Map:
if rv.Type().Key().Kind() != reflect.String {
return reflect.Value{}, fmt.Errorf("%w: cannot select %q on map with non-string keys", ErrEvaluate, name)
}
mv := rv.MapIndex(mapStringKey(rv.Type().Key(), name))
if !mv.IsValid() {
return reflect.Value{}, fmt.Errorf("%w: key %q not found%s",
ErrEvaluate, name, fieldHint(rv.Interface(), name, fieldTags))
}
return mv, nil
}
return reflect.Value{}, fmt.Errorf("%w: cannot select %q on %v", ErrEvaluate, name, rv.Type())
}
func selectField(recv any, name string, fieldTags *structTagConfig) (any, error) {
// Translate rewritten identifiers (currently only `map`) back to
// their user-visible form so field/key/error lookups match what
// the user actually typed.
name = displayIdent(name)
if recv == nil {
return nil, fmt.Errorf("%w: cannot access %q on nil", ErrEvaluate, name)
}
if m, ok := recv.(map[string]any); ok {
v, ok := m[name]
if !ok {
return nil, fmt.Errorf("%w: key %q not found%s",
ErrEvaluate, name, fieldHint(recv, name, fieldTags))
}
return v, nil
}
rv := reflect.ValueOf(recv)
switch rv.Kind() {
case reflect.Map:
if rv.Type().Key().Kind() != reflect.String {
return nil, fmt.Errorf("%w: cannot select %q on map with non-string keys", ErrEvaluate, name)
}
mv := rv.MapIndex(mapStringKey(rv.Type().Key(), name))
if !mv.IsValid() {
return nil, fmt.Errorf("%w: key %q not found%s",
ErrEvaluate, name, fieldHint(recv, name, fieldTags))
}
return mv.Interface(), nil
case reflect.Struct:
fv, ok, err := structFieldByName(rv, name, fieldTags)
if err != nil {
return nil, err
}
if !ok || !fv.IsValid() {
return nil, fmt.Errorf("%w: field %q not found on %T%s",
ErrEvaluate, name, recv, fieldHint(recv, name, fieldTags))
}
if !fv.CanInterface() {
// Unexported field: deny access rather than panicking via Interface().
return nil, fmt.Errorf("%w: field %q not found on %T%s",
ErrEvaluate, name, recv, fieldHint(recv, name, fieldTags))
}
return fv.Interface(), nil
case reflect.Pointer:
if rv.IsNil() {
return nil, fmt.Errorf("%w: cannot access %q on nil pointer", ErrEvaluate, name)
}
return selectField(rv.Elem().Interface(), name, fieldTags)
}
return nil, fmt.Errorf("%w: cannot select %q on %T", ErrEvaluate, name, recv)
}
func (p *Program) evalIndex(ctx context.Context, n *ast.IndexExpr, env any, depth int) (any, error) {
// Fast path: filter(xs, p)[k] with a small constant k stops at the
// (k+1)-th match instead of materializing the full filtered slice.
if v, ok, err := p.tryFilterIndex(ctx, n, env, depth); ok {
return v, err
}
recv, err := p.eval(ctx, n.X, env, depth)
if err != nil {
return nil, err
}
idx, err := p.eval(ctx, n.Index, env, depth)
if err != nil {
return nil, err
}
return indexValue(recv, idx)
}
// tryFilterIndex recognises `filter(xs, predicate)[N]` where N is a
// non-negative integer literal and `filter` is the built-in special
// form (not shadowed by env or funcs). When matched, it iterates xs
// and stops as soon as the N-th matching element is found, mirroring
// the result of the general path without allocating the intermediate
// slice. ok is true when the fast path was taken.
func (p *Program) tryFilterIndex(ctx context.Context, n *ast.IndexExpr, env any, depth int) (any, bool, error) {
call, ok := n.X.(*ast.CallExpr)
if !ok {
return nil, false, nil
}
ident, ok := call.Fun.(*ast.Ident)
if !ok || ident.Name != "filter" || len(call.Args) != 2 {
return nil, false, nil
}
// Respect identifier shadowing: a user-registered or env-bound
// "filter" goes through the general call path.
if _, inEnv, err := lookupEnv(env, "filter", p.fieldTags); err != nil {
return nil, false, err
} else if inEnv {
return nil, false, nil
}
if _, inFuncs := p.funcs["filter"]; inFuncs {
return nil, false, nil
}
lit, ok := n.Index.(*ast.BasicLit)
if !ok || lit.Kind != token.INT {
return nil, false, nil
}
target, err := strconv.ParseInt(lit.Value, 0, 64)
if err != nil || target < 0 {
return nil, false, nil
}
// Stream the collection via reflect rather than materializing it
// through iterItems — for filter(xs, p)[0] over a 1000-element
// slice, the unstreamed path allocates 1000 any-boxes only to
// throw 999 of them away.
coll, err := p.eval(ctx, call.Args[0], env, depth)
if err != nil {
return nil, true, err
}
if coll == nil {
return nil, true, fmt.Errorf("%w: index %d out of range", ErrEvaluate, target)
}
rv := reflect.ValueOf(coll)
if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array {
return nil, true, fmt.Errorf("%w: filter expects a list as its first argument, got %T",
ErrEvaluate, coll)
}
scope := &itEnv{parent: env}
var seen int64
for i := 0; i < rv.Len(); i++ {
item := rv.Index(i).Interface()
scope.it = item
scope.index = int64(i)
v, err := p.eval(ctx, call.Args[1], scope, depth)
if err != nil {
return nil, true, wrapPredicateErr("filter", call.Args[1], i, err)
}
if !isTruthy(v) {
continue
}
if seen == target {
return item, true, nil
}
seen++
}
return nil, true, fmt.Errorf("%w: index %d out of range", ErrEvaluate, target)
}
func indexValue(recv, idx any) (any, error) {
if recv == nil {
return nil, fmt.Errorf("%w: cannot index nil", ErrEvaluate)
}
if m, ok := recv.(map[string]any); ok {
key, ok := idx.(string)
if !ok {
return nil, fmt.Errorf("%w: map index must be string, got %T", ErrEvaluate, idx)
}
v, ok := m[key]
if !ok {
return nil, fmt.Errorf("%w: key %q not found%s",
ErrEvaluate, key, fieldHint(recv, key, nil))
}
return v, nil
}
rv := reflect.ValueOf(recv)