Skip to main content

lisette_syntax/
collections.rs

1//! Collections with private keys: callers can update values without invalidating
2//! a lookup index or the ordering of a compact table.
3
4use std::{borrow::Borrow, hash::Hash, mem, ops::Index, slice, vec};
5
6use rustc_hash::FxHashMap;
7use std::{collections::hash_map, sync::Arc};
8
9#[derive(Debug, Clone, Copy)]
10struct Slot(u32);
11
12const _: () = assert!(size_of::<Slot>() == 4);
13
14/// An associative index over densely packed records. Hash buckets contain only
15/// keys and slots, so growing the index does not move large compiler records.
16#[derive(Debug, Clone)]
17pub struct DenseMap<K, V> {
18    index: FxHashMap<K, Slot>,
19    entries: Vec<(K, V)>,
20}
21
22impl<K, V> Default for DenseMap<K, V> {
23    fn default() -> Self {
24        Self {
25            index: FxHashMap::default(),
26            entries: Vec::new(),
27        }
28    }
29}
30
31impl<K: Eq + Hash + Clone, V> DenseMap<K, V> {
32    pub fn insert_if_absent(&mut self, key: K, value: V) {
33        if !self.index.contains_key(&key) {
34            self.insert(key, value);
35        }
36    }
37    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
38        if let Some(slot) = self.index.get(&key) {
39            return Some(mem::replace(&mut self.entries[slot.0 as usize].1, value));
40        }
41        self.index.insert(
42            key.clone(),
43            Slot(u32::try_from(self.entries.len()).expect("too many indexed records")),
44        );
45        self.entries.push((key, value));
46        None
47    }
48
49    pub fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<&V>
50    where
51        K: Borrow<Q>,
52    {
53        self.index
54            .get(key)
55            .map(|slot| &self.entries[slot.0 as usize].1)
56    }
57
58    pub fn get_mut<Q: Eq + Hash + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
59    where
60        K: Borrow<Q>,
61    {
62        self.index
63            .get(key)
64            .map(|slot| &mut self.entries[slot.0 as usize].1)
65    }
66
67    pub fn contains_key<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> bool
68    where
69        K: Borrow<Q>,
70    {
71        self.index.contains_key(key)
72    }
73
74    pub fn retain(&mut self, mut keep: impl FnMut(&K, &mut V) -> bool) {
75        let mut slot = 0;
76        while slot < self.entries.len() {
77            let (key, value) = &mut self.entries[slot];
78            if keep(key, value) {
79                slot += 1;
80                continue;
81            }
82            let removed = self.entries.swap_remove(slot);
83            self.index.remove(&removed.0);
84            if let Some((moved, _)) = self.entries.get(slot) {
85                *self.index.get_mut(moved).expect("moved record is indexed") = Slot(slot as u32);
86            }
87            // Restore the index before dropping the removed value or invoking
88            // the predicate again, including when either unwinds.
89            drop(removed);
90        }
91    }
92}
93
94impl<K, V> DenseMap<K, V> {
95    pub fn len(&self) -> usize {
96        self.entries.len()
97    }
98    pub fn is_empty(&self) -> bool {
99        self.entries.is_empty()
100    }
101    pub fn iter(&self) -> Entries<'_, K, V> {
102        Entries(self.entries.iter())
103    }
104    pub fn keys(&self) -> impl Iterator<Item = &K> {
105        self.entries.iter().map(|(key, _)| key)
106    }
107    pub fn values(&self) -> impl Iterator<Item = &V> {
108        self.entries.iter().map(|(_, value)| value)
109    }
110    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
111        self.entries.iter_mut().map(|(_, value)| value)
112    }
113}
114
115impl<K: Eq + Hash + Clone, V> Extend<(K, V)> for DenseMap<K, V> {
116    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, entries: I) {
117        let entries = entries.into_iter();
118        self.entries.reserve(entries.size_hint().0);
119        self.index.reserve(entries.size_hint().0);
120        for (key, value) in entries {
121            self.insert(key, value);
122        }
123    }
124}
125
126impl<K: Eq + Hash + Clone, V> FromIterator<(K, V)> for DenseMap<K, V> {
127    fn from_iter<I: IntoIterator<Item = (K, V)>>(entries: I) -> Self {
128        let mut map = Self::default();
129        map.extend(entries);
130        map
131    }
132}
133
134impl<K: Eq + Hash + Clone + Borrow<Q>, V, Q: Eq + Hash + ?Sized> Index<&Q> for DenseMap<K, V> {
135    type Output = V;
136    fn index(&self, key: &Q) -> &V {
137        self.get(key).expect("key must be present")
138    }
139}
140
141impl<K, V> IntoIterator for DenseMap<K, V> {
142    type Item = (K, V);
143    type IntoIter = vec::IntoIter<(K, V)>;
144    fn into_iter(self) -> Self::IntoIter {
145        self.entries.into_iter()
146    }
147}
148
149impl<'a, K, V> IntoIterator for &'a DenseMap<K, V> {
150    type Item = (&'a K, &'a V);
151    type IntoIter = Entries<'a, K, V>;
152    fn into_iter(self) -> Self::IntoIter {
153        self.iter()
154    }
155}
156
157pub struct Entries<'a, K, V>(slice::Iter<'a, (K, V)>);
158
159impl<'a, K, V> Iterator for Entries<'a, K, V> {
160    type Item = (&'a K, &'a V);
161    fn next(&mut self) -> Option<Self::Item> {
162        self.0.next().map(|(key, value)| (key, value))
163    }
164    fn size_hint(&self) -> (usize, Option<usize>) {
165        self.0.size_hint()
166    }
167}
168impl<K, V> ExactSizeIterator for Entries<'_, K, V> {}
169
170/// A compact lexical-frame dictionary. Replacement retains one entry per key;
171/// reverse lookup favors recently introduced locals without a hash allocation.
172#[derive(Debug, Clone)]
173pub struct FlatMap<K, V>(Vec<(K, V)>);
174
175impl<K, V> Default for FlatMap<K, V> {
176    fn default() -> Self {
177        Self(Vec::new())
178    }
179}
180
181impl<K: Eq, V> FlatMap<K, V> {
182    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
183        if let Some(existing) = self.get_mut(&key) {
184            return Some(mem::replace(existing, value));
185        }
186        self.0.push((key, value));
187        None
188    }
189    pub fn insert_if_absent(&mut self, key: K, value: V) {
190        if self.get(&key).is_none() {
191            self.0.push((key, value));
192        }
193    }
194    pub fn get<Q: Eq + ?Sized>(&self, key: &Q) -> Option<&V>
195    where
196        K: Borrow<Q>,
197    {
198        self.0
199            .iter()
200            .rev()
201            .find(|(candidate, _)| candidate.borrow() == key)
202            .map(|(_, value)| value)
203    }
204    pub fn get_mut<Q: Eq + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
205    where
206        K: Borrow<Q>,
207    {
208        self.0
209            .iter_mut()
210            .rev()
211            .find(|(candidate, _)| <K as Borrow<Q>>::borrow(candidate) == key)
212            .map(|(_, value)| value)
213    }
214    pub fn iter(&self) -> Entries<'_, K, V> {
215        Entries(self.0.iter())
216    }
217    pub fn keys(&self) -> impl Iterator<Item = &K> {
218        self.0.iter().map(|(key, _)| key)
219    }
220    pub fn values(&self) -> impl Iterator<Item = &V> {
221        self.0.iter().map(|(_, value)| value)
222    }
223}
224
225/// Read-mostly dictionaries share their storage until a value changes. Empty
226/// dictionaries allocate nothing. Hash iteration order remains the same as the
227/// producer's table because emission and diagnostic ordering depend on it.
228#[derive(Debug, Clone)]
229pub struct SharedMap<K, V>(Option<Arc<FxHashMap<K, V>>>);
230
231impl<K, V> Default for SharedMap<K, V> {
232    fn default() -> Self {
233        Self(None)
234    }
235}
236
237impl<K: Eq + Hash + Clone, V: Clone> SharedMap<K, V> {
238    fn make_mut(&mut self) -> &mut FxHashMap<K, V> {
239        Arc::make_mut(self.0.get_or_insert_with(|| Arc::new(FxHashMap::default())))
240    }
241    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
242        self.make_mut().insert(key, value)
243    }
244    pub fn insert_if_absent(&mut self, key: K, value: V) {
245        if !self.contains_key(&key) {
246            self.make_mut().entry(key).or_insert(value);
247        }
248    }
249    pub fn get_mut<Q: Eq + Hash + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
250    where
251        K: Borrow<Q>,
252    {
253        if !self.contains_key(key) {
254            return None;
255        }
256        self.make_mut().get_mut(key)
257    }
258    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
259        self.0
260            .iter_mut()
261            .flat_map(|map| Arc::make_mut(map).values_mut())
262    }
263}
264
265impl<K: Eq + Hash, V> SharedMap<K, V> {
266    pub fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<&V>
267    where
268        K: Borrow<Q>,
269    {
270        self.0.as_ref()?.get(key)
271    }
272    pub fn get_key_value<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
273    where
274        K: Borrow<Q>,
275    {
276        self.0.as_ref()?.get_key_value(key)
277    }
278    pub fn contains_key<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> bool
279    where
280        K: Borrow<Q>,
281    {
282        self.get(key).is_some()
283    }
284}
285
286impl<K, V> SharedMap<K, V> {
287    pub fn len(&self) -> usize {
288        self.0.as_ref().map_or(0, |map| map.len())
289    }
290    pub fn is_empty(&self) -> bool {
291        self.len() == 0
292    }
293    pub fn iter(&self) -> SharedEntries<'_, K, V> {
294        SharedEntries(self.0.as_ref().map(|map| map.iter()))
295    }
296    pub fn keys(&self) -> impl Iterator<Item = &K> {
297        self.iter().map(|(key, _)| key)
298    }
299    pub fn values(&self) -> impl Iterator<Item = &V> {
300        self.iter().map(|(_, value)| value)
301    }
302    pub fn into_values(self) -> impl Iterator<Item = V>
303    where
304        K: Clone,
305        V: Clone,
306    {
307        self.into_iter().map(|(_, value)| value)
308    }
309}
310
311impl<K: Eq + Hash, V: PartialEq> PartialEq for SharedMap<K, V> {
312    fn eq(&self, other: &Self) -> bool {
313        self.len() == other.len()
314            && self
315                .iter()
316                .all(|(key, value)| other.get(key) == Some(value))
317    }
318}
319
320impl<K: Eq + Hash, V> FromIterator<(K, V)> for SharedMap<K, V> {
321    fn from_iter<I: IntoIterator<Item = (K, V)>>(entries: I) -> Self {
322        let map: FxHashMap<_, _> = entries.into_iter().collect();
323        if map.is_empty() {
324            Self::default()
325        } else {
326            Self(Some(Arc::new(map)))
327        }
328    }
329}
330
331impl<K: Clone, V: Clone> IntoIterator for SharedMap<K, V> {
332    type Item = (K, V);
333    type IntoIter = hash_map::IntoIter<K, V>;
334    fn into_iter(self) -> Self::IntoIter {
335        self.0
336            .map(Arc::unwrap_or_clone)
337            .unwrap_or_default()
338            .into_iter()
339    }
340}
341impl<'a, K, V> IntoIterator for &'a SharedMap<K, V> {
342    type Item = (&'a K, &'a V);
343    type IntoIter = SharedEntries<'a, K, V>;
344    fn into_iter(self) -> Self::IntoIter {
345        self.iter()
346    }
347}
348impl<K: Eq + Hash + Borrow<Q>, V, Q: Eq + Hash + ?Sized> Index<&Q> for SharedMap<K, V> {
349    type Output = V;
350    fn index(&self, key: &Q) -> &V {
351        self.get(key).expect("key must be present")
352    }
353}
354
355pub struct SharedEntries<'a, K, V>(Option<hash_map::Iter<'a, K, V>>);
356impl<'a, K, V> Iterator for SharedEntries<'a, K, V> {
357    type Item = (&'a K, &'a V);
358    fn next(&mut self) -> Option<Self::Item> {
359        self.0.as_mut()?.next()
360    }
361    fn size_hint(&self) -> (usize, Option<usize>) {
362        self.0.as_ref().map_or((0, Some(0)), Iterator::size_hint)
363    }
364}
365impl<K, V> ExactSizeIterator for SharedEntries<'_, K, V> {}
366
367#[cfg(feature = "serde")]
368mod serde_impl {
369    use super::{Arc, FxHashMap, SharedMap};
370    use serde::{Deserialize, Deserializer, Serialize, Serializer};
371    use std::hash::Hash;
372
373    impl<K: Serialize, V: Serialize> Serialize for SharedMap<K, V> {
374        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
375            serializer.collect_map(self.iter())
376        }
377    }
378    impl<'de, K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>> Deserialize<'de>
379        for SharedMap<K, V>
380    {
381        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
382            let map = FxHashMap::deserialize(deserializer)?;
383            Ok(if map.is_empty() {
384                SharedMap::default()
385            } else {
386                SharedMap(Some(Arc::new(map)))
387            })
388        }
389    }
390}
391
392#[cfg(target_pointer_width = "64")]
393const _: () = assert!(size_of::<SharedMap<u32, u32>>() == 8);
394
395#[cfg(test)]
396mod tests;