Skip to main content

xur_span/
symbol.rs

1//! Interned strings.
2//!
3//! As in rustc, every distinct name is stored once in a global interner and
4//! referred to by a small [`Symbol`] index, so names are `Copy` and cheap to
5//! compare and hash. Interned strings are leaked: they live for the rest of
6//! the process, which is exactly how long a compiler needs them.
7
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::{LazyLock, Mutex, MutexGuard};
11
12use crate::Span;
13
14static INTERNER: LazyLock<Mutex<Interner>> = LazyLock::new(Default::default);
15
16/// An interned string.
17#[derive(Clone, Copy, PartialEq, Eq, Hash)]
18pub struct Symbol(u32);
19
20impl Symbol {
21    pub fn intern(string: &str) -> Self {
22        interner().intern(string)
23    }
24
25    pub fn as_str(self) -> &'static str {
26        interner().strings[self.0 as usize]
27    }
28}
29
30impl fmt::Debug for Symbol {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        fmt::Debug::fmt(self.as_str(), f)
33    }
34}
35
36impl fmt::Display for Symbol {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str(self.as_str())
39    }
40}
41
42/// A name together with where it was written.
43#[derive(Clone, Copy, PartialEq, Eq, Hash)]
44pub struct Ident {
45    pub name: Symbol,
46    pub span: Span,
47}
48
49impl Ident {
50    pub fn new(name: Symbol, span: Span) -> Self {
51        Self { name, span }
52    }
53}
54
55impl fmt::Debug for Ident {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{:?}@{:?}", self.name, self.span)
58    }
59}
60
61impl fmt::Display for Ident {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        fmt::Display::fmt(&self.name, f)
64    }
65}
66
67#[derive(Default)]
68struct Interner {
69    symbols: HashMap<&'static str, Symbol>,
70    strings: Vec<&'static str>,
71}
72
73impl Interner {
74    fn intern(&mut self, string: &str) -> Symbol {
75        if let Some(&symbol) = self.symbols.get(string) {
76            return symbol;
77        }
78        let index = u32::try_from(self.strings.len()).expect("too many interned symbols");
79        let symbol = Symbol(index);
80        let string: &'static str = Box::leak(string.into());
81        self.strings.push(string);
82        self.symbols.insert(string, symbol);
83        symbol
84    }
85}
86
87fn interner() -> MutexGuard<'static, Interner> {
88    // The interner is never left in an inconsistent state, so a panic in
89    // another thread while holding the lock does not invalidate it.
90    INTERNER
91        .lock()
92        .unwrap_or_else(|poisoned| poisoned.into_inner())
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn interning_is_idempotent() {
101        assert_eq!(Symbol::intern("foo"), Symbol::intern("foo"));
102        assert_ne!(Symbol::intern("foo"), Symbol::intern("bar"));
103    }
104
105    #[test]
106    fn round_trips() {
107        assert_eq!(Symbol::intern("α_beta").as_str(), "α_beta");
108    }
109
110    #[test]
111    fn formatting() {
112        let ident = Ident::new(Symbol::intern("main"), Span::new(3, 7));
113        assert_eq!(ident.to_string(), "main");
114        assert_eq!(format!("{ident:?}"), r#""main"@3..7"#);
115    }
116}