1
//! Unit tests for the runtime-type inference used to promote the
2
//! body's tail value when a binding form has side effects. Each
3
//! variant must map to the wasm type the codegen path emits;
4
//! otherwise upstream consumers downcast to the wrong shape and the
5
//! wasm becomes invalid.
6

            
7
use crate::ast::{Expr, Fraction, Number, PairElement, WasmType};
8

            
9
use super::infer::infer_runtime_type;
10
use crate::reader::Reader;
11

            
12
/// `infer_runtime_type` is the fallback for promoting a let body's
13
/// tail value to a runtime type when the body has side-effects.
14
#[test]
15
1
fn infer_runtime_type_integer_is_index_fraction_is_scalar() {
16
    // ADR-0028: an integer literal defaults to Index (I32); a fractional
17
    // literal is a dimensionless Scalar (Ratio). Mirrors `classify_stack_type`.
18
1
    assert_eq!(
19
1
        infer_runtime_type(&Expr::Number(Number::Index(0))),
20
1
        WasmType::I32
21
    );
22
1
    assert_eq!(
23
1
        infer_runtime_type(&Expr::Number(Number::Scalar(Fraction::new(1, 2)))),
24
1
        WasmType::Ratio
25
    );
26
1
}
27

            
28
#[test]
29
1
fn infer_runtime_type_lambda_is_anyref() {
30
1
    let lambda = Expr::Lambda(
31
1
        crate::ast::LambdaParams::simple(vec!["X".to_string()]),
32
1
        Box::new(Expr::Symbol("X".to_string())),
33
1
    );
34
1
    assert_eq!(infer_runtime_type(&lambda), WasmType::AnyRef);
35
1
}
36

            
37
#[test]
38
1
fn infer_runtime_type_bool_is_bool() {
39
    // Bool/nil literals lower to `WasmType::Bool` on the stack, so the let-body
40
    // tail inference must mirror that (sizing the binding local to match the
41
    // value codegen pushes — see the WasmType::Bool serialization split).
42
1
    assert_eq!(infer_runtime_type(&Expr::T), WasmType::Bool);
43
1
    assert_eq!(infer_runtime_type(&Expr::Nil), WasmType::Bool);
44
1
}
45

            
46
/// A let body whose tail is a String literal must report
47
/// `StringRef`. The previous hardcoded `PairRef(I32)` fallback
48
/// made `(cons (let ...) nil)` see a pair-of-pair and refuse
49
/// at compile time.
50
#[test]
51
1
fn infer_runtime_type_string_is_stringref() {
52
1
    assert_eq!(
53
1
        infer_runtime_type(&Expr::String("hi".into())),
54
1
        WasmType::StringRef,
55
    );
56
1
}
57

            
58
/// `WasmLocal(idx, ty)` carries its wasm type directly. Promoting
59
/// must surface that type unchanged.
60
#[test]
61
1
fn infer_runtime_type_wasm_local_passes_type_through() {
62
1
    assert_eq!(
63
1
        infer_runtime_type(&Expr::WasmLocal(5, WasmType::Ratio)),
64
1
        WasmType::Ratio,
65
    );
66
1
    assert_eq!(
67
1
        infer_runtime_type(&Expr::WasmLocal(7, WasmType::StringRef)),
68
1
        WasmType::StringRef,
69
    );
70
1
}
71

            
72
/// `WasmRuntime(ty)` carries its wasm type directly. Same path
73
/// as `WasmLocal` from the inference perspective.
74
#[test]
75
1
fn infer_runtime_type_wasm_runtime_passes_type_through() {
76
1
    assert_eq!(
77
1
        infer_runtime_type(&Expr::WasmRuntime(WasmType::Commodity)),
78
1
        WasmType::Commodity,
79
    );
80
1
}
81

            
82
2
fn dolist_accumulator_type(list: &str) -> Option<WasmType> {
83
2
    let body = crate::Reader::parse_expr(&format!("(dolist (y {list}) (setf acc (cons y acc)))"))
84
2
        .expect("parse");
85
2
    let symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
86
2
    super::infer::assigned_var_runtime_type(&[body], "ACC", &Expr::Nil, &symbols).expect("infer")
87
2
}
88

            
89
#[test]
90
1
fn a_dolist_over_a_constant_list_types_the_loop_var_for_the_accumulator() {
91
1
    assert_eq!(
92
1
        dolist_accumulator_type("'(1 2 3)"),
93
1
        Some(WasmType::PairRef(PairElement::I32))
94
    );
95
1
    assert_eq!(
96
1
        dolist_accumulator_type("'(1/2 3/4)"),
97
1
        Some(WasmType::PairRef(PairElement::Ratio))
98
    );
99
1
}
100

            
101
7
fn accumulator_type_of(source: &str, runtime_n: bool) -> Option<WasmType> {
102
7
    accumulator_result_of(source, runtime_n).expect("infer")
103
7
}
104

            
105
10
fn accumulator_result_of(source: &str, runtime_n: bool) -> crate::error::Result<Option<WasmType>> {
106
10
    let body = crate::Reader::parse_expr(source).expect("parse");
107
10
    let mut symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
108
10
    if runtime_n {
109
2
        symbols.define(
110
2
            crate::runtime::Symbol::new("N", crate::runtime::SymbolKind::Variable)
111
2
                .with_value(Expr::WasmRuntime(WasmType::I32)),
112
2
        );
113
8
    }
114
10
    super::infer::assigned_var_runtime_type(&[body], "ACC", &Expr::Nil, &symbols)
115
10
}
116

            
117
#[test]
118
1
fn an_unrolled_loop_variable_is_bound_as_its_datum() {
119
1
    let ratio = Some(WasmType::PairRef(PairElement::Ratio));
120
1
    assert_eq!(
121
1
        accumulator_type_of(
122
1
            "(do ((i 1/1 (+ i 1/1))) ((= i 4/1)) (setf acc (cons (* i 1/2) acc)))",
123
1
            false
124
1
        ),
125
1
        ratio
126
    );
127
1
    assert_eq!(
128
1
        accumulator_type_of(
129
1
            "(dolist (y '(1/1 2/1 3/1)) (setf acc (cons (* y 1/2) acc)))",
130
1
            false
131
1
        ),
132
1
        ratio
133
    );
134
1
}
135

            
136
#[test]
137
1
fn an_unrolled_index_variable_beside_a_fraction_is_a_mix() {
138
1
    for source in [
139
1
        "(do ((i 1 (+ i 1))) ((= i 4)) (setf acc (cons (* i 1/2) acc)))",
140
1
        "(dolist (y '(1 2 3)) (setf acc (cons (* y 1/2) acc)))",
141
1
    ] {
142
2
        let err = accumulator_result_of(source, false).expect_err("a mix, CL a list of 1/2 steps");
143
2
        assert!(
144
2
            err.to_string()
145
2
                .contains("* cannot mix an index (count) with a scalar"),
146
            "{source}: {err}"
147
        );
148
    }
149
1
}
150

            
151
#[test]
152
1
fn a_runtime_loop_variable_is_bound_as_a_runtime_value() {
153
1
    assert_eq!(
154
1
        accumulator_type_of(
155
1
            "(do ((i 1 (+ i 1))) ((= i n)) (setf acc (cons (* (index->scalar i) 1/2) acc)))",
156
1
            true
157
1
        ),
158
1
        Some(WasmType::PairRef(PairElement::Ratio))
159
    );
160
1
}
161

            
162
#[test]
163
1
fn a_runtime_index_loop_variable_beside_a_fraction_is_a_mix() {
164
1
    let err = accumulator_result_of(
165
1
        "(do ((i 1 (+ i 1))) ((= i n)) (setf acc (cons (* i 1/2) acc)))",
166
1
        true,
167
1
    )
168
1
    .expect_err("a mix");
169
1
    assert!(
170
1
        err.to_string()
171
1
            .contains("* cannot mix an index (count) with a scalar"),
172
        "{err}"
173
    );
174
1
}
175

            
176
#[test]
177
1
fn a_list_store_of_the_accumulator_itself_is_a_nested_list() {
178
1
    assert_eq!(
179
1
        accumulator_type_of("(dolist (x (list 1 2)) (setf acc (list acc x)))", false),
180
1
        Some(WasmType::PairRef(PairElement::AnyRef))
181
    );
182
1
}
183

            
184
#[test]
185
1
fn an_inner_binding_of_the_target_shadows_the_outer_one() {
186
1
    let body = crate::Reader::parse_expr("(dolist (x (list 1 2)) (setf acc (list acc x)))")
187
1
        .expect("parse");
188
1
    let mut symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
189
1
    symbols.define(
190
1
        crate::runtime::Symbol::new("ACC", crate::runtime::SymbolKind::Variable)
191
1
            .with_value(Expr::Number(Number::Index(5.into()))),
192
1
    );
193
1
    assert_eq!(
194
1
        super::infer::assigned_var_runtime_type(&[body], "ACC", &Expr::Nil, &symbols)
195
1
            .expect("infer"),
196
1
        Some(WasmType::PairRef(PairElement::AnyRef))
197
    );
198
1
}
199

            
200
#[test]
201
1
fn only_a_nil_initialised_accumulator_is_seen_as_a_list() {
202
1
    let body = crate::Reader::parse_expr("(dolist (x (list 1 2)) (setf acc (list acc x)))")
203
1
        .expect("parse");
204
1
    let symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
205
2
    let infer = |init: &Expr| {
206
2
        super::infer::assigned_var_runtime_type(std::slice::from_ref(&body), "ACC", init, &symbols)
207
2
            .expect("infer")
208
2
    };
209
1
    assert_eq!(
210
1
        infer(&Expr::Nil),
211
1
        Some(WasmType::PairRef(PairElement::AnyRef))
212
    );
213
1
    assert_eq!(
214
1
        infer(&Expr::Number(Number::Index(0.into()))),
215
1
        Some(WasmType::I32)
216
    );
217
1
}
218

            
219
#[test]
220
1
fn differing_stores_widen_the_accumulator_and_agreeing_ones_do_not() {
221
1
    let any = Some(WasmType::PairRef(PairElement::AnyRef));
222
1
    assert_eq!(
223
1
        accumulator_type_of(
224
1
            "(dolist (y '(1 2 3)) (setf acc (cons y acc)) (setf acc (cons 1/2 acc)))",
225
1
            false
226
1
        ),
227
1
        any
228
    );
229
1
    assert_eq!(
230
1
        accumulator_type_of(
231
1
            "(dolist (y '(1 2 3)) (if (> y 2) (setf acc (cons 1/2 acc)) (setf acc (cons y acc))))",
232
1
            false
233
1
        ),
234
1
        any
235
    );
236
1
    assert_eq!(
237
1
        accumulator_type_of(
238
1
            "(dolist (y '(1 2)) (setf acc (cons y acc)) (setf acc (cons y acc)))",
239
1
            false
240
1
        ),
241
1
        Some(WasmType::PairRef(PairElement::I32))
242
    );
243
1
}
244

            
245
#[test]
246
1
fn spec_name_reads_the_variable_of_every_spec_shape() {
247
7
    let read = |text: &str| {
248
7
        let form = Reader::parse(text).expect("parses").exprs.remove(0);
249
7
        super::spec_name(&form).map(str::to_string)
250
7
    };
251
1
    assert_eq!(read("x").as_deref(), Some("X"));
252
1
    assert_eq!(read("(x 1)").as_deref(), Some("X"));
253
1
    assert_eq!(read("((:a x) 1)").as_deref(), Some("X"));
254
1
    assert_eq!(read("((:a x))").as_deref(), Some("X"));
255
1
    assert_eq!(read("((a x) 1)"), None);
256
1
    assert_eq!(read("()"), None);
257
1
    assert_eq!(read("1"), None);
258
1
}
259

            
260
#[test]
261
1
fn a_nil_binder_stored_a_constant_list_loop_variable_takes_its_element_type() {
262
3
    let store = |list: &str| {
263
3
        let body = crate::Reader::parse_expr(&format!("(dolist (x {list}) (setf best x))"))
264
3
            .expect("parse");
265
3
        let symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
266
3
        super::infer::assigned_var_runtime_type(&[body], "BEST", &Expr::Nil, &symbols)
267
3
            .expect("infer")
268
3
    };
269
1
    assert_eq!(store("'(3 1 2)"), Some(WasmType::I32));
270
1
    assert_eq!(store("(list 3 1 2)"), Some(WasmType::I32));
271
1
    assert_eq!(store("'(3 \"a\")"), Some(WasmType::AnyRef));
272
1
}
273

            
274
#[test]
275
1
fn a_nil_binder_stored_a_compound_form_takes_the_forms_type() {
276
4
    let store = |rhs: &str| {
277
4
        let body = crate::Reader::parse_expr(&format!("(dolist (x '(3 1 2)) (setf best {rhs}))"))
278
4
            .expect("parse");
279
4
        let symbols = crate::runtime::SymbolTable::with_builtins_for_wasm();
280
4
        super::infer::assigned_var_runtime_type(&[body], "BEST", &Expr::Nil, &symbols)
281
4
            .expect("infer")
282
4
    };
283
1
    assert_eq!(store("(+ x 0)"), Some(WasmType::I32));
284
1
    assert_eq!(store("(* (index->scalar x) 1/2)"), Some(WasmType::Ratio));
285
1
    assert_eq!(store("(car (list x))"), Some(WasmType::I32));
286
1
    assert_eq!(store("nil"), Some(WasmType::Bool));
287
1
}