1
//! A macro body's control transfer (0014 P14): `expand_macro` keeps one that
2
//! its own BLOCK catches and turns one that escapes the expansion into a
3
//! structured error.
4

            
5
use super::*;
6
use crate::ast::Number;
7
use crate::ast::{KeyParam, LambdaParams};
8
use crate::reader::Reader;
9

            
10
36
fn form(source: &str) -> Expr {
11
36
    Reader::parse(source)
12
36
        .ok()
13
36
        .and_then(|program| program.exprs.into_iter().next())
14
36
        .unwrap_or(Expr::Nil)
15
36
}
16

            
17
14
fn expand(body: &str) -> Result<Expr> {
18
14
    let mut symbols = SymbolTable::with_builtins_for_wasm();
19
14
    expand_macro(
20
14
        &mut symbols,
21
14
        &LambdaParams::simple(Vec::new()),
22
14
        &form(body),
23
14
        &[],
24
14
    )
25
14
}
26

            
27
#[test]
28
1
fn a_macro_body_block_catches_its_own_return_from() {
29
1
    let expansion = expand("(block c (return-from c 5) 0)");
30
1
    assert!(
31
1
        matches!(expansion, Ok(ref v) if *v == form("5")),
32
        "{expansion:?}"
33
    );
34
1
}
35

            
36
#[test]
37
1
fn a_return_from_that_escapes_the_expansion_is_a_structured_error() {
38
1
    let expansion = expand("(return-from nowhere 5)");
39
1
    assert!(
40
1
        matches!(expansion, Err(Error::Compile(ref msg))
41
1
            if msg == "a macro body's RETURN-FROM escapes the expansion"),
42
        "{expansion:?}"
43
    );
44
1
}
45

            
46
4
fn key_macro_params() -> LambdaParams {
47
4
    LambdaParams {
48
4
        key: vec![KeyParam::new("K", None)],
49
4
        ..LambdaParams::simple(Vec::new())
50
4
    }
51
4
}
52

            
53
3
fn expand_key(body: &str, args: &[Expr]) -> Result<Expr> {
54
3
    let mut symbols = SymbolTable::with_builtins_for_wasm();
55
3
    expand_macro(&mut symbols, &key_macro_params(), &form(body), args)
56
3
}
57

            
58
#[test]
59
1
fn a_key_macro_without_keywords_binds_nil() {
60
1
    let expanded = expand_key("(block b (if k (return-from b k)) 2)", &[]);
61
1
    assert!(
62
1
        matches!(expanded, Ok(ref v) if *v == form("2")),
63
        "{expanded:?}"
64
    );
65
1
}
66

            
67
#[test]
68
1
fn a_key_macro_binds_the_given_keyword() {
69
1
    let args = [Expr::Keyword("K".to_string()), form("3")];
70
1
    let expanded = expand_key("k", &args);
71
1
    assert!(
72
1
        matches!(expanded, Ok(ref v) if *v == form("3")),
73
        "{expanded:?}"
74
    );
75
1
}
76

            
77
#[test]
78
1
fn a_key_macro_rejects_an_odd_keyword_list() {
79
1
    let args = [Expr::Keyword("K".to_string())];
80
1
    assert!(matches!(expand_key("k", &args), Err(Error::Compile(_))));
81
1
}
82

            
83
#[test]
84
1
fn a_key_lambda_rejects_an_odd_keyword_list() {
85
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
86
1
    let args = [Expr::Keyword("K".to_string())];
87
1
    let called = crate::compiler::expr::eval_lambda::call_lambda(
88
1
        &mut symbols,
89
1
        &key_macro_params(),
90
1
        &form("k"),
91
1
        &args,
92
1
        None,
93
1
    );
94
1
    assert!(matches!(called, Err(Error::Compile(_))), "{called:?}");
95
1
}
96

            
97
const RUNTIME_EFFECT: &str = "a macro body cannot use a runtime value or effect at expansion time";
98

            
99
#[test]
100
1
fn a_macro_body_with_a_runtime_effect_is_a_structured_error() {
101
1
    for body in [
102
1
        r#"(progn (print "z") 5)"#,
103
1
        "(handler-case (error 'oops \"x\") (oops (e) 2))",
104
1
        "(catch-each (list 1 2) x (* x 2))",
105
1
        "(dolist (i (progn (print 0) (list 1))) (print i)) nil",
106
1
        "(let ((a (print 0))) nil)",
107
1
        "(unwind-protect nil (print 0))",
108
1
        "(funcall (lambda (a) nil) (print 0))",
109
1
    ] {
110
7
        let expansion = expand(body);
111
7
        assert!(
112
7
            matches!(expansion, Err(Error::Compile(ref msg)) if msg == RUNTIME_EFFECT),
113
            "{body}: {expansion:?}"
114
        );
115
    }
116
1
}
117

            
118
#[test]
119
1
fn a_macro_body_that_never_runs_its_runtime_forms_still_expands() {
120
1
    for (body, expected) in [
121
1
        ("(if t 1 (print 0))", "1"),
122
1
        ("(and nil (print 0))", "nil"),
123
1
        ("(let ((f (lambda () (print 0)))) 1)", "1"),
124
1
        ("(dolist (i nil) (print i))", "nil"),
125
1
    ] {
126
4
        let expansion = expand(body);
127
4
        assert!(
128
4
            matches!(expansion, Ok(ref v) if *v == form(expected)),
129
            "{body}: {expansion:?}"
130
        );
131
    }
132
1
}
133

            
134
#[test]
135
1
fn a_pure_macro_body_still_computes_at_expansion() {
136
1
    let expansion = expand("(list '+ 1 2)");
137
1
    assert!(
138
1
        matches!(expansion, Ok(ref v) if *v == form("(+ 1 2)")),
139
        "{expansion:?}"
140
    );
141
1
}
142

            
143
#[test]
144
1
fn nested_macros_sharing_a_parameter_name_expand() {
145
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
146
1
    let program = Reader::parse("(defmacro a (x) (list '+ x 1)) (defmacro b (x) (a x))")
147
1
        .map(|p| p.exprs)
148
        .unwrap_or_default();
149
1
    for definition in &program {
150
2
        assert!(eval_value(&mut symbols, definition).is_ok());
151
    }
152
1
    let expansion = eval_value(&mut symbols, &form("(b 1)"));
153
1
    assert!(
154
1
        matches!(expansion, Ok(ref v) if *v == form("2")),
155
        "{expansion:?}"
156
    );
157
1
}
158

            
159
2
fn expand_optional(default: &str, body: &str) -> Result<Expr> {
160
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
161
2
    let params = LambdaParams {
162
2
        optional: vec![("XS".to_string(), Some(form(default)))],
163
2
        ..LambdaParams::simple(Vec::new())
164
2
    };
165
2
    expand_macro(&mut symbols, &params, &form(body), &[])
166
2
}
167

            
168
#[test]
169
1
fn an_optional_list_default_is_evaluated() {
170
1
    let expansion = expand_optional("(list 1 2)", "(length xs)");
171
1
    assert!(
172
1
        matches!(expansion, Ok(ref v) if *v == form("2")),
173
        "{expansion:?}"
174
    );
175
1
}
176

            
177
#[test]
178
1
fn an_optional_runtime_default_is_refused() {
179
1
    let expansion = expand_optional("(print 0)", "7");
180
1
    assert!(
181
1
        matches!(expansion, Err(Error::Compile(ref m)) if m.contains("runtime value or effect")),
182
        "{expansion:?}"
183
    );
184
1
}
185

            
186
2
fn reads_unbound(body: &str) -> bool {
187
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
188
2
    symbols.define(Symbol::new("G", SymbolKind::Variable).with_value(Expr::T));
189
2
    body_reads_unbound_variable(&symbols, &LambdaParams::simple(Vec::new()), &form(body))
190
2
}
191

            
192
#[test]
193
1
fn a_read_under_a_template_quote_is_found() {
194
1
    assert!(reads_unbound("`(list 'a ',g)"));
195
1
}
196

            
197
#[test]
198
1
fn a_variable_named_in_template_data_is_not_a_read() {
199
1
    assert!(!reads_unbound("`(list 'a g)"));
200
1
}
201

            
202
#[test]
203
1
fn a_call_head_that_is_a_runtime_closure_answers_its_recorded_result() {
204
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
205
1
    let sig = crate::ast::ClosureSigId(7);
206
1
    symbols.record_closure_result(sig, WasmType::Ratio);
207
1
    let head = Expr::WasmRuntime(WasmType::Closure(sig));
208
1
    assert_eq!(
209
1
        call(&mut symbols, &[head]).expect("called"),
210
1
        Expr::WasmRuntime(WasmType::Ratio)
211
    );
212
1
    let unknown = Expr::WasmRuntime(WasmType::Closure(crate::ast::ClosureSigId(8)));
213
1
    assert!(call(&mut symbols, &[unknown]).is_err());
214
1
}
215

            
216
#[test]
217
1
fn a_call_of_an_any_place_evaluates_to_an_any_value() {
218
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
219
1
    let head = Expr::WasmLocal(0, WasmType::AnyRef);
220
1
    let value = call(&mut symbols, &[head, Expr::Number(Number::Index(1.into()))]).expect("calls");
221
1
    assert_eq!(value, Expr::WasmRuntime(WasmType::AnyRef));
222
1
}
223

            
224
#[test]
225
1
fn a_call_headed_by_a_runtime_any_form_evaluates_to_an_any_value() {
226
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
227
1
    let head = Reader::parse_expr("(car (list (lambda () 1) nil))").expect("parses");
228
1
    let value = call(&mut symbols, &[head]).expect("calls");
229
1
    assert_eq!(value, Expr::WasmRuntime(WasmType::AnyRef));
230
1
}
231

            
232
#[test]
233
1
fn a_call_of_a_number_is_not_callable() {
234
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
235
1
    assert!(call(&mut symbols, &[Expr::Number(Number::Index(1.into()))]).is_err());
236
1
}