From fe1f33a76accfdcdf3fa546110a4e74640e8c1c7 Mon Sep 17 00:00:00 2001 From: Faris Basha TM <72191505+farisbasha@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:29:05 +0530 Subject: [PATCH] feat(lang): add assert statements to Forma-Pipe `assert lhs rhs [, "message"]` compares two number expressions (< <= > >= == !=). A false assert fails the script with both values, so the eval transaction rolls back. Comparison operators are only parsed inside assert. Adds a spec line and a GBNF rule. Refs #132 --- crates/forma-lang/src/lib.rs | 1 + crates/forma-lang/src/pipeline.rs | 108 +++++++++++++++++++- crates/forma-lang/tests/assert_statement.rs | 84 +++++++++++++++ grammar/forma_pipe.gbnf | 4 +- 4 files changed, 195 insertions(+), 2 deletions(-) create mode 100644 crates/forma-lang/tests/assert_statement.rs diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs index 78d9b62..52f2e33 100644 --- a/crates/forma-lang/src/lib.rs +++ b/crates/forma-lang/src/lib.rs @@ -79,6 +79,7 @@ add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis= bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all] move(x,y,z) rot(rx,ry,rz) scale(sx,sy,sz) align(x|y|z,min|center|max,val) on(base) align_z0(z) mat(name,color=(r,g,b),metallic=,roughness=) color(r,g,b) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z) +assert expr <|<=|>|>=|==|!= expr[,"msg"] (fails + rolls back) Topics: deform|curves|uv|remesh|scene"#; /// Progressive on-demand domain specs (loaded only when requested). diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs index 7902859..c5e29cc 100644 --- a/crates/forma-lang/src/pipeline.rs +++ b/crates/forma-lang/src/pipeline.rs @@ -36,6 +36,12 @@ enum Tok { Minus, Star, Slash, + Lt, + Le, + Gt, + Ge, + EqEq, + Ne, Newline, Eof, } @@ -57,6 +63,12 @@ impl Tok { Tok::Minus => "'-'".into(), Tok::Star => "'*'".into(), Tok::Slash => "'/'".into(), + Tok::Lt => "'<'".into(), + Tok::Le => "'<='".into(), + Tok::Gt => "'>'".into(), + Tok::Ge => "'>='".into(), + Tok::EqEq => "'=='".into(), + Tok::Ne => "'!='".into(), Tok::Newline => "end of line".into(), Tok::Eof => "end of input".into(), } @@ -120,7 +132,13 @@ fn tokenize(src: &str) -> Result, String> { '[' => { depth += 1; out.push((Tok::LBracket, line)); i += 1; } ']' => { depth -= 1; out.push((Tok::RBracket, line)); i += 1; } ',' => { out.push((Tok::Comma, line)); i += 1; } + '=' if chars.get(i + 1) == Some(&'=') => { out.push((Tok::EqEq, line)); i += 2; } '=' => { out.push((Tok::Eq, line)); i += 1; } + '!' if chars.get(i + 1) == Some(&'=') => { out.push((Tok::Ne, line)); i += 2; } + '<' if chars.get(i + 1) == Some(&'=') => { out.push((Tok::Le, line)); i += 2; } + '<' => { out.push((Tok::Lt, line)); i += 1; } + '>' if chars.get(i + 1) == Some(&'=') => { out.push((Tok::Ge, line)); i += 2; } + '>' => { out.push((Tok::Gt, line)); i += 1; } '|' => { out.push((Tok::Pipe, line)); i += 1; } '+' => { out.push((Tok::Plus, line)); i += 1; } '-' => { out.push((Tok::Minus, line)); i += 1; } @@ -467,7 +485,7 @@ fn is_bare_selector_kw(id: &str) -> bool { fn is_builtin_name(name: &str) -> bool { CALL_NAMES.contains(&name) || PIPE_OP_NAMES.contains(&name) - || matches!(name, "def" | "for" | "in" | "range") + || matches!(name, "def" | "for" | "in" | "range" | "assert") || is_reserved_constant(name) } @@ -629,6 +647,12 @@ impl<'a> Parser<'a> { { return self.parse_def_stmt(); } + // Check `assert lhs rhs [, "message"]` + if matches!(self.peek(), Tok::Ident(s) if s == "assert") + && !matches!(self.toks.get(self.pos + 1).map(|t| &t.0), Some(Tok::Eq)) + { + return self.parse_assert_stmt(); + } // Check `ID = expr` if let Tok::Ident(name) = self.peek().clone() { if self.pos + 1 < self.toks.len() && matches!(self.toks[self.pos + 1].0, Tok::Eq) { @@ -694,6 +718,88 @@ impl<'a> Parser<'a> { Ok(()) } + /// `assert lhs rhs [, "message"]`: compares two number expressions and + /// fails the script (rolling it back like any other eval error) when false. + fn parse_assert_stmt(&mut self) -> Result<(), String> { + let line = self.line(); + self.bump(); // 'assert' + let lhs_start = self.pos; + let lhs = self.parse_pipe()?; + let lhs_end = self.pos; + let op = self.bump(); + if !matches!(op, Tok::Lt | Tok::Le | Tok::Gt | Tok::Ge | Tok::EqEq | Tok::Ne) { + return Err(format!( + "line {line}: assert expects a comparison (< <= > >= == !=), got {}", + op.describe() + )); + } + let rhs_start = self.pos; + let rhs = self.parse_pipe()?; + let rhs_end = self.pos; + let message = if matches!(self.peek(), Tok::Comma) { + self.bump(); + match self.bump() { + Tok::Str(m) => Some(m), + other => { + return Err(format!( + "line {line}: assert message must be a string, got {}", + other.describe() + )) + } + } + } else { + None + }; + if !matches!(self.peek(), Tok::Newline | Tok::Eof) { + return Err(format!( + "line {line}: unexpected {} after assert", + self.peek().describe() + )); + } + let ctx = format!("line {line}: assert"); + let a = lhs.as_num(&ctx)?; + let b = rhs.as_num(&ctx)?; + let ok = match op { + Tok::Lt => a < b, + Tok::Le => a <= b, + Tok::Gt => a > b, + Tok::Ge => a >= b, + Tok::EqEq => a == b, + _ => a != b, + }; + if ok { + return Ok(()); + } + let text = format!( + "{} {} {}", + self.source_text(lhs_start, lhs_end), + op.describe().trim_matches('\''), + self.source_text(rhs_start, rhs_end) + ); + let msg = message.map(|m| format!(": {m}")).unwrap_or_default(); + Err(format!("line {line}: assert failed{msg}: {text} (left {a}, right {b})")) + } + + /// Rebuild a compact source snippet from tokens `[start, end)` for diagnostics. + fn source_text(&self, start: usize, end: usize) -> String { + let mut out = String::new(); + for (tok, _) in &self.toks[start..end.min(self.toks.len())] { + let piece = match tok { + Tok::Ident(s) => s.clone(), + Tok::Num(n) => n.to_string(), + Tok::Str(s) => format!("\"{s}\""), + Tok::Comma => ", ".into(), + Tok::Newline | Tok::Eof => continue, + Tok::LParen | Tok::RParen | Tok::LBracket | Tok::RBracket => { + tok.describe().trim_matches('\'').to_string() + } + other => format!(" {} ", other.describe().trim_matches('\'')), + }; + out.push_str(&piece); + } + out + } + fn parse_def_stmt(&mut self) -> Result<(), String> { let def_line = self.line(); self.bump(); // 'def' diff --git a/crates/forma-lang/tests/assert_statement.rs b/crates/forma-lang/tests/assert_statement.rs new file mode 100644 index 0000000..d58fe2a --- /dev/null +++ b/crates/forma-lang/tests/assert_statement.rs @@ -0,0 +1,84 @@ +//! `assert lhs rhs [, "message"]` statements in Forma-Pipe. +use forma_core::Scene; +use forma_lang::{eval_script, Dialect, SPEC_PIPE, SPEC_PIPE_GBNF}; + +fn run(scene: &mut Scene, src: &str) -> Result<(), String> { + eval_script(scene, Dialect::Pipe, src).map(|_| ()) +} + +#[test] +fn passing_asserts_change_nothing() { + let mut s = Scene::new(); + run( + &mut s, + "a = box(1, 1, 1)\nb = box(1, 1, 1, at=(2, 0, 0))\n\ + assert clearance(a, b) >= 0.5\nassert section(a, 0) > 0.5\n\ + w = 0.04\nassert w * 2 <= 0.1\nassert 1 < 2\nassert 2 > 1\nassert 3 == 3\nassert 3 != 4", + ) + .unwrap(); + assert_eq!(s.part_names().len(), 2); +} + +#[test] +fn every_operator_fails_when_false() { + for src in [ + "assert 2 < 1", + "assert 2 <= 1", + "assert 1 > 2", + "assert 1 >= 2", + "assert 1 == 2", + "assert 1 != 1", + ] { + let err = run(&mut Scene::new(), src).unwrap_err(); + assert!(err.starts_with("line 1: assert failed: "), "{src}: {err}"); + } +} + +#[test] +fn failure_reports_expression_values_and_message() { + let err = run( + &mut Scene::new(), + "a = box(1, 1, 1)\nb = box(1, 1, 1, at=(2, 0, 0))\nassert clearance(a, b) >= 1.5, \"gap too small\"", + ) + .unwrap_err(); + assert_eq!( + err, + "line 3: assert failed: gap too small: clearance(a, b) >= 1.5 (left 1, right 1.5)" + ); +} + +#[test] +fn failed_assert_rolls_back_the_script() { + let mut s = Scene::new(); + run(&mut s, "base = box(1, 1, 1)").unwrap(); + let err = run(&mut s, "extra = box(1, 1, 1, at=(3, 0, 0))\nassert clearance(base, extra) > 5"); + assert!(err.is_err()); + assert_eq!(s.part_names(), vec!["base".to_string()]); +} + +#[test] +fn malformed_asserts_are_rejected() { + let cases = [ + ("assert 1", "assert expects a comparison"), + ("assert 1 = 1", "assert expects a comparison"), + ("assert 1 < 2, 3", "assert message must be a string"), + ("assert 1 < 2 3", "unexpected"), + ("a = box(1, 1, 1)\nassert a > 1", "expected number"), + ("def assert(x) = x", "cannot redefine built-in 'assert'"), + ]; + for (src, want) in cases { + let err = run(&mut Scene::new(), src).unwrap_err(); + assert!(err.contains(want), "{src}: {err}"); + } +} + +#[test] +fn comparisons_are_only_allowed_in_assert() { + assert!(run(&mut Scene::new(), "x = 1 < 2").is_err()); +} + +#[test] +fn spec_and_grammar_document_assert() { + assert!(SPEC_PIPE.contains("assert expr")); + assert!(SPEC_PIPE_GBNF.contains("assert-stmt")); +} diff --git a/grammar/forma_pipe.gbnf b/grammar/forma_pipe.gbnf index f9aa47d..406f844 100644 --- a/grammar/forma_pipe.gbnf +++ b/grammar/forma_pipe.gbnf @@ -2,8 +2,10 @@ # Guarantees 0% syntax errors under grammar-constrained LLM generation. root ::= ws-nl (stmt (nl stmt)*)? ws-nl -stmt ::= def-stmt | ident ws "=" ws expr | expr +stmt ::= def-stmt | assert-stmt | ident ws "=" ws expr | expr def-stmt ::= "def" [ \t]+ ident ws "(" ws-nl param-list? ws-nl ")" ws "=" ws expr +assert-stmt ::= "assert" [ \t]+ expr ws cmp-op ws expr (ws "," ws string)? +cmp-op ::= "<=" | ">=" | "==" | "!=" | "<" | ">" param-list ::= param (ws-nl "," ws-nl param)* (ws-nl ",")? param ::= ident (ws "=" ws expr)? expr ::= add-expr (ws-nl "|" ws pipe-call)*