brep_render/engine_state/expressions.rs
1use super::*;
2
3// Expression edits rerun the current history prefix so parameters that reference
4// variables rebuild against the updated environment.
5impl EngineState {
6 /// The history's `expressions` source string (the variable sheet the panel's
7 /// editor binds to). Raw source text — despite the `_json` suffix it mirrors
8 /// the other engine readouts' naming; the verifier reads it verbatim.
9 pub fn expressions_json(&self) -> String {
10 self.history.expressions()
11 }
12
13 /// Replace the `expressions` source and re-run the rolled-to prefix so every
14 /// feature param referencing a variable (e.g. `sizeX = "boxW"`) rebuilds with
15 /// the new value — the panel's live-update path. Returns the build-report JSON.
16 ///
17 /// The source is stored one statement per line
18 /// ([`brep_kernel::format_expressions`]): statements typed or sent on one
19 /// line are split onto lines of their own, text that does not parse is
20 /// stored as given. [`Self::expressions_json`] reads back what was stored.
21 pub fn set_expressions(&mut self, expressions: &str) -> String {
22 self.history.set_expressions(&brep_kernel::format_expressions(expressions));
23 self.rerun_history()
24 }
25
26 /// Show the model evaluated with `preview`'s expressions source instead of
27 /// the document's own, or (`None`) with the document's own again. Runs the
28 /// history when what the runs evaluate changes; re-arming the same source
29 /// runs nothing. Returns the build report.
30 ///
31 /// TRANSIENT by construction: the source is substituted into the run
32 /// REQUEST only (`Self::rerun_history`), never into the history, so the
33 /// document, its undo stacks, its dirty state and what Save writes are
34 /// untouched.
35 ///
36 /// The preview is armed against the history's current
37 /// [`edit_serial`](crate::history::History::edit_serial). The first run
38 /// after the user edits the model (or undoes, or redoes) drops it, so the
39 /// edit rebuilds against the document's own values and nothing previewed
40 /// is shown under it. A host that edits the document ITSELF while
41 /// previewing (the family table writing a cell) re-arms after the write.
42 pub fn set_expression_preview(&mut self, preview: Option<ExpressionPreview>) -> String {
43 let serial = self.history.edit_serial();
44 // What the display was last BUILT with: the stored preview even when
45 // an edit has made it stale, so ending a preview that a block write
46 // (which runs nothing) left on screen still rebuilds.
47 let before = self.expression_preview.as_ref().map(|p| p.expressions.clone());
48 let after = preview.as_ref().map(|p| p.expressions.clone());
49 self.expression_preview = preview.map(|p| ExpressionPreview { serial, ..p });
50 if before == after {
51 return self.history_report.clone();
52 }
53 self.rerun_history()
54 }
55
56 /// Re-arm the stored preview at the history's current edit serial,
57 /// running nothing: for a host that has just edited the document itself
58 /// (the family table committing a cell) and keeps previewing.
59 pub fn rearm_expression_preview(&mut self) {
60 let serial = self.history.edit_serial();
61 if let Some(preview) = self.expression_preview.as_mut() {
62 preview.serial = serial;
63 }
64 }
65
66 /// The preview in force: `None` when there is none, or when the user has
67 /// edited the model since it was armed (the next run drops it).
68 pub fn expression_preview(&self) -> Option<&ExpressionPreview> {
69 self.live_expression_preview()
70 }
71
72 fn live_expression_preview(&self) -> Option<&ExpressionPreview> {
73 self.expression_preview
74 .as_ref()
75 .filter(|p| p.serial == self.history.edit_serial())
76 }
77
78 /// Drop a preview the user has edited the model under.
79 pub(super) fn drop_stale_expression_preview(&mut self) {
80 if self.live_expression_preview().is_none() {
81 self.expression_preview = None;
82 }
83 }
84
85 /// The rolled-to prefix as a run REQUEST: [`History::prefix_request`]
86 /// with the live preview's expressions in place of the document's. Every
87 /// execution of the model — the display run and the main-side re-runs
88 /// that measure, export or pick against it — builds from this, so what is
89 /// measured is what is shown.
90 ///
91 /// [`History::prefix_request`]: crate::history::History::prefix_request
92 pub(super) fn run_request_value(&self) -> serde_json::Value {
93 let mut request = self.history.prefix_request();
94 if let (Some(preview), Some(object)) = (self.live_expression_preview(), request.as_object_mut()) {
95 object.insert("expressions".into(), serde_json::Value::String(preview.expressions.clone()));
96 }
97 request
98 }
99
100 /// The history's `configurator` object (typed named inputs) as JSON — a
101 /// read/display surface for the panel; deeper configurator editing is deferred.
102 pub fn configurator_json(&self) -> String {
103 self.history.configurator().to_string()
104 }
105
106 /// The parsed variable list for the sheet's name/value view:
107 /// `[{ "name": "...", "expr": "..." }, …]` — one entry per `name = rhs;`
108 /// assignment in the expressions source, in source order. The RHS is shown
109 /// verbatim (its DEFINING expression); evaluating it to a live scalar needs the
110 /// kernel's private `Env`, so a computed value column is deferred — the text
111 /// editor + re-run is the source of truth for applied values.
112 pub fn expression_variables_json(&self) -> String {
113 let vars = parse_expression_variables(&self.history.expressions());
114 serde_json::to_string(&vars).unwrap_or_else(|_| "[]".to_string())
115 }
116}
117
118/// Parse the `name = rhs;` assignments from an expressions source into an ordered
119/// `[{name, expr}]` list for the sheet's variable view. Mirrors the kernel
120/// evaluator's statement grammar (`IDENT '=' expr ';'`) without reaching into its
121/// private `Env`: `//` line comments are stripped, statements split on `;`, and
122/// each `IDENT = rhs` yields one entry (a non-identifier LHS or empty RHS is
123/// skipped, matching what the evaluator would reject).
124fn parse_expression_variables(source: &str) -> Vec<serde_json::Value> {
125 // Strip `//` line comments line-by-line (the DSL has no strings, so a bare
126 // `//` always starts a comment), then split statements on ';'.
127 let mut cleaned = String::with_capacity(source.len());
128 for line in source.lines() {
129 let code = match line.find("//") {
130 Some(idx) => &line[..idx],
131 None => line,
132 };
133 cleaned.push_str(code);
134 cleaned.push('\n');
135 }
136 let mut out = Vec::new();
137 for stmt in cleaned.split(';') {
138 let stmt = stmt.trim();
139 if stmt.is_empty() {
140 continue;
141 }
142 let Some(eq) = stmt.find('=') else {
143 continue;
144 };
145 let name = stmt[..eq].trim();
146 let expr = stmt[eq + 1..].trim();
147 if name.is_empty() || expr.is_empty() || !is_identifier(name) {
148 continue;
149 }
150 out.push(serde_json::json!({ "name": name, "expr": expr }));
151 }
152 out
153}
154
155/// Whether `s` is a single expression-DSL identifier (`[A-Za-z_$][A-Za-z0-9_$]*`)
156/// — the valid LHS of an assignment statement.
157fn is_identifier(s: &str) -> bool {
158 let mut chars = s.chars();
159 match chars.next() {
160 Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
161 _ => return false,
162 }
163 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
164}
165
166
167
168/// A transient expressions source for [`EngineState::set_expression_preview`].
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct ExpressionPreview {
171 /// The whole expressions source the runs evaluate while it is in force.
172 pub expressions: String,
173 /// What is being previewed, for the working indicator (a part number).
174 pub label: String,
175 /// The history's edit serial it was armed at (set by the engine).
176 pub serial: u64,
177}
178
179impl ExpressionPreview {
180 pub fn new(expressions: impl Into<String>, label: impl Into<String>) -> Self {
181 Self { expressions: expressions.into(), label: label.into(), serial: 0 }
182 }
183}
184