Skip to main content

brep_kernel/feature_pipeline/
expression.rs

1//! A deterministic recursive-descent evaluator for the practical subset of the
2//! app's expression DSL (user directive: move expressions to Rust).
3//!
4//! The previous app evaluated expressions with a JavaScript `Function()` reading a
5//! `configurator` object and a `resolution` default (see
6//! `PartHistory.buildExpressionSource`). The REAL expressions are arithmetic, so
7//! this ports exactly that arithmetic surface — no arbitrary code eval. Anything outside
8//! the supported grammar is a clear `Err`, never a silent wrong answer.
9//!
10//! Grammar (recursive descent, standard precedence):
11//! ```text
12//!   source      := statement*
13//!   statement   := IDENT '=' expr ';'
14//!   expr        := term (('+' | '-') term)*
15//!   term        := unary (('*' | '/' | '%') unary)*
16//!   unary       := ('-')? primary
17//!   primary     := NUMBER
18//!                | '(' expr ')'
19//!                | dotted ('(' args ')')?
20//!   dotted      := IDENT ('.' IDENT)*
21//!   args        := (expr (',' expr)*)?
22//! ```
23//! Supported: f64 literals (incl. scientific notation), identifiers, `+ - * / %`,
24//! unary `-`, parentheses, member access `configurator.field`, and a `Math.*`
25//! subset: constants `PI`, `E`; unary `sin cos tan sqrt abs floor ceil round`;
26//! `pow(a,b)`; variadic `min`/`max`. `//` line comments are skipped.
27
28use std::collections::HashMap;
29
30/// A value in the expression environment: a scalar, or the injected
31/// `configurator` object (a flat `field -> f64` map, matching what the
32/// `configurator = <values>` prelude exposes to expressions).
33#[derive(Debug, Clone)]
34enum EvalValue {
35    Scalar(f64),
36    Object(HashMap<String, f64>),
37}
38
39/// The expression environment: the variable bindings produced by evaluating the
40/// prelude (`resolution = 32`), the injected `configurator` object, and the
41/// user's `expressions` statements in order.
42#[derive(Debug, Clone, Default)]
43pub struct Env {
44    vars: HashMap<String, EvalValue>,
45    /// If the env failed to build, every `eval()` returns this error. Numeric
46    /// literal params still pass through their own `param_f64` path without ever
47    /// calling `eval`, so an expression-free history is unaffected by a poison.
48    poison: Option<String>,
49}
50
51impl Env {
52    /// Build the environment: prelude `resolution = 32`, then the injected
53    /// `configurator` object, then the user's `expressions` statements in order
54    /// (users may overwrite `resolution`). `configurator_json` may be the full
55    /// configurator state (`{ values: {...}, ... }`) or a bare values map — the
56    /// `.values` sub-object is used when present, matching the prelude.
57    pub fn build(expressions: &str, configurator_json: &serde_json::Value) -> Result<Env, String> {
58        let mut env = Env::default();
59        env.vars
60            .insert("resolution".to_string(), EvalValue::Scalar(32.0));
61        env.vars.insert(
62            "configurator".to_string(),
63            EvalValue::Object(configurator_values(configurator_json)),
64        );
65        env.run_statements(expressions)?;
66        Ok(env)
67    }
68
69    /// A poisoned environment: `eval()` reports `msg`; numeric params still pass
70    /// through. Lets `execute_history` keep the `-> HistoryResult` signature and
71    /// surface an expression-block error per-feature instead of globally.
72    pub fn poisoned(msg: String) -> Env {
73        Env {
74            poison: Some(msg),
75            ..Env::default()
76        }
77    }
78
79    /// Evaluate a single expression string against the environment.
80    pub fn eval(&self, source: &str) -> Result<f64, String> {
81        if let Some(poison) = &self.poison {
82            return Err(format!("expression environment failed to build: {poison}"));
83        }
84        let tokens = tokenize(source)?;
85        let mut parser = Parser::new(&tokens, self);
86        let value = parser.parse_expr()?;
87        parser.expect_eof()?;
88        Ok(value)
89    }
90
91    /// Lookup a bound scalar variable (test/introspection helper).
92    pub fn get(&self, name: &str) -> Option<f64> {
93        match self.vars.get(name) {
94            Some(EvalValue::Scalar(value)) => Some(*value),
95            _ => None,
96        }
97    }
98
99    fn run_statements(&mut self, source: &str) -> Result<(), String> {
100        let tokens = tokenize(source)?;
101        let mut index = 0;
102        while index < tokens.len() && tokens[index] != Token::Eof {
103            // statement := IDENT '=' expr ';'
104            let name = match &tokens[index] {
105                Token::Ident(name) => name.clone(),
106                other => {
107                    return Err(format!(
108                        "expected an identifier at the start of a statement, found {other:?}"
109                    ))
110                }
111            };
112            index += 1;
113            if tokens.get(index) != Some(&Token::Assign) {
114                return Err(format!("expected '=' after `{name}` in expression statement"));
115            }
116            index += 1;
117            // Collect the RHS tokens up to the next ';'.
118            let start = index;
119            while index < tokens.len()
120                && tokens[index] != Token::Semi
121                && tokens[index] != Token::Eof
122            {
123                index += 1;
124            }
125            let rhs = &tokens[start..index];
126            let mut parser = Parser::new(rhs, self);
127            let value = parser.parse_expr()?;
128            parser.expect_eof()?;
129            self.vars.insert(name, EvalValue::Scalar(value));
130            // Consume the terminating ';' if present.
131            if tokens.get(index) == Some(&Token::Semi) {
132                index += 1;
133            }
134        }
135        Ok(())
136    }
137}
138
139/// Put every statement of an expressions source on its own line, in order.
140///
141/// The only edit is a line break after a statement-ending `;` that has more
142/// code after it on the same line: the spaces and tabs after the `;` become a
143/// line break plus that line's own indentation. Nothing else moves. A `;`
144/// followed (on its line) only by a `//` comment keeps it, so a trailing
145/// comment stays with its statement; blank lines, multi-line statements and
146/// comment lines are untouched, and the line-break style (`\n` or `\r\n`)
147/// follows the source's.
148///
149/// Conservative by construction:
150/// * source that does not tokenize, or whose statements are not
151///   `IDENT '=' <well-formed expr> (';' | end)`, is returned exactly as given
152///   (no evaluation: an unknown name or a missing configurator field is not a
153///   syntax error, and still formats);
154/// * the result is returned only when its token stream equals the source's,
155///   so it evaluates to exactly the same variables and values;
156/// * it is idempotent: formatted text has no `;` with code after it on its
157///   line, so formatting it again changes nothing.
158pub fn format_expressions(source: &str) -> String {
159    let Ok(before) = tokenize(source) else {
160        return source.to_string();
161    };
162    if !statements_well_formed(&before) {
163        return source.to_string();
164    }
165    let bytes = source.as_bytes();
166    let newline = if source.contains("\r\n") { "\r\n" } else { "\n" };
167    let mut out = String::with_capacity(source.len() + 16);
168    let mut copied = 0;
169    let mut line_start = 0;
170    // The indentation of the line the current statement starts on (a statement
171    // wrapped over lines keeps its first line's indent for the ones split
172    // after it); `None` until the statement's first code character is seen.
173    let mut indent: Option<(usize, usize)> = None;
174    let mut statement_started = false;
175    let mut i = 0;
176    while i < bytes.len() {
177        match bytes[i] {
178            b'\n' => {
179                line_start = i + 1;
180                i += 1;
181            }
182            b'/' if bytes.get(i + 1) == Some(&b'/') => {
183                while i < bytes.len() && bytes[i] != b'\n' {
184                    i += 1;
185                }
186            }
187            b';' => {
188                let mut next = i + 1;
189                while next < bytes.len() && (bytes[next] == b' ' || bytes[next] == b'\t') {
190                    next += 1;
191                }
192                let rest_of_line_empty = next == bytes.len()
193                    || bytes[next] == b'\n'
194                    || bytes[next] == b'\r'
195                    || (bytes[next] == b'/' && bytes.get(next + 1) == Some(&b'/'));
196                if rest_of_line_empty {
197                    statement_started = false;
198                } else {
199                    let (start, end) = indent.unwrap_or((line_start, line_start));
200                    out.push_str(&source[copied..=i]);
201                    out.push_str(newline);
202                    out.push_str(&source[start..end]);
203                    copied = next;
204                    // The next statement starts on the line just made, with
205                    // the same indent.
206                    statement_started = true;
207                }
208                i = next;
209            }
210            b' ' | b'\t' | b'\r' => i += 1,
211            _ => {
212                if !statement_started {
213                    let end = source[line_start..]
214                        .find(|c: char| c != ' ' && c != '\t')
215                        .map_or(source.len(), |offset| line_start + offset);
216                    indent = Some((line_start, end));
217                    statement_started = true;
218                }
219                i += 1;
220            }
221        }
222    }
223    if copied == 0 {
224        return source.to_string();
225    }
226    out.push_str(&source[copied..]);
227    match tokenize(&out) {
228        Ok(after) if after == before => out,
229        _ => source.to_string(),
230    }
231}
232
233/// Whether a token stream is a sequence of `IDENT '=' expr` statements, each
234/// ended by `;` (the last may end at the end of the source) — the shape
235/// [`Env::build`] accepts, checked without evaluating anything.
236fn statements_well_formed(tokens: &[Token]) -> bool {
237    let mut pos = 0;
238    while tokens.get(pos).is_some_and(|token| *token != Token::Eof) {
239        if !matches!(tokens.get(pos), Some(Token::Ident(_))) || tokens.get(pos + 1) != Some(&Token::Assign) {
240            return false;
241        }
242        pos += 2;
243        if !expr_well_formed(tokens, &mut pos, 0) {
244            return false;
245        }
246        match tokens.get(pos) {
247            Some(Token::Semi) => pos += 1,
248            Some(Token::Eof) | None => {}
249            Some(_) => return false,
250        }
251    }
252    true
253}
254
255/// Nesting deeper than this (parentheses or call arguments) is not
256/// formatted: the check recurses once per level and must not exhaust the
257/// stack on hostile input.
258const MAX_FORMAT_DEPTH: usize = 128;
259
260/// `expr` of the module grammar, syntax only; advances `pos` past it.
261fn expr_well_formed(tokens: &[Token], pos: &mut usize, depth: usize) -> bool {
262    if depth > MAX_FORMAT_DEPTH {
263        return false;
264    }
265    loop {
266        // unary := ('-' | '+')* primary
267        while matches!(tokens.get(*pos), Some(Token::Minus | Token::Plus)) {
268            *pos += 1;
269        }
270        match tokens.get(*pos) {
271            Some(Token::Number(_)) => *pos += 1,
272            Some(Token::LParen) => {
273                *pos += 1;
274                if !expr_well_formed(tokens, pos, depth + 1) || tokens.get(*pos) != Some(&Token::RParen) {
275                    return false;
276                }
277                *pos += 1;
278            }
279            Some(Token::Ident(_)) => {
280                *pos += 1;
281                while tokens.get(*pos) == Some(&Token::Dot) {
282                    if !matches!(tokens.get(*pos + 1), Some(Token::Ident(_))) {
283                        return false;
284                    }
285                    *pos += 2;
286                }
287                if tokens.get(*pos) == Some(&Token::LParen) {
288                    *pos += 1;
289                    if tokens.get(*pos) == Some(&Token::RParen) {
290                        *pos += 1;
291                    } else {
292                        loop {
293                            if !expr_well_formed(tokens, pos, depth + 1) {
294                                return false;
295                            }
296                            match tokens.get(*pos) {
297                                Some(Token::Comma) => *pos += 1,
298                                Some(Token::RParen) => {
299                                    *pos += 1;
300                                    break;
301                                }
302                                _ => return false,
303                            }
304                        }
305                    }
306                }
307            }
308            _ => return false,
309        }
310        // A binary operator continues the expression with another operand.
311        match tokens.get(*pos) {
312            Some(Token::Plus | Token::Minus | Token::Star | Token::Slash | Token::Percent) => *pos += 1,
313            _ => return true,
314        }
315    }
316}
317
318/// Extract the flat `field -> f64` values map from a configurator JSON value,
319/// preferring a `.values` sub-object (the normalized configurator state shape).
320/// Non-numeric fields are dropped (an expression referencing one errors clearly
321/// at member-access time).
322fn configurator_values(configurator: &serde_json::Value) -> HashMap<String, f64> {
323    let source = configurator
324        .get("values")
325        .filter(|value| value.is_object())
326        .unwrap_or(configurator);
327    let mut map = HashMap::new();
328    if let Some(object) = source.as_object() {
329        for (key, value) in object {
330            if let Some(number) = value_as_f64(value) {
331                map.insert(key.clone(), number);
332            }
333        }
334    }
335    map
336}
337
338fn value_as_f64(value: &serde_json::Value) -> Option<f64> {
339    match value {
340        serde_json::Value::Number(number) => number.as_f64(),
341        serde_json::Value::String(text) => text.trim().parse::<f64>().ok(),
342        serde_json::Value::Bool(flag) => Some(if *flag { 1.0 } else { 0.0 }),
343        _ => None,
344    }
345}
346
347// ---------------------------------------------------------------------------
348// Tokenizer
349// ---------------------------------------------------------------------------
350
351#[derive(Debug, Clone, PartialEq)]
352enum Token {
353    Number(f64),
354    Ident(String),
355    Plus,
356    Minus,
357    Star,
358    Slash,
359    Percent,
360    LParen,
361    RParen,
362    Dot,
363    Comma,
364    Assign,
365    Semi,
366    Eof,
367}
368
369fn tokenize(source: &str) -> Result<Vec<Token>, String> {
370    let bytes = source.as_bytes();
371    let mut tokens = Vec::new();
372    let mut i = 0;
373    while i < bytes.len() {
374        let c = bytes[i] as char;
375        if c.is_whitespace() {
376            i += 1;
377            continue;
378        }
379        // `//` line comment.
380        if c == '/' && i + 1 < bytes.len() && bytes[i + 1] as char == '/' {
381            while i < bytes.len() && bytes[i] as char != '\n' {
382                i += 1;
383            }
384            continue;
385        }
386        match c {
387            '+' => {
388                tokens.push(Token::Plus);
389                i += 1;
390            }
391            '-' => {
392                tokens.push(Token::Minus);
393                i += 1;
394            }
395            '*' => {
396                tokens.push(Token::Star);
397                i += 1;
398            }
399            '/' => {
400                tokens.push(Token::Slash);
401                i += 1;
402            }
403            '%' => {
404                tokens.push(Token::Percent);
405                i += 1;
406            }
407            '(' => {
408                tokens.push(Token::LParen);
409                i += 1;
410            }
411            ')' => {
412                tokens.push(Token::RParen);
413                i += 1;
414            }
415            '.' if !next_is_digit(bytes, i + 1) => {
416                tokens.push(Token::Dot);
417                i += 1;
418            }
419            ',' => {
420                tokens.push(Token::Comma);
421                i += 1;
422            }
423            '=' => {
424                tokens.push(Token::Assign);
425                i += 1;
426            }
427            ';' => {
428                tokens.push(Token::Semi);
429                i += 1;
430            }
431            _ if c.is_ascii_digit() || c == '.' => {
432                let (number, next) = scan_number(bytes, i)?;
433                tokens.push(Token::Number(number));
434                i = next;
435            }
436            _ if c.is_ascii_alphabetic() || c == '_' || c == '$' => {
437                let start = i;
438                while i < bytes.len() {
439                    let ch = bytes[i] as char;
440                    if ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' {
441                        i += 1;
442                    } else {
443                        break;
444                    }
445                }
446                tokens.push(Token::Ident(source[start..i].to_string()));
447            }
448            _ => return Err(format!("unexpected character `{c}` in expression")),
449        }
450    }
451    tokens.push(Token::Eof);
452    Ok(tokens)
453}
454
455fn next_is_digit(bytes: &[u8], i: usize) -> bool {
456    i < bytes.len() && (bytes[i] as char).is_ascii_digit()
457}
458
459/// Scan a decimal number with optional fraction and scientific exponent.
460fn scan_number(bytes: &[u8], start: usize) -> Result<(f64, usize), String> {
461    let mut i = start;
462    while next_is_digit(bytes, i) {
463        i += 1;
464    }
465    if i < bytes.len() && bytes[i] as char == '.' {
466        i += 1;
467        while next_is_digit(bytes, i) {
468            i += 1;
469        }
470    }
471    if i < bytes.len() && (bytes[i] as char == 'e' || bytes[i] as char == 'E') {
472        let mut j = i + 1;
473        if j < bytes.len() && (bytes[j] as char == '+' || bytes[j] as char == '-') {
474            j += 1;
475        }
476        if next_is_digit(bytes, j) {
477            i = j;
478            while next_is_digit(bytes, i) {
479                i += 1;
480            }
481        }
482    }
483    let text = std::str::from_utf8(&bytes[start..i]).map_err(|error| error.to_string())?;
484    let value = text
485        .parse::<f64>()
486        .map_err(|_| format!("invalid number literal `{text}`"))?;
487    Ok((value, i))
488}
489
490// ---------------------------------------------------------------------------
491// Parser + evaluator (evaluated directly against a fixed env)
492// ---------------------------------------------------------------------------
493
494struct Parser<'a> {
495    tokens: &'a [Token],
496    pos: usize,
497    env: &'a Env,
498}
499
500impl<'a> Parser<'a> {
501    fn new(tokens: &'a [Token], env: &'a Env) -> Self {
502        Self {
503            tokens,
504            pos: 0,
505            env,
506        }
507    }
508
509    fn peek(&self) -> &Token {
510        self.tokens.get(self.pos).unwrap_or(&Token::Eof)
511    }
512
513    fn advance(&mut self) -> Token {
514        let token = self.tokens.get(self.pos).cloned().unwrap_or(Token::Eof);
515        self.pos += 1;
516        token
517    }
518
519    fn expect_eof(&self) -> Result<(), String> {
520        match self.peek() {
521            Token::Eof => Ok(()),
522            other => Err(format!("unexpected trailing token {other:?} in expression")),
523        }
524    }
525
526    fn parse_expr(&mut self) -> Result<f64, String> {
527        let mut value = self.parse_term()?;
528        loop {
529            match self.peek() {
530                Token::Plus => {
531                    self.advance();
532                    value += self.parse_term()?;
533                }
534                Token::Minus => {
535                    self.advance();
536                    value -= self.parse_term()?;
537                }
538                _ => break,
539            }
540        }
541        Ok(value)
542    }
543
544    fn parse_term(&mut self) -> Result<f64, String> {
545        let mut value = self.parse_unary()?;
546        loop {
547            match self.peek() {
548                Token::Star => {
549                    self.advance();
550                    value *= self.parse_unary()?;
551                }
552                Token::Slash => {
553                    self.advance();
554                    value /= self.parse_unary()?;
555                }
556                Token::Percent => {
557                    self.advance();
558                    value %= self.parse_unary()?;
559                }
560                _ => break,
561            }
562        }
563        Ok(value)
564    }
565
566    fn parse_unary(&mut self) -> Result<f64, String> {
567        if self.peek() == &Token::Minus {
568            self.advance();
569            return Ok(-self.parse_unary()?);
570        }
571        if self.peek() == &Token::Plus {
572            self.advance();
573            return self.parse_unary();
574        }
575        self.parse_primary()
576    }
577
578    fn parse_primary(&mut self) -> Result<f64, String> {
579        match self.advance() {
580            Token::Number(value) => Ok(value),
581            Token::LParen => {
582                let value = self.parse_expr()?;
583                if self.advance() != Token::RParen {
584                    return Err("expected ')'".to_string());
585                }
586                Ok(value)
587            }
588            Token::Ident(first) => {
589                let mut parts = vec![first];
590                while self.peek() == &Token::Dot {
591                    self.advance();
592                    match self.advance() {
593                        Token::Ident(name) => parts.push(name),
594                        other => {
595                            return Err(format!("expected identifier after '.', found {other:?}"))
596                        }
597                    }
598                }
599                if self.peek() == &Token::LParen {
600                    self.advance();
601                    let args = self.parse_args()?;
602                    self.eval_call(&parts.join("."), &args)
603                } else {
604                    self.eval_reference(&parts)
605                }
606            }
607            other => Err(format!("unexpected token {other:?} in expression")),
608        }
609    }
610
611    fn parse_args(&mut self) -> Result<Vec<f64>, String> {
612        let mut args = Vec::new();
613        if self.peek() == &Token::RParen {
614            self.advance();
615            return Ok(args);
616        }
617        loop {
618            args.push(self.parse_expr()?);
619            match self.advance() {
620                Token::Comma => continue,
621                Token::RParen => break,
622                other => return Err(format!("expected ',' or ')' in argument list, found {other:?}")),
623            }
624        }
625        Ok(args)
626    }
627
628    fn eval_reference(&self, parts: &[String]) -> Result<f64, String> {
629        match parts.len() {
630            1 => match self.env.vars.get(&parts[0]) {
631                Some(EvalValue::Scalar(value)) => Ok(*value),
632                Some(EvalValue::Object(_)) => {
633                    Err(format!("`{}` is an object, not a number", parts[0]))
634                }
635                None => Err(format!("unknown identifier `{}`", parts[0])),
636            },
637            2 => {
638                if parts[0] == "Math" {
639                    return match parts[1].as_str() {
640                        "PI" => Ok(std::f64::consts::PI),
641                        "E" => Ok(std::f64::consts::E),
642                        other => Err(format!("unsupported Math constant `Math.{other}`")),
643                    };
644                }
645                match self.env.vars.get(&parts[0]) {
646                    Some(EvalValue::Object(map)) => map
647                        .get(&parts[1])
648                        .copied()
649                        .ok_or_else(|| format!("`{}.{}` is not a number", parts[0], parts[1])),
650                    Some(EvalValue::Scalar(_)) => {
651                        Err(format!("`{}` is a number, not an object", parts[0]))
652                    }
653                    None => Err(format!("unknown identifier `{}`", parts[0])),
654                }
655            }
656            _ => Err(format!("unsupported member access `{}`", parts.join("."))),
657        }
658    }
659
660    fn eval_call(&self, name: &str, args: &[f64]) -> Result<f64, String> {
661        let expect = |arity: usize| -> Result<(), String> {
662            if args.len() == arity {
663                Ok(())
664            } else {
665                Err(format!(
666                    "`{name}` expects {arity} argument(s), got {}",
667                    args.len()
668                ))
669            }
670        };
671        match name {
672            "Math.sin" => {
673                expect(1)?;
674                Ok(args[0].sin())
675            }
676            "Math.cos" => {
677                expect(1)?;
678                Ok(args[0].cos())
679            }
680            "Math.tan" => {
681                expect(1)?;
682                Ok(args[0].tan())
683            }
684            "Math.sqrt" => {
685                expect(1)?;
686                Ok(args[0].sqrt())
687            }
688            "Math.abs" => {
689                expect(1)?;
690                Ok(args[0].abs())
691            }
692            "Math.floor" => {
693                expect(1)?;
694                Ok(args[0].floor())
695            }
696            "Math.ceil" => {
697                expect(1)?;
698                Ok(args[0].ceil())
699            }
700            "Math.round" => {
701                expect(1)?;
702                // JavaScript Math.round rounds half up (toward +inf); Rust round() is
703                // half-away-from-zero. Match JavaScript.
704                Ok((args[0] + 0.5).floor())
705            }
706            "Math.pow" => {
707                expect(2)?;
708                Ok(args[0].powf(args[1]))
709            }
710            "Math.min" => {
711                if args.is_empty() {
712                    return Ok(f64::INFINITY);
713                }
714                Ok(args.iter().copied().fold(f64::INFINITY, f64::min))
715            }
716            "Math.max" => {
717                if args.is_empty() {
718                    return Ok(f64::NEG_INFINITY);
719                }
720                Ok(args.iter().copied().fold(f64::NEG_INFINITY, f64::max))
721            }
722            other => Err(format!("unsupported function `{other}`")),
723        }
724    }
725}
726