1
//! LAMBDA / FUNCTION / FUNCALL / APPLY codegen.
2

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

            
5
#[test]
6
1
fn lambda_literal_compiles() {
7
1
    compile_and_validate("(lambda (x) (+ x 1))");
8
1
}
9

            
10
#[test]
11
1
fn lambda_with_rest_param() {
12
1
    let err = compile_expect_error("(lambda (x &rest more) x)");
13
1
    assert!(
14
1
        err.contains("not yet supported as a first-class wasm closure"),
15
        "got: {err}"
16
    );
17
1
}
18

            
19
#[test]
20
1
fn lambda_with_optional_param() {
21
1
    let err = compile_expect_error("(lambda (x &optional (y 10)) (+ x y))");
22
1
    assert!(
23
1
        err.contains("not yet supported as a first-class wasm closure"),
24
        "got: {err}"
25
    );
26
1
}
27

            
28
#[test]
29
1
fn function_form_quotes_symbol() {
30
1
    compile_and_validate("(defun greet (x) x) (function greet)");
31
1
}
32

            
33
#[test]
34
1
fn function_unknown_symbol_errors() {
35
1
    let err = compile_expect_error("(function no-such-fn)");
36
1
    assert!(
37
1
        err.contains("function definition")
38
            || err.contains("no-such-fn")
39
            || err.contains("Undefined")
40
            || err.contains("NO-SUCH-FN"),
41
        "got: {err}",
42
    );
43
1
}
44

            
45
#[test]
46
1
fn funcall_resolves_designator_and_calls() {
47
1
    compile_and_validate("(defun double (x) (* x 2)) (funcall (function double) 5)");
48
1
}
49

            
50
#[test]
51
1
fn funcall_with_runtime_arg() {
52
1
    compile_and_validate(&wrap_with_runtime_ratio(
53
1
        "(defun double (n) (* n 2/1)) (funcall (function double) X)",
54
1
    ));
55
1
}
56

            
57
#[test]
58
1
fn apply_with_list() {
59
1
    compile_and_validate("(defun sum3 (a b c) (+ a b c)) (apply (function sum3) (list 1 2 3))");
60
1
}
61

            
62
#[test]
63
1
fn apply_with_runtime_arg() {
64
1
    compile_and_validate(&wrap_with_runtime_ratio(
65
1
        "(defun id (n) n) (apply (function id) (list X))",
66
1
    ));
67
1
}
68

            
69
#[test]
70
1
fn funcall_empty_args_errors() {
71
1
    let err = compile_expect_error("(funcall)");
72
1
    assert!(
73
1
        err.contains("funcall") || err.contains("FUNCALL") || err.contains("function argument"),
74
        "got: {err}"
75
    );
76
1
}
77

            
78
#[test]
79
1
fn apply_too_few_args_errors() {
80
1
    let err = compile_expect_error("(apply)");
81
1
    assert!(err.contains("apply") || err.contains("APPLY"), "got: {err}");
82
1
}
83

            
84
#[test]
85
1
fn apply_one_arg_errors() {
86
1
    let err = compile_expect_error("(apply (function +))");
87
1
    assert!(err.contains("apply") || err.contains("APPLY"), "got: {err}");
88
1
}
89

            
90
#[test]
91
1
fn apply_with_non_list_last_arg_errors() {
92
1
    let err = compile_expect_error("(defun id (x) x) (apply (function id) 42)");
93
1
    assert!(
94
1
        err.contains("apply") || err.contains("APPLY") || err.contains("quoted list"),
95
        "got: {err}"
96
    );
97
1
}
98

            
99
#[test]
100
1
fn apply_with_quoted_non_list_errors() {
101
    // `'42` is a quoted number, not a quoted list — apply must
102
    // reject so the spread doesn't reinterpret an atom as args.
103
1
    let err = compile_expect_error("(defun id (x) x) (apply (function id) '42)");
104
1
    assert!(
105
1
        err.contains("apply") || err.contains("APPLY") || err.contains("quoted list"),
106
        "got: {err}"
107
    );
108
1
}
109

            
110
#[test]
111
1
fn apply_with_empty_quoted_list_compiles() {
112
    // `apply` with `'()` as the last arg should be a zero-arg call
113
    // — the empty spread is a real use case for variadic helpers.
114
1
    compile_and_validate("(defun zero () 0) (apply (function zero) '())");
115
1
}
116

            
117
#[test]
118
1
fn function_with_lambda_compiles() {
119
    // `(function (lambda ...))` route — exercises the inline lambda
120
    // case in function_form, distinct from the bare symbol case.
121
1
    compile_and_validate("(function (lambda (x) x))");
122
1
}
123

            
124
#[test]
125
1
fn function_with_invalid_arg_errors() {
126
    // Bare number isn't a symbol or lambda — function_form's
127
    // fallback error path.
128
1
    let err = compile_expect_error("(function 42)");
129
1
    assert!(
130
1
        err.contains("symbol or lambda") || err.contains("FUNCTION"),
131
        "got: {err}"
132
    );
133
1
}
134

            
135
#[test]
136
1
fn lambda_missing_body_errors() {
137
1
    let err = compile_expect_error("(lambda)");
138
1
    assert!(
139
1
        err.contains("LAMBDA") || err.contains("parameter list"),
140
        "got: {err}"
141
    );
142
1
}
143

            
144
#[test]
145
1
fn lambda_only_params_errors() {
146
1
    let err = compile_expect_error("(lambda (x))");
147
1
    assert!(
148
1
        err.contains("LAMBDA") || err.contains("parameter list"),
149
        "got: {err}"
150
    );
151
1
}
152

            
153
#[test]
154
1
fn lambda_multi_form_body_wraps_in_progn() {
155
    // Two body forms must be wrapped in PROGN — exercises the
156
    // `forms.push(Symbol("PROGN"))` branch in `lambda()`.
157
1
    compile_and_validate("(funcall (lambda (x) (+ x 1) (+ x 2)) 5)");
158
1
}
159

            
160
/// Tier 1.5 Gap A regression-lock: a FUNCALL whose return value is
161
/// consumed in arithmetic must drive the `stack` callback in
162
/// special::lambda::FORMS — without it, `compile_for_stack` errored
163
/// with "special form 'FUNCALL' cannot produce stack value".
164
#[test]
165
1
fn funcall_at_stack_position_compiles() {
166
1
    compile_and_validate("(defun double (x) (* x 2)) (+ (funcall (function double) 5) 1)");
167
1
}
168

            
169
/// Tier 1.5 Gap A regression-lock: same constraint for APPLY in
170
/// stack position.
171
#[test]
172
1
fn apply_at_stack_position_compiles() {
173
1
    compile_and_validate("(defun sum2 (a b) (+ a b)) (+ (apply (function sum2) (list 3 4)) 1)");
174
1
}
175

            
176
/// Tier 1.5 runtime-closure dispatch: a let-bound lambda used in
177
/// FUNCALL must lower through the `$closure` GC value + `call_ref`
178
/// path, not the inline lambda-call path. Locks the call-site
179
/// rewrite that promotes `Expr::Lambda` inits to `Expr::WasmLocal`
180
/// closures.
181
#[test]
182
1
fn let_bound_lambda_funcall_compiles_via_call_ref() {
183
1
    compile_and_validate("(let ((f (lambda (x) (* x 2)))) (funcall f 5))");
184
1
}
185

            
186
#[test]
187
1
fn let_star_bound_lambda_funcall_compiles_via_call_ref() {
188
1
    compile_and_validate("(let* ((f (lambda (x) (* x 2)))) (funcall f 5))");
189
1
}
190

            
191
/// Stack-position variant: the runtime-closure dispatch must serve
192
/// `compile_symbol_call_for_stack` too so the value flows into
193
/// surrounding arithmetic.
194
#[test]
195
1
fn let_bound_lambda_funcall_at_stack_position_compiles() {
196
1
    compile_and_validate("(let ((f (lambda (x) (* x 2)))) (+ (funcall f 5) 1))");
197
1
}
198

            
199
/// Arity mismatch on a runtime-closure call must be caught at compile
200
/// time by `compile_call_ref` — the `$closure_<sig>` carries the
201
/// expected param count and we can't dispatch through `call_ref` with
202
/// the wrong shape.
203
#[test]
204
1
fn let_bound_lambda_funcall_arity_mismatch_errors() {
205
1
    let err = compile_expect_error("(let ((f (lambda (x) (* x 2)))) (funcall f 5 6))");
206
1
    assert!(
207
1
        err.contains("closure") || err.contains("arity") || err.contains("expected"),
208
        "got: {err}"
209
    );
210
1
}
211

            
212
/// Tier 1.5 Gap B closure: a recursive defun called with a runtime
213
/// arg lowers through the monomorph cache + runtime-call path
214
/// (`__defun_<name>_<sig>` wasm fn) instead of overflowing the inline
215
/// const-fold walk. Validation is enough — the wasm's recursive
216
/// `call $idx` survives the validator's stack-typing pass only if the
217
/// fixpoint return-type inference converged on the right `Ratio`
218
/// signature.
219
#[test]
220
1
fn recursive_defun_with_runtime_arg_compiles_and_runs() {
221
1
    let src = "(defun fact (n) (if (<= n 1/1) 1/1 (* n (fact (- n 1/1)))))
222
1
               (let* ((X (transaction-post-date 0))) (fact X))";
223
1
    compile_and_validate(src);
224
1
}
225

            
226
/// A recursive runtime-call defun whose signature includes a `nil` / `nil`
227
/// literal argument must compile. Bool/nil literals lower to `WasmType::Bool`
228
/// on the stack, so `infer_arg_type` must classify them as `Bool` too —
229
/// otherwise the monomorph signature says `I32` while `emit_runtime_call`
230
/// pushes `Bool` and the exact-type check rejects the call. Regression for the
231
/// WasmType::Bool / runtime-call inference mismatch.
232
#[test]
233
1
fn recursive_defun_with_bool_literal_arg_compiles() {
234
1
    let src = "(defun bounce (x flag) (if flag (bounce x nil) x))
235
1
               (let* ((X (transaction-post-date 0))) (bounce X t))";
236
1
    compile_and_validate(src);
237
1
}
238

            
239
/// A recursive runtime-arg defun nested as an ARGUMENT to a native (not in
240
/// head position) routes through the eval-side recursion guard
241
/// (`dispatch_symbol` re-entry → `recursive_runtime_call_type` placeholder)
242
/// rather than overflowing the const-fold walk, then the codegen monomorph
243
/// path emits the real call. `fact` has a base case so it's well-formed;
244
/// validation confirms the nested call lowered without a compiler overflow.
245
#[test]
246
1
fn recursive_runtime_arg_call_nested_in_native_compiles() {
247
1
    let src = "(defun fact (n) (if (<= n 1/1) 1/1 (* n (fact (- n 1/1)))))
248
1
               (let* ((X (transaction-post-date 0))) (+ 1/1 (fact X)))";
249
1
    compile_and_validate(src);
250
1
}
251

            
252
/// A pass-through recursive runtime-arg call (`(loopx x)`) nested in a native
253
/// COMPILES: the eval-side re-entry guard hands it to the codegen monomorph
254
/// path (the compile-time walk terminates; the unbounded recursion becomes a
255
/// runtime trap, not a compiler overflow). Validation confirms the nested
256
/// `call $idx` lowered. The nms suite covers the runtime-trap behavior and the
257
/// depth-guard error path for the cases the monomorph path can't take over.
258
#[test]
259
1
fn passthrough_recursive_runtime_arg_nested_in_native_compiles() {
260
1
    compile_and_validate(
261
1
        "(defun loopx (x) (loopx x)) \
262
1
         (let* ((X (transaction-post-date 0))) (+ 1/1 (loopx X)))",
263
1
    );
264
1
}
265

            
266
/// Two distinct call sites of the same defun with the same arg-type
267
/// signature share a single emitted monomorph — the cache key is
268
/// `(name, params)`. Compile success + validation is the contract the
269
/// test pins; emitting two helpers for an identical signature would
270
/// not change the wire result but would bloat the wasm and is the
271
/// regression we're guarding against.
272
#[test]
273
1
fn monomorph_cache_reuses_for_same_sig() {
274
1
    let src = "(defun double (n) (* n 2/1))
275
1
               (let* ((X (transaction-post-date 0))
276
1
                      (Y (transaction-post-date 1)))
277
1
                 (+ (double X) (double Y)))";
278
1
    compile_and_validate(src);
279
1
}
280

            
281
/// Same defun called with two different runtime arg types must emit
282
/// two distinct monomorphs because the cache is keyed on the param
283
/// signature, not the name. We exercise it with `Ratio` on one site
284
/// and a `Ratio`-bearing local on another — both routes hit the
285
/// runtime-call path.
286
#[test]
287
1
fn monomorph_cache_separates_for_different_sigs() {
288
1
    let src = "(defun id (n) n)
289
1
               (let* ((X (transaction-post-date 0))
290
1
                      (IDX (entity-count)))
291
1
                 (+ (id X) (id X)))";
292
1
    compile_and_validate(src);
293
1
}
294

            
295
/// Regression (AFL, compile-level): a lambda body that is a too-short binder
296
/// form — `(map (lambda (s) (do)) (list 1))` — drove closure param-type
297
/// inference to slice `&elems[2..]` out of range and PANIC. `compile_expect_error`
298
/// fails on a panic, so this pins the public contract that the malformed shape
299
/// surfaces a structured compile error through the real `compile()` path, not a
300
/// SIGABRT. (The `param_infer` unit test covers the helper in isolation.)
301
#[test]
302
1
fn lambda_body_short_binder_does_not_panic_compiler() {
303
1
    for body in ["(do)", "(let)", "(dolist)", "(do*)"] {
304
4
        let _ = compile_expect_error(&format!("(map (lambda (s) {body}) (list 1))"));
305
    }
306
1
}