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
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
//! Statements.
//!
//! Statements and declarations are the same construct in C++ (a declaration *is* a statement), and
//! telling them apart is the parser's central ambiguity. [`parse_declaration_or_expression_statement`]
//! is where that is resolved; the control-flow rules below are ordinary recursive descent.

use crate::{
    grammar::{
        ParseResult,
        cpp::{decls, exprs, modules, types},
    },
    kind::{CppSyntaxKind, CppTokenKind},
    parser::{CompleteMarker, CppParser, MarkerEventContainer},
    parser_error::CppParseError,
};

use super::{decls::parse_using_declaration, expect_token, exprs::parse_expr};

/// Parse a compound statement — `{ ... }` — or, in C++, a *single* statement.
///
/// The `{` is what distinguishes `Foo::Foo() : a(1) {}` (a function body) from
/// `Foo::Foo() : a(1);` (a declaration), so this rule drives most of the declaration/definition
/// decision and is the first thing a real declaration parser will need to hook into.
pub(crate) fn parse_compound_stat(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::CompoundStat);

    if p.current_token() == CppTokenKind::LeftBrace {
        p.bump();

        // **The skipped body** — see [`ParserConfig::skip_bodies`]. The `{` is already in; every token up to and
        // including the matching `}` is bumped flat into the `CompoundStat` and nothing is built over them.
        //
        // Counting braces over **the same token stream the grammar would have been driven by** is what makes this
        // sound rather than a guess: a `{` inside a string or a comment is one token and cannot be counted, a brace a
        // macro expands to is not in this stream at all, and `#if` does not remove tokens from it, so a brace in a
        // branch nobody takes is counted exactly as the unskipped parse would have counted it.
        //
        // What it gives up, and the reason only the indexer sets the flag: a body is where a `return` statement is,
        // so `auto` loses its deduced type in a summary built this way, and a diagnostic written inside a body is not
        // reported. Both are answers about a file while it is being **read**, not while it is being indexed.
        if p.parse_config.skips_bodies() {
            let mut depth = 1usize;
            while depth > 0 {
                match p.current_token() {
                    // A missing `}` is the one case where the unskipped parse would have reported something and this
                    // does not: there is no `parse_stats` to notice, and the block simply ends at the end of the
                    // text. It is written here rather than left to be discovered — the indexer tolerates a file it
                    // cannot finish, and a diagnostic is not what it is for.
                    CppTokenKind::Eof => break,
                    CppTokenKind::LeftBrace => depth += 1,
                    CppTokenKind::RightBrace => depth -= 1,
                    _ => {}
                }
                p.bump();
            }
            return Ok(m.complete(p));
        }

        // A name declared inside a brace is not a type name outside it, so the table's scope follows the
        // braces. This is the approximation the table documents: it counts *parser* depth, which is enough to
        // keep a local class from being a type name for the next function.
        p.enter_type_name_scope();
        // …and this brace is a *block*, whatever class body encloses it: a `:` in here is never a bit-field's
        // width. See `CppParser::is_at_class_member_level`.
        p.enter_block_body();
        parse_stats(p);
        p.leave_block_body();
        p.leave_type_name_scope();

        if p.current_token() == CppTokenKind::RightBrace {
            p.bump();
            return Ok(m.complete(p));
        }

        // A missing `}` is the single most common error while editing. Keeping the block and
        // recording the absence as a zero-width node gives completion a sane place to live instead
        // of swallowing the rest of the file into an error node — but the problem must still be
        // reported, or the editor has no way to tell the user about it.
        p.emit_missing_node();
        p.push_error(CppParseError::syntax_error_from(
            &t!("expected `}`"),
            p.current_token_range(),
        ));
        return Ok(m.complete(p));
    }

    if let Err(err) = parse_stat(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Parse statements until a token that cannot start one.
pub fn parse_stats(p: &mut CppParser) {
    // **How many `}` this block owes to statements it gave up on** — the statement-level half of the brace debt
    // the class body keeps (`grammar/cpp/decls.rs`). A statement that failed after
    // consuming a `{` — an initialiser, a lambda's body, a nested block — leaves the block one brace short, and the
    // recovery below skips *to* the next `}`, which belongs to the failed statement: the block ends there and every
    // statement after it is left to the enclosing rule.
    //
    // ```cpp
    // void f() {
    //   S s{
    // #if X
    //     1
    // #endif
    //     ;                 // the `;` is in the other branch: invalid, and the member fails
    //   };
    //   after();            // ← this used to be outside `f`
    // }
    // ```
    let mut unclosed_braces = 0isize;

    // **The one offset at which the recovery already decided not to skip** — see the Err arm below, where this
    // keeps a statement that fails twice at the same token from spinning the loop.
    let mut the_last_early_exit = usize::MAX;

    // **Where this block began**, so that a file boundary crossed after it can end it. A scope may not cross a file
    // boundary: a header that opens a `namespace` and never closes it must not hold the files spliced after it. See
    // [`ParserConfig::with_file_boundaries`], and note that the boundaries are empty for a parse of one
    // file's own text, which is every parse but a stitched unit.
    let since = p.current_token_range().start_offset;

    while !block_follow(p) || unclosed_braces > 0 {
        if p.is_eof() {
            break;
        }

        // The file this block is written in has ended, and the `}` it never wrote is not in the next one.
        if p.crossed_a_file_boundary_since(since) {
            break;
        }

        // **A comment between two statements belongs to the block, not to either statement.**
        //
        // `expect_semicolon` consumes a statement's `;` and stops before a comment, so that a comment written below a
        // declaration is not filed under it — the shape the module note in `tests/doc_owner.rs` describes. What that
        // leaves is the comment sitting at this loop's cursor, and a loop that went straight on to read a statement
        // would read the comment as rubble: measured, `/// Which primitive a shape is.` before an `enum class` in a
        // namespace became an `ErrorNode` and a spurious "expected primary expression".
        //
        // Emitting it here is what puts it in the block, which encloses both the statement above and the statement
        // below and is therefore the only honest answer to "which one does this describe".
        p.emit_trivia_after_current_token();
        if p.is_eof() || (block_follow(p) && unclosed_braces <= 0) {
            break;
        }

        // A `}` with a debt outstanding closes the statement that was abandoned, not this block.
        if p.current_token() == CppTokenKind::RightBrace {
            unclosed_braces -= 1;
            let error = p.mark(CppSyntaxKind::ErrorNode);
            p.bump();
            error.complete(p);
            continue;
        }

        let level = p.open_marks();
        let before_events = p.current_event_count();
        match parse_stat(p) {
            Ok(_) => {}
            Err(err) => {
                // **One mistake, one error.** A statement that is re-read at the same token — which is what the
                // early exit below does when the cursor is already at the next statement — fails in the same place
                // and would report the same thing twice. Measured: `int b = ;` at file scope, where a fixture that
                // pins "one error, in the second declaration" started seeing two, both at the same offset.
                let before = p.current_token_index();
                if before != the_last_early_exit {
                    p.push_error(err);
                }

                // `?` early returns inside `parse_stat` leave markers open. Close them before
                // recovering, otherwise the event stream stays unbalanced and corrupts the rest
                // of the file rather than just this statement.
                p.recover_to_level(level);

                // Charge the failed statement for the braces it consumed and never closed — from the events,
                // because a rule that rolled back (the declaration/expression choice does) has already truncated
                // them, and what it read is then re-read below as rubble.
                unclosed_braces += p.brace_balance_since(before_events).max(0);

                // Skip to next semicolon or closing brace for error recovery…
                //
                // **Unless a new statement starts here**, which is not a recovery at all: a statement that ended
                // because its `;` was missing has already ended — the rules above emit a `MissingNode` for exactly
                // that — and the token at the cursor belongs to the *next* statement. Skipping to the following `;`
                // deletes it, and the deletion is invisible: measured on
                //
                // ```cpp
                //     A* a = nullptr;
                //     a->                  // ← what a reader's cursor is in the middle of
                //     int second = 1;      // ← this Declaration was not in the tree at all
                //     second = 2;          // ← …and so `second` was undeclared for the rest of the file
                // ```
                //
                // where three `X->` in a row left only the first with a type. Every completion and every check after
                // the cursor reads the tree, so while a reader types `obj->` the rest of their function goes dark.
                //
                // `continue` rather than falling through to the guard below: nothing was consumed, and that guard
                // leaves the *block* when nothing was consumed. The one-per-offset note is what keeps this from
                // spinning — a statement that fails again at the same token takes the skip below.
                if before != the_last_early_exit && begins_a_statement(p) {
                    the_last_early_exit = before;
                    continue;
                }
                the_last_early_exit = usize::MAX;
                while !p.is_eof()
                    && p.current_token() != CppTokenKind::Semicolon
                    && p.current_token() != CppTokenKind::RightBrace
                {
                    if p.current_token() == CppTokenKind::LeftBrace {
                        unclosed_braces += 1;
                    }
                    p.bump();
                }
                if p.current_token() == CppTokenKind::Semicolon {
                    p.bump();
                }

                // …**and carry on with the block**, unless the recovery consumed nothing — the one case that
                // would spin this loop, and the one where the token is the `}` this block ends at.
                //
                // The `break` that used to stand here is what made a single unreadable statement cost the whole
                // block: everything after it was left to the enclosing rule, whose recovery is coarser still. It
                // is the shape `bits/stl_map.h` pays for — `__glibcxx_function_requires(…)` is a macro written
                // without its `;`, so `operator[]` failed, `iterator __i = lower_bound(__k);` was swallowed by
                // the skip, and the block ended at the next `if` with "expected `}`". `std::map`'s member list
                // stopped at line 511 and `m.find` answered "not declared in this file".
                if p.current_token_index() == before {
                    // A `{` that nothing claimed is the one token worth reading before giving up: it opens
                    // something the statement never finished, so the block owes a `}` for it.
                    if p.current_token() == CppTokenKind::LeftBrace {
                        unclosed_braces += 1;
                        let error = p.mark(CppSyntaxKind::ErrorNode);
                        p.bump();
                        error.complete(p);
                        continue;
                    }
                    break;
                }
            }
        }
    }
}

/// **Could a statement of its own begin at this token?** — the question the recovery in [`parse_stats`] asks before
/// skipping tokens, because a statement that ended for want of a `;` has already ended and what follows belongs to the
/// next one.
///
/// Deliberately **narrower than the statement dispatcher**: a name can continue an expression (`x = a b` is not
/// recoverable by starting a statement at `b`), so a bare identifier answers `no` here and keeps the old skip — unless
/// it is followed by a name, which is the `Type name` shape no expression has.
fn begins_a_statement(p: &mut CppParser) -> bool {
    match p.current_token() {
        CppTokenKind::IfKeyword
        | CppTokenKind::WhileKeyword
        | CppTokenKind::DoKeyword
        | CppTokenKind::ForKeyword
        | CppTokenKind::SwitchKeyword
        | CppTokenKind::TryKeyword
        | CppTokenKind::ReturnKeyword
        | CppTokenKind::CoReturnKeyword
        | CppTokenKind::CoYieldKeyword
        | CppTokenKind::BreakKeyword
        | CppTokenKind::ContinueKeyword
        | CppTokenKind::GotoKeyword
        | CppTokenKind::ThrowKeyword
        | CppTokenKind::LeftBrace => true,
        // `auto x = …` is a declaration; `decltype` is already in the builtin list below.
        CppTokenKind::AutoKeyword => true,
        // **`Type name`** — `std::unique_ptr<std::string> b;`, `Widget w;`, `Foo* p;`. A name cannot be followed by
        // another name in an expression, so reading this shape as the start of a declaration takes nothing away from
        // a program that parses; it is the shape a reader's cursor sits above while they type `obj->` on the line
        // before it.
        // **`obj.member` / `obj->member`, which an expression cannot continue into.** `a b.c` is not a valid
        // continuation of anything, so `ident .` is a statement of its own — and it is what the line below a reader's
        // unfinished `x->` holds: measured, `p->\n    v.member` skipped the whole `v.member` statement (a bare
        // identifier answered "no" here and the skip took it to the `}`), so every completion and every check after
        // the cursor read a tree without it. `full.size()` on the line after an unfinished arrow is the shape a
        // reader reports as "补全全是错的".
        CppTokenKind::Identifier => a_type_and_a_name_follow(p) || a_member_access_follows(p),
        kind => exprs::starter_of_a_builtin_type(kind) || decls::can_begin_a_declaration(kind),
    }
}

/// `Type name` written at the cursor — see [`begins_a_statement`], which asks this for a leading identifier.
///
/// The scan is the shape: `ident (:: ident)* [<…>] [*|&|const]* ident`, followed by a token that can follow a
/// declarator. Template arguments are counted by depth because they nest (`vector<vector<int>>`), and the scan is
/// bounded because this runs on a recovery path, where the input is by definition something the grammar refused.
/// **`ident .` / `ident ->` at the cursor** — a member-expression statement, see [`begins_a_statement`].
///
/// Deliberately only the operator: `ident ident` is the declaration shape (and `a_type_and_a_name_follow` asks it),
/// while `ident .` and `ident ->` have no reading that continues the expression before them, so the narrow test
/// takes nothing away from a program that parses.
fn a_member_access_follows(p: &CppParser) -> bool {
    matches!(
        p.peek_token_kind_at(1..2).first().copied(),
        Some(CppTokenKind::Dot | CppTokenKind::Arrow)
    )
}

fn a_type_and_a_name_follow(p: &CppParser) -> bool {
    const MAX_TOKENS: usize = 96;
    let kind = |offset: usize| p.peek_token_kind_at(offset..offset + 1).first().copied();

    if !matches!(kind(0), Some(CppTokenKind::Identifier)) {
        return false;
    }
    let mut at = 1usize;
    while at < MAX_TOKENS {
        match kind(at) {
            Some(CppTokenKind::Scope) if matches!(kind(at + 1), Some(CppTokenKind::Identifier)) => {
                at += 2
            }
            Some(CppTokenKind::Less) => {
                let mut depth = 0usize;
                loop {
                    match kind(at) {
                        Some(CppTokenKind::Less) => {
                            depth += 1;
                            at += 1;
                        }
                        // `>>` closes two: `vector<vector<int>>` is how every container is written — and the lexer
                        // produces it on demand, so this reads the two `Greater` tokens it is split into.
                        Some(CppTokenKind::Greater) => {
                            depth = depth.saturating_sub(1);
                            at += 1;
                        }
                        Some(_) => at += 1,
                        None => return false,
                    }
                    if depth == 0 {
                        break;
                    }
                    if at >= MAX_TOKENS {
                        return false;
                    }
                }
            }
            _ => break,
        }
    }
    while matches!(
        kind(at),
        Some(CppTokenKind::Star | CppTokenKind::Ampersand | CppTokenKind::ConstKeyword)
    ) {
        at += 1;
    }
    if !matches!(kind(at), Some(CppTokenKind::Identifier)) {
        return false;
    }
    matches!(
        kind(at + 1),
        Some(
            CppTokenKind::Assign
                | CppTokenKind::Semicolon
                | CppTokenKind::LeftParen
                | CppTokenKind::LeftBracket
                | CppTokenKind::LeftBrace
                | CppTokenKind::Comma
                | CppTokenKind::Colon
        )
    )
}

fn block_follow(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::RightBrace            // }
            | CppTokenKind::Eof             // End of file
            | CppTokenKind::CaseKeyword     // case (in switch)
            | CppTokenKind::DefaultKeyword  // default (in switch)
            | CppTokenKind::ElseKeyword     // else
            | CppTokenKind::CatchKeyword // catch
    )
}

/// Dispatch to the statement rule for the current token.
///
/// Every statement passes through here, which makes this the natural enforcement point for the
/// marker contract documented in `grammar::mod`: an `Err` leaving this function has closed every
/// node the statement opened, so callers can recover by skipping tokens without having to know how
/// deep the failed rule got.
pub fn parse_stat(p: &mut CppParser) -> ParseResult {
    let _phase = crate::parser::phases::during("statement");
    let base = p.open_marks();

    let result = match p.current_token() {
        // Control flow statements
        CppTokenKind::IfKeyword => parse_if_statement(p),
        CppTokenKind::WhileKeyword => parse_while_statement(p),
        CppTokenKind::DoKeyword => parse_do_while_statement(p),
        CppTokenKind::ForKeyword => parse_for_statement(p),
        CppTokenKind::SwitchKeyword => parse_switch_statement(p),
        CppTokenKind::TryKeyword => parse_try_statement(p),

        // `__try` / `__catch(…)` — the implementation's spellings of the same statement. See
        // [`at_the_implementations_try`] for why the spelling is the right thing to match on here rather than a
        // table lookup, and for the measurements behind it.
        CppTokenKind::Identifier if at_the_implementations_try(p) => parse_try_statement(p),

        // An **`asm` statement** — the compilers' own statement, whose payload is not C++ at all. Claimed here,
        // before the name is read as an expression, because `asm` is an ordinary identifier to this lexer and the
        // declaration/expression rule has nothing to make of the operands. See [`at_an_asm_statement`].
        CppTokenKind::Identifier if at_an_asm_statement(p) => parse_asm_statement(p),
        CppTokenKind::ReturnKeyword => parse_return_statement(p),
        // Coroutine statements. `co_return` is `return` under another name — the same operand, the same optional
        // value, the same `;` — so it is the same rule through a different keyword rather than a copy of it.
        CppTokenKind::CoReturnKeyword => parse_return_statement(p),
        CppTokenKind::CoYieldKeyword => parse_throw_statement(p),
        CppTokenKind::BreakKeyword => parse_keyword_statement(p, CppSyntaxKind::BreakStat),
        CppTokenKind::ContinueKeyword => parse_keyword_statement(p, CppSyntaxKind::ContinueStat),
        CppTokenKind::GotoKeyword => parse_goto_statement(p),
        CppTokenKind::ThrowKeyword => parse_throw_statement(p),

        // Compound statement
        CppTokenKind::LeftBrace => parse_compound_stat(p),

        // **An attribute in front of a statement**, which is where MSVC puts `[[msvc::constexpr]]`:
        //
        // ```cpp
        // _MSVC_CONSTEXPR return ::new (static_cast<void*>(_Location)) _Ty[1]();     // <memory>:547
        // ```
        //
        // `vcruntime.h` defines that macro as `[[msvc::constexpr]]` under `/std:c++20`, and the attribute is read
        // here because **no statement rule can start at it**: `parse_declaration_or_expression_statement` tries the
        // declaration reading first and finds no type, then falls through to the expression reading, where `[` in
        // operand position is an error. The recovery from that is what this costs — measured, the two errors left in
        // a 2.1 MB translation unit were this one shape, and they left `<xutility>`'s namespace open.
        //
        // # Why statement position is the easy place to accept it
        //
        // Because a `[[` here has no competitor at all: an expression statement may begin with a name, a literal, a
        // `(`, a `[` of a *subscript* on something already named — and never with two `[` in a row. The subscript
        // that makes the same test delicate in the expression grammar is written *after* its subject, so it cannot
        // be the first token of a statement.
        //
        // The attribute is read as its own node and the statement after it is read by this same rule, so
        // `[[a]] [[b]] return x;` is an attribute run and a return statement rather than a run of nothing.
        _ if types::at_an_attribute(p) => {
            if let Err(err) = types::parse_attribute_specifiers(p) {
                Err(err)
            } else if matches!(
                p.current_token(),
                CppTokenKind::CaseKeyword | CppTokenKind::DefaultKeyword
            ) {
                // **An attribute may be the first token of a labelled statement**: the standard's
                // `labeled-statement` begins with an attribute-specifier-seq, and `[[likely]] case 1:` is how a
                // reader marks the branch that is expected to win:
                //
                // ```cpp
                // switch (choice) {
                //     [[likely]] case 2:
                //         …
                // }
                // ```
                //
                // The statement rule cannot read a `case` on its own — a label is the switch body's, not a
                // statement's — so before this the `case` was taken for an expression statement and reported
                // `expected primary expression`. Read here, the attribute is the label's and the statement it
                // labels follows as it always does.
                if let Err(err) = read_switch_labels(p, base) {
                    Err(err)
                } else {
                    parse_stat(p)
                }
            } else {
                parse_stat(p)
            }
        }

        // C++20 modules. Checked *before* the label case below: `module : private;` and
        // `module A:B;` both look exactly like `identifier :` — a label — and the label rule would
        // eat the `module` and leave the rest as a stray statement.
        //
        // This is the cost of `module` and `import` being contextual keywords rather than real ones:
        // the parser has to decide from the shape of the declaration, and it has to do so early
        // enough that no other rule claims the tokens first.
        _ if modules::starts_module_related_declaration(p) => decls::parse_declaration(p),

        // A label: `foo:` at the start of a statement.
        CppTokenKind::Identifier
            if p.peek_token_kind_at(1..2).as_slice() == [CppTokenKind::Colon] =>
        {
            parse_label_statement(p)
        }

        // An empty statement.
        CppTokenKind::Semicolon => {
            let m = p.mark(CppSyntaxKind::EmptyStat);
            p.bump();
            Ok(m.complete(p))
        }

        // A macro from a header standing where a declaration goes, which is how every libstdc++ header opens a
        // namespace version: `_GLIBCXX_BEGIN_NAMESPACE_VERSION` on a line of its own. See the rule.
        CppTokenKind::Identifier if at_a_macro_that_stands_for_a_declaration(p) => {
            parse_a_macro_that_stands_for_a_declaration(p)
        }

        // Everything else is a declaration or an expression statement.
        _ => parse_declaration_or_expression_statement(p),
    };

    if result.is_err() {
        p.close_marks_above(base);
    }

    result
}

/// Does an **`asm` statement** start at the cursor?
///
/// The compilers' own statement, and the one whose payload this grammar must not try to read:
///
/// ```cpp
/// __asm__ volatile ("tilerelease" ::);                        // amxtileintrin.h:56
/// __asm__ __volatile__ ("pconfig\n\t" : "=a" (retval) : "a" (leaf) : "cc");
/// __asm__ ("int {$}3" : );                                    // _mingw.h:584
/// ```
///
/// `asm` is not a C++ keyword — it is C's, and an extension spelled the same way by GCC and by MSVC — so this
/// lexer produces an ordinary identifier and the *shape* has to claim it: one of the three spellings, an
/// optional `volatile`/`inline`/`goto` (and GCC's `__volatile__`, which is a plain name to the lexer), and then a
/// **balanced group** — `( … )` for GCC, `{ … }` for MSVC's `__asm { … }`.
///
/// That shape has no competitor at statement position: a name followed by a parenthesised group is otherwise a
/// *call*, and a call is read — the difference is the spelling, and the three spellings are the compilers' own.
fn at_an_asm_statement(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::Identifier
        || !matches!(p.current_token_text(), "asm" | "__asm" | "__asm__")
    {
        return false;
    }

    let mut offset = 1usize;
    loop {
        match p.peek_token_kind_at(offset..offset + 1).first() {
            Some(
                &CppTokenKind::VolatileKeyword
                | &CppTokenKind::InlineKeyword
                | &CppTokenKind::GotoKeyword,
            ) => offset += 1,
            Some(&CppTokenKind::Identifier)
                if matches!(p.peek_token_text_at(offset), "__volatile__" | "__volatile") =>
            {
                offset += 1;
            }
            Some(&CppTokenKind::LeftParen | &CppTokenKind::LeftBrace) => return true,
            _ => return false,
        }
    }
}

/// Read an `asm` statement: its keyword, its qualifiers, and its payload **as tokens**.
///
/// The payload is the compiler's operand language, not C++ — `"int {$}3":`, `[ret] "=r" (ret)`, `"a" (leaf)` —
/// so it is kept as the balanced group it is, with the tokens in order inside [`CppSyntaxKind::AsmStat`]. Reading
/// it as anything else would mean inventing a grammar for a language this layer does not implement, and would
/// lose the text a consumer wants to show.
///
/// The `;` is required after a `( … )` payload and **not** after a `{ … }` one: MSVC's `__asm { … }` is a block
/// and ends without a semicolon, which is a difference in the language rather than in this rule's convenience.
fn parse_asm_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::AsmStat);

    p.bump(); // the keyword

    loop {
        match p.current_token() {
            CppTokenKind::VolatileKeyword
            | CppTokenKind::InlineKeyword
            | CppTokenKind::GotoKeyword => p.bump(),
            CppTokenKind::Identifier
                if matches!(p.current_token_text(), "__volatile__" | "__volatile") =>
            {
                p.bump();
            }
            _ => break,
        }
    }

    let (open, close, closes_itself) = match p.current_token() {
        CppTokenKind::LeftParen => (CppTokenKind::LeftParen, CppTokenKind::RightParen, false),
        CppTokenKind::LeftBrace => (CppTokenKind::LeftBrace, CppTokenKind::RightBrace, true),
        _ => {
            p.close_marks_above(base);
            return Err(CppParseError::syntax_error_from(
                &t!("expected `(` after `asm`"),
                p.current_token_range(),
            ));
        }
    };

    // The balanced group, token by token. The lexer has already made strings and comments single tokens, so a
    // bracket inside one cannot be mistaken for the payload's own.
    let mut depth = 0isize;
    while !p.is_eof() {
        let kind = p.current_token();
        if kind == open {
            depth += 1;
        } else if kind == close {
            depth -= 1;
            if depth == 0 {
                p.bump();
                break;
            }
        }
        p.bump();
    }

    if depth != 0 {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("unterminated `asm` payload"),
            p.current_token_range(),
        ));
    }

    if p.current_token() == CppTokenKind::Semicolon {
        p.bump();
    } else if !closes_itself {
        p.emit_missing_node();
        p.push_error(CppParseError::syntax_error_from(
            &t!("expected `;`"),
            p.current_token_range(),
        ));
    }

    Ok(m.complete(p))
}

/// Read the invocation at `start` as a statement — the reader of [`a_macro_invocation_starts_at`].
///
/// Two shapes, and the difference is not cosmetic: one carries a group and is read by [`parse_macro_call`], and one
/// does not and is read by [`parse_a_macro_that_stands_for_a_declaration`]. Asking which shape this is, at the one
/// place that knows the name has already been claimed, keeps each reader's precondition true.
///
/// The reading is asked for **after** the declaration reading, which is what the caller arranges: at file scope
/// `MACRO(args) name (…)` is a *declaration whose specifiers are the macro*, and a rule that claimed it first would
/// take that reading away — the first version of this one did exactly that, and
/// `a_macro_may_stand_between_the_type_and_the_declarator` caught it.
fn parse_a_macro_invocation_statement(p: &mut CppParser, start: usize) -> ParseResult {
    // **No group, no [`parse_macro_call`]**: that reader's first act is to read the argument list, and a bare
    // invocation is read by the rule that reads a name and *optionally* a group. Asking which shape this is, at the
    // one place that knows the name has already been claimed, is cheaper than a flag inside the reader and keeps
    // each reader's precondition true.
    let after_the_name = decls::next_significant_index(p, start);
    if p.token_kind_at(after_the_name) != CppTokenKind::LeftParen {
        return parse_a_macro_that_stands_for_a_declaration(p);
    }

    parse_macro_call(p)
}

pub(super) fn a_macro_invocation_starts_at(p: &CppParser, index: usize) -> bool {
    if p.token_kind_at(index) != CppTokenKind::Identifier {
        return false;
    }

    let name = p.token_text_at(index);
    let after = decls::next_significant_index(p, index);

    // The form with a group: a name reserved to the implementation, whose group ends where a statement ends.
    //
    // The name and the group are the whole of the evidence, and that is the point rather than a shortcut: the
    // reading has to be the same reading whether or not a toolchain, an include closure, or an index is behind the
    // parse, and `__glibcxx_function_requires(_Concept<T>)` is written the same way in all three. See
    // [`types::written_in_the_implementations_namespace`] for what "reserved" buys.
    p.token_kind_at(after) == CppTokenKind::LeftParen
        && types::written_in_the_implementations_namespace(name)
        && kind_after_the_balanced_group(p, index).is_some_and(ends_a_statement)
}

/// **The index just past a reserved invocation that a declaration follows**, or `None` — see the arm that reads it.
///
/// The three conditions are [`a_macro_invocation_starts_at`]'s, with a declaration where that rule wants a statement:
/// a name [`types::written_in_the_implementations_namespace`] reserved, a balanced group, and a token that
/// [`starts_a_new_declaration`] (or `export`) after it.
fn index_after_a_reserved_invocation_before_a_declaration(
    p: &CppParser,
    index: usize,
) -> Option<usize> {
    if p.token_kind_at(index) != CppTokenKind::Identifier
        || !types::written_in_the_implementations_namespace(p.token_text_at(index))
    {
        return None;
    }
    if p.token_kind_at(decls::next_significant_index(p, index)) != CppTokenKind::LeftParen {
        return None;
    }
    let after = index_after_the_balanced_group(p, index)?;
    let kind = p.token_kind_at(after);
    (starts_a_new_declaration(kind) || kind == CppTokenKind::ExportKeyword).then_some(after)
}

/// Does a run of annotation invocations stand **in front of** the declaration it annotates?
///
/// MSVC's SAL annotations are written that way, and no table needs to know any of them (they are the
/// `_SAL2_Source_` family in `<sal.h>`):
///
/// ```c
/// _Check_return_wat_
/// _Success_(return == 0)
/// _ACRTIMP errno_t __cdecl fopen_s(…);
/// ```
///
/// The declaration reading fails on the **second** name's group: `_Check_return_wat_ _Success_(return == 0)` reads
/// as `type name(parameters)`, and `_ACRTIMP` cannot continue it — so the file got an expression statement and
/// then `expected ';'` against the name it could not consume. What is left is the reading the file means: each
/// name is an invocation, and the declaration follows them.
///
/// Three things make it a rule rather than a licence:
///
/// * every name must be one the **implementation** reserved
///   ([`types::written_in_the_implementations_namespace`]), which is what keeps `Wat Ever f(void);` — a
///   declaration with unknown specifiers — reading as a declaration;
/// * **at least one of them must carry a group**, because the group is what says these names are invoked and not
///   declared (`_Check_return_ _Ret_notnull_` on its own is a declaration head);
/// * the run must end **where a declaration begins** — a specifier keyword or a name — which is the anchor: a run
///   that ends anywhere else is left to the error it already had.
///
/// The names are asked about by **shape, not by evidence**, and that is measured: with the closure's macro bodies
/// in force (the census's environment) `_Success_` is a macro with a positional body, and a parse with no toolchain
/// behind it has never heard of the name — the file is the same file and the reading has to be the same reading.
///
/// Returns the index just past the run, or `None` when there is no run here.
fn index_after_a_run_of_annotation_invocations(p: &CppParser, index: usize) -> Option<usize> {
    let mut index = index;
    let mut saw_a_group = false;

    loop {
        if p.token_kind_at(index) != CppTokenKind::Identifier
            || !types::written_in_the_implementations_namespace(p.token_text_at(index))
        {
            break;
        }

        if p.token_kind_at(decls::next_significant_index(p, index)) == CppTokenKind::LeftParen {
            index = index_after_the_balanced_group(p, index)?;
            saw_a_group = true;
        } else {
            index = decls::next_significant_index(p, index);
        }
    }

    let a_declaration_begins_here = starts_a_new_declaration(p.token_kind_at(index))
        || p.token_kind_at(index) == CppTokenKind::Identifier;

    (saw_a_group && a_declaration_begins_here).then_some(index)
}

/// The index of the first significant token **after** the balanced group that follows the token at `index`.
///
/// `None` when there is no such group (an unbalanced one, or a `;` before it closes — the call already ended, so
/// the question does not arise).
pub(super) fn index_after_the_balanced_group(p: &CppParser, index: usize) -> Option<usize> {
    let mut index = decls::next_significant_index(p, index);
    let mut depth = 0isize;
    while index < p.token_count() {
        match p.token_kind_at(index) {
            CppTokenKind::LeftParen => depth += 1,
            CppTokenKind::RightParen => {
                depth -= 1;
                if depth == 0 {
                    return Some(decls::next_significant_index(p, index));
                }
            }
            CppTokenKind::Semicolon | CppTokenKind::Eof | CppTokenKind::None => return None,
            _ => {}
        }
        index += 1;
    }

    None
}

/// The kind of the first significant token **after** the balanced group that follows the token at `index`.
///
/// `None` when there is no such group (an unbalanced one, or a `;` before it closes — the call already ended, so
/// the question does not arise).
fn kind_after_the_balanced_group(p: &CppParser, index: usize) -> Option<CppTokenKind> {
    index_after_the_balanced_group(p, index).map(|after| p.token_kind_at(after))
}

/// Can this token **not** continue the expression that ends with the group before it — so that the group was the
/// whole of what the file wrote there?
///
/// The list is deliberately made of answers that end a statement rather than of operators: `if`, `#`, `}`, `return`
/// and a following name all say the invocation is complete, while `.`, `[`, `(`, `->` and every operator say it
/// continues. A **block** is not in the list, because `g(x) { }` is the mistake the block form of the
/// macro-statement rule already has to weigh (see [`decls::a_macro_definition_follows`]).
fn ends_a_statement(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        // The scope, and the directives that end a line inside it.
        CppTokenKind::RightBrace
            | CppTokenKind::Hash
            | CppTokenKind::Eof
            | CppTokenKind::None
            // A statement keyword: what follows a complete invocation.
            | CppTokenKind::IfKeyword
            | CppTokenKind::WhileKeyword
            | CppTokenKind::ForKeyword
            | CppTokenKind::SwitchKeyword
            | CppTokenKind::DoKeyword
            | CppTokenKind::ReturnKeyword
            | CppTokenKind::TryKeyword
            | CppTokenKind::ThrowKeyword
            | CppTokenKind::BreakKeyword
            | CppTokenKind::ContinueKeyword
            | CppTokenKind::GotoKeyword
            | CppTokenKind::CaseKeyword
            | CppTokenKind::DefaultKeyword
            | CppTokenKind::ElseKeyword
            | CppTokenKind::CatchKeyword
            // …and a name, which starts the next declaration or statement rather than continuing this expression.
            // Two invocations in a row are ordinary in these headers, and the second one's follower is whatever
            // comes after both:
            //
            // ```cpp
            // __glibcxx_function_requires(_ConvertibleConcept<_ValueType1, _ValueType2>)   // :170
            // __glibcxx_function_requires(_ConvertibleConcept<_ValueType2, _ValueType1>)   // :172
            // typedef typename iterator_traits<_ForwardIterator1>::reference _ReferenceType1;
            // ```
            | CppTokenKind::Identifier
    )
        // …or the start of a **declaration**, which is the same answer one step along.
        || starts_a_new_declaration(kind)
}

/// Does a **macro invocation that stands for a declaration** start at the cursor?
///
/// `_GLIBCXX_BEGIN_NAMESPACE_VERSION` alone on a line inside a namespace body, or
/// `_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(__cxx11)`, is a macro from a header: `bits/c++config.h` expands the first
/// to `namespace __8 {` in one branch and to **nothing at all** in the other. No table the parser can be handed
/// knows the name — the `#define` is in an *included* file, and the external hook is not wired to a file's
/// includes (see `eat_namespace_head_macros`, and for why that connection is a design round
/// of its own). So the shape decides, and it decides only where it has no competitor:
///
/// ```text
/// _GLIBCXX_BEGIN_NAMESPACE_VERSION   then `template`, `class`, `typedef`, `}`   -> a macro
/// _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(__cxx11)   then a declaration          -> a macro
/// x = 1;                             the `=` continues an expression        -> an assignment, unchanged
/// Widget w;                          a declarator follows                   -> a declaration, unchanged
/// FOO(x);                            the group ends at a `;`                -> the most vexing parse, unchanged
/// COUNT                              inside a body, where a missing `;` is the competing reading
/// ```
///
/// # The question is "what may follow", and it is asked of the token after the invocation
///
/// A lone name at file or namespace scope has two readings, and what tells them apart is the token after the
/// invocation — after the **group** when there is one, since the group is the macro's:
///
/// ```text
/// MACRO template<…>        a declaration can begin there   -> a macro
/// MACRO}                   the scope ends there            -> a macro
/// MACRO(A, B) int x;       a declaration can begin there   -> a macro
/// Widget w;                an identifier is not a type     -> a declaration, unchanged
/// x = 1;                   `=` continues the name          -> an assignment, unchanged
/// FOO(x);                  a `;` follows the group         -> the most vexing parse, unchanged
/// TEST(A, B) { … }         a `{` follows the group         -> a definition, unchanged
/// COUNT                    inside a body, where a missing `;` is the competing reading
/// ```
///
/// The first version of this rule asked "does a *declarator* follow the name" instead, and `x = 1;` is what that
/// cost: no declarator follows an `=`, so an assignment was read as a macro and the `=` then had no left-hand
/// side. `Widget w;` is why the answer cannot simply be "an identifier follows": that is a declaration, and it is
/// the `;`, the `{` and the identifier that say so.
///
/// # What it costs
///
/// A file that writes a macro-shaped name followed by a declaration and means something else gets a `MacroCall`
/// where a reader might have wanted an error. Nothing is invented about it, every token is still in the tree, and
/// the declarations after it are read normally — which is the whole point: not reading it cost every declaration
/// in the file (190 diagnostics in `bits/stl_algobase.h` alone).
fn at_a_macro_that_stands_for_a_declaration(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::Identifier || p.is_inside_a_body() {
        return false;
    }

    let after = decls::kind_after_the_run_of_names(p);
    starts_a_new_declaration(after) || ends_the_scope(after)
}

/// Can a declaration begin with this token kind — by an **anchor**, or by a **type**?
///
/// The union of two lists the grammar already keeps apart: [`can_begin_a_declaration`] (the keywords that can only
/// start a declaration, plus the specifiers) and the type keywords (`int`, `void`, `auto`, …, and the elaborated
/// `class`/`struct`/`union`/`enum`). A declaration begins with one or the other, and a caller asking "may a
/// declaration begin here" needs both — which is why this is a name rather than a longer list at the call site.
///
/// What is deliberately **not** here is an ordinary identifier: `Widget w;` is a declaration in which an
/// identifier follows a name, and a rule that accepted one would read `Widget` as a macro.
fn starts_a_new_declaration(kind: CppTokenKind) -> bool {
    decls::can_begin_a_declaration(kind) || types::is_type_specifier_keyword(kind)
}

/// Does this token end the scope the cursor is in, or start a directive — so that nothing continues it?
///
/// The other half of "what may follow", beside [`starts_a_new_declaration`]: a macro standing for a declaration is
/// the last thing on its line, so `}` and a following directive are both ordinary things to find after it. `#` is
/// here rather than in the declaration list because a directive does not begin a declaration — it begins a
/// *directive*, and the declaration it is about to write is the next thing on the next line.
fn ends_the_scope(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::RightBrace | CppTokenKind::Hash | CppTokenKind::Eof | CppTokenKind::None
    )
}

/// Read a macro invocation that stands for a declaration: `NAME` or `NAME ( tokens )`.
///
/// The same node the statement form produces, for the same reason — a macro's meaning is not knowable here, and
/// dressing it up as a declaration would hide that. No `;` is consumed: a macro standing for a declaration does
/// not write one, and a `;` that is there belongs to the empty statement rule.
pub(super) fn parse_a_macro_that_stands_for_a_declaration(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::MacroCall);

    let name = p.mark(CppSyntaxKind::NameExpr);
    p.bump();
    name.complete(p);

    if p.current_token() == CppTokenKind::LeftParen {
        decls::parse_balanced_token_group(p, CppSyntaxKind::ArgumentList)?;
    }

    Ok(m.complete(p))
}

/// Read a macro invocation as a statement: `NAME ( tokens ) [ { … } ] [ ; ]`.
///
/// The arguments are a **balanced token group**, not an argument list of the grammar: a macro's parameters are
/// pasted into identifiers and types alike (`TEST(Format, 1k_row)`), so nothing may be interpreted. The group is
/// kept as an `ArgumentList` because that is what it is — the macro's arguments — and the block that may follow
/// belongs to the same node, because it is part of what the macro's body produced.
fn parse_macro_call(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::MacroCall);

    let name = p.mark(CppSyntaxKind::NameExpr);
    p.bump();
    name.complete(p);

    decls::parse_balanced_token_group(p, CppSyntaxKind::ArgumentList)?;

    // What the macro's body supplies. A block is the body of a macro that expands to a statement or a whole
    // definition (`IF_EXIST(op) if (…)`, gtest's `TEST(A, B) { … }`); a `;` is the ordinary function-like macro;
    // and **nothing at all** is the case this rule exists for — a body that is a complete statement of its own.
    match p.current_token() {
        CppTokenKind::LeftBrace => {
            if let Err(err) = parse_compound_stat(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }
        CppTokenKind::Semicolon => p.bump(),
        _ => {}
    }

    Ok(m.complete(p))
}

/// Resolve the declaration/expression ambiguity by trying the declaration reading first.
///
/// See the module documentation in `decls` for why this is decided by backtracking rather than by a
/// heuristic on the first tokens. The rewind is cheap — the parser is an event list and a token
/// cursor — and getting it wrong produces a wrong but plausible tree, which is much worse.
fn parse_declaration_or_expression_statement(p: &mut CppParser) -> ParseResult {
    // A preprocessor directive is not a C++ construct at all; it only exists at the token level.
    if p.current_token() == CppTokenKind::Hash {
        return parse_preprocessor_directive(p);
    }

    // `using` declarations cannot be expressions, so they do not need the speculative path.
    if p.current_token() == CppTokenKind::UsingKeyword {
        return parse_using_declaration(p);
    }

    // Anchors let the speculative declaration pass be skipped: `static`, `class`, `typename` and
    // friends can never begin an expression, so there is nothing to disambiguate.
    if decls::starts_declaration(p) {
        return decls::parse_declaration(p);
    }

    // **`take(&n);` is a call, and the declaration reading makes it the declaration of a reference.**
    //
    // Measured: that line parsed to zero errors, round-tripped exactly, and produced **no `CallExpr` at all** — a
    // `Declaration` whose declarator was a `ReferenceType` (`&`) and a `NameExpr` (`n`), with `take` read as the type.
    // This grammar lets any identifier start a type, so the most-vexing-parse shape is available everywhere, and
    // nothing that starts from a call — signature help, hover on the callee, both argument checks — could see the most
    // ordinary line there is. `take(p)` was unaffected, which is why the defect read as a template problem for a round.
    //
    // The rule is one lookahead and is exact: an identifier, then `(`, then `&` is a call whose first argument is an
    // address. `void f(int& x);` is not matched — there the `&` follows a type, not the parenthesis — and neither is
    // `f(&x)` used as anything but a statement, because this rule only runs where a statement begins.
    if a_call_whose_first_argument_is_an_address(p) {
        return parse_expression_statement(p);
    }

    let start = p.current_token_index();
    let checkpoint = p.checkpoint();
    match decls::parse_declaration(p) {
        Ok(marker) => {
            // The declaration reading **succeeded**, and that is not the end of the question: a macro invocation
            // from an included header reads as a function declaration too — `__glibcxx_function_requires(_Concept<T>)`
            // is `NAME ( parameter )`, and the declaration rule has no reason to refuse it. What separates the two
            // is the `;`: a declaration has one and the macro's body supplies it, so there is none and the token
            // after the group cannot continue a declaration. Only a name the implementation reserved is asked
            // about, so `Widget w(1);` and every ordinary missing-`;` mistake keep their readings.
            if p.last_consumed_token_kind() != Some(CppTokenKind::Semicolon)
                && a_macro_invocation_starts_at(p, start)
            {
                p.rollback(checkpoint);
                return parse_a_macro_invocation_statement(p, start);
            }
            Ok(marker)
        }
        Err(err) => {
            if crate::probes::declaration_trace() {
                eprintln!(
                    "[decl] the declaration reading failed at {}: {err:?}",
                    p.current_token_range().start_offset
                );
            }
            // Not a declaration. Rewind **first**: the question below is asked about the token the statement began
            // at, and the failed attempt left the cursor somewhere past it.
            p.rollback(checkpoint);
            // The same reading is asked for once more, because a shape the declaration rule *refuses* may be this
            // one: `_foo(x)` in front of `}` reads as a declaration of a type `_foo` with a parameter list, which
            // is a declaration of nothing. See [`at_a_macro_call_statement_without_evidence`].
            if a_macro_invocation_starts_at(p, start) {
                return parse_a_macro_invocation_statement(p, start);
            }
            // **A reserved invocation in front of the declaration it annotates**, on the same line:
            //
            // ```cpp
            // _NON_MEMBER_CALL(_IS_MEMFUNPTR_EXPLICIT_THIS_GUIDES, , , noexcept)
            // export template <class _Ty> inline constexpr bool is_member_function_pointer_v = …;
            // ```
            //
            // `a_macro_invocation_starts_at` refuses this one because it wants the invocation to be the whole statement
            // (it ends at `;`), and here a declaration follows instead. The evidence is still the same three things:
            // a name the implementation **reserved**, a balanced group, and a **declaration** after it — measured, it
            // is the last error in the 4.85 MB rendering of `import std;` (`<xtr1common>`, where the definition was not
            // in force at that point of the walk). The invocation is consumed and the declaration after it parsed by
            // the rule that owns it, so one error does not become a recovery that swallows the rest of the file.
            if let Some(after) = index_after_a_reserved_invocation_before_a_declaration(p, start) {
                while p.current_token_index() < after && !p.is_eof() {
                    p.bump();
                }
                return decls::parse_declaration(p);
            }
            // **A run of annotations in front of the declaration they annotate**. One invocation per
            // statement: the next statement begins at the next name of the run and this same decision is asked
            // again, so `_Check_return_wat_` / `_Success_(…)` / the declaration come out as two invocations and
            // the declaration — which is what the file wrote. See
            // [`index_after_a_run_of_annotation_invocations`].
            if index_after_a_run_of_annotation_invocations(p, start).is_some() {
                return parse_a_macro_that_stands_for_a_declaration(p);
            }
            // Not a declaration, and not a macro from a header. Read it as an expression.
            parse_expression_statement(p)
        }
    }
}

/// Parse a preprocessor directive as a leaf of the syntax tree: `#` name rest-of-line.
///
/// The directive is kept as a node rather than skipped, for two reasons. It has to stay in the tree
/// for the CST to remain lossless, and the *unselected* branches of `#if` contain real
/// declarations — an editor needs to see them, both so the file parses at all and so that code
/// inside a disabled branch is not reported as garbage.
///
/// One directive gets special treatment: `#include` is followed by a header name, which the lexer
/// only produces on request because `<` and `>` are far too common to guess at.
/// Exposed to the initializer rule, which meets directives between the elements of a table rather than between
/// statements — see [`decls::parse_braced_initializer`].
pub(super) fn parse_preprocessor_directive(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::PreprocessorDirective);
    // Where the directive begins, for the one thing that has to be said about its *text* afterwards: a
    // replacement list is not C++ (see the `forget_unrecognized_characters_within` call at the end).
    let directive_from = p.current_token_range().start_offset;

    // A directive runs to the end of its **logical** line, and a `\`-newline splice does not end one.
    //
    // The boundary has to be computed as an *offset*, not looked for as a `Newline` token: the newline
    // is trivia, and `bump` skips trivia while attaching it to the current node. So after consuming the
    // last real token of the line the cursor is already on the next line's first token, a `Newline` is
    // never seen, and a loop that waits for one consumes the whole file. That failure is not local —
    // every declaration after the first directive disappears into it.
    //
    // A splice is the other half of the same problem. `#define F(a, b) \` followed by the body on the
    // next line is one directive, and a boundary taken at the first newline byte cuts the body off
    // after the `\` — leaving a macro whose replacement list is empty while the file still round-trips,
    // which is the kind of wrong that no losslessness check can see.
    let text = p.origin_text();
    let mut line_end = logical_line_end(text, p.current_token_range().start_offset);

    p.bump(); // `#`

    // **How deep the conditional nesting is**, kept here because this is the one place a directive is read: a
    // construct that asks "did I open a conditional inside myself?" cannot count the directives it *read* — a
    // nested reading may have consumed one on its way past (the expression grammar's operator-position seam does
    // exactly that, and the conditional that follows it is the case). The question is instead "how many were open
    // when I started, and how many are open now", and this is what keeps that answer.
    //
    // `#else`/`#elif` stay at the level they were opened at; `#endif` closes one; everything else — `#define`,
    // `#include`, `#pragma`, the null directive — does not nest.
    //
    // The name is matched by **text** rather than by kind, and the two spellings that need that are the common
    // ones: `if` and `else` are C++ keywords, so `#if`/`#else` arrive as `IfKeyword`/`ElseKeyword` and a
    // kind-based test would miss every one of them. The line bound is what keeps the null directive (`#` alone on
    // a line) from reading the *next* line's `if` as its own name.
    if p.current_token_range().start_offset < line_end {
        p.note_a_directive_name();
    }

    // The directive name is a plain identifier (`include`, `define`, `if`, ...); the null directive
    // `#` alone on a line has none.
    let directive_is_include = p.current_token() == CppTokenKind::Identifier
        && matches!(p.current_token_text(), "include" | "include_next");
    if p.current_token() == CppTokenKind::Identifier {
        p.bump();
    }

    // Reading the rest token by token keeps the text in the tree; the preprocessor layer re-reads
    // these tokens when it needs their real meaning.
    let mut header_name_expected = directive_is_include;

    while !p.is_eof() && p.current_token_range().start_offset < line_end {
        if p.current_token() == CppTokenKind::LineContinuation {
            // The directive continues on the line after the splice, so the boundary moves with it.
            p.bump();
            line_end = logical_line_end(text, p.current_token_range().start_offset);
            continue;
        }

        if header_name_expected {
            header_name_expected = false;
            if p.try_lex_header_name() {
                continue;
            }
        }

        p.bump();
    }

    // **A replacement list is not C++ text**. `shared/apiset.h:64` is
    // `#define API_SET_BY_ORDINAL(X,O,PO)   X @##O NONAME PRIVATE` inside `#ifdef _API_SET_HOST` — apiset-tool
    // syntax in a branch no compiler takes — and `shared/driverspecs.h:401` carries a `\` in a SAL macro's body.
    // A compiler lexes neither until the macro is *used*, so the character diagnostics that landed inside this
    // directive's own line are dropped: 42 messages over the SDK corpus, all of them about text no compiler would
    // refuse. Everything else inside the line is still reported — see the method's own documentation.
    let directive_to = p.current_token_range().start_offset;
    p.forget_unrecognized_characters_within(directive_from, directive_to);

    Ok(m.complete(p))
}

/// The offset at which the logical line containing `start` ends.
///
/// A newline does not end a logical line when the byte before it is a `\` — that is a splice, and
/// translation phase 2 has already removed it by the time a directive's extent matters. Only the
/// backslash immediately before the newline counts, which is what the standard says and what keeps a
/// `\\` at the end of a line from swallowing the next one.
pub(super) fn logical_line_end(text: &str, start: usize) -> usize {
    let Some(rest) = text.get(start..) else {
        return text.len();
    };

    let bytes = rest.as_bytes();
    let mut index = 0;

    while index < bytes.len() {
        if bytes[index] == b'\n' {
            // Look back for the splice. `\r\n` is one line ending, so the check skips a `\r`.
            let before = if index > 0 && bytes[index - 1] == b'\r' {
                index.checked_sub(2)
            } else {
                index.checked_sub(1)
            };
            let spliced = before.is_some_and(|at| bytes[at] == b'\\');
            if !spliced {
                return start + index;
            }
        }
        index += 1;
    }

    text.len()
}

/// Parse an expression statement: `expr ;`.
fn parse_expression_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ExpressionStat);

    if let Err(err) = parse_expr(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // A statement ends at a `;`. Reaching something else means the expression did not cover the
    // statement, which is what makes the caller's recovery kick in.
    if p.current_token() == CppTokenKind::Semicolon {
        p.bump();
        return Ok(m.complete(p));
    }

    // **The tokens stay, so the node gets its end event.** `close_marks_above` would detach it instead, and an
    // unpaired `NodeStart` is balanced by the tree builder at the end of the stream — so this statement would
    // swallow everything after it, including the `}` of its own block. That is exactly what a macro written
    // without its `;` costs (`bits/stl_map.h:530`, and with it `std::map::find`).
    p.emit_missing_node();
    p.end_marks_to(base);
    Err(CppParseError::syntax_error_from(
        &t!("expected `;` after expression"),
        p.current_token_range(),
    ))
}

fn parse_if_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::IfStat);

    p.bump(); // Consume 'if'

    // `if constexpr (...)`, and C++23's `if consteval` / `if !consteval`.
    //
    // The two forms could hardly be less alike underneath. `if constexpr` still takes a parenthesised
    // condition, while `if consteval` takes *no* condition at all: the statement is selected by
    // whether the evaluation is constant, and the braces follow the keyword directly. So this is not
    // one flag but two — the keyword says which form, and only `constexpr` is followed by a condition.
    //
    // The negation is part of the second form rather than the start of an expression, which is why it
    // has to be consumed here. Leaving it to `parse_condition` reports `expected (` against a `!` that
    // is perfectly valid C++23.
    let consteval_form = if p.current_token() == CppTokenKind::ConstexprKeyword {
        p.bump();
        false
    } else if p.current_token() == CppTokenKind::ConstevalKeyword
        || (p.current_token() == CppTokenKind::Identifier && p.current_token_text() == "consteval")
    {
        p.bump();
        true
    } else if p.current_token() == CppTokenKind::LogicalNot
        && p.peek_token_kind_at(1..2).as_slice() == [CppTokenKind::ConstevalKeyword]
    {
        p.bump(); // `!`
        p.bump(); // `consteval`
        true
    } else {
        false
    };

    // A **macro standing between `if` and its condition**: `if _GLIBCXX17_CONSTEXPR (std::is_same_v<…>)`, which is
    // how the standard library writes `if constexpr` in a header that must also compile as C++14 — there the macro
    // expands to **nothing at all**, and in C++17 to `constexpr`.
    //
    // Accepted by shape rather than by table, and the shape is decisive: `if` is followed by a `(` in every
    // program C++ accepts, so an identifier in between takes no valid program away. That is the fallback side of
    // the rule — where a table cannot answer because the `#define` is
    // in an *included* header (`bits/c++config.h`), and where both readings of the tokens are wrong if the macro
    // is not one. It is *not* evidence-free in the way `MY_API` was: nothing legal is being re-read.
    //
    // The `(` is required, which is what keeps this away from `if consteval` — that word also arrives as an
    // identifier, and it is followed by a `{`, not by a condition.
    if p.current_token() == CppTokenKind::Identifier
        && p.peek_next_token() == CppTokenKind::LeftParen
    {
        p.bump(); // the macro that stands for `constexpr`, or for nothing
    }

    // `if consteval` has no condition to parse. Asking for one would report `expected (` against the
    // `{` that is really the body, which is worse than useless: it accuses correct code.
    if !consteval_form && let Err(err) = parse_condition(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    if let Err(err) = parse_statement_body(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // The joint between an `if`'s branch and its `else` — the same seam `parse_try_statement` documents, and the
    // one the standard library hits first:
    //
    // ```cpp
    // if constexpr (__or_<…>::value)
    //   _S_copy(…);
    // #if __cpp_lib_concepts              // ← here: `bits/basic_string.h`, line 490, its first error
    // else if constexpr (requires { … })
    // ```
    //
    // Without it the `#endif`…`#if` pair is what the else-branch is read as, the `else` becomes a statement with
    // nothing before it, and the error is reported against the `}` of a class whose body is a hundred lines away.
    // Read as the node it is, then **ask again whether the token is `else`** rather than assuming: a `#` that is
    // not a directive is still an error, and this seam only accepts directives.
    if let Err(err) = eat_preprocessor_directives(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    if p.current_token() == CppTokenKind::ElseKeyword {
        let else_m = p.mark(CppSyntaxKind::ElseStat);
        p.bump();

        // The other side of the same joint: `else` and the statement it introduces.
        if let Err(err) = eat_preprocessor_directives(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        if let Err(err) = parse_statement_body(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        else_m.complete(p);
    }

    Ok(m.complete(p))
}

fn parse_while_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::WhileStat);

    p.bump(); // Consume 'while'

    if let Err(err) = parse_condition(p) {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = parse_statement_body(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

fn parse_do_while_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::DoWhileStat);

    p.bump(); // Consume 'do'
    if let Err(err) = parse_statement_body(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    if let Err(err) = expect_token(p, CppTokenKind::WhileKeyword) {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = parse_condition(p) {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = expect_token(p, CppTokenKind::Semicolon) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Parse `( ... )` after `if`/`while`/`switch`/`for`, or a condition declaration.
///
/// # The C++17 initializer
///
/// `if (auto q = find(x); q != nullptr)` is a *declaration* and then a *condition*, separated by a `;` — two
/// constructs where the grammar had one. The declaration is read by the for-init rule, which is the same
/// declaration without the trailing `;` that a header does not own; the `;` is then consumed here and the
/// condition follows as a plain expression.
///
/// The order matters and so does the fallback. A `;` inside the parentheses is what marks the form, and it
/// cannot be mistaken for anything else: no expression statement's `;` can appear inside a condition's
/// parentheses, because the condition's own parentheses have not closed. So the scan is a lookahead for a `;`
/// at depth zero, and when there is none the rule behaves exactly as before.
fn parse_condition(p: &mut CppParser) -> ParseResult {
    let _ = p.open_marks();
    let m = p.mark(CppSyntaxKind::ParenExpr);

    expect_token(p, CppTokenKind::LeftParen)?;

    // `if (init; condition)` — an initializer, then the condition.
    if a_semicolon_ends_an_initializer(p) {
        parse_initializer_part(p)?;
        expect_token(p, CppTokenKind::Semicolon)?;
        parse_expr(p)?;
        expect_token(p, CppTokenKind::RightParen)?;
        return Ok(m.complete(p));
    }

    // A condition may declare a variable: `if (Foo* p = get())`, `if (const auto n = g())`.
    //
    // The declaration here is the one a **condition** reads — specifiers, one declarator, an initialiser, no `;`
    // of its own — and that is the whole of the fix, not a detail: `parse_declaration` insists on a `;`, so the
    // attempt failed, the fallback read an *expression*, and the two readings came out as a silent multiplication
    // and an error respectively:
    //
    // ```text
    // if (Foo* p = get())     read as `Foo * p = get()` — a BinaryExpr nobody reports, and not valid C++ either
    // if (Foo p = get())      `expected ), but get identifier` against the `=`
    // if (const auto n = g()) `expected primary expression` against the `=`
    // ```
    //
    // The rule's two refusals are what keep the expression path for the conditions that are expressions: a
    // condition declares **one** variable and it must be **initialised**, so `if (a && b)` and `if (v.size())`
    // never reach a declaration. See `parse_condition_declaration`.
    let checkpoint = p.checkpoint();
    if decls::parse_condition_declaration(p).is_err() {
        p.rollback(checkpoint);
        parse_expr(p)?;
    }

    // **A condition's end is its own `)`, however much of the expression was understood** — the same reading
    // the `decltype` payload takes, and for the same reason. `if (_STD f())` is written by every standard-library
    // header: `_STD` is a macro (`yvals.h` defines it as `::std::`) and a file parsed on its own has not read that
    // header, so it arrives as a plain identifier and `_STD f()` is two identifiers in a row. The expression rule
    // reads the first and stops; reporting `expected )` against the second failed the whole `if`, and the failure
    // took the declaration written after the function with it.
    //
    // Measured, on three lines:
    //
    // ```cpp
    // struct S { void f() { if (!_STD g()) { } } };
    // struct After { int c; };   // no fact at all
    // ```
    //
    // …and the shape is not rare: `while (_STD g())` and `int x = _STD g();` break the same way, while a bare
    // `_STD g();` **statement** does not — which is what says the fault is the enclosing rule's expectation
    // rather than the expression reading. `vector` alone stops at the first of them, line 409.
    if !matches!(p.current_token(), CppTokenKind::RightParen) {
        types::skip_to_the_closing_paren(p);
    }
    expect_token(p, CppTokenKind::RightParen)?;
    Ok(m.complete(p))
}

/// Is there a `;` at the condition's own depth, making this an `if (init; condition)`?
///
/// A lookahead rather than a parse, because the two forms have to be told apart *before* the declaration rule
/// runs — that rule consumes a `;` as its own terminator and would take this one with it. The scan is bounded
/// and tracks nesting, so a `;` inside a lambda body or a nested parentheses is not mistaken for the
/// separator.
fn a_semicolon_ends_an_initializer(p: &CppParser) -> bool {
    let mut depth = 0isize;

    for kind in p.peek_token_kind_at(0..64) {
        match kind {
            CppTokenKind::LeftParen | CppTokenKind::LeftBracket | CppTokenKind::LeftBrace => {
                depth += 1
            }
            CppTokenKind::RightParen | CppTokenKind::RightBracket | CppTokenKind::RightBrace => {
                if depth == 0 {
                    return false;
                }
                depth -= 1;
            }
            CppTokenKind::Semicolon if depth == 0 => return true,
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
    }

    false
}

/// Parse the initializer half of `if (init; condition)`, which may be a declaration or an expression.
///
/// The same two readings a `for` header's init part has, and the same rule: the declaration is tried first
/// because it is the one that can be refused, and an expression is what is left when it is.
fn parse_initializer_part(p: &mut CppParser) -> ParseResult {
    let checkpoint = p.checkpoint();

    if decls::parse_for_init_declaration(p).is_ok() {
        return Ok(CompleteMarker::empty());
    }
    p.rollback(checkpoint);

    parse_expr(p)
}

/// Parse the body of a control-flow statement: a block, or one statement.
///
/// # Attributes come first
///
/// `if (__n > 1) [[likely]]`, `else [[unlikely]]`, `while (x) [[likely]]` — C++20 lets an attribute stand on the
/// *substatement*, which is a position where nothing else may go, and the standard library's own headers use it
/// (16 occurrences in 7 files of the measured closure, every one of them after an `if` condition). Reading them
/// here rather than in each of the five statements that own a substatement is what makes one rule cover the lot:
/// the then-branch, the else-branch and every loop body reach their statement through this function, and none of
/// them can be reached any other way.
///
/// The node is a sibling of the body inside the statement, because that is what it is: an attribute *on* the
/// statement, not part of it. The reader is the same one `[[nodiscard]]` goes through — see
/// [`types::parse_attribute_specifiers`] — so nothing here is specific to `likely`.
fn parse_statement_body(p: &mut CppParser) -> ParseResult {
    types::parse_attribute_specifiers(p)?;

    if p.current_token() == CppTokenKind::LeftBrace {
        return parse_compound_stat(p);
    }

    // A dangling `;` is an empty statement, which is a valid body.
    parse_stat(p)
}

fn parse_for_statement(p: &mut CppParser) -> ParseResult {
    let _ = p.open_marks();
    let m = p.mark(CppSyntaxKind::ForStat);

    p.bump(); // Consume 'for'

    // `for co_await (...)` (C++20).
    if p.current_token() == CppTokenKind::CoAwaitKeyword {
        p.bump();
    }

    expect_token(p, CppTokenKind::LeftParen)?;

    // Range-based for: `for (decl : range)`.
    if starts_a_range_for(p) {
        let checkpoint = p.checkpoint();

        // A range declaration is optional in C++20 (`for (auto v : m)` vs. `for (v : m)`), so a failure here
        // means the header held an expression and the range reading is still open.
        //
        // The rule is the *for-init* one rather than a whole declaration: the header has no `;` of its own, so
        // a rule expecting one reports "expected `;`" against the range expression.
        if decls::parse_for_init_declaration(p).is_err() {
            p.rollback(checkpoint.clone());
            parse_expr(p)?;
        }

        if p.current_token() == CppTokenKind::Colon {
            // The kind is decided *here*, before the node is closed, and set on the marker rather than on the
            // value `complete` hands back. The marker's kind is what the `NodeStart` event was emitted with, and
            // `complete` only reads it — so writing to the returned `CompleteMarker` changes a copy and leaves
            // the tree with the `ForStat` the node was opened as. That is how a range-based `for` came out
            // labelled as a C-style one while parsing perfectly.
            let mut m = m;
            m.set_kind(p, CppSyntaxKind::RangeForStat);

            p.bump();
            // **The range may be a braced-init-list**: `for (int x : {1, 2, 3})`. A `{` where an expression would
            // be cannot begin one — every other place that means a list already reads it as one (an argument, an
            // assignment's right side, a declaration's initializer) — so this is the same rule in the one position
            // it was missing, and not a second reading of braces.
            if p.current_token() == CppTokenKind::LeftBrace {
                decls::parse_braced_initializer(p)?;
            } else {
                parse_expr(p)?;
            }
            expect_token(p, CppTokenKind::RightParen)?;
            parse_statement_body(p)?;

            return Ok(m.complete(p));
        }

        // Not a range-for after all; fall through to the C-style reading. The checkpoint was taken before the
        // range reading, so rewinding here also undoes the optional range declaration that parsed successfully.
        p.rollback(checkpoint);
    }

    // C-style: `for (init ; cond ; step)`.
    if p.current_token() != CppTokenKind::Semicolon {
        parse_declaration_or_expression_statement_without_semicolon(p)?;
    }
    expect_token(p, CppTokenKind::Semicolon)?;

    if p.current_token() != CppTokenKind::Semicolon {
        parse_expr(p)?;
    }
    expect_token(p, CppTokenKind::Semicolon)?;

    if p.current_token() != CppTokenKind::RightParen {
        parse_declaration_or_expression_statement_without_semicolon(p)?;
    }
    expect_token(p, CppTokenKind::RightParen)?;

    parse_statement_body(p)?;

    Ok(m.complete(p))
}

/// Would a `:` later in the `for` header make this a range-based for?
///
/// Called with the cursor just **inside** the opening `(`, so the header is scanned at relative depth zero and
/// a `:` at that depth is the range separator. Scanning from depth one instead — the state *before* the `(` was
/// consumed — makes every `:` look nested, so the scan never fires and `for (auto x : items)` is read as a
/// C-style header and fails on the `:`.
///
/// A `?` at depth zero rules the range reading out, because `a ? b : c` has a `:` that is not a separator.
fn starts_a_range_for(p: &CppParser) -> bool {
    let mut depth = 0isize;
    let mut saw_question = false;

    for kind in p.peek_token_kind_at(0..64) {
        match kind {
            CppTokenKind::LeftParen | CppTokenKind::LeftBracket | CppTokenKind::LeftBrace => {
                depth += 1
            }
            CppTokenKind::RightParen | CppTokenKind::RightBracket | CppTokenKind::RightBrace => {
                depth -= 1;
                // The header's own `)` at depth zero ends it without a range separator.
                if depth < 0 {
                    return false;
                }
            }
            CppTokenKind::Question => saw_question = true,
            CppTokenKind::Semicolon if depth == 0 => return false,
            CppTokenKind::Colon if depth == 0 => return !saw_question,
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
    }

    false
}

/// Parse the init or step part of a `for` header, which has no trailing semicolon of its own.
fn parse_declaration_or_expression_statement_without_semicolon(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();

    let checkpoint = p.checkpoint();
    if decls::parse_for_init_declaration(p).is_ok() {
        return Ok(CompleteMarker::empty());
    }
    p.rollback(checkpoint);

    let m = p.mark(CppSyntaxKind::ExpressionStat);
    if let Err(err) = parse_expr(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

fn parse_switch_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::SwitchStat);

    p.bump(); // Consume 'switch'

    if let Err(err) = parse_condition(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // **A `switch` body is a *statement*, and a brace block is only one of them.** Requiring `{` here is what made
    // gtest unreadable: its assertion macros expand to
    //
    // ```text
    // switch (0) case 0: default: if (const AssertionResult gtest_ar_ = …) ; else AssertHelper(…) = Message();
    // ```
    //
    // (`GTEST_SWITCH_`), a body with **labels and one statement** and no braces at all. Measured on
    // `Test/src/FilePattern_unitest.cpp`: 62 `SyntaxError`s, one per assertion — `expected {, but get case` — on a
    // file whose rendering is correct, so the preprocessor was blamed for a gap in the grammar.
    //
    // The two shapes are read in their own terms: a block holds many statements and is read as before; anything else
    // is a run of `case`/`default` labels followed by the one statement they label, which is what the language says a
    // labelled statement is.
    if p.current_token() != CppTokenKind::LeftBrace {
        read_switch_labels(p, base)?;
        if let Err(err) = parse_stat(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    if let Err(err) = expect_token(p, CppTokenKind::LeftBrace) {
        p.close_marks_above(base);
        return Err(err);
    }

    while p.current_token() != CppTokenKind::RightBrace && !p.is_eof() {
        match p.current_token() {
            CppTokenKind::CaseKeyword | CppTokenKind::DefaultKeyword => {
                read_switch_labels(p, base)?;
            }
            _ => {
                // Regular statements inside the switch body.
                parse_stat(p)?;
            }
        }
    }

    if p.current_token() == CppTokenKind::RightBrace {
        p.bump();
    } else {
        p.emit_missing_node();
    }

    Ok(m.complete(p))
}

/// **A run of `case`/`default` labels**, each one complete — the prefix of a labelled statement.
///
/// One `case` label is `case <constant-expression> :` or a range `case 1 ... 5:`; `default` is the keyword and the
/// colon. Both are read here rather than at the two call sites, because a `switch` body reads them in a block and
/// without one, and the grammar must not have two answers for the same token.
fn read_switch_labels(p: &mut CppParser, base: usize) -> ParseResult {
    loop {
        match p.current_token() {
            CppTokenKind::CaseKeyword => {
                let case = p.mark(CppSyntaxKind::CaseStat);
                p.bump();
                // A case label may be a constant expression or a range `case 1 ... 5:`.
                //
                // Read with pack expansion *refused*, because this rule owns the `...` of the range: with the
                // expansion reading on, `case 2 ... 4:` parsed as a pack expansion of `2` and then reported a
                // missing `:`. The range is the one construct in a statement where a `...` follows an
                // expression and is not an expansion.
                if let Err(err) = exprs::parse_expr_without_pack_expansion(p) {
                    p.close_marks_above(base);
                    return Err(err);
                }
                if p.current_token() == CppTokenKind::Ellipsis {
                    p.bump();
                    if let Err(err) = parse_expr(p) {
                        p.close_marks_above(base);
                        return Err(err);
                    }
                }
                if let Err(err) = expect_token(p, CppTokenKind::Colon) {
                    p.close_marks_above(base);
                    return Err(err);
                }
                case.complete(p);
            }
            CppTokenKind::DefaultKeyword => {
                let default = p.mark(CppSyntaxKind::DefaultStat);
                p.bump();
                if let Err(err) = expect_token(p, CppTokenKind::Colon) {
                    p.close_marks_above(base);
                    return Err(err);
                }
                default.complete(p);
            }
            _ => return Ok(CompleteMarker::empty()),
        }
    }
}

/// The name the standard library's own header gives to `try`, and to `catch`.
///
/// `bits/exception_defines.h` defines both, and its definition is the evidence for reading them as the keywords
/// they stand for:
///
/// ```text
/// #ifdef __EXCEPTIONS                     #else
/// # define __try      try                  # define __try      if (true)
/// # define __catch(X) catch(X)            # define __catch(X) if (false)
/// #endif
/// ```
///
/// # Why the spelling, and not a table
///
/// The same reasoning as the compiler's attribute spellings (`__attribute__`, `__declspec`), and it takes the same
/// two conditions to be satisfied: the names are
/// **reserved to the implementation** (a double underscore, so no conforming program may define them), and the
/// `#define` that gives them meaning is the *implementation's*, not the file's — no header a project writes can
/// turn `__try` into something else. Both matter: the rule that reads a macro from a header
/// ([`at_a_macro_that_stands_for_a_declaration`]) deliberately refuses inside a body and requires the table,
/// which is why these two spellings were not read at all.
///
/// # What the wrong reading cost, measured
///
/// `__try { g(); }` used to be an **expression**, not a statement: a name followed by `{` is list-initialisation
/// of a temporary (`Vec<int>{1, 2}`), so the block was read as an `InitListExpr` holding a statement —
/// `expected }, but get ;` against the `;` of the first statement inside it, and then the brace matching of the
/// whole function was off by one, which is what the `expected }` and the stray `ErrorNode` after it were. Of the
/// 185 files in the closure of six standard headers, **18 contain `__try`** and 17 of them fail.
///
/// The reading is a `TryStat` with `CatchStat` handlers rather than a `MacroCall`: the construct *is* the
/// statement under the branch that has exceptions on, and reading it as a macro would lose the pairing between
/// the body and its handlers — the one thing a consumer of a `try` is looking for. The `if (true)`/`if (false)`
/// branch would be a different statement, and it is the branch a reader cannot see without evaluating
/// `__EXCEPTIONS`; records that both branches of a conditional are read as text, and this
/// takes the reading that keeps the structure.
const THE_KEYWORD_TRY_IS_SPELLED: &str = "__try";

/// The same, for `catch` — see [`THE_KEYWORD_TRY_IS_SPELLED`].
const THE_KEYWORD_CATCH_IS_SPELLED: &str = "__catch";

/// MSVC's two handlers for a `__try` block — see [`parse_try_statement`].
///
/// `__except` takes a **filter expression** in parentheses (`__except (EXCEPTION_EXECUTE_HANDLER)`), `__finally`
/// takes none; both are followed by a block. They are identifiers rather than keywords, like `__try` itself, so the
/// spelling is what tells them from a call.
const THE_KEYWORD_EXCEPT_IS_SPELLED: &str = "__except";
const THE_KEYWORD_FINALLY_IS_SPELLED: &str = "__finally";

/// Is the cursor on one of the handlers MSVC's `__try` can take?
fn at_the_implementations_handler(p: &CppParser) -> bool {
    p.current_token() == CppTokenKind::Identifier
        && matches!(
            p.current_token_text(),
            THE_KEYWORD_EXCEPT_IS_SPELLED | THE_KEYWORD_FINALLY_IS_SPELLED
        )
}

/// `__except (…)` — the filter, which is an expression rather than a parameter list.
fn parse_parenthesized_filter(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::ParenExpr);
    expect_token(p, CppTokenKind::LeftParen)?;
    crate::grammar::cpp::exprs::parse_expr(p)?;
    expect_token(p, CppTokenKind::RightParen)?;
    Ok(m.complete(p))
}

/// Is the cursor on `__try`, with a block to follow?
///
/// The block is required because `__try` is *also* an MSVC keyword for structured exception handling
/// (`__try`/`__except`/`__finally`), which is a different construct with a different shape. Neither spelling
/// appears in the measured closure, so nothing is claimed about it here; requiring the `{` is what keeps a SEH
/// `__try` from being read as a `try` statement whose block happens to be there.
fn at_the_implementations_try(p: &CppParser) -> bool {
    p.current_token() == CppTokenKind::Identifier
        && p.current_token_text() == THE_KEYWORD_TRY_IS_SPELLED
        && p.peek_next_token() == CppTokenKind::LeftBrace
}

/// Is the cursor on `__catch` **with its argument list**?
///
/// `__catch` is function-like by definition — its `#define` has a parameter — so the parenthesis is part of the
/// spelling, and requiring it is what tells the macro from a name that merely starts the same way. Its argument
/// list is the handler's parameter list, which is why the reading calls the same rule `catch (…)` does.
fn at_the_implementations_catch(p: &CppParser) -> bool {
    p.current_token() == CppTokenKind::Identifier
        && p.current_token_text() == THE_KEYWORD_CATCH_IS_SPELLED
        && p.peek_next_token() == CppTokenKind::LeftParen
}

fn parse_try_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::TryStat);

    p.bump(); // Consume 'try' — or the implementation's spelling of it, which is the same one token

    // **Directives at every joint of a `try`.** A handler that exists in a debug build and not in a release one
    // is a real spelling, and the directive that decides it can land between any two tokens of the statement —
    // between `try` and its block, and between the block and the `catch`:
    //
    // ```cpp
    // #if !defined(_DEBUG)
    //     try
    // #endif
    //     {
    //         …
    //     }
    // #if !defined(_DEBUG)
    //     catch (std::exception &e) { … }
    // #endif
    // ```
    //
    // That is `IOSession.cpp` in the first real C++ project, and the shape is worth reading carefully because
    // the *first* of the two joints is the one that breaks the statement: with `try` followed by `#endif`, the
    // block was not the try's block at all, so the statement ended there and the `catch` became a statement with
    // no statement before it — reported as `expected }` against the `catch`.
    //
    // Read as the nodes they are, exactly as the other places that read one inside a construct record, for the
    // same argument; a `#` anywhere it cannot be a directive is still an error.
    if let Err(err) = eat_preprocessor_directives(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    if let Err(err) = parse_compound_stat(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    if let Err(err) = eat_preprocessor_directives(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // **MSVC's structured exception handling**: `__try { … } __except (filter) { … }` and
    // `__try { … } __finally { … }`.
    //
    // They are the same statement shape as `try`/`catch` — a block and one or more handler blocks — and they are
    // written by every Windows driver and by MSVC's own headers. The handler's *filter* is an expression
    // (`__except (GetExceptionCode() == …)`), not a parameter list, which is the one difference that matters to
    // this rule. The two spellings are identifiers rather than keywords, so they are matched by text, exactly as
    // `__try` already is.
    while at_the_implementations_handler(p) {
        let handler = p.mark(CppSyntaxKind::CatchStat);
        let is_a_filter = p.current_token_text() == THE_KEYWORD_EXCEPT_IS_SPELLED;
        p.bump();

        if is_a_filter
            && p.current_token() == CppTokenKind::LeftParen
            && let Err(err) = parse_parenthesized_filter(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }

        if let Err(err) = eat_preprocessor_directives(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        if let Err(err) = parse_compound_stat(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        handler.complete(p);

        if let Err(err) = eat_preprocessor_directives(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    while p.current_token() == CppTokenKind::CatchKeyword || at_the_implementations_catch(p) {
        let handler = p.mark(CppSyntaxKind::CatchStat);
        p.bump();

        if p.current_token() == CppTokenKind::LeftParen
            && let Err(err) = parse_parameter_list_inline(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }

        // The same joint, one handler along: `catch (E& e)` and its block.
        if let Err(err) = eat_preprocessor_directives(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        if let Err(err) = parse_compound_stat(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        handler.complete(p);

        if let Err(err) = eat_preprocessor_directives(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    Ok(m.complete(p))
}

/// Read the preprocessor directives at the cursor as nodes, and stop at the first thing that is not one.
///
/// For the constructs whose parts a conditional can separate — see [`parse_try_statement`] — the same
/// reading applies in an initializer, in a string-literal run, and between a
/// function's head and its body. The directives stay in the tree, so nothing is lost and a consumer can see
/// which branch each one guards.
fn eat_preprocessor_directives(p: &mut CppParser) -> ParseResult {
    while p.current_token() == CppTokenKind::Hash {
        parse_preprocessor_directive(p)?;
    }
    Ok(CompleteMarker::empty())
}

/// Parse a catch clause's parameter list, reusing the declaration grammar.
fn parse_parameter_list_inline(p: &mut CppParser) -> ParseResult {
    decls::parse_parameter_list(p)
}

fn parse_return_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ReturnStat);

    p.bump(); // Consume 'return'

    // `return;` and `co_return;` are complete statements.
    if p.current_token() != CppTokenKind::Semicolon
        && !p.is_eof()
        && let Err(err) = parse_return_value(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    if p.current_token() == CppTokenKind::Semicolon {
        p.bump();
    } else {
        // **A missing `;` is an error, and this rule used to say nothing.**
        //
        // It emitted a zero-width `MissingNode` and returned `Ok`, which is not a diagnosis: the tree stays
        // well-formed, `get_errors` is empty, and `return 0` written with no semicolon is **accepted**. Reported from
        // an editor, where a `return 0` with no `;` produced no diagnostic and no amount of waiting helped — the
        // analysis was right to say nothing, because the parser had found nothing.
        //
        // Every other statement that ends in a `;` reports it: `parse_keyword_statement` (`break`, `continue`),
        // `parse_goto_statement`, `parse_throw_statement`. Measured on the pair:
        //
        // ```text
        // int f() { int x }        errors=1   the declaration rule reports it
        // int f() { return 0 }     errors=0   and this rule did not
        // ```
        //
        // `decls::expect_semicolon` is the shared rule, and using it rather than repeating the shape is deliberate:
        // it is the one that knows about a `;` a conditional branch already carried
        // (`take_the_terminator_came_from_a_branch`) and about leaving the layout after the `;` to the enclosing
        // block rather than taking it into this node.
        if let Err(err) = decls::expect_semicolon(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    Ok(m.complete(p))
}

/// Parse what follows `return`: an expression, or a braced-init-list.
fn parse_return_value(p: &mut CppParser) -> ParseResult {
    if p.current_token() == CppTokenKind::LeftBrace {
        // `return {1, 2};`
        return decls::parse_braced_initializer(p);
    }

    parse_expr(p)
}

fn parse_keyword_statement(p: &mut CppParser, kind: CppSyntaxKind) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(kind);
    p.bump();

    if p.current_token() == CppTokenKind::Semicolon {
        p.bump();
    } else {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("expected `;`"),
            p.current_token_range(),
        ));
    }

    Ok(m.complete(p))
}

fn parse_goto_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::GotoStat);

    p.bump(); // Consume 'goto'

    // **GNU's computed `goto`** — `goto *table[state];`, which is how an interpreter dispatches. The `*` is the
    // operator rather than a dereference of a label, and the operand is an ordinary expression: without this arm the
    // statement stopped after `goto` and reported `expected ;, but get *` (measured on a nine-file C corpus, and pinned
    // by `a_computed_goto_and_a_negative_case_range_parse`).
    if p.current_token() == CppTokenKind::Star
        && p.language()
            .support(crate::features::Feature::LabelsAsValues)
    {
        p.bump();
        if let Err(err) = crate::grammar::cpp::exprs::parse_expr(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        if let Err(err) = expect_token(p, CppTokenKind::Semicolon) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    if p.current_token() == CppTokenKind::Identifier {
        p.bump();
    }
    if let Err(err) = expect_token(p, CppTokenKind::Semicolon) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

fn parse_throw_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ThrowStat);

    p.bump(); // Consume 'throw'
    if p.current_token() != CppTokenKind::Semicolon
        && let Err(err) = parse_expr(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = expect_token(p, CppTokenKind::Semicolon) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

fn parse_label_statement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::LabelStat);

    p.bump(); // the label
    if let Err(err) = expect_token(p, CppTokenKind::Colon) {
        p.close_marks_above(base);
        return Err(err);
    }

    // Attributes may follow a label: `foo: [[likely]]`.
    while p.current_token() == CppTokenKind::LeftBracket
        && p.peek_next_token() == CppTokenKind::LeftBracket
    {
        if types::parse_attribute_specifier(p).is_err() {
            break;
        }
    }

    Ok(m.complete(p))
}

/// **Is this statement `name ( & …`?** — see the rule at the head of `parse_declaration_or_expression_statement`.
fn a_call_whose_first_argument_is_an_address(p: &CppParser) -> bool {
    // `token_kind_at` is an **absolute** index, so the lookahead is from the current token — the first version of this
    // asked for tokens 0, 1 and 2, which are the first three of the file and never a call.
    let at = p.current_token_index();
    p.token_kind_at(at) == CppTokenKind::Identifier
        && p.token_kind_at(at + 1) == CppTokenKind::LeftParen
        && p.token_kind_at(at + 2) == CppTokenKind::Ampersand
}