Lines
96.19 %
Functions
86.36 %
Branches
100 %
//! The key of a binder site: which form binds the variable, and the constants
//! and local functions that form references. Eval and codegen compute it here
//! from the same form and table, so both name a site alike. It never holds a
//! type the fixpoint solves, so widening a home cannot re-key a site.
use std::collections::BTreeSet;
use std::hash::{DefaultHasher, Hash, Hasher};
use tracing::trace;
use crate::ast::{Expr, LambdaParams, WasmType};
use crate::compiler::expr::classify_stack_type;
use crate::compiler::join::fact;
use crate::compiler::special::binding::shared::assigned_scope;
use crate::runtime::{HomeKey, Symbol, SymbolTable};
#[derive(Clone, Copy, Debug)]
pub(crate) enum Surface {
Eval,
Codegen,
}
/// The key of each binder of a form, `None` for one no store can reach.
pub(crate) type SiteKeys = Vec<Option<HomeKey>>;
/// A binder `binder_keys` keys: its name, whether a DO step stores to it, and
/// the forms its stores can come from.
pub(crate) type Binder<'a> = (&'a str, bool, Vec<&'a Expr>);
/// The key of each binder of `head` that a store can reach, `None` for the
/// rest: an assigned or stepped one that is not a dynamic special, outside a
/// macro body (which only evaluates and has no code to give a home).
pub(crate) fn binder_keys<'a>(
symbols: &SymbolTable,
surface: Surface,
(head, args): (&str, &[Expr]),
binders: impl IntoIterator<Item = Binder<'a>>,
) -> SiteKeys {
let binders: Vec<Binder> = binders.into_iter().collect();
let scratch = symbols.scan_scratch();
let assigned = |(var, stepped, forms): &Binder| {
!symbols.is_macro_expansion()
&& !symbols.is_dynamic_special(var)
&& (*stepped
|| !matches!(
assigned_scope(&scratch, var, forms.iter().copied()),
Ok(None)
))
};
let sites: Vec<bool> = binders.iter().map(assigned).collect();
if !sites.contains(&true) {
return vec![None; binders.len()];
let (form, names) = form_digest(head, args);
let scope = scope_digest(symbols, &names);
let owner = symbols.function_owner();
binders
.iter()
.zip(sites)
.map(|((var, ..), site)| {
let key = site.then(|| HomeKey::Binder(owner, form, (*var).to_string(), scope))?;
trace!(?surface, ?key, "binder site");
Some(key)
})
.collect()
/// The identity of a function body: a global function by its name; a LABELS
/// function or a lambda by its source within the function `symbols` compiles.
pub(crate) fn function_owner(symbols: &SymbolTable, callee: Option<&str>, body: &Expr) -> u64 {
let global = callee.filter(|name| !symbols.lookup(name).is_some_and(Symbol::is_local_function));
let mut hasher = DefaultHasher::new();
match global {
Some(name) => name.hash(&mut hasher),
None => (
symbols.function_owner(),
form_digest(callee.unwrap_or_default(), std::slice::from_ref(body)).0,
)
.hash(&mut hasher),
hasher.finish()
/// A structural hash of the forms, walked with an explicit stack so a deep
/// datum cannot overflow the native one. It reads the source text only, and
/// returns the symbols the forms mention.
fn form_digest<'a>(head: &str, forms: &'a [Expr]) -> (u64, BTreeSet<&'a str>) {
let mut names = BTreeSet::new();
head.hash(&mut hasher);
let mut pending: Vec<&Expr> = forms.iter().rev().collect();
while let Some(expr) = pending.pop() {
std::mem::discriminant(expr).hash(&mut hasher);
match expr {
Expr::Nil
| Expr::T
| Expr::RuntimeValue(_)
| Expr::WasmRuntime(_)
| Expr::WasmLocal(..)
| Expr::WasmGlobal(..)
| Expr::Instance(..) => {}
Expr::Number(n) => n.hash(&mut hasher),
Expr::Symbol(text) => {
names.insert(text.as_str());
text.hash(&mut hasher);
Expr::String(text) | Expr::Keyword(text) => text.hash(&mut hasher),
Expr::Bytes(bytes) => bytes.hash(&mut hasher),
Expr::Cons(car, cdr) => pending.extend([cdr.as_ref(), car.as_ref()]),
Expr::List(items) => {
items.len().hash(&mut hasher);
pending.extend(items.iter().rev());
Expr::Quote(inner)
| Expr::Datum(inner)
| Expr::Quasiquote(inner)
| Expr::Unquote(inner)
| Expr::UnquoteSplicing(inner) => pending.push(inner),
Expr::Lambda(params, body) => {
hash_param_names(params, &mut hasher);
pending.push(body);
pending.extend(params.defaults().collect::<Vec<_>>().into_iter().rev());
(hasher.finish(), names)
fn hash_param_names(params: &LambdaParams, hasher: &mut DefaultHasher) {
params.required.hash(hasher);
params
.optional
.for_each(|(name, _)| name.hash(hasher));
params.rest.hash(hasher);
.key
.for_each(|param| param.keyword.hash(hasher));
params.aux.iter().for_each(|(name, _)| name.hash(hasher));
#[derive(Hash)]
enum Scope {
Const(Option<WasmType>),
Runtime,
LocalFn(u64),
/// What a referenced name contributes to the key: a constant by its literal
/// type, a local function by its source, anything else (a closure, a local, an
/// alias of a global) as runtime.
fn scope_of(symbol: &Symbol) -> Option<Scope> {
if symbol.is_local_function() {
let lambda = symbol.function()?;
let (digest, _) = form_digest("", std::slice::from_ref(lambda));
return Some(Scope::LocalFn(digest));
Some(match symbol.value()? {
value
if value.is_wasm_runtime()
|| matches!(value, Expr::RuntimeValue(_) | Expr::Lambda(..)) =>
{
Scope::Runtime
value => Scope::Const(classify_stack_type(value).map(fact)),
fn scope_digest(symbols: &SymbolTable, names: &BTreeSet<&str>) -> u64 {
for name in names {
let scope = symbols
.lookup(name)
.filter(|_| !symbols.is_special(name))
.and_then(scope_of);
if let Some(scope) = scope {
(name, scope).hash(&mut hasher);
#[cfg(test)]
#[path = "binder_key_tests.rs"]
mod tests;