1
//! Cross-module tests for the iteration family. Span `do_loop` and
2
//! `common` because the form-result-type inference is exercised end-
3
//! to-end via `do_form` / `do_star_form`. Keeping the tests in a
4
//! sibling module instead of either sub-module avoids re-exporting
5
//! the private inference helpers just to test them.
6

            
7
use crate::ast::{Expr, Fraction, Number, PairElement, WasmType};
8
use crate::error::Result;
9
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
10

            
11
use super::common::body_yields_runtime;
12
use super::do_form::do_form;
13
use super::do_star_form::do_star_form;
14
use super::sizing::{infer_compiled_type, infer_wasm_type, var_type_hint};
15

            
16
/// Constructs `(do ((i 0 (+ i 1))) ((= i N) result) (setf result
17
/// (cons cons_car result)))` — the canonical tag-sync pattern.
18
/// `N` is a runtime symbol forcing the runtime path; `result` is a
19
/// pre-bound accumulator that the body builds via setf. The
20
/// caller varies `cons_car` to exercise the static PairElement
21
/// inference that the codegen path actually emits for the
22
/// accumulator.
23
3
fn do_with_setf_cons_car(cons_car: Expr) -> Vec<Expr> {
24
3
    let i_var = Expr::List(vec![
25
3
        Expr::Symbol("i".into()),
26
3
        Expr::Number(Number::Index(0)),
27
3
        Expr::List(vec![
28
3
            Expr::Symbol("+".into()),
29
3
            Expr::Symbol("i".into()),
30
3
            Expr::Number(Number::Index(1)),
31
3
        ]),
32
3
    ]);
33
3
    let end_clause = Expr::List(vec![
34
3
        Expr::List(vec![
35
3
            Expr::Symbol("=".into()),
36
3
            Expr::Symbol("i".into()),
37
3
            Expr::Symbol("N".into()),
38
3
        ]),
39
3
        Expr::Symbol("result".into()),
40
3
    ]);
41
3
    let body_setf = Expr::List(vec![
42
3
        Expr::Symbol("SETF".into()),
43
3
        Expr::Symbol("result".into()),
44
3
        Expr::List(vec![
45
3
            Expr::Symbol("CONS".into()),
46
3
            cons_car,
47
3
            Expr::Symbol("result".into()),
48
3
        ]),
49
3
    ]);
50
3
    vec![Expr::List(vec![i_var]), end_clause, body_setf]
51
3
}
52

            
53
3
fn symbols_with_runtime_n_and_acc() -> SymbolTable {
54
3
    let mut s = SymbolTable::with_builtins();
55
3
    s.define(Symbol::new("N", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::I32)));
56
3
    s.define(Symbol::new("result", SymbolKind::Variable).with_value(Expr::Nil));
57
3
    s
58
3
}
59

            
60
/// Bug parity with `do_form`: the accumulator's CONS car is the loop var
61
/// `i`, an integer DO* var. After ADR-0028 an integer DO var is a runtime
62
/// Index (I32), so codegen emits a `pair<i32>` (i31-boxed car); `do_star_form`'s
63
/// static return type must match. Resolving `i` to its const `0` init would
64
/// type it as Ratio (the numeric-literal cell slot) and make a downstream
65
/// `dolist` / `car` consumer downcast the wrong way and trap at runtime.
66
#[test]
67
1
fn do_star_runtime_result_matches_index_cons_car() {
68
1
    let mut symbols = symbols_with_runtime_n_and_acc();
69
1
    let args = do_with_setf_cons_car(Expr::Symbol("i".into()));
70
1
    let result = do_star_form(&mut symbols, &args).unwrap();
71
1
    assert_eq!(
72
1
        result,
73
1
        Expr::WasmRuntime(WasmType::PairRef(PairElement::I32)),
74
        "do* with body `(setf result (cons i result))` where i is an \
75
         integer (Index) DO var must report PairRef(I32)"
76
    );
77
1
}
78

            
79
/// Same harness, Bool car. A bool rides its own `PairElement::Bool` slot
80
/// (shares I32's i31-boxed car but serializes as Nil/Bool, not Number), so
81
/// the accumulator's static type is `PairRef(Bool)`.
82
#[test]
83
1
fn do_star_runtime_result_matches_bool_cons_car() {
84
1
    let mut symbols = symbols_with_runtime_n_and_acc();
85
1
    let args = do_with_setf_cons_car(Expr::T);
86
1
    let result = do_star_form(&mut symbols, &args).unwrap();
87
1
    assert_eq!(
88
1
        result,
89
1
        Expr::WasmRuntime(WasmType::PairRef(PairElement::Bool))
90
    );
91
1
}
92

            
93
/// Same shape via plain `do` — locks in the `do_form` infer_env fix. The CONS
94
/// car is the integer DO var `i` (runtime Index → I32 cell), so the result is
95
/// `PairRef(I32)`, matching what the runtime codegen emits for `(cons i …)`.
96
#[test]
97
1
fn do_runtime_result_matches_index_cons_car() {
98
1
    let mut symbols = symbols_with_runtime_n_and_acc();
99
1
    let args = do_with_setf_cons_car(Expr::Symbol("i".into()));
100
1
    let result = do_form(&mut symbols, &args).unwrap();
101
1
    assert_eq!(
102
1
        result,
103
1
        Expr::WasmRuntime(WasmType::PairRef(PairElement::I32))
104
    );
105
1
}
106

            
107
/// A COUNTING `do` whose result form is a plain integer accumulator (not a
108
/// cons-built list) must report `I32`, not `PairRef`. Hard-coding `PairRef`
109
/// mistyped `(= (count …) 0)` as "= expects numeric, got pair". Mirrors codegen
110
/// `compile_do_runtime_for_stack` → `compile_for_stack(n)` (the let-promoted
111
/// integer local → I32).
112
#[test]
113
1
fn do_counting_result_is_index_not_pair() {
114
1
    let mut symbols = SymbolTable::with_builtins();
115
1
    symbols.define(
116
1
        Symbol::new("N", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::I32)),
117
1
    );
118
1
    symbols
119
1
        .define(Symbol::new("n", SymbolKind::Variable).with_value(Expr::Number(Number::Index(0))));
120
1
    let i_var = Expr::List(vec![
121
1
        Expr::Symbol("i".into()),
122
1
        Expr::Number(Number::Index(0)),
123
1
        Expr::List(vec![
124
1
            Expr::Symbol("+".into()),
125
1
            Expr::Symbol("i".into()),
126
1
            Expr::Number(Number::Index(1)),
127
1
        ]),
128
1
    ]);
129
1
    let end_clause = Expr::List(vec![
130
1
        Expr::List(vec![
131
1
            Expr::Symbol("=".into()),
132
1
            Expr::Symbol("i".into()),
133
1
            Expr::Symbol("N".into()),
134
1
        ]),
135
1
        Expr::Symbol("n".into()),
136
1
    ]);
137
1
    let body = Expr::List(vec![
138
1
        Expr::Symbol("SETF".into()),
139
1
        Expr::Symbol("n".into()),
140
1
        Expr::List(vec![
141
1
            Expr::Symbol("+".into()),
142
1
            Expr::Symbol("n".into()),
143
1
            Expr::Number(Number::Index(1)),
144
1
        ]),
145
1
    ]);
146
1
    let args = vec![Expr::List(vec![i_var]), end_clause, body];
147
1
    let result = do_form(&mut symbols, &args).unwrap();
148
1
    assert_eq!(result, Expr::WasmRuntime(WasmType::I32));
149
1
}
150

            
151
/// `infer_wasm_type` drives the do-var local allocation type.
152
/// Each variant must report the wasm type the codegen path emits
153
/// for an init expression of that shape; a disagreement lands a
154
/// local of the wrong type and the wasm fails validation when
155
/// `local.set` checks the operand.
156
#[test]
157
1
fn infer_wasm_type_integer_is_index_fraction_is_scalar() {
158
    // ADR-0028: an integer literal defaults to Index (I32); a fractional
159
    // literal is a dimensionless Scalar (Ratio). Mirrors `classify_stack_type`.
160
1
    let s = SymbolTable::with_builtins();
161
1
    assert_eq!(
162
1
        infer_wasm_type(&Expr::Number(Number::Index(0)), None, &s),
163
1
        Some(WasmType::I32)
164
    );
165
1
    assert_eq!(
166
1
        infer_wasm_type(&Expr::Number(Number::Scalar(Fraction::new(1, 2))), None, &s),
167
1
        Some(WasmType::Ratio)
168
    );
169
1
}
170

            
171
#[test]
172
1
fn infer_wasm_type_bool_is_bool() {
173
    // Bool/nil literals lower to `WasmType::Bool` on the stack; a DO loop var
174
    // sized here must match so a later read keeps Nil/Bool fidelity (not
175
    // Number). A nil without a pair step-hint is the falsy `Bool`.
176
1
    let s = SymbolTable::with_builtins();
177
1
    assert_eq!(infer_wasm_type(&Expr::T, None, &s), Some(WasmType::Bool));
178
1
    assert_eq!(infer_wasm_type(&Expr::Nil, None, &s), Some(WasmType::Bool));
179
1
}
180

            
181
#[test]
182
1
fn infer_wasm_type_string_is_stringref() {
183
1
    let s = SymbolTable::with_builtins();
184
1
    assert_eq!(
185
1
        infer_wasm_type(&Expr::String("hi".into()), None, &s),
186
1
        Some(WasmType::StringRef),
187
    );
188
1
}
189

            
190
#[test]
191
1
fn infer_wasm_type_wasm_runtime_passes_through() {
192
1
    let s = SymbolTable::with_builtins();
193
1
    assert_eq!(
194
1
        infer_wasm_type(&Expr::WasmRuntime(WasmType::Commodity), None, &s),
195
1
        Some(WasmType::Commodity),
196
    );
197
1
}
198

            
199
#[test]
200
1
fn infer_wasm_type_nil_with_pair_step_hint_uses_pair() {
201
1
    let mut s = SymbolTable::with_builtins();
202
1
    s.define(
203
1
        Symbol::new("acc", SymbolKind::Variable)
204
1
            .with_value(Expr::WasmRuntime(WasmType::PairRef(PairElement::Ratio))),
205
1
    );
206
    // Step expr `(cons 1/2 acc)` — car is Number-fraction so the
207
    // pair-element resolves to Ratio.
208
1
    let step = Expr::List(vec![
209
1
        Expr::Symbol("CONS".into()),
210
1
        Expr::Number(Number::Scalar(Fraction::new(1, 2))),
211
1
        Expr::Symbol("acc".into()),
212
1
    ]);
213
1
    assert_eq!(
214
1
        infer_wasm_type(&Expr::Nil, Some(&step), &s),
215
1
        Some(WasmType::PairRef(PairElement::Ratio)),
216
    );
217
1
}
218

            
219
#[test]
220
1
fn infer_wasm_type_nil_with_runtime_branch_step_uses_the_branch_type() {
221
1
    let mut s = SymbolTable::with_builtins();
222
1
    s.define(
223
1
        Symbol::new("FLAG", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::Bool)),
224
1
    );
225
1
    let step = parse_args("(if flag 7 8)").remove(0);
226
1
    assert_eq!(
227
1
        infer_wasm_type(&Expr::Nil, Some(&step), &s),
228
1
        Some(WasmType::I32)
229
    );
230
1
}
231

            
232
9
fn parse_args(source: &str) -> Vec<Expr> {
233
9
    crate::reader::Reader::parse(source).expect("parses").exprs
234
9
}
235

            
236
4
fn symbols_with_x() -> SymbolTable {
237
4
    let mut symbols = SymbolTable::with_builtins();
238
4
    symbols
239
4
        .define(Symbol::new("X", SymbolKind::Variable).with_value(Expr::Number(Number::Index(1))));
240
4
    symbols
241
4
}
242

            
243
2
fn macro_symbols() -> SymbolTable {
244
2
    let mut symbols = symbols_with_x();
245
2
    symbols.mark_macro_expansion();
246
2
    symbols
247
2
}
248

            
249
2
fn x_value(symbols: &SymbolTable) -> Option<Expr> {
250
2
    symbols.lookup("X").and_then(|s| s.value().cloned())
251
2
}
252

            
253
#[test]
254
1
fn a_static_do_setting_an_outer_var_is_refused_in_a_macro_body() {
255
1
    let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (setf x (+ x i))");
256
1
    for form in [do_form, do_star_form] {
257
2
        let mut symbols = macro_symbols();
258
2
        let err = form(&mut symbols, &args).unwrap_err();
259
2
        assert!(err.to_string().contains("may not mutate a global"), "{err}");
260
    }
261
1
}
262

            
263
#[test]
264
1
fn a_static_do_outside_a_macro_body_leaves_the_outer_var_alone() {
265
1
    let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (setf x (+ x i))");
266
1
    let mut symbols = symbols_with_x();
267
1
    do_form(&mut symbols, &args).unwrap();
268
1
    assert!(!matches!(x_value(&symbols), Some(Expr::WasmRuntime(_))));
269
1
    let mut symbols = symbols_with_x();
270
1
    do_star_form(&mut symbols, &args).unwrap();
271
1
    assert!(!matches!(x_value(&symbols), Some(Expr::WasmRuntime(_))));
272
1
}
273

            
274
#[test]
275
1
fn a_static_do_with_an_effect_body_is_a_runtime_placeholder_in_a_macro_body() {
276
1
    let mut symbols = SymbolTable::with_builtins();
277
1
    symbols.mark_macro_expansion();
278
1
    let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (print i)");
279
1
    assert!(do_form(&mut symbols, &args).unwrap().is_wasm_runtime());
280
1
    assert!(do_star_form(&mut symbols, &args).unwrap().is_wasm_runtime());
281
1
}
282

            
283
#[test]
284
1
fn a_static_do_with_an_effect_body_is_nil_outside_a_macro_body() {
285
1
    let mut symbols = SymbolTable::with_builtins();
286
1
    let args = parse_args("((i 0 (+ i 1))) ((= i 2)) (print i)");
287
1
    assert_eq!(do_form(&mut symbols, &args).unwrap(), Expr::Nil);
288
1
    assert_eq!(do_star_form(&mut symbols, &args).unwrap(), Expr::Nil);
289
1
}
290

            
291
#[test]
292
1
fn a_static_do_with_a_pure_body_still_folds() {
293
1
    let mut symbols = SymbolTable::with_builtins();
294
1
    let args = parse_args("((i 0 (+ i 1))) ((= i 2) i) (+ i 0)");
295
1
    let result = do_form(&mut symbols, &args).unwrap();
296
1
    assert!(!result.is_wasm_runtime(), "{result:?}");
297
1
}
298

            
299
#[test]
300
1
fn a_const_dolist_with_an_effect_body_is_a_runtime_placeholder_in_a_macro_body() {
301
1
    let mut symbols = SymbolTable::with_builtins();
302
1
    symbols.mark_macro_expansion();
303
1
    let args = parse_args("(i (quote (1 2))) (print i)");
304
1
    let result = super::dolist::dolist_form(&mut symbols, &args).unwrap();
305
1
    assert_eq!(result, Expr::WasmRuntime(WasmType::Bool));
306
1
}
307

            
308
#[test]
309
1
fn a_const_dolist_with_an_effect_body_is_nil_outside_a_macro_body() {
310
1
    let mut symbols = SymbolTable::with_builtins();
311
1
    let args = parse_args("(i (quote (1 2))) (print i)");
312
1
    let result = super::dolist::dolist_form(&mut symbols, &args).unwrap();
313
1
    assert_eq!(result, Expr::Nil);
314
1
}
315

            
316
#[test]
317
1
fn body_yields_runtime_only_in_a_macro_body() {
318
1
    let body = parse_args("(print 1)");
319
1
    let mut symbols = SymbolTable::with_builtins();
320
1
    assert!(!body_yields_runtime(&mut symbols, &body).unwrap());
321
1
    symbols.mark_macro_expansion();
322
1
    assert!(body_yields_runtime(&mut symbols, &body).unwrap());
323
1
}
324

            
325
3
fn parse_forms(source: &str) -> Vec<Expr> {
326
3
    let Expr::List(elems) = crate::Reader::parse_expr(source).expect("parse") else {
327
        panic!("not a list");
328
    };
329
3
    elems
330
3
}
331

            
332
#[test]
333
1
fn a_do_var_is_sized_from_its_step_else_its_first_body_store() {
334
1
    let body = parse_forms("(progn (setf acc (cons i acc)) (setf acc (cons 1/2 acc)))");
335
1
    let step = crate::Reader::parse_expr("(cons 1/2 acc)").expect("parse");
336
1
    assert_eq!(var_type_hint(Some(&step), &body[1..], "ACC"), Some(&step));
337
1
    assert_eq!(
338
1
        var_type_hint(None, &body[1..], "ACC"),
339
1
        Some(&crate::Reader::parse_expr("(cons i acc)").expect("parse")),
340
    );
341
1
    let shadowed = parse_forms("(progn (let ((acc 1)) (setf acc (cons i acc))))");
342
1
    assert_eq!(var_type_hint(None, &shadowed[1..], "ACC"), None);
343
1
}
344

            
345
#[test]
346
1
fn a_runtime_do_result_form_reads_the_body_stored_accumulator() {
347
1
    let form = parse_forms(
348
1
        "(do ((i 0 (+ i 1)) (acc nil)) ((= i n) (length acc)) (setf acc (cons i acc)))",
349
1
    );
350
1
    let mut symbols = SymbolTable::with_builtins();
351
1
    symbols.define(
352
1
        Symbol::new("N", SymbolKind::Variable).with_value(Expr::WasmRuntime(WasmType::I32)),
353
1
    );
354
1
    assert_eq!(
355
1
        do_form(&mut symbols, &form[1..]).expect("do"),
356
1
        Expr::WasmRuntime(WasmType::I32)
357
    );
358
1
}
359

            
360
4
fn compiled_type_of_step(source: &str) -> WasmType {
361
4
    let step = crate::Reader::parse_expr(source).expect("parse");
362
4
    let mut ctx = crate::compiler::context::CompileContext::new_with_host_fns(&[]).expect("ctx");
363
4
    let emit = crate::compiler::emit::FunctionEmitter::new();
364
4
    let mut symbols = SymbolTable::with_builtins_for_wasm();
365
4
    infer_compiled_type(&mut ctx, &emit, &mut symbols, &Expr::Nil, Some(&step)).expect("sized")
366
4
}
367

            
368
#[test]
369
1
fn a_compiled_step_sizes_a_nil_init_var_unless_it_never_falls_through() {
370
1
    assert_eq!(compiled_type_of_step("(+ 1 2)"), WasmType::I32);
371
1
    assert_eq!(
372
1
        compiled_type_of_step("(list 1 2)"),
373
1
        WasmType::PairRef(PairElement::I32)
374
    );
375
1
    assert_eq!(
376
1
        compiled_type_of_step("(let ((k 1)) (error 'boom \"x\"))"),
377
1
        WasmType::Bool
378
    );
379
1
    assert_eq!(
380
1
        compiled_type_of_step("(block c (error 'boom \"x\"))"),
381
1
        WasmType::Bool
382
    );
383
1
}
384

            
385
#[test]
386
1
fn only_codegen_sizes_a_nil_init_var_whose_step_reaches_an_exit() {
387
1
    let s = SymbolTable::with_builtins_for_wasm();
388
1
    for source in [
389
1
        "(block c (return-from b 9))",
390
1
        "(let ((q 1)) (return-from b q))",
391
1
        "(error 'boom \"x\")",
392
1
    ] {
393
3
        let step = crate::Reader::parse_expr(source).expect("parse");
394
3
        assert_eq!(
395
3
            infer_wasm_type(&Expr::Nil, Some(&step), &s),
396
3
            None,
397
            "{source}"
398
        );
399
    }
400
1
}
401

            
402
11
fn do_form_source(step: &str) -> String {
403
11
    format!("(do ((i 0 (+ i 1)) (v nil {step})) ((= i (entity-count)) v))")
404
11
}
405

            
406
11
fn eval_and_compiled_types(source: &str) -> (Result<Expr>, WasmType) {
407
    use crate::compiler::context::CompileContext;
408
    use crate::compiler::emit::FunctionEmitter;
409
    use crate::compiler::expr::{compile_for_stack, eval_value};
410

            
411
11
    let form = crate::Reader::parse_expr(source).expect("parse");
412
11
    let evaluated = eval_value(&mut SymbolTable::with_builtins_for_wasm(), &form);
413
11
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
414
11
    let mut emit = FunctionEmitter::new();
415
11
    let mut symbols = SymbolTable::with_builtins_for_wasm();
416
11
    let compiled = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &form).expect("compiles");
417
11
    (evaluated, compiled)
418
11
}
419

            
420
9
fn assert_eval_types_as_compiled(source: &str) {
421
9
    let (evaluated, compiled) = eval_and_compiled_types(source);
422
9
    assert_eq!(
423
9
        evaluated.expect("evaluates").wasm_type(),
424
9
        Some(compiled),
425
        "{source}"
426
    );
427
9
}
428

            
429
#[test]
430
1
fn eval_value_types_a_nil_init_do_as_compile_for_stack_does() {
431
1
    for step in ["(list i)", "\"s\"", "(cons i v)", "(> i 1)"] {
432
4
        assert_eval_types_as_compiled(&do_form_source(step));
433
4
        assert_eval_types_as_compiled(&do_form_source(step).replacen("(do ", "(do* ", 1));
434
    }
435
1
}
436

            
437
#[test]
438
1
fn eval_value_types_a_nested_nil_init_do_as_compile_for_stack_does() {
439
1
    let inner = do_form_source("(list i)");
440
1
    assert_eval_types_as_compiled(&format!(
441
1
        "(do ((j 0 (+ j 1)) (w nil {inner})) ((= j (entity-count)) w))"
442
1
    ));
443
1
}
444

            
445
#[test]
446
1
fn eval_value_types_a_block_wrapped_exit_step_do_as_compile_for_stack_does() {
447
1
    let source = format!(
448
        "(list (block b {}))",
449
1
        do_form_source("(if (> i 5) (return-from b 1) \"s\")")
450
    );
451
1
    let (evaluated, compiled) = eval_and_compiled_types(&source);
452
1
    assert_eq!(compiled, WasmType::PairRef(PairElement::AnyRef), "{source}");
453
1
    if let Ok(value) = evaluated {
454
        assert_eq!(value.wasm_type(), Some(compiled), "{source}");
455
1
    }
456
1
}
457

            
458
#[test]
459
1
fn eval_value_leaves_a_nil_init_do_whose_step_exits_to_compile_for_stack() {
460
1
    let (evaluated, _) = eval_and_compiled_types(&format!(
461
1
        "(block b {})",
462
1
        do_form_source("(block c (return-from b 9))")
463
1
    ));
464
1
    assert!(evaluated.is_err());
465
1
}