1
//! CAR/CDR/CONS list-construction extras, plus LENGTH / APPEND / PAIR?
2
//! (const-fold + runtime pair-chain paths).
3

            
4
use super::common::{compile_and_validate, compile_expect_error, wrap_with_runtime_ratio};
5

            
6
#[test]
7
1
fn car_of_static_pair() {
8
1
    compile_and_validate("(car (cons 1 nil))");
9
1
}
10

            
11
#[test]
12
1
fn cdr_of_static_pair() {
13
1
    compile_and_validate("(cdr (cons 1 (cons 2 nil)))");
14
1
}
15

            
16
#[test]
17
1
fn list_constructor_with_constants() {
18
1
    compile_and_validate("(list 1 2 3)");
19
1
}
20

            
21
#[test]
22
1
fn list_with_strings() {
23
1
    compile_and_validate("(list \"a\" \"b\" \"c\")");
24
1
}
25

            
26
#[test]
27
1
fn list_empty_is_nil() {
28
1
    compile_and_validate("(list)");
29
1
}
30

            
31
#[test]
32
1
fn cons_chain_three_levels() {
33
1
    compile_and_validate("(cons 1 (cons 2 (cons 3 (cons 4 nil))))");
34
1
}
35

            
36
#[test]
37
1
fn car_after_cons_of_quoted_constant() {
38
1
    compile_and_validate("(car '(1 2 3))");
39
1
}
40

            
41
#[test]
42
1
fn cdr_after_cons_of_quoted_constant() {
43
1
    compile_and_validate("(cdr '(1 2 3))");
44
1
}
45

            
46
#[test]
47
1
fn car_cdr_of_quoted_constant_at_value_position() {
48
    // Quoted-datum CAR/CDR lowers on BOTH compile surfaces: a numeric element
49
    // folds to its value; a quoted tail or a nested list is the `$pair` chain
50
    // of its members; a symbol head renders as its printed name.
51
1
    compile_and_validate("(cdr '(1 2 3))");
52
1
    compile_and_validate("(car '(1 2 3))");
53
1
    compile_and_validate("(car (cdr '(1 2 3)))");
54
1
    compile_and_validate("(car '((1 2) 3))");
55
1
    compile_and_validate("(car '(x y))");
56
1
    compile_and_validate("(cdr '(a b c))");
57
1
}
58

            
59
#[test]
60
1
fn reverse_cons_of_constant_list_at_value_position() {
61
    // Same divergence class as CAR/CDR: a constant / runtime-builder list
62
    // through REVERSE or CONS folds to a datum that the eval-with-type stack
63
    // handler used to reject. Both surfaces now lower it.
64
1
    compile_and_validate("(reverse '(1 2 3))");
65
1
    compile_and_validate("(reverse (list 1 2 3))");
66
1
    compile_and_validate("(cons 0 '(1 2 3))");
67
1
    compile_and_validate("(cons 0 (list 1 2 3))");
68
    // A dotted pair has no `$pair` representation (plan 0014 Stage 1): the
69
    // structured rejection, never a printed string.
70
1
    let err = compile_expect_error("(cons 1 2)");
71
1
    assert!(
72
1
        err.contains("'(1 . 2) has no list cell representation"),
73
        "{err}"
74
    );
75
1
    compile_and_validate("(append '(1 2) '(3))");
76
1
    compile_and_validate("(append '(a b) '(c))");
77
1
}
78

            
79
#[test]
80
1
fn map_over_static_list() {
81
1
    compile_and_validate("(defun double (x) (* x 2)) (map (function double) '(1 2 3))");
82
1
}
83

            
84
#[test]
85
1
fn reverse_static_list() {
86
1
    compile_and_validate("(reverse '(1 2 3))");
87
1
}
88

            
89
#[test]
90
1
fn reverse_empty_list() {
91
1
    compile_and_validate("(reverse '())");
92
1
}
93

            
94
#[test]
95
1
fn map_with_let_bound_lambda_over_static_list() {
96
    // Runtime closure dispatch on a literal list — rewrites per-element
97
    // funcall via call_ref.
98
1
    compile_and_validate("(let ((double (lambda (x) (* x 2)))) (map double '(1 2 3)))");
99
1
}
100

            
101
#[test]
102
1
fn map_with_let_bound_lambda_over_runtime_pair_chain() {
103
    // Runtime closure + runtime PairRef list — full reverse-build-then-
104
    // reverse loop.
105
1
    compile_and_validate(&wrap_with_runtime_ratio(
106
1
        "(let ((double (lambda (n) (* n 2/1)))) \
107
1
         (map double (cons X (cons (transaction-post-date 1) nil))))",
108
1
    ));
109
1
}
110

            
111
#[test]
112
1
fn map_static_fn_over_runtime_pair_chain() {
113
    // Static defun + runtime PairRef list — exercise the runtime-list
114
    // path with a non-closure callee.
115
1
    compile_and_validate(&wrap_with_runtime_ratio(
116
1
        "(defun double (n) (* n 2/1)) \
117
1
         (map (function double) (cons X (cons (transaction-post-date 1) nil)))",
118
1
    ));
119
1
}
120

            
121
#[test]
122
1
fn reverse_runtime_pair_chain() {
123
    // (cons X (cons (transaction-post-date 1) ...)) builds a runtime
124
    // PairRef<ratio> chain — reverse must walk the cells via the
125
    // pair_new accumulator loop, not constant-fold.
126
1
    compile_and_validate(&wrap_with_runtime_ratio(
127
1
        "(reverse (cons X (cons (transaction-post-date 1) nil)))",
128
1
    ));
129
1
}
130

            
131
#[test]
132
1
fn filter_constant_fold_with_static_pred() {
133
1
    compile_and_validate("(defun pos? (x) (< 0 x)) (filter (function pos?) '(1 -1 2 -2 3))");
134
1
}
135

            
136
#[test]
137
1
fn filter_with_let_bound_lambda_over_static_list() {
138
    // Runtime closure dispatch over a literal list — per-element
139
    // FUNCALL → call_ref + truth-flag prepend loop.
140
1
    compile_and_validate("(let ((pos? (lambda (x) (< 0 x)))) (filter pos? '(1 -1 2 -2 3)))");
141
1
}
142

            
143
#[test]
144
1
fn filter_static_fn_over_runtime_pair_chain() {
145
    // Static predicate + runtime PairRef list — exercises the
146
    // runtime-list path with the predicate routed through FUNCALL.
147
1
    compile_and_validate(&wrap_with_runtime_ratio(
148
1
        "(defun pos? (x) (< 0/1 x)) \
149
1
         (filter (function pos?) (cons X (cons (transaction-post-date 1) nil)))",
150
1
    ));
151
1
}
152

            
153
#[test]
154
1
fn filter_with_let_bound_lambda_over_runtime_pair_chain() {
155
    // Runtime closure + runtime PairRef — full reverse-build-then-
156
    // reverse loop with conditional prepend.
157
1
    compile_and_validate(&wrap_with_runtime_ratio(
158
1
        "(let ((pos? (lambda (x) (< 0/1 x)))) \
159
1
         (filter pos? (cons X (cons (transaction-post-date 1) nil))))",
160
1
    ));
161
1
}
162

            
163
#[test]
164
1
fn fold_constant_fold_sum() {
165
1
    compile_and_validate("(defun add (a b) (+ a b)) (fold (function add) 0 '(1 2 3 4))");
166
1
}
167

            
168
#[test]
169
1
fn fold_with_let_bound_lambda_over_static_list() {
170
    // Runtime closure threading the accumulator through the literal
171
    // path's per-element FUNCALL → call_ref.
172
1
    compile_and_validate(
173
1
        "(let ((acc-add (lambda (acc x) (+ acc x)))) (fold acc-add 0 '(1 2 3 4)))",
174
1
    );
175
1
}
176

            
177
#[test]
178
1
fn fold_static_fn_over_runtime_pair_chain() {
179
    // Static fn + runtime PairRef list — runtime-list FOLD path.
180
1
    compile_and_validate(&wrap_with_runtime_ratio(
181
1
        "(defun add (a b) (+ a b)) \
182
1
         (fold (function add) 0/1 (cons X (cons (transaction-post-date 1) nil)))",
183
1
    ));
184
1
}
185

            
186
#[test]
187
1
fn fold_with_let_bound_lambda_over_runtime_pair_chain() {
188
1
    compile_and_validate(&wrap_with_runtime_ratio(
189
1
        "(let ((acc-add (lambda (acc x) (+ acc x)))) \
190
1
         (fold acc-add 0/1 (cons X (cons (transaction-post-date 1) nil))))",
191
1
    ));
192
1
}
193

            
194
// LENGTH / APPEND / PAIR? — previously phantom natives (registered
195
// symbols + documented, no codegen handler). Regression for that hole.
196

            
197
#[test]
198
1
fn length_constant_folds() {
199
1
    compile_and_validate("(length '(1 2 3))");
200
1
}
201

            
202
#[test]
203
1
fn length_in_index_arithmetic() {
204
    // ADR-0028: LENGTH is an Index (a count), so it composes with Index
205
    // arithmetic — `(+ 1 (length …))` is Index + Index → Index.
206
1
    compile_and_validate("(+ 1 (length '(1 2 3)))");
207
1
}
208

            
209
#[test]
210
1
fn length_runtime_in_index_arithmetic() {
211
    // A runtime LENGTH is a runtime Index and composes with an integer literal
212
    // under Index arithmetic (it does not implicitly become a Scalar).
213
1
    compile_and_validate(&wrap_with_runtime_ratio(
214
1
        "(+ (length (cons X (cons (transaction-post-date 1) nil))) 1)",
215
1
    ));
216
1
}
217

            
218
#[test]
219
1
fn length_runtime_pair_chain() {
220
1
    compile_and_validate(&wrap_with_runtime_ratio(
221
1
        "(length (cons X (cons (transaction-post-date 1) nil)))",
222
1
    ));
223
1
}
224

            
225
#[test]
226
1
fn length_runtime_compared_to_constant() {
227
    // The canonical use: `(= (length …) N)` on a runtime chain.
228
1
    compile_and_validate(&wrap_with_runtime_ratio(
229
1
        "(= (length (cons X (cons (transaction-post-date 1) nil))) 2)",
230
1
    ));
231
1
}
232

            
233
#[test]
234
1
fn append_constant_folds() {
235
1
    compile_and_validate("(append '(1 2) '(3 4))");
236
1
}
237

            
238
#[test]
239
1
fn append_runtime_chain_with_nil() {
240
1
    compile_and_validate(&wrap_with_runtime_ratio(
241
1
        "(append (cons X (cons (transaction-post-date 1) nil)) nil)",
242
1
    ));
243
1
}
244

            
245
/// General concat: a runtime list followed by a NON-empty constant list. The
246
/// constant operand is materialized into a runtime `$pair` chain (the cell
247
/// type is monomorphic), so this is no longer rejected.
248
#[test]
249
1
fn append_runtime_chain_then_constant_list() {
250
1
    compile_and_validate(&wrap_with_runtime_ratio("(append (cons X nil) '(1 2))"));
251
1
}
252

            
253
/// Mirror: a constant list followed by a runtime chain.
254
#[test]
255
1
fn append_constant_list_then_runtime_chain() {
256
1
    compile_and_validate(&wrap_with_runtime_ratio("(append '(1 2) (cons X nil))"));
257
1
}
258

            
259
/// A constant string list materialized alongside a runtime chain — string
260
/// members lower through the cons builder as data.
261
#[test]
262
1
fn append_constant_string_list_with_runtime_chain() {
263
1
    compile_and_validate(&wrap_with_runtime_ratio(
264
1
        "(append (cons (transaction-post-date 1) nil) '(7 8))",
265
1
    ));
266
1
}
267

            
268
/// Round-2 regression: a constant list of symbols quoted into an APPEND is a
269
/// symbol chain, not "Undefined symbol A" from re-evaluating the datum as a
270
/// variable reference.
271
#[test]
272
1
fn append_constant_symbol_list_is_a_symbol_chain() {
273
1
    compile_and_validate(&wrap_with_runtime_ratio("(append '(a b) (cons X nil))"));
274
1
}
275

            
276
#[test]
277
1
fn pair_p_true_on_constant_list() {
278
1
    compile_and_validate("(pair? '(1 2 3))");
279
1
}
280

            
281
#[test]
282
1
fn pair_p_false_on_nil() {
283
1
    compile_and_validate("(pair? nil)");
284
1
}
285

            
286
#[test]
287
1
fn pair_p_runtime_chain() {
288
1
    compile_and_validate(&wrap_with_runtime_ratio("(pair? (cons X nil))"));
289
1
}
290

            
291
#[test]
292
1
fn pair_p_in_value_position() {
293
1
    compile_and_validate("(defun is-pair (x) (pair? x)) (is-pair '(1))");
294
1
}
295

            
296
// MAP / FILTER / FOLD with a callback whose body isn't constant-foldable
297
// (produces a runtime value or a side effect). The const-folders used to
298
// either crash (FOLD: serialize a placeholder with no stack producer) or
299
// silently bake the placeholder in / drop the side effect (MAP/FILTER). They
300
// now detect a runtime callback result and route to per-element runtime
301
// lowering. Pre-existing bug class, fixed together.
302

            
303
#[test]
304
1
fn fold_nil_seed_build_list_over_runtime_list() {
305
    // nil-seeded accumulator built into a list over a runtime chain — the
306
    // accumulator is sized from the body's PairRef return, nil seeds to a
307
    // null pair (was: "init type bool doesn't match accumulator type").
308
1
    compile_and_validate(&wrap_with_runtime_ratio(
309
1
        "(fold (lambda (acc x) (cons x acc)) nil (cons X nil))",
310
1
    ));
311
1
}
312

            
313
#[test]
314
1
fn fold_print_body_runs_at_runtime() {
315
1
    compile_and_validate("(fold (lambda (acc x) (print x)) 0 '(1 2))");
316
1
}
317

            
318
#[test]
319
1
fn map_print_body_emits_per_element() {
320
1
    let with = compile_and_validate("(map (lambda (x) (print \"yyyyyyyy\")) '(1 2 3))");
321
1
    let without = compile_and_validate("(map (lambda (x) x) '(1 2 3))");
322
1
    assert!(
323
1
        with.len() > without.len(),
324
        "map per-element print dropped: {} vs {}",
325
        with.len(),
326
        without.len()
327
    );
328
1
}
329

            
330
#[test]
331
1
fn filter_print_body_emits_per_element() {
332
1
    let with = compile_and_validate("(filter (lambda (x) (print \"yyyyyyyy\")) '(1 2 3))");
333
1
    let without = compile_and_validate("(filter (lambda (x) t) '(1 2 3))");
334
1
    assert!(
335
1
        with.len() > without.len(),
336
        "filter per-element print dropped: {} vs {}",
337
        with.len(),
338
        without.len()
339
    );
340
1
}
341

            
342
#[test]
343
1
fn map_runtime_body_over_constant_list() {
344
1
    compile_and_validate("(map (lambda (x) (transaction-post-date 0)) '(1 2))");
345
1
}
346

            
347
#[test]
348
1
fn filter_runtime_predicate_over_constant_list() {
349
1
    compile_and_validate("(filter (lambda (x) (transaction-is-multi-currency 0)) '(1 2))");
350
1
}
351

            
352
// Runtime-bail edge cases (HOF review round). Each was rejected/mis-lowered
353
// after the initial const-fold→runtime bail; now handled.
354

            
355
/// FOLD forced onto the runtime path (side-effecting body) with a NON-nil
356
/// constant-list accumulator seed. The seed is materialized into a runtime
357
/// `$pair` chain (was: "cannot compile to WASM stack value: '(1)").
358
#[test]
359
1
fn fold_runtime_body_with_constant_list_seed() {
360
1
    compile_and_validate("(fold (lambda (acc x) (print x) acc) '(1) '(2))");
361
1
}
362

            
363
/// MAP whose per-element results have DIFFERENT types widens the result chain
364
/// to `AnyRef` (ADR-0025) instead of erroring "heterogeneous result elements".
365
#[test]
366
1
fn map_heterogeneous_results_widen_to_anyref() {
367
1
    compile_and_validate("(map (lambda (x) (if (= x 1) (print x) (tag-name 0))) '(1 2))");
368
1
}
369

            
370
/// FILTER over a heterogeneous constant list (ratio + string) widens the kept
371
/// chain to `AnyRef` instead of erroring "heterogeneous element types".
372
#[test]
373
1
fn filter_heterogeneous_list_widens_to_anyref() {
374
1
    compile_and_validate("(filter (lambda (x) (print x)) '(1 \"a\"))");
375
1
}
376

            
377
/// MAP over MULTIPLE constant lists with a non-constant-foldable body lowers
378
/// row-by-row at runtime (was: "requires exactly one list argument").
379
#[test]
380
1
fn map_multi_list_runtime_body() {
381
1
    compile_and_validate("(map (lambda (x y) (print x)) '(1 2) '(3 4))");
382
1
}
383

            
384
/// Multi-list MAP that IS constant-foldable still folds.
385
#[test]
386
1
fn map_multi_list_constant_folds() {
387
1
    compile_and_validate("(map (lambda (a b) (+ a b)) '(1 2) '(3 4))");
388
1
}
389

            
390
/// ADR-0028: a FOLD over a let-bound closure, bound in turn in a `let`, sizes
391
/// the binding local from the COMPILED (closure-sig) accumulator type. The
392
/// eval side can't see the closure sig and falls back to the integer seed's
393
/// type (Index); without sizing from codegen the binding would `local.set` a
394
/// Ratio value into an I32 local — invalid wasm.
395
#[test]
396
1
fn fold_closure_result_bound_in_let_compiles() {
397
1
    compile_and_validate(
398
1
        "(let* ((f (lambda (a x) (+ a x))) \
399
1
                (acc (fold f 0/1 (cons (transaction-post-date 0) nil)))) \
400
1
           acc)",
401
1
    );
402
1
}
403

            
404
/// A wrong-arity closure used as a FILTER predicate over an EMPTY list is still
405
/// arity-checked — no element reaches `compile_call_ref`, so the empty-list
406
/// fast path validates the predicate's arity itself.
407
#[test]
408
1
fn filter_wrong_arity_closure_over_empty_list_errors() {
409
1
    let err = compile_expect_error("(let ((f (lambda (a b) (< a b)))) (filter f '()))");
410
1
    assert!(
411
1
        err.to_lowercase().contains("arity") || err.contains("closure") || err.contains("argument"),
412
        "expected an arity error, got: {err}"
413
    );
414
1
}
415

            
416
/// A symbol or keyword is a `$symbol` struct in every value position; the
417
/// module validates (plan 0014 Stage 8).
418
#[test]
419
1
fn runtime_symbols_validate() {
420
1
    for src in [
421
1
        "(let ((y nil)) (setf y 'z) y)",
422
1
        "(defvar k :a) (setf k :a) (list (eq? k :a) (eq? k :b))",
423
1
        "(defun pick (c) (if c 'x 'y)) (list (pick t) (pick nil))",
424
1
        "(defvar y '(a b)) (dolist (x y 'done) (print x))",
425
1
        "(let ((a 'x) (b 'y)) (setf b 'x) (eql a b))",
426
1
        "(defvar s 'abc) (setf s 'abc) (string= s \"ABC\")",
427
1
        "(list 'a 1 \"s\")",
428
1
        "(cons 'a nil)",
429
1
        "(car '(a b))",
430
1
    ] {
431
9
        compile_and_validate(src);
432
    }
433
1
}