1
//! The runtime-clause tail of a `COND` chain: stack codegen and its eval
2
//! mirror. Both walk the remaining clauses in a loop, so chain length costs
3
//! no native recursion.
4
//!
5
//! Codegen emits one `block (result T)` holding `test; if; body; br 1; end`
6
//! per runtime clause, then the tail value, so wasm nesting stays two levels
7
//! deep for any clause count. `T` is reconciled over every arm at once, which
8
//! is more precise than joining clause by clause: a literal adopts a sibling
9
//! Scalar, and a nil arm rides a sibling list.
10

            
11
use wasm_encoder::BlockType;
12

            
13
use crate::ast::{Expr, WasmType};
14
use crate::compiler::context::CompileContext;
15
use crate::compiler::emit::FunctionEmitter;
16
use crate::compiler::expr::format_form;
17
use crate::compiler::expr::{classify_stack_type, compile_for_stack, probe_value};
18
use crate::error::{Error, Result};
19
use crate::runtime::SymbolTable;
20

            
21
use super::arms::{
22
    Arm, compile_branch_arm, eval_arm, finish_branch_arm, in_runtime_branch, reconcile_arms,
23
};
24
use super::block_exits::{eval_and_diverges, form_diverges};
25

            
26
2302763
fn clause_elems(clause: &Expr) -> Result<&[Expr]> {
27
2302763
    let elems = clause.as_list().ok_or_else(|| {
28
12
        Error::Compile(format!(
29
12
            "COND: clause must be a list, got {}",
30
12
            format_form(clause)
31
12
        ))
32
12
    })?;
33
2302751
    if elems.is_empty() {
34
        return Err(Error::Compile("COND: empty clause".to_string()));
35
2302751
    }
36
2302751
    Ok(elems)
37
2302763
}
38

            
39
/// The value of a clause whose test holds: the test value itself for a
40
/// bodyless clause, else its body.
41
109671
fn clause_value_expr(elems: &[Expr], test: Expr) -> Expr {
42
109671
    match elems {
43
109671
        [_, body @ ..] if !body.is_empty() => Expr::body(body),
44
208
        _ => test,
45
    }
46
109671
}
47

            
48
/// A runtime clause awaiting the reconciled result type.
49
struct RuntimeClause {
50
    /// Code before the clause's `if`: skipped constant clauses, the test and
51
    /// its i32 condition.
52
    lead: FunctionEmitter,
53
    body: FunctionEmitter,
54
    body_expr: Expr,
55
    body_arm: Option<Arm>,
56
}
57

            
58
/// A walked chain. `pending` collects code at block depth until the next
59
/// runtime clause takes it as its `lead`; once the walk ends it holds the
60
/// tail that runs when no clause is taken.
61
struct Chain {
62
    clauses: Vec<RuntimeClause>,
63
    pending: FunctionEmitter,
64
    tail: Option<(Expr, Arm)>,
65
    inner_depth: u32,
66
}
67

            
68
impl Chain {
69
13848
    fn new(inner_depth: u32) -> Self {
70
13848
        Self {
71
13848
            clauses: Vec::new(),
72
13848
            pending: FunctionEmitter::new_seeded(inner_depth),
73
13848
            tail: None,
74
13848
            inner_depth,
75
13848
        }
76
13848
    }
77

            
78
    /// Compiles a runtime clause's test into `pending` as its `if` condition
79
    /// and returns the clause's value form. Only a bodyless clause, whose
80
    /// value is the test itself, holds the test in a local.
81
2203290
    fn compile_test(
82
2203290
        &mut self,
83
2203290
        ctx: &mut CompileContext,
84
2203290
        symbols: &mut SymbolTable,
85
2203290
        elems: &[Expr],
86
2203290
    ) -> Result<Expr> {
87
2203290
        let [test] = elems else {
88
2202662
            super::compile_test_condition(ctx, &mut self.pending, symbols, &elems[0])?;
89
2202651
            return Ok(Expr::body(&elems[1..]));
90
        };
91
628
        let ty = compile_for_stack(ctx, &mut self.pending, symbols, test)?;
92
626
        let local = ctx.alloc_local(ty)?;
93
626
        self.pending.local_set(local);
94
626
        let held = Expr::WasmLocal(local, ty);
95
626
        super::compile_test_condition(ctx, &mut self.pending, symbols, &held)?;
96
626
        Ok(held)
97
2203290
    }
98

            
99
2203277
    fn push_clause(
100
2203277
        &mut self,
101
2203277
        ctx: &mut CompileContext,
102
2203277
        symbols: &mut SymbolTable,
103
2203277
        body_expr: Expr,
104
2203277
    ) -> Result<()> {
105
2203277
        let mut body = FunctionEmitter::new_seeded(self.inner_depth + 1);
106
2203277
        let body_arm = compile_branch_arm(ctx, &mut body, symbols, &body_expr, None)?;
107
2203069
        let lead = std::mem::replace(
108
2203069
            &mut self.pending,
109
2203069
            FunctionEmitter::new_seeded(self.inner_depth),
110
2203069
        );
111
2203069
        self.clauses.push(RuntimeClause {
112
2203069
            lead,
113
2203069
            body,
114
2203069
            body_expr,
115
2203069
            body_arm,
116
2203069
        });
117
2203069
        Ok(())
118
2203277
    }
119

            
120
12373
    fn set_tail(
121
12373
        &mut self,
122
12373
        ctx: &mut CompileContext,
123
12373
        symbols: &mut SymbolTable,
124
12373
        expr: Expr,
125
12373
    ) -> Result<()> {
126
12373
        let arm = compile_branch_arm(ctx, &mut self.pending, symbols, &expr, None)?;
127
12165
        self.tail = arm.map(|arm| (expr, arm));
128
12165
        Ok(())
129
12373
    }
130

            
131
    /// Walks the clauses after the first runtime one until a clause is
132
    /// known to be taken, a test diverges, or the chain runs out.
133
13627
    fn walk(
134
13627
        &mut self,
135
13627
        ctx: &mut CompileContext,
136
13627
        symbols: &mut SymbolTable,
137
13627
        clauses: &[Expr],
138
13627
    ) -> Result<()> {
139
13627
        for clause in clauses {
140
2202234
            let elems = clause_elems(clause)?;
141
2202228
            let probe = probe_value(&mut symbols.clone(), &elems[0])?;
142
2202228
            if form_diverges(&mut symbols.clone(), &elems[0])? {
143
1248
                compile_for_stack(ctx, &mut self.pending, symbols, &elems[0])?;
144
                // Code past the test's exit leaves a value `block_end` cannot
145
                // clear; under UNWIND-PROTECT the frame even sees it live.
146
1248
                self.pending.unreachable();
147
1248
                return Ok(());
148
2200980
            }
149
2200980
            if super::is_runtime_test(&probe) {
150
2189442
                let value = self.compile_test(ctx, symbols, elems)?;
151
2189442
                self.push_clause(ctx, symbols, value)?;
152
2189442
                continue;
153
11538
            }
154
11538
            if elems.len() == 1 && probe.is_wasm_runtime() {
155
                return self.set_tail(ctx, symbols, elems[0].clone());
156
11538
            }
157
11538
            let test = super::apply_const_test(ctx, &mut self.pending, symbols, &elems[0], &probe)?;
158
11538
            if !test.is_nil() {
159
11538
                return self.set_tail(ctx, symbols, clause_value_expr(elems, test));
160
            }
161
        }
162
835
        self.set_tail(ctx, symbols, Expr::Nil)
163
13627
    }
164

            
165
13413
    fn reconcile(&self) -> Result<WasmType> {
166
13413
        let arms: Vec<Arm> = self
167
13413
            .clauses
168
13413
            .iter()
169
2202855
            .filter_map(|clause| clause.body_arm)
170
13413
            .chain(self.tail.as_ref().map(|(_, arm)| *arm))
171
            .collect();
172
13413
        Ok(reconcile_arms(&arms))
173
13413
    }
174

            
175
13413
    fn finish(
176
13413
        &mut self,
177
13413
        ctx: &mut CompileContext,
178
13413
        symbols: &mut SymbolTable,
179
13413
        result: WasmType,
180
13413
    ) -> Result<()> {
181
13413
        for clause in &mut self.clauses {
182
2202855
            if let Some(arm) = clause.body_arm {
183
2202432
                finish_branch_arm(
184
2202432
                    ctx,
185
2202432
                    &mut clause.body,
186
2202432
                    symbols,
187
2202432
                    &clause.body_expr,
188
2202432
                    arm,
189
2202432
                    result,
190
2202432
                )?;
191
423
            }
192
        }
193
13205
        if let Some((expr, arm)) = &self.tail {
194
9876
            finish_branch_arm(ctx, &mut self.pending, symbols, expr, *arm, result)?;
195
3329
        }
196
12997
        Ok(())
197
13413
    }
198

            
199
12997
    fn emit(
200
12997
        &self,
201
12997
        ctx: &CompileContext,
202
12997
        emit: &mut FunctionEmitter,
203
12997
        result: WasmType,
204
12997
    ) -> Result<()> {
205
12997
        emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(result)?));
206
12997
        for clause in &self.clauses {
207
2202439
            emit.splice(&clause.lead)?;
208
2202439
            emit.if_block(BlockType::Empty);
209
2202439
            emit.splice(&clause.body)?;
210
2202439
            if clause.body.is_reachable() {
211
2202016
                emit.br(1);
212
423
            }
213
2202439
            emit.block_end()?;
214
        }
215
12997
        emit.splice(&self.pending)?;
216
12997
        emit.block_end()
217
12997
    }
218
}
219

            
220
/// Compiles a COND suffix whose first clause has a genuinely runtime test.
221
/// That test runs unconditionally; everything after it is compiled inside a
222
/// runtime branch.
223
13848
pub(super) fn compile_cond_runtime_chain_for_stack(
224
13848
    ctx: &mut CompileContext,
225
13848
    emit: &mut FunctionEmitter,
226
13848
    symbols: &mut SymbolTable,
227
13848
    args: &[Expr],
228
13848
) -> Result<WasmType> {
229
13848
    let Some((first, rest)) = args.split_first() else {
230
        return Err(Error::Compile(
231
            "internal: COND runtime chain called with no clauses".to_string(),
232
        ));
233
    };
234
13848
    let first = clause_elems(first)?;
235
13848
    let mut chain = Chain::new(emit.block_depth() + 1);
236
13848
    let value = chain.compile_test(ctx, symbols, first)?;
237
13835
    in_runtime_branch(symbols, |symbols| {
238
13835
        chain.push_clause(ctx, symbols, value)?;
239
13627
        chain.walk(ctx, symbols, rest)
240
13835
    })?;
241
13413
    let result = chain.reconcile()?;
242
13413
    chain.finish(ctx, symbols, result)?;
243
12997
    chain.emit(ctx, emit, result)?;
244
12997
    Ok(result)
245
13848
}
246

            
247
/// Eval mirror of [`compile_cond_runtime_chain_for_stack`]. `elems`/`held`
248
/// is the first runtime clause, whose test already ran on the live
249
/// `symbols`; the rest is probed on one guarded clone.
250
12082
pub(super) fn cond_runtime_chain_form(
251
12082
    symbols: &mut SymbolTable,
252
12082
    elems: &[Expr],
253
12082
    held: Expr,
254
12082
    rest: &[Expr],
255
12082
) -> Result<WasmType> {
256
12082
    let mut probe = symbols.clone();
257
12082
    probe.enter_runtime_branch()?;
258
12082
    let mut arms: Vec<Arm> = eval_arm(&probe, &clause_value_expr(elems, held))?
259
        .into_iter()
260
        .collect();
261
11666
    eval_rest_arms(&mut probe, rest, &mut arms)?;
262
11660
    Ok(reconcile_arms(&arms))
263
12082
}
264

            
265
11666
fn eval_rest_arms(probe: &mut SymbolTable, rest: &[Expr], arms: &mut Vec<Arm>) -> Result<()> {
266
11666
    for clause in rest {
267
86681
        let elems = clause_elems(clause)?;
268
86675
        let (test, diverges) = eval_and_diverges(probe, &elems[0])?;
269
86675
        if diverges {
270
624
            return Ok(());
271
86051
        }
272
86051
        if super::is_runtime_test(&test) {
273
75441
            let held = Expr::WasmRuntime(classify_stack_type(&test).unwrap_or(WasmType::I32));
274
75441
            arms.extend(eval_arm(probe, &clause_value_expr(elems, held))?);
275
75441
            continue;
276
10610
        }
277
10610
        if !test.is_nil() {
278
10610
            arms.extend(eval_arm(probe, &clause_value_expr(elems, test))?);
279
10610
            return Ok(());
280
        }
281
    }
282
426
    arms.push(Arm::Nil);
283
426
    Ok(())
284
11666
}
285

            
286
#[cfg(test)]
287
#[path = "cond_runtime_chain_tests.rs"]
288
mod tests;