cpp_parser 0.3.0

A lossless C++ parser over the preprocessed text: the tree every layer above it reads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
use crate::{kind::CppTokenKind, parser_error::CppParseError, text::Reader};

use super::{
    char_kind::{is_name_continue, is_name_continue_with_dollar, is_name_start_with_dollar},
    lexer_config::LexerConfig,
    token_data::CppTokenData,
};

pub struct CppLexer<'a> {
    reader: Reader<'a>,
    lexer_config: LexerConfig,
    errors: &'a mut Vec<CppParseError>,
}

impl<'a> CppLexer<'a> {
    pub fn new(
        text: &'a str,
        lexer_config: LexerConfig,
        errors: &'a mut Vec<CppParseError>,
    ) -> CppLexer<'a> {
        CppLexer {
            reader: Reader::new(text),
            lexer_config,
            errors,
        }
    }

    pub fn tokenize(&mut self) -> Vec<CppTokenData> {
        let mut tokens = vec![];

        while !self.reader.is_eof() {
            let kind = self.lex();
            if kind == CppTokenKind::Eof {
                break;
            }

            self.push(tokens.as_mut(), kind);
        }

        tokens
    }

    /// Push the token just lexed, **broken up when it is one of the three the grammar cannot use whole**.
    ///
    /// # Maximal munch runs first, and is not negotiable
    ///
    /// [`CppLexer::lex`] takes the longest run of characters that could be one token, because that is translation
    /// phase 3 and it is what makes `a->b` one token while `a - >b` is three. Nothing here changes that.
    ///
    /// What maximal munch produces, though, is a **preprocessing token**, and the grammar works *above* the
    /// preprocessor. `>>` is one preprocessing token and **two `>` tokens**, and only the grammar knows which
    /// reading a given one has — `std::vector<std::vector<int>>` ends in two closers, `a >> b` is a shift, and the
    /// tokens are the same. So the split belongs to the end of phase 3 rather than to the parser.
    ///
    /// # Which three, and why only those
    ///
    /// Exactly the spellings whose **first character is a `>` that can close a template-argument-list**: `>>`,
    /// `>=` and `>>=`. `<<`, `<=`, `->`, `::` and `...` are pushed whole — none of them can close a list, so
    /// breaking them would buy nothing and cost every consumer of those tokens a join.
    ///
    /// # What this replaces, and the layer it deletes
    ///
    /// The parser used to split them **on demand, in place**, with `Vec::insert` — which shifts every token after
    /// the cursor, so one split cost `O(tokens remaining)` and a file needing `k` of them cost `O(k · n)`. Measured
    /// on the 3.3 MB cooked `<vector>` stream: **2759 ms**, with the per-byte cost climbing 244 → 847 µs/KB down the
    /// ladder; the same text with `>>` written `> >` parsed in 793 ms at a flat 243 µs/KB. Doing it here costs one
    /// `Vec` push per part and nothing after that.
    ///
    /// The other half of the same fact is the **compensation** the old spelling forced on the grammar: the angle
    /// scanners counted a `RightShift` as *two* brackets — `angles += 2`, `depth -= 2` — each one a place that had
    /// to know how the lexer spells things, and `types.rs` even said so in a comment ("the lexer has already glued
    /// `>>` into a single `RightShift`"). With every `>` one bracket, those collapse.
    fn push(&self, tokens: &mut Vec<CppTokenData>, kind: CppTokenKind) {
        let range = self.reader.saved_range();
        let start = range.start_offset;

        // One byte per part, and the parts are contiguous by construction: the lexer only produces these three
        // after consuming exactly these characters.
        let part = |at: usize, kind| CppTokenData::new(kind, crate::text::SourceRange::new(at, 1));

        match kind {
            CppTokenKind::RightShift => {
                tokens.push(part(start, CppTokenKind::Greater));
                tokens.push(part(start + 1, CppTokenKind::Greater));
            }
            CppTokenKind::GreaterEqual => {
                tokens.push(part(start, CppTokenKind::Greater));
                tokens.push(part(start + 1, CppTokenKind::Assign));
            }
            CppTokenKind::RightShiftAssign => {
                tokens.push(part(start, CppTokenKind::Greater));
                tokens.push(part(start + 1, CppTokenKind::Greater));
                tokens.push(part(start + 2, CppTokenKind::Assign));
            }
            _ => tokens.push(CppTokenData::new(kind, range)),
        }
    }

    /// Convert identifier to keyword token if it matches a C++ keyword
    /// **Is this standard-gated keyword a keyword here?** — `consteval` is one from C++20 and an ordinary identifier
    /// before it, and a project that used the name for a variable is entitled to keep doing so. The guard, not the level,
    /// is what decides: a C configuration answers differently from a C++ one, which the old enum could not express.
    fn accepts(&self, feature: crate::features::Feature) -> bool {
        self.lexer_config.language().support(feature)
    }

    fn name_to_kind(&self, name: &str) -> CppTokenKind {
        match name {
            // Basic keywords
            "auto" => CppTokenKind::AutoKeyword,
            "bool" => CppTokenKind::BoolLiteral,
            "break" => CppTokenKind::BreakKeyword,
            "case" => CppTokenKind::CaseKeyword,
            "catch" => CppTokenKind::CatchKeyword,
            "char" => CppTokenKind::CharKeyword,
            "class" => CppTokenKind::ClassKeyword,
            "const" => CppTokenKind::ConstKeyword,
            "continue" => CppTokenKind::ContinueKeyword,
            "default" => CppTokenKind::DefaultKeyword,
            "delete" => CppTokenKind::DeleteKeyword,
            "do" => CppTokenKind::DoKeyword,
            "double" => CppTokenKind::DoubleKeyword,
            "else" => CppTokenKind::ElseKeyword,
            "enum" => CppTokenKind::EnumKeyword,
            "extern" => CppTokenKind::ExternKeyword,
            "false" => CppTokenKind::FalseKeyword,
            "float" => CppTokenKind::FloatKeyword,
            "for" => CppTokenKind::ForKeyword,
            "goto" => CppTokenKind::GotoKeyword,
            "if" => CppTokenKind::IfKeyword,
            "inline" => CppTokenKind::InlineKeyword,
            "int" => CppTokenKind::IntKeyword,
            "long" => CppTokenKind::LongKeyword,
            "new" => CppTokenKind::NewKeyword,
            "operator" => CppTokenKind::OperatorKeyword,
            "private" => CppTokenKind::PrivateKeyword,
            "protected" => CppTokenKind::ProtectedKeyword,
            "public" => CppTokenKind::PublicKeyword,
            "return" => CppTokenKind::ReturnKeyword,
            "short" => CppTokenKind::ShortKeyword,
            "signed" => CppTokenKind::SignedKeyword,
            "sizeof" => CppTokenKind::SizeofKeyword,
            "static" => CppTokenKind::StaticKeyword,
            "struct" => CppTokenKind::StructKeyword,
            "switch" => CppTokenKind::SwitchKeyword,
            "this" => CppTokenKind::ThisKeyword,
            "throw" => CppTokenKind::ThrowKeyword,
            "true" => CppTokenKind::TrueKeyword,
            "try" => CppTokenKind::TryKeyword,
            "typedef" => CppTokenKind::TypedefKeyword,
            "typeid" => CppTokenKind::TypeidKeyword,
            "typename" => CppTokenKind::TypenameKeyword,
            "union" => CppTokenKind::UnionKeyword,
            "unsigned" => CppTokenKind::UnsignedKeyword,
            "using" => CppTokenKind::UsingKeyword,
            "virtual" => CppTokenKind::VirtualKeyword,
            "void" => CppTokenKind::VoidKeyword,
            "volatile" => CppTokenKind::VolatileKeyword,
            "while" => CppTokenKind::WhileKeyword,

            // C++11 and later keywords
            "alignas" if self.accepts(crate::features::Feature::AlignasCpp) => {
                CppTokenKind::AlignasKeyword
            }
            "alignof" => CppTokenKind::AlignofKeyword,
            "constexpr" if self.accepts(crate::features::Feature::Constexpr) => {
                CppTokenKind::ConstexprKeyword
            }
            "consteval" if self.accepts(crate::features::Feature::Consteval) => {
                CppTokenKind::ConstevalKeyword
            }
            "constinit" if self.accepts(crate::features::Feature::Constinit) => {
                CppTokenKind::ConstinitKeyword
            }
            "decltype" => CppTokenKind::DecltypeKeyword,

            // The **GNU spellings of constructs that are standard keywords**, mapped to the same kind because a
            // compiler treats them as the keyword they are: `typedef __typeof__(x) T;` is a declaration whose
            // specifiers are a type, by the same rule that makes `typedef decltype(x) T;` one. Reading them as
            // ordinary identifiers instead is what `typedef __typeof__(nullptr) nullptr_t;` did — the name came
            // out as a *declarator* and the declaration as `expected ;` (measured in `stddef.h`,
            // `bits/stl_heap.h`, `bits/stl_uninitialized.h` of the standard-library closure).
            //
            // The tree keeps the spelling: a token's text is the source text, so a consumer that needs to tell
            // `__typeof__` from `decltype` reads the token, not the kind — and one that asks "is this a type
            // expression?" gets the right answer for both.
            // …and the spelling without the underscores, which GCC has accepted since before `decltype` existed and
            // which real headers write (`typeof(x) y = …;` in glibc's `sys/types.h`). Measured: `__typeof__` parsed and
            // `typeof` did not, which is the worst kind of gap — one spelling of a construct working and the other not.
            // **`typeof` is a feature, not a keyword.** C23 and GNU in every mode; `__typeof__` and `__typeof` are the GNU
            // spellings, `__decltype` is MSVC's, and all four are the same token *when the configuration says so* and an
            // ordinary identifier when it does not — which is what a strict `-std=c++20` parse must see, and what the
            // `typeof` test in `extensions_gnu.rs` pins from the other side.
            "__typeof__" | "__typeof" | "__decltype" | "typeof" | "typeof_unqual"
                if self
                    .lexer_config
                    .language()
                    .support(crate::features::Feature::Typeof) =>
            {
                CppTokenKind::DecltypeKeyword
            }
            // **The four named casts.** Absent until now, and their absence was invisible: an unrecognised
            // `static_cast` is an *identifier*, so `static_cast<int>(x)` lexes as `static_cast` `<` `int` `>` `(`
            // `x` `)` and parses — without an error — as a comparison chain. Measured: `auto x =
            // static_cast<int>(a);` refused with `UnknownType("static_cast<int>")`, which is the left half of that
            // chain.
            "static_cast" => CppTokenKind::StaticCastKeyword,
            "dynamic_cast" => CppTokenKind::DynamicCastKeyword,
            "const_cast" => CppTokenKind::ConstCastKeyword,
            "reinterpret_cast" => CppTokenKind::ReinterpretCastKeyword,
            "explicit" => CppTokenKind::ExplicitKeyword,
            "export" => CppTokenKind::ExportKeyword,
            "mutable" => CppTokenKind::MutableKeyword,
            "friend" => CppTokenKind::FriendKeyword,
            "register" => CppTokenKind::RegisterKeyword,
            "namespace" => CppTokenKind::NamespaceKeyword,
            "noexcept" => CppTokenKind::NoexceptKeyword,
            "nullptr" if self.accepts(crate::features::Feature::Nullptr) => {
                CppTokenKind::NullptrKeyword
            }
            "static_assert"
                if self.accepts(crate::features::Feature::StaticAssert)
                    || self.accepts(crate::features::Feature::StaticAssertC) =>
            {
                CppTokenKind::StaticAssertKeyword
            }
            "template" => CppTokenKind::TemplateKeyword,
            "thread_local" if self.accepts(crate::features::Feature::ThreadLocal) => {
                CppTokenKind::ThreadLocalKeyword
            }

            // C++20 keywords
            // `concept` and `requires` are deliberately **not** here. Both are contextual keywords — the grammar
            // reads them as keywords in the positions the standard gives them a meaning, and as ordinary names
            // everywhere else — so the lexer hands them over as identifiers and the grammar decides. See
            // [`crate::grammar::cpp::is_contextual_keyword`].
            "co_await" if self.accepts(crate::features::Feature::Coroutines) => {
                CppTokenKind::CoAwaitKeyword
            }
            "co_return" if self.accepts(crate::features::Feature::Coroutines) => {
                CppTokenKind::CoReturnKeyword
            }
            "co_yield" if self.accepts(crate::features::Feature::Coroutines) => {
                CppTokenKind::CoYieldKeyword
            }

            // Not a keyword, return as identifier
            _ => CppTokenKind::Identifier,
        }
    }

    /// Main lexing function - tokenizes the next token from the input
    fn lex(&mut self) -> CppTokenKind {
        self.reader.reset_buff();

        match self.reader.current_char() {
            // Whitespace
            '\n' | '\r' => self.lex_newline(),
            // **A form feed and a vertical tab are whitespace too**. The standard lists five whitespace
            // characters (`space`, horizontal tab, newline, vertical tab, form feed) and the Windows SDK writes a
            // form feed as a *page break*: `um/winnt.h:9968` is the two bytes `0C 0D` on a line of its own, and
            // `um/winioctl.h:9838` the same — eleven messages of `unrecognized character` over the SDK corpus, for
            // a character no compiler has ever refused outside a literal. `\u{feff}` is a byte-order mark, which is
            // whitespace here because a BOM at the start of a file is the file's own text — and **the predicate is
            // shared with `lex_whitespace`**, which is the lesson of the first attempt at this: adding the
            // character to the dispatch alone left the consumer matching nothing, and a zero-length whitespace
            // token at a fixed offset is an infinite loop that eats memory (48 GB before it died).
            ' ' | '\t' | '\u{b}' | '\u{c}' | '\u{feff}' => self.lex_whitespace(),

            // Single character tokens
            '(' => {
                self.reader.bump();
                CppTokenKind::LeftParen
            }
            ')' => {
                self.reader.bump();
                CppTokenKind::RightParen
            }
            '{' => {
                self.reader.bump();
                CppTokenKind::LeftBrace
            }
            '}' => {
                self.reader.bump();
                CppTokenKind::RightBrace
            }
            '[' => {
                self.reader.bump();
                CppTokenKind::LeftBracket
            }
            ']' => {
                self.reader.bump();
                CppTokenKind::RightBracket
            }
            ';' => {
                self.reader.bump();
                CppTokenKind::Semicolon
            }
            ',' => {
                self.reader.bump();
                CppTokenKind::Comma
            }
            '~' => {
                self.reader.bump();
                CppTokenKind::Tilde
            }
            '?' => {
                self.reader.bump();
                CppTokenKind::Question
            }

            // Operators that can be single or multi-character
            '+' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::PlusAssign
                    }
                    '+' => {
                        self.reader.bump();
                        CppTokenKind::PlusPlus
                    }
                    _ => CppTokenKind::Plus,
                }
            }
            '-' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::MinusAssign
                    }
                    '-' => {
                        self.reader.bump();
                        CppTokenKind::MinusMinus
                    }
                    '>' => {
                        self.reader.bump();
                        if self.reader.current_char() == '*' {
                            self.reader.bump();
                            CppTokenKind::ArrowStar
                        } else {
                            CppTokenKind::Arrow
                        }
                    }
                    _ => CppTokenKind::Minus,
                }
            }
            '*' => {
                self.reader.bump();
                if self.reader.current_char() == '=' {
                    self.reader.bump();
                    CppTokenKind::StarAssign
                } else {
                    CppTokenKind::Star
                }
            }
            '/' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::SlashAssign
                    }
                    '/' => {
                        // Single-line comment
                        self.reader.bump();
                        self.reader.eat_while(|ch| ch != '\n' && ch != '\r');
                        CppTokenKind::LineComment
                    }
                    '*' => {
                        // Block comment
                        self.reader.bump();
                        self.lex_block_comment()
                    }
                    _ => CppTokenKind::Slash,
                }
            }
            '%' => {
                self.reader.bump();
                if self.reader.current_char() == '=' {
                    self.reader.bump();
                    CppTokenKind::PercentAssign
                } else {
                    CppTokenKind::Percent
                }
            }
            '=' => {
                self.reader.bump();
                if self.reader.current_char() == '=' {
                    self.reader.bump();
                    CppTokenKind::Equal
                } else {
                    CppTokenKind::Assign
                }
            }
            '!' => {
                self.reader.bump();
                if self.reader.current_char() == '=' {
                    self.reader.bump();
                    CppTokenKind::NotEqual
                } else {
                    CppTokenKind::LogicalNot
                }
            }
            '<' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '=' => {
                        self.reader.bump();
                        if self.reader.current_char() == '>' {
                            self.reader.bump();
                            CppTokenKind::Spaceship
                        } else {
                            CppTokenKind::LessEqual
                        }
                    }
                    '<' => {
                        self.reader.bump();
                        if self.reader.current_char() == '=' {
                            self.reader.bump();
                            CppTokenKind::LeftShiftAssign
                        } else {
                            CppTokenKind::LeftShift
                        }
                    }
                    _ => CppTokenKind::Less,
                }
            }
            '>' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::GreaterEqual
                    }
                    '>' => {
                        self.reader.bump();
                        if self.reader.current_char() == '=' {
                            self.reader.bump();
                            CppTokenKind::RightShiftAssign
                        } else {
                            CppTokenKind::RightShift
                        }
                    }
                    _ => CppTokenKind::Greater,
                }
            }
            '&' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '&' => {
                        self.reader.bump();
                        CppTokenKind::LogicalAnd
                    }
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::AmpersandAssign
                    }
                    _ => CppTokenKind::Ampersand,
                }
            }
            '|' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '|' => {
                        self.reader.bump();
                        CppTokenKind::LogicalOr
                    }
                    '=' => {
                        self.reader.bump();
                        CppTokenKind::PipeAssign
                    }
                    _ => CppTokenKind::Pipe,
                }
            }
            '^' => {
                self.reader.bump();
                if self.reader.current_char() == '=' {
                    self.reader.bump();
                    CppTokenKind::CaretAssign
                } else {
                    CppTokenKind::Caret
                }
            }
            ':' => {
                self.reader.bump();
                if self.reader.current_char() == ':' {
                    self.reader.bump();
                    CppTokenKind::Scope
                } else {
                    CppTokenKind::Colon
                }
            }
            '.' => {
                self.reader.bump();
                match self.reader.current_char() {
                    '.' => {
                        self.reader.bump();
                        if self.reader.current_char() == '.' {
                            self.reader.bump();
                            CppTokenKind::Ellipsis
                        } else {
                            // Not a valid token, but we handle it gracefully
                            CppTokenKind::Unknown
                        }
                    }
                    '*' => {
                        self.reader.bump();
                        CppTokenKind::DotStar
                    }
                    '0'..='9' => {
                        // Decimal number starting with '.', e.g. `.5`. `.` has already been
                        // consumed, so tell `lex_number` to skip its own first-character step.
                        self.lex_number()
                    }
                    _ => CppTokenKind::Dot,
                }
            }
            '#' => {
                self.reader.bump();
                if self.reader.current_char() == '#' {
                    self.reader.bump();
                    CppTokenKind::HashHash
                } else {
                    CppTokenKind::Hash
                }
            }

            // String and character literals, including the `u8`/`u`/`U`/`L` encoding prefixes and
            // the `R` raw-string prefix.
            '"' => self.lex_string_literal(),
            '\'' => self.lex_char_literal(),

            // A backslash starts either a line splice or nothing valid at all.
            '\\' => self.lex_backslash(),

            // Numbers
            '0'..='9' => self.lex_number(),

            // Identifiers, keywords, and the prefixed literals that look like identifiers at the
            // first character (`u8"x"`, `L'c'`, `R"(...)"`).
            ch if is_name_start_with_dollar(ch, self.lexer_config.dollar_in_identifier) => {
                self.lex_identifier_like()
            }

            // End of file
            _ if self.reader.is_eof() => CppTokenKind::Eof,

            // Unknown character
            _ => {
                self.reader.bump();
                // Still emit a token, so the tree stays lossless, but say so: an unrecognised
                // character is either a typo in the source or a gap in the lexer, and both should
                // be visible rather than silently absorbed into the surrounding construct.
                self.errors.push(CppParseError::syntax_error_from(
                    &format!(
                        "unrecognized character `{}`",
                        self.reader.current_saved_text()
                    ),
                    self.reader.saved_range(),
                ));
                CppTokenKind::Unknown
            }
        }
    }

    /// Lex a backslash: a line splice, the start of a universal character name, or an error.
    ///
    /// Translation phase 2 deletes `\` immediately followed by a newline. That makes the splice
    /// *trivia* for the parser, but it is not ordinary whitespace: a directive such as
    /// `#define FOO \<newline> bar` continues across it, and the preprocessor layer needs to see
    /// the splice to know that.
    fn lex_backslash(&mut self) -> CppTokenKind {
        match self.reader.lookahead(1) {
            '\n' | '\r' => {
                self.reader.bump();
                self.eat_newline();
                CppTokenKind::LineContinuation
            }
            // `\u00e9` is an identifier spelled with a universal character name, which is the only
            // way an identifier can begin with something other than an `XID_Start` character.
            // `lex_identifier_like` records the diagnostic itself when the escape is malformed, so
            // there is exactly one error per bad escape.
            'u' | 'U' => self.lex_identifier_like(),
            _ => {
                self.reader.bump();
                self.errors.push(CppParseError::syntax_error_from(
                    &t!("stray `\\` outside of a string or line splice"),
                    self.reader.saved_range(),
                ));
                CppTokenKind::Unknown
            }
        }
    }

    /// Consume the current newline character, including the second half of a `\r\n` or `\n\r` pair.
    fn eat_newline(&mut self) {
        match self.reader.current_char() {
            '\n' => {
                self.reader.bump();
                if self.reader.current_char() == '\r' {
                    self.reader.bump();
                }
            }
            '\r' => {
                self.reader.bump();
                if self.reader.current_char() == '\n' {
                    self.reader.bump();
                }
            }
            _ => {}
        }
    }

    /// Is this a character the lexer reads as **trivia whitespace** — run together into one token?
    ///
    /// One predicate for the two places that have to agree: the dispatch arm that *starts* a whitespace token and
    /// `lex_whitespace`, which *extends* it. The standard's whitespace is five characters (`space`, horizontal tab,
    /// newline, vertical tab, form feed); newline has its own token, and a byte-order mark is here because a BOM is
    /// the file's own text rather than an unrecognised character — see `lex_whitespace`.
    fn is_trivia_whitespace(ch: char) -> bool {
        matches!(ch, ' ' | '\t' | '\u{b}' | '\u{c}' | '\u{feff}')
    }

    /// A **byte-order mark** is whitespace here. `\u{feff}` at the start of a file is the BOM that Visual Studio
    /// and a good many Windows editors write, and the standard has the implementation drop it in translation
    /// phase 1 — so a file saved that way is a perfectly good translation unit. Treating it as an unrecognised
    /// character reported `unrecognized character \u{feff}` at offset 0, which is the worst place a diagnostic can
    /// land: *every* file the editor opened with a BOM looked broken at its first byte (37 of the 200 files in the
    /// first real C++ project put in front of this parser). It is also the zero-width no-break space, so the same
    /// character in the middle of a file is trivia for the same reason.
    fn lex_whitespace(&mut self) -> CppTokenKind {
        // **The same set the dispatch matches**. The two ran apart for exactly one character's worth of
        // time: adding `\u{c}` to the dispatch arm above without adding it *here* made this loop consume nothing
        // and the lexer hand back a zero-length `Whitespace` token at the same offset, for ever — every file with a
        // form feed in it hung, and the token vector grew until the process died with
        // `memory allocation of 51539607552 bytes failed`. Measured on a two-byte file (`0C 0D`), which is what
        // `um/winnt.h:9968` is. One predicate, one place: `is_trivia_whitespace` below.
        self.reader.eat_while(Self::is_trivia_whitespace);
        CppTokenKind::Whitespace
    }

    /// Lex newline characters
    fn lex_newline(&mut self) -> CppTokenKind {
        self.eat_newline();
        CppTokenKind::Newline
    }

    /// Lex block comment /* ... */
    ///
    /// Block comments do **not** nest in C++ (`/* /* */` ends at the first `*/`), unlike the Lua
    /// this lexer was ported from. Treating them as nesting silently swallows everything up to the
    /// next `*/` and reports an "unfinished comment" for perfectly valid code.
    fn lex_block_comment(&mut self) -> CppTokenKind {
        while !self.reader.is_eof() {
            match self.reader.current_char() {
                '*' => {
                    self.reader.bump();
                    if self.reader.current_char() == '/' {
                        self.reader.bump();
                        return CppTokenKind::BlockComment;
                    }
                }
                _ => {
                    self.reader.bump();
                }
            }
        }

        self.errors.push(CppParseError::syntax_error_from(
            &t!("unfinished block comment"),
            self.reader.saved_range(),
        ));
        CppTokenKind::BlockComment
    }

    /// Lex something that starts like an identifier: a keyword, a name, or a prefixed literal.
    ///
    /// The four prefixes `u8`, `u`, `U` and `L` are shared between character/string literals and
    /// ordinary identifiers, so `u8"x"` and `u8x` have to be told apart by lookahead. `R` and `LR`
    /// etc. additionally introduce raw strings, where the "string" has completely different
    /// escaping rules.
    /// Lex something that starts like an identifier: a keyword, a name, or a prefixed literal.
    ///
    /// The four prefixes `u8`, `u`, `U` and `L` are shared between character/string literals and
    /// ordinary identifiers, so `u8"x"` and `u8x` have to be told apart by lookahead. `R` and `LR`
    /// etc. additionally introduce raw strings, where the "string" has completely different
    /// escaping rules.
    ///
    /// Also entered for a leading `\`, which can only be a universal character name here.
    fn lex_identifier_like(&mut self) -> CppTokenKind {
        let dollar = self.lexer_config.dollar_in_identifier;

        // The encoding prefixes are not all one character: `u8` is two, and `u8R`/`uR` add the raw
        // marker on top. Getting the length wrong here does not merely mislabel a token, it re-lexes
        // the body of the literal as C++.
        if let Some((prefix_len, quote)) = self.literal_prefix_at(self.reader.current_char()) {
            match quote {
                '"' => {
                    for _ in 0..prefix_len {
                        self.reader.bump();
                    }
                    return self.lex_string_literal();
                }
                '\'' => {
                    for _ in 0..prefix_len {
                        self.reader.bump();
                    }
                    return self.lex_char_literal();
                }
                'R' => {
                    if !self.lexer_config.supports_raw_strings() {
                        self.errors.push(CppParseError::syntax_error_from(
                            &t!("raw string literals require C++11"),
                            self.reader.saved_range(),
                        ));
                    }
                    for _ in 0..prefix_len {
                        self.reader.bump();
                    }
                    return self.lex_raw_string_literal();
                }
                _ => {}
            }
        }

        // Universal character names are the only non-`XID` way to begin an identifier. Callers that
        // dispatch on `\` (see `lex_backslash`) land here too, so `saved_range` covers the whole
        // name rather than just the escape.
        if self.reader.current_char() == '\\' && matches!(self.reader.lookahead(1), 'u' | 'U') {
            self.reader.bump(); // `\`
            self.reader.bump(); // `u` or `U`
            if !self.lex_universal_character_name() {
                self.errors.push(CppParseError::syntax_error_from(
                    &t!("invalid universal character name in identifier"),
                    self.reader.saved_range(),
                ));
                return CppTokenKind::Unknown;
            }
            while self.lex_identifier_continuation(dollar) {}
            return self.name_to_kind(self.reader.current_saved_text());
        }

        // Plain identifier or keyword.
        self.reader.bump();
        while self.lex_identifier_continuation(dollar) {}

        let name = self.reader.current_saved_text();
        self.name_to_kind(name)
    }

    /// If an encoding prefix for a string/character/raw literal starts here, return its length in
    /// characters and the quote character that follows it.
    ///
    /// Emulating the grammar rather than probing a fixed set is what keeps `u"x"`, `u8"x"`,
    /// `u8R"(x)"`, `LR"(x)"` and `L'c'` all working while leaving `u8x` and `Lvalue` as names.
    fn literal_prefix_at(&self, first: char) -> Option<(usize, char)> {
        // Bare `R"(...)` raw string: no encoding prefix.
        if self.lexer_config.supports_raw_strings()
            && first == 'R'
            && self.reader.lookahead(1) == '"'
        {
            return Some((0, 'R'));
        }

        if !self.lexer_config.string_prefixes {
            return None;
        }

        let prefix_len = match first {
            'U' | 'L' => 1,
            'u' => match self.reader.lookahead(1) {
                '8' => 2,
                'R' if self.reader.lookahead(2) == '"'
                    && self.lexer_config.supports_raw_strings() =>
                {
                    1
                }
                _ => 1,
            },
            _ => return None,
        };

        match self.reader.lookahead(prefix_len) {
            '"' => Some((prefix_len, '"')),
            '\'' => Some((prefix_len, '\'')),
            'R' if self.reader.lookahead(prefix_len + 1) == '"'
                && self.lexer_config.supports_raw_strings() =>
            {
                Some((prefix_len, 'R'))
            }
            _ => None,
        }
    }

    /// Consume one more identifier character, including a universal character name.
    ///
    /// Returns whether anything was consumed. An invalid `\u` escape is reported but still stops
    /// the identifier — a stray backslash must not silently become part of a name.
    fn lex_identifier_continuation(&mut self, dollar_allowed: bool) -> bool {
        let ch = self.reader.current_char();
        if is_name_continue_with_dollar(ch, dollar_allowed) {
            self.reader.bump();
            return true;
        }

        if ch == '\\' && matches!(self.reader.lookahead(1), 'u' | 'U') {
            self.reader.bump(); // `\`
            self.reader.bump(); // `u` or `U`
            if self.lex_universal_character_name() {
                return true;
            }

            self.errors.push(CppParseError::syntax_error_from(
                &t!("invalid universal character name in identifier"),
                self.reader.saved_range(),
            ));
            return false;
        }

        false
    }

    /// The `u`/`U` of a universal character name has just been consumed; read its digits and check
    /// that the code point it denotes may appear in an identifier.
    fn lex_universal_character_name(&mut self) -> bool {
        let digits = if self.reader.current_saved_text() == "\\u" {
            4
        } else {
            8
        };

        let mut code: u32 = 0;
        for _ in 0..digits {
            match self.reader.current_char().to_digit(16) {
                Some(value) => {
                    code = code * 16 + value;
                    self.reader.bump();
                }
                None => {
                    // Stop at the first bad digit so the rest of the line still lexes normally.
                    while self.reader.current_saved_text().len() < 2 + digits
                        && is_name_continue(self.reader.current_char())
                    {
                        self.reader.bump();
                    }
                    return false;
                }
            }
        }

        char::from_u32(code).is_some_and(is_name_continue)
    }

    /// Lex a string literal `"..."`, with the opening quote as the current character.
    fn lex_string_literal(&mut self) -> CppTokenKind {
        self.reader.bump(); // consume opening quote

        while !self.reader.is_eof() {
            match self.reader.current_char() {
                '"' => {
                    self.reader.bump(); // consume closing quote
                    return self.finish_literal(CppTokenKind::StringLiteral);
                }
                '\\' => {
                    self.reader.bump(); // consume backslash
                    if !self.reader.is_eof() {
                        self.reader.bump(); // consume escaped character
                    }
                }
                '\n' | '\r' => {
                    // A newline cannot appear in an ordinary literal; report and stop here so the
                    // rest of the line is still lexed normally.
                    self.errors.push(CppParseError::syntax_error_from(
                        &t!("unterminated string literal"),
                        self.reader.saved_range(),
                    ));
                    return CppTokenKind::StringLiteral;
                }
                _ => {
                    self.reader.bump();
                }
            }
        }

        // Reached EOF without finding closing quote
        self.errors.push(CppParseError::syntax_error_from(
            &t!("unterminated string literal"),
            self.reader.saved_range(),
        ));
        CppTokenKind::StringLiteral
    }

    /// Attach a user-defined literal suffix to the literal just lexed, if one follows.
    ///
    /// The suffix must be part of the literal token: `"hello"_s` lexed as a string plus an
    /// identifier makes the parser see two expressions where the language has one.
    ///
    /// The suffix is **any identifier**, not only one that starts with `_`. Requiring the underscore split
    /// everything else into two tokens, and the two that matter are ordinary modern C++:
    ///
    /// ```text
    /// auto timeout = 100ms;    std::chrono_literals — ms, us, ns, s, min, h
    /// auto text = "name"sv;    std::string_view_literals
    /// ```
    ///
    /// A suffix that does not begin with `_` is *reserved* — a rule about programs, not about tokens, and one
    /// GCC and Clang accept with a warning. The token is a single user-defined literal either way.
    fn finish_literal(&mut self, kind: CppTokenKind) -> CppTokenKind {
        if !is_name_start_with_dollar(self.reader.current_char(), false) {
            return kind;
        }

        self.reader.bump();
        self.reader
            .eat_while(|ch| is_name_continue_with_dollar(ch, false));
        CppTokenKind::UserDefinedLiteral
    }

    /// Lex a raw string literal `R"delim(...)delim"`.
    ///
    /// The current character is the `R` of the prefix. Raw strings are the one place where the
    /// lexer cannot work character by character: escapes do not apply, and the terminator is
    /// `)delim"` where `delim` is up to 16 characters chosen by the author. Treating `R"(...)"` as
    /// an ordinary string produces a token cut at the first inner quote, which then re-lexes the
    /// rest of the raw string as C++ — the single most destructive lexing mistake possible.
    fn lex_raw_string_literal(&mut self) -> CppTokenKind {
        self.reader.bump(); // `R`
        self.reader.bump(); // `"`

        // Delimiter: at most 16 characters, none of which may be `(`, `)`, whitespace or `\`.
        let mut delimiter = String::new();
        loop {
            let ch = self.reader.current_char();
            if ch == '(' {
                break;
            }
            // `\0` means end of input, so an opening paren is missing.
            if ch == '\\' || ch == '\0' || ch == ')' || ch.is_whitespace() || delimiter.len() >= 16
            {
                self.errors.push(CppParseError::syntax_error_from(
                    &t!("malformed raw string delimiter"),
                    self.reader.saved_range(),
                ));
                return CppTokenKind::StringLiteral;
            }
            delimiter.push(ch);
            self.reader.bump();
        }

        self.reader.bump(); // `(`

        loop {
            if self.reader.is_eof() {
                self.errors.push(CppParseError::syntax_error_from(
                    &t!("unterminated raw string literal"),
                    self.reader.saved_range(),
                ));
                return CppTokenKind::StringLiteral;
            }

            if self.reader.current_char() == ')' {
                // Compare the following characters against `delim"` without consuming them.
                let matches = delimiter
                    .chars()
                    .enumerate()
                    .all(|(offset, expected)| self.reader.lookahead(1 + offset) == expected)
                    && self.reader.lookahead(1 + delimiter.len()) == '"';

                if matches {
                    // Consume `)`, the delimiter and the closing quote.
                    for _ in 0..(2 + delimiter.len()) {
                        self.reader.bump();
                    }
                    return CppTokenKind::StringLiteral;
                }
            }

            self.reader.bump();
        }
    }

    /// Lex character literal `'...'`
    fn lex_char_literal(&mut self) -> CppTokenKind {
        self.reader.bump(); // consume opening quote

        while !self.reader.is_eof() {
            match self.reader.current_char() {
                '\'' => {
                    self.reader.bump(); // consume closing quote
                    return self.finish_literal(CppTokenKind::CharLiteral);
                }
                '\\' => {
                    self.reader.bump(); // consume backslash
                    if !self.reader.is_eof() {
                        self.reader.bump(); // consume escaped character
                    }
                }
                '\n' | '\r' => {
                    // Unterminated character literal
                    self.errors.push(CppParseError::syntax_error_from(
                        &t!("unterminated character literal"),
                        self.reader.saved_range(),
                    ));
                    return CppTokenKind::CharLiteral;
                }
                _ => {
                    self.reader.bump();
                }
            }
        }

        // Reached EOF without finding closing quote
        self.errors.push(CppParseError::syntax_error_from(
            &t!("unterminated character literal"),
            self.reader.saved_range(),
        ));
        CppTokenKind::CharLiteral
    }
    /// Lex numeric literals (integers, floats, hex, binary, etc.)
    ///
    /// Handles the digit separator `'` (C++14), the binary `0b` prefix (C++14) and user-defined
    /// literal suffixes (C++11), which is why the suffix part has to be decided against the token
    /// kind rather than guessed from a fixed list.
    fn lex_number(&mut self) -> CppTokenKind {
        enum NumberState {
            Int,
            Float,
            Hex,
            HexFloat,
            Binary,
            WithExponent,
        }

        let separators = self.lexer_config.supports_digit_separators();
        let mut state = NumberState::Int;
        let first = self.reader.current_char();

        // Handle special number prefixes
        if first == '0' {
            self.reader.bump();
            match self.reader.current_char() {
                'x' | 'X' => {
                    self.reader.bump();
                    state = NumberState::Hex;
                }
                'b' | 'B' => {
                    // **A feature, not a level test.** `0b1010` is C++14's, and a C configuration is a different question
                    // the level could never answer: `CppLanguageLevel` has no C values at all.
                    if !self
                        .lexer_config
                        .language()
                        .support(crate::features::Feature::BinaryLiterals)
                    {
                        self.errors.push(CppParseError::syntax_error_from(
                            &t!("binary literals require C++14"),
                            self.reader.saved_range(),
                        ));
                    }
                    self.reader.bump();
                    state = NumberState::Binary;
                }
                '0'..='7' => {
                    // Octal number (continue as normal integer)
                    state = NumberState::Int;
                }
                '.' => {
                    // `0.5` and `0.` — the dot has to be consumed here. Leaving it to the loop does
                    // not work: the `Float` state has no rule for `.`, so the scan would stop with
                    // the dot unconsumed and the caller would read `0` and `.5` as two literals.
                    self.reader.bump();
                    state = NumberState::Float;
                }
                _ => {
                    // Just a zero
                }
            }
        } else if first == '.' {
            // A float starting with a decimal point: `.5`. The dispatcher has already consumed the
            // dot and delegated here, because a `.` is only a number when a digit follows it —
            // otherwise it is member access.
            state = NumberState::Float;
        } else {
            // Regular decimal number
            self.reader.bump();
        }

        // Continue reading digits based on state
        loop {
            if self.reader.is_eof() {
                break;
            }

            let ch = self.reader.current_char();

            // A digit separator is only a separator *between* digits: `1'000` yes, `1'` no (that is
            // a user-defined literal on `1`). Look ahead rather than treating `'` as part of the
            // number, or `operator''` style suffixes get glued onto the literal.
            if ch == '\'' && separators {
                let next = self.reader.lookahead(1);
                let digit_follows = match state {
                    NumberState::Hex | NumberState::HexFloat => next.is_ascii_hexdigit(),
                    NumberState::Binary => matches!(next, '0' | '1'),
                    _ => next.is_ascii_digit(),
                };
                if digit_follows {
                    self.reader.bump();
                    continue;
                }
                break;
            }

            let should_continue = match (&state, ch) {
                (NumberState::Int, '0'..='9') => true,
                (NumberState::Int, '.') => {
                    state = NumberState::Float;
                    true
                }
                (NumberState::Int, 'e' | 'E') => {
                    self.reader.bump();
                    if matches!(self.reader.current_char(), '+' | '-') {
                        self.reader.bump();
                    }
                    state = NumberState::WithExponent;
                    continue; // Don't bump again
                }
                (NumberState::Float, '0'..='9') => true,
                (NumberState::Float, 'e' | 'E') => {
                    self.reader.bump();
                    if matches!(self.reader.current_char(), '+' | '-') {
                        self.reader.bump();
                    }
                    state = NumberState::WithExponent;
                    continue;
                }
                (NumberState::Hex, '0'..='9' | 'a'..='f' | 'A'..='F') => true,
                (NumberState::Hex, '.') => {
                    state = NumberState::HexFloat;
                    true
                }
                (NumberState::Hex, 'p' | 'P') => {
                    self.reader.bump();
                    if matches!(self.reader.current_char(), '+' | '-') {
                        self.reader.bump();
                    }
                    state = NumberState::WithExponent;
                    continue;
                }
                (NumberState::HexFloat, '0'..='9' | 'a'..='f' | 'A'..='F') => true,
                (NumberState::HexFloat, 'p' | 'P') => {
                    self.reader.bump();
                    if matches!(self.reader.current_char(), '+' | '-') {
                        self.reader.bump();
                    }
                    state = NumberState::WithExponent;
                    continue;
                }
                (NumberState::Binary, '0' | '1') => true,
                (NumberState::WithExponent, '0'..='9') => true,
                _ => false,
            };

            if should_continue {
                self.reader.bump();
            } else {
                break;
            }
        }

        let is_float = matches!(
            state,
            NumberState::Float | NumberState::HexFloat | NumberState::WithExponent
        );

        // Standard suffixes. `u`/`U`/`l`/`L` for integers and `f`/`F`/`l`/`L` for floats. A
        // user-defined suffix starts with `_` and makes the whole thing a `UserDefinedLiteral`,
        // which the parser must not treat as a plain number.
        if is_float {
            // **The fixed-width suffixes come first, because they begin with the same letter.** C++23
            // [lex.fcon] adds `f16 f32 f64 f128 f32x f64x f128x` and `bf16` in both cases, and GCC 15's
            // `<limits>` and `<numbers>` write their `_Float16` constants with them:
            // `6.103515625e-05F16`. The single-letter rule consumed the `F` and left `16` standing as an
            // integer, so the declaration read as `return 6.1e-05F 16;` — measured as 12 `expected ;` errors
            // in those two headers, and the suffix is the whole of it.
            if let Some(width) = self.fixed_width_float_suffix() {
                for _ in 0..width {
                    self.reader.bump();
                }
            } else if matches!(self.reader.current_char(), 'f' | 'F' | 'l' | 'L') {
                self.reader.bump();
            }
        } else {
            self.reader
                .eat_while(|c| matches!(c, 'u' | 'U' | 'l' | 'L' | 'z' | 'Z'));
        }

        // A **user-defined suffix**, which is any identifier — see [`Self::finish_literal`] for why requiring an
        // underscore was wrong. Nothing valid is lost by reading one here: a number immediately followed by a name
        // character is not two tokens in any reading of C++ (`12abc` is ill-formed either way), and every
        // legitimate continuation has been consumed above — the exponent (`1e5`), the hex digits (`0x1f`) and the
        // standard suffixes (`1u`, `1LL`, `1.5f`, `1z`).
        if is_name_start_with_dollar(self.reader.current_char(), false) {
            self.reader.bump();
            self.reader
                .eat_while(|c| is_name_continue_with_dollar(c, false));
            return CppTokenKind::UserDefinedLiteral;
        }

        if is_float {
            CppTokenKind::FloatingLiteral
        } else {
            CppTokenKind::IntegerLiteral
        }
    }

    /// **The length of a fixed-width floating-point suffix at the cursor**, if one is written there.
    ///
    /// C++23 [lex.fcon] spells them `f16 f32 f64 f128 f32x f64x f128x bf16`, each in both cases. Longest
    /// first, because `f32x` and `f32` share a prefix — letting `f32` answer first would leave the `x` as a name
    /// character and turn the literal into a user-defined one, which is the opposite of what the file wrote.
    fn fixed_width_float_suffix(&self) -> Option<usize> {
        const SUFFIXES: [&str; 16] = [
            "f128x", "F128x", "f32x", "F32x", "f64x", "F64x", "f128", "F128", "bf16", "BF16",
            "f16", "F16", "f32", "F32", "f64", "F64",
        ];
        for suffix in SUFFIXES {
            if suffix
                .chars()
                .enumerate()
                .all(|(at, expected)| self.reader.lookahead(at) == expected)
            {
                return Some(suffix.len());
            }
        }
        None
    }

    /// Lex a header name, as it appears in `#include <iostream>` or `#include "local.h"`.
    ///
    /// This is a separate entry point rather than part of the ordinary sweep, because which tokens
    /// form a header name depends entirely on the enclosing directive: outside one, `<iostream>` is
    /// `Less`, `Identifier`, `Greater` and must stay that way or every template breaks.
    ///
    /// The preprocessor layer calls this with the cursor positioned on the `<` or `"`. If the input
    /// is not actually a well-formed header name, nothing is consumed and `None` is returned, so the
    /// caller can fall back to ordinary tokenization — `#include FOO(x)` and `#include <a> + 1` are
    /// both legal to write and both must keep working.
    pub fn lex_header_name(&mut self) -> Option<CppTokenKind> {
        // The token buffer is reset lazily on the first `lex` call, so an entry point that is not
        // `lex` has to prime the reader itself.
        self.reader.begin_token();

        let opening = self.reader.current_char();
        let terminator = match opening {
            '<' => '>',
            '"' => '"',
            _ => return None,
        };

        // The opening delimiter has not been consumed yet, so `lookahead(1)` is the first character
        // of the header name itself.
        let inner = self.scan_header_name_body(terminator)?;

        // Consume the opening delimiter, the body and the closing delimiter.
        for _ in 0..(inner + 2) {
            self.reader.bump();
        }

        Some(CppTokenKind::HeaderName)
    }

    /// Number of characters between the delimiters, or `None` if the header name is malformed.
    fn scan_header_name_body(&self, terminator: char) -> Option<usize> {
        let mut length = 0usize;

        loop {
            match self.reader.lookahead(length + 1) {
                // Unterminated: decline rather than swallow the rest of the line.
                '\0' | '\n' | '\r' | ';' | '\\' => return None,
                ch if ch == terminator => {
                    return (length > 0).then_some(length);
                }
                _ => length += 1,
            }
        }
    }
}

/// **The one lexer entry point**: every token of `text`, plus whatever the lexer could not read.
///
/// It exists so that there is exactly one token stream. The parser reads its tokens through this
/// function, and a caller that wants only tokens — the preprocessor layer, folding, semantic tokens —
/// calls it directly; a second implementation would be free to disagree with the first about where a
/// token begins, and "the directive starts here" is a question both layers ask.
///
/// The stream covers the file byte for byte: concatenating the tokens' text reproduces `text`. There is
/// no `Eof` token — the lexer stops there, and "past the last token" is `text.len()`.
/// **The first preprocessing token of `text`**, as `(kind, range)`, without building the stream — `None` when the text
/// holds only trivia.
///
/// The renderer asks "would joining these two spellings change the first token?" once per pair of adjacent tokens of a
/// rendering (`joining_would_merge`), and on a `import std;` read that is **1.3 million questions**. Each one used to
/// build a `String` for the join and a whole `Vec<CppTokenData>` for the answer about one token; this answers it from a
/// borrowed buffer and no vector.
///
/// The `>>`, `>=` and `>>=` split that [`CppLexer::push`] performs is applied here too, because the answer is about the
/// **first token of the stream**, and for those three that is a one-byte `>`.
pub fn lex_first(
    text: &str,
    config: &LexerConfig,
) -> Option<(CppTokenKind, crate::text::SourceRange)> {
    let mut errors = Vec::new();
    let mut lexer = CppLexer::new(text, *config, &mut errors);
    let kind = lexer.lex();
    if kind == CppTokenKind::Eof {
        return None;
    }
    let range = lexer.reader.saved_range();
    match kind {
        // The three the stream splits — see [`CppLexer::push`]: the first token of the stream is a one-byte `>`.
        CppTokenKind::RightShift | CppTokenKind::GreaterEqual | CppTokenKind::RightShiftAssign => {
            Some((
                CppTokenKind::Greater,
                crate::text::SourceRange::new(range.start_offset, 1),
            ))
        }
        other => Some((other, range)),
    }
}
pub fn lex(text: &str, config: &LexerConfig) -> (Vec<CppTokenData>, Vec<CppParseError>) {
    let mut errors = Vec::new();
    let tokens = CppLexer::new(text, *config, &mut errors).tokenize();
    (tokens, errors)
}