1
mod anyref;
2
#[cfg(test)]
3
mod capture_free_tests;
4
mod captures;
5
mod constants;
6
mod emit;
7
mod funcall;
8
mod function_form;
9
mod guards;
10
mod shape;
11
#[cfg(test)]
12
mod site_tests;
13
mod source;
14
#[cfg(test)]
15
mod value_tests;
16

            
17
pub(in crate::compiler) mod monomorph;
18
mod param_infer;
19
pub(in crate::compiler) use param_infer::{has_type_evidence, infer_params};
20

            
21
pub(in crate::compiler) use captures::compute_captures;
22
pub(in crate::compiler) use shape::{
23
    has_v1_param_shape, non_v1_lambda_error, reject_non_v1_lambda,
24
};
25

            
26
use crate::ast::Expr;
27
use crate::error::{Error, Result};
28
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
29

            
30
use super::super::context::CompileContext;
31
use super::super::emit::FunctionEmitter;
32
use crate::ast::WasmType;
33

            
34
use super::super::expr::{
35
    compile_expr, compile_for_stack, compile_string, eval_value, format_expr, member_value,
36
    serialize_stack_to_output,
37
};
38
use super::SpecialFormSpec;
39
use super::binding::{parse_function_params, rebind_params};
40
use crate::ast::LambdaParams;
41
use crate::compiler::native::function_operand::function_operand;
42
use funcall::{
43
    compile_apply_form, compile_apply_form_for_stack, compile_funcall, compile_funcall_for_stack,
44
};
45
use function_form::function_form;
46

            
47
pub(super) const FORMS: &[SpecialFormSpec] = &[
48
    SpecialFormSpec {
49
        name: "LAMBDA",
50
        eval: eval_lambda,
51
        compile: spec_compile_lambda,
52
        stack: Some(compile_lambda_for_stack),
53
        effect: Some(compile_lambda_for_effect),
54
    },
55
    SpecialFormSpec {
56
        name: "FUNCTION",
57
        eval: function_form,
58
        compile: compile_function_form,
59
        stack: Some(compile_function_for_stack),
60
        effect: Some(compile_function_for_effect),
61
    },
62
    SpecialFormSpec {
63
        name: "FUNCALL",
64
        eval: funcall,
65
        compile: compile_funcall,
66
        stack: Some(compile_funcall_for_stack),
67
        effect: Some(compile_funcall_for_effect),
68
    },
69
    SpecialFormSpec {
70
        name: "APPLY",
71
        eval: apply,
72
        compile: compile_apply_form,
73
        stack: Some(compile_apply_form_for_stack),
74
        effect: Some(compile_apply_form_for_effect),
75
    },
76
];
77

            
78
/// FUNCALL / APPLY in effect position must never serialize: `compile_funcall`
79
/// / `compile_apply_form` are written for VALUE position and delegate to
80
/// `compile_call`, which pushes AND serializes the call's result to the RPC
81
/// output stream (correct for a top-level statement, wrong for a discarded
82
/// intermediate — a FUNCALL inside a loop body would otherwise push one
83
/// output entity per iteration until the output buffer is exhausted).
84
/// Compile via the SAME stack path and drop the result instead.
85
19228
fn compile_funcall_for_effect(
86
19228
    ctx: &mut CompileContext,
87
19228
    emit: &mut FunctionEmitter,
88
19228
    symbols: &mut SymbolTable,
89
19228
    args: &[Expr],
90
19228
) -> Result<()> {
91
19228
    compile_funcall_for_stack(ctx, emit, symbols, args)?;
92
19014
    emit.drop_value();
93
19014
    Ok(())
94
19228
}
95

            
96
1251
fn compile_apply_form_for_effect(
97
1251
    ctx: &mut CompileContext,
98
1251
    emit: &mut FunctionEmitter,
99
1251
    symbols: &mut SymbolTable,
100
1251
    args: &[Expr],
101
1251
) -> Result<()> {
102
1251
    compile_apply_form_for_stack(ctx, emit, symbols, args)?;
103
1251
    emit.drop_value();
104
1251
    Ok(())
105
1251
}
106

            
107
1962216
fn eval_lambda(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
108
1962216
    lambda(symbols, args)
109
1962216
}
110

            
111
2098
fn spec_compile_lambda(
112
2098
    ctx: &mut CompileContext,
113
2098
    emit: &mut FunctionEmitter,
114
2098
    symbols: &mut SymbolTable,
115
2098
    args: &[Expr],
116
2098
) -> Result<()> {
117
2098
    compile_lambda_form(ctx, emit, symbols, args)
118
2098
}
119

            
120
107402
fn compile_lambda_for_stack(
121
107402
    ctx: &mut CompileContext,
122
107402
    emit: &mut FunctionEmitter,
123
107402
    symbols: &mut SymbolTable,
124
107402
    args: &[Expr],
125
107402
) -> Result<WasmType> {
126
107402
    let result = lambda(symbols, args)?;
127
107400
    closure_for_stack(ctx, emit, symbols, &result)
128
107402
}
129

            
130
3130
fn compile_function_for_stack(
131
3130
    ctx: &mut CompileContext,
132
3130
    emit: &mut FunctionEmitter,
133
3130
    symbols: &mut SymbolTable,
134
3130
    args: &[Expr],
135
3130
) -> Result<WasmType> {
136
3130
    match function_form(symbols, args)? {
137
832
        designator @ Expr::Datum(_) => compile_for_stack(ctx, emit, symbols, &designator),
138
2298
        result => closure_for_stack(ctx, emit, symbols, &result),
139
    }
140
3130
}
141

            
142
/// A closure value does not run its body, so a statement of one only checks
143
/// the form and emits nothing.
144
6396
fn compile_lambda_for_effect(
145
6396
    _ctx: &mut CompileContext,
146
6396
    _emit: &mut FunctionEmitter,
147
6396
    symbols: &mut SymbolTable,
148
6396
    args: &[Expr],
149
6396
) -> Result<()> {
150
6396
    lambda(symbols, args).map(drop)
151
6396
}
152

            
153
208
fn compile_function_for_effect(
154
208
    _ctx: &mut CompileContext,
155
208
    _emit: &mut FunctionEmitter,
156
208
    symbols: &mut SymbolTable,
157
208
    args: &[Expr],
158
208
) -> Result<()> {
159
208
    function_form(symbols, args).map(drop)
160
208
}
161

            
162
2098
pub(super) fn compile_lambda_form(
163
2098
    ctx: &mut CompileContext,
164
2098
    emit: &mut FunctionEmitter,
165
2098
    symbols: &mut SymbolTable,
166
2098
    args: &[Expr],
167
2098
) -> Result<()> {
168
2098
    let result = lambda(symbols, args)?;
169
1678
    emit_closure_value(ctx, emit, symbols, &result)
170
2098
}
171

            
172
1666
pub(super) fn compile_function_form(
173
1666
    ctx: &mut CompileContext,
174
1666
    emit: &mut FunctionEmitter,
175
1666
    symbols: &mut SymbolTable,
176
1666
    args: &[Expr],
177
1666
) -> Result<()> {
178
1666
    match function_form(symbols, args)? {
179
        designator @ Expr::Datum(_) => compile_expr(ctx, emit, symbols, &designator),
180
418
        result => emit_closure_value(ctx, emit, symbols, &result),
181
    }
182
1666
}
183

            
184
/// Lower a value-position lambda/function expression: a v1 `Lambda` is a
185
/// wasm closure value, a non-v1 one the structured error, anything else
186
/// `function_form` returned prints as its source text.
187
2096
fn emit_closure_value(
188
2096
    ctx: &mut CompileContext,
189
2096
    emit: &mut FunctionEmitter,
190
2096
    symbols: &mut SymbolTable,
191
2096
    result: &Expr,
192
2096
) -> Result<()> {
193
2096
    if matches!(result, Expr::Lambda(..)) {
194
2096
        let ty = closure_for_stack(ctx, emit, symbols, result)?;
195
1666
        return serialize_stack_to_output(ctx, emit, ty);
196
    }
197
    compile_string(ctx, emit, &format_expr(result))
198
2096
}
199

            
200
/// Pushes the closure value of a v1 `Lambda`; anything else has no stack value.
201
135922
pub(in crate::compiler) fn closure_for_stack(
202
135922
    ctx: &mut CompileContext,
203
135922
    emit: &mut FunctionEmitter,
204
135922
    symbols: &mut SymbolTable,
205
135922
    result: &Expr,
206
135922
) -> Result<WasmType> {
207
135922
    let Expr::Lambda(params, body) = result else {
208
        return Err(Error::Compile(format!(
209
            "cannot compile to WASM stack value: {}",
210
            format_expr(result)
211
        )));
212
    };
213
135922
    let sig = try_emit_lambda_for_value(ctx, emit, symbols, params, body)?
214
134461
        .ok_or_else(non_v1_lambda_error)?;
215
132778
    Ok(WasmType::Closure(sig))
216
135922
}
217

            
218
/// Whether `body` is safe to INLINE at a different site (a HOF call): it must
219
/// reference NO free outer variable. A captured free var — whether a runtime
220
/// `WasmLocal` OR a compile-time CONST (`(let ((x 1)) (lambda … x) …)`) — would
221
/// resolve to its CREATION-site value through the closure's env / const fold,
222
/// but an inline at the call site resolves it THERE (possibly shadowed or a
223
/// different const), producing a wrong value. So the check is stricter than
224
/// `compute_captures` (which only tracks WasmLocal captures for env building):
225
/// any free symbol that resolves to a `Variable` (let-/param-bound) OR carries a
226
/// `function` binding (a user `defun` / redefined builtin) makes the body
227
/// inline-unsafe — both can resolve differently at a later inline site. Bare
228
/// operators / natives (no `function`) and special forms resolve identically
229
/// everywhere and are fine. Re-running this at the inline site catches a global
230
/// the body uses that an inner binder has since shadowed or `defun`-redefined.
231
/// A global `defun` in OPERATOR position is the exception: the call resolves it
232
/// where the body runs, so it is no capture unless a LABELS function of that
233
/// name is in scope. Conservative: a body that merely shadows an outer name with
234
/// its own inner binder may be rejected, costing precision (not correctness).
235
///
236
/// Only a SIMPLE (required-params-only) lambda is an inline candidate — an
237
/// optional / key / aux default expr or a `&rest` binder would each need its
238
/// own capture analysis, so a lambda carrying any stays on the `call_ref` path.
239
191688
pub(in crate::compiler) fn is_capture_free(
240
191688
    symbols: &SymbolTable,
241
191688
    params: &LambdaParams,
242
191688
    body: &Expr,
243
191688
) -> bool {
244
191688
    if !params.optional.is_empty()
245
191687
        || params.rest.is_some()
246
191687
        || !params.key.is_empty()
247
191687
        || !params.aux.is_empty()
248
    {
249
1
        return false;
250
191687
    }
251
191687
    references_no_free_variable(symbols, &params.required, body)
252
191688
}
253

            
254
/// `bound` are names lexically bound by the closure (its required params) — a
255
/// reference to one is never a creation-site capture. The walk is conservative
256
/// for nested binders: it does NOT extend `bound` with an inner lambda's params,
257
/// so a shadowing inner name that collides with a creation-site `Variable` is
258
/// rejected (precision, not soundness).
259
736396
fn references_no_free_variable(symbols: &SymbolTable, bound: &[String], expr: &Expr) -> bool {
260
736396
    match expr {
261
        // A bound param is never a capture. A free symbol is inline-safe only if
262
        // it resolves to a STABLE global: not a `Variable` (a let/param binding
263
        // an inner scope could shadow) AND carrying no `function` binding. A
264
        // symbol with a `function` is a user `defun` — or a builtin operator a
265
        // `defun` has REDEFINED in place (kind stays `Operator`, `function` set).
266
        // Either way its meaning can differ between the closure's creation scope
267
        // and a later inline site, so reject it; the closure keeps `call_ref`,
268
        // which invokes the value compiled at creation. Bare operators / natives
269
        // (no `function`) resolve identically everywhere and stay inlinable.
270
        Expr::Symbol(name) => {
271
365504
            bound.iter().any(|p| p == name)
272
213304
                || (!resolves_to_variable(symbols, name) && !has_function_binding(symbols, name))
273
        }
274
        // QUOTE's argument is data, not evaluated — it captures nothing.
275
4857
        Expr::Quote(_) | Expr::Datum(_) => true,
276
252459
        Expr::List(elems) if matches!(elems.first(), Some(Expr::Symbol(h)) if h.eq_ignore_ascii_case("quote")) => {
277
            true
278
        }
279
        // A macro call is opaque pre-expansion: it can expand to a creation-scope
280
        // variable, which an inline would re-expand (and re-resolve) at the call
281
        // site. Conservatively treat any macro-headed form as a capture.
282
252459
        Expr::List(elems) if matches!(elems.first(), Some(Expr::Symbol(h)) if matches!(symbols.resolve_head(h), Head::Macro(..))) => {
283
4191
            false
284
        }
285
        // QUASIQUOTE evaluates only its unquoted forms, against the surrounding scope.
286
12
        Expr::Quasiquote(template) => template
287
12
            .unquoted_forms()
288
12
            .into_iter()
289
12
            .all(|form| references_no_free_variable(symbols, bound, form)),
290
        Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
291
            references_no_free_variable(symbols, bound, inner)
292
        }
293
        // A nested lambda's body (and any param default) still evaluates against
294
        // the creation scope when the outer body runs, so it must be walked too;
295
        // never short-circuit it to capture-free.
296
        Expr::Lambda(inner_params, inner_body) => {
297
3745
            inner_params
298
3745
                .defaults()
299
                .all(|d| references_no_free_variable(symbols, bound, d))
300
3745
                && references_no_free_variable(symbols, bound, inner_body)
301
        }
302
        Expr::List(elems) => {
303
248268
            let operands = match elems.split_first() {
304
224301
                Some((Expr::Symbol(head), rest)) if is_global_defun(symbols, head) => rest,
305
197968
                _ => elems.as_slice(),
306
            };
307
248268
            operands
308
248268
                .iter()
309
540952
                .all(|e| references_no_free_variable(symbols, bound, e))
310
        }
311
        // A dotted pair can hide an unquoted free symbol (`(,x . nil)`); both
312
        // arms evaluate when the surrounding quasiquote expands, so walk both.
313
        Expr::Cons(car, cdr) => {
314
            references_no_free_variable(symbols, bound, car)
315
                && references_no_free_variable(symbols, bound, cdr)
316
        }
317
109819
        _ => true,
318
    }
319
736396
}
320

            
321
/// Whether `name` called in operator position reaches a global `defun`: a call
322
/// resolves it at the call site, so a later redefinition is the CL late binding,
323
/// and a LABELS function of that name is visible only where it is in scope.
324
224301
fn is_global_defun(symbols: &SymbolTable, name: &str) -> bool {
325
224301
    symbols.lookup(name).is_some_and(|sym| {
326
200666
        sym.kind() == SymbolKind::Function && sym.function().is_some() && !sym.is_local_function()
327
200666
    })
328
224301
}
329

            
330
213304
fn resolves_to_variable(symbols: &SymbolTable, name: &str) -> bool {
331
213304
    symbols.lookup(name).is_some_and(Symbol::is_variable)
332
213304
}
333

            
334
/// Whether `name` resolves to a symbol carrying a `function` body — a user
335
/// `defun` (or a builtin a `defun` redefined in place), whose meaning can change
336
/// between a closure's creation scope and a later inline site.
337
200108
fn has_function_binding(symbols: &SymbolTable, name: &str) -> bool {
338
200108
    symbols
339
200108
        .lookup(name)
340
151397
        .is_some_and(|sym| sym.function().is_some())
341
200108
}
342

            
343
/// Constructs a v1 lambda's closure value on the wasm stack and returns its
344
/// `ClosureSigId`; `Ok(None)` for a non-v1 lambda (the caller reports
345
/// `non_v1_lambda_error` or keeps the form inline).
346
254503
pub(in crate::compiler) fn try_emit_lambda_for_value(
347
254503
    ctx: &mut CompileContext,
348
254503
    emit: &mut FunctionEmitter,
349
254503
    symbols: &mut SymbolTable,
350
254503
    params: &LambdaParams,
351
254503
    body: &Expr,
352
254503
) -> Result<Option<crate::ast::ClosureSigId>> {
353
254503
    if !shape::is_v1_eligible(symbols, params, body) {
354
1915
        return Ok(None);
355
252588
    }
356
252588
    let sig = emit::emit_lambda_value(ctx, emit, symbols, params, body)?;
357
199955
    Ok(Some(sig))
358
254503
}
359

            
360
/// Variant for host-iteration call sites (CATCH-EACH and similar). The
361
/// host fn passes per-element items as raw anyref, so the closure body
362
/// fn is wired with anyref params and downcasts to the declared user
363
/// types in its prologue. The resulting `ClosureSigId` describes the
364
/// wire-level signature `(anyref...) -> anyref` — the caller emits the
365
/// closure value, then funcref+env are extracted and handed to the
366
/// host fn for per-element invocation.
367
11655
pub(in crate::compiler) fn try_emit_lambda_for_host_iter(
368
11655
    ctx: &mut CompileContext,
369
11655
    emit: &mut FunctionEmitter,
370
11655
    symbols: &mut SymbolTable,
371
11655
    params: &LambdaParams,
372
11655
    body: &Expr,
373
11655
    user_param_types: &[WasmType],
374
11655
) -> Result<Option<crate::ast::ClosureSigId>> {
375
11655
    if !shape::is_v1_eligible(symbols, params, body) {
376
        return Ok(None);
377
11655
    }
378
11655
    let sig = emit::emit_lambda_value_typed(
379
11655
        ctx,
380
11655
        emit,
381
11655
        symbols,
382
11655
        params,
383
11655
        body,
384
11655
        user_param_types,
385
11655
        emit::CallingConvention::HostAnyref,
386
11655
    )?;
387
9985
    Ok(Some(sig))
388
11655
}
389

            
390
6065
pub(super) fn build_apply_call(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Vec<Expr>> {
391
6065
    if args.len() < 2 {
392
416
        return Err(Error::Compile(
393
416
            "apply requires at least a function and one argument".to_string(),
394
416
        ));
395
5649
    }
396
5649
    let leading = &args[..args.len() - 1];
397
    // Evaluate the designator + leading args BEFORE deciding the last-arg
398
    // spread: a leading arg can rebind `LIST` (left-to-right eval order), and
399
    // `spread_apply_last_arg`'s builtin-`LIST` check must see that rebinding.
400
5649
    let mut all_args: Vec<Expr> = Vec::with_capacity(leading.len() + 1);
401
5649
    all_args.push(resolve_apply_designator(symbols, &leading[0])?);
402
5649
    for arg in &leading[1..] {
403
1456
        all_args.push(eval_value(symbols, arg)?);
404
    }
405
5649
    all_args.extend(spread_apply_last_arg(symbols, &args[args.len() - 1])?);
406
5025
    Ok(all_args)
407
6065
}
408

            
409
/// Resolve APPLY's last argument into the list of argument expressions to
410
/// spread. A syntactic `(LIST e1 e2 …)` spreads its element EXPRESSIONS
411
/// directly (`(apply f (list a b c))` ≡ `(f a b c)`) — this is the only form
412
/// that carries genuinely runtime elements, since a runtime `(list …)` no
413
/// longer eval-folds to a quoted list (it builds a `$pair` chain). A quoted
414
/// literal list spreads its constant elements; `nil` spreads nothing.
415
/// Anything else (a bare runtime pair, a non-list value) is an error: APPLY
416
/// can't statically know a runtime list's arity.
417
16763
pub(super) fn spread_apply_last_arg(symbols: &mut SymbolTable, arg: &Expr) -> Result<Vec<Expr>> {
418
16763
    if let Expr::List(elems) = arg
419
13203
        && let Some(Expr::Symbol(head)) = elems.first()
420
13203
        && head.eq_ignore_ascii_case("LIST")
421
    {
422
12567
        return Ok(elems[1..].to_vec());
423
4196
    }
424
4196
    match eval_value(symbols, arg)? {
425
1691
        Expr::Datum(inner) => match *inner {
426
1691
            Expr::List(elems) => Ok(elems.into_iter().map(member_value).collect()),
427
            Expr::Nil => Ok(vec![]),
428
            _ => Err(apply_last_arg_error()),
429
        },
430
425
        Expr::Nil => Ok(vec![]),
431
2080
        _ => Err(apply_last_arg_error()),
432
    }
433
16763
}
434

            
435
2080
fn apply_last_arg_error() -> Error {
436
2080
    Error::Compile(
437
2080
        "apply: last argument must be a literal list — `(list …)`, a quoted \
438
2080
         list, or nil (a runtime list's arity isn't known at compile time)"
439
2080
            .to_string(),
440
2080
    )
441
2080
}
442

            
443
2078954
pub(super) fn lambda(symbols: &SymbolTable, args: &[Expr]) -> Result<Expr> {
444
2078954
    if args.len() < 2 {
445
417
        return Err(Error::Compile(
446
417
            "LAMBDA requires a parameter list and body".to_string(),
447
417
        ));
448
2078537
    }
449
2078537
    let params = parse_function_params(symbols, "LAMBDA", &args[0])?;
450
2078305
    let (params, body) = rebind_params(symbols, params, Expr::body(&args[1..]))?;
451
2078305
    let body = constants::close_over_constants(symbols, &params, body)?;
452
2075809
    crate::compiler::datum::bounded(symbols, Expr::Lambda(params, Box::new(body)))
453
2078954
}
454

            
455
866544
pub(super) fn funcall(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
456
866544
    if args.is_empty() {
457
        return Err(Error::Compile(
458
            "funcall requires at least a function argument".to_string(),
459
        ));
460
866544
    }
461
866544
    tracing::debug!(args = args.len(), "compiling funcall");
462
866544
    let mut call = args.to_vec();
463
866544
    call[0] = function_operand(symbols, &call[0])?;
464
866544
    super::super::expr::call(symbols, &call)
465
866544
}
466

            
467
5649
pub(super) fn apply(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
468
5649
    let all_args = build_apply_call(symbols, args)?;
469
5025
    super::super::expr::call(symbols, &all_args)
470
5649
}
471

            
472
16971
pub(super) fn resolve_apply_designator(symbols: &mut SymbolTable, arg: &Expr) -> Result<Expr> {
473
16971
    let arg = &function_operand(symbols, arg)?;
474
16971
    match arg {
475
        Expr::Symbol(name) => {
476
            let sym = symbols
477
                .lookup(name)
478
                .ok_or_else(|| Error::undefined_symbol(name))?;
479
            if sym.value().is_some() {
480
                eval_value(symbols, arg)
481
            } else {
482
                Ok(Expr::Symbol(name.clone()))
483
            }
484
        }
485
16971
        _ => eval_value(symbols, arg),
486
    }
487
16971
}