Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions src/core/cache.rs
Original file line number Diff line number Diff line change
@@ -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<TermId>,
lambda: rustc_hash::FxHashMap<u64, TermId>,
apply: rustc_hash::FxHashMap<u64, TermId>,
}

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<TermId> {
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<TermId> {
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<TermId> {
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);
}
}
1 change: 1 addition & 0 deletions src/core/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod arena;
mod cache;
mod term;
mod traits;
mod types;
Expand Down
51 changes: 26 additions & 25 deletions src/core/term.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::{
core::{
TermView, TypeId,
TypeId, View,
arena::{Arena, Id},
cache::TermCache,
},
symbol::SymbolId,
};
Expand All @@ -14,12 +15,10 @@ pub struct Term {
pub parameters: Arena<Option<SymbolId>>,
pub annotations: Arena<Option<TypeId>>,
pub free_variables: Vec<SymbolId>,
variable_cache: Vec<Option<TermId>>,
lambda_cache: rustc_hash::FxHashMap<TermId, TermId>,
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)
}
Expand All @@ -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),
}
}

Expand All @@ -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
}

Expand All @@ -94,19 +86,20 @@ impl Term {
parameter: Option<SymbolId>,
annotation: Option<TypeId>,
) -> 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
}

Expand All @@ -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
}
}
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/core/traits.rs
Original file line number Diff line number Diff line change
@@ -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) -> &Lambda;
fn apply(&self, id: ApplyId) -> &Apply;
Expand Down
Loading