Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Define a named parameter inline from any value input (#4071) (#7341)

froglemonade2f595f38e1c18
diff --git a/crates/doc/src/expr.rs b/crates/doc/src/expr.rs
index 00d281be2d..01688c5050 100644
--- a/crates/doc/src/expr.rs
+++ b/crates/doc/src/expr.rs
@@ -352,6 +352,14 @@ fn lex_spans(s: &str) -> Result<Vec<(Tok, usize, usize)>, DocError> {
{
i = k + 1;
}
+ // A value typed as a definition, `name = expression` (#4071), is worth its expression: the
+ // name is what it defines, not part of it (`Document::define_inline` stores it apart).
+ if i == 0
+ && definition(s).is_some()
+ && let Some(eq) = s.find('=')
+ {
+ i = cs.iter().position(|(b, _)| *b > eq).unwrap_or(cs.len());
+ }
while let Some(&(_, c)) = cs.get(i) {
if c.is_whitespace() {
i += 1;
@@ -565,6 +573,10 @@ pub fn rename_reference(s: &str, old: &str, new: &str) -> String {
/// Is the expression just a number (with an optional unit), like `20`, `20 mm` or `-1.5 in`?
pub fn is_literal(s: &str) -> bool {
+ // A definition names its value: it is not just a number, whatever it defines (#4071).
+ if definition(s).is_some() {
+ return false;
+ }
let Ok(toks) = lex(s) else { return false };
let toks: &[Tok] = match toks.first() {
Some(Tok::Op('-' | '+')) => toks.get(1..).unwrap_or_default(),
@@ -592,8 +604,8 @@ fn is_name_shaped(s: &str) -> bool {
/// A value typed as a definition, `name = expression` (or `#name = expression`, #2371): the name
/// without the `#` and the text after the first `=`, both trimmed (the text may be empty). `None` for anything else, including text whose
/// left side is not shaped like a name (`2 = 3`), which stays an ordinary expression and fails
-/// to parse as before. The dimension input defines a user parameter this way (#2916); other
-/// value inputs can take the same form later.
+/// to parse as before. Every value input defines a user parameter this way (#2916, #4071): until
+/// `Document::define_inline` stores the parameter, the text evaluates as its expression.
pub fn definition(s: &str) -> Option<(&str, &str)> {
let (name, rhs) = s.split_once('=')?;
let name = name.trim();
@@ -979,6 +991,9 @@ pub fn eval_with(s: &str, lookup: &dyn Fn(&str) -> Result<Value, DocError>) -> R
pub fn eval_with_defaults(s: &str, lookup: &dyn Fn(&str) -> Result<Value, DocError>, defaults: Defaults) -> Result<Value, DocError> {
let (toks, spans): (Vec<Tok>, Vec<(usize, usize)>) = lex_spans(s)?.into_iter().map(|(t, a, b)| (t, (a, b))).unzip();
if toks.is_empty() {
+ if let Some((name, _)) = definition(s) {
+ return Err(DocError::Expr(format!("`{name} =` needs a value after the `=`")));
+ }
return Err(DocError::Expr("empty expression".into()));
}
let mut p = Parser { toks, spans, pos: 0, lookup, depth: 0, defaults };
@@ -1470,6 +1485,27 @@ mod tests {
}
}
+ /// Until the design stores it, a definition is worth its expression (#4071): the name is
+ /// not a reference, it is never a plain number, and it renames like its expression.
+ #[test]
+ fn a_definition_evaluates_as_its_expression() {
+ let look = |n: &str| if n == "a" { Ok(Value::length(4.0)) } else { Err(DocError::Expr(format!("unknown parameter `{n}`"))) };
+ let ev = |s: &str| eval_with(s, &look).and_then(|v| v.to_kind(Kind::Length));
+ assert_eq!(ev("w = 20").ok(), Some(20.0));
+ assert_eq!(ev("#w = a * 2").ok(), Some(8.0));
+ assert_eq!(ev("szerokość=1 in").ok(), Some(25.4));
+ assert_eq!(references("w = a + b"), ["a", "b"]);
+ assert!(references("w = 3").is_empty());
+ assert_eq!(rename_reference("w = a * 2", "a", "len"), "w = len * 2");
+ assert_eq!(rename_reference("a = a * 2", "a", "len"), "a = len * 2");
+ assert!(!is_literal("w = 20") && !is_bare_number("w = 20"));
+ assert!(ev("w = w").unwrap_err().to_string().contains("unknown parameter `w`"));
+ assert!(ev("w =").unwrap_err().to_string().contains("`w =` needs a value after the `=`"));
+ for bad in ["w = = 3", "2 = 3", "w == 3", "w = 3 = 4", "= 5 ="] {
+ assert!(ev(bad).is_err(), "{bad}");
+ }
+ }
+
/// A reserved name is refused by saying what kind of word it is.
#[test]
fn a_reserved_name_is_refused_by_its_kind() {
diff --git a/crates/doc/src/inline_params.rs b/crates/doc/src/inline_params.rs
new file mode 100644
index 0000000000..a7aa629528
--- /dev/null
+++ b/crates/doc/src/inline_params.rs
@@ -0,0 +1,202 @@
+//! Values typed as definitions, `name = expression` (#4071): any value input, typed or sent as
+//! a command's parameter, can name its value. Until the design stores it, such a text evaluates
+//! as its expression (`expr::definition`), so a command reads and checks it like any other value;
+//! [`Document::define_inline`] then makes the user parameter `name` with that expression and
+//! leaves `name` where the text was.
+
+use serde::Serialize;
+
+use crate::expr::{self, Kind};
+use crate::params::ExprRole;
+use crate::walk::Walk;
+use crate::{DocError, Document, FeatureKind, Result};
+
+/// A user parameter a value typed as `name = expression` defined.
+#[derive(Clone, Debug, PartialEq, Serialize)]
+pub struct Defined {
+ pub name: String,
+ pub expression: String,
+ pub unit: String,
+}
+
+/// How the place a definition was typed in reads a bare number, which the parameter keeps.
+#[derive(Clone, Copy)]
+enum Reads<'a> {
+ /// A typed value of this kind: lengths in the design's units, angles in degrees.
+ Typed(Kind),
+ /// A model parameter's (a dimension's) own unit.
+ Unit(&'a str),
+ /// A primitive's placement coordinate: millimetres whatever the design's units.
+ Millimetres,
+ /// A value of no fixed kind: the parameter takes its value's unit.
+ Inferred,
+}
+
+/// A definition found: the name, its expression and its unit (`None`: its value's own).
+struct Pending {
+ name: String,
+ expression: String,
+ unit: Option<String>,
+}
+
+/// The definitions found so far: each slot's text becomes the name, the definition is kept.
+struct Found {
+ units: String,
+ defs: Vec<Pending>,
+ problem: Option<String>,
+}
+
+impl Found {
+ /// If `text` is a definition, note it and leave the name in its place.
+ fn take(&mut self, text: &mut String, reads: Reads) {
+ let Some((name, rhs)) = expr::definition(text) else { return };
+ if rhs.is_empty() {
+ self.problem.get_or_insert_with(|| format!("`{name} =` needs a value after the `=`"));
+ return;
+ }
+ let (expression, unit) = match reads {
+ Reads::Typed(Kind::Length) => {
+ let units = expr::length_unit_or_mm(&self.units);
+ (with_unit(rhs, units), Some(units.to_string()))
+ }
+ Reads::Typed(Kind::Angle) => (rhs.to_string(), Some("deg".to_string())),
+ Reads::Typed(Kind::Unitless) => (rhs.to_string(), Some(String::new())),
+ Reads::Unit(u) => (rhs.to_string(), Some(u.to_string())),
+ Reads::Millimetres => (rhs.to_string(), Some("mm".to_string())),
+ Reads::Inferred => (rhs.to_string(), None),
+ };
+ let name = name.to_string();
+ match self.defs.iter().find(|d| d.name == name) {
+ // The same definition in two places (one typed value a command stores twice).
+ Some(d) if d.expression == expression && d.unit == unit => {}
+ Some(_) => {
+ self.problem.get_or_insert_with(|| format!("`{name}` is defined twice with different values"));
+ return;
+ }
+ None => self.defs.push(Pending { name: name.clone(), expression, unit }),
+ }
+ *text = name;
+ }
+
+ /// [`Found::take`] for an expression field.
+ fn take_expr(&mut self, e: &mut expr::Expr, reads: Reads) {
+ if expr::definition(e.as_str()).is_none() {
+ return;
+ }
+ let mut text = e.as_str().to_string();
+ self.take(&mut text, reads);
+ *e = text.into();
+ }
+}
+
+/// A bare number in the design's length unit, as a typed length reads it.
+fn with_unit(rhs: &str, units: &str) -> String {
+ if units != "mm" && expr::is_bare_number(rhs) { format!("{} {units}", rhs.trim()) } else { rhs.to_string() }
+}
+
+impl Document {
+ /// Store every value typed as `name = expression`: the user parameter `name` with that
+ /// expression (a bare number read as the value would read it, in that unit), and `name`
+ /// where the text was. A name that is taken or reserved is refused, as is a definition where
+ /// none can be made: in a parameter's own expression or a configuration cell. All or nothing:
+ /// on an error the design is unchanged.
+ pub fn define_inline(&mut self) -> Result<Vec<Defined>> {
+ // Where a definition is refused: a parameter's expression defines nothing else (the
+ // parameters command renames the parameter instead), nor does a configuration row.
+ if let Some(p) = self.params.iter().find(|p| !p.model && expr::definition(&p.expr).is_some()) {
+ let other = expr::definition(&p.expr).map(|(n, _)| n).unwrap_or_default();
+ return Err(DocError::Invalid(format!(
+ "the expression of `{}` cannot define another parameter `{other}`: add `{other}` as a parameter of its own",
+ p.name
+ )));
+ }
+ // Only a parameter's cells are expressions (a text parameter's are texts).
+ let numeric: Vec<bool> =
+ self.configs.columns.iter().map(|c| matches!(c, crate::config::Column::Param(n) if self.text_param(n).is_none())).collect();
+ let mut cells = self.configs.rows.iter().flat_map(|r| r.cells.iter().zip(&numeric).filter(|(_, n)| **n).map(|(c, _)| c));
+ if let Some(other) = cells.find_map(|c| expr::definition(c).map(|(n, _)| n)) {
+ return Err(DocError::Invalid(format!("a configuration cell cannot define the parameter `{other}`: add it in Parameters first")));
+ }
+ let mut next = self.clone();
+ let mut found = Found { units: next.units.clone(), defs: Vec::new(), problem: None };
+ for p in next.params.iter_mut().filter(|p| p.model) {
+ let unit = p.unit.clone();
+ found.take(&mut p.expr, Reads::Unit(&unit));
+ }
+ for f in &mut next.features {
+ f.kind.walk_exprs_mut(&mut |(_, e, kind, role)| {
+ let reads = if role == ExprRole::Placement { Reads::Millimetres } else { Reads::Typed(kind) };
+ found.take_expr(e, reads);
+ });
+ if let FeatureKind::Sketch { sketch, .. } = &mut f.kind {
+ for p in &mut sketch.patterns {
+ if let Some(e) = p.count_expression.as_mut() {
+ found.take(e, Reads::Typed(Kind::Unitless));
+ }
+ for (key, e) in &mut p.expressions {
+ let kind = match key.as_str() {
+ "count" | "count2" => Kind::Unitless,
+ "angle" => Kind::Angle,
+ _ => Kind::Length,
+ };
+ found.take(e, Reads::Typed(kind));
+ }
+ }
+ for link in &mut sketch.links {
+ if let solidcraft_sketch::LinkSource::Text { exprs, .. } = &mut link.source {
+ for e in [&mut exprs.x, &mut exprs.y, &mut exprs.height].into_iter().flatten() {
+ found.take(e, Reads::Typed(Kind::Length));
+ }
+ if let Some(e) = exprs.angle.as_mut() {
+ found.take(e, Reads::Typed(Kind::Angle));
+ }
+ }
+ }
+ }
+ }
+ for e in next.assembly.exprs_mut() {
+ found.take(e, Reads::Inferred);
+ }
+ for r in &mut next.sheet.rules {
+ let kinds = r.fields().map(|(_, _, k)| k);
+ for ((_, e), k) in r.fields_mut().into_iter().zip(kinds) {
+ found.take(e, Reads::Typed(k));
+ }
+ }
+ for r in &mut next.plastic.rules {
+ let kinds = r.fields().map(|(_, _, k)| k);
+ for ((_, e), k) in r.fields_mut().into_iter().zip(kinds) {
+ found.take(e, Reads::Typed(k));
+ }
+ }
+ for c in &mut next.canvases {
+ c.plane.walk_exprs_mut(&mut |(_, e, kind, _)| found.take_expr(e, Reads::Typed(kind)));
+ }
+ if let Some(problem) = found.problem {
+ return Err(DocError::Invalid(problem));
+ }
+ if found.defs.is_empty() {
+ return Ok(Vec::new());
+ }
+ for d in &found.defs {
+ if let Some(problem) = Self::param_name_problem(&d.name) {
+ return Err(DocError::Invalid(problem));
+ }
+ if self.name_taken(&d.name) {
+ return Err(DocError::Invalid(format!(
+ "there is already a parameter `{}`: type `{}` to use it, or change it in Parameters",
+ d.name, d.name
+ )));
+ }
+ }
+ let mut out = Vec::with_capacity(found.defs.len());
+ for d in found.defs {
+ next.add_user_param(&d.name, &d.expression, d.unit.as_deref(), None)
+ .map_err(|e| DocError::Invalid(format!("`{} = {}`: {e}", d.name, d.expression)))?;
+ let unit = next.param(&d.name).map(|p| p.unit.clone()).unwrap_or_default();
+ out.push(Defined { name: d.name, expression: d.expression, unit });
+ }
+ *self = next;
+ Ok(out)
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 0139ba2245..ba108b9465 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -36,7 +36,9 @@ pub mod frame;
mod history_names;
pub mod hole_reference;
pub mod ids;
+mod inline_params;
pub use format_offsets::whole_profile_selection_from_value;
+pub use inline_params::Defined;
pub mod joints;
mod lineage;
pub mod metadata;
diff --git a/crates/doc/src/params.rs b/crates/doc/src/params.rs
index bad1ab7df1..6def887168 100644
--- a/crates/doc/src/params.rs
+++ b/crates/doc/src/params.rs
@@ -225,6 +225,12 @@ impl Document {
/// A typed length that is a bare number means the design's units: it gets that unit written
/// in (feature inputs are stored in mm otherwise). Anything else is returned unchanged.
pub fn with_design_unit(&self, e: &str, kind: Kind) -> String {
+ // A definition's value reads as the value would (#4071): `w = 2` is `w = 2 in`.
+ if let Some((name, rhs)) = expr::definition(e)
+ && expr::is_bare_number(rhs)
+ {
+ return format!("{name} = {}", self.with_design_unit(rhs, kind));
+ }
let u = self.units.trim();
let bare = expr::is_bare_number(e);
if kind == Kind::Length && bare && !u.is_empty() && u != "mm" && expr::unit_info(u).is_some_and(|(k, _)| k == Kind::Length) {
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rs
index e8b86a4e9c..d99d57d2fd 100644
--- a/crates/engine/src/cmd/parameters.rs
+++ b/crates/engine/src/cmd/parameters.rs
@@ -15,7 +15,8 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit; \
a text parameter's expression is its text, quotes round it optional: sketch texts' words are built from it), comment?, \
- favorite?: bool, new_name?: rename (references follow); or delete: name; or changes: {name: expression, …} (existing \
+ favorite?: bool, new_name?: rename (references follow; an expression `new = value` renames to `new` and sets value, \
+ or sets `new` when the expression is just `new`); or delete: name; or changes: {name: expression, …} (existing \
parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \
restored: features whose earlier result for the same inputs was reused (e.g. a value set back), switched?: [{feature, name, suppressed}] \
(the configuration rules that switch a feature's suppression and read a parameter whose value changed run in their order, as on \
@@ -87,6 +88,11 @@ pub(super) fn known(s: &Session, name: &str) -> bool {
s.doc.param(name).is_some() || s.doc.text_param(name).is_some() || s.doc.features.iter().any(|f| f.param_names.iter().any(|n| n == name))
}
+/// Whether `name` is (or, with this unit, becomes) a text parameter, whose expression is text.
+fn is_text(s: &Session, name: &str, unit: Option<&str>) -> bool {
+ s.doc.text_param(name).is_some() || unit.is_some_and(solidcraft_doc::text_params::is_text_unit)
+}
+
fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "parameters.change";
let solved = s.solved_sketches();
@@ -106,13 +112,41 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
name = new.trim().to_string();
}
let has_expr = p.get("expression").is_some() || p.get("value").is_some();
- let e = if has_expr {
+ let mut e = if has_expr {
Some(expr_arg(p, "expression").or_else(|| expr_arg(p, "value")).ok_or_else(|| bad(cmd, "`expression` must be a number or text"))?)
} else if out.get("renamed").is_some() || p.get("favorite").is_some() || p.get("comment").is_some() {
None
} else {
return Err(bad(cmd, "`expression` must be a number or text"));
};
+ // `name = expression` names the value being changed (#4071): the parameter (a dimension's
+ // `d7`, a feature input's) is renamed, references following, and takes the expression. A
+ // text parameter's text is only text.
+ if let Some((new, rhs)) = e.as_deref().filter(|_| !is_text(s, &name, str_(p, "unit"))).and_then(expr::definition) {
+ if out.get("renamed").is_some() {
+ return Err(bad(cmd, format!("`{new} = …` renames `{name}` already: give `new_name` or `name = expression`, not both")));
+ }
+ if rhs.is_empty() {
+ return Err(bad(cmd, format!("`{new} =` needs a value after the `=`")));
+ }
+ let (new, rhs) = (new.to_string(), rhs.to_string());
+ // A value that is just a parameter's name changes that parameter: a dimension made as
+ // `w = 20` shows `w`, and `w = 30` typed over it sets `w`.
+ let refers_to = s.doc.all_param_exprs().into_iter().find(|(n, _, _)| *n == name).map(|(_, e, _)| e);
+ if refers_to.as_deref().map(str::trim) == Some(new.as_str()) && s.doc.param(&new).is_some() {
+ out["changed_through"] = json!(name);
+ name = new.clone();
+ }
+ if new != name {
+ if known(s, &new) {
+ return Err(bad(cmd, format!("there is already a parameter `{new}`: type `{new}` to use it, or change it in Parameters")));
+ }
+ let n = s.doc_mut().rename_param(&name, &new)?;
+ out["renamed"] = json!({"from": name, "to": new, "references_updated": n});
+ name = new;
+ }
+ e = Some(rhs);
+ }
let (unit, comment) = (str_(p, "unit"), str_(p, "comment"));
let before = s.doc.param_values().0;
match &e {
@@ -220,6 +254,10 @@ fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -
let mut list = Vec::with_capacity(map.len());
for (name, e) in map {
let e = expr_arg(&json!({"e": e}), "e").ok_or_else(|| bad(cmd, format!("`changes.{name}` must be a number or text")))?;
+ // Renaming is one parameter at a time (#4071).
+ if let Some((new, _)) = expr::definition(&e).filter(|_| !is_text(s, name.trim(), None)) {
+ return Err(bad(cmd, format!("`changes.{name}`: `{new} = …` would rename `{name}`; change it on its own to rename it")));
+ }
list.push((name.trim().to_string(), e));
}
let before = s.doc.param_values().0;
@@ -435,7 +473,9 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
Some(k) => v.to_kind_in(k, defaults).map(|x| (x, k)),
None => v.kind().map(|k| (v.v, k)).ok_or_else(|| solidcraft_doc::DocError::Expr(format!("the result is {}", v.describe()))),
});
- Ok(match r {
+ // `name = expression` is worth its expression, and names what it would define (#4071).
+ let defines = expr::definition(&e).map(|(n, _)| n);
+ let mut out = match r {
Ok((v, k)) => {
let value = match k {
Kind::Length => expr::Value::length(v),
@@ -450,7 +490,11 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
json!({"ok": true, "value": v, "kind": k, "display_value": shown, "references": refs})
}
Err(err) => json!({"ok": false, "error": err.to_string().trim_start_matches("expression: ").to_string(), "references": refs}),
- })
+ };
+ if let Some(name) = defines {
+ out["defines"] = json!(name);
+ }
+ Ok(out)
}
fn complete(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/parameters_tests.rs b/crates/engine/src/cmd/parameters_tests.rs
index 2871b24241..e986ff584f 100644
--- a/crates/engine/src/cmd/parameters_tests.rs
+++ b/crates/engine/src/cmd/parameters_tests.rs
@@ -753,3 +753,160 @@ fn flipped_offset_sketch_plane_follows_its_parameter() {
run(&mut s, "parameters.change", json!({"name": "d", "expression": "50 mm"}));
assert!((volume(&mut s) - 400.0 * 50.0).abs() < 1e-6, "{}", volume(&mut s));
}
+
+/// A value typed as `name = expression` in any value input defines the user parameter `name`
+/// and leaves the input using it (#4071): a feature's distance, an angle, a count, a sheet metal
+/// rule and a canvas offset. The parameter takes the input's unit, the design's for a bare length.
+#[test]
+fn any_value_input_can_define_a_parameter() {
+ let mut s = Session::default();
+ block(&mut s);
+ let r = run(&mut s, "solid.extrude", json!({"sketch": "Base", "distance": "depth = 15", "operation": "new", "body_name": "Second"}));
+ assert_eq!(r["defined"], "depth", "{r}");
+ assert_eq!(r["definitions"], json!([{"name": "depth", "expression": "15", "unit": "mm"}]), "{r}");
+ let l = run(&mut s, "parameters.list", json!({}));
+ assert_eq!((row(&l, "depth")["source"].as_str(), row(&l, "depth")["expression"].as_str()), (Some("user"), Some("15")), "{l}");
+ // The input shows the name afterwards, and follows the parameter.
+ let input = l["parameters"].as_array().unwrap().iter().find(|r| r["feature"] == "Extrude2" && r["input"] == "Distance").unwrap().clone();
+ assert_eq!(input["expression"], "depth", "{input}");
+ assert!(rel(volume(&mut s), 40.0 * 30.0 * 10.0 + 40.0 * 30.0 * 15.0) < 1e-9);
+ run(&mut s, "parameters.change", json!({"name": "depth", "expression": "20 mm"}));
+ assert!(rel(volume(&mut s), 40.0 * 30.0 * 10.0 + 40.0 * 30.0 * 20.0) < 1e-9);
+ // One undo removes the feature and its parameter together.
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc.param("depth").is_none());
+ assert!(s.doc.features.iter().all(|f| f.name != "Extrude2"));
+ run(&mut s, "edit.redo", json!({}));
+ assert!(s.doc.param("depth").is_some());
+
+ // An angle input's parameter is in degrees; `#name` works as in a dimension.
+ let r = run(&mut s, "solid.extrude", json!({"sketch": "Base", "distance": 5, "taper": "#draft = 2", "operation": "new"}));
+ assert_eq!(r["definitions"][0], json!({"name": "draft", "expression": "2", "unit": "deg"}), "{r}");
+
+ // Sheet metal rules and a canvas offset take one too.
+ run(&mut s, "sheet.manage_rules", json!({"name": "Steel", "thickness": "gauge = 2", "active": true}));
+ assert_eq!((s.doc.sheet.rules[0].thickness.as_str(), s.doc.param("gauge").map(|p| p.expr.as_str())), ("gauge", Some("2")));
+ let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ png.extend([0, 0, 0, 4, 0, 0, 0, 2, 8, 6, 0, 0, 0, 0, 0, 0, 0]);
+ run(&mut s, "canvas.insert", json!({"data": solidcraft_doc::canvas::base64_encode(&png), "plane": "XY", "offset": "lift = 15"}));
+ match &s.doc.canvases[0].plane {
+ solidcraft_doc::PlaneRef::Offset { distance, .. } => assert_eq!(distance.as_ref(), "lift"),
+ other => panic!("{other:?}"),
+ }
+ assert_eq!(s.doc.param("lift").map(|p| (p.expr.as_str(), p.unit.as_str())), Some(("15", "mm")));
+}
+
+/// In an inch design a bare number defines a parameter in inches, as the bare value would read;
+/// a value with a unit keeps it.
+#[test]
+fn a_defined_length_takes_the_design_unit() {
+ let mut s = Session::default();
+ run(&mut s, "document.units", json!({"units": "in"}));
+ let r = run(&mut s, "solid.box", json!({"length": "l = 2", "width": "w = 25.4 mm", "height": 1}));
+ assert_eq!(
+ r["definitions"],
+ json!([{"name": "l", "expression": "2 in", "unit": "in"}, {"name": "w", "expression": "25.4 mm", "unit": "in"}]),
+ "{r}"
+ );
+ assert!(rel(volume(&mut s), 50.8 * 25.4 * 25.4) < 1e-9);
+}
+
+/// A definition that cannot be made fails the command and leaves the design as it was: a taken,
+/// reserved or malformed name, no value, a value that names itself, two different values for one
+/// name, and a parameter's or configuration cell's own expression.
+#[test]
+fn a_refused_definition_changes_nothing() {
+ let mut s = Session::default();
+ block(&mut s);
+ let undo = s.undo.len();
+ let features = s.doc.features.len();
+ let refused = [
+ (json!({"distance": "len = 5"}), "there is already a parameter `len`: type `len` to use it"),
+ (json!({"distance": "mm = 5"}), "`mm` is a unit name"),
+ (json!({"distance": "pi = 5"}), "`pi` is a constant"),
+ (json!({"distance": "w ="}), "`w =` needs a value after the `=`"),
+ (json!({"distance": "w = "}), "needs a value"),
+ (json!({"distance": "w = w + 1"}), "w"),
+ (json!({"distance": "w = = 3"}), "unexpected `=`"),
+ (json!({"distance": "= 5 ="}), ""),
+ (json!({"distance": "w = 5", "distance2": "w = 6"}), "`w` is defined twice"),
+ ];
+ for (p, message) in refused {
+ let mut q = json!({"sketch": "Base", "operation": "new"});
+ for (k, v) in p.as_object().unwrap() {
+ q[k] = v.clone();
+ }
+ let e = err(&mut s, "solid.extrude", q.clone());
+ assert!(e.contains(message), "{q}: {e}");
+ assert_eq!((s.undo.len(), s.doc.features.len()), (undo, features), "{q}: a refused definition changed the design");
+ assert!(s.doc.param("w").is_none(), "{q}");
+ }
+ // The same definition twice is one parameter.
+ let r = run(&mut s, "solid.extrude", json!({"sketch": "Base", "operation": "new", "distance": "w = 5", "distance2": "w = 5"}));
+ assert_eq!(r["definitions"].as_array().map(Vec::len), Some(1), "{r}");
+ run(&mut s, "edit.undo", json!({}));
+ // A parameter's own expression or a configuration cell defines nothing.
+ let e = err(&mut s, "parameters.add", json!({"name": "a", "expression": "b = 5"}));
+ assert!(e.contains("cannot define another parameter `b`"), "{e}");
+ assert!(s.doc.param("a").is_none() && s.doc.param("b").is_none());
+ let e = err(&mut s, "parameters.change", json!({"changes": {"len": "b = 5"}}));
+ assert!(e.contains("change it on its own to rename it"), "{e}");
+ // Text that only looks like a definition, where no value is read, is left alone.
+ let r = run(&mut s, "parameters.add", json!({"name": "label", "expression": "a = b", "unit": "text"}));
+ assert!(r.get("defined").is_none(), "{r}");
+}
+
+/// Changing a parameter to `name = expression` names it (#4071): the dimension's or feature
+/// input's own parameter is renamed, references follow, and it takes the expression; no other
+/// parameter is made. One undo takes both back.
+#[test]
+fn changing_a_parameter_to_a_definition_renames_it() {
+ let mut s = Session::default();
+ block(&mut s);
+ let l = run(&mut s, "parameters.list", json!({"filter": "feature"}));
+ let d = l["parameters"].as_array().unwrap().iter().find(|r| r["input"] == "Distance").unwrap()["name"].as_str().unwrap().to_string();
+ let count = run(&mut s, "parameters.list", json!({}))["count"].clone();
+ let r = run(&mut s, "parameters.change", json!({"name": d, "expression": "height = 12"}));
+ assert_eq!((r["name"].as_str(), r["renamed"]["from"].as_str()), (Some("height"), Some(d.as_str())), "{r}");
+ assert_eq!(expr_of(&mut s, "height"), "12");
+ assert!(rel(volume(&mut s), 40.0 * 30.0 * 12.0) < 1e-9);
+ assert_eq!(run(&mut s, "parameters.list", json!({}))["count"], count, "no extra parameter");
+ // A dimension's parameter too; whatever refers to it follows.
+ let width =
+ s.doc.sketch(s.doc.features[0].id).unwrap().constraints.iter().find_map(|c| c.param.clone().filter(|p| expr_of_now(&s, p) == "40")).unwrap();
+ run(&mut s, "solid.box", json!({"length": width.clone(), "width": 5, "height": 5, "corner": [100, 0, 0]}));
+ run(&mut s, "parameters.change", json!({"name": width, "expression": "wide = 50"}));
+ assert_eq!(expr_of(&mut s, "wide"), "50");
+ assert!(rel(volume(&mut s), 50.0 * 30.0 * 12.0 + 50.0 * 25.0) < 1e-9);
+ run(&mut s, "edit.undo", json!({}));
+ assert!(s.doc.param("wide").is_none());
+ assert_eq!(expr_of_now(&s, &width), "40");
+ // Its own name is just a change; a taken name is refused.
+ run(&mut s, "parameters.change", json!({"name": "height", "expression": "height = 14"}));
+ assert_eq!(expr_of(&mut s, "height"), "14");
+ let e = err(&mut s, "parameters.change", json!({"name": "height", "expression": "len = 3"}));
+ assert!(e.contains("there is already a parameter `len`"), "{e}");
+ let e = err(&mut s, "parameters.change", json!({"name": "height", "new_name": "h", "expression": "x = 3"}));
+ assert!(e.contains("not both"), "{e}");
+}
+
+fn expr_of_now(s: &Session, name: &str) -> String {
+ s.doc.param(name).map(|p| p.expr.clone()).unwrap_or_default()
+}
+
+/// A dimension made as `w = 20` shows `w`; typing `w = 30` over it sets `w` rather than being
+/// refused as a taken name (#4071).
+#[test]
+fn a_definition_of_the_parameter_a_value_names_changes_it() {
+ let mut s = Session::default();
+ block(&mut s);
+ run(&mut s, "solid.box", json!({"length": "w = 20", "width": 5, "height": 5, "corner": [100, 0, 0]}));
+ let l = run(&mut s, "parameters.list", json!({"filter": "feature"}));
+ let d = l["parameters"].as_array().unwrap().iter().find(|r| r["expression"] == "w").unwrap()["name"].as_str().unwrap().to_string();
+ let r = run(&mut s, "parameters.change", json!({"name": d, "expression": "w = 30"}));
+ assert_eq!((r["name"].as_str(), r["changed_through"].as_str()), (Some("w"), Some(d.as_str())), "{r}");
+ assert_eq!((expr_of(&mut s, "w"), expr_of(&mut s, &d)), ("30".to_string(), "w".to_string()));
+ let r = run(&mut s, "expr.evaluate", json!({"expression": "q = w * 2", "kind": "length"}));
+ assert_eq!((r["ok"].as_bool(), r["value"].as_f64(), r["defines"].as_str()), (Some(true), Some(60.0), Some("q")), "{r}");
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index dbee11f2ac..ba02014e71 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1199,6 +1199,12 @@ impl Session {
Err(EngineError::Internal(spec.id.to_string(), msg))
}
};
+ // A value typed as `name = expression` defines the user parameter `name` (#4071), in the
+ // same undo step; a refused definition fails the command, which leaves the design as it was.
+ let r = match r {
+ Ok((v, live_edit)) if params::has_definition(params) => self.define_inline(spec.id, v).map(|v| (v, live_edit)),
+ r => r,
+ };
// A parameter error that did not name the command names it here: the engine knows which
// command ran, and the reader of the parameters may not (#6651).
let r = match r {
@@ -1286,6 +1292,20 @@ impl Session {
result
}
+ /// Store the definitions a command left in the design (`Document::define_inline`): its
+ /// result names them, `defined` the first (as `sketch.dimension` does) and `definitions` all.
+ fn define_inline(&mut self, id: &str, mut v: Value) -> Result<Value> {
+ let mut doc = (*self.doc).clone();
+ let defined = doc.define_inline().map_err(|e| EngineError::BadParams { cmd: id.to_string(), msg: e.to_string() })?;
+ let Some(first) = defined.first() else { return Ok(v) };
+ if let Some(out) = v.as_object_mut() {
+ out.insert("defined".into(), serde_json::json!(first.name));
+ out.insert("definitions".into(), serde_json::json!(defined));
+ }
+ self.doc = Arc::new(doc);
+ Ok(v)
+ }
+
/// A sketch command's result gets `created`: the ids of the points, curves, constraints and
/// dimensions it added to its sketch (the `sketch` param, else the active sketch), so every
/// drawing and modify command reports them the same way (see `cmd::sketch_created`). A command
diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs
index 443076a3e1..10e6343a15 100644
--- a/crates/engine/src/params.rs
+++ b/crates/engine/src/params.rs
@@ -180,6 +180,25 @@ pub fn string_list_or_default(p: &Value, k: &str) -> Vec<String> {
}
}
+/// Whether any text in `p` is shaped like a definition, `name = expression` (#4071), so the
+/// design may hold one to store once the command has run (`Document::define_inline`). Looks at
+/// most a bounded number of values deep into hostile input.
+pub fn has_definition(p: &Value) -> bool {
+ fn walk(v: &Value, budget: &mut usize) -> bool {
+ if *budget == 0 {
+ return false;
+ }
+ *budget -= 1;
+ match v {
+ Value::String(s) => s.len() <= 4096 && s.contains('=') && solidcraft_doc::expr::definition(s).is_some(),
+ Value::Array(a) => a.iter().any(|x| walk(x, budget)),
+ Value::Object(o) => o.values().any(|x| walk(x, budget)),
+ _ => false,
+ }
+ }
+ walk(p, &mut 100_000)
+}
+
#[cfg(test)]
mod tests {
use serde_json::json;
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 16b55cfdc8..a3c374c8cd 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -709,6 +709,10 @@ pub(crate) fn hostile_values() -> Vec<Value> {
json!("mm = 5"),
json!("w = w"),
json!("w == 1/0"),
+ // Every value input reads `name = expression` (#4071).
+ json!("a = = 3"),
+ json!("é = 1e308 * 10"),
+ json!(format!("{} = 1", "n".repeat(5000))),
json!([]),
json!([1e308, -1e308]),
json!([0, 0, 0]),
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 812816f2ab..0a0c53f8dd 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -4632,6 +4632,8 @@ fn box_corner(s: &Session, fields: &[(&'static str, String)], p: Vec3, normal: O
};
// A plain length ("20 mm", "2 in"; a bare number has the design's unit by now) gives a
// plain number (mm).
+ // A size typed as `l = 20` is placed by its value: `l` exists only once the box does.
+ let size = solidcraft_engine::doc::expr::definition(&size).map_or(size.clone(), |(_, rhs)| rhs.to_string());
let plain = solidcraft_engine::doc::expr::is_literal(&size)
.then(|| solidcraft_engine::doc::Document::eval_in(&Default::default(), &size, ValueKind::Length).ok())
.flatten();
diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs
index 2825ea7502..8e062ec3f0 100644
--- a/crates/ui-egui/src/dialogs_all_tests.rs
+++ b/crates/ui-egui/src/dialogs_all_tests.rs
@@ -943,6 +943,33 @@ fn viewport_profile_click_returns_extrude_value_focus() {
assert!((bounds.max.z - bounds.min.z - 30.0).abs() < 1e-7);
}
+/// Typing `depth = 30` in the extrude dialog's distance defines the user parameter `depth` and
+/// the extrude uses it, in the dialog's one undo step; the preview made nothing (#4071).
+#[test]
+fn a_dialog_field_typed_as_a_definition_defines_the_parameter() {
+ let mut h = extrude_focus_fixture();
+ let undo = h.app.session.undo.len();
+ // As above: the first click returns focus to the distance, the second picks the profile.
+ h.step(&json!({"click":{"world":[15,10,0]}})).unwrap();
+ h.step(&json!({"text":"30"})).unwrap();
+ h.step(&json!({"click":{"world":[15,10,0]}})).unwrap();
+ h.step(&json!({"text":"depth = 30"})).unwrap();
+ assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Extrude { distance, .. } if distance == "depth = 30"));
+ h.settle();
+ assert!(h.app.session.doc.param("depth").is_none(), "the preview defined nothing");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ assert!(h.app.dialog.is_none(), "{:?} {:?}", h.app.status, h.app.dialog.as_ref().map(|d| (d.error.clone(), format!("{:?}", d.kind))));
+ let doc = &h.app.session.doc;
+ let depth = doc.param("depth").expect("the user parameter was added");
+ assert!(!depth.model && depth.expr == "30" && depth.unit == "mm", "{depth:?}");
+ let extrude = doc.features.iter().rev().find(|f| f.name.starts_with("Extrude")).unwrap();
+ assert!(extrude.kind.inputs().iter().any(|(label, e, _)| *label == "Distance" && e == "depth"), "{:?}", extrude.kind.inputs());
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ let bounds = h.app.session.world_state().bodies.first().unwrap().mesh().bounds();
+ assert!((bounds.max.z - bounds.min.z - 30.0).abs() < 1e-7);
+}
+
#[test]
fn viewport_empty_click_falls_back_to_first_numeric_dialog_field() {
let mut h = extrude_focus_fixture();
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index b5084274ed..1f7cf530ef 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -951,9 +951,12 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
}
Ok(reply) => {
clear_picks(app);
- match reply.get("defined").and_then(serde_json::Value::as_str) {
- Some(name) => app.set_status(format!("Dimension applied; parameter `{name}` defined"), false),
- None => app.set_status("Dimension applied", false),
+ // A new dimension defines its parameter; an edited one renames its own (#4071).
+ let named = reply.get("renamed").and_then(|r| r.get("to")).and_then(serde_json::Value::as_str);
+ match (reply.get("defined").and_then(serde_json::Value::as_str), named) {
+ (Some(name), _) => app.set_status(format!("Dimension applied; parameter `{name}` defined"), false),
+ (None, Some(name)) => app.set_status(format!("Dimension applied; parameter named `{name}`"), false),
+ (None, None) => app.set_status("Dimension applied", false),
}
}
}
diff --git a/crates/ui-egui/src/dimension_create_ui_tests.rs b/crates/ui-egui/src/dimension_create_ui_tests.rs
index 1c5b15091a..fa7bf3dfba 100644
--- a/crates/ui-egui/src/dimension_create_ui_tests.rs
+++ b/crates/ui-egui/src/dimension_create_ui_tests.rs
@@ -1271,3 +1271,29 @@ fn a_shown_dimension_that_breaks_a_later_feature_reports_it_and_undoes() {
assert_eq!(h.app.session.doc.to_json(), before);
assert!(!failed(&h), "undo brings the fillet back");
}
+
+/// Editing an existing dimension to `name = value` names its own parameter (#4071): `d1`
+/// becomes `width`, set to the value, in one undo step, and opening it again shows `width`'s
+/// value as its expression. No other parameter is made.
+#[test]
+fn editing_a_dimension_to_a_definition_names_its_parameter() {
+ let mut h = line([25., 0.]);
+ place(&mut h, &[[12.5, 0.]], [12.5, 8.]);
+ type_value(&mut h, "25");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.settle();
+ let params = h.app.session.doc.params.len();
+ let undo = h.app.session.undo.len();
+ crate::dim_view::edit_param(&h.app, "d1");
+ h.settle();
+ type_value(&mut h, "width = 30");
+ h.step(&json!({"key":"Enter"})).unwrap();
+ let doc = &h.app.session.doc;
+ assert!(doc.param("d1").is_none(), "{:?}", h.app.status);
+ assert_eq!(doc.param("width").map(|p| p.expr.as_str()), Some("30"));
+ assert_eq!(doc.params.len(), params, "renamed, not added");
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ assert!(h.app.status.as_ref().is_some_and(|s| !s.2 && s.0.contains("`width`")), "{:?}", h.app.status);
+ let sk = doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
+ assert!(sk.constraints.iter().any(|c| c.param.as_deref() == Some("width") && c.kind.value().is_some_and(|v| (v - 30.0).abs() < 1e-6)));
+}
diff --git a/crates/ui-egui/src/length_input.rs b/crates/ui-egui/src/length_input.rs
index 6b9c9175c9..1fbd7e019a 100644
--- a/crates/ui-egui/src/length_input.rs
+++ b/crates/ui-egui/src/length_input.rs
@@ -32,6 +32,12 @@ pub(crate) fn defaults(doc: &Document, mut kind: crate::dialogs::Kind) -> crate:
/// Keep named and dimensional expressions intact so they remain driving expressions.
pub(crate) fn expression(doc: &Document, text: &str, kind: Kind) -> String {
let text = text.trim();
+ // A definition's value is frozen the same way; the name stays (#4071).
+ if let Some((name, rhs)) = solidcraft_engine::doc::expr::definition(text)
+ && !rhs.is_empty()
+ {
+ return format!("{name} = {}", expression(doc, rhs, kind));
+ }
let normalized = doc.with_design_unit(text, kind);
if kind == Kind::Length && unit(doc) != "mm" && normalized == text && doc.eval(text, Kind::Unitless).is_ok() {
// A decimal comma is numeric only outside parentheses. Preserve function-argument
@@ -58,6 +64,15 @@ pub(crate) fn expression(doc: &Document, text: &str, kind: Kind) -> String {
}
}
+/// For a field whose command takes only a number, which keeps no expression to name: a typed
+/// `name = value` is refused with the way to name it, rather than defining nothing (#4071).
+pub(crate) fn no_definition(text: &str, label: &str) -> Result<(), String> {
+ match solidcraft_engine::doc::expr::definition(text) {
+ Some((name, _)) => Err(format!("{label} keeps no expression, so it cannot define `{name}`: add `{name}` in Parameters, then type `{name}`")),
+ None => Ok(()),
+ }
+}
+
pub(crate) fn eval(doc: &Document, text: &str, kind: Kind) -> solidcraft_engine::doc::Result<f64> {
doc.eval(&expression(doc, text, kind), kind)
}
diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs
index 0b4d281df3..230a63cfea 100644
--- a/crates/ui-egui/src/sketch_modify_ui.rs
+++ b/crates/ui-egui/src/sketch_modify_ui.rs
@@ -612,6 +612,7 @@ fn curve_ids(inputs: &[SelInput], i: usize) -> Vec<String> {
/// parameters, in the range the command accepts. Checking the range here lets the window say
/// so in its own error line instead of the status bar.
pub(crate) fn factor(app: &SolveApp, text: &str) -> Result<f64, String> {
+ crate::length_input::no_definition(text, "Factor")?;
let v = app.session.doc.eval(text.trim(), ValueKind::Unitless).map_err(|e| format!("Factor: {e}"))?;
if !(v.is_finite() && v > 1e-9 && v < 1e6) {
return Err("Factor must be a positive number".into());
@@ -627,6 +628,7 @@ pub(crate) fn value(app: &SolveApp, text: &str, kind: ValueKind, label: &str) ->
if text.is_empty() {
return Ok(0.0);
}
+ crate::length_input::no_definition(text, label)?;
let doc = &app.session.doc;
let v = crate::length_input::eval(doc, text, kind).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() {
@@ -689,6 +691,7 @@ fn corner_ids(app: &SolveApp, inputs: &[SelInput], i: usize) -> Vec<String> {
/// of a field, where an empty row means zero and a negative distance is a direction; neither is
/// a radius or a chamfer leg, so this one is its own.
fn corner_size(app: &SolveApp, label: &str, text: &str, kind: ValueKind) -> Result<f64, String> {
+ crate::length_input::no_definition(text, label)?;
let doc = &app.session.doc;
let v = crate::length_input::eval(doc, text.trim(), kind).map_err(|e| format!("{label}: {e}"))?;
if !v.is_finite() || v <= 1e-9 {
@@ -776,7 +779,12 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<String
}
if *mode == TWO_SIDES {
let d2 = signed_length(app, "Distance 2", distance2, false)?;
- m.insert("distance2".into(), json!(if d2 > 0.0 { distance2.trim().to_string() } else { format!("-({})", distance2.trim()) }));
+ // The other way is the value negated; a definition keeps its name (#4071).
+ let negated = match solidcraft_engine::doc::expr::definition(distance2) {
+ Some((name, rhs)) => format!("{name} = -({rhs})"),
+ None => format!("-({})", distance2.trim()),
+ };
+ m.insert("distance2".into(), json!(if d2 > 0.0 { distance2.trim().to_string() } else { negated }));
}
}
("sketch.offset", params)
diff --git a/crates/ui-egui/src/sketch_text.rs b/crates/ui-egui/src/sketch_text.rs
index 40f459fa7a..6cf025a5a5 100644
--- a/crates/ui-egui/src/sketch_text.rs
+++ b/crates/ui-egui/src/sketch_text.rs
@@ -385,6 +385,17 @@ pub(crate) fn preview(app: &mut SolveApp, k: &mut Tx) -> Option<Result<(), Strin
}
let mut live = params;
live["live"] = json!(true);
+ // The live edit runs on the design itself: a typed definition is made once, by OK, and the
+ // preview shows its value (#4071).
+ let at = live.get_mut("at").and_then(Value::as_array_mut).map(|a| a.iter_mut().collect::<Vec<_>>()).unwrap_or_default();
+ for v in at {
+ value_of_definition(v);
+ }
+ for key in ["height", "angle"] {
+ if let Some(v) = live.get_mut(key) {
+ value_of_definition(v);
+ }
+ }
Some(
folded(app, k, |app| app.session.execute("sketch.edit_text", &live))
.map(|_| {
@@ -394,6 +405,13 @@ pub(crate) fn preview(app: &mut SolveApp, k: &mut Tx) -> Option<Result<(), Strin
)
}
+/// A field typed as `name = value`, as just its value.
+fn value_of_definition(v: &mut Value) {
+ if let Some((_, rhs)) = v.as_str().and_then(solidcraft_engine::doc::expr::definition) {
+ *v = json!(rhs);
+ }
+}
+
/// OK: the fields' final edit (which also brings the features after the sketch up to date), in
/// the dialog's one undo step.
pub(crate) fn apply(app: &mut SolveApp, k: &mut Tx) -> Result<(), String> {
@@ -643,7 +661,9 @@ fn edit_params(app: &SolveApp, k: &Tx) -> Result<Value, String> {
}
v
};
- let names_parameters = i < ANGLE_END && !solidcraft_engine::doc::expr::references(value).is_empty();
+ // A field that names parameters, or names its value (`h = 10`, #4071), goes as typed.
+ let names_parameters = i < ANGLE_END
+ && (!solidcraft_engine::doc::expr::references(value).is_empty() || solidcraft_engine::doc::expr::definition(value).is_some());
sent[i] = match given {
Some(e) => json!(e),
None if value != initial && names_parameters => json!(value.trim()),
diff --git a/docs/book/src/guide/parameters.md b/docs/book/src/guide/parameters.md
index 75aa289d78..4a4b375a6f 100644
--- a/docs/book/src/guide/parameters.md
+++ b/docs/book/src/guide/parameters.md
@@ -10,13 +10,32 @@ name (`d1`, `d2`, …). Click another driving dimension to use its name: when th
just a number (such as `10` or `10 mm`) the name replaces it; otherwise it goes in at the
cursor, replacing selected text and keeping what you typed, so typing `10 + ` and clicking
`d1` gives `10 + d1`. Add arithmetic such as `/ 2` to build a dependent dimension. Press **Enter** to apply
-the expression or **Escape** to cancel the edit. When placing a new dimension, `width = 40` (or `#width = 40`) adds
-the user parameter `width` with that value (a bare number is in the design's units) and
-dimensions with it; a name that is already taken is refused. The value boxes shown while drawing
-a shape (a line's length, a rectangle's width and height, a circle's diameter) take the same
-form: the shape is drawn at that size, and its dimension uses the new parameter.
+the expression or **Escape** to cancel the edit.
Add and edit user parameters through the existing **Change Parameters** command.
+## Naming a value as you type it
+
+Any value input can name its value: type `width = 40` (or `#width = 40`) for a dimension, a
+value box while drawing a shape (a line's length, a rectangle's width and height, a circle's
+diameter: the shape is drawn at that size and its dimension uses the parameter), an extrude
+distance, a fillet radius, a hole diameter, a sheet metal rule, a joint's offset and so on.
+SolidCraft adds the user parameter `width` with the expression `40`, and the input uses
+`width` from then on, so editing it again shows `width`. A bare number reads as it would in that
+input (the design's units for a length, degrees for an angle), and the parameter keeps that
+unit. The right-hand side can be any expression, such as `width = depth * 2`. The command and
+its parameter are one undo step.
+
+Editing a value that already has its own parameter (a dimension's `d7`, a feature input's) with
+`height = 12` renames that parameter to `height`, references following, and sets it to 12; no
+other parameter is made. When the value is just a parameter's name (`width`), `width = 50` sets
+that parameter instead. A name that is already taken, a unit, function or constant name, or a
+value that refers to itself is refused with the reason, and nothing changes. A parameter's own
+expression and a configuration cell can't define another parameter.
+
+Scripts, the control channel and MCP tools take the same form in any expression parameter
+(`"distance": "depth = 15"`); the result names what it made in `defined` (the first name) and
+`definitions` (`[{name, expression, unit}]`).
+
In the MANAGE tab's PARAMETERS section, click **Parameters** to open the user and model
parameter editor. The **Configurations** button in CONFIGURATIONS opens the configuration table;
**Configure** remains in the dropdown for configuring columns.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 9e8ca29401..3b3f3c7a29 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -256,6 +256,13 @@ read in the design's units, exactly as if it were typed into the dimension box:
unit regardless of the design, pass an expression with one: `"value": "50 mm"` or
`"value": "0.5 in"`. Angles are degrees unless the expression says otherwise.
+Any expression parameter of any command can also define a user parameter as it sets the value:
+`"distance": "depth = 15"` adds `depth` (15, read as the bare value would be) and stores `depth`
+in the input, in the same undo step. The reply names it in `defined` and lists every definition
+in `definitions: [{name, expression, unit}]`; a taken or reserved name fails the command and
+changes nothing. `parameters.change` with `"expression": "height = 12"` renames the parameter it
+changes instead (see the parameters guide).
+
The viewport also shows an X/Y/Z-aligned dimension chain between the endpoints of the
currently shown distance (centre, minimum or maximum), with each world-axis distance
labelled separately as an absolute value (including zero).
diff --git a/docs/mcp.md b/docs/mcp.md
index f61470d317..1df3da7dd7 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -281,7 +281,7 @@ The `skill_reference` tool returns these documents from the copies built into So
| `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). |
| `measure` | `body?` or `items?` | Area (mm²), bbox, topology counts and `closed` per body. Volume (mm³), volume centre of mass, density and mass are reported only for closed, consistently oriented bodies (null or omitted for open surfaces). Volume/mass totals skip open bodies; `total.open_bodies_skipped` gives their count. Area and topology totals include all bodies. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. |
| `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). |
-| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. |
+| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. An expression `new_name = expression` renames the parameter as it sets it; in any other tool's expression parameter it adds the user parameter `new_name` and the input uses it (`defined`, `definitions` in the reply). |
| `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. |
| `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). |
| `undo`, `redo` | — | Undo / redo one change. |