proc_macro/bridge/
symbol.rs1use std::cell::RefCell;
13use std::fmt;
14use std::num::NonZero;
15
16use crate::bridge::{Buffer, Decode, Encode, Mark, arena, client, fxhash, server};
17
18#[derive(Copy, Clone, PartialEq, Eq, Hash)]
20pub struct Symbol(NonZero<u32>);
21
22impl !Send for Symbol {}
23impl !Sync for Symbol {}
24
25impl Symbol {
26 pub(crate) fn new(string: &str) -> Self {
28 INTERNER.with_borrow_mut(|i| i.intern(string))
29 }
30
31 pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self {
35 if Self::is_valid_ascii_ident(string.as_bytes()) || string == "$crate" {
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 if string.is_ascii() {
48 Err(())
49 } else {
50 client::Methods::symbol_normalize_and_validate_ident(string)
51 }
52 .unwrap_or_else(|_| panic!("`{:?}` is not a valid identifier", string))
53 }
54
55 pub(crate) fn with<R>(self, f: impl FnOnce(&str) -> R) -> R {
57 INTERNER.with_borrow(|i| f(i.get(self)))
58 }
59
60 pub(crate) fn invalidate_all() {
63 INTERNER.with_borrow_mut(|i| i.clear());
64 }
65
66 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 fn can_be_raw(string: &str) -> bool {
81 !matches!(string, "_" | "super" | "self" | "Self" | "crate" | "$crate")
82 }
83}
84
85impl fmt::Debug for Symbol {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 self.with(|s| fmt::Debug::fmt(s, f))
88 }
89}
90
91impl fmt::Display for Symbol {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 self.with(|s| fmt::Display::fmt(s, f))
94 }
95}
96
97impl<S> Encode<S> for Symbol {
98 fn encode(self, w: &mut Buffer, s: &mut S) {
99 self.with(|sym| sym.encode(w, s))
100 }
101}
102
103impl<S: server::Server> Decode<'_, '_, server::HandleStore<S>> for server::MarkedSymbol<S> {
104 fn decode(r: &mut &[u8], s: &mut server::HandleStore<S>) -> Self {
105 Mark::mark(S::intern_symbol(<&str>::decode(r, s)))
106 }
107}
108
109impl<S: server::Server> Encode<server::HandleStore<S>> for server::MarkedSymbol<S> {
110 fn encode(self, w: &mut Buffer, s: &mut server::HandleStore<S>) {
111 S::with_symbol_string(&self.unmark(), |sym| sym.encode(w, s))
112 }
113}
114
115impl<S> Decode<'_, '_, S> for Symbol {
116 fn decode(r: &mut &[u8], s: &mut S) -> Self {
117 Symbol::new(<&str>::decode(r, s))
118 }
119}
120
121thread_local! {
122 static INTERNER: RefCell<Interner> = RefCell::new(Interner {
123 arena: arena::Arena::new(),
124 names: fxhash::FxHashMap::default(),
125 strings: Vec::new(),
126 sym_base: NonZero::new(1).unwrap(),
128 });
129}
130
131struct Interner {
133 arena: arena::Arena,
134 names: fxhash::FxHashMap<&'static str, Symbol>,
138 strings: Vec<&'static str>,
139 sym_base: NonZero<u32>,
143}
144
145impl Interner {
146 fn intern(&mut self, string: &str) -> Symbol {
147 if let Some(&name) = self.names.get(string) {
148 return name;
149 }
150
151 let name = Symbol(
152 self.sym_base
153 .checked_add(self.strings.len() as u32)
154 .expect("`proc_macro` symbol name overflow"),
155 );
156
157 let string: &str = self.arena.alloc_str(string);
158
159 let string: &'static str = unsafe { &*(string as *const str) };
162 self.strings.push(string);
163 self.names.insert(string, name);
164 name
165 }
166
167 fn get(&self, symbol: Symbol) -> &str {
169 let name = symbol
172 .0
173 .get()
174 .checked_sub(self.sym_base.get())
175 .expect("use-after-free of `proc_macro` symbol");
176 self.strings[name as usize]
177 }
178
179 fn clear(&mut self) {
182 self.sym_base = self.sym_base.saturating_add(self.strings.len() as u32);
185 self.names.clear();
186 self.strings.clear();
187
188 self.arena = arena::Arena::new();
191 }
192}