Skip to content

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

32.5 KB
Raw Blame
//! Parameters: Change Parameters (add, edit, rename, delete) and the `parameters.*` commands
//! behind the parameters dialog — list, add, rename, favourite, comment, users, dependency
//! graph, CSV/JSON import and export, expression evaluation and autocomplete.

use serde_json::{Value, json};
use solidcraft_doc::FeatureKind;
use solidcraft_doc::expr::{self, Kind};
use solidcraft_sketch::{Analysis, ConstraintKind, CurveKind, Hold, Sketch, solve_with};

use super::{CommandSpec, sketch_store};
use crate::params::{bad, bool_, str_};
use crate::schema::parameters::{
    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};

const ADD_CONTRACT: TypedContract<ParamAddParams> = TypedContract::new();
const RENAME_CONTRACT: TypedContract<ParamRenameParams> = TypedContract::new();
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", 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, \
         or sets `new` when the expression is just `new`); or delete: name; or changes: {name: expression, …} (existing \
         parameters, checked together and rebuilt once, all or nothing) → changed?: {name: value} (with changes), recomputed: features rebuilt, \
         restored: features whose earlier result for the same inputs was reused (e.g. a value set back), switched?: [{feature, name, suppressed}] \
         (the configuration rules that switch a feature's suppression and read a parameter whose value changed run in their order, as on \
         activation; driven parameters and restrictions wait for a configuration edit or activation)",
    ),
    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",
    ),
    CommandSpec::new("parameters.add", "Add User Parameter", crate::checked!("parameters.add", add))
        .icon("new")
        .contract(&ADD_CONTRACT)
        .output(output_schema_for::<ParamAdded>)
        .params("name, expression, unit?: as parameters.change (text: a text parameter, its expression the text), comment?, favorite?: bool"),
    CommandSpec::new("parameters.rename", "Rename Parameter", crate::checked!("parameters.rename", rename))
        .icon("rename")
        .contract(&RENAME_CONTRACT)
        .output(output_schema_for::<ParamRenamed>)
        .params("name, new_name (expressions, feature inputs and dimensions that use it follow)"),
    CommandSpec::new("parameters.delete", "Delete Parameter", crate::checked!("parameters.delete", delete))
        .icon("delete")
        .contract(&NAME_CONTRACT)
        .output(output_schema_for::<ParamDeleted>)
        .params("name (refused while something uses it; the error lists the users)"),
    CommandSpec::new("parameters.favorite", "Favorite Parameter", crate::checked!("parameters.favorite", favorite))
        .icon("star")
        .contract(&FAVORITE_CONTRACT)
        .output(output_schema_for::<ParamFavorited>)
        .params("name, favorite?: bool (default true)"),
    CommandSpec::new("parameters.move", "Move Parameter", crate::checked!("parameters.move", move_param))
        .icon("reorder")
        .contract(&MOVE_CONTRACT)
        .output(output_schema_for::<ParamMoved>)
        .params("name, before | after: another user parameter; the user parameter is listed just before or after it"),
    CommandSpec::new("parameters.comment", "Comment Parameter", crate::checked!("parameters.comment", comment))
        .icon("text")
        .contract(&COMMENT_CONTRACT)
        .output(output_schema_for::<ParamCommented>)
        .params("name, comment"),
    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", 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", 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", 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", 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", 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}]"),
];

fn expr_arg(p: &Value, k: &str) -> Option<String> {
    match p.get(k)? {
        Value::String(x) => Some(x.clone()),
        Value::Number(n) => n.as_f64().filter(|v| v.is_finite()).map(|v| format!("{v}")),
        _ => None,
    }
}

fn param_name<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {
    str_(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` is required"))
}

/// Features that fail (name and error).
fn failing(s: &Session) -> Vec<FailedFeature> {
    FailedFeature::of(&s.model.results)
}

pub(super) fn known(s: &Session, name: &str) -> bool {
    s.doc.param(name).is_some() || s.doc.text_param(name).is_some() || s.doc.features.iter().any(|f| f.param_names.iter().any(|n| n == name))
}

/// Whether `name` is (or, with this unit, becomes) a text parameter, whose expression is text.
fn is_text(s: &Session, name: &str, unit: Option<&str>) -> bool {
    s.doc.text_param(name).is_some() || unit.is_some_and(solidcraft_doc::text_params::is_text_unit)
}

fn change_param(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.change";
    let solved = s.solved_sketches();
    if let Some(changes) = p.get("changes") {
        return change_many(s, changes, &solved);
    }
    if let Some(n) = str_(p, "delete") {
        s.doc_mut().remove_param(n.trim())?;
        s.settle_value_edit(&solved)?;
        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 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)?;
        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 renamed.is_some() || p.get("favorite").is_some() || p.get("comment").is_some() {
        None
    } else {
        return Err(bad(cmd, "`expression` must be a number or text"));
    };
    // `name = expression` names the value being changed (#4071): the parameter (a dimension's
    // `d7`, a feature input's) is renamed, references following, and takes the expression. A
    // text parameter's text is only text.
    if let Some((new, rhs)) = e.as_deref().filter(|_| !is_text(s, &name, str_(p, "unit"))).and_then(expr::definition) {
        if renamed.is_some() {
            return Err(bad(cmd, format!("`{new} = …` renames `{name}` already: give `new_name` or `name = expression`, not both")));
        }
        if rhs.is_empty() {
            return Err(bad(cmd, format!("`{new} =` needs a value after the `=`")));
        }
        let (new, rhs) = (new.to_string(), rhs.to_string());
        // A value that is just a parameter's name changes that parameter: a dimension made as
        // `w = 20` shows `w`, and `w = 30` typed over it sets `w`.
        let refers_to = s.doc.all_param_exprs().into_iter().find(|(n, _, _)| *n == name).map(|(_, e, _)| e);
        if refers_to.as_deref().map(str::trim) == Some(new.as_str()) && s.doc.param(&new).is_some() {
            changed_through = Some(name);
            name = new.clone();
        }
        if new != name {
            if known(s, &new) {
                return Err(bad(cmd, format!("there is already a parameter `{new}`: type `{new}` to use it, or change it in Parameters")));
            }
            let n = s.doc_mut().rename_param(&name, &new)?;
            renamed = Some(ParamRename { from: name, to: new.clone(), references_updated: n });
            name = new;
        }
        e = Some(rhs);
    }
    let (unit, comment) = (str_(p, "unit"), str_(p, "comment"));
    let before = s.doc.param_values().0;
    match &e {
        Some(e) => s.doc_mut().change_param(&name, e, unit, comment)?,
        None => {
            if !known(s, &name) {
                return Err(bad(cmd, format!("no parameter `{name}`")));
            }
            if let Some(c) = comment {
                s.doc_mut().set_param_comment(&name, c)?;
            }
        }
    }
    if let Some(f) = bool_(p, "favorite") {
        s.doc_mut().set_favorite(&name, f)?;
    }
    let switched = switch_by_rules(s, &before);
    if e.is_some() {
        keep_dimension_start(s, &name);
    }
    s.settle_value_edit(&solved)?;
    let (vals, _) = s.doc.param_values();
    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
/// line's start). None for other dimensions.
fn dimension_start(sk: &Sketch, kind: &ConstraintKind) -> Option<usize> {
    match kind {
        ConstraintKind::Distance { p, .. } | ConstraintKind::DistanceX { p, .. } | ConstraintKind::DistanceY { p, .. } => Some(*p),
        ConstraintKind::Length { l, .. } => match sk.curves.get(*l)?.kind {
            CurveKind::Line { a, .. } => Some(a),
            _ => None,
        },
        _ => None,
    }
}

/// A length dimension driven by `name` keeps its first point where it is when the value
/// changes, so a rectangle's side grows from its first corner, not from both ends (#6070). The
/// sketch is solved here with that point held, before the design evaluates from its stored
/// positions. Where holding it can't solve (a symmetry moves both ends), evaluation solves as
/// before.
fn keep_dimension_start(s: &mut Session, name: &str) {
    let targets: Vec<(u64, usize)> = s
        .doc
        .features
        .iter()
        .filter_map(|f| match &f.kind {
            FeatureKind::Sketch { sketch, .. } => sketch
                .constraints
                .iter()
                .find(|c| !c.driven && c.param.as_deref() == Some(name))
                .and_then(|c| dimension_start(sketch, &c.kind))
                .map(|p| (f.id, p)),
            _ => None,
        })
        .collect();
    if targets.is_empty() {
        return;
    }
    let vals = s.doc.evaluation_values();
    for (id, start) in targets {
        let Ok(stored) = sketch_store::read(&s.doc, id) else { continue };
        let mut trial = stored.clone();
        if s.doc.apply_dimension_values(&vals, &mut trial).is_err() {
            continue;
        }
        let reference: Vec<_> = stored.points.iter().map(|p| p.pos).collect();
        let hold = Hold { points: vec![start], radii: Vec::new() };
        let solved = if trial.offsets.is_empty() && trial.freeform_offsets.is_empty() {
            solve_with(&mut trial, &hold, Some(&reference), Analysis::StatusOnly, None).keeps_orientation()
        } else {
            // A solve against stale offset points can stretch an attached cap into a different
            // tangency branch. Keep the start through the complete solve/refresh sequence.
            let Some(p) = trial.points.get_mut(start) else { continue };
            p.fixed = true;
            s.doc
                .solve_sketch_with_analysis(&vals, &mut trial, &stored.driving_values(), Some(stored), Analysis::StatusOnly)
                .is_ok_and(|report| report.keeps_orientation())
        };
        if !solved {
            continue;
        }
        if stored.points.len() == trial.points.len() {
            // Only the points move: the stored dimensions keep their own values.
            let mut kept = stored.clone();
            for (p, q) in kept.points.iter_mut().zip(&trial.points) {
                p.pos = q.pos;
            }
            let _ = sketch_store::write(s.doc_mut(), id, kept);
        }
    }
}

/// `parameters.change {changes}`: several existing parameters set at once, so a design is
/// rebuilt once for all of them instead of once per parameter.
fn change_many(s: &mut Session, changes: &Value, solved: &crate::SketchValues) -> Result<Value> {
    let cmd = "parameters.change";
    let Some(map) = changes.as_object() else { return Err(bad(cmd, "`changes` must be an object of name: expression")) };
    if map.is_empty() {
        return Err(bad(cmd, "`changes` is empty"));
    }
    let mut list = Vec::with_capacity(map.len());
    for (name, e) in map {
        let e = expr_arg(&json!({"e": e}), "e").ok_or_else(|| bad(cmd, format!("`changes.{name}` must be a number or text")))?;
        // Renaming is one parameter at a time (#4071).
        if let Some((new, _)) = expr::definition(&e).filter(|_| !is_text(s, name.trim(), None)) {
            return Err(bad(cmd, format!("`changes.{name}`: `{new} = …` would rename `{name}`; change it on its own to rename it")));
        }
        list.push((name.trim().to_string(), e));
    }
    let before = s.doc.param_values().0;
    s.doc_mut().change_params_atomic(&list)?;
    let switched = switch_by_rules(s, &before);
    for (name, _) in &list {
        keep_dimension_start(s, name);
    }
    s.settle_value_edit(solved)?;
    let (vals, _) = s.doc.param_values();
    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<SwitchedFeature> {
    if s.doc.configs.rules.is_empty() {
        return Vec::new();
    }
    let switched = s.doc_mut().apply_suppression_rules(before);
    switched
        .into_iter()
        .map(|(id, suppressed)| {
            let name = s.doc.features.iter().find(|f| f.id == id).map(|f| f.name.clone());
            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(),
        _ => "all".to_string(),
    };
    let mut rows: Vec<solidcraft_doc::ParamRow> = s
        .doc
        .param_rows()
        .into_iter()
        .filter(|r| match filter.as_str() {
            "favorites" | "favourites" | "favorite" => r.favorite,
            "user" | "sketch" | "feature" => r.source == filter,
            "model" => r.source != "user",
            _ => true,
        })
        .collect();
    // 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());
    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> {
    let cmd = "parameters.add";
    let name = param_name(cmd, p)?.to_string();
    let e = expr_arg(p, "expression").or_else(|| expr_arg(p, "value")).ok_or_else(|| bad(cmd, "`expression` must be a number or text"))?;
    let solved = s.solved_sketches();
    s.doc_mut().add_user_param(&name, &e, str_(p, "unit"), str_(p, "comment"))?;
    s.settle_value_edit(&solved)?;
    if let Some(f) = bool_(p, "favorite") {
        s.doc_mut().set_favorite(&name, f)?;
    }
    let (vals, _) = s.doc.param_values();
    let value = match s.doc.text_param(&name) {
        Some(t) => AddedValue::Text { unit: solidcraft_doc::text_params::TEXT_UNIT.into(), text: t.text.clone(), value: None },
        None => AddedValue::Number {
            unit: s.doc.param(&name).map(|x| x.unit.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),
        },
    };
    reply(cmd, ParamAdded { name, value, param_warnings: Vec::new() })
}

/// A reply as JSON: these commands build their replies from the types their output schemas
/// describe, so the two can't drift apart.
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
    serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}

fn rename(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.rename";
    let name = param_name(cmd, p)?.to_string();
    let new = str_(p, "new_name").ok_or_else(|| bad(cmd, "`new_name` is required"))?;
    let references_updated = s.doc_mut().rename_param(&name, new)?;
    reply(cmd, ParamRenamed { from: name, to: new.trim().to_string(), references_updated, param_warnings: Vec::new() })
}

fn delete(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.delete";
    let name = param_name(cmd, p)?.to_string();
    let solved = s.solved_sketches();
    s.doc_mut().remove_param(&name)?;
    s.settle_value_edit(&solved)?;
    reply(cmd, ParamDeleted { deleted: name, param_warnings: Vec::new() })
}

fn favorite(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.favorite";
    let name = param_name(cmd, p)?.to_string();
    let favorite = bool_(p, "favorite").unwrap_or(true);
    s.doc_mut().set_favorite(&name, favorite)?;
    reply(cmd, ParamFavorited { name, favorite, param_warnings: Vec::new() })
}

fn move_param(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.move";
    let name = param_name(cmd, p)?.to_string();
    let (target, after) = match (str_(p, "before"), str_(p, "after")) {
        (Some(t), None) => (t.to_string(), false),
        (None, Some(t)) => (t.to_string(), true),
        _ => return Err(bad(cmd, "give one of `before` or `after`: another user parameter")),
    };
    s.doc_mut().move_user_param(&name, &target, after)?;
    let order = s.doc.params.iter().filter(|q| !q.model).map(|q| q.name.clone()).collect();
    reply(cmd, ParamMoved { name, order, param_warnings: Vec::new() })
}

fn comment(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.comment";
    let name = param_name(cmd, p)?.to_string();
    let c = str_(p, "comment").ok_or_else(|| bad(cmd, "`comment` must be text"))?;
    s.doc_mut().set_param_comment(&name, c)?;
    reply(cmd, ParamCommented { name, comment: c.to_string(), param_warnings: Vec::new() })
}

fn users(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.users";
    let name = param_name(cmd, p)?;
    if !known(s, name) {
        return Err(bad(cmd, format!("no parameter `{name}`")));
    }
    let users = s.doc.param_users(name);
    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());
    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> {
    let cmd = "parameters.export";
    let path = str_(p, "path");
    let format = str_(p, "format").map(str::to_ascii_lowercase).unwrap_or_else(|| match path {
        Some(x) if x.to_ascii_lowercase().ends_with(".json") => "json".into(),
        _ => "csv".into(),
    });
    let text = match format.as_str() {
        "csv" => s.doc.params_csv(),
        "json" => {
            let rows: Vec<Value> = s
                .doc
                .param_rows()
                .into_iter()
                .filter(|r| r.source == "user")
                // The `value` field keeps the number in the parameter's own unit, as the CSV
                // column does, rounded for reading (#10747).
                .map(|r| json!({"name": r.name, "expression": r.expression, "unit": r.unit, "value": r.display_value.or(r.value), "comment": r.comment, "favorite": r.favorite}))
                .collect();
            serde_json::to_string_pretty(&rows).map_err(|e| bad(cmd, e.to_string()))?
        }
        other => return Err(bad(cmd, format!("unknown format `{other}` (csv or json)"))),
    };
    if let Some(path) = path {
        solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
    }
    reply(cmd, ParamExportResult { format, path: path.map(str::to_string), text, param_warnings: Vec::new() })
}

/// Largest parameter table we read from a file.
const MAX_PARAMETER_BYTES: usize = 16 << 20;

fn import(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "parameters.import";
    let text = match (str_(p, "text"), str_(p, "path")) {
        (Some(t), _) => t.to_string(),
        (None, Some(path)) => {
            solidcraft_io::vfs::read_to_string(path, MAX_PARAMETER_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?
        }
        _ => return Err(bad(cmd, "give `text` or `path`")),
    };
    let solved = s.solved_sketches();
    let names = s.doc_mut().import_params(&text)?;
    s.settle_value_edit(&solved)?;
    reply(cmd, ParamImportResult { imported: names, errors: failing(s), param_warnings: Vec::new() })
}

fn evaluate(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "expr.evaluate";
    let e = expr_arg(p, "expression").ok_or_else(|| bad(cmd, "`expression` must be text or a number"))?;
    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) {
        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()
    {
        return Err(bad(cmd, format!("unknown unit `{u}`")));
    }
    let kind = match (str_(p, "kind"), unit) {
        (Some("length"), _) => Some(Kind::Length),
        (Some("angle"), _) => Some(Kind::Angle),
        (Some("unitless" | "number"), _) => Some(Kind::Unitless),
        (Some(other), _) => return Err(bad(cmd, format!("unknown kind `{other}` (length, angle or unitless)"))),
        (None, Some(u)) => Some(Kind::from_unit(u)),
        (None, None) => None,
    };
    let (vals, _) = s.doc.param_values();
    // Bare numbers follow the asked-for unit when given, else the design's length unit (#9015).
    let doc_len = expr::unit_info(s.doc.units.trim()).filter(|(k, _)| *k == Kind::Length).map(|(_, s)| s).unwrap_or(1.0);
    let defaults = expr::Defaults::for_unit(unit.unwrap_or(""), doc_len);
    let refs = expr::references(&e);
    let lookup = |n: &str| vals.get(n).copied().ok_or_else(|| solidcraft_doc::DocError::Expr(format!("unknown parameter `{n}`")));
    let r = expr::eval_with_defaults(&e, &lookup, defaults).and_then(|v| match kind {
        Some(k) => v.to_kind_in(k, defaults).map(|x| (x, k)),
        None => v.kind().map(|k| (v.v, k)).ok_or_else(|| solidcraft_doc::DocError::Expr(format!("the result is {}", v.describe()))),
    });
    // `name = expression` is worth its expression, and names what it would define (#4071).
    let defines = expr::definition(&e).map(|(n, _)| n);
    let body = match r {
        Ok((v, k)) => {
            let value = match k {
                Kind::Length => expr::Value::length(v),
                Kind::Angle => expr::Value::angle(v),
                Kind::Unitless => expr::Value::num(v),
            };
            let shown = match (unit, k) {
                (Some(u), _) => expr::value_in_unit(value, u),
                (None, Kind::Angle) => v.to_degrees(),
                (None, _) => v,
            };
            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) => ExprEvaluatedBody::Failed {
            ok: false,
            error: err.to_string().trim_start_matches("expression: ").to_string(),
            references: refs,
            defines: defines.map(str::to_string),
        },
    };
    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();
    let lower = word.to_ascii_lowercase();
    let starts = |n: &str| word.is_empty() || n.to_ascii_lowercase().starts_with(&lower);
    // A parameter matches wherever the word appears in its name (`side` finds
    // `cab_side_thickness`, #2757) or by the starts of its words in order (`toodia` finds
    // `tooth_outward_flange_diameter`, #11978); functions, constants and units match from the
    // 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<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.
    rows.sort_by_key(|r| (!starts(&r.name), !contains(&r.name), !r.favorite, r.source != "user"));
    for r in rows.into_iter().take(200) {
        // The completion shows the parameter's own unit, so it reads `display_value`.
        let v = r.display_value.or(r.value).map(|v| format!("{v:.4} {}", r.unit).trim().to_string()).unwrap_or_else(|| "error".into());
        let mut detail = format!("{} = {v}", r.expression);
        if let (Some(f), Some(i)) = (&r.feature, r.input) {
            detail.push_str(&format!(" ({f} {i})"));
        }
        if !r.comment.is_empty() {
            detail.push_str(&format!(" — {}", r.comment));
        }
        out.push(Completion { text: r.name, kind: CompletionKind::Parameter, detail });
    }
    for (f, sig) in expr::FUNCTIONS {
        if starts(f) {
            out.push(Completion { text: format!("{f}("), kind: CompletionKind::Function, detail: sig.to_string() });
        }
    }
    if starts("pi") {
        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(Completion { text: u.to_string(), kind: CompletionKind::Unit, detail: EvalKind::from(*k).word().to_string() });
        }
    }
    reply(cmd, ExprCompletions { word, suggestions: out, param_warnings: Vec::new() })
}

#[cfg(test)]
#[path = "parameters_tests.rs"]
mod tests;