Lines
100 %
Functions
Branches
//! Codegen for the runtime path of `DO` / `DO*`.
//!
//! `compile_do_runtime_loop` emits the actual wasm `block / loop / br_if`
//! prelude + body + step sequence; the three wrapper functions
//! (`compile_do_runtime` / `_for_effect` / `_for_stack`) differ only
//! in how they consume the result-forms after the loop exits — value
//! position, effect-only, or push-to-stack respectively.
//! Both `DO` and `DO*` parallel/sequential semantics are encoded as
//! `DoLoop.sequential`. The step assignment block here is the only
//! place that distinction surfaces in the runtime codegen.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_body, compile_for_effect, compile_for_stack, compile_nil, probe_value, store_begin,
store_end,
};
use crate::error::Result;
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
use super::super::binding::bind_var_home;
use super::super::binding::shared::needs_cell_stepped;
use super::super::compile_store_value;
use super::super::setf_scan::collect_setf_targets;
use super::common::{DoLoop, promote_to_wasm_local};
use super::sizing::{infer_compiled_type, var_type_hint};
/// What variable `at` of a DO sees: every step, the end test, the result forms
/// and the body, and for DO* the initializers of the variables after it.
pub(super) fn loop_scope<'a>(dl: &DoLoop<'a>, at: usize) -> Vec<&'a Expr> {
let vars = dl.vars;
let later_inits = vars[at + 1..]
.iter()
.filter(|_| dl.sequential)
.filter_map(|v| v.init.as_ref());
later_inits
.chain(vars.iter().filter_map(|v| v.step.as_ref()))
.chain(std::iter::once(dl.end_test))
.chain(dl.result_forms)
.chain(dl.body)
.collect()
}
/// Computes every step before any variable changes; a celled variable's value
/// waits in a temp because its cell ref must sit below it for the store.
fn compile_parallel_steps(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
local: &mut SymbolTable,
wasm_vars: &[(Expr, u32, WasmType, Option<Expr>)],
) -> Result<()> {
let mut plain = Vec::new();
let mut celled = Vec::new();
for (place, idx, ty, step) in wasm_vars {
let Some(step_expr) = step else { continue };
compile_store_value(ctx, emit, local, place, step_expr, *ty)?;
if ctx.cell_of(*idx).is_some() {
let temp = ctx.alloc_local(*ty)?;
emit.local_set(temp);
celled.push((*idx, temp));
} else {
plain.push(*idx);
for idx in plain.into_iter().rev() {
emit.local_set(idx);
for (idx, temp) in celled {
store_begin(ctx, emit, idx);
emit.local_get(temp);
store_end(ctx, emit, idx, false);
Ok(())
/// Allocates the local of variable `at`, typed by its home: the join of its
/// init and the hint the refused stores of the previous attempt left.
fn bind_do_var(
(local, peek): (&mut SymbolTable, &mut SymbolTable),
dl: &DoLoop<'_>,
at: usize,
) -> Result<(Symbol, u32, WasmType)> {
let v = &dl.vars[at];
let shared = needs_cell_stepped(local, &v.name, v.step.is_some(), loop_scope(dl, at))?;
let init_expr = v.init.clone().unwrap_or(Expr::Nil);
// Probe on a CLONE: the value only sizes the local and detects a nil init;
// the live emission below is the single application of any seed side effects.
let init_val = probe_value(&mut local.clone(), &init_expr)?;
let key = dl.keys.get(at).and_then(Option::as_ref);
let (idx, ty) = bind_var_home(
ctx,
emit,
local,
key,
(Some(&init_expr), &init_val),
shared,
|ctx, emit, _| {
let step_hint = var_type_hint(v.step.as_ref(), dl.body, &v.name);
peek.define(Symbol::new(&v.name, SymbolKind::Variable).with_value(Expr::Nil));
infer_compiled_type(ctx, emit, peek, &init_val, step_hint).map(Some)
},
)?;
let var = Symbol::new(&v.name, SymbolKind::Variable)
.with_value(Expr::WasmLocal(idx, ty))
.with_home(key.cloned());
Ok((var, idx, ty))
fn compile_do_runtime_loop(
// The DO-vars are declared before the setf targets are promoted, so a
// CONS step can resolve them.
let mut wasm_vars: Vec<(Expr, u32, WasmType, Option<Expr>)> = Vec::new();
// A parallel DO's inits all see the outer scope; `peek` still lets a step
// that mentions an earlier variable type its accumulator.
let mut peek = local.clone();
let mut declared = Vec::new();
for (at, v) in dl.vars.iter().enumerate() {
let (var, idx, ty) = bind_do_var(ctx, emit, (local, &mut peek), dl, at)?;
peek.define(var.clone());
if dl.sequential {
local.define(var);
declared.push(var);
wasm_vars.push((Expr::Symbol(v.name.clone()), idx, ty, v.step.clone()));
for var in declared {
let do_var_names: Vec<_> = dl.vars.iter().map(|v| v.name.clone()).collect();
for (target, rhs) in collect_setf_targets(dl.body) {
if !do_var_names.contains(&target) {
promote_to_wasm_local(ctx, emit, local, &target, rhs.as_ref())?;
// block $exit
emit.block_start();
// loop $continue
emit.loop_start();
if compile_for_stack(ctx, emit, local, dl.end_test)? == crate::ast::WasmType::I32 {
// An index end-test is a count, never nil: the loop ends at once.
emit.drop_value();
emit.i32_const(1);
emit.br_if(1);
local.enter_skippable()?;
let compiled = dl
.body
.try_for_each(|expr| compile_for_effect(ctx, emit, local, expr));
local.exit_skippable()?;
compiled?;
for (place, idx, ty, step) in &wasm_vars {
if let Some(step_expr) = step {
store_begin(ctx, emit, *idx);
store_end(ctx, emit, *idx, false);
compile_parallel_steps(ctx, emit, local, &wasm_vars)?;
emit.br(0);
emit.block_end()?; // end loop
emit.block_end()?; // end block
pub(super) fn compile_do_runtime(
symbols: &mut SymbolTable,
let mut local = symbols.clone();
compile_do_runtime_loop(ctx, emit, &mut local, dl)?;
if dl.result_forms.is_empty() {
compile_nil(ctx, emit)?;
compile_body(ctx, emit, &mut local, dl.result_forms)?;
pub(super) fn compile_do_runtime_for_effect(
for expr in dl.result_forms {
compile_for_effect(ctx, emit, &mut local, expr)?;
pub(super) fn compile_do_runtime_for_stack(
) -> Result<WasmType> {
let Some((last, effects)) = dl.result_forms.split_last() else {
// No result forms ≡ nil — falsy i31, typed `Bool` so it serializes as
// Nil and agrees with the eval mirror's `Expr::Nil`.
emit.i32_const(0);
return Ok(WasmType::Bool);
for expr in effects {
compile_for_stack(ctx, emit, &mut local, last)