1
//! `IF` special form — eval, effect-compile, and stack-compile paths.
2
//! Constant-folds when the test resolves at compile time; emits a
3
//! WASM `if/else` block when the test is a runtime value. The
4
//! stack variant carries the result type so call sites composing
5
//! `(if ...)` with arithmetic see the right WasmType.
6

            
7
use wasm_encoder::BlockType;
8

            
9
use crate::ast::{Expr, WasmType};
10
use crate::compiler::context::CompileContext;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::compiler::expr::{
13
    compile_expr, compile_for_stack, compile_for_stack_expecting, compile_nil, eval_value,
14
    probe_value, serialize_stack_to_output,
15
};
16
use crate::error::{Error, Result};
17
use crate::runtime::SymbolTable;
18

            
19
use super::arms::{
20
    Arm, compile_branch_arm, emit_typed_nil, eval_arm, finish_branch_arm, reconcile_arms,
21
    reconcile_arms_expecting,
22
};
23

            
24
30103
pub(super) fn compile_if(
25
30103
    ctx: &mut CompileContext,
26
30103
    emit: &mut FunctionEmitter,
27
30103
    symbols: &mut SymbolTable,
28
30103
    args: &[Expr],
29
30103
) -> Result<()> {
30
30103
    if args.len() < 2 || args.len() > 3 {
31
416
        return Err(Error::Compile(
32
416
            "IF requires a test, a then-form, and an optional else-form".to_string(),
33
416
        ));
34
29687
    }
35
29687
    let (test, test_diverges) = classify_test(symbols, &args[0])?;
36
29687
    if test_diverges {
37
        // The test transfers control before yielding a condition (`(error …)`,
38
        // `(return-from …)`). Compile it for effect so the exit actually
39
        // fires; both branches are then dead. Const-folding past it (the bug
40
        // this guards) would silently drop the exit and pick a branch.
41
        return crate::compiler::expr::compile_for_effect(ctx, emit, symbols, &args[0]);
42
29687
    }
43
29687
    if super::is_runtime_test(&test) {
44
        // Runtime test: emit ONE merged `if (result T)` block via the stack
45
        // path, then serialize the single result. Serializing each branch
46
        // separately (via `compile_expr`) double-advances the compile-time
47
        // output cursor — both branches bake an entity header, but only one
48
        // runs, so the decoder reads a garbage entity slot ("unknown value
49
        // type"). The stack path collapses both arms to one value.
50
9443
        let ty = compile_runtime_test_if(ctx, emit, symbols, args, None)?;
51
9228
        return serialize_stack_to_output(ctx, emit, ty);
52
20244
    }
53
20244
    let test = super::apply_const_test(ctx, emit, symbols, &args[0], &test)?;
54
20244
    if !test.is_nil() {
55
5234
        compile_expr(ctx, emit, symbols, &args[1])
56
15010
    } else if args.len() == 3 {
57
14592
        compile_expr(ctx, emit, symbols, &args[2])
58
    } else {
59
418
        compile_nil(ctx, emit)?;
60
418
        Ok(())
61
    }
62
30103
}
63

            
64
/// The test's probed value and whether it transfers control, both taken on
65
/// clones: its compile-time side effects (setf / macro expansion) must reach
66
/// the live table exactly once, through the emit that follows.
67
226401
fn classify_test(symbols: &SymbolTable, test: &Expr) -> Result<(Expr, bool)> {
68
226401
    let value = probe_value(&mut symbols.clone(), test)?;
69
226401
    let diverges = super::block_exits::form_diverges(&mut symbols.clone(), test)?;
70
226401
    Ok((value, diverges))
71
226401
}
72

            
73
/// The `IF` whose test classified as a runtime value.
74
192836
fn compile_runtime_test_if(
75
192836
    ctx: &mut CompileContext,
76
192836
    emit: &mut FunctionEmitter,
77
192836
    symbols: &mut SymbolTable,
78
192836
    args: &[Expr],
79
192836
    expected: Option<WasmType>,
80
192836
) -> Result<WasmType> {
81
192836
    super::compile_test_condition(ctx, emit, symbols, &args[0])?;
82
192162
    compile_runtime_if(ctx, emit, symbols, args, expected)
83
192836
}
84

            
85
196714
pub(super) fn compile_if_for_stack(
86
196714
    ctx: &mut CompileContext,
87
196714
    emit: &mut FunctionEmitter,
88
196714
    symbols: &mut SymbolTable,
89
196714
    args: &[Expr],
90
196714
) -> Result<WasmType> {
91
196714
    compile_if_expecting(ctx, emit, symbols, args, None)
92
196714
}
93

            
94
/// An IF whose consumer expects `expected`: arms that are all literals
95
/// fitting it are emitted as it, and each branch form is compiled expecting it.
96
196714
pub(super) fn compile_if_expecting(
97
196714
    ctx: &mut CompileContext,
98
196714
    emit: &mut FunctionEmitter,
99
196714
    symbols: &mut SymbolTable,
100
196714
    args: &[Expr],
101
196714
    expected: Option<WasmType>,
102
196714
) -> Result<WasmType> {
103
196714
    if args.len() < 2 || args.len() > 3 {
104
        return Err(Error::Compile(
105
            "IF requires a test, a then-form, and an optional else-form".to_string(),
106
        ));
107
196714
    }
108
196714
    let (test, test_diverges) = classify_test(symbols, &args[0])?;
109
196714
    if test_diverges {
110
        // The test exits before producing a condition; compiling it for the
111
        // stack emits its terminating control flow (`br`/`throw`), leaving a
112
        // polymorphic stack that satisfies any declared result type. Both
113
        // branches are dead. Report I32 as a nominal type for callers.
114
419
        compile_for_stack(ctx, emit, symbols, &args[0])?;
115
419
        return Ok(WasmType::I32);
116
196295
    }
117
196295
    if super::is_runtime_test(&test) {
118
183393
        return compile_runtime_test_if(ctx, emit, symbols, args, expected);
119
12902
    }
120
12902
    let test = super::apply_const_test(ctx, emit, symbols, &args[0], &test)?;
121
12900
    if !test.is_nil() {
122
6118
        compile_for_stack_expecting(ctx, emit, symbols, &args[1], expected)
123
6782
    } else if args.len() == 3 {
124
6780
        compile_for_stack_expecting(ctx, emit, symbols, &args[2], expected)
125
    } else {
126
        // Const-false IF with no else ≡ nil — falsy i31, typed `Bool` so it
127
        // serializes as Nil and matches the eval mirror's `Expr::Nil`.
128
2
        emit.i32_const(0);
129
2
        Ok(WasmType::Bool)
130
    }
131
196714
}
132

            
133
/// Emit the runtime `if (result T)` block, with the i32 condition already on
134
/// the stack. Each branch compiles into its own scratch seeded at the
135
/// branch's wasm depth (`parent + 1`) — `compile_for_stack` lowers a
136
/// recursive self-call to `call $idx` and terminates, where an `eval_value`
137
/// peek would inline the body and recurse forever. The real branch types are
138
/// then unified (divergence-aware, widen-to-AnyRef on disagreement), each
139
/// scratch is coerced to `T`, and both are spliced into the live block — so
140
/// each branch is compiled exactly once.
141
192162
fn compile_runtime_if(
142
192162
    ctx: &mut CompileContext,
143
192162
    emit: &mut FunctionEmitter,
144
192162
    symbols: &mut SymbolTable,
145
192162
    args: &[Expr],
146
192162
    expected: Option<WasmType>,
147
192162
) -> Result<WasmType> {
148
192162
    let branch_depth = emit.block_depth() + 1;
149
192162
    let mut then_scratch = FunctionEmitter::new_seeded(branch_depth);
150
192162
    let then_arm = compile_branch_arm(ctx, &mut then_scratch, symbols, &args[1], expected)?;
151
180912
    let mut else_scratch = FunctionEmitter::new_seeded(branch_depth);
152
180912
    let else_arm = match args.get(2) {
153
        Some(else_form) => {
154
169670
            compile_branch_arm(ctx, &mut else_scratch, symbols, else_form, expected)?
155
        }
156
11242
        None => Some(Arm::Nil),
157
    };
158
180622
    let arms: Vec<Arm> = [then_arm, else_arm].into_iter().flatten().collect();
159
180622
    let result_ty = reconcile_arms_expecting(&arms, expected);
160

            
161
180622
    if let Some(arm) = then_arm {
162
138111
        finish_branch_arm(ctx, &mut then_scratch, symbols, &args[1], arm, result_ty)?;
163
42511
    }
164
180414
    match (args.get(2), else_arm) {
165
        (Some(else_form), Some(arm)) => {
166
163748
            finish_branch_arm(ctx, &mut else_scratch, symbols, else_form, arm, result_ty)?;
167
        }
168
11242
        (None, _) => emit_typed_nil(ctx, &mut else_scratch, result_ty)?,
169
5424
        (Some(_), None) => {}
170
    }
171

            
172
180414
    emit.if_block(BlockType::Result(ctx.wasm_val_type(result_ty)?));
173
180414
    emit.splice(&then_scratch)?;
174
180414
    emit.else_block();
175
180414
    emit.splice(&else_scratch)?;
176
180414
    emit.block_end()?;
177
180414
    Ok(result_ty)
178
192162
}
179

            
180
756549
pub(super) fn if_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
181
756549
    if args.len() < 2 || args.len() > 3 {
182
1
        return Err(Error::Compile(
183
1
            "IF requires a test, a then-form, and an optional else-form".to_string(),
184
1
        ));
185
756548
    }
186
    // The test runs exactly once, on the live table, whichever way it
187
    // classifies.
188
756548
    let (test, test_diverges) = super::block_exits::eval_and_diverges(symbols, &args[0])?;
189
751380
    if test_diverges {
190
419
        return Ok(test);
191
750961
    }
192
750961
    if super::is_runtime_test(&test) {
193
        // A runtime-test IF emits a wasm `if (result T)` block whose T the
194
        // codegen path (`compile_if_for_stack`) reconciles from both arms.
195
        // Eval-time typing MUST agree, or a binder that sizes a local from this
196
        // eval type (let / defvar / lambda arg) mismatches the value codegen
197
        // pushes — so both sides reconcile the same arms.
198
495038
        let then_arm = eval_arm(symbols, &args[1])?;
199
377100
        let else_arm = match args.get(2) {
200
361591
            Some(else_form) => eval_arm(symbols, else_form)?,
201
15509
            None => Some(Arm::Nil),
202
        };
203
357143
        let arms: Vec<Arm> = [then_arm, else_arm].into_iter().flatten().collect();
204
357143
        return Ok(Expr::WasmRuntime(reconcile_arms(&arms)));
205
255923
    }
206
255923
    if !test.is_nil() {
207
127203
        eval_value(symbols, &args[1])
208
128720
    } else if args.len() == 3 {
209
89370
        eval_value(symbols, &args[2])
210
    } else {
211
39350
        Ok(Expr::Nil)
212
    }
213
756549
}
214

            
215
#[cfg(test)]
216
#[path = "if_form_tests.rs"]
217
mod tests;