1
//! Self-hosted test framework: `DEFTEST`, `ASSERT-EQUAL`, `RUN-TESTS`.
2
//!
3
//! `DEFTEST` registers a named body in the symbol table; `ASSERT-EQUAL`
4
//! signals a Compile error on mismatch (caught by `RUN-TESTS`); the
5
//! runner iterates the test registry and produces a multi-line String
6
//! summary with pass/fail counts and per-failure detail.
7

            
8
use crate::ast::{Expr, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{compile_expr, eval_value, format_expr};
12
use crate::compiler::native::same_datum;
13
use crate::error::{Error, Result};
14
use crate::reserved::reject_reserved;
15
use crate::runtime::SymbolTable;
16

            
17
use super::compile_static_result_for_stack;
18

            
19
/// `(deftest NAME body...)` registers a test in the symbol table.
20
/// `RUN-TESTS` later iterates the registry and evaluates each body
21
/// once, counting passes / failures. The test body is wrapped in
22
/// `PROGN` so multi-form bodies behave correctly.
23
12120
pub(super) fn deftest(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
24
12120
    if args.len() < 2 {
25
208
        return Err(Error::Compile(
26
208
            "DEFTEST requires a name and at least one body form".to_string(),
27
208
        ));
28
11912
    }
29
11912
    let name = match &args[0] {
30
11703
        Expr::Symbol(s) => reject_reserved(symbols, s).map(|()| s.clone())?,
31
        other => {
32
209
            return Err(Error::Compile(format!(
33
209
                "DEFTEST: expected symbol for test name, got {}",
34
209
                format_expr(other)
35
209
            )));
36
        }
37
    };
38
11700
    let body = Expr::body(&args[1..]);
39
11700
    symbols.register_test(&name, body);
40
11700
    Ok(Expr::quoted(Expr::Symbol(name)))
41
12120
}
42

            
43
3124
pub(super) fn compile_deftest(
44
3124
    ctx: &mut CompileContext,
45
3124
    emit: &mut FunctionEmitter,
46
3124
    symbols: &mut SymbolTable,
47
3124
    args: &[Expr],
48
3124
) -> Result<()> {
49
3124
    let result = deftest(symbols, args)?;
50
2708
    compile_expr(ctx, emit, symbols, &result)
51
3124
}
52

            
53
/// `(assert-equal A B)` evaluates both sides; if the resulting
54
/// `Expr` values aren't `==` it signals a Compile error. Inside a
55
/// test, that error is caught by `RUN-TESTS` and counted as a
56
/// failure; outside a test it propagates as any other compile
57
/// error.
58
12292
pub(super) fn assert_equal(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
59
12292
    if args.len() != 2 {
60
208
        return Err(Error::Arity {
61
208
            name: "ASSERT-EQUAL".to_string(),
62
208
            expected: 2,
63
208
            actual: args.len(),
64
208
        });
65
12084
    }
66
12084
    let a = eval_value(symbols, &args[0])?;
67
12084
    let b = eval_value(symbols, &args[1])?;
68
12084
    if same_datum(&a, &b, "ASSERT-EQUAL")? {
69
10824
        Ok(Expr::Nil)
70
    } else {
71
1256
        Err(Error::Compile(format!(
72
1256
            "assertion failed: {} != {}",
73
1256
            format_expr(&a),
74
1256
            format_expr(&b)
75
1256
        )))
76
    }
77
12292
}
78

            
79
834
pub(super) fn compile_assert_equal(
80
834
    ctx: &mut CompileContext,
81
834
    emit: &mut FunctionEmitter,
82
834
    symbols: &mut SymbolTable,
83
834
    args: &[Expr],
84
834
) -> Result<()> {
85
834
    let result = assert_equal(symbols, args)?;
86
416
    compile_expr(ctx, emit, symbols, &result)
87
834
}
88

            
89
/// `(run-tests)` evaluates every test registered via `DEFTEST` and
90
/// returns a multi-line String summary: `ran N tests: P passed, F
91
/// failed' followed by per-failure detail lines.
92
2511
pub(super) fn run_tests(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
93
2511
    if !args.is_empty() {
94
209
        return Err(Error::Arity {
95
209
            name: "RUN-TESTS".to_string(),
96
209
            expected: 0,
97
209
            actual: args.len(),
98
209
        });
99
2302
    }
100
2302
    let tests = symbols.tests();
101
2302
    let mut pass = 0usize;
102
2302
    let mut failures: Vec<String> = Vec::new();
103
2302
    for (name, body) in &tests {
104
11038
        match eval_value(symbols, body) {
105
10199
            Ok(_) => pass += 1,
106
839
            Err(err) => failures.push(format!("  {name}: {err}")),
107
        }
108
    }
109
2302
    let total = tests.len();
110
2302
    let fail = failures.len();
111
2302
    let mut lines = vec![format!("ran {total} tests: {pass} passed, {fail} failed")];
112
2302
    if !failures.is_empty() {
113
839
        lines.push("failures:".to_string());
114
839
        lines.extend(failures);
115
1463
    }
116
2302
    Ok(Expr::String(lines.join("\n")))
117
2511
}
118

            
119
2088
pub(super) fn compile_run_tests(
120
2088
    ctx: &mut CompileContext,
121
2088
    emit: &mut FunctionEmitter,
122
2088
    symbols: &mut SymbolTable,
123
2088
    args: &[Expr],
124
2088
) -> Result<()> {
125
2088
    let result = run_tests(symbols, args)?;
126
1880
    compile_expr(ctx, emit, symbols, &result)
127
2088
}
128

            
129
8991
pub(super) fn compile_deftest_for_stack(
130
8991
    ctx: &mut CompileContext,
131
8991
    emit: &mut FunctionEmitter,
132
8991
    symbols: &mut SymbolTable,
133
8991
    args: &[Expr],
134
8991
) -> Result<WasmType> {
135
8991
    let result = deftest(symbols, args)?;
136
8988
    compile_static_result_for_stack(ctx, emit, symbols, &result)
137
8991
}
138

            
139
417
pub(super) fn compile_assert_equal_for_stack(
140
417
    ctx: &mut CompileContext,
141
417
    emit: &mut FunctionEmitter,
142
417
    symbols: &mut SymbolTable,
143
417
    args: &[Expr],
144
417
) -> Result<WasmType> {
145
417
    let result = assert_equal(symbols, args)?;
146
208
    compile_static_result_for_stack(ctx, emit, symbols, &result)
147
417
}
148

            
149
420
pub(super) fn compile_run_tests_for_stack(
150
420
    ctx: &mut CompileContext,
151
420
    emit: &mut FunctionEmitter,
152
420
    symbols: &mut SymbolTable,
153
420
    args: &[Expr],
154
420
) -> Result<WasmType> {
155
420
    let result = run_tests(symbols, args)?;
156
420
    compile_static_result_for_stack(ctx, emit, symbols, &result)
157
420
}