Lines
97.69 %
Functions
95.92 %
Branches
100 %
//! Binding one `LET` / `LET*` variable: resolving its init, then either
//! keeping a constant, lifting a lambda to a closure local, or allocating a
//! runtime local, which for an assigned variable has a home its stores widen.
use crate::ast::{Expr, LambdaParams, Place, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
applying_lambda, bind_local, close_factory_call, compile_for_effect, compile_for_stack,
emit_box_anyref, emit_local_read, emit_nil_default, eval_value, fold_value, probe_value,
reads_only,
};
use crate::compiler::join::{Arm, reconcile_arms};
use crate::compiler::native::function_operand::runs_nothing;
use crate::compiler::special::{is_closure_factory_call, try_emit_lambda_for_value};
use crate::error::{Error, Result};
use crate::runtime::{HomeKey, SymbolTable};
use super::super::{compile_into_home, literal_arm};
use super::infer::assigned_var_runtime_type;
/// How a binding's init resolved, which decides what `bind_runtime_or_const`
/// emits for it.
pub(super) enum Init {
/// A fold-safe constant: bound as data, nothing emitted.
Datum(Expr),
/// A constant whose form carries effects (a store, a print, a transfer):
/// the form is compiled for effect, then the constant is bound.
Effectful(Expr),
/// A runtime value, or a compile-time value only the evaluator can hold
/// (a lambda): bound as the evaluator resolved it.
Resolved(Expr),
}
impl Init {
fn value(&self) -> &Expr {
match self {
Init::Datum(value) | Init::Effectful(value) | Init::Resolved(value) => value,
/// Resolves one init: its fold-safe datum, else a probe on a clone decides
/// between a runtime local, an evaluator-only value and an effectful
/// constant (0014 Stage 2: a store inside an init is never lost, S24).
pub(super) fn resolve_binding(
symbols: &mut SymbolTable,
init: Option<Expr>,
) -> Result<(Option<Expr>, Init)> {
let Some(expr) = init else {
return Ok((None, Init::Datum(Expr::Nil)));
if let Some(datum) = fold_value(symbols, &expr)? {
return Ok((Some(expr), Init::Datum(datum)));
let probed = probe_value(&mut symbols.clone(), &expr)?;
let init = match probed {
ref value if value.is_wasm_runtime() => Init::Resolved(probed),
Expr::Lambda(..) if is_closure_factory_call(symbols, &expr)? => Init::Resolved(probed),
Expr::Lambda(..) if !runs_nothing(symbols, &expr) && !reads_only(symbols, &expr) => {
Init::Effectful(probed)
Expr::Lambda(_, _) | Expr::RuntimeValue(_) => Init::Resolved(eval_value(symbols, &expr)?),
// A binding holds data: a bare symbol an init evaluates to is bound
// quoted, never as a reference to the variable it names (0014
// obligation (f)).
symbol @ Expr::Symbol(_) => Init::Effectful(Expr::quoted(symbol)),
constant => Init::Effectful(constant),
Ok((Some(expr), init))
/// Lifts a v1 lambda to a closure value held in a fresh local, or `None` when
/// the lambda does not fit the v1 emit slice.
pub(in crate::compiler) fn bind_lambda_closure(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
params: &LambdaParams,
body: &Expr,
shared: bool,
) -> Result<Option<Expr>> {
let Some(sig) = try_emit_lambda_for_value(ctx, emit, symbols, params, body)? else {
return Ok(None);
let ty = WasmType::Closure(sig);
let idx = bind_local(ctx, emit, ty, shared)?;
// Only a capture-free closure keeps its source: inlining a capturing one
// at a HOF call site would resolve its free variables there, not where it
// was created. A celled closure variable can be reassigned from another
// closure, so it keeps none either.
if !shared && crate::compiler::special::is_capture_free(symbols, params, body) {
symbols.record_closure_body(Place::Local(idx), params.clone(), body.clone());
Ok(Some(Expr::WasmLocal(idx, ty)))
/// What binding a variable needs to know: its name, the scope forms that
/// follow, whether it lives in a shared cell, and the site of its home when a
/// store can reach it.
pub(super) struct Bind<'a> {
pub(super) name: &'a str,
pub(super) body: &'a [Expr],
pub(super) shared: bool,
/// The scope an assigned variable is sized in, when it must see its siblings.
pub(super) sizing: Option<&'a SymbolTable>,
pub(super) key: Option<&'a HomeKey>,
/// Binds one variable; an assigned one gets the home its stores record into.
pub(super) fn bind_variable(
bind: &Bind,
init_expr: Option<&Expr>,
init: &Init,
) -> Result<(Expr, Option<HomeKey>)> {
let copies_closure = matches!(
(init.value(), init_expr),
(
Expr::WasmLocal(_, WasmType::Closure(_)),
Some(Expr::Symbol(_))
)
);
match bind.key {
Some(key) if !copies_closure && !matches!(init.value(), Expr::Lambda(..)) => {
let val = init.value();
let (idx, ty) = bind_var_home(
ctx,
emit,
symbols,
Some(key),
(init_expr, val),
bind.shared,
|_, _, symbols| {
let sizing = bind.sizing.unwrap_or(&*symbols);
assigned_var_runtime_type(bind.body, bind.name, val, sizing)
},
)?;
Ok((Expr::WasmLocal(idx, ty), Some(key.clone())))
_ => {
let value = bind_runtime_or_const(ctx, emit, symbols, bind.shared, init_expr, init)?;
Ok((value, None))
/// Allocates the local of a variable that may be assigned, typed by its home:
/// the join of the init and the hint, the stores of the previous attempt that
/// did not fit. A literal init takes the home's type, a nil one without a hint
/// the type `seed` predicts; any other compiles as itself and is boxed when the
/// home holds any value.
pub(in crate::compiler::special) fn bind_var_home(
key: Option<&HomeKey>,
(init_expr, val): (Option<&Expr>, &Expr),
seed: impl FnOnce(
&mut CompileContext,
&mut FunctionEmitter,
&mut SymbolTable,
) -> Result<Option<WasmType>>,
) -> Result<(u32, WasmType)> {
let hint = key.and_then(|key| symbols.hint(key));
let (arm, ty) = match literal_arm(val) {
Some(arm) => {
let ty = var_home_type(arm, hint, || seed(ctx, emit, symbols))?;
match init_expr {
Some(expr) => compile_into_home(ctx, emit, symbols, expr, ty, arm == Arm::Nil)?,
None => emit_nil_default(ctx, emit, ty)?,
(arm, ty)
None => bind_compiled(ctx, emit, symbols, init_expr, hint)?,
if let Some(key) = key {
let datum = (!val.is_wasm_runtime()).then(|| val.clone());
symbols.open_binder(key, arm, datum, ty);
Ok((idx, ty))
fn bind_compiled(
hint: Option<WasmType>,
) -> Result<(Arm, WasmType)> {
let expr = init_expr
.ok_or_else(|| Error::Compile("runtime binding requires an init expression".to_string()))?;
let actual = compile_for_stack(ctx, emit, symbols, expr)?;
let ty = home_type(Arm::Value(actual), hint);
box_into_home(ctx, emit, actual, ty);
Ok((Arm::Value(actual), ty))
/// Boxes the value of type `actual` on the stack when its `home` holds any value.
pub(in crate::compiler::special) fn box_into_home(
ctx: &CompileContext,
actual: WasmType,
home: WasmType,
) {
if home == WasmType::AnyRef {
emit_box_anyref(ctx, emit, actual);
/// The type of an assigned variable's local: the init `arm` joined with the
/// `hint` the refused stores of the previous attempt left, else for a nil init
/// with the type its stores are sized to, which `seed` computes.
pub(in crate::compiler::special) fn var_home_type(
arm: Arm,
seed: impl FnOnce() -> Result<Option<WasmType>>,
) -> Result<WasmType> {
let seed = match (hint, arm) {
(None, Arm::Nil) => seed()?,
_ => hint,
Ok(home_type(arm, seed))
/// The type a local holds that the init `arm` and the `seed` both fit.
pub(in crate::compiler::special) fn home_type(arm: Arm, seed: Option<WasmType>) -> WasmType {
let arms: Vec<Arm> = std::iter::once(arm).chain(seed.map(Arm::Value)).collect();
reconcile_arms(&arms)
/// If the init is a runtime value, compile the init expression to the WASM
/// stack, allocate a local, and return `WasmLocal`. If it is an
/// `Expr::Lambda` that fits the Tier 1.5 v1 emit slice, lift it to a real
/// wasm closure value: emit the closure construction sequence, allocate a
/// `Closure(sig)` local, and return the corresponding `WasmLocal`.
/// Otherwise return the constant value untouched (the body's const-fold
/// path keeps working), after compiling an effectful init for its effects.
fn bind_runtime_or_const(
) -> Result<Expr> {
match val {
// A closure variable bound from another one gets its own local: sharing
// the slot would make a later `setf` of either change both.
Expr::WasmLocal(from, ty @ WasmType::Closure(_))
if matches!(init_expr, Some(Expr::Symbol(_))) =>
{
emit_local_read(ctx, emit, *from);
let idx = bind_local(ctx, emit, *ty, shared)?;
Ok(Expr::WasmLocal(idx, *ty))
value if value.is_wasm_runtime() => {
// The compiled type is authoritative: the eval-time placeholder can
// disagree with what codegen pushes (e.g. a fold over a runtime closure).
let (_, actual_ty) = bind_compiled(ctx, emit, symbols, init_expr, None)?;
let idx = bind_local(ctx, emit, actual_ty, shared)?;
Ok(Expr::WasmLocal(idx, actual_ty))
Expr::Lambda(..) => {
if let (Init::Effectful(_), Some(expr)) = (init, init_expr) {
compile_for_effect(ctx, emit, symbols, expr)?;
let closed = match init_expr {
Some(call) if is_closure_factory_call(symbols, call)? => {
close_factory_call(ctx, emit, symbols, call)?
_ => val.clone(),
let Expr::Lambda(params, body) = &closed else {
return Ok(closed);
let source = init_expr.unwrap_or(&closed);
let emitted = applying_lambda(symbols, source, |symbols| {
bind_lambda_closure(ctx, emit, symbols, params, body, shared)
})?;
Ok(emitted.unwrap_or_else(|| closed.clone()))
Ok(val.clone())