1
//! `COND` clause chain. A constant-test clause prefix folds in a plain loop;
2
//! from the first genuinely runtime clause on, `cond_runtime_chain` walks the
3
//! rest, also without native recursion.
4

            
5
use wasm_encoder::BlockType;
6

            
7
use crate::ast::{Expr, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::format_form;
11
use crate::compiler::expr::{
12
    classify_stack_type, compile_body, compile_body_for_stack, compile_expr, compile_for_effect,
13
    compile_for_stack, compile_nil, probe_value, serialize_stack_to_output,
14
};
15
use crate::error::{Error, Result};
16
use crate::runtime::SymbolTable;
17

            
18
use super::cond_runtime_chain::{compile_cond_runtime_chain_for_stack, cond_runtime_chain_form};
19

            
20
5885
pub(super) fn compile_cond(
21
5885
    ctx: &mut CompileContext,
22
5885
    emit: &mut FunctionEmitter,
23
5885
    symbols: &mut SymbolTable,
24
5885
    args: &[Expr],
25
5885
) -> Result<()> {
26
5885
    for (i, clause) in args.iter().enumerate() {
27
422322
        let elems = clause.as_list().ok_or_else(|| {
28
4
            Error::Compile(format!(
29
4
                "COND: clause must be a list, got {}",
30
4
                format_form(clause)
31
4
            ))
32
4
        })?;
33
422318
        if elems.is_empty() {
34
            return Err(Error::Compile("COND: empty clause".to_string()));
35
422318
        }
36
        // Classify on a CLONE so the test's compile-time effects reach the
37
        // live table only via the single emit below.
38
422318
        let test = probe_value(&mut symbols.clone(), &elems[0])?;
39
422318
        let test_diverges = super::block_exits::form_diverges(&mut symbols.clone(), &elems[0])?;
40
422318
        if super::is_runtime_test(&test) || test_diverges {
41
            // Runtime (or diverging) test: emit ONE merged `if (result T)`
42
            // chain via the stack path, then serialize the single result.
43
            // Serializing each clause body separately double-advances the
44
            // compile-time output cursor (every clause bakes an entity header,
45
            // but only one runs) — the decoder then reads a garbage entity
46
            // slot. The IF-chain the stack path builds also fires a diverging
47
            // test correctly (vs. const-folding past it). Mirror IF's fix.
48
3760
            let ty = compile_cond_for_stack(ctx, emit, symbols, &args[i..])?;
49
3342
            return serialize_stack_to_output(ctx, emit, ty);
50
418558
        }
51
418558
        if elems.len() == 1 && test.is_wasm_runtime() {
52
            return compile_expr(ctx, emit, symbols, &elems[0]);
53
418558
        }
54
418558
        let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &test)?;
55
418558
        if !test.is_nil() {
56
1701
            if elems.len() == 1 {
57
208
                return compile_expr(ctx, emit, symbols, &test);
58
1493
            }
59
1493
            return compile_body(ctx, emit, symbols, &elems[1..]);
60
416857
        }
61
    }
62
420
    compile_nil(ctx, emit)?;
63
420
    Ok(())
64
5885
}
65

            
66
16031
pub(super) fn compile_cond_for_stack(
67
16031
    ctx: &mut CompileContext,
68
16031
    emit: &mut FunctionEmitter,
69
16031
    symbols: &mut SymbolTable,
70
16031
    args: &[Expr],
71
16031
) -> Result<WasmType> {
72
    // A constant-test clause prefix is a plain loop over `args`; the first
73
    // genuinely runtime clause hands the rest to the runtime chain.
74
16031
    let mut idx = 0;
75
    loop {
76
43763
        let Some(clause) = args.get(idx) else {
77
6
            emit.i32_const(0);
78
6
            return Ok(WasmType::Bool);
79
        };
80
43757
        let elems = clause.as_list().ok_or_else(|| {
81
5
            Error::Compile(format!(
82
5
                "COND: clause must be a list, got {}",
83
5
                format_form(clause)
84
5
            ))
85
5
        })?;
86
43752
        if elems.is_empty() {
87
            return Err(Error::Compile("COND: empty clause".to_string()));
88
43752
        }
89
43752
        let probe = probe_value(&mut symbols.clone(), &elems[0])?;
90
43544
        let test_diverges = super::block_exits::form_diverges(&mut symbols.clone(), &elems[0])?;
91
43544
        if !super::is_runtime_test(&probe) && !test_diverges {
92
            // Fold a genuine compile-time CONSTANT first — wrapping it in a
93
            // WasmLocal placeholder unconditionally (the previous approach)
94
            // makes `if_form` treat a known-true constant as a live runtime
95
            // test needing a real branch, compiling the provably-unreachable
96
            // `rest` and surfacing whatever it contains (e.g. an undefined
97
            // symbol) even though CL semantics say it never runs. Only a
98
            // genuinely runtime (or diverging) test needs the real wasm
99
            // local + branch.
100
29488
            if elems.len() == 1 {
101
                // CL: a bodyless clause returns its test value, evaluated
102
                // exactly once.
103
832
                if probe.is_wasm_runtime() {
104
                    // A `Never`-repr runtime value (index / money / closure)
105
                    // can never be nil — it folds true unconditionally, so
106
                    // `rest` is unreachable and must never compile (mirrors
107
                    // `compile_cond`'s own `elems.len() == 1 &&
108
                    // test.is_wasm_runtime()` case).
109
                    return compile_for_stack(ctx, emit, symbols, &elems[0]);
110
832
                }
111
832
                let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &probe)?;
112
832
                if !test.is_nil() {
113
416
                    return compile_for_stack(ctx, emit, symbols, &test);
114
416
                }
115
416
                idx += 1;
116
416
                continue;
117
28656
            }
118
28656
            let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &probe)?;
119
28656
            if !test.is_nil() {
120
1340
                return compile_body_for_stack(ctx, emit, symbols, &elems[1..]);
121
27316
            }
122
27316
            idx += 1;
123
27316
            continue;
124
14056
        }
125
        // A diverging test never returns control to decide a branch —
126
        // compile it for its diverging effect alone and stop. `rest` (and
127
        // the clause's own body) are UNREACHABLE and must never be
128
        // compiled: routing a diverging test through the held-test IF
129
        // construction below would hand `if_form` a normal boolean branch
130
        // and make it compile+classify the unreachable body too, surfacing
131
        // whatever it contains (e.g. an undefined symbol) as a compile
132
        // error even though CL semantics say it never runs.
133
14056
        if test_diverges {
134
208
            return compile_for_stack(ctx, emit, symbols, &elems[0]);
135
13848
        }
136
13848
        return compile_cond_runtime_chain_for_stack(ctx, emit, symbols, &args[idx..]);
137
    }
138
16031
}
139

            
140
20318
pub(super) fn compile_cond_for_effect(
141
20318
    ctx: &mut CompileContext,
142
20318
    emit: &mut FunctionEmitter,
143
20318
    symbols: &mut SymbolTable,
144
20318
    args: &[Expr],
145
20318
) -> Result<()> {
146
20318
    for (i, clause) in args.iter().enumerate() {
147
436532
        let elems = clause.as_list().ok_or_else(|| {
148
3
            Error::Compile(format!(
149
3
                "COND: clause must be a list, got {}",
150
3
                format_form(clause)
151
3
            ))
152
3
        })?;
153
436529
        if elems.is_empty() {
154
            return Err(Error::Compile("COND: empty clause".to_string()));
155
436529
        }
156
        // Classify on a CLONE so the test's compile-time side effects are not
157
        // applied to the live table during classification — they ride the
158
        // single emit below exactly once.
159
436529
        let test = probe_value(&mut symbols.clone(), &elems[0])?;
160
436529
        let test_diverges = super::block_exits::form_diverges(&mut symbols.clone(), &elems[0])?;
161
436529
        if super::is_runtime_test(&test) || test_diverges {
162
6061
            return compile_cond_runtime_for_effect(ctx, emit, symbols, &args[i..]);
163
430468
        }
164
430468
        let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &test)?;
165
430468
        if !test.is_nil() {
166
14043
            for expr in &elems[1..] {
167
13627
                compile_for_effect(ctx, emit, symbols, expr)?;
168
            }
169
13835
            return Ok(());
170
416425
        }
171
    }
172
211
    Ok(())
173
20318
}
174

            
175
/// Effect-position codegen for a COND suffix whose first clause has a runtime
176
/// (or diverging) test. Each runtime clause opens a guard `if` and (when not
177
/// last) an `else`; clause bodies compile for effect — so effect-only forms
178
/// (`DOLIST`, etc.) that have no stack lowering still work, unlike a
179
/// stack+drop rewrite. Tracks the ACTUAL number of open guard blocks (not the
180
/// clause index, which over-counts when const-false clauses sit between
181
/// runtime ones) so the closing `block_end`s match exactly.
182
6061
fn compile_cond_runtime_for_effect(
183
6061
    ctx: &mut CompileContext,
184
6061
    emit: &mut FunctionEmitter,
185
6061
    symbols: &mut SymbolTable,
186
6061
    args: &[Expr],
187
6061
) -> Result<()> {
188
    // Each open `if` block below is a REAL conditional in the emitted wasm,
189
    // but a compile-time-only place (`SETF`'s const-place branch) has no
190
    // bytecode of its own to guard — without marking the scope, its
191
    // compile-time model update would apply unconditionally regardless of
192
    // which branch runs. Entered ONCE, on the FIRST runtime clause (not
193
    // once per clause: this loop is flat iteration over `args`, not native
194
    // recursion, so it must not charge the shared recursion budget more
195
    // than once), and always undone on the way out — whichever of this
196
    // function's several return points is taken.
197
6061
    let mut guarded = false;
198
6061
    let result = compile_cond_runtime_for_effect_body(ctx, emit, symbols, args, &mut guarded);
199
6061
    if guarded {
200
5437
        symbols.exit_runtime_guard()?;
201
624
    }
202
6061
    result
203
6061
}
204

            
205
6061
fn compile_cond_runtime_for_effect_body(
206
6061
    ctx: &mut CompileContext,
207
6061
    emit: &mut FunctionEmitter,
208
6061
    symbols: &mut SymbolTable,
209
6061
    args: &[Expr],
210
6061
    guarded: &mut bool,
211
6061
) -> Result<()> {
212
6061
    let last = args.len() - 1;
213
6061
    let mut open_guards = 0u32;
214
6061
    for (i, clause) in args.iter().enumerate() {
215
14205
        let elems = clause.as_list().ok_or_else(|| {
216
3
            Error::Compile(format!(
217
3
                "COND: clause must be a list, got {}",
218
3
                format_form(clause)
219
3
            ))
220
3
        })?;
221
14202
        if elems.is_empty() {
222
            return Err(Error::Compile("COND: empty clause".to_string()));
223
14202
        }
224
14202
        let test = probe_value(&mut symbols.clone(), &elems[0])?;
225
14202
        let test_diverges = super::block_exits::form_diverges(&mut symbols.clone(), &elems[0])?;
226
14202
        if test_diverges {
227
            // Compile the test for effect so its exit fires; the remaining
228
            // chain is dead. Close exactly the guards opened so far.
229
624
            compile_for_effect(ctx, emit, symbols, &elems[0])?;
230
624
            for _ in 0..open_guards {
231
                emit.block_end()?;
232
            }
233
624
            return Ok(());
234
13578
        }
235
13578
        if super::is_runtime_test(&test) {
236
            // The FIRST runtime clause's own test always runs
237
            // unconditionally to decide the branch — only its BODY (and
238
            // the rest of the chain) is conditional — so it must compile
239
            // BEFORE the guard is entered, matching stack/eval position.
240
            // A LATER runtime clause's test is itself only reached when
241
            // every earlier test was false, so it compiles WHILE already
242
            // guarded, correctly.
243
13347
            let entering_guard = !*guarded;
244
13347
            super::compile_test_condition(ctx, emit, symbols, &elems[0])?;
245
13347
            if entering_guard {
246
5437
                symbols.enter_runtime_guard()?;
247
5437
                *guarded = true;
248
7910
            }
249
13347
            emit.if_block(BlockType::Empty);
250
            // Each runtime clause opens exactly one `if` block (one `end`),
251
            // whether or not an `else` arm follows — count it.
252
13347
            open_guards += 1;
253
13347
            for expr in &elems[1..] {
254
13347
                compile_for_effect(ctx, emit, symbols, expr)?;
255
            }
256
12931
            if i != last {
257
7936
                emit.else_block();
258
4995
            }
259
        } else {
260
231
            let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &test)?;
261
231
            if !test.is_nil() {
262
23
                for expr in &elems[1..] {
263
23
                    compile_for_effect(ctx, emit, symbols, expr)?;
264
                }
265
23
                for _ in 0..open_guards {
266
23
                    emit.block_end()?;
267
                }
268
23
                return Ok(());
269
208
            }
270
        }
271
    }
272
4995
    for _ in 0..open_guards {
273
12905
        emit.block_end()?;
274
    }
275
4995
    Ok(())
276
6061
}
277

            
278
198670
pub(super) fn cond_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
279
    // Same non-recursive walk as `compile_cond_for_stack`: a constant-false
280
    // clause prefix is a plain loop, and a runtime clause hands the rest to
281
    // `cond_runtime_chain_form`.
282
198670
    for (i, clause) in args.iter().enumerate() {
283
615942
        let elems = clause.as_list().ok_or_else(|| {
284
9
            Error::Compile(format!(
285
9
                "COND: clause must be a list, got {}",
286
9
                format_form(clause)
287
9
            ))
288
9
        })?;
289
615933
        if elems.is_empty() {
290
            return Err(Error::Compile("COND: empty clause".to_string()));
291
615933
        }
292
        // The test runs exactly once on the live table, whichever way it
293
        // classifies.
294
615933
        let (test, test_diverges) = super::block_exits::eval_and_diverges(symbols, &elems[0])?;
295
615517
        if test_diverges {
296
            // Its `Err` already propagated; the body and the rest are
297
            // unreachable.
298
208
            return Ok(test);
299
615309
        }
300
615309
        if super::is_runtime_test(&test) {
301
12082
            let held = Expr::WasmRuntime(classify_stack_type(&test).unwrap_or(WasmType::I32));
302
12082
            let result_ty = cond_runtime_chain_form(symbols, elems, held, &args[i + 1..])?;
303
11660
            return Ok(Expr::WasmRuntime(result_ty));
304
603227
        }
305
603227
        if !test.is_nil() {
306
185930
            if elems.len() == 1 {
307
416
                return Ok(test);
308
185514
            }
309
185514
            return super::super::binding::eval_body(symbols, &elems[1..]);
310
417297
        }
311
    }
312
25
    Ok(Expr::Nil)
313
198670
}