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/// until the frame grows past `FLAT_MAP_INDEX_THRESHOLD` entries.
173#[derive(Debug, Clone)]
174pub struct FlatMap<K, V> {
175    entries: Vec<(K, V)>,
176    index: Option<FxHashMap<K, Slot>>,
177}
178
179const FLAT_MAP_INDEX_THRESHOLD: usize = 16;
180
181impl<K, V> Default for FlatMap<K, V> {
182    fn default() -> Self {
183        Self {
184            entries: Vec::new(),
185            index: None,
186        }
187    }
188}
189
190impl<K: Eq + Hash + Clone, V> FlatMap<K, V> {
191    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
192        if let Some(existing) = self.get_mut(&key) {
193            return Some(mem::replace(existing, value));
194        }
195        self.push(key, value);
196        None
197    }
198    pub fn insert_if_absent(&mut self, key: K, value: V) {
199        if self.get(&key).is_none() {
200            self.push(key, value);
201        }
202    }
203    pub fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<&V>
204    where
205        K: Borrow<Q>,
206    {
207        self.position(key).map(|position| &self.entries[position].1)
208    }
209    pub fn get_mut<Q: Eq + Hash + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
210    where
211        K: Borrow<Q>,
212    {
213        self.position(key)
214            .map(|position| &mut self.entries[position].1)
215    }
216    pub fn iter(&self) -> Entries<'_, K, V> {
217        Entries(self.entries.iter())
218    }
219    pub fn keys(&self) -> impl Iterator<Item = &K> {
220        self.entries.iter().map(|(key, _)| key)
221    }
222    pub fn values(&self) -> impl Iterator<Item = &V> {
223        self.entries.iter().map(|(_, value)| value)
224    }
225
226    fn position<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<usize>
227    where
228        K: Borrow<Q>,
229    {
230        match &self.index {
231            Some(index) => index.get(key).map(|slot| slot.0 as usize),
232            None => self
233                .entries
234                .iter()
235                .rposition(|(candidate, _)| candidate.borrow() == key),
236        }
237    }
238
239    fn push(&mut self, key: K, value: V) {
240        let slot = Slot(u32::try_from(self.entries.len()).expect("too many flat map entries"));
241        if let Some(index) = &mut self.index {
242            index.insert(key.clone(), slot);
243        } else if self.entries.len() == FLAT_MAP_INDEX_THRESHOLD {
244            let mut index: FxHashMap<K, Slot> = self
245                .entries
246                .iter()
247                .enumerate()
248                .map(|(position, (candidate, _))| (candidate.clone(), Slot(position as u32)))
249                .collect();
250            index.insert(key.clone(), slot);
251            self.index = Some(index);
252        }
253        self.entries.push((key, value));
254    }
255}
256
257/// Read-mostly dictionaries share their storage until a value changes. Empty
258/// dictionaries allocate nothing. Hash iteration order remains the same as the
259/// producer's table because emission and diagnostic ordering depend on it.
260#[derive(Debug, Clone)]
261pub struct SharedMap<K, V>(Option<Arc<FxHashMap<K, V>>>);
262
263impl<K, V> Default for SharedMap<K, V> {
264    fn default() -> Self {
265        Self(None)
266    }
267}
268
269impl<K: Eq + Hash + Clone, V: Clone> SharedMap<K, V> {
270    fn make_mut(&mut self) -> &mut FxHashMap<K, V> {
271        Arc::make_mut(self.0.get_or_insert_with(|| Arc::new(FxHashMap::default())))
272    }
273    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
274        self.make_mut().insert(key, value)
275    }
276    pub fn insert_if_absent(&mut self, key: K, value: V) {
277        if !self.contains_key(&key) {
278            self.make_mut().entry(key).or_insert(value);
279        }
280    }
281    pub fn get_mut<Q: Eq + Hash + ?Sized>(&mut self, key: &Q) -> Option<&mut V>
282    where
283        K: Borrow<Q>,
284    {
285        if !self.contains_key(key) {
286            return None;
287        }
288        self.make_mut().get_mut(key)
289    }
290    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
291        self.0
292            .iter_mut()
293            .flat_map(|map| Arc::make_mut(map).values_mut())
294    }
295}
296
297impl<K: Eq + Hash, V> SharedMap<K, V> {
298    pub fn get<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<&V>
299    where
300        K: Borrow<Q>,
301    {
302        self.0.as_ref()?.get(key)
303    }
304    pub fn get_key_value<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
305    where
306        K: Borrow<Q>,
307    {
308        self.0.as_ref()?.get_key_value(key)
309    }
310    pub fn contains_key<Q: Eq + Hash + ?Sized>(&self, key: &Q) -> bool
311    where
312        K: Borrow<Q>,
313    {
314        self.get(key).is_some()
315    }
316}
317
318impl<K, V> SharedMap<K, V> {
319    pub fn len(&self) -> usize {
320        self.0.as_ref().map_or(0, |map| map.len())
321    }
322    pub fn is_empty(&self) -> bool {
323        self.len() == 0
324    }
325    pub fn iter(&self) -> SharedEntries<'_, K, V> {
326        SharedEntries(self.0.as_ref().map(|map| map.iter()))
327    }
328    pub fn keys(&self) -> impl Iterator<Item = &K> {
329        self.iter().map(|(key, _)| key)
330    }
331    pub fn values(&self) -> impl Iterator<Item = &V> {
332        self.iter().map(|(_, value)| value)
333    }
334    pub fn into_values(self) -> impl Iterator<Item = V>
335    where
336        K: Clone,
337        V: Clone,
338    {
339        self.into_iter().map(|(_, value)| value)
340    }
341}
342
343impl<K: Eq + Hash, V: PartialEq> PartialEq for SharedMap<K, V> {
344    fn eq(&self, other: &Self) -> bool {
345        self.len() == other.len()
346            && self
347                .iter()
348                .all(|(key, value)| other.get(key) == Some(value))
349    }
350}
351
352impl<K: Eq + Hash, V> FromIterator<(K, V)> for SharedMap<K, V> {
353    fn from_iter<I: IntoIterator<Item = (K, V)>>(entries: I) -> Self {
354        let map: FxHashMap<_, _> = entries.into_iter().collect();
355        if map.is_empty() {
356            Self::default()
357        } else {
358            Self(Some(Arc::new(map)))
359        }
360    }
361}
362
363impl<K: Clone, V: Clone> IntoIterator for SharedMap<K, V> {
364    type Item = (K, V);
365    type IntoIter = hash_map::IntoIter<K, V>;
366    fn into_iter(self) -> Self::IntoIter {
367        self.0
368            .map(Arc::unwrap_or_clone)
369            .unwrap_or_default()
370            .into_iter()
371    }
372}
373impl<'a, K, V> IntoIterator for &'a SharedMap<K, V> {
374    type Item = (&'a K, &'a V);
375    type IntoIter = SharedEntries<'a, K, V>;
376    fn into_iter(self) -> Self::IntoIter {
377        self.iter()
378    }
379}
380impl<K: Eq + Hash + Borrow<Q>, V, Q: Eq + Hash + ?Sized> Index<&Q> for SharedMap<K, V> {
381    type Output = V;
382    fn index(&self, key: &Q) -> &V {
383        self.get(key).expect("key must be present")
384    }
385}
386
387pub struct SharedEntries<'a, K, V>(Option<hash_map::Iter<'a, K, V>>);
388impl<'a, K, V> Iterator for SharedEntries<'a, K, V> {
389    type Item = (&'a K, &'a V);
390    fn next(&mut self) -> Option<Self::Item> {
391        self.0.as_mut()?.next()
392    }
393    fn size_hint(&self) -> (usize, Option<usize>) {
394        self.0.as_ref().map_or((0, Some(0)), Iterator::size_hint)
395    }
396}
397impl<K, V> ExactSizeIterator for SharedEntries<'_, K, V> {}
398
399#[cfg(feature = "serde")]
400mod serde_impl {
401    use super::{Arc, FxHashMap, SharedMap};
402    use serde::{Deserialize, Deserializer, Serialize, Serializer};
403    use std::hash::Hash;
404
405    impl<K: Serialize, V: Serialize> Serialize for SharedMap<K, V> {
406        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
407            serializer.collect_map(self.iter())
408        }
409    }
410    impl<'de, K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>> Deserialize<'de>
411        for SharedMap<K, V>
412    {
413        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
414            let map = FxHashMap::deserialize(deserializer)?;
415            Ok(if map.is_empty() {
416                SharedMap::default()
417            } else {
418                SharedMap(Some(Arc::new(map)))
419            })
420        }
421    }
422}
423
424#[cfg(target_pointer_width = "64")]
425const _: () = assert!(size_of::<SharedMap<u32, u32>>() == 8);
426
427#[cfg(test)]
428mod tests;