1
//! Depth-guarded datum walk (ADR-0034 / plan 0011 Phase 0).
2
//!
3
//! [`cost`] gives the work-unit charge for an `Expr` datum — one unit per
4
//! node — for macro expansion output and constant-folded data. The walk
5
//! recurses the native stack one frame per nesting level, so it carries
6
//! its own depth guard rather than relying on the caller to bound the
7
//! datum's shape first.
8

            
9
use std::cell::Cell;
10

            
11
use crate::ast::Expr;
12
use crate::error::{Error, Result};
13
use crate::reader::MAX_READ_DEPTH;
14
use crate::runtime::{Closure, SymbolTable, Value, with_sufficient_stack};
15

            
16
/// Ceiling on datum nesting a single [`cost`] walk accepts.
17
///
18
/// Derived from a source-level fact rather than a stack measurement: the
19
/// reader's `MAX_READ_DEPTH` already bounds how deeply a datum written in
20
/// source can nest, and no macro here multiplies that nesting per expansion
21
/// round, so twice it keeps a 2x margin. A measurement alone is not
22
/// compositional — `cost` runs inside `expand_macro_then`, itself up to
23
/// `MAX_SHARED_RECURSION_DEPTH` frames deep, each already holding a large
24
/// share of the same stack.
25
///
26
/// One counted level can carry two native `Expr` levels, since a `Quote`
27
/// directly around a list walks at its child's depth, so a walk at this
28
/// ceiling recurses roughly twice it.
29
pub(crate) const MAX_ELAB_DEPTH: usize = 2 * MAX_READ_DEPTH;
30

            
31
/// `expr`, refused when it nests deeper than [`MAX_ELAB_DEPTH`]. Compile-time
32
/// evaluation passes every datum it builds from evaluated values through
33
/// this, so an accumulator cannot grow deep enough for `Expr`'s recursive
34
/// `Clone`/`Drop` to overflow the native stack. The datum's [`cost`] is
35
/// charged to the work budget, so a loop that rebuilds a growing list pays
36
/// for every copy, not one unit per call.
37
12214127
pub(crate) fn bounded(symbols: &SymbolTable, expr: Expr) -> Result<Expr> {
38
12214127
    symbols.charge_work(cost(&expr)?)?;
39
12212234
    Ok(expr)
40
12214127
}
41

            
42
/// Work-unit cost of `expr`: one unit per node, guarded so a
43
/// pathologically deep datum fails structurally instead of overflowing
44
/// the native stack while being counted. A `Quote` directly around a list
45
/// or cons adds no level, so the ceiling counts user-visible nesting; a
46
/// compile-time `Value` (struct, pair, vector, closure env) is walked too.
47
12904221
pub(crate) fn cost(expr: &Expr) -> Result<u64> {
48
12904221
    cost_at_depth(expr, 0, &Cell::new(0))
49
12904221
}
50

            
51
/// Deepest nesting level of `expr`, guarded like [`cost`].
52
2403748
pub(crate) fn nesting(expr: &Expr) -> Result<usize> {
53
2403748
    let deepest = Cell::new(0);
54
2403748
    cost_at_depth(expr, 0, &deepest)?;
55
2403747
    Ok(deepest.get())
56
2403748
}
57

            
58
/// Refuses a datum nested deeper than [`MAX_ELAB_DEPTH`].
59
1614382227
fn check_depth(depth: usize, deepest: &Cell<usize>) -> Result<()> {
60
1614382227
    deepest.set(deepest.get().max(depth));
61
1614382227
    if depth > MAX_ELAB_DEPTH {
62
1877
        return Err(Error::Resource(format!(
63
1877
            "datum nesting exceeded the elaboration depth limit of {MAX_ELAB_DEPTH} levels"
64
1877
        )));
65
1614380350
    }
66
1614380350
    Ok(())
67
1614382227
}
68

            
69
1614381964
fn cost_at_depth(expr: &Expr, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
70
1614381964
    check_depth(depth, deepest)?;
71
1614380088
    let children = with_sufficient_stack(|| child_cost(expr, depth, deepest))?;
72
1614136082
    Ok(1 + children)
73
1614381964
}
74

            
75
263
fn value_cost_at_depth(value: &Value, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
76
263
    check_depth(depth, deepest)?;
77
262
    let children = with_sufficient_stack(|| value_children_cost(value, depth, deepest))?;
78
134
    Ok(1 + children)
79
263
}
80

            
81
262
fn value_children_cost(value: &Value, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
82
262
    Ok(match value {
83
        Value::Pair(pair) => {
84
1
            value_cost_at_depth(&pair.car, depth + 1, deepest)?
85
1
                + value_cost_at_depth(&pair.cdr, depth + 1, deepest)?
86
        }
87
2
        Value::Vector(items) | Value::Closure(Closure { env: items, .. }) => items
88
2
            .iter()
89
3
            .map(|item| value_cost_at_depth(item, depth + 1, deepest))
90
            .sum::<Result<u64>>()?,
91
255
        Value::Struct { fields, .. } => fields
92
255
            .iter()
93
255
            .map(|(_, item)| value_cost_at_depth(item, depth + 1, deepest))
94
128
            .sum::<Result<u64>>()?,
95
        Value::Nil
96
        | Value::T
97
        | Value::Number(_)
98
        | Value::String(_)
99
        | Value::Symbol(_)
100
        | Value::Bytes(_)
101
        | Value::Condition
102
4
        | Value::Commodity { .. } => 0,
103
    })
104
262
}
105

            
106
1614380088
fn child_cost(expr: &Expr, depth: usize, deepest: &Cell<usize>) -> Result<u64> {
107
1614380088
    match expr {
108
        Expr::Cons(car, cdr) => {
109
5250
            Ok(cost_at_depth(car, depth + 1, deepest)? + cost_at_depth(cdr, depth + 1, deepest)?)
110
        }
111
550573068
        Expr::List(items) => items
112
550573068
            .iter()
113
1586526210
            .map(|item| cost_at_depth(item, depth + 1, deepest))
114
            .sum(),
115
        Expr::Quote(inner) | Expr::Datum(inner)
116
10196311
            if matches!(inner.as_ref(), Expr::List(_) | Expr::Cons(_, _)) =>
117
        {
118
10251121
            cost_at_depth(inner, depth, deepest)
119
        }
120
        Expr::Quote(inner)
121
        | Expr::Datum(inner)
122
        | Expr::Quasiquote(inner)
123
        | Expr::Unquote(inner)
124
119911
        | Expr::UnquoteSplicing(inner) => cost_at_depth(inner, depth + 1, deepest),
125
        Expr::Lambda(params, body) => {
126
2159655
            let mut total = cost_at_depth(body, depth + 1, deepest)?;
127
2159447
            for value in params.defaults() {
128
6601
                total += cost_at_depth(value, depth + 1, deepest)?;
129
            }
130
2159447
            Ok(total)
131
        }
132
3
        Expr::RuntimeValue(value) => value_cost_at_depth(value, depth + 1, deepest),
133
        Expr::Nil
134
        | Expr::T
135
        | Expr::Number(_)
136
        | Expr::String(_)
137
        | Expr::Symbol(_)
138
        | Expr::Keyword(_)
139
        | Expr::Bytes(_)
140
        | Expr::WasmRuntime(_)
141
        | Expr::WasmLocal(_, _)
142
        | Expr::WasmGlobal(_, _)
143
1051271080
        | Expr::Instance(_, _) => Ok(0),
144
    }
145
1614380088
}
146

            
147
#[cfg(test)]
148
#[path = "datum_tests.rs"]
149
mod tests;