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

            
7
60
fn forms(source: &str) -> Vec<Expr> {
8
60
    Reader::parse(source)
9
60
        .map(|program| program.exprs)
10
        .unwrap_or_default()
11
60
}
12

            
13
18
fn targets(source: &str) -> Vec<String> {
14
18
    collect_setf_targets(&forms(source))
15
18
        .into_iter()
16
        .map(|(name, _)| name)
17
        .collect()
18
18
}
19

            
20
#[test]
21
1
fn a_lambda_parameter_shadows_the_outer_variable() {
22
1
    assert!(targets("(lambda (x) (setf x 1))").is_empty());
23
1
    assert_eq!(targets("(lambda (y) (setf x 1))"), ["X"]);
24
1
}
25

            
26
#[test]
27
1
fn a_binders_init_runs_outside_its_own_scope() {
28
1
    assert_eq!(targets("(let ((x (setf x 1))) (setf x 2))"), ["X"]);
29
1
    assert!(targets("(let ((x 0)) (setf x 2))").is_empty());
30
1
    assert!(targets("(let* ((x 0) (y (setf x 1))) y)").is_empty());
31
1
    assert_eq!(targets("(do ((x (setf x 1) (setf x 2))) (t))"), ["X"]);
32
1
    assert!(targets("(do ((x 0 (setf x 2))) (t))").is_empty());
33
1
    assert_eq!(targets("(dolist (x (setf x 1)) (setf x 2))"), ["X"]);
34
1
}
35

            
36
#[test]
37
1
fn a_lambda_default_sees_only_the_parameters_before_it() {
38
1
    assert_eq!(
39
1
        targets("(lambda (&optional (x (setf y 1)) (y 2)) x)"),
40
1
        ["Y"]
41
    );
42
1
    assert!(targets("(lambda (&optional (y 2) (x (setf y 1))) x)").is_empty());
43
1
}
44

            
45
#[test]
46
1
fn a_case_key_or_clause_name_is_not_a_form() {
47
1
    assert!(targets("(case k (setf y 1))").is_empty());
48
1
    assert!(targets("(handler-case (f) (setf (e) y))").is_empty());
49
1
    assert_eq!(targets("(case k (a (setf y 1)))"), ["Y"]);
50
1
    assert_eq!(targets("(cond ((setf y 1) 2))"), ["Y"]);
51
1
    assert_eq!(targets("(do () ((setf y 1) (setf z 2)))"), ["Y", "Z"]);
52
1
}
53

            
54
#[test]
55
1
fn code_forms_skip_names_keys_and_codes() {
56
7
    let shown = |source: &str| {
57
7
        let parsed = forms(source);
58
7
        let Some(Expr::List(elems)) = parsed.first() else {
59
            return Vec::new();
60
        };
61
7
        code_forms(elems).cloned().collect::<Vec<_>>()
62
7
    };
63
1
    assert_eq!(shown("(cond (a b) (c))"), forms("a b c"));
64
1
    assert_eq!(shown("(case k (1 a b) ((2) c))"), forms("k a b c"));
65
1
    assert_eq!(shown("(handler-case x (e (v) a))"), forms("x a"));
66
1
    assert_eq!(shown("(labels ((f (p) a b)) c)"), forms("a b c"));
67
1
    assert_eq!(shown("(do () (m a) b)"), forms("m a b"));
68
1
    assert_eq!(shown("(do ((i 0 s)) (m a) b)"), forms("0 s m a b"));
69
1
    assert_eq!(shown("(defun f (p (q d)) a)"), forms("d a"));
70
1
}
71

            
72
#[test]
73
1
fn code_mapped_rewrites_only_the_code_positions() {
74
3
    let mapped = |source: &str| {
75
3
        let parsed = forms(source);
76
3
        let Some(Expr::List(elems)) = parsed.first() else {
77
            return Vec::new();
78
        };
79
3
        let mark = forms("x").into_iter().next().unwrap_or(Expr::Nil);
80
9
        code_mapped(elems, &mut |form| {
81
9
            Ok(Expr::List(vec![mark.clone(), form.clone()]))
82
9
        })
83
        .unwrap_or_default()
84
3
    };
85
1
    assert_eq!(mapped("(case k (1 a))"), forms("(x case) (x k) (1 (x a))"));
86
1
    assert_eq!(
87
1
        mapped("(defmacro m (p (q d)) a)"),
88
1
        forms("(x defmacro) m (p (q (x d))) (x a)")
89
    );
90
1
    assert_eq!(
91
1
        mapped("(labels ((f (p) a)) b)"),
92
1
        forms("(x labels) ((f (p) (x a))) (x b)")
93
    );
94
1
}
95

            
96
#[test]
97
1
fn quoted_data_assigns_nothing() {
98
1
    assert!(targets("(quote (setf x 1))").is_empty());
99
1
    assert!(targets("'(setf x 1)").is_empty());
100
1
}
101

            
102
#[test]
103
1
fn assignment_queries_share_the_scoped_walk() {
104
1
    let body = forms("(setf x 1) (lambda (x) (setf x 2)) (setf y 3)");
105
1
    assert!(assigns(&body, "X"));
106
1
    assert_eq!(
107
1
        setf_rhs_of(&body, "X"),
108
1
        [&Expr::Number(Number::Index(1.into()))]
109
    );
110
1
    assert!(!assigns(&forms("(lambda (x) (setf x 2))"), "X"));
111
1
}
112

            
113
10
fn element(source: &str) -> Option<PairElement> {
114
10
    let symbols = SymbolTable::with_builtins_for_wasm();
115
10
    forms(source)
116
10
        .first()
117
10
        .and_then(|form| step_pair_element(form, &symbols))
118
10
}
119

            
120
#[test]
121
1
fn a_native_cons_or_list_builds_its_element() {
122
1
    assert_eq!(element("(cons \"a\" r)"), Some(PairElement::StringRef));
123
1
    assert_eq!(element("(list \"a\" \"b\")"), Some(PairElement::StringRef));
124
1
    assert_eq!(element("(list t \"b\")"), Some(PairElement::AnyRef));
125
1
}
126

            
127
#[test]
128
1
fn a_list_inside_the_stored_value_is_not_the_stored_value() {
129
1
    assert_eq!(element("(block c (dolist (y (list \"a\")) y) 0)"), None);
130
1
}
131

            
132
#[test]
133
1
fn quoted_and_lambda_subtrees_build_nothing() {
134
1
    assert_eq!(element("(car (list (quote (cons \"a\" 2))))"), None);
135
1
    assert_eq!(element("(lambda () (cons \"a\" r))"), None);
136
1
}
137

            
138
#[test]
139
1
fn disagreeing_branch_arms_widen() {
140
1
    assert_eq!(
141
1
        element("(if c (cons \"a\" r) (list t))"),
142
1
        Some(PairElement::AnyRef)
143
    );
144
1
    assert_eq!(
145
1
        element("(if c (cons \"a\" r) r)"),
146
1
        Some(PairElement::StringRef)
147
    );
148
1
    assert_eq!(
149
1
        element("(cond (a (cons \"a\" r)) (t (cons t r)))"),
150
1
        Some(PairElement::AnyRef)
151
    );
152
1
}
153

            
154
2
fn identity_lambda() -> Expr {
155
2
    Expr::Lambda(
156
2
        LambdaParams::simple(vec!["X".to_string()]),
157
2
        Box::new(Expr::Symbol("X".to_string())),
158
2
    )
159
2
}
160

            
161
#[test]
162
1
fn a_user_cons_builds_nothing() {
163
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
164
1
    symbols.define(
165
1
        crate::runtime::Symbol::new("CONS", SymbolKind::Function).with_function(identity_lambda()),
166
1
    );
167
1
    let form = &forms("(cons \"a\" r)")[0];
168
1
    assert_eq!(step_pair_element(form, &symbols), None);
169
1
}
170

            
171
#[test]
172
1
fn a_defun_name_stays_user_callable_over_a_closure_local() {
173
    let defun =
174
1
        crate::runtime::Symbol::new("F", SymbolKind::Function).with_function(identity_lambda());
175
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
176
1
    symbols.define(defun.clone());
177
1
    assert!(names_user_callable("F", &symbols));
178
1
    symbols.define(defun.with_value(Expr::WasmLocal(3, WasmType::Closure(ClosureSigId(7)))));
179
1
    assert!(names_user_callable("F", &symbols));
180
1
}
181

            
182
#[test]
183
1
fn a_runtime_list_item_rides_a_cell_as_any() {
184
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
185
1
    symbols.define(
186
1
        crate::runtime::Symbol::new("ACC", SymbolKind::Variable)
187
1
            .with_value(Expr::WasmRuntime(WasmType::PairRef(PairElement::I32))),
188
1
    );
189
1
    let form = &forms("(list acc 1)")[0];
190
1
    assert_eq!(step_pair_element(form, &symbols), Some(PairElement::AnyRef));
191
1
}
192

            
193
2
fn symbols_with_f(body: Expr) -> SymbolTable {
194
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
195
2
    symbols.define(
196
2
        crate::runtime::Symbol::new("F", SymbolKind::Function).with_function(Expr::Lambda(
197
2
            LambdaParams::simple(vec!["X".to_string()]),
198
2
            Box::new(body),
199
2
        )),
200
2
    );
201
2
    symbols
202
2
}
203

            
204
#[test]
205
1
fn a_user_function_car_is_typed_by_its_result() {
206
1
    let symbols = symbols_with_f(Expr::Symbol("X".to_string()));
207
1
    let form = &forms("(cons (f \"a\") r)")[0];
208
1
    assert_eq!(
209
1
        step_pair_element(form, &symbols),
210
1
        Some(PairElement::StringRef)
211
    );
212
1
}
213

            
214
#[test]
215
1
fn a_non_terminating_user_function_car_builds_nothing() {
216
1
    let symbols = symbols_with_f(forms("(f x)").remove(0));
217
1
    let form = &forms("(cons (f 1) r)")[0];
218
1
    assert_eq!(step_pair_element(form, &symbols), None);
219
1
}
220

            
221
2
fn element_with_closure(source: &str, body: Expr) -> Option<PairElement> {
222
2
    let mut symbols = SymbolTable::with_builtins_for_wasm();
223
2
    let closure = Expr::Lambda(LambdaParams::simple(Vec::new()), Box::new(body));
224
2
    symbols.define(Symbol::new("F", SymbolKind::Variable).with_value(closure));
225
2
    forms(source)
226
2
        .first()
227
2
        .and_then(|form| step_pair_element(form, &symbols))
228
2
}
229

            
230
#[test]
231
1
fn a_funcall_of_a_closure_variable_builds_the_closures_element() {
232
1
    let five = Expr::Number(Number::Index(5));
233
1
    assert_eq!(
234
1
        element_with_closure("(cons (funcall f) r)", five),
235
1
        Some(PairElement::I32)
236
    );
237
1
    assert_eq!(
238
1
        element_with_closure("(cons (funcall f) r)", Expr::String("s".to_string())),
239
1
        Some(PairElement::StringRef)
240
    );
241
1
}
242

            
243
#[test]
244
1
fn a_funcall_of_an_unbound_variable_builds_nothing() {
245
1
    assert_eq!(element("(cons (funcall f) r)"), None);
246
1
}
247

            
248
#[test]
249
1
fn a_call_head_that_is_not_a_symbol_is_scanned() {
250
1
    assert_eq!(targets("((lambda () (setf y 1)))"), ["Y"]);
251
1
}