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

            
4
use super::*;
5
use crate::ast::{ClosureSigId, EntityKind, Fraction, PairElement};
6
use crate::compiler::CompileMode;
7
use crate::compiler::context::CompileContext;
8
use crate::runtime::SymbolTable;
9

            
10
/// The contract `classify_stack_type` exists to uphold: for every literal /
11
/// already-resolved runtime `Expr` it classifies (returns `Some`), the
12
/// prediction equals the `WasmType` `compile_for_stack` actually pushes.
13
/// Any drift here is the class of bug (#56/#57/#58/#59) that motivated the
14
/// single source of truth, so this test compiles each shape for real and
15
/// compares. (`None`-classified shapes — symbols, calls — are not value
16
/// literals and aren't asserted here.)
17
#[test]
18
1
fn classify_stack_type_matches_compile_for_stack() {
19
12
    let quote = |inner: Expr| Expr::Quote(Box::new(inner));
20
11
    let datum = |inner: Expr| Expr::Datum(Box::new(inner));
21
24
    let sym = |name: &str| Expr::Symbol(name.to_string());
22
1
    let runtime = [
23
1
        WasmType::I32,
24
1
        WasmType::Bool,
25
1
        WasmType::Ratio,
26
1
        WasmType::Commodity,
27
1
        WasmType::StringRef,
28
1
        WasmType::SymbolRef,
29
1
        WasmType::PairRef(PairElement::Bool),
30
1
        WasmType::EntityRef(EntityKind::Account),
31
1
        WasmType::Closure(ClosureSigId(0)),
32
1
        WasmType::AnyRef,
33
1
    ];
34
8
    let quote_form = |datum: Expr| Expr::List(vec![sym("QUOTE"), datum]);
35
1
    let mut cases: Vec<Expr> = vec![
36
1
        quote_form(sym("A")),
37
1
        quote_form(Expr::Number(Number::Index(3))),
38
1
        quote_form(Expr::String("s".to_string())),
39
1
        quote_form(Expr::Keyword("K".to_string())),
40
1
        quote_form(Expr::List(vec![
41
1
            Expr::Number(Number::Index(1)),
42
1
            Expr::Number(Number::Index(2)),
43
1
        ])),
44
1
        quote_form(Expr::Nil),
45
1
        quote_form(Expr::List(vec![])),
46
1
        quote_form(Expr::T),
47
1
        Expr::Number(Number::Index(7)),
48
1
        Expr::Number(Number::Scalar(Fraction::new(1, 2))),
49
1
        Expr::Number(Number::Scalar(Fraction::from_integer(2))),
50
1
        Expr::RuntimeValue(Value::Commodity {
51
1
            amount: Fraction::new(7, 2),
52
1
            commodity_id: uuid::Uuid::from_u128(5),
53
1
        }),
54
1
        Expr::T,
55
1
        Expr::Nil,
56
1
        Expr::Nil,
57
1
        Expr::String("hi".to_string()),
58
1
        Expr::List(vec![]),
59
1
        Expr::Keyword("K".to_string()),
60
    ];
61
1
    let data = [
62
1
        Expr::Nil,
63
1
        Expr::Number(Number::Index(3)),
64
1
        Expr::String("s".to_string()),
65
1
        sym("A"),
66
1
        Expr::Keyword("K".to_string()),
67
1
        Expr::List(vec![sym("A"), Expr::Keyword("K".to_string())]),
68
1
        Expr::List(vec![sym("A"), Expr::String("s".to_string())]),
69
1
        Expr::Quasiquote(Box::new(Expr::List(vec![sym("A")]))),
70
1
        Expr::List(vec![
71
1
            Expr::Number(Number::Index(1)),
72
1
            Expr::Number(Number::Index(2)),
73
1
        ]),
74
1
        Expr::List(vec![
75
1
            Expr::Number(Number::Index(1)),
76
1
            Expr::String("s".to_string()),
77
1
        ]),
78
1
        Expr::List(vec![
79
1
            Expr::Number(Number::Index(1)),
80
1
            Expr::List(vec![Expr::Number(Number::Index(2))]),
81
1
        ]),
82
1
    ];
83
1
    for inner in data {
84
11
        cases.push(quote(inner.clone()));
85
11
        cases.push(datum(inner));
86
    }
87
1
    cases.push(quote(Expr::List(vec![sym("QUOTE"), sym("A")])));
88
1
    cases.push(Expr::quoted(Expr::quoted_code(sym("A"))));
89
    // A `WasmLocal` of every wasm type — `compile_for_stack` emits
90
    // `local.get` and returns the local's declared type unchanged.
91
10
    cases.extend(runtime.iter().map(|ty| Expr::WasmLocal(0, *ty)));
92
4
    cases.extend(["index", "scalar", "money", "string"].map(|target| {
93
4
        Expr::List(vec![
94
4
            sym("THE"),
95
4
            sym(target),
96
4
            Expr::WasmLocal(0, WasmType::AnyRef),
97
4
        ])
98
4
    }));
99

            
100
1
    for expr in &cases {
101
56
        let predicted = classify_stack_type(expr)
102
            .unwrap_or_else(|| panic!("classify_stack_type returned None for {expr:?}"));
103
56
        let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
104
56
        let mut emit = FunctionEmitter::new();
105
56
        let mut symbols = SymbolTable::with_builtins_for_wasm();
106
56
        let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, expr)
107
            .unwrap_or_else(|e| panic!("compile_for_stack {expr:?}: {e}"));
108
56
        assert_eq!(
109
56
            predicted, emitted,
110
            "classify_stack_type disagrees with compile_for_stack for {expr:?}"
111
        );
112
    }
113
1
}
114

            
115
/// A quoted list is the `$pair` chain of its members, a symbol member riding
116
/// the symbol cell; a dotted pair has no stack value at all.
117
#[test]
118
1
fn a_quoted_list_datum_is_a_pair_chain_or_the_structured_rejection() {
119
2
    let quote = |inner: Expr| Expr::Datum(Box::new(inner));
120
3
    let sym = |name: &str| Expr::Symbol(name.to_string());
121
1
    let one = Expr::Number(Number::Index(1));
122
1
    let symbols_list = quote(Expr::List(vec![sym("A"), sym("B")]));
123
1
    let dotted = quote(Expr::cons(one.clone(), sym("B")));
124
1
    assert_eq!(
125
1
        classify_stack_type(&symbols_list),
126
1
        Some(WasmType::PairRef(PairElement::Symbol))
127
    );
128
1
    assert_eq!(classify_stack_type(&dotted), None);
129
2
    let compile = |datum: &Expr| {
130
2
        let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
131
2
        let mut emit = FunctionEmitter::new();
132
2
        let mut symbols = SymbolTable::with_builtins_for_wasm();
133
2
        compile_for_stack(&mut ctx, &mut emit, &mut symbols, datum)
134
2
    };
135
1
    assert_eq!(
136
1
        compile(&symbols_list).expect("a symbol list is a chain"),
137
1
        WasmType::PairRef(PairElement::Symbol)
138
    );
139
1
    assert_eq!(
140
1
        compile(&dotted)
141
1
            .expect_err("a dotted pair is rejected")
142
1
            .to_string(),
143
1
        "Compile error: cannot compile to WASM stack value: '(1 . B) has no list cell representation"
144
    );
145
1
}
146

            
147
/// Shapes that aren't a directly-emittable literal/runtime value (they need
148
/// a call/list walk or aren't stack values) classify as `None`.
149
#[test]
150
1
fn classify_stack_type_is_none_for_non_literal_shapes() {
151
1
    assert_eq!(classify_stack_type(&Expr::Symbol("X".to_string())), None);
152
    // A namespaced symbol (ADR-0029) is still just a Symbol — its canonical
153
    // `NS:NAME` key must not be mistaken for any typed literal shape.
154
1
    assert_eq!(
155
1
        classify_stack_type(&Expr::Symbol("FOO:BAR".to_string())),
156
1
        None
157
    );
158
1
    assert_eq!(
159
1
        classify_stack_type(&Expr::WasmRuntime(WasmType::Ratio)),
160
1
        Some(WasmType::Ratio)
161
    );
162
1
}
163

            
164
/// `nil_repr` is exhaustive over every `WasmType` variant (a unit test rather
165
/// than relying on the `match`'s own exhaustiveness check alone, so a future
166
/// reviewer sees the enumerated contract in one place) and its Never/Null
167
/// split matches [`emit_nil_default`]'s success/failure split — the "pinned
168
/// against codegen" requirement from ADR-0033.
169
#[test]
170
1
fn nil_repr_covers_every_wasm_type_and_matches_emit_nil_default() {
171
    use super::super::atoms::emit_nil_default;
172
    use crate::compiler::emit::FunctionEmitter;
173

            
174
1
    let ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
175
    let sig = {
176
1
        let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
177
1
        ctx.intern_closure_signature(&[], WasmType::Ratio)
178
1
            .expect("closure sig")
179
    };
180
1
    let every_variant = [
181
1
        WasmType::I32,
182
1
        WasmType::Bool,
183
1
        WasmType::Ratio,
184
1
        WasmType::Commodity,
185
1
        WasmType::StringRef,
186
1
        WasmType::PairRef(PairElement::I32),
187
1
        WasmType::AnyRef,
188
1
        WasmType::EntityRef(EntityKind::Account),
189
1
        WasmType::StructRef(crate::ast::StructId(0)),
190
1
        WasmType::Closure(sig),
191
1
    ];
192
1
    for ty in every_variant {
193
10
        let repr = nil_repr(&ty);
194
10
        let mut emit = FunctionEmitter::new();
195
10
        let outcome = emit_nil_default(&ctx, &mut emit, ty);
196
10
        match repr {
197
4
            NilRepr::Never => assert!(
198
4
                outcome.is_err(),
199
                "{ty} classifies as Never but emit_nil_default succeeded"
200
            ),
201
6
            NilRepr::I32Zero | NilRepr::Null => assert!(
202
6
                outcome.is_ok(),
203
                "{ty} classifies as {repr:?} but emit_nil_default failed: {:?}",
204
                outcome.err()
205
            ),
206
        }
207
    }
208
1
}
209

            
210
/// The classifier and codegen agree on the folded form, not only on a type:
211
/// a quoted constant is the constant itself.
212
#[test]
213
1
fn a_quoted_constant_classifies_as_the_folded_constant() {
214
5
    let sym = |name: &str| Expr::Symbol(name.to_string());
215
1
    for (datum, folded) in [
216
1
        (Expr::Nil, Expr::Nil),
217
1
        (Expr::List(vec![]), Expr::Nil),
218
1
        (Expr::T, Expr::T),
219
1
    ] {
220
3
        assert_eq!(Expr::quoted(datum.clone()), folded);
221
3
        let form = Expr::List(vec![sym("QUOTE"), datum]);
222
3
        assert_eq!(classify_stack_type(&form), classify_stack_type(&folded));
223
    }
224
1
    assert_eq!(Expr::quoted(sym("A")), Expr::Datum(Box::new(sym("A"))));
225
1
}
226

            
227
#[test]
228
1
fn a_symbol_is_a_string_designator_and_nothing_else_is_changed() {
229
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
230
1
    let mut emit = FunctionEmitter::new();
231
1
    assert_eq!(
232
1
        string_designator(&mut ctx, &mut emit, WasmType::SymbolRef).expect("symbol"),
233
1
        WasmType::StringRef
234
    );
235
1
    for ty in [WasmType::StringRef, WasmType::I32, WasmType::AnyRef] {
236
3
        assert_eq!(
237
3
            string_designator(&mut ctx, &mut emit, ty).expect("other"),
238
3
            ty
239
        );
240
    }
241
1
    let quoted = Expr::Datum(Box::new(Expr::Symbol("A".to_string())));
242
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
243
1
    compile_for_stack_as(
244
1
        &mut ctx,
245
1
        &mut emit,
246
1
        &mut symbols,
247
1
        &quoted,
248
1
        WasmType::StringRef,
249
1
    )
250
1
    .expect("a symbol where a string is expected");
251
1
}
252

            
253
#[test]
254
1
fn member_value_quotes_only_a_bare_symbol() {
255
1
    let sym = Expr::Symbol("A".to_string());
256
1
    assert_eq!(
257
1
        crate::compiler::expr::member_value(sym.clone()),
258
1
        Expr::Datum(Box::new(sym))
259
    );
260
1
    let one = Expr::Number(Number::Index(1));
261
1
    assert_eq!(crate::compiler::expr::member_value(one.clone()), one);
262
1
}
263

            
264
#[test]
265
1
fn member_value_quotes_every_non_self_evaluating_member() {
266
1
    let one = Expr::Number(Number::Index(1));
267
1
    let list = Expr::List(vec![one.clone()]);
268
1
    let cons = Expr::cons(one.clone(), one.clone());
269
1
    for member in [list, cons] {
270
2
        assert_eq!(
271
2
            crate::compiler::expr::member_value(member.clone()),
272
2
            Expr::Datum(Box::new(member))
273
        );
274
    }
275
1
    let datum = Expr::Datum(Box::new(Expr::Symbol("A".to_string())));
276
1
    assert_eq!(crate::compiler::expr::member_value(datum.clone()), datum);
277
1
}
278

            
279
/// A session instance classifies as its struct type and compiles to a read of
280
/// the global its prologue allocated.
281
#[test]
282
1
fn classify_stack_type_matches_compile_for_stack_for_a_session_instance() {
283
    use crate::compiler::emit::FunctionEmitter;
284
    use crate::runtime::{Found, StructInstance};
285

            
286
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
287
1
    let id = symbols
288
1
        .define_struct("PT", vec!["X".to_string()])
289
1
        .expect("defines");
290
1
    let instance = StructInstance {
291
1
        layout: id,
292
1
        fields: vec![Expr::Nil],
293
1
    };
294
1
    symbols.define(
295
1
        crate::runtime::Symbol::new("P", crate::runtime::SymbolKind::Variable)
296
1
            .with_value(Expr::Instance(0, id)),
297
1
    );
298
1
    symbols.settle_instances(Found::from([(0, Some(instance))]), 1);
299
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
300
1
    let mut emit = FunctionEmitter::new();
301
    let scan =
302
1
        crate::compiler::expr::prepare_unit(&mut symbols, &[], CompileMode::Script).expect("scans");
303
1
    crate::compiler::special::allocate_instances(&mut ctx, &mut emit, &mut symbols, &scan)
304
1
        .expect("prologue");
305
1
    let leaf = Expr::Instance(0, id);
306
1
    let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &leaf).expect("compiles");
307
1
    assert_eq!(classify_stack_type(&leaf), Some(WasmType::StructRef(id)));
308
1
    assert_eq!(emitted, WasmType::StructRef(id));
309
1
}
310

            
311
/// `(f 4)` with a closure in the value cell and a function in the function
312
/// cell calls the function, and the call's stack type is the function's.
313
#[test]
314
1
fn a_call_of_a_name_with_both_cells_pushes_the_function_type() {
315
    use crate::runtime::{Head, Symbol, SymbolKind};
316

            
317
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
318
1
    let sig = ctx
319
1
        .intern_closure_signature(&[], WasmType::Ratio)
320
1
        .expect("sig");
321
1
    let body = Expr::Number(Number::Index(100));
322
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
323
1
    symbols.define(
324
1
        Symbol::new("F", SymbolKind::Variable)
325
1
            .with_function(Expr::Lambda(
326
1
                crate::ast::LambdaParams::simple(vec!["X".to_string()]),
327
1
                Box::new(body.clone()),
328
1
            ))
329
1
            .with_value(Expr::WasmLocal(0, WasmType::Closure(sig))),
330
1
    );
331
1
    assert!(matches!(symbols.resolve_head("F"), Head::Function(..)));
332
1
    let call = crate::reader::Reader::parse_expr("(f 4)").expect("parses");
333
1
    let mut emit = FunctionEmitter::new();
334
1
    let emitted = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &call).expect("compiles");
335
1
    assert_eq!(classify_stack_type(&body), Some(emitted));
336
1
}
337

            
338
/// `(f 4)` with only a closure in the value cell has no head: it classifies as
339
/// nothing and `compile_for_stack` refuses it, never calling the closure.
340
#[test]
341
1
fn a_call_of_a_name_with_only_a_closure_value_is_refused() {
342
    use crate::runtime::{Head, Symbol, SymbolKind};
343

            
344
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).expect("ctx");
345
1
    let sig = ctx
346
1
        .intern_closure_signature(&[], WasmType::Ratio)
347
1
        .expect("sig");
348
1
    let mut symbols = SymbolTable::with_builtins_for_wasm();
349
1
    symbols.define(
350
1
        Symbol::new("F", SymbolKind::Variable)
351
1
            .with_value(Expr::WasmLocal(0, WasmType::Closure(sig))),
352
1
    );
353
1
    assert!(matches!(symbols.resolve_head("F"), Head::Unknown));
354
1
    let call = crate::reader::Reader::parse_expr("(f 4)").expect("parses");
355
1
    let mut emit = FunctionEmitter::new();
356
1
    let err = compile_for_stack(&mut ctx, &mut emit, &mut symbols, &call).expect_err("refused");
357
1
    assert_eq!(
358
1
        err.to_string(),
359
1
        "Compile error: undefined function F; use (funcall f …)"
360
    );
361
1
    assert_eq!(classify_stack_type(&call), None);
362
1
}