Lines
98.28 %
Functions
100 %
Branches
//! The source a closure keeps for a host that carries it to the next unit.
use crate::ast::WasmType;
use crate::compiler::expr::format_form;
use crate::compiler::{CompileMode, Compiler};
use crate::host_fn::HostFnSpec;
use crate::reader::Reader;
use crate::runtime::SymbolTable;
use crate::ast::Expr;
fn after(source: &str) -> SymbolTable {
let specs = [HostFnSpec::new("idx", "test", "idx").returns(WasmType::I32)];
let mut symbols = SymbolTable::with_builtins();
symbols.register_host_fns(&specs);
let program = Reader::parse(source).expect("parses");
Compiler::with_host_fns(specs.to_vec())
.compile_with_mode(&program, &mut symbols, CompileMode::Eval)
.expect("compiles");
symbols
}
fn carried_text(symbols: &SymbolTable, site: i32) -> Option<String> {
let source = symbols.closure_source(site)?;
let values = source.fields().iter().map(|_| Expr::Nil).collect();
match source.lambda(values) {
Expr::Lambda(params, body) => Some(format!("{:?} {}", params.required, format_form(&body))),
_ => None,
#[test]
fn a_capture_free_lambda_keeps_its_source() {
let symbols = after("(lambda (x) (* x 2))");
assert_eq!(
carried_text(&symbols, 0).as_deref(),
Some(r#"["X"] (* X 2)"#)
);
fn each_lambda_of_a_unit_has_its_own_site() {
let symbols = after("(list (lambda (x) 1) (lambda (x) 2))");
assert_eq!(carried_text(&symbols, 0).as_deref(), Some(r#"["X"] 1"#));
assert_eq!(carried_text(&symbols, 1).as_deref(), Some(r#"["X"] 2"#));
assert_eq!(carried_text(&symbols, 2), None);
fn a_runtime_capture_is_a_field_of_the_environment() {
let symbols = after("(let ((n (idx))) (lambda () n))");
let source = symbols.closure_source(0).expect("kept");
assert_eq!(source.fields(), [("N".to_string(), WasmType::I32)]);
fn a_lexical_constant_is_bound_around_the_body() {
let symbols = after("(let ((r 1/10)) (lambda (x) (* x r)))");
Some(r#"["X"] (LET ((R 1/10)) (* X R))"#)
fn a_shared_cell_in_the_environment_keeps_no_source() {
let symbols = after("(let ((n 0)) (lambda () (setf n (+ n 1))))");
assert_eq!(symbols.closure_source(0), None);
fn a_labels_function_in_the_body_keeps_no_source() {
let symbols = after("(labels ((h (y) (* y 10))) (lambda (x) (h x)))");
fn a_user_macro_in_the_body_keeps_its_expansion() {
let symbols = after("(defmacro dbl (x) `(* ,x 2)) (lambda (y) (dbl y))");
Some(r#"["Y"] (* Y 2)"#)
fn a_built_in_macro_in_the_body_keeps_its_source() {
let symbols = after("(lambda (x) (when (> x 0) 1))");
assert!(symbols.closure_source(0).is_some());