Lines
94.47 %
Functions
92.86 %
Branches
100 %
//! Effect-position codegen.
//!
//! `compile_for_effect` is the entry point — it inspects the leading
//! form and either dispatches into the specialised SETF / IF / PROGN
//! handlers below, hands off to a special form's effect path, or
//! falls back to value-position emit when the form has a runtime
//! result that must be consumed.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::error::{Error, Result};
use crate::runtime::{Head, SymbolTable, with_sufficient_stack};
use super::call::applying_lambda;
use super::call_runtime::try_compile_runtime_call;
use super::eval::{call, eval_value, expand_macro_then};
use super::fold::probe_value;
use super::lambda_params::compile_and_bind_lambda_params;
use super::local_cell::{store_begin_place, store_end_place};
use super::quasiquote::quasiquote_form;
use super::stack::compile_for_stack;
use crate::compiler::special::{compound_setf_call, promoted_place};
#[inline(never)]
fn compile_quasiquote_for_effect(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
template: &Expr,
) -> Result<()> {
compile_for_effect(ctx, emit, symbols, &quasiquote_form(template)?)
}
pub(in crate::compiler) fn compile_for_effect(
expr: &Expr,
with_sufficient_stack(|| {
symbols.charge_work(1)?;
if let Expr::Quasiquote(template) = expr {
return compile_quasiquote_for_effect(ctx, emit, symbols, template);
if try_compile_inline_lambda_call_for_effect(ctx, emit, symbols, expr)? {
return Ok(());
if let Expr::List(elems) = expr
&& let Some(Expr::Symbol(name)) = elems.first()
{
let args = &elems[1..];
let head = symbols.resolve_head(name);
let builtin = head.is_builtin();
// Expand macros (e.g. WHEN → IF) and recurse
if let Head::Macro(params, body) = head {
let (params, body) = (params.clone(), body.clone());
return expand_macro_then(symbols, ¶ms, &body, args, |symbols, code| {
compile_for_effect(ctx, emit, symbols, &code)
});
if builtin {
if try_compile_builtin_for_effect(ctx, emit, symbols, name, args)? {
} else if try_compile_defun_call_for_effect(ctx, emit, symbols, expr, name, args)? {
// A value-producing native / host-fn call (LIST, CONS, +, an accessor,
// …) whose result is discarded in effect position: COMPILE it and drop
// the value, so effects in its ARGUMENTS (a nested `setf`, a promoted
// accumulator update, …) actually emit. `eval_value` alone const-folds
// without emitting — that silently dropped those arg effects. Non-value
// special forms (LAMBDA, FUNCTION) are NOT compilable for stack and
// stay on the eval path below.
if !(builtin && crate::compiler::special::is_special_form(name)) {
return compile_value_producing_call_for_effect(
ctx, emit, symbols, expr, name, args,
);
// A bare atom, or a non-value special form, in effect position: const-fold
// it (no stack value to emit).
eval_value(symbols, expr)?;
Ok(())
})
/// The effect path of a name that still resolves to the compiler's own
/// builtin; `Ok(false)` leaves the form to the caller's tail.
fn try_compile_builtin_for_effect(
name: &str,
args: &[Expr],
) -> Result<bool> {
match name {
"DEBUG" => crate::compiler::native::compile_debug_effect(ctx, emit, symbols, args)?,
"PRINT" => crate::compiler::native::compile_print_effect(ctx, emit, symbols, args)?,
"DISPLAY" => crate::compiler::native::compile_display_effect(ctx, emit, symbols, args)?,
"NEWLINE" => crate::compiler::native::compile_newline_effect(ctx, emit, symbols, args)?,
"SETF" => compile_setf_for_effect(ctx, emit, symbols, args)?,
"CREATE-TAG" | "DELETE-ENTITY" => {
crate::compiler::native::compile(ctx, emit, symbols, name, args)?;
"IF" => compile_if_for_effect(ctx, emit, symbols, args)?,
"PROGN" => compile_progn_for_effect(ctx, emit, symbols, args)?,
// `eval_value` does not model side effects (`create-tag`, `debug`,
// host fns, a `(return-from …)`'s `br`), so a special form routed
// there would drop its wasm; derived from the registry, not a list.
_ if crate::compiler::special::is_special_form(name)
&& !crate::compiler::special::is_eval_only_special_form(name) =>
crate::compiler::special::compile_for_effect(ctx, emit, symbols, name, args)?;
_ => return Ok(false),
Ok(true)
/// The generic `(name args...)` call once no special-cased name / macro /
/// special form matched, and `name` resolves to a user-defined `DEFUN`
/// whose call classifies as genuinely RUNTIME: `Ok(true)` means fully
/// emitted (inlined or routed to the monomorph helper); `Ok(false)` means
/// `name` isn't such a call (not a lambda at all, or one that folds to a
/// compile-time constant) and the caller's own tail handles it.
fn try_compile_defun_call_for_effect(
let (params, body) = match symbols.resolve_head(name) {
Head::Function(params, body) => (params.clone(), body.clone()),
};
// Classify on a DISPOSABLE clone — this decides which codegen path to
// take, so it must not itself apply the call's compile-time effects (a
// nested `setf`, a host-fn call in an argument, …) to the live table.
// The runtime branch below applies them exactly once, in codegen; the
// non-runtime fallthrough (the caller's tail, once this returns
// `Ok(false)`) applies them exactly once via `compile_for_stack`.
let val = probe_value(&mut symbols.clone(), expr)?;
if !val.is_wasm_runtime() {
return Ok(false);
// A recursive runtime-arg call routes to the monomorph helper (its
// result is computed then dropped here); otherwise inline the body,
// depth-guarded so a non-terminating recursion is a structured error,
// not a native compiler-stack overflow — same contract as the
// value/stack call paths.
if try_compile_runtime_call(ctx, emit, symbols, name, ¶ms, &body, args)?.is_some() {
emit.drop_value();
return Ok(true);
let Some(mut local) =
compile_and_bind_lambda_params(ctx, emit, symbols, ¶ms, &body, args, Some(name))?
else {
ctx.push_inlining_frame(symbols, name)?;
let defined_at = super::call::definition_depth(symbols, name);
let result = ctx.with_hidden_labels(defined_at, |ctx| {
compile_for_effect(ctx, emit, &mut local, &body)
ctx.pop_inlining_frame(symbols, name)?;
result?;
/// A value-producing native / host-fn call (LIST, CONS, +, an accessor, …)
/// whose result is discarded in effect position: COMPILE it and drop the
/// value, so effects in its ARGUMENTS (a nested `setf`, a promoted
/// accumulator update, …) actually emit. `eval_value` alone const-folds
/// without emitting — that would silently drop those arg effects.
fn compile_value_producing_call_for_effect(
// A host fn — including a VOID one (`result: None`, e.g. `rpc-log`) —
// routes through its effect compiler, which emits the import call and
// drops any result. `compile_for_stack` would reject a void host fn
// ("no return type"). A non-host value-producing native is compiled and
// dropped.
if symbols.resolve_head(name).is_builtin() && ctx.lookup_host_fn(name).is_some() {
return crate::compiler::native::compile_host_fn_for_effect(ctx, emit, symbols, name, args);
compile_for_stack(ctx, emit, symbols, expr)?;
fn compile_progn_for_effect(
for arg in args {
compile_for_effect(ctx, emit, symbols, arg)?;
/// Compiles an inline lambda call `((lambda (params) body) args...)` — a
/// non-symbol head, since the reader parses `(lambda …)` as an `Expr::List`
/// that resolves to `Expr::Lambda` only once evaluated, mirroring
/// `compile_call_for_stack`'s own two arms — for effect, inlining its body
/// into the SAME emitter (mirroring `compile_lambda_call_for_stack`).
/// Returns `false` (nothing compiled) for anything else, incl. a `List`
/// callee that resolves to something other than a lambda: without this,
/// the generic symbol-headed dispatch in `compile_for_effect` falls
/// through to the eval-only interpreter fallback at the bottom of this
/// module, which never emits wasm at all, silently dropping the body's
/// effects (including any `(return-from …)` the body contains, which
/// needs a real `br` to an enclosing `BLOCK`, not a symbolic eval
/// placeholder).
fn try_compile_inline_lambda_call_for_effect(
let Expr::List(elems) = expr else {
let Some(head) = elems.first() else {
if matches!(head, Expr::Symbol(_)) {
let resolved = match head {
Expr::Lambda(_, _) => Some(head.clone()),
Expr::List(inner) => match call(symbols, inner)? {
lambda @ Expr::Lambda(_, _) => Some(lambda),
_ => None,
},
let Some(Expr::Lambda(params, body)) = resolved else {
applying_lambda(symbols, head, |symbols| {
compile_and_bind_lambda_params(ctx, emit, symbols, ¶ms, &body, &elems[1..], None)?
})?;
fn compile_if_for_effect(
if args.len() < 2 || args.len() > 3 {
return Err(Error::Compile(
"IF requires a test, a then-form, and an optional else-form".to_string(),
));
// Classify on a CLONE — the test's compile-time effects reach the live
// table only via the single emit below.
let test = probe_value(&mut symbols.clone(), &args[0])?;
let test_diverges = crate::compiler::special::form_diverges_scratch(symbols, &args[0])?;
if test_diverges {
// The test transfers control before producing a condition; compile it
// for effect so the exit fires. Both branches are dead.
return compile_for_effect(ctx, emit, symbols, &args[0]);
if crate::compiler::special::is_runtime_test(&test) {
crate::compiler::special::compile_test_condition(ctx, emit, symbols, &args[0])?;
emit.if_block(wasm_encoder::BlockType::Empty);
crate::compiler::special::in_runtime_branch(symbols, |symbols| {
compile_for_effect(ctx, emit, symbols, &args[1])?;
if let Some(else_form) = args.get(2) {
emit.else_block();
compile_for_effect(ctx, emit, symbols, else_form)?;
emit.block_end()?;
let test = crate::compiler::special::apply_const_test(ctx, emit, symbols, &args[0], &test)?;
if !test.is_nil() {
compile_for_effect(ctx, emit, symbols, &args[1])
} else if args.len() == 3 {
compile_for_effect(ctx, emit, symbols, &args[2])
} else {
fn compile_setf_for_effect(
if !args.len().is_multiple_of(2) {
"SETF requires an even number of arguments".to_string(),
let args = &crate::compiler::special::expand_macro_places(symbols, args)?;
for pair in args.chunks(2) {
let place = &pair[0];
let value_expr = &pair[1];
if let Some(call) = compound_setf_call(symbols, place, value_expr)? {
compile_for_effect(ctx, emit, symbols, &call)?;
continue;
if let Some((target, ty)) = promoted_place(symbols, place) {
// A diverging rhs (`(return-from …)`, `(error …)`) never
// produces a value the local actually receives — control
// transfers away first, so its nominal type (always `AnyRef`
// for a `return-from`, boxed for its own enclosing BLOCK)
// must not be coerced against the local's declared type.
// Compile it for effect so the exit fires; the store below
// is dead code, same treatment IF/COND give a diverging test.
if crate::compiler::special::form_diverges_scratch(symbols, value_expr)? {
compile_for_effect(ctx, emit, symbols, value_expr)?;
// Coerce the rhs to the local's declared type (literal Index↔Scalar
// crossing, nil → typed default); a real clash is a clean compile
// error, not an invalid `local.set`.
store_begin_place(ctx, emit, target);
crate::compiler::special::compile_store_value(
ctx, emit, symbols, place, value_expr, ty,
)?;
// Reassigning a closure local invalidates the body recorded for it
// at bind time — the local now holds a different closure, so a later
// FOLD inlining the stale body would call the wrong fn. Forget AFTER
// compiling the rhs (which may legitimately FOLD the OLD closure)
// and before the store.
if matches!(ty, WasmType::Closure(_)) {
symbols.forget_closure_body(target);
store_end_place(ctx, emit, target, false);
crate::compiler::special::mark_cell_store(emit, symbols, place, target);
// const place, no PRE-EXISTING runtime storage of its
// own — unsafe under a runtime guard (see
// `reject_compile_time_setf_under_runtime_guard`).
crate::compiler::special::reject_compile_time_setf_under_runtime_guard(symbols)?;
crate::compiler::special::reject_uncarried_global_store(symbols, place)?;
let value = crate::compiler::special::compile_const_place_setf_rhs(
ctx, emit, symbols, place, value_expr,
crate::compiler::special::setf_set_place(symbols, place, value)?;