Lines
98.47 %
Functions
100 %
Branches
use super::{
designator_operand, effect_prefix, hoist_call_function, hoist_function_arg, is_computed,
reject_non_function, resolve_designator, runs_nothing,
};
use crate::ast::{Expr, LambdaParams, Place, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::fold::walk::{is_lambda_head, is_lambda_literal};
use crate::reader::Reader;
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
fn form(source: &str) -> Expr {
Reader::parse_expr(source).expect("form parses")
}
#[test]
fn progn_splits_into_effects_and_value() {
let call = form("(progn (print 1) 'car)");
let (effects, value) = effect_prefix(&call);
assert_eq!(effects.len(), 1);
assert_eq!(value, &form("'car"));
fn any_other_form_is_its_own_value() {
let call = form("(list (print 1) 'car)");
assert!(effects.is_empty());
assert_eq!(value, &call);
fn is_computed_classifies_the_head() {
let table = SymbolTable::with_builtins();
assert!(!is_computed(&table, &form("(lambda (x) x)")).expect("scan"));
assert!(!is_computed(&table, &form("(quote (print 1))")).expect("scan"));
assert!(!is_computed(&table, &form("(function car)")).expect("scan"));
assert!(is_computed(&table, &form("(car (list (lambda (x) x)))")).expect("scan"));
assert!(is_computed(&table, &form("(mk (print 1))")).expect("scan"));
fn is_lambda_literal_classifies_the_head() {
assert!(is_lambda_literal(&table, &form("(lambda (x) x)")));
assert!(is_lambda_literal(&table, &form("(function car)")));
assert!(!is_lambda_literal(&table, &form("(car (list 1))")));
fn is_lambda_head_accepts_only_spelled_out_lambdas() {
assert!(is_lambda_head(&table, &form("(lambda (x) x)")));
assert!(is_lambda_head(&table, &form("(function (lambda (x) x))")));
assert!(!is_lambda_head(&table, &form("(function car)")));
assert!(!is_lambda_head(&table, &form("(function (car))")));
assert!(!is_lambda_head(&table, &form("(mk 1)")));
assert!(!is_lambda_head(&table, &Expr::Nil));
fn closure_global_table(ctx: &mut CompileContext) -> SymbolTable {
let sig = ctx
.intern_closure_signature(&[], WasmType::Ratio)
.expect("closure sig");
let mut table = SymbolTable::with_builtins_for_wasm();
let global = Symbol::new("F", SymbolKind::Variable)
.with_value(Expr::WasmGlobal(0, WasmType::Closure(sig)));
table.define(global);
table
type Hoist = fn(
&mut CompileContext,
&mut FunctionEmitter,
&mut SymbolTable,
&[Expr],
) -> crate::error::Result<Option<Vec<Expr>>>;
fn hoisted_function(ctx: &mut CompileContext, hoist: Hoist, args: &[&str]) -> Expr {
let mut table = closure_global_table(ctx);
let mut emit = FunctionEmitter::new();
let forms: Vec<Expr> = args.iter().map(|arg| form(arg)).collect();
let hoisted = hoist(ctx, &mut emit, &mut table, &forms)
.expect("hoists")
.expect("a live operand");
hoisted[0].clone()
fn a_closure_global_stays_a_name_when_the_later_operands_run_nothing() {
let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
assert_eq!(
hoisted_function(&mut ctx, hoist_call_function, &["f", "'(1 2)"]),
form("f")
);
fn a_closure_global_is_read_into_a_local_before_a_later_effect() {
let function = hoisted_function(
&mut ctx,
hoist_call_function,
&["f", "(progn (print 1) nil)"],
assert!(matches!(function, Expr::WasmLocal(_, WasmType::Closure(_))));
fn a_lambda_literal_is_not_pinned() {
&["(lambda (x) x)", "(progn (print 1) nil)"],
assert!(matches!(function, Expr::List(_)));
fn a_pinned_closure_keeps_the_recorded_body() {
let mut table = closure_global_table(&mut ctx);
let params = LambdaParams::simple(vec!["x".to_string()]);
table.record_closure_body(Place::Global(0), params.clone(), Expr::Nil);
let forms = [form("f"), form("(progn (print 1) nil)")];
let hoisted = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms)
let (copy, _) = hoisted[0].place().expect("a local copy");
assert_eq!(table.closure_body(copy), Some(&(params, Expr::Nil)));
fn a_higher_order_native_reads_a_closure_global_even_when_the_rest_is_pure() {
let function = hoisted_function(&mut ctx, hoist_function_arg, &["f", "'(1 2)"]);
fn hoisting_a_hoisted_function_adds_no_second_local() {
let forms = [form("f"), form("'(1 2)")];
let first = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms)
let second = hoist_function_arg(&mut ctx, &mut emit, &mut table, &first)
assert_eq!(first[0], second[0]);
fn table_with_factory() -> SymbolTable {
let params = LambdaParams::simple(vec!["A".to_string()]);
let body = form("(lambda (x) (+ x a))");
table.define(
Symbol::new("MK", SymbolKind::Function).with_function(Expr::Lambda(params, Box::new(body))),
fn a_closure_factory_call_is_computed_even_with_constant_arguments() {
let table = table_with_factory();
assert!(is_computed(&table, &form("(mk 3)")).expect("scan"));
fn a_factory_designator_is_lowered_to_a_lambda_over_a_hidden_variable() {
let mut table = table_with_factory();
let forms = [form("(mk 3)"), form("'(1 2)")];
let Expr::Lambda(_, body) = &hoisted[0] else {
panic!("a lambda, got {:?}", hoisted[0]);
let Expr::List(scope) = body.as_ref() else {
panic!("a LET scope, got {body:?}");
assert_eq!(scope[0], Expr::symbol("LET"));
fn a_quoted_name_resolves_to_the_global_function_a_labels_one_hides() {
let mut table = SymbolTable::new();
let global = Symbol::new("F", SymbolKind::Function).with_function(Expr::Lambda(
LambdaParams::simple(Vec::new()),
Box::new(Expr::T),
));
let expected = global.function().cloned();
table.define(Symbol::new("F", SymbolKind::Function).local_function());
let Expr::Datum(named) = resolve_designator(&table, &form("(quote f)")).expect("resolved")
else {
panic!("a designator datum");
let Expr::Symbol(alias) = *named else {
panic!("an alias name");
table.lookup(&alias).and_then(|s| s.function().cloned()),
expected
fn an_unhidden_quoted_name_resolves_to_its_datum() {
let table = SymbolTable::new();
let resolved = resolve_designator(&table, &form("'car")).expect("resolved");
assert_eq!(resolved, Expr::Datum(Box::new(Expr::symbol("CAR"))));
fn an_operand_runs_nothing_only_when_nothing_in_it_runs() {
let mut table = SymbolTable::with_builtins();
let succ = Expr::Lambda(
LambdaParams::simple(vec!["X".to_string()]),
Box::new(form("(+ x 1)")),
table.define(Symbol::new("SUCC", SymbolKind::Function).with_function(succ));
for (source, quiet) in [
("(+ 1 2)", true),
("(setf n 9)", false),
("(succ 2)", true),
("(succ (setf n 9))", false),
("(lambda (y) y)", true),
] {
assert_eq!(runs_nothing(&table, &form(source)), quiet, "{source}");
fn a_macro_is_no_function_designator() {
let body = Expr::Lambda(LambdaParams::simple(Vec::new()), Box::new(Expr::Nil));
table.define(Symbol::new("DBL", SymbolKind::Macro).with_function(body.clone()));
table.define(Symbol::new("TWICE", SymbolKind::Function).with_function(body));
let err = reject_non_function(&table, "DBL").expect_err("a macro");
err.to_string(),
"Compile error: DBL is a macro, not a function"
assert!(reject_non_function(&table, "TWICE").is_ok());
let builtin = reject_non_function(&table, "MAPCAR").expect_err("a builtin macro");
builtin.to_string(),
"Compile error: MAPCAR cannot be used as a function value yet"
assert!(resolve_designator(&table, &form("'dbl")).is_err());
assert!(resolve_designator(&table, &form("'twice")).is_ok());
fn one_rule_names_what_is_no_function_designator() {
for (name, message) in [
("IF", "IF is a special operator, not a function"),
("LET", "LET is a special operator, not a function"),
("AND", "AND is a macro, not a function"),
("WHEN", "WHEN is a macro, not a function"),
("MAPC", "MAPC cannot be used as a function value yet"),
let rejected = reject_non_function(&table, name)
.err()
.map(|e| e.to_string());
rejected,
Some(format!("Compile error: {message}")),
"{name}"
for name in ["CAR", "+", "FUNCALL", "APPLY", "EVAL", "ERROR"] {
assert!(reject_non_function(&table, name).is_ok(), "{name}");
fn a_function_form_of_a_built_in_resolves_as_its_quoted_name() {
let resolved = resolve_designator(&table, &form("#'car")).expect("a native");
resolved,
resolve_designator(&table, &form("'car")).expect("quoted")
fn any_local_table() -> SymbolTable {
let local =
Symbol::new("G", SymbolKind::Variable).with_value(Expr::WasmLocal(0, WasmType::AnyRef));
table.define(local);
fn a_higher_order_native_refuses_an_any_function_operand() {
let err = hoist_function_arg(&mut ctx, &mut emit, &mut any_local_table(), &[form("g")])
.expect_err("refused");
assert!(err.to_string().contains("call it through (lambda"), "{err}");
fn a_call_keeps_an_any_function_operand_for_the_run_time_check() {
let hoisted = hoist_call_function(&mut ctx, &mut emit, &mut any_local_table(), &[form("g")])
assert_eq!(hoisted[0], form("g"));
fn a_computed_any_operand_is_held_in_a_local() {
let operand = designator_operand(
&mut emit,
&mut table,
&form("(car (list (lambda () 1) nil))"),
)
.expect("lowers");
assert!(
matches!(operand, Expr::WasmLocal(_, WasmType::AnyRef)),
"{operand:?}"
fn a_raising_function_operand_ends_the_call() {
let forms = [form("(error 'x \"m\")"), form("'(1 2)")];
let hoisted = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms).expect("hoists");
assert_eq!(hoisted, None);