SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: the parameter commands and Evaluate Expression describe their exact parameters and reply (#12497) (#12590)
PeppaWutzdc679cae34fb
diff --git a/crates/engine/src/cmd/parameters.rs b/crates/engine/src/cmd/parameters.rsindex 583b0f1e2d..d19fc98685 100644--- a/crates/engine/src/cmd/parameters.rs+++ b/crates/engine/src/cmd/parameters.rs@@ -10,8 +10,11 @@ use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solveuse super::{CommandSpec, sketch_store};use crate::params::{bad, bool_, str_};use crate::schema::parameters::{- AddedValue, ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams,- ParamMoved, ParamNameParams, ParamRenameParams, ParamRenamed,+ AddedValue, Completion, CompletionKind, DrivenFeature, EvalKind, ExprCompleteParams, ExprCompletions, ExprEvaluateParams, ExprEvaluated,+ ExprEvaluatedBody, FailedFeature, ParamAddParams, ParamAdded, ParamChangeParams, ParamChanged, ParamChangedBody, ParamChangedOne,+ ParamCommentParams, ParamCommented, ParamDeleted, ParamExportParams, ParamExportResult, ParamFavoriteParams, ParamFavorited, ParamGraphParams,+ ParamGraphResult, ParamImportParams, ParamImportResult, ParamListParams, ParamListResult, ParamMoveParams, ParamMoved, ParamNameParams,+ ParamRename, ParamRenameParams, ParamRenamed, ParamUsersParams, ParamUsersResult, ParameterRow, ParameterUser, SwitchedFeature,};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};@@ -22,9 +25,22 @@ const NAME_CONTRACT: TypedContract<ParamNameParams> = TypedContract::new();const COMMENT_CONTRACT: TypedContract<ParamCommentParams> = TypedContract::new();const FAVORITE_CONTRACT: TypedContract<ParamFavoriteParams> = TypedContract::new();const MOVE_CONTRACT: TypedContract<ParamMoveParams> = TypedContract::new();+const CHANGE_CONTRACT: TypedContract<ParamChangeParams> = TypedContract::new();+const LIST_CONTRACT: TypedContract<ParamListParams> = TypedContract::new();+const USERS_CONTRACT: TypedContract<ParamUsersParams> = TypedContract::new();+const GRAPH_CONTRACT: TypedContract<ParamGraphParams> = TypedContract::new();+const EXPORT_CONTRACT: TypedContract<ParamExportParams> = TypedContract::new();+const IMPORT_CONTRACT: TypedContract<ParamImportParams> = TypedContract::new();+const EVALUATE_CONTRACT: TypedContract<ExprEvaluateParams> = TypedContract::new();+const COMPLETE_CONTRACT: TypedContract<ExprCompleteParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("parameters.change", "Change Parameters", change_param).at("SOLID", "MODIFY").icon("params").params(+ CommandSpec::new("parameters.change", "Change Parameters", crate::checked!("parameters.change", change_param))+ .at("SOLID", "MODIFY")+ .icon("params")+ .contract(&CHANGE_CONTRACT)+ .output(output_schema_for::<ParamChanged>)+ .params("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, \@@ -34,7 +50,13 @@ pub static COMMANDS: &[CommandSpec] = &[(the configuration rules that switch a feature's suppression and read a parameter whose value changed run in their order, as on \activation; driven parameters and restrictions wait for a configuration edit or activation)",),- CommandSpec::new("parameters.list", "List Parameters", list).icon("list").noundo().doc_only().params(+ CommandSpec::new("parameters.list", "List Parameters", crate::checked!("parameters.list", list))+ .icon("list")+ .noundo()+ .doc_only()+ .contract(&LIST_CONTRACT)+ .output(output_schema_for::<ParamListResult>)+ .params("favorites?: bool (only favourites), filter?: all|user|sketch|feature|favorites → parameters (name, expression, unit, value (mm/deg in every \reply), display_value (in its own unit), source, feature/input, comment, favorite, uses, used_by, error) and cycles",),@@ -68,30 +90,42 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&COMMENT_CONTRACT).output(output_schema_for::<ParamCommented>).params("name, comment"),- CommandSpec::new("parameters.users", "Parameter Users", users)+ CommandSpec::new("parameters.users", "Parameter Users", crate::checked!("parameters.users", users)).icon("graph").noundo()+ .contract(&USERS_CONTRACT)+ .output(output_schema_for::<ParamUsersResult>).params("name → users (parameters, feature inputs, dimensions) and the features it drives"),- CommandSpec::new("parameters.graph", "Parameter Graph", graph)+ CommandSpec::new("parameters.graph", "Parameter Graph", crate::checked!("parameters.graph", graph)).icon("graph").noundo()+ .contract(&GRAPH_CONTRACT)+ .output(output_schema_for::<ParamGraphResult>).params("→ nodes, edges [user, used] (users include Feature:<name>), cycles, errors"),- CommandSpec::new("parameters.export", "Export Parameters", export)+ CommandSpec::new("parameters.export", "Export Parameters", crate::checked!("parameters.export", export)).icon("export").noundo()+ .contract(&EXPORT_CONTRACT)+ .output(output_schema_for::<ParamExportResult>).params("format?: csv|json (default csv, or from the path), path?: write to a file → text"),- CommandSpec::new("parameters.import", "Import Parameters", import)+ CommandSpec::new("parameters.import", "Import Parameters", crate::checked!("parameters.import", import)).icon("import")+ .contract(&IMPORT_CONTRACT)+ .output(output_schema_for::<ParamImportResult>).params("text: CSV (header with name, expression, unit?, comment?) or JSON [{name, expression, unit?, comment?}] | path; all or nothing"),- CommandSpec::new("expr.evaluate", "Evaluate Expression", evaluate)+ CommandSpec::new("expr.evaluate", "Evaluate Expression", crate::checked!("expr.evaluate", evaluate)).icon("params").noundo().doc_only()+ .contract(&EVALUATE_CONTRACT)+ .output(output_schema_for::<ExprEvaluated>).params("expression, kind?: length|angle|unitless (or unit?: mm|in|deg…; text: the text a text parameter would hold, as `text`) → ok, value (mm/rad), display_value, references, error"),- CommandSpec::new("parameters.complete", "Complete Expression", complete)+ CommandSpec::new("parameters.complete", "Complete Expression", crate::checked!("parameters.complete", complete)).icon("params").noundo().doc_only()+ .contract(&COMPLETE_CONTRACT)+ .output(output_schema_for::<ExprCompletions>).params("prefix?: the text before the cursor → word, suggestions [{text, kind: parameter|function|unit|constant, detail}]"),];@@ -108,8 +142,8 @@ fn param_name<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {}/// Features that fail (name and error).-fn failing(s: &Session) -> Vec<Value> {- s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect()+fn failing(s: &Session) -> Vec<FailedFeature> {+ FailedFeature::of(&s.model.results)}pub(super) fn known(s: &Session, name: &str) -> bool {@@ -130,19 +164,20 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {if let Some(n) = str_(p, "delete") {s.doc_mut().remove_param(n.trim())?;s.settle_value_edit(&solved)?;- return Ok(json!({"deleted": n.trim()}));+ return reply(cmd, ParamChanged { body: ParamChangedBody::Deleted { deleted: n.trim().to_string() }, param_warnings: Vec::new() });}let mut name = param_name(cmd, p)?.to_string();- let mut out = json!({});+ let mut renamed: Option<ParamRename> = None;+ let mut changed_through: Option<String> = None;if let Some(new) = str_(p, "new_name") {let n = s.doc_mut().rename_param(&name, new)?;- out["renamed"] = json!({"from": name, "to": new.trim(), "references_updated": n});+ renamed = Some(ParamRename { from: name, to: new.trim().to_string(), references_updated: n });name = new.trim().to_string();}let has_expr = p.get("expression").is_some() || p.get("value").is_some();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() {+ } else if 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"));@@ -151,7 +186,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {// `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() {+ if renamed.is_some() {return Err(bad(cmd, format!("`{new} = …` renames `{name}` already: give `new_name` or `name = expression`, not both")));}if rhs.is_empty() {@@ -162,7 +197,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {// `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);+ changed_through = Some(name);name = new.clone();}if new != name {@@ -170,7 +205,7 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {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});+ renamed = Some(ParamRename { from: name, to: new.clone(), references_updated: n });name = new;}e = Some(rhs);@@ -197,20 +232,20 @@ fn change_param(s: &mut Session, p: &Value) -> Result<Value> {}s.settle_value_edit(&solved)?;let (vals, _) = s.doc.param_values();- if !switched.is_empty() {- out["switched"] = json!(switched);- }- out["name"] = json!(name);- out["expression"] = json!(e);- if let Some(t) = s.doc.text_param(&name) {- out["text"] = json!(t.text);- }- out["value"] = json!(vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))));- out["display_value"] = json!(s.doc.param_display_value(&vals, &name).map(expr::round_reported));- out["recomputed"] = json!(s.model.last_recomputed);- out["restored"] = json!(s.model.last_restored);- out["errors"] = json!(failing(s));- Ok(out)+ let one = ParamChangedOne {+ renamed,+ changed_through,+ switched,+ text: s.doc.text_param(&name).map(|t| t.text.clone()),+ value: vals.get(&name).map(|v| expr::round_reported(expr::reported_value(*v))),+ display_value: s.doc.param_display_value(&vals, &name).map(expr::round_reported),+ recomputed: s.model.last_recomputed,+ restored: s.model.last_restored,+ errors: failing(s),+ name,+ expression: e,+ };+ reply(cmd, ParamChanged { body: ParamChangedBody::One(Box::new(one)), param_warnings: Vec::new() })}/// The point a length dimension keeps when its value changes: the first it measures from (a@@ -308,19 +343,15 @@ fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -}s.settle_value_edit(solved)?;let (vals, _) = s.doc.param_values();- let values: serde_json::Map<String, Value> =- list.iter().map(|(n, _)| (n.clone(), json!(vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v)))))).collect();- let mut out = json!({"changed": values, "recomputed": s.model.last_recomputed, "restored": s.model.last_restored, "errors": failing(s)});- if !switched.is_empty() {- out["switched"] = json!(switched);- }- Ok(out)+ let changed = list.iter().map(|(n, _)| (n.clone(), vals.get(n).map(|v| expr::round_reported(expr::reported_value(*v))))).collect();+ let body = ParamChangedBody::Many { changed, recomputed: s.model.last_recomputed, restored: s.model.last_restored, errors: failing(s), switched };+ reply(cmd, ParamChanged { body, param_warnings: Vec::new() })}/// The configuration rules that switch a feature's suppression and read a parameter this edit/// changed (`Document::apply_suppression_rules`), applied before the design is rebuilt, so that/// one rebuild has them: `[{feature, name, suppressed}]` for each feature they switched.-fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String, expr::Value>) -> Vec<Value> {+fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String, expr::Value>) -> Vec<SwitchedFeature> {if s.doc.configs.rules.is_empty() {return Vec::new();}@@ -329,12 +360,13 @@ fn switch_by_rules(s: &mut Session, before: &std::collections::BTreeMap<String,.into_iter().map(|(id, suppressed)| {let name = s.doc.features.iter().find(|f| f.id == id).map(|f| f.name.clone());- json!({"feature": id, "name": name, "suppressed": suppressed})+ SwitchedFeature { feature: id, name, suppressed }}).collect()}fn list(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "parameters.list";let filter = match (bool_(p, "favorites"), str_(p, "filter")) {(Some(true), _) => "favorites".to_string(),(_, Some(f)) => f.to_ascii_lowercase(),@@ -354,7 +386,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {// Favourites first; otherwise the table order (user, sketch, feature).rows.sort_by_key(|r| !r.favorite);let cycles = solidcraft_doc::cycles(&s.doc.all_param_exprs());- Ok(json!({"parameters": rows, "count": rows.len(), "cycles": cycles}))+ let count = rows.len();+ let parameters = rows.into_iter().map(ParameterRow::from).collect();+ reply(cmd, ParamListResult { parameters, count, cycles: cycles.into_iter().collect(), param_warnings: Vec::new() })}fn add(s: &mut Session, p: &Value) -> Result<Value> {@@ -438,17 +472,24 @@ fn users(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, format!("no parameter `{name}`")));}let users = s.doc.param_users(name);- let drives: Vec<Value> =- s.doc.features_using_param(name).iter().filter_map(|id| s.doc.feature(*id)).map(|f| json!({"id": f.id, "name": f.name})).collect();- Ok(json!({"name": name, "users": users, "drives": drives}))+ let users = users.into_iter().map(ParameterUser::from).collect();+ let drives = s+ .doc+ .features_using_param(name)+ .iter()+ .filter_map(|id| s.doc.feature(*id))+ .map(|f| DrivenFeature { id: f.id, name: f.name.clone() })+ .collect();+ reply(cmd, ParamUsersResult { name: name.to_string(), users, drives, param_warnings: Vec::new() })}fn graph(s: &mut Session, _p: &Value) -> Result<Value> {+ let cmd = "parameters.graph";let (_, errs) = s.doc.param_values();let nodes: Vec<String> = s.doc.param_defs().into_iter().map(|d| d.name).collect();let edges: Vec<[String; 2]> = s.doc.param_graph().into_iter().map(|(a, b)| [a, b]).collect();let cycles = solidcraft_doc::cycles(&s.doc.all_param_exprs());- Ok(json!({"nodes": nodes, "edges": edges, "cycles": cycles, "errors": errs}))+ reply(cmd, ParamGraphResult { nodes, edges, cycles: cycles.into_iter().collect(), errors: errs, param_warnings: Vec::new() })}fn export(s: &mut Session, p: &Value) -> Result<Value> {@@ -477,7 +518,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {if let Some(path) = path {solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;}- Ok(json!({"format": format, "path": path, "text": text}))+ reply(cmd, ParamExportResult { format, path: path.map(str::to_string), text, param_warnings: Vec::new() })}/// Largest parameter table we read from a file.@@ -495,7 +536,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {let solved = s.solved_sketches();let names = s.doc_mut().import_params(&text)?;s.settle_value_edit(&solved)?;- Ok(json!({"imported": names, "errors": failing(s)}))+ reply(cmd, ParamImportResult { imported: names, errors: failing(s), param_warnings: Vec::new() })}fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {@@ -504,7 +545,8 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {let unit = str_(p, "unit");// A text parameter's expression is its text.if unit.is_some_and(solidcraft_doc::text_params::is_text_unit) {- return Ok(json!({"ok": true, "kind": "text", "text": solidcraft_doc::text_params::unquote(&e), "references": []}));+ let body = ExprEvaluatedBody::Text { ok: true, kind: "text".into(), text: solidcraft_doc::text_params::unquote(&e), references: Vec::new() };+ return reply(cmd, ExprEvaluated { body, param_warnings: Vec::new() });}if let Some(u) = unit&& expr::unit_info(u).is_none()@@ -531,7 +573,7 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {});// `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 {+ let body = match r {Ok((v, k)) => {let value = match k {Kind::Length => expr::Value::length(v),@@ -543,17 +585,27 @@ fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {(None, Kind::Angle) => v.to_degrees(),(None, _) => v,};- json!({"ok": true, "value": expr::round_reported(v), "kind": k, "display_value": expr::round_reported(shown), "references": refs})+ ExprEvaluatedBody::Value {+ ok: true,+ value: expr::round_reported(v),+ kind: EvalKind::from(k),+ display_value: expr::round_reported(shown),+ references: refs,+ defines: defines.map(str::to_string),+ }}- Err(err) => json!({"ok": false, "error": err.to_string().trim_start_matches("expression: ").to_string(), "references": refs}),+ Err(err) => ExprEvaluatedBody::Failed {+ ok: false,+ error: err.to_string().trim_start_matches("expression: ").to_string(),+ references: refs,+ defines: defines.map(str::to_string),+ },};- if let Some(name) = defines {- out["defines"] = json!(name);- }- Ok(out)+ reply(cmd, ExprEvaluated { body, param_warnings: Vec::new() })}fn complete(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "parameters.complete";let text = str_(p, "prefix").unwrap_or("");// The identifier being typed: trailing letters, digits and underscores.let word: String = text.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<Vec<_>>().into_iter().rev().collect();@@ -565,7 +617,7 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {// start.let contains = |n: &str| word.is_empty() || n.to_ascii_lowercase().contains(&lower);let within = |n: &str| contains(n) || solidcraft_doc::name_words_match(n, &word);- let mut out: Vec<Value> = Vec::new();+ let mut out: Vec<Completion> = Vec::new();let mut rows: Vec<solidcraft_doc::ParamRow> = s.doc.param_rows().into_iter().filter(|r| within(&r.name)).collect();// Names that start with the word, then names that contain it, then names matched only by// the starts of their words; within each, favourites, then user parameters, then the others.@@ -580,22 +632,22 @@ fn complete(s: &mut Session, p: &Value) -> Result<Value> {if !r.comment.is_empty() {detail.push_str(&format!(" — {}", r.comment));}- out.push(json!({"text": r.name, "kind": "parameter", "detail": detail}));+ out.push(Completion { text: r.name, kind: CompletionKind::Parameter, detail });}for (f, sig) in expr::FUNCTIONS {if starts(f) {- out.push(json!({"text": format!("{f}("), "kind": "function", "detail": sig}));+ out.push(Completion { text: format!("{f}("), kind: CompletionKind::Function, detail: sig.to_string() });}}if starts("pi") {- out.push(json!({"text": "pi", "kind": "constant", "detail": "3.14159…"}));+ out.push(Completion { text: "pi".into(), kind: CompletionKind::Constant, detail: "3.14159…".into() });}for (u, k, _) in expr::UNITS {if !word.is_empty() && starts(u) {- out.push(json!({"text": u, "kind": "unit", "detail": k}));+ out.push(Completion { text: u.to_string(), kind: CompletionKind::Unit, detail: EvalKind::from(*k).word().to_string() });}}- Ok(json!({"word": word, "suggestions": out}))+ reply(cmd, ExprCompletions { word, suggestions: out, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/schema/parameters.rs b/crates/engine/src/schema/parameters.rsindex 01450f844d..b011bc74a0 100644--- a/crates/engine/src/schema/parameters.rs+++ b/crates/engine/src/schema/parameters.rs@@ -1,17 +1,23 @@-//! Contracts and result types for the commands in `cmd/parameters.rs` that manage the design's-//! user parameters by name (#11941): `parameters.add`, `.rename`, `.delete`, `.comment`,-//! `.favorite` and `.move`.+//! Contracts and result types for the commands in `cmd/parameters.rs`: those that manage the+//! design's user parameters by name (#11941), `parameters.add`, `.rename`, `.delete`, `.comment`,+//! `.favorite` and `.move`, and the rest (#12497): `parameters.change`, `.list`, `.users`,+//! `.graph`, `.export`, `.import`, `.complete` and `expr.evaluate`.//!//! The handlers read their parameters from the raw JSON, so each key here reads as its handler//! reads it and fails with the handler's message. Whether a parameter exists, and whether a new//! name, unit or expression is valid, stays the document's to check, with its messages.-use schemars::{JsonSchema, Schema};+use std::borrow::Cow;+use std::collections::BTreeMap;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};use serde::de::Error as _;use serde::{Deserialize, Deserializer, Serialize};-use serde_json::Value;+use serde_json::{Map, Value, json};+use solidcraft_doc::expr::Kind;+use solidcraft_doc::{ParamRow, ParamUser};-use super::check::whole;+use super::check::{located, whole};/// A parameter's name, as `cmd/parameters.rs`'s `param_name` reads `name`: text that isn't blank,/// with its message for anything else. Spaces at either end are dropped.@@ -296,6 +302,854 @@ pub struct ParamMoved {pub param_warnings: Vec<String>,}+// ---------------------------------------------------------------------------------------------+// #12497: `parameters.change`, `.list`, `.users`, `.graph`, `.export`, `.import`, `.complete`+// and `expr.evaluate`.+// ---------------------------------------------------------------------------------------------++/// Adds `key` to the schema's `required` list: for a key the type has optional so that the+/// handler, not the check, refuses it when it's left out.+fn require(schema: &mut Schema, key: &str) {+ match schema.get_mut("required") {+ Some(Value::Array(required)) => {+ if !required.iter().any(|k| k == key) {+ required.push(key.into());+ }+ }+ _ => {+ schema.insert("required".into(), Value::Array(vec![key.into()]));+ }+ }+}++/// `key` as text: `null` is left out, as `str_` reads it. Anything else is refused, though the+/// handler would read it as left out; `message` is the handler's for that case, if it has one.+fn text_or_null<'de, D: Deserializer<'de>>(d: D, message: &str) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::String(s) => Ok(Some(s)),+ _ => Err(D::Error::custom(whole(message))),+ }+}++/// What `parameters.change` takes, in the form it's read in: see [`ParamChangeParams`].+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = change_forms)]+pub struct ParamChangeKeys {+ /// Several existing parameters at once, `{name: expression}`: they are checked together and+ /// the design is rebuilt once, all or nothing. Renaming isn't done this way. When given,+ /// no other key is read.+ #[serde(default, deserialize_with = "changes_map", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "changes_schema")]+ pub changes: Option<Map<String, Value>>,+ /// Delete this user parameter (refused while something uses it). When given as text, no+ /// other key but `changes` is read.+ #[serde(default, deserialize_with = "delete_text")]+ pub delete: Option<String>,+ /// The parameter to change, by name: a user parameter, a sketch dimension or a feature's+ /// named input. Spaces at either end are dropped.+ #[serde(default, deserialize_with = "change_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String", length(min = 1))]+ pub name: Option<String>,+ /// The new value: a number, or an expression as text (`25 mm`, `W / 2`). A text+ /// parameter's expression is its text, quotes round it optional. `name = value` renames+ /// the parameter to `name` and sets the value (or sets `name` when the value is just+ /// `name`). Needed unless `new_name`, `favorite` or `comment` is given.+ #[serde(default, deserialize_with = "expression")]+ #[schemars(schema_with = "expression_schema")]+ pub expression: Option<Value>,+ /// Another name for `expression`, read when `expression` isn't a number or text.+ #[serde(default, deserialize_with = "expression")]+ #[schemars(schema_with = "expression_schema")]+ pub value: Option<Value>,+ /// The unit: `mm`, `cm`, `m`, `in`, `ft`, `deg`, `rad`, `""` (no unit) or `text`. Default:+ /// the parameter's own, or for a new one its value's unit, a length in the design's units.+ #[serde(default, deserialize_with = "unit_text")]+ pub unit: Option<String>,+ /// A note to show with the parameter.+ #[serde(default, deserialize_with = "comment_key")]+ pub comment: Option<String>,+ /// List it with the favourites, first, or not.+ #[serde(default, deserialize_with = "favorite_flag")]+ pub favorite: Option<bool>,+ /// Rename the parameter: the expressions, feature inputs and dimensions that use it follow.+ /// With an `expression` the new value is set too.+ #[serde(default, deserialize_with = "new_name_key")]+ pub new_name: Option<String>,+}++fn changes_map<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Map<String, Value>>, D::Error> {+ let Value::Object(map) = Value::deserialize(d)? else {+ return Err(D::Error::custom(whole("`changes` must be an object of name: expression")));+ };+ if map.is_empty() {+ return Err(D::Error::custom(whole("`changes` is empty")));+ }+ for (name, e) in &map {+ // `expr_arg`: text, or a number.+ if !matches!(e, Value::String(_) | Value::Number(_)) {+ return Err(D::Error::custom(whole(format!("`changes.{name}` must be a number or text"))));+ }+ }+ Ok(Some(map))+}++fn changes_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Several existing parameters at once, `{name: expression}`: they are checked together and the design is rebuilt once, all or nothing. Renaming isn't done this way (`name = value` is refused). When given, no other key is read.",+ "type": "object",+ "minProperties": 1,+ "additionalProperties": {"type": ["number", "string"]}+ })+}++fn delete_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`delete` must be text")+}++fn unit_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`unit` must be text")+}++fn comment_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`comment` must be text")+}++fn new_name_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`new_name` must be text")+}++fn favorite_flag<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::Bool(b) => Ok(Some(b)),+ _ => Err(D::Error::custom(whole("`favorite` must be true or false"))),+ }+}++/// `name` of a single change, as `param_name` reads it: text that isn't blank, `null` included+/// in what is refused.+fn change_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ param_name(d).map(Some)+}++/// `parameters.change` takes one of three forms: `changes`, `delete` or `name` with what to+/// change about it.+fn change_forms(schema: &mut Schema) {+ let name_with = json!({+ "required": ["name"],+ "properties": {"name": {"type": "string"}},+ "anyOf": [+ {"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},+ {"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}},+ {"required": ["new_name"]},+ {"required": ["favorite"]},+ {"required": ["comment"]}+ ]+ });+ schema.insert(+ "anyOf".into(),+ json!([+ {"required": ["changes"]},+ {"required": ["delete"], "properties": {"delete": {"type": "string"}}},+ name_with+ ]),+ );+}++/// Change a parameter: set its expression, unit, comment or favourite, rename it (references+/// follow), delete it, or set several existing parameters at once. The design is rebuilt once+/// and the features that changed are named in the reply. One undo step.+///+/// The handler reads `changes` alone when it is given, else `delete` alone when that is text,+/// else the keys of a single change; the keys of a form it doesn't read are left unchecked.+#[derive(Debug)]+pub struct ParamChangeParams(pub ParamChangeKeys);++impl<'de> Deserialize<'de> for ParamChangeParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if let Some(keys) = value.as_object_mut() {+ let only = if keys.contains_key("changes") {+ Some("changes")+ } else if matches!(keys.get("delete"), Some(Value::String(_))) {+ Some("delete")+ } else {+ None+ };+ // Otherwise a single change: `changes` isn't there, and `delete` isn't text.+ if let Some(only) = only {+ keys.retain(|k, _| k == only || !CHANGE_KEYS.contains(&k.as_str()));+ }+ // `value` is read only when `expression` isn't a number or text.+ else if matches!(keys.get("expression"), Some(Value::String(_) | Value::Number(_))) {+ keys.remove("value");+ }+ }+ serde_path_to_error::deserialize(&value).map(ParamChangeParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++const CHANGE_KEYS: [&str; 9] = ["changes", "delete", "name", "expression", "value", "unit", "comment", "favorite", "new_name"];++impl JsonSchema for ParamChangeParams {+ fn schema_name() -> Cow<'static, str> {+ "ParamChangeParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ ParamChangeKeys::json_schema(generator)+ }+}++/// A feature that failed to rebuild: its name and error.+#[derive(Debug, Serialize, JsonSchema)]+pub struct FailedFeature {+ /// The feature's name.+ pub feature: String,+ /// Why it failed.+ pub error: String,+}++impl FailedFeature {+ /// The features of `results` that failed.+ pub fn of(results: &[solidcraft_doc::FeatureResult]) -> Vec<FailedFeature> {+ results.iter().filter_map(|r| r.error.as_ref().map(|e| FailedFeature { feature: r.name.clone(), error: e.clone() })).collect()+ }+}++/// A feature a configuration rule switched on or off.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SwitchedFeature {+ /// The feature's id.+ pub feature: u64,+ /// Its name; `null` if it is gone.+ pub name: Option<String>,+ /// Whether it is suppressed now.+ pub suppressed: bool,+}++/// A parameter that was renamed.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamRename {+ /// The old name.+ pub from: String,+ /// The new name.+ pub to: String,+ /// How many expressions, feature inputs and dimensions were changed to use the new name.+ pub references_updated: usize,+}++/// What `parameters.change` returns: one of three shapes, by what was asked.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamChanged {+ #[serde(flatten)]+ pub body: ParamChangedBody,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// The shapes of a `parameters.change` reply.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum ParamChangedBody {+ /// A parameter was deleted (`delete`).+ Deleted {+ /// The deleted parameter's name.+ deleted: String,+ },+ /// Several parameters were set (`changes`).+ Many {+ /// Each changed parameter's value, in mm for a length and degrees for an angle; `null`+ /// where it can't be worked out.+ changed: BTreeMap<String, Option<f64>>,+ /// How many features were rebuilt.+ recomputed: usize,+ /// How many features reused an earlier result for the same inputs (a value set back).+ restored: usize,+ /// The features that failed to rebuild.+ errors: Vec<FailedFeature>,+ /// The features the configuration rules switched, when they did.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ switched: Vec<SwitchedFeature>,+ },+ /// One parameter was changed.+ One(Box<ParamChangedOne>),+}++/// What changing one parameter returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamChangedOne {+ /// Set when the parameter was renamed (`new_name`, or `name = expression`).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub renamed: Option<ParamRename>,+ /// Set when `name = expression` set the parameter that the changed value's expression named:+ /// the name asked for.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub changed_through: Option<String>,+ /// The features the configuration rules switched, when they did.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub switched: Vec<SwitchedFeature>,+ /// The parameter's name now.+ pub name: String,+ /// The expression it has now; `null` when only its name, comment or favourite changed.+ pub expression: Option<String>,+ /// A text parameter's text.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+ /// Its value in mm for a length and degrees for an angle, as in every reply; `null` if it+ /// can't be worked out.+ pub value: Option<f64>,+ /// Its value in its own unit; `null` if it can't be worked out.+ pub display_value: Option<f64>,+ /// How many features were rebuilt.+ pub recomputed: usize,+ /// How many features reused an earlier result for the same inputs (a value set back).+ pub restored: usize,+ /// The features that failed to rebuild.+ pub errors: Vec<FailedFeature>,+}++/// List the parameters: the user's, the sketch dimensions' and the feature inputs', favourites+/// first, with each one's expression, value, uses and users, and any cycles. Changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ParamListKeys {+ /// Only the favourites. When true, `filter` isn't read. Default: false.+ #[serde(default, deserialize_with = "list_favorites")]+ pub favorites: Option<bool>,+ /// Which parameters, ignoring case: `all`, `user`, `sketch` (dimensions), `feature` (inputs),+ /// `model` (every one but the user's) or `favorites`. Anything else lists all. Default: all.+ #[serde(default, deserialize_with = "list_filter")]+ pub filter: Option<String>,+}++fn list_favorites<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::Bool(b) => Ok(Some(b)),+ _ => Err(D::Error::custom(whole("`favorites` must be true or false"))),+ }+}++fn list_filter<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`filter` must be text")+}++/// `parameters.list`'s parameters: [`ParamListKeys`], with `filter` left unread when+/// `favorites` is true, as the handler leaves it.+#[derive(Debug)]+pub struct ParamListParams(pub ParamListKeys);++impl<'de> Deserialize<'de> for ParamListParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if let Some(keys) = value.as_object_mut().filter(|o| o.get("favorites") == Some(&Value::Bool(true))) {+ keys.remove("filter");+ }+ serde_path_to_error::deserialize(&value).map(ParamListParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++impl JsonSchema for ParamListParams {+ fn schema_name() -> Cow<'static, str> {+ "ParamListParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ ParamListKeys::json_schema(generator)+ }+}++/// One row of the parameters table.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParameterRow {+ pub name: String,+ pub expression: String,+ /// Its unit; `""` for none, `text` for a text parameter.+ pub unit: String,+ /// Its value in mm for a length and degrees for an angle, whatever its own unit; `null` if+ /// it can't be worked out (a text parameter has none).+ pub value: Option<f64>,+ /// Its value in its own unit, as the Parameters window shows it.+ pub display_value: Option<f64>,+ /// Why it can't be worked out, when it can't.+ pub error: Option<String>,+ pub comment: String,+ /// `user`, `sketch` (a dimension) or `feature` (a feature's named input).+ pub source: String,+ /// For a feature input: the feature.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub feature: Option<String>,+ /// For a feature input: the input's label.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub input: Option<String>,+ pub favorite: bool,+ /// The names its expression uses.+ pub uses: Vec<String>,+ /// The names whose expressions use it.+ pub used_by: Vec<String>,+ /// A text parameter's text.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+}++impl From<ParamRow> for ParameterRow {+ fn from(r: ParamRow) -> Self {+ ParameterRow {+ name: r.name,+ expression: r.expression,+ unit: r.unit,+ value: r.value,+ display_value: r.display_value,+ error: r.error,+ comment: r.comment,+ source: r.source.to_string(),+ feature: r.feature,+ input: r.input.map(str::to_string),+ favorite: r.favorite,+ uses: r.uses,+ used_by: r.used_by,+ text: r.text,+ }+ }+}++/// What `parameters.list` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamListResult {+ /// The parameters listed, favourites first.+ pub parameters: Vec<ParameterRow>,+ /// How many there are.+ pub count: usize,+ /// The names whose expressions refer to themselves, directly or through others.+ pub cycles: Vec<String>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// List what uses a parameter: other parameters, feature inputs, sketch dimensions,+/// configurations, joints, rules and canvases, and the features it drives. Changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ParamUsersParams {+ /// The parameter, by name: a user parameter, a dimension or a feature's named input.+ #[serde(deserialize_with = "param_name")]+ #[schemars(length(min = 1))]+ pub name: String,+}++/// Something that uses a parameter.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ParameterUser {+ /// Another parameter's expression (a stored one or a feature input).+ Parameter { name: String },+ /// A feature input (`input` is its label, e.g. `Distance`).+ Feature { feature: u64, name: String, input: String },+ /// A sketch dimension (`constraint` is its id).+ Dimension { feature: u64, name: String, constraint: String },+ /// A configured column or an expression saved in a configuration row.+ Configuration { row: Option<String>, column: String },+ /// A joint's offset, angle or value, or a motion link's gear, rack or screw length (`input`+ /// says which).+ Joint { joint: u64, name: String, input: String },+ /// A sheet metal or plastic rule's value (`kind` says which, `field` which value).+ Rule { kind: String, name: String, field: String },+ /// The plane a canvas lies on (`input` is its label, e.g. `Offset`).+ Canvas { canvas: u64, name: String, input: String },+}++impl From<ParamUser> for ParameterUser {+ fn from(u: ParamUser) -> Self {+ match u {+ ParamUser::Parameter { name } => ParameterUser::Parameter { name },+ ParamUser::Feature { feature, name, input } => ParameterUser::Feature { feature, name, input },+ ParamUser::Dimension { feature, name, constraint } => ParameterUser::Dimension { feature, name, constraint },+ ParamUser::Configuration { row, column } => ParameterUser::Configuration { row, column },+ ParamUser::Joint { joint, name, input } => ParameterUser::Joint { joint, name, input },+ ParamUser::Rule { kind, name, field } => ParameterUser::Rule { kind, name, field },+ ParamUser::Canvas { canvas, name, input } => ParameterUser::Canvas { canvas, name, input },+ }+ }+}++/// A feature a parameter drives.+#[derive(Debug, Serialize, JsonSchema)]+pub struct DrivenFeature {+ /// The feature's id.+ pub id: u64,+ pub name: String,+}++/// What `parameters.users` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamUsersResult {+ /// The parameter's name, spaces at either end dropped.+ pub name: String,+ /// What uses it directly.+ pub users: Vec<ParameterUser>,+ /// The features it drives, directly or through other parameters.+ pub drives: Vec<DrivenFeature>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// `parameters.graph` takes no parameters.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ParamGraphParams {}++/// What `parameters.graph` returns: the dependency graph of the parameters.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamGraphResult {+ /// Every parameter name: the user's, the dimensions' and the feature inputs'.+ pub nodes: Vec<String>,+ /// `[user, used]`: the first's expression uses the second; a user may be `Feature:<name>`.+ pub edges: Vec<[String; 2]>,+ /// The names whose expressions refer to themselves, directly or through others.+ pub cycles: Vec<String>,+ /// The parameters that can't be worked out, with why, by name.+ pub errors: BTreeMap<String, String>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// Export the user parameters as CSV or JSON text, and write it to a file when a path is+/// given. Changes nothing in the design.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ParamExportParams {+ /// `csv` or `json`, ignoring case. Default: `json` when `path` ends in `.json`, else `csv`.+ #[serde(default)]+ pub format: Option<String>,+ /// A file to write the text to. Default: none is written.+ #[serde(default)]+ pub path: Option<String>,+}++/// What `parameters.export` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamExportResult {+ /// The format used, `csv` or `json`.+ pub format: String,+ /// The file written; `null` if none was.+ pub path: Option<String>,+ /// The exported text.+ pub text: String,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `parameters.import` takes, as the handler reads it: see [`ParamImportParams`].+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = import_forms)]+pub struct ParamImportKeys {+ /// The table as text: CSV with a header (`name`, `expression`, and optionally `unit` and+ /// `comment`), or JSON `[{name, expression, unit?, comment?}]`. When given, `path` isn't+ /// read.+ #[serde(default, deserialize_with = "import_text", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub text: Option<String>,+ /// A file to read the table from, in the same forms. Read when `text` isn't given.+ #[serde(default, deserialize_with = "import_text", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub path: Option<String>,+}++/// `text` and `path`: text; `null` is left out, as `str_` reads it. Anything else gets the+/// message the handler gives when it finds neither.+fn import_text<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "give `text` or `path`")+}++/// `parameters.import` needs `text` or `path` as text.+fn import_forms(schema: &mut Schema) {+ schema.insert(+ "anyOf".into(),+ json!([+ {"required": ["text"], "properties": {"text": {"type": "string"}}},+ {"required": ["path"], "properties": {"path": {"type": "string"}}}+ ]),+ );+}++/// Add the parameters in a CSV or JSON table, all or nothing. A name that exists is refused.+/// One undo step.+///+/// `path` is not read when `text` is text, as the handler leaves it.+#[derive(Debug)]+pub struct ParamImportParams(pub ParamImportKeys);++impl<'de> Deserialize<'de> for ParamImportParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if let Some(keys) = value.as_object_mut() {+ match keys.get("text") {+ Some(Value::String(_)) => {+ keys.remove("path");+ }+ // Not text, so the handler reads `path`: when that works, this is the one thing+ // wrong; when it doesn't, the handler's message says what is needed.+ Some(Value::Number(_) | Value::Bool(_) | Value::Array(_) | Value::Object(_))+ if matches!(keys.get("path"), Some(Value::String(_))) =>+ {+ return Err(D::Error::custom(whole("`text` must be text")));+ }+ _ => {}+ }+ }+ serde_path_to_error::deserialize(&value).map(ParamImportParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++impl JsonSchema for ParamImportParams {+ fn schema_name() -> Cow<'static, str> {+ "ParamImportParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ ParamImportKeys::json_schema(generator)+ }+}++/// What `parameters.import` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ParamImportResult {+ /// The names of the parameters added, in order.+ pub imported: Vec<String>,+ /// The features that failed to rebuild with them.+ pub errors: Vec<FailedFeature>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `expr.evaluate` takes, as the handler reads it: see [`ExprEvaluateParams`].+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = expression_required)]+pub struct ExprEvaluateKeys {+ /// The expression: text (`25 mm`, `W / 2`, `name = 3 * W`) or a number. With unit `text`, the+ /// text a text parameter would hold.+ // Optional in the type and required in the schema (`expression_required`): left out, the+ // handler refuses it with its own message.+ #[serde(default, deserialize_with = "evaluate_expression", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ExpressionText")]+ pub expression: Option<ExpressionText>,+ /// The unit the answer is shown in, and what bare numbers mean: `mm`, `cm`, `m`, `in`, `ft`,+ /// `deg`, `rad`, `""` (none) or `text` (a text parameter's text). Default: none; bare numbers+ /// follow the design's length unit.+ #[serde(default, deserialize_with = "evaluate_unit")]+ pub unit: Option<String>,+ /// What it must evaluate to: `length`, `angle` or `unitless` (`number` too). Default: the+ /// unit's kind, or what the expression is. Not read when `unit` is `text`.+ #[serde(default, deserialize_with = "evaluate_kind")]+ pub kind: Option<String>,+}++/// An expression given as text or as a number, as `expr_arg` reads it.+#[derive(Debug, Clone, PartialEq)]+pub struct ExpressionText(pub String);++impl JsonSchema for ExpressionText {+ fn schema_name() -> Cow<'static, str> {+ "ExpressionText".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "An expression as text, or a number.", "type": ["number", "string"]})+ }+}++fn evaluate_expression<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ExpressionText>, D::Error> {+ match Value::deserialize(d)? {+ Value::String(s) => Ok(Some(ExpressionText(s))),+ Value::Number(n) => n+ .as_f64()+ .filter(|v| v.is_finite())+ .map(|v| Some(ExpressionText(format!("{v}"))))+ .ok_or_else(|| D::Error::custom(whole("`expression` must be text or a number"))),+ _ => Err(D::Error::custom(whole("`expression` must be text or a number"))),+ }+}++fn evaluate_unit<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`unit` must be text")+}++fn evaluate_kind<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`kind` must be text")+}++fn expression_required(schema: &mut Schema) {+ require(schema, "expression");+}++/// Evaluate an expression against the design's parameters, without changing anything: its+/// value (in mm for a length, radians for an angle), its value in the unit asked for, what it+/// names, or why it fails. `name = expression` is worth its expression and says what it would+/// define.+///+/// `kind` is not read when `unit` is `text`, as the handler leaves it.+#[derive(Debug)]+pub struct ExprEvaluateParams(pub ExprEvaluateKeys);++impl<'de> Deserialize<'de> for ExprEvaluateParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if let Some(keys) = value.as_object_mut()+ && keys.get("unit").and_then(Value::as_str).is_some_and(solidcraft_doc::text_params::is_text_unit)+ {+ keys.remove("kind");+ }+ serde_path_to_error::deserialize(&value).map(ExprEvaluateParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++impl JsonSchema for ExprEvaluateParams {+ fn schema_name() -> Cow<'static, str> {+ "ExprEvaluateParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ ExprEvaluateKeys::json_schema(generator)+ }+}++/// What an evaluated expression is.+#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum EvalKind {+ Length,+ Angle,+ Unitless,+}++impl From<Kind> for EvalKind {+ fn from(k: Kind) -> Self {+ match k {+ Kind::Length => EvalKind::Length,+ Kind::Angle => EvalKind::Angle,+ Kind::Unitless => EvalKind::Unitless,+ }+ }+}++impl EvalKind {+ /// The word for it, as it's serialized.+ pub fn word(self) -> &'static str {+ match self {+ EvalKind::Length => "length",+ EvalKind::Angle => "angle",+ EvalKind::Unitless => "unitless",+ }+ }+}++/// What `expr.evaluate` returns: one of three shapes.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ExprEvaluated {+ #[serde(flatten)]+ pub body: ExprEvaluatedBody,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// The shapes of an `expr.evaluate` reply.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum ExprEvaluatedBody {+ /// With unit `text`: the text a text parameter would hold.+ Text {+ /// Always true.+ ok: bool,+ /// Always `text`.+ kind: String,+ /// The text, without the quotes round it.+ text: String,+ /// Always empty.+ references: Vec<String>,+ },+ /// The expression evaluated.+ Value {+ /// Always true.+ ok: bool,+ /// Its value: mm for a length, radians for an angle.+ value: f64,+ /// What it is.+ kind: EvalKind,+ /// Its value in the unit asked for; with none, degrees for an angle and the value itself+ /// otherwise.+ display_value: f64,+ /// The parameters it names.+ references: Vec<String>,+ /// For `name = expression`: the name it would define.+ #[serde(skip_serializing_if = "Option::is_none")]+ defines: Option<String>,+ },+ /// The expression didn't evaluate.+ Failed {+ /// Always false.+ ok: bool,+ /// Why.+ error: String,+ /// The parameters it names.+ references: Vec<String>,+ /// For `name = expression`: the name it would define.+ #[serde(skip_serializing_if = "Option::is_none")]+ defines: Option<String>,+ },+}++/// Suggest completions for the word at the end of some expression text: parameters (by name,+/// anywhere in it), functions, constants and units. Changes nothing.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ExprCompleteParams {+ /// The text before the cursor; the word being typed is its trailing letters, digits and+ /// underscores. Default: empty, which lists every parameter, function and constant.+ #[serde(default, deserialize_with = "complete_prefix")]+ pub prefix: Option<String>,+}++fn complete_prefix<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ text_or_null(d, "`prefix` must be text")+}++/// What a completion is.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum CompletionKind {+ Parameter,+ Function,+ Unit,+ Constant,+}++/// One suggestion.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Completion {+ /// The text to insert: a parameter's name, a function's name and `(`, a constant or a unit.+ pub text: String,+ pub kind: CompletionKind,+ /// A parameter's expression and value, a function's signature, or a unit's kind.+ pub detail: String,+}++/// What `parameters.complete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ExprCompletions {+ /// The word being completed; empty when the text ends in something else.+ pub word: String,+ /// Parameters first (names that start with the word, then the rest; favourites and user+ /// parameters first, at most 200), then functions, the constant `pi` and units.+ pub suggestions: Vec<Completion>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}+#[cfg(test)]#[path = "parameters_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/parameters_tests.rs b/crates/engine/src/schema/parameters_tests.rsindex 06c3925bbe..e0189b0948 100644--- a/crates/engine/src/schema/parameters_tests.rs+++ b/crates/engine/src/schema/parameters_tests.rs@@ -1,8 +1,10 @@use serde_json::{Value, json};use super::{- ParamAddParams, ParamAdded, ParamCommentParams, ParamCommented, ParamDeleted, ParamFavoriteParams, ParamFavorited, ParamMoveParams, ParamMoved,- ParamNameParams, ParamRenameParams, ParamRenamed,+ ExprCompleteParams, ExprCompletions, ExprEvaluateParams, ExprEvaluated, ParamAddParams, ParamAdded, ParamChangeParams, ParamChanged,+ ParamChangedBody, ParamCommentParams, ParamCommented, ParamDeleted, ParamExportParams, ParamExportResult, ParamFavoriteParams, ParamFavorited,+ ParamGraphParams, ParamGraphResult, ParamImportParams, ParamImportResult, ParamListParams, ParamListResult, ParamMoveParams, ParamMoved,+ ParamNameParams, ParamRenameParams, ParamRenamed, ParamUsersParams, ParamUsersResult, SwitchedFeature,};use crate::Session;use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};@@ -16,6 +18,17 @@ fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<ParamCommentParams>(), &["comment", "name"]);assert_keys(input_schema_for::<ParamFavoriteParams>(), &["favorite", "name"]);assert_keys(input_schema_for::<ParamMoveParams>(), &["after", "before", "name"]);+ assert_keys(+ input_schema_for::<ParamChangeParams>(),+ &["changes", "comment", "delete", "expression", "favorite", "name", "new_name", "unit", "value"],+ );+ assert_keys(input_schema_for::<ParamListParams>(), &["favorites", "filter"]);+ assert_keys(input_schema_for::<ParamUsersParams>(), &["name"]);+ assert_keys(input_schema_for::<ParamGraphParams>(), &[]);+ assert_keys(input_schema_for::<ParamExportParams>(), &["format", "path"]);+ assert_keys(input_schema_for::<ParamImportParams>(), &["path", "text"]);+ assert_keys(input_schema_for::<ExprEvaluateParams>(), &["expression", "kind", "unit"]);+ assert_keys(input_schema_for::<ExprCompleteParams>(), &["prefix"]);}/// The calls fail on a design without parameters, with the handlers' messages or the@@ -49,6 +62,39 @@ fn strict_keeps_todays_errors() {("parameters.move", json!({"name": "W", "before": "A", "after": "B"})),("parameters.move", json!({"name": "W", "before": 5})),("parameters.move", json!({"name": "Nope", "before": "A"})),+ ("parameters.change", json!({})),+ ("parameters.change", json!({"name": "W"})),+ ("parameters.change", json!({"name": " ", "expression": 1})),+ ("parameters.change", json!({"name": "W", "expression": true})),+ ("parameters.change", json!({"name": "W", "expression": null})),+ ("parameters.change", json!({"changes": null})),+ ("parameters.change", json!({"changes": [1]})),+ ("parameters.change", json!({"changes": {}})),+ ("parameters.change", json!({"changes": {"W": true}})),+ ("parameters.change", json!({"changes": {"W": [1]}, "name": "W", "expression": 2})),+ ("parameters.change", json!({"changes": {"Nope": 1}})),+ ("parameters.change", json!({"delete": "Nope"})),+ ("parameters.change", json!({"delete": " "})),+ ("parameters.change", json!({"name": "Nope", "favorite": true})),+ ("parameters.change", json!({"name": "Nope", "new_name": "X"})),+ ("parameters.users", json!({})),+ ("parameters.users", json!({"name": 5})),+ ("parameters.users", json!({"name": "Nope"})),+ ("parameters.export", json!({"format": "xml"})),+ ("parameters.export", json!({"format": "CSV", "path": "/nonexistent-dir/x/y.csv"})),+ ("parameters.import", json!({})),+ ("parameters.import", json!({"text": null, "path": null})),+ ("parameters.import", json!({"text": 5})),+ ("parameters.import", json!({"path": 5})),+ ("parameters.import", json!({"text": "name,expression\n1W,1"})),+ ("parameters.import", json!({"path": "/nonexistent-dir/x/y.csv"})),+ ("expr.evaluate", json!({})),+ ("expr.evaluate", json!({"expression": null})),+ ("expr.evaluate", json!({"expression": true})),+ ("expr.evaluate", json!({"expression": ["1"]})),+ ("expr.evaluate", json!({"expression": "1", "unit": "furlong"})),+ ("expr.evaluate", json!({"expression": "1", "kind": "colour"})),+ ("expr.evaluate", json!({"expression": "1", "unit": "mm", "kind": "colour"})),]);}@@ -144,3 +190,348 @@ fn parameter_edits_reply_with_their_schemas() {let error = warned.execute("parameters.favorite", &p).err().map(|e| e.to_string()).unwrap_or_default();assert!(error.contains("`favourite`"), "{error}");}++/// Whether the contract reports anything for the call, and what: the warnings of Warn.+fn issues(id: &str, p: Value) -> Vec<String> {+ crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()+}++/// `parameters.change` reads `changes` alone when it is there, `delete` alone when that is text,+/// else the keys of one change: a call that works today in any of the forms gets no warning for+/// a key of a form it doesn't read, and each form has the handler's messages.+#[test]+fn change_reads_only_the_keys_of_the_form_it_is_in() {+ let none = Vec::<String>::new();+ // The keys of another form are not read: a wrong one is no problem.+ assert_eq!(+ issues("parameters.change", json!({"changes": {"W": 1, "H": "2 mm"}, "name": 5, "expression": true, "unit": 1, "favorite": "x"})),+ none+ );+ assert_eq!(issues("parameters.change", json!({"delete": "W", "name": 5, "expression": true, "favorite": "x", "unit": 3})), none);+ assert_eq!(issues("parameters.change", json!({"changes": {"W": 1}, "delete": 5})), none);+ // A `delete` that isn't text is read as left out: the single change form it falls to+ // reports it.+ assert_eq!(issues("parameters.change", json!({"delete": 5, "name": "W", "expression": 1})), ["`delete` must be text"]);+ assert_eq!(issues("parameters.change", json!({"delete": null, "name": "W", "expression": 1})), none);+ // The single change form.+ for p in [+ json!({"name": "W", "expression": 5}),+ json!({"name": " W ", "value": "2 mm", "unit": "mm", "comment": "c", "favorite": true}),+ json!({"name": "W", "new_name": "X"}),+ json!({"name": "W", "favorite": false}),+ json!({"name": "W", "comment": "x"}),+ json!({"name": "W", "expression": null, "value": 3}),+ json!({"name": "W", "favorite": null}),+ ] {+ assert_eq!(issues("parameters.change", p.clone()), none, "{p}");+ }+ for (p, message) in [+ (json!({"name": 5, "expression": 1}), "`name` is required"),+ (json!({"name": null, "expression": 1}), "`name` is required"),+ (json!({"name": "W", "expression": true}), "`expression` must be a number or text"),+ (json!({"name": "W", "new_name": 5}), "`new_name` must be text"),+ (json!({"name": "W", "expression": 1, "unit": 5}), "`unit` must be text"),+ (json!({"name": "W", "expression": 1, "comment": 5}), "`comment` must be text"),+ (json!({"name": "W", "expression": 1, "favorite": "yes"}), "`favorite` must be true or false"),+ (json!({"changes": null}), "`changes` must be an object of name: expression"),+ (json!({"changes": ["W"]}), "`changes` must be an object of name: expression"),+ (json!({"changes": {}}), "`changes` is empty"),+ (json!({"changes": {"W": 1, "H": null}}), "`changes.H` must be a number or text"),+ ] {+ assert_eq!(issues("parameters.change", p.clone()), [message], "{p}");+ }+ // `value` is read only when `expression` isn't a number or text.+ assert_eq!(issues("parameters.change", json!({"name": "W", "expression": "5", "value": true})), none);+ assert_eq!(issues("parameters.change", json!({"name": "W", "expression": null, "value": true})), ["`expression` must be a number or text"]);+ // A missing key is the handler's to refuse, with its own message.+ for p in [json!({}), json!({"name": "W"}), json!({"expression": 1})] {+ assert_eq!(issues("parameters.change", p.clone()), Vec::<String>::new(), "{p}");+ }+}++/// `parameters.list` doesn't read `filter` when `favorites` is true; `parameters.import` doesn't+/// read `path` when `text` is text; `expr.evaluate` doesn't read `kind` when `unit` is `text`.+#[test]+fn list_import_and_evaluate_read_keys_only_where_the_handlers_do() {+ let none = Vec::<String>::new();+ assert_eq!(issues("parameters.list", json!({"favorites": true, "filter": 5})), none);+ assert_eq!(issues("parameters.list", json!({"favorites": false, "filter": 5})), ["`filter` must be text"]);+ assert_eq!(issues("parameters.list", json!({"filter": ["user"]})), ["`filter` must be text"]);+ assert_eq!(issues("parameters.list", json!({"favorites": "yes"})), ["`favorites` must be true or false"]);+ assert_eq!(issues("parameters.list", json!({"filter": null, "favorites": null})), none);+ assert_eq!(issues("parameters.list", json!({"filter": "bogus"})), none);++ assert_eq!(issues("parameters.import", json!({"text": "name,expression\nW,1", "path": 5})), none);+ assert_eq!(issues("parameters.import", json!({"text": "", "path": []})), none);+ assert_eq!(issues("parameters.import", json!({"path": "p.csv"})), none);+ assert_eq!(issues("parameters.import", json!({"text": null, "path": "p.csv"})), none);+ assert_eq!(issues("parameters.import", json!({"path": 5})), ["give `text` or `path`"]);+ assert_eq!(issues("parameters.import", json!({"text": 5})), ["give `text` or `path`"]);+ assert_eq!(issues("parameters.import", json!({"text": 5, "path": "p.csv"})), ["`text` must be text"]);++ assert_eq!(issues("expr.evaluate", json!({"expression": "a b", "unit": "text", "kind": 5})), none);+ assert_eq!(issues("expr.evaluate", json!({"expression": "a b", "unit": " TEXT ", "kind": "bogus"})), none);+ assert_eq!(issues("expr.evaluate", json!({"expression": 5, "unit": "mm", "kind": 5})), ["`kind` must be text"]);+ assert_eq!(issues("expr.evaluate", json!({"expression": 5, "unit": 5})), ["`unit` must be text"]);+ assert_eq!(issues("expr.evaluate", json!({"expression": 5, "kind": "angle", "unit": null})), none);+ assert_eq!(issues("expr.evaluate", json!({"expression": 2.5})), none);+ assert_eq!(issues("expr.evaluate", json!({"expression": {}})), ["`expression` must be text or a number"]);+ assert_eq!(issues("parameters.complete", json!({"prefix": 5})), ["`prefix` must be text"]);+ assert_eq!(issues("parameters.complete", json!({"prefix": null})), none);+ assert_eq!(issues("parameters.export", json!({"format": "JSON", "path": "x.csv"})), none);+ assert_eq!(issues("parameters.users", json!({"name": " "})), ["`name` is required"]);+ assert_eq!(issues("parameters.graph", json!({"nodes": 1})), ["unknown key `nodes`"]);+}++/// The schemas say which forms and keys the handlers need: `parameters.change`'s three forms,+/// `parameters.import`'s `text` or `path`, `expr.evaluate`'s `expression`.+#[test]+fn the_new_schemas_take_what_the_handlers_read() {+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {+ let schema = schema.as_value();+ for (p, takes) in cases {+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");+ }+ };+ takes(+ input_schema_for::<ParamChangeParams>(),+ &[+ (json!({"name": "W", "expression": "10 mm"}), true),+ (json!({"name": "W", "new_name": "X"}), true),+ (json!({"name": "W", "favorite": true}), true),+ (json!({"changes": {"W": 1}}), true),+ (json!({"delete": "W"}), true),+ (json!({}), false),+ (json!({"name": "W"}), false),+ (json!({"expression": 1}), false),+ (json!({"delete": 5}), false),+ (json!({"name": "W", "expression": true}), false),+ ],+ );+ takes(+ input_schema_for::<ParamImportParams>(),+ &[(json!({"text": "x"}), true), (json!({"path": "p.csv"}), true), (json!({}), false), (json!({"text": 5}), false)],+ );+ takes(+ input_schema_for::<ExprEvaluateParams>(),+ &[+ (json!({"expression": "1 + 2"}), true),+ (json!({"expression": 3, "unit": "mm", "kind": "length"}), true),+ (json!({}), false),+ (json!({"expression": true}), false),+ ],+ );+ takes(input_schema_for::<ParamUsersParams>(), &[(json!({"name": "W"}), true), (json!({}), false), (json!({"name": ""}), false)]);+ takes(+ input_schema_for::<ParamListParams>(),+ &[(json!({}), true), (json!({"favorites": true, "filter": "user"}), true), (json!({"favorites": "x"}), false)],+ );+ takes(+ input_schema_for::<ParamExportParams>(),+ &[(json!({}), true), (json!({"format": "json", "path": "p.json"}), true), (json!({"path": 1}), false)],+ );+ takes(input_schema_for::<ExprCompleteParams>(), &[(json!({}), true), (json!({"prefix": "si"}), true), (json!({"prefix": 1}), false)]);+ // `conforms` doesn't read nested `anyOf` inside a branch's `properties`; the forms are pinned.+ let change = input_schema_for::<ParamChangeParams>();+ assert_eq!(+ change.as_value()["anyOf"],+ json!([+ {"required": ["changes"]},+ {"required": ["delete"], "properties": {"delete": {"type": "string"}}},+ {+ "required": ["name"],+ "properties": {"name": {"type": "string"}},+ "anyOf": [+ {"required": ["expression"], "properties": {"expression": {"type": ["number", "string"]}}},+ {"required": ["value"], "properties": {"value": {"type": ["number", "string"]}}},+ {"required": ["new_name"]},+ {"required": ["favorite"]},+ {"required": ["comment"]}+ ]+ }+ ])+ );+}++fn matches(schema: schemars::Schema, id: &str, reply: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");+}++/// #12497: every command of the group, run in every form in Warn, replies as its output schema+/// says and without warnings (Warn runs a call the contract refuses anyway, so the absence of+/// `param_warnings` is what shows the contract accepts the call).+#[test]+fn the_parameter_commands_reply_with_their_schemas() {+ let dir = std::env::temp_dir().join(format!("solidcraft-params-schema-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ run("parameters.add", json!({"name": "W", "expression": "10 mm", "favorite": true}));+ run("parameters.add", json!({"name": "H", "expression": 5, "unit": "mm"}));+ run("parameters.add", json!({"name": "Label", "expression": "Rev A", "unit": "text"}));+ run("solid.box", json!({"length": "W", "width": "H * 2", "height": 4, "body_name": "Block"}));++ // Change: one parameter in each of its forms, several at once, a delete.+ let r = run("parameters.change", json!({"name": "W", "expression": "12 mm", "comment": "wall"}));+ assert!(r["value"] == 12.0 && r["expression"] == "12 mm" && r.get("renamed").is_none(), "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"name": "W", "value": 14, "unit": "mm", "favorite": false}));+ assert_eq!(r["value"], 14.0, "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"name": "W", "new_name": "Wall"}));+ assert!(r["renamed"]["from"] == "W" && r["renamed"]["to"] == "Wall" && r["expression"].is_null(), "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"name": "Wall", "comment": "thin", "favorite": true}));+ assert!(r["expression"].is_null() && r["name"] == "Wall", "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"name": "Wall", "expression": "Wide = 16"}));+ assert!(r["renamed"]["to"] == "Wide" && r["name"] == "Wide", "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"name": "Label", "expression": "Rev B"}));+ assert_eq!(r["text"], "Rev B", "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ let r = run("parameters.change", json!({"changes": {"Wide": 20, "H": "6 mm"}}));+ assert!(r["changed"]["Wide"] == 20.0 && r["changed"]["H"] == 6.0, "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ // The other forms' keys are not read, so a bad one doesn't warn.+ let r = run("parameters.change", json!({"changes": {"H": 7}, "name": 5, "expression": true}));+ assert_eq!(r["changed"]["H"], 7.0, "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);+ run("parameters.add", json!({"name": "Spare", "expression": 1}));+ let r = run("parameters.change", json!({"delete": " Spare ", "name": 5}));+ assert_eq!(r["deleted"], "Spare", "{r}");+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &r);++ // List: all forms of the filter, favourites first.+ let all = run("parameters.list", json!({}));+ assert_eq!(all["count"], all["parameters"].as_array().map_or(0, Vec::len), "{all}");+ matches(output_schema_for::<ParamListResult>(), "parameters.list", &all);+ for p in [+ json!({"favorites": true}),+ json!({"favorites": true, "filter": 5}),+ json!({"filter": "USER"}),+ json!({"filter": "feature"}),+ json!({"filter": "sketch"}),+ json!({"filter": "model"}),+ json!({"filter": "bogus"}),+ ] {+ let r = run("parameters.list", p);+ matches(output_schema_for::<ParamListResult>(), "parameters.list", &r);+ }+ let favorites = run("parameters.list", json!({"favorites": true}));+ assert!(favorites["parameters"].as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|r| r["favorite"] == true)), "{favorites}");+ let feature = run("parameters.list", json!({"filter": "feature"}));+ assert!(feature["parameters"].as_array().is_some_and(|a| a.iter().all(|r| r["source"] == "feature")), "{feature}");++ // Users and graph.+ let users = run("parameters.users", json!({"name": " H "}));+ assert_eq!(users["name"], "H", "{users}");+ assert!(users["users"].as_array().is_some_and(|u| !u.is_empty()) && users["drives"][0]["name"] == "Box1", "{users}");+ matches(output_schema_for::<ParamUsersResult>(), "parameters.users", &users);+ let graph = run("parameters.graph", json!({}));+ assert!(graph["nodes"].as_array().is_some_and(|n| n.contains(&json!("H"))), "{graph}");+ matches(output_schema_for::<ParamGraphResult>(), "parameters.graph", &graph);++ // Export in both formats, to text and to a file; import them back.+ let csv = run("parameters.export", json!({}));+ assert!(csv["format"] == "csv" && csv["path"].is_null(), "{csv}");+ matches(output_schema_for::<ParamExportResult>(), "parameters.export", &csv);+ let json_text = run("parameters.export", json!({"format": "JSON"}));+ assert_eq!(json_text["format"], "json", "{json_text}");+ matches(output_schema_for::<ParamExportResult>(), "parameters.export", &json_text);+ let file = dir.join("parameters.json");+ let written = run("parameters.export", json!({"path": file}));+ assert!(written["format"] == "json" && written["path"].is_string(), "{written}");+ matches(output_schema_for::<ParamExportResult>(), "parameters.export", &written);+ let mut other = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let imported = other.execute("parameters.import", &json!({"path": file})).unwrap_or_else(|e| panic!("{e}"));+ assert!(imported["imported"].as_array().is_some_and(|n| n.len() == 3), "{imported}");+ matches(output_schema_for::<ParamImportResult>(), "parameters.import", &imported);+ let from_text = other.execute("parameters.import", &json!({"text": "name,expression\nZ,3", "path": 5})).unwrap_or_else(|e| panic!("{e}"));+ assert_eq!(from_text["imported"], json!(["Z"]), "{from_text}");+ matches(output_schema_for::<ParamImportResult>(), "parameters.import", &from_text);++ // Evaluate: a length, an angle, a unitless number, a definition, an error, a text.+ for p in [+ json!({"expression": "H * 2"}),+ json!({"expression": 3, "unit": "in"}),+ json!({"expression": "90 deg"}),+ json!({"expression": "30", "unit": "deg"}),+ json!({"expression": "2 * 3", "kind": "unitless"}),+ json!({"expression": "Wide", "kind": "length"}),+ json!({"expression": "len = 3 mm"}),+ json!({"expression": "nope + 1"}),+ json!({"expression": "Rev \"A\"", "unit": "text", "kind": 5}),+ ] {+ let r = run("expr.evaluate", p.clone());+ matches(output_schema_for::<ExprEvaluated>(), "expr.evaluate", &r);+ assert_eq!(r["ok"], !p["expression"].as_str().is_some_and(|e| e.starts_with("nope")), "{r}");+ }+ let r = run("expr.evaluate", json!({"expression": "len = 3 mm"}));+ assert!(r["defines"] == "len" && r["kind"] == "length" && r["value"] == 3.0, "{r}");+ let r = run("expr.evaluate", json!({"expression": "'Rev A'", "unit": "text"}));+ assert!(r["kind"] == "text" && r["text"] == "Rev A" && r["references"] == json!([]), "{r}");+ let r = run("expr.evaluate", json!({"expression": "nope + 1"}));+ assert!(r["ok"] == false && r["error"].is_string() && r["references"] == json!(["nope"]), "{r}");++ // Complete: parameters, functions, constants, units.+ for p in+ [json!({}), json!({"prefix": "H"}), json!({"prefix": "2 * si"}), json!({"prefix": "p"}), json!({"prefix": "3 m"}), json!({"prefix": null})]+ {+ let r = run("parameters.complete", p);+ matches(output_schema_for::<ExprCompletions>(), "parameters.complete", &r);+ }+ let r = run("parameters.complete", json!({"prefix": "3 m"}));+ assert!(r["suggestions"].as_array().is_some_and(|a| a.iter().any(|c| c["kind"] == "unit" && c["detail"] == "length")), "{r}");+ let r = run("parameters.complete", json!({"prefix": "p"}));+ assert!(r["suggestions"].as_array().is_some_and(|a| a.iter().any(|c| c["kind"] == "constant")), "{r}");+ let _ = std::fs::remove_dir_all(&dir);+}++/// A misspelt key runs in Warn and is reported, with a reply that still matches; strict refuses+/// it. Each command of the group.+#[test]+fn a_misspelt_key_is_reported_for_each_command() {+ let calls = [+ ("parameters.change", json!({"name": "W", "comment": "c", "favorit": true}), "favorit"),+ ("parameters.list", json!({"favourites": true}), "favourites"),+ ("parameters.users", json!({"name": "W", "nam": 1}), "nam"),+ ("parameters.graph", json!({"node": 1}), "node"),+ ("parameters.export", json!({"formt": "csv"}), "formt"),+ ("parameters.import", json!({"text": "name,expression\nQ,1", "pth": "x"}), "pth"),+ ("expr.evaluate", json!({"expression": "1", "unt": "mm"}), "unt"),+ ("parameters.complete", json!({"prefx": "W"}), "prefx"),+ ];+ for (id, p, key) in calls {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ s.execute("parameters.add", &json!({"name": "W", "expression": "10 mm"})).unwrap_or_else(|e| panic!("{e}"));+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ assert!(r["param_warnings"].to_string().contains(key), "{id}: {r}");+ let schema = crate::cmd::find_command(id).and_then(|c| c.output).map(|f| f()).unwrap_or_else(|| panic!("{id} has no output schema"));+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r} doesn't match {}", schema.as_value());+ s.param_check = ParamCheck::Strict;+ let error = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains(&format!("`{key}`")), "{id}: {error}");+ }+}++/// A configuration rule's switch has the shape the schema describes.+#[test]+fn a_switched_feature_serializes_as_the_schema_says() {+ let body = ParamChangedBody::Many {+ changed: [("W".to_string(), Some(1.0))].into(),+ recomputed: 2,+ restored: 0,+ errors: Vec::new(),+ switched: vec![SwitchedFeature { feature: 3, name: Some("Hole".into()), suppressed: true }],+ };+ let reply = serde_json::to_value(ParamChanged { body, param_warnings: Vec::new() }).unwrap_or_default();+ assert_eq!(+ reply,+ json!({"changed": {"W": 1.0}, "recomputed": 2, "restored": 0, "errors": [], "switched": [{"feature": 3, "name": "Hole", "suppressed": true}]})+ );+ matches(output_schema_for::<ParamChanged>(), "parameters.change", &reply);+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex a824b0fcac..7b5dd35770 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -13,7 +13,6 @@ doc.recovery_discarddoc.recovery_listdocument.inspectengine.commands-expr.evaluateface.deletefile.exportfile.insert_mesh@@ -47,13 +46,6 @@ occurrence.dragoccurrence.groundoccurrence.moveoccurrence.properties-parameters.change-parameters.complete-parameters.export-parameters.graph-parameters.import-parameters.list-parameters.usersrender.aging.describerender.backendsrender.cancel