Lines
89.96 %
Functions
91.07 %
Branches
100 %
//! Shared types and helpers across the DO/DO*/DOLIST family.
//!
//! Three concerns live here:
//! - parsing the form's surface syntax (`parse_do_vars`,
//! `parse_end_clause`, `DoVar`, `DoLoop`);
//! - static-time termination + result-type inference
//! (`static_loop_iterations`, `infer_result_pair_element`);
//! - the codegen-side setf-target promotion shared by all three
//! constructs (`promote_to_wasm_local`).
//! Everything is `pub(super)` so the sibling `do_loop` and `dolist`
//! modules can use it; nothing escapes to the broader codebase.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::binder_key::{SiteKeys, Surface, binder_keys};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::format_form;
use crate::compiler::expr::{compile_for_stack, eval_value};
use crate::compiler::special::control::form_diverges_scratch;
use crate::error::{Error, Result};
use crate::reserved::reject_reserved;
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
use super::super::binding::reject_duplicate_names;
use super::super::setf_scan::{collect_setf_targets, step_pair_element};
use super::runtime::loop_scope;
use super::sizing::{infer_compiled_type, infer_wasm_type};
/// Per-binding spec parsed from the variable list of a DO/DO* form.
/// `(name init step)` — both `init` and `step` are optional in source
/// syntax; the runtime treats absent init as `nil` and absent step as
/// "leave the binding alone for this iteration."
pub(super) struct DoVar {
pub(super) name: String,
pub(super) init: Option<Expr>,
pub(super) step: Option<Expr>,
}
/// Owns the raw shape of a do-loop after the surface form has been
/// validated. Reused by both the runtime codegen entry points
/// (`compile_do_runtime{,_for_effect,_for_stack}`) and the iterators
/// inside each variant.
pub(super) struct DoLoop<'a> {
pub(super) vars: &'a [DoVar],
pub(super) end_test: &'a Expr,
pub(super) result_forms: &'a [Expr],
pub(super) body: &'a [Expr],
/// True for DO* (sequential steps), false for DO (parallel).
pub(super) sequential: bool,
/// The binder site of each variable a store can reach.
pub(super) keys: &'a [Option<HomeKey>],
/// The surface parts of a DO / DO* form.
pub(super) struct ParsedLoop<'a> {
pub(super) vars: Vec<DoVar>,
pub(super) keys: SiteKeys,
sequential: bool,
impl ParsedLoop<'_> {
pub(super) fn do_loop(&self) -> DoLoop<'_> {
DoLoop {
vars: &self.vars,
end_test: self.end_test,
result_forms: self.result_forms,
body: self.body,
sequential: self.sequential,
keys: &self.keys,
/// Parses a DO / DO* form and keys the binder site of each variable.
pub(super) fn parse_loop<'a>(
symbols: &SymbolTable,
surface: Surface,
head: &str,
args: &'a [Expr],
) -> Result<ParsedLoop<'a>> {
let [vars, end_clause, body @ ..] = args else {
return Err(Error::Compile(format!(
"{head} requires a variable list and an end clause"
)));
};
let vars = parse_do_vars(symbols, head, vars)?;
let (end_test, result_forms) = parse_end_clause(head, end_clause)?;
let mut parsed = ParsedLoop {
vars,
end_test,
result_forms,
body,
keys: Vec::new(),
sequential,
let dl = parsed.do_loop();
let keys = binder_keys(
symbols,
surface,
(head, args),
dl.vars
.iter()
.enumerate()
.map(|(at, var)| (var.name.as_str(), var.step.is_some(), loop_scope(&dl, at))),
);
parsed.keys = keys;
Ok(parsed)
pub(super) const MAX_STATIC_LOOP_ITERS: usize = 64;
pub(super) fn parse_do_vars(
context: &str,
expr: &Expr,
) -> Result<Vec<DoVar>> {
let list = expr.as_list().ok_or_else(|| {
Error::Compile(format!(
"{context}: expected variable list, got {}",
format_form(expr)
))
})?;
let vars: Vec<DoVar> = list
.map(|spec| match spec {
Expr::Symbol(name) => reject_reserved(symbols, name).map(|()| DoVar {
name: name.clone(),
init: None,
step: None,
}),
Expr::List(elems) if !elems.is_empty() && elems.len() <= 3 => {
let name = elems[0].as_symbol().ok_or_else(|| {
"{context}: variable name must be a symbol, got {}",
format_form(&elems[0])
reject_reserved(symbols, name)?;
Ok(DoVar {
name: name.to_string(),
init: elems.get(1).cloned(),
step: elems.get(2).cloned(),
})
_ => Err(Error::Compile(format!(
"{context}: malformed variable spec: {}",
format_form(spec)
))),
.collect::<Result<_>>()?;
reject_duplicate_names("variable", context, vars.iter().map(|var| &var.name))?;
Ok(vars)
pub(super) fn parse_end_clause<'a>(
expr: &'a Expr,
) -> Result<(&'a Expr, &'a [Expr])> {
let elems = expr.as_list().ok_or_else(|| {
"{context}: end clause must be a list, got {}",
if elems.is_empty() {
"{context}: end clause must have a test form"
Ok((&elems[0], &elems[1..]))
/// Whether a loop's steps are dead for the eval surface's BLOCK join: its
/// `body` always diverges, so codegen never reaches them. Classified only
/// while a BLOCK is open outside a macro body, which has no codegen to agree
/// with.
pub(super) fn steps_are_dead(symbols: &SymbolTable, body: &[Expr]) -> Result<bool> {
if symbols.is_dead_code() {
return Ok(true);
if !symbols.has_eval_block() || symbols.is_macro_expansion() {
return Ok(false);
for form in body {
if form_diverges_scratch(symbols, form)? {
Ok(false)
/// Looks for an accumulator `(cons V <result-name>)` that determines
/// the runtime `PairElement` of the do's result. Two patterns: body
/// `(setf acc (cons V acc))` and step `(acc nil (cons V acc))` (or
/// nested via if/cond). Without inspecting the step path, a do whose
/// accumulator lives in its var-step gets the placeholder I32, and
/// consumer dolists downcast to i31 — runtime cast trap.
pub(super) fn infer_result_pair_element(
result_form: &Expr,
body: &[Expr],
stepped: &[(String, Option<Expr>)],
) -> Option<PairElement> {
let Expr::Symbol(target) = result_form else {
return None;
let from_body = collect_setf_targets(body)
.into_iter()
.find_map(|(name, rhs)| {
(name == *target)
.then_some(rhs)
.flatten()
.as_ref()
.and_then(|r| step_pair_element(r, symbols))
});
if from_body.is_some() {
return from_body;
stepped.iter().find_map(|(name, step)| {
if name != target {
step.as_ref().and_then(|s| step_pair_element(s, symbols))
/// Eval-path mirror of [`promote_to_wasm_local`]: when a *runtime* loop body
/// `setf`s an OUTER variable, the loop's runtime iteration mutates it, but the
/// eval (const-fold) surface never runs that body, so the variable keeps its
/// stale const init. Mark each such target as a `WasmRuntime` placeholder of
/// its codegen-inferred type so the enclosing eval (an IF-test classification,
/// a defun's tail value) sees it as runtime — exactly what codegen's
/// accumulator promotion does. Idempotent: re-marking an already-runtime
/// target is a no-op, keeping the two-surface re-eval design sound.
pub(in crate::compiler::special) fn mark_runtime_setf_targets(
symbols: &mut SymbolTable,
exclude: &[&str],
) {
for (name, rhs) in collect_setf_targets(body) {
if exclude.contains(&name.as_str()) {
continue;
// Only re-type a var that is ALREADY bound in this scope — never
// synthesize a missing one. A `setf` to an undefined / nested-bound
// name is codegen's concern (`promote_to_wasm_local` errors on it); the
// eval mirror must not mask that by defining a spurious outer symbol.
let Some(current) = symbols.lookup(&name).and_then(|s| s.value().cloned()) else {
if current.is_wasm_runtime() {
let ty = infer_wasm_type(¤t, rhs.as_ref(), symbols).unwrap_or(WasmType::AnyRef);
symbols.define(Symbol::new(&name, SymbolKind::Variable).with_value(Expr::WasmRuntime(ty)));
/// Runs a statically-unrolled loop body; true when, in a macro body, a form
/// answered a runtime placeholder (an effect or transfer the evaluator cannot run).
pub(super) fn body_yields_runtime(symbols: &mut SymbolTable, body: &[Expr]) -> Result<bool> {
let in_macro = symbols.is_macro_expansion();
for expr in body {
if eval_value(symbols, expr)?.is_wasm_runtime() && in_macro {
pub(in crate::compiler::special) fn promote_to_wasm_local(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
name: &str,
step_hint: Option<&Expr>,
) -> Result<()> {
// A store target nothing defines yet is a definition (DEFPARAMETER) or a
// new global: its own form reports it when the body compiles.
let Some(sym) = symbols.lookup(name) else {
return Ok(());
if sym.value().is_some_and(Expr::is_wasm_runtime) {
let val = sym.value().cloned().unwrap_or(Expr::Nil);
let ty = infer_compiled_type(ctx, emit, symbols, &val, step_hint)?;
let idx = ctx.alloc_local(ty)?;
if matches!(ty, WasmType::PairRef(_)) && matches!(val, Expr::Nil) {
emit.ref_null(ctx.ids.ty_pair);
} else {
compile_for_stack(ctx, emit, symbols, &val)?;
emit.local_set(idx);
symbols.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmLocal(idx, ty)));
Ok(())
/// A step result the unroller can apply: a compile-time constant. A runtime
/// value (a store into runtime storage, a host call) needs the runtime loop.
fn static_value(value: Result<Expr>) -> Option<Expr> {
value.ok().filter(|value| !value.is_wasm_runtime())
/// [`static_loop_iterations`] with the simulated steps dead when
/// `dead_steps` (see [`steps_are_dead`]).
pub(super) fn steps_terminate(
local: &mut SymbolTable,
end_test: &Expr,
dead_steps: bool,
) -> bool {
let dead = local.is_dead_code();
local.set_dead_code(dead_steps);
let terminates =
static_loop_iterations(local, end_test, stepped, sequential, MAX_STATIC_LOOP_ITERS)
.is_some();
local.set_dead_code(dead);
terminates
/// The iterations a constant loop runs before its end test holds, `None` when
/// it does not end within `max_iterations` or leaves the constants.
pub(super) fn static_loop_iterations(
local: &SymbolTable,
max_iterations: usize,
) -> Option<usize> {
let mut sim = local.clone();
for iteration in 0..max_iterations {
match eval_value(&mut sim, end_test) {
Ok(test) if test.is_wasm_runtime() => return None,
Ok(test) if !test.is_nil() => return Some(iteration),
Ok(_) => {}
Err(_) => return None,
if sequential {
for (name, step) in stepped {
let Some(s) = step else { continue };
let val = static_value(eval_value(&mut sim, s))?;
if let Some(sym) = sim.lookup_mut(name) {
sym.set_value(val);
let new_vals = stepped
.filter_map(|(name, step)| {
step.as_ref()
.map(|s| static_value(eval_value(&mut sim, s)).map(|v| (name.clone(), v)))
.collect::<Option<Vec<_>>>();
let new_vals = new_vals?;
for (name, val) in new_vals {
if let Some(sym) = sim.lookup_mut(&name) {
None