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.
1112use std::cell::RefCell;
13use std::num::NonZero;
1415use super::*;
1617/// Handle for a symbol string stored within the Interner.
18#[derive(#[automatically_derived]
impl ::core::marker::Copy for Symbol { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Symbol {
#[inline]
fn clone(&self) -> Symbol {
let _: ::core::clone::AssertParamIsClone<NonZero<u32>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Symbol {
#[inline]
fn eq(&self, other: &Symbol) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Symbol {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {
let _: ::core::cmp::AssertParamIsEq<NonZero<u32>>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Symbol {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
19pub struct Symbol(NonZero<u32>);
2021impl !Sendfor Symbol {}
22impl !Syncfor Symbol {}
2324impl Symbol {
25/// Intern a new `Symbol`
26pub(crate) fn new(string: &str) -> Self {
27INTERNER.with_borrow_mut(|i| i.intern(string))
28 }
2930/// Creates a new `Symbol` for an identifier.
31 ///
32 /// Validates and normalizes before converting it to a symbol.
33pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
34// Fast-path: check if this is a valid ASCII identifier
35if Self::is_valid_ascii_ident(string.as_bytes()) || string == "$crate" {
36if is_raw && !Self::can_be_raw(string) {
37{
::core::panicking::panic_fmt(format_args!("`{0}` cannot be a raw identifier",
string));
};panic!("`{}` cannot be a raw identifier", string);
38 }
39return Self::new(string);
40 }
4142// Slow-path: If the string is already ASCII we're done, otherwise ask
43 // our server to do this for us over RPC.
44 // We don't need to check for identifiers which can't be raw here,
45 // because all of them are ASCII.
46if string.is_ascii() {
47Err(())
48 } else {
49 client::Symbol::normalize_and_validate_ident(string)
50 }
51 .unwrap_or_else(|_| {
::core::panicking::panic_fmt(format_args!("`{0:?}` is not a valid identifier",
string));
}panic!("`{:?}` is not a valid identifier", string))
52 }
5354/// Run a callback with the symbol's string value.
55pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
56INTERNER.with_borrow(|i| f(i.get(self)))
57 }
5859/// Clear out the thread-local symbol interner, making all previously
60 /// created symbols invalid such that `with` will panic when called on them.
61pub(crate) fn invalidate_all() {
62INTERNER.with_borrow_mut(|i| i.clear());
63 }
6465/// Checks if the ident is a valid ASCII identifier.
66 ///
67 /// This is a short-circuit which is cheap to implement within the
68 /// proc-macro client to avoid RPC when creating simple idents, but may
69 /// return `false` for a valid identifier if it contains non-ASCII
70 /// characters.
71fn is_valid_ascii_ident(bytes: &[u8]) -> bool {
72#[allow(non_exhaustive_omitted_patterns)] match bytes.first() {
Some(b'_' | b'a'..=b'z' | b'A'..=b'Z') => true,
_ => false,
}matches!(bytes.first(), Some(b'_' | b'a'..=b'z' | b'A'..=b'Z'))73 && bytes[1..]
74 .iter()
75 .all(|b| #[allow(non_exhaustive_omitted_patterns)] match b {
b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => true,
_ => false,
}matches!(b, b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9'))
76 }
7778// Mimics the behavior of `Symbol::can_be_raw` from `rustc_span`
79fn can_be_raw(string: &str) -> bool {
80 !#[allow(non_exhaustive_omitted_patterns)] match string {
"_" | "super" | "self" | "Self" | "crate" | "$crate" => true,
_ => false,
}matches!(string, "_" | "super" | "self" | "Self" | "crate" | "$crate")81 }
82}
8384impl fmt::Debugfor Symbol {
85fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86self.with(|s| fmt::Debug::fmt(s, f))
87 }
88}
8990impl fmt::Displayfor Symbol {
91fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92self.with(|s| fmt::Display::fmt(s, f))
93 }
94}
9596impl<S> Encode<S> for Symbol {
97fn encode(self, w: &mut Writer, s: &mut S) {
98self.with(|sym| sym.encode(w, s))
99 }
100}
101102impl<S: server::Server> Decode<'_, '_, server::HandleStore<server::MarkedTypes<S>>>
103for Marked<S::Symbol, Symbol>
104{
105fn decode(r: &mut Reader<'_>, s: &mut server::HandleStore<server::MarkedTypes<S>>) -> Self {
106 Mark::mark(S::intern_symbol(<&str>::decode(r, s)))
107 }
108}
109110impl<S: server::Server> Encode<server::HandleStore<server::MarkedTypes<S>>>
111for Marked<S::Symbol, Symbol>
112{
113fn 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}
117118impl<S> Decode<'_, '_, S> for Symbol {
119fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
120Symbol::new(<&str>::decode(r, s))
121 }
122}
123124const INTERNER: ::std::thread::LocalKey<RefCell<Interner>> =
{
#[inline]
fn __rust_std_internal_init_fn() -> RefCell<Interner> {
RefCell::new(Interner {
arena: arena::Arena::new(),
names: fxhash::FxHashMap::default(),
strings: Vec::new(),
sym_base: NonZero::new(1).unwrap(),
})
}
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<RefCell<Interner>>() {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<Interner>,
()> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
} else {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<Interner>, !>
=
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
}
})
}
};thread_local! {
125static INTERNER: RefCell<Interner> = RefCell::new(Interner {
126 arena: arena::Arena::new(),
127 names: fxhash::FxHashMap::default(),
128 strings: Vec::new(),
129// Start with a base of 1 to make sure that `NonZero<u32>` works.
130sym_base: NonZero::new(1).unwrap(),
131 });
132}133134/// Basic interner for a `Symbol`, inspired by the one in `rustc_span`.
135struct Interner {
136 arena: arena::Arena,
137// SAFETY: These `'static` lifetimes are actually references to data owned
138 // by the Arena. This is safe, as we never return them as static references
139 // from `Interner`.
140names: fxhash::FxHashMap<&'static str, Symbol>,
141 strings: Vec<&'static str>,
142// The offset to apply to symbol names stored in the interner. This is used
143 // to ensure that symbol names are not re-used after the interner is
144 // cleared.
145sym_base: NonZero<u32>,
146}
147148impl Interner {
149fn intern(&mut self, string: &str) -> Symbol {
150if let Some(&name) = self.names.get(string) {
151return name;
152 }
153154let name = Symbol(
155self.sym_base
156 .checked_add(self.strings.len() as u32)
157 .expect("`proc_macro` symbol name overflow"),
158 );
159160let string: &str = self.arena.alloc_str(string);
161162// SAFETY: we can extend the arena allocation to `'static` because we
163 // only access these while the arena is still alive.
164let string: &'static str = unsafe { &*(stringas *const str) };
165self.strings.push(string);
166self.names.insert(string, name);
167name168 }
169170/// Reads a symbol's value from the store while it is held.
171fn get(&self, symbol: Symbol) -> &str {
172// NOTE: Subtract out the offset which was added to make the symbol
173 // nonzero and prevent symbol name re-use.
174let name = symbol175 .0
176.get()
177 .checked_sub(self.sym_base.get())
178 .expect("use-after-free of `proc_macro` symbol");
179self.strings[nameas usize]
180 }
181182/// Clear all symbols from the store, invalidating them such that `get` will
183 /// panic if they are accessed in the future.
184fn clear(&mut self) {
185// NOTE: Be careful not to panic here, as we may be called on the client
186 // when a `catch_unwind` isn't installed.
187self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
188self.names.clear();
189self.strings.clear();
190191// SAFETY: This is cleared after the names and strings tables are
192 // cleared out, so no references into the arena should remain.
193self.arena = arena::Arena::new();
194 }
195}