1use serde_json::Value;
43
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct RenameOutcome {
47 pub rewritten: usize,
49 pub referencing_features: Vec<String>,
52 pub blocks: Vec<String>,
55}
56
57const NAMED_BLOCKS: &[&str] = &["features", "assembly", "pmi", "sheets", "cam", "simulation", "instructions", "exploded"];
63
64const PORT_NAME_KEYS: &[&str] = &["pointRef", "directionRef", "contactBody"];
67
68const 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
83const RESERVED: &[&str] = &["XY", "XZ", "YZ", "ORIGIN", "Math", "configurator"];
85
86pub const MAX_NAME_LEN: usize = 64;
88
89pub 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
118pub fn rename_name(name: &str, old: &str, new: &str) -> Option<String> {
121 rename_name_in(name, old, new, &crate::ComponentNamespace::new())
122}
123
124pub 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 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 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
187fn 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
232pub 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
243struct Rename<'a> {
246 old: &'a str,
247 new: &'a str,
248 namespace: &'a crate::ComponentNamespace,
249 component: bool,
250}
251
252const 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
273fn 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
298fn 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
314pub 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 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