Lines
98.36 %
Functions
80.77 %
Branches
100 %
//! Depth-guarded datum walk (ADR-0034 / plan 0011 Phase 0).
//!
//! [`cost`] gives the work-unit charge for an `Expr` datum — one unit per
//! node — for macro expansion output and constant-folded data. The walk
//! recurses the native stack one frame per nesting level, so it carries
//! its own depth guard rather than relying on the caller to bound the
//! datum's shape first.
use std::cell::Cell;
use crate::ast::Expr;
use crate::error::{Error, Result};
use crate::reader::MAX_READ_DEPTH;
use crate::runtime::{Closure, SymbolTable, Value, with_sufficient_stack};
/// Ceiling on datum nesting a single [`cost`] walk accepts.
///
/// Derived from a source-level fact rather than a stack measurement: the
/// reader's `MAX_READ_DEPTH` already bounds how deeply a datum written in
/// source can nest, and no macro here multiplies that nesting per expansion
/// round, so twice it keeps a 2x margin. A measurement alone is not
/// compositional — `cost` runs inside `expand_macro_then`, itself up to
/// `MAX_SHARED_RECURSION_DEPTH` frames deep, each already holding a large
/// share of the same stack.
/// One counted level can carry two native `Expr` levels, since a `Quote`
/// directly around a list walks at its child's depth, so a walk at this
/// ceiling recurses roughly twice it.
pub(crate) const MAX_ELAB_DEPTH: usize = 2 * MAX_READ_DEPTH;
/// `expr`, refused when it nests deeper than [`MAX_ELAB_DEPTH`]. Compile-time
/// evaluation passes every datum it builds from evaluated values through
/// this, so an accumulator cannot grow deep enough for `Expr`'s recursive
/// `Clone`/`Drop` to overflow the native stack. The datum's [`cost`] is
/// charged to the work budget, so a loop that rebuilds a growing list pays
/// for every copy, not one unit per call.
pub(crate) fn bounded(symbols: &SymbolTable, expr: Expr) -> Result<Expr> {
symbols.charge_work(cost(&expr)?)?;
Ok(expr)
}
/// Work-unit cost of `expr`: one unit per node, guarded so a
/// pathologically deep datum fails structurally instead of overflowing
/// the native stack while being counted. A `Quote` directly around a list
/// or cons adds no level, so the ceiling counts user-visible nesting; a
/// compile-time `Value` (struct, pair, vector, closure env) is walked too.
pub(crate) fn cost(expr: &Expr) -> Result<u64> {
cost_at_depth(expr, 0, &Cell::new(0))
/// Deepest nesting level of `expr`, guarded like [`cost`].
pub(crate) fn nesting(expr: &Expr) -> Result<usize> {
let deepest = Cell::new(0);
cost_at_depth(expr, 0, &deepest)?;
Ok(deepest.get())
/// Refuses a datum nested deeper than [`MAX_ELAB_DEPTH`].
fn check_depth(depth: usize, deepest: &Cell<usize>) -> Result<()> {
deepest.set(deepest.get().max(depth));
if depth > MAX_ELAB_DEPTH {
return Err(Error::Resource(format!(
"datum nesting exceeded the elaboration depth limit of {MAX_ELAB_DEPTH} levels"
)));
Ok(())
fn cost_at_depth(expr: &Expr, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
check_depth(depth, deepest)?;
let children = with_sufficient_stack(|| child_cost(expr, depth, deepest))?;
Ok(1 + children)
fn value_cost_at_depth(value: &Value, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
let children = with_sufficient_stack(|| value_children_cost(value, depth, deepest))?;
fn value_children_cost(value: &Value, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
Ok(match value {
Value::Pair(pair) => {
value_cost_at_depth(&pair.car, depth + 1, deepest)?
+ value_cost_at_depth(&pair.cdr, depth + 1, deepest)?
Value::Vector(items) | Value::Closure(Closure { env: items, .. }) => items
.iter()
.map(|item| value_cost_at_depth(item, depth + 1, deepest))
.sum::<Result<u64>>()?,
Value::Struct { fields, .. } => fields
.map(|(_, item)| value_cost_at_depth(item, depth + 1, deepest))
Value::Nil
| Value::T
| Value::Number(_)
| Value::String(_)
| Value::Symbol(_)
| Value::Bytes(_)
| Value::Condition
| Value::Commodity { .. } => 0,
})
fn child_cost(expr: &Expr, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
match expr {
Expr::Cons(car, cdr) => {
Ok(cost_at_depth(car, depth + 1, deepest)? + cost_at_depth(cdr, depth + 1, deepest)?)
Expr::List(items) => items
.map(|item| cost_at_depth(item, depth + 1, deepest))
.sum(),
Expr::Quote(inner) | Expr::Datum(inner)
if matches!(inner.as_ref(), Expr::List(_) | Expr::Cons(_, _)) =>
{
cost_at_depth(inner, depth, deepest)
Expr::Quote(inner)
| Expr::Datum(inner)
| Expr::Quasiquote(inner)
| Expr::Unquote(inner)
| Expr::UnquoteSplicing(inner) => cost_at_depth(inner, depth + 1, deepest),
Expr::Lambda(params, body) => {
let mut total = cost_at_depth(body, depth + 1, deepest)?;
for value in params.defaults() {
total += cost_at_depth(value, depth + 1, deepest)?;
Ok(total)
Expr::RuntimeValue(value) => value_cost_at_depth(value, depth + 1, deepest),
Expr::Nil
| Expr::T
| Expr::Number(_)
| Expr::String(_)
| Expr::Symbol(_)
| Expr::Keyword(_)
| Expr::Bytes(_)
| Expr::WasmRuntime(_)
| Expr::WasmLocal(_, _)
| Expr::WasmGlobal(_, _)
| Expr::Instance(_, _) => Ok(0),
#[cfg(test)]
#[path = "datum_tests.rs"]
mod tests;