arblang 0.1.24

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
Documentation
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
1001
1002
1003
1004
1005
//! Arb's computational substrate: arithmetic expressions are compiled to a
//! `fusevm::Chunk` and executed on the fusevm VM (Cranelift JIT for hot chunks).
//! This is what "arb runs on fusevm" means concretely — every computed value in
//! a spec flows through fusevm bytecode, not a bespoke evaluator.
//!
//! `x` is the pipeline input scalar; a bareword identifier (`amount`, `latency`)
//! is a field of the current record, resolved by the caller's closure. Both are
//! baked into the chunk as constants per evaluation, so no VM slot state is
//! assumed across `run()`.
//! Comparisons (`== != < <= > >=`) lower to fusevm's `Num*` ops and yield a
//! boolean; `eval_pred` reads the result via `Value::is_truthy` for `where`.

use fusevm::vm::{VMResult, VM};
use fusevm::{ChunkBuilder, Op, Value};
use std::cell::RefCell;

#[derive(Debug, Clone, Copy)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    /// Logical `and`/`or` over truthiness (each operand normalized to 0/1).
    And,
    Or,
}

#[derive(Debug, Clone)]
pub enum Expr {
    Num(f64),
    /// The pipeline input scalar.
    Var,
    /// A named field of the current record, resolved at eval time.
    Field(String),
    /// A live control reference (`.th` — an `input`/control widget's value),
    /// written `.name` in a predicate. `resolve_pipeline` substitutes it with a
    /// `Num` before eval when the control holds a number; unresolved -> NaN.
    Control(String),
    /// A string literal — only produced by substituting a string control.
    Str(String),
    /// `match(.q)` — substring test of the whole line against a control's text.
    /// Evaluated Rust-side (not on the numeric VM); empty control -> matches all.
    Match(Box<Expr>),
    /// `<field> in .lv` — set membership: keep lines whose FIELD value is in the
    /// control's comma-separated selected set. Empty set -> matches all.
    InSet(String, Box<Expr>),
    Neg(Box<Expr>),
    /// Logical negation: truthy input -> 0, falsy -> 1.
    Not(Box<Expr>),
    /// `name(arg, …)` — a call to an inline-Rust FFI export registered by a
    /// `rust { ... }` block. Numeric-only: each arg is evaluated to an f64 and
    /// marshaled as a `fusevm::Value::float`; the export's return is read back as
    /// an f64. An unregistered name (or a failed call) evaluates to NaN, so a
    /// comparison against it is simply false.
    Call(String, Vec<Expr>),
    /// Membership: `left in [a, b, c]` — truthy iff `left` equals any element
    /// (jq `IN`). Empty list is always falsy.
    InList(Box<Expr>, Vec<Expr>),
    /// Range membership: `left in lo..hi` — truthy iff `lo <= left <= hi`.
    InRange(Box<Expr>, Box<Expr>, Box<Expr>),
    /// Ternary `cond ? then : else` — only the taken branch is evaluated (real
    /// fusevm branching), so a guarded `x != 0 ? 100/x : 0` never divides by 0.
    Cond(Box<Expr>, Box<Expr>, Box<Expr>),
    Bin(BinOp, Box<Expr>, Box<Expr>),
}

/// Parse an expression: numbers, `x`, `+ - * / %`, comparisons
/// (`== != < <= > >=`), unary `-`, and parentheses.
pub fn parse(src: &str) -> Result<Expr, String> {
    let mut p = Parser {
        c: src.chars().collect(),
        i: 0,
        depth: 0,
    };
    let e = p.ternary()?;
    if p.peek().is_some() {
        return Err(format!("calc: unexpected `{}`", p.c[p.i]));
    }
    Ok(e)
}

/// Evaluate as a number with no field resolver (field refs -> NaN).
pub fn eval(e: &Expr, x: f64) -> Result<f64, String> {
    eval_ctx(e, x, &|_| f64::NAN)
}

/// Collect the names of every `Control` reference in `e` (e.g. `.th` -> "th").
pub fn control_names(e: &Expr, out: &mut Vec<String>) {
    match e {
        Expr::Control(n) => out.push(n.clone()),
        Expr::Num(_) | Expr::Var | Expr::Field(_) | Expr::Str(_) => {}
        Expr::Neg(a) | Expr::Not(a) | Expr::Match(a) | Expr::InSet(_, a) => control_names(a, out),
        Expr::Call(_, items) => items.iter().for_each(|it| control_names(it, out)),
        Expr::InList(l, items) => {
            control_names(l, out);
            items.iter().for_each(|it| control_names(it, out));
        }
        Expr::InRange(l, lo, hi) => {
            control_names(l, out);
            control_names(lo, out);
            control_names(hi, out);
        }
        Expr::Cond(a, b, c) => {
            control_names(a, out);
            control_names(b, out);
            control_names(c, out);
        }
        Expr::Bin(_, a, b) => {
            control_names(a, out);
            control_names(b, out);
        }
    }
}

/// Split control refs by the type they resolve to: `Match`/`InSet` inners are
/// string controls, everything else is numeric. Lets `resolve_pipeline` require
/// numeric controls to resolve (or drop the filter) while string controls with
/// an empty value simply match everything.
pub fn control_names_typed(e: &Expr, num: &mut Vec<String>, strv: &mut Vec<String>) {
    match e {
        Expr::Control(n) => num.push(n.clone()),
        Expr::Match(inner) | Expr::InSet(_, inner) => {
            if let Expr::Control(n) = inner.as_ref() {
                strv.push(n.clone());
            } else {
                control_names_typed(inner, num, strv);
            }
        }
        Expr::Num(_) | Expr::Var | Expr::Field(_) | Expr::Str(_) => {}
        Expr::Neg(a) | Expr::Not(a) => control_names_typed(a, num, strv),
        Expr::Call(_, items) => items
            .iter()
            .for_each(|it| control_names_typed(it, num, strv)),
        Expr::InList(l, items) => {
            control_names_typed(l, num, strv);
            items
                .iter()
                .for_each(|it| control_names_typed(it, num, strv));
        }
        Expr::InRange(l, lo, hi) => {
            control_names_typed(l, num, strv);
            control_names_typed(lo, num, strv);
            control_names_typed(hi, num, strv);
        }
        Expr::Cond(a, b, c) => {
            control_names_typed(a, num, strv);
            control_names_typed(b, num, strv);
            control_names_typed(c, num, strv);
        }
        Expr::Bin(_, a, b) => {
            control_names_typed(a, num, strv);
            control_names_typed(b, num, strv);
        }
    }
}

/// Whether `e` contains a string predicate (`match`/`in .set`) — the query layer
/// routes such a `where` to the Rust evaluator instead of the numeric VM.
pub fn expr_has_str(e: &Expr) -> bool {
    match e {
        Expr::Match(_) | Expr::InSet(..) | Expr::Str(_) => true,
        Expr::Num(_) | Expr::Var | Expr::Field(_) | Expr::Control(_) => false,
        Expr::Neg(a) | Expr::Not(a) => expr_has_str(a),
        // A Call yields an f64; numeric-only args carry no string predicate, but
        // recurse for consistency with every other compound node.
        Expr::Call(_, items) => items.iter().any(expr_has_str),
        Expr::InList(l, items) => expr_has_str(l) || items.iter().any(expr_has_str),
        Expr::InRange(l, lo, hi) => expr_has_str(l) || expr_has_str(lo) || expr_has_str(hi),
        Expr::Cond(a, b, c) => expr_has_str(a) || expr_has_str(b) || expr_has_str(c),
        Expr::Bin(_, a, b) => expr_has_str(a) || expr_has_str(b),
    }
}

/// Rewrite every `Control(name)` in `e` to `Control("{ns}.{name}")`, in place —
/// used by `import X as Y` to namespace a module's control references.
pub fn prefix_controls(e: &mut Expr, ns: &str) {
    match e {
        Expr::Control(n) => *n = format!("{ns}.{n}"),
        Expr::Num(_) | Expr::Var | Expr::Field(_) | Expr::Str(_) => {}
        Expr::Neg(a) | Expr::Not(a) | Expr::Match(a) | Expr::InSet(_, a) => prefix_controls(a, ns),
        Expr::Call(_, items) => items.iter_mut().for_each(|it| prefix_controls(it, ns)),
        Expr::InList(l, items) => {
            prefix_controls(l, ns);
            items.iter_mut().for_each(|it| prefix_controls(it, ns));
        }
        Expr::InRange(l, lo, hi) => {
            prefix_controls(l, ns);
            prefix_controls(lo, ns);
            prefix_controls(hi, ns);
        }
        Expr::Cond(a, b, c) => {
            prefix_controls(a, ns);
            prefix_controls(b, ns);
            prefix_controls(c, ns);
        }
        Expr::Bin(_, a, b) => {
            prefix_controls(a, ns);
            prefix_controls(b, ns);
        }
    }
}

/// Return a copy of `e` with control refs substituted: a numeric `Control` ->
/// `Num(num(n))` when resolvable (else left as-is -> NaN); a string control
/// inside `match`/`in .set` -> `Str(strv(n))` (empty when unset -> matches all).
pub fn substitute_controls(
    e: &Expr,
    num: &dyn Fn(&str) -> Option<f64>,
    strv: &dyn Fn(&str) -> Option<String>,
) -> Expr {
    let sub = |b: &Expr| Box::new(substitute_controls(b, num, strv));
    // Resolve a control ref to a string node (for match/in-set inners).
    let sub_str = |b: &Expr| -> Box<Expr> {
        match b {
            Expr::Control(n) => Box::new(Expr::Str(strv(n).unwrap_or_default())),
            other => Box::new(substitute_controls(other, num, strv)),
        }
    };
    match e {
        Expr::Control(n) => match num(n) {
            Some(v) => Expr::Num(v),
            None => Expr::Control(n.clone()),
        },
        Expr::Match(inner) => Expr::Match(sub_str(inner)),
        Expr::InSet(field, inner) => Expr::InSet(field.clone(), sub_str(inner)),
        Expr::Num(_) | Expr::Var | Expr::Field(_) | Expr::Str(_) => e.clone(),
        Expr::Call(name, items) => Expr::Call(
            name.clone(),
            items
                .iter()
                .map(|it| substitute_controls(it, num, strv))
                .collect(),
        ),
        Expr::Neg(a) => Expr::Neg(sub(a)),
        Expr::Not(a) => Expr::Not(sub(a)),
        Expr::InList(l, items) => Expr::InList(
            sub(l),
            items
                .iter()
                .map(|it| substitute_controls(it, num, strv))
                .collect(),
        ),
        Expr::InRange(l, lo, hi) => Expr::InRange(sub(l), sub(lo), sub(hi)),
        Expr::Cond(a, b, c) => Expr::Cond(sub(a), sub(b), sub(c)),
        Expr::Bin(op, a, b) => Expr::Bin(*op, sub(a), sub(b)),
    }
}

/// Arm fusevm's Cranelift tiers on a VM about to run an expression chunk.
///
/// One flag gates both tiers: `vm.rs`'s tiered auto-dispatch checks
/// `tracing_jit` before it will even ask `is_block_eligible`, so without this
/// call a chunk runs on the interpreter no matter what the `jit` feature says.
/// An arb expression lowers to straight-line native ops with no backward
/// branch, so the block tier is the one that takes it — compiled once, then
/// reused from fusevm's on-disk cache across runs, which is what a predicate
/// evaluated over every row wants. `arb --tiers` reports the outcome.
fn arm_tiers(vm: &mut VM) {
    vm.enable_tracing_jit();
}

/// Lower `e` to a fusevm chunk (with `x` and resolved fields baked in), run it on
/// the VM, and return the resulting number. `resolve` maps a field name to its
/// numeric value.
pub fn eval_ctx(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64) -> Result<f64, String> {
    let mut b = ChunkBuilder::new();
    emit(e, x, resolve, &mut b);
    with_pooled_vm(b.build(), |vm| match vm.run() {
        VMResult::Ok(v) => Ok(v.to_float()),
        VMResult::Halted => Ok(vm.peek().to_float()),
        VMResult::Error(err) => Err(err),
    })
}

thread_local! {
    /// Recycled VMs for the per-record expression path.
    ///
    /// `where`/`map` lower a chunk PER LINE — the chunk is a function of `x` and
    /// the resolved fields, both baked in as constants — so a stream of N records
    /// ran `VM::new` N times, and each of those rebuilds the VM's builtin table
    /// and its stack/frame/global vectors from scratch. `VMPool::acquire` keeps
    /// those allocations and only clears state, which is exactly what a
    /// per-record caller needs.
    ///
    /// Measured over 50,000 records, release build, against `jq 1.8.2` on the
    /// same data: `field v; where x > 500` was 1.174s before this (jq: 0.141s).
    static VM_POOL: RefCell<fusevm::vm::VMPool> = RefCell::new(fusevm::vm::VMPool::new());
}

/// Run `f` against a VM from this thread's pool, returning it afterwards.
fn with_pooled_vm<T>(chunk: fusevm::Chunk, f: impl FnOnce(&mut VM) -> T) -> T {
    VM_POOL.with(|p| {
        // The pool is borrowed only to check a VM out and back in, never across
        // `f` — a nested expression evaluation (an FFI argument) re-enters here.
        let mut vm = p.borrow_mut().acquire(chunk);
        arm_tiers(&mut vm);
        let r = f(&mut vm);
        p.borrow_mut().release(vm);
        r
    })
}

/// Lower `e` to the fusevm chunk [`eval_ctx`] would run, without running it.
///
/// The chunk is a function of `x` and the resolved fields, not of `e` alone:
/// both are baked in as `LoadFloat` constants (see the private `emit`). Two evaluations
/// of the same expression at different `x` are therefore *different* chunks
/// with different op hashes, which is what [`crate::tiers`] exists to report on.
pub fn chunk_of(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64) -> fusevm::Chunk {
    let mut b = ChunkBuilder::new();
    emit(e, x, resolve, &mut b);
    b.build()
}

/// Evaluate as a predicate with no field resolver.
pub fn eval_pred(e: &Expr, x: f64) -> Result<bool, String> {
    eval_pred_ctx(e, x, &|_| f64::NAN)
}

/// Evaluate `e` as a predicate — compiled to fusevm, run on the VM, read as a
/// boolean via `Value::is_truthy`. `resolve` maps a field name to its value.
pub fn eval_pred_ctx(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64) -> Result<bool, String> {
    let mut b = ChunkBuilder::new();
    emit(e, x, resolve, &mut b);
    with_pooled_vm(b.build(), |vm| match vm.run() {
        VMResult::Ok(v) => Ok(v.is_truthy()),
        VMResult::Halted => Ok(vm.peek().is_truthy()),
        VMResult::Error(err) => Err(err),
    })
}

/// Evaluate a `name(args)` inline-Rust FFI call at lowering time: resolve each
/// argument to an f64 on the same VM, marshal it as a `fusevm::Value::float`
/// (fusevm coerces to the export's `i64`/`f64` signature), dispatch to the
/// registered export, and read the return back as an f64. An unregistered name
/// or a failed call yields NaN — the same way an unresolved control degrades —
/// so the emitter can bake the result in as a constant without a fallible path.
fn eval_call(name: &str, args: &[Expr], x: f64, resolve: &dyn Fn(&str) -> f64) -> f64 {
    if !fusevm::ffi::is_registered(name) {
        return f64::NAN;
    }
    let vals: Vec<Value> = args
        .iter()
        .map(|a| Value::float(eval_ctx(a, x, resolve).unwrap_or(f64::NAN)))
        .collect();
    match fusevm::ffi::try_call(name, &vals) {
        Some(Ok(v)) => v.to_float(),
        _ => f64::NAN,
    }
}

fn emit(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64, b: &mut ChunkBuilder) {
    match e {
        Expr::Num(n) => {
            b.emit(Op::LoadFloat(*n), 0);
        }
        Expr::Var => {
            b.emit(Op::LoadFloat(x), 0);
        }
        Expr::Field(name) => {
            b.emit(Op::LoadFloat(resolve(name)), 0);
        }
        // An unsubstituted control (its value was empty/non-numeric) -> NaN, so
        // comparisons against it are false. Normally resolve_pipeline replaces it
        // with a Num, or drops the whole `where` op, before we get here.
        Expr::Control(_) => {
            b.emit(Op::LoadFloat(f64::NAN), 0);
        }
        // String predicates never reach the numeric VM — the query layer routes a
        // string-bearing `where` to a Rust evaluator. Emit a neutral 0 so any
        // stray numeric use degrades gracefully instead of panicking.
        Expr::Str(_) | Expr::Match(_) | Expr::InSet(..) => {
            b.emit(Op::LoadFloat(0.0), 0);
        }
        // An FFI call can't run inside fusevm bytecode, so evaluate it now and
        // bake the resulting f64 in as a constant.
        Expr::Call(name, args) => {
            b.emit(Op::LoadFloat(eval_call(name, args, x, resolve)), 0);
        }
        Expr::Neg(a) => {
            emit(a, x, resolve, b);
            b.emit(Op::Negate, 0);
        }
        Expr::Not(a) => {
            // Logical not: `a == 0` yields 1 for falsy `a`, 0 for truthy.
            emit(a, x, resolve, b);
            b.emit(Op::LoadFloat(0.0), 0);
            b.emit(Op::NumEq, 0);
        }
        Expr::InList(left, items) => {
            // Sum of `(left == item)` over the list; truthy iff any matched.
            // The sum COUNTS matches, so a list with a repeated element yields 2
            // or 3 — fine for `where`'s truthiness test, wrong for `map`/`calc`,
            // which print the expression's value. Normalize back to 0/1.
            if items.is_empty() {
                b.emit(Op::LoadFloat(0.0), 0);
            } else {
                for (k, it) in items.iter().enumerate() {
                    emit(left, x, resolve, b);
                    emit(it, x, resolve, b);
                    b.emit(Op::NumEq, 0);
                    if k > 0 {
                        b.emit(Op::Add, 0);
                    }
                }
                if items.len() > 1 {
                    emit_normalize_bool(b);
                }
            }
        }
        Expr::InRange(left, lo, hi) => {
            // `(left >= lo) and (left <= hi)` — both yield 0/1, product is 1 iff
            // in range.
            emit(left, x, resolve, b);
            emit(lo, x, resolve, b);
            b.emit(Op::NumGe, 0);
            emit(left, x, resolve, b);
            emit(hi, x, resolve, b);
            b.emit(Op::NumLe, 0);
            b.emit(Op::Mul, 0);
        }
        Expr::Cond(c, t, e2) => {
            // Real branching: `JumpIfFalse` pops the condition and skips to the
            // else branch when falsy, so only the taken branch runs.
            emit(c, x, resolve, b);
            let jf = b.emit(Op::JumpIfFalse(0), 0);
            emit(t, x, resolve, b);
            let jend = b.emit(Op::Jump(0), 0);
            let else_pos = b.current_pos();
            b.patch_jump(jf, else_pos);
            emit(e2, x, resolve, b);
            let end_pos = b.current_pos();
            b.patch_jump(jend, end_pos);
        }
        // `and`/`or` operate on truthiness: normalize each side to 0/1 first,
        // then `and` = product (1 iff both 1), `or` = sum (>=1 iff either 1).
        Expr::Bin(BinOp::And, a, c) => {
            emit_bool(a, x, resolve, b);
            emit_bool(c, x, resolve, b);
            b.emit(Op::Mul, 0);
        }
        Expr::Bin(BinOp::Or, a, c) => {
            emit_bool(a, x, resolve, b);
            emit_bool(c, x, resolve, b);
            b.emit(Op::Add, 0);
            // The sum is 2 when BOTH sides are true. `where` only reads
            // truthiness so it never noticed, but `map`/`calc` print the value —
            // `map x > 1 or x > 2` at x=5 printed `2`. Every other
            // boolean-producing node (`and`, a comparison, `not`) yields 0/1, so
            // normalize `or` to match.
            emit_normalize_bool(b);
        }
        Expr::Bin(op, a, c) => {
            emit(a, x, resolve, b);
            emit(c, x, resolve, b);
            b.emit(
                match op {
                    BinOp::Add => Op::Add,
                    BinOp::Sub => Op::Sub,
                    BinOp::Mul => Op::Mul,
                    BinOp::Div => Op::Div,
                    BinOp::Mod => Op::Mod,
                    BinOp::Eq => Op::NumEq,
                    BinOp::Ne => Op::NumNe,
                    BinOp::Lt => Op::NumLt,
                    BinOp::Le => Op::NumLe,
                    BinOp::Gt => Op::NumGt,
                    BinOp::Ge => Op::NumGe,
                    BinOp::And | BinOp::Or => unreachable!("handled above"),
                },
                0,
            );
        }
    }
}

/// Emit `e` normalized to a boolean 0.0/1.0 (`e != 0`), for logical combinators.
fn emit_bool(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64, b: &mut ChunkBuilder) {
    emit(e, x, resolve, b);
    emit_normalize_bool(b);
}

/// Normalize the value already on the stack to a boolean 0.0/1.0 (`v != 0`).
/// Used wherever a node builds its answer by SUMMING 0/1 terms (`or`, `in
/// [list]`), whose sum can exceed 1 and would otherwise leak out of a `map`
/// or `calc` as a count instead of a boolean.
fn emit_normalize_bool(b: &mut ChunkBuilder) {
    b.emit(Op::LoadFloat(0.0), 0);
    b.emit(Op::NumNe, 0);
}

struct Parser {
    c: Vec<char>,
    i: usize,
    /// Recursion depth of `primary()`, so a pathologically nested expression
    /// (`(((…x…)))`) fails closed instead of overflowing the stack.
    depth: usize,
}

/// Cap on `(`-nesting in `map`/`where`/`calc` expressions — well past any real
/// expression, but bounded so a malicious input can't abort the process.
///
/// The bound that matters is STACK, not syntax: one nesting level costs one
/// frame per nonterminal between `primary` and its recursive call. A
/// parenthesized group re-enters at `ternary`, so a level walks
/// `ternary → or → and → not → comparison → additive → multiplicative → unary →
/// primary` — about twice the chain a group that re-entered at `additive` cost,
/// and a limit tuned for the shorter chain aborted the process (SIGABRT) instead
/// of erroring. Halved to keep the guard inside the same stack budget;
/// `tests/expr.rs::deep_nesting_errors_not_stack_overflow` is what proves it.
const MAX_EXPR_DEPTH: usize = 128;

impl Parser {
    /// Peek the next non-whitespace char (consuming leading whitespace).
    fn peek(&mut self) -> Option<char> {
        while self.i < self.c.len() && self.c[self.i].is_whitespace() {
            self.i += 1;
        }
        self.c.get(self.i).copied()
    }

    /// Lowest precedence: `cond ? then : else` (right-associative).
    fn ternary(&mut self) -> Result<Expr, String> {
        let cond = self.or_expr()?;
        if self.peek() == Some('?') {
            self.i += 1;
            let then = self.ternary()?;
            if self.peek() != Some(':') {
                return Err("calc: expected `:` in `?:`".into());
            }
            self.i += 1;
            let els = self.ternary()?;
            return Ok(Expr::Cond(Box::new(cond), Box::new(then), Box::new(els)));
        }
        Ok(cond)
    }

    /// `a or b`.
    fn or_expr(&mut self) -> Result<Expr, String> {
        let mut left = self.and_expr()?;
        while self.match_kw("or") {
            let right = self.and_expr()?;
            left = Expr::Bin(BinOp::Or, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    /// `a and b`, binding tighter than `or`.
    fn and_expr(&mut self) -> Result<Expr, String> {
        let mut left = self.not_expr()?;
        while self.match_kw("and") {
            let right = self.not_expr()?;
            left = Expr::Bin(BinOp::And, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    /// Prefix `not`, binding tighter than `and`/`or` but looser than comparison.
    fn not_expr(&mut self) -> Result<Expr, String> {
        if self.match_kw("not") {
            // `not not … 1` recurses here, never through `primary`, so guard it
            // too or a long chain overflows the stack (rc=134).
            self.deepen()?;
            let inner = self.not_expr();
            self.depth -= 1;
            return Ok(Expr::Not(Box::new(inner?)));
        }
        self.comparison()
    }

    /// Consume the keyword `kw` if it is the next whole word (not a prefix of a
    /// longer identifier, e.g. `and` must not match inside `android`).
    fn match_kw(&mut self, kw: &str) -> bool {
        let save = self.i;
        while self.i < self.c.len() && self.c[self.i].is_whitespace() {
            self.i += 1;
        }
        let start = self.i;
        let kwc: Vec<char> = kw.chars().collect();
        let end = start + kwc.len();
        let boundary_ok =
            end >= self.c.len() || !(self.c[end].is_ascii_alphanumeric() || self.c[end] == '_');
        if end <= self.c.len() && self.c[start..end] == kwc[..] && boundary_ok {
            self.i = end;
            true
        } else {
            self.i = save;
            false
        }
    }

    fn comparison(&mut self) -> Result<Expr, String> {
        let mut left = self.additive()?;
        if self.match_kw("in") {
            return self.in_list(left);
        }
        while let Some(op) = self.cmp_op() {
            let right = self.additive()?;
            left = Expr::Bin(op, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    /// Parse a `.name` control reference into `Expr::Control(name)`.
    fn control_ref(&mut self) -> Result<Expr, String> {
        if self.peek() != Some('.') {
            return Err("expected a control ref `.name`".into());
        }
        self.i += 1; // consume '.'
        let name = self.dotted_ident();
        if name.is_empty() {
            return Err("expected a control name after `.`".into());
        }
        Ok(Expr::Control(name))
    }

    /// Parse the right-hand side of an `in` test: a `.name` control set, a
    /// `[a, b, c]` list, or a `lo..hi` range.
    fn in_list(&mut self, left: Expr) -> Result<Expr, String> {
        // `<field> in .lv` — set membership against a live control's selected set.
        // Only a `.`+letter is a control ref; `.5` stays a fractional range bound.
        if self.peek() == Some('.')
            && matches!(self.c.get(self.i + 1), Some(c) if c.is_ascii_alphabetic() || *c == '_')
        {
            let field = match &left {
                Expr::Field(n) => n.clone(),
                Expr::Var => "x".to_string(),
                _ => return Err("in .set: left side must be a field".into()),
            };
            let ctrl = self.control_ref()?;
            return Ok(Expr::InSet(field, Box::new(ctrl)));
        }
        if self.peek() != Some('[') {
            // `lo..hi` range membership.
            let lo = self.additive()?;
            if !(self.peek() == Some('.') && self.c.get(self.i + 1) == Some(&'.')) {
                return Err("in: expected `[list]` or `lo..hi`".into());
            }
            self.i += 2;
            let hi = self.additive()?;
            return Ok(Expr::InRange(Box::new(left), Box::new(lo), Box::new(hi)));
        }
        self.i += 1;
        let mut items = Vec::new();
        loop {
            if self.peek() == Some(']') {
                self.i += 1;
                break;
            }
            items.push(self.additive()?);
            match self.peek() {
                Some(',') => self.i += 1,
                Some(']') => {
                    self.i += 1;
                    break;
                }
                _ => return Err("in: expected `,` or `]`".into()),
            }
        }
        Ok(Expr::InList(Box::new(left), items))
    }

    /// Consume a comparison operator (`< <= > >= == !=`) if one is next.
    fn cmp_op(&mut self) -> Option<BinOp> {
        let c = self.peek()?;
        if !matches!(c, '<' | '>' | '=' | '!') {
            return None;
        }
        let next = self.c.get(self.i + 1).copied();
        let (op, len) = match (c, next) {
            ('<', Some('=')) => (BinOp::Le, 2),
            ('<', _) => (BinOp::Lt, 1),
            ('>', Some('=')) => (BinOp::Ge, 2),
            ('>', _) => (BinOp::Gt, 1),
            ('=', Some('=')) => (BinOp::Eq, 2),
            ('!', Some('=')) => (BinOp::Ne, 2),
            _ => return None,
        };
        self.i += len;
        Some(op)
    }

    fn additive(&mut self) -> Result<Expr, String> {
        let mut left = self.multiplicative()?;
        while let Some(c) = self.peek() {
            let op = match c {
                '+' => BinOp::Add,
                '-' => BinOp::Sub,
                _ => break,
            };
            self.i += 1;
            let right = self.multiplicative()?;
            left = Expr::Bin(op, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    fn multiplicative(&mut self) -> Result<Expr, String> {
        let mut left = self.unary()?;
        while let Some(c) = self.peek() {
            let op = match c {
                '*' => BinOp::Mul,
                '/' => BinOp::Div,
                '%' => BinOp::Mod,
                _ => break,
            };
            self.i += 1;
            let right = self.unary()?;
            left = Expr::Bin(op, Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    fn unary(&mut self) -> Result<Expr, String> {
        if self.peek() == Some('-') {
            self.i += 1;
            // `- - … 1` recurses here, never through `primary`; guard it too.
            self.deepen()?;
            let inner = self.unary();
            self.depth -= 1;
            return Ok(Expr::Neg(Box::new(inner?)));
        }
        self.primary()
    }

    /// Enter one recursion level, failing closed if it exceeds `MAX_EXPR_DEPTH`
    /// (decrementing itself on that error). Every self-recursive parse point —
    /// `primary` (paren nesting), `not_expr`, `unary` — calls this then does
    /// `self.depth -= 1` after its recursive call, so adversarial input errors
    /// instead of overflowing the stack.
    fn deepen(&mut self) -> Result<(), String> {
        self.depth += 1;
        if self.depth > MAX_EXPR_DEPTH {
            self.depth -= 1;
            return Err("calc: expression too deeply nested".into());
        }
        Ok(())
    }

    fn primary(&mut self) -> Result<Expr, String> {
        self.deepen()?;
        let r = self.primary_inner();
        self.depth -= 1;
        r
    }

    fn primary_inner(&mut self) -> Result<Expr, String> {
        match self.peek() {
            // A parenthesized group is a FULL expression, the same nonterminal a
            // call argument gets. Recursing into `additive` instead stopped at the
            // first comparison or keyword, so the three natural groupings —
            // `(x > 1) and (x < 5)`, `not (a or b)`, `(x > 1 ? 10 : 20)` — were
            // rejected with "calc: expected `)`" even though the doc comment on
            // `parse` lists parentheses as supported.
            Some('(') => {
                self.i += 1;
                let e = self.ternary()?;
                if self.peek() != Some(')') {
                    return Err("calc: expected `)`".into());
                }
                self.i += 1;
                Ok(e)
            }
            Some(c) if c.is_ascii_alphabetic() || c == '_' => {
                let name = self.ident();
                // `match(.q)` — a builtin substring test against a control string.
                if name == "match" && self.peek() == Some('(') {
                    self.i += 1; // consume '('
                    let inner = self.control_ref()?;
                    if self.peek() != Some(')') {
                        return Err("match: expected `)`".into());
                    }
                    self.i += 1;
                    return Ok(Expr::Match(Box::new(inner)));
                }
                // `name(arg, …)` — an inline-Rust FFI call. Any other identifier
                // immediately followed by `(` was previously a parse error, so
                // this grammar addition is purely additive.
                if self.peek() == Some('(') {
                    return self.call(name);
                }
                Ok(if name == "x" {
                    Expr::Var
                } else {
                    Expr::Field(name)
                })
            }
            // `.name` is a control reference (a live widget value); `.5` stays a
            // number. Distinguish by whether the char after `.` is a letter.
            Some('.') if matches!(self.c.get(self.i + 1), Some(c) if c.is_ascii_alphabetic() || *c == '_') =>
            {
                self.i += 1; // consume the leading `.`
                Ok(Expr::Control(self.dotted_ident()))
            }
            Some(c) if c.is_ascii_digit() || c == '.' => self.number(),
            // A double-quoted string literal. jq's `select(.status == "ok")` is a
            // COMPARE, which the spec documents as in-subset, but without a string
            // atom the predicate could not even parse; `eval_where` gives the
            // resulting `Str` node its string-comparison semantics.
            Some('"') => {
                self.i += 1; // consume the opening quote
                let mut s = String::new();
                while let Some(&c) = self.c.get(self.i) {
                    match c {
                        '"' => {
                            self.i += 1;
                            return Ok(Expr::Str(s));
                        }
                        '\\' if self.i + 1 < self.c.len() => {
                            s.push(match self.c[self.i + 1] {
                                'n' => '\n',
                                't' => '\t',
                                o => o,
                            });
                            self.i += 2;
                        }
                        _ => {
                            s.push(c);
                            self.i += 1;
                        }
                    }
                }
                Err("calc: unterminated string literal".into())
            }
            Some(c) => Err(format!("calc: unexpected `{c}`")),
            None => Err("calc: unexpected end of expression".into()),
        }
    }

    fn ident(&mut self) -> String {
        let start = self.i;
        while self.i < self.c.len()
            && (self.c[self.i].is_ascii_alphanumeric() || self.c[self.i] == '_')
        {
            self.i += 1;
        }
        self.c[start..self.i].iter().collect()
    }

    /// A control name that may be dot-segmented (`ps.sel`, `g.cpu`): the leading
    /// ident, then any `.segment` where the char after the `.` is a letter/`_` (so
    /// `.5` fractional bounds and `..` ranges are left alone). Enables the
    /// `.<widget>.sel` selection accessor (SPEC §14) as a live control ref.
    fn dotted_ident(&mut self) -> String {
        let mut name = self.ident();
        while self.i < self.c.len()
            && self.c[self.i] == '.'
            && matches!(self.c.get(self.i + 1), Some(c) if c.is_ascii_alphabetic() || *c == '_')
        {
            self.i += 1; // consume '.'
            name.push('.');
            name.push_str(&self.ident());
        }
        name
    }

    /// Parse the argument list of a `name(arg, …)` FFI call — the leading `(` is
    /// the next char. Each argument is a full expression; `,` separates and `)`
    /// closes. A zero-arg call `name()` is allowed.
    fn call(&mut self, name: String) -> Result<Expr, String> {
        self.i += 1; // consume '('
        let mut args = Vec::new();
        if self.peek() != Some(')') {
            loop {
                args.push(self.ternary()?);
                match self.peek() {
                    Some(',') => self.i += 1,
                    Some(')') => break,
                    _ => return Err(format!("calc: expected `,` or `)` in call to `{name}`")),
                }
            }
        }
        self.i += 1; // consume ')'
        Ok(Expr::Call(name, args))
    }

    fn number(&mut self) -> Result<Expr, String> {
        let start = self.i;
        while self.i < self.c.len() && self.c[self.i].is_ascii_digit() {
            self.i += 1;
        }
        // At most one fractional part, and only when the `.` is followed by a
        // digit — so `1..10` (a range) leaves the `..` for the range parser
        // instead of the number greedily swallowing both dots.
        if self.i < self.c.len()
            && self.c[self.i] == '.'
            && matches!(self.c.get(self.i + 1), Some(d) if d.is_ascii_digit())
        {
            self.i += 1;
            while self.i < self.c.len() && self.c[self.i].is_ascii_digit() {
                self.i += 1;
            }
        }
        // An exponent suffix, so a literal can be written the way arb PRINTS one.
        // `fmt_num` renders a computed number in jq's format, which is
        // exponential past `1e16` and below `1e-4` — without this, arb emitted
        // `1e+17` and then rejected `x > 1e+17` with "calc: unexpected `e`", so a
        // value the language produced could not be typed back into it. The
        // stream side never had that gap: a DATA line is read with Rust's
        // `parse::<f64>`, which has always accepted `1e17`.
        //
        // Only consume the `e` when what follows really is an exponent — a
        // digit, or a sign then a digit. A bare trailing `e` stays whatever the
        // caller meant it to be rather than turning `1 e` into a bad number.
        if matches!(self.c.get(self.i), Some('e' | 'E')) {
            let after_sign = match self.c.get(self.i + 1) {
                Some('+' | '-') => self.i + 2,
                _ => self.i + 1,
            };
            if matches!(self.c.get(after_sign), Some(d) if d.is_ascii_digit()) {
                self.i = after_sign;
                while self.i < self.c.len() && self.c[self.i].is_ascii_digit() {
                    self.i += 1;
                }
            }
        }
        let s: String = self.c[start..self.i].iter().collect();
        s.parse::<f64>()
            .map(Expr::Num)
            .map_err(|_| format!("calc: bad number `{s}`"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dotted_control_name_parses_whole() {
        // `.ps.sel` (a widget's selection accessor) is one control ref, not
        // `.ps` followed by a stray `.sel`.
        let e = parse(".ps.sel").unwrap();
        let mut names = Vec::new();
        control_names(&e, &mut names);
        assert_eq!(names, vec!["ps.sel".to_string()]);
    }

    #[test]
    fn dotted_control_substitutes_and_evals() {
        // `.k.v * 2` with the control resolved to 21 -> 42.
        let e = parse(".k.v * 2").unwrap();
        let num = |n: &str| if n == "k.v" { Some(21.0) } else { None };
        let strv = |_: &str| None;
        let sub = substitute_controls(&e, &num, &strv);
        assert_eq!(eval(&sub, 0.0).unwrap(), 42.0);
    }

    /// Every boolean-producing node must yield 0 or 1, because `map`/`calc`
    /// print the expression's VALUE. `or` lowered to the sum of its two
    /// normalized operands, so a row where both sides held answered `2`; `in
    /// [list]` lowered to the count of matching elements, so a list with a
    /// repeated element answered `2` or `3`. `where` reads only truthiness and
    /// never saw either.
    #[test]
    fn boolean_nodes_yield_zero_or_one_not_a_count() {
        let ev = |src: &str, x: f64| eval(&parse(src).unwrap(), x).unwrap();
        // Both sides of the `or` hold.
        assert_eq!(ev("x > 1 or x > 2", 5.0), 1.0);
        assert_eq!(ev("x > 1 or x > 2", 0.0), 0.0);
        // Exactly one side holds — the case that was already right.
        assert_eq!(ev("x > 4 or x < 1", 5.0), 1.0);
        // Chained `or`, three terms all true.
        assert_eq!(ev("x > 1 or x > 2 or x > 3", 9.0), 1.0);
        // A repeated element in an `in` list.
        assert_eq!(ev("x in [1,1,1]", 1.0), 1.0);
        assert_eq!(ev("x in [1,5,5,9]", 5.0), 1.0);
        assert_eq!(ev("x in [1,2,3]", 7.0), 0.0);
        // A single-element list still answers 0/1.
        assert_eq!(ev("x in [5]", 5.0), 1.0);
    }

    /// A parenthesized group is a full expression, not just an additive one.
    /// `(x > 1) and (x < 5)`, `not (a or b)` and `(cond ? a : b)` are the
    /// spellings a reader writes first, and each used to be `calc: expected `)``.
    #[test]
    fn parentheses_group_a_whole_expression() {
        let ev = |src: &str, x: f64| eval(&parse(src).unwrap(), x).unwrap();
        assert_eq!(ev("(x > 1) and (x < 5)", 3.0), 1.0);
        assert_eq!(ev("(x > 1) and (x < 5)", 9.0), 0.0);
        assert_eq!(ev("not (x > 1 or x > 2)", 5.0), 0.0);
        assert_eq!(ev("not (x > 1 or x > 2)", 0.0), 1.0);
        assert_eq!(ev("(x > 5 ? 100 : 0)", 9.0), 100.0);
        assert_eq!(ev("(x > 5 ? 100 : 0)", 1.0), 0.0);
        // Arithmetic grouping is unchanged.
        assert_eq!(ev("(x + 2) * 3", 1.0), 9.0);
        assert_eq!(ev("x - (2 - 1)", 5.0), 4.0);
        assert_eq!(ev("((x))", 7.0), 7.0);
    }

    #[test]
    fn fractional_bound_still_a_number_not_a_control() {
        // `.5` stays a number; only `.<letter>` is a control ref.
        assert!(matches!(
            parse("x + .5").unwrap(),
            Expr::Bin(BinOp::Add, _, _)
        ));
    }
}