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::fmt;
14use std::num::NonZero;
1516use crate::bridge::{Buffer, Decode, Encode, Mark, arena, client, fxhash, server};
1718/// Handle for a symbol string stored within the Interner.
19#[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_fields_are_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)]
20pub struct Symbol(NonZero<u32>);
2122impl !Sendfor Symbol {}
23impl !Syncfor Symbol {}
2425impl Symbol {
26/// Intern a new `Symbol`
27pub(crate) fn new(string: &str) -> Self {
28INTERNER.with_borrow_mut(|i| i.intern(string))
29 }
3031/// Creates a new `Symbol` for an identifier.
32 ///
33 /// Validates and normalizes before converting it to a symbol.
34pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
35// Fast-path: check if this is a valid ASCII identifier
36if Self::is_valid_ascii_ident(string.as_bytes()) || string == "$crate" {
37if is_raw && !Self::can_be_raw(string) {
38{
::core::panicking::panic_fmt(format_args!("`{0}` cannot be a raw identifier",
string));
};panic!("`{}` cannot be a raw identifier", string);
39 }
40return Self::new(string);
41 }
4243// 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.
47if string.is_ascii() {
48Err(())
49 } else {
50 client::Methods::symbol_normalize_and_validate_ident(string)
51 }
52 .unwrap_or_else(|_| {
::core::panicking::panic_fmt(format_args!("`{0:?}` is not a valid identifier",
string));
}panic!("`{:?}` is not a valid identifier", string))
53 }
5455/// Run a callback with the symbol's string value.
56pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
57INTERNER.with_borrow(|i| f(i.get(self)))
58 }
5960/// Clear out the thread-local symbol interner, making all previously
61 /// created symbols invalid such that `with` will panic when called on them.
62pub(crate) fn invalidate_all() {
63INTERNER.with_borrow_mut(|i| i.clear());
64 }
6566/// 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.
72fn is_valid_ascii_ident(bytes: &[u8]) -> bool {
73#[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'))74 && bytes[1..]
75 .iter()
76 .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'))
77 }
7879// Mimics the behavior of `Symbol::can_be_raw` from `rustc_span`
80fn can_be_raw(string: &str) -> bool {
81 !#[allow(non_exhaustive_omitted_patterns)] match string {
"_" | "super" | "self" | "Self" | "crate" | "$crate" => true,
_ => false,
}matches!(string, "_" | "super" | "self" | "Self" | "crate" | "$crate")82 }
83}
8485impl fmt::Debugfor Symbol {
86fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87self.with(|s| fmt::Debug::fmt(s, f))
88 }
89}
9091impl fmt::Displayfor Symbol {
92fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93self.with(|s| fmt::Display::fmt(s, f))
94 }
95}
9697impl<S> Encode<S> for Symbol {
98fn encode(self, w: &mut Buffer, s: &mut S) {
99self.with(|sym| sym.encode(w, s))
100 }
101}
102103impl<S: server::Server> Decode<'_, '_, server::HandleStore<S>> for server::MarkedSymbol<S> {
104fn decode(r: &mut &[u8], s: &mut server::HandleStore<S>) -> Self {
105 Mark::mark(S::intern_symbol(<&str>::decode(r, s)))
106 }
107}
108109impl<S: server::Server> Encode<server::HandleStore<S>> for server::MarkedSymbol<S> {
110fn encode(self, w: &mut Buffer, s: &mut server::HandleStore<S>) {
111 S::with_symbol_string(&self.unmark(), |sym| sym.encode(w, s))
112 }
113}
114115impl<S> Decode<'_, '_, S> for Symbol {
116fn decode(r: &mut &[u8], s: &mut S) -> Self {
117Symbol::new(<&str>::decode(r, s))
118 }
119}
120121const 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! {
122static INTERNER: RefCell<Interner> = RefCell::new(Interner {
123 arena: arena::Arena::new(),
124 names: fxhash::FxHashMap::default(),
125 strings: Vec::new(),
126// Start with a base of 1 to make sure that `NonZero<u32>` works.
127sym_base: NonZero::new(1).unwrap(),
128 });
129}130131/// Basic interner for a `Symbol`, inspired by the one in `rustc_span`.
132struct Interner {
133 arena: arena::Arena,
134// SAFETY: These `'static` lifetimes are actually references to data owned
135 // by the Arena. This is safe, as we never return them as static references
136 // from `Interner`.
137names: fxhash::FxHashMap<&'static str, Symbol>,
138 strings: Vec<&'static str>,
139// The offset to apply to symbol names stored in the interner. This is used
140 // to ensure that symbol names are not re-used after the interner is
141 // cleared.
142sym_base: NonZero<u32>,
143}
144145impl Interner {
146fn intern(&mut self, string: &str) -> Symbol {
147if let Some(&name) = self.names.get(string) {
148return name;
149 }
150151let name = Symbol(
152self.sym_base
153 .checked_add(self.strings.len() as u32)
154 .expect("`proc_macro` symbol name overflow"),
155 );
156157let string: &str = self.arena.alloc_str(string);
158159// SAFETY: we can extend the arena allocation to `'static` because we
160 // only access these while the arena is still alive.
161let string: &'static str = unsafe { &*(stringas *const str) };
162self.strings.push(string);
163self.names.insert(string, name);
164name165 }
166167/// Reads a symbol's value from the store while it is held.
168fn get(&self, symbol: Symbol) -> &str {
169// NOTE: Subtract out the offset which was added to make the symbol
170 // nonzero and prevent symbol name re-use.
171let name = symbol172 .0
173.get()
174 .checked_sub(self.sym_base.get())
175 .expect("use-after-free of `proc_macro` symbol");
176self.strings[nameas usize]
177 }
178179/// Clear all symbols from the store, invalidating them such that `get` will
180 /// panic if they are accessed in the future.
181fn clear(&mut self) {
182// NOTE: Be careful not to panic here, as we may be called on the client
183 // when a `catch_unwind` isn't installed.
184self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
185self.names.clear();
186self.strings.clear();
187188// SAFETY: This is cleared after the names and strings tables are
189 // cleared out, so no references into the arena should remain.
190self.arena = arena::Arena::new();
191 }
192}