1
use super::*;
2
use crate::ast::Fraction;
3
use crate::ast::Number;
4
use crate::ast::{LambdaParams, WasmType};
5
use crate::runtime::{Symbol, SymbolKind};
6

            
7
33
fn runtime_symbols(names: &[&str]) -> SymbolTable {
8
    // Reader case-folds source symbols to uppercase; matching that
9
    // here means the SymbolTable lookup hits when the test body
10
    // parses `x` as `X`.
11
33
    let mut table = SymbolTable::new();
12
33
    for n in names {
13
32
        table.define(
14
32
            Symbol::new(n.to_uppercase(), SymbolKind::Variable)
15
32
                .with_value(Expr::WasmRuntime(WasmType::I32)),
16
32
        );
17
    }
18
33
    table
19
33
}
20

            
21
96
fn parse(src: &str) -> Expr {
22
96
    crate::Reader::parse_expr(src).expect("parse")
23
96
}
24

            
25
41
fn captured(symbols: &SymbolTable, params: &LambdaParams, body: &Expr) -> CaptureSet {
26
41
    compute_captures(symbols, params, body).expect("captures")
27
41
}
28

            
29
8
fn capture_count(symbols: &SymbolTable, params: &LambdaParams, body: &Expr) -> usize {
30
8
    captured(symbols, params, body).len()
31
8
}
32

            
33
#[test]
34
1
fn empty_body_has_no_captures() {
35
1
    let symbols = runtime_symbols(&["x"]);
36
1
    let params = LambdaParams::simple(vec!["a".into()]);
37
1
    let body = Expr::Nil;
38
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
39
1
}
40

            
41
#[test]
42
1
fn body_referencing_only_params_has_no_captures() {
43
1
    let symbols = runtime_symbols(&["x"]);
44
1
    let params = LambdaParams::simple(vec!["a".into()]);
45
1
    let body = parse("(+ a 1)");
46
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
47
1
}
48

            
49
#[test]
50
1
fn body_referencing_outer_runtime_name_captures_it() {
51
1
    let symbols = runtime_symbols(&["x"]);
52
1
    let params = LambdaParams::simple(vec!["a".into()]);
53
1
    let body = parse("(+ a x)");
54
1
    let captures = captured(&symbols, &params, &body);
55
1
    assert_eq!(captures.len(), 1);
56
1
    assert!(captures.contains("X"));
57
1
}
58

            
59
#[test]
60
1
fn multiple_captures_preserve_first_seen_order() {
61
1
    let symbols = runtime_symbols(&["x", "y", "z"]);
62
1
    let params = LambdaParams::simple(vec![]);
63
1
    let body = parse("(+ z x y x)");
64
1
    let captures = captured(&symbols, &params, &body);
65
1
    let collected: Vec<&str> = captures.iter().collect();
66
1
    assert_eq!(collected, vec!["Z", "X", "Y"]);
67
1
}
68

            
69
#[test]
70
1
fn a_lexical_constant_is_not_captured() {
71
1
    let mut symbols = SymbolTable::new();
72
1
    symbols.define(
73
1
        Symbol::new("PI", SymbolKind::Variable)
74
1
            .with_value(Expr::Number(Number::Scalar(Fraction::new(22, 7)))),
75
1
    );
76
1
    let params = LambdaParams::simple(vec!["a".into()]);
77
1
    let body = parse("(+ a pi)");
78
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
79
1
}
80

            
81
#[test]
82
1
fn constant_globals_are_not_captured() {
83
1
    let mut symbols = SymbolTable::new();
84
1
    symbols.define(
85
1
        Symbol::new("PI", SymbolKind::Variable)
86
1
            .with_value(Expr::Number(Number::Scalar(Fraction::new(22, 7)))),
87
1
    );
88
1
    symbols.mark_special("PI");
89
1
    let params = LambdaParams::simple(vec!["a".into()]);
90
1
    let body = parse("(+ a pi)");
91
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
92
1
}
93

            
94
#[test]
95
1
fn unknown_symbols_are_not_captured() {
96
    // Symbol not in the table at all — capture analysis can't
97
    // claim it; later compile passes will surface UndefinedSymbol.
98
1
    let symbols = runtime_symbols(&[]);
99
1
    let params = LambdaParams::simple(vec![]);
100
1
    let body = parse("(+ undefined-thing 1)");
101
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
102
1
}
103

            
104
#[test]
105
1
fn nested_let_shadows_outer_capture() {
106
1
    let symbols = runtime_symbols(&["x"]);
107
1
    let params = LambdaParams::simple(vec![]);
108
1
    let body = parse("(let ((x 5)) (+ x 1))");
109
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
110
1
}
111

            
112
#[test]
113
1
fn nested_let_init_still_captures_outer() {
114
    // The initializer of a LET binding sees the outer scope, so
115
    // `x` in `(let ((x x)) ...)` is a capture of the outer x.
116
1
    let symbols = runtime_symbols(&["x"]);
117
1
    let params = LambdaParams::simple(vec![]);
118
1
    let body = parse("(let ((x x)) (+ x 1))");
119
1
    let captures = captured(&symbols, &params, &body);
120
1
    assert_eq!(captures.len(), 1);
121
1
    assert!(captures.contains("X"));
122
1
}
123

            
124
#[test]
125
1
fn nested_lambda_introduces_own_params_but_outer_capture_propagates() {
126
1
    let symbols = runtime_symbols(&["x"]);
127
1
    let params = LambdaParams::simple(vec![]);
128
1
    let body = parse("(lambda (a) (+ a x))");
129
1
    let captures = captured(&symbols, &params, &body);
130
1
    assert_eq!(captures.len(), 1);
131
1
    assert!(captures.contains("X"));
132
1
}
133

            
134
#[test]
135
1
fn nested_lambda_param_does_not_become_outer_capture() {
136
1
    let symbols = runtime_symbols(&[]);
137
1
    let params = LambdaParams::simple(vec![]);
138
1
    let body = parse("(lambda (a) (+ a 1))");
139
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
140
1
}
141

            
142
#[test]
143
1
fn quoted_symbols_are_not_captures() {
144
1
    let symbols = runtime_symbols(&["x"]);
145
1
    let params = LambdaParams::simple(vec![]);
146
1
    let body = parse("'x");
147
1
    assert_eq!(capture_count(&symbols, &params, &body), 0);
148
1
}
149

            
150
#[test]
151
1
fn unquote_under_a_template_quote_captures() {
152
1
    let symbols = runtime_symbols(&["x"]);
153
1
    let params = LambdaParams::simple(vec![]);
154
1
    let body = parse("`(a ',x)");
155
1
    let captures = captured(&symbols, &params, &body);
156
1
    assert!(captures.contains("X"));
157
1
}
158

            
159
#[test]
160
1
fn dolist_var_does_not_become_capture() {
161
1
    let symbols = runtime_symbols(&["xs"]);
162
1
    let params = LambdaParams::simple(vec![]);
163
1
    let body = parse("(dolist (item xs) (+ item 1))");
164
1
    let captures = captured(&symbols, &params, &body);
165
1
    assert_eq!(captures.len(), 1);
166
1
    assert!(captures.contains("XS"));
167
1
    assert!(!captures.contains("ITEM"));
168
1
}
169

            
170
#[test]
171
1
fn do_with_empty_variable_list_still_captures() {
172
1
    let symbols = runtime_symbols(&["c"]);
173
1
    let params = LambdaParams::simple(vec![]);
174
1
    let body = parse("(do () ((> c 3) c) (setf c (+ c 1)))");
175
1
    let captures = compute_captures(&symbols, &params, &body).expect("captures");
176
1
    assert!(captures.contains("C"));
177
1
}
178

            
179
7
fn captured_names(symbols: &SymbolTable, body: &str) -> Vec<String> {
180
7
    let params = LambdaParams::simple(vec![]);
181
7
    compute_captures(symbols, &params, &parse(body))
182
7
        .expect("captures")
183
7
        .iter()
184
7
        .map(str::to_string)
185
7
        .collect()
186
7
}
187

            
188
#[test]
189
1
fn a_do_step_sees_every_loop_variable() {
190
1
    let symbols = runtime_symbols(&["j"]);
191
1
    let read = "(do ((i 0 (+ i j)) (j 0 (+ j 1))) ((> i 3) i))";
192
1
    assert!(captured_names(&symbols, read).is_empty());
193
1
    let store = "(do ((i 0 (progn (setf j 9) (+ i 1))) (j 0 (+ j 1))) ((> i 2) j))";
194
1
    assert!(captured_names(&symbols, store).is_empty());
195
1
    assert!(stored(&symbols, store).is_empty());
196
1
}
197

            
198
#[test]
199
1
fn a_dolist_result_form_sees_the_loop_variable() {
200
1
    let symbols = runtime_symbols(&["x"]);
201
1
    assert!(captured_names(&symbols, "(dolist (x '(1 2) x) nil)").is_empty());
202
1
}
203

            
204
#[test]
205
1
fn a_lambda_list_default_reads_the_enclosing_scope() {
206
1
    let symbols = runtime_symbols(&["c", "y"]);
207
1
    assert_eq!(
208
1
        captured_names(&symbols, "(lambda (&optional (x c)) x)"),
209
1
        ["C"]
210
    );
211
1
    let later = "(lambda (&optional (x y) (y 2)) x)";
212
1
    assert_eq!(captured_names(&symbols, later), ["Y"]);
213
1
}
214

            
215
#[test]
216
1
fn a_parsed_lambda_default_reads_the_enclosing_scope() {
217
1
    let symbols = runtime_symbols(&["c"]);
218
1
    let params = LambdaParams {
219
1
        optional: vec![("X".into(), Some(parse("c")))],
220
1
        ..LambdaParams::simple(vec![])
221
1
    };
222
1
    let lambda = Expr::Lambda(params, Box::new(parse("x")));
223
1
    let found = compute_captures(&symbols, &LambdaParams::simple(vec![]), &lambda);
224
1
    assert_eq!(found.expect("captures").iter().collect::<Vec<_>>(), ["C"]);
225
1
}
226

            
227
#[test]
228
1
fn labels_names_and_parameters_are_bound() {
229
1
    let symbols = runtime_symbols(&["f", "x", "y"]);
230
1
    assert!(captured_names(&symbols, "(labels ((f (x) (f x))) (f 1))").is_empty());
231
1
    assert_eq!(
232
1
        captured_names(&symbols, "(labels ((f (x) y)) (f x))"),
233
1
        ["Y", "X"]
234
    );
235
1
}
236

            
237
37
fn with_function(symbols: &mut SymbolTable, name: &str, body: &str) {
238
37
    symbols.define(
239
37
        Symbol::new(name.to_uppercase(), SymbolKind::Function).with_function(Expr::Lambda(
240
37
            LambdaParams::simple(vec![]),
241
37
            Box::new(parse(body)),
242
37
        )),
243
37
    );
244
37
}
245

            
246
13
fn stored(symbols: &SymbolTable, body: &str) -> Vec<String> {
247
13
    let params = LambdaParams::simple(vec![]);
248
13
    captured(symbols, &params, &parse(body))
249
13
        .stored_captures()
250
13
        .map(str::to_string)
251
13
        .collect()
252
13
}
253

            
254
#[test]
255
1
fn a_store_to_a_captured_name_is_reported() {
256
1
    let symbols = runtime_symbols(&["x", "y"]);
257
1
    assert_eq!(stored(&symbols, "(progn (setf x (+ x 1)) y)"), vec!["X"]);
258
1
}
259

            
260
#[test]
261
1
fn a_store_through_a_field_place_is_not_a_store_to_the_variable() {
262
1
    let symbols = runtime_symbols(&["p"]);
263
1
    assert!(stored(&symbols, "(setf (pt-x p) 1)").is_empty());
264
1
}
265

            
266
#[test]
267
1
fn a_store_to_a_local_binding_is_not_a_captured_store() {
268
1
    let symbols = runtime_symbols(&["x"]);
269
1
    assert!(stored(&symbols, "(let ((x 0)) (setf x 1) x)").is_empty());
270
1
}
271

            
272
#[test]
273
1
fn a_called_user_function_contributes_its_captures_and_stores() {
274
1
    let mut symbols = runtime_symbols(&["g"]);
275
1
    with_function(&mut symbols, "reader", "g");
276
1
    with_function(&mut symbols, "writer", "(setf g 1)");
277
1
    let params = LambdaParams::simple(vec![]);
278
1
    let read = captured(&symbols, &params, &parse("(reader)"));
279
1
    assert!(read.contains("G"));
280
1
    assert_eq!(read.stored_captures().count(), 0);
281
1
    assert_eq!(stored(&symbols, "(writer)"), vec!["G"]);
282
1
}
283

            
284
#[test]
285
1
fn mutually_recursive_functions_are_followed_once() {
286
1
    let mut symbols = runtime_symbols(&["g"]);
287
1
    with_function(&mut symbols, "ping", "(progn (pong) (setf g 1))");
288
1
    with_function(&mut symbols, "pong", "(ping)");
289
1
    assert_eq!(stored(&symbols, "(ping)"), vec!["G"]);
290
1
}
291

            
292
#[test]
293
1
fn a_chain_of_calls_past_the_ceiling_is_refused() {
294
1
    let mut symbols = runtime_symbols(&["g"]);
295
1
    let links = crate::runtime::MAX_SHARED_RECURSION_DEPTH + 2;
296
1
    for index in 0..links {
297
26
        with_function(
298
26
            &mut symbols,
299
26
            &format!("f{index}"),
300
26
            &format!("(f{})", index + 1),
301
26
        );
302
    }
303
1
    with_function(&mut symbols, &format!("f{links}"), "(setf g 1)");
304
1
    let params = LambdaParams::simple(vec![]);
305
1
    let refusal = compute_captures(&symbols, &params, &parse("(f0)"));
306
1
    assert!(matches!(refusal, Err(Error::Resource(_))));
307
1
}
308

            
309
5
fn with_macro(symbols: &mut SymbolTable, name: &str, params: LambdaParams, body: &str) {
310
5
    symbols.define(
311
5
        Symbol::new(name.to_uppercase(), SymbolKind::Macro)
312
5
            .with_function(Expr::Lambda(params, Box::new(parse(body)))),
313
5
    );
314
5
}
315

            
316
#[test]
317
1
fn a_template_macro_use_is_walked_through_its_expansion() {
318
1
    let mut symbols = runtime_symbols(&["g"]);
319
1
    with_macro(
320
1
        &mut symbols,
321
1
        "bump",
322
1
        LambdaParams::simple(vec![]),
323
1
        "'(setf g 1)",
324
1
    );
325
1
    with_macro(&mut symbols, "rd", LambdaParams::simple(vec![]), "'g");
326
1
    assert_eq!(stored(&symbols, "(bump)"), vec!["G"]);
327
1
    let params = LambdaParams::simple(vec![]);
328
1
    let read = captured(&symbols, &params, &parse("(rd)"));
329
1
    assert!(read.contains("G"));
330
1
    assert_eq!(read.stored_captures().count(), 0);
331
1
}
332

            
333
#[test]
334
1
fn an_opaque_macro_use_may_store_to_every_capture() {
335
1
    let mut symbols = runtime_symbols(&["g"]);
336
1
    with_macro(
337
1
        &mut symbols,
338
1
        "bump",
339
1
        LambdaParams::simple(vec!["v".into()]),
340
1
        "(list 'setf v 1)",
341
1
    );
342
1
    assert_eq!(stored(&symbols, "(bump g)"), vec!["G"]);
343
1
}
344

            
345
12
fn followed(symbols: &SymbolTable, src: &str) -> Vec<String> {
346
12
    let params = LambdaParams::simple(vec![]);
347
12
    captured(symbols, &params, &parse(src))
348
12
        .followed_functions()
349
12
        .map(str::to_string)
350
12
        .collect()
351
12
}
352

            
353
#[test]
354
1
fn a_call_and_the_functions_behind_it_are_followed() {
355
1
    let mut symbols = runtime_symbols(&[]);
356
1
    with_function(&mut symbols, "outer", "(inner)");
357
1
    with_function(&mut symbols, "inner", "1");
358
1
    assert_eq!(followed(&symbols, "(outer)"), vec!["OUTER", "INNER"]);
359
1
}
360

            
361
#[test]
362
1
fn a_function_named_as_a_value_is_followed() {
363
1
    let mut symbols = runtime_symbols(&[]);
364
1
    with_function(&mut symbols, "g", "1");
365
1
    assert_eq!(followed(&symbols, "(funcall #'g 1)"), vec!["G"]);
366
1
    assert_eq!(followed(&symbols, "(funcall 'g 1)"), vec!["G"]);
367
1
    assert!(followed(&symbols, "(funcall 'h 1)").is_empty());
368
1
}
369

            
370
#[test]
371
1
fn a_labels_function_shadows_a_call_and_sharp_quote_but_not_a_quoted_name() {
372
1
    let mut symbols = runtime_symbols(&[]);
373
1
    with_function(&mut symbols, "g", "1");
374
3
    let labels = |use_form: &str| format!("(labels ((g (y) y)) {use_form})");
375
1
    assert!(followed(&symbols, &labels("(g 1)")).is_empty());
376
1
    assert!(followed(&symbols, &labels("(funcall #'g 1)")).is_empty());
377
1
    assert_eq!(followed(&symbols, &labels("(funcall 'g 1)")), vec!["G"]);
378
1
}
379

            
380
#[test]
381
1
fn a_function_name_in_a_constant_the_body_reads_is_followed() {
382
1
    let mut symbols = runtime_symbols(&[]);
383
1
    with_function(&mut symbols, "g", "1");
384
1
    for (name, value) in [("n", "'g"), ("ops", "(list g)"), ("pair", "(g . 1)")] {
385
3
        let value = parse(value);
386
3
        symbols.define(Symbol::new(name.to_uppercase(), SymbolKind::Variable).with_value(value));
387
3
        assert_eq!(
388
3
            followed(&symbols, &format!("(funcall {name} 1)")),
389
3
            vec!["G"]
390
        );
391
    }
392
1
}
393

            
394
#[test]
395
1
fn a_quoted_list_names_the_functions_in_it() {
396
1
    let mut symbols = runtime_symbols(&[]);
397
1
    with_function(&mut symbols, "g", "1");
398
1
    assert_eq!(followed(&symbols, "(car '(a g))"), vec!["G"]);
399
1
    assert!(followed(&symbols, "(car '(a h))").is_empty());
400
1
}
401

            
402
#[test]
403
1
fn a_clause_key_named_like_an_opaque_macro_is_not_a_macro_use() {
404
1
    let mut symbols = runtime_symbols(&["g"]);
405
1
    with_macro(
406
1
        &mut symbols,
407
1
        "bump",
408
1
        LambdaParams::simple(vec!["v".into()]),
409
1
        "(list 'setf v 1)",
410
1
    );
411
1
    assert!(stored(&symbols, "(case g (bump g))").is_empty());
412
1
    assert!(stored(&symbols, "(handler-case g (bump (e) 1))").is_empty());
413
1
    assert_eq!(stored(&symbols, "(cond (t (bump g)))"), vec!["G"]);
414
1
}
415

            
416
#[test]
417
1
fn a_labels_function_named_like_an_opaque_macro_is_not_a_macro_use() {
418
1
    let mut symbols = runtime_symbols(&["g"]);
419
1
    with_macro(
420
1
        &mut symbols,
421
1
        "bump",
422
1
        LambdaParams::simple(vec!["v".into()]),
423
1
        "(list 'setf v 1)",
424
1
    );
425
1
    assert!(stored(&symbols, "(labels ((bump (v) v)) (bump g))").is_empty());
426
1
    assert_eq!(
427
1
        stored(&symbols, "(progn (labels ((f (v) v)) (f g)) (bump g))"),
428
1
        vec!["G"]
429
    );
430
1
}