Lines
99.25 %
Functions
91.3 %
Branches
100 %
//! Tests for `classify_stack_type` / `nil_repr` (moved out of `stack.rs`
//! per CLAUDE.md's file-size guideline).
use super::*;
use crate::ast::{ClosureSigId, EntityKind, Fraction, PairElement};
use crate::compiler::CompileMode;
use crate::compiler::context::CompileContext;
use crate::runtime::SymbolTable;
/// The contract `classify_stack_type` exists to uphold: for every literal /
/// already-resolved runtime `Expr` it classifies (returns `Some`), the
/// prediction equals the `WasmType` `compile_for_stack` actually pushes.
/// Any drift here is the class of bug (#56/#57/#58/#59) that motivated the
/// single source of truth, so this test compiles each shape for real and
/// compares. (`None`-classified shapes — symbols, calls — are not value
/// literals and aren't asserted here.)
#[test]
fn classify_stack_type_matches_compile_for_stack() {
let quote = |inner: Expr| Expr::Quote(Box::new(inner));
let datum = |inner: Expr| Expr::Datum(Box::new(inner));
let sym = |name: &str| Expr::Symbol(name.to_string());
let runtime = [
WasmType::I32,
WasmType::Bool,
WasmType::Ratio,
WasmType::Commodity,
WasmType::StringRef,
WasmType::SymbolRef,
WasmType::PairRef(PairElement::Bool),
WasmType::EntityRef(EntityKind::Account),
WasmType::Closure(ClosureSigId(0)),
WasmType::AnyRef,
];
let quote_form = |datum: Expr| Expr::List(vec![sym("QUOTE"), datum]);
let mut cases: Vec<Expr> = vec![
quote_form(sym("A")),
quote_form(Expr::Number(Number::Index(3))),
quote_form(Expr::String("s".to_string())),
quote_form(Expr::Keyword("K".to_string())),
quote_form(Expr::List(vec![
Expr::Number(Number::Index(1)),
Expr::Number(Number::Index(2)),
])),
quote_form(Expr::Nil),
quote_form(Expr::List(vec![])),
quote_form(Expr::T),
Expr::Number(Number::Index(7)),
Expr::Number(Number::Scalar(Fraction::new(1, 2))),
Expr::Number(Number::Scalar(Fraction::from_integer(2))),
Expr::RuntimeValue(Value::Commodity {
amount: Fraction::new(7, 2),
commodity_id: uuid::Uuid::from_u128(5),
}),
Expr::T,
Expr::Nil,
Expr::String("hi".to_string()),
Expr::List(vec![]),
Expr::Keyword("K".to_string()),
let data = [
Expr::Number(Number::Index(3)),
Expr::String("s".to_string()),
sym("A"),
Expr::List(vec![sym("A"), Expr::Keyword("K".to_string())]),
Expr::List(vec![sym("A"), Expr::String("s".to_string())]),
Expr::Quasiquote(Box::new(Expr::List(vec![sym("A")]))),
Expr::List(vec![
]),
Expr::List(vec![Expr::Number(Number::Index(2))]),
for inner in data {
cases.push(quote(inner.clone()));
cases.push(datum(inner));
}
cases.push(quote(Expr::List(vec![sym("QUOTE"), sym("A")])));
cases.push(Expr::quoted(Expr::quoted_code(sym("A"))));
// A `WasmLocal` of every wasm type — `compile_for_stack` emits
// `local.get` and returns the local's declared type unchanged.
cases.extend(runtime.iter().map(|ty| Expr::WasmLocal(0, *ty)));
cases.extend(["index", "scalar", "money", "string"].map(|target| {
sym("THE"),
sym(target),
Expr::WasmLocal(0, WasmType::AnyRef),
])
}));
for expr in &cases {
let predicted = classify_stack_type(expr)
.unwrap_or_else(|| panic!("classify_stack_type returned None for {expr:?}"));
let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
let mut emit = FunctionEmitter::new();
let mut symbols = SymbolTable::with_builtins_for_wasm();
let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, expr)
.unwrap_or_else(|e| panic!("compile_for_stack {expr:?}: {e}"));
assert_eq!(
predicted, emitted,
"classify_stack_type disagrees with compile_for_stack for {expr:?}"
);
/// A quoted list is the `$pair` chain of its members, a symbol member riding
/// the symbol cell; a dotted pair has no stack value at all.
fn a_quoted_list_datum_is_a_pair_chain_or_the_structured_rejection() {
let quote = |inner: Expr| Expr::Datum(Box::new(inner));
let one = Expr::Number(Number::Index(1));
let symbols_list = quote(Expr::List(vec![sym("A"), sym("B")]));
let dotted = quote(Expr::cons(one.clone(), sym("B")));
classify_stack_type(&symbols_list),
Some(WasmType::PairRef(PairElement::Symbol))
assert_eq!(classify_stack_type(&dotted), None);
let compile = |datum: &Expr| {
compile_for_stack(&mut ctx, &mut emit, &mut symbols, datum)
};
compile(&symbols_list).expect("a symbol list is a chain"),
WasmType::PairRef(PairElement::Symbol)
compile(&dotted)
.expect_err("a dotted pair is rejected")
.to_string(),
"Compile error: cannot compile to WASM stack value: '(1 . B) has no list cell representation"
/// Shapes that aren't a directly-emittable literal/runtime value (they need
/// a call/list walk or aren't stack values) classify as `None`.
fn classify_stack_type_is_none_for_non_literal_shapes() {
assert_eq!(classify_stack_type(&Expr::Symbol("X".to_string())), None);
// A namespaced symbol (ADR-0029) is still just a Symbol — its canonical
// `NS:NAME` key must not be mistaken for any typed literal shape.
classify_stack_type(&Expr::Symbol("FOO:BAR".to_string())),
None
classify_stack_type(&Expr::WasmRuntime(WasmType::Ratio)),
Some(WasmType::Ratio)
/// `nil_repr` is exhaustive over every `WasmType` variant (a unit test rather
/// than relying on the `match`'s own exhaustiveness check alone, so a future
/// reviewer sees the enumerated contract in one place) and its Never/Null
/// split matches [`emit_nil_default`]'s success/failure split — the "pinned
/// against codegen" requirement from ADR-0033.
fn nil_repr_covers_every_wasm_type_and_matches_emit_nil_default() {
use super::super::atoms::emit_nil_default;
use crate::compiler::emit::FunctionEmitter;
let ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
let sig = {
ctx.intern_closure_signature(&[], WasmType::Ratio)
.expect("closure sig")
let every_variant = [
WasmType::PairRef(PairElement::I32),
WasmType::StructRef(crate::ast::StructId(0)),
WasmType::Closure(sig),
for ty in every_variant {
let repr = nil_repr(&ty);
let outcome = emit_nil_default(&ctx, &mut emit, ty);
match repr {
NilRepr::Never => assert!(
outcome.is_err(),
"{ty} classifies as Never but emit_nil_default succeeded"
),
NilRepr::I32Zero | NilRepr::Null => assert!(
outcome.is_ok(),
"{ty} classifies as {repr:?} but emit_nil_default failed: {:?}",
outcome.err()
/// The classifier and codegen agree on the folded form, not only on a type:
/// a quoted constant is the constant itself.
fn a_quoted_constant_classifies_as_the_folded_constant() {
for (datum, folded) in [
(Expr::Nil, Expr::Nil),
(Expr::List(vec![]), Expr::Nil),
(Expr::T, Expr::T),
] {
assert_eq!(Expr::quoted(datum.clone()), folded);
let form = Expr::List(vec![sym("QUOTE"), datum]);
assert_eq!(classify_stack_type(&form), classify_stack_type(&folded));
assert_eq!(Expr::quoted(sym("A")), Expr::Datum(Box::new(sym("A"))));
fn a_symbol_is_a_string_designator_and_nothing_else_is_changed() {
string_designator(&mut ctx, &mut emit, WasmType::SymbolRef).expect("symbol"),
WasmType::StringRef
for ty in [WasmType::StringRef, WasmType::I32, WasmType::AnyRef] {
string_designator(&mut ctx, &mut emit, ty).expect("other"),
ty
let quoted = Expr::Datum(Box::new(Expr::Symbol("A".to_string())));
compile_for_stack_as(
&mut ctx,
&mut emit,
&mut symbols,
"ed,
)
.expect("a symbol where a string is expected");
fn member_value_quotes_only_a_bare_symbol() {
let sym = Expr::Symbol("A".to_string());
crate::compiler::expr::member_value(sym.clone()),
Expr::Datum(Box::new(sym))
assert_eq!(crate::compiler::expr::member_value(one.clone()), one);
fn member_value_quotes_every_non_self_evaluating_member() {
let list = Expr::List(vec![one.clone()]);
let cons = Expr::cons(one.clone(), one.clone());
for member in [list, cons] {
crate::compiler::expr::member_value(member.clone()),
Expr::Datum(Box::new(member))
let datum = Expr::Datum(Box::new(Expr::Symbol("A".to_string())));
assert_eq!(crate::compiler::expr::member_value(datum.clone()), datum);
/// A session instance classifies as its struct type and compiles to a read of
/// the global its prologue allocated.
fn classify_stack_type_matches_compile_for_stack_for_a_session_instance() {
use crate::runtime::{Found, StructInstance};
let id = symbols
.define_struct("PT", vec!["X".to_string()])
.expect("defines");
let instance = StructInstance {
layout: id,
fields: vec![Expr::Nil],
symbols.define(
crate::runtime::Symbol::new("P", crate::runtime::SymbolKind::Variable)
.with_value(Expr::Instance(0, id)),
symbols.settle_instances(Found::from([(0, Some(instance))]), 1);
let scan =
crate::compiler::expr::prepare_unit(&mut symbols, &[], CompileMode::Script).expect("scans");
crate::compiler::special::allocate_instances(&mut ctx, &mut emit, &mut symbols, &scan)
.expect("prologue");
let leaf = Expr::Instance(0, id);
let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &leaf).expect("compiles");
assert_eq!(classify_stack_type(&leaf), Some(WasmType::StructRef(id)));
assert_eq!(emitted, WasmType::StructRef(id));
/// `(f 4)` with a closure in the value cell and a function in the function
/// cell calls the function, and the call's stack type is the function's.
fn a_call_of_a_name_with_both_cells_pushes_the_function_type() {
use crate::runtime::{Head, Symbol, SymbolKind};
let sig = ctx
.intern_closure_signature(&[], WasmType::Ratio)
.expect("sig");
let body = Expr::Number(Number::Index(100));
Symbol::new("F", SymbolKind::Variable)
.with_function(Expr::Lambda(
crate::ast::LambdaParams::simple(vec!["X".to_string()]),
Box::new(body.clone()),
))
.with_value(Expr::WasmLocal(0, WasmType::Closure(sig))),
assert!(matches!(symbols.resolve_head("F"), Head::Function(..)));
let call = crate::reader::Reader::parse_expr("(f 4)").expect("parses");
let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &call).expect("compiles");
assert_eq!(classify_stack_type(&body), Some(emitted));
/// `(f 4)` with only a closure in the value cell has no head: it classifies as
/// nothing and `compile_for_stack` refuses it, never calling the closure.
fn a_call_of_a_name_with_only_a_closure_value_is_refused() {
assert!(matches!(symbols.resolve_head("F"), Head::Unknown));
let err = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &call).expect_err("refused");
err.to_string(),
"Compile error: undefined function F; use (funcall f …)"
assert_eq!(classify_stack_type(&call), None);