Skip to main content

brep_kernel/feature_pipeline/
rename.rs

1//! Rename a feature everywhere it is named (owner 2026-11-27: a TRUE rename).
2//!
3//! A feature's id is also the name of the solid it makes and the head of every
4//! face, edge, frame and sketch child it publishes (`E4:S3:PROFILE_START`,
5//! `CU1_PZ`, `D1:XY`, `S3:G20`, `E4:S3:PROFILE_START|E4:S3:L1_SW`). Those names
6//! are what every other part of the document stores: feature params (reference
7//! fields, boolean targets), sketch external references, assembly constraints,
8//! PMI annotations, sheet views and dimension anchors, ports, wires, CAM,
9//! simulation and instruction blocks. [`rename_feature_in_document`] rewrites
10//! the id and every such name in one pass over the document, so the caller can
11//! adopt the result as ONE history edit (one undo step).
12//!
13//! A name is rewritten per TOKEN, never as a substring:
14//! - a string is split into segments at `|` (an edge between two faces) and `#`
15//!   (a sheet anchor's edge), and each segment into tokens at `:`;
16//! - a token is the old id, or the old id followed by `_`, `@`, `[`, `.` or `#`
17//!   (`CU1_PZ`, `S1@0,0,0`, `Ext_top[0]`), which keeps `E40` and `xE4` untouched;
18//! - after a component token (`ACOMP2:`), the rest of the segment names the
19//!   component's own part and is never touched.
20//!
21//! Only the blocks that hold model entity names are walked (`NAMED_BLOCKS`;
22//! in `ports`, only the keys points are placed by). Free text (labels, notes,
23//! annotation text), the eCAD blocks (reference designators: `D1` is a diode
24//! there), the expression and configurator blocks, the family table and the
25//! parts library are left alone. The
26//! `metadata` block is keyed by names; the engine keeps it apart from the
27//! history and renames its keys with [`rename_name`].
28//!
29//! A COMPONENT renames the same way: its id heads every name of its part
30//! (`ACOMP2:Part_PZ` becomes `Motor:Part_PZ`), a Pattern Component instance
31//! names it inside (`APAT1.ACOMP2.i4` becomes `APAT1.Motor.i4`), and the eCAD
32//! blocks' occurrence keys (`instance`, `occurrence`) follow it. Names are read
33//! against the document's [`crate::ComponentNamespace`], so what follows a
34//! component's id is its part's and is never rewritten.
35//!
36//! Refused by name, so nothing is half renamed: an id that is not a feature,
37//! a pattern of components (`APAT<n>`: its instance ids are read by that
38//! shape), an illegal or reserved name, a name already used in the document,
39//! and an id another feature's id extends (`E4` when `E4_B` exists: its
40//! references could not be told apart).
41
42use serde_json::Value;
43
44/// What a rename changed.
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct RenameOutcome {
47    /// The number of strings (and map keys) rewritten, the id itself included.
48    pub rewritten: usize,
49    /// The ids of the features whose params or data name the renamed one (the
50    /// renamed feature excluded), in document order.
51    pub referencing_features: Vec<String>,
52    /// The top-level blocks other than `features` that were rewritten
53    /// (`assembly`, `pmi`, `sheets`, ...), in document order.
54    pub blocks: Vec<String>,
55}
56
57/// The top-level blocks that hold model entity names, walked whole (less
58/// [`TEXT_KEYS`]). Every other block is left alone: the eCAD blocks (`pcb`,
59/// `symbol`, `pads`, `diagram`) speak reference designators, nets and pin
60/// numbers (`D1` is a diode there and a datum here), and the rest hold
61/// expressions, settings, another document or no names at all.
62const NAMED_BLOCKS: &[&str] = &["features", "assembly", "pmi", "sheets", "cam", "simulation", "instructions", "exploded"];
63
64/// `ports` holds its own port and point names beside the entity names its
65/// points are placed on: only these keys of it are entity names.
66const PORT_NAME_KEYS: &[&str] = &["pointRef", "directionRef", "contactBody"];
67
68/// Keys whose values are free text or codes, never entity names.
69const TEXT_KEYS: &[&str] = &[
70    "type",
71    "partName",
72    "text",
73    "label",
74    "description",
75    "notes",
76    "note",
77    "title",
78    "comment",
79    "prefix",
80    "suffix",
81];
82
83/// Names the scene owns already (the origin planes).
84const RESERVED: &[&str] = &["XY", "XZ", "YZ", "ORIGIN", "Math", "configurator"];
85
86/// The longest name accepted.
87pub const MAX_NAME_LEN: usize = 64;
88
89/// Whether `name` may be given to a feature: a letter, then letters, digits or
90/// `-`, at most [`MAX_NAME_LEN`] long, not reserved and not a component id.
91/// `_`, `:`, `|`, `.`, `@`, `#` and spaces are refused because they are the
92/// separators of the names built from an id.
93pub fn validate_name(name: &str) -> Result<(), String> {
94    if name.is_empty() {
95        return Err("the new name is empty".into());
96    }
97    if name.len() > MAX_NAME_LEN {
98        return Err(format!("the new name is longer than {MAX_NAME_LEN} characters"));
99    }
100    let mut chars = name.chars();
101    if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) {
102        return Err(format!("`{name}` must start with a letter"));
103    }
104    if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '-')) {
105        return Err(format!(
106            "`{name}` has `{bad}`: a name may hold only letters, digits and `-` (`_ : | . @ #` and spaces separate the names built from it)"
107        ));
108    }
109    if RESERVED.contains(&name) {
110        return Err(format!("`{name}` is reserved"));
111    }
112    if crate::is_component_reference(name) || name.starts_with("APAT") {
113        return Err(format!("`{name}` has the form of a component id (ACOMP<n>, APAT<n>)"));
114    }
115    Ok(())
116}
117
118/// `name` with `old` renamed to `new` per the token rule, or `None` when it
119/// does not name `old`.
120pub fn rename_name(name: &str, old: &str, new: &str) -> Option<String> {
121    rename_name_in(name, old, new, &crate::ComponentNamespace::new())
122}
123
124/// [`rename_name`] read against a document's components (`namespace`): a
125/// token that is a component there (registered, or of the `ACOMP<n>` shape)
126/// opens a part's own names, which are never rewritten. For a component
127/// rename the namespace holds both the old and the new id.
128pub fn rename_name_in(name: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> Option<String> {
129    if old.is_empty() || !name.contains(old) {
130        return None;
131    }
132    let mut out = String::with_capacity(name.len() + new.len());
133    let mut changed = false;
134    let mut segment_start = 0;
135    let bytes = name.as_bytes();
136    for index in 0..=bytes.len() {
137        if index == bytes.len() || bytes[index] == b'|' || bytes[index] == b'#' {
138            let (segment, hit) = rename_segment(&name[segment_start..index], old, new, namespace);
139            changed |= hit;
140            out.push_str(&segment);
141            if index < bytes.len() {
142                out.push(bytes[index] as char);
143            }
144            segment_start = index + 1;
145        }
146    }
147    changed.then_some(out)
148}
149
150fn rename_segment(segment: &str, old: &str, new: &str, namespace: &crate::ComponentNamespace) -> (String, bool) {
151    let tokens: Vec<&str> = segment.split(':').collect();
152    let mut out = Vec::with_capacity(tokens.len());
153    let mut changed = false;
154    let mut foreign = false;
155    for (index, token) in tokens.iter().enumerate() {
156        if foreign {
157            out.push(token.to_string());
158            continue;
159        }
160        let renamed = rename_token(token, old, new);
161        changed |= renamed.is_some();
162        // A component token followed by more: the rest is the component's part.
163        if index + 1 < tokens.len() && namespace.is_component(token) {
164            foreign = true;
165        }
166        out.push(renamed.unwrap_or_else(|| token.to_string()));
167    }
168    (out.join(":"), changed)
169}
170
171fn rename_token(token: &str, old: &str, new: &str) -> Option<String> {
172    // A Pattern Component instance names its seed inside: `APAT1.ACOMP3.i4`.
173    if token.starts_with("APAT") {
174        let parts: Vec<&str> = token.split('.').collect();
175        if parts.len() >= 3 && parts[1..parts.len() - 1].join(".") == old && parts[parts.len() - 1].starts_with('i') {
176            return Some(format!("{}.{new}.{}", parts[0], parts[parts.len() - 1]));
177        }
178    }
179    let rest = token.strip_prefix(old)?;
180    if rest.is_empty() || rest.starts_with(['_', '@', '[', '.', '#']) {
181        Some(format!("{new}{rest}"))
182    } else {
183        None
184    }
185}
186
187/// Every string and map key the walk would rewrite: `(path, text)`.
188fn walk(value: &mut Value, path: &mut Vec<String>, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
189    let (old, new) = (r.old, r.new);
190    match value {
191        Value::String(text) => {
192            if let Some(renamed) = rename_name_in(text, old, new, r.namespace) {
193                hits.push(path.join("/"));
194                if apply {
195                    *text = renamed;
196                }
197            }
198        }
199        Value::Array(items) => {
200            for (index, item) in items.iter_mut().enumerate() {
201                path.push(index.to_string());
202                walk(item, path, r, apply, hits);
203                path.pop();
204            }
205        }
206        Value::Object(map) => {
207            let keys: Vec<String> = map.keys().cloned().collect();
208            for key in keys {
209                if TEXT_KEYS.contains(&key.as_str()) {
210                    continue;
211                }
212                let renamed_key = rename_name_in(&key, old, new, r.namespace);
213                path.push(key.clone());
214                if renamed_key.is_some() {
215                    hits.push(path.join("/"));
216                }
217                if let Some(child) = map.get_mut(&key) {
218                    walk(child, path, r, apply, hits);
219                }
220                path.pop();
221                if let (true, Some(renamed)) = (apply, renamed_key) {
222                    if let Some(child) = map.remove(&key) {
223                        map.insert(renamed, child);
224                    }
225                }
226            }
227        }
228        _ => {}
229    }
230}
231
232/// The places in `document` that name `name` (as an id or the head of a
233/// derived name): `/`-joined JSON paths. Empty when the name is free.
234pub fn name_uses(document: &Value, name: &str) -> Vec<String> {
235    let mut probe = document.clone();
236    let mut hits = Vec::new();
237    let namespace = crate::component_namespace(document);
238    let r = Rename { old: name, new: name, namespace: &namespace, component: namespace.inner(name).is_some() };
239    walk_document(&mut probe, &r, false, &mut hits);
240    hits
241}
242
243/// One rename: the id, its new name, the document's components (with both
244/// ids for a component), and whether a component is renamed.
245struct Rename<'a> {
246    old: &'a str,
247    new: &'a str,
248    namespace: &'a crate::ComponentNamespace,
249    component: bool,
250}
251
252/// The keys of the eCAD blocks that hold an assembly OCCURRENCE (a component
253/// chain): a part's `instance`, a sub-board zone's `occurrence`. Only a
254/// component rename reaches them.
255const OCCURRENCE_KEYS: &[&str] = &["instance", "occurrence"];
256
257fn walk_document(document: &mut Value, r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
258    let Some(map) = document.as_object_mut() else {
259        return;
260    };
261    for (key, value) in map.iter_mut() {
262        let mut path = vec![key.clone()];
263        if NAMED_BLOCKS.contains(&key.as_str()) {
264            walk(value, &mut path, r, apply, hits);
265        } else if key == "ports" {
266            walk_keys(value, &mut path, PORT_NAME_KEYS, r, apply, hits);
267        } else if r.component && ["pcb", "diagram", "symbol", "pads"].contains(&key.as_str()) {
268            walk_keys(value, &mut path, OCCURRENCE_KEYS, r, apply, hits);
269        }
270    }
271}
272
273/// Walk `value` rewriting only the values under `keys`, wherever they sit.
274fn walk_keys(value: &mut Value, path: &mut Vec<String>, keys: &[&str], r: &Rename<'_>, apply: bool, hits: &mut Vec<String>) {
275    match value {
276        Value::Array(items) => {
277            for (index, item) in items.iter_mut().enumerate() {
278                path.push(index.to_string());
279                walk_keys(item, path, keys, r, apply, hits);
280                path.pop();
281            }
282        }
283        Value::Object(map) => {
284            for (key, child) in map.iter_mut() {
285                path.push(key.clone());
286                if keys.contains(&key.as_str()) {
287                    walk(child, path, r, apply, hits);
288                } else {
289                    walk_keys(child, path, keys, r, apply, hits);
290                }
291                path.pop();
292            }
293        }
294        _ => {}
295    }
296}
297
298/// Whether the expressions text or the configurator uses `name` as a word.
299fn expression_names_word(document: &Value, name: &str) -> bool {
300    let word = |text: &str| {
301        text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| w == name)
302    };
303    document.get("expressions").and_then(Value::as_str).is_some_and(word)
304        || document.get("configurator").and_then(Value::as_object).is_some_and(|m| m.keys().any(|k| word(k)))
305}
306
307fn feature_id(feature: &Value) -> Option<&str> {
308    let params = feature.get("inputParams")?;
309    ["id", "featureID"]
310        .iter()
311        .find_map(|key| params.get(*key).and_then(Value::as_str).filter(|id| !id.is_empty()))
312}
313
314/// Rename feature `old` to `new` throughout `document` (a history document:
315/// `features`, `assembly`, `pmi`, `sheets`, ...), in place. On a refusal the
316/// document is unchanged and the error says why.
317pub fn rename_feature_in_document(document: &mut Value, old: &str, new: &str) -> Result<RenameOutcome, String> {
318    if old == new {
319        return Err(format!("`{old}` already has that name"));
320    }
321    validate_name(new)?;
322    let features = document.get("features").and_then(Value::as_array).cloned().unwrap_or_default();
323    let ids: Vec<&str> = features.iter().filter_map(feature_id).collect();
324    if !ids.contains(&old) {
325        return Err(format!("no feature is named `{old}`"));
326    }
327    if crate::feature_pipeline::is_pattern_component_id(old) {
328        return Err(format!(
329            "`{old}` is a pattern of components: its instances are named `{old}.<seed>.i<n>`, so a pattern keeps its APAT<n> id"
330        ));
331    }
332    // The document's components, with the new id beside the old for a
333    // component rename, so both read as one while names are rewritten.
334    let mut namespace = crate::component_namespace(document);
335    let component = namespace.inner(old).cloned();
336    if let Some(inner) = component.clone() {
337        namespace.insert(new, inner);
338    }
339    let r = Rename { old, new, namespace: &namespace, component: component.is_some() };
340    if let Some(other) = ids.iter().find(|id| **id != old && rename_name_in(id, old, new, &namespace).is_some()) {
341        return Err(format!(
342            "feature `{other}` has a name that starts with `{old}`: their references could not be told apart; rename `{other}` first"
343        ));
344    }
345    for name in [old, new] {
346        if expression_names_word(document, name) {
347            return Err(format!(
348                "`{name}` is also an expression or configurator variable: params that use it could not be told from references; rename the variable first"
349            ));
350        }
351    }
352    let taken = name_uses(document, new);
353    if let Some(first) = taken.first() {
354        return Err(format!("`{new}` is already a name in this document (at {first})"));
355    }
356    let mut hits = Vec::new();
357    walk_document(document, &r, true, &mut hits);
358    let mut outcome = RenameOutcome { rewritten: hits.len(), ..RenameOutcome::default() };
359    for hit in &hits {
360        let mut parts = hit.split('/');
361        match (parts.next(), parts.next()) {
362            (Some("features"), Some(index)) => {
363                let id = index.parse::<usize>().ok().and_then(|i| features.get(i)).and_then(feature_id);
364                if let Some(id) = id.filter(|id| *id != old) {
365                    if !outcome.referencing_features.iter().any(|f| f == id) {
366                        outcome.referencing_features.push(id.to_string());
367                    }
368                }
369            }
370            (Some(block), _) if block != "features" => {
371                if !outcome.blocks.iter().any(|b| b == block) {
372                    outcome.blocks.push(block.to_string());
373                }
374            }
375            _ => {}
376        }
377    }
378    Ok(outcome)
379}
380