Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

Language: reject extra positional arguments and trailing tokens, list accepted names

finalpantasy0e93d8b4de6f
diff --git a/crates/forma-lang/src/compact.rs b/crates/forma-lang/src/compact.rs
index 990b314..a2a7cf5 100644
--- a/crates/forma-lang/src/compact.rs
+++ b/crates/forma-lang/src/compact.rs
@@ -317,6 +317,48 @@ pub fn eval_compact(scene: &mut Scene, src: &str) -> Result<(), String> {
continue;
}
let cmd = tokens[0];
+ // Trailing tokens on fixed-arity commands used to be dropped silently.
+ let fixed_arity: Option<(usize, &str)> = match cmd {
+ "bev" => Some((5, "bev ID edge_sel w [segs]")),
+ "fil" => Some((5, "fil ID edge_sel r [segs]")),
+ "shl" => Some((4, "shl ID t [open|closed]")),
+ "ext" => Some((4, "ext ID face_sel d")),
+ "ins" => Some((5, "ins ID face_sel a [d]")),
+ "subdiv" => Some((3, "subdiv ID n")),
+ "mov" => Some((5, "mov ID dx dy dz")),
+ "rot" => Some((5, "rot ID rx ry rz")),
+ "scl" => Some((5, "scl ID sx sy sz")),
+ "z0" => Some((3, "z0 ID z")),
+ "mir" => Some((3, "mir ID x|y|z")),
+ "del" => Some((2, "del ID")),
+ "ckpt" => Some((2, "ckpt ID")),
+ "rb" => Some((2, "rb ID")),
+ "undo" => Some((1, "undo")),
+ _ => None,
+ };
+ if let Some((max_tokens, usage)) = fixed_arity {
+ if tokens.len() > max_tokens {
+ return Err(format!(
+ "line {line}: {cmd}: unexpected trailing token '{}' (usage: {usage})",
+ tokens[max_tokens]
+ ));
+ }
+ }
+ if cmd == "shl" && tokens.len() > 3 && tokens[3] != "open" && tokens[3] != "closed" {
+ return Err(format!("line {line}: shl: expected open or closed, got '{}' (usage: shl ID t [open|closed])", tokens[3]));
+ }
+ if cmd == "mir" && tokens.len() > 2 && !matches!(tokens[2], "x" | "y" | "z") {
+ return Err(format!("line {line}: mir: invalid axis '{}' (usage: mir ID x|y|z)", tokens[2]));
+ }
+ if matches!(cmd, "bev" | "fil" | "subdiv") {
+ let (idx, what) = if cmd == "subdiv" { (2, "n") } else { (4, "segs") };
+ if let Some(tok) = tokens.get(idx) {
+ let v = parse_f(tok, line)?;
+ if !(v >= 0.0 && v <= 1024.0 && v.fract() == 0.0) {
+ return Err(format!("line {line}: {cmd}: {what} must be a whole number >= 0 (got {tok})"));
+ }
+ }
+ }
match cmd {
"new" => {
if tokens.len() < 3 {
@@ -469,7 +511,11 @@ pub fn eval_compact(scene: &mut Scene, src: &str) -> Result<(), String> {
}
scene.set_part(id, mesh).map_err(|e| format!("line {line}: {e}"))?;
}
- other => return Err(format!("line {line}: unknown command '{other}'")),
+ other => {
+ return Err(format!(
+ "line {line}: unknown command '{other}' (accepted: new, add, sub, int, bev, fil, shl, ext, ins, subdiv, mov, rot, scl, z0, mir, del, ckpt, rb, undo)"
+ ))
+ }
}
}
Ok(())
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index d1701fd..f2e7942 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -287,6 +287,93 @@ fn warn_if_clamped(scene: &mut Scene, op: &str, param: &str, requested: usize, l
}
}
+/// Most positional arguments each function reads. More than this used to be dropped silently.
+fn max_call_positional(name: &str) -> Option<usize> {
+ Some(match name {
+ "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad" => 1,
+ "bezier" => 2,
+ "nurbs" | "bspline" => 3,
+ "clearance" | "section" => 2,
+ "checkpoint" | "rollback" | "del" | "remove" => 1,
+ "undo" => 0,
+ "box" => 3,
+ "cyl" | "cylinder" | "prism" => 4,
+ "cone" | "frustum" => 4,
+ "sphere" => 2,
+ "torus" => 3,
+ "revolve" => 2,
+ "arc_tube" => 7,
+ "tube" => 3,
+ "extrude2d" => 3,
+ "pipe" | "hollow_cyl" => 5,
+ "loft" => 2,
+ "thread" | "helix" => 5,
+ "sweep" => 2,
+ "text3d" | "text" => 3,
+ "load" | "import" => 2,
+ _ => return None,
+ })
+}
+
+/// Most positional arguments each pipeline op reads (not counting the piped mesh).
+fn max_pipe_positional(op_name: &str) -> Option<usize> {
+ Some(match op_name {
+ "add" | "union" | "cut" | "sub" | "diff" | "intersect" => 1,
+ "bevel" => 3,
+ "shell" | "extrude" | "subsurf" | "subdiv" => 2,
+ "inset" => 3,
+ "move" | "translate" | "rot" | "rotate" | "scale" | "color" => 3,
+ "align_z0" => 1,
+ "align" => 3,
+ "on" | "place_on" => 2,
+ "mat" | "material" => 4,
+ "mirror" => 2,
+ "pattern_linear" | "array" | "pattern_radial" | "radial" => 3,
+ "decimate" | "lod" | "textures" | "tex" | "paint" | "remesh" => 1,
+ "lit" | "flat" => 0,
+ "smooth" | "unwrap" | "uv" => 2,
+ "solidify" | "deform" | "bisect" => 3,
+ _ => return None,
+ })
+}
+
+fn check_positional_count(n: usize, max: Option<usize>, allowed_kw: Option<&[&str]>, ctx: &str) -> Result<(), String> {
+ let Some(max) = max else { return Ok(()) };
+ if n <= max {
+ return Ok(());
+ }
+ let kws = match allowed_kw {
+ Some(k) if !k.is_empty() => format!("; keywords: {}", k.join(", ")),
+ _ => String::new(),
+ };
+ Err(format!("{ctx}: takes at most {max} positional argument(s), got {n}{kws}"))
+}
+
+const CALL_NAMES: &[&str] = &[
+ "box", "cyl", "cylinder", "prism", "cone", "frustum", "sphere", "torus", "revolve", "arc_tube", "tube", "extrude2d",
+ "pipe", "hollow_cyl", "loft", "thread", "helix", "sweep", "text3d", "text", "load", "import", "bezier", "nurbs",
+ "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "del", "remove", "sqrt", "sin", "cos", "asin",
+ "acos", "abs", "deg", "rad",
+];
+
+const PIPE_OP_NAMES: &[&str] = &[
+ "add", "union", "cut", "sub", "diff", "intersect", "bevel", "shell", "extrude", "inset", "subsurf",
+ "subdiv", "move", "translate", "rot", "rotate", "scale", "align_z0", "align", "on", "place_on", "mat", "material",
+ "color", "mirror", "pattern_linear", "array", "pattern_radial", "radial", "decimate", "lod", "textures", "tex",
+ "paint", "lit", "smooth", "flat", "solidify", "deform", "unwrap", "uv", "remesh", "bisect",
+];
+
+/// " — did you mean 'x'?" for the closest known name, plus the full list of accepted names.
+fn unknown_name_hint(name: &str, known: &[&str]) -> String {
+ let lower = name.to_lowercase();
+ let best = known.iter().map(|k| (edit_distance(&lower, k), *k)).min();
+ let suggestion = match best {
+ Some((d, k)) if d <= 2.max(name.len() / 3) => format!(" (did you mean '{k}'?)"),
+ _ => String::new(),
+ };
+ format!("{suggestion}; accepted: {}", known.join(", "))
+}
+
fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
Some(match name {
"sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad" => &["x"],
@@ -622,6 +709,7 @@ impl<'a> Parser<'a> {
if let Some(allowed) = allowed_call_kwargs(name) {
check_allowed_kwargs(&kw, allowed, &ctx)?;
}
+ check_positional_count(pos.len(), max_call_positional(name), allowed_call_kwargs(name), &ctx)?;
let get_num_any = |idx: usize, keys: &[&str], def: Option<f64>| -> Result<f64, String> {
for &k in keys {
if let Some(v) = kw.get(k) {
@@ -963,7 +1051,11 @@ impl<'a> Parser<'a> {
.load_asset_mesh_with_opts(path_or_key, yup)
.map_err(|e| format!("{ctx}: {e}"))?
}
- _ => return Err(format!("{ctx}: unknown function '{name}'")),
+ _ => {
+ let mut known: Vec<&str> = CALL_NAMES.to_vec();
+ known.extend_from_slice(PIPE_OP_NAMES);
+ return Err(format!("{ctx}: unknown function '{name}'{}", unknown_name_hint(name, &known)));
+ }
};
// Optional placement kwargs common to all primitives: rot=, at= (single OR multi-point!), z0=
@@ -1020,6 +1112,7 @@ impl<'a> Parser<'a> {
if let Some(allowed) = allowed_pipe_kwargs(op_name) {
check_allowed_kwargs(&kw, allowed, &ctx)?;
}
+ check_positional_count(pos.len(), max_pipe_positional(op_name), allowed_pipe_kwargs(op_name), &ctx)?;
let op_id = self.scene.next_op();
match op_name {
"add" | "union" | "cut" | "sub" | "diff" | "intersect" => {
@@ -1313,7 +1406,7 @@ impl<'a> Parser<'a> {
let clear_inner = kw.get("clear_inner").or_else(|| pos.get(2)).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(false);
forma_core::remesh::bisect_mesh(&mesh, n, offset, clear_inner, op_id).map_err(|e| format!("{ctx}: {e}"))
}
- _ => Err(format!("{ctx}: unknown pipeline op '{op_name}'")),
+ _ => Err(format!("{ctx}: unknown pipeline op '{op_name}'{}", unknown_name_hint(op_name, PIPE_OP_NAMES))),
}
}
}
diff --git a/crates/forma-lang/tests/validation.rs b/crates/forma-lang/tests/validation.rs
new file mode 100644
index 0000000..801b9ba
--- /dev/null
+++ b/crates/forma-lang/tests/validation.rs
@@ -0,0 +1,138 @@
+//! Input validation of both dialects: nothing the user typed may be dropped silently.
+use forma_core::Scene;
+use forma_lang::{eval_script, Dialect};
+
+fn pipe_err(src: &str) -> String {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ match eval_script(&mut s, Dialect::Pipe, src) {
+ Ok(_) => panic!("expected an error for: {src}"),
+ Err(e) => e,
+ }
+}
+
+fn compact_err(src: &str) -> String {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ match eval_script(&mut s, Dialect::Compact, src) {
+ Ok(_) => panic!("expected an error for: {src}"),
+ Err(e) => e,
+ }
+}
+
+#[test]
+fn pipe_rejects_extra_positional_arguments() {
+ for src in [
+ "p = box(1,1,1,1,1)",
+ "p = sphere(1,2,3,4,5)",
+ "p = torus(2,0.5,16,9)",
+ "p = box(1,1,1) | move(1,2,3,4)",
+ "p = box(1,1,1) | scale(1,1,1,5)",
+ "p = box(1,1,1) | rot(1,2,3,4)",
+ "p = box(1,1,1) | shell(0.1, true, 0.3)",
+ "p = box(1,1,1) | inset(top, 0.1, 0.2, 0.3)",
+ "p = box(1,1,1) | subsurf(1,false,3)",
+ "p = box(1,1,1) | decimate(0.5, 3, 4)",
+ "p = box(1,1,1) | cut(box(0.5,0.5,2), box(0.2,0.2,3))",
+ "p = move(box(1,1,1), 1, 2, 3, 4)",
+ ] {
+ let e = pipe_err(src);
+ assert!(e.contains("positional argument"), "{src} -> {e}");
+ assert!(e.lines().count() == 1, "one-line message expected: {e}");
+ }
+ // The message names the command and lists what it accepts.
+ let e = pipe_err("p = box(1,1,1) | shell(0.1, true, 0.3)");
+ assert!(e.contains("shell()") && e.contains("at most 2") && e.contains("open_top"), "{e}");
+}
+
+#[test]
+fn pipe_valid_forms_from_the_spec_still_evaluate() {
+ for src in [
+ "p = box(1,2,3)",
+ "p = box(2)",
+ "p = cyl(1,2,16)",
+ "p = cyl(1,2,segs=6,axis=x)",
+ "p = cone(1,0.5,2)",
+ "p = sphere(1)",
+ "p = torus(2,0.5)",
+ "p = pipe(1,0.8,2)",
+ "p = revolve([(0,0),(1,0),(0.5,1),(0,1)], segs=32)",
+ "p = tube([(0,0,0),(1,0,0),(1,1,0)], r=0.08)",
+ "p = extrude2d([(0,0),(1,0),(1,1),(0,1)], 0, 1)",
+ "p = box(1,1,1) | move(1,2,3) | rot(0,0,45) | scale(2,2,2)",
+ "p = box(1,1,1) | move((1,2,3))",
+ "p = box(1,1,1) | shell(0.1, open_top=true)",
+ "p = box(2,2,1) | inset(top, 0.2, depth=-0.2)",
+ "p = box(2,2,1) | extrude(top, 0.5)",
+ "p = box(1,1,1) | bevel(vertical, 0.1, segs=2)",
+ "p = box(1,1,1) | mirror(x)",
+ "p = box(1,1,1) | array(3, (2,0,0))",
+ "p = box(1,1,1) | radial(4, r=2)",
+ "p = box(1,1,1) | align(z, min, 0)",
+ "p = box(2,2,2) | cut(cyl(0.5,3))",
+ "p = cut(box(2,2,2), cyl(0.5,3))",
+ "p = box(1,1,1) | subsurf(1)",
+ "p = box(1,1,1) | mat(\"steel\", color=(0.5,0.5,0.5))",
+ "p = text3d(\"AB-12\", height=0.5, depth=0.1)",
+ ] {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ if let Err(e) = eval_script(&mut s, Dialect::Pipe, src) {
+ panic!("valid script rejected: {src} -> {e}");
+ }
+ }
+}
+
+#[test]
+fn pipe_unknown_names_get_a_suggestion_and_the_accepted_list() {
+ let e = pipe_err("p = bx(1,1,1)");
+ assert!(e.contains("unknown function 'bx'") && e.contains("did you mean 'box'") && e.contains("accepted:"), "{e}");
+ let e = pipe_err("p = box(1,1,1) | bevell(all, 0.1)");
+ assert!(e.contains("unknown pipeline op 'bevell'") && e.contains("did you mean 'bevel'"), "{e}");
+ assert!(e.contains("accepted:") && e.contains("bevel") && e.lines().count() == 1, "{e}");
+ let e = pipe_err("p = box(1,1,1, foo=3)");
+ assert!(e.contains("box()") && e.contains("unknown keyword argument 'foo'") && e.contains("valid:"), "{e}");
+ let e = pipe_err("p = box(\"a\",1,1)");
+ assert!(e.contains("box()") && e.contains("expected number"), "{e}");
+ let e = pipe_err("p = cyl(1)");
+ assert!(e.contains("cyl()") && e.contains("missing argument 'h'"), "{e}");
+}
+
+#[test]
+fn pipe_surfaces_kernel_refusals_by_operation_name() {
+ assert!(pipe_err("p = text3d(\"A\u{e7}\", height=0.5, depth=0.1)").contains("text3d: unsupported character"));
+ assert!(pipe_err("p = revolve([(0,0),(1,0),(-0.5,1),(0,1)])").contains("negative radius"));
+ assert!(pipe_err("p = box(2,2,1) | inset(top, 5)").contains("does not fit"));
+ assert!(pipe_err("p = box(2,2,1) | inset(top, 0)").contains("inset: amount"));
+ assert!(pipe_err("p = box(2,2,1) | extrude(top, -2)").contains("extrude:"));
+ assert!(pipe_err("p = tube([(0,0,0),(1,0,0),(0,0.05,0)], r=0.2)").contains("tube:"));
+ assert!(pipe_err("p = box(2,2,2) | cut(box(3,3,3))").contains("empty result"));
+}
+
+#[test]
+fn compact_rejects_trailing_tokens_and_bad_enums() {
+ for (src, needle) in [
+ ("new a box 1 1 1\nmov a 1 2 3 4", "mov: unexpected trailing token '4'"),
+ ("new a box 1 1 1\nscl a 1 2 3 4", "scl: unexpected trailing token"),
+ ("new a box 1 1 1\nshl a 0.1 open extra", "shl: unexpected trailing token 'extra'"),
+ ("new a box 1 1 1\nshl a 0.1 opn", "shl: expected open or closed"),
+ ("new a box 1 1 1\nins a top 0.1 0.1 9", "ins: unexpected trailing token"),
+ ("new a box 1 1 1\nsubdiv a 1 2", "subdiv: unexpected trailing token"),
+ ("new a box 1 1 1\nsubdiv a -1", "subdiv: n must be a whole number"),
+ ("new a box 1 1 1\nbev a all 0.1 2.5", "bev: segs must be a whole number"),
+ ("new a box 1 1 1\nmir a xyz", "mir: invalid axis 'xyz'"),
+ ("new a box 1 1 1\nmir a x y", "mir: unexpected trailing token"),
+ ("new a box 1 1 1\nz0 a 1 2", "z0: unexpected trailing token"),
+ ("new a box 1 1 1\nundo now", "undo: unexpected trailing token"),
+ ("new a box 1 1 1 9", "unexpected trailing token '9'"),
+ ("frob a 1", "unknown command 'frob' (accepted:"),
+ ("new a bx 1 1 1", "unknown primitive 'bx'"),
+ ] {
+ let e = compact_err(src);
+ assert!(e.contains(needle), "{src:?} -> {e}");
+ assert!(e.lines().count() == 1, "one-line message expected: {e}");
+ }
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Compact, "new a box 2 2 1\nmov a 1 2 3\nshl a 0.1 closed\nmir a x").unwrap();
+}