1
// Skipped under Miri: these tests compile+run wasm via wasmtime, whose
2
// Cranelift backend refuses to run under Miri.
3
#![cfg(not(miri))]
4

            
5
use nms::interpreter::Interpreter;
6
use scripting::nomiscript::{Fraction, Number, Pair, Value, vec_to_list};
7

            
8
12
fn int(n: i64) -> Value {
9
12
    Value::Number(Number::Index(n))
10
12
}
11

            
12
5
fn ints(items: &[i64]) -> Value {
13
11
    vec_to_list(items.iter().map(|n| int(*n)).collect())
14
5
}
15

            
16
// LIST
17

            
18
#[test]
19
1
fn test_eval_list_empty() {
20
1
    let mut interp = Interpreter::new(false).unwrap();
21
1
    let results = interp.eval("(list)").unwrap();
22
1
    assert_eq!(results, vec![Value::Nil]);
23
1
}
24

            
25
#[test]
26
1
fn test_eval_list_numbers() {
27
1
    let mut interp = Interpreter::new(false).unwrap();
28
1
    let results = interp.eval("(list 1 2 3)").unwrap();
29
1
    assert_eq!(results, vec![ints(&[1, 2, 3])]);
30
1
}
31

            
32
#[test]
33
1
fn test_eval_list_mixed() {
34
1
    let mut interp = Interpreter::new(false).unwrap();
35
1
    let results = interp.eval(r#"(list 1 "hello" t)"#).unwrap();
36
1
    assert_eq!(
37
1
        results,
38
1
        vec![vec_to_list(vec![
39
1
            int(1),
40
1
            Value::String("hello".to_string()),
41
1
            Value::T
42
1
        ])]
43
    );
44
1
}
45

            
46
// CONS
47

            
48
#[test]
49
1
fn test_eval_cons_onto_list() {
50
1
    let mut interp = Interpreter::new(false).unwrap();
51
1
    let results = interp.eval("(cons 1 (list 2 3))").unwrap();
52
1
    assert_eq!(results, vec![ints(&[1, 2, 3])]);
53
1
}
54

            
55
#[test]
56
1
fn test_eval_cons_onto_nil() {
57
1
    let mut interp = Interpreter::new(false).unwrap();
58
1
    let results = interp.eval("(cons 1 nil)").unwrap();
59
1
    assert_eq!(results, vec![ints(&[1])]);
60
1
}
61

            
62
#[test]
63
1
fn test_eval_cons_arity_error() {
64
1
    let mut interp = Interpreter::new(false).unwrap();
65
1
    assert!(interp.eval("(cons 1)").is_err());
66
1
    assert!(interp.eval("(cons 1 2 3)").is_err());
67
1
}
68

            
69
#[test]
70
1
fn test_eval_numeric_literal_in_list_stays_ratio() {
71
    // A numeric literal is a dimensionless Ratio in EVERY context — including a
72
    // pair cell — never an i32 count. Reclassifying an integer literal to I32
73
    // when it rides a list cell was an illegal implicit Ratio→count conversion:
74
    // the `5` came back from CAR as a count and arithmetic refused it. These
75
    // exercise the RUNTIME pair path (a runtime element forces the chain
76
    // runtime), so the literal `5` must survive as a usable Ratio.
77
1
    let mut interp = Interpreter::new(false).unwrap();
78
    // CAR of a runtime list holding `5` then arithmetic on it.
79
1
    assert_eq!(
80
1
        interp
81
1
            .eval("(let* ((p (cons 5 (cons (transaction-post-date 0) nil)))) (+ (car p) 1/1))")
82
1
            .unwrap(),
83
1
        vec![Value::Number(Number::Scalar(Fraction::new(6, 1)))]
84
    );
85
    // CL 6: a cell holds a scalar, so the bare integer beside it is a mix.
86
1
    let refused = interp
87
1
        .eval("(let* ((p (cons 5 (cons (transaction-post-date 0) nil)))) (+ (car p) 1))")
88
1
        .expect_err("a mix");
89
1
    assert!(
90
1
        refused
91
1
            .to_string()
92
1
            .contains("+ cannot mix an index (count) with a scalar"),
93
        "{refused}"
94
    );
95
    // a mixed literal+runtime list no longer miscompiles to Bool; CAR is 5.
96
1
    assert_eq!(
97
1
        interp
98
1
            .eval("(car (list 5 (transaction-post-date 0)))")
99
1
            .unwrap(),
100
1
        vec![Value::Number(Number::Scalar(Fraction::new(5, 1)))]
101
    );
102
1
}
103

            
104
// CAR over a list whose element is a RUNTIME value (#57). `(list <runtime>)`
105
// used to embed the runtime placeholder inside a quoted compile-time list, so
106
// CAR extracted a bare placeholder with no stack value -> invalid wasm. Now
107
// `list` desugars a runtime element to the CONS chain, so every element type
108
// round-trips through the $pair stack path.
109

            
110
#[test]
111
1
fn test_eval_car_of_list_with_runtime_i32() {
112
    // tag-count is 0 on the minimal input; the i32 COUNT element keeps Number.
113
1
    let mut interp = Interpreter::new(false).unwrap();
114
1
    assert_eq!(
115
1
        interp
116
1
            .eval("(car (list (transaction-tag-count 0)))")
117
1
            .unwrap(),
118
1
        vec![Value::Number(Number::Index(0))]
119
    );
120
1
}
121

            
122
#[test]
123
1
fn test_eval_car_of_list_with_runtime_ratio() {
124
1
    let mut interp = Interpreter::new(false).unwrap();
125
1
    assert_eq!(
126
1
        interp
127
1
            .eval("(car (list (transaction-post-date 0)))")
128
1
            .unwrap(),
129
1
        vec![Value::Number(Number::Scalar(Fraction::new(0, 1)))]
130
    );
131
1
}
132

            
133
#[test]
134
1
fn test_eval_car_of_list_with_runtime_bool() {
135
    // A bool element rides its own PairElement::Bool slot, so CAR recovers a
136
    // truth value: (= 0 0) -> T, (< 0 0) -> Nil — NOT Number(1)/(0).
137
1
    let mut interp = Interpreter::new(false).unwrap();
138
1
    assert_eq!(
139
1
        interp
140
1
            .eval("(car (list (= (transaction-tag-count 0) 0)))")
141
1
            .unwrap(),
142
1
        vec![Value::T]
143
    );
144
1
    assert_eq!(
145
1
        interp
146
1
            .eval("(car (list (< 0 (transaction-tag-count 0))))")
147
1
            .unwrap(),
148
1
        vec![Value::Nil]
149
    );
150
1
}
151

            
152
#[test]
153
1
fn test_eval_cdr_then_car_of_multi_runtime_list() {
154
    // Two runtime bool elements; CDR then CAR reaches the second cell.
155
1
    let mut interp = Interpreter::new(false).unwrap();
156
1
    assert_eq!(
157
1
        interp
158
1
            .eval(
159
1
                "(car (cdr (list (= (transaction-tag-count 0) 0) \
160
1
                 (< 0 (transaction-tag-count 0)))))"
161
1
            )
162
1
            .unwrap(),
163
1
        vec![Value::Nil]
164
    );
165
1
}
166

            
167
#[test]
168
1
fn test_eval_do_accumulator_of_runtime_cons_car() {
169
    // A `do` whose accumulator step is `(cons <host-fn-call> acc)` must size the
170
    // accumulator local from the (eval-resolved) cons car's element type. The
171
    // car is a not-yet-reduced `(transaction-… i)` List form; the pair-element
172
    // walker now evals it on a clone instead of falling to the scalar default
173
    // (which mis-sized `acc` and failed CONS cdr typing). Pre-existing bug
174
    // surfaced while completing the PairElement::Bool work.
175
1
    let mut interp = Interpreter::new(false).unwrap();
176
    // i32 car: CAR of the accumulated list keeps Number.
177
1
    assert_eq!(
178
1
        interp
179
1
            .eval(
180
1
                "(car (do ((i 0 (+ i 1)) \
181
1
                 (acc nil (cons (transaction-tag-count 0) acc))) \
182
1
                 ((= i 3) acc)))"
183
1
            )
184
1
            .unwrap(),
185
1
        vec![Value::Number(Number::Index(0))]
186
    );
187
    // bool car: CAR recovers a truth value (Bool), not Number.
188
1
    assert_eq!(
189
1
        interp
190
1
            .eval(
191
1
                "(car (do ((i 0 (+ i 1)) \
192
1
                 (acc nil (cons (= (transaction-tag-count 0) 0) acc))) \
193
1
                 ((= i 3) acc)))"
194
1
            )
195
1
            .unwrap(),
196
1
        vec![Value::T]
197
    );
198
1
}
199

            
200
#[test]
201
1
fn test_eval_runtime_list_applies_element_side_effects_once() {
202
    // A runtime `(list …)` desugars to a CONS chain built from the
203
    // already-resolved elements, NOT a re-eval of the source args — so a SETF
204
    // side effect in an element runs exactly once. `n` ends at 1, not 2.
205
1
    let mut interp = Interpreter::new(false).unwrap();
206
1
    assert_eq!(
207
1
        interp
208
1
            .eval("(let* ((n 0)) (list (transaction-tag-count 0) (setf n (+ n 1))) n)")
209
1
            .unwrap(),
210
1
        vec![Value::Number(Number::Index(1))]
211
    );
212
1
}
213

            
214
#[test]
215
1
fn test_eval_apply_spreads_the_builtin_list() {
216
1
    let mut interp = Interpreter::new(false).unwrap();
217
1
    assert_eq!(
218
1
        interp
219
1
            .eval("(defun f (a) (+ a 100)) (apply (function f) (list 5))")
220
1
            .unwrap(),
221
1
        vec![Value::Number(Number::Index(105))]
222
    );
223
1
}
224

            
225
// QUOTE
226

            
227
#[test]
228
1
fn test_eval_quote_number() {
229
1
    let mut interp = Interpreter::new(false).unwrap();
230
1
    let results = interp.eval("(quote 42)").unwrap();
231
1
    assert_eq!(results, vec![Value::Number(Number::Index(42))]);
232
1
}
233

            
234
#[test]
235
1
fn test_eval_quote_reader_sugar() {
236
1
    let mut interp = Interpreter::new(false).unwrap();
237
1
    let results = interp.eval("'42").unwrap();
238
1
    assert_eq!(results, vec![Value::Number(Number::Index(42))]);
239
1
}
240

            
241
#[test]
242
1
fn test_eval_quote_string() {
243
1
    let mut interp = Interpreter::new(false).unwrap();
244
1
    let results = interp.eval("(quote \"hello\")").unwrap();
245
1
    assert_eq!(results, vec![Value::String("hello".to_string())]);
246
1
}
247

            
248
// DESCRIBE
249

            
250
#[test]
251
1
fn test_eval_describe_function() {
252
1
    let mut interp = Interpreter::new(false).unwrap();
253
1
    let results = interp
254
1
        .eval(r#"(defun sum (a b) "Adds two numbers" (+ a b)) (describe sum)"#)
255
1
        .unwrap();
256
1
    match &results[0] {
257
        Value::String(s) => {
258
1
            assert!(s.contains("SUM is a function"), "got: {s}");
259
1
            assert!(s.contains("Lambda:"), "got: {s}");
260
1
            assert!(s.contains("Adds two numbers"), "got: {s}");
261
        }
262
        _ => panic!("expected string, got {:?}", results[0]),
263
    }
264
1
}
265

            
266
#[test]
267
1
fn test_eval_describe_variable() {
268
1
    let mut interp = Interpreter::new(false).unwrap();
269
1
    let results = interp
270
1
        .eval(r#"(defvar *x* 42 "The answer") (describe *x*)"#)
271
1
        .unwrap();
272
1
    match &results[0] {
273
        Value::String(s) => {
274
1
            assert!(s.contains("*X* is a variable"), "got: {s}");
275
1
            assert!(s.contains("Value: 42"), "got: {s}");
276
1
            assert!(s.contains("The answer"), "got: {s}");
277
        }
278
        _ => panic!("expected string, got {:?}", results[0]),
279
    }
280
1
}
281

            
282
// Nested calls
283

            
284
#[test]
285
1
fn test_nested_comparison_with_subtraction() {
286
1
    let mut interp = Interpreter::new(false).unwrap();
287
1
    assert_eq!(interp.eval("(= 1 (- 3 2))").unwrap(), vec![Value::T]);
288
1
}
289

            
290
#[test]
291
1
fn test_nested_addition_with_multiplication() {
292
1
    let mut interp = Interpreter::new(false).unwrap();
293
1
    assert_eq!(
294
1
        interp.eval("(+ 1 (* 2 3))").unwrap(),
295
1
        vec![Value::Number(Number::Index(7))]
296
    );
297
1
}
298

            
299
#[test]
300
1
fn test_nested_subtraction_multiple_args() {
301
1
    let mut interp = Interpreter::new(false).unwrap();
302
1
    assert_eq!(
303
1
        interp.eval("(- 10 (+ 1 2) (- 5 2))").unwrap(),
304
1
        vec![Value::Number(Number::Index(4))]
305
    );
306
1
}
307

            
308
#[test]
309
1
fn test_nested_addition_both_sides() {
310
1
    let mut interp = Interpreter::new(false).unwrap();
311
1
    assert_eq!(
312
1
        interp.eval("(+ (+ 1 2) (+ 3 4))").unwrap(),
313
1
        vec![Value::Number(Number::Index(10))]
314
    );
315
1
}
316

            
317
#[test]
318
1
fn test_deeply_nested_addition() {
319
1
    let mut interp = Interpreter::new(false).unwrap();
320
1
    assert_eq!(
321
1
        interp.eval("(+ 1 (+ 2 (+ 3 4)))").unwrap(),
322
1
        vec![Value::Number(Number::Index(10))]
323
    );
324
1
}
325

            
326
#[test]
327
1
fn test_nested_calls_with_defun() {
328
1
    let mut interp = Interpreter::new(false).unwrap();
329
1
    assert_eq!(
330
1
        interp
331
1
            .eval("(defun double (x) (* x 2)) (+ (double 3) (double 4))")
332
1
            .unwrap(),
333
1
        vec![Value::Number(Number::Index(14))]
334
    );
335
1
}
336

            
337
#[test]
338
1
fn test_nested_equal_with_arithmetic() {
339
1
    let mut interp = Interpreter::new(false).unwrap();
340
1
    assert_eq!(
341
1
        interp.eval("(equal (+ 1 1) (- 4 2))").unwrap(),
342
1
        vec![Value::T]
343
    );
344
1
}
345

            
346
#[test]
347
1
fn test_nested_funcall_with_arithmetic() {
348
1
    let mut interp = Interpreter::new(false).unwrap();
349
1
    assert_eq!(
350
1
        interp.eval("(funcall #'+ (- 10 3) (* 2 3))").unwrap(),
351
1
        vec![Value::Number(Number::Index(13))]
352
    );
353
1
}
354

            
355
/// A dotted datum onto a list or `nil` tail is the proper list it spells
356
/// (one `$pair` representation, plan 0014 Stage 1, a symbol member riding a
357
/// symbol cell); a non-list tail has no cell representation and is the
358
/// structured rejection, never a printed string.
359
#[test]
360
1
fn quoted_dotted_lists_are_the_proper_lists_they_spell() {
361
1
    let mut interp = Interpreter::new(false).unwrap();
362
1
    assert_eq!(interp.eval("'(1 . (2 3))").unwrap(), vec![ints(&[1, 2, 3])]);
363
1
    assert_eq!(interp.eval("'(1 . nil)").unwrap(), vec![ints(&[1])]);
364
1
    assert_eq!(
365
1
        interp.eval("'(a . nil)").unwrap(),
366
1
        vec![vec_to_list(vec![Value::Symbol("A".into())])]
367
    );
368
1
    let err = interp
369
1
        .eval("'(1 . 2)")
370
1
        .expect_err("a dotted pair")
371
1
        .to_string();
372
1
    assert!(
373
1
        err.contains("'(1 . 2) has no list cell representation"),
374
        "{err}"
375
    );
376
1
}
377

            
378
// ADR-0033 Phase 3: an index widened into an AnyRef (a missing-else beside a
379
// count) must decode as its Number, not the pre-Phase-3 "non-null marker"
380
// boolean.
381
#[test]
382
1
fn test_count_widened_to_anyref_decodes_as_its_number() {
383
1
    let mut interp = Interpreter::new(false).unwrap();
384
1
    let results = interp
385
1
        .eval("(if (>= (entity-count) 0) (entity-count))")
386
1
        .unwrap();
387
1
    assert_eq!(results, vec![Value::Number(Number::Index(0))]);
388
1
}
389

            
390
// A `t` literal riding a widened `AnyRef` result must decode by identity
391
// against the `$t` singleton, not the pre-Phase-3 non-null-marker fallback.
392
#[test]
393
1
fn test_t_widened_to_anyref_decodes_as_t() {
394
1
    let mut interp = Interpreter::new(false).unwrap();
395
1
    let results = interp
396
1
        .eval("(if (>= (entity-count) 0) t (entity-count))")
397
1
        .unwrap();
398
1
    assert_eq!(results, vec![Value::T]);
399
1
}
400

            
401
// ADR-0033 Phase 6: a Ratio riding a widened `AnyRef` result (here, `or`'s
402
// Bool-vs-Ratio arm mismatch) must decode as its own Number, not the
403
// pre-Phase-6 non-null-marker fallback (which wrote the `T` tag for any
404
// struct/array car it didn't recognise).
405
#[test]
406
1
fn test_ratio_widened_to_anyref_decodes_as_its_number_in_the_debug_serializer() {
407
1
    let mut interp = Interpreter::new(false).unwrap();
408
1
    let results = interp
409
1
        .eval("(or (> (entity-count) 5) (index->scalar (entity-count)))")
410
1
        .unwrap();
411
1
    assert_eq!(
412
1
        results,
413
1
        vec![Value::Number(Number::Scalar(Fraction::new(0, 1)))]
414
    );
415
1
}
416

            
417
// A String riding a widened `AnyRef` result must decode as its own String,
418
// not the pre-Phase-6 non-null-marker fallback.
419
#[test]
420
1
fn test_string_widened_to_anyref_decodes_as_its_string_in_the_debug_serializer() {
421
1
    let mut interp = Interpreter::new(false).unwrap();
422
1
    let results = interp.eval(r#"(or (> (entity-count) 5) "x")"#).unwrap();
423
1
    assert_eq!(results, vec![Value::String("x".to_string())]);
424
1
}
425

            
426
// A list in a dynamic cell is neither the boolean true nor a placeholder: the
427
// debug serializer walks it like any other list.
428
#[test]
429
1
fn test_pair_widened_to_anyref_decodes_as_its_list_in_the_debug_serializer() {
430
1
    let mut interp = Interpreter::new(false).unwrap();
431
1
    let results = interp
432
1
        .eval("(or (> (transaction-tag-count 0) 0) (list 1))")
433
1
        .unwrap();
434
1
    assert_eq!(
435
1
        results,
436
1
        vec![Pair::cons(Value::Number(Number::Index(1)), Value::Nil)]
437
    );
438
1
}
439

            
440
// A flat COND with 25 genuinely-runtime clauses (past the shared recursion
441
// ceiling of 24) compiles and selects the matching clause; `entity-count` is
442
// 0, so only the 25th test matches.
443
#[test]
444
1
fn test_cond_25_genuinely_runtime_clauses_selects_the_matching_clause() {
445
1
    let mut interp = Interpreter::new(false).unwrap();
446
1
    let leading: String = (1..=24)
447
24
        .map(|i| format!("((= (entity-count) {i}) {i}) "))
448
        .collect();
449
1
    let src = format!("(cond {leading}((= (entity-count) 0) 100) (t 999))");
450
1
    let results = interp.eval(&src).unwrap();
451
1
    assert_eq!(results, vec![Value::Number(Number::Index(100))]);
452
1
}
453

            
454
// Same chain with no matching clause falls through to the `t` clause.
455
#[test]
456
1
fn test_cond_25_genuinely_runtime_clauses_falls_through_to_else() {
457
1
    let mut interp = Interpreter::new(false).unwrap();
458
1
    let clauses: String = (1..=25)
459
25
        .map(|i| format!("((= (entity-count) {i}) {i}) "))
460
        .collect();
461
1
    let src = format!("(cond {clauses}(t 999))");
462
1
    let results = interp.eval(&src).unwrap();
463
1
    assert_eq!(results, vec![Value::Number(Number::Index(999))]);
464
1
}