1
//! Control-flow special forms.
2
//!
3
//! Split by form:
4
//! - [`quote`] — `QUOTE`.
5
//! - [`if_form`] — `IF` (compile + for-stack + eval).
6
//! - [`progn`] — `PROGN` (sequencing).
7
//! - [`and_or`] — `AND` / `OR` short-circuit boolean forms.
8
//! - [`cond`] — `COND` clause chain (rewrites to nested IF for stack).
9
//! - [`block`] — `BLOCK` / `RETURN-FROM` lexical labelled exits.
10

            
11
mod and_or;
12
mod arms;
13
mod block;
14
mod block_exits;
15
mod block_parse;
16
mod case;
17
mod cond;
18
mod cond_runtime_chain;
19
pub(in crate::compiler) mod error_form;
20
mod exit_scan;
21
mod handler_case;
22
mod if_form;
23
mod nil_block;
24
mod progn;
25
mod quote;
26
mod skip_region;
27
mod tagbody;
28
mod unwind_protect;
29

            
30
use crate::ast::{Expr, WasmType};
31
use crate::compiler::context::CompileContext;
32
use crate::compiler::emit::FunctionEmitter;
33
use crate::compiler::expr::{NilRepr, compile_for_stack, nil_repr};
34
use crate::error::Result;
35
use crate::runtime::SymbolTable;
36

            
37
use super::SpecialFormSpec;
38

            
39
pub(in crate::compiler) use arms::in_runtime_branch;
40
pub(in crate::compiler::special) use case::FORMS as CASE_FORMS;
41
pub(in crate::compiler::special) use nil_block::wrapped_loop;
42
pub(in crate::compiler) use unwind_protect::protect;
43

            
44
/// The divergence classifier for callers outside the `control` module. It
45
/// classifies on a clone, so the caller's table never sees the walk's
46
/// compile-time effects — see [`block_exits::form_diverges`].
47
12411469
pub(in crate::compiler) fn form_diverges_scratch(
48
12411469
    symbols: &SymbolTable,
49
12411469
    form: &Expr,
50
12411469
) -> Result<bool> {
51
12411469
    block_exits::form_diverges(&mut symbols.clone(), form)
52
12411469
}
53

            
54
/// Whether `form`, just evaluated from exit count `exits`, leaves the rest of
55
/// its sequence dead for the eval surface's BLOCK join: it reached an exit
56
/// and always diverges. Classified only while a BLOCK is open outside a macro
57
/// body, which has no codegen to agree with.
58
373466
pub(in crate::compiler) fn ends_live_code(
59
373466
    symbols: &SymbolTable,
60
373466
    form: &Expr,
61
373466
    exits: u64,
62
373466
) -> Result<bool> {
63
373466
    if !symbols.has_eval_block()
64
20774
        || symbols.is_macro_expansion()
65
14488
        || symbols.measurements().exits() == exits
66
    {
67
365672
        return Ok(false);
68
7794
    }
69
7794
    form_diverges_scratch(symbols, form)
70
373466
}
71

            
72
/// A form a consumer's expected type reaches: its arms are still free to
73
/// adopt it.
74
#[derive(Clone, Copy)]
75
pub(in crate::compiler) enum ExpectingForm {
76
    Block,
77
    If,
78
}
79

            
80
impl ExpectingForm {
81
    /// The BLOCK or IF form `expr` is, with its arguments. Neither name can be
82
    /// redefined, so the head alone decides.
83
316090
    pub(in crate::compiler) fn of(expr: &Expr) -> Option<(Self, &[Expr])> {
84
316090
        let Expr::List(elems) = expr else {
85
85691
            return None;
86
        };
87
230399
        let (Expr::Symbol(name), args) = elems.split_first()? else {
88
            return None;
89
        };
90
230399
        match name.as_str() {
91
2474
            "BLOCK" => Some((Self::Block, args)),
92
4920
            "IF" => Some((Self::If, args)),
93
223005
            _ => None,
94
        }
95
316090
    }
96

            
97
118
    pub(in crate::compiler) fn compile(
98
118
        self,
99
118
        ctx: &mut CompileContext,
100
118
        emit: &mut FunctionEmitter,
101
118
        symbols: &mut SymbolTable,
102
118
        args: &[Expr],
103
118
        expected: WasmType,
104
118
    ) -> Result<WasmType> {
105
118
        match self {
106
118
            Self::Block => block::compile_block_expecting(ctx, emit, symbols, args, Some(expected)),
107
            Self::If => if_form::compile_if_expecting(ctx, emit, symbols, args, Some(expected)),
108
        }
109
118
    }
110
}
111

            
112
/// Any value is a valid test (ADR-0033). A runtime value needs an actual wasm
113
/// branch exactly when it CAN be `nil` at runtime (`nil_repr` is `I32Zero` or
114
/// `Null`); a `Never`-typed runtime value (index / scalar / money / closure)
115
/// can never be nil, so it folds true through [`apply_const_test`] instead —
116
/// compiled for its effects, never branched on. Every IF / COND path (eval,
117
/// stack, effect) shares this, so no path branches where another folds.
118
5266131
pub(in crate::compiler) fn is_runtime_test(test: &Expr) -> bool {
119
5266131
    test.wasm_type()
120
3420575
        .is_some_and(|ty| !matches!(nil_repr(&ty), NilRepr::Never))
121
5266131
}
122

            
123
/// Emits `test` as a bare i32 wasm condition, per the `nil_repr` of the type
124
/// it compiled to: a `Bool` already IS its own 0/1 condition; a nullable
125
/// reference's condition is "not null" (`ref.is_null` then `i32.eqz`). A test
126
/// that compiled to a never-nil type (an operand the probe could not type,
127
/// such as one that raises) has run; its value is dropped and the condition
128
/// is true. Shared by every runtime-test compile path (IF / COND / AND / OR).
129
2504605
pub(in crate::compiler) fn compile_test_condition(
130
2504605
    ctx: &mut CompileContext,
131
2504605
    emit: &mut FunctionEmitter,
132
2504605
    symbols: &mut SymbolTable,
133
2504605
    test: &Expr,
134
2504605
) -> Result<()> {
135
2504605
    let ty = compile_for_stack(ctx, emit, symbols, test)?;
136
2503705
    match nil_repr(&ty) {
137
2489965
        NilRepr::I32Zero => {}
138
        NilRepr::Null => {
139
12700
            emit.ref_is_null();
140
12700
            emit.i32_eqz();
141
        }
142
        NilRepr::Never => {
143
1040
            emit.drop_value();
144
1040
            emit.i32_const(1);
145
        }
146
    }
147
2503705
    Ok(())
148
2504605
}
149

            
150
/// Applies a const-path IF/COND test exactly once and returns the value to
151
/// branch on: an index test (always truthy) is compiled for its runtime
152
/// effects, a constant test's effects are ALSO compiled (not just
153
/// `eval_value`d) — a `setf` on a runtime local inside the test needs a real
154
/// `local.set`, which `eval_value` alone never emits, even though the
155
/// test's own resulting VALUE is statically known. `classified` is the
156
/// caller's own disposable-clone probe of `form`'s fold, so this returns it
157
/// directly rather than re-deriving it (which would re-apply the form's
158
/// compile-time effects a second time).
159
979845
pub(in crate::compiler) fn apply_const_test(
160
979845
    ctx: &mut crate::compiler::context::CompileContext,
161
979845
    emit: &mut crate::compiler::emit::FunctionEmitter,
162
979845
    symbols: &mut SymbolTable,
163
979845
    form: &Expr,
164
979845
    classified: &Expr,
165
979845
) -> Result<Expr> {
166
979845
    crate::compiler::expr::compile_for_effect(ctx, emit, symbols, form)?;
167
979843
    Ok(classified.clone())
168
979845
}
169

            
170
pub(super) const FORMS: &[SpecialFormSpec] = &[
171
    SpecialFormSpec {
172
        name: "QUOTE",
173
        eval: quote::eval_quote,
174
        compile: quote::spec_compile_quote,
175
        stack: Some(quote::compile_quote_for_stack),
176
        effect: Some(quote::compile_quote_effect),
177
    },
178
    SpecialFormSpec {
179
        name: "IF",
180
        eval: if_form::if_form,
181
        compile: if_form::compile_if,
182
        stack: Some(if_form::compile_if_for_stack),
183
        effect: None,
184
    },
185
    SpecialFormSpec {
186
        name: "PROGN",
187
        eval: progn::progn_form,
188
        compile: progn::compile_progn,
189
        stack: Some(progn::compile_progn_for_stack),
190
        effect: None,
191
    },
192
    SpecialFormSpec {
193
        name: "AND",
194
        eval: and_or::and_form,
195
        compile: and_or::compile_and,
196
        stack: Some(and_or::compile_and_for_stack),
197
        effect: Some(and_or::compile_and_for_effect),
198
    },
199
    SpecialFormSpec {
200
        name: "OR",
201
        eval: and_or::or_form,
202
        compile: and_or::compile_or,
203
        stack: Some(and_or::compile_or_for_stack),
204
        effect: Some(and_or::compile_or_for_effect),
205
    },
206
    SpecialFormSpec {
207
        name: "COND",
208
        eval: cond::cond_form,
209
        compile: cond::compile_cond,
210
        stack: Some(cond::compile_cond_for_stack),
211
        effect: Some(cond::compile_cond_for_effect),
212
    },
213
    SpecialFormSpec {
214
        name: "ERROR",
215
        eval: error_form::eval_error,
216
        compile: error_form::compile_error,
217
        stack: Some(error_form::compile_error_for_stack),
218
        effect: None,
219
    },
220
    SpecialFormSpec {
221
        name: "BLOCK",
222
        eval: block::eval_block,
223
        compile: block::compile_block,
224
        stack: Some(block::compile_block_for_stack),
225
        effect: Some(block::compile_block_for_effect),
226
    },
227
    SpecialFormSpec {
228
        name: "RETURN-FROM",
229
        eval: block::eval_return_from,
230
        compile: block::compile_return_from,
231
        stack: Some(block::compile_return_from_for_stack),
232
        effect: None,
233
    },
234
    SpecialFormSpec {
235
        name: "TAGBODY",
236
        eval: tagbody::eval_tagbody,
237
        compile: tagbody::compile_tagbody,
238
        stack: Some(tagbody::compile_tagbody_for_stack),
239
        effect: Some(tagbody::compile_tagbody_for_effect),
240
    },
241
    SpecialFormSpec {
242
        name: "GO",
243
        eval: tagbody::eval_go,
244
        compile: tagbody::compile_go,
245
        stack: Some(tagbody::compile_go_for_stack),
246
        effect: None,
247
    },
248
    SpecialFormSpec {
249
        name: "HANDLER-CASE",
250
        eval: handler_case::eval_handler_case,
251
        compile: handler_case::compile_handler_case,
252
        stack: Some(handler_case::compile_handler_case_for_stack),
253
        effect: Some(handler_case::compile_handler_case_for_effect),
254
    },
255
    SpecialFormSpec {
256
        name: "UNWIND-PROTECT",
257
        eval: unwind_protect::eval_unwind_protect,
258
        compile: unwind_protect::compile_unwind_protect,
259
        stack: Some(unwind_protect::compile_unwind_protect_for_stack),
260
        effect: Some(unwind_protect::compile_unwind_protect_for_effect),
261
    },
262
];
263

            
264
#[cfg(test)]
265
#[path = "expected_tests.rs"]
266
mod expected_tests;