rucc_lex/keyword.rs
1//! Keywords, and which ones the dialect has.
2//!
3//! Design: `spec/06-lexer-and-parser.md` section 6.1.
4//!
5//! Phase 7 turns an identifier into a keyword when the active `-std=` says that spelling is
6//! one. Doing that with a string comparison, or with a hash lookup on the text, would put a
7//! second pass over every identifier in the file right after the scan that already interned
8//! it. So the keywords are interned first, before anything else, which makes their symbols one
9//! contiguous run at the bottom of the table. Recognition is then a subtraction, a bounds
10//! check and a byte load, and every identifier a program actually declares fails the bounds
11//! check on the first instruction.
12//!
13//! The dialect gate is part of the same load. Whether a spelling is a keyword depends on the
14//! dialect, and the dialect is fixed for the whole compilation, so [`Keywords::new`] resolves
15//! it once: each entry holds the keyword it means in this dialect, or nothing when the
16//! spelling is an ordinary identifier here. `restrict` is a keyword from C99 and a variable
17//! name in C89, `typeof` is one in C23 and in the GNU dialects and not in `-std=c17`, and
18//! `__typeof__` is one everywhere, which is why headers are written with the ugly spelling.
19//!
20//! Which spelling is a keyword in which dialect was measured rather than read out of the
21//! standard, because the standard does not describe the GNU dialects and the underscore
22//! spellings are on in dialects that predate them. Every identifier below was compiled as
23//! `void f(void) { int KW = 0; (void)KW; }` against gcc 13.3 on x86-64 Linux and against
24//! clang, in each of c89, gnu89, c99, gnu99, c11, gnu11, c17, gnu17, c23 and gnu23, with two
25//! ordinary identifiers along for the ride to catch a probe that had stopped measuring
26//! anything. The two compilers agree except where noted.
27//!
28//! Three differences from gcc 13.3, one of which gcc 16 has since closed:
29//!
30//! `_BitInt` is a keyword here in every dialect. That was a difference from gcc 13.3, which
31//! does not have the type at all, and is not one from gcc 16: the type arrived in gcc 14, the
32//! spelling is a keyword there in every dialect, and `-pedantic` warns about the type before
33//! C23 rather than about the spelling. clang does the same. It is in the reserved namespace,
34//! so nothing legal can notice.
35//!
36//! `__float128` and `__bf16` are not keywords. gcc registers them as predefined type names,
37//! which a declaration is allowed to shadow, and `void f(void) { int __float128 = 0; }`
38//! compiles there. clang makes both of them keywords and rejects it. We follow gcc, so they
39//! belong with the other predefined types rather than here.
40//!
41//! gcc also reserves `_Sat`, `_Fract`, `_Accum`, `__seg_fs` and `__seg_gs` in the GNU
42//! dialects. They are left out until the fixed point types and the named address spaces are
43//! implemented, because a keyword the parser can only refuse is worse for a program than an
44//! identifier it can at least read.
45
46use rucc_base::{Interner, Symbol};
47use rucc_session::Std;
48
49/// A keyword, meaning a spelling the grammar knows rather than a name a program chose.
50///
51/// One variant per meaning, not per spelling. `__inline__` and `inline` are the same keyword
52/// because they are the same declaration specifier, and a parser that had to know which of
53/// them was written would be carrying the difference all the way to the AST for nothing.
54/// Where two spellings mean genuinely different things they stay apart: `__alignof__` is
55/// [`Keyword::GnuAlignof`] rather than [`Keyword::Alignof`], because GNU's asks for the
56/// alignment the target prefers and C's asks for the one the ABI requires, and on i386 they
57/// disagree about `double`.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub enum Keyword {
60 /// `auto`.
61 Auto,
62 /// `break`.
63 Break,
64 /// `case`.
65 Case,
66 /// `char`.
67 Char,
68 /// `const`, and the GNU spelling `__const`.
69 Const,
70 /// `continue`.
71 Continue,
72 /// `default`.
73 Default,
74 /// `do`.
75 Do,
76 /// `double`.
77 Double,
78 /// `else`.
79 Else,
80 /// `enum`.
81 Enum,
82 /// `extern`.
83 Extern,
84 /// `float`.
85 Float,
86 /// `for`.
87 For,
88 /// `goto`.
89 Goto,
90 /// `if`.
91 If,
92 /// `int`.
93 Int,
94 /// `long`.
95 Long,
96 /// `register`.
97 Register,
98 /// `return`.
99 Return,
100 /// `short`.
101 Short,
102 /// `signed`, and the GNU spelling `__signed__`.
103 Signed,
104 /// `sizeof`.
105 Sizeof,
106 /// `static`.
107 Static,
108 /// `struct`.
109 Struct,
110 /// `switch`.
111 Switch,
112 /// `typedef`.
113 Typedef,
114 /// `union`.
115 Union,
116 /// `unsigned`.
117 Unsigned,
118 /// `void`.
119 Void,
120 /// `volatile`, and the GNU spelling `__volatile__`.
121 Volatile,
122 /// `while`.
123 While,
124 /// `inline`, from C99, and the GNU spelling `__inline__`.
125 Inline,
126 /// `restrict`, from C99, and the GNU spelling `__restrict__`.
127 Restrict,
128 /// `_Bool`, and `bool` from C23.
129 Bool,
130 /// `_Complex`, and the GNU spelling `__complex__`.
131 Complex,
132 /// `_Imaginary`.
133 Imaginary,
134 /// `_Alignas`, and `alignas` from C23.
135 Alignas,
136 /// `_Alignof`, and `alignof` from C23.
137 Alignof,
138 /// `_Atomic`.
139 Atomic,
140 /// `_Generic`.
141 Generic,
142 /// `_Noreturn`.
143 Noreturn,
144 /// `_Static_assert`, and `static_assert` from C23.
145 StaticAssert,
146 /// `_Thread_local`, `thread_local` from C23, and the GNU spelling `__thread`.
147 ThreadLocal,
148 /// `_BitInt`.
149 BitInt,
150 /// `_Decimal32`.
151 Decimal32,
152 /// `_Decimal64`.
153 Decimal64,
154 /// `_Decimal128`.
155 Decimal128,
156 /// `_Float16`.
157 Float16,
158 /// `_Float32`.
159 Float32,
160 /// `_Float64`.
161 Float64,
162 /// `_Float128`.
163 Float128,
164 /// `_Float32x`.
165 Float32x,
166 /// `_Float64x`.
167 Float64x,
168 /// `_Float128x`.
169 Float128x,
170 /// `constexpr`, from C23.
171 Constexpr,
172 /// `false`, from C23.
173 False,
174 /// `nullptr`, from C23.
175 Nullptr,
176 /// `true`, from C23.
177 True,
178 /// `typeof`, from C23 and from the GNU dialects, and the spelling `__typeof__`.
179 Typeof,
180 /// `typeof_unqual`, from C23, and the spelling `__typeof_unqual__`.
181 TypeofUnqual,
182 /// `asm`, in the GNU dialects, and the spelling `__asm__`.
183 Asm,
184 /// `__attribute__`.
185 Attribute,
186 /// `__auto_type`, which is not `auto`: it deduces from an initialiser in every dialect.
187 AutoType,
188 /// `__alignof__`, which asks for the preferred alignment rather than the required one.
189 GnuAlignof,
190 /// `__extension__`, which turns off the pedantic diagnostics for one expression.
191 Extension,
192 /// `__imag__`.
193 Imag,
194 /// `__real__`.
195 Real,
196 /// `__int128`.
197 Int128,
198 /// `__label__`, which declares a local label in a statement expression.
199 Label,
200 /// `__builtin_offsetof`, which is syntax rather than a function because it takes a type.
201 BuiltinOffsetof,
202 /// `__builtin_choose_expr`.
203 BuiltinChooseExpr,
204 /// `__builtin_types_compatible_p`.
205 BuiltinTypesCompatibleP,
206 /// `__builtin_va_arg`.
207 BuiltinVaArg,
208 /// `__builtin_va_list`, the target's type for a variable argument list.
209 BuiltinVaList,
210 /// `__builtin_va_start`.
211 BuiltinVaStart,
212 /// `__builtin_va_end`.
213 BuiltinVaEnd,
214 /// `__builtin_va_copy`.
215 BuiltinVaCopy,
216}
217
218impl Keyword {
219 /// The spelling to print in a diagnostic, which is the standard one where there is one.
220 ///
221 /// This walks the table, because it is only ever reached while writing a message and a
222 /// second array indexed by the enum would be one more place for the two to disagree.
223 #[must_use]
224 pub fn as_str(self) -> &'static str {
225 KEYWORDS
226 .iter()
227 .find(|entry| entry.keyword == self)
228 .map_or("keyword", |entry| entry.spelling)
229 }
230}
231
232/// The keywords of one dialect, ready to be looked up by symbol.
233///
234/// Built once per compilation, against the interner that compilation will use, before any
235/// source has been read.
236#[derive(Debug)]
237pub struct Keywords {
238 /// The symbol of the first entry. Everything below this is not a keyword, and so is
239 /// everything at or past the end of `active`.
240 base: u32,
241 /// The keyword each spelling means in this dialect, indexed by symbol minus `base`, and
242 /// [`None`] for a spelling this dialect leaves as an ordinary identifier.
243 active: Box<[Option<Keyword>]>,
244}
245
246impl Keywords {
247 /// Interns every keyword spelling and resolves which of them this dialect has.
248 ///
249 /// # Panics
250 ///
251 /// Panics if `interner` has already been given one of these spellings, since the symbols
252 /// would no longer be one run and every lookup after that would be wrong. Build this
253 /// first, immediately after the interner itself.
254 #[must_use]
255 pub fn new(interner: &mut Interner, std: Std, gnu: bool) -> Keywords {
256 let dialect = mask(std, gnu);
257 let mut base = 0;
258 let mut active = Vec::with_capacity(KEYWORDS.len());
259 for entry in KEYWORDS {
260 let symbol = interner.intern(entry.spelling).raw();
261 if active.is_empty() {
262 base = symbol;
263 }
264 let want = base + u32::try_from(active.len()).expect("the table is not that long");
265 assert!(
266 symbol == want,
267 "`{}` was interned before the keyword table was built",
268 entry.spelling
269 );
270 active.push((entry.dialects & dialect != 0).then_some(entry.keyword));
271 }
272 Keywords { base, active: active.into_boxed_slice() }
273 }
274
275 /// The keyword `symbol` is in this dialect, and [`None`] when it is an identifier.
276 #[must_use]
277 #[inline]
278 pub fn get(&self, symbol: Symbol) -> Option<Keyword> {
279 let index = symbol.raw().checked_sub(self.base)?;
280 // A `usize` cast rather than a conversion: the index is already known to fit, because
281 // the slice it indexes was built from symbols this interner handed out.
282 *self.active.get(index as usize)?
283 }
284
285 /// Whether `symbol` is a keyword in this dialect.
286 #[must_use]
287 #[inline]
288 pub fn contains(&self, symbol: Symbol) -> bool {
289 self.get(symbol).is_some()
290 }
291
292 /// How many spellings the table holds, active in this dialect or not.
293 #[must_use]
294 pub fn len(&self) -> usize {
295 self.active.len()
296 }
297
298 /// Whether the table is empty, which it never is.
299 #[must_use]
300 pub fn is_empty(&self) -> bool {
301 self.active.is_empty()
302 }
303}
304
305/// One bit per dialect, plus one for the GNU extensions.
306const C89: u8 = 1 << 0;
307const C99: u8 = 1 << 1;
308const C11: u8 = 1 << 2;
309const C17: u8 = 1 << 3;
310const C23: u8 = 1 << 4;
311const GNU: u8 = 1 << 5;
312
313/// A spelling that is a keyword in every dialect, GNU or not.
314const ALWAYS: u8 = C89 | C99 | C11 | C17 | C23 | GNU;
315/// From C99 onwards, and not in `-std=gnu89`. This is `restrict`, and it is the one place the
316/// GNU dialects are not a superset: gcc and clang both keep `restrict` out of `gnu89` and
317/// offer `__restrict` there instead.
318const SINCE_C99: u8 = C99 | C11 | C17 | C23;
319/// From C99 onwards, and in every GNU dialect including `gnu89`. This is `inline`.
320const SINCE_C99_OR_GNU: u8 = SINCE_C99 | GNU;
321/// C23 only. The lowercase spellings of the C11 keywords are here, and so is the rest of what
322/// C23 added, and `-std=gnu17` does not have any of them.
323const SINCE_C23: u8 = C23;
324/// C23, and every GNU dialect. This is `typeof`, which gcc has had for decades and which C23
325/// standardised, so `-std=c17` is the only place it is a variable name.
326const SINCE_C23_OR_GNU: u8 = C23 | GNU;
327/// The GNU dialects only. This is `asm`, which is a keyword in `gnu23` and an identifier in
328/// `c23`, where `__asm__` has to be written instead.
329const GNU_ONLY: u8 = GNU;
330
331/// A spelling, what it means, and where it is a keyword.
332struct Entry {
333 /// The spelling as it appears in source.
334 spelling: &'static str,
335 /// What the grammar makes of it.
336 keyword: Keyword,
337 /// The dialects it is a keyword in, as a mask of the bits above.
338 dialects: u8,
339}
340
341/// Shorthand, so that the table below reads as a table rather than a page of struct literals.
342const fn e(spelling: &'static str, keyword: Keyword, dialects: u8) -> Entry {
343 Entry { spelling, keyword, dialects }
344}
345
346/// Every keyword spelling in every dialect we support.
347///
348/// The order is the interning order and so decides the symbols, which nothing may depend on;
349/// it is grouped by where each spelling came from because that is how it is checked against a
350/// compiler. The first entry for a keyword is the spelling [`Keyword::as_str`] prints.
351static KEYWORDS: &[Entry] = &[
352 // The C89 keywords. Nothing has ever removed one, so all of them are unconditional.
353 e("auto", Keyword::Auto, ALWAYS),
354 e("break", Keyword::Break, ALWAYS),
355 e("case", Keyword::Case, ALWAYS),
356 e("char", Keyword::Char, ALWAYS),
357 e("const", Keyword::Const, ALWAYS),
358 e("continue", Keyword::Continue, ALWAYS),
359 e("default", Keyword::Default, ALWAYS),
360 e("do", Keyword::Do, ALWAYS),
361 e("double", Keyword::Double, ALWAYS),
362 e("else", Keyword::Else, ALWAYS),
363 e("enum", Keyword::Enum, ALWAYS),
364 e("extern", Keyword::Extern, ALWAYS),
365 e("float", Keyword::Float, ALWAYS),
366 e("for", Keyword::For, ALWAYS),
367 e("goto", Keyword::Goto, ALWAYS),
368 e("if", Keyword::If, ALWAYS),
369 e("int", Keyword::Int, ALWAYS),
370 e("long", Keyword::Long, ALWAYS),
371 e("register", Keyword::Register, ALWAYS),
372 e("return", Keyword::Return, ALWAYS),
373 e("short", Keyword::Short, ALWAYS),
374 e("signed", Keyword::Signed, ALWAYS),
375 e("sizeof", Keyword::Sizeof, ALWAYS),
376 e("static", Keyword::Static, ALWAYS),
377 e("struct", Keyword::Struct, ALWAYS),
378 e("switch", Keyword::Switch, ALWAYS),
379 e("typedef", Keyword::Typedef, ALWAYS),
380 e("union", Keyword::Union, ALWAYS),
381 e("unsigned", Keyword::Unsigned, ALWAYS),
382 e("void", Keyword::Void, ALWAYS),
383 e("volatile", Keyword::Volatile, ALWAYS),
384 e("while", Keyword::While, ALWAYS),
385 // The two C99 additions that are ordinary words. Everything else C99 and C11 added is
386 // spelled with a leading underscore precisely so that it could be turned on in the
387 // older dialects without breaking a program that had used the name, and both
388 // compilers do exactly that.
389 e("inline", Keyword::Inline, SINCE_C99_OR_GNU),
390 e("restrict", Keyword::Restrict, SINCE_C99),
391 e("_Bool", Keyword::Bool, ALWAYS),
392 e("_Complex", Keyword::Complex, ALWAYS),
393 e("_Imaginary", Keyword::Imaginary, ALWAYS),
394 e("_Alignas", Keyword::Alignas, ALWAYS),
395 e("_Alignof", Keyword::Alignof, ALWAYS),
396 e("_Atomic", Keyword::Atomic, ALWAYS),
397 e("_Generic", Keyword::Generic, ALWAYS),
398 e("_Noreturn", Keyword::Noreturn, ALWAYS),
399 e("_Static_assert", Keyword::StaticAssert, ALWAYS),
400 e("_Thread_local", Keyword::ThreadLocal, ALWAYS),
401 e("_BitInt", Keyword::BitInt, ALWAYS),
402 e("_Decimal32", Keyword::Decimal32, ALWAYS),
403 e("_Decimal64", Keyword::Decimal64, ALWAYS),
404 e("_Decimal128", Keyword::Decimal128, ALWAYS),
405 e("_Float16", Keyword::Float16, ALWAYS),
406 e("_Float32", Keyword::Float32, ALWAYS),
407 e("_Float64", Keyword::Float64, ALWAYS),
408 e("_Float128", Keyword::Float128, ALWAYS),
409 e("_Float32x", Keyword::Float32x, ALWAYS),
410 e("_Float64x", Keyword::Float64x, ALWAYS),
411 e("_Float128x", Keyword::Float128x, ALWAYS),
412 // C23, which spelled the C11 keywords as words and added its own. A program that used
413 // `bool` as a variable name still compiles in every earlier dialect, which is the
414 // whole reason this table is gated rather than fixed.
415 e("alignas", Keyword::Alignas, SINCE_C23),
416 e("alignof", Keyword::Alignof, SINCE_C23),
417 e("bool", Keyword::Bool, SINCE_C23),
418 e("constexpr", Keyword::Constexpr, SINCE_C23),
419 e("false", Keyword::False, SINCE_C23),
420 e("nullptr", Keyword::Nullptr, SINCE_C23),
421 e("static_assert", Keyword::StaticAssert, SINCE_C23),
422 e("thread_local", Keyword::ThreadLocal, SINCE_C23),
423 e("true", Keyword::True, SINCE_C23),
424 e("typeof", Keyword::Typeof, SINCE_C23_OR_GNU),
425 e("typeof_unqual", Keyword::TypeofUnqual, SINCE_C23),
426 e("asm", Keyword::Asm, GNU_ONLY),
427 // The GNU spellings. All of them are in the reserved namespace, so gcc turns them on
428 // in every dialect including `-std=c89`, and a header that has to work under `-std=`
429 // anything is written with these rather than with the words above.
430 e("__asm", Keyword::Asm, ALWAYS),
431 e("__asm__", Keyword::Asm, ALWAYS),
432 e("__alignof", Keyword::GnuAlignof, ALWAYS),
433 e("__alignof__", Keyword::GnuAlignof, ALWAYS),
434 e("__attribute", Keyword::Attribute, ALWAYS),
435 e("__attribute__", Keyword::Attribute, ALWAYS),
436 e("__auto_type", Keyword::AutoType, ALWAYS),
437 e("__complex", Keyword::Complex, ALWAYS),
438 e("__complex__", Keyword::Complex, ALWAYS),
439 e("__const", Keyword::Const, ALWAYS),
440 e("__extension__", Keyword::Extension, ALWAYS),
441 e("__imag", Keyword::Imag, ALWAYS),
442 e("__imag__", Keyword::Imag, ALWAYS),
443 e("__inline", Keyword::Inline, ALWAYS),
444 e("__inline__", Keyword::Inline, ALWAYS),
445 e("__int128", Keyword::Int128, ALWAYS),
446 e("__label__", Keyword::Label, ALWAYS),
447 e("__real", Keyword::Real, ALWAYS),
448 e("__real__", Keyword::Real, ALWAYS),
449 e("__restrict", Keyword::Restrict, ALWAYS),
450 e("__restrict__", Keyword::Restrict, ALWAYS),
451 e("__signed", Keyword::Signed, ALWAYS),
452 e("__signed__", Keyword::Signed, ALWAYS),
453 // gcc's own diagnostics keep `__thread` and `_Thread_local` apart, but in C they are
454 // one storage class with two spellings, so the parser is given one keyword.
455 e("__thread", Keyword::ThreadLocal, ALWAYS),
456 e("__typeof", Keyword::Typeof, ALWAYS),
457 e("__typeof__", Keyword::Typeof, ALWAYS),
458 e("__typeof_unqual", Keyword::TypeofUnqual, ALWAYS),
459 e("__typeof_unqual__", Keyword::TypeofUnqual, ALWAYS),
460 e("__volatile", Keyword::Volatile, ALWAYS),
461 e("__volatile__", Keyword::Volatile, ALWAYS),
462 // The builtins that are syntax rather than functions, because an argument of theirs is a
463 // type name, or is not evaluated, or is the object itself rather than its value, or because
464 // what they name is a type. Everything else called `__builtin_` is an ordinary identifier
465 // that resolves to a declaration, and belongs nowhere near this table.
466 e("__builtin_offsetof", Keyword::BuiltinOffsetof, ALWAYS),
467 e("__builtin_choose_expr", Keyword::BuiltinChooseExpr, ALWAYS),
468 e("__builtin_types_compatible_p", Keyword::BuiltinTypesCompatibleP, ALWAYS),
469 e("__builtin_va_arg", Keyword::BuiltinVaArg, ALWAYS),
470 // The rest of the variable argument family. `__builtin_va_list` names a type, and the other
471 // three are handed the list object rather than its value, since what they do is write it.
472 // gcc declares those three as functions taking the address of a list and has its own header
473 // pass the list itself, which works because the list is an array on the targets where the
474 // difference shows. Taking the address here is the same thing without the special case.
475 e("__builtin_va_list", Keyword::BuiltinVaList, ALWAYS),
476 e("__builtin_va_start", Keyword::BuiltinVaStart, ALWAYS),
477 e("__builtin_va_end", Keyword::BuiltinVaEnd, ALWAYS),
478 e("__builtin_va_copy", Keyword::BuiltinVaCopy, ALWAYS),
479];
480
481/// The bits a dialect matches, which is its own and the GNU one when the extensions are on.
482const fn mask(std: Std, gnu: bool) -> u8 {
483 let dialect = match std {
484 Std::C89 => C89,
485 Std::C99 => C99,
486 Std::C11 => C11,
487 Std::C17 => C17,
488 Std::C23 => C23,
489 };
490 if gnu { dialect | GNU } else { dialect }
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 /// The keywords of one dialect, and an interner that has them and nothing else.
498 fn build(std: Std, gnu: bool) -> (Keywords, Interner) {
499 let mut interner = Interner::new();
500 let keywords = Keywords::new(&mut interner, std, gnu);
501 (keywords, interner)
502 }
503
504 /// What `text` means in this dialect, having been interned the way the scanner would.
505 fn lookup(std: Std, gnu: bool, text: &str) -> Option<Keyword> {
506 let (keywords, mut interner) = build(std, gnu);
507 keywords.get(interner.intern(text))
508 }
509
510 #[test]
511 fn a_word_the_language_has_always_had_is_a_keyword_in_every_dialect() {
512 for std in [Std::C89, Std::C99, Std::C11, Std::C17, Std::C23] {
513 for gnu in [false, true] {
514 assert_eq!(lookup(std, gnu, "int"), Some(Keyword::Int));
515 assert_eq!(lookup(std, gnu, "sizeof"), Some(Keyword::Sizeof));
516 assert_eq!(lookup(std, gnu, "_Complex"), Some(Keyword::Complex));
517 }
518 }
519 }
520
521 #[test]
522 fn a_name_a_program_chose_is_never_a_keyword() {
523 // Including one that only just misses, and one that reads like a keyword and is not.
524 for name in ["x", "intx", "in", "INT", "fortran", "ordinary", "__builtin_expect"] {
525 assert_eq!(lookup(Std::C23, true, name), None, "{name} is not a keyword");
526 }
527 }
528
529 #[test]
530 fn restrict_arrived_in_c99_and_gnu89_did_not_get_it_early() {
531 // Measured: gcc and clang both leave `restrict` out of `-std=gnu89`, which is the one
532 // place the GNU dialect is not a superset of the standard one it is based on.
533 assert_eq!(lookup(Std::C89, false, "restrict"), None);
534 assert_eq!(lookup(Std::C89, true, "restrict"), None);
535 assert_eq!(lookup(Std::C99, false, "restrict"), Some(Keyword::Restrict));
536 // `__restrict__` is how a header written for both says it, and it works in c89.
537 assert_eq!(lookup(Std::C89, false, "__restrict__"), Some(Keyword::Restrict));
538 }
539
540 #[test]
541 fn inline_arrived_in_c99_and_gnu89_did_get_it_early() {
542 assert_eq!(lookup(Std::C89, false, "inline"), None);
543 assert_eq!(lookup(Std::C89, true, "inline"), Some(Keyword::Inline));
544 assert_eq!(lookup(Std::C99, false, "inline"), Some(Keyword::Inline));
545 }
546
547 #[test]
548 fn typeof_is_a_gnu_extension_that_c23_made_standard() {
549 assert_eq!(lookup(Std::C17, false, "typeof"), None);
550 assert_eq!(lookup(Std::C17, true, "typeof"), Some(Keyword::Typeof));
551 assert_eq!(lookup(Std::C23, false, "typeof"), Some(Keyword::Typeof));
552 // `typeof_unqual` is the C23 half only, which is what both compilers do.
553 assert_eq!(lookup(Std::C17, true, "typeof_unqual"), None);
554 assert_eq!(lookup(Std::C23, false, "typeof_unqual"), Some(Keyword::TypeofUnqual));
555 assert_eq!(lookup(Std::C17, false, "__typeof__"), Some(Keyword::Typeof));
556 }
557
558 #[test]
559 fn asm_is_the_one_word_c23_still_does_not_have() {
560 assert_eq!(lookup(Std::C23, false, "asm"), None);
561 assert_eq!(lookup(Std::C23, true, "asm"), Some(Keyword::Asm));
562 assert_eq!(lookup(Std::C89, false, "__asm__"), Some(Keyword::Asm));
563 }
564
565 #[test]
566 fn the_c23_words_are_variable_names_in_every_earlier_dialect() {
567 let added = [
568 ("alignas", Keyword::Alignas),
569 ("alignof", Keyword::Alignof),
570 ("bool", Keyword::Bool),
571 ("constexpr", Keyword::Constexpr),
572 ("false", Keyword::False),
573 ("nullptr", Keyword::Nullptr),
574 ("static_assert", Keyword::StaticAssert),
575 ("thread_local", Keyword::ThreadLocal),
576 ("true", Keyword::True),
577 ];
578 for (spelling, keyword) in added {
579 assert_eq!(lookup(Std::C17, true, spelling), None, "{spelling} in gnu17");
580 assert_eq!(lookup(Std::C23, false, spelling), Some(keyword), "{spelling} in c23");
581 }
582 // The underscore spellings they replaced go on working, which is what lets one header
583 // serve both.
584 assert_eq!(lookup(Std::C17, false, "_Static_assert"), Some(Keyword::StaticAssert));
585 assert_eq!(lookup(Std::C23, false, "_Static_assert"), Some(Keyword::StaticAssert));
586 }
587
588 #[test]
589 fn two_spellings_of_one_thing_are_one_keyword() {
590 for spelling in ["const", "__const"] {
591 assert_eq!(lookup(Std::C23, true, spelling), Some(Keyword::Const));
592 }
593 for spelling in ["_Thread_local", "thread_local", "__thread"] {
594 assert_eq!(lookup(Std::C23, true, spelling), Some(Keyword::ThreadLocal));
595 }
596 // And the one pair that looks like two spellings and is not. GNU's `__alignof__`
597 // reports the preferred alignment, C's `_Alignof` the required one.
598 assert_ne!(
599 lookup(Std::C23, true, "__alignof__"),
600 lookup(Std::C23, true, "_Alignof"),
601 "the two alignments are different questions"
602 );
603 }
604
605 #[test]
606 fn every_keyword_prints_a_spelling_that_is_that_keyword() {
607 for entry in KEYWORDS {
608 let printed = entry.keyword.as_str();
609 let found = KEYWORDS
610 .iter()
611 .find(|other| other.spelling == printed)
612 .unwrap_or_else(|| panic!("{printed} is not in the table"));
613 assert_eq!(found.keyword, entry.keyword, "{printed} prints for the wrong keyword");
614 }
615 }
616
617 #[test]
618 fn no_spelling_is_in_the_table_twice() {
619 // A repeat would be interned once, the run of symbols would be short by one, and
620 // `Keywords::new` would refuse to build at all. Better to say why here.
621 let mut seen: Vec<&str> = KEYWORDS.iter().map(|entry| entry.spelling).collect();
622 seen.sort_unstable();
623 let count = seen.len();
624 seen.dedup();
625 assert_eq!(seen.len(), count, "a spelling appears twice in the table");
626 }
627
628 #[test]
629 fn recognition_does_not_depend_on_what_was_interned_afterwards() {
630 // The property the whole design rests on: the keywords are one run at the bottom of
631 // the table, so an identifier interned later cannot land inside it however many there
632 // are.
633 let (keywords, mut interner) = build(Std::C23, true);
634 for i in 0..1000 {
635 let symbol = interner.intern(&format!("name{i}"));
636 assert_eq!(keywords.get(symbol), None);
637 }
638 assert_eq!(keywords.get(interner.intern("while")), Some(Keyword::While));
639 }
640
641 #[test]
642 #[should_panic(expected = "`static` was interned before the keyword table was built")]
643 fn an_interner_that_already_has_a_keyword_in_it_is_refused() {
644 // Silently building a table whose symbols are not one run would mean a compiler that
645 // recognised the wrong words, which is not a failure anybody would find quickly.
646 let mut interner = Interner::new();
647 interner.intern("static");
648 let _ = Keywords::new(&mut interner, Std::C23, true);
649 }
650
651 #[test]
652 fn a_lookup_is_a_bounds_check_on_one_run_of_symbols() {
653 let (keywords, _) = build(Std::C23, true);
654 assert!(!keywords.is_empty());
655 assert_eq!(keywords.len(), KEYWORDS.len());
656 }
657}