Lines
97.92 %
Functions
96.3 %
Branches
100 %
//! `BLOCK` / `RETURN-FROM` — Common-Lisp lexical labelled-exit
//! primitive. `(block name body...)` opens a wasm `block` whose label
//! is bound to `name` for the body's lexical extent;
//! `(return-from name value)` walks the BLOCK label stack and emits
//! `<value>` followed by `br <relative-depth>` to that block's exit.
//!
//! The block's wasm result type is discovered at **emit time**: the body
//! is compiled into a scratch buffer first; each reachable
//! `(return-from name v)` records `v`'s arm into the block frame, and
//! the fall-through tail (if control can reach it) contributes its arm
//! too. Reconciling those gives the result type `T`; then `block (result T)`
//! is opened in the parent and the scratch bytes spliced in. A numeric
//! literal arm emitted at another type than `T` makes that first pass a
//! discarded `recompile` probe: only `T`, as a `StructuralType`, survives
//! it, and a second pass compiles every literal exit and tail at `T`
//! (0014 P6a-i). The discarded pass also reports every nested block's join,
//! so the second pass compiles each of them once, at its join; a nested
//! block left unsettled while an enclosing pass can still be discarded
//! defers to it instead of recompiling itself (4.3b). Because only
//! *compiled* (reachable) exits record, code stored as a value
//! (quote / lambda / labels bodies, discarded macro args) contributes
//! nothing — no syntactic pre-scan and no per-form blocklist. The scratch
//! emitter is seeded at the depth the block frame will occupy, so every
//! relative `br` (incl. RETURN-FROM to an outer block) stays correct
//! after splicing.
//! Lexical-only: a RETURN-FROM whose name doesn't resolve to a BLOCK
//! frame in scope is a structured compile error. Dynamic non-local
//! exits are Tier 3 territory (try_table + throw).
use wasm_encoder::BlockType;
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_for_effect, emit_box_anyref, eval_value, probe_value, serialize_stack_to_output,
};
use crate::compiler::join::NEVER_RETURNS;
use crate::compiler::observations::{Observations, ObservedBlock, StructuralType};
use crate::compiler::recompile::Trial;
use crate::compiler::recompile::recompile;
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::super::binding::{eval_body, infer_runtime_type_with_body};
use super::arms::{
Arm, Exit, arm_of_form, compile_exit_value, lands_raw, reconcile_arms,
reconcile_arms_expecting, rides,
use super::block_exits::form_diverges;
use super::block_parse::{parse_block, parse_return_from};
use super::exit_scan::has_exit_to;
use super::skip_region::{after_exit, first_skipped, in_region, kept_definitions};
/// A block's value is its body's, except that a `return-from` to it makes the
/// value runtime: an exit's value is only known once emitted. The exits
/// evaluated against the block join with the tail as the compiled block's
/// do; an exit `has_exit_to` sees but the walk never reached leaves the tail
/// to type it. A transfer naming this block (raised only while a macro body
/// runs, see [`eval_return_from`]) is the block's value.
pub(super) fn eval_block(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
symbols.enter_shared_recursion()?;
let evaluated = eval_block_site(symbols, args);
let exited = symbols.exit_shared_recursion();
let value = evaluated?;
exited?;
Ok(value)
}
fn eval_block_site(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
let (name, body) = parse_block(args)?;
let (value, exits) = symbols.with_eval_block(name, |symbols| eval_body(symbols, body));
let value = match value {
Err(Error::Transfer { block, value }) if block == name => {
return Ok(*value);
other => other?,
match body.last() {
Some(_) if raises_transfers(symbols) => Ok(value),
Some(tail) if !exits.is_empty() => {
let ty = exit_join(symbols, body, tail, &value, exits)?;
Ok(Expr::WasmRuntime(ty))
Some(tail) if !value.is_wasm_runtime() && has_exit_to(symbols, name, body) => {
let ty = infer_runtime_type_with_body(&value, tail, body, symbols);
_ => Ok(value),
/// The block's type from its evaluated exit `arms` and, unless a body form
/// diverges, the tail's arm — the arms [`compile_block_pass`] reconciles.
fn exit_join(
symbols: &SymbolTable,
body: &[Expr],
tail: &Expr,
value: &Expr,
mut arms: Vec<Arm>,
) -> Result<WasmType> {
let mut falls_through = true;
for form in body {
if form_diverges(&mut symbols.clone(), form)? {
falls_through = false;
break;
if falls_through {
arms.push(arm_of_form(tail, value)?);
Ok(reconcile_arms(&arms))
/// Inside a macro body, outside any runtime branch, the evaluator is the real
/// interpreter: a reached exit raises a transfer and a block that completed
/// without one has its body's value. Everywhere else evaluation only peeks at
/// types for codegen, which compiles the exit itself.
fn raises_transfers(symbols: &SymbolTable) -> bool {
symbols.is_macro_expansion() && !symbols.is_under_any_runtime_guard()
pub(super) fn eval_return_from(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
let (name, value) = parse_return_from(args)?;
symbols.measurements().note_exit();
if raises_transfers(symbols) {
let value = eval_value(symbols, value)?;
return Err(Error::Transfer {
block: name.to_string(),
value: Box::new(value),
});
let value_ty = super::block_exits::peek_value_type(symbols, value)?;
if !form_diverges(&mut symbols.clone(), value)? {
let resolved = probe_value(&mut symbols.clone(), value)?;
symbols.record_eval_exit(name, arm_of_form(value, &resolved)?);
Ok(Expr::WasmRuntime(value_ty))
pub(super) fn compile_block(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
let ty = compile_block_for_stack(ctx, emit, symbols, args)?;
serialize_stack_to_output(ctx, emit, ty)
pub(super) fn compile_block_for_effect(
compile_block_for_stack(ctx, emit, symbols, args)?;
emit.drop_value();
Ok(())
pub(super) fn compile_block_for_stack(
compile_block_expecting(ctx, emit, symbols, args, None)
/// A BLOCK whose consumer expects `expected`: its first pass targets it, so a
/// block whose arms are all literals that fit it compiles once, as it.
pub(super) fn compile_block_expecting(
expected: Option<WasmType>,
let compiled = compile_block_site(ctx, emit, symbols, args, expected);
symbols.leave_shared_recursion(compiled)
fn compile_block_site(
if body.is_empty() {
// Empty `(block n)` ≡ nil — falsy i31, typed `Bool` to serialize as
// Nil and match the eval mirror (`eval_block` → `Expr::Nil`).
emit.i32_const(0);
return Ok(WasmType::Bool);
// The block frame sits one structured-control level below the parent's
// current depth. The body compiles into a scratch emitter seeded there,
// so relative `br` targets resolve as if the frame were already open;
// splicing preserves them.
let site = BlockSite {
name,
body,
frame_depth: emit.block_depth() + 1,
start: ctx.block_join_start(),
expected,
let guess = ctx.expected_block_join(name, body.len());
let outer = ctx.open_block_probe();
let first = recompile(ctx, symbols, |ctx, symbols| {
probe_block(ctx, symbols, &site, guess.as_ref(), outer.is_open())
let deferred = matches!(&first, Ok(Trial::Commit(pass)) if !pass.settled);
ctx.close_block_probe(outer, deferred);
let (pass, passes) = match first? {
Trial::Commit(pass) => (pass, 1),
Trial::Discard(observed) => {
let target = observed.result.intern(ctx)?;
let pass = ctx.expecting_block_joins(observed.blocks, |ctx| {
compile_block_pass(ctx, symbols, &site, Some(target))
})?;
(pass, 2)
ctx.compile_stats_mut().note_block_passes(passes);
let join = StructuralType::of(pass.result_ty, ctx)?;
ctx.record_block_join(
site.start,
ObservedBlock {
name: name.to_string(),
body_len: body.len(),
join,
},
);
emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(pass.result_ty)?));
if pass.padded {
emit.block_start_typed(BlockType::Result(ctx.wasm_val_type(WasmType::I32)?));
emit.splice(&pass.scratch)?;
emit.block_end()?;
emit_box_anyref(ctx, emit, WasmType::I32);
Ok(pass.result_ty)
/// Whether a pass at `target` opens an index pad just inside the block: the
/// `(result i32)` block an index exit [`lands_raw`] into, boxed after it.
fn pads_index(target: Option<WasmType>) -> bool {
target == Some(WasmType::AnyRef)
/// Where a BLOCK compiles: its label and body, the depth its frame takes,
/// where its join is recorded and the type its consumer expects.
struct BlockSite<'a> {
name: &'a str,
body: &'a [Expr],
frame_depth: u32,
start: usize,
/// One compilation of a BLOCK body: its bytes, its reconciled result type,
/// whether every arm was already emitted as that type and whether the bytes
/// sit in an index pad.
struct BlockPass {
scratch: FunctionEmitter,
result_ty: WasmType,
settled: bool,
padded: bool,
/// The first pass, at the join an enclosing pass observed for this block if
/// it has one, else at the type its consumer expects. It commits when
/// settled, or unsettled when `may_defer` (an enclosing pass will be
/// discarded instead); otherwise it is discarded and reports its join and its
/// nested blocks' joins.
fn probe_block(
site: &BlockSite,
guess: Option<&StructuralType>,
may_defer: bool,
) -> Result<Trial<BlockPass, Observations>> {
let target = guess
.map(|join| join.intern(ctx))
.transpose()?
.or(site.expected);
let pass = compile_block_pass(ctx, symbols, site, target)?;
if pass.settled || may_defer {
return Ok(Trial::Commit(pass));
let result = StructuralType::of(pass.result_ty, ctx)?;
let blocks = ctx.take_block_joins(site.start);
Ok(Trial::Discard(Observations { result, blocks }))
/// Compiles the body at `target`, or, without one, at each arm's own type. A
/// join of literals alone that fit the consumer's expectation is it; a guessed
/// `target` is never adopted, so a stale guess cannot settle. The pass is
/// settled when every exit's bytes already stand as the join.
fn compile_block_pass(
target: Option<WasmType>,
) -> Result<BlockPass> {
let BlockSite {
frame_depth,
..
} = *site;
let padded = pads_index(target);
let mut scratch = FunctionEmitter::new_seeded(frame_depth + u32::from(padded));
ctx.push_block_label(name, frame_depth, target);
let body_result = compile_block_body(ctx, &mut scratch, symbols, name, body, target);
let exits = ctx.pop_block_label(name)?;
let tail = body_result?;
if let Some((_, stack)) = tail
&& padded
&& !lands_raw(stack, target)
{
scratch.br(1);
let compiled: Vec<Exit> = tail
.map(|(exit, _)| exit)
.into_iter()
.chain(exits)
.collect();
let arms: Vec<Arm> = compiled.iter().map(|exit| exit.arm).collect();
let result_ty = reconcile_arms_expecting(&arms, expected);
if tail.is_none() {
// The body's tail is dead (an earlier form diverged); its concrete
// value would clash with the block result type, so a trailing
// `unreachable` resets the validator to a polymorphic stack. Live
// values leave only via the recorded `return-from` `br` edges.
scratch.unreachable();
let settled =
!ctx.block_probe_dirty() && compiled.iter().all(|exit| rides(exit.emitted, result_ty));
Ok(BlockPass {
scratch,
result_ty,
settled,
padded,
})
/// Compile a BLOCK body into `emit`, stopping at the first form that
/// unconditionally diverges — sequential forms after it are dead and must
/// not be emitted (their `(return-from)`s would record bogus exits, and
/// their bytes are unreachable). Returns the tail's exit and the type it left
/// on the stack, `None` when control cannot fall through to it. From the
/// first form that may exit the block on, a definition is refused.
fn compile_block_body(
name: &str,
) -> Result<Option<(Exit, WasmType)>> {
let last = body.len() - 1;
let exits = |form: &Expr| has_exit_to(symbols, name, std::slice::from_ref(form));
let first_exit = first_skipped(body, exits);
let kept = kept_definitions(body, first_exit, exits);
for (idx, form) in body.iter().enumerate() {
let region = after_exit(idx, first_exit.at, "BLOCK", &kept);
// Classify divergence on a CLONE: `form_diverges` runs `eval_value`
// (const-folding, macro expansion) which can mutate the symbol
// table via `setf`/`defparameter`. The form is compiled for real
// right after, so letting the classification mutate `symbols` would
// double-apply those effects. The clone keeps the query pure.
let diverges = form_diverges(&mut symbols.clone(), form)?;
if idx == last {
let tail = in_region(symbols, region.as_ref(), |symbols| {
compile_exit_value(ctx, emit, symbols, form, target)
return Ok((!diverges).then_some(tail));
// A diverging non-tail form exits the block; the rest is dead. It is
// compiled for effect so its `return-from` records and its `br` is
// emitted — the tail value comes from the recorded exits, sealed by
// the caller's `unreachable`.
in_region(symbols, region.as_ref(), |symbols| {
compile_for_effect(ctx, emit, symbols, form)
if diverges {
return Ok(None);
// Unreachable: an empty body is handled by the caller.
Ok(None)
pub(super) fn compile_return_from(
compile_return_from_for_stack(ctx, emit, symbols, args)?;
/// A RETURN-FROM inside a function body (a closure compiles as its own
/// function) sees only that body's blocks; the message says so when the
/// block it names is open in the code around it.
fn no_enclosing_block(ctx: &CompileContext, name: &str) -> Error {
match ctx.block_is_out_of_reach(name) {
true => Error::Compile(format!(
"RETURN-FROM '{name}' inside a function or closure cannot exit a BLOCK of its \
enclosing code; return a value from the function instead"
)),
false => Error::Compile(format!(
"RETURN-FROM '{name}': no enclosing BLOCK with that name"
pub(super) fn compile_return_from_for_stack(
let (target_depth, target) = match ctx.lookup_block_label(name) {
Some(frame) => (frame.wasm_depth, frame.target),
None => return Err(no_enclosing_block(ctx, name)),
if !emit.is_reachable() {
// Dead code (a DO step after a body that always exits): no value
// leaves, so nothing joins the block and no `br` is needed.
compile_for_effect(ctx, emit, symbols, value)?;
return Ok(NEVER_RETURNS);
let (exit, stack) = compile_exit_value(ctx, emit, symbols, value, target)?;
// Emit-time discovery: the enclosing block reconciles its result type
// from exactly the exits that can carry a value.
if emit.is_reachable() {
ctx.record_block_exit(name, exit);
// CL unwind semantics: before branching out, run the cleanup of every
// `(unwind-protect)` this exit crosses (innermost-first). The value is
// already on the stack; cleanups compile for effect (stack-neutral) so
// they don't disturb it. `br` then carries the value to the target block.
super::unwind_protect::emit_crossing_cleanups(ctx, emit, symbols, target_depth)?;
let landing = target_depth + u32::from(lands_raw(stack, target));
let current = emit.block_depth();
let relative = current.checked_sub(landing).ok_or_else(|| {
Error::Compile(format!(
"RETURN-FROM '{name}': inconsistent block-depth tracking ({current} < {landing})"
))
emit.br(relative);
// After a `br`, control never reaches here. wasm's stack polymorphism
// past `unreachable` lets the validator infer any surrounding-block
// result type, so we don't materialize a typed value.
emit.unreachable();
// A lone arm reconciles to its own type.
Ok(reconcile_arms(&[exit.arm]))
#[cfg(test)]
#[path = "block_tests.rs"]
mod tests;
#[path = "block_join_tests.rs"]
mod join_tests;
#[path = "block_memo_tests.rs"]
mod memo_tests;
#[path = "block_eval_join_tests.rs"]
mod eval_join_tests;