Lines
98.77 %
Functions
90.91 %
Branches
100 %
//! Function call dispatch.
//!
//! Three call paths coexist; per ADR-0027 the inline path stays as the
//! const-fold fast path and the runtime-call / call_ref paths are
//! additive:
//! - **Inline path** ([`compile_lambda_call`] /
//! [`compile_lambda_call_for_stack`] /
//! [`compile_and_bind_lambda_params`]) — clones the symbol table,
//! binds each arg into the local scope (constants flow through as
//! values; runtime args get an outer-scope local), then walks the
//! body via `compile_expr` / `compile_for_stack`. This is the only
//! path that can const-fold a fully-known argument list down to a
//! single value, and it's the path the test framework, macro
//! expansion, and the commodity-mismatch invariant all sit on.
//! - **Runtime-call path** (`call_runtime::try_compile_runtime_call`) — fires when
//! the inline walk would diverge (recursion plus a runtime arg). The
//! defun body is emitted once per call-site signature into a
//! monomorph helper fn; each matching call site lowers to
//! `call $monomorph_idx`. See `compiler/special/lambda/monomorph.rs`.
//! - **Closure call_ref path** ([`compile_call_ref`]) — fires when the
//! call head is a `WasmLocal` of a `Closure(sig)` value (the operand of
//! FUNCALL / APPLY, or a closure passed through MAP/FOLD). Loads `funcref` + env from the struct and
//! `call_ref`s through the typed signature.
//! Entry points:
//! - [`compile_call`] — effect-position call from `compile_expr`'s list
//! branch. Dispatches on the call head: symbol → `compile_symbol_call`,
//! inline lambda → inline path, list head → recurse after `eval`.
//! - [`compile_symbol_call`] (private) — macro-expand if applicable,
//! then dispatch in order: runtime-call → inline → closure call_ref →
//! native → special form.
//! - The stack-position mirrors live in [`super::stack`].
use super::respecialise::compile_closure_call;
use crate::ast::{ClosureSigId, Expr, LambdaParams, Number, Place, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::join::NEVER_RETURNS;
use crate::compiler::native::function_operand::effect_prefix;
use crate::compiler::special::{bind_lambda_closure, infer_params, used_as_function};
use crate::error::{Error, Result};
use crate::runtime::{Head, SymbolTable};
use super::any_call::compile_any_call;
use super::call_runtime::try_compile_runtime_call;
use super::compile::compile_expr;
use super::effect::compile_for_effect;
use super::eval::{call, expand_macro_then};
use super::fold::walk::{is_lambda_head, is_lambda_literal};
use super::fold::{fold_safe, probe_value};
use super::format::not_callable;
use super::lambda_params::compile_and_bind_lambda_params;
use super::local_cell::emit_place_read;
use super::stack::{classify_stack_type, compile_for_stack, compile_for_stack_as};
pub(in crate::compiler) fn compile_call(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
elems: &[Expr],
) -> Result<()> {
let (head, args) = elems
.split_first()
.ok_or_else(|| Error::Compile("empty function call".to_string()))?;
match head {
Expr::Symbol(name) => compile_symbol_call(ctx, emit, symbols, name, args),
Expr::Datum(inner) => match inner.as_ref() {
_ => Err(not_callable(head)),
},
Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
compile_lambda_call(ctx, emit, symbols, params, body, args, None)
}),
Expr::List(inner) => {
let resolved = call(symbols, inner)?;
match resolved {
compile_lambda_call(ctx, emit, symbols, ¶ms, &body, args, None)
}
Expr::WasmLocal(..) | Expr::WasmGlobal(..) => match call_target(head) {
Some(CallTarget::Closure(place, sig)) => {
compile_closure_call(ctx, emit, symbols, (place, sig), args)
Some(CallTarget::Any(place)) => {
let ty = compile_any_call(ctx, emit, symbols, place, args)?;
crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty)
None => Err(not_callable(head)),
/// Runs `apply`, the application of the lambda `head` stands for, one level
/// deep in the shared recursion budget unless `head` is a lambda the source
/// spells out: a lambda a call or a name produces can build and apply another
/// of itself without end, the nesting of literals is bounded by the source.
pub(crate) fn applying_lambda<T>(
head: &Expr,
apply: impl FnOnce(&mut SymbolTable) -> Result<T>,
) -> Result<T> {
if is_lambda_head(symbols, head) {
return apply(symbols);
symbols.within_shared_recursion(apply)
/// What a call head names without a symbol, as `apply` leaves it.
pub(in crate::compiler) enum CallTarget {
Closure(Place, ClosureSigId),
/// A value only run time can tell is a function.
Any(Place),
pub(in crate::compiler) fn call_target(head: &Expr) -> Option<CallTarget> {
match head.place()? {
(place, WasmType::Closure(sig)) => Some(CallTarget::Closure(place, sig)),
(place, WasmType::AnyRef) => Some(CallTarget::Any(place)),
_ => None,
/// The closure place and signature a call head names, if it is a closure.
pub(in crate::compiler) fn call_place(head: &Expr) -> Option<(Place, ClosureSigId)> {
match call_target(head)? {
CallTarget::Closure(place, sig) => Some((place, sig)),
CallTarget::Any(_) => None,
fn compile_symbol_call(
name: &str,
args: &[Expr],
match symbols.resolve_head(name) {
Head::Macro(params, body) => {
let (params, body) = (params.clone(), body.clone());
expand_macro_then(symbols, ¶ms, &body, args, |symbols, code| {
compile_expr(ctx, emit, symbols, &code)
})
Head::Function(params, body) => {
let args = &lift_function_args(ctx, emit, symbols, (¶ms, &body), args)?;
if let Some(ty) =
try_compile_runtime_call(ctx, emit, symbols, name, ¶ms, &body, args)?
{
return crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty);
ctx.push_inlining_frame(symbols, name)?;
let result = compile_lambda_call(ctx, emit, symbols, ¶ms, &body, args, Some(name));
ctx.pop_inlining_frame(symbols, name)?;
result
Head::Native => crate::compiler::native::compile(ctx, emit, symbols, name, args),
Head::SpecialForm => crate::compiler::special::compile(ctx, emit, symbols, name, args),
Head::Unknown if symbols.contains(name) => Err(symbols.not_callable(name, "")),
Head::Unknown => Err(Error::undefined_symbol(name)),
/// Lowers a call against a runtime closure value held in `closure`.
/// Stack discipline mirrors `$fn_<sig>`'s declared signature
/// `(env, args...)`: load env from the closure, push each arg, then
/// load the funcref and `call_ref`.
pub(in crate::compiler) fn compile_call_ref(
closure: Place,
sig: ClosureSigId,
) -> Result<WasmType> {
let (closure_type_idx, fn_type_idx, expected_params, result_ty) = {
let entry = ctx.closure_sig(sig)?;
(
entry.closure_type_idx,
entry.fn_type_idx,
entry.params.clone(),
entry.result,
)
};
if args.len() != expected_params.len() {
return Err(Error::Arity {
name: "closure".to_string(),
expected: expected_params.len(),
actual: args.len(),
});
// Snapshot the closure value before compiling arguments: an argument that
// reassigns the callee local (e.g. `(progn (setf f g) 1)`) must not let the
// env be read from the old closure and the funcref from the new one.
let saved = ctx.alloc_local(WasmType::Closure(sig))?;
emit_place_read(ctx, emit, closure)?;
emit.local_set(saved);
emit.local_get(saved);
emit.struct_get(closure_type_idx, 1);
for (index, (arg, &expected)) in args.iter().zip(expected_params.iter()).enumerate() {
// A nil becomes the typed default; any other argument must be of the
// parameter's kind.
compile_closure_arg(ctx, emit, symbols, arg, expected).map_err(|e| {
let hint = pin_hint(symbols, (closure, index), (arg, expected));
mismatch(expected, e, &hint)
})?;
emit.struct_get(closure_type_idx, 0);
emit.call_ref(fn_type_idx);
Ok(result_ty)
/// Pushes `arg` as the closure parameter `expected`; an integer literal is an
/// index and never a scalar.
pub(super) fn compile_closure_arg(
arg: &Expr,
expected: WasmType,
if expected == WasmType::Ratio
&& matches!(
probe_value(&mut symbols.clone(), arg)?,
Expr::Number(Number::Index(_))
return Err(Error::Dimension(
"an integer argument is an index, not a scalar; \
bridge explicitly with `(index->scalar ...)`"
.to_string(),
));
compile_for_stack_as(ctx, emit, symbols, arg, expected)
/// `args` with each lambda literal that lands in a positional parameter the
/// body uses bound to a closure local first, so the monomorph decision sees the
/// closure a `let` would bind. A lambda after an effectful argument is left to
/// the binder, which lifts it in argument order.
pub(in crate::compiler) fn lift_function_args(
(params, body): (&LambdaParams, &Expr),
) -> Result<Vec<Expr>> {
let positional = params
.required
.iter()
.chain(params.optional.iter().map(|(p, _)| p));
let mut pure_so_far = true;
let mut lifted = Vec::with_capacity(args.len());
for (arg, param) in args
.zip(positional.map(Some).chain(std::iter::repeat(None)))
let (_, value) = effect_prefix(arg);
let used = match param {
Some(param) => used_as_function(symbols, body, param)?,
None => false,
if used
&& pure_so_far
&& is_lambda_literal(symbols, value)
&& let Expr::Lambda(lambda, lambda_body) = probe_value(&mut symbols.clone(), value)?
lifted.push(lift_lambda(
ctx,
emit,
symbols,
arg,
(&lambda, &lambda_body),
)?);
continue;
pure_so_far &= fold_safe(symbols, arg);
lifted.push(arg.clone());
Ok(lifted)
/// Binds the lambda `arg` evaluates to a closure local, after running the
/// effects `arg` carries once; the lambda itself when it does not fit the v1
/// emit slice.
pub(in crate::compiler) fn lift_lambda(
) -> Result<Expr> {
compile_for_effect(ctx, emit, symbols, arg)?;
let closure = bind_lambda_closure(ctx, emit, symbols, params, body, false)?;
Ok(closure.unwrap_or_else(|| Expr::Lambda(params.clone(), Box::new(body.clone()))))
/// The call's error for an argument that is not the closure's `expected`
/// parameter type. The inner message, without the "Compile error: " prefix
/// `err`'s `Display` carries.
fn mismatch(expected: WasmType, err: Error, hint: &str) -> Error {
let detail = match err {
Error::Compile(msg) => msg,
other => other.to_string().replacen("Compile error: ", "", 1),
Error::Compile(format!(
"closure argument type mismatch: expected {expected:?}: {detail}{hint}"
))
/// What to add to the mismatch of `arg` against parameter `index` of the
/// closure in `place`, when `arg` has a type the parameter's does not match: the
/// THE pin the type lacks, named when the source is recorded.
pub(in crate::compiler) fn pin_hint(
symbols: &SymbolTable,
(place, index): (Place, usize),
(arg, expected): (&Expr, WasmType),
) -> String {
let arg_type = probe_value(&mut symbols.clone(), arg)
.ok()
.and_then(|value| classify_stack_type(&value));
if arg_type.is_none_or(|ty| ty == expected) {
return String::new();
let Some((params, body)) = symbols.closure_body(place) else {
return "; pin the parameter with THE unless its body does".to_string();
match params.required.get(index) {
Some(name) if infer_params(symbols, params, body).ambiguous.get(index) == Some(&true) => {
format!("; cannot infer the type of parameter {name}; pin it with THE")
_ => String::new(),
/// The BLOCK labels visible where the function `name` was defined.
pub(in crate::compiler) fn definition_depth(symbols: &SymbolTable, name: &str) -> usize {
symbols
.lookup(name)
.map_or(0, crate::runtime::Symbol::block_depth)
/// Inlines a lambda call. A named function's body (`callee` is `Some`) sees
/// only the BLOCK labels and lexical variables of its definition site, never
/// the caller's; the arguments are bound first, at the call site, where
/// everything shows.
pub(super) fn compile_lambda_call(
params: &LambdaParams,
body: &Expr,
callee: Option<&str>,
let Some(mut local) =
compile_and_bind_lambda_params(ctx, emit, symbols, params, body, args, callee)?
else {
return Ok(());
match callee {
Some(name) => {
let depth = definition_depth(symbols, name);
ctx.with_hidden_labels(depth, |ctx| compile_expr(ctx, emit, &mut local, body))
None => compile_expr(ctx, emit, &mut local, body),
pub(in crate::compiler) fn compile_lambda_call_for_stack(
return Ok(NEVER_RETURNS);
ctx.with_hidden_labels(depth, |ctx| compile_for_stack(ctx, emit, &mut local, body))
None => compile_for_stack(ctx, emit, &mut local, body),
#[cfg(test)]
#[path = "call_tests.rs"]
mod tests;