postscriptum 0.1.1

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
//! Static Rhai validation (G7): syntax + `eval()` refusal + unknown
//! roots — a line-port of quartertone's
//! `src/views/expressions.rs` (`unknown_roots` + `uses_dynamic_eval`).
//!
//! UX/early-error ONLY, never the security boundary: nodes the walker
//! cannot classify are ALLOWED (fail open — G1 fuel caps + the G2
//! sandbox are the backstop). `ASTNode` is `non_exhaustive`, so the
//! `_` arms below are load-bearing forward-compat, not laziness: new
//! rhai node kinds must not break the build (verified by compiling,
//! not by enumerating).
//!
//! Requires rhai's `internals` feature (empty, API-only).

use std::collections::HashSet;

use rhai::{AST, Expr, Stmt};

use crate::{ExprIssue, ExprIssueKind};

/// Bare roots the AST references that are neither in `allowed_roots`
/// nor locally declared (`let`/loop vars/fn params). Order-stable,
/// deduplicated. Best-effort (see module docs).
fn unknown_roots(ast: &AST, allowed_roots: &[&str]) -> Vec<String> {
    // Named-function params are in scope inside their bodies.
    let mut declared: HashSet<String> = HashSet::new();
    for meta in ast.iter_functions() {
        declared.extend(meta.params.iter().map(|s| s.to_string()));
    }
    let mut unknown: Vec<String> = Vec::new();

    // `AST::walk` descends automatically (including fn bodies); the
    // callback only classifies the node at the path tip. `let`-style
    // declarations share one flat namespace (no scope popping):
    // block-shadow misses fail OPEN by design, never closed.
    // (No let-chains here — MSRV is 1.85.)
    let mut visit = |path: &[rhai::ASTNode]| {
        let Some(last) = path.last() else {
            return true;
        };
        let node: &rhai::ASTNode = last;
        match node {
            rhai::ASTNode::Stmt(stmt) => match stmt {
                Stmt::Var(boxed, ..) => {
                    declared.insert(boxed.0.name.to_string());
                }
                Stmt::For(boxed, ..) => {
                    declared.insert(boxed.0.name.to_string());
                    if let Some(second) = &boxed.1 {
                        declared.insert(second.name.to_string());
                    }
                }
                _ => {}
            },
            rhai::ASTNode::Expr(expr) => {
                // Port note: quartertone nests `if let` here; let-else
                // keeps every clippy vintage silent with identical
                // semantics (the arm returns `true` either way).
                // Tuple shape is cfg-gated (`no_module` drops two
                // fields) but the NAME stays second in both — `.1`
                // holds across feature sets.
                let Expr::Variable(boxed, ..) = expr else {
                    return true;
                };
                let name = boxed.1.to_string();
                if !allowed_roots.contains(&name.as_str()) && !declared.contains(&name) {
                    unknown.push(name);
                }
            }
            // `ASTNode` is non_exhaustive: future node kinds fail OPEN
            // (runtime isolation is the backstop), never closed.
            _ => {}
        }
        true
    };
    ast.walk(&mut visit);

    // Dedupe, keep first-seen order.
    let mut seen = HashSet::new();
    unknown.retain(|n| seen.insert(n.clone()));
    unknown
}

/// True when the AST calls `eval(...)` anywhere. `eval` is core
/// dispatch (present even in `new_raw`), and eval'd strings defeat the
/// static root check above — so validation refuses it outright with a
/// dedicated issue. (`Fn("eval")` indirection stays possible but runs
/// inside the same fuel + sandbox: bounded, capability-free, and still
/// subject to runtime isolation.)
fn uses_dynamic_eval(ast: &AST) -> bool {
    let mut found = false;
    let mut visit = |path: &[rhai::ASTNode]| {
        if found {
            return false;
        }
        if let Some(last) = path.last() {
            let node: &rhai::ASTNode = last;
            // Top-level `eval(...)` parses as Stmt::FnCall; nested
            // occurrences (e.g. `x = eval(s)`) as Expr::FnCall.
            let name = match node {
                rhai::ASTNode::Stmt(stmt) => {
                    if let Stmt::FnCall(boxed, ..) = stmt {
                        Some(boxed.name.as_str())
                    } else {
                        None
                    }
                }
                rhai::ASTNode::Expr(expr) => {
                    if let Expr::FnCall(boxed, ..) = expr {
                        Some(boxed.name.as_str())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            if name == Some("eval") {
                found = true;
                return false;
            }
        }
        true
    };
    ast.walk(&mut visit);
    found
}

/// Walk an already-compiled AST and collect issues (eval refusal
/// first, then unknown roots — quartertone's order). Message texts
/// mirror quartertone's `validate.rs` so the migration keeps its
/// pins; `locator` is preserved verbatim.
pub(super) fn check_ast(ast: &AST, locator: &str, allowed_roots: &[&str]) -> Vec<ExprIssue> {
    let mut issues = Vec::new();
    if uses_dynamic_eval(ast) {
        issues.push(ExprIssue {
            locator: locator.to_string(),
            message: "dynamic eval() is not allowed in view expressions".to_string(),
            kind: ExprIssueKind::DynamicEval,
        });
    }
    for name in unknown_roots(ast, allowed_roots) {
        issues.push(ExprIssue {
            locator: locator.to_string(),
            message: format!(
                "unknown identifier '{name}' (available: {})",
                allowed_roots.join(", ")
            ),
            kind: ExprIssueKind::UnknownRoot,
        });
    }
    issues
}