BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
use super::*;

// ============================================================================
// Expressions / parameters (appended — the expressions/parameters panel slice).
// A SEPARATE `impl` block so concurrent edits to the primary block do not
// conflict; additive over the existing history API. The engine-owned `History`
// carries an `expressions` source that feature params evaluate against (a numeric
// param may be the string `"boxW"`, resolved by the pipeline's shared expression
// env). Editing it here re-runs the rolled-to prefix so every var-referencing
// param rebuilds live.
// ============================================================================
impl EngineState {
    /// The history's `expressions` source string (the variable sheet the panel's
    /// editor binds to). Raw source text — despite the `_json` suffix it mirrors
    /// the other engine readouts' naming; the verifier reads it verbatim.
    pub fn expressions_json(&self) -> String {
        self.history.expressions()
    }

    /// Replace the `expressions` source and re-run the rolled-to prefix so every
    /// feature param referencing a variable (e.g. `sizeX = "boxW"`) rebuilds with
    /// the new value — the panel's live-update path. Returns the build-report JSON.
    pub fn set_expressions(&mut self, expressions: &str) -> String {
        self.history.set_expressions(expressions);
        self.rerun_history()
    }

    /// The history's `configurator` object (typed named inputs) as JSON — a
    /// read/display surface for the panel; deeper configurator editing is deferred.
    pub fn configurator_json(&self) -> String {
        self.history.configurator().to_string()
    }

    /// The parsed variable list for the sheet's name/value view:
    /// `[{ "name": "...", "expr": "..." }, …]` — one entry per `name = rhs;`
    /// assignment in the expressions source, in source order. The RHS is shown
    /// verbatim (its DEFINING expression); evaluating it to a live scalar needs the
    /// kernel's private `Env`, so a computed value column is deferred — the text
    /// editor + re-run is the source of truth for applied values.
    pub fn expression_variables_json(&self) -> String {
        let vars = parse_expression_variables(&self.history.expressions());
        serde_json::to_string(&vars).unwrap_or_else(|_| "[]".to_string())
    }
}

/// Parse the `name = rhs;` assignments from an expressions source into an ordered
/// `[{name, expr}]` list for the sheet's variable view. Mirrors the kernel
/// evaluator's statement grammar (`IDENT '=' expr ';'`) without reaching into its
/// private `Env`: `//` line comments are stripped, statements split on `;`, and
/// each `IDENT = rhs` yields one entry (a non-identifier LHS or empty RHS is
/// skipped, matching what the evaluator would reject).
fn parse_expression_variables(source: &str) -> Vec<serde_json::Value> {
    // Strip `//` line comments line-by-line (the DSL has no strings, so a bare
    // `//` always starts a comment), then split statements on ';'.
    let mut cleaned = String::with_capacity(source.len());
    for line in source.lines() {
        let code = match line.find("//") {
            Some(idx) => &line[..idx],
            None => line,
        };
        cleaned.push_str(code);
        cleaned.push('\n');
    }
    let mut out = Vec::new();
    for stmt in cleaned.split(';') {
        let stmt = stmt.trim();
        if stmt.is_empty() {
            continue;
        }
        let Some(eq) = stmt.find('=') else {
            continue;
        };
        let name = stmt[..eq].trim();
        let expr = stmt[eq + 1..].trim();
        if name.is_empty() || expr.is_empty() || !is_identifier(name) {
            continue;
        }
        out.push(serde_json::json!({ "name": name, "expr": expr }));
    }
    out
}

/// Whether `s` is a single expression-DSL identifier (`[A-Za-z_$][A-Za-z0-9_$]*`)
/// — the valid LHS of an assignment statement.
fn is_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

#[cfg(test)]
mod expressions_tests {
    use super::*;

    /// The X-extent (bbox width) of a solid in the current scene.
    fn extent_x(engine: &EngineState, name: &str) -> f64 {
        let s = engine.scene.solid(name).expect("solid present");
        s.bbox.max[0] - s.bbox.min[0]
    }

    /// A single-cube history whose `sizeX` is an EXPRESSION STRING referencing the
    /// variable `boxW` (defined in `expressions`); sizeY/sizeZ are plain numbers.
    fn var_cube_request(expressions: &str) -> String {
        serde_json::json!({
            "expressions": expressions,
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": "Var",
                    "sizeX": "boxW", "sizeY": 20.0, "sizeZ": 20.0,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    #[test]
    fn expressions_drive_feature_param_and_resize_live() {
        let mut engine = EngineState::new();
        // A cube whose width is the variable `boxW = 30`.
        engine.set_history_json(&var_cube_request("boxW = 30;")).unwrap();
        let x0 = extent_x(&engine, "Var");
        assert!((x0 - 30.0).abs() < 1e-6, "sizeX resolved from boxW=30: {x0}");

        // EDIT the sheet (the panel's path): boxW = 50 → the cube grows LIVE, no
        // feature-param edit needed (the param still reads `"boxW"`).
        engine.set_expressions("boxW = 50;");
        let x1 = extent_x(&engine, "Var");
        assert!(x1 > x0 + 10.0, "raising boxW resized the cube: {x1} > {x0}");
        assert!((x1 - 50.0).abs() < 1e-6, "sizeX now resolves to 50: {x1}");

        // The getter reflects the applied source, and the variable list parses it.
        assert_eq!(engine.expressions_json(), "boxW = 50;");
        let vars: serde_json::Value =
            serde_json::from_str(&engine.expression_variables_json()).unwrap();
        assert_eq!(vars[0]["name"], "boxW");
        assert_eq!(vars[0]["expr"], "50");
    }

    #[test]
    fn parse_variables_handles_comments_and_computed_rhs() {
        let vars = parse_expression_variables(
            "boxW = 30; // width\nboxH = boxW / 2;\n; \n7 = bad;",
        );
        // Two valid assignments; the empty statement and the numeric LHS are dropped.
        assert_eq!(vars.len(), 2);
        assert_eq!(vars[0]["name"], "boxW");
        assert_eq!(vars[0]["expr"], "30");
        assert_eq!(vars[1]["name"], "boxH");
        assert_eq!(vars[1]["expr"], "boxW / 2");
    }
}