Lines
96.5 %
Functions
97.22 %
Branches
100 %
//! The runtime-clause tail of a `COND` chain: stack codegen and its eval
//! mirror. Both walk the remaining clauses in a loop, so chain length costs
//! no native recursion.
//!
//! Codegen emits one `block (result T)` holding `test; if; body; br 1; end`
//! per runtime clause, then the tail value, so wasm nesting stays two levels
//! deep for any clause count. `T` is reconciled over every arm at once, which
//! is more precise than joining clause by clause: a literal adopts a sibling
//! Scalar, and a nil arm rides a sibling list.
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_for_stack, probe_value};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::arms::{
Arm, compile_branch_arm, eval_arm, finish_branch_arm, in_runtime_branch, reconcile_arms,
};
use super::block_exits::{eval_and_diverges, form_diverges};
fn clause_elems(clause: &Expr) -> Result<&[Expr]> {
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()));
}
Ok(elems)
/// The value of a clause whose test holds: the test value itself for a
/// bodyless clause, else its body.
fn clause_value_expr(elems: &[Expr], test: Expr) -> Expr {
match elems {
[_, body @ ..] if !body.is_empty() => Expr::body(body),
_ => test,
/// A runtime clause awaiting the reconciled result type.
struct RuntimeClause {
/// Code before the clause's `if`: skipped constant clauses, the test and
/// its i32 condition.
lead: FunctionEmitter,
body: FunctionEmitter,
body_expr: Expr,
body_arm: Option<Arm>,
/// A walked chain. `pending` collects code at block depth until the next
/// runtime clause takes it as its `lead`; once the walk ends it holds the
/// tail that runs when no clause is taken.
struct Chain {
clauses: Vec<RuntimeClause>,
pending: FunctionEmitter,
tail: Option<(Expr, Arm)>,
inner_depth: u32,
impl Chain {
fn new(inner_depth: u32) -> Self {
Self {
clauses: Vec::new(),
pending: FunctionEmitter::new_seeded(inner_depth),
tail: None,
inner_depth,
/// Compiles a runtime clause's test into `pending` as its `if` condition
/// and returns the clause's value form. Only a bodyless clause, whose
/// value is the test itself, holds the test in a local.
fn compile_test(
&mut self,
ctx: &mut CompileContext,
symbols: &mut SymbolTable,
elems: &[Expr],
) -> Result<Expr> {
let [test] = elems else {
super::compile_test_condition(ctx, &mut self.pending, symbols, &elems[0])?;
return Ok(Expr::body(&elems[1..]));
let ty = compile_for_stack(ctx, &mut self.pending, symbols, test)?;
let local = ctx.alloc_local(ty)?;
self.pending.local_set(local);
let held = Expr::WasmLocal(local, ty);
super::compile_test_condition(ctx, &mut self.pending, symbols, &held)?;
Ok(held)
fn push_clause(
) -> Result<()> {
let mut body = FunctionEmitter::new_seeded(self.inner_depth + 1);
let body_arm = compile_branch_arm(ctx, &mut body, symbols, &body_expr, None)?;
let lead = std::mem::replace(
&mut self.pending,
FunctionEmitter::new_seeded(self.inner_depth),
);
self.clauses.push(RuntimeClause {
lead,
body,
body_expr,
body_arm,
});
Ok(())
fn set_tail(
expr: Expr,
let arm = compile_branch_arm(ctx, &mut self.pending, symbols, &expr, None)?;
self.tail = arm.map(|arm| (expr, arm));
/// Walks the clauses after the first runtime one until a clause is
/// known to be taken, a test diverges, or the chain runs out.
fn walk(
clauses: &[Expr],
for clause in clauses {
let elems = clause_elems(clause)?;
let probe = probe_value(&mut symbols.clone(), &elems[0])?;
if form_diverges(&mut symbols.clone(), &elems[0])? {
compile_for_stack(ctx, &mut self.pending, symbols, &elems[0])?;
// Code past the test's exit leaves a value `block_end` cannot
// clear; under UNWIND-PROTECT the frame even sees it live.
self.pending.unreachable();
return Ok(());
if super::is_runtime_test(&probe) {
let value = self.compile_test(ctx, symbols, elems)?;
self.push_clause(ctx, symbols, value)?;
continue;
if elems.len() == 1 && probe.is_wasm_runtime() {
return self.set_tail(ctx, symbols, elems[0].clone());
let test = super::apply_const_test(ctx, &mut self.pending, symbols, &elems[0], &probe)?;
if !test.is_nil() {
return self.set_tail(ctx, symbols, clause_value_expr(elems, test));
self.set_tail(ctx, symbols, Expr::Nil)
fn reconcile(&self) -> Result<WasmType> {
let arms: Vec<Arm> = self
.clauses
.iter()
.filter_map(|clause| clause.body_arm)
.chain(self.tail.as_ref().map(|(_, arm)| *arm))
.collect();
Ok(reconcile_arms(&arms))
fn finish(
result: WasmType,
for clause in &mut self.clauses {
if let Some(arm) = clause.body_arm {
finish_branch_arm(
ctx,
&mut clause.body,
symbols,
&clause.body_expr,
arm,
result,
)?;
if let Some((expr, arm)) = &self.tail {
finish_branch_arm(ctx, &mut self.pending, symbols, expr, *arm, result)?;
fn emit(
&self,
ctx: &CompileContext,
emit: &mut FunctionEmitter,
emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(result)?));
for clause in &self.clauses {
emit.splice(&clause.lead)?;
emit.if_block(BlockType::Empty);
emit.splice(&clause.body)?;
if clause.body.is_reachable() {
emit.br(1);
emit.block_end()?;
emit.splice(&self.pending)?;
emit.block_end()
/// Compiles a COND suffix whose first clause has a genuinely runtime test.
/// That test runs unconditionally; everything after it is compiled inside a
/// runtime branch.
pub(super) fn compile_cond_runtime_chain_for_stack(
args: &[Expr],
) -> Result<WasmType> {
let Some((first, rest)) = args.split_first() else {
return Err(Error::Compile(
"internal: COND runtime chain called with no clauses".to_string(),
));
let first = clause_elems(first)?;
let mut chain = Chain::new(emit.block_depth() + 1);
let value = chain.compile_test(ctx, symbols, first)?;
in_runtime_branch(symbols, |symbols| {
chain.push_clause(ctx, symbols, value)?;
chain.walk(ctx, symbols, rest)
let result = chain.reconcile()?;
chain.finish(ctx, symbols, result)?;
chain.emit(ctx, emit, result)?;
Ok(result)
/// Eval mirror of [`compile_cond_runtime_chain_for_stack`]. `elems`/`held`
/// is the first runtime clause, whose test already ran on the live
/// `symbols`; the rest is probed on one guarded clone.
pub(super) fn cond_runtime_chain_form(
held: Expr,
rest: &[Expr],
let mut probe = symbols.clone();
probe.enter_runtime_branch()?;
let mut arms: Vec<Arm> = eval_arm(&probe, &clause_value_expr(elems, held))?
.into_iter()
eval_rest_arms(&mut probe, rest, &mut arms)?;
fn eval_rest_arms(probe: &mut SymbolTable, rest: &[Expr], arms: &mut Vec<Arm>) -> Result<()> {
for clause in rest {
let (test, diverges) = eval_and_diverges(probe, &elems[0])?;
if diverges {
if super::is_runtime_test(&test) {
let held = Expr::WasmRuntime(classify_stack_type(&test).unwrap_or(WasmType::I32));
arms.extend(eval_arm(probe, &clause_value_expr(elems, held))?);
arms.extend(eval_arm(probe, &clause_value_expr(elems, test))?);
arms.push(Arm::Nil);
#[cfg(test)]
#[path = "cond_runtime_chain_tests.rs"]
mod tests;