BREP_kernel 0.33.0

Rust B-rep CAD kernel (next.BREP.io): a boundary representation (B-rep) geometry kernel for building CAD applications, native and WebAssembly.
Documentation
//! Rename a feature everywhere it is named (owner 2026-11-27: a TRUE rename).
//!
//! A feature's id is also the name of the solid it makes and the head of every
//! face, edge, frame and sketch child it publishes (`E4:S3:PROFILE_START`,
//! `CU1_PZ`, `D1:XY`, `S3:G20`, `E4:S3:PROFILE_START|E4:S3:L1_SW`). Those names
//! are what every other part of the document stores: feature params (reference
//! fields, boolean targets), sketch external references, assembly constraints,
//! PMI annotations, sheet views and dimension anchors, ports, wires, CAM,
//! simulation and instruction blocks. [`rename_feature_in_document`] rewrites
//! the id and every such name in one pass over the document, so the caller can
//! adopt the result as ONE history edit (one undo step).
//!
//! A name is rewritten per TOKEN, never as a substring:
//! - a string is split into segments at `|` (an edge between two faces) and `#`
//!   (a sheet anchor's edge), and each segment into tokens at `:`;
//! - a token is the old id, or the old id followed by `_`, `@`, `[`, `.` or `#`
//!   (`CU1_PZ`, `S1@0,0,0`, `Ext_top[0]`), which keeps `E40` and `xE4` untouched;
//! - after a component token (`ACOMP2:`), the rest of the segment names the
//!   component's own part and is never touched.
//!
//! Only the blocks that hold model entity names are walked (`NAMED_BLOCKS`;
//! in `ports`, only the keys points are placed by). Free text (labels, notes,
//! annotation text), the eCAD blocks (reference designators: `D1` is a diode
//! there), the expression and configurator blocks, the family table and the
//! parts library are left alone. The
//! `metadata` block is keyed by names; the engine keeps it apart from the
//! history and renames its keys with [`rename_name`].
//!
//! A COMPONENT renames the same way: its id heads every name of its part
//! (`ACOMP2:Part_PZ` becomes `Motor:Part_PZ`), a Pattern Component instance
//! names it inside (`APAT1.ACOMP2.i4` becomes `APAT1.Motor.i4`), and the eCAD
//! blocks' occurrence keys (`instance`, `occurrence`) follow it. Names are read
//! against the document's [`crate::ComponentNamespace`], so what follows a
//! component's id is its part's and is never rewritten.
//!
//! Refused by name, so nothing is half renamed: an id that is not a feature,
//! a pattern of components (`APAT<n>`: its instance ids are read by that
//! shape), an illegal or reserved name, a name already used in the document,
//! and an id another feature's id extends (`E4` when `E4_B` exists: its
//! references could not be told apart).

use serde_json::Value;

/// What a rename changed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RenameOutcome {
    /// The number of strings (and map keys) rewritten, the id itself included.
    pub rewritten: usize,
    /// The ids of the features whose params or data name the renamed one (the
    /// renamed feature excluded), in document order.
    pub referencing_features: Vec<String>,
    /// The top-level blocks other than `features` that were rewritten
    /// (`assembly`, `pmi`, `sheets`, ...), in document order.
    pub blocks: Vec<String>,
}

/// The top-level blocks that hold model entity names, walked whole (less
/// [`TEXT_KEYS`]). Every other block is left alone: the eCAD blocks (`pcb`,
/// `symbol`, `pads`, `diagram`) speak reference designators, nets and pin
/// numbers (`D1` is a diode there and a datum here), and the rest hold
/// expressions, settings, another document or no names at all.
const NAMED_BLOCKS: &[&str] = &["features", "assembly", "pmi", "sheets", "cam", "simulation", "instructions", "exploded"];

/// `ports` holds its own port and point names beside the entity names its
/// points are placed on: only these keys of it are entity names.
const PORT_NAME_KEYS: &[&str] = &["pointRef", "directionRef", "contactBody"];

/// Keys whose values are free text or codes, never entity names.
const TEXT_KEYS: &[&str] = &[
    "type",
    "partName",
    "text",
    "label",
    "description",
    "notes",
    "note",
    "title",
    "comment",
    "prefix",
    "suffix",
];

/// Names the scene owns already (the origin planes).
const RESERVED: &[&str] = &["XY", "XZ", "YZ", "ORIGIN", "Math", "configurator"];

/// The longest name accepted.
pub const MAX_NAME_LEN: usize = 64;

/// Whether `name` may be given to a feature: a letter, then letters, digits or
/// `-`, at most [`MAX_NAME_LEN`] long, not reserved and not a component id.
/// `_`, `:`, `|`, `.`, `@`, `#` and spaces are refused because they are the
/// separators of the names built from an id.
pub fn validate_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("the new name is empty".into());
    }
    if name.len() > MAX_NAME_LEN {
        return Err(format!("the new name is longer than {MAX_NAME_LEN} characters"));
    }
    let mut chars = name.chars();
    if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) {
        return Err(format!("`{name}` must start with a letter"));
    }
    if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '-')) {
        return Err(format!(
            "`{name}` has `{bad}`: a name may hold only letters, digits and `-` (`_ : | . @ #` and spaces separate the names built from it)"
        ));
    }
    if RESERVED.contains(&name) {
        return Err(format!("`{name}` is reserved"));
    }
    if crate::is_component_reference(name) || name.starts_with("APAT") {
        return Err(format!("`{name}` has the form of a component id (ACOMP<n>, APAT<n>)"));
    }
    Ok(())
}

/// `name` with `old` renamed to `new` per the token rule, or `None` when it
/// does not name `old`.
pub fn rename_name(name: &str, old: &str, new: &str) -> Option<String> {
    rename_name_in(name, old, new, &crate::ComponentNamespace::new())
}

/// [`rename_name`] read against a document's components (`namespace`): a
/// token that is a component there (registered, or of the `ACOMP<n>` shape)
/// opens a part's own names, which are never rewritten. For a component
/// rename the namespace holds both the old and the new id.
pub fn rename_name_in(name: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> Option<String> {
    if old.is_empty() || !name.contains(old) {
        return None;
    }
    let mut out = String::with_capacity(name.len() + new.len());
    let mut changed = false;
    let mut segment_start = 0;
    let bytes = name.as_bytes();
    for index in 0..=bytes.len() {
        if index == bytes.len() || bytes[index] == b'|' || bytes[index] == b'#' {
            let (segment, hit) = rename_segment(&name[segment_start..index], old, new, namespace);
            changed |= hit;
            out.push_str(&segment);
            if index < bytes.len() {
                out.push(bytes[index] as char);
            }
            segment_start = index + 1;
        }
    }
    changed.then_some(out)
}

fn rename_segment(segment: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> (String, bool) {
    let tokens: Vec<&str> = segment.split(':').collect();
    let mut out = Vec::with_capacity(tokens.len());
    let mut changed = false;
    let mut foreign = false;
    for (index, token) in tokens.iter().enumerate() {
        if foreign {
            out.push(token.to_string());
            continue;
        }
        let renamed = rename_token(token, old, new);
        changed |= renamed.is_some();
        // A component token followed by more: the rest is the component's part.
        if index + 1 < tokens.len() && namespace.is_component(token) {
            foreign = true;
        }
        out.push(renamed.unwrap_or_else(|| token.to_string()));
    }
    (out.join(":"), changed)
}

fn rename_token(token: &str, old: &str, new: &str) -> Option<String> {
    // A Pattern Component instance names its seed inside: `APAT1.ACOMP3.i4`.
    if token.starts_with("APAT") {
        let parts: Vec<&str> = token.split('.').collect();
        if parts.len() >= 3 && parts[1..parts.len() - 1].join(".") == old && parts[parts.len() - 1].starts_with('i') {
            return Some(format!("{}.{new}.{}", parts[0], parts[parts.len() - 1]));
        }
    }
    let rest = token.strip_prefix(old)?;
    if rest.is_empty() || rest.starts_with(['_', '@', '[', '.', '#']) {
        Some(format!("{new}{rest}"))
    } else {
        None
    }
}

/// Every string and map key the walk would rewrite: `(path, text)`.
fn walk(value: &mut Value, path: &mut Vec<String>, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
    let (old, new) = (r.old, r.new);
    match value {
        Value::String(text) => {
            if let Some(renamed) = rename_name_in(text, old, new, r.namespace) {
                hits.push(path.join("/"));
                if apply {
                    *text = renamed;
                }
            }
        }
        Value::Array(items) => {
            for (index, item) in items.iter_mut().enumerate() {
                path.push(index.to_string());
                walk(item, path, r, apply, hits);
                path.pop();
            }
        }
        Value::Object(map) => {
            let keys: Vec<String> = map.keys().cloned().collect();
            for key in keys {
                if TEXT_KEYS.contains(&key.as_str()) {
                    continue;
                }
                let renamed_key = rename_name_in(&key, old, new, r.namespace);
                path.push(key.clone());
                if renamed_key.is_some() {
                    hits.push(path.join("/"));
                }
                if let Some(child) = map.get_mut(&key) {
                    walk(child, path, r, apply, hits);
                }
                path.pop();
                if let (true, Some(renamed)) = (apply, renamed_key) {
                    if let Some(child) = map.remove(&key) {
                        map.insert(renamed, child);
                    }
                }
            }
        }
        _ => {}
    }
}

/// The places in `document` that name `name` (as an id or the head of a
/// derived name): `/`-joined JSON paths. Empty when the name is free.
pub fn name_uses(document: &Value, name: &str) -> Vec<String> {
    let mut probe = document.clone();
    let mut hits = Vec::new();
    let namespace = crate::component_namespace(document);
    let r = Rename { old: name, new: name, namespace: &namespace, component: namespace.inner(name).is_some() };
    walk_document(&mut probe, &r, false, &mut hits);
    hits
}

/// One rename: the id, its new name, the document's components (with both
/// ids for a component), and whether a component is renamed.
struct Rename<'a> {
    old: &'a str,
    new: &'a str,
    namespace: &'a crate::ComponentNamespace,
    component: bool,
}

/// The keys of the eCAD blocks that hold an assembly OCCURRENCE (a component
/// chain): a part's `instance`, a sub-board zone's `occurrence`. Only a
/// component rename reaches them.
const OCCURRENCE_KEYS: &[&str] = &["instance", "occurrence"];

fn walk_document(document: &mut Value, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
    let Some(map) = document.as_object_mut() else {
        return;
    };
    for (key, value) in map.iter_mut() {
        let mut path = vec![key.clone()];
        if NAMED_BLOCKS.contains(&key.as_str()) {
            walk(value, &mut path, r, apply, hits);
        } else if key == "ports" {
            walk_keys(value, &mut path, PORT_NAME_KEYS, r, apply, hits);
        } else if r.component && ["pcb", "diagram", "symbol", "pads"].contains(&key.as_str()) {
            walk_keys(value, &mut path, OCCURRENCE_KEYS, r, apply, hits);
        }
    }
}

/// Walk `value` rewriting only the values under `keys`, wherever they sit.
fn walk_keys(value: &mut Value, path: &mut Vec<String>, keys: &[&str], r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
    match value {
        Value::Array(items) => {
            for (index, item) in items.iter_mut().enumerate() {
                path.push(index.to_string());
                walk_keys(item, path, keys, r, apply, hits);
                path.pop();
            }
        }
        Value::Object(map) => {
            for (key, child) in map.iter_mut() {
                path.push(key.clone());
                if keys.contains(&key.as_str()) {
                    walk(child, path, r, apply, hits);
                } else {
                    walk_keys(child, path, keys, r, apply, hits);
                }
                path.pop();
            }
        }
        _ => {}
    }
}

/// Whether the expressions text or the configurator uses `name` as a word.
fn expression_names_word(document: &Value, name: &str) -> bool {
    let word = |text: &str| {
        text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| w == name)
    };
    document.get("expressions").and_then(Value::as_str).is_some_and(word)
        || document.get("configurator").and_then(Value::as_object).is_some_and(|m| m.keys().any(|k| word(k)))
}

fn feature_id(feature: &Value) -> Option<&str> {
    let params = feature.get("inputParams")?;
    ["id", "featureID"]
        .iter()
        .find_map(|key| params.get(*key).and_then(Value::as_str).filter(|id| !id.is_empty()))
}

/// Rename feature `old` to `new` throughout `document` (a history document:
/// `features`, `assembly`, `pmi`, `sheets`, ...), in place. On a refusal the
/// document is unchanged and the error says why.
pub fn rename_feature_in_document(document: &mut Value, old: &str, new: &str) -> Result<RenameOutcome, String> {
    if old == new {
        return Err(format!("`{old}` already has that name"));
    }
    validate_name(new)?;
    let features = document.get("features").and_then(Value::as_array).cloned().unwrap_or_default();
    let ids: Vec<&str> = features.iter().filter_map(feature_id).collect();
    if !ids.contains(&old) {
        return Err(format!("no feature is named `{old}`"));
    }
    if crate::feature_pipeline::is_pattern_component_id(old) {
        return Err(format!(
            "`{old}` is a pattern of components: its instances are named `{old}.<seed>.i<n>`, so a pattern keeps its APAT<n> id"
        ));
    }
    // The document's components, with the new id beside the old for a
    // component rename, so both read as one while names are rewritten.
    let mut namespace = crate::component_namespace(document);
    let component = namespace.inner(old).cloned();
    if let Some(inner) = component.clone() {
        namespace.insert(new, inner);
    }
    let r = Rename { old, new, namespace: &namespace, component: component.is_some() };
    if let Some(other) = ids.iter().find(|id| **id != old && rename_name_in(id, old, new, &namespace).is_some()) {
        return Err(format!(
            "feature `{other}` has a name that starts with `{old}`: their references could not be told apart; rename `{other}` first"
        ));
    }
    for name in [old, new] {
        if expression_names_word(document, name) {
            return Err(format!(
                "`{name}` is also an expression or configurator variable: params that use it could not be told from references; rename the variable first"
            ));
        }
    }
    let taken = name_uses(document, new);
    if let Some(first) = taken.first() {
        return Err(format!("`{new}` is already a name in this document (at {first})"));
    }
    let mut hits = Vec::new();
    walk_document(document, &r, true, &mut hits);
    let mut outcome = RenameOutcome { rewritten: hits.len(), ..RenameOutcome::default() };
    for hit in &hits {
        let mut parts = hit.split('/');
        match (parts.next(), parts.next()) {
            (Some("features"), Some(index)) => {
                let id = index.parse::<usize>().ok().and_then(|i| features.get(i)).and_then(feature_id);
                if let Some(id) = id.filter(|id| *id != old) {
                    if !outcome.referencing_features.iter().any(|f| f == id) {
                        outcome.referencing_features.push(id.to_string());
                    }
                }
            }
            (Some(block), _) if block != "features" => {
                if !outcome.blocks.iter().any(|b| b == block) {
                    outcome.blocks.push(block.to_string());
                }
            }
            _ => {}
        }
    }
    Ok(outcome)
}