Lines
97.17 %
Functions
100 %
Branches
//! `CONS` constructor. Eval path constant-folds chains; compile path
//! pushes typed car/cdr onto the stack and calls `pair_new`.
//! `push_pair_car` boxes i32 values (indices range-checked by
//! `box_index`); `push_pair_cdr` emits `ref.null pair` for terminal `nil`,
//! materializes a constant list, or validates a typed `PairRef(elem)`
//! matches the declared element.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::datum::bounded;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_expr, compile_for_effect, compile_for_stack, compile_for_stack_as, emit_box_anyref,
emit_box_cell, eval_value, fold_value, is_untyped, no_list_cell_representation, probe_value,
quoted_datum, serialize_stack_to_output,
};
use crate::compiler::join::Arm;
use crate::error::{Error, Result};
use crate::runtime::{SymbolTable, Value};
use super::append::emit_nil_pair_operand;
use super::datum::{compile_folded_to_stack, is_datum_result};
use super::infer::{chain_pair_element, infer_pair_element, is_scalar_literal};
use super::spill::{compile_spilled_chain, lambda_runs_at_runtime};
pub(super) fn cons(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
check_arity(args)?;
let car = eval_value(symbols, &args[0])?;
let cdr = eval_value(symbols, &args[1])?;
let closure_car = lambda_runs_at_runtime(symbols, std::slice::from_ref(&car));
if car.is_wasm_runtime()
|| closure_car
|| cdr.is_wasm_runtime()
|| matches!(cdr.wasm_type(), Some(WasmType::PairRef(_)))
{
let elem = infer_pair_element(&car, &cdr)?;
return Ok(Expr::WasmRuntime(WasmType::PairRef(elem)));
}
bounded(
symbols,
match cdr {
Expr::Datum(inner) => match *inner {
Expr::List(mut elems) => {
elems.insert(0, car);
Expr::quoted_list(elems)
Expr::Nil => Expr::quoted_list(vec![car]),
other => Expr::quoted(Expr::cons(car, other)),
},
)
fn check_arity(args: &[Expr]) -> Result<()> {
if args.len() != 2 {
return Err(Error::Arity {
name: "CONS".to_string(),
expected: 2,
actual: args.len(),
});
Ok(())
pub(super) fn compile_cons(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
if let Some(folded) = fold_cons(symbols, args)? {
return compile_expr(ctx, emit, symbols, &folded);
let ty = compile_cons_to_stack(ctx, emit, symbols, args)?;
serialize_stack_to_output(ctx, emit, ty)
/// The datum a fold-safe `(cons …)` folds to, or `None` when the pair is
/// built at runtime.
fn fold_cons(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Option<Expr>> {
let form = Expr::List(
std::iter::once(Expr::symbol("CONS"))
.chain(args.iter().cloned())
.collect(),
);
Ok(fold_value(symbols, &form)?.filter(is_datum_result))
pub(super) fn compile_cons_to_stack(
) -> Result<WasmType> {
// A fully-constant cons folds to a quoted list datum (e.g. (cons 0 '(1 2 3))
// → '(0 1 2 3)); render it as a datum so value position agrees with the
// effect path instead of trapping when push_pair_cdr meets the quoted cdr.
// Only a runtime car/cdr (PairRef result) takes the pair_new path below.
return compile_folded_to_stack(ctx, emit, symbols, folded);
// If an argument transfers control before the pair is built (a
// `(return-from …)` / `(error …)` — args evaluate left-to-right before the
// call), the rest is dead: the pair is never constructed, so a non-list cdr
// must NOT be rejected. Emit the live prefix (which performs the exit) and
// return a placeholder element. Classify divergence on a CLONE (the exit is
// still recorded by the single emit below).
if crate::compiler::special::form_diverges_scratch(symbols, &args[0])? {
let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
return Ok(WasmType::PairRef(
PairElement::from_wasm_type(ty).unwrap_or(PairElement::AnyRef),
));
if crate::compiler::special::form_diverges_scratch(symbols, &args[1])? {
// Car is evaluated (for its effects) then the cdr exits before
// `pair_new`; the car value is dead, so compile it for effect.
compile_for_effect(ctx, emit, symbols, &args[0])?;
let ty = compile_for_stack(ctx, emit, symbols, &args[1])?;
// The element type is decided up front, on a clone, so the live table sees
// each operand's effects once, from its own compilation.
let mut probe = symbols.clone();
let car_resolved = probe_value(&mut probe, &args[0])?;
let cdr_resolved = probe_value(&mut probe, &args[1])?;
let elem = if is_untyped(&cdr_resolved) {
PairElement::AnyRef
} else {
infer_pair_element(&car_resolved, &cdr_resolved)?
push_pair_car(ctx, emit, symbols, &args[0], elem)?;
push_pair_cdr(ctx, emit, symbols, &args[1], elem, &cdr_resolved)?;
emit.call(ctx.ids.pair_new);
Ok(WasmType::PairRef(elem))
/// Emit `elem_args` as a nul-terminated `$pair` chain. LIST uses this so it
/// never synthesizes a `(CONS …)` form. `elem_args` are the
/// ORIGINAL element expressions (emitted once via `push_pair_car`); the
/// chain's element type is decided up front from their resolved values by
/// [`chain_pair_element`] — the same rule the eval `list` reports — so every
/// cell is emitted homogeneously.
pub(in crate::compiler) fn compile_pair_chain(
elem_args: &[Expr],
let resolved: Vec<Expr> = elem_args
.iter()
.map(|a| probe_value(&mut probe, a))
.collect::<Result<_>>()?;
if lambda_runs_at_runtime(symbols, &resolved) {
return compile_spilled_chain(ctx, emit, symbols, elem_args, &resolved);
let elem = chain_pair_element(&resolved)?;
emit_pair_chain(ctx, emit, symbols, elem_args, elem)?;
/// Materialize a constant list's `elements` (DATA, not expressions) as a
/// `$pair` chain whose cells ride `elem`, the element its consumer declared.
/// A member the cell push would otherwise RESOLVE (a bare symbol → variable
/// lookup, a nested list → a call) is quoted so it stays literal; one with no
/// runtime representation then surfaces "cannot compile to WASM stack value".
pub(super) fn emit_constant_chain(
elements: Vec<Expr>,
elem: PairElement,
let members: Vec<Expr> = elements
.into_iter()
.map(|e| match e {
Expr::Number(_)
| Expr::String(_)
| Expr::T
| Expr::Nil
| Expr::Instance(_, _)
| Expr::RuntimeValue(Value::Commodity { .. }) => e,
other => Expr::quoted(other),
})
.collect();
for member in &members {
push_constant_car(ctx, emit, symbols, member, elem)?;
close_pair_chain(ctx, emit, members.len());
/// Emit the `pair_new` cells for `elem_args` (original expressions), every car
/// at the unified `elem` slot. All cars are pushed in source order, then the
/// terminating `nil`, and each `pair_new` folds the top `[car, cdr_ref]` into
/// one cell — innermost first — without recursing per element.
fn emit_pair_chain(
for car in elem_args {
push_pair_car(ctx, emit, symbols, car, elem)?;
close_pair_chain(ctx, emit, elem_args.len());
/// Terminates the `count` pushed cars with `nil` and folds each `[car,
/// cdr_ref]` pair into a cell, innermost first.
pub(super) fn close_pair_chain(ctx: &CompileContext, emit: &mut FunctionEmitter, count: usize) {
emit.ref_null(ctx.ids.ty_pair);
for _ in 0..count {
pub(super) fn push_pair_car(
arg: &Expr,
let resolved = probe_value(&mut symbols.clone(), arg)?;
check_cell_representable(&resolved, elem)?;
match elem {
PairElement::AnyRef => push_anyref_car(ctx, emit, symbols, arg),
_ => push_typed_car(ctx, emit, symbols, arg, elem),
/// [`push_pair_car`] for a constant list member, which is its own probe.
fn push_constant_car(
member: &Expr,
check_cell_representable(member, elem)?;
PairElement::AnyRef => push_constant_arm(ctx, emit, symbols, member).map(drop),
_ => push_typed_car(ctx, emit, symbols, member, elem),
/// A nested constant list has a real materialization for an AnyRef cell
/// (ADR-0033 Phase 6: `push_anyref_car` builds it as a `$pair` chain), so it
/// alone is let through; every OTHER quoted datum (a symbol, a dotted cons, a
/// quasiquote) stays a compile error for every cell kind, AnyRef included —
/// it has no list-cell representation at all.
fn check_cell_representable(resolved: &Expr, elem: PairElement) -> Result<()> {
let is_nested_list_literal = matches!(
quoted_datum(resolved),
Some(Expr::List(elems)) if !elems.is_empty()
if crate::compiler::expr::is_quoted_datum(resolved)
&& !(elem == PairElement::AnyRef && is_nested_list_literal)
return Err(no_list_cell_representation(resolved));
fn push_typed_car(
// Value cells: a dimension-flexible integer literal coerces to the
// cell's stratum (Index or Scalar) rather than mismatching the slot.
PairElement::I32 | PairElement::Bool | PairElement::Ratio => {
compile_for_stack_as(ctx, emit, symbols, arg, elem.as_wasm_type())?;
emit_box_cell(ctx, emit, elem, elem);
// Reference cells (string / entity / commodity): keep the strict match
// so a `nil` or wrong-typed car stays a COMPILE error rather than a
// typed null that `CAR`'s non-null cast would trap on at runtime.
_ => {
let actual = compile_for_stack(ctx, emit, symbols, arg)?;
if PairElement::from_wasm_type(actual) != Some(elem) {
return Err(Error::Compile(format!(
"CONS car: expected {elem} to match the inferred pair element, got {actual}"
)));
/// A heterogeneous cell: `nil` rides as a null ref (never an i31 zero), a
/// scalar literal as a ratio (never a truncated index), a nested constant
/// list as a real `$pair` chain (ADR-0033 Phase 6 — it has no scalar/string
/// representation, so it must not fall through to the printed-datum path
/// `compile_for_stack` takes for a quoted list used as an ordinary value),
/// anything else as its own value boxed to anyref. The arm names what was
/// pushed, for a home that must read it back.
pub(in crate::compiler) fn push_anyref_arm(
) -> Result<Arm> {
push_resolved_arm(ctx, emit, symbols, arg, &resolved)
/// [`push_anyref_arm`] for a carried constant, which is its own probe: the
/// session prologue pushes one per instance field, so it must not clone the
/// symbol table.
pub(in crate::compiler) fn push_constant_arm(
value: &Expr,
push_resolved_arm(ctx, emit, symbols, value, value)
/// [`push_anyref_arm`] for an `arg` whose probe is `resolved`.
fn push_resolved_arm(
resolved: &Expr,
if matches!(resolved, Expr::Nil) {
if !matches!(arg, Expr::Nil) {
compile_for_effect(ctx, emit, symbols, arg)?;
emit.ref_null_any();
return Ok(Arm::Nil);
if is_scalar_literal(resolved) {
compile_for_stack_as(ctx, emit, symbols, arg, WasmType::Ratio)?;
return Ok(Arm::Value(WasmType::Ratio));
if let Some(Expr::List(members)) = quoted_datum(resolved)
&& !members.is_empty()
// `members` are DATA, not expressions: a nested `(+ 1 2)` here means
// "the list containing the symbol +, the number 1 and the number 2",
// never a call to evaluate. `emit_constant_chain` (used for the same
// shape in a CONS cdr) quotes every non-self-evaluating member before
// materializing it, so a nested list stays a nested list at every
// recursion level and a bare symbol renders as its printed name
// instead of resolving a lexical variable. And since `resolved` — not
// `arg` — is what carries this datum, `arg`'s own producer (if it has
// one; a literal quote has none) must still run for effect exactly
// once, matching `push_pair_cdr`'s rule for the identical shape.
if !matches!(arg, Expr::Quote(_) | Expr::Datum(_)) {
emit_constant_chain(ctx, emit, symbols, members.clone(), PairElement::AnyRef)?;
return Ok(Arm::Value(WasmType::PairRef(PairElement::AnyRef)));
emit_box_anyref(ctx, emit, actual);
Ok(Arm::Value(actual))
/// [`push_anyref_arm`] for a caller that only wants the value pushed.
pub(in crate::compiler) fn push_anyref_car(
push_anyref_arm(ctx, emit, symbols, arg).map(drop)
fn push_pair_cdr(
return Ok(());
if let Some(Expr::List(members)) = quoted_datum(resolved) {
return emit_constant_chain(ctx, emit, symbols, members.clone(), elem);
match actual {
// The widened-AnyRef case accepts any typed pair as the cdr —
// `$pair` already carries `anyref` cars (a bool car rides the same
// ref.null/`$t` representation in either cell kind, ADR-0033), so no
// per-element rebuild is needed once we've decided to ride the
// heterogeneous variant.
WasmType::PairRef(actual_elem) if actual_elem == elem || elem == PairElement::AnyRef => {
WasmType::PairRef(actual_elem) => Err(Error::Compile(format!(
"CONS cdr element type mismatch — expected pair<{elem}>, got pair<{actual_elem}>"
))),
WasmType::Bool => emit_nil_pair_operand(ctx, emit),
other => Err(Error::Compile(format!(
"CONS cdr must be a pair or nil, got {other}"