1
//! Depth-safe teardown for a constructed [`Expr`] datum (plan 0011 Phase 0).
2
//!
3
//! `Expr`'s recursive variants (`Cons`, `List`, `Quote`/`Quasiquote`/
4
//! `Unquote`/`UnquoteSplicing`, `Lambda`) nest through `Box<Expr>` /
5
//! `Vec<Expr>`. Rust's compiler-generated drop glue tears these down one
6
//! native stack frame per nesting level, with no compile-time recursion
7
//! guard able to see it — the overflow would happen *after* elaboration,
8
//! when a deep macro-generated or quasiquote-spliced datum is discarded.
9
//! `Expr::RuntimeValue` embeds a [`Value`], which recurses the same way
10
//! through its own `Pair` / `Vector` / `Struct` / `Closure` variants, so
11
//! teardown carries a second, matching worklist for those.
12
//!
13
//! [`drop_iteratively`] flattens the structure into owned worklists before
14
//! dropping it, so teardown cost is bounded by heap allocation, never by
15
//! native stack depth. A blanket `impl Drop for Expr` (or `Value`) was
16
//! rejected: both types are pattern-matched by value (moving variant fields
17
//! out) at dozens of call sites across the compiler, and a type that
18
//! implements `Drop` cannot be partially moved out of — every one of
19
//! those sites would need rewriting to borrow instead, which is a
20
//! behaviour-changing refactor far outside this framework-only phase.
21
//! `drop_iteratively` is called explicitly instead, at the sites that
22
//! construct or discard datums large enough to matter (e.g. a constant-
23
//! folded list). `Pair` itself has an iterative `Drop` along the cdr
24
//! (nothing moves its fields out), which leaves the car, vector and struct
25
//! nesting to these worklists.
26

            
27
use crate::ast::{Expr, LambdaParams};
28
use crate::runtime::Value;
29

            
30
/// Drops `expr` without recursing the native stack, regardless of how
31
/// deeply it — or any `Value` it embeds via `Expr::RuntimeValue` — nests.
32
1060
pub(crate) fn drop_iteratively(mut expr: Expr) {
33
1060
    let mut pending_exprs = Vec::new();
34
1060
    let mut pending_values = Vec::new();
35
1060
    take_children(&mut expr, &mut pending_exprs, &mut pending_values);
36
1060
    drop(expr);
37
    loop {
38
3556215
        if let Some(mut child) = pending_exprs.pop() {
39
2055153
            take_children(&mut child, &mut pending_exprs, &mut pending_values);
40
2055153
            drop(child);
41
2055153
            continue;
42
1501062
        }
43
1501062
        let Some(mut value) = pending_values.pop() else {
44
1060
            break;
45
        };
46
1500002
        take_value_children(&mut value, &mut pending_values);
47
1500002
        drop(value);
48
    }
49
1060
}
50

            
51
/// Moves every direct `Expr` child out of `expr` (replacing each with the
52
/// leaf `Expr::Nil`) and appends them to `pending_exprs` — or, for an
53
/// embedded `Value`, to `pending_values` — leaving `expr` itself childless
54
/// so dropping it directly costs one stack frame.
55
2056217
fn take_children(expr: &mut Expr, pending_exprs: &mut Vec<Expr>, pending_values: &mut Vec<Value>) {
56
2056217
    match expr {
57
        Expr::Cons(car, cdr) => {
58
500001
            pending_exprs.push(std::mem::replace(car.as_mut(), Expr::Nil));
59
500001
            pending_exprs.push(std::mem::replace(cdr.as_mut(), Expr::Nil));
60
        }
61
501057
        Expr::List(items) => pending_exprs.append(items),
62
        Expr::Quote(inner)
63
        | Expr::Datum(inner)
64
        | Expr::Quasiquote(inner)
65
        | Expr::Unquote(inner)
66
        | Expr::UnquoteSplicing(inner) => {
67
501055
            pending_exprs.push(std::mem::replace(inner.as_mut(), Expr::Nil));
68
        }
69
        Expr::Lambda(params, body) => {
70
1
            pending_exprs.push(std::mem::replace(body.as_mut(), Expr::Nil));
71
1
            take_param_defaults(params, pending_exprs);
72
        }
73
        Expr::RuntimeValue(value) => {
74
3
            pending_values.push(std::mem::replace(value, Value::Nil));
75
        }
76
        Expr::Nil
77
        | Expr::T
78
        | Expr::Number(_)
79
        | Expr::String(_)
80
        | Expr::Symbol(_)
81
        | Expr::Keyword(_)
82
        | Expr::Bytes(_)
83
        | Expr::WasmRuntime(_)
84
        | Expr::WasmLocal(_, _)
85
        | Expr::WasmGlobal(_, _)
86
554100
        | Expr::Instance(_, _) => {}
87
    }
88
2056217
}
89

            
90
1
fn take_param_defaults(params: &mut LambdaParams, pending: &mut Vec<Expr>) {
91
1
    let defaults = params
92
1
        .optional
93
1
        .iter_mut()
94
        .map(|(_, default)| default)
95
1
        .chain(params.key.iter_mut().map(|param| &mut param.default))
96
1
        .chain(params.aux.iter_mut().map(|(_, default)| default));
97
1
    pending.extend(defaults.filter_map(Option::take));
98
1
}
99

            
100
/// Moves every direct `Value` child out of `value` (replacing each with the
101
/// leaf `Value::Nil`) and appends them to `pending`, leaving `value` itself
102
/// childless so dropping it directly costs one stack frame.
103
1500006
fn take_value_children(value: &mut Value, pending: &mut Vec<Value>) {
104
1500006
    match value {
105
        Value::Pair(pair) => {
106
500001
            pending.push(std::mem::replace(&mut pair.car, Value::Nil));
107
500001
            pending.push(std::mem::replace(&mut pair.cdr, Value::Nil));
108
        }
109
500002
        Value::Vector(items) => pending.append(items),
110
1
        Value::Struct { fields, .. } => pending.extend(fields.drain(..).map(|(_, item)| item)),
111
1
        Value::Closure(closure) => pending.append(&mut closure.env),
112
        Value::Nil
113
        | Value::T
114
        | Value::Number(_)
115
        | Value::String(_)
116
        | Value::Symbol(_)
117
        | Value::Bytes(_)
118
        | Value::Condition
119
500001
        | Value::Commodity { .. } => {}
120
    }
121
1500006
}
122

            
123
#[cfg(test)]
124
#[path = "ast_teardown_tests.rs"]
125
mod tests;