Skip to main content

arb/
expr.rs

1//! Arb's computational substrate: arithmetic expressions are compiled to a
2//! `fusevm::Chunk` and executed on the fusevm VM (Cranelift JIT for hot chunks).
3//! This is what "arb runs on fusevm" means concretely — every computed value in
4//! a spec flows through fusevm bytecode, not a bespoke evaluator.
5//!
6//! `x` is the pipeline input scalar; a bareword identifier (`amount`, `latency`)
7//! is a field of the current record, resolved by the caller's closure. Both are
8//! baked into the chunk as constants per evaluation, so no VM slot state is
9//! assumed across `run()`.
10//! Comparisons (`== != < <= > >=`) lower to fusevm's `Num*` ops and yield a
11//! boolean; `eval_pred` reads the result via `Value::is_truthy` for `where`.
12
13use fusevm::vm::{VMResult, VM};
14use fusevm::{ChunkBuilder, Op};
15
16#[derive(Debug, Clone, Copy)]
17pub enum BinOp {
18    Add,
19    Sub,
20    Mul,
21    Div,
22    Mod,
23    Eq,
24    Ne,
25    Lt,
26    Le,
27    Gt,
28    Ge,
29}
30
31#[derive(Debug, Clone)]
32pub enum Expr {
33    Num(f64),
34    /// The pipeline input scalar.
35    Var,
36    /// A named field of the current record, resolved at eval time.
37    Field(String),
38    Neg(Box<Expr>),
39    Bin(BinOp, Box<Expr>, Box<Expr>),
40}
41
42/// Parse an expression: numbers, `x`, `+ - * / %`, comparisons
43/// (`== != < <= > >=`), unary `-`, and parentheses.
44pub fn parse(src: &str) -> Result<Expr, String> {
45    let mut p = Parser {
46        c: src.chars().collect(),
47        i: 0,
48    };
49    let e = p.comparison()?;
50    if p.peek().is_some() {
51        return Err(format!("calc: unexpected `{}`", p.c[p.i]));
52    }
53    Ok(e)
54}
55
56/// Evaluate as a number with no field resolver (field refs -> NaN).
57pub fn eval(e: &Expr, x: f64) -> Result<f64, String> {
58    eval_ctx(e, x, &|_| f64::NAN)
59}
60
61/// Lower `e` to a fusevm chunk (with `x` and resolved fields baked in), run it on
62/// the VM, and return the resulting number. `resolve` maps a field name to its
63/// numeric value.
64pub fn eval_ctx(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64) -> Result<f64, String> {
65    let mut b = ChunkBuilder::new();
66    emit(e, x, resolve, &mut b);
67    let mut vm = VM::new(b.build());
68    match vm.run() {
69        VMResult::Ok(v) => Ok(v.to_float()),
70        VMResult::Halted => Ok(vm.peek().to_float()),
71        VMResult::Error(err) => Err(err),
72    }
73}
74
75/// Evaluate as a predicate with no field resolver.
76pub fn eval_pred(e: &Expr, x: f64) -> Result<bool, String> {
77    eval_pred_ctx(e, x, &|_| f64::NAN)
78}
79
80/// Evaluate `e` as a predicate — compiled to fusevm, run on the VM, read as a
81/// boolean via `Value::is_truthy`. `resolve` maps a field name to its value.
82pub fn eval_pred_ctx(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64) -> Result<bool, String> {
83    let mut b = ChunkBuilder::new();
84    emit(e, x, resolve, &mut b);
85    let mut vm = VM::new(b.build());
86    match vm.run() {
87        VMResult::Ok(v) => Ok(v.is_truthy()),
88        VMResult::Halted => Ok(vm.peek().is_truthy()),
89        VMResult::Error(err) => Err(err),
90    }
91}
92
93fn emit(e: &Expr, x: f64, resolve: &dyn Fn(&str) -> f64, b: &mut ChunkBuilder) {
94    match e {
95        Expr::Num(n) => {
96            b.emit(Op::LoadFloat(*n), 0);
97        }
98        Expr::Var => {
99            b.emit(Op::LoadFloat(x), 0);
100        }
101        Expr::Field(name) => {
102            b.emit(Op::LoadFloat(resolve(name)), 0);
103        }
104        Expr::Neg(a) => {
105            emit(a, x, resolve, b);
106            b.emit(Op::Negate, 0);
107        }
108        Expr::Bin(op, a, c) => {
109            emit(a, x, resolve, b);
110            emit(c, x, resolve, b);
111            b.emit(
112                match op {
113                    BinOp::Add => Op::Add,
114                    BinOp::Sub => Op::Sub,
115                    BinOp::Mul => Op::Mul,
116                    BinOp::Div => Op::Div,
117                    BinOp::Mod => Op::Mod,
118                    BinOp::Eq => Op::NumEq,
119                    BinOp::Ne => Op::NumNe,
120                    BinOp::Lt => Op::NumLt,
121                    BinOp::Le => Op::NumLe,
122                    BinOp::Gt => Op::NumGt,
123                    BinOp::Ge => Op::NumGe,
124                },
125                0,
126            );
127        }
128    }
129}
130
131struct Parser {
132    c: Vec<char>,
133    i: usize,
134}
135
136impl Parser {
137    /// Peek the next non-whitespace char (consuming leading whitespace).
138    fn peek(&mut self) -> Option<char> {
139        while self.i < self.c.len() && self.c[self.i].is_whitespace() {
140            self.i += 1;
141        }
142        self.c.get(self.i).copied()
143    }
144
145    fn comparison(&mut self) -> Result<Expr, String> {
146        let mut left = self.additive()?;
147        while let Some(op) = self.cmp_op() {
148            let right = self.additive()?;
149            left = Expr::Bin(op, Box::new(left), Box::new(right));
150        }
151        Ok(left)
152    }
153
154    /// Consume a comparison operator (`< <= > >= == !=`) if one is next.
155    fn cmp_op(&mut self) -> Option<BinOp> {
156        let c = self.peek()?;
157        if !matches!(c, '<' | '>' | '=' | '!') {
158            return None;
159        }
160        let next = self.c.get(self.i + 1).copied();
161        let (op, len) = match (c, next) {
162            ('<', Some('=')) => (BinOp::Le, 2),
163            ('<', _) => (BinOp::Lt, 1),
164            ('>', Some('=')) => (BinOp::Ge, 2),
165            ('>', _) => (BinOp::Gt, 1),
166            ('=', Some('=')) => (BinOp::Eq, 2),
167            ('!', Some('=')) => (BinOp::Ne, 2),
168            _ => return None,
169        };
170        self.i += len;
171        Some(op)
172    }
173
174    fn additive(&mut self) -> Result<Expr, String> {
175        let mut left = self.multiplicative()?;
176        while let Some(c) = self.peek() {
177            let op = match c {
178                '+' => BinOp::Add,
179                '-' => BinOp::Sub,
180                _ => break,
181            };
182            self.i += 1;
183            let right = self.multiplicative()?;
184            left = Expr::Bin(op, Box::new(left), Box::new(right));
185        }
186        Ok(left)
187    }
188
189    fn multiplicative(&mut self) -> Result<Expr, String> {
190        let mut left = self.unary()?;
191        while let Some(c) = self.peek() {
192            let op = match c {
193                '*' => BinOp::Mul,
194                '/' => BinOp::Div,
195                '%' => BinOp::Mod,
196                _ => break,
197            };
198            self.i += 1;
199            let right = self.unary()?;
200            left = Expr::Bin(op, Box::new(left), Box::new(right));
201        }
202        Ok(left)
203    }
204
205    fn unary(&mut self) -> Result<Expr, String> {
206        if self.peek() == Some('-') {
207            self.i += 1;
208            return Ok(Expr::Neg(Box::new(self.unary()?)));
209        }
210        self.primary()
211    }
212
213    fn primary(&mut self) -> Result<Expr, String> {
214        match self.peek() {
215            Some('(') => {
216                self.i += 1;
217                let e = self.additive()?;
218                if self.peek() != Some(')') {
219                    return Err("calc: expected `)`".into());
220                }
221                self.i += 1;
222                Ok(e)
223            }
224            Some(c) if c.is_ascii_alphabetic() || c == '_' => {
225                let name = self.ident();
226                Ok(if name == "x" {
227                    Expr::Var
228                } else {
229                    Expr::Field(name)
230                })
231            }
232            Some(c) if c.is_ascii_digit() || c == '.' => self.number(),
233            Some(c) => Err(format!("calc: unexpected `{c}`")),
234            None => Err("calc: unexpected end of expression".into()),
235        }
236    }
237
238    fn ident(&mut self) -> String {
239        let start = self.i;
240        while self.i < self.c.len()
241            && (self.c[self.i].is_ascii_alphanumeric() || self.c[self.i] == '_')
242        {
243            self.i += 1;
244        }
245        self.c[start..self.i].iter().collect()
246    }
247
248    fn number(&mut self) -> Result<Expr, String> {
249        let start = self.i;
250        while self.i < self.c.len() && (self.c[self.i].is_ascii_digit() || self.c[self.i] == '.') {
251            self.i += 1;
252        }
253        let s: String = self.c[start..self.i].iter().collect();
254        s.parse::<f64>()
255            .map(Expr::Num)
256            .map_err(|_| format!("calc: bad number `{s}`"))
257    }
258}