flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
Documentation
//! Interned identifiers.

use std::collections::HashMap;
use std::sync::Arc;

/// An interned identifier.
///
/// A `Symbol` is a four-byte `Copy` index into one [`Interner`]. Equality is an
/// integer comparison rather than a string comparison, which is what keeps name
/// resolution cheap when every expression carries a name.
///
/// A `Symbol` is deliberately **not** serializable. The index means nothing
/// without the interner that produced it, so a serialized one would be a number
/// that reads like a name. Code that must persist an identifier persists the
/// text.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);

impl Symbol {
    /// Returns the symbol at interner position `index`.
    ///
    /// Only [`Interner`] calls this: a symbol built from an arbitrary number
    /// names whatever happens to sit at that position.
    const fn from_u32(index: u32) -> Self {
        Self(index)
    }

    /// Returns this symbol's interner position.
    pub const fn as_u32(self) -> u32 {
        self.0
    }
}

impl std::fmt::Debug for Symbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Symbol({})", self.0)
    }
}

/// The owner of every [`Symbol`].
///
/// The interner is an explicit handle rather than a thread-local or a process
/// global. Two consequences are worth the extra parameter: a `Symbol` is
/// meaningful only against the interner that made it, which is a fact the type
/// system can be made to carry, and nothing in this workspace acquires hidden
/// shared state to resolve a name.
#[derive(Default)]
pub struct Interner {
    strings: Vec<Arc<str>>,
    lookup: HashMap<Arc<str>, Symbol>,
}

impl Interner {
    /// Returns an interner that holds nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the symbol for `text`, interning it if it is new.
    ///
    /// # Panics
    ///
    /// Panics when the interner already holds `u32::MAX + 1` distinct
    /// identifiers, more than any source map can hold.
    pub fn intern(&mut self, text: &str) -> Symbol {
        if let Some(symbol) = self.lookup.get(text) {
            return *symbol;
        }

        let symbol = Symbol::from_u32(
            u32::try_from(self.strings.len()).expect("interner exceeded the u32 symbol range"),
        );
        let shared: Arc<str> = Arc::from(text);
        self.strings.push(Arc::clone(&shared));
        self.lookup.insert(shared, symbol);
        symbol
    }

    /// Returns the text `symbol` names.
    ///
    /// # Panics
    ///
    /// Panics when `symbol` came from a different interner, which is a defect
    /// rather than a condition to recover from.
    pub fn resolve(&self, symbol: Symbol) -> &str {
        let position = crate::widen(symbol.as_u32());
        self.strings
            .get(position)
            .unwrap_or_else(|| panic!("symbol {position} does not belong to this interner"))
    }

    /// Returns the symbol for `text` if it has already been interned.
    pub fn get(&self, text: &str) -> Option<Symbol> {
        self.lookup.get(text).copied()
    }

    /// Returns how many distinct identifiers have been interned.
    pub fn len(&self) -> usize {
        self.strings.len()
    }

    /// Returns whether nothing has been interned.
    pub fn is_empty(&self) -> bool {
        self.strings.is_empty()
    }
}

impl std::fmt::Debug for Interner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Interner")
            .field("len", &self.strings.len())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{Interner, Symbol};

    #[test]
    fn interning_one_spelling_twice_yields_one_symbol() {
        let mut interner = Interner::new();
        let first = interner.intern("account");
        let again = interner.intern("account");
        let other = interner.intern("amount");

        assert_eq!(first, again);
        assert_ne!(first, other);
        assert_eq!(interner.len(), 2);
        assert_eq!(interner.resolve(first), "account");
        assert_eq!(interner.resolve(other), "amount");
    }

    #[test]
    fn a_spelling_can_be_looked_up_without_interning_it() {
        let mut interner = Interner::new();
        assert_eq!(interner.get("account"), None);

        let symbol = interner.intern("account");
        assert_eq!(interner.get("account"), Some(symbol));
        assert_eq!(interner.len(), 1);
    }

    #[test]
    fn an_empty_interner_holds_nothing() {
        let interner = Interner::new();
        assert!(interner.is_empty());
        assert_eq!(interner.len(), 0);
    }

    #[test]
    fn symbols_order_hash_and_render_by_position() {
        let mut interner = Interner::new();
        let first = interner.intern("a");
        let second = interner.intern("b");

        assert!(first < second);
        assert_eq!(format!("{first:?}"), "Symbol(0)");
        assert_eq!(first.as_u32(), 0);

        let unique: std::collections::HashSet<Symbol> =
            [first, first, second].into_iter().collect();
        assert_eq!(unique.len(), 2);
    }

    #[test]
    fn an_interner_reports_its_size_in_debug_output() {
        assert_eq!(format!("{:?}", Interner::new()), "Interner { len: 0, .. }");
    }

    #[test]
    #[should_panic(expected = "does not belong to this interner")]
    fn resolving_a_foreign_symbol_is_a_defect() {
        let mut mine = Interner::new();
        let _ = mine.intern("a");

        let mut theirs = Interner::new();
        let _ = theirs.intern("x");
        let _ = theirs.intern("y");

        let _ = mine.resolve(theirs.intern("z"));
    }
}