use std::cell::RefCell;
use std::num::NonZeroU32;
use std::str;
use super::*;
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Symbol(NonZeroU32);
impl !Send for Symbol {}
impl !Sync for Symbol {}
impl Symbol {
pub(crate) fn new(string: &str) -> Self {
INTERNER.with_borrow_mut(|i| i.intern(string))
}
pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
if Self::is_valid_ascii_ident(string.as_bytes()) {
if is_raw && !Self::can_be_raw(string) {
panic!("`{}` cannot be a raw identifier", string);
}
return Self::new(string);
}
if string.is_ascii() {
Err(())
} else {
client::Symbol::normalize_and_validate_ident(string)
}
.unwrap_or_else(|_| panic!("`{:?}` is not a valid identifier", string))
}
pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
INTERNER.with_borrow(|i| f(i.get(self)))
}
pub(crate) fn invalidate_all() {
INTERNER.with_borrow_mut(|i| i.clear());
}
fn is_valid_ascii_ident(bytes: &[u8]) -> bool {
matches!(bytes.first(), Some(b'_' | b'a'..=b'z' | b'A'..=b'Z'))
&& bytes[1..]
.iter()
.all(|b| matches!(b, b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9'))
}
fn can_be_raw(string: &str) -> bool {
match string {
"_" | "super" | "self" | "Self" | "crate" => false,
_ => true,
}
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.with(|s| fmt::Debug::fmt(s, f))
}
}
impl ToString for Symbol {
fn to_string(&self) -> String {
self.with(|s| s.to_owned())
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.with(|s| fmt::Display::fmt(s, f))
}
}
impl<S> Encode<S> for Symbol {
fn encode(self, w: &mut Writer, s: &mut S) {
self.with(|sym| sym.encode(w, s))
}
}
impl<S: server::Server> DecodeMut<'_, '_, client::HandleStore<server::MarkedTypes<S>>>
for Marked<S::Symbol, Symbol>
{
fn decode(r: &mut Reader<'_>, s: &mut client::HandleStore<server::MarkedTypes<S>>) -> Self {
Mark::mark(S::intern_symbol(<&str>::decode(r, s)))
}
}
impl<S: server::Server> Encode<client::HandleStore<server::MarkedTypes<S>>>
for Marked<S::Symbol, Symbol>
{
fn encode(self, w: &mut Writer, s: &mut client::HandleStore<server::MarkedTypes<S>>) {
S::with_symbol_string(&self.unmark(), |sym| sym.encode(w, s))
}
}
impl<S> DecodeMut<'_, '_, S> for Symbol {
fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
Symbol::new(<&str>::decode(r, s))
}
}
thread_local! {
static INTERNER: RefCell<Interner> = RefCell::new(Interner {
arena: arena::Arena::new(),
names: fxhash::FxHashMap::default(),
strings: Vec::new(),
sym_base: NonZeroU32::new(1).unwrap(),
});
}
struct Interner {
arena: arena::Arena,
names: fxhash::FxHashMap<&'static str, Symbol>,
strings: Vec<&'static str>,
sym_base: NonZeroU32,
}
impl Interner {
fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol(
self.sym_base
.checked_add(self.strings.len() as u32)
.expect("`proc_macro` symbol name overflow"),
);
let string: &str = self.arena.alloc_str(string);
let string: &'static str = unsafe { &*(string as *const str) };
self.strings.push(string);
self.names.insert(string, name);
name
}
fn get(&self, symbol: Symbol) -> &str {
let name = symbol
.0
.get()
.checked_sub(self.sym_base.get())
.expect("use-after-free of `proc_macro` symbol");
self.strings[name as usize]
}
fn clear(&mut self) {
self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
self.names.clear();
self.strings.clear();
self.arena = arena::Arena::new();
}
}