1
//! Control-flow helpers for `BLOCK` emit-time result typing.
2
//!
3
//! The block's result type is discovered while the body is compiled —
4
//! each reachable `(return-from)` records its value type into the block
5
//! frame (see `block.rs`). This module no longer collects exit types by
6
//! syntactic pre-scan; it only answers two narrower, decidable questions
7
//! the emitter still needs:
8
//!
9
//! - [`form_diverges`] — does a single form unconditionally diverge? Its
10
//!   clients and their roles are inventoried on the function.
11
//!
12
//! Divergence is conservative: any form we cannot prove diverges is
13
//! treated as falling through. Over-estimating fall-through only costs a
14
//! redundant (harmless) seal `unreachable`; it never drops a live value,
15
//! because actual exit values ride the recorded `return-from` `br` edges.
16

            
17
use crate::ast::{Expr, WasmType};
18
use crate::compiler::expr::{eval_value, expand_macro, probe_value};
19
use crate::error::Result;
20
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable, with_sufficient_stack};
21

            
22
use super::super::binding::spec_name;
23
use super::block_parse::parse_block;
24
use super::exit_scan::has_exit_to;
25

            
26
const BLOCK: &str = "block";
27
const RETURN_FROM: &str = "return-from";
28
const ERROR: &str = "error";
29
const IF: &str = "if";
30
const PROGN: &str = "progn";
31
const UNWIND_PROTECT: &str = "unwind-protect";
32
const LET_FORMS: [&str; 2] = ["let", "let*"];
33
const CALL_FORMS: [&str; 2] = ["funcall", "apply"];
34

            
35
/// Whether control can fall through `body` to its tail value position.
36
/// False once a form unconditionally diverges — subsequent forms (incl.
37
/// the tail) are dead. Internal helper for `PROGN` divergence.
38
134128
fn body_falls_through(symbols: &mut SymbolTable, body: &[Expr]) -> Result<bool> {
39
134128
    for (idx, form) in body.iter().enumerate() {
40
234462
        let is_tail = idx + 1 == body.len();
41
234462
        if form_diverges(symbols, form)? {
42
39448
            return Ok(false);
43
195014
        }
44
195014
        if is_tail {
45
94464
            return Ok(true);
46
100550
        }
47
    }
48
216
    Ok(true)
49
134128
}
50

            
51
/// Whether `form` unconditionally diverges (cannot fall through to its
52
/// successor): `(error …)`, any `(return-from …)`, a `PROGN`
53
/// whose last reachable form diverges, a `BLOCK` nothing can leave, an `IF` whose test or live
54
/// branch(es) all diverge, or a `LET` / `LET*` with an init that diverges. Anything else is conservatively treated as
55
/// falling through — code stored as a value (quote / lambda / labels
56
/// bodies) and ordinary calls do not diverge here.
57
///
58
/// CONTRACT: this is a *query* that internally runs `eval_value` (for
59
/// const-fold / macro expansion / IF-test classification), which can apply
60
/// compile-time side effects (`setf`, macro expansion) to `symbols`. Callers
61
/// MUST pass a THROWAWAY CLONE (`&mut symbols.clone()`), never the live table
62
/// — every call site does. Because `symbols` here is already disposable, the
63
/// internal re-evaluations (e.g. `if_diverges` classifying then valuing the
64
/// test) are clone-local and cannot double-apply effects to a live table.
65
///
66
/// ROLES. A syntactic belief, not the emitter frame's may-analysis; mirror
67
/// inventory #2 of plan 0014; its eval-side replacement is WONTFIX (ISS-154).
68
/// - *routing* — what to compile, and what is dead and compiled for effect:
69
///   `cons.rs:109,115`, `operand.rs:38` (`always_raises`, also read by
70
///   `ordering/to_stack.rs::is_spilled`), `effect.rs:265,325` (these three
71
///   through `form_diverges_scratch`),
72
///   `if_form.rs:69`, `cond.rs:39,90,160,225`, `tagbody.rs:118`,
73
///   `block.rs:180`, `cond_runtime_chain.rs:143`.
74
/// - *type* — a `WasmType` or arm membership, which the eval mirrors cannot
75
///   take from a frame: `handler_case.rs:74,111,114`,
76
///   `unwind_protect.rs:72,144`, `arms.rs:39` (`compile_arm`), `arms.rs:138`
77
///   (`eval_arm`), `block.rs:180` (`tail_ty`), and via [`eval_and_diverges`]
78
///   `if_form.rs:172`, `cond.rs:294`, `cond_runtime_chain.rs:269`.
79
/// - *seal* — an `unreachable` before the enclosing `else`/`end`, clearing a
80
///   dead residue `block_end` cannot: `arms.rs:39` (S1),
81
///   `cond_runtime_chain.rs:143` (S9), `unwind_protect.rs:144` (S8),
82
///   `block.rs:180` (its `!falls_through` seal).
83
///
84
/// Every seal site serves a second role as well. The recursive calls in this
85
/// file are the classifier's own walk, not clients.
86
26731519
pub(super) fn form_diverges(symbols: &mut SymbolTable, form: &Expr) -> Result<bool> {
87
26731519
    with_sufficient_stack(|| {
88
26731519
        symbols.measurements().note_walk();
89
26731519
        let Expr::List(items) = form else {
90
17421388
            return Ok(false);
91
        };
92
9310131
        let head = match items.first() {
93
9306951
            Some(Expr::Symbol(s)) => s.as_str(),
94
            // A genuinely-eager non-symbol callee — an inline lambda `((lambda …)
95
            // args)` or a computed function `((f) args)` (head is a `List`/`Lambda`
96
            // node) — evaluates the callee then each arg before the call, so it
97
            // diverges if any of them diverges. Other non-symbol heads (notably a
98
            // quoted symbol `('quote …)`, which the call path may route to the LAZY
99
            // QUOTE special form) are NOT classified eager: over-reporting
100
            // divergence is unsafe (it would drop a live tail), so we conservatively
101
            // fall through to non-diverging for them.
102
            Some(callee @ (Expr::List(_) | Expr::Lambda(_, _))) => {
103
3177
                if form_diverges(symbols, callee)? {
104
                    return Ok(true);
105
3177
                }
106
3177
                for arg in &items[1..] {
107
2954
                    if form_diverges(symbols, arg)? {
108
1254
                        return Ok(true);
109
1700
                    }
110
                }
111
1923
                return Ok(false);
112
            }
113
3
            _ => return Ok(false),
114
        };
115

            
116
9306951
        if head.eq_ignore_ascii_case(RETURN_FROM) || head.eq_ignore_ascii_case(ERROR) {
117
304775
            return Ok(true);
118
9002176
        }
119
9002176
        if head.eq_ignore_ascii_case(PROGN) {
120
127209
            return body_falls_through(symbols, &items[1..]).map(|ft| !ft);
121
8874967
        }
122
8874967
        if head.eq_ignore_ascii_case(BLOCK) {
123
10087
            return block_diverges(symbols, &items[1..]);
124
8864880
        }
125
8864880
        if head.eq_ignore_ascii_case(IF) {
126
68690
            return if_diverges(symbols, items);
127
8796190
        }
128
        // `(unwind-protect body cleanup...)` diverges if EITHER the protected
129
        // body diverges (the raise/return-from propagates past the form after
130
        // cleanup) OR a cleanup form diverges. Cleanup always runs on the way out,
131
        // so a `(return-from)` / `(error)` / `(go)` in a reachable cleanup
132
        // unconditionally transfers control — the body's value never falls
133
        // through. Misjudging this leaves a dead tail "reachable" and lets BLOCK
134
        // unify a bogus type against the real (cleanup) exit.
135
8796190
        if head.eq_ignore_ascii_case(UNWIND_PROTECT) {
136
15769
            let Some((body, cleanup)) = items[1..].split_first() else {
137
                return Ok(false);
138
            };
139
15769
            if form_diverges(symbols, body)? {
140
12614
                return Ok(true);
141
3155
            }
142
            // Cleanup runs as a sequence; it diverges iff control can't fall
143
            // through it (some reachable form unconditionally exits).
144
3155
            return body_falls_through(symbols, cleanup).map(|ft| !ft);
145
8780421
        }
146
17460255
        if LET_FORMS.iter().any(|form| head.eq_ignore_ascii_case(form)) {
147
103803
            return let_inits_diverge(symbols, &items[1..], head.eq_ignore_ascii_case("let*"));
148
8676618
        }
149
        // A macro call whose expansion diverges (e.g. expands to a bare
150
        // `(return-from …)`) is itself diverging. Expand one step and
151
        // re-classify, mirroring the compile path.
152
8676618
        if matches!(symbols.resolve_head(head), Head::Macro(..)) {
153
55895
            return macro_diverges(symbols, head, &items[1..]);
154
8620723
        }
155
        // An eager call (native / operator / user function) evaluates ALL its
156
        // arguments before the call, so it diverges if any argument diverges — the
157
        // arg's `(return-from …)` / `(error …)` transfers control before the call
158
        // runs. e.g. `(cons (return-from b "x") 2)` exits via the car, leaving the
159
        // block's tail dead. Gated on an eager-call head: special forms (handled
160
        // above) and lazy heads (QUOTE / AND / OR with short-circuit) must NOT
161
        // propagate — over-reporting divergence would wrongly drop a live tail.
162
8620723
        if head_is_eager_call(symbols, head) {
163
7636176
            for arg in &items[1..] {
164
6957334
                if form_diverges(symbols, arg)? {
165
10340
                    return Ok(true);
166
6946162
                }
167
            }
168
984547
        }
169
8609551
        Ok(false)
170
26731519
    })
171
26731519
}
172

            
173
/// A LET / LET* never reaches its body when an init diverges structurally;
174
/// a division by zero in an init raises at run time instead. A LET* init sees
175
/// the earlier variables as opaque runtime values, never as probed ones.
176
103803
fn let_inits_diverge(symbols: &mut SymbolTable, args: &[Expr], sequential: bool) -> Result<bool> {
177
103803
    let Some(Expr::List(specs)) = args.first() else {
178
1064
        return Ok(false);
179
    };
180
102739
    if sequential {
181
3216
        symbols.push_scope();
182
99523
    }
183
102739
    let diverges = specs_diverge(symbols, specs, sequential);
184
102739
    if sequential {
185
3216
        symbols.pop_scope()?;
186
99523
    }
187
102739
    diverges
188
103803
}
189

            
190
102739
fn specs_diverge(symbols: &mut SymbolTable, specs: &[Expr], sequential: bool) -> Result<bool> {
191
102739
    for spec in specs {
192
131780
        if let Expr::List(pair) = spec
193
131780
            && let Some(init) = pair.get(1)
194
131780
            && form_diverges(symbols, init)?
195
        {
196
32
            return Ok(true);
197
131748
        }
198
131748
        if sequential && let Some(name) = spec_name(spec) {
199
3938
            symbols.define_scoped(
200
3938
                Symbol::new(name, SymbolKind::Variable)
201
3938
                    .with_value(Expr::WasmRuntime(WasmType::AnyRef)),
202
3938
            );
203
127810
        }
204
    }
205
102707
    Ok(false)
206
102739
}
207

            
208
/// A BLOCK whose body diverges and which no `return-from` can leave never
209
/// yields a value; a malformed one is left to its own compile error.
210
10087
fn block_diverges(symbols: &mut SymbolTable, args: &[Expr]) -> Result<bool> {
211
10087
    let Ok((name, body)) = parse_block(args) else {
212
        return Ok(false);
213
    };
214
10087
    if has_exit_to(symbols, name, body) {
215
6323
        return Ok(false);
216
3764
    }
217
3764
    body_falls_through(symbols, body).map(|falls| !falls)
218
10087
}
219

            
220
/// Evaluates `form` on `symbols` and reports whether it diverges. A form that
221
/// evaluated no `return-from` / `error` cannot diverge, so the divergence walk
222
/// runs, on a clone taken before the evaluation, only when one was evaluated.
223
1459156
pub(super) fn eval_and_diverges(symbols: &mut SymbolTable, form: &Expr) -> Result<(Expr, bool)> {
224
1459156
    let mut before = symbols.clone();
225
1459156
    let exits = symbols.measurements().exits();
226
1459156
    let value = eval_value(symbols, form)?;
227
1453572
    let diverges = symbols.measurements().exits() != exits && form_diverges(&mut before, form)?;
228
1453572
    Ok((value, diverges))
229
1459156
}
230

            
231
/// Whether `head` names an eager call — a native, operator, user function,
232
/// `FUNCALL` or `APPLY` that evaluates all its arguments before being applied.
233
/// Other special forms and macros (lazy / custom evaluation order) are excluded.
234
8620723
fn head_is_eager_call(symbols: &SymbolTable, head: &str) -> bool {
235
8620723
    matches!(
236
8620723
        symbols.resolve_head(head),
237
        Head::Native | Head::Function(..)
238
1009475
    ) || CALL_FORMS
239
1009475
        .iter()
240
1995107
        .any(|form| head.eq_ignore_ascii_case(form))
241
8620723
}
242

            
243
/// Classify divergence of a macro call by one-step expansion + recursion,
244
/// with a depth guard balanced like `expand_macro_then`: enter before
245
/// expanding, exit after the recursive re-classification (including the
246
/// error path) so a self-referential macro is bounded while sibling
247
/// divergence checks on the same throwaway table start from fresh depth.
248
55895
fn macro_diverges(symbols: &mut SymbolTable, head: &str, args: &[Expr]) -> Result<bool> {
249
55895
    with_macro_expansion(symbols, head, args, form_diverges).map(|diverges| diverges == Some(true))
250
55895
}
251

            
252
/// Expands the macro call `(head args…)` one step and hands the code to
253
/// `then` inside the macro-expansion depth guard; `None` when `head` has no
254
/// macro body.
255
55895
pub(super) fn with_macro_expansion<T>(
256
55895
    symbols: &mut SymbolTable,
257
55895
    head: &str,
258
55895
    args: &[Expr],
259
55895
    then: impl FnOnce(&mut SymbolTable, &Expr) -> Result<T>,
260
55895
) -> Result<Option<T>> {
261
55895
    let func = symbols.lookup(head).and_then(|sym| sym.function().cloned());
262
55895
    let Some(Expr::Lambda(params, body)) = func else {
263
        return Ok(None);
264
    };
265
55895
    symbols.enter_macro_expansion()?;
266
    let result =
267
55893
        expand_macro(symbols, &params, &body, args).and_then(|expansion| then(symbols, &expansion));
268
55893
    symbols.exit_macro_expansion()?;
269
55893
    result.map(Some)
270
55895
}
271

            
272
/// `IF` divergence, mirroring the emitter's const-fold: a diverging *test*
273
/// makes the whole IF diverge (control transfers away before the branches);
274
/// otherwise a constant test keeps only the live branch and a runtime test
275
/// diverges only when *both* branches diverge (a missing else-branch falls
276
/// through). The test is classified only when the branches differ: with equal
277
/// verdicts the live branch's is the answer whichever it is.
278
68690
fn if_diverges(symbols: &mut SymbolTable, items: &[Expr]) -> Result<bool> {
279
68690
    if items.len() < 3 || items.len() > 4 {
280
        return Ok(false);
281
68690
    }
282
68690
    if form_diverges(symbols, &items[1])? {
283
627
        return Ok(true);
284
68063
    }
285
68063
    let then_div = form_diverges(symbols, &items[2])?;
286
68063
    let else_div = match items.get(3) {
287
53963
        Some(else_branch) => form_diverges(symbols, else_branch)?,
288
14100
        None => false,
289
    };
290
68063
    if then_div == else_div {
291
38658
        return Ok(then_div);
292
29405
    }
293
29405
    let test = probe_value(symbols, &items[1])?;
294
29405
    if test.is_wasm_runtime() {
295
25183
        return Ok(false);
296
4222
    }
297
4222
    Ok(if test.is_nil() { else_div } else { then_div })
298
68690
}
299

            
300
/// Static `WasmType` a value-position form would deposit on the stack,
301
/// looking through a `(return-from name V)` to `V`. Mirrors the literal
302
/// lowerings the stack-compile path uses. Used by `eval_return_from` to
303
/// surface a runtime placeholder of the right type.
304
174077
pub(super) fn peek_value_type(symbols: &mut SymbolTable, expr: &Expr) -> Result<WasmType> {
305
174077
    if let Expr::List(items) = expr
306
923
        && let Some(Expr::Symbol(head)) = items.first()
307
923
        && head.eq_ignore_ascii_case(RETURN_FROM)
308
        && items.len() == 3
309
    {
310
        return peek_value_type(symbols, &items[2]);
311
174077
    }
312
174077
    let resolved = probe_value(symbols, expr)?;
313
174077
    Ok(crate::compiler::expr::classify_stack_type(&resolved).unwrap_or(WasmType::I32))
314
174077
}
315

            
316
#[cfg(test)]
317
#[path = "block_exits_tests.rs"]
318
mod tests;