Lines
91.02 %
Functions
100 %
Branches
//! `CAR` / `CDR` selectors. Eval path resolves through quote / cons /
//! list shapes; compile path goes through `struct.get $pair` plus the
//! shared `emit_pair_car_downcast` helper so the car comes back at
//! the type the static `PairRef(elem)` recorded.
use wasm_encoder::BlockType;
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_for_stack, describe_operand, eval_value, fold_call, format_expr, member_value,
serialize_stack_to_output,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::datum::{compile_folded_to_stack, emit_folded_output};
pub(super) fn car(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.len() != 1 {
return Err(Error::Arity {
name: "CAR".to_string(),
expected: 1,
actual: args.len(),
});
}
let arg = eval_value(symbols, &args[0])?;
match arg.wasm_type() {
Some(WasmType::PairRef(elem)) => return Ok(Expr::WasmRuntime(elem.as_wasm_type())),
// A `$pair` cast from an `AnyRef` list operand has an `AnyRef` car
// (ADR-0033: the dispatch throws a catchable `TYPE-ERROR` for
// anything that isn't null or a `$pair`, so the value here — once it
// compiles — is exactly a `PairRef(AnyRef)`'s element).
Some(WasmType::AnyRef) => return Ok(Expr::WasmRuntime(WasmType::AnyRef)),
_ => {}
match arg {
Expr::Nil => Ok(Expr::Nil),
Expr::List(elems) => {
if elems.is_empty() {
Ok(Expr::Nil)
} else {
Ok(member_value(elems[0].clone()))
Expr::Cons(car, _) => Ok(member_value(*car)),
Expr::Datum(inner) => match *inner {
other => Err(Error::Compile(format!(
"CAR expects a list, got {}",
format_expr(&other)
))),
},
pub(super) fn cdr(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
name: "CDR".to_string(),
Some(WasmType::PairRef(elem)) => return Ok(Expr::WasmRuntime(WasmType::PairRef(elem))),
// Same coercion as `car`'s eval mirror: a dispatched `AnyRef`
// operand becomes a `PairRef(AnyRef)` chain once it compiles.
Some(WasmType::AnyRef) => {
return Ok(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef)));
if elems.len() <= 1 {
Ok(Expr::quoted_list(elems[1..].to_vec()))
Expr::Cons(_, cdr) => Ok(*cdr),
let tail = elems[1..].to_vec();
Ok(Expr::quoted_list(tail))
"CDR expects a list, got {}",
pub(super) fn compile_car(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
check_arity("CAR", args)?;
if let Some(folded) = fold_call(symbols, "CAR", args)? {
return emit_folded_output(ctx, emit, symbols, folded);
let ty = compile_car_runtime(ctx, emit, symbols, &args[0])?;
serialize_stack_to_output(ctx, emit, ty)
pub(super) fn compile_cdr(
check_arity("CDR", args)?;
if let Some(folded) = fold_call(symbols, "CDR", args)? {
let ty = compile_cdr_runtime(ctx, emit, symbols, &args[0])?;
pub(super) fn compile_car_to_stack(
) -> Result<WasmType> {
return compile_folded_to_stack(ctx, emit, symbols, folded);
compile_car_runtime(ctx, emit, symbols, &args[0])
fn compile_car_runtime(
arg: &Expr,
let arg_ty = compile_for_stack(ctx, emit, symbols, arg)?;
let elem = match arg_ty {
WasmType::PairRef(e) => e,
WasmType::AnyRef => {
coerce_anyref_to_pair(ctx, emit)?;
PairElement::AnyRef
other => return reject_non_list(ctx, emit, symbols, "CAR", arg, other),
let pair_ty = WasmType::PairRef(elem);
let pair_local = ctx.alloc_local(pair_ty)?;
let car_ty = elem.as_wasm_type();
emit.local_tee(pair_local);
emit.ref_is_null();
emit.if_block(BlockType::Result(ctx.wasm_val_type(car_ty)?));
emit_nil_car(ctx, emit, elem);
emit.else_block();
emit.local_get(pair_local);
emit.struct_get(ctx.ids.ty_pair, 0);
emit_pair_car_downcast(ctx, emit, elem)?;
emit.block_end()?;
Ok(car_ty)
fn check_arity(name: &str, args: &[Expr]) -> Result<()> {
if args.len() == 1 {
return Ok(());
Err(Error::Arity {
name: name.to_string(),
})
/// Consumes a compiled list operand that is not a `$pair` chain. Only a `Bool`
/// can be nil, so it is nil when zero and a catchable `TYPE-ERROR` otherwise;
/// any other static type is no list.
pub(in crate::compiler) fn throw_unless_nil(
ctx: &CompileContext,
symbols: &SymbolTable,
name: &str,
operand: &Expr,
ty: WasmType,
if ty != WasmType::Bool {
let got = describe_operand(symbols, operand, ty);
return emit.reject_if_live(Error::Compile(format!("{name} expects a list, got {got}")));
emit.if_block(BlockType::Empty);
emit.call(ctx.ids.not_a_list);
emit.unreachable();
emit.block_end()
/// [`throw_unless_nil`] for a value-returning selector: the nil it leaves is a
/// zero bool.
pub(in crate::compiler) fn reject_non_list(
throw_unless_nil(ctx, emit, symbols, name, operand, ty)?;
emit.i32_const(0);
Ok(WasmType::Bool)
/// The car of a null pair (`(car nil)`), typed for its element: `nil` is a bool
/// zero or a null reference. An index, scalar, money or closure value is never
/// nil, so such a list throws a catchable `TYPE-ERROR` rather than trapping.
fn emit_nil_car(ctx: &CompileContext, emit: &mut FunctionEmitter, elem: PairElement) {
match elem {
PairElement::I32
| PairElement::Ratio
| PairElement::Commodity
| PairElement::Closure(_) => {
emit.call(ctx.ids.car_of_nil);
PairElement::Bool => emit.i32_const(0),
PairElement::AnyRef => emit.ref_null_any(),
PairElement::StringRef => emit.ref_null(ctx.ids.ty_i8_array),
PairElement::Symbol => emit.ref_null(ctx.ids.ty_symbol),
PairElement::Entity(kind) => emit.ref_null(ctx.ids.entity_type(kind)),
PairElement::Struct(_) => emit.ref_null(ctx.ids.ty_struct),
/// Runtime-dispatches an `AnyRef` list operand per ADR-0033: pops it and
/// pushes an equivalent `(ref null $pair)` — every `$pair` cell physically
/// rides the SAME struct regardless of its static element, so once coerced,
/// a caller treats the result exactly like an already-`PairRef(AnyRef)`
/// value (its car is `AnyRef`, the standard `PairElement::AnyRef` downcast
/// no-op). `ref.test` against a NULLABLE `$pair` accepts null too, so this
/// is one test: a `$pair` or nil pass through cast; anything else throws the
/// catchable `TYPE-ERROR` ("not a list") — never an uncatchable trap.
pub(in crate::compiler) fn coerce_anyref_to_pair(
let local = ctx.alloc_local(WasmType::AnyRef)?;
emit.local_set(local);
emit.local_get(local);
emit.ref_test(ctx.ids.ty_pair);
let pair_ty = ctx.wasm_val_type(WasmType::PairRef(PairElement::AnyRef))?;
emit.if_block(BlockType::Result(pair_ty));
emit.ref_cast_nullable(ctx.ids.ty_pair);
Ok(())
/// Downcasts an `anyref` (just popped from `$pair.car`) to the
/// element-specific wasm type recorded in the `PairRef(elem)` static
/// info. Single source of truth for the i31/struct/ref.null downcast pattern —
/// reused by CAR, DOLIST's body, and the eval-mode pair capture.
pub(in crate::compiler) fn emit_pair_car_downcast(
elem: PairElement,
PairElement::I32 => {
emit.ref_cast_i31();
emit.i31_get_s();
// A bool car is `ref.null` (nil) / the `$t` singleton (t), never an
// i31 (ADR-0033) — unboxing is "is it non-null?".
PairElement::Bool => {
emit.i32_eqz();
PairElement::Ratio => emit.ref_cast(ctx.ids.ty_ratio),
PairElement::Commodity => emit.ref_cast(ctx.ids.ty_commodity),
// `StringRef` / `EntityRef` cells CAN legitimately hold nil (ADR-0033
// Phase 5): a nullable cast keeps it nil rather than trapping the
// engine on `ref.cast`. The `TYPE-ERROR` null check runs later, only
// when a consumer actually dereferences the value.
PairElement::StringRef => emit.ref_cast_nullable(ctx.ids.ty_i8_array),
PairElement::Symbol => emit.ref_cast_nullable(ctx.ids.ty_symbol),
PairElement::Entity(kind) => emit.ref_cast_nullable(ctx.ids.entity_type(kind)),
PairElement::Struct(_) => emit.ref_cast_nullable(ctx.ids.ty_struct),
PairElement::Closure(sig) => {
emit.ref_cast_nullable(ctx.closure_sig(sig)?.closure_type_idx);
PairElement::AnyRef => {}
pub(super) fn compile_cdr_to_stack(
compile_cdr_runtime(ctx, emit, symbols, &args[0])
fn compile_cdr_runtime(
let pair_ty = match arg_ty {
WasmType::PairRef(_) => arg_ty,
WasmType::PairRef(PairElement::AnyRef)
other => return reject_non_list(ctx, emit, symbols, "CDR", arg, other),
// `(cdr nil)` is nil: a null pair stays null rather than trapping.
emit.if_block(BlockType::Result(ctx.wasm_val_type(pair_ty)?));
emit.ref_null(ctx.ids.ty_pair);
emit.struct_get(ctx.ids.ty_pair, 1);
Ok(pair_ty)