Lines
93.59 %
Functions
98.48 %
Branches
100 %
//! Runtime-type inference for the let-body's tail value: a setf walk that reads
//! an accumulator's cons car so the promoted type matches codegen.
use crate::ast::{Expr, PairElement, WasmType};
use crate::compiler::expr::{classify_stack_type, eval_value, list_datum_members, quoted_datum};
use crate::compiler::join::Arm;
use crate::compiler::native::literal_pair_element;
use crate::compiler::special::lambda::compute_captures;
use crate::error::{Error, Result};
use crate::runtime::{HomeKey, Symbol, SymbolKind, SymbolTable, with_sufficient_stack};
use super::super::iteration::sizing::{infer_wasm_type, var_type_hint};
use super::super::iteration::unrolled_inits;
use super::super::setf_scan::{assigns, binder_rebinds, join, setf_rhs_of, step_pair_element};
use super::let_bind::home_type;
use super::let_eval::as_binding_datum;
use super::shared::assigned_scope;
/// `elems[from..]`, never panicking on a malformed/short binder form: a `(do)`
/// / `(dolist)` / `(let)` with fewer than `from` elements yields an empty slice
/// rather than an out-of-range slice index. This walk is a best-effort
/// accumulator-type inference hint, so a too-short form simply has no body to
/// scan; the malformed form is rejected by the real binding-compile path later.
fn tail(elems: &[Expr], from: usize) -> &[Expr] {
elems.get(from..).unwrap_or(&[])
}
pub(super) fn infer_runtime_type(expr: &Expr) -> WasmType {
// Bytes share StringRef's `i8_array` representation but aren't a
// `compile_for_stack` literal, so they're classified here, not in the
// shared `classify_stack_type`.
if let Expr::Bytes(_) = expr {
return WasmType::StringRef;
// A closure's type needs its interned signature, which only codegen has.
if let Expr::Lambda(..) = expr {
return WasmType::AnyRef;
match crate::compiler::expr::classify_stack_type(expr) {
Some(ty) => ty,
// For any remaining shape (List, Symbol, Quote, etc.) fall
// back to a generic PairRef. PairElement::I32 is the
// least-restrictive guess; downstream consumers refuse it
// explicitly when wrong, so a disagreement surfaces as a
// compile error rather than a runtime trap.
None => WasmType::PairRef(PairElement::I32),
/// Runtime local type for a let-var the body assigns, `None` if never assigned.
/// A const-initialized accumulator must become a real wasm local, else its
/// `setf` is lost across loop scopes.
pub(super) fn assigned_var_runtime_type(
body: &[Expr],
name: &str,
init_val: &Expr,
symbols: &SymbolTable,
) -> Result<Option<WasmType>> {
let Some(body) = &assigned_scope(symbols, name, body)? else {
return Ok(None);
};
let mut env = symbols.clone();
if let Some(elem) = walk_for_setf_pair_element(body, name, init_val, &mut env) {
return Ok(Some(WasmType::PairRef(elem)));
// Size from the first setf rhs with a runtime type (a nil init would
// otherwise give `Bool`), resolved on a clone with the depth-guarded
// inliner; else the init's type. A conflicting later store is codegen's.
for rhs in setf_rhs_of(body, name) {
match eval_value(&mut env.clone(), rhs) {
Ok(value) => {
if let Some(ty) = value.wasm_type().or_else(|| stored_type(&value)) {
return Ok(Some(ty));
Err(err @ Error::Dimension(_)) => return Err(err),
Err(_) => {}
Ok(Some(infer_runtime_type(init_val)))
/// The scope a nil accumulator of a LET is sized in: its siblings' values,
/// on the table the inits ran in, are visible to the stores that build it.
pub(super) fn sibling_scope(
outer: &SymbolTable,
bindings: &[(String, Option<Expr>)],
values: impl IntoIterator<Item = Expr>,
) -> Option<SymbolTable> {
let nil_init = |init: &Option<Expr>| matches!(init, None | Some(Expr::Nil));
if bindings.len() < 2 || !bindings.iter().any(|(_, init)| nil_init(init)) {
return None;
let mut scope = outer.clone();
for ((name, _), value) in bindings.iter().zip(values) {
let value = reads_outer_bindings(outer, bindings, value);
scope.define(Symbol::new(name, SymbolKind::Variable).with_value(value));
Some(scope)
/// A sibling lambda's body reads the LET's outer bindings, not its siblings.
fn reads_outer_bindings(
value: Expr,
) -> Expr {
let Expr::Lambda(params, body) = value else {
return value;
let Ok(captures) = compute_captures(outer, ¶ms, &body) else {
return Expr::Lambda(params, body);
let rebound: Vec<Expr> = bindings
.iter()
.filter(|(name, _)| captures.reads(name))
.filter_map(|(name, _)| {
let outer_value = outer.lookup(name)?.value()?.clone();
Some(Expr::List(vec![Expr::Symbol(name.clone()), outer_value]))
})
.collect();
if rebound.is_empty() {
let wrapped = Expr::List(vec![Expr::symbol("LET"), Expr::List(rebound), *body]);
Expr::Lambda(params, Box::new(wrapped))
/// The type a store of the datum `value` sizes a nil-initialised local to: the
/// datum's own, as codegen pushes it; a stored `nil` sizes nothing.
fn stored_type(value: &Expr) -> Option<WasmType> {
classify_stack_type(value).filter(|_| *value != Expr::Nil)
/// A let-var the body mutates is a runtime local in codegen even when its init
/// is a constant, so eval types it as one. With a hint the binder holds the
/// join of its init and the hint, as codegen's `home_type` allocates it.
///
/// Skipped while `symbols.is_macro_expansion()`: a macro's private body is
/// never codegen'd, and promoting would block the compile-time arithmetic it
/// uses to build its expansion.
pub(super) fn promote_assigned_binding(
val: Expr,
key: &Option<HomeKey>,
) -> Result<Expr> {
if symbols.is_macro_expansion() || matches!(val, Expr::Lambda(_, _)) {
return Ok(val);
if let Some(hint) = key.as_ref().and_then(|key| symbols.hint(key)) {
return Ok(hinted_binding(val, hint));
if val.is_wasm_runtime() {
Ok(
match assigned_var_runtime_type(body, name, &val, symbols)? {
Some(ty) if key.is_some() && val == Expr::Nil => {
Expr::WasmRuntime(home_type(Arm::Nil, Some(ty)))
Some(ty) => Expr::WasmRuntime(ty),
None => val,
},
)
fn hinted_binding(val: Expr, hint: WasmType) -> Expr {
let Some(ty) = classify_stack_type(&val).filter(|_| val.is_wasm_runtime()) else {
return Expr::WasmRuntime(hint);
match home_type(Arm::Value(ty), Some(hint)) {
joined if joined == ty => val,
joined => Expr::WasmRuntime(joined),
/// The type of a tail Symbol fed by a `(setf <name> (cons V <name>))`
/// accumulator: the cons car's PairElement, with dolist/do loop variables
/// resolved on the way.
pub(in crate::compiler::special) fn infer_runtime_type_with_body(
val: &Expr,
result_expr: &Expr,
) -> WasmType {
if let Expr::Symbol(name) = result_expr {
if let Some(elem) = walk_for_setf_pair_element(body, name, val, &mut env) {
return WasmType::PairRef(elem);
infer_runtime_type(val)
/// Walks `body` for `(setf <name> <rhs>)` and infers the matching
/// PairElement from the cons car of the rhs. Tracks DOLIST/DO/LET
/// loop-var bindings into `env` so nested setfs resolve their car
/// symbol against the right type.
fn walk_for_setf_pair_element(
target: &str,
init: &Expr,
env: &mut SymbolTable,
) -> Option<PairElement> {
if matches!(init, Expr::Nil) {
env.define(
Symbol::new(target, SymbolKind::Variable)
.with_value(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef))),
);
let mut joined = None;
for form in body {
walk_form(form, target, env, &mut joined);
joined
fn walk_form(form: &Expr, target: &str, env: &mut SymbolTable, out: &mut Option<PairElement>) {
with_sufficient_stack(|| {
let Expr::List(elems) = form else {
return;
// A binder that rebinds `target` shadows it: any `(setf target …)` inside
// refers to the inner variable, not the accumulator we're typing.
if binder_rebinds(elems, target) {
let head = elems.first().and_then(|e| match e {
Expr::Symbol(s) => Some(s.as_str()),
_ => None,
});
let children = match head {
Some("SETF") => {
fold_setf_stores(&elems[1..], target, env, out);
&elems[1..]
Some("DOLIST") => {
bind_dolist_var(elems, env);
tail(elems, 2)
Some("DO") | Some("DO*") => {
bind_do_vars(elems, head.unwrap_or_default(), env);
tail(elems, 3)
Some("LET") | Some("LET*") => {
bind_let_vars(elems, env);
_ => elems,
for e in children {
walk_form(e, target, env, out);
/// Joins the element built by every `(setf target rhs)` pair into `out`, so a
/// local stored with differing elements is sized to the widest, as codegen builds it.
fn fold_setf_stores(
pairs: &[Expr],
env: &SymbolTable,
out: &mut Option<PairElement>,
) {
for pair in pairs.chunks(2) {
if let Some(Expr::Symbol(var)) = pair.first()
&& var == target
&& let Some(rhs) = pair.get(1)
{
*out = join([*out, step_pair_element(rhs, env)].into_iter());
fn bind_let_vars(elems: &[Expr], env: &mut SymbolTable) {
let Some(Expr::List(bindings)) = elems.get(1) else {
for b in bindings {
if let Expr::List(parts) = b
&& let Some(Expr::Symbol(bname)) = parts.first()
let init_val = match parts.get(1) {
Some(init) => {
let mut probe = env.clone();
eval_value(&mut probe, init).unwrap_or(Expr::Nil)
None => Expr::Nil,
env.define(Symbol::new(bname, SymbolKind::Variable).with_value(init_val));
/// Binds a DOLIST variable as codegen does: the list's datum when it is a
/// constant list the body does not store into, else a runtime element.
fn bind_dolist_var(elems: &[Expr], env: &mut SymbolTable) {
let Some(Expr::List(spec)) = elems.get(1) else {
let (Some(Expr::Symbol(var)), Some(list_expr)) = (spec.first(), spec.get(1)) else {
let Ok(list_val) = eval_value(&mut env.clone(), list_expr) else {
let Some(WasmType::PairRef(elem)) = classify_stack_type(&list_val) else {
let value = literal_representative(&list_val, elem, tail(elems, 2), var)
.map_or(Expr::WasmRuntime(elem.as_wasm_type()), as_binding_datum);
env.define(Symbol::new(var, SymbolKind::Variable).with_value(value));
/// The first member of a constant list whose members all ride `elem` cells.
fn literal_representative(
list_val: &Expr,
elem: PairElement,
var: &str,
) -> Option<Expr> {
if assigns(body, var) {
let members = list_datum_members(quoted_datum(list_val).unwrap_or(list_val))?;
let first = members.first()?;
members
.all(|m| literal_pair_element(m) == Some(elem))
.then(|| first.clone())
/// Binds the variables of a DO / DO* form as codegen does: the iteration's
/// datum for a loop P11 unrolls, a runtime value of the init's type otherwise.
fn bind_do_vars(elems: &[Expr], head: &str, env: &mut SymbolTable) {
let Some(Expr::List(vars)) = elems.get(1) else {
let unrolled = unrolled_inits(&mut env.clone(), head, tail(elems, 1))
.ok()
.flatten();
for (at, spec) in vars.iter().enumerate() {
let Expr::List(parts) = spec else {
continue;
let Some(Expr::Symbol(name)) = parts.first() else {
let value = match unrolled.as_ref().and_then(|inits| inits.get(at)) {
Some(init) => as_binding_datum(init.clone()),
None => {
let Some(Ok(init_val)) = parts.get(1).map(|i| eval_value(&mut env.clone(), i))
else {
let hint = var_type_hint(parts.get(2), tail(elems, 3), name);
Expr::WasmRuntime(infer_wasm_type(&init_val, hint, env).unwrap_or(WasmType::AnyRef))
env.define(Symbol::new(name, SymbolKind::Variable).with_value(value));