1
//! Binding a lambda's parameters from a call's arguments on the inline path.
2

            
3
use crate::ast::{Expr, KeyParam, LambdaParams, Place};
4
use crate::compiler::binder_key::function_owner;
5
use crate::compiler::context::CompileContext;
6
use crate::compiler::emit::FunctionEmitter;
7
use crate::error::{Error, Result};
8
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
9

            
10
use super::call::{applying_lambda, lift_lambda};
11
use super::closure_factory::close_factory_call;
12
use super::default_check::reject_expanded_defaults;
13
use super::effect::compile_for_effect;
14
use super::eval_lambda::{check_keyword_args, find_keyword_value};
15
use super::fold::walk::is_lambda_literal;
16
use super::fold::{fold_value, probe_value};
17
use super::local_cell::bind_local;
18
use super::operand::compile_raising_to_end;
19
use super::stack::compile_for_stack;
20
use crate::compiler::datum;
21
use crate::compiler::native::compile_pair_chain;
22
use crate::compiler::native::function_operand::effect_prefix;
23
use crate::compiler::special::{
24
    bind_lambda_closure, is_closure_factory_call, needs_cell, record_closure_result,
25
    used_as_function,
26
};
27

            
28
/// Codegen-aware analog of the eval-only lambda-param binder. For
29
/// each required / optional / rest / key / aux parameter whose
30
/// argument resolves to a runtime value (host fn call result, prior
31
/// `WasmLocal`, etc.), this emits the wasm to compute the value once,
32
/// stashes it in a fresh local, and binds the parameter symbol to
33
/// `Expr::WasmLocal(idx, ty)` so subsequent body references emit
34
/// `local.get N`. Constant args (`Number` / `Bool` / `Nil` / `String`
35
/// / `Bytes` / `Quote(_)` / etc) bind directly to the resolved value
36
/// — no wasm emitted, body continues to const-fold against the
37
/// value.
38
///
39
/// The runtime/constant split is what lets the inline path remain the
40
/// const-fold fast path: a defun whose entire arg list resolves at
41
/// compile time walks the body without emitting a single wasm
42
/// instruction; introducing one runtime arg promotes only that arg
43
/// into a local, leaving the rest to fold.
44
///
45
/// `None` when an argument always raises: the arguments up to and including it
46
/// are compiled, then control is dead and the body never runs.
47
848741
pub(in crate::compiler) fn compile_and_bind_lambda_params(
48
848741
    ctx: &mut CompileContext,
49
848741
    emit: &mut FunctionEmitter,
50
848741
    symbols: &mut SymbolTable,
51
848741
    params: &LambdaParams,
52
848741
    body: &Expr,
53
848741
    args: &[Expr],
54
848741
    callee: Option<&str>,
55
848741
) -> Result<Option<SymbolTable>> {
56
848741
    check_lambda_arity(params, args)?;
57
845829
    reject_expanded_defaults(symbols, callee.unwrap_or("LAMBDA"), params)?;
58
845826
    let scope = param_scope(params, body);
59

            
60
    // Every explicit argument is compiled/evaluated SEQUENTIALLY against the
61
    // LIVE caller table FIRST — collecting each param's bound value — and
62
    // `local` (the callee's body environment) is cloned from `symbols` only
63
    // AFTER all of them have applied their real effects. An argument's own
64
    // compile-time effect (a nested `setf`/`defvar`) must be visible both to
65
    // a LATER argument (already true — they share `symbols`) and to the
66
    // callee body itself; cloning `local` up front (the old bug) snapshotted
67
    // it from the PRE-effect caller state, so the body saw stale bindings.
68
845826
    let mut arg_idx = 0;
69
    let Some(required_bound) =
70
845826
        bind_required_params(ctx, emit, symbols, params, &scope, args, &mut arg_idx)?
71
    else {
72
2999
        return Ok(None);
73
    };
74
    let Some(optional_bound) =
75
841572
        bind_optional_params(ctx, emit, symbols, params, &scope, args, &mut arg_idx)?
76
    else {
77
208
        return Ok(None);
78
    };
79
841358
    let Some(trailing) = bind_trailing_args(ctx, emit, symbols, params, args, arg_idx)? else {
80
419
        return Ok(None);
81
    };
82
840523
    let rest_bound = bind_rest_param(ctx, emit, symbols, params, &scope, &trailing)?;
83
840523
    let Some(key_bound) = bind_key_params(ctx, emit, symbols, params, &scope, &trailing)? else {
84
        return Ok(None);
85
    };
86

            
87
839468
    let mut local = symbols.clone();
88
839468
    local.enter_function_body(function_owner(symbols, callee, body));
89
839468
    if let Some(name) = callee {
90
467709
        local.hide_caller_lexicals(name)?;
91
371759
    }
92
836722
    install_bound_params(
93
836722
        ctx,
94
836722
        &mut local,
95
836722
        required_bound,
96
836722
        optional_bound,
97
836722
        rest_bound,
98
836722
        key_bound,
99
836722
    )?;
100
836722
    Ok(bind_aux_params(ctx, emit, &mut local, params, &scope)?.then_some(local))
101
848741
}
102

            
103
/// `lambda`'s arity check — shared shape (not code) with `eval.rs`'s
104
/// `call_lambda`, which mirrors this function's parameter-binding pipeline
105
/// step for step.
106
848741
fn check_lambda_arity(params: &LambdaParams, args: &[Expr]) -> Result<()> {
107
848741
    let min_args = params.required.len();
108
848741
    let max_args = if params.rest.is_some() || !params.key.is_empty() {
109
121773
        None
110
    } else {
111
726968
        Some(min_args + params.optional.len())
112
    };
113
848741
    if args.len() < min_args {
114
1456
        return Err(Error::Arity {
115
1456
            name: "lambda".to_string(),
116
1456
            expected: min_args,
117
1456
            actual: args.len(),
118
1456
        });
119
847285
    }
120
847285
    if let Some(max) = max_args
121
725512
        && args.len() > max
122
    {
123
1456
        return Err(Error::Arity {
124
1456
            name: "lambda".to_string(),
125
1456
            expected: max,
126
1456
            actual: args.len(),
127
1456
        });
128
845829
    }
129
845829
    Ok(())
130
848741
}
131

            
132
845826
fn bind_required_params(
133
845826
    ctx: &mut CompileContext,
134
845826
    emit: &mut FunctionEmitter,
135
845826
    symbols: &mut SymbolTable,
136
845826
    params: &LambdaParams,
137
845826
    scope: &[Expr],
138
845826
    args: &[Expr],
139
845826
    arg_idx: &mut usize,
140
845826
) -> Result<Option<Vec<(String, Expr)>>> {
141
845826
    let mut bound = Vec::with_capacity(params.required.len());
142
845826
    for param in &params.required {
143
1070829
        let arg = &args[*arg_idx];
144
1070829
        let Some(value) = bind_param_arg(ctx, emit, symbols, param, scope, arg)? else {
145
2999
            return Ok(None);
146
        };
147
1066575
        bound.push((param.clone(), value));
148
1066575
        *arg_idx += 1;
149
    }
150
841572
    Ok(Some(bound))
151
845826
}
152

            
153
841572
fn bind_optional_params(
154
841572
    ctx: &mut CompileContext,
155
841572
    emit: &mut FunctionEmitter,
156
841572
    symbols: &mut SymbolTable,
157
841572
    params: &LambdaParams,
158
841572
    scope: &[Expr],
159
841572
    args: &[Expr],
160
841572
    arg_idx: &mut usize,
161
841572
) -> Result<Option<Vec<(String, Expr)>>> {
162
841572
    let mut bound = Vec::with_capacity(params.optional.len());
163
841572
    for (param, default) in &params.optional {
164
6140
        let value = if *arg_idx < args.len() {
165
1046
            let v = bind_param_arg(ctx, emit, symbols, param, scope, &args[*arg_idx])?;
166
1046
            *arg_idx += 1;
167
1046
            v
168
5094
        } else if let Some(default_expr) = default {
169
4675
            bind_param_arg(ctx, emit, symbols, param, scope, default_expr)?
170
        } else {
171
419
            bind_param_arg(ctx, emit, symbols, param, scope, &Expr::Nil)?
172
        };
173
6134
        let Some(value) = value else {
174
208
            return Ok(None);
175
        };
176
5926
        bound.push((param.clone(), value));
177
    }
178
841358
    Ok(Some(bound))
179
841572
}
180

            
181
/// Binds every argument past the positional ones once, left to right, as a
182
/// caller's `&rest` / `&key` sections both read them.
183
841358
fn bind_trailing_args(
184
841358
    ctx: &mut CompileContext,
185
841358
    emit: &mut FunctionEmitter,
186
841358
    symbols: &mut SymbolTable,
187
841358
    params: &LambdaParams,
188
841358
    args: &[Expr],
189
841358
    arg_idx: usize,
190
841358
) -> Result<Option<Vec<Expr>>> {
191
841358
    if params.rest.is_none() && params.key.is_empty() {
192
719585
        return Ok(Some(Vec::new()));
193
121773
    }
194
121773
    args[arg_idx..]
195
121773
        .iter()
196
281789
        .map(|arg| compile_arg_for_param(ctx, emit, symbols, (arg, false)).transpose())
197
        .collect::<Option<Result<Vec<_>>>>()
198
        .transpose()
199
841358
}
200

            
201
840523
fn bind_rest_param(
202
840523
    ctx: &mut CompileContext,
203
840523
    emit: &mut FunctionEmitter,
204
840523
    symbols: &mut SymbolTable,
205
840523
    params: &LambdaParams,
206
840523
    scope: &[Expr],
207
840523
    trailing: &[Expr],
208
840523
) -> Result<Option<(String, Expr)>> {
209
840523
    params
210
840523
        .rest
211
840523
        .as_ref()
212
4178
        .map(|rest_param| -> Result<(String, Expr)> {
213
4178
            let rest_list = rest_list_value(ctx, emit, symbols, trailing.to_vec())?;
214
4178
            let rest_list = share_if_celled(ctx, emit, symbols, rest_param, scope, rest_list)?;
215
4178
            Ok((rest_param.clone(), rest_list))
216
4178
        })
217
        .transpose()
218
840523
}
219

            
220
/// The rest list: a quoted datum when every argument is constant, otherwise a
221
/// runtime chain built from the already-bound argument values.
222
4178
fn rest_list_value(
223
4178
    ctx: &mut CompileContext,
224
4178
    emit: &mut FunctionEmitter,
225
4178
    symbols: &mut SymbolTable,
226
4178
    rest_args: Vec<Expr>,
227
4178
) -> Result<Expr> {
228
4178
    if !rest_args.iter().any(Expr::is_wasm_runtime) {
229
2300
        return datum::bounded(symbols, Expr::quoted_list(rest_args));
230
1878
    }
231
1878
    let ty = compile_pair_chain(ctx, emit, symbols, &rest_args)?;
232
1878
    let idx = ctx.alloc_local(ty)?;
233
1878
    emit.local_set(idx);
234
1878
    Ok(Expr::WasmLocal(idx, ty))
235
4178
}
236

            
237
840523
fn bind_key_params(
238
840523
    ctx: &mut CompileContext,
239
840523
    emit: &mut FunctionEmitter,
240
840523
    symbols: &mut SymbolTable,
241
840523
    params: &LambdaParams,
242
840523
    scope: &[Expr],
243
840523
    trailing: &[Expr],
244
840523
) -> Result<Option<Vec<(String, Expr)>>> {
245
840523
    check_keyword_args(params, trailing)?;
246
839468
    let mut bound = Vec::with_capacity(params.key.len());
247
    for KeyParam {
248
        name: param,
249
        keyword,
250
        default,
251
839468
    } in &params.key
252
    {
253
193716
        let keyword = Expr::Keyword(keyword.clone());
254
193716
        let supplied = find_keyword_value(trailing, &keyword)?.cloned();
255
193716
        let value = match (supplied, default) {
256
135877
            (Some(value), _) => Some(share_if_celled(ctx, emit, symbols, param, scope, value)?),
257
            (None, Some(default_expr)) => {
258
47852
                bind_param_arg(ctx, emit, symbols, param, scope, default_expr)?
259
            }
260
9987
            (None, None) => bind_param_arg(ctx, emit, symbols, param, scope, &Expr::Nil)?,
261
        };
262
193716
        let Some(value) = value else {
263
            return Ok(None);
264
        };
265
193716
        bound.push((param.clone(), value));
266
    }
267
839468
    Ok(Some(bound))
268
840523
}
269

            
270
/// Registers every collected `(param, value)` pair into `local`, in the
271
/// required/optional/rest/key order CL binds them.
272
836722
fn install_bound_params(
273
836722
    ctx: &CompileContext,
274
836722
    local: &mut SymbolTable,
275
836722
    required: Vec<(String, Expr)>,
276
836722
    optional: Vec<(String, Expr)>,
277
836722
    rest: Option<(String, Expr)>,
278
836722
    key: Vec<(String, Expr)>,
279
836722
) -> Result<()> {
280
836722
    for (param, value) in required.into_iter().chain(optional).chain(rest).chain(key) {
281
1268892
        record_closure_result(local, ctx, &value)?;
282
1268892
        local.define(Symbol::new(&param, SymbolKind::Variable).with_value(value));
283
    }
284
836722
    Ok(())
285
836722
}
286

            
287
/// Expressions that can see a parameter's cell: every `&aux` initializer plus the body.
288
845826
fn param_scope(params: &LambdaParams, body: &Expr) -> Vec<Expr> {
289
845826
    let inits = params.aux.iter().filter_map(|(_, init)| init.clone());
290
845826
    inits.chain(std::iter::once(body.clone())).collect()
291
845826
}
292

            
293
836722
fn bind_aux_params(
294
836722
    ctx: &mut CompileContext,
295
836722
    emit: &mut FunctionEmitter,
296
836722
    local: &mut SymbolTable,
297
836722
    params: &LambdaParams,
298
836722
    scope: &[Expr],
299
836722
) -> Result<bool> {
300
3153
    let later_scope = |k: usize| -> Vec<Expr> {
301
3153
        let inits = params.aux[k + 1..]
302
3153
            .iter()
303
3
            .filter_map(|(_, init)| init.clone());
304
3153
        inits.chain(scope.last().cloned()).collect()
305
3153
    };
306
836722
    for (k, (param, init)) in params.aux.iter().enumerate() {
307
3153
        let init_expr = init.as_ref().unwrap_or(&Expr::Nil);
308
3153
        let Some(value) = bind_param_arg(ctx, emit, local, param, &later_scope(k), init_expr)?
309
        else {
310
208
            return Ok(false);
311
        };
312
2945
        local.define(Symbol::new(param, SymbolKind::Variable).with_value(value));
313
    }
314
836514
    Ok(true)
315
836722
}
316

            
317
1137961
fn bind_param_arg(
318
1137961
    ctx: &mut CompileContext,
319
1137961
    emit: &mut FunctionEmitter,
320
1137961
    symbols: &mut SymbolTable,
321
1137961
    param: &str,
322
1137961
    scope: &[Expr],
323
1137961
    arg: &Expr,
324
1137961
) -> Result<Option<Expr>> {
325
1137961
    if needs_cell(symbols, param, scope)? {
326
51
        if compile_raising_to_end(ctx, emit, symbols, arg)? {
327
3
            return Ok(None);
328
48
        }
329
48
        compile_shared_arg(ctx, emit, symbols, arg).map(Some)
330
    } else {
331
1137910
        let value = effect_prefix(arg).1;
332
1137910
        let lift = (is_lambda_literal(symbols, value) || is_closure_factory_call(symbols, value)?)
333
2355
            && uses_as_function(symbols, scope, param)?;
334
1137910
        compile_arg_for_param(ctx, emit, symbols, (arg, lift))
335
    }
336
1137961
}
337

            
338
2355
fn uses_as_function(symbols: &SymbolTable, scope: &[Expr], param: &str) -> Result<bool> {
339
2355
    for form in scope {
340
2355
        if used_as_function(symbols, form, param)? {
341
2347
            return Ok(true);
342
8
        }
343
    }
344
8
    Ok(false)
345
2355
}
346

            
347
/// Moves an already-bound value into a cell when its parameter needs one.
348
140055
fn share_if_celled(
349
140055
    ctx: &mut CompileContext,
350
140055
    emit: &mut FunctionEmitter,
351
140055
    symbols: &mut SymbolTable,
352
140055
    param: &str,
353
140055
    scope: &[Expr],
354
140055
    value: Expr,
355
140055
) -> Result<Expr> {
356
140055
    if needs_cell(symbols, param, scope)? {
357
6
        compile_shared_arg(ctx, emit, symbols, &value)
358
    } else {
359
140049
        Ok(value)
360
    }
361
140055
}
362

            
363
/// Binds a parameter its body assigns and a closure captures to a fresh cell
364
/// holding the argument, constant or not.
365
54
fn compile_shared_arg(
366
54
    ctx: &mut CompileContext,
367
54
    emit: &mut FunctionEmitter,
368
54
    symbols: &mut SymbolTable,
369
54
    arg: &Expr,
370
54
) -> Result<Expr> {
371
54
    let ty = compile_for_stack(ctx, emit, symbols, arg)?;
372
54
    let idx = bind_local(ctx, emit, ty, true)?;
373
54
    Ok(Expr::WasmLocal(idx, ty))
374
54
}
375

            
376
/// Per-argument binding helper. A fold-safe argument binds to its datum
377
/// with nothing emitted. Otherwise a runtime value (`Expr::WasmRuntime` /
378
/// `Expr::WasmLocal`) is emitted onto the stack and stashed in a fresh
379
/// local, and everything else (an effectful constant, a quoted form, a
380
/// lambda) is compiled for effect — even if the parameter is unused, so a
381
/// transfer among the arguments still fires (ISS-026) — then binds to the
382
/// resolved value. `None` for an argument that always raises: it is compiled
383
/// and control ends there.
384
1419699
fn compile_arg_for_param(
385
1419699
    ctx: &mut CompileContext,
386
1419699
    emit: &mut FunctionEmitter,
387
1419699
    symbols: &mut SymbolTable,
388
1419699
    (arg, lift): (&Expr, bool),
389
1419699
) -> Result<Option<Expr>> {
390
1419699
    if let Some(datum) = fold_value(symbols, arg)? {
391
851332
        return Ok(Some(datum));
392
568367
    }
393
568367
    if compile_raising_to_end(ctx, emit, symbols, arg)? {
394
3831
        return Ok(None);
395
564536
    }
396
564536
    resolve_arg(ctx, emit, symbols, (arg, lift)).map(Some)
397
1419699
}
398

            
399
564536
fn resolve_arg(
400
564536
    ctx: &mut CompileContext,
401
564536
    emit: &mut FunctionEmitter,
402
564536
    symbols: &mut SymbolTable,
403
564536
    (arg, lift): (&Expr, bool),
404
564536
) -> Result<Expr> {
405
    // Classify on a DISPOSABLE clone; the real, single application of
406
    // `arg`'s effects happens below, on the live table — either via
407
    // `compile_for_stack` (a genuinely runtime value) or `compile_for_effect`
408
    // (a compile-time-constant value that may still carry a nested runtime
409
    // effect, e.g. a `setf` on an existing `WasmLocal`, or a host-fn call).
410
564536
    let resolved = probe_value(&mut symbols.clone(), arg)?;
411
564530
    match &resolved {
412
2124
        Expr::Lambda(..) if is_closure_factory_call(symbols, arg)? => {
413
13
            let closed = close_factory_call(ctx, emit, symbols, arg)?;
414
13
            match &closed {
415
13
                Expr::Lambda(params, body) if lift => {
416
9
                    let bound = applying_lambda(symbols, arg, |symbols| {
417
9
                        bind_lambda_closure(ctx, emit, symbols, params, body, false)
418
9
                    })?;
419
9
                    Ok(bound.unwrap_or_else(|| closed.clone()))
420
                }
421
4
                _ => Ok(closed),
422
            }
423
        }
424
        // Both a fresh runtime value AND an already-`WasmLocal`-resolving
425
        // expression go through the SAME real compile into a FRESH local:
426
        // `arg` can be a COMPOUND expression that merely ENDS on a
427
        // `WasmLocal` reference (e.g. `(progn (setf hits (+ hits 1)) n)`),
428
        // whose own effects (the `setf`) must still run; and even a bare
429
        // variable reference must be SNAPSHOT into its own storage now,
430
        // not aliased to the source local, or a later argument mutating
431
        // that same source variable would change an EARLIER argument's
432
        // already-bound value out from under it. Size the local from the
433
        // type codegen ACTUALLY pushes, not the eval-time placeholder — the
434
        // two can disagree (see `compile_concrete_vs_anyref_identity`'s doc
435
        // comment for the same reasoning).
436
        Expr::WasmRuntime(_)
437
        | Expr::WasmLocal(_, _)
438
        | Expr::WasmGlobal(_, _)
439
        | Expr::Instance(_, _) => {
440
554267
            let actual_ty = compile_for_stack(ctx, emit, symbols, arg)?;
441
552596
            let idx = ctx.alloc_local(actual_ty)?;
442
552596
            emit.local_set(idx);
443
552596
            if let Some((params, body)) = resolved
444
552596
                .place()
445
484909
                .and_then(|(p, _)| symbols.closure_body(p))
446
                .cloned()
447
            {
448
1938
                symbols.record_closure_body(Place::Local(idx), params, body);
449
550658
            }
450
552596
            Ok(Expr::WasmLocal(idx, actual_ty))
451
        }
452
2111
        Expr::Lambda(params, body) if lift => lift_lambda(ctx, emit, symbols, arg, (params, body)),
453
        _ => {
454
8360
            compile_for_effect(ctx, emit, symbols, arg)?;
455
8360
            Ok(resolved)
456
        }
457
    }
458
564536
}