use crate::catcode::Cat;
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::RwLock;
#[derive(Clone, Copy)]
pub struct CsId(&'static str);
impl PartialEq for CsId {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self.0.as_ptr(), other.0.as_ptr()) && self.0.len() == other.0.len()
}
}
impl Eq for CsId {}
impl std::hash::Hash for CsId {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(self.0.as_ptr() as usize).hash(state);
}
}
impl std::fmt::Debug for CsId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Cs({})", self.0)
}
}
struct Names {
to_id: HashMap<&'static str, &'static str>,
count: usize,
}
static NAMES: Lazy<RwLock<Names>> = Lazy::new(|| {
RwLock::new(Names {
to_id: HashMap::new(),
count: 0,
})
});
impl CsId {
pub fn intern(name: &str) -> CsId {
thread_local! {
static SEEN: std::cell::RefCell<HashMap<Box<str>, &'static str>> =
std::cell::RefCell::new(HashMap::new());
}
if let Some(hit) = SEEN.with(|c| c.borrow().get(name).copied()) {
return CsId(hit);
}
let canonical = Self::intern_shared(name);
SEEN.with(|c| c.borrow_mut().insert(name.into(), canonical.0));
canonical
}
fn intern_shared(name: &str) -> CsId {
if let Some(s) = NAMES.read().expect("names").to_id.get(name) {
return CsId(s);
}
let mut n = NAMES.write().expect("names");
if let Some(s) = n.to_id.get(name) {
return CsId(s);
}
let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());
n.to_id.insert(leaked, leaked);
n.count += 1;
CsId(leaked)
}
pub fn name(self) -> &'static str {
self.0
}
pub fn interned_count() -> usize {
NAMES.read().expect("names").count
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Token {
Char(char, Cat),
Cs(CsId),
}
impl Token {
pub fn cs(name: &str) -> Token {
Token::Cs(CsId::intern(name))
}
pub fn cs_name(&self) -> Option<&'static str> {
match self {
Token::Cs(id) => Some(id.name()),
Token::Char(..) => None,
}
}
pub fn is_cs(&self, name: &str) -> bool {
matches!(self, Token::Cs(id) if *id == CsId::intern(name))
}
pub fn to_text(&self, escape: char) -> String {
match self {
Token::Char(c, _) => c.to_string(),
Token::Cs(id) => {
let name = id.name();
let single = name.chars().count() == 1;
match single {
true => format!("{escape}{name}"),
false => format!("{escape}{name} "),
}
}
}
}
pub fn is_space(&self) -> bool {
matches!(self, Token::Char(_, Cat::Space))
}
}