Lines
96.06 %
Functions
77.27 %
Branches
100 %
//! `COND` clause chain. A constant-test clause prefix folds in a plain loop;
//! from the first genuinely runtime clause on, `cond_runtime_chain` walks the
//! rest, also without native recursion.
use wasm_encoder::BlockType;
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::format_form;
use crate::compiler::expr::{
classify_stack_type, compile_body, compile_body_for_stack, compile_expr, compile_for_effect,
compile_for_stack, compile_nil, probe_value, serialize_stack_to_output,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::cond_runtime_chain::{compile_cond_runtime_chain_for_stack, cond_runtime_chain_form};
pub(super) fn compile_cond(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
for (i, clause) in args.iter().enumerate() {
let elems = clause.as_list().ok_or_else(|| {
Error::Compile(format!(
"COND: clause must be a list, got {}",
format_form(clause)
))
})?;
if elems.is_empty() {
return Err(Error::Compile("COND: empty clause".to_string()));
}
// Classify on a CLONE so the test's compile-time effects reach the
// live table only via the single emit below.
let test = probe_value(&mut symbols.clone(), &elems[0])?;
let test_diverges = super::block_exits::form_diverges(&mut symbols.clone(), &elems[0])?;
if super::is_runtime_test(&test) || test_diverges {
// Runtime (or diverging) test: emit ONE merged `if (result T)`
// chain via the stack path, then serialize the single result.
// Serializing each clause body separately double-advances the
// compile-time output cursor (every clause bakes an entity header,
// but only one runs) — the decoder then reads a garbage entity
// slot. The IF-chain the stack path builds also fires a diverging
// test correctly (vs. const-folding past it). Mirror IF's fix.
let ty = compile_cond_for_stack(ctx, emit, symbols, &args[i..])?;
return serialize_stack_to_output(ctx, emit, ty);
if elems.len() == 1 && test.is_wasm_runtime() {
return compile_expr(ctx, emit, symbols, &elems[0]);
let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &test)?;
if !test.is_nil() {
if elems.len() == 1 {
return compile_expr(ctx, emit, symbols, &test);
return compile_body(ctx, emit, symbols, &elems[1..]);
compile_nil(ctx, emit)?;
Ok(())
pub(super) fn compile_cond_for_stack(
) -> Result<WasmType> {
// A constant-test clause prefix is a plain loop over `args`; the first
// genuinely runtime clause hands the rest to the runtime chain.
let mut idx = 0;
loop {
let Some(clause) = args.get(idx) else {
emit.i32_const(0);
return Ok(WasmType::Bool);
let probe = probe_value(&mut symbols.clone(), &elems[0])?;
if !super::is_runtime_test(&probe) && !test_diverges {
// Fold a genuine compile-time CONSTANT first — wrapping it in a
// WasmLocal placeholder unconditionally (the previous approach)
// makes `if_form` treat a known-true constant as a live runtime
// test needing a real branch, compiling the provably-unreachable
// `rest` and surfacing whatever it contains (e.g. an undefined
// symbol) even though CL semantics say it never runs. Only a
// genuinely runtime (or diverging) test needs the real wasm
// local + branch.
// CL: a bodyless clause returns its test value, evaluated
// exactly once.
if probe.is_wasm_runtime() {
// A `Never`-repr runtime value (index / money / closure)
// can never be nil — it folds true unconditionally, so
// `rest` is unreachable and must never compile (mirrors
// `compile_cond`'s own `elems.len() == 1 &&
// test.is_wasm_runtime()` case).
return compile_for_stack(ctx, emit, symbols, &elems[0]);
let test = super::apply_const_test(ctx, emit, symbols, &elems[0], &probe)?;
return compile_for_stack(ctx, emit, symbols, &test);
idx += 1;
continue;
return compile_body_for_stack(ctx, emit, symbols, &elems[1..]);
// A diverging test never returns control to decide a branch —
// compile it for its diverging effect alone and stop. `rest` (and
// the clause's own body) are UNREACHABLE and must never be
// compiled: routing a diverging test through the held-test IF
// construction below would hand `if_form` a normal boolean branch
// and make it compile+classify the unreachable body too, surfacing
// whatever it contains (e.g. an undefined symbol) as a compile
// error even though CL semantics say it never runs.
if test_diverges {
return compile_cond_runtime_chain_for_stack(ctx, emit, symbols, &args[idx..]);
pub(super) fn compile_cond_for_effect(
// Classify on a CLONE so the test's compile-time side effects are not
// applied to the live table during classification — they ride the
// single emit below exactly once.
return compile_cond_runtime_for_effect(ctx, emit, symbols, &args[i..]);
for expr in &elems[1..] {
compile_for_effect(ctx, emit, symbols, expr)?;
return Ok(());
/// Effect-position codegen for a COND suffix whose first clause has a runtime
/// (or diverging) test. Each runtime clause opens a guard `if` and (when not
/// last) an `else`; clause bodies compile for effect — so effect-only forms
/// (`DOLIST`, etc.) that have no stack lowering still work, unlike a
/// stack+drop rewrite. Tracks the ACTUAL number of open guard blocks (not the
/// clause index, which over-counts when const-false clauses sit between
/// runtime ones) so the closing `block_end`s match exactly.
fn compile_cond_runtime_for_effect(
// Each open `if` block below is a REAL conditional in the emitted wasm,
// but a compile-time-only place (`SETF`'s const-place branch) has no
// bytecode of its own to guard — without marking the scope, its
// compile-time model update would apply unconditionally regardless of
// which branch runs. Entered ONCE, on the FIRST runtime clause (not
// once per clause: this loop is flat iteration over `args`, not native
// recursion, so it must not charge the shared recursion budget more
// than once), and always undone on the way out — whichever of this
// function's several return points is taken.
let mut guarded = false;
let result = compile_cond_runtime_for_effect_body(ctx, emit, symbols, args, &mut guarded);
if guarded {
symbols.exit_runtime_guard()?;
result
fn compile_cond_runtime_for_effect_body(
guarded: &mut bool,
let last = args.len() - 1;
let mut open_guards = 0u32;
// Compile the test for effect so its exit fires; the remaining
// chain is dead. Close exactly the guards opened so far.
compile_for_effect(ctx, emit, symbols, &elems[0])?;
for _ in 0..open_guards {
emit.block_end()?;
if super::is_runtime_test(&test) {
// The FIRST runtime clause's own test always runs
// unconditionally to decide the branch — only its BODY (and
// the rest of the chain) is conditional — so it must compile
// BEFORE the guard is entered, matching stack/eval position.
// A LATER runtime clause's test is itself only reached when
// every earlier test was false, so it compiles WHILE already
// guarded, correctly.
let entering_guard = !*guarded;
super::compile_test_condition(ctx, emit, symbols, &elems[0])?;
if entering_guard {
symbols.enter_runtime_guard()?;
*guarded = true;
emit.if_block(BlockType::Empty);
// Each runtime clause opens exactly one `if` block (one `end`),
// whether or not an `else` arm follows — count it.
open_guards += 1;
if i != last {
emit.else_block();
} else {
pub(super) fn cond_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
// Same non-recursive walk as `compile_cond_for_stack`: a constant-false
// clause prefix is a plain loop, and a runtime clause hands the rest to
// `cond_runtime_chain_form`.
// The test runs exactly once on the live table, whichever way it
// classifies.
let (test, test_diverges) = super::block_exits::eval_and_diverges(symbols, &elems[0])?;
// Its `Err` already propagated; the body and the rest are
// unreachable.
return Ok(test);
let held = Expr::WasmRuntime(classify_stack_type(&test).unwrap_or(WasmType::I32));
let result_ty = cond_runtime_chain_form(symbols, elems, held, &args[i + 1..])?;
return Ok(Expr::WasmRuntime(result_ty));
return super::super::binding::eval_body(symbols, &elems[1..]);
Ok(Expr::Nil)