Persistent names read by one parser; four misreadings fixed (#5814) (#5966)

* doc: persistent names read as their structure; joint.inspect splits an edge with a blend face first

`persistent_name::{FaceName, EdgeName}` parse a face or edge name once (blends, inner walls,
copies, pieces, numbered pieces, `~k`) and write it back as the same text, bounded against
hostile input. A suffix after a blend's edge naming a later feature belongs to the blend face.

joint.inspect split an edge at its first `|`, so an edge whose first face is a blend
(`F4:blend:F3:+x|F3:+z#[…]|F5:-y`) came back as a cut-off blend name and a string that is no
face. It now uses `EdgeName::parse`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* doc: persistent names as typed values: features, roles, suffixes, a lexer and errors that say where

`FaceName` is a base (made by a feature in a role, a blend and the edge it rounds, an inner
wall, a body's face by index, other text) and its suffixes (copy, piece, numbered piece).
Roles are typed where the vocabulary is known (top, side:<curve>, +x, face:<k>, …) and kept as
written otherwise. The text form is lexed into tokens and read by the grammar in the module's
doc; a name that doesn't read says where and what was expected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* names: read what made a face, its kind and its feature ids through persistent_name

The places that took a name apart by hand to find the feature that made a face, whether it is
a blend, a copy, a numbered piece or a wall, or to remap feature ids on copy, now ask the typed
name (`made_by`, `split_feature`, `is_blend`, `is_copy`, `is_numbered_piece`, `is_wall`,
`features`, `map`). A name that doesn't read falls back to the old text check.

- An offset of a face that only names a blend inside it (`F2:top#[F5:blend:…]`) is no longer
  taken for a fillet's.
- Copying a component remaps feature ids inside a piece's `#[…]` too.
- A shell's inner wall split by a later cut keeps the qualifier on the wall.
- joint.inspect finds the sketch curve of a copied side (`side:l1@F7.2`).

Finding a face by name (strip_piece, parent_piece) is unchanged: it reads a trailing
qualifier as the whole name's and moves once the text form says where it belongs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* engine: regression tests for press-pull on a wall that only names a fillet and joint.inspect on a copied side

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* names: an edge holds one face or more; made_by reads only the leading token

An open boundary's edge has one face and an edge several faces meet at has more, so an edge name
is a list of faces (a blend's own edge still takes two at most, as before). `made_by` reads just
the leading `F<n>:`, which every name a feature made starts with, so asking it of every face
each frame stays cheap. Names are read up to 1 MiB: a face engraved with text has piece names
past 4 KiB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* persistent_name: split into lexer, parser, write, text and tests

No code changed; callers' paths stay the same (`pub use text::*`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
JIJINBEI
2026-10-25 01:48:26 +00:00
committed by GitHub
parent 3f6b9fe89f
commit cdde7d62b2
23 changed files with 1179 additions and 61 deletions
@@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
use solidcraft_doc::Document;
use solidcraft_doc::joints::cam::CamProfile;
use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size};
use solidcraft_doc::persistent_name::{Base, FaceName, FeatureId, Place};
use crate::{EngineError, Result};
@@ -182,6 +183,27 @@ fn validate_map<K: Ord, V: Ord>(map: &BTreeMap<K, V>) -> Result<()> {
/// alter F10). Body-based legacy names are remapped only through an explicit identity map.
fn face_name(name: &str, features: &BTreeMap<u64, u64>, bodies: &BTreeMap<String, String>) -> Option<String> {
let body = name.match_indices(':').filter_map(|(end, _)| bodies.get_key_value(name.get(..end)?)).next_back();
// A name that reads, on no copied body's prefix (whose name may look like a feature token),
// is remapped by its structure: every feature that made a face must map; one around a piece
// (`#[…]`) maps when it was copied too.
if body.is_none()
&& let Ok(face) = FaceName::parse(name)
&& !matches!(face.base, Base::Other(_))
{
let mut body_mapped = false;
let out = face.map(
&mut |id, place| match place {
Place::Name => features.get(&id.0).map(|n| FeatureId(*n)),
Place::Qualifier => Some(features.get(&id.0).map_or(id, |n| FeatureId(*n))),
},
&mut |b| {
let n = bodies.get(b).cloned();
body_mapped |= n.is_some();
n
},
)?;
return (body_mapped || face.made_by().is_some()).then(|| out.to_string());
}
let mut out = String::new();
let mut last = 0usize;
let mut mapped = false;
@@ -153,6 +153,9 @@ fn naming_remaps_exact_tokens_unicode_and_legacy_body_identity() {
assert!(face_name("F1:start@F99.1", &features, &bodies).is_none());
assert!(face_name("Foreign:face:0", &features, &bodies).is_none());
assert!(face_name("Foreign:face:0@F1.1", &features, &bodies).is_none());
// A piece's faces around it are copied too; one from a feature not copied stays.
assert_eq!(face_name("F1:top#[F1:side:l2,F10:side:l2]", &features, &bodies).as_deref(), Some("F21:top#[F21:side:l2,F30:side:l2]"));
assert_eq!(face_name("F1:top#[F99:x]", &features, &bodies).as_deref(), Some("F21:top#[F99:x]"));
let bodies = BTreeMap::from([("F1:Housing".into(), "F1:Housing (copy)".into())]);
assert_eq!(face_name("F1:Housing:face:0@F10.1", &features, &bodies).as_deref(), Some("F1:Housing (copy):face:0@F30.1"));
}
+5 -1
View File
@@ -180,7 +180,11 @@ fn show(s: &mut Session, _p: &Value) -> Result<Value> {
format!("Component: {}", s.doc.components.iter().find(|c| c.id == *id).map(|c| c.name.clone()).unwrap_or_else(|| id.to_string()))
}
Column::FaceAppearance(target) => {
format!("Face: {} / {}", target.body, target.name.split_once(':').map(|(_, role)| role).unwrap_or(&target.name))
format!(
"Face: {} / {}",
target.body,
solidcraft_doc::persistent_name::split_feature(&target.name).map(|(_, role)| role).unwrap_or(&target.name)
)
}
_ => s.doc.config_key(column),
};
+2 -2
View File
@@ -1203,8 +1203,8 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
&& super::face::face_is_planar(s, fp) == Some(false)
{
let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default();
let fid = name.strip_prefix('F').and_then(|r| r.split(':').next()).and_then(|x| x.parse::<u64>().ok());
if name.contains(":blend") {
let fid = solidcraft_doc::persistent_name::made_by(&name);
if solidcraft_doc::persistent_name::is_blend(&name) {
let f = fid.and_then(|id| s.doc.feature(id)).cloned().ok_or_else(|| bad(cmd, "the blend's feature is gone"))?;
let (key, old) = match &f.kind {
FeatureKind::Fillet { radius, .. } => ("radius", radius.clone()),
+12 -28
View File
@@ -5,7 +5,8 @@
use serde_json::{Value, json};
use solidcraft_doc::joints::{self, Joint, JointOrigin, Snap, XRef};
use solidcraft_doc::naming::{legacy_name, strip_piece};
use solidcraft_doc::naming::legacy_name;
use solidcraft_doc::persistent_name::{Base, EdgeName, FaceName, Role};
use solidcraft_doc::{Document, MAX_PLACEMENT_DEPTH, ModelState};
use super::{component_of, joint_id, link_json, named_values, occurrence_name};
@@ -171,26 +172,20 @@ fn face_ref(doc: &Document, name: &str) -> Value {
}
None => name,
};
let stem = strip_piece(bare);
let Some((fid, role)) = stem.strip_prefix('F').and_then(|r| r.split_once(':')).and_then(|(id, role)| Some((id.parse::<u64>().ok()?, role)))
else {
return v;
};
v["role_in_feature"] = json!(role);
let Ok(face) = FaceName::parse(bare) else { return v };
let Some(fid) = face.made_by().map(|id| id.0) else { return v };
let stem = face.stem().to_string();
v["role_in_feature"] = json!(stem.strip_prefix(&format!("F{fid}:")).unwrap_or(&stem));
let Some(f) = doc.feature(fid) else {
v["feature"] = json!({"id": fid, "error": format!("feature {fid} is gone")});
return v;
};
v["feature"] = json!({"id": f.id, "name": f.name, "type": f.kind.type_name()});
if let Some(curve) = role.strip_prefix("side:") {
// A later profile's side is `s<k>.<curve>`.
let curve = curve
.split_once('.')
.filter(|(k, _)| k.strip_prefix('s').is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
.map_or(curve, |(_, c)| c);
// A side swept from a sketch curve (a later profile's too, `side:s<k>.<curve>`).
if let Base::Made { role: Role::Side { curve, .. }, .. } = &face.base {
let found = f.kind.input_sketches().into_iter().find_map(|id| {
let sk = doc.sketch(id).ok()?;
let c = sk.curves.iter().find(|c| c.id == curve)?;
let c = sk.curves.iter().find(|c| c.id == *curve)?;
let curve_type = serde_json::to_value(&c.kind).ok().and_then(|k| k.get("type").cloned()).unwrap_or(Value::Null);
let name = doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
Some(json!({"id": id, "name": name, "curve": curve, "curve_type": curve_type}))
@@ -204,20 +199,9 @@ fn face_ref(doc: &Document, name: &str) -> Value {
/// what each of its faces refers to.
fn edge_ref(doc: &Document, name: &str) -> Value {
let bare = legacy_name(name).unwrap_or(name);
let bare = bare.rsplit_once('~').filter(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())).map_or(bare, |(e, _)| e);
// Split at the `|` outside a piece's `#[…]`.
let mut depth = 0i32;
let split = bare.char_indices().find(|(_, c)| {
match c {
'[' => depth += 1,
']' => depth -= 1,
_ => {}
}
*c == '|' && depth == 0
});
let faces: Vec<Value> = match split {
Some((i, _)) => [bare.get(..i), bare.get(i + 1..)].into_iter().flatten().map(|f| face_ref(doc, f)).collect(),
None => Vec::new(),
let faces: Vec<Value> = match EdgeName::parse(bare) {
Ok(e) => e.faces.iter().map(|f| face_ref(doc, &f.to_string())).collect(),
Err(_) => Vec::new(),
};
let mut v = json!({"name": name, "faces": faces});
if legacy_name(name).is_some() {
+59
View File
@@ -1937,6 +1937,65 @@ fn joint_inspect_reports_a_lost_origin() {
assert_eq!(hinge["a"]["resolves"], true);
}
/// An edge whose first face is a fillet's: the fillet face's name holds the edge it rounds
/// (`F2:blend:<face>|<face>`), so the edge's two faces are the whole blend name and the slot's
/// wall, not the blend name cut at its own `|`.
#[test]
fn joint_inspect_splits_an_edge_of_a_blend_face_into_its_two_faces() {
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Base"}));
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "corner": [0, 0, 0]}));
run(&mut s, "solid.fillet", json!({"edges": [[40, 20, 10]], "radius": 3}));
run(&mut s, "solid.box", json!({"length": 10, "width": 4, "height": 20, "corner": [32, 18, -5], "operation": "cut"}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Cap"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "corner": [200, 0, 0]}));
// On the slot's wall y = 18, halfway round the fillet (axis x = 37, z = 7, r = 3).
let h = 3.0 * std::f64::consts::FRAC_1_SQRT_2;
run(
&mut s,
"joint.create",
json!({"type": "rigid", "name": "OnBlend", "a": {"occurrence": "Base", "edge": [37.0 + h, 18, 7.0 + h]},
"b": {"occurrence": "Cap", "face": [205, 5, 5]}}),
);
let j = run(&mut s, "joint.inspect", json!({"joint": "OnBlend"}))["joints"][0].clone();
let edge = reference(&j, "a", "edge");
let name = edge["name"].as_str().unwrap_or_default().to_string();
let faces: Vec<String> = edge["faces"].as_array().into_iter().flatten().filter_map(|f| f["name"].as_str().map(str::to_string)).collect();
// `F4:blend:F3:+x|F3:+z#[F3:-y,F5:-y]|F5:-y`: the blend piece beside the slot, and the slot's wall.
assert!(name.split_once(':').is_some_and(|(_, r)| r.starts_with("blend:")), "the blend face comes first: {name}");
assert_eq!(faces.len(), 2, "{edge}");
assert_eq!(format!("{}|{}", faces[0], faces[1]), name, "{edge}");
assert!(faces[0].contains(":blend:") && faces[0].contains('|'), "{edge}");
assert!(!faces[1].contains('|'), "{edge}");
}
/// A joint on a pattern's copy of a pin: the copy's wall (`F3:side:c1@F4.1`) still names the
/// sketch curve it was swept from, `c1`.
#[test]
fn joint_inspect_finds_the_sketch_curve_of_a_copied_side() {
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Pins"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "PinSketch"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5, "id": "c1"}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 20, "name": "Pin"}));
run(&mut s, "solid.pattern.rectangular", json!({"features": ["Pin"], "dir1": [1, 0, 0], "count1": 2, "spacing1": 30}));
run(&mut s, "component.activate", json!({"component": "root"}));
run(&mut s, "component.create", json!({"name": "Cap"}));
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "corner": [200, 0, 0]}));
run(
&mut s,
"joint.create",
json!({"type": "revolute", "name": "OnCopy", "a": {"occurrence": "Pins", "circle": [35, 0, 20]}, "b": {"occurrence": "Cap", "face": [205, 5, 5]}}),
);
let j = run(&mut s, "joint.inspect", json!({"joint": "OnCopy"}))["joints"][0].clone();
let wall = reference(&j, "a", "face");
assert!(wall["name"].as_str().is_some_and(|n| n.contains(":side:c1@F")), "a copy's wall: {j}");
assert_eq!((&wall["sketch"]["curve"], &wall["sketch"]["name"]), (&json!("c1"), &json!("PinSketch")), "{j}");
assert!(wall["sketch"]["error"].is_null(), "{j}");
}
/// `joint.inspect` reads only: no undo step, the design unchanged, and the id agents' gates
/// treat as reading (`*.inspect`).
#[test]