Lines
98.51 %
Functions
91.38 %
Branches
100 %
//! `DO` (parallel-step variant) compile + eval handlers.
//!
//! The three compile entry points (`compile_do`, `_for_effect`,
//! `_for_stack`) hand the loop to `unroll::compile_loop`, which unrolls it
//! statically when P11 applies and otherwise emits the runtime loop.
//! `do_form` is the eval-only handler for value-position use.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::binder_key::Surface;
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{classify_stack_type, eval_value};
use crate::compiler::join::Arm;
use crate::error::{Error, Result};
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
use super::super::binding::{eval_body, var_home_type};
use super::super::literal_arm;
use super::common::{
DoVar, MAX_STATIC_LOOP_ITERS, ParsedLoop, body_yields_runtime, infer_result_pair_element,
mark_runtime_setf_targets, parse_loop, static_loop_iterations, steps_are_dead, steps_terminate,
};
use super::sizing::{infer_wasm_type, var_type_hint};
use super::unroll::{Pos, compile_loop, iteration_share, left_to_runtime_loop};
pub(super) fn compile_in(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
(head, sequential): (&str, bool),
args: &[Expr],
pos: Pos,
) -> Result<Option<WasmType>> {
let parsed = parse_loop(symbols, Surface::Codegen, head, sequential, args)?;
compile_loop(ctx, emit, symbols, &parsed.do_loop(), pos)
}
pub(super) fn compile_do(
) -> Result<()> {
compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Value).map(|_| ())
pub(super) fn compile_do_for_stack(
) -> Result<WasmType> {
compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Stack)?
.ok_or_else(|| Error::Compile("internal: DO in stack position left no value".to_string()))
pub(super) fn compile_do_for_effect(
compile_in(ctx, emit, symbols, ("DO", false), args, Pos::Effect).map(|_| ())
/// The runtime type a DO loop yields, mirroring `compile_do_runtime_for_stack`:
/// the last result form's type, `Bool` when there is none. A grown cons
/// accumulator is a list typed by its car; any other form takes its own type.
pub(super) fn runtime_result_type(
result_forms: &[Expr],
body: &[Expr],
stepped: &[(String, Option<Expr>)],
infer_env: &SymbolTable,
) -> WasmType {
let Some(last) = result_forms.last() else {
return WasmType::Bool;
if let Some(elem) = infer_result_pair_element(last, body, stepped, infer_env) {
return WasmType::PairRef(elem);
// A runtime value reports its own type; a constant goes through the classifier.
let resolved = eval_value(&mut infer_env.clone(), last).unwrap_or(Expr::Nil);
resolved
.wasm_type()
.or_else(|| classify_stack_type(&resolved))
.unwrap_or(WasmType::PairRef(PairElement::I32))
/// Evaluates the body and every step once, as codegen compiles them, so the
/// exits a runtime loop holds reach the BLOCKs they leave.
fn record_loop_exits(
env: &mut SymbolTable,
init_values: &[(String, Expr, Option<Expr>)],
dead_steps: bool,
eval_body(&mut env.clone(), body)?;
let outer_dead = env.is_dead_code();
env.set_dead_code(outer_dead || dead_steps);
for step in init_values.iter().filter_map(|(_, _, step)| step.as_ref()) {
eval_value(&mut env.clone(), step)?;
env.set_dead_code(outer_dead);
Ok(())
/// The type the eval surface reports for a loop left to codegen. Each variable
/// is bound as the runtime type codegen sizes it, so the result form resolves
/// as it does there; `Err` when a variable's type is known only to codegen.
pub(super) fn eval_result_type(
base: &SymbolTable,
keys: &[Option<HomeKey>],
let mut infer_env = base.clone();
infer_env.set_dead_code(dead_steps);
for ((name, val, step), key) in init_values.iter().zip(keys) {
infer_env.define(Symbol::new(name, SymbolKind::Variable).with_value(val.clone()));
let sized = infer_wasm_type(val, var_type_hint(step.as_ref(), body, name), &infer_env)
.ok_or_else(|| {
Error::Compile(format!("DO: the type of {name} is known only to codegen"))
})?;
let arm = literal_arm(val).unwrap_or(Arm::Value(sized));
let hint = key.as_ref().and_then(|key| base.hint(key));
let ty = var_home_type(arm, hint, || Ok(Some(sized)))?;
infer_env.define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::WasmRuntime(ty)));
infer_env.set_dead_code(base.is_dead_code());
record_loop_exits(&mut infer_env, init_values, body, dead_steps)?;
let stepped: Vec<(String, Option<Expr>)> = init_values
.iter()
.map(|(name, _, step)| (name.clone(), step.clone()))
.collect();
Ok(runtime_result_type(
result_forms,
body,
&stepped,
&infer_env,
))
pub(super) fn do_form(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
eval_loop(symbols, ("DO", false), args)
fn variable(name: &str, value: &Expr) -> Symbol {
Symbol::new(name, SymbolKind::Variable).with_value(value.clone())
type InitValues = Vec<(String, Expr, Option<Expr>)>;
/// Evaluates the inits: each against the enclosing scope for DO, against the
/// variables before it for DO*. Returns the scope the loop runs in.
fn eval_inits(
vars: Vec<DoVar>,
sequential: bool,
) -> Result<(SymbolTable, InitValues)> {
let mut sequential_scope = sequential.then(|| symbols.clone());
let mut inits = Vec::with_capacity(vars.len());
for v in vars {
let scope = sequential_scope.as_mut().unwrap_or(&mut *symbols);
let val = match v.init {
Some(expr) => eval_value(scope, &expr)?,
None => Expr::Nil,
if let Some(local) = sequential_scope.as_mut() {
local.define(variable(&v.name, &val));
inits.push((v.name, val, v.step));
let local = sequential_scope.unwrap_or_else(|| {
let mut local = symbols.clone();
for (name, val, _) in &inits {
local.define(variable(name, val));
local
});
Ok((local, inits))
fn set_variable(local: &mut SymbolTable, head: &str, name: &str, value: Expr) -> Result<()> {
.lookup_mut(name)
.ok_or_else(|| Error::Compile(format!("{head}: variable '{name}' is not bound")))?
.set_value(value);
fn step_variables(
local: &mut SymbolTable,
let mut pending = Vec::new();
for (name, step) in stepped {
let Some(step) = step else { continue };
let value = eval_value(local, step)?;
if sequential {
set_variable(local, head, name, value)?;
} else {
pending.push((name, value));
pending
.into_iter()
.try_for_each(|(name, value)| set_variable(local, head, name, value))
pub(super) fn eval_loop(
) -> Result<Expr> {
let ParsedLoop {
vars,
end_test,
keys,
..
} = parse_loop(symbols, Surface::Eval, head, sequential, args)?;
let end_test = end_test.clone();
let result_forms: Vec<Expr> = result_forms.to_vec();
let (mut local, init_values) = eval_inits(symbols, vars, sequential)?;
let needs_runtime = init_values.iter().any(|(_, v, _)| v.is_wasm_runtime());
let dead_steps = steps_are_dead(&local, body)?;
let base = symbols.speculative_clone();
let result_ty =
|| eval_result_type(&base, &init_values, &keys, &result_forms, body, dead_steps);
if needs_runtime || eval_value(&mut local, &end_test)?.is_wasm_runtime() {
return Ok(Expr::WasmRuntime(result_ty()?));
if left_to_runtime_loop(symbols, head, args)?
|| (!symbols.is_macro_expansion()
&& !steps_terminate(&mut local, &end_test, &stepped, sequential, dead_steps))
{
if symbols.is_macro_expansion() {
let vars: Vec<&str> = stepped.iter().map(|(name, _)| name.as_str()).collect();
mark_runtime_setf_targets(symbols, body, &vars);
// Simulating the steps of a macro's own loop would evaluate their effects.
let iterations = match symbols.is_macro_expansion() {
true => None,
false => static_loop_iterations(
&local,
&end_test,
sequential,
MAX_STATIC_LOOP_ITERS,
),
let share = iteration_share(symbols, iterations.unwrap_or(1));
loop {
let test = eval_value(&mut local, &end_test)?;
if !test.is_nil() {
return if result_forms.is_empty() {
Ok(Expr::Nil)
eval_body(&mut local, &result_forms)
if local.with_unroll_allowance(share, |local| body_yields_runtime(local, body))? {
step_variables(&mut local, (head, sequential), &stepped)?;