Skip to main content

foundry_evm_symbolic/runtime/expr/
hashcons.rs

1use alloy_primitives::map::foldhash::fast::FixedState;
2use hashbrown::{HashTable, hash_table::Entry};
3use std::{
4    cmp::Ordering,
5    fmt,
6    hash::{BuildHasher, Hash, Hasher},
7    sync::{Arc, Weak},
8};
9
10/// Shared handle for a hash-consed value.
11///
12/// Equality is pointer equality only. Hashing writes the cached structural hash
13/// instead of walking the value.
14pub(in crate::runtime) struct HashConsed<T> {
15    inner: Arc<HashConsedInner<T>>,
16}
17
18struct HashConsedInner<T> {
19    hash: u64,
20    value: T,
21}
22
23impl<T> HashConsed<T> {
24    #[inline]
25    pub(in crate::runtime::expr) fn stable_hash_cmp(&self, other: &Self) -> Ordering {
26        self.inner.hash.cmp(&other.inner.hash)
27    }
28
29    /// Orders nodes within one hash-consing context without inspecting or rendering their value.
30    ///
31    /// The cached structural hash handles the common case. Pointer identity is only a tie-breaker
32    /// for distinct nodes with the same hash; structurally equal values share one node.
33    #[inline]
34    pub(in crate::runtime::expr) fn identity_cmp(&self, other: &Self) -> Ordering {
35        self.stable_hash_cmp(other).then_with(|| {
36            let left = Arc::as_ptr(&self.inner);
37            let right = Arc::as_ptr(&other.inner);
38            left.cmp(&right)
39        })
40    }
41
42    #[inline]
43    pub(in crate::runtime) fn value(&self) -> &T {
44        &self.inner.value
45    }
46}
47
48impl<T> Clone for HashConsed<T> {
49    #[inline]
50    fn clone(&self) -> Self {
51        Self { inner: self.inner.clone() }
52    }
53}
54
55impl<T> PartialEq for HashConsed<T> {
56    #[inline]
57    fn eq(&self, other: &Self) -> bool {
58        Arc::ptr_eq(&self.inner, &other.inner)
59    }
60}
61
62impl<T> Eq for HashConsed<T> {}
63
64impl<T> Hash for HashConsed<T> {
65    #[inline]
66    fn hash<H: Hasher>(&self, state: &mut H) {
67        self.inner.hash.hash(state);
68    }
69}
70
71impl<T: fmt::Debug> fmt::Debug for HashConsed<T> {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        self.value().fmt(f)
74    }
75}
76
77const MIN_GC_THRESHOLD: usize = 1024;
78
79/// Hash-consing table for sharing structurally equal immutable values.
80///
81/// The table stores weak references so interned values disappear when the rest of
82/// the symbolic state stops using them. `make` removes dead entries encountered
83/// during lookup and periodically sweeps distinct dead values before they can
84/// grow the table without bound.
85pub(in crate::runtime) struct HashCons<T> {
86    table: HashTable<HashConsEntry<T>>,
87    hash_builder: FixedState,
88    gc_threshold: usize,
89}
90
91struct HashConsEntry<T> {
92    hash: u64,
93    value: Weak<HashConsedInner<T>>,
94}
95
96impl<T> HashConsEntry<T> {
97    const fn hash(&self) -> u64 {
98        self.hash
99    }
100}
101
102impl<T> HashCons<T> {
103    pub(in crate::runtime) fn new() -> Self {
104        Self {
105            table: HashTable::new(),
106            hash_builder: FixedState::default(),
107            gc_threshold: MIN_GC_THRESHOLD,
108        }
109    }
110
111    fn hash<Q: Hash + ?Sized>(&self, value: &Q) -> u64 {
112        self.hash_builder.hash_one(value)
113    }
114}
115
116impl<T: Eq + Hash> HashCons<T> {
117    pub(in crate::runtime) fn make(&mut self, value: T) -> HashConsed<T> {
118        if self.table.len() >= self.gc_threshold {
119            self.table.retain(|entry| entry.value.strong_count() != 0);
120            self.gc_threshold = self.table.len().saturating_mul(2).max(MIN_GC_THRESHOLD);
121        }
122
123        let hash = self.hash(&value);
124        loop {
125            let mut found = None;
126            let mut matched_dead_entry = false;
127            match self.table.entry(
128                hash,
129                |entry| {
130                    if entry.hash() != hash {
131                        return false;
132                    }
133                    match entry.value.upgrade() {
134                        Some(existing) if existing.value == value => {
135                            found = Some(existing);
136                            true
137                        }
138                        None => {
139                            matched_dead_entry = true;
140                            true
141                        }
142                        Some(_) => false,
143                    }
144                },
145                HashConsEntry::hash,
146            ) {
147                Entry::Occupied(entry) => {
148                    if let Some(inner) = found {
149                        return HashConsed { inner };
150                    }
151                    debug_assert!(matched_dead_entry);
152                    let _ = entry.remove();
153                }
154                Entry::Vacant(entry) => {
155                    let inner = Arc::new(HashConsedInner { hash, value });
156                    entry.insert(HashConsEntry { hash, value: Arc::downgrade(&inner) });
157                    return HashConsed { inner };
158                }
159            }
160        }
161    }
162}