1
//! Function call dispatch.
2
//!
3
//! Three call paths coexist; per ADR-0027 the inline path stays as the
4
//! const-fold fast path and the runtime-call / call_ref paths are
5
//! additive:
6
//!
7
//! - **Inline path** ([`compile_lambda_call`] /
8
//!   [`compile_lambda_call_for_stack`] /
9
//!   [`compile_and_bind_lambda_params`]) — clones the symbol table,
10
//!   binds each arg into the local scope (constants flow through as
11
//!   values; runtime args get an outer-scope local), then walks the
12
//!   body via `compile_expr` / `compile_for_stack`. This is the only
13
//!   path that can const-fold a fully-known argument list down to a
14
//!   single value, and it's the path the test framework, macro
15
//!   expansion, and the commodity-mismatch invariant all sit on.
16
//! - **Runtime-call path** (`call_runtime::try_compile_runtime_call`) — fires when
17
//!   the inline walk would diverge (recursion plus a runtime arg). The
18
//!   defun body is emitted once per call-site signature into a
19
//!   monomorph helper fn; each matching call site lowers to
20
//!   `call $monomorph_idx`. See `compiler/special/lambda/monomorph.rs`.
21
//! - **Closure call_ref path** ([`compile_call_ref`]) — fires when the
22
//!   call head is a `WasmLocal` of a `Closure(sig)` value (the operand of
23
//!   FUNCALL / APPLY, or a closure passed through MAP/FOLD). Loads `funcref` + env from the struct and
24
//!   `call_ref`s through the typed signature.
25
//!
26
//! Entry points:
27
//! - [`compile_call`] — effect-position call from `compile_expr`'s list
28
//!   branch. Dispatches on the call head: symbol → `compile_symbol_call`,
29
//!   inline lambda → inline path, list head → recurse after `eval`.
30
//! - [`compile_symbol_call`] (private) — macro-expand if applicable,
31
//!   then dispatch in order: runtime-call → inline → closure call_ref →
32
//!   native → special form.
33
//! - The stack-position mirrors live in [`super::stack`].
34

            
35
use super::respecialise::compile_closure_call;
36
use crate::ast::{ClosureSigId, Expr, LambdaParams, Number, Place, WasmType};
37
use crate::compiler::context::CompileContext;
38
use crate::compiler::emit::FunctionEmitter;
39
use crate::compiler::join::NEVER_RETURNS;
40
use crate::compiler::native::function_operand::effect_prefix;
41
use crate::compiler::special::{bind_lambda_closure, infer_params, used_as_function};
42
use crate::error::{Error, Result};
43
use crate::runtime::{Head, SymbolTable};
44

            
45
use super::any_call::compile_any_call;
46
use super::call_runtime::try_compile_runtime_call;
47
use super::compile::compile_expr;
48
use super::effect::compile_for_effect;
49
use super::eval::{call, expand_macro_then};
50
use super::fold::walk::{is_lambda_head, is_lambda_literal};
51
use super::fold::{fold_safe, probe_value};
52
use super::format::not_callable;
53
use super::lambda_params::compile_and_bind_lambda_params;
54
use super::local_cell::emit_place_read;
55
use super::stack::{classify_stack_type, compile_for_stack, compile_for_stack_as};
56

            
57
1958126
pub(in crate::compiler) fn compile_call(
58
1958126
    ctx: &mut CompileContext,
59
1958126
    emit: &mut FunctionEmitter,
60
1958126
    symbols: &mut SymbolTable,
61
1958126
    elems: &[Expr],
62
1958126
) -> Result<()> {
63
1958126
    let (head, args) = elems
64
1958126
        .split_first()
65
        .ok_or_else(|| Error::Compile("empty function call".to_string()))?;
66
1958126
    match head {
67
1889098
        Expr::Symbol(name) => compile_symbol_call(ctx, emit, symbols, name, args),
68
7332
        Expr::Datum(inner) => match inner.as_ref() {
69
7332
            Expr::Symbol(name) => compile_symbol_call(ctx, emit, symbols, name, args),
70
            _ => Err(not_callable(head)),
71
        },
72
7212
        Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
73
7208
            compile_lambda_call(ctx, emit, symbols, params, body, args, None)
74
7208
        }),
75
        Expr::List(inner) => {
76
5862
            let resolved = call(symbols, inner)?;
77
4391
            match resolved {
78
4389
                Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
79
4385
                    compile_lambda_call(ctx, emit, symbols, &params, &body, args, None)
80
4385
                }),
81
2
                _ => Err(not_callable(head)),
82
            }
83
        }
84
48602
        Expr::WasmLocal(..) | Expr::WasmGlobal(..) => match call_target(head) {
85
            Some(CallTarget::Closure(place, sig)) => {
86
39387
                compile_closure_call(ctx, emit, symbols, (place, sig), args)
87
            }
88
            Some(CallTarget::Any(place)) => {
89
9215
                let ty = compile_any_call(ctx, emit, symbols, place, args)?;
90
9215
                crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty)
91
            }
92
            None => Err(not_callable(head)),
93
        },
94
20
        _ => Err(not_callable(head)),
95
    }
96
1958126
}
97

            
98
/// Runs `apply`, the application of the lambda `head` stands for, one level
99
/// deep in the shared recursion budget unless `head` is a lambda the source
100
/// spells out: a lambda a call or a name produces can build and apply another
101
/// of itself without end, the nesting of literals is bounded by the source.
102
1440132
pub(crate) fn applying_lambda<T>(
103
1440132
    symbols: &mut SymbolTable,
104
1440132
    head: &Expr,
105
1440132
    apply: impl FnOnce(&mut SymbolTable) -> Result<T>,
106
1440132
) -> Result<T> {
107
1440132
    if is_lambda_head(symbols, head) {
108
586039
        return apply(symbols);
109
854093
    }
110
854093
    symbols.within_shared_recursion(apply)
111
1440132
}
112

            
113
/// What a call head names without a symbol, as `apply` leaves it.
114
pub(in crate::compiler) enum CallTarget {
115
    Closure(Place, ClosureSigId),
116
    /// A value only run time can tell is a function.
117
    Any(Place),
118
}
119

            
120
540140
pub(in crate::compiler) fn call_target(head: &Expr) -> Option<CallTarget> {
121
540140
    match head.place()? {
122
127763
        (place, WasmType::Closure(sig)) => Some(CallTarget::Closure(place, sig)),
123
18654
        (place, WasmType::AnyRef) => Some(CallTarget::Any(place)),
124
1042
        _ => None,
125
    }
126
540140
}
127

            
128
/// The closure place and signature a call head names, if it is a closure.
129
392694
pub(in crate::compiler) fn call_place(head: &Expr) -> Option<(Place, ClosureSigId)> {
130
392694
    match call_target(head)? {
131
11
        CallTarget::Closure(place, sig) => Some((place, sig)),
132
1
        CallTarget::Any(_) => None,
133
    }
134
392694
}
135

            
136
1896430
fn compile_symbol_call(
137
1896430
    ctx: &mut CompileContext,
138
1896430
    emit: &mut FunctionEmitter,
139
1896430
    symbols: &mut SymbolTable,
140
1896430
    name: &str,
141
1896430
    args: &[Expr],
142
1896430
) -> Result<()> {
143
1896430
    match symbols.resolve_head(name) {
144
        Head::Macro(params, body) => {
145
21133
            let (params, body) = (params.clone(), body.clone());
146
21133
            expand_macro_then(symbols, &params, &body, args, |symbols, code| {
147
20357
                compile_expr(ctx, emit, symbols, &code)
148
20357
            })
149
        }
150
        Head::Function(params, body) => {
151
95732
            let (params, body) = (params.clone(), body.clone());
152
95732
            let args = &lift_function_args(ctx, emit, symbols, (&params, &body), args)?;
153
            if let Some(ty) =
154
95732
                try_compile_runtime_call(ctx, emit, symbols, name, &params, &body, args)?
155
            {
156
4429
                return crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty);
157
90465
            }
158
90465
            ctx.push_inlining_frame(symbols, name)?;
159
90049
            let result = compile_lambda_call(ctx, emit, symbols, &params, &body, args, Some(name));
160
90049
            ctx.pop_inlining_frame(symbols, name)?;
161
90049
            result
162
        }
163
229853
        Head::Native => crate::compiler::native::compile(ctx, emit, symbols, name, args),
164
1530557
        Head::SpecialForm => crate::compiler::special::compile(ctx, emit, symbols, name, args),
165
19155
        Head::Unknown if symbols.contains(name) => Err(symbols.not_callable(name, "")),
166
17691
        Head::Unknown => Err(Error::undefined_symbol(name)),
167
    }
168
1896430
}
169

            
170
/// Lowers a call against a runtime closure value held in `closure`.
171
/// Stack discipline mirrors `$fn_<sig>`'s declared signature
172
/// `(env, args...)`: load env from the closure, push each arg, then
173
/// load the funcref and `call_ref`.
174
76849
pub(in crate::compiler) fn compile_call_ref(
175
76849
    ctx: &mut CompileContext,
176
76849
    emit: &mut FunctionEmitter,
177
76849
    symbols: &mut SymbolTable,
178
76849
    closure: Place,
179
76849
    sig: ClosureSigId,
180
76849
    args: &[Expr],
181
76849
) -> Result<WasmType> {
182
    let (closure_type_idx, fn_type_idx, expected_params, result_ty) = {
183
76849
        let entry = ctx.closure_sig(sig)?;
184
76849
        (
185
76849
            entry.closure_type_idx,
186
76849
            entry.fn_type_idx,
187
76849
            entry.params.clone(),
188
76849
            entry.result,
189
76849
        )
190
    };
191
76849
    if args.len() != expected_params.len() {
192
416
        return Err(Error::Arity {
193
416
            name: "closure".to_string(),
194
416
            expected: expected_params.len(),
195
416
            actual: args.len(),
196
416
        });
197
76433
    }
198
    // Snapshot the closure value before compiling arguments: an argument that
199
    // reassigns the callee local (e.g. `(progn (setf f g) 1)`) must not let the
200
    // env be read from the old closure and the funcref from the new one.
201
76433
    let saved = ctx.alloc_local(WasmType::Closure(sig))?;
202
76433
    emit_place_read(ctx, emit, closure)?;
203
76433
    emit.local_set(saved);
204
76433
    emit.local_get(saved);
205
76433
    emit.struct_get(closure_type_idx, 1);
206
76433
    for (index, (arg, &expected)) in args.iter().zip(expected_params.iter()).enumerate() {
207
        // A nil becomes the typed default; any other argument must be of the
208
        // parameter's kind.
209
52595
        compile_closure_arg(ctx, emit, symbols, arg, expected).map_err(|e| {
210
640
            let hint = pin_hint(symbols, (closure, index), (arg, expected));
211
640
            mismatch(expected, e, &hint)
212
640
        })?;
213
    }
214
75793
    emit.local_get(saved);
215
75793
    emit.struct_get(closure_type_idx, 0);
216
75793
    emit.call_ref(fn_type_idx);
217
75793
    Ok(result_ty)
218
76849
}
219

            
220
/// Pushes `arg` as the closure parameter `expected`; an integer literal is an
221
/// index and never a scalar.
222
52760
pub(super) fn compile_closure_arg(
223
52760
    ctx: &mut CompileContext,
224
52760
    emit: &mut FunctionEmitter,
225
52760
    symbols: &mut SymbolTable,
226
52760
    arg: &Expr,
227
52760
    expected: WasmType,
228
52760
) -> Result<()> {
229
52760
    if expected == WasmType::Ratio
230
5105
        && matches!(
231
5105
            probe_value(&mut symbols.clone(), arg)?,
232
            Expr::Number(Number::Index(_))
233
        )
234
    {
235
9
        return Err(Error::Dimension(
236
9
            "an integer argument is an index, not a scalar; \
237
9
             bridge explicitly with `(index->scalar ...)`"
238
9
                .to_string(),
239
9
        ));
240
52751
    }
241
52751
    compile_for_stack_as(ctx, emit, symbols, arg, expected)
242
52760
}
243

            
244
/// `args` with each lambda literal that lands in a positional parameter the
245
/// body uses bound to a closure local first, so the monomorph decision sees the
246
/// closure a `let` would bind. A lambda after an effectful argument is left to
247
/// the binder, which lifts it in argument order.
248
433992
pub(in crate::compiler) fn lift_function_args(
249
433992
    ctx: &mut CompileContext,
250
433992
    emit: &mut FunctionEmitter,
251
433992
    symbols: &mut SymbolTable,
252
433992
    (params, body): (&LambdaParams, &Expr),
253
433992
    args: &[Expr],
254
433992
) -> Result<Vec<Expr>> {
255
433992
    let positional = params
256
433992
        .required
257
433992
        .iter()
258
433992
        .chain(params.optional.iter().map(|(p, _)| p));
259
433992
    let mut pure_so_far = true;
260
433992
    let mut lifted = Vec::with_capacity(args.len());
261
433992
    for (arg, param) in args
262
433992
        .iter()
263
433992
        .zip(positional.map(Some).chain(std::iter::repeat(None)))
264
    {
265
626456
        let (_, value) = effect_prefix(arg);
266
626456
        let used = match param {
267
349053
            Some(param) => used_as_function(symbols, body, param)?,
268
277403
            None => false,
269
        };
270
626456
        if used
271
304233
            && pure_so_far
272
250069
            && is_lambda_literal(symbols, value)
273
1351
            && let Expr::Lambda(lambda, lambda_body) = probe_value(&mut symbols.clone(), value)?
274
        {
275
903
            lifted.push(lift_lambda(
276
903
                ctx,
277
903
                emit,
278
903
                symbols,
279
903
                arg,
280
903
                (&lambda, &lambda_body),
281
903
            )?);
282
903
            continue;
283
625553
        }
284
625553
        pure_so_far &= fold_safe(symbols, arg);
285
625553
        lifted.push(arg.clone());
286
    }
287
433992
    Ok(lifted)
288
433992
}
289

            
290
/// Binds the lambda `arg` evaluates to a closure local, after running the
291
/// effects `arg` carries once; the lambda itself when it does not fit the v1
292
/// emit slice.
293
2793
pub(in crate::compiler) fn lift_lambda(
294
2793
    ctx: &mut CompileContext,
295
2793
    emit: &mut FunctionEmitter,
296
2793
    symbols: &mut SymbolTable,
297
2793
    arg: &Expr,
298
2793
    (params, body): (&LambdaParams, &Expr),
299
2793
) -> Result<Expr> {
300
2793
    compile_for_effect(ctx, emit, symbols, arg)?;
301
2793
    let closure = bind_lambda_closure(ctx, emit, symbols, params, body, false)?;
302
2793
    Ok(closure.unwrap_or_else(|| Expr::Lambda(params.clone(), Box::new(body.clone()))))
303
2793
}
304

            
305
/// The call's error for an argument that is not the closure's `expected`
306
/// parameter type. The inner message, without the "Compile error: " prefix
307
/// `err`'s `Display` carries.
308
642
fn mismatch(expected: WasmType, err: Error, hint: &str) -> Error {
309
642
    let detail = match err {
310
629
        Error::Compile(msg) => msg,
311
13
        other => other.to_string().replacen("Compile error: ", "", 1),
312
    };
313
642
    Error::Compile(format!(
314
642
        "closure argument type mismatch: expected {expected:?}: {detail}{hint}"
315
642
    ))
316
642
}
317

            
318
/// What to add to the mismatch of `arg` against parameter `index` of the
319
/// closure in `place`, when `arg` has a type the parameter's does not match: the
320
/// THE pin the type lacks, named when the source is recorded.
321
651
pub(in crate::compiler) fn pin_hint(
322
651
    symbols: &SymbolTable,
323
651
    (place, index): (Place, usize),
324
651
    (arg, expected): (&Expr, WasmType),
325
651
) -> String {
326
651
    let arg_type = probe_value(&mut symbols.clone(), arg)
327
651
        .ok()
328
650
        .and_then(|value| classify_stack_type(&value));
329
651
    if arg_type.is_none_or(|ty| ty == expected) {
330
3
        return String::new();
331
648
    }
332
648
    let Some((params, body)) = symbols.closure_body(place) else {
333
429
        return "; pin the parameter with THE unless its body does".to_string();
334
    };
335
219
    match params.required.get(index) {
336
218
        Some(name) if infer_params(symbols, params, body).ambiguous.get(index) == Some(&true) => {
337
4
            format!("; cannot infer the type of parameter {name}; pin it with THE")
338
        }
339
215
        _ => String::new(),
340
    }
341
651
}
342

            
343
/// The BLOCK labels visible where the function `name` was defined.
344
413373
pub(in crate::compiler) fn definition_depth(symbols: &SymbolTable, name: &str) -> usize {
345
413373
    symbols
346
413373
        .lookup(name)
347
413373
        .map_or(0, crate::runtime::Symbol::block_depth)
348
413373
}
349

            
350
/// Inlines a lambda call. A named function's body (`callee` is `Some`) sees
351
/// only the BLOCK labels and lexical variables of its definition site, never
352
/// the caller's; the arguments are bound first, at the call site, where
353
/// everything shows.
354
102296
pub(super) fn compile_lambda_call(
355
102296
    ctx: &mut CompileContext,
356
102296
    emit: &mut FunctionEmitter,
357
102296
    symbols: &mut SymbolTable,
358
102296
    params: &LambdaParams,
359
102296
    body: &Expr,
360
102296
    args: &[Expr],
361
102296
    callee: Option<&str>,
362
102296
) -> Result<()> {
363
    let Some(mut local) =
364
102296
        compile_and_bind_lambda_params(ctx, emit, symbols, params, body, args, callee)?
365
    else {
366
208
        return Ok(());
367
    };
368
98302
    match callee {
369
        Some(name) => {
370
86061
            let depth = definition_depth(symbols, name);
371
86061
            ctx.with_hidden_labels(depth, |ctx| compile_expr(ctx, emit, &mut local, body))
372
        }
373
12241
        None => compile_expr(ctx, emit, &mut local, body),
374
    }
375
102296
}
376

            
377
669498
pub(in crate::compiler) fn compile_lambda_call_for_stack(
378
669498
    ctx: &mut CompileContext,
379
669498
    emit: &mut FunctionEmitter,
380
669498
    symbols: &mut SymbolTable,
381
669498
    params: &LambdaParams,
382
669498
    body: &Expr,
383
669498
    args: &[Expr],
384
669498
    callee: Option<&str>,
385
669498
) -> Result<WasmType> {
386
    let Some(mut local) =
387
669498
        compile_and_bind_lambda_params(ctx, emit, symbols, params, body, args, callee)?
388
    else {
389
1751
        return Ok(NEVER_RETURNS);
390
    };
391
663141
    match callee {
392
        Some(name) => {
393
303642
            let depth = definition_depth(symbols, name);
394
303642
            ctx.with_hidden_labels(depth, |ctx| compile_for_stack(ctx, emit, &mut local, body))
395
        }
396
359499
        None => compile_for_stack(ctx, emit, &mut local, body),
397
    }
398
669498
}
399

            
400
#[cfg(test)]
401
#[path = "call_tests.rs"]
402
mod tests;