Lines
88.52 %
Functions
92.86 %
Branches
100 %
//! `REVERSE` — produce the input list in reversed order. Constant-folds
//! when the input is a compile-time list literal; for runtime
//! `PairRef(elem)` chains, walks the input cell-by-cell building a fresh
//! reversed chain via the `pair_new` helper.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_for_stack, eval_value, fold_call, format_expr, serialize_stack_to_output,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::car_cdr::{coerce_anyref_to_pair, reject_non_list};
use super::datum::{compile_folded_to_stack, emit_folded_output};
pub(super) fn reverse(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.len() != 1 {
return Err(Error::Arity {
name: "REVERSE".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(WasmType::PairRef(elem))),
Some(WasmType::AnyRef) => {
return Ok(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef)));
_ => {}
let elements = match arg {
Expr::Nil => return Ok(Expr::Nil),
Expr::List(elems) => elems,
Expr::Datum(inner) => match *inner {
other => {
return Err(Error::Compile(format!(
"REVERSE expects a list, got {}",
format_expr(&other)
)));
},
let reversed: Vec<Expr> = elements.into_iter().rev().collect();
Ok(Expr::quoted_list(reversed))
pub(super) fn compile_reverse(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
check_arity(args)?;
if let Some(folded) = fold_call(symbols, "REVERSE", args)? {
return emit_folded_output(ctx, emit, symbols, folded);
let ty = compile_reverse_runtime(ctx, emit, symbols, &args[0])?;
serialize_stack_to_output(ctx, emit, ty)
fn check_arity(args: &[Expr]) -> Result<()> {
if args.len() == 1 {
return Ok(());
Err(Error::Arity {
})
pub(super) fn compile_reverse_to_stack(
) -> Result<WasmType> {
return compile_folded_to_stack(ctx, emit, symbols, folded);
compile_reverse_runtime(ctx, emit, symbols, &args[0])
fn compile_reverse_runtime(
arg: &Expr,
let elem = match compile_for_stack(ctx, emit, symbols, arg)? {
WasmType::PairRef(e) => e,
WasmType::AnyRef => {
coerce_anyref_to_pair(ctx, emit)?;
PairElement::AnyRef
other => return reject_non_list(ctx, emit, symbols, "REVERSE", arg, other),
emit_reverse_from_stack(ctx, emit, elem)?;
Ok(WasmType::PairRef(elem))
/// Walks `list_expr` cell by cell, prepending each car onto a fresh
/// accumulator chain, and leaves the reversed chain on the wasm stack.
pub(in crate::compiler::native::list) fn emit_reverse_loop(
list_expr: &Expr,
elem: PairElement,
let arg_ty = compile_for_stack(ctx, emit, symbols, list_expr)?;
if matches!(arg_ty, WasmType::AnyRef) {
emit_reverse_from_stack(ctx, emit, elem)
/// Reverses the `$pair` chain on top of the stack. The accumulator starts
/// as a null `$pair` ref and is rebuilt every iteration via
/// `pair_new(car, acc)`.
fn emit_reverse_from_stack(
let pair_idx = ctx.ids.ty_pair;
let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
let acc_local = ctx.alloc_local(WasmType::PairRef(elem))?;
emit.local_set(pair_local);
emit.ref_null(pair_idx);
emit.local_set(acc_local);
emit.block_start();
emit.loop_start();
emit.local_get(pair_local);
emit.ref_is_null();
emit.br_if(1);
// pair_new expects (anyref car, ref null $pair cdr). The car comes
// straight off the input pair as anyref — no downcast needed since
// we're rebuilding into a fresh pair of the same element type.
emit.struct_get(pair_idx, 0);
emit.local_get(acc_local);
emit.call(ctx.ids.pair_new);
emit.struct_get(pair_idx, 1);
emit.br(0);
emit.block_end()?;
Ok(())