1//! Client-side interner used for symbols.
2//!
3//! This is roughly based on the symbol interner from `rustc_span` and the
4//! DroplessArena from `rustc_arena`. It is unfortunately a complete
5//! copy/re-implementation rather than a dependency as it is difficult to depend
6//! on crates from within `proc_macro`, due to it being built at the same time
7//! as `std`.
8//!
9//! If at some point in the future it becomes easier to add dependencies to
10//! proc_macro, this module should probably be removed or simplified.
11
12use std::cell::RefCell;
13use std::num::NonZero;
14use std::str;
15
16use super::*;
17
18/// Handle for a symbol string stored within the Interner.
19#[derive(Copy, Clone, PartialEq, Eq, Hash)]
20pub struct Symbol(NonZero<u32>);
21
22impl !Send for Symbol {}
23impl !Sync for Symbol {}
24
25impl Symbol {
26 /// Intern a new `Symbol`
27 pub(crate) fn new(string: &str) -> Self {
28 INTERNER.with_borrow_mut(|i| i.intern(string))
29 }
30
31 /// Creates a new `Symbol` for an identifier.
32 ///
33 /// Validates and normalizes before converting it to a symbol.
34 pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
35 // Fast-path: check if this is a valid ASCII identifier
36 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 // Slow-path: If the string is already ASCII we're done, otherwise ask
44 // our server to do this for us over RPC.
45 // We don't need to check for identifiers which can't be raw here,
46 // because all of them are ASCII.
47 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 /// Run a callback with the symbol's string value.
56 pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
57 INTERNER.with_borrow(|i| f(i.get(self)))
58 }
59
60 /// Clear out the thread-local symbol interner, making all previously
61 /// created symbols invalid such that `with` will panic when called on them.
62 pub(crate) fn invalidate_all() {
63 INTERNER.with_borrow_mut(|i| i.clear());
64 }
65
66 /// Checks if the ident is a valid ASCII identifier.
67 ///
68 /// This is a short-circuit which is cheap to implement within the
69 /// proc-macro client to avoid RPC when creating simple idents, but may
70 /// return `false` for a valid identifier if it contains non-ASCII
71 /// characters.
72 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 // Mimics the behavior of `Symbol::can_be_raw` from `rustc_span`
80 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: &str| fmt::Debug::fmt(self:s, f))
91 }
92}
93
94impl fmt::Display for Symbol {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 self.with(|s: &str| fmt::Display::fmt(self: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: &str| 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: &str| 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 // Start with a base of 1 to make sure that `NonZero<u32>` works.
134 sym_base: NonZero::new(1).unwrap(),
135 });
136}
137
138/// Basic interner for a `Symbol`, inspired by the one in `rustc_span`.
139struct Interner {
140 arena: arena::Arena,
141 // SAFETY: These `'static` lifetimes are actually references to data owned
142 // by the Arena. This is safe, as we never return them as static references
143 // from `Interner`.
144 names: fxhash::FxHashMap<&'static str, Symbol>,
145 strings: Vec<&'static str>,
146 // The offset to apply to symbol names stored in the interner. This is used
147 // to ensure that symbol names are not re-used after the interner is
148 // cleared.
149 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 // SAFETY: we can extend the arena allocation to `'static` because we
167 // only access these while the arena is still alive.
168 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 /// Reads a symbol's value from the store while it is held.
175 fn get(&self, symbol: Symbol) -> &str {
176 // NOTE: Subtract out the offset which was added to make the symbol
177 // nonzero and prevent symbol name re-use.
178 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 /// Clear all symbols from the store, invalidating them such that `get` will
187 /// panic if they are accessed in the future.
188 fn clear(&mut self) {
189 // NOTE: Be careful not to panic here, as we may be called on the client
190 // when a `catch_unwind` isn't installed.
191 self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
192 self.names.clear();
193 self.strings.clear();
194
195 // SAFETY: This is cleared after the names and strings tables are
196 // cleared out, so no references into the arena should remain.
197 self.arena = arena::Arena::new();
198 }
199}
200