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