Lines
97.45 %
Functions
100 %
Branches
//! `AND` / `OR` short-circuit forms (ADR-0033: they return VALUES, as in
//! Common Lisp, not booleans). Both walk their operands in a plain loop
//! (never recursing to fold a constant-only prefix — a naive recursive
//! rewrite would exhaust the native stack on a long flat chain, e.g. `(and
//! nil t t t ...)` with thousands of operands) and delegate to `if_form` /
//! `compile_expr` for the one genuinely-runtime `IF` a non-constant operand
//! needs, so test lowering (`nil_repr`), arm reconciliation and boxing have
//! exactly one implementation, shared with `IF` itself.
//!
//! `AND` needs no temporary: once an operand is known non-nil its own value
//! is never needed again (the result comes from the rest of the chain), so
//! a runtime operand parks in a throwaway local purely to give `if_form` a
//! side-effect-free test to re-read. `OR` needs a live operand's value in
//! both the test and the result position (`(or a b)` is "if a is non-nil,
//! a; else b"), so its runtime chain stores the operand in a wasm local and
//! embeds `Expr::WasmLocal` (the compiled case) or `Expr::WasmRuntime` (the
//! eval-mirror's type-only placeholder) directly into a synthetic IF —
//! referencing the already-computed value instead of re-evaluating it.
//! A chain's constant prefix (however long) costs no native-stack
//! recursion at all — it's a plain `for` loop. Only a genuinely-runtime
//! operand recurses (once per such operand, through `if_form`'s own
//! "then"/"else"-branch re-entry into `and_form`/`or_form`), and that
//! recursion is depth-guarded (`SymbolTable::enter_runtime_guard`, charged
//! against `MAX_SHARED_RECURSION_DEPTH`) into a structured `Error::Resource`
//! rather than a native stack overflow.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
classify_stack_type, compile_for_effect, compile_for_stack, eval_value, probe_value,
serialize_stack_to_output,
};
use crate::error::Result;
use crate::runtime::SymbolTable;
use super::if_form;
/// `(AND rest...)` / `(OR rest...)` as a plain call AST node — built fresh
/// (not pre-evaluated) so recursing into `and_form`/`or_form` or their
/// stack compilers evaluates each of `rest` exactly once, lazily, exactly
/// like any other nested call.
fn chain_expr(head: &str, rest: &[Expr]) -> Expr {
let mut items = Vec::with_capacity(rest.len() + 1);
items.push(Expr::Symbol(head.to_string()));
items.extend_from_slice(rest);
Expr::List(items)
}
pub(super) fn compile_and(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
let ty = compile_and_for_stack(ctx, emit, symbols, args)?;
serialize_stack_to_output(ctx, emit, ty)
/// Walks `args` left to right in a plain loop: a compile-time-constant nil
/// operand ends the chain immediately (CL semantics — nothing after it,
/// including its own further operands, ever runs); a non-nil constant just
/// applies its effects and moves on; the first genuinely-runtime operand
/// parks in a throwaway local and hands the rest of the chain to `if_form`
/// as `(if <local> (and rest...) nil)`. The constant walk never recurses;
/// only the one runtime hand-off does, depth-guarded.
pub(super) fn compile_and_for_stack(
) -> Result<WasmType> {
let Some((last, init)) = args.split_last() else {
return compile_for_stack(ctx, emit, symbols, &Expr::T);
for (idx, operand) in init.iter().enumerate() {
let probe = probe_value(&mut symbols.clone(), operand)?;
if probe.is_wasm_runtime() {
if !super::is_runtime_test(&probe) {
// A `Never`-repr runtime value (index / money / closure) can
// never be nil — it folds true unconditionally, so it is
// NOT a genuine guard: `runtime_guard_depth` must not rise
// for it (a definition later in the chain would be reached
// unconditionally, not under any runtime branch).
compile_for_effect(ctx, emit, symbols, operand)?;
continue;
let ty = compile_for_stack(ctx, emit, symbols, operand)?;
let local = ctx.alloc_local(ty)?;
emit.local_set(local);
let test = Expr::WasmLocal(local, ty);
let rest = chain_expr("AND", &args[idx + 1..]);
symbols.enter_runtime_guard()?;
let result =
if_form::compile_if_for_stack(ctx, emit, symbols, &[test, rest, Expr::Nil]);
symbols.exit_runtime_guard()?;
return result;
if probe.is_nil() {
if !matches!(operand, Expr::Nil) {
emit.i32_const(0);
return Ok(WasmType::Bool);
compile_for_stack(ctx, emit, symbols, last)
/// Effect-position `AND`: unlike [`compile_and_for_stack`], a definition
/// form (`DEFVAR`/`DEFPARAMETER`/`DEFUN`, …) has no stack lowering at all,
/// so this does NOT route every operand through `compile_for_stack` — only
/// a genuinely-runtime operand whose TRUTHINESS controls whether later
/// operands run needs a stack value (parked in a local, tested, and the
/// rest of the chain nested inside the `if`'s true arm); every other
/// operand, including the last, compiles for effect only. Same left-to-right
/// walk and constant short-circuit as the stack path, same depth guard for
/// the one recursive runtime hand-off.
pub(super) fn compile_and_for_effect(
return Ok(());
// never be nil — it folds true unconditionally, so it never
// gates the rest of the chain; compile it for effect only.
// `compile_test_condition` already compiles `operand` for its
// value exactly once and converts the emitted type to a
// condition — no need to separately park it in a local, wrap
// that in a `WasmLocal`, and reload it through a SECOND
// `compile_test_condition` call. Still runs BEFORE
// `enter_runtime_guard` below, so the test's own unconditional
// effects are never wrongly treated as guarded.
super::compile_test_condition(ctx, emit, symbols, operand)?;
emit.if_block(wasm_encoder::BlockType::Empty);
// `enter_runtime_guard` also marks (via `runtime_guard_depth`) that
// anything compiled here — however deeply nested through
// IF/COND/LET/PROGN/macro expansion — is under a GENUINELY
// RUNTIME guard: a definition form reached from here refuses
// itself at its own registration site (see
// `SymbolTable::is_under_any_runtime_guard`), rather than a
// syntactic pre-scan of this suffix (which can't see through
// macros/nesting and can't tell a reachable definition from one
// a constant operand earlier in THIS SAME suffix would already
// short-circuit past).
let result = compile_and_for_effect(ctx, emit, symbols, &args[idx + 1..]);
result?;
emit.block_end()?;
compile_for_effect(ctx, emit, symbols, last)
/// Eval-mirror of [`compile_and_for_stack`]: same left-to-right loop, same
/// early exit on a constant nil, same depth-guarded single recursion for
/// the first genuinely-runtime operand.
pub(super) fn and_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
return Ok(Expr::T);
let value = eval_value(symbols, operand)?;
if value.is_wasm_runtime() && super::is_runtime_test(&value) {
let placeholder =
Expr::WasmRuntime(classify_stack_type(&value).unwrap_or(WasmType::I32));
let result = if_form::if_form(symbols, &[placeholder, rest, Expr::Nil]);
if value.is_nil() {
return Ok(Expr::Nil);
// Never-nil runtime value (or an ordinary non-nil constant): its
// own effects already applied above via `eval_value`; not a
// genuine guard, so `runtime_guard_depth` must not rise for it — move on.
eval_value(symbols, last)
pub(super) fn compile_or(
let ty = compile_or_for_stack(ctx, emit, symbols, args)?;
/// Same left-to-right, non-recursive walk as [`compile_and_for_stack`]: a
/// non-nil constant IS the result (no runtime park, no widening through a
/// synthetic IF); a constant `nil` contributes only its own compile-time
/// effects (if it isn't the literal `nil` itself) before OR moves on. Only
/// the first genuinely-runtime operand parks in a (reusable) local and
/// hands the rest of the chain to `if_form` as `(if <local> <local> (or
/// rest...))`.
pub(super) fn compile_or_for_stack(
// `(or)` is nil — falsy i31, typed `Bool` to match the eval mirror.
// Never-nil: this operand IS the OR's result (matching the
// truthy-constant arm below) — not a genuine guard, so
// `runtime_guard_depth` must not rise for it.
return compile_for_stack(ctx, emit, symbols, operand);
// The already-computed value stands in for both the test and the
// true-branch result of `(if operand operand (or rest...))` — a
// `local.get` re-read, never a re-evaluation of `operand`.
let held = Expr::WasmLocal(local, ty);
let rest = chain_expr("OR", &args[idx + 1..]);
let synthetic = [held.clone(), held, rest];
let result = if_form::compile_if_for_stack(ctx, emit, symbols, &synthetic);
if !probe.is_nil() {
/// Effect-position `OR`: mirrors [`compile_and_for_effect`] — only a
/// genuinely-runtime operand whose TRUTHINESS decides whether the rest of
/// the chain runs needs a stack value; every other operand, including the
/// last, compiles for effect only. A truthy runtime operand IS the OR's
/// (discarded) result, so the rest of the chain lives in the `if`'s ELSE
/// arm rather than its THEN arm (the reverse of AND's placement).
pub(super) fn compile_or_for_effect(
// Never-nil: this operand IS the OR's result — nothing after
// it ever runs.
// See the matching comment in `compile_and_for_effect`: a
// single `compile_test_condition` call replaces the
// park-in-a-local-then-reload sequence, compiling `operand`
// exactly once, still before `enter_runtime_guard` below.
emit.else_block();
let result = compile_or_for_effect(ctx, emit, symbols, &args[idx + 1..]);
// Constant non-nil: this operand IS the OR's result — its
// effects run, and nothing after it does.
/// Eval-mirror of [`compile_or_for_stack`]: same left-to-right loop, same
/// constant-value short-circuit, same depth-guarded single recursion for
pub(super) fn or_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
// Mirror `compile_or_for_stack`'s synthetic IF with a type-only
// placeholder (the eval mirror has no real wasm local to reuse) —
// `if_form` reconciles it against the rest exactly as codegen will.
let result = if_form::if_form(symbols, &[placeholder.clone(), placeholder, rest]);
if !value.is_nil() {
// Never-nil runtime value, or an ordinary non-nil constant: IS
// the OR's result — not a genuine guard.
return Ok(value);