Skip to main content

brep_kernel/feature_pipeline/
family.rs

1//! A family seed's table and the pure functions over it, shared by the CAD app
2//! (`BREP_app/src/family_table.rs`) and the PLM server (`BREP_plm/src/seed.rs`)
3//! so a member the server assembles is the member the CAD app would write, and
4//! a stamp either side writes compares equal.
5//!
6//! The table lives in the family document itself, as the top-level
7//! `familyTable` block: one row per member. A row's values are EXPRESSION
8//! SOURCE, keyed by the expression name a column drives: Generate replaces that
9//! name's definition in the member's `expressions` source with the row's text
10//! ([`rewrite_expressions`]).
11//!
12//! Pure and serde_json-only: no engine, no store, nothing native, so it builds
13//! for wasm as the rest of the kernel does.
14
15use std::collections::BTreeMap;
16
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20/// The document key the family table is stored under.
21pub const FAMILY_TABLE_KEY: &str = "familyTable";
22/// The document key a generated member records its family under.
23pub const FAMILY_SOURCE_KEY: &str = "familySource";
24/// The document key a spun-out copy records its template under.
25pub const TEMPLATE_SOURCE_KEY: &str = "templateSource";
26/// The Save As lineage chain the CAD app writes (identities a part was saved
27/// from). Not the model; members and template instances do not inherit it.
28pub const DERIVED_FROM_KEY: &str = "derivedFrom";
29/// The document key the class is stored under. A normal part writes none.
30pub const DOCUMENT_CLASS_KEY: &str = "documentClass";
31
32/// A family's table: one row per member. A block missing either list reads
33/// as that list empty.
34#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct FamilyTable {
37    #[serde(default)]
38    pub columns: Vec<FamilyColumn>,
39    #[serde(default)]
40    pub rows: Vec<FamilyRow>,
41}
42
43#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct FamilyColumn {
46    /// The expression name this column drives (e.g. `length`).
47    pub name: String,
48    /// Optional display label; empty = show `name`.
49    #[serde(default)]
50    pub label: String,
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct FamilyRow {
56    /// Typed by the user: the member's part number (on the file system, its
57    /// file name `<partNumber>.nbrep`).
58    pub part_number: String,
59    /// The member revision this row writes. The CAD app on the file system
60    /// ignores it; the PLM honours it.
61    #[serde(default)]
62    pub revision: String,
63    #[serde(default)]
64    pub description: String,
65    /// Column name -> expression source text for this row ("12", "m * 2").
66    #[serde(default)]
67    pub values: BTreeMap<String, String>,
68}
69
70/// `row` as Generate uses it: only the values of the table's CURRENT columns,
71/// and only non-empty ones. A cell left empty keeps the family's own
72/// definition; a value left behind by a removed column is ignored.
73pub fn effective_row(table: &FamilyTable, row: &FamilyRow) -> FamilyRow {
74    let mut row = row.clone();
75    row.values.retain(|name, value| {
76        !value.trim().is_empty() && table.columns.iter().any(|column| column.name == *name)
77    });
78    row
79}
80
81/// `expressions` with every statement that defines a name in `values`
82/// replaced, in place, by `name = <value>`, so later statements that use it
83/// see the new value; a name the source never defines is appended. Comments
84/// outside the replaced statements are kept and the rest of the source is
85/// untouched byte for byte. The ONE rewrite: a family row and a template's
86/// spin-out both use it.
87pub fn rewrite_expressions(expressions: &str, values: &BTreeMap<String, String>) -> String {
88    let mut out = expressions.to_string();
89    let mut defined = std::collections::BTreeSet::new();
90    // Splice back to front so earlier spans keep their offsets.
91    for (start, end) in statement_spans(expressions).into_iter().rev() {
92        let Some(name) = assigned_name(&expressions[start..end]) else {
93            continue;
94        };
95        if let Some(value) = values.get(name) {
96            out.replace_range(start..end, &format!("{name} = {}", value.trim()));
97            defined.insert(name.to_string());
98        }
99    }
100    // Appended, not prepended: a cell may use the family's own variables
101    // (`a * 3`), and the evaluator runs statements in order.
102    for (name, value) in values {
103        if !defined.contains(name.as_str()) {
104            if !out.is_empty() && !out.trim_end().ends_with(';') {
105                out.push(';');
106            }
107            if !out.is_empty() && !out.ends_with('\n') {
108                out.push('\n');
109            }
110            out.push_str(&format!("{name} = {};\n", value.trim()));
111        }
112    }
113    out
114}
115
116/// The byte spans of the source's statements: from the first code character
117/// after the previous `;` up to (not including) the next `;` or the end.
118/// `//` comments are skipped, so a comment ahead of a statement is not in its
119/// span and survives a replacement.
120fn statement_spans(source: &str) -> Vec<(usize, usize)> {
121    let bytes = source.as_bytes();
122    let mut spans = Vec::new();
123    let mut start = None;
124    let mut i = 0;
125    while i < bytes.len() {
126        match bytes[i] {
127            b'/' if bytes.get(i + 1) == Some(&b'/') => {
128                while i < bytes.len() && bytes[i] != b'\n' {
129                    i += 1;
130                }
131                continue;
132            }
133            b';' => {
134                if let Some(s) = start.take() {
135                    spans.push((s, i));
136                }
137            }
138            c if !c.is_ascii_whitespace() && start.is_none() => start = Some(i),
139            _ => {}
140        }
141        i += 1;
142    }
143    if let Some(s) = start {
144        spans.push((s, source.len()));
145    }
146    spans
147}
148
149/// The name a statement assigns (`name = rhs`).
150fn assigned_name(statement: &str) -> Option<&str> {
151    let eq = statement.find('=')?;
152    let name = statement[..eq].trim();
153    is_identifier(name).then_some(name)
154}
155
156/// An expression name: a letter, `_` or `$`, then letters, digits, `_`, `$`.
157pub fn is_identifier(name: &str) -> bool {
158    let mut chars = name.chars();
159    chars
160        .next()
161        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
162        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
163}
164
165/// The top-level keys that are NOT the family's model: the table itself (a
166/// row edit must not regenerate every member), the class, the view state the
167/// file reopens in, and stamps.
168pub const NOT_THE_MODEL: [&str; 7] = [
169    FAMILY_TABLE_KEY,
170    // The Save As lineage chain: where the document came from, not its model.
171    DERIVED_FROM_KEY,
172    DOCUMENT_CLASS_KEY,
173    "workbench",
174    FAMILY_SOURCE_KEY,
175    TEMPLATE_SOURCE_KEY,
176    // The embedded preview a CAD save writes into the document: derived from
177    // the model and rendered anew on every save.
178    "thumbnail",
179];
180
181/// A content hash of the family's model: the whole document less the keys in
182/// [`NOT_THE_MODEL`]. Key order does not matter ([`stable_json_hash`]).
183/// Changing it regenerates every member.
184///
185/// [`stable_json_hash`]: crate::stable_json_hash
186pub fn history_hash(family: &Value) -> String {
187    let mut model = family.clone();
188    if let Some(object) = model.as_object_mut() {
189        for key in NOT_THE_MODEL {
190            object.remove(key);
191        }
192    }
193    format!("{:016x}", super::parts_library::stable_json_hash(&model))
194}
195
196/// A content hash of what a row puts into its member: its part number,
197/// description and effective values (not its revision).
198pub fn row_hash(row: &FamilyRow) -> String {
199    let value = serde_json::json!({
200        "partNumber": row.part_number.trim(),
201        "description": row.description.trim(),
202        "values": row.values,
203    });
204    format!("{:016x}", super::parts_library::stable_json_hash(&value))
205}
206