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