1
use super::{
2
    designator_operand, effect_prefix, hoist_call_function, hoist_function_arg, is_computed,
3
    reject_non_function, resolve_designator, runs_nothing,
4
};
5
use crate::ast::{Expr, LambdaParams, Place, WasmType};
6
use crate::compiler::context::CompileContext;
7
use crate::compiler::emit::FunctionEmitter;
8
use crate::compiler::expr::fold::walk::{is_lambda_head, is_lambda_literal};
9
use crate::reader::Reader;
10
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
11

            
12
52
fn form(source: &str) -> Expr {
13
52
    Reader::parse_expr(source).expect("form parses")
14
52
}
15

            
16
#[test]
17
1
fn progn_splits_into_effects_and_value() {
18
1
    let call = form("(progn (print 1) 'car)");
19
1
    let (effects, value) = effect_prefix(&call);
20
1
    assert_eq!(effects.len(), 1);
21
1
    assert_eq!(value, &form("'car"));
22
1
}
23

            
24
#[test]
25
1
fn any_other_form_is_its_own_value() {
26
1
    let call = form("(list (print 1) 'car)");
27
1
    let (effects, value) = effect_prefix(&call);
28
1
    assert!(effects.is_empty());
29
1
    assert_eq!(value, &call);
30
1
}
31

            
32
#[test]
33
1
fn is_computed_classifies_the_head() {
34
1
    let table = SymbolTable::with_builtins();
35
1
    assert!(!is_computed(&table, &form("(lambda (x) x)")).expect("scan"));
36
1
    assert!(!is_computed(&table, &form("(quote (print 1))")).expect("scan"));
37
1
    assert!(!is_computed(&table, &form("(function car)")).expect("scan"));
38
1
    assert!(is_computed(&table, &form("(car (list (lambda (x) x)))")).expect("scan"));
39
1
    assert!(is_computed(&table, &form("(mk (print 1))")).expect("scan"));
40
1
}
41

            
42
#[test]
43
1
fn is_lambda_literal_classifies_the_head() {
44
1
    let table = SymbolTable::with_builtins();
45
1
    assert!(is_lambda_literal(&table, &form("(lambda (x) x)")));
46
1
    assert!(is_lambda_literal(&table, &form("(function car)")));
47
1
    assert!(!is_lambda_literal(&table, &form("(car (list 1))")));
48
1
}
49

            
50
#[test]
51
1
fn is_lambda_head_accepts_only_spelled_out_lambdas() {
52
1
    let table = SymbolTable::with_builtins();
53
1
    assert!(is_lambda_head(&table, &form("(lambda (x) x)")));
54
1
    assert!(is_lambda_head(&table, &form("(function (lambda (x) x))")));
55
1
    assert!(!is_lambda_head(&table, &form("(function car)")));
56
1
    assert!(!is_lambda_head(&table, &form("(function (car))")));
57
1
    assert!(!is_lambda_head(&table, &form("(mk 1)")));
58
1
    assert!(!is_lambda_head(&table, &Expr::Nil));
59
1
}
60

            
61
6
fn closure_global_table(ctx: &mut CompileContext) -> SymbolTable {
62
6
    let sig = ctx
63
6
        .intern_closure_signature(&[], WasmType::Ratio)
64
6
        .expect("closure sig");
65
6
    let mut table = SymbolTable::with_builtins_for_wasm();
66
6
    let global = Symbol::new("F", SymbolKind::Variable)
67
6
        .with_value(Expr::WasmGlobal(0, WasmType::Closure(sig)));
68
6
    table.define(global);
69
6
    table
70
6
}
71

            
72
type Hoist = fn(
73
    &mut CompileContext,
74
    &mut FunctionEmitter,
75
    &mut SymbolTable,
76
    &[Expr],
77
) -> crate::error::Result<Option<Vec<Expr>>>;
78

            
79
4
fn hoisted_function(ctx: &mut CompileContext, hoist: Hoist, args: &[&str]) -> Expr {
80
4
    let mut table = closure_global_table(ctx);
81
4
    let mut emit = FunctionEmitter::new();
82
8
    let forms: Vec<Expr> = args.iter().map(|arg| form(arg)).collect();
83
4
    let hoisted = hoist(ctx, &mut emit, &mut table, &forms)
84
4
        .expect("hoists")
85
4
        .expect("a live operand");
86
4
    hoisted[0].clone()
87
4
}
88

            
89
#[test]
90
1
fn a_closure_global_stays_a_name_when_the_later_operands_run_nothing() {
91
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
92
1
    assert_eq!(
93
1
        hoisted_function(&mut ctx, hoist_call_function, &["f", "'(1 2)"]),
94
1
        form("f")
95
    );
96
1
}
97

            
98
#[test]
99
1
fn a_closure_global_is_read_into_a_local_before_a_later_effect() {
100
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
101
1
    let function = hoisted_function(
102
1
        &mut ctx,
103
1
        hoist_call_function,
104
1
        &["f", "(progn (print 1) nil)"],
105
1
    );
106
1
    assert!(matches!(function, Expr::WasmLocal(_, WasmType::Closure(_))));
107
1
}
108

            
109
#[test]
110
1
fn a_lambda_literal_is_not_pinned() {
111
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
112
1
    let function = hoisted_function(
113
1
        &mut ctx,
114
1
        hoist_call_function,
115
1
        &["(lambda (x) x)", "(progn (print 1) nil)"],
116
1
    );
117
1
    assert!(matches!(function, Expr::List(_)));
118
1
}
119

            
120
#[test]
121
1
fn a_pinned_closure_keeps_the_recorded_body() {
122
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
123
1
    let mut table = closure_global_table(&mut ctx);
124
1
    let params = LambdaParams::simple(vec!["x".to_string()]);
125
1
    table.record_closure_body(Place::Global(0), params.clone(), Expr::Nil);
126
1
    let mut emit = FunctionEmitter::new();
127
1
    let forms = [form("f"), form("(progn (print 1) nil)")];
128
1
    let hoisted = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms)
129
1
        .expect("hoists")
130
1
        .expect("a live operand");
131
1
    let (copy, _) = hoisted[0].place().expect("a local copy");
132
1
    assert_eq!(table.closure_body(copy), Some(&(params, Expr::Nil)));
133
1
}
134

            
135
#[test]
136
1
fn a_higher_order_native_reads_a_closure_global_even_when_the_rest_is_pure() {
137
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
138
1
    let function = hoisted_function(&mut ctx, hoist_function_arg, &["f", "'(1 2)"]);
139
1
    assert!(matches!(function, Expr::WasmLocal(_, WasmType::Closure(_))));
140
1
}
141

            
142
#[test]
143
1
fn hoisting_a_hoisted_function_adds_no_second_local() {
144
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
145
1
    let mut table = closure_global_table(&mut ctx);
146
1
    let mut emit = FunctionEmitter::new();
147
1
    let forms = [form("f"), form("'(1 2)")];
148
1
    let first = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms)
149
1
        .expect("hoists")
150
1
        .expect("a live operand");
151
1
    let second = hoist_function_arg(&mut ctx, &mut emit, &mut table, &first)
152
1
        .expect("hoists")
153
1
        .expect("a live operand");
154
1
    assert_eq!(first[0], second[0]);
155
1
}
156

            
157
2
fn table_with_factory() -> SymbolTable {
158
2
    let mut table = SymbolTable::with_builtins_for_wasm();
159
2
    let params = LambdaParams::simple(vec!["A".to_string()]);
160
2
    let body = form("(lambda (x) (+ x a))");
161
2
    table.define(
162
2
        Symbol::new("MK", SymbolKind::Function).with_function(Expr::Lambda(params, Box::new(body))),
163
2
    );
164
2
    table
165
2
}
166

            
167
#[test]
168
1
fn a_closure_factory_call_is_computed_even_with_constant_arguments() {
169
1
    let table = table_with_factory();
170
1
    assert!(is_computed(&table, &form("(mk 3)")).expect("scan"));
171
1
}
172

            
173
#[test]
174
1
fn a_factory_designator_is_lowered_to_a_lambda_over_a_hidden_variable() {
175
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
176
1
    let mut table = table_with_factory();
177
1
    let mut emit = FunctionEmitter::new();
178
1
    let forms = [form("(mk 3)"), form("'(1 2)")];
179
1
    let hoisted = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms)
180
1
        .expect("hoists")
181
1
        .expect("a live operand");
182
1
    let Expr::Lambda(_, body) = &hoisted[0] else {
183
        panic!("a lambda, got {:?}", hoisted[0]);
184
    };
185
1
    let Expr::List(scope) = body.as_ref() else {
186
        panic!("a LET scope, got {body:?}");
187
    };
188
1
    assert_eq!(scope[0], Expr::symbol("LET"));
189
1
}
190

            
191
#[test]
192
1
fn a_quoted_name_resolves_to_the_global_function_a_labels_one_hides() {
193
1
    let mut table = SymbolTable::new();
194
1
    let global = Symbol::new("F", SymbolKind::Function).with_function(Expr::Lambda(
195
1
        LambdaParams::simple(Vec::new()),
196
1
        Box::new(Expr::T),
197
1
    ));
198
1
    let expected = global.function().cloned();
199
1
    table.define(global);
200
1
    table.define(Symbol::new("F", SymbolKind::Function).local_function());
201
1
    let Expr::Datum(named) = resolve_designator(&table, &form("(quote f)")).expect("resolved")
202
    else {
203
        panic!("a designator datum");
204
    };
205
1
    let Expr::Symbol(alias) = *named else {
206
        panic!("an alias name");
207
    };
208
1
    assert_eq!(
209
1
        table.lookup(&alias).and_then(|s| s.function().cloned()),
210
1
        expected
211
    );
212
1
}
213

            
214
#[test]
215
1
fn an_unhidden_quoted_name_resolves_to_its_datum() {
216
1
    let table = SymbolTable::new();
217
1
    let resolved = resolve_designator(&table, &form("'car")).expect("resolved");
218
1
    assert_eq!(resolved, Expr::Datum(Box::new(Expr::symbol("CAR"))));
219
1
}
220

            
221
#[test]
222
1
fn an_operand_runs_nothing_only_when_nothing_in_it_runs() {
223
1
    let mut table = SymbolTable::with_builtins();
224
1
    let succ = Expr::Lambda(
225
1
        LambdaParams::simple(vec!["X".to_string()]),
226
1
        Box::new(form("(+ x 1)")),
227
1
    );
228
1
    table.define(Symbol::new("SUCC", SymbolKind::Function).with_function(succ));
229
1
    for (source, quiet) in [
230
1
        ("(+ 1 2)", true),
231
1
        ("(setf n 9)", false),
232
1
        ("(succ 2)", true),
233
1
        ("(succ (setf n 9))", false),
234
1
        ("(lambda (y) y)", true),
235
1
    ] {
236
5
        assert_eq!(runs_nothing(&table, &form(source)), quiet, "{source}");
237
    }
238
1
}
239

            
240
#[test]
241
1
fn a_macro_is_no_function_designator() {
242
1
    let mut table = SymbolTable::with_builtins();
243
1
    let body = Expr::Lambda(LambdaParams::simple(Vec::new()), Box::new(Expr::Nil));
244
1
    table.define(Symbol::new("DBL", SymbolKind::Macro).with_function(body.clone()));
245
1
    table.define(Symbol::new("TWICE", SymbolKind::Function).with_function(body));
246
1
    let err = reject_non_function(&table, "DBL").expect_err("a macro");
247
1
    assert_eq!(
248
1
        err.to_string(),
249
1
        "Compile error: DBL is a macro, not a function"
250
    );
251
1
    assert!(reject_non_function(&table, "TWICE").is_ok());
252
1
    let builtin = reject_non_function(&table, "MAPCAR").expect_err("a builtin macro");
253
1
    assert_eq!(
254
1
        builtin.to_string(),
255
1
        "Compile error: MAPCAR cannot be used as a function value yet"
256
    );
257
1
    assert!(resolve_designator(&table, &form("'dbl")).is_err());
258
1
    assert!(resolve_designator(&table, &form("'twice")).is_ok());
259
1
}
260

            
261
#[test]
262
1
fn one_rule_names_what_is_no_function_designator() {
263
1
    let table = SymbolTable::with_builtins();
264
1
    for (name, message) in [
265
1
        ("IF", "IF is a special operator, not a function"),
266
1
        ("LET", "LET is a special operator, not a function"),
267
1
        ("AND", "AND is a macro, not a function"),
268
1
        ("WHEN", "WHEN is a macro, not a function"),
269
1
        ("MAPC", "MAPC cannot be used as a function value yet"),
270
1
    ] {
271
5
        let rejected = reject_non_function(&table, name)
272
5
            .err()
273
5
            .map(|e| e.to_string());
274
5
        assert_eq!(
275
5
            rejected,
276
5
            Some(format!("Compile error: {message}")),
277
            "{name}"
278
        );
279
    }
280
1
    for name in ["CAR", "+", "FUNCALL", "APPLY", "EVAL", "ERROR"] {
281
6
        assert!(reject_non_function(&table, name).is_ok(), "{name}");
282
    }
283
1
}
284

            
285
#[test]
286
1
fn a_function_form_of_a_built_in_resolves_as_its_quoted_name() {
287
1
    let table = SymbolTable::with_builtins();
288
1
    let resolved = resolve_designator(&table, &form("#'car")).expect("a native");
289
1
    assert_eq!(
290
1
        resolved,
291
1
        resolve_designator(&table, &form("'car")).expect("quoted")
292
    );
293
1
}
294

            
295
2
fn any_local_table() -> SymbolTable {
296
2
    let mut table = SymbolTable::with_builtins_for_wasm();
297
    let local =
298
2
        Symbol::new("G", SymbolKind::Variable).with_value(Expr::WasmLocal(0, WasmType::AnyRef));
299
2
    table.define(local);
300
2
    table
301
2
}
302

            
303
#[test]
304
1
fn a_higher_order_native_refuses_an_any_function_operand() {
305
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
306
1
    let mut emit = FunctionEmitter::new();
307
1
    let err = hoist_function_arg(&mut ctx, &mut emit, &mut any_local_table(), &[form("g")])
308
1
        .expect_err("refused");
309
1
    assert!(err.to_string().contains("call it through (lambda"), "{err}");
310
1
}
311

            
312
#[test]
313
1
fn a_call_keeps_an_any_function_operand_for_the_run_time_check() {
314
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
315
1
    let mut emit = FunctionEmitter::new();
316
1
    let hoisted = hoist_call_function(&mut ctx, &mut emit, &mut any_local_table(), &[form("g")])
317
1
        .expect("hoists")
318
1
        .expect("a live operand");
319
1
    assert_eq!(hoisted[0], form("g"));
320
1
}
321

            
322
#[test]
323
1
fn a_computed_any_operand_is_held_in_a_local() {
324
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
325
1
    let mut emit = FunctionEmitter::new();
326
1
    let mut table = SymbolTable::with_builtins_for_wasm();
327
1
    let operand = designator_operand(
328
1
        &mut ctx,
329
1
        &mut emit,
330
1
        &mut table,
331
1
        &form("(car (list (lambda () 1) nil))"),
332
1
    )
333
1
    .expect("lowers");
334
1
    assert!(
335
1
        matches!(operand, Expr::WasmLocal(_, WasmType::AnyRef)),
336
        "{operand:?}"
337
    );
338
1
}
339

            
340
#[test]
341
1
fn a_raising_function_operand_ends_the_call() {
342
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
343
1
    let mut emit = FunctionEmitter::new();
344
1
    let mut table = SymbolTable::with_builtins_for_wasm();
345
1
    let forms = [form("(error 'x \"m\")"), form("'(1 2)")];
346
1
    let hoisted = hoist_function_arg(&mut ctx, &mut emit, &mut table, &forms).expect("hoists");
347
1
    assert_eq!(hoisted, None);
348
1
}