Lines
85.5 %
Functions
86.84 %
Branches
100 %
//! Runtime-call path: lowers a recursive call with a runtime argument
//! through a monomorph helper fn (see `compiler/special/lambda/monomorph.rs`).
use crate::ast::{Expr, LambdaParams, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::context::monomorph::{MonomorphEntry, Slot};
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::special::lookup_or_emit_monomorph;
use crate::error::{Error, Result};
use crate::runtime::{Symbol, SymbolTable};
use super::boxing::emit_box_anyref;
use super::fold::{probe_typed, probe_value};
use super::local_cell::emit_local_read;
use super::operand::always_raises;
use super::stack::compile_for_stack;
/// Tier 1.5 Gap B runtime-call dispatch. If the inline const-fold walk
/// would diverge — `name` is recursive AND at least one arg resolves to
/// a runtime value — we lower the call through a real wasm fn instead.
/// The body is emitted once per call-site signature (cached) and each
/// matching call site emits `call $monomorph_idx`. Returns `None` to
/// signal "stay on the inline path"; `Some(ret_ty)` means the runtime
/// stack now holds the call's result.
pub(super) fn try_compile_runtime_call(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
name: &str,
params: &LambdaParams,
body: &Expr,
args: &[Expr],
) -> Result<Option<WasmType>> {
if !needs_runtime_call(ctx, symbols, name, body, args) || any_raises(symbols, args)? {
return Ok(None);
}
let arg_types = infer_arg_types(symbols, args)?;
let closures = arg_closure_sources(ctx, symbols, args)?;
let entry = lookup_or_emit_monomorph(ctx, symbols, name, params, body, &arg_types, closures)?;
emit_runtime_call(ctx, emit, symbols, args, &arg_types, &entry)?;
Ok(Some(entry.ret_ty))
/// An always-raising argument stays on the inline path, which compiles the
/// arguments up to it and never enters the body.
fn any_raises(symbols: &SymbolTable, args: &[Expr]) -> Result<bool> {
for arg in args {
if always_raises(symbols, arg)? {
return Ok(true);
Ok(false)
/// Pure classification — the whole arg list is probed SEQUENTIALLY on ONE
/// DISPOSABLE clone (so a later arg's probe still sees an earlier arg's
/// compile-time effects, e.g. a `setf`), never on the live table: this runs
/// ahead of the real per-argument compile ([`compile_arg_for_param`]), so it
/// must not apply any argument's effects itself — the real, single
/// application happens later, in codegen.
fn needs_runtime_call(
ctx: &CompileContext,
symbols: &SymbolTable,
self_name: &str,
) -> bool {
let mut probe = symbols.clone();
let any_runtime = args.iter().any(|arg| arg_resolves_runtime(&mut probe, arg));
any_runtime && body_calls_inlining_or_self(ctx, self_name, body)
fn arg_resolves_runtime(probe: &mut SymbolTable, arg: &Expr) -> bool {
probe_value(probe, arg).is_ok_and(|value| value.is_wasm_runtime())
/// Same disposable-clone, sequential-visibility probing as
/// [`needs_runtime_call`] — a SEPARATE clone of the (still unmodified) live
/// table, since this runs only once `needs_runtime_call` already decided a
/// runtime call is needed and its own probe was already discarded.
fn infer_arg_types(symbols: &SymbolTable, args: &[Expr]) -> Result<Vec<WasmType>> {
args.iter()
.map(|arg| infer_arg_type(&mut probe, arg))
.collect()
/// The interned source of each capture-free closure argument.
fn arg_closure_sources(
) -> Result<Vec<Option<u32>>> {
.map(|arg| {
let resolved = probe_value(&mut probe, arg)?;
let source = resolved
.place()
.and_then(|(place, _)| probe.closure_body(place))
.cloned();
source
.map(|(params, body)| ctx.monomorph_cache_mut().intern_source(params, body))
.transpose()
})
fn infer_arg_type(probe: &mut SymbolTable, arg: &Expr) -> Result<WasmType> {
let resolved = probe_typed(probe, arg)?;
// The monomorph parameter slot type is exactly the stack type the arg
// lowers to — the shared classifier keeps the signature, the eval-path
// recursive-call placeholder, and `compile_for_stack` in agreement.
crate::compiler::expr::classify_stack_type(&resolved).ok_or_else(|| {
Error::Compile(format!(
"runtime-call lowering can't classify argument type for {resolved:?}; \
rewrite the call so each argument is a numeric or runtime value"
))
fn emit_runtime_call(
arg_types: &[WasmType],
entry: &MonomorphEntry,
) -> Result<()> {
for (arg, &expected) in args.iter().zip(arg_types.iter()) {
let actual = compile_for_stack(ctx, emit, symbols, arg)?;
if expected == WasmType::AnyRef {
emit_box_anyref(ctx, emit, actual);
} else if actual != expected {
return Err(Error::Compile(format!(
"runtime-call argument type mismatch: expected {expected:?}, got {actual:?}"
)));
for slot in &entry.slots {
push_slot(ctx, emit, symbols, slot)?;
emit.call(entry.func_idx);
Ok(())
/// A cell slot passes the cell itself, so the helper and its caller share
/// every store; a plain slot passes the current value.
fn push_slot(
slot: &Slot,
let Some(Expr::WasmLocal(idx, _)) = symbols.lookup(&slot.name).and_then(Symbol::value) else {
"{}: a runtime-call slot is not bound to a local at the call site",
slot.name
};
match (slot.cell, ctx.cell_of(*idx)) {
(true, None) => Err(Error::Compile(format!(
"{}: a runtime-call slot expected a shared cell",
))),
(true, Some(_)) => {
emit.local_get(*idx);
(false, _) => {
emit_local_read(ctx, emit, *idx);
fn body_calls_inlining_or_self(ctx: &CompileContext, self_name: &str, expr: &Expr) -> bool {
match expr {
Expr::List(elems) => {
if let Some(Expr::Symbol(name)) = elems.first()
&& (name == self_name || ctx.is_inlining(name))
{
return true;
elems
.iter()
.any(|e| body_calls_inlining_or_self(ctx, self_name, e))
Expr::Quasiquote(template) => template
.unquoted_forms()
.into_iter()
.any(|form| body_calls_inlining_or_self(ctx, self_name, form)),
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
body_calls_inlining_or_self(ctx, self_name, inner)
Expr::Cons(car, cdr) => {
body_calls_inlining_or_self(ctx, self_name, car)
|| body_calls_inlining_or_self(ctx, self_name, cdr)
Expr::Lambda(_, body) => body_calls_inlining_or_self(ctx, self_name, body),
_ => false,
#[cfg(test)]
#[path = "call_runtime_tests.rs"]
mod tests;