Lines
99.3 %
Functions
100 %
Branches
use super::*;
use crate::ast::{ClosureSigId, Number};
use crate::reader::Reader;
use crate::runtime::{Fraction, Symbol, SymbolKind};
fn sym(s: &str) -> Expr {
Expr::Symbol(s.to_string())
}
fn list(items: Vec<Expr>) -> Expr {
Expr::List(items)
fn num(n: i64) -> Expr {
Expr::Number(Number::Index(n))
fn pinned(body: &Expr, name: &str) -> Option<WasmType> {
pinned_in(body, name, &SymbolTable::new())
fn pinned_in(body: &Expr, name: &str, symbols: &SymbolTable) -> Option<WasmType> {
pinned_param_type(body, name, &Scope::new(symbols, &[]))
fn with_local(name: &str, ty: WasmType) -> SymbolTable {
let mut symbols = SymbolTable::with_builtins();
symbols.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(0, ty)));
symbols
fn pair(elem: PairElement) -> Option<WasmType> {
Some(WasmType::PairRef(elem))
#[test]
fn cons_cdr_literal_car_is_that_cell() {
let body = list(vec![sym("CONS"), num(1), sym("acc")]);
assert_eq!(pinned(&body, "acc"), pair(PairElement::I32));
fn cons_cdr_nonliteral_car_widens_to_anyref() {
let body = list(vec![sym("CONS"), sym("x"), sym("acc")]);
assert_eq!(pinned(&body, "acc"), pair(PairElement::AnyRef));
assert_eq!(pinned(&body, "x"), None);
fn no_cons_cdr_use_is_unconstrained() {
let body = list(vec![sym("*"), sym("x"), list(vec![sym("foo")])]);
fn string_native_arg_pins_stringref() {
// (string= s "x") → s is a string.
let body = list(vec![sym("STRING="), sym("s"), Expr::String("x".into())]);
assert_eq!(pinned(&body, "s"), Some(WasmType::StringRef));
fn quoted_string_native_does_not_pin() {
// (quote (string= x "a")) — quoted data must NOT pin `x` to StringRef.
let body = list(vec![
sym("quote"),
list(vec![sym("string="), sym("x"), Expr::String("a".into())]),
]);
fn quasiquoted_string_native_does_not_pin() {
sym("quasiquote"),
fn shadowing_let_body_does_not_retype_outer_param() {
// (let ((x nil)) (cons 1 x)) — cdr is the INNER `x`; outer stays None.
let inner = list(vec![
sym("LET"),
list(vec![list(vec![sym("x"), Expr::Nil])]),
list(vec![sym("CONS"), num(1), sym("x")]),
assert_eq!(pinned(&inner, "x"), None);
fn let_initializer_cons_cdr_is_still_outer_scope() {
// (let ((acc (cons 1 acc))) acc) — the init `(cons 1 acc)` references the
// OUTER `acc` (the binding isn't in scope for its own init), so `acc` IS
// a list accumulator. Scanning must reach the init even though the let
// rebinds `acc`.
let form = list(vec![
list(vec![list(vec![
sym("acc"),
list(vec![sym("CONS"), num(1), sym("acc")]),
])]),
assert_eq!(pinned(&form, "acc"), pair(PairElement::I32));
fn dolist_list_expr_cons_cdr_is_outer_scope() {
// (dolist (e (cons 1 acc)) e) — the list expr references outer `acc`.
sym("DOLIST"),
list(vec![sym("e"), list(vec![sym("CONS"), num(1), sym("acc")])]),
sym("e"),
fn lambda_binder_shadows_outer_param() {
list(vec![
sym("LAMBDA"),
list(vec![sym("x")]),
]),
sym("y"),
fn short_binder_body_does_not_panic_on_slice() {
// Regression (AFL): a too-short binder form — `(do)`, `(let)`,
// `(lambda)` — used to index `&elems[2..]` / `&elems[1..]` out of range
// and panic. Param inference is best-effort, so a malformed form must
// contribute no pin (return None), never crash.
for head in ["DO", "DO*", "LET", "LET*", "DOLIST", "LAMBDA"] {
let bare = list(vec![sym(head)]);
assert_eq!(pinned(&bare, "x"), None, "bare ({head})");
// Nested under a lambda body, mirroring the fuzz-found shape
// `(lambda (s) (do))`.
let nested = list(vec![sym("DO")]);
assert_eq!(pinned(&nested, "s"), None);
fn literal_car_cells_map_to_their_slots() {
assert_eq!(car_cell_element(&num(3)), PairElement::I32);
assert_eq!(car_cell_element(&Expr::Nil), PairElement::Bool);
assert_eq!(car_cell_element(&Expr::T), PairElement::Bool);
assert_eq!(
car_cell_element(&Expr::String("s".into())),
PairElement::StringRef
);
assert_eq!(car_cell_element(&sym("v")), PairElement::AnyRef);
car_cell_element(&Expr::Quote(Box::new(sym("v")))),
PairElement::Symbol
car_cell_element(&Expr::Keyword("K".into())),
fn a_typed_variable_beside_the_param_pins_its_dimension() {
let body = list(vec![sym("+"), sym("acc"), sym("k")]);
for ty in [WasmType::I32, WasmType::Ratio, WasmType::Commodity] {
assert_eq!(pinned_in(&body, "k", &with_local("acc", ty)), Some(ty));
fn each_operator_pins_the_dimensions_it_shares() {
let additive = ["+", "-", "<", ">", "<=", ">=", "=", "/="];
let multiplicative = ["*", "/", "mod"];
for (op, ty) in additive
.iter()
.flat_map(|op| [WasmType::I32, WasmType::Ratio, WasmType::Commodity].map(|ty| (op, ty)))
{
let body = list(vec![sym(op), sym("m"), sym("k")]);
pinned_in(&body, "k", &with_local("m", ty)),
Some(ty),
"{op}"
for op in multiplicative {
for ty in [WasmType::I32, WasmType::Ratio] {
let money = list(vec![sym(op), sym("m"), sym("k")]);
pinned_in(&money, "k", &with_local("m", WasmType::Commodity)),
None,
fn a_comparison_pins_like_arithmetic() {
let body = list(vec![sym("<"), sym("k"), sym("n")]);
pinned_in(&body, "k", &with_local("n", WasmType::I32)),
Some(WasmType::I32)
fn a_literal_neighbour_pins_its_kind() {
let body = list(vec![sym("+"), sym("k"), num(2)]);
assert_eq!(pinned(&body, "k"), Some(WasmType::I32));
fn a_non_numeric_or_unknown_neighbour_never_pins() {
pinned_in(&body, "k", &with_local("acc", WasmType::StringRef)),
None
assert_eq!(pinned_in(&body, "k", &SymbolTable::new()), None);
fn a_param_not_beside_the_variable_is_not_pinned() {
sym("+"),
list(vec![sym("*"), sym("k"), list(vec![sym("foo")])]),
pinned_in(&body, "k", &with_local("acc", WasmType::I32)),
fn an_inner_binder_hides_the_neighbour() {
let bindings = list(vec![list(vec![sym("acc"), Expr::String("s".into())])]);
let inner = list(vec![sym("+"), sym("acc"), sym("k")]);
let body = list(vec![sym("let"), bindings, inner]);
fn a_lambda_param_hides_the_neighbour() {
let body = list(vec![sym("lambda"), list(vec![sym("acc")]), inner]);
fn infer_param_types_hides_the_lambdas_own_params() {
let symbols = with_local("acc", WasmType::I32);
let own = LambdaParams::simple(vec!["acc".to_string(), "k".to_string()]);
infer_params(&symbols, &own, &body).types,
vec![Some(WasmType::I32); 2]
let captured = LambdaParams::simple(vec!["k".to_string()]);
infer_params(&symbols, &captured, &body).types,
vec![Some(WasmType::I32)]
fn infer_param_types_pins_a_param_beside_a_literal_to_its_kind() {
let symbols = SymbolTable::new();
let params = LambdaParams::simple(vec!["x".to_string()]);
let index = list(vec![sym("+"), sym("x"), num(1)]);
infer_params(&symbols, ¶ms, &index).types,
let half = Expr::Number(Number::Scalar(Fraction::new(1, 2)));
let scalar = list(vec![sym("*"), sym("x"), half]);
infer_params(&symbols, ¶ms, &scalar).types,
vec![Some(WasmType::Ratio)]
fn infer_param_types_leaves_a_param_never_used_numerically_unpinned() {
infer_params(&SymbolTable::new(), ¶ms, &sym("x")).types,
vec![None]
fn infer_param_types_pins_a_param_passed_to_a_typed_closure() {
let sig = ClosureSigId(0);
let mut symbols = with_local("f", WasmType::Closure(sig));
symbols.record_closure_params(sig, &[WasmType::I32]);
let params = LambdaParams::simple(vec!["y".to_string()]);
let body = list(vec![sym("funcall"), sym("f"), sym("y")]);
infer_params(&symbols, ¶ms, &body).types,
fn form(source: &str) -> Expr {
Reader::parse_expr(source).expect("form parses")
fn pinned_form(source: &str, name: &str, symbols: &SymbolTable) -> Option<WasmType> {
pinned_in(&form(source), &name.to_uppercase(), symbols)
fn a_constant_bound_neighbour_pins_its_kind() {
let mut symbols = SymbolTable::new();
symbols.define(Symbol::new("A", SymbolKind::Variable).with_value(num(3)));
assert_eq!(pinned_form("(+ x a)", "x", &symbols), Some(WasmType::I32));
fn a_compound_operand_is_typed_by_its_result() {
let scalar = with_local("R", WasmType::Ratio);
pinned_form("(+ x (* 2/1 r))", "x", &scalar),
Some(WasmType::Ratio)
pinned_form("(+ 1/1 x r)", "x", &scalar),
let money = with_local("M", WasmType::Commodity);
pinned_form("(+ x (* 1/2 m))", "x", &money),
Some(WasmType::Commodity)
fn a_compound_operand_mentioning_the_param_does_not_type_it() {
assert_eq!(pinned_form("(+ x (car x))", "x", &scalar), None);
fn a_self_recursive_factory_ends_in_the_shared_ceiling_error() {
for source in [
"(defun mk () (lambda (x) (let ((g (mk))) (funcall g x)))) (funcall (mk) 2)",
"(defun mk (a) (lambda (x) (let ((g (mk a))) (funcall g x)))) (funcall (mk 1) 2)",
] {
let program = Reader::parse(source).expect("parses");
let mut symbols = SymbolTable::with_builtins_for_wasm();
let result = crate::compiler::Compiler::new().compile(&program, &mut symbols);
assert!(
matches!(result, Err(crate::error::Error::Resource(_))),
"{source}: {result:?}"
fn the_pins_its_subject_to_the_type_it_names() {
let symbols = SymbolTable::with_builtins();
for (source, pin) in [
("(the index x)", Some(WasmType::I32)),
("(the scalar x)", Some(WasmType::Ratio)),
(
"(list (+ (the scalar x) (length (list 1 x))))",
Some(WasmType::Ratio),
),
("(the index y)", None),
assert_eq!(pinned_form(source, "x", &symbols), pin, "{source}");
fn inferred(source: &str, symbols: &SymbolTable) -> Vec<Option<WasmType>> {
let Expr::List(parts) = form(source) else {
panic!("{source} is not a list");
};
let [_, Expr::List(names), body] = parts.as_slice() else {
panic!("{source} is not a lambda");
let names = names
.filter_map(|name| match name {
Expr::Symbol(name) => Some(name.clone()),
_ => None,
})
.collect();
infer_params(symbols, &LambdaParams::simple(names), body).types
fn a_parameter_no_use_pins_takes_the_one_dimension_its_body_accepts() {
for (source, pins) in [
("(lambda (x) (index->scalar x))", vec![Some(WasmType::I32)]),
"(lambda (x) (scalar->index x))",
vec![Some(WasmType::Ratio)],
("(lambda (x) (list x))", vec![Some(WasmType::I32)]),
("(lambda (x) (undefined-function x))", vec![None]),
assert_eq!(inferred(source, &symbols), pins, "{source}");
fn a_pinned_parameter_keeps_its_pin_beside_a_trial_typed_one() {
let source = "(lambda (a s) (+ (the scalar s) (index->scalar a)))";
inferred(source, &symbols),
vec![Some(WasmType::I32), Some(WasmType::Ratio)]
fn trial_typing_reaches_a_parameter_through_a_let_bound_lambda() {
let source = "(lambda (x) (let ((f (lambda (v) (index->scalar v)))) (funcall f x)))";
assert_eq!(inferred(source, &symbols), vec![Some(WasmType::I32)]);
fn trial_typing_reaches_a_parameter_through_a_let_bound_closure_from_a_list() {
let held = Expr::Lambda(
LambdaParams::simple(vec!["N".to_string()]),
Box::new(form("(index->scalar n)")),
symbols.define(
Symbol::new("GS", SymbolKind::Variable)
.with_value(Expr::Cons(Box::new(held), Box::new(Expr::Nil))),
let source = "(lambda (x) (let ((f (car gs))) (list (funcall f x))))";
fn define(symbols: &mut SymbolTable, (name, kind): (&str, SymbolKind), param: &str, body: &str) {
let params = LambdaParams::simple(vec![param.to_string()]);
let lambda = Expr::Lambda(params, Box::new(form(body)));
symbols.define(Symbol::new(name, kind).with_function(lambda));
fn unpinned_parameters_are_typed_jointly() {
"(lambda (a b) (list a (index->scalar b)))",
vec![Some(WasmType::I32); 2],
"(lambda (acc x) (+ acc (index->scalar x)))",
vec![Some(WasmType::Ratio), Some(WasmType::I32)],
"(lambda (a b c d) (list a b c d))",
vec![Some(WasmType::I32); 4],
fn money_beside_another_dimension_never_fits() {
let source = "(lambda (m s) (list (+ m (the money s))))";
vec![Some(WasmType::Commodity), Some(WasmType::Commodity)]
fn a_callee_default_takes_its_literals_kind_in_a_trial() {
let params = LambdaParams {
required: vec!["N".to_string()],
optional: vec![("K".to_string(), Some(num(1)))],
..LambdaParams::simple(Vec::new())
let lambda = Expr::Lambda(params, Box::new(form("(+ n k)")));
symbols.define(Symbol::new("HD", SymbolKind::Function).with_function(lambda));
inferred("(lambda (x) (list (hd x)))", &symbols),
fn trial_typing_reaches_a_parameter_through_its_callee() {
define(
&mut symbols,
("H", SymbolKind::Function),
"Y",
"(index->scalar y)",
("DBL", SymbolKind::Macro),
"V",
"`(index->scalar ,v)",
"(lambda (x) (h x))",
"(lambda (x) (funcall #'h x))",
"(lambda (x) (dbl x))",
"(lambda (x) (labels ((g (y) (index->scalar y))) (g x)))",
"(lambda (x) (let ((v x)) (index->scalar v)))",
vec![Some(WasmType::I32)],
"{source}"
fn a_probe_out_of_its_budget_pins_nothing() {
while symbols.enter_shared_recursion().is_ok() {}
inferred("(lambda (x) (index->scalar x))", &symbols),
fn only_a_parameter_several_dimensions_fit_is_ambiguous() {
let params = LambdaParams::simple(vec!["A".to_string(), "B".to_string()]);
let body = form("(list a (index->scalar b))");
infer_params(&symbols, ¶ms, &body).ambiguous,
vec![true, false]
fn four_unpinned_parameters_are_trial_typed_and_five_are_not() {
let four = LambdaParams::simple(["A", "B", "C", "D"].map(String::from).to_vec());
let found = infer_params(&symbols, &four, &form("(list a b c d)"));
assert_eq!(found.types, vec![Some(WasmType::I32); 4]);
assert_eq!(found.ambiguous, vec![true; 4]);
let five = LambdaParams::simple(["A", "B", "C", "D", "E"].map(String::from).to_vec());
let found = infer_params(&symbols, &five, &form("(list a b c d e)"));
assert_eq!(found.types, vec![None; 5]);
assert_eq!(found.ambiguous, vec![true; 5]);
fn a_first_fit_placeholder_is_no_type_evidence() {
let params = LambdaParams::simple(vec!["X".to_string()]);
assert!(!has_type_evidence(&symbols, ¶ms, &form("(list x)"), 0));
assert!(has_type_evidence(
&symbols,
¶ms,
&form("(index->scalar x)"),
0
));