Skip to main content

flow_span/
symbol.rs

1//! Interned identifiers.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6/// An interned identifier.
7///
8/// A `Symbol` is a four-byte `Copy` index into one [`Interner`]. Equality is an
9/// integer comparison rather than a string comparison, which is what keeps name
10/// resolution cheap when every expression carries a name.
11///
12/// A `Symbol` is deliberately **not** serializable. The index means nothing
13/// without the interner that produced it, so a serialized one would be a number
14/// that reads like a name. Code that must persist an identifier persists the
15/// text.
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Symbol(u32);
18
19impl Symbol {
20    /// Returns the symbol at interner position `index`.
21    ///
22    /// Only [`Interner`] calls this: a symbol built from an arbitrary number
23    /// names whatever happens to sit at that position.
24    const fn from_u32(index: u32) -> Self {
25        Self(index)
26    }
27
28    /// Returns this symbol's interner position.
29    pub const fn as_u32(self) -> u32 {
30        self.0
31    }
32}
33
34impl std::fmt::Debug for Symbol {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "Symbol({})", self.0)
37    }
38}
39
40/// The owner of every [`Symbol`].
41///
42/// The interner is an explicit handle rather than a thread-local or a process
43/// global. Two consequences are worth the extra parameter: a `Symbol` is
44/// meaningful only against the interner that made it, which is a fact the type
45/// system can be made to carry, and nothing in this workspace acquires hidden
46/// shared state to resolve a name.
47#[derive(Default)]
48pub struct Interner {
49    strings: Vec<Arc<str>>,
50    lookup: HashMap<Arc<str>, Symbol>,
51}
52
53impl Interner {
54    /// Returns an interner that holds nothing.
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// Returns the symbol for `text`, interning it if it is new.
60    ///
61    /// # Panics
62    ///
63    /// Panics when the interner already holds `u32::MAX + 1` distinct
64    /// identifiers, more than any source map can hold.
65    pub fn intern(&mut self, text: &str) -> Symbol {
66        if let Some(symbol) = self.lookup.get(text) {
67            return *symbol;
68        }
69
70        let symbol = Symbol::from_u32(
71            u32::try_from(self.strings.len()).expect("interner exceeded the u32 symbol range"),
72        );
73        let shared: Arc<str> = Arc::from(text);
74        self.strings.push(Arc::clone(&shared));
75        self.lookup.insert(shared, symbol);
76        symbol
77    }
78
79    /// Returns the text `symbol` names.
80    ///
81    /// # Panics
82    ///
83    /// Panics when `symbol` came from a different interner, which is a defect
84    /// rather than a condition to recover from.
85    pub fn resolve(&self, symbol: Symbol) -> &str {
86        let position = crate::widen(symbol.as_u32());
87        self.strings
88            .get(position)
89            .unwrap_or_else(|| panic!("symbol {position} does not belong to this interner"))
90    }
91
92    /// Returns the symbol for `text` if it has already been interned.
93    pub fn get(&self, text: &str) -> Option<Symbol> {
94        self.lookup.get(text).copied()
95    }
96
97    /// Returns how many distinct identifiers have been interned.
98    pub fn len(&self) -> usize {
99        self.strings.len()
100    }
101
102    /// Returns whether nothing has been interned.
103    pub fn is_empty(&self) -> bool {
104        self.strings.is_empty()
105    }
106}
107
108impl std::fmt::Debug for Interner {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.debug_struct("Interner")
111            .field("len", &self.strings.len())
112            .finish_non_exhaustive()
113    }
114}
115
116#[cfg(test)]
117#[cfg_attr(coverage, coverage(off))]
118mod tests {
119    use super::{Interner, Symbol};
120
121    #[test]
122    fn interning_one_spelling_twice_yields_one_symbol() {
123        let mut interner = Interner::new();
124        let first = interner.intern("account");
125        let again = interner.intern("account");
126        let other = interner.intern("amount");
127
128        assert_eq!(first, again);
129        assert_ne!(first, other);
130        assert_eq!(interner.len(), 2);
131        assert_eq!(interner.resolve(first), "account");
132        assert_eq!(interner.resolve(other), "amount");
133    }
134
135    #[test]
136    fn a_spelling_can_be_looked_up_without_interning_it() {
137        let mut interner = Interner::new();
138        assert_eq!(interner.get("account"), None);
139
140        let symbol = interner.intern("account");
141        assert_eq!(interner.get("account"), Some(symbol));
142        assert_eq!(interner.len(), 1);
143    }
144
145    #[test]
146    fn an_empty_interner_holds_nothing() {
147        let interner = Interner::new();
148        assert!(interner.is_empty());
149        assert_eq!(interner.len(), 0);
150    }
151
152    #[test]
153    fn symbols_order_hash_and_render_by_position() {
154        let mut interner = Interner::new();
155        let first = interner.intern("a");
156        let second = interner.intern("b");
157
158        assert!(first < second);
159        assert_eq!(format!("{first:?}"), "Symbol(0)");
160        assert_eq!(first.as_u32(), 0);
161
162        let unique: std::collections::HashSet<Symbol> =
163            [first, first, second].into_iter().collect();
164        assert_eq!(unique.len(), 2);
165    }
166
167    #[test]
168    fn an_interner_reports_its_size_in_debug_output() {
169        assert_eq!(format!("{:?}", Interner::new()), "Interner { len: 0, .. }");
170    }
171
172    #[test]
173    #[should_panic(expected = "does not belong to this interner")]
174    fn resolving_a_foreign_symbol_is_a_defect() {
175        let mut mine = Interner::new();
176        let _ = mine.intern("a");
177
178        let mut theirs = Interner::new();
179        let _ = theirs.intern("x");
180        let _ = theirs.intern("y");
181
182        let _ = mine.resolve(theirs.intern("z"));
183    }
184}