Lines
99.38 %
Functions
100 %
Branches
//! Cross-module tests for the iteration family. Span `do_loop` and
//! `common` because the form-result-type inference is exercised end-
//! to-end via `do_form` / `do_star_form`. Keeping the tests in a
//! sibling module instead of either sub-module avoids re-exporting
//! the private inference helpers just to test them.
use crate::ast::{Expr, Fraction, Number, PairElement, WasmType};
use crate::error::Result;
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
use super::common::body_yields_runtime;
use super::do_form::do_form;
use super::do_star_form::do_star_form;
use super::sizing::{infer_compiled_type, infer_wasm_type, var_type_hint};
/// Constructs `(do ((i 0 (+ i 1))) ((= i N) result) (setf result
/// (cons cons_car result)))` — the canonical tag-sync pattern.
/// `N` is a runtime symbol forcing the runtime path; `result` is a
/// pre-bound accumulator that the body builds via setf. The
/// caller varies `cons_car` to exercise the static PairElement
/// inference that the codegen path actually emits for the
/// accumulator.
fn do_with_setf_cons_car(cons_car: Expr) -> Vec<Expr> {
let i_var = Expr::List(vec![
Expr::Symbol("i".into()),
Expr::Number(Number::Index(0)),
Expr::List(vec![
Expr::Symbol("+".into()),
Expr::Number(Number::Index(1)),
]),
]);
let end_clause = Expr::List(vec![
Expr::Symbol("=".into()),
Expr::Symbol("N".into()),
Expr::Symbol("result".into()),
let body_setf = Expr::List(vec![
Expr::Symbol("SETF".into()),
Expr::Symbol("CONS".into()),
cons_car,
vec![Expr::List(vec![i_var]), end_clause, body_setf]
}
fn symbols_with_runtime_n_and_acc() -> SymbolTable {
let mut s = SymbolTable::with_builtins();
s.define(Symbol::new("N", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::I32)));
s.define(Symbol::new("result", SymbolKind::Variable).with_value(Expr::Nil));
s
/// Bug parity with `do_form`: the accumulator's CONS car is the loop var
/// `i`, an integer DO* var. After ADR-0028 an integer DO var is a runtime
/// Index (I32), so codegen emits a `pair<i32>` (i31-boxed car); `do_star_form`'s
/// static return type must match. Resolving `i` to its const `0` init would
/// type it as Ratio (the numeric-literal cell slot) and make a downstream
/// `dolist` / `car` consumer downcast the wrong way and trap at runtime.
#[test]
fn do_star_runtime_result_matches_index_cons_car() {
let mut symbols = symbols_with_runtime_n_and_acc();
let args = do_with_setf_cons_car(Expr::Symbol("i".into()));
let result = do_star_form(&mut symbols, &args).unwrap();
assert_eq!(
result,
Expr::WasmRuntime(WasmType::PairRef(PairElement::I32)),
"do* with body `(setf result (cons i result))` where i is an \
integer (Index) DO var must report PairRef(I32)"
);
/// Same harness, Bool car. A bool rides its own `PairElement::Bool` slot
/// (shares I32's i31-boxed car but serializes as Nil/Bool, not Number), so
/// the accumulator's static type is `PairRef(Bool)`.
fn do_star_runtime_result_matches_bool_cons_car() {
let args = do_with_setf_cons_car(Expr::T);
Expr::WasmRuntime(WasmType::PairRef(PairElement::Bool))
/// Same shape via plain `do` — locks in the `do_form` infer_env fix. The CONS
/// car is the integer DO var `i` (runtime Index → I32 cell), so the result is
/// `PairRef(I32)`, matching what the runtime codegen emits for `(cons i …)`.
fn do_runtime_result_matches_index_cons_car() {
let result = do_form(&mut symbols, &args).unwrap();
Expr::WasmRuntime(WasmType::PairRef(PairElement::I32))
/// A COUNTING `do` whose result form is a plain integer accumulator (not a
/// cons-built list) must report `I32`, not `PairRef`. Hard-coding `PairRef`
/// mistyped `(= (count …) 0)` as "= expects numeric, got pair". Mirrors codegen
/// `compile_do_runtime_for_stack` → `compile_for_stack(n)` (the let-promoted
/// integer local → I32).
fn do_counting_result_is_index_not_pair() {
let mut symbols = SymbolTable::with_builtins();
symbols.define(
Symbol::new("N", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::I32)),
symbols
.define(Symbol::new("n", SymbolKind::Variable).with_value(Expr::Number(Number::Index(0))));
Expr::Symbol("n".into()),
let body = Expr::List(vec![
let args = vec![Expr::List(vec![i_var]), end_clause, body];
assert_eq!(result, Expr::WasmRuntime(WasmType::I32));
/// `infer_wasm_type` drives the do-var local allocation type.
/// Each variant must report the wasm type the codegen path emits
/// for an init expression of that shape; a disagreement lands a
/// local of the wrong type and the wasm fails validation when
/// `local.set` checks the operand.
fn infer_wasm_type_integer_is_index_fraction_is_scalar() {
// ADR-0028: an integer literal defaults to Index (I32); a fractional
// literal is a dimensionless Scalar (Ratio). Mirrors `classify_stack_type`.
let s = SymbolTable::with_builtins();
infer_wasm_type(&Expr::Number(Number::Index(0)), None, &s),
Some(WasmType::I32)
infer_wasm_type(&Expr::Number(Number::Scalar(Fraction::new(1, 2))), None, &s),
Some(WasmType::Ratio)
fn infer_wasm_type_bool_is_bool() {
// Bool/nil literals lower to `WasmType::Bool` on the stack; a DO loop var
// sized here must match so a later read keeps Nil/Bool fidelity (not
// Number). A nil without a pair step-hint is the falsy `Bool`.
assert_eq!(infer_wasm_type(&Expr::T, None, &s), Some(WasmType::Bool));
assert_eq!(infer_wasm_type(&Expr::Nil, None, &s), Some(WasmType::Bool));
fn infer_wasm_type_string_is_stringref() {
infer_wasm_type(&Expr::String("hi".into()), None, &s),
Some(WasmType::StringRef),
fn infer_wasm_type_wasm_runtime_passes_through() {
infer_wasm_type(&Expr::WasmRuntime(WasmType::Commodity), None, &s),
Some(WasmType::Commodity),
fn infer_wasm_type_nil_with_pair_step_hint_uses_pair() {
s.define(
Symbol::new("acc", SymbolKind::Variable)
.with_value(Expr::WasmRuntime(WasmType::PairRef(PairElement::Ratio))),
// Step expr `(cons 1/2 acc)` — car is Number-fraction so the
// pair-element resolves to Ratio.
let step = Expr::List(vec![
Expr::Number(Number::Scalar(Fraction::new(1, 2))),
Expr::Symbol("acc".into()),
infer_wasm_type(&Expr::Nil, Some(&step), &s),
Some(WasmType::PairRef(PairElement::Ratio)),
fn infer_wasm_type_nil_with_runtime_branch_step_uses_the_branch_type() {
Symbol::new("FLAG", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::Bool)),
let step = parse_args("(if flag 7 8)").remove(0);
fn parse_args(source: &str) -> Vec<Expr> {
crate::reader::Reader::parse(source).expect("parses").exprs
fn symbols_with_x() -> SymbolTable {
.define(Symbol::new("X", SymbolKind::Variable).with_value(Expr::Number(Number::Index(1))));
fn macro_symbols() -> SymbolTable {
let mut symbols = symbols_with_x();
symbols.mark_macro_expansion();
fn x_value(symbols: &SymbolTable) -> Option<Expr> {
symbols.lookup("X").and_then(|s| s.value().cloned())
fn a_static_do_setting_an_outer_var_is_refused_in_a_macro_body() {
let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (setf x (+ x i))");
for form in [do_form, do_star_form] {
let mut symbols = macro_symbols();
let err = form(&mut symbols, &args).unwrap_err();
assert!(err.to_string().contains("may not mutate a global"), "{err}");
fn a_static_do_outside_a_macro_body_leaves_the_outer_var_alone() {
do_form(&mut symbols, &args).unwrap();
assert!(!matches!(x_value(&symbols), Some(Expr::WasmRuntime(_))));
do_star_form(&mut symbols, &args).unwrap();
fn a_static_do_with_an_effect_body_is_a_runtime_placeholder_in_a_macro_body() {
let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (print i)");
assert!(do_form(&mut symbols, &args).unwrap().is_wasm_runtime());
assert!(do_star_form(&mut symbols, &args).unwrap().is_wasm_runtime());
fn a_static_do_with_an_effect_body_is_nil_outside_a_macro_body() {
assert_eq!(do_form(&mut symbols, &args).unwrap(), Expr::Nil);
assert_eq!(do_star_form(&mut symbols, &args).unwrap(), Expr::Nil);
fn a_static_do_with_a_pure_body_still_folds() {
let args = parse_args("((i 0 (+ i 1))) ((= i 2) i) (+ i 0)");
assert!(!result.is_wasm_runtime(), "{result:?}");
fn a_const_dolist_with_an_effect_body_is_a_runtime_placeholder_in_a_macro_body() {
let args = parse_args("(i (quote (1 2))) (print i)");
let result = super::dolist::dolist_form(&mut symbols, &args).unwrap();
assert_eq!(result, Expr::WasmRuntime(WasmType::Bool));
fn a_const_dolist_with_an_effect_body_is_nil_outside_a_macro_body() {
assert_eq!(result, Expr::Nil);
fn body_yields_runtime_only_in_a_macro_body() {
let body = parse_args("(print 1)");
assert!(!body_yields_runtime(&mut symbols, &body).unwrap());
assert!(body_yields_runtime(&mut symbols, &body).unwrap());
fn parse_forms(source: &str) -> Vec<Expr> {
let Expr::List(elems) = crate::Reader::parse_expr(source).expect("parse") else {
panic!("not a list");
};
elems
fn a_do_var_is_sized_from_its_step_else_its_first_body_store() {
let body = parse_forms("(progn (setf acc (cons i acc)) (setf acc (cons 1/2 acc)))");
let step = crate::Reader::parse_expr("(cons 1/2 acc)").expect("parse");
assert_eq!(var_type_hint(Some(&step), &body[1..], "ACC"), Some(&step));
var_type_hint(None, &body[1..], "ACC"),
Some(&crate::Reader::parse_expr("(cons i acc)").expect("parse")),
let shadowed = parse_forms("(progn (let ((acc 1)) (setf acc (cons i acc))))");
assert_eq!(var_type_hint(None, &shadowed[1..], "ACC"), None);
fn a_runtime_do_result_form_reads_the_body_stored_accumulator() {
let form = parse_forms(
"(do ((i 0 (+ i 1)) (acc nil)) ((= i n) (length acc)) (setf acc (cons i acc)))",
do_form(&mut symbols, &form[1..]).expect("do"),
Expr::WasmRuntime(WasmType::I32)
fn compiled_type_of_step(source: &str) -> WasmType {
let step = crate::Reader::parse_expr(source).expect("parse");
let mut ctx = crate::compiler::context::CompileContext::new_with_host_fns(&[]).expect("ctx");
let emit = crate::compiler::emit::FunctionEmitter::new();
let mut symbols = SymbolTable::with_builtins_for_wasm();
infer_compiled_type(&mut ctx, &emit, &mut symbols, &Expr::Nil, Some(&step)).expect("sized")
fn a_compiled_step_sizes_a_nil_init_var_unless_it_never_falls_through() {
assert_eq!(compiled_type_of_step("(+ 1 2)"), WasmType::I32);
compiled_type_of_step("(list 1 2)"),
WasmType::PairRef(PairElement::I32)
compiled_type_of_step("(let ((k 1)) (error 'boom \"x\"))"),
WasmType::Bool
compiled_type_of_step("(block c (error 'boom \"x\"))"),
fn only_codegen_sizes_a_nil_init_var_whose_step_reaches_an_exit() {
let s = SymbolTable::with_builtins_for_wasm();
for source in [
"(block c (return-from b 9))",
"(let ((q 1)) (return-from b q))",
"(error 'boom \"x\")",
] {
None,
"{source}"
fn do_form_source(step: &str) -> String {
format!("(do ((i 0 (+ i 1)) (v nil {step})) ((= i (entity-count)) v))")
fn eval_and_compiled_types(source: &str) -> (Result<Expr>, WasmType) {
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{compile_for_stack, eval_value};
let form = crate::Reader::parse_expr(source).expect("parse");
let evaluated = eval_value(&mut SymbolTable::with_builtins_for_wasm(), &form);
let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
let mut emit = FunctionEmitter::new();
let compiled = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &form).expect("compiles");
(evaluated, compiled)
fn assert_eval_types_as_compiled(source: &str) {
let (evaluated, compiled) = eval_and_compiled_types(source);
evaluated.expect("evaluates").wasm_type(),
Some(compiled),
fn eval_value_types_a_nil_init_do_as_compile_for_stack_does() {
for step in ["(list i)", "\"s\"", "(cons i v)", "(> i 1)"] {
assert_eval_types_as_compiled(&do_form_source(step));
assert_eval_types_as_compiled(&do_form_source(step).replacen("(do ", "(do* ", 1));
fn eval_value_types_a_nested_nil_init_do_as_compile_for_stack_does() {
let inner = do_form_source("(list i)");
assert_eval_types_as_compiled(&format!(
"(do ((j 0 (+ j 1)) (w nil {inner})) ((= j (entity-count)) w))"
));
fn eval_value_types_a_block_wrapped_exit_step_do_as_compile_for_stack_does() {
let source = format!(
"(list (block b {}))",
do_form_source("(if (> i 5) (return-from b 1) \"s\")")
let (evaluated, compiled) = eval_and_compiled_types(&source);
assert_eq!(compiled, WasmType::PairRef(PairElement::AnyRef), "{source}");
if let Ok(value) = evaluated {
assert_eq!(value.wasm_type(), Some(compiled), "{source}");
fn eval_value_leaves_a_nil_init_do_whose_step_exits_to_compile_for_stack() {
let (evaluated, _) = eval_and_compiled_types(&format!(
"(block b {})",
do_form_source("(block c (return-from b 9))")
assert!(evaluated.is_err());