proc_macro/bridge/
symbol.rs1use std::cell::RefCell;
13use std::num::NonZero;
14use std::str;
15
16use super::*;
17
18#[derive(Copy, Clone, PartialEq, Eq, Hash)]
20pub struct Symbol(NonZero<u32>);
21
22impl !Send for Symbol {}
23impl !Sync for Symbol {}
24
25impl Symbol {
26    pub(crate) fn new(string: &str) -> Self {
28        INTERNER.with_borrow_mut(|i| i.intern(string))
29    }
30
31    pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
35        if Self::is_valid_ascii_ident(string.as_bytes()) {
37            if is_raw && !Self::can_be_raw(string) {
38                panic!("`{}` cannot be a raw identifier", string);
39            }
40            return Self::new(string);
41        }
42
43        if string.is_ascii() {
48            Err(())
49        } else {
50            client::Symbol::normalize_and_validate_ident(string)
51        }
52        .unwrap_or_else(|_| panic!("`{:?}` is not a valid identifier", string))
53    }
54
55    pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
57        INTERNER.with_borrow(|i| f(i.get(self)))
58    }
59
60    pub(crate) fn invalidate_all() {
63        INTERNER.with_borrow_mut(|i| i.clear());
64    }
65
66    fn is_valid_ascii_ident(bytes: &[u8]) -> bool {
73        matches!(bytes.first(), Some(b'_' | b'a'..=b'z' | b'A'..=b'Z'))
74            && bytes[1..]
75                .iter()
76                .all(|b| matches!(b, b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9'))
77    }
78
79    fn can_be_raw(string: &str) -> bool {
81        match string {
82            "_" | "super" | "self" | "Self" | "crate" => false,
83            _ => true,
84        }
85    }
86}
87
88impl fmt::Debug for Symbol {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        self.with(|s| fmt::Debug::fmt(s, f))
91    }
92}
93
94impl fmt::Display for Symbol {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        self.with(|s| fmt::Display::fmt(s, f))
97    }
98}
99
100impl<S> Encode<S> for Symbol {
101    fn encode(self, w: &mut Writer, s: &mut S) {
102        self.with(|sym| sym.encode(w, s))
103    }
104}
105
106impl<S: server::Server> DecodeMut<'_, '_, server::HandleStore<server::MarkedTypes<S>>>
107    for Marked<S::Symbol, Symbol>
108{
109    fn decode(r: &mut Reader<'_>, s: &mut server::HandleStore<server::MarkedTypes<S>>) -> Self {
110        Mark::mark(S::intern_symbol(<&str>::decode(r, s)))
111    }
112}
113
114impl<S: server::Server> Encode<server::HandleStore<server::MarkedTypes<S>>>
115    for Marked<S::Symbol, Symbol>
116{
117    fn encode(self, w: &mut Writer, s: &mut server::HandleStore<server::MarkedTypes<S>>) {
118        S::with_symbol_string(&self.unmark(), |sym| sym.encode(w, s))
119    }
120}
121
122impl<S> DecodeMut<'_, '_, S> for Symbol {
123    fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
124        Symbol::new(<&str>::decode(r, s))
125    }
126}
127
128thread_local! {
129    static INTERNER: RefCell<Interner> = RefCell::new(Interner {
130        arena: arena::Arena::new(),
131        names: fxhash::FxHashMap::default(),
132        strings: Vec::new(),
133        sym_base: NonZero::new(1).unwrap(),
135    });
136}
137
138struct Interner {
140    arena: arena::Arena,
141    names: fxhash::FxHashMap<&'static str, Symbol>,
145    strings: Vec<&'static str>,
146    sym_base: NonZero<u32>,
150}
151
152impl Interner {
153    fn intern(&mut self, string: &str) -> Symbol {
154        if let Some(&name) = self.names.get(string) {
155            return name;
156        }
157
158        let name = Symbol(
159            self.sym_base
160                .checked_add(self.strings.len() as u32)
161                .expect("`proc_macro` symbol name overflow"),
162        );
163
164        let string: &str = self.arena.alloc_str(string);
165
166        let string: &'static str = unsafe { &*(string as *const str) };
169        self.strings.push(string);
170        self.names.insert(string, name);
171        name
172    }
173
174    fn get(&self, symbol: Symbol) -> &str {
176        let name = symbol
179            .0
180            .get()
181            .checked_sub(self.sym_base.get())
182            .expect("use-after-free of `proc_macro` symbol");
183        self.strings[name as usize]
184    }
185
186    fn clear(&mut self) {
189        self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
192        self.names.clear();
193        self.strings.clear();
194
195        self.arena = arena::Arena::new();
198    }
199}