Lines
86.43 %
Functions
75 %
Branches
100 %
//! Tier 1.5 monomorph emit — closes Gap B.
//!
//! When a defun is called with a runtime arg the inline const-fold path
//! has no terminating walk (each step re-enters the body without
//! reducing toward a base case). The runtime-call path emits the body
//! once as a real wasm fn keyed on the call-site argument signature
//! and lowers each call site to `call $monomorph_idx`. The recursion
//! itself terminates at runtime via the same mechanism every wasm fn
//! uses — the wasm call stack — so the compile-time walk no longer has
//! to.
//! Cache: [`super::super::context::monomorph::MonomorphCache`] is
//! keyed by `(defun_name, [arg_wasm_types])`. Distinct call-site
//! signatures emit distinct wasm fns; identical ones share.
//! Type inference: we don't have a declared return type at the call
//! site. The body's return type is determined by emitting the body —
//! but the body may self-call, and that self-call needs a concrete
//! return type up front. Each guess is one [`recompile`] pass:
//! 1. Intern the guess — the first non-closure param's type (or `Ratio` for
//! nullary recursion), then the previous pass's observation.
//! 2. Register the function with the guessed return type and emit the body
//! with `compile_for_stack`. Self-calls inside the body resolve through
//! the cache entry registered with it and emit `call $self_idx`.
//! 3. If the observed return type matches the guess, queue the helper
//! and commit.
//! 4. Otherwise discard the pass, keeping only the observed type in its
//! structural form: a closure signature interned by the discarded pass
//! does not survive the rollback. Hard cap at 4 passes — anything that
//! doesn't converge is a structured `Error::Compile`.
use super::captures::compute_captures;
use crate::ast::{Expr, LambdaParams, Place, WasmType};
use crate::compiler::binder_key::function_owner;
use crate::compiler::context::CompileContext;
use crate::compiler::context::closure::cell_ref;
use crate::compiler::context::monomorph::{MonomorphEntry, MonomorphKey, Slot};
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{compile_for_stack, recursive_ret_guess};
use crate::compiler::observations::{Observations, StructuralType};
use crate::compiler::recompile::Trial;
use crate::compiler::recompile::recompile;
use crate::error::{Error, Result};
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
use wasm_encoder::ValType;
const FIXPOINT_ITER_CAP: usize = 4;
/// Lookup-or-emit pipeline. Returns the cache entry the caller emits
/// `call <entry.func_idx>` against. Body is the defun's `Expr::Lambda`
/// body; `params` is the defun's parameter list; `arg_types` is the
/// call-site argument signature (one wasm type per required param).
pub(in crate::compiler) fn lookup_or_emit_monomorph(
ctx: &mut CompileContext,
symbols: &mut SymbolTable,
name: &str,
params: &LambdaParams,
body: &Expr,
arg_types: &[WasmType],
closures: Vec<Option<u32>>,
) -> Result<MonomorphEntry> {
if !is_v1_signature(params) {
return Err(Error::Compile(format!(
"runtime-call lowering for '{name}' requires required-only \
parameters; lambdas with &optional/&rest/&key/&aux still go \
through the inline path"
)));
}
if params.required.len() != arg_types.len() {
return Err(Error::Arity {
name: name.to_string(),
expected: params.required.len(),
actual: arg_types.len(),
});
let key = MonomorphKey {
slots: free_slots(ctx, symbols, name, params, body)?,
definition: symbols.lookup(name).map_or(0, Symbol::function_definition),
epoch: symbols.redefinition_epoch(),
params: arg_types.to_vec(),
closures,
};
if let Some(entry) = ctx.monomorph_cache().get(&key) {
return Ok(entry.clone());
emit_monomorph(ctx, symbols, key, params, body, arg_types)
/// The runtime names `body` reads or assigns that the caller owns. A function
/// is emitted apart from its caller, so each travels as a parameter: by value
/// when only read, as the shared cell itself when the unit assigns it. A
/// by-value slot is sound only because nothing in the helper's dynamic extent
/// can store to it; a store to one is refused.
fn free_slots(
ctx: &CompileContext,
symbols: &SymbolTable,
) -> Result<Vec<Slot>> {
let mut view = symbols.clone();
view.hide_caller_lexicals(name)?;
let captures = compute_captures(&view, params, body)?;
let slots: Vec<Slot> = captures
.iter()
.filter_map(|free| match view.lookup(free).and_then(Symbol::value) {
Some(Expr::WasmLocal(idx, ty)) => Some(Slot {
name: free.to_string(),
ty: *ty,
cell: ctx.cell_of(*idx).is_some(),
}),
_ => None,
})
.collect();
let unshared_store = captures
.stored_captures()
.find(|stored| slots.iter().any(|slot| slot.name == *stored && !slot.cell));
match unshared_store {
Some(stored) => Err(Error::Compile(format!(
"{stored}: a function called with runtime arguments assigns a variable that is not \
a shared cell; not supported yet"
))),
None => Ok(slots),
fn is_v1_signature(params: &LambdaParams) -> bool {
params.optional.is_empty()
&& params.rest.is_none()
&& params.key.is_empty()
&& params.aux.is_empty()
fn initial_ret_guess(
) -> Result<StructuralType> {
let guess = recursive_ret_guess(
name,
¶ms.required,
body,
arg_types.iter().copied().map(Some),
);
StructuralType::of(guess, ctx)
fn emit_monomorph(
key: MonomorphKey,
let mut guess = initial_ret_guess(ctx, &key.name, params, body, arg_types)?;
let mut blocks = Vec::new();
for _ in 0..FIXPOINT_ITER_CAP {
let pass = ctx.closing_block_probe(|ctx| {
ctx.expecting_block_joins(blocks, |ctx| {
recompile(ctx, symbols, |ctx, symbols| {
monomorph_pass(ctx, symbols, &key, params, body, arg_types, &guess)
})?;
match pass {
Trial::Commit(entry) => return Ok(entry),
Trial::Discard(observed) => {
guess = observed.result;
blocks = observed.blocks;
Err(Error::Compile(format!(
"type inference for '{}' did not converge within {} iterations; \
the body's return type appears to depend on itself",
key.name, FIXPOINT_ITER_CAP
)))
fn monomorph_pass(
key: &MonomorphKey,
guess: &StructuralType,
) -> Result<Trial<MonomorphEntry, Observations>> {
let expected_ret = guess.intern(ctx)?;
let start = ctx.block_join_start();
match try_emit_body(ctx, symbols, key, params, body, arg_types, expected_ret)? {
Trial::Commit(observed) => {
ctx.monomorph_cache_mut()
.insert(key.clone(), observed.clone());
Ok(Trial::Commit(observed))
Trial::Discard(observed_ret) => Ok(Trial::Discard(Observations {
result: StructuralType::of(observed_ret, ctx)?,
blocks: ctx.take_block_joins(start),
})),
fn try_emit_body(
expected_ret: WasmType,
) -> Result<Trial<MonomorphEntry, WasmType>> {
let mut param_vts = arg_types
.map(|t| ctx.wasm_val_type(*t))
.collect::<Result<Vec<_>>>()?;
for slot in &key.slots {
param_vts.push(slot_val_type(ctx, slot)?);
let result_vt = ctx.wasm_val_type(expected_ret)?;
let helper_name = next_monomorph_helper_name(key, arg_types);
let func_idx = ctx.register_function(&helper_name, ¶m_vts, &[result_vt])?;
let slot = ctx.reserve_helper();
let entry = MonomorphEntry {
func_idx,
ret_ty: expected_ret,
slots: key.slots.clone(),
ctx.monomorph_cache_mut().insert(key.clone(), entry);
let arg_count = u32::try_from(arg_types.len())
.map_err(|_| Error::Compile("monomorph param count exceeds u32 range".to_string()))?;
let param_count = u32::try_from(param_vts.len())
let mut local_symbols = symbols.clone();
local_symbols.enter_function_body(function_owner(symbols, Some(&key.name), body));
local_symbols.hide_caller_lexicals(&key.name)?;
local_symbols.drop_runtime_locals();
for (idx, (param_name, ty)) in params.required.iter().zip(arg_types.iter()).enumerate() {
let local_idx = u32::try_from(idx)
.map_err(|_| Error::Compile("monomorph param index exceeds u32 range".to_string()))?;
local_symbols.define(
Symbol::new(param_name, SymbolKind::Variable)
.with_value(Expr::WasmLocal(local_idx, *ty)),
let snapshot = ctx.take_local_pool(param_count);
ctx.forget_outer_labels();
record_closure_params(ctx, &mut local_symbols, key);
let mut helper_emit = FunctionEmitter::new();
let prologue = bind_slots(
ctx,
&mut helper_emit,
symbols,
&mut local_symbols,
arg_count,
&key.slots,
if let Err(e) = prologue.and_then(|()| ctx.push_inlining_frame(&mut local_symbols, &key.name)) {
ctx.restore_local_pool(snapshot);
return Err(e);
let body_result = compile_for_stack(ctx, &mut helper_emit, &mut local_symbols, body);
ctx.pop_inlining_frame(&mut local_symbols, &key.name)?;
let observed_ret = match body_result {
Ok(ty) => ty,
Err(e) => {
let helper_locals = match ctx.build_helper_locals(param_count) {
Ok(locals) => locals,
let helper_fn = match helper_emit.finish(&helper_locals) {
Ok(helper_fn) => helper_fn,
if observed_ret != expected_ret {
return Ok(Trial::Discard(observed_ret));
ctx.fill_helper(slot, helper_fn)?;
Ok(Trial::Commit(MonomorphEntry {
ret_ty: observed_ret,
}))
fn record_closure_params(ctx: &CompileContext, symbols: &mut SymbolTable, key: &MonomorphKey) {
for (idx, id) in (0..).zip(&key.closures) {
let source = id.and_then(|id| ctx.monomorph_cache().source(id).cloned());
if let Some((params, body)) = source {
symbols.record_closure_body(Place::Local(idx), params, body);
fn slot_val_type(ctx: &mut CompileContext, slot: &Slot) -> Result<ValType> {
if slot.cell {
return Ok(cell_ref(ctx.intern_cell_type(slot.ty)?));
ctx.wasm_val_type(slot.ty)
/// Binds each slot's name to the helper's parameter after the arguments; a
/// cell slot is copied into a fresh cell local, which the pool owns.
fn bind_slots(
helper: &mut FunctionEmitter,
caller: &SymbolTable,
local_symbols: &mut SymbolTable,
arg_count: u32,
slots: &[Slot],
) -> Result<()> {
for (param, slot) in (arg_count..).zip(slots) {
let idx = if slot.cell {
let cell = ctx.alloc_cell_local(slot.ty)?;
helper.local_get(param);
helper.local_set(cell);
cell
} else {
param
let id = caller
.lookup(&slot.name)
.map_or(0, Symbol::value_definition);
Symbol::new(&slot.name, SymbolKind::Variable)
.with_value(Expr::WasmLocal(idx, slot.ty))
.with_definition(id),
Ok(())
fn next_monomorph_helper_name(key: &MonomorphKey, arg_types: &[WasmType]) -> String {
let mut name = format!("__defun_{}_d{}_e{}", key.name, key.definition, key.epoch);
for ty in arg_types {
name.push('_');
name.push_str(&format_wasm_type(*ty));
for id in key.closures.iter().flatten() {
name.push_str(&format!("_src{id}"));
let kind = if slot.cell { "cell" } else { "val" };
name.push_str(&format!(
"_{}_{kind}_{}",
slot.name,
format_wasm_type(slot.ty)
));
name
fn format_wasm_type(ty: WasmType) -> String {
match ty {
WasmType::Ratio => "ratio".to_string(),
WasmType::Commodity => "commodity".to_string(),
WasmType::I32 => "i32".to_string(),
WasmType::Bool => "bool".to_string(),
WasmType::StringRef => "string".to_string(),
WasmType::SymbolRef => "symbol".to_string(),
WasmType::PairRef(element) => format!("pair_{element:?}").to_lowercase(),
WasmType::EntityRef(kind) => format!("entity_{}", kind.type_name()),
WasmType::StructRef(id) => format!("struct{}", id.0),
WasmType::Closure(sig) => format!("closure{}", sig.0),
WasmType::AnyRef => "any".to_string(),
#[cfg(test)]
#[path = "monomorph_tests.rs"]
mod tests;