rucc_base/intern.rs
1//! String interning.
2//!
3//! Identifiers are compared constantly: on every macro lookup, every scope lookup, every
4//! typedef disambiguation. Interning turns those comparisons into an integer compare and
5//! turns the storage into one arena instead of a `String` per occurrence. The lexer interns
6//! during the scan rather than after it, per `spec/06-lexer-and-parser.md`, so an identifier
7//! is never materialised as a `String` at all.
8//!
9//! # Reserved names
10//!
11//! Every interner starts with the names in [`RESERVED`] already in it, in that order, which is
12//! what makes the constants in [`sym`] the symbols they are. The reason is that a pass past the
13//! lexer holds the interner through a shared reference and cannot add to it, and a pass that
14//! builds a type of its own still has to name it: the members of the target's `va_list` are
15//! named by the ABI and never by the source, so the names have to exist before anything is read.
16//!
17//! # Determinism
18//!
19//! [`Symbol`] ordering is allocation order, which is the order the source was read in. That
20//! is deterministic for a given input, and it is the reason the compiler can sort by symbol
21//! anywhere it needs a stable order without reaching for the string. Hashing a `Symbol` must
22//! never leak into output ordering, because hash order is not stable across runs, and
23//! `spec/02-the-goal.md` makes byte-identical output a requirement rather than a nicety.
24//!
25//! # Spellings that are not text
26//!
27//! A source file is UTF-8 and an identifier in it is text, but the body of a string literal is
28//! bytes and does not have to be text at all: `"\xff"` may be written as the byte itself, and
29//! the object it initialises is one byte long whatever that byte is. So [`Interner::intern_bytes`]
30//! takes a spelling that is not UTF-8 and [`Interner::resolve_bytes`] gives it back exactly,
31//! while [`Interner::resolve`] still hands back a `&str`, because almost everything that holds a
32//! symbol wants to print it. What it hands back for such a symbol is the lossy reading, with the
33//! bytes that are not characters replaced, which is right for a message and wrong for an object,
34//! and the object is what `resolve_bytes` is for.
35
36use std::collections::HashMap;
37use std::fmt;
38
39use crate::index::Idx;
40
41/// Marker for the symbol table, so that `Idx<SymbolTable>` cannot be confused with any
42/// other index.
43#[derive(Debug)]
44pub struct SymbolTable;
45
46/// An interned string.
47///
48/// Four bytes, `Copy`, and equal exactly when the strings are equal. Resolving one back to
49/// text needs the [`Interner`] it came from, which is deliberate: it makes accidentally
50/// printing an identifier in a hot path visible at the call site.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
52pub struct Symbol(Idx<SymbolTable>);
53
54impl Symbol {
55 /// The underlying index, for packing a symbol into a bitfield.
56 #[inline]
57 pub const fn raw(self) -> u32 {
58 self.0.raw()
59 }
60
61 /// The symbol a [`Symbol::raw`] came from, which is the other half of packing one away.
62 ///
63 /// # Panics
64 ///
65 /// Panics if `raw` is not an index this interner could have handed out, which catches a
66 /// field holding something other than a symbol rather than resolving to the wrong string.
67 #[inline]
68 #[must_use]
69 pub const fn from_raw(raw: u32) -> Symbol {
70 Symbol(Idx::new(raw))
71 }
72}
73
74/// The names every interner is built with, in the order they are interned.
75///
76/// The list is short on purpose. A name belongs here when the compiler has to write it down and
77/// the source is not the place it comes from, which so far is the target's type for a variable
78/// argument list and nothing else.
79pub const RESERVED: &[&str] = &[
80 "__va_list_tag",
81 "gp_offset",
82 "fp_offset",
83 "overflow_arg_area",
84 "reg_save_area",
85 "__va_list",
86 "__stack",
87 "__gr_top",
88 "__vr_top",
89 "__gr_offs",
90 "__vr_offs",
91];
92
93/// The symbols for the names in [`RESERVED`].
94///
95/// Each constant is the position of its name in that list, so the two are one table written
96/// twice and a test here holds them together.
97pub mod sym {
98 use super::Symbol;
99
100 /// `__va_list_tag`, the tag of the record a SysV x86-64 `va_list` is an array of one of.
101 pub const VA_LIST_TAG: Symbol = Symbol::from_raw(0);
102 /// `gp_offset`, how far into the saved general registers the list has read.
103 pub const GP_OFFSET: Symbol = Symbol::from_raw(1);
104 /// `fp_offset`, the same for the saved floating point registers.
105 pub const FP_OFFSET: Symbol = Symbol::from_raw(2);
106 /// `overflow_arg_area`, the arguments that were passed on the stack.
107 pub const OVERFLOW_ARG_AREA: Symbol = Symbol::from_raw(3);
108 /// `reg_save_area`, where the callee spilled the argument registers.
109 pub const REG_SAVE_AREA: Symbol = Symbol::from_raw(4);
110 /// `__va_list`, the tag of the record an AAPCS64 `va_list` is.
111 pub const VA_LIST: Symbol = Symbol::from_raw(5);
112 /// `__stack`, the arguments that were passed on the stack.
113 pub const STACK: Symbol = Symbol::from_raw(6);
114 /// `__gr_top`, the end of the saved general registers.
115 pub const GR_TOP: Symbol = Symbol::from_raw(7);
116 /// `__vr_top`, the end of the saved vector registers.
117 pub const VR_TOP: Symbol = Symbol::from_raw(8);
118 /// `__gr_offs`, how far back from `__gr_top` the list has read, in bytes and negative.
119 pub const GR_OFFS: Symbol = Symbol::from_raw(9);
120 /// `__vr_offs`, the same for `__vr_top`.
121 pub const VR_OFFS: Symbol = Symbol::from_raw(10);
122}
123
124/// An append-only set of strings, each mapped to a [`Symbol`].
125///
126/// Strings are never removed, which is what makes a `Symbol` valid for the lifetime of the
127/// compilation and what lets the storage be a plain growing buffer.
128pub struct Interner {
129 /// Every interned string, concatenated. One allocation that doubles, rather than one
130 /// allocation per identifier.
131 buf: String,
132 /// Where each symbol starts and ends in `buf`.
133 spans: Vec<(u32, u32)>,
134 /// Lookup from text to symbol. The key is a span into `buf` rather than an owned
135 /// `String`, which is why the map is keyed by the string and rebuilt through `resolve`.
136 map: HashMap<Box<str>, Symbol>,
137 /// The spelling of a symbol whose bytes are not UTF-8, which `buf` cannot hold because
138 /// `buf` is a `String`. A map rather than a column beside `spans`, because a compilation
139 /// has a handful of these at most and usually none: a raw byte in a string literal is the
140 /// only thing that puts one here.
141 raw: HashMap<Symbol, Box<[u8]>>,
142 /// Lookup from those bytes back to their symbol, so that interning the same spelling twice
143 /// is the same symbol. Kept apart from `map` because two spellings that are not text can
144 /// read the same lossily and still have to be told apart.
145 raw_map: HashMap<Box<[u8]>, Symbol>,
146}
147
148impl Default for Interner {
149 fn default() -> Self {
150 Self::new()
151 }
152}
153
154impl Interner {
155 /// An interner holding the reserved names and nothing else.
156 pub fn new() -> Self {
157 Self::with_capacity(RESERVED.len())
158 }
159
160 /// An interner with room for `cap` strings, to avoid regrowing on a large header set.
161 pub fn with_capacity(cap: usize) -> Self {
162 let cap = cap.max(RESERVED.len());
163 let mut interner = Self {
164 buf: String::with_capacity(cap * 8),
165 spans: Vec::with_capacity(cap),
166 map: HashMap::with_capacity(cap),
167 raw: HashMap::new(),
168 raw_map: HashMap::new(),
169 };
170 for name in RESERVED {
171 interner.intern(name);
172 }
173 interner
174 }
175
176 /// Interns `s`, returning the existing symbol if it has been seen.
177 ///
178 /// # Panics
179 ///
180 /// Panics if more than `Idx::MAX` distinct strings are interned.
181 pub fn intern(&mut self, s: &str) -> Symbol {
182 if let Some(&sym) = self.map.get(s) {
183 return sym;
184 }
185 let start = u32::try_from(self.buf.len()).expect("interner buffer overflow");
186 self.buf.push_str(s);
187 let end = u32::try_from(self.buf.len()).expect("interner buffer overflow");
188 let sym = Symbol(Idx::from_usize(self.spans.len()));
189 self.spans.push((start, end));
190 self.map.insert(s.into(), sym);
191 sym
192 }
193
194 /// Interns a spelling that may not be text, returning the existing symbol if it has been seen.
195 ///
196 /// A spelling that is UTF-8 is interned as itself, so nothing changes for the common case and
197 /// a byte spelling equal to a name is the same symbol as that name. One that is not gets a
198 /// symbol of its own whose text is the lossy reading, which is what [`Interner::resolve`]
199 /// hands back, and whose bytes are kept beside it for [`Interner::resolve_bytes`].
200 ///
201 /// # Panics
202 ///
203 /// Panics if more than `Idx::MAX` distinct spellings are interned.
204 pub fn intern_bytes(&mut self, bytes: &[u8]) -> Symbol {
205 if let Ok(text) = std::str::from_utf8(bytes) {
206 return self.intern(text);
207 }
208 if let Some(&sym) = self.raw_map.get(bytes) {
209 return sym;
210 }
211 // Pushed straight into the buffer rather than through `intern`, because the lossy
212 // reading may be a string that is already in there and this spelling is not that one.
213 let lossy = String::from_utf8_lossy(bytes);
214 let start = u32::try_from(self.buf.len()).expect("interner buffer overflow");
215 self.buf.push_str(&lossy);
216 let end = u32::try_from(self.buf.len()).expect("interner buffer overflow");
217 let sym = Symbol(Idx::from_usize(self.spans.len()));
218 self.spans.push((start, end));
219 self.raw.insert(sym, bytes.into());
220 self.raw_map.insert(bytes.into(), sym);
221 sym
222 }
223
224 /// The text behind a symbol.
225 ///
226 /// # Panics
227 ///
228 /// Panics if the symbol came from a different interner. There is one interner per
229 /// compilation, so this is a bug rather than a condition to handle.
230 pub fn resolve(&self, sym: Symbol) -> &str {
231 let (start, end) = self.spans[sym.0.index()];
232 &self.buf[start as usize..end as usize]
233 }
234
235 /// The bytes behind a symbol, which is the spelling exactly as it was written.
236 ///
237 /// The same as `resolve(sym).as_bytes()` for every symbol that came from text, which is all
238 /// of them but the ones [`Interner::intern_bytes`] made from bytes that are not UTF-8.
239 ///
240 /// # Panics
241 ///
242 /// Panics if the symbol came from a different interner, as [`Interner::resolve`] does.
243 pub fn resolve_bytes(&self, sym: Symbol) -> &[u8] {
244 match self.raw.get(&sym) {
245 Some(bytes) => bytes,
246 None => self.resolve(sym).as_bytes(),
247 }
248 }
249
250 /// How many distinct strings have been interned, the reserved names included.
251 pub fn len(&self) -> usize {
252 self.spans.len()
253 }
254
255 /// Whether anything but the reserved names has been interned.
256 pub fn is_empty(&self) -> bool {
257 self.spans.len() <= RESERVED.len()
258 }
259
260 /// Total bytes of interned text, which is the number worth watching on a large build.
261 pub fn bytes(&self) -> usize {
262 self.buf.len()
263 }
264}
265
266impl fmt::Debug for Interner {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 // Dumping every identifier in a translation unit is never what anyone wanted from a
269 // `{:?}` on the session, so this reports the shape instead.
270 f.debug_struct("Interner")
271 .field("symbols", &self.spans.len())
272 .field("bytes", &self.buf.len())
273 .finish()
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280
281 #[test]
282 fn the_same_string_gets_the_same_symbol() {
283 let mut i = Interner::new();
284 let before = i.len();
285 let a = i.intern("static_assert");
286 let b = i.intern("static_assert");
287 assert_eq!(a, b);
288 assert_eq!(i.len() - before, 1);
289 }
290
291 #[test]
292 fn different_strings_get_different_symbols() {
293 let mut i = Interner::new();
294 let before = i.len();
295 assert_ne!(i.intern("int"), i.intern("long"));
296 assert_eq!(i.len() - before, 2);
297 }
298
299 #[test]
300 fn the_reserved_names_are_there_before_anything_is_read() {
301 let i = Interner::new();
302 assert_eq!(i.len(), RESERVED.len());
303 assert!(i.is_empty(), "the reserved names do not count as something having been read");
304 assert_eq!(i.resolve(sym::VA_LIST_TAG), "__va_list_tag");
305 assert_eq!(i.resolve(sym::GP_OFFSET), "gp_offset");
306 assert_eq!(i.resolve(sym::FP_OFFSET), "fp_offset");
307 assert_eq!(i.resolve(sym::OVERFLOW_ARG_AREA), "overflow_arg_area");
308 assert_eq!(i.resolve(sym::REG_SAVE_AREA), "reg_save_area");
309 assert_eq!(i.resolve(sym::VA_LIST), "__va_list");
310 assert_eq!(i.resolve(sym::STACK), "__stack");
311 assert_eq!(i.resolve(sym::GR_TOP), "__gr_top");
312 assert_eq!(i.resolve(sym::VR_TOP), "__vr_top");
313 assert_eq!(i.resolve(sym::GR_OFFS), "__gr_offs");
314 assert_eq!(i.resolve(sym::VR_OFFS), "__vr_offs");
315 }
316
317 #[test]
318 fn a_reserved_name_written_in_the_source_is_the_symbol_it_already_had() {
319 let mut i = Interner::new();
320 let before = i.len();
321 assert_eq!(i.intern("__va_list_tag"), sym::VA_LIST_TAG);
322 assert_eq!(i.len(), before);
323 }
324
325 #[test]
326 fn every_interner_agrees_on_where_the_reserved_names_are() {
327 let small = Interner::new();
328 let large = Interner::with_capacity(4096);
329 for (at, name) in RESERVED.iter().enumerate() {
330 let sym = Symbol::from_raw(u32::try_from(at).expect("eleven names fit in a u32"));
331 assert_eq!(small.resolve(sym), *name);
332 assert_eq!(large.resolve(sym), *name);
333 }
334 }
335
336 #[test]
337 fn resolves_back_to_the_text() {
338 let mut i = Interner::new();
339 let s = i.intern("__builtin_constant_p");
340 assert_eq!(i.resolve(s), "__builtin_constant_p");
341 }
342
343 #[test]
344 fn symbols_are_numbered_in_allocation_order() {
345 let mut i = Interner::new();
346 let first = i.intern("a");
347 let second = i.intern("b");
348 assert!(first < second, "symbol order must be allocation order, not hash order");
349 }
350
351 #[test]
352 fn the_empty_string_is_internable() {
353 let mut i = Interner::new();
354 let before = i.bytes();
355 let s = i.intern("");
356 assert_eq!(i.resolve(s), "");
357 assert_eq!(i.bytes(), before);
358 }
359
360 #[test]
361 fn a_spelling_that_is_text_is_the_same_symbol_however_it_was_interned() {
362 let mut i = Interner::new();
363 let text = i.intern("hello");
364 assert_eq!(i.intern_bytes(b"hello"), text);
365 assert_eq!(i.resolve_bytes(text), b"hello");
366 }
367
368 #[test]
369 fn a_spelling_that_is_not_text_keeps_its_bytes() {
370 let mut i = Interner::new();
371 let raw = i.intern_bytes(b"\"\xff\"");
372 assert_eq!(i.resolve_bytes(raw), b"\"\xff\"");
373 assert_eq!(i.intern_bytes(b"\"\xff\""), raw, "interning it twice is one symbol");
374 // The text is the lossy reading, which is what a message quoting it would print.
375 assert_eq!(i.resolve(raw), "\"\u{fffd}\"");
376 }
377
378 #[test]
379 fn two_spellings_that_read_the_same_lossily_are_still_two_symbols() {
380 let mut i = Interner::new();
381 let one = i.intern_bytes(b"\xff");
382 let other = i.intern_bytes(b"\xfe");
383 assert_eq!(i.resolve(one), i.resolve(other), "both read as the replacement character");
384 assert_ne!(one, other, "the bytes differ, so the spellings do");
385 assert_eq!(i.resolve_bytes(one), b"\xff");
386 assert_eq!(i.resolve_bytes(other), b"\xfe");
387 // And neither of them is the text that reads the same, which the source may also hold.
388 assert_ne!(i.intern("\u{fffd}"), one);
389 }
390
391 #[test]
392 fn a_symbol_is_four_bytes() {
393 assert_eq!(size_of::<Symbol>(), 4);
394 assert_eq!(size_of::<Option<Symbol>>(), 4);
395 }
396}