parameters.add: a parameter with no unit takes the design's units (#8865) (#8880)

* claim: #8865

* parameters.add: a parameter with no unit takes the design's units (#8865)

A new parameter given no unit took "mm" for any length or bare number, so
in an inch design `parameters.add {name: v, expression: "40/2"}` made a
20 mm parameter where the Parameters dialog makes 20 in. The unit a new
parameter infers is now a length in the design's units (mm designs are
unchanged); parameters.change on a new name and parameters.import share
the same inference. Angles and unit-less values keep their units.

A definition typed into a value of no fixed kind (a coupling's pitch,
a joint's value) still reads its bare number as millimetres, as that
field does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HiroKenEz
2026-10-29 18:18:04 +00:00
committed by GitHub
parent 9416e975e0
commit c857f2fe70
7 changed files with 96 additions and 10 deletions
+1 -1
View File
@@ -3705,7 +3705,7 @@ impl Document {
}
/// Add or change a parameter. Fails if the result would not evaluate. A new parameter
/// without a unit takes the unit of its value (mm, deg or none).
/// without a unit takes the unit of its value (a length in the design's units, deg or none).
pub fn set_param(&mut self, name: &str, expr_s: &str, unit: Option<&str>, comment: Option<&str>) -> Result<()> {
// A text parameter: one with the text unit, or an existing one when no unit is given.
match (unit.map(crate::text_params::is_text_unit), self.text_param(name).is_some()) {
+5 -1
View File
@@ -191,7 +191,11 @@ impl Document {
}
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)
// A value of no fixed kind (a joint's) is evaluated without the design's units, so
// its bare number stays a millimetre length whatever they are (#8865): `w = 5` is
// what `5` is there.
let unit = d.unit.unwrap_or_else(|| Self::infer_unit_in(&next.param_values().0, &d.expression, "mm"));
next.add_user_param(&d.name, &d.expression, Some(&unit), 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 });
+7 -6
View File
@@ -585,7 +585,7 @@ impl Document {
}
let unit = match unit {
Some(u) => u.trim().to_string(),
None => Self::infer_unit_in(vals, expr_s),
None => Self::infer_unit_in(vals, expr_s, &self.units),
};
self.params.push(crate::Param {
name: name.into(),
@@ -696,18 +696,19 @@ impl Document {
}
/// The unit for a new parameter with this expression: that of its value; a bare number is
/// a length (mm).
/// a length in the design's units, as a typed length reads it (#8865).
pub(crate) fn infer_unit(&self, e: &str) -> String {
Self::infer_unit_in(&self.param_values().0, e)
Self::infer_unit_in(&self.param_values().0, e, &self.units)
}
/// [`Document::infer_unit`] against parameter values already worked out.
fn infer_unit_in(vals: &BTreeMap<String, Value>, e: &str) -> String {
/// [`Document::infer_unit`] against parameter values already worked out, a length taking
/// `units` (the design's, or `mm` where a bare number reads as millimetres).
pub(crate) fn infer_unit_in(vals: &BTreeMap<String, Value>, e: &str, units: &str) -> String {
let v = expr::eval_with(e, &|n| vals.get(n).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{n}`"))));
match v.ok().and_then(|v| v.kind()) {
Some(Kind::Unitless) if !expr::references(e).is_empty() => String::new(),
Some(Kind::Angle) => "deg".into(),
_ => "mm".into(),
_ => expr::length_unit_or_mm(units).to_string(),
}
}
@@ -188,6 +188,22 @@ fn a_screw_advances_its_pitch_per_turn() {
assert!(close_to(shown(&mut s, "Lift"), 10.0), "{}", shown(&mut s, "Lift"));
}
/// A coupling's length reads a bare number as millimetres in any design, so a parameter defined
/// in it (`lead = 1.5`) keeps that millimetre, while `parameters.add` without a unit takes the
/// design's units (#8865): the screw advances 1.5 mm a turn in an inch design too.
#[test]
fn a_pitch_defined_in_an_inch_design_reads_as_the_screw_does() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
base(&mut s);
part(&mut s, "Nut", [-1.0, -1.0, 0.0]);
pin(&mut s, "cylindrical", "Thread", "Base", "Nut", Vec3::ZERO, Vec3::Z);
run(&mut s, "joint.screw", json!({"joint": "Thread", "pitch": "lead = 1.5"}));
assert_eq!(s.doc.param("lead").map(|p| (p.expr.as_str(), p.unit.as_str())), Some(("1.5", "mm")));
let r = run(&mut s, "joint.drive", json!({"joint": "Thread", "values": [720]}));
assert!(close_to(r["values"][1]["value"].as_f64().unwrap_or(f64::NAN), 3.0), "{r}");
}
/// A motor gear turns the four-bar's crank: half as fast, the other way round, and the loop
/// follows.
#[test]
+1 -1
View File
@@ -13,7 +13,7 @@ use crate::{EngineError, Result, Session};
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; \
"name, expression (number or text), unit?: mm|cm|m|in|ft|deg|rad|\"\"|text (new parameters default to their value's unit, a length the design's units; \
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; 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 \
+63
View File
@@ -812,6 +812,69 @@ fn a_defined_length_takes_the_design_unit() {
assert!(rel(volume(&mut s), 50.8 * 25.4 * 25.4) < 1e-9);
}
/// A parameter added without a unit takes the unit of its value, a length in the design's units
/// as a typed length would be (#8865): `40/2` in an inch design is 20 in, as the Parameters
/// dialog makes it. A unit given, an angle and a unit-less value keep their own.
#[test]
fn a_parameter_added_without_a_unit_takes_the_design_unit() {
let added = |s: &mut Session, p: Value| {
let r = run(s, "parameters.add", p);
(r["unit"].as_str().unwrap_or("?").to_string(), r["value"].as_f64().unwrap_or(f64::NAN), r["display_value"].as_f64().unwrap_or(f64::NAN))
};
let close = |got: (String, f64, f64), unit: &str, mm: f64, shown: f64| {
assert!(got.0 == unit && rel(got.1, mm) < 1e-9 && rel(got.2, shown) < 1e-9, "{got:?}, expected {unit} {mm} mm ({shown})");
};
// A millimetre design is as it was.
let mut s = Session::default();
close(added(&mut s, json!({"name": "v", "expression": "40/2"})), "mm", 20.0, 20.0);
close(added(&mut s, json!({"name": "w", "expression": "v + 1"})), "mm", 21.0, 21.0);
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
close(added(&mut s, json!({"name": "v", "expression": "40/2"})), "in", 508.0, 20.0);
close(added(&mut s, json!({"name": "given", "expression": "40/2", "unit": "in"})), "in", 508.0, 20.0);
close(added(&mut s, json!({"name": "metric", "expression": "40/2", "unit": "mm"})), "mm", 20.0, 20.0);
// A value with a unit keeps its size and shows in the design's units.
close(added(&mut s, json!({"name": "plate", "expression": "25.4 mm"})), "in", 25.4, 1.0);
// One that refers to another parameter: its bare number is an inch too.
close(added(&mut s, json!({"name": "more", "expression": "v + 1"})), "in", 533.4, 21.0);
close(added(&mut s, json!({"name": "half", "expression": "v / 2"})), "in", 254.0, 10.0);
// An angle stays in degrees, a unit-less count stays unit-less.
close(added(&mut s, json!({"name": "turn", "expression": "30 deg"})), "deg", 30f64.to_radians(), 30.0);
close(added(&mut s, json!({"name": "n", "expression": "4", "unit": ""})), "", 4.0, 4.0);
close(added(&mut s, json!({"name": "twice", "expression": "n * 2"})), "", 8.0, 8.0);
// parameters.change and parameters.import make a new parameter the same way.
run(&mut s, "parameters.change", json!({"name": "c", "expression": "3"}));
assert_eq!(s.doc.param("c").map(|p| p.unit.as_str()), Some("in"));
run(&mut s, "parameters.import", json!({"text": "name,expression\nimported,2\n"}));
assert_eq!(s.doc.param("imported").map(|p| p.unit.as_str()), Some("in"));
let (vals, _) = s.doc.param_values();
assert!(vals.get("imported").is_some_and(|v| rel(v.v, 50.8) < 1e-9), "{:?}", vals.get("imported"));
// An existing parameter changed without a unit keeps its own.
run(&mut s, "parameters.change", json!({"name": "metric", "expression": "30"}));
assert_eq!(s.doc.param("metric").map(|p| p.unit.as_str()), Some("mm"));
// A centimetre design works the same way.
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "cm"}));
close(added(&mut s, json!({"name": "v", "expression": "3"})), "cm", 30.0, 3.0);
}
/// Hostile parameters.add input in an inch design is refused with a reason and adds nothing.
#[test]
fn a_hostile_parameter_in_an_inch_design_is_refused() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
// 1e308 inches is past any finite millimetre value.
for (name, e) in [("huge", "1e308"), ("inf", "1e308 * 1e308"), ("nan", "0/0"), ("bad", "2 furlong"), ("empty", " "), ("self_ref", "self_ref + 1")]
{
let why = err(&mut s, "parameters.add", json!({"name": name, "expression": e}));
assert!(!why.is_empty() && s.doc.param(name).is_none(), "{name}: {why}");
}
let why = err(&mut s, "parameters.add", json!({"name": "u", "expression": "1", "unit": "furlong"}));
assert!(why.contains("unknown unit"), "{why}");
assert!(s.doc.params.is_empty());
}
/// 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.
+3 -1
View File
@@ -75,7 +75,9 @@ in use can't be deleted (the error lists its users).
The design's units (Document Settings in the browser: mm, cm, m, in or ft) set how a bare number
or unitless arithmetic expression typed into a length field is read. In an inch design `0.25`
and `1 / 4` mean 0.25 in. Operation dialogs start with lengths in the design's units, including
and `1 / 4` mean 0.25 in. A new user parameter given no unit (`parameters.add` or
`parameters.import` without `unit`) is a length in the design's units, as the Parameters dialog
makes it: `40/2` is 20 in. Operation dialogs start with lengths in the design's units, including
secondary distances, wall thicknesses, gaps, offsets and radii. Canvas handles and live sketch
values use the same units as the operation. Angles, counts and scale factors keep their own
units. Preferences selects the default units for new designs; existing designs use their own