Lines
99.46 %
Functions
100 %
Branches
//! `APPEND` — concatenate lists left to right. Constant-folds when every
//! argument is a compile-time list; otherwise lowers the two-list runtime
//! case by reversing the prefix onto an accumulator seeded with the
//! suffix chain (so the suffix is shared, not copied).
use wasm_encoder::BlockType;
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_stack, describe_operand, eval_value, fold_call, fold_value,
format_expr, probe_value, serialize_stack_to_output,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::car_cdr::coerce_anyref_to_pair;
use super::datum::compile_folded_to_stack;
use super::infer::chain_pair_element;
use super::map::extract_list_elements;
pub(super) fn append(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.iter().any(|a| {
eval_value(symbols, a)
.map(|r| matches!(r.wasm_type(), Some(WasmType::PairRef(_) | WasmType::AnyRef)))
.unwrap_or(false)
}) {
return Ok(Expr::WasmRuntime(WasmType::PairRef(result_element(
symbols, args,
)?)));
}
let mut out = Vec::new();
for arg in args {
let resolved = eval_value(symbols, arg)?;
out.extend(extract_list_elements(&resolved).map_err(|_| {
Error::Compile(format!(
"APPEND expects lists, got {}",
format_expr(&resolved)
))
})?);
bounded(symbols, Expr::quoted_list(out))
/// The element type of a runtime APPEND result: [`chain_pair_element`] over
/// every constant list's members plus one placeholder per runtime `PairRef`
/// chain, so a constant list is typed exactly as LIST types its cells. An
/// empty constant list / nil doesn't constrain the result, and a non-list
/// operand contributes nothing: it throws at runtime.
fn result_element(symbols: &SymbolTable, args: &[Expr]) -> Result<PairElement> {
let mut members = Vec::new();
let mut probe = symbols.clone();
let resolved = probe_value(&mut probe, arg)?;
match resolved.wasm_type() {
Some(WasmType::PairRef(e)) => members.push(Expr::WasmRuntime(e.as_wasm_type())),
Some(WasmType::AnyRef) => members.push(Expr::WasmRuntime(WasmType::AnyRef)),
_ => members.extend(extract_list_elements(&resolved).unwrap_or_default()),
chain_pair_element(&members)
pub(super) fn compile_append(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
if let Some(folded) = fold_call(symbols, "APPEND", args)? {
return compile_expr(ctx, emit, symbols, &folded);
let ty = compile_append_runtime(ctx, emit, symbols, args)?;
serialize_stack_to_output(ctx, emit, ty)
pub(super) fn compile_append_to_stack(
) -> Result<WasmType> {
return compile_folded_to_stack(ctx, emit, symbols, folded);
compile_append_runtime(ctx, emit, symbols, args)
fn compile_append_runtime(
if args.len() != 2 {
// Runtime n-ary APPEND is ISS-082 (WONTFIX).
return Err(Error::Compile(
"APPEND with a runtime list argument requires exactly 2 lists".to_string(),
));
let elem = result_element(symbols, args)?;
let pair_idx = ctx.ids.ty_pair;
let prefix_local = ctx.alloc_local(WasmType::PairRef(elem))?;
let acc_local = ctx.alloc_local(WasmType::PairRef(elem))?;
// Both operands run, left to right, before either is checked as a list;
// the suffix is the shared tail, and the prefix is prepended onto it in
// reverse.
let first = evaluate_list_arg(ctx, emit, symbols, &args[0], elem)?;
let second = evaluate_list_arg(ctx, emit, symbols, &args[1], elem)?;
validate_list_arg(ctx, emit, first, prefix_local)?;
validate_list_arg(ctx, emit, second, acc_local)?;
let reversed_local = ctx.alloc_local(WasmType::PairRef(elem))?;
reverse_into(ctx, emit, pair_idx, prefix_local, reversed_local)?;
prepend_reversed(ctx, emit, pair_idx, reversed_local, acc_local)?;
emit.local_get(acc_local);
Ok(WasmType::PairRef(elem))
/// Walks the reversed prefix, prepending each car onto `acc_local`.
fn prepend_reversed(
pair_idx: u32,
reversed_local: u32,
acc_local: u32,
emit.block_start();
emit.loop_start();
emit.local_get(reversed_local);
emit.ref_is_null();
emit.br_if(1);
emit.struct_get(pair_idx, 0);
emit.call(ctx.ids.pair_new);
emit.local_set(acc_local);
emit.struct_get(pair_idx, 1);
emit.local_set(reversed_local);
emit.br(0);
emit.block_end()?;
emit.block_end()
/// An evaluated APPEND operand: its local and, unless it is already a `$pair`
/// chain of the result element, the list-like type it was compiled to.
struct ListOperand {
local: u32,
ty: Option<WasmType>,
/// Evaluates an APPEND argument into a local. A constant list is materialized
/// into a fresh `$pair` chain whose cells ride the result element `elem` (so a
/// concrete result label never covers mismatched cells); anything else is
/// compiled, so its effects run. Nothing is checked here.
fn evaluate_list_arg(
arg: &Expr,
elem: PairElement,
) -> Result<ListOperand> {
if let Some(elements) = fold_value(symbols, arg)?.and_then(|c| extract_list_elements(&c).ok()) {
super::cons::emit_constant_chain(ctx, emit, symbols, elements, elem)?;
let local = ctx.alloc_local(WasmType::PairRef(elem))?;
emit.local_set(local);
return Ok(ListOperand { local, ty: None });
let ty = compile_for_stack(ctx, emit, symbols, arg)?;
if !matches!(ty, WasmType::PairRef(_) | WasmType::AnyRef | WasmType::Bool) {
emit.drop_value();
let got = describe_operand(symbols, arg, ty);
emit.reject_if_live(Error::Compile(format!("APPEND expects a list, got {got}")))?;
let local = ctx.alloc_local(ty)?;
Ok(ListOperand {
local,
ty: Some(ty),
})
/// Stores an evaluated operand's `$pair` chain in `target`: a nil is the null
/// pair, and a runtime `AnyRef` or `Bool` that is no list throws `TYPE-ERROR`.
fn validate_list_arg(
operand: ListOperand,
target: u32,
emit.local_get(operand.local);
match operand.ty {
None | Some(WasmType::PairRef(_)) => {}
Some(WasmType::AnyRef) => coerce_anyref_to_pair(ctx, emit)?,
Some(WasmType::Bool) => emit_nil_pair_operand(ctx, emit)?,
_ => {}
emit.local_set(target);
Ok(())
/// A bool APPEND operand is the empty list when zero, a `TYPE-ERROR` otherwise.
pub(super) fn emit_nil_pair_operand(
let pair_ty = ctx.wasm_val_type(WasmType::PairRef(PairElement::AnyRef))?;
emit.if_block(BlockType::Result(pair_ty));
emit.call(ctx.ids.not_a_list);
emit.unreachable();
emit.else_block();
emit.ref_null(ctx.ids.ty_pair);
/// Reverses the chain in `src_local` into `dst_local` (a fresh null-seeded
/// accumulator), consuming `src_local`. Used so APPEND can prepend the
/// prefix onto the shared suffix in original order.
fn reverse_into(
src_local: u32,
dst_local: u32,
emit.ref_null(pair_idx);
emit.local_set(dst_local);
emit.local_get(src_local);
emit.local_get(dst_local);
emit.local_set(src_local);