Lines
100 %
Functions
Branches
//! A macro body's control transfer (0014 P14): `expand_macro` keeps one that
//! its own BLOCK catches and turns one that escapes the expansion into a
//! structured error.
use super::*;
use crate::ast::Number;
use crate::ast::{KeyParam, LambdaParams};
use crate::reader::Reader;
fn form(source: &str) -> Expr {
Reader::parse(source)
.ok()
.and_then(|program| program.exprs.into_iter().next())
.unwrap_or(Expr::Nil)
}
fn expand(body: &str) -> Result<Expr> {
let mut symbols = SymbolTable::with_builtins_for_wasm();
expand_macro(
&mut symbols,
&LambdaParams::simple(Vec::new()),
&form(body),
&[],
)
#[test]
fn a_macro_body_block_catches_its_own_return_from() {
let expansion = expand("(block c (return-from c 5) 0)");
assert!(
matches!(expansion, Ok(ref v) if *v == form("5")),
"{expansion:?}"
);
fn a_return_from_that_escapes_the_expansion_is_a_structured_error() {
let expansion = expand("(return-from nowhere 5)");
matches!(expansion, Err(Error::Compile(ref msg))
if msg == "a macro body's RETURN-FROM escapes the expansion"),
fn key_macro_params() -> LambdaParams {
LambdaParams {
key: vec![KeyParam::new("K", None)],
..LambdaParams::simple(Vec::new())
fn expand_key(body: &str, args: &[Expr]) -> Result<Expr> {
expand_macro(&mut symbols, &key_macro_params(), &form(body), args)
fn a_key_macro_without_keywords_binds_nil() {
let expanded = expand_key("(block b (if k (return-from b k)) 2)", &[]);
matches!(expanded, Ok(ref v) if *v == form("2")),
"{expanded:?}"
fn a_key_macro_binds_the_given_keyword() {
let args = [Expr::Keyword("K".to_string()), form("3")];
let expanded = expand_key("k", &args);
matches!(expanded, Ok(ref v) if *v == form("3")),
fn a_key_macro_rejects_an_odd_keyword_list() {
let args = [Expr::Keyword("K".to_string())];
assert!(matches!(expand_key("k", &args), Err(Error::Compile(_))));
fn a_key_lambda_rejects_an_odd_keyword_list() {
let called = crate::compiler::expr::eval_lambda::call_lambda(
&key_macro_params(),
&form("k"),
&args,
None,
assert!(matches!(called, Err(Error::Compile(_))), "{called:?}");
const RUNTIME_EFFECT: &str = "a macro body cannot use a runtime value or effect at expansion time";
fn a_macro_body_with_a_runtime_effect_is_a_structured_error() {
for body in [
r#"(progn (print "z") 5)"#,
"(handler-case (error 'oops \"x\") (oops (e) 2))",
"(catch-each (list 1 2) x (* x 2))",
"(dolist (i (progn (print 0) (list 1))) (print i)) nil",
"(let ((a (print 0))) nil)",
"(unwind-protect nil (print 0))",
"(funcall (lambda (a) nil) (print 0))",
] {
let expansion = expand(body);
matches!(expansion, Err(Error::Compile(ref msg)) if msg == RUNTIME_EFFECT),
"{body}: {expansion:?}"
fn a_macro_body_that_never_runs_its_runtime_forms_still_expands() {
for (body, expected) in [
("(if t 1 (print 0))", "1"),
("(and nil (print 0))", "nil"),
("(let ((f (lambda () (print 0)))) 1)", "1"),
("(dolist (i nil) (print i))", "nil"),
matches!(expansion, Ok(ref v) if *v == form(expected)),
fn a_pure_macro_body_still_computes_at_expansion() {
let expansion = expand("(list '+ 1 2)");
matches!(expansion, Ok(ref v) if *v == form("(+ 1 2)")),
fn nested_macros_sharing_a_parameter_name_expand() {
let program = Reader::parse("(defmacro a (x) (list '+ x 1)) (defmacro b (x) (a x))")
.map(|p| p.exprs)
.unwrap_or_default();
for definition in &program {
assert!(eval_value(&mut symbols, definition).is_ok());
let expansion = eval_value(&mut symbols, &form("(b 1)"));
matches!(expansion, Ok(ref v) if *v == form("2")),
fn expand_optional(default: &str, body: &str) -> Result<Expr> {
let params = LambdaParams {
optional: vec![("XS".to_string(), Some(form(default)))],
};
expand_macro(&mut symbols, ¶ms, &form(body), &[])
fn an_optional_list_default_is_evaluated() {
let expansion = expand_optional("(list 1 2)", "(length xs)");
fn an_optional_runtime_default_is_refused() {
let expansion = expand_optional("(print 0)", "7");
matches!(expansion, Err(Error::Compile(ref m)) if m.contains("runtime value or effect")),
fn reads_unbound(body: &str) -> bool {
symbols.define(Symbol::new("G", SymbolKind::Variable).with_value(Expr::T));
body_reads_unbound_variable(&symbols, &LambdaParams::simple(Vec::new()), &form(body))
fn a_read_under_a_template_quote_is_found() {
assert!(reads_unbound("`(list 'a ',g)"));
fn a_variable_named_in_template_data_is_not_a_read() {
assert!(!reads_unbound("`(list 'a g)"));
fn a_call_head_that_is_a_runtime_closure_answers_its_recorded_result() {
let sig = crate::ast::ClosureSigId(7);
symbols.record_closure_result(sig, WasmType::Ratio);
let head = Expr::WasmRuntime(WasmType::Closure(sig));
assert_eq!(
call(&mut symbols, &[head]).expect("called"),
Expr::WasmRuntime(WasmType::Ratio)
let unknown = Expr::WasmRuntime(WasmType::Closure(crate::ast::ClosureSigId(8)));
assert!(call(&mut symbols, &[unknown]).is_err());
fn a_call_of_an_any_place_evaluates_to_an_any_value() {
let head = Expr::WasmLocal(0, WasmType::AnyRef);
let value = call(&mut symbols, &[head, Expr::Number(Number::Index(1.into()))]).expect("calls");
assert_eq!(value, Expr::WasmRuntime(WasmType::AnyRef));
fn a_call_headed_by_a_runtime_any_form_evaluates_to_an_any_value() {
let head = Reader::parse_expr("(car (list (lambda () 1) nil))").expect("parses");
let value = call(&mut symbols, &[head]).expect("calls");
fn a_call_of_a_number_is_not_callable() {
assert!(call(&mut symbols, &[Expr::Number(Number::Index(1.into()))]).is_err());