Lines
96.17 %
Functions
94.44 %
Branches
100 %
//! Result-type reconciliation shared by the multi-arm special forms (IF,
//! HANDLER-CASE). Each reachable arm is an already-compiled value, a
//! dimension-flexible numeric literal, or `nil`; the latter two are emitted only
//! once the unified block type is known, so a literal crosses Index↔Scalar
//! (ADR-0028) and a `nil` beside a list stays a null pair.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
classify_stack_type, compile_for_effect, compile_for_stack, compile_for_stack_as,
compile_for_stack_expecting, emit_box_anyref, emit_nil_default, eval_value, fold_safe,
fold_value, format_form,
};
pub(super) use crate::compiler::join::{
Arm, Exit, reconcile_arms, reconcile_arms_expecting, rides,
use crate::compiler::join::{NilRepr, literal_fits, nil_repr};
use crate::compiler::native::{chain_pair_element, compile_constant_list};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::block_exits::form_diverges;
const PROGN: &str = "progn";
/// Compiles one arm into `scratch`: a diverging arm emits its exit and yields
/// `None`; a literal / `nil` arm is deferred to [`finish_arm`]; any other arm
/// is compiled now as a [`Arm::Value`], expecting `expected`.
///
/// A diverging arm is sealed here, before the enclosing `else`/`end`: code
/// compiled past its `throw`/`br` (`(+ 1 (error …))`) leaves a concrete value
/// on the polymorphic stack, and only `unreachable` truncates it to the frame
/// floor — `block_end`'s seal after `end` comes too late. Under
/// UNWIND-PROTECT's conditional rethrow the frame even sees the arm live.
pub(super) fn compile_arm(
ctx: &mut CompileContext,
scratch: &mut FunctionEmitter,
symbols: &mut SymbolTable,
expr: &Expr,
expected: Option<WasmType>,
) -> Result<Option<Arm>> {
if form_diverges(&mut symbols.clone(), expr)? {
compile_for_stack(ctx, scratch, symbols, expr)?;
scratch.unreachable();
return Ok(None);
}
if let Some(arm) = deferred_arm(symbols, expr) {
return Ok(Some(arm));
Ok(Some(Arm::Value(compile_for_stack_expecting(
ctx, scratch, symbols, expr, expected,
)?)))
/// Compiles a BLOCK exit's or tail's value `expr` into its [`Exit`] and the
/// type it leaves on the stack. Its arm keeps a numeric literal or `nil`
/// distinct from a computed value. At a reconciled `target` a deferred arm is
/// emitted as it, and a computed value is compiled expecting it; at `AnyRef`
/// it is boxed, except an index, which [`lands_raw`] leaves to the join.
pub(super) fn compile_exit_value(
emit: &mut FunctionEmitter,
target: Option<WasmType>,
) -> Result<(Exit, WasmType)> {
let deferred =
deferred_arm(symbols, expr).filter(|arm| matches!(arm, Arm::NumberLiteral(_) | Arm::Nil));
match (deferred, target) {
(Some(arm @ Arm::NumberLiteral(_)), Some(WasmType::AnyRef)) => {
let raw = compile_for_stack(ctx, emit, symbols, expr)?;
Ok(land(ctx, emit, arm, raw, target))
(Some(arm), Some(result)) if finishes_at(arm, result) => {
finish_arm(ctx, emit, symbols, expr, arm, result)?;
Ok((
Exit {
arm,
emitted: result,
},
result,
))
(Some(arm), _) => {
let emitted = compile_for_stack(ctx, emit, symbols, expr)?;
Ok((Exit { arm, emitted }, emitted))
(None, _) => {
let ty = compile_for_stack_expecting(ctx, emit, symbols, expr, target)?;
Ok(land(ctx, emit, Arm::Value(ty), ty, target))
/// Whether an exit value of `stack` type, bound for `target`, is left raw for
/// the join to box where it lands: boxing an index can raise INDEX-OVERFLOW,
/// which no handler the exit crosses may catch (0011 F2/S12).
pub(super) fn lands_raw(stack: WasmType, target: Option<WasmType>) -> bool {
stack == WasmType::I32 && target == Some(WasmType::AnyRef)
/// The [`Exit`] of an emitted `raw` value bound for `target`, boxed now
/// unless it [`lands_raw`], and the type left on the stack.
fn land(
ctx: &CompileContext,
arm: Arm,
raw: WasmType,
) -> (Exit, WasmType) {
let emitted = match target {
Some(WasmType::AnyRef) => WasmType::AnyRef,
_ => raw,
if lands_raw(raw, target) {
return (Exit { arm, emitted }, raw);
box_arm_value(ctx, emit, raw, emitted);
(Exit { arm, emitted }, emitted)
/// Whether [`finish_arm`] emits the deferred `arm` as `result`: a literal
/// that fits it or is boxed into it, a `nil` that has a representation in it.
fn finishes_at(arm: Arm, result: WasmType) -> bool {
match arm {
Arm::NumberLiteral(lit) => literal_fits(result, lit) || result == WasmType::AnyRef,
Arm::Nil => nil_repr(&result) != NilRepr::Never,
Arm::Value(_) | Arm::ConstantList(_) => false,
/// Runs `f` inside a runtime-conditional branch, so a compile-time-only
/// definition or SETF reached from it is refused rather than applied
/// unconditionally.
pub(in crate::compiler) fn in_runtime_branch<T>(
f: impl FnOnce(&mut SymbolTable) -> Result<T>,
) -> Result<T> {
symbols.enter_runtime_branch()?;
let result = f(symbols);
let exited = symbols.exit_runtime_branch();
result.and_then(|value| exited.map(|()| value))
/// [`compile_arm`] for an arm that runs only when a runtime test selects it.
pub(super) fn compile_branch_arm(
in_runtime_branch(symbols, |symbols| {
compile_arm(ctx, scratch, symbols, expr, expected)
})
/// [`finish_arm`] for an arm that runs only when a runtime test selects it:
/// a deferred arm's effects compile here, so they need the same guard.
pub(super) fn finish_branch_arm(
result: WasmType,
) -> Result<()> {
finish_arm(ctx, scratch, symbols, expr, arm, result)
/// The deferred arm of a non-diverging `expr` that resolves to a numeric
/// literal or `nil`; `None` when the arm must be compiled up front. Probes on a
/// clone so no compile-time effect is applied.
fn deferred_arm(symbols: &SymbolTable, expr: &Expr) -> Option<Arm> {
if let Some(arm) = progn_value_arm(expr) {
return Some(arm);
match eval_value(&mut symbols.clone(), expr).ok()? {
Expr::Nil => Some(Arm::Nil),
// Only a fold-safe constant list is deferred: any other list-valued
// arm is compiled, so the effects it carries are emitted.
Expr::Datum(inner) if fold_safe(symbols, expr) => match *inner {
Expr::List(members) => chain_pair_element(&members).ok().map(Arm::ConstantList),
_ => None,
Expr::Datum(_) => None,
value => literal_arm(&value),
/// The arm of a PROGN whose value form is literally `nil` or a number: that
/// is its value whatever runtime effects precede it, though the evaluator
/// types such a body as runtime.
fn progn_value_arm(expr: &Expr) -> Option<Arm> {
match progn_value(expr)? {
value => literal_arm(value),
/// The form a PROGN nest takes its value from; `None` when `expr` is no PROGN.
fn progn_value(expr: &Expr) -> Option<&Expr> {
let mut value = None;
let mut form = expr;
while let Expr::List(elems) = form
&& let (Some(Expr::Symbol(head)), Some(last)) = (elems.first(), elems.last())
&& elems.len() > 1
&& head.eq_ignore_ascii_case(PROGN)
{
value = Some(last);
form = last;
value
/// The arm a non-diverging `expr` contributes on the ctx-less eval surface,
/// peeked on a clone inside a runtime branch — the mirror of
/// [`compile_branch_arm`]. A constant list lowers to
/// a pair chain typed by the LIST rule; an unclassifiable value is `I32`.
pub(super) fn eval_arm(symbols: &SymbolTable, expr: &Expr) -> Result<Option<Arm>> {
let mut probe = symbols.clone();
probe.enter_runtime_branch()?;
let mut pristine = probe.clone();
let exits = probe.measurements().exits();
let value = eval_value(&mut probe, expr);
let exited = probe.measurements().exits() != exits;
if (exited || value.is_err()) && form_diverges(&mut pristine, expr)? {
probe.measurements().note_exit();
Ok(Some(arm_of_form(expr, &value?)?))
/// The arm of a form whose resolved eval value is `value`.
pub(super) fn arm_of_form(expr: &Expr, value: &Expr) -> Result<Arm> {
match progn_value_arm(expr) {
Some(arm) => Ok(arm),
None => arm_of_value(value),
/// The arm a resolved eval value contributes; a value with no stack type is
/// a structured error.
fn arm_of_value(value: &Expr) -> Result<Arm> {
match value {
Expr::Nil => Ok(Arm::Nil),
Expr::Datum(inner) if let Expr::List(members) = inner.as_ref() => {
Ok(Arm::Value(WasmType::PairRef(chain_pair_element(members)?)))
_ => match (literal_arm(value), classify_stack_type(value)) {
(Some(arm), _) => Ok(arm),
(None, Some(ty)) => Ok(Arm::Value(ty)),
(None, None) => Err(Error::Compile(format!(
"no runtime value type for {}",
format_form(value)
))),
fn literal_arm(value: &Expr) -> Option<Arm> {
Expr::Number(_) => classify_stack_type(value).map(Arm::NumberLiteral),
/// Completes an arm into its `scratch` at the unified `result`: a compiled
/// value is boxed when the block is `AnyRef`, a deferred literal is compiled at
/// the result stratum, a deferred `nil` emits its effects then the typed nil.
pub(super) fn finish_arm(
let raw = finish_arm_raw(ctx, scratch, symbols, expr, arm, result)?;
box_arm_value(ctx, scratch, raw, result);
Ok(())
/// [`finish_arm`] short of the box, for a caller that boxes where the value
/// lands; returns the type left on the stack.
pub(super) fn finish_arm_raw(
) -> Result<WasmType> {
Arm::Value(ty) => Ok(ty),
Arm::NumberLiteral(lit) if literal_fits(result, lit) => {
match progn_value(expr) {
Some(value) => {
compile_for_effect(ctx, scratch, symbols, expr)?;
compile_for_stack_as(ctx, scratch, symbols, value, result)?;
None => compile_for_stack_as(ctx, scratch, symbols, expr, result)?,
Ok(result)
Arm::NumberLiteral(_) => compile_for_stack(ctx, scratch, symbols, expr),
Arm::Nil => {
if !matches!(expr, Expr::Nil) {
emit_nil_default(ctx, scratch, result)?;
Arm::ConstantList(own) => {
let elem = match result {
WasmType::PairRef(elem) => elem,
_ => own,
let members = constant_list_members(symbols, expr)?;
compile_constant_list(ctx, scratch, symbols, members, elem)
/// The members of a constant-list arm, which `deferred_arm` admitted only
/// when fold-safe.
fn constant_list_members(symbols: &mut SymbolTable, expr: &Expr) -> Result<Vec<Expr>> {
match fold_value(symbols, expr)? {
Some(Expr::Datum(inner)) => match *inner {
Expr::List(members) => Ok(members),
other => Err(not_a_constant_list(&other)),
Some(other) => Err(not_a_constant_list(&other)),
None => Err(not_a_constant_list(expr)),
fn not_a_constant_list(value: &Expr) -> Error {
Error::Compile(format!(
"constant-list arm resolved to {value:?}, not a list"
/// Retypes an already-emitted arm value of `ty` to the block `result`: an
/// i32-repr value boxes into an anyref block. A `PairRef` widening never
/// needs a rebuild — a bool car already rides the same ref.null/`$t`
/// representation as an anyref car (ADR-0033).
pub(super) fn box_arm_value(
ty: WasmType,
) {
if result == WasmType::AnyRef {
emit_box_anyref(ctx, scratch, ty);
/// Pushes `nil` typed as the block `result` — an alias for
/// [`emit_nil_default`], kept for `IF`'s missing-else call site.
pub(super) fn emit_typed_nil(
emit_nil_default(ctx, scratch, result)
#[cfg(test)]
#[path = "arms_tests.rs"]
mod tests;
#[path = "landing_tests.rs"]
mod landing_tests;