1
use crate::ast::Fraction;
2
use crate::ast::{Expr, Number, PairElement, WasmType};
3

            
4
use super::infer::{chain_pair_element, infer_pair_element, literal_pair_element};
5

            
6
1565
fn int(n: i64) -> Expr {
7
1565
    Expr::Number(Number::Index(n))
8
1565
}
9

            
10
#[test]
11
1
fn chain_of_integer_literals_is_an_index_chain() {
12
1
    assert_eq!(
13
1
        chain_pair_element(&[int(1), int(2)]).unwrap(),
14
1
        PairElement::I32
15
    );
16
1
}
17

            
18
#[test]
19
1
fn chain_integer_literals_cross_to_a_ratio_neighbor() {
20
1
    let half = Expr::Number(Number::Scalar(Fraction::new(1, 2)));
21
1
    assert_eq!(
22
1
        chain_pair_element(&[half, int(3)]).unwrap(),
23
1
        PairElement::Ratio
24
    );
25
1
    assert_eq!(
26
1
        chain_pair_element(&[Expr::WasmRuntime(WasmType::Ratio), int(3)]).unwrap(),
27
1
        PairElement::Ratio
28
    );
29
1
}
30

            
31
#[test]
32
1
fn chain_integer_literals_at_the_index_bounds_are_an_index_chain() {
33
1
    assert_eq!(
34
1
        chain_pair_element(&[int((1 << 30) - 1), int(-(1 << 30))]).unwrap(),
35
1
        PairElement::I32
36
    );
37
1
}
38

            
39
#[test]
40
1
fn chain_of_bool_and_nil_uses_bool() {
41
1
    assert_eq!(
42
1
        chain_pair_element(&[Expr::T, Expr::Nil]).unwrap(),
43
1
        PairElement::Bool
44
    );
45
1
}
46

            
47
#[test]
48
1
fn chain_integer_literal_adopts_runtime_index_on_either_side() {
49
1
    let index = Expr::WasmRuntime(WasmType::I32);
50
1
    assert_eq!(
51
1
        chain_pair_element(&[index.clone(), int(2)]).unwrap(),
52
1
        PairElement::I32
53
    );
54
1
    assert_eq!(
55
1
        chain_pair_element(&[int(2), index]).unwrap(),
56
1
        PairElement::I32
57
    );
58
1
}
59

            
60
#[test]
61
1
fn chain_literal_tail_disagreeing_with_runtime_head_widens_to_anyref() {
62
1
    let scalar = Expr::WasmRuntime(WasmType::Ratio);
63
1
    assert_eq!(
64
1
        chain_pair_element(&[scalar, Expr::String("a".to_string())]).unwrap(),
65
1
        PairElement::AnyRef
66
    );
67
1
}
68

            
69
#[test]
70
1
fn chain_integer_literal_against_non_numeric_slot_widens_to_anyref() {
71
1
    assert_eq!(
72
1
        chain_pair_element(&[int(1), Expr::Nil]).unwrap(),
73
1
        PairElement::AnyRef
74
    );
75
1
    assert_eq!(
76
1
        chain_pair_element(&[Expr::String("a".to_string()), int(1)]).unwrap(),
77
1
        PairElement::AnyRef
78
    );
79
1
}
80

            
81
#[test]
82
1
fn chain_fractional_literal_against_runtime_index_widens_to_anyref() {
83
1
    let half = Expr::Number(Number::Scalar(Fraction::new(1, 2)));
84
1
    assert_eq!(
85
1
        chain_pair_element(&[Expr::WasmRuntime(WasmType::I32), half]).unwrap(),
86
1
        PairElement::AnyRef
87
    );
88
1
}
89

            
90
#[test]
91
1
fn chain_of_nothing_uses_anyref_and_of_symbols_the_symbol_slot() {
92
2
    let symbol = |name: &str| Expr::Symbol(name.to_string());
93
1
    assert_eq!(chain_pair_element(&[]).unwrap(), PairElement::AnyRef);
94
1
    assert_eq!(
95
1
        chain_pair_element(&[symbol("A"), Expr::Keyword("K".to_string())]).unwrap(),
96
1
        PairElement::Symbol
97
    );
98
1
    assert_eq!(
99
1
        chain_pair_element(&[symbol("A"), Expr::String("s".to_string())]).unwrap(),
100
1
        PairElement::AnyRef
101
    );
102
1
}
103

            
104
#[test]
105
1
fn a_runtime_nested_list_rides_an_anyref_cell() {
106
1
    let nested = Expr::WasmRuntime(WasmType::PairRef(PairElement::I32));
107
1
    assert_eq!(
108
1
        chain_pair_element(&[nested.clone(), int(1)]).unwrap(),
109
1
        PairElement::AnyRef
110
    );
111
1
    assert_eq!(
112
1
        infer_pair_element(&nested, &Expr::Nil).unwrap(),
113
1
        PairElement::AnyRef
114
    );
115
1
}
116

            
117
#[test]
118
1
fn chain_of_a_runtime_closure_rides_its_own_cell() {
119
1
    let sig = crate::ast::ClosureSigId(0);
120
1
    let closure = Expr::WasmRuntime(WasmType::Closure(sig));
121
1
    assert_eq!(
122
1
        chain_pair_element(&[closure.clone(), closure]).unwrap(),
123
1
        PairElement::Closure(sig)
124
    );
125
1
}
126

            
127
/// `infer_pair_element` decides the static PairElement from a
128
/// `(cons car cdr)` form, balancing the car's compile-time type
129
/// against the cdr's. The legacy integration test reached this
130
/// via `Symbol::new("BAL").with_value(Expr::WasmRuntime(Commodity))`
131
/// in the symbol table; the unit form exercises the function
132
/// directly so the contract is locked in without needing a
133
/// script-mode Commodity producer.
134
#[test]
135
1
fn commodity_car_with_nil_cdr_is_commodity_pair() {
136
1
    let car = Expr::WasmRuntime(WasmType::Commodity);
137
1
    let elem = infer_pair_element(&car, &Expr::Nil).unwrap();
138
1
    assert_eq!(elem, PairElement::Commodity);
139
1
}
140

            
141
#[test]
142
1
fn commodity_car_with_pair_of_i32_cdr_widens_to_anyref() {
143
    // ADR-0025 escape hatch: when the car and cdr disagree on element
144
    // type, CONS widens to `PairElement::AnyRef` (canonical Common Lisp
145
    // heterogeneous `cons`) rather than rejecting. The strict typed path
146
    // still applies when both arms agree.
147
1
    let car = Expr::WasmRuntime(WasmType::Commodity);
148
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::I32));
149
1
    let elem = infer_pair_element(&car, &cdr).expect("heterogeneous CONS widens to AnyRef");
150
1
    assert_eq!(elem, PairElement::AnyRef);
151
1
}
152

            
153
#[test]
154
1
fn ratio_car_with_pair_of_ratio_cdr_resolves_to_ratio_pair() {
155
1
    let car = Expr::WasmRuntime(WasmType::Ratio);
156
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::Ratio));
157
1
    let elem = infer_pair_element(&car, &cdr).unwrap();
158
1
    assert_eq!(elem, PairElement::Ratio);
159
1
}
160

            
161
#[test]
162
1
fn integer_number_car_with_nil_cdr_is_an_index_cell() {
163
1
    let elem = infer_pair_element(&int(1), &Expr::Nil).unwrap();
164
1
    assert_eq!(elem, PairElement::I32);
165
1
}
166

            
167
#[test]
168
1
fn integer_number_car_adopts_a_ratio_cdr() {
169
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::Ratio));
170
1
    assert_eq!(
171
1
        infer_pair_element(&int(1), &cdr).unwrap(),
172
1
        PairElement::Ratio
173
    );
174
1
}
175

            
176
#[test]
177
1
fn nil_car_takes_the_bool_slot_and_widens() {
178
1
    let index_cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::I32));
179
1
    assert_eq!(
180
1
        infer_pair_element(&Expr::Nil, &index_cdr).unwrap(),
181
1
        PairElement::AnyRef
182
    );
183
1
    let bool_cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::Bool));
184
1
    assert_eq!(
185
1
        infer_pair_element(&Expr::Nil, &bool_cdr).unwrap(),
186
1
        PairElement::Bool
187
    );
188
1
}
189

            
190
#[test]
191
1
fn runtime_car_unifies_with_quoted_list_cdr_members() {
192
2
    let quoted = |members: Vec<Expr>| Expr::Datum(Box::new(Expr::List(members)));
193
1
    let index = Expr::WasmRuntime(WasmType::I32);
194
1
    assert_eq!(
195
1
        infer_pair_element(&index, &quoted(vec![int(1), int(2)])).unwrap(),
196
1
        PairElement::I32
197
    );
198
1
    assert_eq!(
199
1
        infer_pair_element(&index, &quoted(vec![Expr::Nil])).unwrap(),
200
1
        PairElement::AnyRef
201
    );
202
1
}
203

            
204
#[test]
205
1
fn constant_car_without_slot_adopts_typed_cdr_or_is_rejected() {
206
1
    let list = Expr::Datum(Box::new(Expr::List(vec![int(1)])));
207
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::StringRef));
208
1
    assert_eq!(
209
1
        infer_pair_element(&list, &cdr).unwrap(),
210
1
        PairElement::StringRef
211
    );
212
1
    assert!(infer_pair_element(&list, &Expr::Nil).is_err());
213
1
}
214

            
215
#[test]
216
1
fn a_symbol_car_rides_the_symbol_slot_and_widens_beside_a_string() {
217
1
    let symbol = Expr::Datum(Box::new(Expr::Symbol("A".to_string())));
218
1
    let strings = Expr::WasmRuntime(WasmType::PairRef(PairElement::StringRef));
219
1
    let symbols = Expr::WasmRuntime(WasmType::PairRef(PairElement::Symbol));
220
1
    assert_eq!(
221
1
        infer_pair_element(&symbol, &Expr::Nil).unwrap(),
222
1
        PairElement::Symbol
223
    );
224
1
    assert_eq!(
225
1
        infer_pair_element(&symbol, &symbols).unwrap(),
226
1
        PairElement::Symbol
227
    );
228
1
    assert_eq!(
229
1
        infer_pair_element(&symbol, &strings).unwrap(),
230
1
        PairElement::AnyRef
231
    );
232
1
}
233

            
234
#[test]
235
1
fn literal_pair_element_of_a_symbol_or_keyword_is_the_symbol_slot() {
236
1
    for datum in [
237
1
        Expr::Symbol("A".to_string()),
238
1
        Expr::Keyword("K".to_string()),
239
1
        Expr::Quote(Box::new(Expr::Symbol("A".to_string()))),
240
1
        Expr::Quote(Box::new(Expr::Keyword("K".to_string()))),
241
1
        Expr::Datum(Box::new(Expr::Symbol("A".to_string()))),
242
1
        Expr::Datum(Box::new(Expr::Keyword("K".to_string()))),
243
1
    ] {
244
6
        assert_eq!(
245
6
            literal_pair_element(&datum),
246
6
            Some(PairElement::Symbol),
247
            "{datum:?}"
248
        );
249
    }
250
1
}
251

            
252
#[test]
253
1
fn fractional_number_car_with_nil_cdr_uses_ratio_default() {
254
1
    let car = Expr::Number(Number::Scalar(Fraction::new(1, 2)));
255
1
    let elem = infer_pair_element(&car, &Expr::Nil).unwrap();
256
1
    assert_eq!(elem, PairElement::Ratio);
257
1
}
258

            
259
#[test]
260
1
fn bool_car_with_nil_cdr_uses_bool_slot() {
261
    // A bool literal car rides PairElement::Bool (not I32), so CAR recovers a
262
    // truth value that serializes as Nil/Bool rather than Number.
263
1
    let car = Expr::T;
264
1
    let elem = infer_pair_element(&car, &Expr::Nil).unwrap();
265
1
    assert_eq!(elem, PairElement::Bool);
266
1
}
267

            
268
#[test]
269
1
fn string_car_with_nil_cdr_uses_stringref() {
270
1
    let car = Expr::String("hi".to_string());
271
1
    let elem = infer_pair_element(&car, &Expr::Nil).unwrap();
272
1
    assert_eq!(elem, PairElement::StringRef);
273
1
}
274

            
275
#[test]
276
1
fn anyref_cdr_propagates_anyref_pair_element() {
277
1
    let car = Expr::WasmRuntime(WasmType::Ratio);
278
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef));
279
1
    let elem = infer_pair_element(&car, &cdr).expect("AnyRef cdr accepts any car");
280
1
    assert_eq!(elem, PairElement::AnyRef);
281
1
}
282

            
283
#[test]
284
1
fn ratio_car_with_pair_of_string_cdr_widens_to_anyref() {
285
1
    let car = Expr::WasmRuntime(WasmType::Ratio);
286
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::StringRef));
287
1
    let elem = infer_pair_element(&car, &cdr).expect("heterogeneous CONS widens to AnyRef");
288
1
    assert_eq!(elem, PairElement::AnyRef);
289
1
}
290

            
291
#[test]
292
1
fn anyref_widen_is_symmetric_and_idempotent() {
293
1
    assert_eq!(
294
1
        PairElement::I32.widen(PairElement::Ratio),
295
1
        PairElement::AnyRef
296
    );
297
1
    assert_eq!(
298
1
        PairElement::Ratio.widen(PairElement::I32),
299
1
        PairElement::AnyRef
300
    );
301
1
    assert_eq!(
302
1
        PairElement::AnyRef.widen(PairElement::I32),
303
1
        PairElement::AnyRef
304
    );
305
1
    assert_eq!(PairElement::I32.widen(PairElement::I32), PairElement::I32);
306
1
}
307

            
308
#[test]
309
1
fn literal_string_car_with_pair_of_ratio_cdr_widens_to_anyref() {
310
    // Regression: before the literal-shape branch ran ahead of the
311
    // cdr-element fallback, a literal String car with a typed Ratio
312
    // cdr was silently classified as Ratio and erroried at codegen
313
    // ("expected ratio, got string"). The widening contract says a
314
    // disagreeing arm widens to AnyRef instead.
315
1
    let car = Expr::String("label".to_string());
316
1
    let cdr = Expr::WasmRuntime(WasmType::PairRef(PairElement::Ratio));
317
1
    let elem = infer_pair_element(&car, &cdr).expect("literal car widens against typed cdr");
318
1
    assert_eq!(elem, PairElement::AnyRef);
319
1
}
320

            
321
#[test]
322
1
fn pair_element_anyref_round_trips_through_wasm_type() {
323
1
    assert_eq!(PairElement::AnyRef.as_wasm_type(), WasmType::AnyRef);
324
1
    assert_eq!(
325
1
        PairElement::from_wasm_type(WasmType::AnyRef),
326
1
        Some(PairElement::AnyRef)
327
    );
328
1
}
329

            
330
#[test]
331
1
fn cons_charges_the_datum_it_builds_to_the_work_budget() {
332
1
    let mut symbols = crate::runtime::SymbolTable::new();
333
1
    let mut list = Expr::Nil;
334
1
    for _ in 0..50 {
335
50
        list = super::cons::cons(&mut symbols, &[int(1), list]).unwrap();
336
    }
337
1
    assert!(symbols.measurements().charged() >= 50 * 51 / 2);
338
1
}
339

            
340
#[test]
341
1
fn append_charges_the_datum_it_builds_to_the_work_budget() {
342
1
    let mut symbols = crate::runtime::SymbolTable::new();
343
1
    let items = Expr::quoted_list((0..40).map(int).collect());
344
1
    let before = symbols.measurements().charged();
345
1
    super::append::append(&mut symbols, &[items.clone(), items]).unwrap();
346
1
    assert!(symbols.measurements().charged() - before >= 80);
347
1
}
348

            
349
#[test]
350
1
fn a_list_growing_cons_loop_exhausts_the_work_budget() {
351
1
    let mut symbols = crate::runtime::SymbolTable::new();
352
1
    let mut list = Expr::Nil;
353
1
    let mut steps = 0_u64;
354
    let outcome = loop {
355
1444
        assert!(steps < 2_000, "no work-budget error after {steps} conses");
356
1444
        match super::cons::cons(&mut symbols, &[int(1), list.clone()]) {
357
1443
            Ok(next) => list = next,
358
1
            Err(err) => break err,
359
        }
360
1443
        steps += 1;
361
    };
362
1
    assert!(matches!(outcome, crate::error::Error::Resource(_)));
363
1
}
364

            
365
#[test]
366
1
fn a_chain_with_an_integer_literal_beyond_the_index_range_is_refused() {
367
1
    for literal in [1 << 30, i64::from(i32::MAX), -(1 << 30) - 1] {
368
3
        let message = chain_pair_element(&[int(1), int(literal)])
369
3
            .expect_err("no index holds it")
370
3
            .to_string();
371
3
        assert!(message.contains("outside the index range"), "{message}");
372
3
        assert!(infer_pair_element(&int(literal), &Expr::Nil).is_err());
373
3
        assert!(
374
3
            infer_pair_element(
375
3
                &int(1),
376
3
                &Expr::Datum(Box::new(Expr::List(vec![int(literal)])))
377
3
            )
378
3
            .is_err()
379
        );
380
    }
381
1
}
382

            
383
#[test]
384
1
fn a_map_function_refusing_the_element_dimension_is_an_error_not_a_guess() {
385
    use super::map_runtime::predict_map_result_element;
386
1
    let symbols = crate::runtime::SymbolTable::with_builtins();
387
1
    let function = crate::reader::Reader::parse_expr("(lambda (z) (index->scalar z))")
388
1
        .expect("function parses");
389
1
    let refused = predict_map_result_element(&symbols, &function, PairElement::Ratio);
390
1
    assert!(
391
1
        matches!(refused, Err(crate::error::Error::Dimension(_))),
392
        "{refused:?}"
393
    );
394
1
    let accepted = predict_map_result_element(&symbols, &function, PairElement::I32);
395
1
    assert_eq!(accepted.expect("an index element fits"), PairElement::Ratio);
396
1
}