1
//! `call_lambda` and its parameter-binding helpers, split out of `eval.rs`
2
//! per CLAUDE.md's file-size guideline. Applying a `LambdaParams` list
3
//! against a call's argument forms is one cohesive step of the eval path
4
//! (`eval.rs::dispatch_symbol` / `call`), distinct from dispatch and macro
5
//! expansion.
6

            
7
use crate::ast::{Expr, KeyParam, LambdaParams, WasmType};
8
use crate::compiler::binder_key::function_owner;
9
use crate::compiler::native::chain_pair_element;
10
use crate::error::{Error, Result};
11
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
12

            
13
use super::closure_factory::{close_over_params, unbound_runtime_capture};
14
use super::default_check::reject_expanded_defaults;
15
use super::eval::eval_value;
16
use super::format::format_form;
17

            
18
2764712
pub(super) fn call_lambda(
19
2764712
    symbols: &mut SymbolTable,
20
2764712
    params: &LambdaParams,
21
2764712
    body: &Expr,
22
2764712
    args: &[Expr],
23
2764712
    callee: Option<&str>,
24
2764712
) -> Result<Expr> {
25
2764712
    check_lambda_arity(params, args)?;
26
2764088
    reject_expanded_defaults(symbols, callee.unwrap_or("LAMBDA"), params)?;
27

            
28
    // Every explicit argument is evaluated SEQUENTIALLY against the LIVE
29
    // caller table FIRST — collecting each param's bound value — and
30
    // `local_symbols` (the callee's body environment) is cloned from
31
    // `symbols` only AFTER all of them have applied their real (compile-time)
32
    // effects. Cloning up front (the old bug) snapshotted the callee's
33
    // environment from the PRE-effect caller state, so e.g. `(defparameter p
34
    // 0) (defun f (unused) p) (f (progn (setf p 1) 0))` read `f`'s body
35
    // against the stale `p`.
36
2764088
    let mut arg_idx = 0;
37
2764088
    let required_bound = bind_required_params(symbols, params, args, &mut arg_idx)?;
38
2758246
    let optional_bound = bind_optional_params(symbols, params, args, &mut arg_idx)?;
39
2757828
    let rest_bound = bind_rest_param(symbols, params, args, arg_idx)?;
40
2757412
    let key_bound = bind_key_params(symbols, params, args, arg_idx)?;
41

            
42
2756371
    let mut local_symbols = symbols.clone();
43
2756371
    local_symbols.enter_function_body(function_owner(symbols, callee, body));
44
2756371
    if let Some(name) = callee {
45
1806819
        local_symbols.hide_caller_lexicals(name)?;
46
949552
    }
47
2755123
    install_bound_params(
48
2755123
        &mut local_symbols,
49
2755123
        required_bound,
50
2755123
        optional_bound,
51
2755123
        rest_bound,
52
2755123
        key_bound,
53
2755123
    );
54
2755123
    bind_aux_params(&mut local_symbols, params)?;
55

            
56
2754915
    let value = eval_value(&mut local_symbols, body)?;
57
2190329
    let closed = close_over_params(
58
2190329
        symbols,
59
2190329
        &local_symbols,
60
2190329
        (callee.unwrap_or("LAMBDA"), params),
61
2190329
        value,
62
2190329
    )?;
63
2190296
    Ok(unbound_runtime_capture(symbols, closed))
64
2764712
}
65

            
66
/// `lambda`'s arity check — shared shape (not code) with `call.rs`'s
67
/// `compile_and_bind_lambda_params`, which mirrors this function's
68
/// parameter-binding pipeline step for step.
69
2764712
fn check_lambda_arity(params: &LambdaParams, args: &[Expr]) -> Result<()> {
70
2764712
    let min_args = params.required.len();
71
    // If we have &key or &rest, we can have unlimited args
72
2764712
    let max_args = if params.rest.is_some() || !params.key.is_empty() {
73
258706
        None
74
    } else {
75
2506006
        Some(min_args + params.optional.len())
76
    };
77
2764712
    if args.len() < min_args {
78
624
        return Err(Error::Arity {
79
624
            name: "lambda".to_string(),
80
624
            expected: min_args,
81
624
            actual: args.len(),
82
624
        });
83
2764088
    }
84
2764088
    if let Some(max) = max_args
85
2505382
        && args.len() > max
86
    {
87
        return Err(Error::Arity {
88
            name: "lambda".to_string(),
89
            expected: max,
90
            actual: args.len(),
91
        });
92
2764088
    }
93
2764088
    Ok(())
94
2764712
}
95

            
96
2764088
fn bind_required_params(
97
2764088
    symbols: &mut SymbolTable,
98
2764088
    params: &LambdaParams,
99
2764088
    args: &[Expr],
100
2764088
    arg_idx: &mut usize,
101
2764088
) -> Result<Vec<(String, Expr)>> {
102
2764088
    let mut bound = Vec::with_capacity(params.required.len());
103
2764088
    for param in &params.required {
104
2628584
        let resolved = eval_value(symbols, &args[*arg_idx])?;
105
2622742
        bound.push((param.clone(), resolved));
106
2622742
        *arg_idx += 1;
107
    }
108
2758246
    Ok(bound)
109
2764088
}
110

            
111
2758246
fn bind_optional_params(
112
2758246
    symbols: &mut SymbolTable,
113
2758246
    params: &LambdaParams,
114
2758246
    args: &[Expr],
115
2758246
    arg_idx: &mut usize,
116
2758246
) -> Result<Vec<(String, Expr)>> {
117
2758246
    let mut bound = Vec::with_capacity(params.optional.len());
118
2758246
    for (param, default) in &params.optional {
119
12593
        let value = if *arg_idx < args.len() {
120
2288
            eval_value(symbols, &args[*arg_idx])?
121
10305
        } else if let Some(default_expr) = default {
122
9886
            eval_value(symbols, default_expr)?
123
        } else {
124
419
            Expr::Nil
125
        };
126
12175
        bound.push((param.clone(), value));
127
12175
        if *arg_idx < args.len() {
128
2288
            *arg_idx += 1;
129
9887
        }
130
    }
131
2757828
    Ok(bound)
132
2758246
}
133

            
134
2757828
fn bind_rest_param(
135
2757828
    symbols: &mut SymbolTable,
136
2757828
    params: &LambdaParams,
137
2757828
    args: &[Expr],
138
2757828
    arg_idx: usize,
139
2757828
) -> Result<Option<(String, Expr)>> {
140
2757828
    params
141
2757828
        .rest
142
2757828
        .as_ref()
143
33304
        .map(|rest_param| -> Result<(String, Expr)> {
144
33304
            let rest_args: Vec<Expr> = args[arg_idx..]
145
33304
                .iter()
146
37464
                .map(|arg| eval_value(symbols, arg))
147
208
                .collect::<Result<_>>()?;
148
33096
            Ok((rest_param.clone(), rest_list_value(symbols, rest_args)?))
149
33304
        })
150
        .transpose()
151
2757828
}
152

            
153
/// The rest list: a quoted datum when every argument is constant, otherwise a
154
/// runtime list value the capture rule sees.
155
33096
fn rest_list_value(symbols: &SymbolTable, rest_args: Vec<Expr>) -> Result<Expr> {
156
33096
    if !rest_args.iter().any(Expr::is_wasm_runtime) {
157
30796
        return crate::compiler::datum::bounded(symbols, Expr::quoted_list(rest_args));
158
2300
    }
159
2300
    let elem = chain_pair_element(&rest_args)?;
160
2300
    Ok(Expr::WasmRuntime(WasmType::PairRef(elem)))
161
33096
}
162

            
163
/// The value following the first `keyword` in a `&key` argument list; CL
164
/// rejects an odd-length list.
165
425623
pub(super) fn find_keyword_value<'a>(args: &'a [Expr], keyword: &Expr) -> Result<Option<&'a Expr>> {
166
425623
    if !args.len().is_multiple_of(2) {
167
        return Err(Error::Compile("odd number of &KEY arguments".to_string()));
168
425623
    }
169
425623
    Ok(args
170
425623
        .as_chunks::<2>()
171
425623
        .0
172
425623
        .iter()
173
474850
        .find_map(|pair| (pair[0] == *keyword).then_some(&pair[1])))
174
425623
}
175

            
176
/// Rejects a `&key` argument list whose pairs do not all name a declared
177
/// keyword.
178
1069946
pub(super) fn check_keyword_args(params: &LambdaParams, args: &[Expr]) -> Result<()> {
179
1069946
    if params.key.is_empty() {
180
723555
        return Ok(());
181
346391
    }
182
346391
    if !args.len().is_multiple_of(2) {
183
846
        return Err(Error::Compile("odd number of &KEY arguments".to_string()));
184
345545
    }
185
345545
    args.as_chunks::<2>()
186
345545
        .0
187
345545
        .iter()
188
343812
        .try_for_each(|pair| match &pair[0] {
189
            Expr::Keyword(name)
190
343809
                if params
191
343809
                    .key
192
343809
                    .iter()
193
448862
                    .any(|param| param.keyword.eq_ignore_ascii_case(name)) =>
194
            {
195
343173
                Ok(())
196
            }
197
639
            other => Err(Error::Compile(format!(
198
639
                "unknown keyword argument {}",
199
639
                format_form(other)
200
639
            ))),
201
343812
        })
202
1069946
}
203

            
204
2757412
fn bind_key_params(
205
2757412
    symbols: &mut SymbolTable,
206
2757412
    params: &LambdaParams,
207
2757412
    args: &[Expr],
208
2757412
    arg_idx: usize,
209
2757412
) -> Result<Vec<(String, Expr)>> {
210
2757412
    let mut bound = Vec::with_capacity(params.key.len());
211
2757412
    if params.key.is_empty() {
212
2532010
        return Ok(bound);
213
225402
    }
214
    // Find keyword arguments in the remaining args
215
225402
    let remaining_args = &args[arg_idx..];
216
225402
    check_keyword_args(params, remaining_args)?;
217
    for KeyParam {
218
        name: param,
219
        keyword,
220
        default,
221
225401
    } in &params.key
222
    {
223
228315
        let keyword = Expr::Keyword(keyword.clone());
224
228315
        let found_value = find_keyword_value(remaining_args, &keyword)?
225
205203
            .map(|form| eval_value(symbols, form))
226
1040
            .transpose()?;
227

            
228
227275
        let value = if let Some(val) = found_value {
229
204163
            val
230
23112
        } else if let Some(default_expr) = default {
231
5224
            eval_value(symbols, default_expr)?
232
        } else {
233
17888
            Expr::Nil
234
        };
235

            
236
227275
        bound.push((param.clone(), value));
237
    }
238
224361
    Ok(bound)
239
2757412
}
240

            
241
/// Registers every collected `(param, value)` pair into `local`, in the
242
/// required/optional/rest/key order CL binds them.
243
2755123
fn install_bound_params(
244
2755123
    local: &mut SymbolTable,
245
2755123
    required: Vec<(String, Expr)>,
246
2755123
    optional: Vec<(String, Expr)>,
247
2755123
    rest: Option<(String, Expr)>,
248
2755123
    key: Vec<(String, Expr)>,
249
2755123
) {
250
2755123
    for (param, value) in required.into_iter().chain(optional).chain(rest).chain(key) {
251
2894454
        local.define(Symbol::new(&param, SymbolKind::Variable).with_value(value));
252
    }
253
2755123
}
254

            
255
// Bind aux parameters (auxiliary variables)
256
2755123
fn bind_aux_params(local: &mut SymbolTable, params: &LambdaParams) -> Result<()> {
257
2755123
    for (param, init) in &params.aux {
258
6692
        let value = if let Some(init_expr) = init {
259
6484
            eval_value(local, init_expr)?
260
        } else {
261
208
            Expr::Nil
262
        };
263
6484
        local.define(Symbol::new(param, SymbolKind::Variable).with_value(value));
264
    }
265
2754915
    Ok(())
266
2755123
}