1
//! Tests for `compile_body_into_helper` (moved out of `emit.rs` per
2
//! CLAUDE.md's file-size guideline).
3

            
4
use super::*;
5
use crate::compiler::context::CompileContext;
6
use crate::runtime::SymbolTable;
7

            
8
/// Carried-in fix (ADR-0033 Phase 3): `bind_user_params` failing between
9
/// `take_local_pool` and `restore_local_pool` used to leak the trial
10
/// allocation (the `HostAnyref` downcast for a `Closure` param allocates
11
/// a local via `ctx.alloc_local` BEFORE `emit_anyref_to_typed_downcast`
12
/// fails on the type), leaving the local pool permanently shifted for
13
/// every lambda compiled afterward. `compile_body_into_helper` must
14
/// restore the snapshot on that error path too.
15
#[test]
16
1
fn bind_user_params_failure_restores_the_local_pool_snapshot() {
17
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
18
1
    let idx_before = ctx.alloc_local(WasmType::I32).expect("alloc");
19
1
    let symbols = SymbolTable::with_builtins_for_wasm();
20
1
    let unknown = crate::ast::ClosureSigId(99);
21

            
22
1
    let result = compile_body_into_helper(
23
1
        &mut ctx,
24
1
        &symbols,
25
1
        &["x".to_string()],
26
1
        &[WasmType::Closure(unknown)],
27
1
        &Expr::Nil,
28
1
        &[],
29
1
        CallingConvention::HostAnyref,
30
1
    );
31
1
    assert!(
32
1
        result.is_err(),
33
        "a Closure param of an unknown signature cannot be downcast"
34
    );
35

            
36
1
    let idx_after = ctx.alloc_local(WasmType::I32).expect("alloc");
37
1
    assert_eq!(
38
1
        idx_after,
39
1
        idx_before + 1,
40
        "the local pool must be restored to its pre-call snapshot after \
41
         bind_user_params fails, not left shifted by the leaked trial local"
42
    );
43
1
}
44

            
45
15
fn compile_error(source: &str) -> Error {
46
15
    let program = crate::reader::Reader::parse(source).expect("parses");
47
15
    let hosts = vec![
48
15
        crate::host_fn::HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
49
15
            .returns(WasmType::I32),
50
    ];
51
15
    let mut symbols = SymbolTable::with_builtins_for_wasm();
52
15
    symbols.register_host_fns(&hosts);
53
15
    match crate::compiler::Compiler::with_host_fns(hosts).compile(&program, &mut symbols) {
54
15
        Err(err) => err,
55
        Ok(_) => panic!("{source} compiles"),
56
    }
57
15
}
58

            
59
4
fn mix() -> Error {
60
4
    compile_error("(+ (rpc-protocol-version) 1/2)")
61
4
}
62

            
63
#[test]
64
1
fn every_dimension_producer_builds_the_dimension_variant() {
65
1
    for source in [
66
1
        "(+ (rpc-protocol-version) 1/2)",
67
1
        "(+ 1/2 (rpc-protocol-version))",
68
1
        "(the index 1/2)",
69
1
        "(index->scalar 1/2)",
70
1
        "(scalar->index (rpc-protocol-version))",
71
1
        "(* (rpc-protocol-version) 1/2)",
72
1
        "(let ((a (rpc-protocol-version))) (+ a 1/2))",
73
1
    ] {
74
7
        let err = compile_error(source);
75
7
        assert!(matches!(err, Error::Dimension(_)), "{source}: {err:?}");
76
    }
77
1
}
78

            
79
#[test]
80
1
fn an_error_that_is_no_dimension_mix_stays_a_plain_compile_error() {
81
1
    for source in ["(list if)", "(funcall #'if 1)"] {
82
2
        let err = compile_error(source);
83
2
        assert!(matches!(err, Error::Compile(_)), "{source}: {err:?}");
84
    }
85
1
}
86

            
87
#[test]
88
1
fn a_dimension_error_names_the_ambiguous_parameter_the_body_uses() {
89
1
    let params = LambdaParams::simple(vec!["X".to_string(), "Y".to_string()]);
90
1
    let body = Expr::List(vec![Expr::symbol("LIST"), Expr::symbol("Y")]);
91
1
    let err = name_unpinned_param(mix(), (&params, &body), &[false, true]);
92
1
    assert_eq!(
93
1
        err.to_string(),
94
1
        format!(
95
            "{}; cannot infer the type of parameter Y; pin it with THE",
96
1
            mix()
97
        )
98
    );
99
1
}
100

            
101
#[test]
102
1
fn a_genuine_mix_names_no_parameter() {
103
1
    for source in [
104
1
        "(defvar *f* (lambda (a s) (list a (+ (the scalar s) (length (list 1 a)))))) 1",
105
1
        "(defvar *f* (lambda (a b s) (list a (+ b 1 (the scalar s))))) 1",
106
1
    ] {
107
2
        let message = compile_error(source).to_string();
108
2
        assert!(message.contains("cannot mix"), "{source}: {message}");
109
2
        assert!(!message.contains("cannot infer"), "{source}: {message}");
110
    }
111
1
}
112

            
113
#[test]
114
1
fn a_dimension_error_stays_when_every_used_parameter_is_pinned_or_unused() {
115
1
    let params = LambdaParams::simple(vec!["X".to_string(), "Y".to_string()]);
116
1
    let body = Expr::List(vec![Expr::symbol("+"), Expr::symbol("X"), Expr::Nil]);
117
1
    assert_eq!(
118
1
        name_unpinned_param(mix(), (&params, &body), &[false, true]).to_string(),
119
1
        mix().to_string()
120
    );
121
1
}
122

            
123
#[test]
124
1
fn an_error_of_another_family_is_not_blamed_on_a_parameter() {
125
1
    let params = LambdaParams::simple(vec!["X".to_string()]);
126
1
    let other = Error::Compile("boom".to_string());
127
1
    let err = name_unpinned_param(other, (&params, &Expr::symbol("X")), &[true]);
128
1
    assert_eq!(err.to_string(), "Compile error: boom");
129
1
}