Lines
99.4 %
Functions
96.25 %
Branches
100 %
//! The homes the unit allocated for its stored globals and what its stores
//! write into them (plan 0014 stage GJ): a global's home type is the join of
//! its init and every store, found by compiling the unit again.
//!
//! The book is shared by every clone the compile makes, like the work budget,
//! because a DOLIST body or a monomorph compiles on a clone. It is replaced
//! with each attempt and journalled with the rest of a trial's state.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use crate::ast::{Expr, StructId, WasmType};
use crate::compiler::join::{Arm, fact, reconcile_arms};
use super::table::SymbolTable;
/// What a home belongs to: a stored global, a field every instance of a
/// struct layout shares, or an assigned binder: its enclosing function, form
/// digest, variable and constant-scope digest.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum HomeKey {
Global(String),
Field(StructId, u16),
Binder(Option<u64>, u64, String, u64),
}
impl HomeKey {
pub(crate) fn global(name: &str) -> Self {
Self::Global(name.to_string())
#[derive(Clone, Debug)]
struct Home {
base: Vec<Arm>,
datum: Option<Expr>,
ty: WasmType,
arms: Vec<Arm>,
/// The home is a placeholder `AnyRef` no writer has typed yet.
provisional: bool,
/// The closure a provisional home was first stored.
closure: Option<ClosureShape>,
/// A global the unit made a cell of before any of its forms compiled.
#[derive(Clone, Copy, Debug)]
pub(super) struct Cell {
/// The i32 global that is 1 once the cell holds a value.
flag: u32,
seed: Seed,
/// What the unit's definitions compiled so far did to the cell.
defined: CellBinding,
/// What a cell holds when its unit starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Seed {
Unbound,
/// An earlier unit's constant, so the cell starts bound.
Constant,
/// An earlier unit's lambda, so the cell starts as a closure of it.
Closure,
/// An earlier unit's value no constant holds: the cell starts bound but
/// unreadable, and its flag is 1 once the unit stored a value.
Lost,
/// Whether the definitions a unit compiled so far bound a cell at run time.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum CellBinding {
#[default]
/// Only a definition that may be skipped reached it.
Maybe,
Bound,
impl Home {
fn typed(base: Vec<Arm>, datum: Option<Expr>, ty: WasmType) -> Self {
Self {
base,
datum,
ty,
arms: Vec::new(),
provisional: false,
closure: None,
fn provisional() -> Self {
provisional: true,
..Self::typed(Vec::new(), None, WasmType::AnyRef)
fn joined(&self) -> WasmType {
let arms: Vec<Arm> = self.base.iter().chain(&self.arms).copied().collect();
fact(reconcile_arms(&arms))
fn holds_every_store(&self) -> bool {
if self.provisional {
return self.arms.is_empty() || self.joined() == self.ty;
let arms: Vec<Arm> = std::iter::once(Arm::Value(self.ty))
.chain(self.base.iter().copied())
.chain(self.arms.iter().copied())
.collect();
reconcile_arms(&arms) == self.ty
#[derive(Clone, Debug, Default)]
pub(crate) struct HomeBook {
hints: BTreeMap<HomeKey, WasmType>,
closure_hints: BTreeMap<String, ClosureShape>,
homes: BTreeMap<HomeKey, Home>,
expired: BTreeSet<String>,
/// The cells of this attempt: each global the unit writes, made at its
/// start. Shared with every scratch copy of the table.
cells: BTreeMap<String, Cell>,
/// The definition forms of this attempt, by slot, and the flag each sets
/// once it has run. Shared with every scratch copy of the table.
pub(super) definitions:
BTreeMap<(String, super::definitions::Slot), Vec<super::definitions::Version>>,
/// The symbols the unit writes, as they stood before it.
pub(super) pre_unit: BTreeMap<String, super::definitions::Written>,
/// The rebind globals of each special global a binder of this attempt saves.
pub(super) rebinds: BTreeMap<u32, super::rebind::Rebind>,
/// The globals this attempt makes cells of because an earlier attempt
/// found their one definition's init runs at run time.
forced: BTreeSet<String>,
/// The globals this attempt found such a definition for, with what its
/// init probes to.
asked: BTreeMap<String, Asked>,
/// The cells this attempt starts without the closure an earlier unit
/// carried, because a store of the previous attempt refused it, and the
/// ones this attempt found such a store for.
unseeded: BTreeSet<String>,
refused: BTreeSet<String>,
/// The global functions the closures this attempt created call, by name.
pub(super) closure_deps: BTreeSet<String>,
impl HomeBook {
/// The hints for the next attempt, when some home of this one is
/// narrower than its stores: the join recomputed from this attempt's
/// stores for each narrow home, over the hints this attempt started with. A
/// closure joins to `AnyRef`; a provisional home that holds one asks for it.
fn widened(&self) -> Option<HashMap<HomeKey, WasmType>> {
let verdicts: Vec<(&HomeKey, &Home, bool)> = self
.homes
.iter()
.filter(|(_, home)| !home.arms.is_empty())
.map(|(name, home)| (name, home, home.holds_every_store()))
let narrow = verdicts.iter().any(|(_, _, holds)| !holds)
|| self.holds_new_closure()
|| !self.asked.is_empty()
|| !self.refused.is_empty();
let mut hints: HashMap<HomeKey, WasmType> = self
.hints
.map(|(key, ty)| (key.clone(), *ty))
hints.extend(
verdicts
.into_iter()
.filter(|(_, _, holds)| !holds)
.map(|(key, home, _)| (key.clone(), home.joined())),
);
hints.extend(self.asked.iter().filter_map(|(name, asked)| match asked {
Asked::Typed(ty) => Some((HomeKey::global(name), fact(*ty))),
Asked::Closure(_) | Asked::Untyped => None,
}));
narrow.then_some(hints)
fn holds_new_closure(&self) -> bool {
self.homes.values().any(|home| home.closure.is_some())
/// The closures the next attempt allocates cells for: those this attempt
/// started with and the ones its provisional homes were first stored.
fn closure_shapes(&self) -> HashMap<String, ClosureShape> {
let mut shapes: HashMap<String, ClosureShape> = self
.closure_hints
.map(|(name, shape)| (name.clone(), shape.clone()))
shapes.extend(self.homes.iter().filter_map(|(key, home)| match key {
HomeKey::Global(name) => home.closure.clone().map(|shape| (name.clone(), shape)),
HomeKey::Field(..) | HomeKey::Binder(..) => None,
shapes.extend(self.asked.iter().filter_map(|(name, asked)| match asked {
Asked::Closure(shape) => Some((name.clone(), shape.clone())),
Asked::Typed(_) | Asked::Untyped => None,
shapes
pub(super) fn locked(book: &Mutex<HomeBook>) -> MutexGuard<'_, HomeBook> {
book.lock().unwrap_or_else(PoisonError::into_inner)
impl SymbolTable {
/// Starts an attempt at the unit with a fresh book that carries `hints`.
pub(crate) fn begin_home_attempt(&mut self, hints: HashMap<HomeKey, WasmType>) {
self.homes = Arc::new(Mutex::new(HomeBook {
hints: hints.into_iter().collect(),
..HomeBook::default()
pub(crate) fn end_home_attempt(&mut self) {
self.homes = Arc::default();
/// The type the stores of the previous attempt asked the home `key` to have.
#[must_use]
pub(crate) fn hint(&self, key: &HomeKey) -> Option<WasmType> {
locked(&self.homes).hints.get(key).copied()
/// Records the home this attempt allocated for `name`, typed `ty` from the
/// `base` arms of its init; a constant init keeps its `datum`.
pub(crate) fn note_home(&self, name: &str, base: Vec<Arm>, datum: Option<Expr>, ty: WasmType) {
if matches!(ty, WasmType::Closure(_)) {
return;
locked(&self.homes)
.insert(HomeKey::global(name), Home::typed(base, datum, ty));
/// Records the placeholder home of a cell no writer has typed yet: the
/// next attempt gives it the join of the stores this one compiles.
pub(crate) fn note_provisional_home(&self, name: &str) {
.insert(HomeKey::global(name), Home::provisional());
/// Records the closure stored into the provisional home `name`, the first
/// one deciding.
pub(crate) fn note_closure_shape(&self, name: &str, shape: ClosureShape) {
if let Some(home) = locked(&self.homes).homes.get_mut(&HomeKey::global(name))
&& home.provisional
&& home.closure.is_none()
{
home.closure = Some(shape);
/// Keeps the first constant written to `name`'s home as the init a store
/// is typed against.
pub(crate) fn note_home_datum(&self, name: &str, datum: &Expr) {
&& home.datum.is_none()
home.datum = Some(datum.clone());
fn home_datum(&self, key: &HomeKey) -> Option<Expr> {
.get(key)
.and_then(|home| home.datum.clone())
/// Records what a store writes into the home `key`; a home an earlier unit
/// allocated is not in the book and records nothing.
pub(crate) fn note_store(&self, key: &HomeKey, arm: Arm) {
if let Some(home) = locked(&self.homes).homes.get_mut(key) {
home.arms.push(arm);
/// The hints for the next attempt, unless every home of this one already
/// has the join of its stores.
pub(crate) fn widened_homes(&self) -> Option<HashMap<HomeKey, WasmType>> {
locked(&self.homes).widened()
/// A copy of the table where the variable of the home `key` is the
/// constant its home was initialised with, for typing a store as its first
/// execution sees it. None inside such a copy, so a store its trial
/// compiles runs no trial.
pub(crate) fn probe_at_init(&self, key: &HomeKey, name: &str) -> Option<Self> {
let datum = self.home_datum(key).filter(|_| !self.in_init_trial)?;
let mut probe = self.clone();
probe.in_init_trial = true;
probe.stored_globals.remove(name);
probe.dynamic_specials.remove(name);
probe.lookup_mut(name)?.set_value(datum);
Some(probe)
/// Drops the runtime value of every global or local an earlier unit's
/// module allocated, and with it the manifest no host took: the unit about to
/// compile is a fresh module without them.
pub(crate) fn expire_homes(&mut self) {
self.unit_slots.clear();
self.unit_closures.clear();
let expired: Vec<String> = self
.symbols
.iter_mut()
.filter(|(_, symbol)| {
matches!(
symbol.value(),
Some(Expr::WasmGlobal(..) | Expr::WasmLocal(..))
)
})
.map(|(name, symbol)| {
symbol.clear_value();
name.clone()
for name in &expired {
self.lost_homes.remove(name);
locked(&self.homes).expired.extend(expired);
pub(super) fn is_expired(&self, name: &str) -> bool {
locked(&self.homes).expired.contains(name)
pub(crate) fn home_book(&self) -> HomeBook {
locked(&self.homes).clone()
pub(crate) fn restore_home_book(&self, book: HomeBook) {
*locked(&self.homes) = book;
mod binders;
mod cells;
mod fields;
mod shapes;
pub(crate) use shapes::{Asked, ClosureShape};
#[cfg(test)]
#[path = "homes_tests.rs"]
mod tests;