From ed3f96d4e1657aa9b4c1c51e44629f650aea2f4d Mon Sep 17 00:00:00 2001 From: Yazalde Filimone Date: Sun, 18 Oct 2026 15:14:36 +0200 Subject: [PATCH] move term interning caches into TermCache Extract the variable/lambda/apply hash-consing tables out of Term into TermCache behind a small intern API. Fixes the missing-field build error. Variables now use a dense Vec with a TermId::EMPTY sentinel and apply keys are packed into a u64. Semantics unchanged. --- src/core/cache.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++ src/core/mod.rs | 1 + src/core/term.rs | 51 ++++++++++++------------ src/core/traits.rs | 2 +- 4 files changed, 127 insertions(+), 26 deletions(-) create mode 100644 src/core/cache.rs diff --git a/src/core/cache.rs b/src/core/cache.rs new file mode 100644 index 0000000..dd6bd1a --- /dev/null +++ b/src/core/cache.rs @@ -0,0 +1,99 @@ +use crate::core::TermId; + +/// Structural hash-consing for the term arenas: identical nodes share one +/// `TermId`, so id equality *is* structural equality and reduction graphs stay a +/// compact DAG. Nodes are keyed by the least data that determines them. +#[derive(Clone, Default)] +pub struct TermCache { + /// Indexed by de Bruijn index; empty slots hold `TermId::EMPTY`. + variable: Vec, + lambda: rustc_hash::FxHashMap, + apply: rustc_hash::FxHashMap, +} + +impl TermCache { + pub fn with_capacity(variables: usize) -> Self { + Self { variable: Vec::with_capacity(variables), ..Default::default() } + } + + #[inline(always)] + pub fn variable(&self, index: u32) -> Option { + match self.variable.get(index as usize) { + Some(&id) if id != TermId::EMPTY => Some(id), + _ => None, + } + } + + #[inline] + pub fn set_variable(&mut self, index: u32, id: TermId) { + let slot = index as usize; + if slot >= self.variable.len() { + self.variable.resize(slot + 1, TermId::EMPTY); + } + self.variable[slot] = id; + } + + #[inline(always)] + pub fn lambda(&self, body: TermId) -> Option { + self.lambda.get(&(body.raw() as u64)).copied() + } + + #[inline] + pub fn set_lambda(&mut self, body: TermId, id: TermId) { + self.lambda.insert(body.raw() as u64, id); + } + + #[inline(always)] + pub fn apply(&self, function: TermId, argument: TermId) -> Option { + self.apply.get(&pack(function, argument)).copied() + } + + #[inline] + pub fn set_apply(&mut self, function: TermId, argument: TermId, id: TermId) { + self.apply.insert(pack(function, argument), id); + } +} + +/// Both halves are 32-bit ids, packed into one word so a lookup hashes once. +#[inline(always)] +fn pack(function: TermId, argument: TermId) -> u64 { + ((function.raw() as u64) << 32) | argument.raw() as u64 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::arena::Id; + + fn variable(index: u32) -> TermId { + TermId::variable(Id::new(index)) + } + + #[test] + fn variable_slots_are_sparse_and_miss_on_empty() { + let mut cache = TermCache::default(); + assert_eq!(cache.variable(0), None); + assert_eq!(cache.variable(9), None); + + cache.set_variable(9, variable(0)); + assert_eq!(cache.variable(0), None); + assert_eq!(cache.variable(9), Some(variable(0))); + } + + #[test] + fn apply_key_is_injective_in_its_pair() { + let mut cache = TermCache::default(); + cache.set_apply(variable(1), variable(2), variable(3)); + assert_eq!(cache.apply(variable(1), variable(2)), Some(variable(3))); + assert_eq!(cache.apply(variable(2), variable(1)), None); + assert_eq!(cache.apply(variable(1), variable(0)), None); + } + + #[test] + fn lambda_key_is_the_body() { + let mut cache = TermCache::default(); + cache.set_lambda(variable(7), variable(8)); + assert_eq!(cache.lambda(variable(7)), Some(variable(8))); + assert_eq!(cache.lambda(variable(6)), None); + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index dd52850..e9dfa97 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1,4 +1,5 @@ pub mod arena; +mod cache; mod term; mod traits; mod types; diff --git a/src/core/term.rs b/src/core/term.rs index a582091..4ba56c2 100644 --- a/src/core/term.rs +++ b/src/core/term.rs @@ -1,7 +1,8 @@ use crate::{ core::{ - TermView, TypeId, + TypeId, View, arena::{Arena, Id}, + cache::TermCache, }, symbol::SymbolId, }; @@ -14,12 +15,10 @@ pub struct Term { pub parameters: Arena>, pub annotations: Arena>, pub free_variables: Vec, - variable_cache: Vec>, - lambda_cache: rustc_hash::FxHashMap, - apply_cache: rustc_hash::FxHashMap<(TermId, TermId), TermId>, + cache: TermCache, } -impl TermView for Term { +impl View for Term { fn variable(&self, id: VariableId) -> &Variable { self.variables.get(id) } @@ -42,9 +41,7 @@ impl Term { parameters: Arena::new(), annotations: Arena::new(), free_variables: Vec::new(), - variable_cache: Vec::with_capacity(32), - lambda_cache: rustc_hash::FxHashMap::default(), - apply_cache: rustc_hash::FxHashMap::default(), + cache: TermCache::with_capacity(32), } } @@ -69,17 +66,12 @@ impl Term { } pub fn add_variable(&mut self, variable: Variable) -> TermId { - let idx = variable.index as usize; - if idx < self.variable_cache.len() { - if let Some(id) = self.variable_cache[idx] { - return id; - } - } else { - self.variable_cache.resize(idx + 1, None); + if let Some(id) = self.cache.variable(variable.index) { + return id; } let index = self.variables.add(variable); let id = TermId::variable(index); - self.variable_cache[idx] = Some(id); + self.cache.set_variable(variable.index, id); id } @@ -94,19 +86,20 @@ impl Term { parameter: Option, annotation: Option, ) -> TermId { - if annotation.is_none() - && parameter.is_none() - && let Some(&id) = self.lambda_cache.get(&lambda.body) - { + let interned = annotation.is_none() && parameter.is_none(); + if interned && let Some(id) = self.cache.lambda(lambda.body) { return id; } + let index = self.lambdas.add(lambda); self.parameters.add(parameter); self.annotations.add(annotation); let id = TermId::lambda(index); - if annotation.is_none() && parameter.is_none() { - self.lambda_cache.insert(lambda.body, id); + + if interned { + self.cache.set_lambda(lambda.body, id); } + id } @@ -119,13 +112,12 @@ impl Term { } pub fn add_apply(&mut self, apply: Apply) -> TermId { - let key = (apply.function, apply.argument); - if let Some(&id) = self.apply_cache.get(&key) { + if let Some(id) = self.cache.apply(apply.function, apply.argument) { return id; } let index = self.applies.add(apply); let id = TermId::apply(index); - self.apply_cache.insert(key, id); + self.cache.set_apply(apply.function, apply.argument, id); id } } @@ -148,6 +140,15 @@ impl TermId { pub const KIND_MASK: u32 = 0b11 << 30; pub const INDEX_MASK: u32 = !Self::KIND_MASK; + /// Reserved id that marks an empty cache slot. Tag `3` is produced by no + /// constructor, so it can never collide with a real node. + pub(crate) const EMPTY: Self = Self(3 << 30); + + #[inline(always)] + pub(crate) fn raw(self) -> u32 { + self.0 + } + #[inline(always)] pub fn variable(id: VariableId) -> Self { Self(id.index() & Self::INDEX_MASK) diff --git a/src/core/traits.rs b/src/core/traits.rs index 3dee826..f48b9da 100644 --- a/src/core/traits.rs +++ b/src/core/traits.rs @@ -1,7 +1,7 @@ use crate::core::{Apply, ApplyId, Lambda, LambdaId, Variable, VariableId}; #[allow(dead_code)] -pub trait TermView { +pub trait View { fn variable(&self, id: VariableId) -> &Variable; fn lambda(&self, id: LambdaId) -> Λ fn apply(&self, id: ApplyId) -> &Apply;