Lines
99.64 %
Functions
97.5 %
Branches
100 %
//! `LET` / `LET*` codegen (effect, stack, value-position variants).
//!
//! Six entry points share the same shape: parse the bindings list,
//! resolve each init (parallel for LET, sequential for LET*), bind via
//! `bind_variable` to either a constant or a freshly-allocated
//! wasm local inside a symbol-table scope frame, then compile the body.
//! The frame shadows without copying the table, so a definition the body
//! makes outlives it (0014 Stage 2, ISS-039). The only difference between
//! the entry points is what the body-compile target is.
use crate::ast::{Expr, WasmType};
use crate::compiler::binder_key::Surface;
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_body, compile_body_for_stack, compile_diverging_to_end, compile_for_effect,
probe_value, serialize_stack_to_output,
};
use crate::compiler::join::NEVER_RETURNS;
use crate::error::Result;
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable};
use super::super::control::protect;
use super::super::{compile_store_value, form_diverges_scratch};
use super::dynamic::{
DynamicHome, bind, dynamic_home, reject_missed_specials, restore_forms, save_all,
use super::infer::sibling_scope;
use super::let_bind::{Bind, bind_variable, resolve_binding};
use super::parse::{reject_duplicate_names, split_let};
use super::shared::needs_cell;
use super::shared::star_scope;
/// What the body compiles to.
#[derive(Clone, Copy)]
enum Target {
Value,
Stack,
Effect,
}
pub(super) fn compile_let(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
in_live_frame(ctx, emit, symbols, args, Target::Value, compile_parallel).map(|_| ())
pub(super) fn compile_let_for_stack(
) -> Result<WasmType> {
in_live_frame(ctx, emit, symbols, args, Target::Stack, compile_parallel)
pub(super) fn compile_let_for_effect(
in_live_frame(ctx, emit, symbols, args, Target::Effect, compile_parallel).map(|_| ())
pub(super) fn compile_let_star(
in_live_frame(ctx, emit, symbols, args, Target::Value, compile_sequential).map(|_| ())
pub(super) fn compile_let_star_for_stack(
in_live_frame(ctx, emit, symbols, args, Target::Stack, compile_sequential)
pub(super) fn compile_let_star_for_effect(
in_live_frame(ctx, emit, symbols, args, Target::Effect, compile_sequential).map(|_| ())
/// LET: every init resolves and binds against the enclosing scope before
/// anything is saved; a dynamic special's init is staged in a local. The
/// save, the store of the staged values and the body are the protected region.
fn compile_parallel(
target: Target,
let (bindings, keys, body) = split_let(symbols, Surface::Codegen, "LET", false, args)?;
reject_duplicate_names("variable", "LET", bindings.iter().map(|(name, _)| name))?;
reject_missed_specials(symbols, bindings.iter().map(|(name, _)| name.as_str()))?;
let mut bound = Vec::with_capacity(bindings.len());
let mut staged = Vec::new();
let mut homes = Vec::new();
let probed = bindings.iter().map(|(_, init)| match init {
Some(init) => {
probe_value(&mut symbols.clone(), init).unwrap_or(Expr::WasmRuntime(WasmType::AnyRef))
None => Expr::Nil,
});
let sizing = sibling_scope(symbols, &bindings, probed);
for ((name, init), key) in bindings.iter().zip(&keys) {
if init_raises(ctx, emit, symbols, init.as_ref())? {
return Ok(NEVER_RETURNS);
if let Some(home) = dynamic_home(symbols, name) {
compile_store_value(
ctx,
emit,
symbols,
&Expr::Symbol(name.clone()),
init.as_ref().unwrap_or(&Expr::Nil),
home.ty,
)?;
if !emit.is_reachable() {
let tmp = ctx.alloc_local(home.ty)?;
emit.local_set(tmp);
staged.push((home, tmp));
homes.push(home);
continue;
let (init_expr, init) = resolve_binding(symbols, init.clone())?;
let shared = needs_cell(symbols, name, body)?;
let value = bind_variable(
&Bind {
name,
body,
shared,
sizing: sizing.as_ref(),
key: key.as_ref(),
},
init_expr.as_ref(),
&init,
bound.push((name, value));
with_dynamic(
("LET", args),
&homes,
target,
|ctx, emit, symbols, target| {
for (home, tmp) in staged {
emit.local_get(tmp);
bind(emit, home);
symbols.push_scope();
for (name, (value, home)) in bound {
record_closure_result(symbols, ctx, &value)?;
symbols.define_scoped(
Symbol::new(name, SymbolKind::Variable)
.with_value(value)
.with_home(home),
);
let compiled = compile_target(ctx, emit, symbols, body, target);
symbols.pop_scope()?;
compiled
)
/// LET*: only reached when no spec binds a dynamic special (`rebind` nests
/// those); the frame opens first and each init sees the bindings before it.
fn compile_sequential(
let (bindings, keys, body) = split_let(symbols, Surface::Codegen, "LET*", true, args)?;
let compiled =
bind_sequentially(ctx, emit, symbols, &bindings, &keys, body).and_then(|live| match live {
true => compile_target(ctx, emit, symbols, body, target),
false => Ok(NEVER_RETURNS),
/// Binds the LET* variables in order; `false` once an init diverges.
fn bind_sequentially(
bindings: &[(String, Option<Expr>)],
keys: &[Option<HomeKey>],
body: &[Expr],
) -> Result<bool> {
for (at, ((name, init), key)) in bindings.iter().zip(keys).enumerate() {
return Ok(false);
let scope: Vec<Expr> = star_scope(bindings, at, body, true)
.into_iter()
.cloned()
.collect();
let shared = needs_cell(symbols, name, &scope)?;
body: &scope,
sizing: None,
record_closure_result(symbols, ctx, &value.0)?;
.with_value(value.0)
.with_home(value.1),
Ok(true)
fn init_raises(
init: Option<&Expr>,
let Some(init) = init else {
compile_diverging_to_end(ctx, emit, symbols, init, form_diverges_scratch)
type LetCompile = fn(
&mut CompileContext,
&mut FunctionEmitter,
&mut SymbolTable,
&[Expr],
Target,
) -> Result<WasmType>;
/// A LET entered in dead code compiles once on a live scratch, so an init that
/// never returns ends it there as it does in live code.
fn in_live_frame(
compile: LetCompile,
if emit.is_reachable() {
return compile(ctx, emit, symbols, args, target);
let (ty, _) = emit.on_live_scratch(|scratch| compile(ctx, scratch, symbols, args, target))?;
Ok(ty)
/// Saves the dynamic specials at `homes`, then runs `inner` with each
/// restored on every exit of it; without one, `inner` runs as it is.
fn with_dynamic(
(head, args): (&str, &[Expr]),
homes: &[DynamicHome],
inner: impl FnOnce(
) -> Result<WasmType>,
let saved = save_all(ctx, emit, symbols, homes)?;
if saved.is_empty() {
return inner(ctx, emit, symbols, target);
let form = Expr::List(
std::iter::once(Expr::symbol(head))
.chain(args.iter().cloned())
.collect(),
let diverges = form_diverges_scratch(symbols, &form)?;
let cleanup = restore_forms(&saved);
let ty = protect(
&cleanup,
diverges,
|ctx, scratch, symbols| inner(ctx, scratch, symbols, Target::Stack),
match target {
Target::Stack => Ok(ty),
Target::Value => serialize_stack_to_output(ctx, emit, ty).map(|()| WasmType::Bool),
Target::Effect => {
emit.drop_value();
Ok(WasmType::Bool)
fn compile_target(
Target::Value => compile_body(ctx, emit, symbols, body).map(|()| WasmType::Bool),
Target::Stack => compile_body_for_stack(ctx, emit, symbols, body),
for form in body {
compile_for_effect(ctx, emit, symbols, form)?;
/// When a binding's emitted value is a closure, record its signature's result
/// type into the body's symbol table so the ctx-less eval surface (FOLD's
/// accumulator probe, binding-local sizing) can predict a HOF result type that
/// agrees with codegen — see `SymbolTable::closure_results`.
pub(in crate::compiler) fn record_closure_result(
local: &mut SymbolTable,
ctx: &CompileContext,
bound: &Expr,
if let Some((_, WasmType::Closure(sig))) = bound.place() {
let shape = ctx.closure_sig(sig)?;
local.record_closure_result(sig, shape.result);
local.record_closure_params(sig, &shape.params);
Ok(())