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 /// `__int128_t`, which gcc predeclares as a typedef of the signed one. It is a keyword
199 /// here for the reason `__builtin_va_list` is: the compiler is the only thing that can
200 /// name the type, and a name nothing declares has to come from somewhere.
201 Int128T,
202 /// `__uint128_t`, the unsigned one, which Apple's SDK headers use to declare the NEON
203 /// register state and which nothing else can spell.
204 UInt128T,
205 /// `__label__`, which declares a local label in a statement expression.
206 Label,
207 /// `__builtin_offsetof`, which is syntax rather than a function because it takes a type.
208 BuiltinOffsetof,
209 /// `__builtin_choose_expr`.
210 BuiltinChooseExpr,
211 /// `__builtin_types_compatible_p`.
212 BuiltinTypesCompatibleP,
213 /// `__builtin_va_arg`.
214 BuiltinVaArg,
215 /// `__builtin_va_list`, the target's type for a variable argument list.
216 BuiltinVaList,
217 /// `__builtin_va_start`.
218 BuiltinVaStart,
219 /// `__builtin_va_end`.
220 BuiltinVaEnd,
221 /// `__builtin_va_copy`.
222 BuiltinVaCopy,
223}
224
225impl Keyword {
226 /// The spelling to print in a diagnostic, which is the standard one where there is one.
227 ///
228 /// This walks the table, because it is only ever reached while writing a message and a
229 /// second array indexed by the enum would be one more place for the two to disagree.
230 #[must_use]
231 pub fn as_str(self) -> &'static str {
232 KEYWORDS
233 .iter()
234 .find(|entry| entry.keyword == self)
235 .map_or("keyword", |entry| entry.spelling)
236 }
237}
238
239/// The keywords of one dialect, ready to be looked up by symbol.
240///
241/// Built once per compilation, against the interner that compilation will use, before any
242/// source has been read.
243#[derive(Debug)]
244pub struct Keywords {
245 /// The symbol of the first entry. Everything below this is not a keyword, and so is
246 /// everything at or past the end of `active`.
247 base: u32,
248 /// The keyword each spelling means in this dialect, indexed by symbol minus `base`, and
249 /// [`None`] for a spelling this dialect leaves as an ordinary identifier.
250 active: Box<[Option<Keyword>]>,
251}
252
253impl Keywords {
254 /// Interns every keyword spelling and resolves which of them this dialect has.
255 ///
256 /// # Panics
257 ///
258 /// Panics if `interner` has already been given one of these spellings, since the symbols
259 /// would no longer be one run and every lookup after that would be wrong. Build this
260 /// first, immediately after the interner itself.
261 #[must_use]
262 pub fn new(interner: &mut Interner, std: Std, gnu: bool) -> Keywords {
263 let dialect = mask(std, gnu);
264 let mut base = 0;
265 let mut active = Vec::with_capacity(KEYWORDS.len());
266 for entry in KEYWORDS {
267 let symbol = interner.intern(entry.spelling).raw();
268 if active.is_empty() {
269 base = symbol;
270 }
271 let want = base + u32::try_from(active.len()).expect("the table is not that long");
272 assert!(
273 symbol == want,
274 "`{}` was interned before the keyword table was built",
275 entry.spelling
276 );
277 active.push((entry.dialects & dialect != 0).then_some(entry.keyword));
278 }
279 Keywords { base, active: active.into_boxed_slice() }
280 }
281
282 /// The keyword `symbol` is in this dialect, and [`None`] when it is an identifier.
283 #[must_use]
284 #[inline]
285 pub fn get(&self, symbol: Symbol) -> Option<Keyword> {
286 let index = symbol.raw().checked_sub(self.base)?;
287 // A `usize` cast rather than a conversion: the index is already known to fit, because
288 // the slice it indexes was built from symbols this interner handed out.
289 *self.active.get(index as usize)?
290 }
291
292 /// Whether `symbol` is a keyword in this dialect.
293 #[must_use]
294 #[inline]
295 pub fn contains(&self, symbol: Symbol) -> bool {
296 self.get(symbol).is_some()
297 }
298
299 /// How many spellings the table holds, active in this dialect or not.
300 #[must_use]
301 pub fn len(&self) -> usize {
302 self.active.len()
303 }
304
305 /// Whether the table is empty, which it never is.
306 #[must_use]
307 pub fn is_empty(&self) -> bool {
308 self.active.is_empty()
309 }
310}
311
312/// One bit per dialect, plus one for the GNU extensions.
313const C89: u8 = 1 << 0;
314const C99: u8 = 1 << 1;
315const C11: u8 = 1 << 2;
316const C17: u8 = 1 << 3;
317const C23: u8 = 1 << 4;
318const GNU: u8 = 1 << 5;
319
320/// A spelling that is a keyword in every dialect, GNU or not.
321const ALWAYS: u8 = C89 | C99 | C11 | C17 | C23 | GNU;
322/// From C99 onwards, and not in `-std=gnu89`. This is `restrict`, and it is the one place the
323/// GNU dialects are not a superset: gcc and clang both keep `restrict` out of `gnu89` and
324/// offer `__restrict` there instead.
325const SINCE_C99: u8 = C99 | C11 | C17 | C23;
326/// From C99 onwards, and in every GNU dialect including `gnu89`. This is `inline`.
327const SINCE_C99_OR_GNU: u8 = SINCE_C99 | GNU;
328/// C23 only. The lowercase spellings of the C11 keywords are here, and so is the rest of what
329/// C23 added, and `-std=gnu17` does not have any of them.
330const SINCE_C23: u8 = C23;
331/// C23, and every GNU dialect. This is `typeof`, which gcc has had for decades and which C23
332/// standardised, so `-std=c17` is the only place it is a variable name.
333const SINCE_C23_OR_GNU: u8 = C23 | GNU;
334/// The GNU dialects only. This is `asm`, which is a keyword in `gnu23` and an identifier in
335/// `c23`, where `__asm__` has to be written instead.
336const GNU_ONLY: u8 = GNU;
337
338/// A spelling, what it means, and where it is a keyword.
339struct Entry {
340 /// The spelling as it appears in source.
341 spelling: &'static str,
342 /// What the grammar makes of it.
343 keyword: Keyword,
344 /// The dialects it is a keyword in, as a mask of the bits above.
345 dialects: u8,
346}
347
348/// Shorthand, so that the table below reads as a table rather than a page of struct literals.
349const fn e(spelling: &'static str, keyword: Keyword, dialects: u8) -> Entry {
350 Entry { spelling, keyword, dialects }
351}
352
353/// Every keyword spelling in every dialect we support.
354///
355/// The order is the interning order and so decides the symbols, which nothing may depend on;
356/// it is grouped by where each spelling came from because that is how it is checked against a
357/// compiler. The first entry for a keyword is the spelling [`Keyword::as_str`] prints.
358static KEYWORDS: &[Entry] = &[
359 // The C89 keywords. Nothing has ever removed one, so all of them are unconditional.
360 e("auto", Keyword::Auto, ALWAYS),
361 e("break", Keyword::Break, ALWAYS),
362 e("case", Keyword::Case, ALWAYS),
363 e("char", Keyword::Char, ALWAYS),
364 e("const", Keyword::Const, ALWAYS),
365 e("continue", Keyword::Continue, ALWAYS),
366 e("default", Keyword::Default, ALWAYS),
367 e("do", Keyword::Do, ALWAYS),
368 e("double", Keyword::Double, ALWAYS),
369 e("else", Keyword::Else, ALWAYS),
370 e("enum", Keyword::Enum, ALWAYS),
371 e("extern", Keyword::Extern, ALWAYS),
372 e("float", Keyword::Float, ALWAYS),
373 e("for", Keyword::For, ALWAYS),
374 e("goto", Keyword::Goto, ALWAYS),
375 e("if", Keyword::If, ALWAYS),
376 e("int", Keyword::Int, ALWAYS),
377 e("long", Keyword::Long, ALWAYS),
378 e("register", Keyword::Register, ALWAYS),
379 e("return", Keyword::Return, ALWAYS),
380 e("short", Keyword::Short, ALWAYS),
381 e("signed", Keyword::Signed, ALWAYS),
382 e("sizeof", Keyword::Sizeof, ALWAYS),
383 e("static", Keyword::Static, ALWAYS),
384 e("struct", Keyword::Struct, ALWAYS),
385 e("switch", Keyword::Switch, ALWAYS),
386 e("typedef", Keyword::Typedef, ALWAYS),
387 e("union", Keyword::Union, ALWAYS),
388 e("unsigned", Keyword::Unsigned, ALWAYS),
389 e("void", Keyword::Void, ALWAYS),
390 e("volatile", Keyword::Volatile, ALWAYS),
391 e("while", Keyword::While, ALWAYS),
392 // The two C99 additions that are ordinary words. Everything else C99 and C11 added is
393 // spelled with a leading underscore precisely so that it could be turned on in the
394 // older dialects without breaking a program that had used the name, and both
395 // compilers do exactly that.
396 e("inline", Keyword::Inline, SINCE_C99_OR_GNU),
397 e("restrict", Keyword::Restrict, SINCE_C99),
398 e("_Bool", Keyword::Bool, ALWAYS),
399 e("_Complex", Keyword::Complex, ALWAYS),
400 e("_Imaginary", Keyword::Imaginary, ALWAYS),
401 e("_Alignas", Keyword::Alignas, ALWAYS),
402 e("_Alignof", Keyword::Alignof, ALWAYS),
403 e("_Atomic", Keyword::Atomic, ALWAYS),
404 e("_Generic", Keyword::Generic, ALWAYS),
405 e("_Noreturn", Keyword::Noreturn, ALWAYS),
406 e("_Static_assert", Keyword::StaticAssert, ALWAYS),
407 e("_Thread_local", Keyword::ThreadLocal, ALWAYS),
408 e("_BitInt", Keyword::BitInt, ALWAYS),
409 e("_Decimal32", Keyword::Decimal32, ALWAYS),
410 e("_Decimal64", Keyword::Decimal64, ALWAYS),
411 e("_Decimal128", Keyword::Decimal128, ALWAYS),
412 e("_Float16", Keyword::Float16, ALWAYS),
413 e("_Float32", Keyword::Float32, ALWAYS),
414 e("_Float64", Keyword::Float64, ALWAYS),
415 e("_Float128", Keyword::Float128, ALWAYS),
416 e("_Float32x", Keyword::Float32x, ALWAYS),
417 e("_Float64x", Keyword::Float64x, ALWAYS),
418 e("_Float128x", Keyword::Float128x, ALWAYS),
419 // C23, which spelled the C11 keywords as words and added its own. A program that used
420 // `bool` as a variable name still compiles in every earlier dialect, which is the
421 // whole reason this table is gated rather than fixed.
422 e("alignas", Keyword::Alignas, SINCE_C23),
423 e("alignof", Keyword::Alignof, SINCE_C23),
424 e("bool", Keyword::Bool, SINCE_C23),
425 e("constexpr", Keyword::Constexpr, SINCE_C23),
426 e("false", Keyword::False, SINCE_C23),
427 e("nullptr", Keyword::Nullptr, SINCE_C23),
428 e("static_assert", Keyword::StaticAssert, SINCE_C23),
429 e("thread_local", Keyword::ThreadLocal, SINCE_C23),
430 e("true", Keyword::True, SINCE_C23),
431 e("typeof", Keyword::Typeof, SINCE_C23_OR_GNU),
432 e("typeof_unqual", Keyword::TypeofUnqual, SINCE_C23),
433 e("asm", Keyword::Asm, GNU_ONLY),
434 // The GNU spellings. All of them are in the reserved namespace, so gcc turns them on
435 // in every dialect including `-std=c89`, and a header that has to work under `-std=`
436 // anything is written with these rather than with the words above.
437 e("__asm", Keyword::Asm, ALWAYS),
438 e("__asm__", Keyword::Asm, ALWAYS),
439 e("__alignof", Keyword::GnuAlignof, ALWAYS),
440 e("__alignof__", Keyword::GnuAlignof, ALWAYS),
441 e("__attribute", Keyword::Attribute, ALWAYS),
442 e("__attribute__", Keyword::Attribute, ALWAYS),
443 e("__auto_type", Keyword::AutoType, ALWAYS),
444 e("__complex", Keyword::Complex, ALWAYS),
445 e("__complex__", Keyword::Complex, ALWAYS),
446 e("__const", Keyword::Const, ALWAYS),
447 e("__extension__", Keyword::Extension, ALWAYS),
448 e("__imag", Keyword::Imag, ALWAYS),
449 e("__imag__", Keyword::Imag, ALWAYS),
450 e("__inline", Keyword::Inline, ALWAYS),
451 e("__inline__", Keyword::Inline, ALWAYS),
452 e("__int128", Keyword::Int128, ALWAYS),
453 e("__int128_t", Keyword::Int128T, ALWAYS),
454 e("__label__", Keyword::Label, ALWAYS),
455 e("__real", Keyword::Real, ALWAYS),
456 e("__real__", Keyword::Real, ALWAYS),
457 e("__restrict", Keyword::Restrict, ALWAYS),
458 e("__restrict__", Keyword::Restrict, ALWAYS),
459 e("__signed", Keyword::Signed, ALWAYS),
460 e("__signed__", Keyword::Signed, ALWAYS),
461 // gcc's own diagnostics keep `__thread` and `_Thread_local` apart, but in C they are
462 // one storage class with two spellings, so the parser is given one keyword.
463 e("__thread", Keyword::ThreadLocal, ALWAYS),
464 e("__typeof", Keyword::Typeof, ALWAYS),
465 e("__typeof__", Keyword::Typeof, ALWAYS),
466 e("__typeof_unqual", Keyword::TypeofUnqual, ALWAYS),
467 e("__typeof_unqual__", Keyword::TypeofUnqual, ALWAYS),
468 e("__uint128_t", Keyword::UInt128T, ALWAYS),
469 e("__volatile", Keyword::Volatile, ALWAYS),
470 e("__volatile__", Keyword::Volatile, ALWAYS),
471 // The builtins that are syntax rather than functions, because an argument of theirs is a
472 // type name, or is not evaluated, or is the object itself rather than its value, or because
473 // what they name is a type. Everything else called `__builtin_` is an ordinary identifier
474 // that resolves to a declaration, and belongs nowhere near this table.
475 e("__builtin_offsetof", Keyword::BuiltinOffsetof, ALWAYS),
476 e("__builtin_choose_expr", Keyword::BuiltinChooseExpr, ALWAYS),
477 e("__builtin_types_compatible_p", Keyword::BuiltinTypesCompatibleP, ALWAYS),
478 e("__builtin_va_arg", Keyword::BuiltinVaArg, ALWAYS),
479 // The rest of the variable argument family. `__builtin_va_list` names a type, and the other
480 // three are handed the list object rather than its value, since what they do is write it.
481 // gcc declares those three as functions taking the address of a list and has its own header
482 // pass the list itself, which works because the list is an array on the targets where the
483 // difference shows. Taking the address here is the same thing without the special case.
484 e("__builtin_va_list", Keyword::BuiltinVaList, ALWAYS),
485 e("__builtin_va_start", Keyword::BuiltinVaStart, ALWAYS),
486 e("__builtin_va_end", Keyword::BuiltinVaEnd, ALWAYS),
487 e("__builtin_va_copy", Keyword::BuiltinVaCopy, ALWAYS),
488];
489
490/// The bits a dialect matches, which is its own and the GNU one when the extensions are on.
491const fn mask(std: Std, gnu: bool) -> u8 {
492 let dialect = match std {
493 Std::C89 => C89,
494 Std::C99 => C99,
495 Std::C11 => C11,
496 Std::C17 => C17,
497 Std::C23 => C23,
498 };
499 if gnu { dialect | GNU } else { dialect }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505
506 /// The keywords of one dialect, and an interner that has them and nothing else.
507 fn build(std: Std, gnu: bool) -> (Keywords, Interner) {
508 let mut interner = Interner::new();
509 let keywords = Keywords::new(&mut interner, std, gnu);
510 (keywords, interner)
511 }
512
513 /// What `text` means in this dialect, having been interned the way the scanner would.
514 fn lookup(std: Std, gnu: bool, text: &str) -> Option<Keyword> {
515 let (keywords, mut interner) = build(std, gnu);
516 keywords.get(interner.intern(text))
517 }
518
519 #[test]
520 fn a_word_the_language_has_always_had_is_a_keyword_in_every_dialect() {
521 for std in [Std::C89, Std::C99, Std::C11, Std::C17, Std::C23] {
522 for gnu in [false, true] {
523 assert_eq!(lookup(std, gnu, "int"), Some(Keyword::Int));
524 assert_eq!(lookup(std, gnu, "sizeof"), Some(Keyword::Sizeof));
525 assert_eq!(lookup(std, gnu, "_Complex"), Some(Keyword::Complex));
526 }
527 }
528 }
529
530 #[test]
531 fn a_name_a_program_chose_is_never_a_keyword() {
532 // Including one that only just misses, and one that reads like a keyword and is not.
533 for name in ["x", "intx", "in", "INT", "fortran", "ordinary", "__builtin_expect"] {
534 assert_eq!(lookup(Std::C23, true, name), None, "{name} is not a keyword");
535 }
536 }
537
538 #[test]
539 fn restrict_arrived_in_c99_and_gnu89_did_not_get_it_early() {
540 // Measured: gcc and clang both leave `restrict` out of `-std=gnu89`, which is the one
541 // place the GNU dialect is not a superset of the standard one it is based on.
542 assert_eq!(lookup(Std::C89, false, "restrict"), None);
543 assert_eq!(lookup(Std::C89, true, "restrict"), None);
544 assert_eq!(lookup(Std::C99, false, "restrict"), Some(Keyword::Restrict));
545 // `__restrict__` is how a header written for both says it, and it works in c89.
546 assert_eq!(lookup(Std::C89, false, "__restrict__"), Some(Keyword::Restrict));
547 }
548
549 #[test]
550 fn inline_arrived_in_c99_and_gnu89_did_get_it_early() {
551 assert_eq!(lookup(Std::C89, false, "inline"), None);
552 assert_eq!(lookup(Std::C89, true, "inline"), Some(Keyword::Inline));
553 assert_eq!(lookup(Std::C99, false, "inline"), Some(Keyword::Inline));
554 }
555
556 #[test]
557 fn typeof_is_a_gnu_extension_that_c23_made_standard() {
558 assert_eq!(lookup(Std::C17, false, "typeof"), None);
559 assert_eq!(lookup(Std::C17, true, "typeof"), Some(Keyword::Typeof));
560 assert_eq!(lookup(Std::C23, false, "typeof"), Some(Keyword::Typeof));
561 // `typeof_unqual` is the C23 half only, which is what both compilers do.
562 assert_eq!(lookup(Std::C17, true, "typeof_unqual"), None);
563 assert_eq!(lookup(Std::C23, false, "typeof_unqual"), Some(Keyword::TypeofUnqual));
564 assert_eq!(lookup(Std::C17, false, "__typeof__"), Some(Keyword::Typeof));
565 }
566
567 #[test]
568 fn asm_is_the_one_word_c23_still_does_not_have() {
569 assert_eq!(lookup(Std::C23, false, "asm"), None);
570 assert_eq!(lookup(Std::C23, true, "asm"), Some(Keyword::Asm));
571 assert_eq!(lookup(Std::C89, false, "__asm__"), Some(Keyword::Asm));
572 }
573
574 #[test]
575 fn the_c23_words_are_variable_names_in_every_earlier_dialect() {
576 let added = [
577 ("alignas", Keyword::Alignas),
578 ("alignof", Keyword::Alignof),
579 ("bool", Keyword::Bool),
580 ("constexpr", Keyword::Constexpr),
581 ("false", Keyword::False),
582 ("nullptr", Keyword::Nullptr),
583 ("static_assert", Keyword::StaticAssert),
584 ("thread_local", Keyword::ThreadLocal),
585 ("true", Keyword::True),
586 ];
587 for (spelling, keyword) in added {
588 assert_eq!(lookup(Std::C17, true, spelling), None, "{spelling} in gnu17");
589 assert_eq!(lookup(Std::C23, false, spelling), Some(keyword), "{spelling} in c23");
590 }
591 // The underscore spellings they replaced go on working, which is what lets one header
592 // serve both.
593 assert_eq!(lookup(Std::C17, false, "_Static_assert"), Some(Keyword::StaticAssert));
594 assert_eq!(lookup(Std::C23, false, "_Static_assert"), Some(Keyword::StaticAssert));
595 }
596
597 #[test]
598 fn two_spellings_of_one_thing_are_one_keyword() {
599 for spelling in ["const", "__const"] {
600 assert_eq!(lookup(Std::C23, true, spelling), Some(Keyword::Const));
601 }
602 for spelling in ["_Thread_local", "thread_local", "__thread"] {
603 assert_eq!(lookup(Std::C23, true, spelling), Some(Keyword::ThreadLocal));
604 }
605 // And the one pair that looks like two spellings and is not. GNU's `__alignof__`
606 // reports the preferred alignment, C's `_Alignof` the required one.
607 assert_ne!(
608 lookup(Std::C23, true, "__alignof__"),
609 lookup(Std::C23, true, "_Alignof"),
610 "the two alignments are different questions"
611 );
612 }
613
614 #[test]
615 fn every_keyword_prints_a_spelling_that_is_that_keyword() {
616 for entry in KEYWORDS {
617 let printed = entry.keyword.as_str();
618 let found = KEYWORDS
619 .iter()
620 .find(|other| other.spelling == printed)
621 .unwrap_or_else(|| panic!("{printed} is not in the table"));
622 assert_eq!(found.keyword, entry.keyword, "{printed} prints for the wrong keyword");
623 }
624 }
625
626 #[test]
627 fn no_spelling_is_in_the_table_twice() {
628 // A repeat would be interned once, the run of symbols would be short by one, and
629 // `Keywords::new` would refuse to build at all. Better to say why here.
630 let mut seen: Vec<&str> = KEYWORDS.iter().map(|entry| entry.spelling).collect();
631 seen.sort_unstable();
632 let count = seen.len();
633 seen.dedup();
634 assert_eq!(seen.len(), count, "a spelling appears twice in the table");
635 }
636
637 #[test]
638 fn recognition_does_not_depend_on_what_was_interned_afterwards() {
639 // The property the whole design rests on: the keywords are one run at the bottom of
640 // the table, so an identifier interned later cannot land inside it however many there
641 // are.
642 let (keywords, mut interner) = build(Std::C23, true);
643 for i in 0..1000 {
644 let symbol = interner.intern(&format!("name{i}"));
645 assert_eq!(keywords.get(symbol), None);
646 }
647 assert_eq!(keywords.get(interner.intern("while")), Some(Keyword::While));
648 }
649
650 #[test]
651 #[should_panic(expected = "`static` was interned before the keyword table was built")]
652 fn an_interner_that_already_has_a_keyword_in_it_is_refused() {
653 // Silently building a table whose symbols are not one run would mean a compiler that
654 // recognised the wrong words, which is not a failure anybody would find quickly.
655 let mut interner = Interner::new();
656 interner.intern("static");
657 let _ = Keywords::new(&mut interner, Std::C23, true);
658 }
659
660 #[test]
661 fn a_lookup_is_a_bounds_check_on_one_run_of_symbols() {
662 let (keywords, _) = build(Std::C23, true);
663 assert!(!keywords.is_empty());
664 assert_eq!(keywords.len(), KEYWORDS.len());
665 }
666}