Skip to content

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

Params: a list parameter refuses a wrong type instead of losing entries (#6651) (#6683)

Homero Thompsonf103468dba20
diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs
index 902005f536..4f107813ec 100644
--- a/crates/engine/src/cmd/clearance.rs
+++ b/crates/engine/src/cmd/clearance.rs
@@ -96,7 +96,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
// Mesh bodies are not measured. A mesh body named in `bodies` or `against` is left out of the
// pairs and listed as unchecked, rather than refused as "no solid body".
let named = |key: &str| -> Result<Vec<usize>> {
- let names = string_list(p, key);
+ let names = string_list(cmd, p, key)?;
let mut out = Vec::new();
for n in &names {
let Some(i) = solid.iter().position(|b| &b.name == n) else {
@@ -259,7 +259,10 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
let (mut overlaps, mut near) = (Vec::new(), Vec::new());
// The mesh bodies the call was about (every one without `bodies`, else those named in
// `bodies` or `against`) come first, so "nothing found" is not read as "no overlap".
- let asked: Vec<String> = ["bodies", "against"].iter().flat_map(|k| string_list(p, k)).collect();
+ let mut asked: Vec<String> = Vec::new();
+ for k in ["bodies", "against"] {
+ asked.extend(string_list(cmd, p, k)?);
+ }
let mut unchecked: Vec<Value> = mesh_bodies
.iter()
.filter(|b| p.get("bodies").is_none_or(Value::is_null) || asked.contains(&b.name))
diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs
index 899aea0723..bcf49bc201 100644
--- a/crates/engine/src/cmd/clipboard.rs
+++ b/crates/engine/src/cmd/clipboard.rs
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use solidcraft_doc::{FeatureKind, PlaneRef};
use super::CommandSpec;
-use crate::params::{bad, string_list, vec3};
+use crate::params::{bad, name_or_id_list, vec3};
use crate::{Result, Session};
pub static COMMANDS: &[CommandSpec] = &[
@@ -22,10 +22,8 @@ pub static COMMANDS: &[CommandSpec] = &[
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.copy";
- let mut keys = string_list(p, "features");
- if let Some(Value::Array(a)) = p.get("features") {
- keys.extend(a.iter().filter_map(Value::as_u64).map(|n| n.to_string()));
- }
+ // The features are named or numbered, and both kinds can sit in one list.
+ let keys = name_or_id_list(cmd, p, "features")?;
if keys.is_empty() || keys.len() > 1000 {
return Err(bad(cmd, "`features` must list 1…1000 features"));
}
diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs
index 3ad97fe656..0ef06e078b 100644
--- a/crates/engine/src/cmd/component.rs
+++ b/crates/engine/src/cmd/component.rs
@@ -381,7 +381,7 @@ fn move_bodies(s: &mut Session, p: &Value) -> Result<Value> {
fn copy_bodies(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.copy_bodies";
let to = if p.get("component").is_some() { component(s, p, "component", cmd)? } else { s.active_component };
- let names = string_list(p, "bodies");
+ let names = string_list(cmd, p, "bodies")?;
if names.is_empty() || names.len() > 1000 {
return Err(bad(cmd, "`bodies` must list 1…1000 bodies"));
}
@@ -407,7 +407,7 @@ fn copy_bodies(s: &mut Session, p: &Value) -> Result<Value> {
// The copy is made where its body is, so it starts out in the same place.
scratch.active_component = from;
scratch.active_occurrence_path = None;
- let mut made = string_list(&scratch.execute("solid.move", &json!({"bodies": bodies, "copy": true}))?, "created_bodies");
+ let mut made = string_list(cmd, &scratch.execute("solid.move", &json!({"bodies": bodies, "copy": true}))?, "created_bodies")?;
// Each copy is its body's name numbered as all copies are (`Cube (2)`, `Cube (2)(2)`): the
// move names a copy of `Cube (2)` `Cube (2) (2)`.
if made.len() == bodies.len() {
@@ -450,7 +450,7 @@ pub(crate) fn transfer_constructor_result(s: &mut Session, p: &Value) -> Result<
fn move_sketches(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "component.move_sketches";
let to = component(s, p, "component", cmd)?;
- let keys = string_list(p, "sketches");
+ let keys = string_list(cmd, p, "sketches")?;
let mut ids = Vec::new();
for k in &keys {
match s.doc.find_feature(k) {
diff --git a/crates/engine/src/cmd/component_transfer.rs b/crates/engine/src/cmd/component_transfer.rs
index ffb66c9fb9..9c7724a247 100644
--- a/crates/engine/src/cmd/component_transfer.rs
+++ b/crates/engine/src/cmd/component_transfer.rs
@@ -34,7 +34,7 @@ fn body_names(s: &Session, p: &Value, cmd: &str, allow_boundary: bool) -> Result
if p.get("bodies").and_then(Value::as_array).is_none_or(|names| names.iter().any(|name| !name.is_string())) {
return Err(bad(cmd, "bodies must be an array of body names"));
}
- let names = string_list(p, "bodies");
+ let names = string_list(cmd, p, "bodies")?;
if names.is_empty() || names.len() > 1000 || names.iter().collect::<BTreeSet<_>>().len() != names.len() {
return Err(bad(cmd, "bodies must list 1..1000 distinct existing definition bodies"));
}
diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs
index 2a6792674e..bf9dbe9063 100644
--- a/crates/engine/src/cmd/config.rs
+++ b/crates/engine/src/cmd/config.rs
@@ -129,16 +129,16 @@ fn add_column(s: &mut Session, c: Column, cmd: &str) -> Result<()> {
fn configure(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "config.configure";
- for n in string_list(p, "params") {
+ for n in string_list(cmd, p, "params")? {
let c = column_of(s, &json!({ "param": n }), cmd)?;
add_column(s, c, cmd)?;
}
- for n in string_list(p, "features") {
+ for n in string_list(cmd, p, "features")? {
let c = column_of(s, &json!({ "feature": n }), cmd)?;
add_column(s, c, cmd)?;
}
for key in ["materials", "appearances"] {
- for n in string_list(p, key) {
+ for n in string_list(cmd, p, key)? {
let field = if key == "materials" { "material" } else { "appearance" };
let c = column_of(s, &json!({ field: n }), cmd)?;
add_column(s, c, cmd)?;
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index d393eb7eea..08736550d3 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use solidcraft_doc::{Feature, FeatureKind};
use super::CommandSpec;
-use crate::params::{bad, bool_, num, str_, string_list};
+use crate::params::{bad, bool_, name_or_id_list, num, str_};
use crate::{EngineError, Result, Sel, Session, Snapshot};
pub static COMMANDS: &[CommandSpec] = &[
@@ -174,10 +174,8 @@ fn feature_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result<u64> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.delete";
- let mut keys = string_list(p, "features");
- if let Some(Value::Array(a)) = p.get("features") {
- keys.extend(a.iter().filter_map(Value::as_u64).map(|n| n.to_string()));
- }
+ // The features are named or numbered, and both kinds can sit in one list.
+ let mut keys = name_or_id_list(cmd, p, "features")?;
if let Some(f) = p.get("feature") {
keys.push(match f {
Value::Number(n) => n.to_string(),
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index dd52429e10..8e8fcee82e 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -10,7 +10,7 @@ use solidcraft_doc::{Dir, FacePick, Position};
use solidcraft_geom::Vec3;
use super::{CommandSpec, not_in_sketch};
-use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec2, vec3};
+use crate::params::{UNKNOWN_COMMAND, bad, bool_, expr, expr_problem, req_expr, str_, string_list, string_list_or_default, vec2, vec3};
use crate::schema::features::{
BoundingSolidParams, BoxParams, ConeParams, CylinderParams, ExtrudeParams, FeatureResult, PipeParams, ScaleParams, SphereParams, TorusParams,
};
@@ -273,7 +273,10 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat
// assembly component considers every body; otherwise keep the active scope.
// Explicit participants override either default.
// A component with no body of its own works on those of the components inside it (#3223).
- let parts = string_list(p, "participants");
+ // The participants only pick the scope here; the feature itself refuses a list of the
+ // wrong type (`add_feature`), so a wrong type cannot make this cut anything. This preview
+ // cannot fail, so it reads the list leniently.
+ let parts = string_list_or_default(p, "participants");
let implicit_all = grouped.is_some() && !st.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component);
let mut bodies: Vec<_> = if !parts.is_empty() {
st.bodies.iter().filter(|b| parts.contains(&b.name)).collect()
@@ -608,12 +611,15 @@ pub(crate) fn profiles(p: &Value, cmd: &str) -> Result<ProfileSel> {
for x in a {
let ids: Vec<String> = match x {
Value::Array(ids) => ids.iter().filter_map(|i| i.as_str().map(str::to_string)).collect(),
- Value::Object(o) => {
- if let Some(c) = o.get("curves") {
- string_list(&json!({"c": c}), "c")
- } else if let Some(ls) = o.get("loops").and_then(Value::as_array) {
+ Value::Object(_) => {
+ if x.get("curves").is_some() {
+ string_list(cmd, x, "curves")?
+ } else if let Some(ls) = x.get("loops").and_then(Value::as_array) {
let outer = ls.iter().find(|l| l.get("outer").and_then(Value::as_bool).unwrap_or(true)).or(ls.first());
- outer.map(|l| string_list(l, "curves")).unwrap_or_default()
+ match outer {
+ Some(l) => string_list(cmd, l, "curves")?,
+ None => Vec::new(),
+ }
} else {
Vec::new()
}
@@ -716,8 +722,8 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->
kind,
FeatureKind::Box { .. } | FeatureKind::Cylinder { .. } | FeatureKind::Sphere { .. } | FeatureKind::Torus { .. } | FeatureKind::Cone { .. }
);
- let (participants, key) = match string_list(p, "participants") {
- v if v.is_empty() && primitive => (string_list(p, "targets"), "targets"),
+ let (participants, key) = match string_list(UNKNOWN_COMMAND, p, "participants")? {
+ v if v.is_empty() && primitive => (string_list(UNKNOWN_COMMAND, p, "targets")?, "targets"),
v => (v, "participants"),
};
if participants.len() > 10_000 || participants.iter().any(|b| b != "*" && s.model.state().body(b).is_none()) {
@@ -757,7 +763,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->
{
f.component = comp;
}
- let mut names = string_list(p, "body_names");
+ let mut names = string_list(UNKNOWN_COMMAND, p, "body_names")?;
if let Some(b) = str_(p, "body_name") {
names.insert(0, b.to_string());
}
@@ -857,9 +863,9 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
Some(o) if o.eq_ignore_ascii_case("auto") => Operation::parse(auto_operation_in(s, p, false).unwrap_or("new")).unwrap_or(Operation::NewBody),
_ => operation(p, cmd)?,
};
- let mut targets = string_list(p, "targets");
+ let mut targets = string_list(cmd, p, "targets")?;
let mut p = std::borrow::Cow::Borrowed(p);
- if operation == Operation::Join && targets.is_empty() && string_list(&p, "participants").is_empty() {
+ if operation == Operation::Join && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() {
// A face's outward extension joins that body, and so does a profile sketched on a body's
// face. Assembly neighbours can touch only an edge of the tool: trying to join them
// first fails, or absorbs unrelated parts (#226). A profile drawn past the face can lie
@@ -870,10 +876,10 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
Some(body) => Some(body),
None => face_body_reached(s, sketch)?,
});
- } else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body)? {
+ } else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body, cmd)? {
p.to_mut()["participants"] = json!(parts);
}
- if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(&p, "participants").is_empty() {
+ if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(cmd, &p, "participants")?.is_empty() {
targets = shown_scope(s);
}
let kind = FeatureKind::Extrude {
@@ -896,10 +902,10 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {
/// none and that body is in a component inside the active one (#5679): the active component's
/// own bodies, as by default, and that body. `None` when the default already reaches it: it is
/// one of the active component's, or a component with no body of its own cuts every body.
-fn cut_scope(s: &Session, p: &Value, operation: Operation, sketch: u64, face_body: Option<String>) -> Result<Option<Vec<String>>> {
+fn cut_scope(s: &Session, p: &Value, operation: Operation, sketch: u64, face_body: Option<String>, cmd: &str) -> Result<Option<Vec<String>>> {
if !matches!(operation, Operation::Cut | Operation::Intersect)
- || !string_list(p, "targets").is_empty()
- || !string_list(p, "participants").is_empty()
+ || !string_list(cmd, p, "targets")?.is_empty()
+ || !string_list(cmd, p, "participants")?.is_empty()
{
return Ok(None);
}
@@ -1045,9 +1051,9 @@ fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {
/// sketch that is on one), as for an extrude, also in a component inside the active one, moved
/// or turned (#5679; refused as [`face_body_reached`] says). Explicit `targets` or
/// `participants` keep theirs.
-fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u64]) -> Result<Vec<BodyName>> {
- let mut targets = string_list(p, "targets");
- if operation == Operation::Join && targets.is_empty() && string_list(p, "participants").is_empty() {
+fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u64], cmd: &str) -> Result<Vec<BodyName>> {
+ let mut targets = string_list(cmd, p, "targets")?;
+ if operation == Operation::Join && targets.is_empty() && string_list(cmd, p, "participants")?.is_empty() {
for sketch in sketches {
if let Some(body) = face_body_reached(s, *sketch)? {
targets.push(body);
@@ -1090,7 +1096,7 @@ fn active_scope<'a>(s: &Session, st: &'a solidcraft_doc::ModelState) -> Vec<&'a
fn thin_param(s: &Session, p: &Value, sketch: u64, cmd: &str) -> Result<ThinWall> {
let st = s.model.state();
let ss = st.sketch(sketch).ok_or_else(|| bad(cmd, "the sketch is not evaluated"))?;
- let mut curves = string_list(p, "curves");
+ let mut curves = string_list(cmd, p, "curves")?;
if curves.is_empty() {
curves =
ss.sketch.curves.iter().filter(|c| !c.construction && !c.centerline && !c.infinite && c.link.is_none()).map(|c| c.id.clone()).collect();
@@ -1223,11 +1229,11 @@ fn revolve(s: &mut Session, p: &Value) -> Result<Value> {
Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be sketch_normal or legacy_axis_start"))?,
};
let operation = operation(p, cmd)?;
- let targets = face_join_targets(s, p, operation, &[sketch])?;
+ let targets = face_join_targets(s, p, operation, &[sketch], cmd)?;
// From a profile on a body's face in a component inside the active one, a cut changes that
// body too, as an extrude's does (#5679).
let mut p = std::borrow::Cow::Borrowed(p);
- if let Some(parts) = cut_scope(s, &p, operation, sketch, None)? {
+ if let Some(parts) = cut_scope(s, &p, operation, sketch, None, cmd)? {
p.to_mut()["participants"] = json!(parts);
}
let kind = FeatureKind::Revolve {
@@ -1752,7 +1758,7 @@ fn chamfer(s: &mut Session, p: &Value) -> Result<Value> {
fn combine(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.combine";
let target = str_(p, "target").ok_or_else(|| bad(cmd, "`target` must be a body name"))?.to_string();
- let tools = string_list(p, "tools");
+ let tools = string_list(cmd, p, "tools")?;
if tools.is_empty() {
return Err(bad(cmd, "`tools` must list bodies"));
}
@@ -1833,7 +1839,7 @@ fn move_placements(s: &mut Session, p: &Value, plan: crate::frames::PlacementMov
fn move_body_feature(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.move";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Err(bad(cmd, "`bodies` must list bodies"));
}
@@ -1894,7 +1900,7 @@ fn copy_keeps_appearance(s: &mut Session, reply: &Value, sources: &[String], cmd
}
fn source_features(s: &Session, p: &Value, cmd: &str) -> Result<Vec<solidcraft_doc::FeatureId>> {
- let names = string_list(p, "features");
+ let names = string_list(cmd, p, "features")?;
if names.is_empty() {
return Err(bad(cmd, "`features` must list features to copy"));
}
@@ -1952,7 +1958,7 @@ fn finish_pattern(
pattern: solidcraft_doc::PatternKind,
bodies: Vec<String>,
) -> Result<Value> {
- let comps = string_list(p, "components");
+ let comps = string_list(UNKNOWN_COMMAND, p, "components")?;
if comps.is_empty() {
return add_feature(s, p, FeatureKind::Pattern { features, pattern, bodies: bodies.into_iter().map(BodyName).collect() });
}
@@ -1972,10 +1978,10 @@ fn finish_pattern(
/// What a pattern copies: features (replayed), bodies (`bodies: [names]`), or components
/// (`components: [names]`, placed again as occurrences).
fn pattern_sources(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<solidcraft_doc::FeatureId>, Vec<String>)> {
- if !string_list(p, "components").is_empty() {
+ if !string_list(cmd, p, "components")?.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Ok((source_features(s, p, cmd)?, Vec::new()));
}
@@ -2042,7 +2048,7 @@ fn pattern_path(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.pattern.path";
let (features, bodies) = pattern_sources(s, p, cmd)?;
let path_sketch = sketch_id(s, p.get("path_sketch").or_else(|| p.get("sketch")), cmd, "path_sketch")?;
- let path = string_list(p, "path");
+ let path = string_list(cmd, p, "path")?;
if path.is_empty() || path.len() > 1000 {
return Err(bad(cmd, "`path` must list 1…1000 curve ids"));
}
@@ -2066,7 +2072,7 @@ fn pattern_path(s: &mut Session, p: &Value) -> Result<Value> {
fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.mirror";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
let features = if bodies.is_empty() { source_features(s, p, cmd)? } else { Vec::new() };
let plane = plane_param(s, p.get("plane"), cmd)?;
let combine = bool_(p, "combine").unwrap_or(false);
@@ -2413,7 +2419,7 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
let sketch = feature_sketch(s, p, cmd)?;
// No points named: every sketch point (standalone points and circle centres, not
// line or arc ends, not the origin).
- let ids = if p.get("points").is_some() { string_list(p, "points") } else { sketch_hole_points(s, sketch) };
+ let ids = if p.get("points").is_some() { string_list(cmd, p, "points")? } else { sketch_hole_points(s, sketch) };
if ids.is_empty() || ids.len() > 10_000 {
return Err(bad(cmd, "`points` must list 1…10000 sketch point ids"));
}
@@ -2568,7 +2574,7 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
None => None,
};
let mut p = p.clone();
- let targets = string_list(&p, "targets");
+ let targets = string_list(cmd, &p, "targets")?;
if p.get("participants").is_none() {
// The bodies to drill, as `targets` (like an extrude's): its participants.
if !targets.is_empty() {
@@ -2754,14 +2760,14 @@ fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.sweep";
let sketch = feature_sketch(s, p, cmd)?;
let path_sketch = sketch_id(s, p.get("path_sketch"), cmd, "path_sketch")?;
- let path = string_list(p, "path");
+ let path = string_list(cmd, p, "path")?;
if path.is_empty() {
return Err(bad(cmd, "`path` must list curve ids"));
}
let (orientation, twist, scale) = sweep_options(s, p, cmd)?;
let (rails, rail_fit) = sweep_rails(s, p, cmd, path_sketch)?;
let operation = operation(p, cmd)?;
- let targets = face_join_targets(s, p, operation, &[sketch])?;
+ let targets = face_join_targets(s, p, operation, &[sketch], cmd)?;
add_feature(
s,
p,
@@ -2863,7 +2869,7 @@ pub(super) fn guide_rails(s: &Session, p: &Value, cmd: &str, what: &str, default
(None, None) => return Err(bad(cmd, "each rail needs the `sketch` its curves are in")),
(Some(_), _) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?,
};
- let curves = string_list(rail, "curves");
+ let curves = string_list(cmd, rail, "curves")?;
if curves.is_empty() || curves.len() > 1000 {
return Err(bad(cmd, "each rail's `curves` must list 1…1000 curve ids in order"));
}
@@ -2899,8 +2905,8 @@ fn loft(s: &mut Session, p: &Value) -> Result<Value> {
let (rails, rail_fit) = guide_rails(s, p, cmd, "loft", None)?;
let operation = operation(p, cmd)?;
let sketches: Vec<u64> = sections.iter().map(|sec| sec.sketch.0).collect();
- let mut targets = face_join_targets(s, p, operation, &sketches)?;
- if operation == Operation::Join && string_list(p, "targets").is_empty() && string_list(p, "participants").is_empty() {
+ let mut targets = face_join_targets(s, p, operation, &sketches, cmd)?;
+ if operation == Operation::Join && string_list(cmd, p, "targets")?.is_empty() && string_list(cmd, p, "participants")?.is_empty() {
let st = s.model.state();
let candidates: Vec<_> = st
.bodies
@@ -2960,7 +2966,7 @@ fn thread(s: &mut Session, p: &Value) -> Result<Value> {
fn pipe(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.pipe";
let path_sketch = sketch_id(s, p.get("path_sketch"), cmd, "path_sketch")?;
- let path = string_list(p, "path");
+ let path = string_list(cmd, p, "path")?;
if path.is_empty() {
return Err(bad(cmd, "`path` must list curve ids"));
}
@@ -2979,7 +2985,7 @@ fn pipe(s: &mut Session, p: &Value) -> Result<Value> {
diameter,
wall,
operation: operation(p, cmd)?,
- targets: string_list(p, "targets").into_iter().map(BodyName).collect(),
+ targets: string_list(cmd, p, "targets")?.into_iter().map(BodyName).collect(),
},
)
}
@@ -2988,12 +2994,12 @@ fn bounding_solid(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.bounding_solid";
let margin = expr(p, "margin").unwrap_or_else(|| "0".into());
check_expr(s, &margin, Kind::Length, cmd, "margin")?;
- add_feature(s, p, FeatureKind::BoundingSolid { bodies: string_list(p, "bodies").into_iter().map(BodyName).collect(), margin })
+ add_feature(s, p, FeatureKind::BoundingSolid { bodies: string_list(cmd, p, "bodies")?.into_iter().map(BodyName).collect(), margin })
}
fn scale(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.scale";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Err(bad(cmd, "`bodies` must list bodies"));
}
diff --git a/crates/engine/src/cmd/features_more.rs b/crates/engine/src/cmd/features_more.rs
index df4ee9844b..6b5f1404b5 100644
--- a/crates/engine/src/cmd/features_more.rs
+++ b/crates/engine/src/cmd/features_more.rs
@@ -128,13 +128,13 @@ fn coil(s: &mut Session, p: &Value) -> Result<Value> {
start_angle,
clockwise,
operation,
- targets: string_list(p, "targets").into_iter().map(BodyName).collect(),
+ targets: string_list(cmd, p, "targets")?.into_iter().map(BodyName).collect(),
},
)
}
fn curves_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
- let c = string_list(p, "curves");
+ let c = string_list(cmd, p, "curves")?;
if c.is_empty() || c.len() > 1000 {
return Err(bad(cmd, "`curves` must list 1…1000 sketch curve ids"));
}
@@ -185,7 +185,7 @@ fn emboss(s: &mut Session, p: &Value) -> Result<Value> {
Some("deboss") => true,
Some(m) => return Err(bad(cmd, format!("unknown mode `{m}` (emboss or deboss)"))),
};
- let mut targets = string_list(p, "targets");
+ let mut targets = string_list(cmd, p, "targets")?;
let face = if let Some(value) = p.get("face") {
let local = vec3(value).ok_or_else(|| bad(cmd, "`face` must be a finite point [x,y,z]"))?;
let at = solidcraft_doc::apply_point(&s.active_component_frame(), local);
@@ -400,7 +400,7 @@ fn replace_face(s: &mut Session, p: &Value) -> Result<Value> {
fn align(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.align";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Err(bad(cmd, "`bodies` must list the bodies to move"));
}
@@ -489,7 +489,7 @@ fn align(s: &mut Session, p: &Value) -> Result<Value> {
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.remove";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Err(bad(cmd, "`bodies` must list bodies"));
}
@@ -541,7 +541,7 @@ pub(super) fn snap_point(s: &Session, kind: &str, at: Vec3) -> Option<Vec3> {
fn boundary_fill(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.boundary_fill";
- let tools = string_list(p, "tools");
+ let tools = string_list(cmd, p, "tools")?;
let st = s.model.state();
if tools.is_empty() || tools.len() > 64 || tools.iter().any(|t| st.body(t).is_none()) {
return Err(bad(cmd, "`tools` must list 1…64 bodies"));
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index be67ca9a22..14892b8f48 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -624,13 +624,14 @@ fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
- let path = path_arg(p, "file.export")?;
+ let cmd = "file.export";
+ let path = path_arg(p, cmd)?;
let format = Format::from_name(str_(p, "format").unwrap_or(path))?;
if format == Format::Urdf {
return export_urdf(s, path, p);
}
- let quality = mesh_quality(p, "file.export")?;
- export_to(s, path, format, &string_list(p, "bodies"), quality)
+ let quality = mesh_quality(p, cmd)?;
+ export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality)
}
/// The OBJ export: the mesh file and the material library beside it, with the colours of the
@@ -663,7 +664,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io
/// anything is written; the meshes go first and the `.urdf` last.
fn export_urdf(s: &Session, path: &str, p: &Value) -> Result<Value> {
let cmd = "file.export";
- if !string_list(p, "bodies").is_empty() {
+ if !string_list(cmd, p, "bodies")?.is_empty() {
return Err(bad(cmd, "urdf exports the whole assembly; omit bodies"));
}
let positive = |k: &str| match p.get(k) {
@@ -749,7 +750,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
cmd,
kind: crate::slicers::TargetKind::Slicer,
spec,
- bodies: string_list(p, "bodies"),
+ bodies: string_list(cmd, p, "bodies")?,
format,
quality,
dest: send::Dest::Path(path),
@@ -758,7 +759,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
},
);
}
- export_to(s, path, format, &string_list(p, "bodies"), quality)
+ export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality)
}
/// The browser build can't start a program.
@@ -791,7 +792,7 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result<Value> {
cmd,
kind: crate::slicers::TargetKind::Slicer,
spec,
- bodies: string_list(p, "bodies"),
+ bodies: string_list(cmd, p, "bodies")?,
format,
quality: Default::default(),
dest: send::Dest::Folder,
diff --git a/crates/engine/src/cmd/file_easyprint.rs b/crates/engine/src/cmd/file_easyprint.rs
index e899553b69..ab87392697 100644
--- a/crates/engine/src/cmd/file_easyprint.rs
+++ b/crates/engine/src/cmd/file_easyprint.rs
@@ -56,7 +56,7 @@ pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result<Value> {
if !bool_(p, "consent").unwrap_or(false) {
return Err(bad(cmd, "this uploads the model to Printables' servers: ask the user, then pass `consent: true`"));
}
- let Exported { bytes, ext, fell_back, .. } = export_bodies(s, cmd, &string_list(p, "bodies"), format)?;
+ let Exported { bytes, ext, fell_back, .. } = export_bodies(s, cmd, &string_list(cmd, p, "bodies")?, format)?;
if bytes.len() > MAX_BYTES {
let mb = bytes.len().div_ceil(1_000_000);
return Err(bad(cmd, format!("the model is {mb} MB and EasyPrint takes {} MB at most: send fewer bodies", MAX_BYTES / 1_000_000)));
diff --git a/crates/engine/src/cmd/frame.rs b/crates/engine/src/cmd/frame.rs
index 57a0f432f3..d0fec7a264 100644
--- a/crates/engine/src/cmd/frame.rs
+++ b/crates/engine/src/cmd/frame.rs
@@ -188,7 +188,7 @@ fn member(s: &mut Session, p: &Value) -> Result<Value> {
let lines = match p.get("lines") {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(a)) if !a.is_empty() && a.len() <= frame::MAX_MEMBERS && a.iter().all(Value::is_string) => {
- let lines = string_list(p, "lines");
+ let lines = string_list(cmd, p, "lines")?;
let mut seen = std::collections::HashSet::new();
if let Some(twice) = lines.iter().find(|l| !seen.insert(l.as_str())) {
return Err(bad(cmd, format!("line `{twice}` is listed twice")));
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index 6cad1e9ded..00c4579517 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -107,10 +107,11 @@ pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value {
}
fn measure(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "inspect.measure";
if let Some(items) = p.get("items") {
return super::measure_sel::measure_items(s, items);
}
- let want = string_list(p, "bodies");
+ let want = string_list(cmd, p, "bodies")?;
let st = s.world_state();
let selected: Vec<_> = st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).collect();
// Each body is measured on its own: on all cores, in body order.
@@ -131,7 +132,7 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
}
}
if !want.is_empty() && bodies.len() != want.len() {
- return Err(bad("inspect.measure", "unknown body name"));
+ return Err(bad(cmd, "unknown body name"));
}
// Sheet metal keeps the edges where bends meet flat faces (so bends stay visible): count its
// B-rep faces as they are, without merging coplanar neighbours.
@@ -450,7 +451,7 @@ fn model_threads(s: &mut Session, _p: &Value) -> Result<Value> {
fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "material.assign";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
let material = str_(p, "material").ok_or_else(|| bad(cmd, "`material` must be a material name"))?;
let canonical = s.doc.material_name(material).ok_or_else(|| bad(cmd, format!("unknown material `{material}` (see material.list)")))?;
let st = s.model.state();
@@ -486,7 +487,7 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
use solidcraft_doc::appearance::FaceLook;
let cmd = "appearance.assign";
let look = appearance_look(cmd, p)?;
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
let st = s.model.state();
if bodies.iter().any(|b| st.body(b).is_none()) {
return Err(bad(cmd, "`bodies` must list existing bodies"));
@@ -508,7 +509,7 @@ pub(super) fn appearance(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let mut comps: Vec<u64> = Vec::new();
- for c in string_list(p, "components") {
+ for c in string_list(cmd, p, "components")? {
let id = s
.doc
.find_component(&c)
diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs
index 43781bb663..453495178c 100644
--- a/crates/engine/src/cmd/interference.rs
+++ b/crates/engine/src/cmd/interference.rs
@@ -73,7 +73,7 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
},
};
let budget = std::time::Duration::from_secs_f64(budget_s);
- let want = string_list(p, "bodies");
+ let want = string_list(cmd, p, "bodies")?;
let st = s.world_state();
let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) =
st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh());
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 6f9ebee769..d0cb77ad8d 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -216,7 +216,12 @@ impl CommandSpec {
/// undo step and the evaluation).
pub(crate) fn run_nested(&self, s: &mut Session, p: &Value) -> Result<Value> {
(self.enabled)(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?;
- (self.run)(s, p)
+ let r = (self.run)(s, p);
+ // A parameter error that did not name the command names it here (see `Session::execute`).
+ match r {
+ Err(crate::EngineError::BadParams { cmd, msg }) if cmd.is_empty() => Err(crate::EngineError::BadParams { cmd: self.id.to_string(), msg }),
+ other => other,
+ }
}
pub fn info(&self, s: &Session) -> CommandInfo {
let e = (self.enabled)(s);
diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs
index 38de1be77c..caf3e33437 100644
--- a/crates/engine/src/cmd/plastic.rs
+++ b/crates/engine/src/cmd/plastic.rs
@@ -120,7 +120,7 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
fn assign_rule(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "plastic.assign_rule";
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() || bodies.len() > 10_000 {
return Err(bad(cmd, "`bodies` must list bodies"));
}
diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs
index 9c563138da..f22de39a54 100644
--- a/crates/engine/src/cmd/sheet.rs
+++ b/crates/engine/src/cmd/sheet.rs
@@ -242,7 +242,7 @@ fn flange(s: &mut Session, p: &Value) -> Result<Value> {
}
"contour" => {
let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if curves.is_empty() || curves.len() > 1000 {
return Err(bad(cmd, "`curves` must list the open chain's lines"));
}
@@ -464,7 +464,7 @@ fn path_flange(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sheet.path_flange";
let edge = p.get("edge").and_then(vec3).ok_or_else(|| bad(cmd, "`edge` must be a point [x, y, z] on a sheet edge"))?;
let sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if curves.is_empty() || curves.len() > sheet::MAX_PATH_LINES {
return Err(bad(cmd, format!("`curves` must list the path's lines (1…{})", sheet::MAX_PATH_LINES)));
}
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 495c78d18b..4f82b7a953 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -930,7 +930,7 @@ fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
}
let closed = bool_(p, "closed").unwrap_or(false);
let infer = bool_(p, "infer").unwrap_or(false);
- let ids = string_list(p, "ids");
+ let ids = string_list(cmd, p, "ids")?;
let ((curves, cons), info) = draw(s, p, cmd, |sk, doc| {
let args: Vec<PArg> = list.iter().map(|v| parg(sk, doc, v, cmd)).collect::<Result<_>>()?;
let n = args.len();
@@ -2039,7 +2039,7 @@ fn c_equal(s: &mut Session, p: &Value) -> Result<Value> {
/// can, so a dimensioned curve keeps its size and the others take it, whatever the order.
fn equal_curves(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.constraint.equal";
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if !(2..=200).contains(&ids.len()) {
return Err(bad(cmd, "`curves` must list 2 to 200 lines or circles/arcs"));
}
@@ -2309,7 +2309,7 @@ fn round_center(sk: &Sketch, c: usize) -> Option<usize> {
fn c_fix(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.constraint.fix";
let want = bool_(p, "fixed");
- let mut refs = string_list(p, "entities");
+ let mut refs = string_list(cmd, p, "entities")?;
if let Some(e) = str_(p, "entity") {
refs.insert(0, e.to_string());
}
@@ -2374,7 +2374,7 @@ pub(super) fn line_pts(sk: &Sketch, l: usize) -> Option<(Vec2, Vec2)> {
fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.dimension";
- let ents = string_list(p, "entities");
+ let ents = string_list(cmd, p, "entities")?;
if ents.is_empty() || ents.len() > 2 {
return Err(bad(cmd, "`entities` must list one or two sketch entities"));
}
@@ -2932,7 +2932,7 @@ fn line_ends(sk: &Sketch, l: usize) -> (usize, usize) {
fn construction(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.construction";
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if ids.is_empty() {
return Err(bad(cmd, "`curves` must list curve ids"));
}
@@ -2966,7 +2966,7 @@ fn construction(s: &mut Session, p: &Value) -> Result<Value> {
fn sketch_delete(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.delete";
- let ids = string_list(p, "entities");
+ let ids = string_list(cmd, p, "entities")?;
if ids.is_empty() {
return Err(bad(cmd, "`entities` must list sketch entity ids"));
}
diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs
index 460fc04211..5d06fcc4de 100644
--- a/crates/engine/src/cmd/sketch_clipboard.rs
+++ b/crates/engine/src/cmd/sketch_clipboard.rs
@@ -71,17 +71,17 @@ pub struct SketchClip {
}
/// Curve and point ids named by `entities`, or the selected sketch geometry.
-fn chosen(s: &Session, p: &Value) -> Vec<String> {
+fn chosen(s: &Session, p: &Value, cmd: &str) -> Result<Vec<String>> {
if p.get("entities").is_some() {
- return string_list(p, "entities");
+ return string_list(cmd, p, "entities");
}
- s.selection
+ Ok(s.selection
.iter()
.filter_map(|sel| match sel {
Sel::SketchCurve { id, .. } | Sel::SketchPoint { id } => Some(id.clone()),
_ => None,
})
- .collect()
+ .collect())
}
fn text_of(sk: &Sketch, ci: usize) -> Option<&str> {
@@ -92,7 +92,7 @@ fn text_of(sk: &Sketch, ci: usize) -> Option<&str> {
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.copy";
let id = target_sketch(s, p, cmd)?;
- let ids = chosen(s, p);
+ let ids = chosen(s, p, cmd)?;
if ids.is_empty() {
return Err(bad(cmd, "select the sketch curves or points to copy"));
}
@@ -211,7 +211,7 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if !(p.is_object() || p.is_null()) {
return Err(bad("sketch.cut", "params must be an object"));
}
- let entities = chosen(s, p);
+ let entities = chosen(s, p, "sketch.cut")?;
let mut q = if p.is_null() { json!({}) } else { p.clone() };
q["entities"] = json!(entities);
let out = copy(s, &q)?;
diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs
index 09b0482960..459cde79ed 100644
--- a/crates/engine/src/cmd/sketch_constraints.rs
+++ b/crates/engine/src/cmd/sketch_constraints.rs
@@ -86,7 +86,7 @@ fn curve(sk: &Sketch, v: Option<&Value>, cmd: &str) -> Result<usize> {
fn c_polygon(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.constraint.polygon";
- let ids = string_list(p, "lines");
+ let ids = string_list(cmd, p, "lines")?;
if ids.len() < 3 || ids.len() > 200 {
return Err(bad(cmd, "`lines` must list 3 to 200 lines of a closed chain"));
}
@@ -361,7 +361,7 @@ fn guess(sk: &Sketch, ents: &[String], cmd: &str) -> Result<ConstraintKind> {
fn smart_constrain(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.constrainer";
- let ents = string_list(p, "entities");
+ let ents = string_list(cmd, p, "entities")?;
let (mut before, mut residual) = (None, None);
let mut name = "";
let (id, info) = edit(s, p, cmd, true, |sk, _| {
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index 8c1cebce29..b80478fb74 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -548,7 +548,7 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.centerline";
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if ids.is_empty() {
return Err(bad(cmd, "`curves` must list lines"));
}
@@ -573,7 +573,7 @@ fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
fn infinite_line(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.infinite";
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if ids.is_empty() {
return Err(bad(cmd, "`curves` must list lines"));
}
@@ -893,7 +893,7 @@ fn tangent_centre(sk: &Sketch, a: usize, b: usize, r: f64, near: Vec2) -> Option
}
fn tangent_curves(sk: &Sketch, p: &Value, cmd: &str, n: usize) -> Result<Vec<usize>> {
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if ids.len() != n {
return Err(bad(cmd, format!("`curves` must list {n} curves")));
}
diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rs
index 02f8f8bdbd..cfd531a16f 100644
--- a/crates/engine/src/cmd/sketch_ends.rs
+++ b/crates/engine/src/cmd/sketch_ends.rs
@@ -63,7 +63,7 @@ fn tie_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.loose_ends.tie";
let only = match p.get("points") {
None | Some(Value::Null) => None,
- Some(Value::Array(a)) if a.iter().all(Value::is_string) => Some(string_list(p, "points")),
+ Some(Value::Array(a)) if a.iter().all(Value::is_string) => Some(string_list(cmd, p, "points")?),
Some(_) => return Err(bad(cmd, "`points` must be a list of point ids")),
};
let (added, info) = edit(s, p, cmd, true, |sk, _| {
diff --git a/crates/engine/src/cmd/sketch_inspect.rs b/crates/engine/src/cmd/sketch_inspect.rs
index fff91dac8e..9f52854040 100644
--- a/crates/engine/src/cmd/sketch_inspect.rs
+++ b/crates/engine/src/cmd/sketch_inspect.rs
@@ -77,7 +77,7 @@ fn curvature_comb(s: &mut Session, p: &Value) -> Result<Value> {
let density = num(p, "density").map(|d| d.clamp(2.0, 2000.0) as usize).unwrap_or(40);
let st = s.model.state();
let mut combs: Vec<(String, Vec<(Vec3, f64, Vec3)>)> = Vec::new();
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if !curves.is_empty() {
let id = match p.get("sketch") {
Some(Value::Number(n)) => n.as_u64(),
@@ -228,7 +228,7 @@ fn minimum_radius(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.minimum_radius";
let st = s.model.state();
let mut items: Vec<(String, Option<(f64, Vec3)>)> = Vec::new();
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if !curves.is_empty() {
let id = match p.get("sketch") {
Some(Value::Number(n)) => n.as_u64(),
@@ -318,7 +318,7 @@ fn isocurves(s: &mut Session, p: &Value) -> Result<Value> {
fn center_of_mass(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "inspect.center_of_mass";
- let names = string_list(p, "bodies");
+ let names = string_list(cmd, p, "bodies")?;
// The world state, as Measure reads: placed occurrences where they are, each placement once.
let st = s.world_state();
let mut out = Vec::new();
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs
index 207a9db59f..1fa1a8beb8 100644
--- a/crates/engine/src/cmd/sketch_modify.rs
+++ b/crates/engine/src/cmd/sketch_modify.rs
@@ -1951,7 +1951,7 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.offset";
- let ids = string_list(p, "curves");
+ let ids = string_list(cmd, p, "curves")?;
if ids.is_empty() || ids.len() > 500 {
return Err(bad(cmd, "`curves` must list 1…500 curves"));
}
@@ -2229,7 +2229,7 @@ fn freeze_offset_profiles(doc: &mut solidcraft_doc::Document, sketch: u64, bound
/// Curves and lone points named in `entities`.
fn entities(sk: &Sketch, p: &Value, cmd: &str) -> Result<(Vec<usize>, Vec<usize>)> {
- let ids = string_list(p, "entities");
+ let ids = string_list(cmd, p, "entities")?;
if ids.is_empty() {
return Err(bad(cmd, "`entities` must list sketch curves or points"));
}
@@ -2505,7 +2505,7 @@ fn move_copy(s: &mut Session, p: &Value) -> Result<Value> {
let rot = rotate(c, ang);
let f = move |q: Vec2| rot(q) + t;
let mut links = Vec::new();
- for entity in string_list(p, "entities") {
+ for entity in string_list(cmd, p, "entities")? {
if let Some(link) = super::sketch_create::text_link(sk, &entity)
&& !links.iter().any(|old| old == link)
{
diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs
index 5749b94319..a74c8069c7 100644
--- a/crates/engine/src/cmd/sketch_project.rs
+++ b/crates/engine/src/cmd/sketch_project.rs
@@ -477,7 +477,7 @@ fn break_link(s: &mut Session, p: &Value) -> Result<Value> {
}
links.push(l.to_string());
}
- for e in crate::params::string_list(p, "entities") {
+ for e in crate::params::string_list(cmd, p, "entities")? {
let l = sk
.curves
.iter()
diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs
index 4c1e4423f1..05d6942e4b 100644
--- a/crates/engine/src/cmd/surface.rs
+++ b/crates/engine/src/cmd/surface.rs
@@ -321,7 +321,7 @@ fn untrim(s: &mut Session, p: &Value) -> Result<Value> {
/// The profiles and curves a surface builder takes: `curves`, and `profiles` (all of them when
/// neither is given).
fn sheet_inputs(p: &Value, cmd: &str) -> Result<(Option<solidcraft_doc::ProfileSel>, Vec<String>)> {
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if curves.len() > 1000 {
return Err(bad(cmd, "at most 1000 curves"));
}
@@ -349,7 +349,7 @@ fn surface_sweep(s: &mut Session, p: &Value) -> Result<Value> {
let sketch = feature_sketch(s, p, cmd)?;
let (profiles, curves) = sheet_inputs(p, cmd)?;
let path_sketch = sketch_id(s, p.get("path_sketch"), cmd, "path_sketch")?;
- let path = string_list(p, "path");
+ let path = string_list(cmd, p, "path")?;
if path.is_empty() || path.len() > 1000 {
return Err(bad(cmd, "`path` must list 1…1000 curve ids"));
}
@@ -402,7 +402,7 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let sketch = sketch_id(s, sec.get("sketch"), cmd, "sections.sketch")?;
- let curves = string_list(sec, "curves");
+ let curves = string_list(cmd, sec, "curves")?;
if curves.len() > 1000 {
return Err(bad(cmd, "at most 1000 curves a section"));
}
@@ -516,7 +516,7 @@ fn ruled(s: &mut Session, p: &Value) -> Result<Value> {
}
fn bodies_param(s: &Session, p: &Value, cmd: &str) -> Result<Vec<String>> {
- let bodies = string_list(p, "bodies");
+ let bodies = string_list(cmd, p, "bodies")?;
if bodies.is_empty() {
return Err(bad(cmd, "`bodies` must list bodies"));
}
@@ -545,7 +545,7 @@ fn thicken(s: &mut Session, p: &Value) -> Result<Value> {
thickness,
symmetric: bool_(p, "symmetric").unwrap_or(false),
operation: operation(p, cmd)?,
- targets: string_list(p, "targets").into_iter().map(BodyName).collect(),
+ targets: string_list(cmd, p, "targets")?.into_iter().map(BodyName).collect(),
};
add_feature(s, p, kind)
}
diff --git a/crates/engine/src/cmd/surface_boundary.rs b/crates/engine/src/cmd/surface_boundary.rs
index 985ab6c644..df909f1aea 100644
--- a/crates/engine/src/cmd/surface_boundary.rs
+++ b/crates/engine/src/cmd/surface_boundary.rs
@@ -48,7 +48,7 @@ fn loop_patch(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`v` and `operation` belong to a curve network: give its curves as `u` and `v`"));
}
let sketch = feature_sketch(s, p, cmd)?;
- let curves = string_list(p, "curves");
+ let curves = string_list(cmd, p, "curves")?;
if !(2..=4).contains(&curves.len()) {
return Err(bad(cmd, "`curves` must list 2 to 4 sketch curves in loop order (or give a network as `u` and `v`)"));
}
@@ -199,7 +199,7 @@ fn network_curves(s: &Session, p: &Value, key: &str, default_sketch: &mut Option
curve.body = Some(BodyName::from(body.to_string()));
curve.edges = pts;
} else {
- curve.curves = string_list(o, "curves");
+ curve.curves = string_list(cmd, o, "curves")?;
if o.get("sketch").is_some_and(|v| !v.is_null()) {
curve.sketch = Some(SketchId(sketch_id(s, o.get("sketch"), cmd, &format!("{name}.sketch"))?));
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 157310622f..c6db3fe6cd 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1185,6 +1185,13 @@ impl Session {
Err(EngineError::Internal(spec.id.to_string(), msg))
}
};
+ // 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 {
+ Ok(r) => Ok(r),
+ Err(EngineError::BadParams { cmd, msg }) if cmd.is_empty() => Err(EngineError::BadParams { cmd: spec.id.to_string(), msg }),
+ Err(e) => Err(e),
+ };
// New/open/recover can replace the Session. Device ownership belongs to the host,
// so its capability metadata survives those document lifecycle commands.
self.render_viewport = host_viewport;
diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs
index 4960fc7467..443076a3e1 100644
--- a/crates/engine/src/params.rs
+++ b/crates/engine/src/params.rs
@@ -87,10 +87,204 @@ pub fn req_expr(cmd: &str, p: &Value, k: &str) -> Result<Expr> {
expr(p, k).ok_or_else(|| bad(cmd, format!("`{k}` {}", expr_problem(p.get(k)))))
}
-pub fn string_list(p: &Value, k: &str) -> Vec<String> {
+/// The most names a list parameter may carry.
+const MAX_STRING_LIST: usize = 10_000;
+
+/// The command name for a caller that does not know it: the engine names the command that ran
+/// when the error reaches it.
+pub const UNKNOWN_COMMAND: &str = "";
+
+/// A short description of a value that is not a name, for the message that refuses it.
+fn json_brief(v: &Value) -> String {
+ match v {
+ Value::Null => "null".to_string(),
+ Value::Bool(b) => b.to_string(),
+ Value::Number(n) => n.to_string(),
+ Value::String(s) => format!("\"{s}\""),
+ // A list or an object is named by its kind alone: it can be long.
+ Value::Array(_) => "a list".to_string(),
+ Value::Object(_) => "an object".to_string(),
+ }
+}
+
+/// A list of names given as a parameter: a list of names, or a single name as a string.
+///
+/// A value of any other kind is refused instead of read as an empty list: an empty list means
+/// "every body" to most commands, so a wrong type would act on the whole model (#6651). An
+/// entry that is not a name is refused too, and a list longer than [`MAX_STRING_LIST`] names is
+/// refused rather than cut short.
+///
+/// A missing parameter is an empty list (it was not given), and so is `null`: the schema
+/// contract declares these parameters optional and reads `null` as absent, as it does for
+/// `str_`. A plain string is a list of one (the shorthand the repository allows on purpose).
+///
+/// The command's name is in the message. A caller that does not know it passes an empty
+/// string: the engine names the command that ran when the error reaches it.
+pub fn string_list(cmd: &str, p: &Value, k: &str) -> Result<Vec<String>> {
+ match p.get(k) {
+ None | Some(Value::Null) => Ok(Vec::new()),
+ Some(Value::String(s)) => Ok(vec![s.clone()]),
+ Some(Value::Array(a)) => {
+ if a.len() > MAX_STRING_LIST {
+ return Err(bad(cmd, format!("`{k}` must list at most {MAX_STRING_LIST} names")));
+ }
+ a.iter()
+ .enumerate()
+ .map(|(i, v)| {
+ v.as_str().map(str::to_string).ok_or_else(|| bad(cmd, format!("`{k}` must list names; the entry {} is {}", i + 1, json_brief(v))))
+ })
+ .collect()
+ }
+ Some(v) => Err(bad(cmd, format!("`{k}` must be a list of names; it is {}", json_brief(v)))),
+ }
+}
+
+/// A list of keys, where an entry is a name or an id: a feature can be named or numbered, and
+/// both kinds can sit in one list.
+///
+/// A value of the wrong kind is refused, and so is an entry that is neither a name nor an id,
+/// named by its position as in [`string_list`]. The commands that take feature keys read them
+/// here, because their list is not a list of names (#6651).
+pub fn name_or_id_list(cmd: &str, p: &Value, k: &str) -> Result<Vec<String>> {
+ match p.get(k) {
+ None | Some(Value::Null) => Ok(Vec::new()),
+ Some(Value::String(s)) => Ok(vec![s.clone()]),
+ Some(Value::Array(a)) => {
+ if a.len() > MAX_STRING_LIST {
+ return Err(bad(cmd, format!("`{k}` must list at most {MAX_STRING_LIST} keys")));
+ }
+ a.iter()
+ .enumerate()
+ .map(|(i, v)| match v {
+ Value::String(s) => Ok(s.clone()),
+ Value::Number(n) if n.is_u64() => Ok(n.to_string()),
+ other => Err(bad(cmd, format!("`{k}` must list names or ids; the entry {} is {}", i + 1, json_brief(other)))),
+ })
+ .collect()
+ }
+ Some(v) => Err(bad(cmd, format!("`{k}` must be a list of names or ids; it is {}", json_brief(v)))),
+ }
+}
+
+/// A list of names read leniently: a value of the wrong kind reads as an empty list, and an
+/// entry that is not a name is dropped.
+///
+/// Only for the parameters where an empty list is harmless: a preview that cannot fail, and a
+/// list of ids that names nothing to act on. A command that acts on bodies reads its lists
+/// with [`string_list`], so a wrong type is refused there.
+pub fn string_list_or_default(p: &Value, k: &str) -> Vec<String> {
match p.get(k) {
- Some(Value::Array(a)) => a.iter().take(10_000).filter_map(|v| v.as_str().map(str::to_string)).collect(),
+ Some(Value::Array(a)) => a.iter().take(MAX_STRING_LIST).filter_map(|v| v.as_str().map(str::to_string)).collect(),
Some(Value::String(s)) => vec![s.clone()],
_ => Vec::new(),
}
}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ const CMD: &str = "solid.test";
+
+ fn list(p: &Value) -> Result<Vec<String>> {
+ string_list(CMD, p, "bodies")
+ }
+
+ fn refused(p: &Value) -> EngineError {
+ list(p).expect_err("the parameter is refused")
+ }
+
+ fn keys(p: &Value) -> Result<Vec<String>> {
+ name_or_id_list(CMD, p, "features")
+ }
+
+ #[test]
+ fn a_missing_parameter_is_an_empty_list() {
+ assert_eq!(list(&json!({})).unwrap(), Vec::<String>::new());
+ }
+
+ #[test]
+ fn null_is_an_empty_list_as_the_schema_contract_says() {
+ // The contract declares these parameters optional: `null` is absent, as for `str_`.
+ assert_eq!(list(&json!({"bodies": null})).unwrap(), Vec::<String>::new());
+ }
+
+ #[test]
+ fn a_list_of_names_is_read_as_it_is() {
+ assert_eq!(list(&json!({"bodies": ["Base", "Other"]})).unwrap(), ["Base", "Other"]);
+ assert_eq!(list(&json!({"bodies": []})).unwrap(), Vec::<String>::new());
+ }
+
+ #[test]
+ fn a_single_name_is_read_as_a_list_of_one() {
+ assert_eq!(list(&json!({"bodies": "Base"})).unwrap(), ["Base"]);
+ }
+
+ #[test]
+ fn a_value_of_the_wrong_kind_is_refused() {
+ for value in [json!(42), json!(true), json!({"body": "Base"}), json!([["Base"]])] {
+ let err = refused(&json!({"bodies": value.clone()}));
+ assert!(matches!(&err, EngineError::BadParams { cmd, msg } if cmd == CMD && msg.contains("bodies")), "{value}: {err}");
+ }
+ }
+
+ #[test]
+ fn an_entry_that_is_not_a_name_is_refused() {
+ for value in [json!(["Base", 7]), json!(["Base", null]), json!(["Base", {"body": "Base"}]), json!(["Base", ["Base"]])] {
+ let err = refused(&json!({"bodies": value.clone()}));
+ assert!(matches!(&err, EngineError::BadParams { cmd, msg } if cmd == CMD && msg.contains("bodies")), "{value}: {err}");
+ }
+ }
+
+ #[test]
+ fn the_entry_that_is_not_a_name_is_named_by_its_position() {
+ let err = refused(&json!({"bodies": ["Base", "Other", 7]}));
+ let EngineError::BadParams { msg, .. } = &err else {
+ panic!("{err}");
+ };
+ assert!(msg.contains("bodies") && msg.contains("3") && msg.contains("7"), "{err}");
+ }
+
+ #[test]
+ fn a_list_of_the_maximum_length_is_read_and_a_longer_one_is_refused() {
+ let names: Vec<String> = (0..MAX_STRING_LIST).map(|i| format!("Body{i}")).collect();
+ assert_eq!(list(&json!({"bodies": names.clone()})).unwrap().len(), MAX_STRING_LIST);
+ let mut too_many = names;
+ too_many.push("OneMore".to_string());
+ let err = refused(&json!({"bodies": too_many}));
+ assert!(matches!(&err, EngineError::BadParams { cmd, .. } if cmd == CMD), "{err}");
+ }
+
+ #[test]
+ fn the_lenient_reader_drops_what_it_cannot_read() {
+ assert_eq!(string_list_or_default(&json!({"bodies": 7}), "bodies"), Vec::<String>::new());
+ assert_eq!(string_list_or_default(&json!({"bodies": ["Base", 7]}), "bodies"), ["Base"]);
+ assert_eq!(string_list_or_default(&json!({"bodies": "Base"}), "bodies"), ["Base"]);
+ }
+
+ #[test]
+ fn a_list_of_names_or_ids_is_read_in_the_order_given() {
+ assert_eq!(keys(&json!({"features": ["Base", 3]})).unwrap(), ["Base", "3"]);
+ assert_eq!(keys(&json!({"features": [3, "Base"]})).unwrap(), ["3", "Base"]);
+ assert_eq!(keys(&json!({"features": "Base"})).unwrap(), ["Base"]);
+ assert_eq!(keys(&json!({})).unwrap(), Vec::<String>::new());
+ }
+
+ #[test]
+ fn an_entry_that_is_neither_a_name_nor_an_id_is_refused() {
+ for value in [json!(true), json!({"id": 3}), json!(["Base"]), json!(3.5), json!(-1)] {
+ let err = keys(&json!({"features": [value.clone()]})).expect_err("the entry is refused");
+ assert!(matches!(&err, EngineError::BadParams { cmd, msg } if cmd == CMD && msg.contains("features")), "{value}: {err}");
+ }
+ }
+
+ #[test]
+ fn a_list_of_keys_of_the_wrong_kind_is_refused() {
+ for value in [json!(42), json!(true), json!({"body": "Base"})] {
+ let err = keys(&json!({"features": value.clone()})).expect_err("the parameter is refused");
+ assert!(matches!(&err, EngineError::BadParams { cmd, msg } if cmd == CMD && msg.contains("features")), "{value}: {err}");
+ }
+ }
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 0b2625834a..94e94ef83b 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -894,6 +894,33 @@ fn hostile_params_never_panic() {
assert!(internal.is_empty(), "commands panicked:\n{}", internal.join("\n"));
}
+/// #6651: a list parameter of the wrong type is refused, not read as an empty list. An empty
+/// list means "every body" to most commands, so a number, an object or a list with a number in
+/// it was read as no list at all: a cut meant for one body cut every body it touched, and the
+/// command reported success.
+///
+/// `null` is not in this list: the schema contract declares these parameters optional and
+/// reads `null` as absent, so it keeps the meaning it always had (no list given).
+#[test]
+fn a_list_parameter_of_the_wrong_type_is_refused() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"corner": [0, 0, 0], "length": 40, "width": 30, "height": 10, "body_name": "Plate"}));
+ run(&mut s, "solid.box", json!({"corner": [60, 0, 0], "length": 10, "width": 10, "height": 20, "body_name": "Block"}));
+ let before = volume(&mut s);
+ // A tool crossing both bodies, meant for the Block only.
+ for targets in [json!(7), json!(true), json!({"body": "Block"}), json!(["Block", 42])] {
+ let params =
+ json!({"corner": [35, 2, -1], "length": 30, "width": 3, "height": 30, "operation": "cut", "body_name": "Slot", "targets": targets});
+ let err = s.execute("solid.box", &params).expect_err("a list parameter of the wrong type is refused");
+ let EngineError::BadParams { cmd, msg } = &err else {
+ panic!("{params}: {err}");
+ };
+ assert_eq!(cmd, "solid.box", "{params}: {err}");
+ assert!(msg.contains("targets"), "{params}: {err}");
+ assert_eq!(volume(&mut s), before, "{params}: the design changed");
+ }
+}
+
#[test]
fn registry_is_consistent() {
let specs = command_specs();