cpp_parser 0.1.1

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
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
//! Declarations.
//!
//! The grammar is `decl-specifier-seq init-declarator-list(opt) ;`, plus the function-definition
//! form where the last declarator is followed by a body instead of a semicolon. Classes, enums and
//! namespaces are declarations whose declarator is special, so they plug in here.
//!
//! # Declarations versus expressions
//!
//! This is *the* ambiguity of C++ parsing, and it cannot be resolved syntactically:
//!
//! ```text
//! a * b;               declaration of `b` as a pointer to `a`? or multiplication?
//! T(x);                declaration of `x`? or a functional cast / function call?
//! Widget w(1, 2, 3);   declaration of `w`? or a call to `w` with three arguments?
//! ```
//!
//! There is no symbol table in a parser that must work on a file being edited, so the question is answered
//! *speculatively*: [`parse_declaration`] tries the declaration reading, and if it does not land on a
//! plausible end (a `;`, a `{`, or an initializer), the caller rewinds and treats the tokens as an
//! expression. [`stats::parse_declaration_or_expression_statement`] is that caller.
//!
//! # What breaks the tie inside the declaration reading
//!
//! The backtrack settles *whether* a statement is a declaration. It cannot settle where the type ends and the
//! declarator begins, which is a decision the declaration reading has to make on its own — and that decision
//! is what [`declarator_starts_with_a_known_type_name`], [`the_arguments_look_like_values`] and
//! [`the_arguments_look_like_declarators`] answer between them. In order of strength:
//!
//! 1. **A keyword type.** `int a(1);` — no expression begins with `int`.
//! 2. **A name the file declares to be a type.** `struct Widget {}; Widget w(1, 2);` — see
//!    [`crate::parser::TypeNames`].
//! 3. **A name, then a second name, then parentheses holding values.** `Widget w(1, 2, 3);` — the shape no
//!    call has. The second name is the declarator and the parentheses are its initializer.
//! 4. **File scope, with parentheses holding names.** `Max(a, b);` — a statement at file scope is not a
//!    call, and bare names are what an initializer most often copies.
//!
//! Each rule is strictly weaker than the one before it, and each is refused rather than guessed when the
//! evidence is absent: a call read as a declaration loses its callee *and* its arguments, while a declaration
//! read as a call merely leaves a variable unbound. That asymmetry is the whole design, and it is why
//! `A(B);` stays a call while `Widget w(1, 2, 3);` is a declaration.
//!
//! The cost is one re-parse of a statement whose first token is ambiguous, and a handful of documented
//! readings given up — `tests/gaps.rs` lists them, and `tests/direct_init.rs` pins the rules themselves.

use crate::{
    grammar::{
        ParseResult,
        cpp::{exprs, modules, stats, types},
    },
    kind::{CppSyntaxKind, CppTokenKind},
    parser::{CompleteMarker, CppParser, Marker, MarkerEventContainer, ParseAnchor},
    parser_error::CppParseError,
    symbols::SymbolKind,
};

use super::{
    at_concept, at_requires, expect_contextual_keyword, expect_token,
    exprs::parse_expr,
    stats::{parse_compound_stat, parse_stats},
    types::{
        definitely_ends_a_type, is_type_specifier_keyword, parse_decl_specifier_seq,
        parse_declarator, parse_declarator_with, parse_name, parse_type_id,
    },
};
/// Parse a template head: `template <typename T, int N>`, or the explicit-specialization
/// `template <>`.
///
/// The head is kept as its own node so a consumer can ask "is this declaration templated?" without
/// re-scanning tokens, and so the parameter list keeps its own children.
///
/// Visible to the specifier sequence, which is the other rule that can meet a head: a declaration whose two
/// conditional branches each write one puts the second head in the middle of that sequence. See the note in
/// [`types::parse_decl_specifier_seq_with`].
pub(super) fn parse_template_head(p: &mut CppParser) -> ParseResult {
    // A template parameter list has the same `>`-closes-the-list property an argument list has:
    // `template <int N = 3>` must not read the `>` as "greater than". Restored on every exit path.
    let previous_depth = p.enter_template_arguments();
    let result = parse_template_head_inner(p, previous_depth);
    p.leave_template_arguments(previous_depth);
    result
}

fn parse_template_head_inner(p: &mut CppParser, outer_depth: Option<usize>) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::TemplateDecl);

    expect_token(p, CppTokenKind::TemplateKeyword)?;

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

    // The parameter list is over, so the angles are closed and a `>` from here on is the greater-than operator
    // again. The clause below is where that shows: `template <typename T> requires (sizeof(T) > 1) void f();`
    // read the `>` as closing a template argument list that had already ended, and reported `expected )`.
    //
    // Restoring the *outer* depth rather than zero, in case this head is itself written inside template
    // arguments. The caller's own restore handles the way out.
    p.leave_template_arguments(outer_depth);

    // C++20: a template head may end in a **requires-clause**: `template <typename T> requires C<T> void f();`.
    // It comes after the parameter list and before whatever the head introduces, which is why this is the place
    // that can read it — the clause belongs to neither the parameters nor the declaration.
    //
    // `requires` is contextual, so the word alone decides nothing: `template <typename T> requires requires(T t)
    // { }` is a clause whose constraint is an expression, and a *name* spelled `requires` would be a parameter
    // list's worth of something else. Reading the clause is what tells them apart, which is why the clause rule
    // is entered and its failure tolerated rather than a lookahead being asked.
    if at_requires(p)
        && let Err(err) = parse_requires_clause(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Parse a **concept declaration** (C++20): `concept Name = constraint;`.
///
/// Entered with the template head already consumed, so the cursor is on `concept`. The four parts are `concept`,
/// a name, `=`, and a constraint — and the constraint is read as an expression, because that is what it is.
///
/// The name is a plain name rather than a declarator: a concept introduces a *name* for a constraint, with no
/// type and no declarator around it, which is why this rule exists instead of the general one.
fn parse_concept_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ConceptDecl);

    expect_contextual_keyword(p, "concept")?;

    // The name. Optional in the grammar's own terms only for recovery: a concept without a name is broken, and
    // saying so once is better than consuming whatever follows as one.
    if p.current_token() == CppTokenKind::Identifier {
        if let Err(err) = parse_name(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    } else {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("expected a concept name"),
            p.current_token_range(),
        ));
    }

    // The constraint, and then a requires-clause of its own may follow: `concept C = true && requires { … };`
    // is one expression, while `concept C = X requires Y;` is not valid — so there is no clause to read here.
    // What *is* read is the expression, and a requires-expression inside it is handled by the expression rule.
    //
    // Read with the braced-initialiser reading refused, for the same reason a requires-clause does: the
    // constraint ends at the `;`, and a `{` in it belongs to a requirement rather than to an initializer.
    //
    // The definition is read **once per branch** (`#if A = X; #else = Y; #endif`), which is how libstdc++ writes
    // `__is_signed_int128` and its neighbours; see [`parse_a_definition_per_branch`].
    let ended = parse_a_definition_per_branch(p, exprs::parse_constraint_expr);

    match ended {
        Err(err) => {
            p.close_marks_above(base);
            return Err(err);
        }
        // `true` means the branch's own `;` was the declaration's, so there is nothing left to ask for.
        Ok(ended) if !ended => {
            if let Err(err) = expect_semicolon(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }
        Ok(_) => {}
    }

    Ok(m.complete(p))
}

/// Is the `requires` at the cursor a **requires-clause** rather than an identifier?
///
/// `requires` is contextual, so the token alone decides nothing — `int requires = 1;` and `f(requires);` are both
/// valid programs, and a clause has to be told from them. The test is the one the type grammar uses for its own
/// ambiguities and for the same reason: **try the reading and see whether it consumes anything**.
///
/// ```text
/// requires C<T>;              a clause: a constraint follows
/// requires (C<T>);            a clause: a parenthesised constraint
/// requires requires { … }     a clause whose constraint is a requires-expression
/// requires = 1;               an identifier — `=` cannot begin a constraint, so nothing is consumed
/// requires;                   … and neither can `;`
/// requires(x);                a call — the parenthesis is consumed as a *constraint*, and what follows tells
/// ```
///
/// An earlier version of this asked what the token after `requires` was, from a list of "tokens that can begin an
/// expression". That list was wrong within minutes — it left out `&&`, so `requires C<T> && C2<T>` read the
/// clause as ending at `C<T>` — and it would have gone on being wrong for every operator added later. Trying the
/// parse has no such list to maintain, and it is the same bounded backtracking the declaration/expression
/// ambiguity already relies on.
///
/// Exposed to the expression grammar for the **nested requirement**: inside a requires-expression's body,
/// `requires C<T>;` is a clause while `requires;` is a simple requirement naming a variable called `requires`.
/// The same test separates them there, for the same reason.
pub(super) fn starts_a_requires_clause(p: &mut CppParser) -> bool {
    let checkpoint = p.checkpoint();
    let started_at = p.current_token_index();
    let parsed = parse_requires_clause(p);
    let consumed = parsed.is_ok() && p.current_token_index() > started_at;
    p.rollback(checkpoint);
    consumed
}

/// Parse a **requires-clause**: `requires` followed by a constraint expression.
///
/// Called from the four places the standard allows one, and shared by all of them because the clause is the same
/// construct in each — only its position differs:
///
/// ```text
/// template <typename T> requires C<T> void f();          after the template parameter list
/// template <typename T> void f(T t) requires C<T>;       after the declarator
/// template <typename T> struct S requires C<T> { };      after a class head
/// template <typename T> concept C = requires { f(); };   … and nested inside a requires-expression
/// ```
///
/// The constraint is read as an **expression**, which is what it is: `C<T>`, `C<T> && C2<T>`, `sizeof(T) > 4`,
/// `(C<T>)`, and a requires-expression are all expressions, and the operator rules already know how to read all
/// of them. Nothing here needs to know which of them it got.
///
/// It stops where an expression stops, which is what makes the clause safe to read in a position where a
/// declaration follows: `requires C<T> void f();` ends the constraint at `void`, because `void` cannot continue
/// an expression.
pub fn parse_requires_clause(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::RequiresClause);

    expect_contextual_keyword(p, "requires")?;

    // The constraint, read with the braced-initialiser reading refused: the `{` after it opens the *body* of
    // whatever the clause constrains. See [`exprs::parse_constraint_expr`].
    if let Err(err) = exprs::parse_constraint_expr(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Parse a template parameter list: the `<` … `>` of `template <typename T>`, and of a C++20 generic
/// lambda's `[]<typename T>`.
///
/// Shared by [`parse_template_head`] and the lambda rule in the expression grammar, because the two
/// spell the same list and only differ in the keyword in front of it — a lambda has none, its capture
/// list stands where `template` does. The list is the part with the rules in it (`>>` splitting, packs,
/// constrained parameters, defaults), so a second copy for lambdas is exactly how generic lambdas would
/// come to disagree with class templates about what a parameter list is.
pub fn parse_template_parameter_list(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::TemplateParameterList);

    expect_token(p, CppTokenKind::Less)?;

    // `template <>` — an explicit specialization has an empty list.
    if p.current_token() == CppTokenKind::Greater {
        p.bump();
        return Ok(m.complete(p));
    }

    loop {
        // A **directive between parameters** — and, like the argument list's own seam, in front of a parameter's
        // default argument, which is where `bits/cpp_type_traits.h:620` writes one:
        //
        // ```cpp
        // template<typename _Tp, bool _TreatAsBytes =
        // #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        //       __is_integer<_Tp>::__value
        // #else
        //       __is_byte<_Tp>::__value
        // #endif
        //         >
        // ```
        if p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            continue;
        }

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

        // **The directive that closes a conditional default argument** — the far end of the seam the parameter
        // rule opens after its `=`:
        //
        // ```cpp
        // template<int N =
        // #if X
        //   1
        // #else
        //   2
        // #endif          // ← arrives here, where the list expects `,` or `>`
        //   >
        // ```
        //
        // Read *before* the terminator is matched rather than by going round the loop again: a directive here
        // ends something, so the next token is the `,`/`>` this parameter was always going to end with — going
        // round would ask for another *parameter* and report a missing type specifier at the `>`.
        let mut terminator = p.current_token();
        while terminator == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            terminator = p.current_token();
        }

        match terminator {
            CppTokenKind::Comma => {
                p.bump();
                continue;
            }
            CppTokenKind::Greater => {
                p.bump();
                break;
            }
            // `>>` closing a nested list — `template <template <class> class T>` — was an arm here, splitting the
            // token in place before bumping once. The lexer now leaves every `>` on its own (`CppLexer::tokenize`),
            // so the arm above is the whole of it: the first `>` ends this list and the outer list's reader finds
            // the second where it expects it.
            // **A macro that is the rest of the list.** `bits/refwrap.h:142` writes
            //
            // ```cpp
            // template<typename _Res, typename... _ArgTypes _GLIBCXX_NOEXCEPT_PARM>
            // ```
            //
            // and that macro is `, bool _NE` in `bits/c++config.h` — the **separator and a parameter** live in a
            // header, so nothing among this file's tokens says the list continues. The position carries as
            // much of the answer as the evidence does: an identifier here can neither continue the parameter that
            // was just read nor close the list, so the file is already wrong unless this name is a macro standing
            // where the separator goes. Read as an invocation, then let the loop continue: the body may supply
            // `, more`, and a body that is empty leaves the next token to close the list.
            CppTokenKind::Identifier if types::written_like_a_macro(p.current_token_text()) => {
                let m = p.mark(CppSyntaxKind::MacroCall);
                let name = p.mark(CppSyntaxKind::NameExpr);
                p.bump();
                name.complete(p);
                m.complete(p);

                if p.current_token() == CppTokenKind::Greater {
                    p.bump();
                    break;
                }
                continue;
            }
            _ => {
                p.close_marks_above(base);
                return Err(CppParseError::syntax_error_from(
                    &t!("expected `,` or `>` in template parameter list"),
                    p.current_token_range(),
                ));
            }
        }
    }

    Ok(m.complete(p))
}

/// Does this token end the part of a template parameter that a declarator could occupy?
///
/// [`definitely_ends_a_type`] plus the two tokens a parameter's *list* provides: a `,` before the next
/// parameter, and the pack marker of `typename... Rest`. A `>` would end it too, and is already in the set —
/// `>>` is not, because by the time the list is being walked a nested closer has been split.
fn ends_a_template_parameter_head(kind: CppTokenKind) -> bool {
    definitely_ends_a_type(kind) || matches!(kind, CppTokenKind::Ellipsis | CppTokenKind::Greater)
}

/// The name this template parameter declares as a **type**, when it declares one.
///
/// Three spellings introduce a type parameter, and all three are asked of the **tokens in front** of the
/// parameter rather than of anything the parse produced:
///
/// ```text
/// typename T        class T        typename… Ts / class… Ts
/// ```
///
/// `template <…> class C` is a fourth, and it is asked after the inner head has been read — the name comes
/// *after* the head, which is the only reason this is called twice in [`parse_template_parameter`].
///
/// Everything else declares a **value** — `int N`, `auto N`, `size_t N` — and is deliberately not a type name:
/// `N[4]` is a subscript of an array, not an array of `N`.
fn a_type_parameter_name(p: &CppParser) -> Option<String> {
    if !matches!(
        p.current_token(),
        CppTokenKind::TypenameKeyword | CppTokenKind::ClassKeyword
    ) {
        return None;
    }

    // `typename… Ts` / `class… Ts`: the name follows the pack marker, which follows the keyword.
    if p.peek_next_token() == CppTokenKind::Ellipsis {
        let name = p.peek_token_text_at(2);
        return (!name.is_empty()).then(|| name.to_string());
    }

    if p.peek_next_token() != CppTokenKind::Identifier {
        return None;
    }

    Some(p.peek_token_text_at(1).to_string())
}

/// Parse one template parameter: `typename T`, `class C`, `int N`, `template <...> class T`,
/// `T...`, or a constrained parameter `C T`.
fn parse_template_parameter(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::TemplateParameter);

    // Which parameters declare a **type**, recorded before anything consumes them: the specifier sequence reads
    // `typename T` as one specifier, so by the time it returns the name is behind the cursor and the spelling
    // that said "this is a type" is the only thing that could have told us. `int N` and `auto N` declare values
    // and are deliberately not recorded — `N[4]` is not an array of anything.
    if let Some(name) = a_type_parameter_name(p) {
        p.declare_template_parameter(&name);
    }

    // A template template parameter: `template <typename> class C`.
    if p.current_token() == CppTokenKind::TemplateKeyword
        && let Err(err) = parse_template_head(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    // The name of a **template template** parameter comes after its head: `template <…> class C`. The head has
    // just been read, so this is the first moment the `class C` half can be seen, and the spelling is the same
    // one the check above looks for.
    if let Some(name) = a_type_parameter_name(p) {
        p.declare_template_parameter(&name);
    }

    // `typename... Rest` — the one spelling that cannot go through the declaration machinery below, and the
    // reason is worth recording because the failure it caused was not where it looked. The specifier sequence
    // sees `typename`, then the `...`, which is not a specifier — so it stops, having consumed only the
    // keyword, and reports the ellipsis as an unreadable specifier while the *parameter* marker ends up at
    // `Rest`. What came out was `expected ',' or '>'` against a name the list had never asked for. Consuming
    // both keywords together here keeps the two halves of the pack in one rule.
    //
    // `class... Ts` and `int... Ns` do not need this: there the marker follows a type that is one keyword, and
    // the specifier loop claims the pair through the pack branch in
    // [`types::parse_one_decl_specifier_inner`].
    if p.current_token() == CppTokenKind::TypenameKeyword
        && p.peek_next_token() == CppTokenKind::Ellipsis
    {
        let typename_type = p.mark(CppSyntaxKind::TypenameType);
        p.bump(); // `typename`
        p.bump(); // `...`
        typename_type.complete(p);

        if p.current_token() == CppTokenKind::Identifier
            && let Err(err) = parse_name(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // The parameter itself is a declaration: `typename T`, `int N`, `auto N`, and a constrained
    // parameter is a type followed by a name. Reusing the declaration machinery keeps the shapes
    // the same as everywhere else.
    //
    // **A constrained parameter declares a *type* as well**, and `a_type_parameter_name` above only knows the
    // `typename`/`class` spellings. The spelling here is a *name* and then the parameter's own name —
    // `template<__format::__char _CharT, size_t _Nm>` — so unless it is recorded, `_CharT` is not a template
    // parameter as far as the argument reader is concerned, and `formatter<_CharT[_Nm], _CharT>` (whose first
    // argument is an array *of* it) reads `_CharT` as an expression and refuses at the `[`. Measured: 2 of the 3
    // remaining errors in GCC 15's `<format>`, and the same shape is how every concept-constrained parameter is
    // written.
    //
    // The specifier must **start with a name** for this to apply: `int N` and `auto N` declare values, and a
    // keyword is what tells them apart.
    let a_name_precedes_the_parameter = matches!(
        p.current_token(),
        CppTokenKind::Identifier | CppTokenKind::Scope
    );
    if let Err(err) = parse_decl_specifier_seq(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // The element name, and a pack expansion marker. The ellipsis is excluded because a parameter can end in
    // one with no name before it — `int... Ns` — and the declarator rule has nothing to read there.
    let declarator_from = p.current_event_count();
    if !ends_a_template_parameter_head(p.current_token())
        && p.current_token() != CppTokenKind::Ellipsis
        && let Err(err) = parse_declarator(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    // **The constrained parameter's name, recorded now that the declarator has produced it.** See the note above
    // the specifier sequence for why this spelling needs its own line.
    if a_name_precedes_the_parameter
        && let Some(name) = p.the_name_a_declarator_introduced(declarator_from)
    {
        p.declare_template_parameter(&name);
    }

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

        // The pack's *name* follows the marker in three of the four spellings — `class... Ts`, `int... Ns`,
        // `typename... Rest` — and only `T...` puts it first. Consuming the marker therefore leaves the
        // parameter unfinished, and what happens next is the name being left behind: the list loop finds an
        // identifier where it expects `,` or `>` and reports the parameter as malformed. The two spellings are
        // indistinguishable at this point, so the rule is the same for both: a name here belongs to the pack.
        if p.current_token() == CppTokenKind::Identifier
            && let Err(err) = parse_name(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    // A default argument. Which grammar applies depends on the parameter kind, and that is not
    // known here: `typename T = std::vector<int>` defaults a *type*, while `int N = 3` defaults a
    // *value*. Trying the type first and falling back to an expression resolves it without tracking
    // which kind of parameter this is — and the type reading must be tried first, because
    // `std::vector<int>` is also a perfectly good (if nonsensical) expression and reading it that
    // way would lose the template argument list.
    //
    // "Did it parse?" is not enough to decide: `parse_type_id` can succeed having consumed
    // *nothing*, which is the correct answer for a type-id that is absent. Without the progress
    // check below, `3` in `int N = 3` leaves a successful, empty type-id behind, the list loop then
    // sees `=` where it expects `,` or `>`, and the whole declaration unwinds into an error node.
    if p.current_token() == CppTokenKind::Assign {
        p.bump();

        // **A directive where the default argument begins** — the conditional default, which is a real spelling
        // in libstdc++ and not only in the file this was found in:
        //
        // ```cpp
        // template<typename _Tp, bool _TreatAsBytes =        // bits/cpp_type_traits.h:620
        // #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        //       __is_integer<_Tp>::__value
        // #else
        //       __is_byte<_Tp>::__value
        // #endif
        //         >
        // ```
        //
        // A `#` after the `=` cannot be anything else: a default argument begins with a type, an expression — or
        // a directive.
        while p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

        // **…and the value itself may be written once per branch.** An `#else`/`#elif` here does *not* start a new
        // parameter — it spells the same argument the other way, so another value follows:
        //
        // ```cpp
        // template<int N =
        // #if X
        //   1
        // #else
        //   2          // ← the same parameter's other spelling, not a parameter with no type
        // #endif
        //   >
        // ```
        //
        // The `#endif` is read on the way *out*, by the parameter list's own seam, which is why only `else`/`elif`
        // is the loop's business here.
        loop {
            parse_a_default_value(p, base)?;

            if p.current_token() != CppTokenKind::Hash
                || !matches!(p.peek_token_text_at(1), "else" | "elif")
            {
                break;
            }

            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }
    }

    Ok(m.complete(p))
}

/// One value of a template parameter's default argument: a type, or an expression.
///
/// The two readings are tried in this order for the reason [`parse_template_parameter`] gives: a type-id is the
/// narrower question, and `std::vector<int>` is also a perfectly good expression to the other one. Factored out
/// because the value can be written **once per branch** — see the loop that calls it.
fn parse_a_default_value(p: &mut CppParser, base: usize) -> ParseResult {
    let type_checkpoint = p.checkpoint();
    let before = p.current_token_index();
    let parsed_a_type = parse_type_id(p).is_ok() && p.current_token_index() > before;

    // A type that **stops in the middle of a value** is not the answer. `ranges_util.h:267` writes
    //
    // ```cpp
    // template<input_or_output_iterator _It, sentinel_for<_It> _Sent = _It,
    //          subrange_kind _Kind = sized_sentinel_for<_Sent, _It>
    //            ? subrange_kind::sized : subrange_kind::unsized>
    // ```
    //
    // and the default is a **conditional expression whose head is a type**: the type reading takes
    // `sized_sentinel_for<_Sent, _It>` and stops, leaving the `?` to the parameter list, which reports
    // ``expected `,` or `>` ``. So the type counts only when the list can actually continue after it — a separator,
    // or the `#` the conditional-default seam reads. Otherwise the same tokens are read as the value they are.
    if parsed_a_type && ends_a_template_parameter(p) {
        return Ok(CompleteMarker::empty());
    }

    p.rollback(type_checkpoint);

    // Read **below the comma operator**: the comma after a default argument separates the next parameter.
    // `template <typename T, int N = 3, typename... Rest>` is three parameters, and a reader that took the comma
    // swallowed the third — which is how this rule was found.
    if let Err(err) = exprs::parse_assignment_expr(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(CompleteMarker::empty())
}

/// Can a template parameter **end** at this token — one of the list's own separators, or a directive seam?
fn ends_a_template_parameter(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::Comma
            | CppTokenKind::Greater
            | CppTokenKind::RightShift
            | CppTokenKind::Hash
            | CppTokenKind::Eof
    )
}
///
/// Returns `Err` without having consumed anything when the input does not look like a declaration,
/// so the caller can fall back to parsing an expression statement.
pub fn parse_declaration(p: &mut CppParser) -> ParseResult {
    // A declaration is the one place a bare template-id may stand where a *name* belongs, and only when the
    // declaration is an **explicit instantiation**: `extern template void f<int>(int);` names the instantiation
    // it asks for, and that name is a template-id. Everywhere else `C<T> x;` gives the arguments to the type.
    //
    // Cleared on entry and restored on the way out, on every path including the error ones: a flag that
    // outlived its declaration would let the *next* one read a bare template-id as a name, which is the silent
    // wrong tree the rule exists to prevent. See [`crate::grammar::cpp::types::a_bare_template_id_is_here`].
    let outer = p.a_template_id_may_be_the_name();
    p.set_a_template_id_may_be_the_name(false);

    // A **template parameter** is a name declared as a type, and it is scoped to the declaration its head
    // introduces — so this is where that scope ends. The count is saved rather than the list, and cut back
    // rather than cleared, so a nested declaration (a member of a class template) keeps the parameters of the
    // head around it: what *it* saved already includes them.
    let parameters_before = p.template_parameter_count();

    let result = parse_declaration_here(p);

    p.truncate_template_parameters(parameters_before);
    p.set_a_template_id_may_be_the_name(outer);
    result
}

fn parse_declaration_here(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let checkpoint = p.checkpoint();

    // Declarations whose shape is not `specifiers declarators ;` get their own rules, dispatched
    // first because the general rule would read their keyword as a type specifier and then report
    // nonsense about everything after it.
    match p.current_token() {
        CppTokenKind::NamespaceKeyword => return parse_namespace_declaration(p),
        CppTokenKind::TypedefKeyword => return parse_typedef_declaration(p),
        CppTokenKind::StaticAssertKeyword => return parse_static_assert(p),

        // `inline namespace v1 { ... }` — an **inline namespace**, which is a namespace whose members are also
        // members of the enclosing one.
        //
        // Dispatched here because `inline` is dispatched nowhere and `namespace` is not a type: the specifier
        // sequence claims `inline`, stops at `namespace`, and the declaration is refused. The keyword is
        // consumed *before* delegating so that the namespace rule starts where it expects to — and it is
        // consumed rather than skipped, so a consumer reading the `NamespaceDecl`'s own tokens can still see
        // that the namespace is inline.
        CppTokenKind::InlineKeyword if p.peek_next_token() == CppTokenKind::NamespaceKeyword => {
            p.bump(); // `inline`
            return parse_namespace_declaration(p);
        }

        // `extern template struct S<int>;` — an **explicit instantiation declaration** — is consumed *inside*
        // the declaration node, below, rather than here: a token is emitted at the moment it is consumed, so
        // consuming it before the marker existed would put `extern template` beside the declaration instead of
        // in it, and "is this declaration an instantiation rather than a definition?" is answered by reading the
        // declaration's own tokens.

        // A using-declaration or alias — `using ns::f;`, `using Alias = T;`.
        //
        // Dispatched here rather than left to the general rule, which begins with a specifier and would read
        // `using` as a type. At file scope the statement rule happens to claim it first, which is why this gap
        // was invisible until a *class member* was written the same way: `using Base::method;` inside a class
        // came out as an error node holding the keyword and a declaration of a type called `Base::method`.
        CppTokenKind::UsingKeyword => return parse_using_declaration(p),
        CppTokenKind::ExternKeyword if starts_a_linkage_specification(p) => {
            return parse_linkage_specification(p);
        }
        // A destructor — `~S();`, `~S() {}`, `virtual ~S() = default;`.
        //
        // Dispatched here rather than left to the general rule because the tilde is *part of the name* and the
        // specifier sequence, which runs first, sees it as a unary operator where a type should be: the whole
        // declaration was refused, the tilde was wrapped in an error node on its own, and what followed was
        // read as a declaration of `S` with a parameter list and nothing named.
        CppTokenKind::Tilde => return parse_destructor_declaration(p),
        // `__thiscall ~_Lockit() noexcept;` — a destructor with a calling convention written before the `~`, which is
        // where MSVC's `<yvals.h>` puts it. The convention is part of the declaration, so it is read inside it.
        CppTokenKind::Identifier
            if p.peek_next_token() == CppTokenKind::Tilde
                && matches!(
                    p.current_token_text(),
                    "__thiscall"
                        | "__cdecl"
                        | "__stdcall"
                        | "__fastcall"
                        | "__vectorcall"
                        | "__clrcall"
                ) =>
        {
            return parse_destructor_declaration(p);
        }

        // A **conversion operator** — `operator int();`, `operator std::string() const;`.
        //
        // Dispatched here for the same reason as the destructor: the name is written first, so no type
        // precedes it and the specifier sequence has nothing to read. It used to be dispatched nowhere at
        // all, and the result was silent: `operator` became an error node, `int` a declaration of a variable
        // named `int`, and the `()` another error — with no message reported.
        //
        // Safe to claim unconditionally, because no *other* declaration begins with `operator`: an overloaded
        // operator's return type comes first (`Ops operator+(const Ops&)`), so a declaration whose first token
        // is `operator` can only be a conversion.
        CppTokenKind::OperatorKeyword => return parse_conversion_operator_declaration(p),

        // A **constructor** — `Widget();`, `Widget(int size);`, `Widget(int) : base(1) {}`.
        //
        // The third declaration whose name is written first, and the one that cannot be recognised by its *first*
        // token alone: the name is also the type, so the general rule below reads it as a specifier and then sees the
        // `(` as the start of a declarator — a **nameless** function declarator. Measured, `Widget(int size);` inside
        // a class body came out as
        //
        // ```text
        //   Declaration
        //     DeclSpecifierSeq > NamedType > NameExpr "Widget"   <- the name, read as the TYPE
        //     InitDeclarator > Declarator > ParameterList        <- and a declarator with no name of its own
        // ```
        //
        // so there was **no constructor declaration in the tree at all**. What that cost, measured: signature help
        // offered nothing for `Widget(|)` — there was no declaration to render a parameter list from — and MSVC's
        // `sprintf_s` arrived in the index as a `Variable` of type `_CSTD`, because the `extern "C"` block its header
        // opens with a macro has exactly this shape and every declaration in it was read the same wrong way.
        //
        // Claimed only where it cannot be anything else: at a **class body's own member level**, at an identifier the
        // declaration could only be naming, followed directly by `(`. The other shape that begins this way is a
        // parameter list starting with `*` or `&` — `Widget (*fp)(int);` declares a member — and it is left to the
        // general rule.
        CppTokenKind::Identifier
            if p.is_at_class_member_level()
                // **The name has to be the class's own.** Shape alone cannot decide: `Widget(` and `f(` are the same
                // two tokens, and the difference that matters is written in the *enclosing* declaration. The test
                // that made this necessary is `a_split_member_head_may_name_its_type_in_the_else_branch`: a member
                // function whose return type is written in the other branch of an `#if` reaches this point as an
                // identifier followed by `(`, and reading it as a constructor renamed the member.
                && p.current_class_name().is_some_and(|class| class == p.current_token_text())
                && p.peek_next_token() == CppTokenKind::LeftParen
                // A parameter list that starts with `*` or `&` belongs to the other shape that begins this way:
                // `Widget (*fp)(int);` declares a member.
                && !matches!(
                    p.peek_token_kind_at(2..3).first(),
                    Some(CppTokenKind::Star | CppTokenKind::Ampersand)
                ) =>
        {
            return parse_constructor_declaration(p);
        }

        // `export` heads a module declaration, an export block, or one exported declaration.
        CppTokenKind::ExportKeyword => {
            if p.peek_token_kind_at(1..2)[0] == CppTokenKind::LeftBrace {
                return modules::parse_export_block(p);
            }

            // Everything else is `export declaration`, and the declaration is parsed by the ordinary rule —
            // which is what puts the `export` *inside* the declaration node, so that a consumer reading a
            // declaration's own tokens can see that it is exported. Consuming the keyword here and then
            // wrapping the result would put it outside instead: a token is emitted at the moment it is
            // consumed, and by then the wrapper had not been opened yet.
            //
            // `module` and `import` are contextual keywords — they arrive as identifiers — so the word after
            // `export` is what says whether this is a module declaration or a re-export. Recognised by
            // spelling, which is what [`modules::parse_exported_declaration`] does.
            if matches!(p.peek_token_text_at(1), "module" | "import") {
                return modules::parse_exported_declaration(p);
            }

            // `using`, `namespace`, `typedef` and `static_assert` have rules of their own, and the general
            // rule below cannot start from any of them: it begins with a specifier, and none of those four
            // keywords is one. `export using Point = shapes::Point;` — an everyday line in a module interface —
            // would be read as an expression and reported as broken. Dispatched *after* the keyword so that it
            // is consumed by the rule that owns the construct, which is where those rules expect to start.
            match p.peek_token_kind_at(1..2)[0] {
                CppTokenKind::UsingKeyword => {
                    p.bump();
                    return parse_using_declaration(p);
                }
                CppTokenKind::NamespaceKeyword => {
                    p.bump();
                    return parse_namespace_declaration(p);
                }
                CppTokenKind::TypedefKeyword => {
                    p.bump();
                    return parse_typedef_declaration(p);
                }
                CppTokenKind::StaticAssertKeyword => {
                    p.bump();
                    return parse_static_assert(p);
                }
                _ => {}
            }
        }
        _ => {}
    }

    // C++20 modules. `module` and `import` are contextual keywords, so this is a text check at the
    // start of a declaration rather than a token kind.
    if modules::starts_global_module_fragment(p) {
        return modules::parse_global_module_fragment(p);
    }
    if modules::starts_private_module_fragment(p) {
        return modules::parse_private_module_fragment(p);
    }
    if modules::starts_module_declaration(p) {
        return modules::parse_module_declaration(p);
    }
    if modules::starts_import_declaration(p) {
        return modules::parse_import_declaration(p);
    }

    let m = p.mark(CppSyntaxKind::Declaration);

    // `extern template void f<int>(int);` — an **explicit instantiation declaration**, which says the
    // instantiation is defined in another translation unit.
    //
    // Not a linkage specification, which is the other thing `extern` introduces: that one is followed by a
    // string literal. This one is followed by `template`, and the declaration after it is an ordinary
    // declaration whose *name* is a template-id — so consuming both keywords and letting the general rule below
    // run is the whole fix. Without it the specifier sequence claims `extern`, stops at `template`, and reports
    // `expected ;`.
    //
    // Consumed **inside** the declaration node rather than at the dispatch above: a token is emitted at the moment
    // it is consumed, so consuming it before the marker existed would put `extern template` beside the
    // declaration instead of in it, and "is this declaration an instantiation rather than a definition?" is
    // answered by reading the declaration's own tokens.
    //
    // The two words together are unambiguous — nothing else in C++ spells `extern template` — so no third
    // condition is asked. There used to be one, and it was wrong in a way that is easy to miss: it required a
    // *keyword* type after the `template`, so `extern template MyType f<int>(int);` — legal C++, with a return
    // type the file names itself — was refused while `extern template void f<int>(int);` was read.
    if p.current_token() == CppTokenKind::ExternKeyword
        && p.peek_next_token() == CppTokenKind::TemplateKeyword
    {
        p.bump(); // `extern`
        p.bump(); // `template`

        // What follows names the instantiation, and for a function that name is a **template-id**:
        // `extern template void f<int>(int);`. Recorded for the declarator rule, which otherwise refuses one —
        // correctly, since a declarator's name may not have template arguments in any other declaration.
        p.set_a_template_id_may_be_the_name(true);
    }

    // The same construct **without** `extern`: `template void f<int>(int);`, `template class C<int>;`,
    // `template int v<int>;`.
    //
    // The standard writes the two spellings as one production — `explicit-instantiation: extern(opt) template
    // declaration` — and the only visible difference is the keyword that may be absent. What made this the harder
    // half is that a bare `template` is otherwise the start of a **template head**, which requires a `<`: the
    // head rule was entered, failed on the type specifier that followed, and took the whole declaration down with
    // it. So the `<` is what tells the two apart, and it is asked here, where both readings are still available.
    //
    // A `template` followed by `<` is a head and is left to the rule below; a `template` followed by anything else
    // cannot be one, because a parameter list is not optional.
    if p.current_token() == CppTokenKind::TemplateKeyword
        && p.peek_next_token() != CppTokenKind::Less
    {
        p.bump(); // `template`
        p.set_a_template_id_may_be_the_name(true);
    }

    // The `export` of `export int helper();`, consumed *inside* the declaration node rather than at the
    // dispatch above. A token is emitted at the moment it is consumed, so an `export` consumed before this
    // marker existed would land beside the declaration instead of in it — and "is this declaration exported?"
    // is answered by reading the declaration's own tokens, which is the whole reason the spelling exists.
    if p.current_token() == CppTokenKind::ExportKeyword {
        p.bump();
    }

    // A template head wraps whatever declaration follows it: `template <typename T> struct V {};`
    // is a template *declaration* whose payload is the class. Handling it here rather than in a
    // separate rule is what lets templates apply to classes, functions, variables, aliases and
    // concepts without five copies of the same parser.
    //
    // # Why it is a loop, and what the file writes
    //
    // Because a conditional **alternation of heads** is a real spelling, and `bits/basic_string.h` writes one —
    // two constructors, one per standard level, each with its own head, both inside one declaration:
    //
    // ```cpp
    // #if __cplusplus >= 201103L
    //   template<typename _InputIterator,
    //            typename = std::_RequireInputIter<_InputIterator>>
    // #else
    //   template<typename _InputIterator>
    // #endif
    //   _GLIBCXX20_CONSTEXPR
    //   basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc())
    // ```
    //
    // Reading **one** head and then one directive is what left that member unread: the second `template` reached
    // the specifier sequence, which has no reading for it, so the declaration failed, the whole attempt was rolled
    // back to the first `template`, and the class body's recovery then wrapped the head one token at a time. The
    // member was not a member, and every declaration after it was read as a child of the rubble. Both halves are
    // needed and both are the same seam: a directive between a head and what it heads, or between two of them.
    let mut seen_a_template_head = false;
    loop {
        if p.current_token() == CppTokenKind::TemplateKeyword {
            // Whatever head it is — empty or not — the declaration it introduces is one of the three that may be
            // **named by a template-id**, because each of them has to say *which* template it is about:
            //
            // ```text
            // template <> void f<int>(int);              an explicit specialization: the head is empty
            // template <class T> bool v<T*> = true;      a partial specialization: it is not
            // ```
            //
            // The empty spelling used to be the only one that set this, and the non-empty one was left to the rule
            // that refuses a bare template-id in a declarator's name — a rule written for the *type/name* ambiguity
            // (`C<T> x;` gives the arguments to the type), which has nothing to resolve here: a variable template's
            // partial specialization writes its arguments in the name position and has nowhere else to put them. It
            // cost `bits/stl_pair.h` (`__is_tuple_v<tuple<_Ts...>>`), `concepts` (`__destructible_impl<_Tp>`) and
            // `bits/functional_hash.h` their first error each.
            //
            // Setting it for *every* templated declaration costs nothing: the flag is only consulted at a declarator's
            // name, and no other declaration a head can introduce writes a template-id there — `template <class T>
            // C<T> x;` gives the arguments to the type, which the specifier sequence has already taken.
            p.set_a_template_id_may_be_the_name(true);

            if let Err(err) = parse_template_head(p) {
                p.rollback(checkpoint);
                return Err(err);
            }
            seen_a_template_head = true;
            continue;
        }

        // A directive between the head and what it heads — the `#endif` half of the shape above, and of
        // `#if __cpp_deduction_guides … template<…> #endif`. Read as the node it is, and go round again: the next
        // token is either another head or the declaration itself, and both are answers this loop already has.
        if seen_a_template_head && p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.rollback(checkpoint);
                return Err(err);
            }
            continue;
        }

        // **A clause that a directive pushed away from the head.** The head rule reads a requires-clause written
        // directly after its parameter list, but libstdc++ puts one *inside a conditional* — and then the clause
        // arrives here, with the directive already read:
        //
        // ```cpp
        // template<typename _Tp, typename _Up>
        // #if __cpp_concepts                                            // bits/alloc_traits.h:72
        //   requires requires { typename _Tp::template rebind<_Up>::other; }
        //   struct __rebind<_Tp, _Up>
        // #else
        //   struct __rebind<_Tp, _Up, __void_t<typename _Tp::template rebind<_Up>::other>>
        // #endif
        //   { using type = …; };
        // ```
        //
        // `requires` is contextual, so the arm is a spelling test with the shape test beside it — the same pair the
        // declarator's clause arm uses (`starts_a_requires_clause` tries the clause and reports whether it consumed
        // anything). Read as a clause of the declaration rather than of the head, which is the only place left for
        // it once a directive stands between: the `TemplateDecl` has been completed by then.
        if seen_a_template_head && at_requires(p) && starts_a_requires_clause(p) {
            if let Err(err) = parse_requires_clause(p) {
                p.rollback(checkpoint);
                return Err(err);
            }
            continue;
        }

        break;
    }

    // The head may be followed by a declaration that *is* its own rule, and those rules begin with a
    // keyword the specifier sequence cannot read: `template <typename U> using rebind = Rebind<U>;` is an
    // alias template, and `using` is not a type specifier — the sequence refused it and the declaration
    // was reported as `expected a type specifier` against the `using` itself.
    //
    // Dispatched *after* the head rather than by the match at the top of this function, because at the top
    // the cursor is on the `template` keyword. The rule is called directly rather than by re-entering this
    // function: the declaration marker is already open above, and a second one would leave this call's own
    // marker unpaired — which the translation-unit assertion reports as a rule that unwound past its owner.
    if p.current_token() == CppTokenKind::UsingKeyword {
        if let Err(err) = parse_using_declaration(p) {
            p.rollback(checkpoint);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // A **concept declaration** (C++20): `template <typename T> concept C = constraint;`.
    //
    // Dispatched here, after the head, because that is the shape of the construct: a concept always has one. It
    // is also why it is dispatched beside `using` and `typedef` rather than at the top of this function — at the
    // top the cursor is on the `template` keyword.
    //
    // A concept has no return type and no declarators — it is `concept`, a name, `=`, and a constraint — so the
    // general rule below, which begins with a specifier sequence, has nothing to start from.
    //
    // **The head is required, and that is what keeps the word usable as a name.** `concept` is contextual, so the
    // spelling alone says nothing, and a bare `concept = 2;` is an assignment to a variable of that name — asking
    // this rule to read it produced `expected a concept name` against the `=`. A concept definition always has a
    // template head, so the head is the condition that tells the two apart, and it is one the parser already
    // knows because it just read one.
    if seen_a_template_head && at_concept(p) {
        if let Err(err) = parse_concept_declaration(p) {
            p.rollback(checkpoint);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    if p.current_token() == CppTokenKind::TypedefKeyword {
        if let Err(err) = parse_typedef_declaration(p) {
            p.rollback(checkpoint);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // Attributes written *between* the template head and the declaration it wraps:
    // `template <typename T> [[nodiscard]] T p();`. That position belongs to neither the head nor the
    // specifier sequence — the head has closed by the time the `[[` appears, and the sequence has not started
    // — so it was read by the *declarator*, which reported `expected ';'` against the attribute.
    //
    // Only when a head was actually consumed: an attribute at the start of an ordinary declaration is a
    // specifier and the sequence below owns it.
    //
    // **…and the same position may hold a directive**, in either order, because a conditional can decide which
    // attribute a declaration carries — `bits/nested_exception.h:203` is the file this was found in:
    //
    // ```cpp
    // template<typename _Ex>
    // # if ! __cpp_rtti
    //   [[__gnu__::__always_inline__]]
    // #endif
    //   inline void
    //   rethrow_if_nested(const _Ex& __ex)
    // ```
    //
    // Reading only *one* attribute pass and then handing over to the specifier sequence left the `#endif` where
    // the sequence expected its first specifier: the sequence reads a directive only **between** specifiers (see
    // the note there), so a `#` in front of the first one is not its to take — and the declaration failed whole,
    // leaving the file as bare tokens with a diagnostic on the attribute. Alternating the two here is the same
    // fix as the directive/macro alternation in `finish_init_declarator`, one position earlier.
    if seen_a_template_head {
        loop {
            let before = p.current_token_index();

            if p.current_token() == CppTokenKind::Hash {
                if let Err(err) = stats::parse_preprocessor_directive(p) {
                    p.rollback(checkpoint);
                    return Err(err);
                }
            } else if let Err(err) = types::parse_attribute_specifiers(p) {
                p.rollback(checkpoint);
                return Err(err);
            }

            if p.current_token_index() == before {
                break;
            }
        }
    }

    let specifiers_from = p.current_event_count();

    if let Err(err) = parse_decl_specifier_seq(p) {
        p.rollback(checkpoint);
        return Err(err);
    }
    // A declaration that ends right after its specifiers: `int;` (useless but legal) or, much more
    // commonly, `struct Foo;`.
    if p.current_token() == CppTokenKind::Semicolon {
        p.bump();
        return Ok(m.complete(p));
    }

    // The same thing, one level in: a **`friend` declaration is a specifier whose payload is the whole
    // declaration**, `;` included. `friend void swap(A&, A&);` therefore leaves the cursor on the *next*
    // member with the statement already finished — indistinguishable from an empty specifier sequence by the
    // cursor alone, which is why the outer rule looked for an init-declarator that was not there, failed, and
    // rewound: `friend` ate every member written after it, and the recovery turned them into error nodes.
    //
    // The specifier sequence reports that it finished a statement, which no other specifier ever does.
    if p.take_declaration_ended_inside_specifiers() {
        return Ok(m.complete(p));
    }

    // Definitions of class-like entities: `class Foo { ... };`, `enum E { ... };`,
    // `namespace ns { ... }`. The specifier sequence already consumed the keyword and the name.
    //
    // The second half of the condition is the case where it consumed the head but **not** the body, because a
    // directive stood between them:
    //
    // ```cpp
    // template<typename _Tp, typename _Up>                                  // bits/alloc_traits.h:72
    //   requires requires { typename _Tp::template rebind<_Up>::other; }
    // #if __cpp_concepts
    //   struct __rebind<_Tp, _Up>                     // this branch's head has no body …
    // #else
    //   struct __rebind<_Tp, _Up, __void_t<…>>
    // #endif
    //   { using type = …; };                          // … and the body after `#endif` is shared by both
    // ```
    //
    // `declaration_opens_a_body` cannot see it: it is answered from the tokens **after the cursor** (the
    // declaration's leading keywords are behind it by now, and all that is left in front is the brace). So the
    // question is asked of the specifiers' own events instead — did they write a class-like head? A `{` after one
    // is that head's body and nothing else, since a variable whose type is a class definition has already had its
    // initializer read by the declarator rule.
    if p.current_token() == CppTokenKind::LeftBrace
        && (declaration_opens_a_body(p) || declaration_wrote_a_class_head(p, specifiers_from))
    {
        if let Err(err) = parse_class_body(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        // **The `;` a class definition ends with, and the error when it is not there.**
        //
        // `struct S { int a; }` with nothing after it is a **syntax error** — [dcl.dcl] makes the semicolon part of
        // the member-specification's declaration — and refusing it is not pedantry: the reading that accepted it
        // silently swallowed the rest of the file. Measured on a reader's own file, one missing semicolon took it
        // from **8 declarations to 2 with no diagnostic at all**, which is what the editor showed as "the class I
        // just wrote has no members and neither has anything after it", and the two symptoms reported from it —
        // no completion for a class in the current file, no completion for `v.` below it — are the same defect seen
        // twice.
        //
        // **Only where the absence is unambiguous.** A class definition may be followed by a declarator
        // (`struct S { … } x;`, `enum E { … } *p;`) and by a `;`, and those are the readings the parser already has;
        // what is left when neither follows is a token that **begins a declaration** or closes a scope, and there
        // the `;` can only have been forgotten. Measured, the three shapes are told apart exactly:
        //
        // ```text
        // struct S { int a; };       4 declarations   the `;` is there
        // struct S { int a; } x;     4 declarations   a declarator follows, and the declaration path reads it
        // struct S { int a; }        2 declarations   **nothing follows** — this error, and the recovery that
        //                                              gets the reader the six declarations it was losing
        // ```
        if p.current_token() == CppTokenKind::Semicolon {
            p.bump();
        } else if a_declaration_cannot_follow(p) {
            p.close_marks_above(base);
            return Err(CppParseError::syntax_error_from(
                &t!("expected `;` after a class definition"),
                p.current_token_range(),
            ));
        }
        return Ok(m.complete(p));
    }

    // One or more init-declarators.
    let mut declarators = 0usize;
    loop {
        if let Err(err) = parse_init_declarator(p) {
            if declarators == 0 {
                p.rollback(checkpoint);
                return Err(err);
            }
            p.close_marks_above(base);
            return Err(err);
        }
        declarators += 1;

        if p.current_token() == CppTokenKind::Comma {
            p.bump();
            continue;
        }
        break;
    }

    // A function definition: the last init-declarator was a function declarator and a body
    // follows. `parse_init_declarator` has already recorded the parameters; the body belongs to
    // the declaration.
    if p.current_token() == CppTokenKind::LeftBrace {
        if let Err(err) = parse_compound_stat(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // A class, struct, union or enum definition ends with `;` as part of the *declaration*, not as
    // an empty declaration after it. `class Foo {};` is one declaration; without this, the `;` is
    // parsed as a stray empty statement.
    if p.current_token() == CppTokenKind::Semicolon
        && declaration_defined_a_class(p, specifiers_from)
    {
        p.bump();
        return Ok(m.complete(p));
    }

    // An **old-style (K&R) parameter list ends the declaration as well**: the `;` that closed its last parameter
    // declaration closed *this* declaration too, so there is no second one to expect.
    //
    // ```c
    // #if defined(__CLASSIC_C__)
    // int main(argc, argv)
    // int argc;
    // char *argv[];
    // #else
    // int main(int argc, char *argv[])
    // #endif
    // { … }
    // ```
    //
    // That is the shape the CMake compiler-id probe is written in, and it is the reason the arm above exists: the
    // head and the body sit in *different branches* of one conditional, so the declaration that carries the
    // old-style list has neither a body of its own nor a `;` left to give — `char *argv[];` spent it. Asking again
    // reported `expected ';'` against the `#else`, and a single diagnostic against a *preprocessor* line took the
    // whole definition with it.
    //
    // Nothing but a body can follow a function declarator, so this costs no reading: a declaration that follows is
    // one the old-style list has already swallowed, and the tokens after the cursor belong to whichever rule owns
    // them — a body (read above), a directive, or a statement that reports on its own terms rather than through a
    // declaration that was never wrong.
    if p.events_contain_any(specifiers_from, &[CppSyntaxKind::OldStyleParameterList]) {
        return Ok(m.complete(p));
    }

    // **A declaration that gave up but keeps its tokens** closes what it opened *with* the end events
    // ([`MarkerEventContainer::end_marks_to`]). `close_marks_above` would detach them without an event, and an
    // unpaired `NodeStart` is balanced by the tree builder at the end of the stream — so the declaration that
    // failed here would swallow every token written after it. This is the path `int x = 1` (with no `;`) and
    // `__glibcxx_class_requires(_Tp, Concept)` take inside a class body, and it is why one such member took the
    // rest of `std::vector`'s class with it. The two paths above this one roll back instead, which is the other
    // correct answer: no events, nothing to pair.
    if let Err(err) = expect_semicolon(p) {
        p.end_marks_to(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Did the specifier sequence just parsed contain a class-like *definition* (a body), as opposed to
/// a forward declaration or an elaborated type specifier?
fn declaration_defined_a_class(p: &CppParser, specifiers_from: usize) -> bool {
    p.events_contain_any(
        specifiers_from,
        &[CppSyntaxKind::ClassBody, CppSyntaxKind::CompoundStat],
    )
}

/// Did the specifier sequence just parsed write a **class-like head** — with or without its body?
///
/// The companion of [`declaration_defined_a_class`], and the difference is the case this exists for: a head whose
/// body is on the *other* side of a directive, so the specifiers hold the head alone (see the note at the call
/// site). `class Foo;` also answers yes, and that is right — a brace after it is an error either way, and letting
/// the body rule report it is more informative than reading the brace as an initializer of nothing.
fn declaration_wrote_a_class_head(p: &CppParser, specifiers_from: usize) -> bool {
    p.events_contain_any(
        specifiers_from,
        &[
            CppSyntaxKind::ClassDef,
            CppSyntaxKind::StructDef,
            CppSyntaxKind::UnionDef,
            CppSyntaxKind::EnumDef,
            CppSyntaxKind::EnumClassDef,
        ],
    )
}

/// Does the `{` at the cursor open a body that belongs to the declaration just parsed, rather than
/// an initializer or a following block?
///
/// Only a class-like or namespace specifier makes a brace a *body*; for anything else, `int x { 1 }`
/// is a brace initializer and `{ ... }` after a declaration is a new block. The distinction is
/// decided from the leading tokens of the declaration, which is enough: `struct` / `class` /
/// `union` / `enum` / `namespace` can only appear at the front.
fn declaration_opens_a_body(p: &CppParser) -> bool {
    p.peek_token_kind_at(0..4).iter().any(|kind| {
        matches!(
            kind,
            CppTokenKind::ClassKeyword
                | CppTokenKind::StructKeyword
                | CppTokenKind::UnionKeyword
                | CppTokenKind::EnumKeyword
                | CppTokenKind::NamespaceKeyword
        )
    })
}

/// Parse a structured binding's name list: the `[a, b]` of `auto [a, b] = pair;`.
///
/// Consumes nothing and returns `Err` when the brackets do not hold a binding pattern, which is what
/// lets a `[` that is something else be handled by its own rule.
///
/// # Why the names are `NameExpr` children
///
/// The same node a reference to a name gets, so "which names does this declare?" is one query over
/// one node kind rather than a second kind that means almost the same thing. Each name is followed by
/// an optional `...`, C++26's pack expansion, which is a token here rather than a node: nothing can
/// be said about it until the pack is known, and that is a semantic question.
pub fn parse_structured_binding(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::StructuredBinding);

    expect_token(p, CppTokenKind::LeftBracket)?;

    // An identifier or a pack expansion — `[a, b]`, `[a, ...]`, `[... xs]`. Anything else means this
    // `[` was not a binding pattern after all, and `Err` here sends it to whichever rule owns it.
    while matches!(
        p.current_token(),
        CppTokenKind::Identifier | CppTokenKind::Ellipsis
    ) {
        if p.current_token() == CppTokenKind::Ellipsis {
            p.bump();
            continue;
        }

        let name = p.mark(CppSyntaxKind::NameExpr);
        if let Err(err) = parse_name(p) {
            name.undo(p);
            p.close_marks_above(base);
            return Err(err);
        }
        name.complete(p);

        if p.current_token() != CppTokenKind::Comma {
            break;
        }
        p.bump();
    }

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

    Ok(m.complete(p))
}

/// Is the declaration being read one whose type is a **placeholder** — `auto`, `auto&`, `decltype(auto)`?
///
/// [dcl.struct.bind] allows a structured binding only where the decl-specifier-seq contains a placeholder
/// type, and that is the whole of what separates a binding from an **array declarator**: `[` opens both, and
/// the tokens inside do not tell them apart — `[x]` and `[x::f]` are a binding pattern and an array bound.
///
/// **What happened without this question.** The reading was taken whenever the cursor stood on a `[` where a
/// declarator's name would go, so a declaration the specifier sequence had already taken a name from — `int a`
/// above the bracket — became a binding of `a`'s *array*:
///
/// ```text
/// int a[x::f];    read as: type `int a`, declarator `StructuredBinding [x::f]`
/// int a[::g];     `::` is not a binding name, so the reading failed and the whole declaration was refused
/// ```
///
/// The first is the worse of the two: no error, no diagnostic, and a shape no compiler accepts.
///
/// The walk goes back over the qualifiers a placeholder may carry and stops at the first token that is a
/// name, a keyword type or the start of the declaration — the same backwards walk
/// [`the_declaration_has_a_type`] uses, for the same reason: by the time the `[` is reached, what named the
/// type is behind the cursor.
pub fn the_declaration_is_a_placeholder(p: &CppParser) -> bool {
    let mut index = p.current_token_index();
    let mut inside = 0i64;

    while index > 0 {
        index -= 1;
        let kind = p.token_kind_at(index);

        if is_declaration_trivia(kind) {
            continue;
        }
        match kind {
            // `auto& [k, v]`, `const auto& [k, v]`, `volatile auto …`.
            CppTokenKind::Ampersand
            | CppTokenKind::LogicalAnd
            | CppTokenKind::ConstKeyword
            | CppTokenKind::VolatileKeyword => {}
            // `decltype(auto) [a] = x;` — the placeholder is inside the parentheses.
            CppTokenKind::RightParen => inside += 1,
            CppTokenKind::LeftParen if inside > 0 => inside -= 1,
            CppTokenKind::AutoKeyword => return true,
            _ => return false,
        }
    }

    false
}

/// Parse one `init-declarator`: a declarator plus an optional initializer or function body.
pub fn parse_init_declarator(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::InitDeclarator);
    // Where the declarator's own events start, so `finish_init_declarator` can tell whether it had a
    // parameter list.
    let declarator_from = p.current_event_count();

    // A structured binding: `auto [a, b] = pair;`, or `auto& [k, v] = map;` where the `&` comes
    // first. The plain form is handled here because it is the whole declarator; the reference form is
    // handled inside `parse_declarator`, which is the only place that knows where the name would go.
    //
    // This is not a declarator in any useful sense — no name, no derived type — so it gets its own
    // node rather than a `Declarator` holding brackets. The distinction matters to a consumer: the
    // names inside are separate variables that share one initializer, and a walk that reports "this
    // declaration declares `[a, b]`" is worse than one that reports nothing.
    if p.current_token() == CppTokenKind::LeftBracket && the_declaration_is_a_placeholder(p) {
        if let Err(err) = parse_structured_binding(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        // A binding pattern is never a function declarator, so the flag has to be cleared rather than left as
        // whatever the previous declarator set. It is sticky by design — an empty parameter list leaves no
        // event behind for a caller to look for — and a stale `true` here is what made
        // `for (auto [a, b] : pairs)` consume `: pairs` as a constructor's member initializer list.
        p.set_last_declarator_is_function(false);

        return finish_init_declarator(p, m, declarator_from);
    }

    // `T(x);` and `int (x);` are parenthesized declarators, not calls. Detecting that here is what
    // keeps the declarator reading from mis-nesting the parentheses.
    //
    // Only when the specifier sequence saw no *name*, though. Once it has, the type is written and everything
    // after it is the declarator, so a `(` there cannot be a declarator of its own — `Max(a);` is a statement
    // whose parentheses hold an argument, and reading them as a parenthesized name `a` invented a variable
    // declaration out of a call. A keyword type is the other way round: `int` is never the declarator, so the
    // parentheses are all that is left to hold one.
    //
    // Direct-initialisation — `Widget widget(1, 2);` — is **not** handled here, and the reason is worth
    // recording because the obvious fix does not work. Reading the argument list as an initializer whenever the
    // parentheses hold something other than a single identifier looks right and does make
    // `Widget widget(1, 2);` parse; it also takes `g(1, 2);` away from the expression reading. The specifier
    // sequence takes `g` for a type, this branch consumes `(1, 2)` as an initializer, and the declaration then
    // declares nothing — so a call statement loses its callee *and* its arguments, which the existing
    // `CallExpr` test caught immediately.
    //
    // It is handled by the declarator's own suffix loop instead, which is where the decision can be made from
    // the whole statement rather than from the parentheses alone: the loop runs because the declarator has a
    // name — `Widget w(…)` — or because the arguments look like declarators at file scope, and never for the
    // single-name shape a call has.
    // **The operators may come first**. `int &(f)(void)` and `const _Ty&(max) (…)` are the same
    // declarations as `int (&f)(void)` and `const _Ty&(max)`: the standard's `ptr-declarator` is `ptr-operator
    // ptr-declarator`, and a parenthesized declarator is one of the things that second `ptr-declarator` can be.
    // MSVC's `<utility>` writes `max` and `min` that way, and the branch below only looked for the `(` **at the
    // cursor** with no type name read — so with a `&` in front the declaration fell through to the expression
    // reading and reported ``expected `;` `` at the parameter list.
    //
    // Whether the operators are still ahead of the cursor or the specifier sequence has already taken them into
    // the type differs with the spelling (`int &` is left to the declarator, `const Wat&` is absorbed), so the
    // question is asked of the **whole shape** instead: operators, `(`, a declarator, `)`, and then a **parameter
    // list**. The last part is what keeps `a * (b);` an expression — a product has no `(` after its `)`.
    let at_a_functions_parenthesized_declarator = at_an_operator_led_parenthesized_declarator(p);

    if at_a_functions_parenthesized_declarator
        || (p.current_token() == CppTokenKind::LeftParen && !p.has_declaration_type_name())
    {
        let checkpoint = p.checkpoint();
        let paren = p.mark(CppSyntaxKind::Declarator);
        // The operators are the declarator's own, and they are read here so that what follows them is the `(` the
        // rest of this branch already knows how to read. When the specifier sequence took them into the type there
        // are none left to read, and the loop does nothing.
        while at_a_pointer_operator(p.current_token()) {
            p.bump();
        }
        p.bump();
        // A parenthesized declarator has to *hold* a declarator, and an empty one is not enough. `int (x)`
        // holds a name and `int (*p)(int)` a pointer; the `(` of `g()` holds neither, because the specifier
        // sequence has taken `g` for a type and there is nothing left to name. Without this the empty reading
        // succeeds, the parentheses are consumed as a declarator, and a call statement becomes a declaration of
        // nothing — losing the callee, the arguments, and the expression.
        let named_something = starts_a_declarator(p) && parse_declarator(p).is_ok();
        if !named_something {
            // Not a parenthesized declarator; let the expression reading have it.
            p.rollback(checkpoint);
        } else if p.current_token() == CppTokenKind::RightParen {
            p.bump();
            paren.complete(p);

            // `S()` is a function declarator, and this branch is the one that recognises it: the empty
            // parentheses are consumed here rather than by `parse_parameter_list`, so the flag that
            // `parse_declarator` would have set has to be set here too. Without it a constructor's member
            // initializer list — `S() : a(1) {}` — is not recognised, because the `:` looks like it follows a
            // variable.
            //
            // Safe for the variable reading (`int (x)`, a parenthesized declarator) because the two are
            // distinguished by what follows: a name cannot be followed by `:`, so the flag is only ever
            // consulted on a path where the function reading is the right one.
            p.set_last_declarator_is_function(true);

            // The qualifiers that follow a parameter list, which the suffix loop below does not know about: it
            // continues on `(` and `[`, and `noexcept` is neither. Leaving them to the caller is how
            // `C() noexcept : x(0)` ended up with the `noexcept` unread and the member initializer list
            // unrecognised — the two mistakes are the same one.
            types::eat_function_qualifiers(p);

            if let Err(err) = finish_declarator_suffixes(p, declarator_from) {
                p.close_marks_above(base);
                return Err(err);
            }
            return finish_init_declarator(p, m, declarator_from);
        } else {
            p.rollback(checkpoint);
        }
    }

    if let Err(err) = parse_declarator_with(p, true) {
        p.close_marks_above(base);
        return Err(err);
    }

    finish_init_declarator(p, m, declarator_from)
}

/// The part after the declarator proper: an initializer, a constructor body, or nothing.
///
/// `declarator_from` is an event index taken before the declarator was parsed, used to ask whether
/// that declarator had a parameter list. It is the only reliable way to tell a brace-or-equal
/// initializer from a function body:
///
/// ```text
/// int x{1};                 // no parameter list -> the brace is an initializer
/// int f() { again: ; }      // parameter list    -> the brace is the function's body
/// ```
///
/// Looking at the token after `{` instead does not work, and the failure is not subtle: a label
/// (`again:`) starts with an identifier, exactly like an initializer clause, so a function whose
/// first statement is a label was read as an `InitListExpr` and then reported "expected primary
/// expression" at its own first statement.
/// Finish an init-declarator: the tail every declaration shares.
///
/// # Why the declaration's marker is handed back open
///
/// A function declarator's **body is the declaration's**, and a constructor reaches its `{` down a path that has to
/// open the declaration around a body it has not read yet — [`CompleteMarker::precede`] is that operation, and it
/// needs the node **closed** already and a `Marker` that is still open for the wrapper. So both are returned: the
/// [completed](CompleteMarker) declaration, which is what a caller with nothing more to read wants, and the raw
/// [`Marker`], which is what a caller with a body to wrap wants.
///
/// Completing the declaration *before* the `{` instead — which is what this did — put every function body beside its
/// declaration. Measured on `struct A { A(int f) : x(f) { } };`: `Declaration@11..26` with `CompoundStat@26..42` as a
/// following sibling, so every constructor's parameters were invisible in its own body.
fn finish_init_declarator(p: &mut CppParser, m: Marker, declarator_from: usize) -> ParseResult {
    // A declarator with a parameter list can only declare a function, so a `{` after it opens a
    // body no matter what is inside. `parse_declaration` handles the body; this rule must not
    // consume it.
    //
    // `declarator_from` is only a fallback for callers that did not go through
    // `parse_declarator`; the flag it can be read from records that an *empty* parameter list was
    // seen, which the event stream cannot express because an empty node is dropped.
    let declarator_is_function = p.last_declarator_is_function()
        || p.events_contain_any(
            declarator_from,
            &[
                CppSyntaxKind::ParameterList,
                CppSyntaxKind::TrailingReturnType,
            ],
        );

    // Attributes written **after the declarator**: `int x [[maybe_unused]] = 1;`,
    // `void f() [[noreturn]];`, `[[nodiscard]] int g() [[deprecated]] { return 1; }`.
    //
    // This is the position C++ calls "after the declarator-id and before the initializer", and it is the one
    // that was missing: the specifier sequence reads the attributes written *before* the type, and the
    // class-head rule reads the ones written after a class's name, but a `[[` here reached the initializer
    // rule, which has no notion of an attribute.
    //
    // Consumed before the `declarator_is_function` answer is used rather than after, because the token after
    // the attributes is what decides — `void f() [[noreturn]] { }` has a body, and the brace is one token
    // further along than the match below would look.
    if let Err(err) = types::parse_attribute_specifiers(p) {
        m.undo(p);
        return Err(err);
    }

    // A **macro** in the same position: `__atomic_flag_data_type _M_i _GLIBCXX20_INIT({});`. Read after the
    // attributes and before the initializer question below, because the token *after* it is what decides whether
    // there is an initializer at all — `int x MACRO = 1;` has one and `int x MACRO;` does not. See
    // [`eat_a_macro_suffix`] for why a name here costs nothing.
    while eat_a_macro_suffix(p) {}

    // **An initializer needs something to initialise.** Without this the declaration reading accepts a
    // declarator that named nothing and is followed by `=`, and what comes out is a *silent wrong tree*: `x = 1;`
    // became `Declaration(DeclSpecifierSeq(x), InitDeclarator(=, Initializer(1)))` — no error, no `ErrorNode`,
    // no `MissingNode`, and a shape a consumer reads as a declaration of a variable named by nothing. Every
    // assignment whose left-hand side this file has not seen a type for was read that way, which is most
    // assignments in a body.
    //
    // Failing here is what lets the statement rule do its job: the declaration reading is rewound and the
    // expression reading — the one that owns an assignment — gets the tokens.
    //
    // The condition is asked *after* the attributes are consumed, because an attribute is not a name and must
    // not be mistaken for one; `a_name_was_parsed` reads the declarator's own events, which is the same
    // question [`a_declaration_is_the_better_reading`] asks about `Widget w(1)` versus `g(1)`.
    if an_initializer_needs_a_name(p, declarator_from) {
        m.undo(p);
        return Err(CppParseError::syntax_error_from(
            &t!("expected a declarator name"),
            p.current_token_range(),
        ));
    }

    // **Directives between a function's head and its body.** A conditional head is a real spelling — the two
    // variants of a signature, one per platform:
    //
    // ```c
    // #if defined(_WIN32)
    // void f(void)
    // #else
    // void f()
    // #endif
    // { … }
    // ```
    //
    // A `#` here cannot be anything else: a declarator is followed by a body, a `;`, an initializer — or a
    // directive. Read as the node it is, and the match below is then asked about the token that really follows.
    // The same argument as the two other places do; a `#` anywhere else in an
    // expression is still an error.
    //
    // # Why this alternates with the macro suffixes
    //
    // Because a conditional can decide **which** suffix is written, and libstdc++ writes its copy-on-write
    // constructor exactly that way (`bits/cow_string.h:515`):
    //
    // ```cpp
    // basic_string()
    // #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0
    //   _GLIBCXX_NOEXCEPT                     // a macro suffix, in one branch only
    // #endif
    // #if __cpp_concepts && __glibcxx_type_trait_variable_templates
    //   requires is_default_constructible_v<_Alloc>
    // #endif
    // #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0
    //   : _M_dataplus(…)                      // …and the initializer list, one per branch
    // #else
    //   : _M_dataplus(…)
    // #endif
    //   { }
    // ```
    //
    // With the two loops written one after the other, the macro suffix after `#endif` reached the match below,
    // which has no reading for a bare identifier between a declarator and its body: the declaration failed, and
    // the recovery then took the constructor's `{ }` for the class's closing brace — so `class basic_string`
    // ended 3400 lines early and every member after it was read at file scope. Alternating is the whole fix: a
    // directive may be followed by a macro, and a macro by a directive.
    loop {
        let mut consumed = false;
        while declarator_is_function && p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                m.undo(p);
                return Err(err);
            }
            consumed = true;

            // **The conditional can decide which *qualifier* is written, not only which macro.** The suffix
            // reader has already run by the time this loop is reached, so a qualifier written after the directive
            // was still waiting when the loop came back — and the reading that came out was well formed, lossless
            // and silent, which is the shape of defect this file keeps having to fix:
            //
            // ```cpp
            // void f()                                    // bits/alloc_traits.h:662
            // #if __cplusplus <= 201703L
            //   noexcept(noexcept(__a.construct(__p, __args...)))
            // #else
            //   noexcept(__is_nothrow_new_constructible<_Up, _Args...>)
            // #endif
            //   { … }
            // ```
            //
            // `noexcept` was read as *the next declaration's type* (`BuiltinType` over `noexcept(true)`, a node
            // whose two tokens have nothing to do with each other), the member after it became a `{ }`-initialised
            // variable, and the body's own directives then landed at class scope — which is where the diagnostic
            // finally appeared, 27 lines later, on a member that was not the one at fault. Asking for the
            // qualifiers again after each directive is the whole fix, and it is the same edit as the macro arm
            // below: what a conditional decides may be any part of the suffix.
            types::eat_function_qualifiers(p);
        }
        consumed |= eat_a_macro_suffix(p);
        if !consumed {
            break;
        }
    }

    match p.current_token() {
        CppTokenKind::Assign => {
            p.bump();

            // `= default` and `= delete` — a *defaulted* or *deleted* function definition. Neither keyword
            // can begin an expression, so the initializer rule has nothing to read and would report
            // `expected primary expression` against the one token that makes a modern comparison operator
            // work: `bool operator==(const D&) const = default;` is how C++20 writes one.
            //
            // Kept inside the `Initializer` node rather than consumed as a bare token, because that is what it
            // is: the initializer of a declarator, spelled with a keyword instead of an expression.
            if matches!(
                p.current_token(),
                CppTokenKind::DefaultKeyword | CppTokenKind::DeleteKeyword
            ) {
                let init = p.mark(CppSyntaxKind::Initializer);
                p.bump();
                init.complete(p);
                return Ok(m.complete(p));
            }

            // **An initializer written once per branch is *not* read here, and that is a measured decision.**
            // The spelling is real — `ext/concurrence.h:58` writes the value of one variable in three branches, a
            // `;` in each — and it can be read by [`parse_a_definition_per_branch`], which the alias and concept
            // rules already use for exactly that shape. Routing variable initializers through it was tried three
            // ways and each one cost more than it bought:
            //
            // ```text
            // 1. every `=` through the machinery     `int x = 1;` came back as rubble: the machinery consumes the
            //                                        branch's `;`, and the declaration reader one frame up then asked
            //                                        for a second one
            // 2. … plus a flag saying "the `;` was the    concurrence.h was fixed and **five files broke** —
            //    initializer's" (taken by `expect_semicolon`)  formatfwd.h, nested_exception.h, cmath, aligned_buffer.h,
            //                                        type_traits.h, all of them asking for a specifier they no longer
            //                                        knew how to read: the flag outlived the declaration that set it
            // 3. … plus "consume a branch's `;` only when     the same five files broke again, because the alias and
            //    `#else`/`#elif` follows it"        concept rules *rely* on the old answer for their own branches
            // ```
            //
            // What the three attempts agree on is that the `;` of the last branch is the *declaration's* `;` and
            // the three readers that share this machinery do not agree on who owns it. That is a design question
            // about `parse_a_definition_per_branch` rather than a missing rule, and the enumerator seam beside
            // it, which shares nothing with it, landed.
            let init = p.mark(CppSyntaxKind::Initializer);

            // **A directive between the `=` and the initializer it introduces.** The last seam of a family the
            // enumerator list, the template parameter list, the parameter list and the braced initialiser all
            // already have, in the one position that was missing it — and the position is not exotic, because a
            // *conditional* initializer is written by putting the `#if` after the `=`:
            //
            // ```cpp
            //   _GLIBCXX17_INLINE const _Lock_policy __default_lock_policy =      // ext/concurrence.h:58
            //   #ifndef __GTHREADS
            //     _S_single;
            //   #elif defined _GLIBCXX_HAVE_ATOMIC_LOCK_POLICY
            //     _S_atomic;
            //   #else
            //     _S_mutex;
            //   #endif
            //
            //   const bool __load_outside_loop =                                  // bits/stl_algobase.h:906
            //   #if __has_builtin(__is_trivially_constructible) \
            //         && __has_builtin(__is_trivially_assignable)
            //       __is_trivially_constructible(_Tp, const _Tp&)
            //       && __is_trivially_assignable(__decltype(*__first), const _Tp&)
            //   #else
            //       __is_trivially_copyable(_Tp)
            //   #endif
            //       ;
            // ```
            //
            // A `#` where an initializer should begin cannot be anything else — an expression has no `#` — so the
            // directive is read as the node it is and the initializer rule is asked again about the token that
            // follows it. This is the same argument as the two other seams of the same kind, and
            // the same one the suffix loop above spells out for a *function's* head; what was missing is only that
            // the declaration's own `=` is a seam too.
            //
            // It stays **inside** the `Initializer` node: the directives are part of how the initializer is
            // written, exactly as they are part of how an enumerator's value is written, and a consumer asking for
            // the initializer's tokens should get all of them.
            while p.current_token() == CppTokenKind::Hash {
                if let Err(err) = stats::parse_preprocessor_directive(p) {
                    init.undo(p);
                    return Err(err);
                }
            }

            if let Err(err) = parse_initializer_clause(p) {
                init.undo(p);
                return Err(err);
            }

            // …and the same seam on the **other side** of the initializer, before the `;` — the spelling the
            // conditional above is closed with when the branches' values are followed by the declaration's own
            // semicolon:
            //
            // ```cpp
            //   const bool __load_outside_loop =
            //   #if __has_builtin(__is_trivially_constructible) \
            //         && __has_builtin(__is_trivially_assignable)
            //       __is_trivially_constructible(_Tp, const _Tp&)
            //       && __is_trivially_assignable(__decltype(*__first), const _Tp&)
            //   #else
            //       __is_trivially_copyable(_Tp)
            //   #endif
            //       ;                        ← the `#endif` stands between the value and this
            // ```
            //
            // Both sides need it for the reason the template argument list needs the seam on both sides of its
            // comma: the `#` is not a token the initializer rule can read, so whichever of the two loops misses it
            // reports against a directive instead of against the declaration.
            //
            // …and the third thing the same shape needs is the **other branch's value**, because the conditional
            // above is a *choice between two values* and each of them is written where the value goes:
            //
            // ```cpp
            //       const bool __load_outside_loop =                       // bits/stl_algobase.h:906
            //       #if __has_builtin(__is_trivially_constructible) \
            //             && __has_builtin(__is_trivially_assignable)
            //         __is_trivially_constructible(_Tp, const _Tp&)
            //         && __is_trivially_assignable(__decltype(*__first), const _Tp&)
            //       #else
            //         __is_trivially_copyable(_Tp)                        ← a second value, not a second declaration
            //       #endif
            //         ;                                                   ← and the `;` is outside both branches
            // ```
            //
            // `#else`/`#elif` is what says another value follows — after `#endif` the declaration simply continues
            // — so the loop reads a value for each branch it opens, and the `;` at the end is still the
            // declaration's own. **That is the part the enumerator seam could not do**: routing the value through
            // `parse_a_definition_per_branch` made the *branch* the owner of the `;`, and three attempts to say
            // otherwise broke five files each time. Here the branches own nothing but their values, which is what
            // the file wrote.
            loop {
                let mut read_another_branch = false;

                while p.current_token() == CppTokenKind::Hash {
                    let opens_another_branch = matches!(p.peek_token_text_at(1), "else" | "elif");
                    if let Err(err) = stats::parse_preprocessor_directive(p) {
                        init.undo(p);
                        return Err(err);
                    }
                    if opens_another_branch {
                        if let Err(err) = parse_initializer_clause(p) {
                            init.undo(p);
                            return Err(err);
                        }
                        read_another_branch = true;
                    }
                }

                if !read_another_branch {
                    break;
                }
            }

            init.complete(p);
        }
        // **A declarator takes one initializer**, and this arm is the shape where a second one is written.
        //
        // The suffix reader can already have read one — `T x(y)` is a direct-initialisation, and which of the two
        // readings `(y)` gets is the preference [`parse_function_suffix_or_initializer`] decides. When it reads it
        // as an initializer, the declarator is **not** a function, and the `{` that follows is a *second*
        // initializer: no declaration has two, and the tree that came out was well formed, lossless and silent —
        //
        // ```cpp
        // struct Base {
        //   _GLIBCXX20_CONSTEXPR void f(size_type) { }   // ← bits/stl_vector.h:192, in `struct _Grow`
        //   int after;
        // };
        // ```
        //
        // read as a variable `f` of type `_GLIBCXX20_CONSTEXPR void` initialised with `size_type` **and then**
        // with `{ }`, after which the declaration had no `;` to end on and `int after;` became its child. That one
        // member took `std::_Vector_base`'s whole class body with it — the facts stopped at the `_Vector_impl`
        // declaration, and `std::vector` had no members at all.
        //
        // Failing here is what lets the recovery do its job, and the recovery is unusually good at this one: the
        // member loop wraps *one* token (`_GLIBCXX20_CONSTEXPR`) in an error node, tries again at `void`, and the
        // parameter reading — which is the right one for `void f(size_type)` — wins with nothing in front of it.
        // The member is read correctly and the ones after it are members, which is the same "advance by one token"
        // property that makes the error-node recovery worth keeping (see the note on `at_a_macro_member`).
        CppTokenKind::LeftBrace
            if !declarator_is_function
                && p.events_contain_any(declarator_from, &[CppSyntaxKind::Initializer]) =>
        {
            m.undo(p);
            return Err(CppParseError::syntax_error_from(
                &t!("a declarator takes only one initializer"),
                p.current_token_range(),
            ));
        }
        CppTokenKind::LeftBrace if !declarator_is_function => {
            // Brace-or-equal initializer on a variable: `Point p{1, 2};`.
            let init = p.mark(CppSyntaxKind::Initializer);
            if let Err(err) = parse_braced_initializer(p) {
                init.undo(p);
                return Err(err);
            }
            init.complete(p);
        }
        // A constructor's member initializer list: `Foo() : a(1), b(2) {}`. Only a *function* declarator can be
        // followed by one, so a `:` after a variable belongs to whatever encloses it.
        //
        // This is what a range-based `for`'s separator is: `for (auto x : items)` has a `:` right after the
        // declared variable, and reading it as a member initializer list swallowed the whole range and then
        // reported "expected `;`" against the header's `)`.
        //
        // The flag alone decides it, because `parse_declarator` sets it on **every** path — false at the start,
        // true when a parameter list is parsed, including an empty one. Consulting the event stream as well looks
        // like belt and braces and is not: an empty parameter list leaves no node behind, so `Foo() : a(1)` would
        // be read as a variable declaration and its member initializer list rejected.
        CppTokenKind::Colon if p.last_declarator_is_function() => {
            parse_member_initializer_list(p)?;
            parse_further_member_initializer_lists(p)?;
        }
        // A **requires-clause** after the declarator (C++20): `void f(T t) requires C<T>;`.
        //
        // Read here because this is where a declarator ends — and it is restricted to a **function** declarator,
        // which is the flag the neighbouring arms already consult. The standard requires more than that
        // ([dcl.decl.general]/5: the clause belongs to a *templated* function), but a function is the part of it
        // that is visible in the tokens, and it is the part that matters: nothing but a body, a `;` or a
        // constructor's `:` can follow a declarator whose clause has been read.
        //
        // **The clause is not the last suffix**, which is the part this arm got wrong for a long time:
        //
        // ```cpp
        // basic_string()                                    // bits/basic_string.h:585
        // _GLIBCXX_NOEXCEPT_IF(is_nothrow_default_constructible<_Alloc>::value)
        // #if __cpp_concepts && __glibcxx_type_trait_variable_templates
        // requires is_default_constructible_v<_Alloc>
        // #endif
        // : _M_dataplus(_M_local_data())
        // { _M_init_local_buf(); _M_set_length(0); }
        // ```
        //
        // A clause is one of the things written *after* a declarator, and the member initializer list is another
        // one that may follow it, with a directive in between — which is what this file does. Returning from the
        // match at the clause left the `:` to the class body, where the only reading available is "not a member":
        // it became an `ErrorNode`, `_M_dataplus(_M_local_data())` became a **declaration** of its own, and every
        // member written after it — the whole public interface of `std::basic_string` — was read as a child of one
        // bogus declaration instead of as a member of the class. Lossless, well formed, and silent: the class
        // body's recovery wraps an unexpected token and moves on, so no error was reported at any of it.
        //
        // The two steps below belong to *this* suffix rather than to the arms above: a `:` with no clause in front
        // of it is already the arm above's, and a directive *before* a clause is the loop before the match's. When
        // a third suffix turns out to be able to follow a clause, this becomes a loop over suffixes rather than a
        // match — see the maintenance conventions on the third occurrence of a rule.
        //
        // **`struct S requires C<T> { };` is not read, and that is deliberate.** The grammar gives a class head
        // no clause at all, and reading one used to detach the class body: the `{ }` that follows the constraint
        // was left for the statement rule, so the tree came out as a *struct declaration* followed by a
        // `CompoundStat` at file scope — well formed, lossless, no diagnostic, and with the class's members
        // belonging to nothing. Reporting `expected ;` against the `requires` is both what the standard says and
        // the only reading that keeps the body where it belongs.
        //
        // `requires` is contextual, so the arm is a *spelling* test with the shape test beside it: the clause is
        // only taken when what follows can begin a constraint. `requires` used as an identifier (`int requires =
        // 1;`) is a declarator **name**, and it reaches this match as the token that ends the declarator rather
        // than beginning a clause — `starts_a_requires_clause` tries the clause and reports that it consumed
        // nothing, which is the same test the class-head refusal above relies on.
        CppTokenKind::Identifier
            if at_requires(p)
                && (declarator_is_function
                    || p.last_consumed_token_kind() == Some(CppTokenKind::RightParen))
                && starts_a_requires_clause(p) =>
        {
            // Asked **before** the clause is parsed, because the constraint is an expression: an expression may
            // contain a declarator of its own (`decltype(…)`, a lambda's parameter list) and parsing one resets
            // the flag this needs to read afterwards.
            let constrains_a_function = true;
            parse_requires_clause(p)?;

            // A directive between the clause and what follows it, for the reason the loop before the match gives.
            while p.current_token() == CppTokenKind::Hash {
                if let Err(err) = stats::parse_preprocessor_directive(p) {
                    m.undo(p);
                    return Err(err);
                }
            }

            // …and the member initializer list a constrained **constructor** may still write after its clause:
            // `S(U u) requires C<U> : a(u) { }`. Without this the `:` is nobody's token; with it, the caller sees
            // the body's `{` where the grammar says it should be.
            if constrains_a_function && p.current_token() == CppTokenKind::Colon {
                parse_member_initializer_list(p)?;
                // …and the other branches' lists, for the same reason this arm exists at all: a conditional can
                // put one per branch, with a directive in between.
                parse_further_member_initializer_lists(p)?;
            }

            // …and a defaulted or deleted definition: `V(const V&) requires C<T> = default;`. The `=` is the
            // declarator's initializer and not part of the constraint, which stops at `||`.
            if p.current_token() == CppTokenKind::Assign
                && matches!(
                    p.peek_next_token(),
                    CppTokenKind::DefaultKeyword | CppTokenKind::DeleteKeyword
                )
            {
                p.bump(); // `=`
                let init = p.mark(CppSyntaxKind::Initializer);
                p.bump();
                init.complete(p);
                return Ok(m.complete(p));
            }
        }
        // A bit-field: `int bits : 3;`, `unsigned flags : 1, spare : 7;`.
        //
        // The same `:` in the same position as a member-initializer list, and the enclosing construct is what
        // tells them apart: a constructor's `:` follows a *function* declarator, which the arm above has already
        // claimed, while a bit-field's follows a member that names no function and sits inside a class body.
        //
        // Read as a member-initializer list, as it was, `int bits : 3` came out as a declarator with no name at
        // all: the width was consumed as an initializer, the member was nameless, and a consumer asking the
        // class for its fields found nothing where the field was.
        CppTokenKind::Colon if p.is_at_class_member_level() => {
            let width = p.mark(CppSyntaxKind::Initializer);
            p.bump(); // `:`

            // The width is a constant-expression, and it is optional in the grammar's own terms only because a
            // nameless bit-field is written `int : 0` — the `:` is never followed by a `;`.
            //
            // Read **below the comma operator**, because a bit-field list is comma-separated:
            // `unsigned flags : 1, spare : 7;` is two fields, and a width reader that took the comma would
            // swallow the second one. This is one of the rules the maintenance convention is about — a rule that
            // spells a comma itself has to opt out of the operator that spells commas.
            if let Err(err) = exprs::parse_assignment_expr(p) {
                width.undo(p);
                return Err(err);
            }
            width.complete(p);
        }
        // An **old-style (K&R) parameter list**: the parameters are declared after the parenthesis rather than
        // inside it.
        //
        // ```c
        // int main(argc, argv)
        //     int argc;
        //     char *argv[];
        // { … }
        // ```
        //
        // The parenthesis has already been read, and read as a *parameter list* — `argc` is a perfectly good
        // parameter type, and nothing in those tokens says it is a name instead. What identifies the old style is
        // what follows: a declaration, where a modern function has its body or its `;`. The declarations are read
        // by the ordinary declaration rule and kept in a list node of their own, so a consumer gets the
        // parameters' types without re-reading tokens.
        //
        // Obsolete in C++ and deprecated in C, but ordinary in C from before 1989 — and this parser is asked to
        // read C. Nothing else can follow a function declarator with a declaration, so the reading costs no
        // modern spelling: `void f() int x;` is not a program in any language, and the tokens say what was meant.
        _ if declarator_is_function && starts_an_old_style_parameter_list(p) => {
            let list = p.mark(CppSyntaxKind::OldStyleParameterList);

            loop {
                let before = p.current_token_index();
                let checkpoint = p.checkpoint();
                match parse_declaration(p) {
                    // A declaration that consumed nothing would spin this loop; one that failed is not an
                    // old-style parameter declaration, which ends the list rather than the declaration.
                    Ok(_) if p.current_token_index() > before => {}
                    _ => {
                        p.rollback(checkpoint);
                        break;
                    }
                }

                if !starts_an_old_style_parameter_list(p) {
                    break;
                }
            }

            list.complete(p);
        }
        _ => {}
    }

    // **The declaration is completed, and the completed marker is handed back** so that a caller with a body to read
    // can wrap it — see this function's note.
    Ok(m.complete(p))
}

/// Does an old-style (K&R) parameter declaration list start at the cursor?
///
/// The question is "can a declaration start here?", and a declaration starts with a **type**: a type keyword
/// (`int argc;`, `char *argv[];`), a class keyword (`struct S x;`), the other specifiers that only a declaration
/// begins — or a **name this file knows to be a type**, because `size_t argc;` is as ordinary in old C as
/// `int argc;` is.
///
/// [`starts_declaration`] is consulted for the specifiers and cannot answer on its own: it holds the anchors a
/// *statement* needs to tell a declaration from an expression, and a plain type keyword is deliberately not one of
/// them — `int x;` is reached by trying the declaration reading, not by an anchor. A `[` or a `*` reaching here is
/// how the two lists differ, which is exactly what the question needs.
///
/// Asked before the declarations are read rather than after they fail, so that a token which cannot begin a
/// declaration — the body's `{`, the `;` of a declaration, a `throw()` specification — is left to the arms that
/// do own it.
fn starts_an_old_style_parameter_list(p: &mut CppParser) -> bool {
    if matches!(
        p.current_token(),
        CppTokenKind::LeftBrace
            | CppTokenKind::Semicolon
            | CppTokenKind::Eof
            | CppTokenKind::None
            | CppTokenKind::Hash
    ) {
        return false;
    }

    types::is_type_specifier_keyword(p.current_token())
        || starts_declaration(p)
        || (p.current_token() == CppTokenKind::Identifier
            && p.is_a_known_type_name(p.current_token_text()))
}

/// Is this token a pointer or reference **declarator** operator — the things a `ptr-declarator` may begin with?
///
/// `&&` is in the list because a reference-to-reference is what a deduced `T&&` declarator is written as, and the
/// lexer makes one token of it; nothing here decides what the type means, only that a declarator may start there.
fn at_a_pointer_operator(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::Star | CppTokenKind::Ampersand | CppTokenKind::LogicalAnd
    )
}

/// Does `ptr-operator* ( declarator ) (` stand at the cursor — a **function** whose name is parenthesized and whose
/// type ends in a pointer or reference operator?
///
/// The shape is the whole test, and each half of it is what keeps a neighbour out:
///
/// ```text
/// const _Ty&(max) (const _Ty& _Left, …)   this rule — MSVC's <utility> spells max/min this way
/// int (&f)(void);                         the `(`-at-the-cursor rule, which already read it
/// a * (b);                                an expression: a product has no `(` after its `)`
/// int *p(void);                           a name, not a `(`: the ordinary declarator path
/// ```
///
/// The operators may already be behind the cursor — the specifier sequence absorbs `*`/`&` after a *name*
/// (`const _Ty&`) and leaves them when the type is a keyword (`int &`), which is a difference of the spelling
/// rather than of the declaration — so both are accepted, and the caller's loop consumes whichever are left.
fn at_an_operator_led_parenthesized_declarator(p: &CppParser) -> bool {
    let mut index = p.current_token_index();

    // Is there an operator in front of the group — at the cursor, or already taken into the type?
    let mut an_operator_leads = at_a_pointer_operator(p.token_kind_at(index));
    if !an_operator_leads {
        // The type took them: the operator is the token before the `(`, and without one this shape has to earn
        // its place some other way — see the bare-name requirement at the end.
        let before = previous_significant_index(p, index);
        an_operator_leads = before.is_some_and(|at| at_a_pointer_operator(p.token_kind_at(at)));
    }

    while at_a_pointer_operator(p.token_kind_at(index)) {
        index = next_significant_index(p, index);
    }

    if p.token_kind_at(index) != CppTokenKind::LeftParen {
        return false;
    }
    index = next_significant_index(p, index);

    // The declarator inside the parentheses: a name, behind whatever decorates it.
    let mut decorated = false;
    while at_a_pointer_operator(p.token_kind_at(index))
        || matches!(
            p.token_kind_at(index),
            CppTokenKind::ConstKeyword | CppTokenKind::VolatileKeyword
        )
    {
        decorated = true;
        index = next_significant_index(p, index);
    }
    if p.token_kind_at(index) != CppTokenKind::Identifier {
        return false;
    }
    index = next_significant_index(p, index);

    if p.token_kind_at(index) != CppTokenKind::RightParen {
        return false;
    }
    index = next_significant_index(p, index);

    // …and the parameter list, which is what makes it a function rather than a product.
    if p.token_kind_at(index) != CppTokenKind::LeftParen {
        return false;
    }

    // **With no operator anywhere, the group must hold a bare name.** `T (max)(T a)` is the same declaration as
    // `T max(T a)` — the standard's declarator may be parenthesized — and the declaration before it is what a
    // **template** writes (`template <class _Ty> constexpr _Ty (max)(…)`, the same rule's other half): there the
    // specifier sequence has read a real type name, so the second half of the branch below is closed, and only
    // this shape can open the first.
    //
    // The bare-name requirement is what keeps the readings around it: `Widget w(1, 2)` and `T (a, b)` are
    // direct-initialisations (their group holds a comma, and nothing follows the `)` but a `;`), and a K&R
    // parameter list (`int main(argc, argv)`) holds two names and a comma. A product (`a * (b)`) has no `(`
    // after its `)` at all.
    an_operator_leads || !decorated
}

/// The index of the last significant token before `index`.
pub(super) fn previous_significant_index(p: &CppParser, index: usize) -> Option<usize> {
    let mut at = index;
    while at > 0 {
        at -= 1;
        if !is_declaration_trivia(p.token_kind_at(at)) {
            return Some(at);
        }
    }

    None
}

/// Continue a declarator after a parenthesized name has been consumed.
///
/// `declarator_from` is the event index where that declarator began, forwarded to
/// [`parse_function_suffix_or_initializer`] so the rule that decides between a parameter list and a
/// direct-initialiser can ask whether the declarator named anything.
fn finish_declarator_suffixes(p: &mut CppParser, declarator_from: usize) -> ParseResult {
    loop {
        match p.current_token() {
            CppTokenKind::LeftParen => {
                // The same decision the main declarator loop makes, through the same function: a `(` after a
                // declared name is a parameter list or the parentheses of a direct-initialised variable. Having
                // two copies of that rule is how they come to disagree.
                parse_function_suffix_or_initializer(p, declarator_from)?;
                if p.current_token() == CppTokenKind::LeftParen {
                    return Ok(CompleteMarker::empty());
                }
            }
            CppTokenKind::LeftBracket => {
                let array = p.mark(CppSyntaxKind::ArrayType);
                p.bump();
                if p.current_token() != CppTokenKind::RightBracket
                    && !p.is_eof()
                    && let Err(err) = parse_expr(p)
                {
                    array.undo(p);
                    return Err(err);
                }
                if let Err(err) = expect_token(p, CppTokenKind::RightBracket) {
                    array.undo(p);
                    return Err(err);
                }
                array.complete(p);
            }
            _ => return Ok(CompleteMarker::empty()),
        }
    }
}

/// Parse the expression or braced list on the right of `=`.
fn parse_initializer_clause(p: &mut CppParser) -> ParseResult {
    if p.current_token() == CppTokenKind::LeftBrace {
        return parse_braced_initializer(p);
    }

    // An **element** of whatever list holds this clause, so it is read below the comma operator — the commas
    // between elements are the list's. `int v[] = {1, 2}` is two elements for exactly this reason.
    exprs::parse_assignment_expr(p)
}

/// A `(` after a declared name: a parameter list, or the parentheses of a direct-initialised variable.
///
/// The two are told apart by what the parentheses can hold:
///
/// ```text
/// int a(b);        a parameter list, because `b` parses as a type — hence a function
/// int a(1);        not a parameter list: `1` is not a type, so this is a variable initialised with `1`
/// Widget w(1, 2);  likewise — a variable initialised with two arguments
/// ```
///
/// The parameter reading is tried before the initializer reading in most cases, because it is the one that can
/// fail on its own: a parameter must have a type, and a literal does not. A failed attempt is rewound, which is
/// the same bounded backtracking [`crate::grammar::cpp::types::parse_declarator`] already relies on for the same
/// ambiguity. Trying the initializer reading first would take `int a(b)` away from the function reading, which is
/// the reading C++ gives it.
///
/// **An untyped list of names is the exception**, and it is tried the other way round: `a` is a valid parameter
/// type as well as a valid argument, so the parameter reading succeeds on `Max(a, b);` and would never be
/// revisited. At file scope that shape is a declaration, so the initializer gets first refusal there.
///
/// Returns whether it consumed anything, so a caller that reaches this on an expression can leave the
/// parentheses alone.
///
/// `declarator_from` is the event index where the declarator being suffixed began, so the question "did that
/// declarator name anything?" can be asked of the events it produced. See
/// [`CppParser::events_contain_any_between`] for why the answer has to come from the event stream rather than
/// from a parameter.
pub fn parse_function_suffix_or_initializer(
    p: &mut CppParser,
    declarator_from: usize,
) -> ParseResult {
    let checkpoint = p.checkpoint();

    // A **macro invocation used where a definition goes**: `TEST(FormatPerformance, 1k_row) { … }`.
    //
    // This is how gtest, Catch2 and every benchmark library write a test, and the shape has no grammar behind it:
    // a name is *called* with tokens that are neither types nor expressions (`1k_row` is a token the macro pastes
    // into an identifier), and a block follows. The declaration reading gets as far as the group and then takes
    // the block for a braced initializer, so the definition has no `;` to end with and the whole statement is
    // reported as an expression — 6 of the 200 files in the first real C++ project, two of them with ~100
    // cascading errors from this one line each.
    //
    // Read here, and only in the shape that has no other reading:
    //
    // * **no declarator name** — `void f(A, B) { }` is an ordinary definition whose declarator is named `f`, and
    //   it never reaches this branch;
    // * **not inside a function body** — there, `g(x) { }` is a statement followed by a block, and a real error is
    //   the better answer;
    // * the group is **balanced** and a `{` follows it, which is the whole test. Nothing else can stand between a
    //   name and a block at declaration level, so the reading costs no valid program.
    //
    // The group is kept as an `ArgumentList` because that is what it is — a macro's arguments, not a parameter
    // list, and not an initializer either. The flag that says "a function declarator" is set so that the block is
    // read as the **body** by `parse_declaration` rather than as one more initializer.
    if a_macro_definition_follows(p, declarator_from) {
        parse_balanced_token_group(p, CppSyntaxKind::ArgumentList)?;
        p.set_last_declarator_is_function(true);
        return Ok(CompleteMarker::empty());
    }

    // A declarator that named **nothing**, in a declaration whose head is a **qualified** name, is the head of a
    // definition — `static void Widget::draw(T)`, `void A::f<int>(int)` — so its parentheses are a parameter list
    // and nothing else.
    //
    // The initializer reading is for `Widget w(T)`, where the declarator *holds* the name `w`; here it holds
    // nothing, and the preference below is what got it wrong: `(T)` is a list of bare names, which is exactly the
    // shape the initializer reading claims, so the definition came out with no parameter list at all — and then
    // the `{` of its body had no declaration to belong to. A qualified name in type position is a definition
    // head, and the suffix reader is the only one that can say so.
    //
    // The parameter reading can still fail — `ns::C::method(1, 2);` is a *call* on a qualified name, and `1` is
    // not a type — and the rewind below hands those tokens back to the readings that follow.
    if !a_name_was_parsed(p, declarator_from) && the_head_of_the_declaration_is_qualified(p) {
        let before_the_parameters = p.checkpoint();
        if parse_parameter_list(p).is_ok() {
            p.set_last_declarator_is_function(true);
            types::eat_function_qualifiers(p);
            return Ok(CompleteMarker::empty());
        }
        p.rollback(before_the_parameters);
    }

    // An untyped list of names has to be claimed *before* the parameter reading is tried, and only here. A
    // parameter must have a type, but a bare name is also a perfectly good type, so `Max(a, b);` parses as a
    // parameter list — two parameters of type `a` and type `b` — and a reading that succeeds is never revisited.
    // At file scope that is the wrong answer for a shape that only a declaration can have, so the initializer
    // reading goes first and the parameter reading is what gets rewound instead. Inside a body the call is the
    // ordinary reading and the order is left alone; see [`a_declaration_is_the_better_reading`].
    //
    // This preference is for a declaration with **no type**, which is what `Max(a, b);` is. A type keyword in
    // front of the declarator's name settles the question the preference was guessing at, and the parameter
    // reading is the right one — `void f(T);` is a function with one unnamed parameter, not a variable `f`
    // initialised with the value `T`. Reading it as a variable was a *silent* wrong tree: well formed, lossless,
    // and no diagnostic. See [`a_type_keyword_precedes_the_declarator_name`].
    //
    // The second form is the same argument one level down: once the leading name *is* a type this file declared,
    // the parentheses follow a declarator name, and `Inner(1)` in them is a value being constructed rather than
    // a parameter. That reading is what a parameter list gets wrong — it takes `Inner` for a parameter's type
    // and then reads `(1)` as that parameter's default argument, which is a declaration of a function nobody
    // wrote.
    let declarator_is_named = p.has_declaration_type_name();
    // **A braced body settles the question**, and it is asked with the *real* suffix readers rather than with a
    // scan that would have to know their vocabulary (the rule that a second copy of a judgement is where its
    // exceptions get missed): parse the group as a parameter list, let the suffix reader have its turn — a macro
    // suffix, a `noexcept`, a trailing return type — and keep that reading only if a `{` is what it reaches.
    //
    // ```cpp
    // _GLIBCXX20_CONSTEXPR
    // inline _Iter_less_val
    // __iter_comp_val(_Iter_less_iter)          // bits/predefined_ops.h:79
    // { return _Iter_less_val(); }
    //
    // template<typename _Ex>
    //   __attribute__ ((__always_inline__))
    //   inline exception_ptr
    //   make_exception_ptr(_Ex) _GLIBCXX_USE_NOEXCEPT    // bits/exception_ptr.h:283
    //   { return exception_ptr(); }
    // ```
    //
    // Neither can be a variable with **two** initializers — `(U)` and then `{ … }` — which is what the
    // preference below made of them: a bare name looks like a declarator as much as it looks like a type
    // ([`the_arguments_look_like_declarators`]), so the definition came out as `a declarator takes only one
    // initializer` (five files of the closure: `exception_ptr.h`, `predefined_ops.h`, `cmath`,
    // `helper_functions.h`, `type_traits.h`).
    //
    // Only where a function definition is legal to begin with. That is *not* "outside a brace": a class body is
    // inside one too (`is_inside_a_body` counts every scope a brace introduces), and a member function defined in
    // its class is the most ordinary definition there is — `struct S { T f(U) { … } };` was the case that showed
    // the difference. What is excluded is a **block**: there `T x(y) { }` is a declaration followed by a block, and
    // defining a function is not something this language does.
    let a_definition_is_legal_here = !p.is_inside_a_body() || p.is_at_class_member_level();

    if a_definition_is_legal_here {
        let before_the_function_reading = p.checkpoint();

        if parse_parameter_list(p).is_ok() {
            // **A trailing return type is the same evidence one token along**: `-> T` belongs to a function
            // declarator and to nothing else — a variable's initializer cannot be followed by one — so a
            // deduction guide reads, and so does any declaration whose head is written that way:
            //
            // ```cpp
            //   template<typename _InputIterator, typename _Allocator, …>
            //     multimap(_InputIterator, _InputIterator, _Allocator)      // bits/stl_multimap.h:1153
            //     -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, …>;
            // ```
            //
            // Asked *before* the qualifier reader consumes it: that reader owns `-> T` (it wraps it in a
            // `TrailingReturnType`), so afterwards there is nothing left to notice. `M(I) -> M<I>;` was read as a
            // variable named by nothing, initialised with `(I)`, and the error landed on the `M<I>`.
            let a_trailing_return_type_follows = p.current_token() == CppTokenKind::Arrow;

            // **…and so do the qualifiers themselves**, which is the same evidence one step further: a
            // `cv`-qualifier, a ref-qualifier or a `noexcept` after a parenthesis group belongs to a *function
            // declarator* and to nothing else, so a reader that consumed one has just been told what this is.
            //
            // Asked as "did the reader move?" rather than as a list of the tokens it may take, because that list
            // is exactly [`types::eat_function_qualifiers`] and a second copy of it here is where the next
            // spelling would be forgotten. The shape that needs it is a **pointer-to-member-function parameter**:
            //
            // ```cpp
            //   mem_fun(_Ret (_Tp::*__f)(_Arg) const)        // bits/stl_function.h:1398 — the first error
            // ```
            //
            // There the group `(_Arg)` is followed by `const` and then by the `)` that closes the *parameter*, so
            // neither `{` nor `->` is what comes next: the first reading was rolled back, the second read `(_Arg)`
            // as a direct-initialiser (a name is as good a declarator as a type, which is the whole of
            // [`the_arguments_look_like_declarators`]), and the `const` was left where a `;` should be. Measured
            // before the fix: `void g(int (C::*p)(int) const);` was clean — an `int` argument cannot be an
            // initialiser, so that shape reached the parameter-list path — while `void g(R (C::*p)(A) const);` was
            // rubble, one name away.
            let qualifiers_after_the_parameter_list = p.current_token_index();
            types::eat_function_qualifiers(p);
            let qualifiers_follow_the_parameter_list =
                p.current_token_index() > qualifiers_after_the_parameter_list;

            if a_trailing_return_type_follows
                || qualifiers_follow_the_parameter_list
                || p.current_token() == CppTokenKind::LeftBrace
            {
                // Kept — so the flag is set *after* the decision, not inside the speculative part: the flag is
                // not part of a checkpoint, and a rollback would leave it saying "function" about a declarator
                // this rule decided was a variable.
                p.set_last_declarator_is_function(true);
                return Ok(CompleteMarker::empty());
            }
        }

        p.rollback(before_the_function_reading);
    }

    if !a_dynamic_exception_specification_follows(p)
        && (p.is_at_file_scope()
            && !a_type_keyword_precedes_the_declarator_name(p)
            && the_arguments_look_like_declarators(p, false)
            || declarator_is_named && the_arguments_look_like_declarators(p, true))
        && let Ok(parsed) = parse_the_initializer(p)
    {
        return Ok(parsed);
    }

    if parse_parameter_list(p).is_ok() {
        // A parameter list is what makes a declarator a function declarator. Recorded here because an *empty*
        // one leaves no node for a later event-stream check to find.
        p.set_last_declarator_is_function(true);
        types::eat_function_qualifiers(p);
        return Ok(CompleteMarker::empty());
    }

    p.rollback(checkpoint);

    // Direct-initialisation, when the evidence says this is a declaration rather than a call. The two are the
    // same tokens:
    //
    // ```text
    // int a(1);        a declaration: `int` is a keyword type
    // Widget w(1, 2);  a declaration, because `Widget` is a type this file declares
    // g(1, 2);         a call, because `g` is not
    // ```
    //
    // The question is settled by asking what the tokens cannot answer — whether the type name is one — using the
    // file's own declarations, plus the scope the statement sits in. See [`a_declaration_is_the_better_reading`].
    if !a_dynamic_exception_specification_follows(p)
        && a_declaration_is_the_better_reading(p, declarator_from)
        && an_argument_list_follows(p)
    {
        return parse_the_initializer(p);
    }

    // **The last reading a parenthesis group can have: an initializer.** Both readings above can refuse it and both
    // are right to: the group's arguments are not values (a bare name is also a type), and the declaration
    // preference has nothing to say when the type came from a *specifier* — `const int n(a, std::g<int>(1).p);` is a
    // declaration whose initializer is a comma expression, and it reached the caller with the `(` unconsumed, which
    // was reported as `expected a parameter list or an initializer` and cost `<format>` a whole declaration.
    //
    // Taking it here costs nothing that was not already refused: this runs only where the alternative is an error.
    if p.current_token() == CppTokenKind::LeftParen
        && let Ok(parsed) = parse_the_initializer(p)
    {
        return Ok(parsed);
    }

    Ok(CompleteMarker::empty())
}

/// Is the balanced group at the cursor followed by a **dynamic exception specification** — `throw (`?
///
/// The one suffix that does not merely continue a reading but *settles* it: a variable declaration has no
/// `throw(…)`, so when the group at the cursor is followed by one, the group is a **parameter list** and the
/// direct-initialiser reading of the same tokens — the other reading of `T x(y)` — is not available.
///
/// Found because the two preferences below took the initialiser reading first and left the suffix with nothing to
/// belong to: `new_handler set_new_handler(new_handler) throw();` in `<new>` came out as an *expression statement*
/// of flat tokens with `expected `;` after expression`, and the whole declaration was lost. The group
/// `(new_handler)` is a bare name, which is a perfectly good one-parameter list *and* a perfectly good
/// parenthesised value, and the first of the two preferences is written for exactly that shape — so the
/// disagreement was between two readings that both succeed, and the suffix is what breaks the tie.
///
/// The suffix is not read here and nothing is consumed: the caller only asks whether the initialiser reading is
/// still the one to take, and the parameter reading that wins instead consumes `throw(…)` through
/// [`types::eat_function_qualifiers`].
fn a_dynamic_exception_specification_follows(p: &CppParser) -> bool {
    let Some(after) = index_after_the_group(p, p.current_token_index()) else {
        return false;
    };

    let throw_at = significant_index_at(p, after);
    p.token_kind_at(throw_at) == CppTokenKind::ThrowKeyword
        && p.token_kind_at(significant_index_at(p, throw_at + 1)) == CppTokenKind::LeftParen
}

/// Is the cursor on the argument list of a **macro invocation used where a definition goes**?
///
/// The shape is `TEST(FormatPerformance, 1k_row) { … }`, and it is the one shape in a declaration where the
/// declaration/expression question has no answer at all: the tokens inside the parentheses are the macro's, so
/// they are neither values nor declarators, and both readings refuse them. The test is therefore about the shape
/// and nothing else — see [`parse_function_suffix_or_initializer`] for the reading:
///
/// * **no declarator name**, so `void f(A, B) { }` — an ordinary definition — never matches;
/// * **not a qualified head**: `void Widget::draw(T) { }` has no declarator name either (the specifier sequence
///   took the whole qualified name), and its parentheses *are* a parameter list. A `::` in the head is what
///   tells the two apart, and the definitions of out-of-line members are far too common to lose;
/// * a **balanced** group with a `{` right after it;
/// * and, **inside a function body**, a name written the way a macro is written — see
///   [`looks_like_a_macro_name`] for why that half is a convention and which mistake it keeps.
///
/// Exposed because the declarator's suffix loop has to ask it *before* it opens at all: its other reasons to open
/// are all answers to the declaration/expression question, and this shape has none of them — which is why
/// `TEST(A, B) { }` (whose arguments look like declarators) worked while `TEST(A, 1) { }` (whose arguments look
/// like values) did not.
pub(super) fn a_macro_definition_follows(p: &CppParser, declarator_from: usize) -> bool {
    !a_name_was_parsed(p, declarator_from)
        && !the_head_of_the_declaration_is_qualified(p)
        && a_block_follows_the_group(p)
        // At *declaration* level the shape has no other reading at all, so any name will do. Inside a **body**
        // it competes with a real mistake — a call whose `;` is missing, followed by a block — so the name has to
        // be written the way a macro is written. See [`looks_like_a_macro_name`], which is the last resort and now
        // the only test: the grammar no longer consults a macro table, because the text it reads has already been
        // preprocessed and a macro invocation cannot be in it.
        && (!p.is_inside_a_body()
            || p.declaration_type_name().is_some_and(looks_like_a_macro_name))
}

/// Is this name written the way a **macro** is written: `TEST`, `IF_EXIST`, `CHECK_EQ`?
///
/// This is a *convention* rather than a grammar rule, and it is used in exactly one place: the "macro invocation
/// used where a definition goes" shape of [`a_macro_definition_follows`], and only where a name could otherwise
/// be a real mistake. Two cases, and they need different answers:
///
/// ```text
/// IF_EXIST(indent_style) { … }   a macro — the block is its body, and there is no other valid reading
/// g(x) { }                       a call with its `;` missing, followed by a block — a syntax error
/// ```
///
/// Both are "a name, a parenthesised group, a block", and no grammar rule separates them: the second is *not*
/// valid C++ at all, so reading it as a macro would silently accept a mistake a reader has to fix. What separates
/// them is how the name is spelled, and it is the same signal a reader uses. `EmmyLuaCodeStyle`'s
/// `IF_EXIST(...) { … }` is the case that made the inside-of-a-body half necessary — 68 diagnostics from the
/// macro invocations in one file.
pub(super) fn looks_like_a_macro_name(name: &str) -> bool {
    let mut characters = name.chars();
    let Some(first) = characters.next() else {
        return false;
    };
    if !(first.is_ascii_uppercase() || first == '_') {
        return false;
    }
    name.chars().all(|character| {
        character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_'
    })
}

/// Is the `(` at the cursor a **balanced** group with a `{` immediately after it?
///
/// The shape test for a macro invocation used as a definition — see
/// [`parse_function_suffix_or_initializer`]. Balanced rather than "parses as something", because the tokens
/// inside are the macro's, and they need not parse as anything at all.
fn a_block_follows_the_group(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::LeftParen {
        return false;
    }

    let mut depth = 0isize;
    let mut offset = 0usize;
    while let Some(kind) = p.peek_token_kind_at(offset..offset + 1).first().copied() {
        match kind {
            CppTokenKind::LeftParen => depth += 1,
            CppTokenKind::RightParen => {
                depth -= 1;
                if depth == 0 {
                    return p
                        .peek_token_kind_at(offset + 1..offset + 2)
                        .first()
                        .copied()
                        == Some(CppTokenKind::LeftBrace);
                }
            }
            // A `;` before the group closes means this is not the shape at all: it is a declaration that ends.
            CppTokenKind::Semicolon if depth == 0 => return false,
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
        offset += 1;
    }

    false
}

/// Consume a balanced parenthesised group as **raw tokens**, under a node of `kind`.
///
/// For the one shape that has no grammar behind it: the arguments of a macro invocation, whose tokens are the
/// macro's own. They are kept in the tree as they were written — lossless, and available to a consumer that wants
/// to show them — while nothing pretends to know what they mean.
pub(super) fn parse_balanced_token_group(p: &mut CppParser, kind: CppSyntaxKind) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(kind);

    let mut depth = 0isize;
    loop {
        match p.current_token() {
            CppTokenKind::LeftParen => {
                depth += 1;
                p.bump();
            }
            CppTokenKind::RightParen => {
                depth -= 1;
                p.bump();
                if depth == 0 {
                    return Ok(m.complete(p));
                }
            }
            CppTokenKind::Eof | CppTokenKind::None => {
                p.close_marks_above(base);
                return Err(CppParseError::syntax_error_from(
                    &t!("unterminated argument list"),
                    p.current_token_range(),
                ));
            }
            _ => p.bump(),
        }
    }
}

/// Read the argument list at the cursor as a direct-initialiser.
fn parse_the_initializer(p: &mut CppParser) -> ParseResult {
    let init = p.mark(CppSyntaxKind::Initializer);
    if let Err(err) = parse_expression_list(p, CppTokenKind::RightParen) {
        init.undo(p);
        return Err(err);
    }
    init.complete(p);
    Ok(CompleteMarker::empty())
}

/// Should `T x(...)` be read as a declaration rather than as a call?
///
/// Two kinds of evidence, both from the file being parsed, and both about what real code looks like rather than
/// about what the grammar permits.
///
/// # The type name
///
/// A declaration begins with a type, and a call begins with a callee. If the leading name is one this file
/// declared — `class Widget`, `typedef ... Integer`, `using Alias = ...` — the declaration reading is the one a
/// compiler would take. [`crate::parser::TypeNames`] is the table; it records only what a declaration spells out,
/// so a miss costs the declaration reading rather than producing a wrong one.
///
/// # The scope
///
/// **A function declaration inside a function body is vanishingly rare**, while a local variable with
/// constructor arguments is everywhere. So the operators, known type names, and member functions declared
/// *before* the current one are the real cases. The parser's brace depth is a good proxy for this: at depth
/// zero the file is declaring things, and inside a body it is writing code. Recording too much depth would
/// make a nested block look like a new file scope, so a single level is treated as "inside a body".
///
/// The direction of the guess matters and is the reason this is worth doing at all: reading a **call** as a
/// declaration loses its callee *and* its arguments, and puts a name in scope that was never declared — so a
/// bare name with no type to back it stays a call. Reading a **declaration** as a call merely leaves the
/// variable unbound, which is the cheaper mistake, and it is the one made when neither signal is present.
pub fn a_declaration_is_the_better_reading(p: &CppParser, declarator_from: usize) -> bool {
    // A keyword type can only begin a declaration: no expression starts with `int`.
    if declarator_starts_with_a_type_keyword(p) {
        return true;
    }

    // A name this file declared to be a type, wherever the declaration is written. Inside a body this is the
    // common case — `Widget w(1, 2);` — and it is also what makes `Widget make();` a declaration at file scope.
    if declarator_starts_with_a_known_type_name(p) {
        return p.is_inside_a_body() || p.is_at_file_scope();
    }

    // What the **caller's table** says about the leading name, when the caller supplied one.
    //
    // This is the consumer the external-table design exists for. `Widget w(1, 2);` and `g(1, 2);` are the same
    // tokens, and the file's own table answers only for names *this* file declares — a class from a header, a
    // helper defined in another translation unit, are exactly the names that made `Widget w(1, 2)` a guess. The
    // index behind this table knows them.
    //
    // A `Function` or `Variable` answer is the part the local table can *never* express: "this name is not a
    // type". That is a reading being refused rather than one being chosen, and it is why the trait answers in
    // kinds rather than in a `bool` — see `crate::symbols`.
    //
    // A `None` — the ordinary case — falls through to the shape preferences below, which is what keeps this a
    // preference and not a dependency.
    if let Some(name) = p.declaration_type_name()
        && let Some(kind) = p.symbol_kind(name)
    {
        return match kind {
            SymbolKind::Type | SymbolKind::Template => true,
            // Not a type, so not a declaration's type: the reading is refused and the expression statement —
            // the call — is what the tokens really are.
            SymbolKind::Function | SymbolKind::Variable | SymbolKind::Namespace => false,
            // A macro in type position is not itself a type — what stands there is what its body produced. The
            // grammar no longer asks "is this name a macro" (the text it reads is preprocessed), but the
            // vocabulary is shared with the environment the *scope walk* reads, so the answer still has to be
            // given a meaning here: not a type.
            SymbolKind::Macro { .. } => false,
        };
    }

    // Nothing in the file says the leading name is a type — it was declared in a header, or below the point
    // being edited — but the declarator **named** something and the list at the cursor is unambiguously an
    // argument list rather than a parameter list. Together those are the shape of direct-initialisation and of
    // nothing else:
    //
    // ```text
    // Widget w(1, 2, 3);   a variable: `w` is named, and `1` cannot be a parameter's type
    // Widget w("name");    likewise for a string
    // g(1, 2, 3);          a call: no name was parsed after the type, so there is nothing to initialise
    // A(B);                likewise — `B` was left outside the type as an argument, not taken as a name
    // ```
    //
    // The two `true`s are a conjunction and neither is disposable. The name is what separates `Widget w(1)` from
    // `g(1)`, and the values are what separate `Widget w(1)` from the *parameter* list of a function declaration
    // whose return type this file has not seen — the reading [`parse_parameter_list`] has already tried and
    // failed on by the time this is asked.
    if a_name_was_parsed(p, declarator_from) && the_arguments_look_like_values(p) {
        return true;
    }

    // Nothing in the file says the leading name is a type, but the arguments do not look like values either.
    // A list of bare identifiers is what a declaration's *initializer* most often looks like — `Max(a, b)` copies
    // two things that are already in scope — while a call passes values, and a value is written as a literal, a
    // call, a member access or an operator. See [`the_arguments_look_like_declarators`].
    //
    // The scope gate is what keeps this off expressions. At file scope a statement cannot be a call, so the
    // reading costs nothing; inside a body a call is the ordinary thing to find, and the guess is not worth
    // making there. Reading a declaration as a call leaves a variable unbound and is recoverable; reading a
    // call as a declaration loses its callee and invents a binding, so the weaker the evidence the less of the
    // file this is allowed to apply to.
    p.has_declaration_type_name()
        && p.is_at_file_scope()
        && the_arguments_look_like_declarators(p, false)
}

/// Did the declarator that began at `declarator_from` name anything?
///
/// The question [`a_declaration_is_the_better_reading`] has to ask and cannot answer from the type name alone:
/// in both `Widget w(1)` and `g(1)` a name was recorded in type position — `Widget` and `g` — so
/// [`CppParser::declaration_type_name`] is `Some` either way, and it is the *second* name that decides.
///
/// Read off the event stream rather than tracked as parser state, because the events are what the tree will be
/// built from: a name that was parsed and then rolled back is not in them, and a name that is in them is one the
/// declarator really has. The lower bound is what keeps the type's own `NameExpr` — recorded while the specifier
/// sequence ran, before this point — out of the answer.
fn a_name_was_parsed(p: &CppParser, declarator_from: usize) -> bool {
    p.events_contain_any_between(
        declarator_from,
        p.current_event_count(),
        &[CppSyntaxKind::NameExpr],
    )
}

/// Is the cursor on an initializer for a declarator that named nothing, in a declaration that has no type?
///
/// The shape that must not be a declaration, and it is worth naming so the guard at the call site reads as the
/// rule rather than as a conjunction of parser states:
///
/// ```text
/// int x = 1;          a name was parsed    -> a declaration, and the `=` initialises it
/// x = 1;              no name, no type     -> an *assignment*, and the expression reading owns it
/// int ns::count = 0;  no name, but a type  -> a declaration whose declarator was folded into the type
/// ```
///
/// The last line is why the condition is not simply "no name was parsed". A **qualified** declarator is read by
/// the specifier sequence rather than by the declarator rule — `ns::count` joins the type and nothing is left to
/// name — so the name test alone would refuse a declaration that is both valid and long-standing. What separates
/// the two is whether what is in front can be a type at all: `ns::count` is written as a type, while a bare
/// undocumented `x` is not.
///
/// That keeps the reading honest in both directions. `x = 1;` is an assignment, which is the shape this exists
/// for. `ns::count = 0;` keeps its declaration reading — the one C++ gives it when `count` is a static member,
/// and the reason `int ns::Widget::count = 0;` has always parsed.
///
/// A structured binding and a parenthesized declarator never reach this: both return before
/// [`finish_init_declarator`] is asked. What is left is the abstract declarator, which is legitimately nameless
/// in a type-id — and a declaration is not a type-id, so a nameless one with no type has nothing to initialise.
fn an_initializer_needs_a_name(p: &CppParser, declarator_from: usize) -> bool {
    matches!(p.current_token(), CppTokenKind::Assign)
        && !a_name_was_parsed(p, declarator_from)
        && !the_declaration_has_a_type(p, declarator_from)
}

/// Does the declaration being parsed already have a type — by any of the names a type can be written with?
///
/// The question the guard above turns on, and the reason it is not simply "was a name parsed". A name is what
/// [`CppParser::declaration_type_name`] records for `T x`, and the declarator rule takes it — so the *name* half
/// is covered by [`a_name_was_parsed`]. What is left is the shape where the type is a **keyword** and the
/// declarator was taken with it, which is `decltype(x) y = 1` and `auto x = 1`.
///
/// [`declarator_starts_with_a_type_keyword`] answers most of that, except that it leaves `auto` and `decltype`
/// out on purpose — both can begin an **expression**, and where the two readings are ambiguous the expression is
/// preferred. That reasoning does not apply here: by the time this is asked the declaration reading has already
/// been chosen and has reached its initializer, so the only question left is whether what came before it was a
/// type. So the walk is repeated with the two keywords put back.
///
/// # What this still does not cover
///
/// `decltype(x) y = 1;` is read as an expression and reported, and that is a **known gap** rather than a
/// regression — it is registered in `crates/cpp_parser/tests/gaps.rs`. The reason is worth recording, because it
/// is the opposite of what it looks like: with the guard removed the construct "parses", but only by way of the
/// defect the guard exists for — a declaration whose declarator named nothing. The walk finds `y` rather than
/// `decltype` because by the time the guard runs, `decltype(x)` has been consumed by an *earlier* attempt and the
/// remaining text is `y = 1`, whose first token is a plain name. Making the guard accept that would put A0-1
/// back. Fixing it properly means making `decltype(auto)` parse as a type specifier in an expression-statement
/// position, which is a rule of its own.
fn the_declaration_has_a_type(p: &CppParser, declarator_from: usize) -> bool {
    let _ = declarator_from;
    if declarator_starts_with_a_type_keyword(p) || declarator_starts_with_a_known_type_name(p) {
        return true;
    }
    if p.has_qualified_declaration_type_name() || the_head_of_the_declaration_is_qualified(p) {
        return true;
    }

    // The two type keywords the rule above excludes, asked at the **start of the declaration**. The walk is that
    // rule's own — back over the consumed tokens, stopping at a `;`, a `{` or a `}`, which no declaration
    // contains — and trivia is skipped so the answer is about the first *significant* token rather than the
    // whitespace before the `=`.
    //
    // **The declarator's own brackets are skipped**, and that is the whole point of the depth counter: they are
    // what stands between the `=` and the type, so asking about the token *immediately* before the initializer
    // answers a question about the declarator instead. `auto [a] = g();` is the case that was measured — the
    // token before the `=` is the `]` of the binding, `]` is not a type keyword, the answer came back "no type",
    // and with `auto` also absent from `declarator_starts_with_a_type_keyword` above, the guard fired on a
    // declaration that has a type written in plain sight. `unsigned [a] = g();` was clean throughout and is the
    // control that isolates this: same shape, and it survives only because `unsigned` *is* in the rule above, so
    // the walk is never reached. A placeholder is not, and that is deliberate — `auto` can begin an expression,
    // so the two readings are decided elsewhere — which leaves this walk as the only thing that can answer.
    let mut index = p.current_token_index();
    let mut inside = 0i64;

    while index > 0 {
        index -= 1;
        let kind = p.token_kind_at(index);

        if is_declaration_trivia(kind) {
            continue;
        }
        match kind {
            CppTokenKind::RightBracket | CppTokenKind::RightParen => inside += 1,
            // A `[` or `(` with nothing open closes the group the walk started inside, and the type is what
            // comes before it — so the *next* token back is the one to ask about.
            CppTokenKind::LeftBracket | CppTokenKind::LeftParen if inside > 0 => inside -= 1,
            CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace
                if inside == 0 =>
            {
                return false;
            }
            _ if inside > 0 => {}
            _ => return types::is_type_specifier_keyword(kind),
        }
    }

    false
}

/// Does the parenthesised list at the cursor hold values rather than declarations?
///
/// The question that separates a direct-initialiser from a parameter list **without** a type table, and the
/// companion to [`the_arguments_look_like_declarators`]: that one asks whether a list of names is a list of
/// things being copied, while this one asks whether the list contains anything that can only be a value.
///
/// The rule is about the **start of each element**, which is the one position where a declarator and an
/// expression cannot be confused: a parameter begins with a type, and no type is written as a literal, as a
/// name that is immediately called, or as an operator that no type contains.
///
/// * a **literal** — `1`, `"name"`, `'c'`, `true`, `nullptr`. A parameter is a type and a declarator, and
///   neither is written as a literal; `Widget w(1, 2, 3)` is decided by the first `1`.
/// * a **call** — `g()`, `g(a, b)`. A parameter's type is never called: `g()` as a *type* is not a thing, and
///   the shape [`parse_parameter_list`] would have to read it as — a parameter of type `g` with a default
///   argument — is what makes `Widget w(g(), h())` fail to parse at all.
/// * an **operator that cannot begin a type** — `+`, `-`, `!`, `~`, `%`, `|`, `==`, `<<`, `=`, and the rest of
///   the arithmetic, comparison and assignment families. A parameter's type is built from `*`, `&`, `&&`,
///   `::`, `<>`, `[]` and `()` and from nothing else, so no parameter's *type* begins with a `+`;
///   `Widget w(a + 1)` is decided by that.
///
/// The operators a type *does* contain are deliberately absent from that list, and `*` and `&` are why it has
/// to be a list rather than "any operator": `A(B * C)` is a multiplication and `A(B* C)` is a parameter named
/// `C` of type `B*`, with nothing but the symbol table to tell them apart. Leaving them out keeps such a
/// statement a call, which is the cheaper mistake — reading a value list as a parameter list leaves a variable
/// unbound and recoverable, while reading a parameter list as a value list swallows a function declaration and
/// everything after it.
fn the_arguments_look_like_values(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::LeftParen {
        return false;
    }

    let mut index = p.current_token_index() + 1;
    let mut depth = 0usize;
    // Are we at the position where an element begins? A list starts there, a `,` at this depth returns
    // there, and a nested bracket leaves it.
    let mut at_element_start = true;

    while index < p.token_count() {
        let kind = p.token_kind_at(index);

        if is_declaration_trivia(kind) {
            index += 1;
            continue;
        }

        match kind {
            // The list's own `)` at the outer depth ends it. Anything seen is settled by then.
            CppTokenKind::RightParen if depth == 0 => return false,
            CppTokenKind::RightParen | CppTokenKind::RightBracket | CppTokenKind::RightBrace => {
                depth = depth.saturating_sub(1);
                at_element_start = false;
            }
            CppTokenKind::LeftParen | CppTokenKind::LeftBracket | CppTokenKind::LeftBrace => {
                // A `(` **or a `{`** in element position is a value, not a type. Anywhere else it is nested
                // inside an element that is already under way.
                //
                // The `{` was missing from this test, and the shape it cost is a common one — a direct-initialiser
                // with a braced element:
                //
                // ```cpp
                // D d(1, {});                       // `d` is a variable initialised with two arguments
                // _Delta1_t(_First, …, {}, {});     // `<algorithm>`: an empty braced-init-list per parameter
                // ```
                //
                // Read without it, the `{` was taken for "an element already under way", the whole group came back
                // **not** looking like values, and the declaration reading was refused — so `D d(1, {})` came out an
                // `ExpressionStat` holding `D`, with `d(1, {` left as rubble. Six of the eight diagnostics on the
                // 3.3 MB cooked `<vector>` stream were this one shape.
                //
                // The argument is the same one `(` has, and it is about what a *type* can be: a parameter's type is
                // built from `*`, `&`, `&&`, `::`, `<>`, `[]` and `()`, and **nothing a type is made of begins with
                // `{`**. So a `{` at the start of an element is a braced-init-list, which is a value.
                //
                // A `{` that does *not* begin an element is untouched, and that is what keeps default arguments
                // reading: in `void f(A a = {})` the element is under way by the time the `{` arrives, so it is
                // nested rather than decisive.
                if at_element_start
                    && matches!(kind, CppTokenKind::LeftParen | CppTokenKind::LeftBrace)
                {
                    return true;
                }
                depth += 1;
                at_element_start = false;
            }
            // **A leading `::` does not spend the element-start marker.** It cannot begin anything *but* a name —
            // `::ns::T`, `::f(x)` — so the element is still at its start when the first identifier arrives, and
            // the arm below is the one that has to judge it.
            //
            // Leaving it to the catch-all spent the marker instead, and the cost was the very shape the note
            // below records fixing one level down: a **qualified call** produced no evidence of a value at all.
            // Measured, and it is the whole of one defect in a real header:
            //
            // ```text
            // const basic_string_view<_CharT> _Str(::std::to_address(_First), ::std::to_address(_First + _Dist));
            //                                                                          ^^^^^^^^^^^^^^^^^^^^^^^
            // ```
            //
            // MSVC's `<format>` writes that line, the element began with `::`, `f`'s follower was never read, the
            // group came back "not values", the declaration reading was refused — ``expected a parameter list or
            // an initializer`` at the `(` — and the file's cooked reading came out with **6 declarations where
            // its own text has 173**. The standard library is full of `::std::`-qualified calls in initialisers,
            // so this is not one line's problem.
            //
            // The `+` is what made it visible and is worth recording as the discriminator: `::f(a * b)` was
            // *clean* and `::f(a + b)` failed, which is why the shape survived so long — `*` and `&` have their
            // own arm further down and the `+` has none.
            CppTokenKind::Scope if at_element_start => {}
            CppTokenKind::Comma if depth == 0 => at_element_start = true,
            CppTokenKind::IntegerLiteral
            | CppTokenKind::FloatingLiteral
            | CppTokenKind::StringLiteral
            | CppTokenKind::CharLiteral
            | CppTokenKind::TrueKeyword
            | CppTokenKind::FalseKeyword
            | CppTokenKind::NullptrKeyword
                if at_element_start =>
            {
                return true;
            }
            // A name, and then whatever follows it. The **next** token is what settles the element: a name
            // whose follower cannot be part of the declaration it introduces is a value, and no later token of
            // the element can change that.
            //
            // ```text
            // Inner(1)      a name that is called — a construction, not a type
            // a + 1         a name followed by an operator no type contains
            // a, b          a name followed by the list's own `,` — an element of its own
            // B* C          a name followed by `*`, which a type *does* contain: left alone
            // ```
            //
            // Reading the follower rather than the name is what keeps the last line out of the answer, and it
            // is why this cannot be decided by looking at the element's first token alone. `B*(C)` — a
            // multiplication and a parameter of type `B*` — stays a call, which is the cheaper mistake; see the
            // note on operators below.
            CppTokenKind::Identifier if at_element_start => {
                // The follower is read after the **whole qualified chain**, not just after its first segment:
                // a `::` says the name continues, so it is not an answer to "what follows this name".
                //
                // ```text
                // std::move(b)     a call — the `(` after `move` settles it
                // std::move(b.c()) likewise, and it is why the chain has to be walked at all
                // B::C             a type — the `,` or `)` after `C` settles it
                // std::string name a type and a name — `name` settles it
                // ```
                //
                // Stopping at the first `::` made a qualified *call* look like a type: the follower was `::`,
                // which keeps the element a declaration, and the element-start marker was spent — so the call's
                // own `(` and everything inside it went unread, and an argument like `std::move(luaLexer.
                // GetTokens())` produced no evidence of a value at all. The declaration reading was then refused
                // and the statement reported `expected ;` against its own `(`. Seven files of the first real C++
                // project put in front of this parser failed on that one shape.
                let mut after = next_significant_index(p, index);
                while p.token_kind_at(after) == CppTokenKind::Scope {
                    let segment = next_significant_index(p, after);
                    if p.token_kind_at(segment) != CppTokenKind::Identifier {
                        break;
                    }
                    after = next_significant_index(p, segment);
                }
                let follower = p.token_kind_at(after);
                // The followers that keep this a *declaration*: another name (`B C`), a pointer or reference
                // (`B* c`), a qualified or templated continuation (`B::C`, `B<C>`), the `,` or `)` that ends a
                // nameless parameter (`void f(B)`), or a bracket or `=` that opens what a declarator carries.
                //
                // Everything else makes it a value, and the two that matter most are the `(` of a call and the
                // operators of an expression. The follower is the first token that is not trivia, so the space
                // in `int a (b)` is not read as the answer.
                let keeps_it_a_declaration = matches!(
                    follower,
                    CppTokenKind::Identifier
                        | CppTokenKind::Scope
                        | CppTokenKind::Less
                        | CppTokenKind::Star
                        | CppTokenKind::Ampersand
                        | CppTokenKind::LogicalAnd
                        | CppTokenKind::Comma
                        | CppTokenKind::RightParen
                        | CppTokenKind::LeftBracket
                        | CppTokenKind::Assign
                        | CppTokenKind::Ellipsis
                        | CppTokenKind::None
                );

                if !keeps_it_a_declaration {
                    return true;
                }
                at_element_start = false;
            }
            // An element that begins with an operator no type contains — `!flag`, `-x`, `~bits`.
            kind if at_element_start && !can_begin_a_type(kind) => return true,
            // A `*` or `&` **in element position is a unary operator**, and the version before this one got it
            // backwards — it asked "does a name follow?", kept the element a declaration when one did, and so read
            // `A(*p)` as a *declaration* where its own comment called it a dereference.
            //
            // The question is misplaced at element position, and `A(B* C)` is why it looked reasonable: there the
            // `*` really does make a pointer declarator. But it is **not at element position** there — the element
            // began with `B`, an identifier, and the arm below has already spent the marker by the time the `*`
            // arrives. Reaching this arm means `*` is the element's *first* token, and a parameter needs a
            // decl-specifier-seq before its declarator while `*` is not one: **no parameter begins with `*` or
            // `&`**, in any spelling. So the token can only be a dereference or an address-of, which is a value.
            //
            // What it cost: `T x(a, &b)` — an address-of in a direct-initialiser — came out an `ExpressionStat`
            // holding `T` with `x ( a , & b` left as rubble, because "not values" refused the declaration reading.
            // `T x(*b)` and `T x(a, b, c)` were the two neighbours that pinned the boundary: the first failed with
            // it, the second worked without it. `<ppltasks.h>` writes `_Options(…, &_Default_Context, …)`.
            CppTokenKind::Star | CppTokenKind::Ampersand | CppTokenKind::LogicalAnd
                if at_element_start =>
            {
                return true;
            }
            // The list ended without a `)`, or the statement did: there is no list to judge.
            CppTokenKind::Semicolon if depth == 0 => return false,
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => at_element_start = false,
        }

        index += 1;
    }

    false
}

/// Can this token stand at the front of a type?
///
/// The set a parameter's type is built from, and nothing else: a specifier keyword, a name, a qualifier or
/// attribute, a `*`, `&`, `&&`, `...`, `::`, `(`, `[` or a template's `<`. Every token outside it — `+`, `-`,
/// `!`, `~`, `%`, `^`, `|`, `==`, `<<`, `=`, `?`, `.`, `->`, and the literals — can only be an operator or a
/// value, which is what [`the_arguments_look_like_values`] reads the answer from.
///
/// Written as "everything except the things a type *can* contain" rather than as the list of operators, because
/// the list of operators is what grows: a new spelling of a type that this does not know about would then be
/// misread as a value, while a new operator would only be misread as a type — the cheaper direction, and the
/// one this crate's other heuristics already choose.
///
/// # What is deliberately absent
///
/// `constexpr`, `mutable`, `virtual` and `explicit` are absent: they are storage and function specifiers, so
/// they cannot decorate a *parameter's* type, and what they really appear in — `Mutable x(1);` — is a variable
/// whose type is named `Mutable`. The specifier-sequence rule has already refused any of them followed by a
/// name in type position, so a `(` after one of them is an initialiser and this answer is the right one.
///
/// `~` is absent for the same kind of reason: it starts a destructor's *name*, and a parameter's type has no
/// name in it. `Widget w(~x)` is a value.
fn can_begin_a_type(kind: CppTokenKind) -> bool {
    is_type_specifier_keyword(kind)
        || matches!(
            kind,
            CppTokenKind::Identifier
                | CppTokenKind::Scope
                | CppTokenKind::ConstKeyword
                | CppTokenKind::VolatileKeyword
                | CppTokenKind::TypenameKeyword
                | CppTokenKind::Star
                | CppTokenKind::Ampersand
                | CppTokenKind::LogicalAnd
                | CppTokenKind::Ellipsis
                | CppTokenKind::LeftParen
                | CppTokenKind::LeftBracket
                | CppTokenKind::Less
        )
}

/// The index of the next significant token after `index`, or one past the end of the stream.
///
/// The token list is indexed, not peeked, in the scans above, so a question about the token *after* the one
/// being looked at has to step over trivia by index. `peek_token_kind_at` cannot answer it: it counts
/// significant tokens from the cursor, and the cursor is not where these scans are.
///
/// Exposed to `types`, which asks the same question about the name a specifier sequence is looking at.
pub(super) fn next_significant_index(p: &CppParser, index: usize) -> usize {
    significant_index_at(p, index + 1)
}

/// The first significant token **at or after** `index`.
///
/// The difference from [`next_significant_index`] is one token, and it is the difference between reading a
/// declaration and eating it: a scanner that has just finished a group holds the index **one past** the closing
/// paren, and that index may be sitting on the newline after it. Asking for the token *after* that one skips
/// whatever the group was followed by — which is how `size_t _Hash_bytes(const void*);` came out as two macro
/// invocations and the `;` landed on the next declaration.
fn significant_index_at(p: &CppParser, index: usize) -> usize {
    let mut index = index;
    while index < p.token_count() && is_declaration_trivia(p.token_kind_at(index)) {
        index += 1;
    }
    index
}

/// Do the parentheses at the cursor hold a list of *declarators* rather than a list of values?
///
/// The question the last heuristic in [`a_declaration_is_the_better_reading`] asks, and it is about shape rather
/// than about names. Two shapes answer yes, and they are the two things that can legitimately stand where a
/// direct-initialiser's argument goes:
///
/// * a **bare name** — `Max(a, b)`, two things already in scope being copied. A *value*, by contrast, is
///   written as a literal, a call, a member access or an operator, and none of those is a name;
/// * a **nested construction** — `Widget w(Inner(1))`, one value being built. A parameter list has no such
///   element: `Inner(1)` is not a type, and reading it as one is exactly how a constructor argument came out as
///   a parameter. It is accepted only where the declaration reading is already established, which is what the
///   `known_type_name` parameter carries — by then a constructed temporary is far likelier than a function whose
///   parameter is named `Inner` and defaulted from `1`.
///
/// Everything else disqualifies the list: a literal, a `::`, a `.`, a `->`, an operator, a bracket. Depth is
/// tracked so that a nested list terminates an element rather than silently continuing it.
///
/// The `)` must close the list. A scan that runs out of tokens answers no, because there is then no list.
fn the_arguments_look_like_declarators(p: &CppParser, known_type_name: bool) -> bool {
    if p.current_token() != CppTokenKind::LeftParen {
        return false;
    }

    let mut index = p.current_token_index() + 1;
    let mut saw_one = false;
    let mut expect_an_element = true;
    let mut depth = 0usize;

    while index < p.token_count() {
        let kind = p.token_kind_at(index);

        if is_declaration_trivia(kind) {
            index += 1;
            continue;
        }

        match kind {
            // The list's own `)`, after one or more complete elements.
            CppTokenKind::RightParen => return depth == 0 && saw_one && !expect_an_element,
            CppTokenKind::LeftParen => {
                // A `(` that follows the name just read turns that name from a bare element into a
                // construction — but only where the declaration reading is already established, and only as one
                // level: the element `Inner(1)` is a value, whereas a call nested inside an element is not.
                if !known_type_name || expect_an_element || depth > 0 {
                    return false;
                }
                depth += 1;
            }
            CppTokenKind::Comma if depth == 0 => {
                if expect_an_element {
                    return false;
                }
                expect_an_element = true;
            }
            CppTokenKind::Identifier if depth == 0 => {
                // A second name with no comma between them is a type and its declarator, which this reading
                // has no element for.
                if !expect_an_element {
                    return false;
                }
                // A qualified name is a path to something rather than a name, so it is not a declarator.
                if p.peek_token_kind_at(1..2).as_slice() == [CppTokenKind::Scope] {
                    return false;
                }
                saw_one = true;
                expect_an_element = false;
            }
            // Inside a nested element: a value. Nothing there is this rule's business.
            _ if depth > 0 => {}
            // Anything else at the top level: a literal, an operator, a `::`, a `.`, an unmatched bracket.
            _ => return false,
        }

        index += 1;
    }

    false
}

/// Did the declaration this declarator belongs to lead with a name this file declared to be a type?
///
/// The companion to [`declarator_starts_with_a_type_keyword`], for the other way a type gets written: by name.
/// The name asked about is the **first** identifier of the declaration, which is what a declaration's type is —
/// `Widget` in `Widget w(1, 2);`.
fn declarator_starts_with_a_known_type_name(p: &CppParser) -> bool {
    p.declaration_type_name()
        .is_some_and(|name| p.is_a_known_type_name(name))
}

/// The name a type whose last segment starts at `from` would be looked up under.
///
/// The specifier loop that reaches this is called once per *segment* of a qualified name, because
/// [`parse_name`](types::parse_name) stops after each one and the loop walks the `::`. So the answer is
/// the **last** identifier of the whole thing: `std::string` is the type `string` seen through `std`, and a
/// lookup that started from `std` would be asking whether a *namespace* is a type.
///
/// The scan starts at the segment's own first token — which is the name, the caller having asked before parsing
/// it — and walks back over identifiers and the `::` between them, stopping at the first thing that is neither.
/// A nested name specifier is a chain of names, so reading the chain backwards finds its last link without
/// needing to know where the chain began. Only the identifier is kept, not the qualifiers: the qualifiers say
/// where to look the name up, which is a question for name resolution rather than for this table.
///
/// `""` when there is no such identifier, which the caller treats as "nothing to remember".
pub fn type_name_at(p: &CppParser, from: ParseAnchor) -> String {
    let mut index = p.current_token_index();

    loop {
        let kind = p.token_kind_at(index);
        if !is_declaration_trivia(kind) {
            if kind == CppTokenKind::Identifier {
                return p.token_text_at(index).to_string();
            }
            // Something that is neither a name nor the `::` between names: the chain ends here.
            if !matches!(kind, CppTokenKind::Scope) {
                return String::new();
            }
        }

        if index == from.token_index() {
            return String::new();
        }
        index -= 1;
    }
}

/// Did the declaration being parsed write a **qualified** name in type position?
///
/// ```text
/// void A::f<int>(int);          the head is `void A::f<int>`
/// static void Widget::draw(T);  the head is `static void Widget::draw`
/// int x = A::b;                 …and this is not a head with a qualified *type*, which the `;` and `=`
///                               before it are what rule out
/// ```
///
/// Asked of the **tokens** rather than of the name the specifier sequence recorded, because the record is empty
/// for the spelling that needs this most: `A::f<int>` ends in a template argument list, so the walk that recovers
/// a name stops on the `>` and reports nothing — and a declaration whose head names a qualified type is the head
/// of a *definition*, whose parentheses are a parameter list and whose declarator has no name of its own.
///
/// The walk is the one the other readers of a declaration's head use: backwards from the cursor to the start of
/// the declaration, stopping at a `;`, `{` or `}`, so it cannot run out of this declaration and answer for the
/// one before it. Trivia needs no skipping — none of it is a `::`.
pub fn the_head_of_the_declaration_is_qualified(p: &CppParser) -> bool {
    let mut index = p.current_token_index();

    while index > 0 {
        index -= 1;
        let kind = p.token_kind_at(index);

        if matches!(
            kind,
            CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace
        ) {
            return false;
        }
        if kind == CppTokenKind::Scope {
            return true;
        }
    }

    false
}

/// Did the declaration this declarator belongs to lead with a type **keyword**?
///
/// The question that separates `int a(1);` from `g(1, 2);`, and the only part of it that is answerable from the
/// tokens: a keyword type is written with a keyword, so a declaration beginning with one is a declaration,
/// while one beginning with a bare name is as likely to be the callee of a call.
///
/// Asked of the **first significant token of the declaration**, found by walking back over the tokens consumed
/// so far to the one that begins it. The walk stops at a `;`, `{` or `}` — no declaration contains one — which
/// is what keeps it inside this statement: without that, `void f() { g(1); }` would find the `void` of the
/// enclosing function and call the call a declaration.
///
/// It also steps over **angle lists**, and stops at a template head's `template`. Both were bugs rather than
/// refinements, and they were the same bug: the walk collected the token that followed the earliest boundary,
/// so for a declaration under a head it collected the `<` of `template <…>` and answered "not a type keyword"
/// for every one of them.
///
/// The symptom was narrow enough to hide and wide enough to matter: the suffix loop of an **unnamed** declarator
/// opens only when this answers yes (a named one opens on its own name), so
/// `template <class T> void f(int[4]);` failed with ``expected a parameter list or an initializer`` — the
/// parameter's `[4]` had nothing to attach to — while `void f(int[4]);` was read, and while the same parameter
/// *with* a name was read too. Measured: `bits/stl_pair.h`, `concepts` and `bits/functional_hash.h` each stopped
/// at a line of this shape.
///
/// The angle stepping is the other half and is what makes the stop at `template` mean anything: a list's own
/// tokens are not the declaration's beginning — `std::vector<int> x` begins at `std::vector` — so both halves of
/// an angle list are stepped over rather than assigned.
///
/// Not asked of the event stream, which was the first attempt and does not work: the events reach back to the
/// beginning of the file, so the `BuiltinType` of an enclosing declaration is indistinguishable from this
/// one's by node kind alone.
fn declarator_starts_with_a_type_keyword(p: &CppParser) -> bool {
    let mut index = p.current_token_index();
    let mut first = None;
    // How many angle lists the walk is inside, counted **backwards**: a `>` opens one, its `<` closes it.
    let mut angles = 0usize;

    while index > 0 {
        index -= 1;
        let kind = p.token_kind_at(index);

        if matches!(
            kind,
            CppTokenKind::Semicolon
                | CppTokenKind::LeftBrace
                | CppTokenKind::RightBrace
                | CppTokenKind::TemplateKeyword
        ) {
            break;
        }
        if is_declaration_trivia(kind) {
            continue;
        }

        match kind {
            CppTokenKind::Greater => angles += 1,
            CppTokenKind::RightShift => angles += 2,
            // The `<` that closes the list being walked through is stepped over like the tokens inside it.
            CppTokenKind::Less if angles > 0 => {
                angles -= 1;
                continue;
            }
            _ => {}
        }
        if angles > 0 {
            continue;
        }

        first = Some(kind);
    }

    // `auto` and `decltype` are deliberately left out of the answer even though they are in
    // [`types::is_type_specifier_keyword`]: both can begin an expression, so `auto(1)` is as readable as
    // a call as it is as a declaration. Of the two readings, the expression is the one to prefer — reading a
    // call as a declaration loses its callee *and* its arguments, while reading a declaration as a call merely
    // leaves a variable unbound.
    first.is_some_and(|kind| {
        types::is_type_specifier_keyword(kind)
            && !matches!(
                kind,
                CppTokenKind::AutoKeyword | CppTokenKind::DecltypeKeyword
            )
    })
}

/// Is a **type keyword** written immediately before the declarator's name — the `void` in `void f(T)`?
///
/// The question the direct-initialisation heuristic has to ask at the `(` of a declarator, and one
/// [`declarator_starts_with_a_type_keyword`] cannot answer: that one reads the *first* token of the whole
/// declaration, which a template head pushes away — `template <typename T> void f(T)` begins with `template`.
/// Here the walk starts at the declarator's own name, so the head is behind it and the type is in front.
///
/// A qualified name is stepped over as one thing: in `void A::f(T)` the name before the `(` is `A::f`, and the
/// type is still the `void` in front of it.
///
/// The answer matters because a declaration that *has* a type must take the parameter reading of the
/// parentheses, however its contents are spelled:
///
/// ```text
/// void f(T);        a function with one unnamed parameter of type `T`
/// template <typename T> void f(T) { }
/// ```
///
/// Both used to be read as *variables* — `f` initialised with the value `T` — because a list of bare names is
/// the one shape a direct-initialiser and a parameter list share, and at file scope the initialiser reading was
/// preferred for it. That preference exists for `Max(a, b);`, a declaration with **no type at all**; a `void` in
/// front of the name settles the question the preference was guessing at.
fn a_type_keyword_precedes_the_declarator_name(p: &CppParser) -> bool {
    let mut index = p.current_token_index();
    let mut seen_an_identifier = false;

    while index > 0 {
        index -= 1;
        let kind = p.token_kind_at(index);

        if is_declaration_trivia(kind) {
            continue;
        }
        if matches!(
            kind,
            CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace
        ) {
            return false;
        }

        match kind {
            CppTokenKind::Identifier => seen_an_identifier = true,
            // A `::` in front of the name just read: this is a qualified name, so the walk continues to the
            // segment in front of it.
            CppTokenKind::Scope if seen_an_identifier => seen_an_identifier = false,
            // The token in front of the name — `auto` and `decltype` are left out for the reason
            // [`declarator_starts_with_a_type_keyword`] gives: both can begin an expression as readily.
            _ if seen_an_identifier => {
                return types::is_type_specifier_keyword(kind)
                    && !matches!(
                        kind,
                        CppTokenKind::AutoKeyword | CppTokenKind::DecltypeKeyword
                    );
            }
            _ => return false,
        }
    }

    false
}

/// Does a declarator begin where the cursor stands?
fn starts_a_declarator(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::Star
            | CppTokenKind::Ampersand
            | CppTokenKind::LogicalAnd
            | CppTokenKind::Identifier
            | CppTokenKind::Scope
            | CppTokenKind::OperatorKeyword
            | CppTokenKind::Tilde
    )
}

/// Token kinds that are not part of a declaration's own text, for the walk above.
fn is_declaration_trivia(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::Whitespace
            | CppTokenKind::Newline
            | CppTokenKind::LineContinuation
            | CppTokenKind::LineComment
            | CppTokenKind::BlockComment
            | CppTokenKind::None
    )
}

/// **Is the token at the cursor one that cannot follow a class definition at all?**
///
/// The question the missing-`;` error rests on, and it is deliberately narrow: a class definition may be followed
/// by a `;` or by a declarator, and **those readings are left alone**. What this answers is the residue — a token
/// that begins a new declaration, closes the enclosing scope, or ends the file. In each of those the `;` can only
/// have been forgotten, and saying so is what gets the reader the declarations that follow instead of losing them:
/// measured, one missing semicolon in a reader's own file took it from 8 declarations to 2 **with no diagnostic**.
///
/// A keyword is what most of the list is, and every one of them is a **declaration-specifier** the grammar already
/// knows how to begin a declaration with. An identifier is deliberately **not** here: `struct S { … } x;` is the
/// declarator reading, and it is a shape the parser handles.
fn a_declaration_cannot_follow(p: &CppParser) -> bool {
    use CppTokenKind::*;

    matches!(
        p.current_token(),
        // The end of the enclosing scope, or of the file.
        RightBrace | None
        // A declaration-specifier, which cannot continue the declaration this one is.
            | StructKeyword
            | ClassKeyword
            | UnionKeyword
            | EnumKeyword
            | TemplateKeyword
            | NamespaceKeyword
            | UsingKeyword
            | TypedefKeyword
            | StaticKeyword
            | InlineKeyword
            | ExternKeyword
            | ConstexprKeyword
            | ConstevalKeyword
            | ConstinitKeyword
            | FriendKeyword
            | VirtualKeyword
            | PublicKeyword
            | PrivateKeyword
            | ProtectedKeyword
            | VoidKeyword
            | AutoKeyword
            | CharKeyword
            | IntKeyword
            | FloatKeyword
            | DoubleKeyword
    )
}

/// Can the `( ` at the cursor open an argument list rather than a parameter list?
///
/// True unless the parentheses are **empty**. `T x()` is the most vexing parse's other half — a function
/// declaration, not a variable — and it is already handled by the parameter-list reading, so the initializer
/// reading must not take it. Everything else is worth trying as an initializer, and the parameter reading has
/// already been tried and rewound by the time this is asked.
fn an_argument_list_follows(p: &CppParser) -> bool {
    p.current_token() == CppTokenKind::LeftParen
        && p.peek_token_kind_at(1..2).as_slice() != [CppTokenKind::RightParen]
}

/// Parse the declaration part of a `for` header, where the `;` belongs to the header rather than to
/// the declaration.
pub fn parse_for_init_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Declaration);

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

    // Where the declarators begin. "Did this declaration name anything?" has to be asked of the events *they*
    // produced — the type's own name is already in the stream behind this bound, and it would answer for them.
    let declarator_from = p.current_event_count();

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

    while p.current_token() == CppTokenKind::Comma {
        p.bump();
        if let Err(err) = parse_init_declarator(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    // A `for` header has no `;` of its own, so a declaration that consumed only a **type** and named nothing has
    // nothing left to fail on:
    //
    // ```text
    // for (;; i++) { }     `i` was read as the type, the declarator came out empty, and the header then reported
    //                      `expected )` against the `++` — the increment was never read as an expression at all
    // ```
    //
    // The ordinary statement path cannot reach that state: its declaration reading has a `;` to insist on, so
    // `i++;` fails there at the `++` and the expression reading takes over. The header is the one place the
    // question has to be asked directly, and it is asked the same way `an_initializer_needs_a_name` asks it —
    // of the events the declarators produced.
    //
    // Nothing legitimate is refused: a `for` init that declares something always names it (`int i = 0`,
    // `Widget w(1)`, `auto [a, b] = pair`), and a type on its own declares nothing to loop over. What the
    // refusal buys is the *fallback*: the caller rewinds and reads the header as an expression, which is what
    // `i++`, `i++, k++` and `v` in `for (v : m)` all are.
    if !a_name_was_parsed(p, declarator_from) {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("expected a declaration that names something"),
            p.current_token_range(),
        ));
    }

    Ok(m.complete(p))
}

/// Parse the **declaration form of a condition**: `if (Foo p = get())`, `while (const auto n = g())`.
///
/// The same shape a `for` header reads — specifiers and one init-declarator, no `;` of its own — because a
/// condition's declaration ends at the `)` that closes the condition. Two differences, and each is load-bearing:
///
/// ```text
/// one declarator, not a list     `if (int a = 1, b = 2)` is not a condition, and C++ says so
/// an initialiser is required     which is the whole of what tells `if (a && b)` (an expression, always) from
///                                `if (a b = c)` — without it the declaration reading claims the first as a
///                                declaration of `b` with type `a&&`, a **wrong** answer rather than a missing one
/// ```
///
/// # Why a condition could not go through `parse_declaration`
///
/// That rule ends with `expect_semicolon`, and a condition has none: the attempt failed, `parse_condition` fell
/// back to an *expression*, and the two readings that came out were
///
/// ```text
/// if (Foo* p = get())       `Foo * p = get()` — a BinaryExpr with **no diagnostic at all**
/// if (const auto n = g())   `expected primary expression` against the `=`
/// ```
///
/// The first is the one worth remembering: every file in the census was lossless and error-free on that reading,
/// so no count could have moved. See `a_condition_may_declare_a_variable` in `tests/gaps.rs`.
///
pub fn parse_condition_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Declaration);

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

    // Where the declarator begins: the two questions below are asked of the events *it* produced, because the
    // type's own name is already in the stream behind this bound and would answer for them.
    let declarator_from = p.current_event_count();

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

    let named = a_name_was_parsed(p, declarator_from);
    let initialised = p.events_contain_any(declarator_from, &[CppSyntaxKind::Initializer]);

    if !named || !initialised {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("a condition declaration needs one variable with an initializer"),
            p.current_token_range(),
        ));
    }

    if p.current_token() == CppTokenKind::Comma {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("a condition declares one variable, not a list"),
            p.current_token_range(),
        ));
    }

    // **What follows has to be the `)` that closes the condition**, and this is the third refusal rather than a
    // detail of the first two: a condition's declaration has no `;` of its own, so the `)` is what says the
    // declaration is over — and the tests above are asked of the *declarator's own events*, which a **parameter
    // list** also produces. `if (NS::fmod(s, T(2)) == 0)` is the shape that separates them, and it is not a
    // hypothetical one: `tr1/riemann_zeta.tcc:173` writes it.
    //
    // ```text
    // if (NS::fmod(s, T(2)) == 0)
    //     └────┬────┘ └──┬──┘     the type is `NS::fmod` (a qualified name is a type), the declarator is
    //          │         │        `(s, T(2))` — a *function* declarator whose parameters named something and
    //          │         │        initialised something, so both tests passed
    //          │         └────────── `T(2)` is read as a parameter with a direct-initialiser
    //          └──────────────────── …and the condition then wanted its `)` where the `==` stands
    // ```
    //
    // With the `)` required, the declaration reading is refused and the *expression* reading — the call the file
    // wrote — takes the tokens, which is the same order of preference [`parse_condition`] documents for the other
    // two refusals: a shape that is not a condition declaration is an expression.
    if p.current_token() != CppTokenKind::RightParen {
        p.close_marks_above(base);
        return Err(CppParseError::syntax_error_from(
            &t!("a condition declaration ends at the `)` that closes the condition"),
            p.current_token_range(),
        ));
    }

    Ok(m.complete(p))
}

/// Parse `{ ... }` as an initializer, keeping it as one node.
pub fn parse_braced_initializer(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::InitListExpr);

    expect_token(p, CppTokenKind::LeftBrace)?;

    while p.current_token() != CppTokenKind::RightBrace && !p.is_eof() {
        // A **preprocessor directive** between the elements. The statement rule reads a directive when it meets
        // one at the start of a statement, but an initializer is not a statement list — and a table whose rows are
        // conditional is exactly what conditional compilation is for:
        //
        // ```c
        // char const info_version[] = {
        //   'I', 'N', 'F', 'O', ':',
        // #ifdef COMPILER_VERSION
        //   COMPILER_VERSION,
        // #endif
        //   '\0' };
        // ```
        //
        // It is read as the node it is — the tree stays lossless and a consumer can still see the directive —
        // rather than reported as a missing element. Only *here* is the directive claimed: in an expression proper
        // a `#` is still an error, so nothing that used to be reported stops being reported.
        if p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            continue;
        }

        // A designated initializer: `.field = 1` (C++20) or `[index] = 1`.
        //
        // **A designator list, not one designator.** C99 6.7.8 has `designator-list = designator | designator-list
        // designator`, and C++20 kept it: `{ .data.integer = i }` names a subobject two levels down, and nvim's
        // `helpers.h` is written that way (`#define INTEGER_OBJ(i) ((Object){ .type = …, .data.integer = i })`).
        // Reading one designator and then expecting `=` turned the second `.` into "expected `;` after expression" —
        // and because the macro is *expanded* before it is parsed, every use of `INTEGER_OBJ(…)` reported two
        // "expected primary expression" errors inside its own expansion. Measured: `(Object){ .type = 1,
        // .data.integer = 2 };` produced one error before this, none after.
        if p.current_token() == CppTokenKind::Dot || p.current_token() == CppTokenKind::LeftBracket
        {
            let designator = p.mark(CppSyntaxKind::DesignatedInitExpr);
            loop {
                if p.current_token() == CppTokenKind::Dot {
                    p.bump();
                    if p.current_token() == CppTokenKind::Identifier {
                        p.bump();
                    }
                } else if p.current_token() == CppTokenKind::LeftBracket {
                    p.bump();
                    let _ = parse_expr(p);
                    let _ = expect_token(p, CppTokenKind::RightBracket);
                } else {
                    break;
                }
            }
            if p.current_token() == CppTokenKind::Assign {
                p.bump();
            }
            if let Err(err) = parse_initializer_clause(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            designator.complete(p);
        } else if let Err(err) = parse_initializer_clause(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        if p.current_token() == CppTokenKind::Comma {
            p.bump();
        } else if p.current_token() != CppTokenKind::Hash {
            // A directive needs no comma in front of it: `'a',\n#ifdef X\n'b',` has one, but
            // `'a'\n#ifdef X\n#endif\n, 'b'` is a row that is *entirely* conditional and has none.
            break;
        }
    }

    expect_token(p, CppTokenKind::RightBrace)?;
    Ok(m.complete(p))
}

/// Parse a constructor member initializer list: `: a(1), b{2}, c()`.
fn parse_member_initializer_list(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();

    expect_token(p, CppTokenKind::Colon)?;

    loop {
        let m = p.mark(CppSyntaxKind::MemberInitializer);
        if let Err(err) = parse_name(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        match p.current_token() {
            CppTokenKind::LeftParen => {
                if let Err(err) = parse_expression_list(p, CppTokenKind::RightParen) {
                    p.close_marks_above(base);
                    return Err(err);
                }
            }
            CppTokenKind::LeftBrace => {
                if let Err(err) = parse_braced_initializer(p) {
                    p.close_marks_above(base);
                    return Err(err);
                }
            }
            // A pack expansion: `Base(args)...`
            CppTokenKind::Ellipsis => p.bump(),
            _ => {}
        }
        m.complete(p);

        if p.current_token() == CppTokenKind::Comma {
            p.bump();
            continue;
        }
        break;
    }

    Ok(CompleteMarker::empty())
}

/// **The other branches' member initializer lists**, when a conditional repeats the list.
///
/// ```cpp
/// basic_string()                                   // bits/cow_string.h:515
/// #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0
///   : _M_dataplus(_S_construct(size_type(), _CharT(), _Alloc()), _Alloc())
/// #else
///   : _M_dataplus(_S_construct(size_type(), _CharT(), _Alloc()), _Alloc())
/// #endif
///   { }
/// ```
///
/// One declarator, one initializer list **per branch**. Reading a single list and returning left the `#else` and
/// the second `:` to the matcher, which has no reading for either: the constructor failed, and the recovery then
/// took its `{ }` for the class's closing brace — so `class basic_string` ended 3400 lines early and every member
/// after it was read at file scope. A directive and a `:` are the only two
/// tokens this loop accepts, so it stops at the first body brace, `;` or anything else.
fn parse_further_member_initializer_lists(p: &mut CppParser) -> ParseResult {
    loop {
        let mut saw_a_directive = false;
        while p.current_token() == CppTokenKind::Hash {
            stats::parse_preprocessor_directive(p)?;
            saw_a_directive = true;
        }

        // The `:` of the next branch, and only after a directive: without one, the first list would be read
        // again — `Foo() : a(1)` has one `:`, and a loop that took every `:` would take a *bit-field*'s.
        if !saw_a_directive || p.current_token() != CppTokenKind::Colon {
            return Ok(CompleteMarker::empty());
        }

        parse_member_initializer_list(p)?;
    }
}
/// Parse a parenthesised list of **initializer clauses**: `(a, b)`, `(a, {})`.
///
/// # An element may be a braced-init-list, and that is the grammar rather than a relaxation
///
/// C++11 gave direct-initialisation two spellings — [dcl.init]:
///
/// ```text
/// direct-initializer:   ( expression-list )        int a(1, 2);
///                       ( initializer-list )       D d(1, {});      ← this one
/// initializer-clause:   assignment-expression
///                       braced-init-list
/// ```
///
/// so `D d(1, {})` is **not** an expression-list with an odd element: `1, {}` is an *initializer-list*, whose
/// second clause is a braced-init-list. `{}` is a perfectly good clause and never was an expression.
///
/// Reading only expressions is what this rule used to do, and the cost was the whole declaration: the group failed,
/// `parse_the_initializer` failed with it, and `D d(1, {})` came out an `ExpressionStat` holding `D` with `d(1, {`
/// left as rubble. Six of the eight diagnostics on the 3.3 MB cooked `<vector>` stream were this one shape, written
/// by `<algorithm>`'s `_Delta1_t(_First, _UFirst, _Pat_size_raw, {}, {})`.
///
/// The call spelling of the same tokens (`g(1, {})`) already read, because a call's arguments go through the
/// expression grammar's own payload reader; the two had different vocabularies for the same list, which is why one
/// worked and the other did not.
///
/// The other two callers are `new`'s placement lists, where a braced clause means nothing — accepting one there is
/// the harmless direction, and refusing it would be a second vocabulary for the same list.
pub fn parse_expression_list(p: &mut CppParser, closing: CppTokenKind) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ArgumentList);
    let opening = if closing == CppTokenKind::RightParen {
        CppTokenKind::LeftParen
    } else {
        CppTokenKind::LeftBracket
    };

    // **Every early return unwinds**, and both of this rule's are a `?` on a `expect_token` that has already
    // failed: `ArgumentList` is open, so a bare `?` leaves a marker no owner will close.
    //
    // Measured: `std::sort(a(), b(, [](int i, int j) { return i < j; });` — a call whose closer is missing, which is
    // what a reader types halfway through — left one `ArgumentList` open for the rest of the file. The caller
    // (`parse_the_initializer`) undoes its own mark, which does not touch this one, so from there on every recovery
    // in the file closed down to a level that still held it (`parse_cpp_unit`'s `open_marks == base + 1`).
    if let Err(err) = expect_token(p, opening) {
        p.close_marks_above(base);
        return Err(err);
    }

    while p.current_token() != closing && !p.is_eof() {
        // One **element** of the list, read below the comma operator: the commas between elements belong to the
        // list, not to an expression. See [`exprs::parse_assignment_expr`].
        let element = if p.current_token() == CppTokenKind::LeftBrace {
            parse_braced_initializer(p)
        } else {
            exprs::parse_assignment_expr(p)
        };
        if let Err(err) = element {
            p.close_marks_above(base);
            return Err(err);
        }
        if p.current_token() == CppTokenKind::Comma {
            p.bump();
            continue;
        }
        break;
    }

    if let Err(err) = expect_token(p, closing) {
        p.close_marks_above(base);
        return Err(err);
    }
    Ok(m.complete(p))
}

/// Parse a function parameter list, including the `(...)` of a variadic function.
pub fn parse_parameter_list(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ParameterList);

    expect_token(p, CppTokenKind::LeftParen)?;

    // `f()` — no parameters at all.
    if p.current_token() == CppTokenKind::RightParen {
        p.bump();
        return Ok(m.complete(p));
    }

    // `f(...)` — an old-style variadic function. The lexer produces one `...` token, but a stray
    // `...` can also follow named parameters.
    if p.current_token() == CppTokenKind::Ellipsis {
        p.bump();
        expect_token(p, CppTokenKind::RightParen)?;
        return Ok(m.complete(p));
    }

    // **How many conditionals were open when this list began** — the gate of the tail seam at the end, and the
    // thing that separates the two spellings which otherwise look identical from there:
    //
    // ```cpp
    //     random_shuffle(_RAIter, _RAIter,              // parallel/algorithmfwd.h:700 — the tail per branch
    // #if __cplusplus >= 201103L                        ← the conditional is *inside* the list
    //            _RandomNumberGenerator&&);
    // #else
    //            _RandomNumberGenerator&);
    // #endif
    //
    // #if X
    //   void f(int a);                                  // …and this one is a whole declaration per branch:
    // #else                                             the `#if` belongs to the statement, and `void g(int a)`
    //   void g(long a);                                 reads as *parameters* just as well as the tail above does
    // #endif
    // ```
    //
    // Without the comparison, the second spelling was read as the first: the `;` before the `#else` is the
    // declaration's, and reading the next branch's text as more parameters produced garbage —
    // `type_traits:1177` and `stl_iterator.h:3023` were how that showed up. With it, the tail seam fires only when
    // the branch it closes was opened after this list began.
    //
    // The count comes from the directive rule rather than from this function, because a nested reading may consume
    // a directive the list never sees — see [`CppParser::open_conditionals`].
    let conditionals_when_the_list_began = p.open_conditionals();

    loop {
        // A **directive between parameters** — the same seam as the one in the template parameter list, and the
        // spelling `bits/algorithmfwd.h:700` writes:
        //
        // ```cpp
        //     random_shuffle(_RAIter, _RAIter,
        // #if __cplusplus >= 201103L
        //            _RandomNumberGenerator&&);
        // #else
        //     random_shuffle(_RAIter, _RAIter,
        //            _RandomNumberGenerator&);
        // #endif
        // ```
        //
        // A `#` at a parameter position cannot be anything else: a parameter begins with a type — or a directive.
        while p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

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

        // **A parameter written once per branch** — an `#else`/`#elif` here spells *this* parameter the other way,
        // so another parameter follows rather than a new one starting:
        //
        // ```cpp
        //   void f(int a,
        // #if X
        //          int b
        // #else
        //          long b
        // #endif
        //          );
        // ```
        //
        // Any other directive (`#endif`, and the `#else` that ends the *first* branch's whole declaration in
        // `bits/algorithmfwd.h`) only closes something, and the terminator is what comes next — which is why the
        // two cases are told apart by the directive's name and not by "is there a `#`".
        loop {
            if p.current_token() != CppTokenKind::Hash {
                break;
            }

            let another_spelling_of_this_parameter =
                matches!(p.peek_token_text_at(1), "else" | "elif");

            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }

            if !another_spelling_of_this_parameter {
                continue;
            }

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

        match p.current_token() {
            CppTokenKind::Comma => {
                p.bump();
                // A trailing `...` after the last named parameter: `int f(int a, ...)`.
                if p.current_token() == CppTokenKind::Ellipsis {
                    p.bump();
                    break;
                }
                continue;
            }
            _ => break,
        }
    }

    expect_token(p, CppTokenKind::RightParen)?;

    // **The list's tail written once per branch** — `parallel/algorithmfwd.h:700`:
    //
    // ```cpp
    //     random_shuffle(_RAIter, _RAIter,
    // #if __cplusplus >= 201103L
    //            _RandomNumberGenerator&&);
    // #else
    //            _RandomNumberGenerator&);
    // #endif
    // ```
    //
    // The `)` just consumed closes the list **in this branch**, and the `;` after it is the declaration's — but
    // the `#else` branch writes the same tail again: more parameters, another `)`, another `;`. So the `)` is not
    // the end of the list, it is the end of *this spelling* of it, and the branches are alternatives of one list.
    //
    // Each spelling's `;` is read here with its tail, and the declaration is told
    // ([`CppParser::note_the_terminator_came_from_a_branch`]) — it would otherwise ask for a `;` and find
    // `#endif`. The last spelling's `;` is consumed here too, because the construct being read is the whole
    // per-branch tail and not just its first spelling.
    //
    // The gate is two conditions rather than one: a `;` immediately followed by a directive that **opens another
    // branch**, *and* a conditional opened after this list began (`conditionals_when_the_list_began`). A `;`
    // followed by an `#endif`, or by the next declaration, stays where it has always been — with the declaration.
    let mut read_a_branch_of_the_tail = false;
    while p.open_conditionals() > conditionals_when_the_list_began
        && let Some(writes_the_terminator) = a_branch_continues_the_tail(p)
    {
        if writes_the_terminator {
            p.bump(); // this branch's `;`
            p.note_the_terminator_came_from_a_branch();
            read_a_branch_of_the_tail = true;
        }

        while p.current_token() == CppTokenKind::Hash {
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

        // …and the branch's own tail: the parameters it repeats, and the `)` that closes the list there.
        while p.current_token() != CppTokenKind::RightParen && !p.is_eof() {
            if let Err(err) = parse_one_parameter(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            if p.current_token() != CppTokenKind::Comma {
                break;
            }
            p.bump();
        }

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

    // The **last** spelling's `;`: this construct read the tail on both sides of the conditional, so it reads the
    // terminator the last branch wrote as well — and if the file wrote none, the declaration still has the flag.
    if read_a_branch_of_the_tail && p.current_token() == CppTokenKind::Semicolon {
        p.bump();
    }

    Ok(m.complete(p))
}

/// Does a **branch** follow the construct whose tail may be written once per branch — and does it carry the
/// declaration's terminator?
///
/// The gate of the tail seams — [`parse_parameter_list`], the template argument list's, and a conditional's, which
/// all ask the same question about the same spelling. Two answers, because the two spellings differ in exactly
/// this:
///
/// ```cpp
///     random_shuffle(_RAIter, _RAIter,                      // parallel/algorithmfwd.h:700 — a `;` per branch
/// #if __cplusplus >= 201103L
///            _RandomNumberGenerator&&);
/// #else
///            _RandomNumberGenerator&);
/// #endif
///
///     void random_shuffle(…,                                // bits/stl_algo.h:4600 — the terminator is shared
/// #if __cplusplus >= 201103L
///            _RandomNumberGenerator&& __rand)
/// #else
///            _RandomNumberGenerator& __rand)
/// #endif
///     { … }
/// ```
///
/// * `Some(true)` — `;` then `#else`/`#elif`: the branch writes the declaration's terminator, so the construct
///   reads it (and the caller is told, since it would otherwise ask for one and find `#endif`);
/// * `Some(false)` — the branch opener directly after the tail: nothing is written, and what ends the declaration
///   (here a body) stands after the `#endif` and stays the caller's business;
/// * `None` — no branch follows: a `;` followed by anything else is the declaration's own terminator, and reading
///   it here would take it from the rule that owns it.
///
/// Nothing is consumed: this is a lookahead, because the answer decides whether the `;` belongs to the construct
/// being read or to the declaration around it. The other half of the gate is a *count* — how many conditionals are
/// open now against how many were open when the construct began — and it comes from the directive rule, not from
/// the construct: see [`CppParser::open_conditionals`].
pub(super) fn a_branch_continues_the_tail(p: &CppParser) -> Option<bool> {
    let mut index = p.current_token_index();
    let mut writes_the_terminator = false;

    if p.token_kind_at(index) == CppTokenKind::Semicolon {
        writes_the_terminator = true;
        index = next_significant_index(p, index);
    }

    if p.token_kind_at(index) != CppTokenKind::Hash {
        return None;
    }

    let directive = next_significant_index(p, index);
    matches!(p.token_text_at(directive), "else" | "elif").then_some(writes_the_terminator)
}

/// One parameter, with the **pack marker** that belongs to it.
///
/// `Args&&... args` and `Ts... rest` write the marker *before* the name in one spelling and after the type in the
/// other, so it is not something [`parse_parameter`] can attach: by the time it returns, the cursor is past the
/// name. The trailing `...` of an old-style variadic function lands here too, which is why it is consumed on every
/// path and not only before a comma.
///
/// Factored out because the list reads a parameter in **two** places — once at the top of its loop and once for
/// each branch of a conditional (`#if X int b #else long b #endif`), where the same parameter is spelled again.
fn parse_one_parameter(p: &mut CppParser) -> ParseResult {
    parse_parameter(p)?;

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

    Ok(CompleteMarker::empty())
}

/// Parse one parameter: a type, an optional declarator, and an optional default argument.
fn parse_parameter(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Parameter);

    // An **explicit object parameter** (C++23): `void f(this S& self)`, `void f(this auto&&) &&`.
    //
    // `this` in parameter position is the start of a *type* — the deduced type of the object — and that is the
    // whole reason this needs its own rule: everywhere else `this` is an expression, so the specifier sequence
    // cannot read it, and the failure was **silent**. The parameter list gave up at the `this`, the declaration
    // reading failed, and the member came out as nothing at all while the tokens that followed were read as a
    // second, phantom member. No diagnostic was produced, so `gaps.rs` could not see it either — it was found by
    // probing for constructs rather than by a test.
    //
    // The shape after `this` is a **type-id** — `S&`, `S&&`, `auto&&` — and reading it as one is what covers
    // every spelling without a case each. It has to be a type, too: the operator `this` is an expression and
    // cannot begin a parameter, so a `this` with no type after it is refused here and left to whatever rule owns
    // it (`f(this);` is a call passing the object).
    //
    // The `this` is kept as a `ThisExpr` node so the text stays where it was written; a consumer looking for the
    // object parameter finds it by that node.
    if p.current_token() == CppTokenKind::ThisKeyword {
        let object = p.mark(CppSyntaxKind::ThisExpr);
        p.bump(); // `this`
        object.complete(p);

        // The type of the object, suffixes included: `S&`, `S&&`, `auto&&`. `parse_type_id` reads the whole
        // type-id, which is exactly what is written here — and its refusal is what makes the guard above
        // unnecessary: `this` followed by something that is not a type does not parse as one, so the caller
        // rewinds and the expression reading gets `f(this)`.
        if let Err(err) = types::parse_type_id(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        // The name, if there is one — `this S&` needs no more than the type.
        if p.current_token() == CppTokenKind::Identifier
            && let Err(err) = parse_name(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }

        // A default argument, read exactly as any other parameter's.
        if p.current_token() == CppTokenKind::Assign {
            p.bump();
            if let Err(err) = exprs::parse_assignment_expr(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

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

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

    // The declarator is optional: `void f(int)` is as valid as `void f(int x)`.
    //
    // The ellipsis is excluded because it is not one: in `Args&&... args` the marker comes between the type and
    // the name, so the name after it is what a declarator would have to be read from — and reading the `...`
    // as a declarator is what produced `expected a parameter list or an initializer` against these parameters.
    if !definitely_ends_a_type(p.current_token())
        && p.current_token() != CppTokenKind::Comma
        && p.current_token() != CppTokenKind::Ellipsis
        && let Err(err) = parse_declarator(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    // A pack expansion: `Args&&... args`. The marker belongs to the parameter it expands, so it is consumed
    // here; the name that follows it belongs to the same parameter and is read as one.
    if p.current_token() == CppTokenKind::Ellipsis {
        p.bump();

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

    // Attributes on the parameter: `void f(int x [[maybe_unused]])`, the same position as on a variable. Read
    // after the declarator and before the default argument, which is the order C++ writes them in — and only
    // here, so the `[[` of an attribute written *before* the type goes on being read by the specifier sequence,
    // which is where it belongs.
    if let Err(err) = types::parse_attribute_specifiers(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // **A macro after the parameter's declarator** — `void f(exarg_T *eap FUNC_ATTR_UNUSED)`.
    //
    // The same shape [`eat_a_macro_suffix`] was written for one level out, and the same argument: after a
    // declarator an identifier has no other reading, so a name here costs no valid program while refusing it costs
    // the whole declaration. Measured on neovim: its `FUNC_ATTR_*` attributes are empty macros that only the
    // *generated* headers define (`gen_declarations.lua` writes `#define DEFINE_EMPTY_ATTRIBUTES` in front of the
    // include), so a closure without those headers keeps the name, and then `arglist.c`'s
    // `void ex_argdedupe(exarg_T *eap FUNC_ATTR_UNUSED) { … }` failed to read as a declaration at all: the file
    // came back as **one `ExpressionStat`** with a syntax error on every function body's closing brace, and the
    // editor showed three `syntax-error` diagnostics on a file that compiles.
    //
    // C's own spellings of the same position — SAL's `_In_`/`_Out_`, MinGW's calling conventions, `__attribute__` a
    // project writes as a macro — are all this shape.
    eat_a_macro_suffix(p);

    if p.current_token() == CppTokenKind::Assign {
        p.bump();
        let init = p.mark(CppSyntaxKind::Initializer);
        if let Err(err) = parse_initializer_clause(p) {
            init.undo(p);
            p.close_marks_above(base);
            return Err(err);
        }
        init.complete(p);
    }

    Ok(m.complete(p))
}

/// Parse the body of a class, struct or union: `{ public: ... };`.
pub fn parse_class_body(p: &mut CppParser) -> ParseResult {
    let _base = p.open_marks();
    let m = p.mark(CppSyntaxKind::ClassBody);

    expect_token(p, CppTokenKind::LeftBrace)?;

    // A nested class is a type name inside this body and not outside it, so the table's scope follows the
    // brace — the same approximation a compound statement makes. The body depth is recorded for the same
    // region, because a `:` after a member declarator means something different in here than outside.
    p.enter_type_name_scope();
    p.enter_class_body();
    let result = parse_class_body_members(p);
    p.leave_class_body();
    p.leave_type_name_scope();
    result?;

    Ok(m.complete(p))
}

///
/// Read a **macro standing among a declarator's suffixes**, and say whether there was one.
///
/// `_GLIBCXX_NOEXCEPT`, `_GLIBCXX_NOTHROW`, `_GLIBCXX_USE_NOEXCEPT`, `_GLIBCXX20_DEPRECATED_SUGGEST("…")`,
/// `_GLIBCXX20_INIT({})` — one of these stands after nearly every declaration libstdc++ writes, and the whole
/// declaration was lost without it: `inline void __terminate() _GLIBCXX_USE_NOEXCEPT` reported `expected ';'`
/// against the macro, and then recovered by eating the body.
///
/// # Why the shape is decisive here
///
/// After a declarator, an identifier has exactly **two** readings in C++, and both are known: a contextual
/// keyword, or a macro. Everything else that may legally stand in this position is a keyword or punctuation —
/// `{`, `;`, `=`, `,`, `:`, `[[`, `->`, `noexcept`, `const`. So a name here costs no valid program, and the
/// alternative is an error; that is the fallback side of the rule — where no table can answer, the shape decides —
/// the same footing as `eat_namespace_head_macros`.
///
/// The three names that would be a *better* reading as something else are refused by spelling, which is the same
/// test the function-suffix loop already makes for `override` and `final`: `override` and `final` are read by
/// that loop, and `requires` begins a clause the declarator loop reads for itself — taking it here would swallow
/// the constraint and leave the clause's tokens on the declaration that follows.
///
/// # Why the group is optional
///
/// Both spellings occur and they mean different things to the macro, not to this: `_GLIBCXX_NOEXCEPT` is a bare
/// name, `_GLIBCXX_NOEXCEPT_IF(noexcept(…))` is an invocation. The group is read as raw tokens by
/// [`parse_balanced_token_group`] — the macro's arguments, nothing interpreted — and the whole thing becomes one
/// `MacroCall`, the same node every other macro reading produces.
pub(super) fn eat_a_macro_suffix(p: &mut CppParser) -> bool {
    if p.current_token() != CppTokenKind::Identifier {
        return false;
    }

    if matches!(p.current_token_text(), "override" | "final" | "requires") {
        return false;
    }

    let checkpoint = p.checkpoint();
    let m = p.mark(CppSyntaxKind::MacroCall);

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

    if p.current_token() == CppTokenKind::LeftParen
        && parse_balanced_token_group(p, CppSyntaxKind::ArgumentList).is_err()
    {
        // An unterminated group is not this shape at all: give the name back and let the caller report whatever
        // it reported before.
        p.rollback(checkpoint);
        return false;
    }

    m.complete(p);
    true
}

fn parse_class_body_members(p: &mut CppParser) -> ParseResult {
    // **How many `}` this body owes to members it gave up on.** A failed member that consumed a `{` without its
    // `}` — a requires-expression's body, a function body, a block — leaves the body's own brace counting one
    // short, and the next `}` (which belongs to the *failed member*) would be taken for the end of the class:
    // every member after it lands at file scope, and the file's only diagnostic appears on the leftover brace at
    // the end. That is `bits/alloc_traits.h` before the brace debt was paid.
    //
    // The debt is paid **before** the body is allowed to end, and the brace that pays it is read as an error node
    // — it is a token no rule claimed, which is what an error node is for. Closing the failed member's markers
    // ([`MarkerEventContainer::end_marks_to`], below) is the other half of the same repair and cannot do this
    // one: it decides what the *tree* looks like, not which `}` belongs to whom.
    let mut unclosed_braces = 0isize;

    while p.current_token() != CppTokenKind::RightBrace || unclosed_braces > 0 {
        if p.is_eof() {
            break;
        }

        // **The layout and the comments between two members belong to the class body.**
        //
        // `expect_semicolon` consumes a member's `;` and stops before a comment, so that a comment written below a
        // member 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 member would read
        // the comment as rubble: measured, an `ErrorNode` holding the newline and the indent, and the class body
        // carrying a syntax error it does not have.
        //
        // Emitting it here, before the member is read, is what puts it in the class body — which is the node that
        // encloses both the member above and the member below, and therefore the only honest answer to "which member
        // does this describe".
        p.emit_trivia_after_current_token();
        if p.is_eof() {
            break;
        }

        // A `}` with a debt outstanding closes the member that was abandoned, not this body.
        if p.current_token() == CppTokenKind::RightBrace {
            // **The body's own brace, reached after trivia.** The loop's condition is checked *before*
            // `emit_trivia_after_current_token`, so a comment written before the closing brace brings the cursor here
            // with **no debt** — and this branch used to take the brace anyway, decrementing the debt to `-1` and
            // filing the brace as an error node. The body then read on past its own end.
            //
            // Measured: `struct S { int x; // note\n};` swallowed the `}` and every declaration after it. On
            // libstdc++'s `<bits/basic_string.h>` the trailing `// TODO check __is_final` on `struct _Alloc_hider`
            // did exactly that, so all 1 100-odd members of `std::basic_string` after it were filed under
            // `basic_string::_Alloc_hider` and `members_of("std::string")` answered 27 typedefs and no function —
            // which is what made `size()`, `begin()` and `end()` on a `std::string` report "no member".
            if unclosed_braces <= 0 {
                break;
            }
            unclosed_braces -= 1;
            let error = p.mark(CppSyntaxKind::ErrorNode);
            p.bump();
            error.complete(p);
            continue;
        }

        let member_base = p.open_marks();

        // A **directive between two members** — the class-scope side of the seam `parse_try_statement` and
        // `parse_if_statement` document, and the one that decides whether a standard-library class has members at
        // all:
        //
        // ```cpp
        // class basic_string {
        //   …
        // protected:
        // #if __cplusplus < 201103L          // ← here
        //   typedef iterator __const_iterator;
        // #else
        //   typedef const_iterator __const_iterator;
        // #endif
        // ```
        //
        // Without this, the `#if` line was read as a **member declaration** whose declarator name is
        // `__cplusplus`, and every declaration after it became a child of that bogus member: the tree stayed
        // lossless and free of diagnostics, the class's *own* members were no longer members, and
        // `bits/basic_string.h` indexed seven typedefs and not one method — the
        // failure mode here is a wrong *shape*, which is why no error-based check could see it.
        //
        // Read as the node it is, then go round the loop again: the next token is a member, an access specifier, or
        // the closing brace, and each of those is a case the loop already handles.
        if p.current_token() == CppTokenKind::Hash {
            stats::parse_preprocessor_directive(p)?;
            continue;
        }

        if matches!(
            p.current_token(),
            CppTokenKind::PublicKeyword
                | CppTokenKind::PrivateKeyword
                | CppTokenKind::ProtectedKeyword
        ) {
            parse_access_specifier(p)?;
            continue;
        }

        // **An empty member declaration**: a `;` with nothing before it, which is legal (C++11 [class.mem]) and which
        // macros leave behind constantly — `_Atomic_integral_facade { ; ; using _Base = …` is what MSVC's `<atomic>`
        // expands `_STL_INTERNAL_STATIC_ASSERT(…);` to when the check is compiled out. It is not an error, and was
        // read as one: an `ErrorNode` per stray semicolon.
        if p.current_token() == CppTokenKind::Semicolon {
            p.bump();
            continue;
        }

        // A **member that is nothing but a macro invocation** — `Q_OBJECT`, `Q_PROPERTY(int x READ x)`,
        // `Q_ENUM(E)` — was read here, from a macro table. It cannot be any more: an attribute-like macro is
        // written where a member goes, but knowing that the *name* is one is macro evidence, and the text this
        // grammar reads has already been preprocessed. See [`at_a_macro_member`], which is kept as the question
        // without the answer.
        let before = p.current_token_index();
        // …and what the *brace balance* looked like before the attempt, so a failure can be charged for the
        // braces it consumed and never closed. See `unclosed_braces` above.
        let before_events = p.current_event_count();

        // # Why a **call-shaped member** is deliberately *not* read here
        //
        // The shape is real — `bits/stl_vector.h:464` writes `__glibcxx_class_requires(_Tp, _SGIAssignableConcept)`
        // on a line of its own, and its macro is defined in an *included* file (`bits/c++config.h`), so
        // [`at_a_macro_member`] cannot see it. Reading "a name, a group, and no `;`" as a macro **after the
        // declaration reading fails** was tried: the shape was asked before the attempt (a failed attempt does not
        // put the cursor back — a `parse_declaration` that gives up has already consumed the name and stopped on
        // the `(`), the checkpoint was rewound only on failure, and the reading is correct in isolation. It was
        // still **reverted**, because it is measurably worse than the recovery it replaces:
        //
        // ```text
        // declarations_in("std::basic_string")   398 → 287   (closure of <string>/<vector>/<map>/<algorithm>)
        // bits/stl_vector.h's first error        540 → 540   (it bought nothing on the file it was written for)
        // ```
        //
        // The reason is the one thing the error-node recovery does that a macro reading cannot: it **advances by
        // one token** and lets the loop try again, so a declaration this parser cannot read costs its own first
        // token and the members written after it are still members. A macro reading takes the name *and* the
        // group, and whatever that group was the beginning of is gone. The standard library charged 111 members
        // for it.
        //
        // So the question stands, and the evidence it needs is **macro evidence**, not
        // shape: either the macro environment (P3) or a source that reaches `bits/c++config.h`.

        // A member is a declaration; anything that is not gets wrapped in an error node so the
        // loop always advances.
        //
        // The nodes the failed attempt opened are closed **with** their end events
        // ([`MarkerEventContainer::end_marks_to`], not `close_marks_above`): a member declaration that fails
        // after consuming tokens — `_GLIBCXX20_CONSTEXPR void f(size_type) { }`, `int x = 1` with no `;` — would
        // otherwise leave an unpaired `NodeStart` that the tree builder balances at the end of the file, so the
        // abandonment swallowed every member written after it. See the note on `end_marks_to`.
        if parse_member(p).is_err() {
            // Two ways a failed member leaves a brace behind, and both have to be charged:
            //
            // * the attempt **stopped somewhere past the member's first token** — then what it consumed is in the
            //   events, and `brace_balance_since` reads it;
            // * the attempt **rolled back** (the declaration rule's speculative pass does that), so the cursor is
            //   back at the member's first token and the loop re-reads the member's tokens one at a time as rubble
            //   — the `{` among them is wrapped by the arm below, and *that* is where it is counted.
            unclosed_braces += p.brace_balance_since(before_events).max(0);
            p.end_marks_to(member_base);
            if p.current_token_index() == before {
                if p.current_token() == CppTokenKind::LeftBrace {
                    unclosed_braces += 1;
                }
                let error = p.mark(CppSyntaxKind::ErrorNode);
                p.bump();
                error.complete(p);
            }
        }
    }

    if p.current_token() == CppTokenKind::RightBrace {
        p.bump();
    } else {
        // An unclosed class body is the normal state of a file being edited.
        p.emit_missing_node();
    }

    Ok(CompleteMarker::empty())
}

fn access_specifier_kind(kind: CppTokenKind) -> CppSyntaxKind {
    match kind {
        CppTokenKind::PublicKeyword => CppSyntaxKind::PublicAccess,
        CppTokenKind::PrivateKeyword => CppSyntaxKind::PrivateAccess,
        _ => CppSyntaxKind::ProtectedAccess,
    }
}

/// Parse `public:`, `private:` or `protected:` — the keyword and its colon, and nothing else.
///
/// # Why the node is closed by hand
///
/// `bump` attaches the trivia *after* a token to whichever node is open, which is usually what you
/// want: `int  x` keeps its spaces together. For an access specifier it is not. Everything after
/// `public:` — the newline, an indented `/// doc`, the member below — would then be a child of the
/// access specifier rather than of the class body, and a consumer asking "which comment documents
/// this member?" would find nothing, because the only comment in the class body is the one the
/// access specifier swallowed.
///
/// So the keyword and colon are consumed directly and the node is closed before the trailing trivia
/// is emitted. The trivia still goes into the tree — it is the class body's — which is what keeps
/// the CST lossless.
fn parse_access_specifier(p: &mut CppParser) -> ParseResult {
    let access = p.mark(access_specifier_kind(p.current_token()));
    p.consume_current_token();
    // The layout between the keyword and its colon (`public :`) belongs to the access specifier. Without reading
    // it first the cursor sits on the whitespace, the colon is not found, and it is left as an `ErrorNode` — which
    // is how every access specifier of a stream spelled with spaces between tokens read.
    p.emit_trivia_after_current_token();
    p.consume_current_token_if(CppTokenKind::Colon);
    access.complete(p);

    // Whatever layout followed the colon belongs to the enclosing block, so it is emitted now that
    // the access node is closed. Only trivia can be here: `bump` is what emits it, and it has not
    // been called since the colon.
    p.emit_trivia_after_current_token();

    Ok(CompleteMarker::empty())
}

/// One class member: a member declaration, or a nested definition.
fn parse_member(p: &mut CppParser) -> ParseResult {
    // A nested class/struct/enum definition, or any other declaration, is handled uniformly by the
    // declaration parser — a member declaration *is* a declaration.
    parse_declaration(p)
}

/// Consume a `;`, or report it as missing without consuming anything.
pub fn expect_semicolon(p: &mut CppParser) -> ParseResult {
    // **A `;` a conditional branch already carried.** The construct just read was written once per branch and its
    // tail included the terminator, so there is nothing to ask for — see
    // [`CppParser::take_the_terminator_came_from_a_branch`], which is a *take* precisely so that one declaration's
    // answer cannot excuse the next one's missing `;`.
    if p.take_the_terminator_came_from_a_branch() {
        return Ok(CompleteMarker::empty());
    }

    if p.current_token() == CppTokenKind::Semicolon {
        // **The `;` goes in, the comment after it does not.**
        //
        // The semicolon is the declaration's own token and stays one — it is a child of this node like any other
        // token. What must not stay is a comment written *below* the declaration: `bump` would attach it here, because
        // this rule runs while the declaration is still open, and the declaration completes after it returns.
        // Measured, `struct S { int x; /// The y. int y; };` filed `/// The y.` under `x`, and the module note in
        // `tests/doc_owner.rs` says the shape should be the other one: a comment between two members belongs to the
        // class body.
        //
        // So the token is consumed directly and only the **layout** that follows it is emitted, leaving a comment for
        // whichever node encloses this declaration. The layout still goes in, which is what keeps the tree lossless —
        // see [`CppParser::emit_layout_after_current_token`], which is this and nothing more.
        //
        // This is the technique `parse_access_specifier` already uses for the same complaint one node over.
        p.consume_current_token();
        p.emit_layout_after_current_token();
        return Ok(CompleteMarker::empty());
    }

    p.emit_missing_node();
    Err(CppParseError::syntax_error_from(
        &t!("expected `;`"),
        p.current_token_range(),
    ))
}

/// Is the current token the start of something that can only be a declaration?
///
/// Used to skip the speculative pass when the answer is obvious. Being conservative is safe: a
/// `false` here only costs a backtrack.
/// Does the `decltype` at the cursor open a **type**, rather than the start of an expression?
///
/// `decltype(x)` is both, and the statement rule needs the answer before it chooses a reading:
///
/// ```text
/// decltype(x) y = 1;    a declaration — the `y` is a declarator
/// decltype(auto) x = f();   likewise
/// decltype(x) + 1;      an expression — the `+` is not one
/// decltype(x)::value    an expression — a `::` continues the *name*, not a declaration
/// ```
///
/// The test is the same speculative one the type table's callers use, and it is safe to make here because the
/// type reading is the one that gets rewound: the type-id is read, and the question is only what stands after
/// it. `parse_type_id` refuses `decltype(x) + 1` on its own — a `+` cannot continue a type — so the walk is
/// needed only for the shapes a type *can* be followed by and a declaration cannot, which is the `::` above.
fn a_decltype_here_is_a_type(p: &mut CppParser) -> bool {
    let checkpoint = p.checkpoint();
    let parsed = types::parse_type_id(p).is_ok();
    let followed_by_a_declarator = parsed && starts_a_declarator(p);
    p.rollback(checkpoint);
    followed_by_a_declarator
}

/// The kind of the first significant token **after** the one at the cursor.
///
/// The question a rule asks when the token at the cursor is a name and what decides the reading is what follows,
/// and it asks it about a **run**: libstdc++ writes two macro names where a declaration goes, and sometimes
/// three —
///
/// ```text
/// _GLIBCXX_BEGIN_NAMESPACE_VERSION
/// _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
///   template <typename> struct _List_iterator;    <- the run ends here, at `template`
/// ```
///
/// — so stopping at the first token after the name would answer "an identifier follows" and refuse a shape whose
/// answer is three tokens further on. A group after a name is stepped over as part of it (`MACRO(a) MACRO(b)
/// template<…>`), because the group is that invocation's.
///
/// What it does **not** do is decide anything: it returns the first token that is neither a name nor a group, and
/// the caller asks its own question about that. `Widget w;` and `x = 1;` both stop on their second token, which
/// is why the run is not a licence to skip a declaration.
pub(super) fn kind_after_the_run_of_names(p: &CppParser) -> CppTokenKind {
    let mut index = next_significant_index(p, p.current_token_index());

    loop {
        // A group belongs to the name in front of it, and the first pass is the name at the **cursor**:
        // `_GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)` is one invocation wherever it is asked about, so a scanner
        // that only stepped over groups *after* names it had already passed would stop on its own `(` and answer
        // `LeftParen` — which is not a declaration start, so the invocation was refused and the declaration
        // behind it came out as an error.
        if p.token_kind_at(index) == CppTokenKind::LeftParen {
            let Some(after) = index_after_the_group(p, index) else {
                return CppTokenKind::None;
            };
            index = significant_index_at(p, after);
            continue;
        }

        if p.token_kind_at(index) != CppTokenKind::Identifier {
            break;
        }
        index = next_significant_index(p, index);
    }

    p.token_kind_at(index)
}

/// The index one past the balanced group that opens at `index`, or `None` if it never closes.
///
/// The one place parentheses are counted, so that the four questions asked about "what follows a group" cannot
/// come to disagree about where a group ends.
fn index_after_the_group(p: &CppParser, index: usize) -> Option<usize> {
    let mut depth = 0isize;
    let mut index = index;

    while index < p.token_count() {
        match p.token_kind_at(index) {
            CppTokenKind::LeftParen => depth += 1,
            CppTokenKind::RightParen => {
                depth -= 1;
                if depth == 0 {
                    return Some(index + 1);
                }
            }
            CppTokenKind::Eof => return None,
            _ => {}
        }
        index += 1;
    }

    None
}

/// Can a declaration begin with this token kind?///
/// Factored out of [`starts_declaration`] because there are two starting points and one question:
/// `starts_declaration` asks it at the **cursor**, where a statement could also begin, and
/// [`stats::at_a_macro_that_stands_for_a_declaration`] asks it at the token **after a name**, where the
/// other reading is an expression that continues. Two copies of this list would be free to disagree about what
/// begins a declaration, and the list is a closed grammatical set — every entry says "a declaration may start
/// with this", which is a different kind of claim from the "which token kinds may be inside a header name" list
/// whose cost entry 22 records.
///
/// The kinds whose answer needs the tokens *after* them (`decltype`, and `concept`, which is contextual) are not
/// here: they stay in [`starts_declaration`], where that lookahead is available.
pub(super) fn can_begin_a_declaration(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        CppTokenKind::TypedefKeyword
            | CppTokenKind::UsingKeyword
            | CppTokenKind::NamespaceKeyword
            | CppTokenKind::TemplateKeyword
            | CppTokenKind::ExternKeyword
            | CppTokenKind::StaticAssertKeyword
            | CppTokenKind::ClassKeyword
            | CppTokenKind::StructKeyword
            | CppTokenKind::UnionKeyword
            | CppTokenKind::EnumKeyword
            | CppTokenKind::AlignasKeyword
            // Specifiers. Several of these also begin expressions — `const` cannot, `static` cannot, `auto`
            // cannot — which is what the caller's lookahead is for.
            | CppTokenKind::ConstKeyword
            | CppTokenKind::VolatileKeyword
            | CppTokenKind::ConstexprKeyword
            | CppTokenKind::StaticKeyword
            | CppTokenKind::InlineKeyword
            | CppTokenKind::VirtualKeyword
            | CppTokenKind::ExplicitKeyword
            | CppTokenKind::FriendKeyword
            | CppTokenKind::MutableKeyword
            | CppTokenKind::ThreadLocalKeyword
            // `register` belongs in this list for the same reason `static` does: a declaration may start with it,
            // and a *statement* that starts this way (`register int x = 0;` inside a body, `_mingw.h:607` at file
            // scope) is a declaration. It cannot begin an expression, so there is no second reading to weigh it
            // against — see [`CppSyntaxKind::RegisterSpec`].
            | CppTokenKind::RegisterKeyword
    )
}

pub fn starts_declaration(p: &mut CppParser) -> bool {
    match p.current_token() {
        // `concept` is **not** an anchor, and the omission is a decision: the word is contextual, and a statement
        // that begins with it is an ordinary use of the name — `concept = 2;`, `concept();`. A concept definition
        // always begins with `template`, which is already an anchor, so nothing is lost by leaving the bare word
        // to the expression rule. Anchoring it here is what made `void f() { concept = 2; }` demand a concept name
        // at the `=`.
        //
        // `alignas` is an anchor and is not an optimisation: without it `alignas(16) E e;` with an unqualified
        // name for the type reaches the expression rule, fails at `alignas`, and reports `expected primary
        // expression` against a token the specifier loop had just learned to read.
        //
        // `decltype(x) y = 1;` and `decltype(auto) x = f();` — and only those. A `decltype` **can** begin an
        // expression (`decltype(x) + 1;`), so it is not an anchor on its own; [`a_decltype_here_is_a_type`] asks
        // whether what follows the type-id is a declarator, which is the same question the two readings differ on.
        //
        // Without the anchor the declaration reading is never taken at all, because `decltype` is in
        // `is_expression_keyword` and no expression rule consumes it — so the statement rule read it as a name,
        // found `y` next, and reported `expected primary expression` against the `decltype` itself.
        CppTokenKind::DecltypeKeyword if a_decltype_here_is_a_type(p) => true,

        kind => can_begin_a_declaration(kind),
    }
}

/// Parse a destructor declaration: `~S();`, `~S() {}`, `virtual ~S() = default;`.
///
/// Entered from [`parse_declaration`] when the cursor is on the `~` of a declaration that has no specifiers —
/// which is the only way a destructor is ever written. The shape is a declaration of one init-declarator whose
/// declarator is the destructor name, so the nodes are the ordinary ones and a consumer finds the destructor
/// the same way it finds any other declaration.
///
/// `virtual ~S() = default;` and `inline ~S() {}` reach here *after* the specifier sequence has consumed
/// `virtual` or `inline`, because those are specifiers the sequence knows; the tilde after them is what stops
/// it. That is why this rule starts at the declarator rather than at a type.
fn parse_destructor_declaration(p: &mut CppParser) -> ParseResult {
    parse_declaration_starting_at_a_name(p, |p| {
        // A calling convention written before the `~` (see the dispatch in [`parse_declaration_here`]).
        if p.current_token() == CppTokenKind::Identifier {
            p.bump();
        }
        types::parse_declarator(p)
    })
}

/// Parse a **conversion** operator declaration: `operator int();`, `operator bool() const;`,
/// `operator std::string() const &;`, `operator const char*() = delete;`.
///
/// Same shape as a destructor declaration, for the same reason and with the same fix: the name is written
/// first and no type precedes it, so the specifier sequence — which runs first in the general rule — has
/// nothing to read and refuses the whole declaration.
///
/// What it did instead was worse than a refusal. `operator` was left as an error node, `int` was read as a
/// declaration of a variable named `int` — which also taught the file's type table that `int` is a type
/// *this file declared* — and the `()` became a further error. No error was reported, so the only symptom
/// was a member list missing its conversion operator.
///
/// Reached from [`parse_declaration`] when the declaration's first token is `operator`, which no other
/// declaration can begin with: an *overloaded* operator's name is preceded by its return type
/// (`Ops operator+(const Ops&)`), so by the time this dispatch is reached the payload cannot be one.
fn parse_conversion_operator_declaration(p: &mut CppParser) -> ParseResult {
    parse_declaration_starting_at_a_name(p, |p| {
        // The name, then the declarator's suffixes: the parameter list of the operator, its cv-qualifiers and
        // its ref-qualifier. `parse_declarator` cannot be used here because it would try to read a *declarator*
        // at a token that is the name — there is no type in front of it for a declarator to follow.
        let name = p.mark(CppSyntaxKind::Declarator);
        if let Err(err) = parse_name(p) {
            name.undo(p);
            return Err(err);
        }
        name.complete(p);
        types::parse_declarator_function_suffixes(p, p.current_event_count())
    })
}

/// Parse a **constructor** declaration: `Widget();`, `Widget(int size);`, `Widget(int) : base(1) {}`.
///
/// The third of the three declarations whose name begins the declaration, and the same shape as the other two: the
/// **name** first (which here is also the type), then the declarator's function suffixes — the parameter list, the
/// cv-qualifiers, the ref-qualifier. `parse_declarator` cannot be used for the name for the same reason the
/// conversion operator gives: it would try to read a *declarator* at a token that is the name, and there is no type
/// in front of it for a declarator to follow.
///
/// What this exists to fix is measured in the dispatch that calls it: a constructor used to be read as a declaration
/// of a nameless declarator, so the tree held no constructor at all.
fn parse_constructor_declaration(p: &mut CppParser) -> ParseResult {
    parse_declaration_starting_at_a_name(p, |p| {
        let name = p.mark(CppSyntaxKind::Declarator);
        if let Err(err) = parse_name(p) {
            name.undo(p);
            return Err(err);
        }
        // **The suffixes are completed *inside* the declarator**, which is what makes the node the same shape a
        // destructor's is — `Declarator > NameExpr + ParameterList`. Completing it before them left the parameter
        // list as the declarator's *sibling*, and `parameter_list_of` (token → innermost `Declarator` → its
        // `ParameterList` child) then answered `None` for every constructor. Measured: `SOURCE at 23: None`, with the
        // constructor's own name at 23.
        let declarator = types::parse_declarator_function_suffixes(p, p.current_event_count());
        name.complete(p);

        // **A member-initializer list belongs to the constructor**, and nothing else may see a `:` here: it comes
        // between the parameter list and the body (`Widget(int size) : size_(size) {}`), which is a position no other
        // declaration has. Read after the suffixes and before the body, which is where the language puts it.
        if declarator.is_ok() && p.current_token() == CppTokenKind::Colon {
            return parse_member_initializer_list(p).map(|_| CompleteMarker::empty());
        }
        declarator
    })
}

/// The tail every declaration shares: one init-declarator, then a body, then a `;`.
///
/// Factored out for exactly two callers — a destructor and a conversion operator — which are the two
/// declarations whose *name* begins the declaration and which therefore cannot go through the specifier
/// sequence. Having two copies of "the body or the `;`" is how the first copy of it came to report
/// `expected ';'` against the `}` of `~S() {}`.
fn parse_declaration_starting_at_a_name(
    p: &mut CppParser,
    parse_the_name: impl FnOnce(&mut CppParser) -> ParseResult,
) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Declaration);

    let declarator_from = p.current_event_count();

    if let Err(err) = parse_the_name(p) {
        p.close_marks_above(base);
        return Err(err);
    }
    // **The declaration's completed marker is kept**, because a body belongs to the declaration: `precede` opens a
    // declaration around the node those events already describe, and the body then joins it as the second child.
    //
    // Completing the declaration *before* the `{` without wrapping put the body beside it; reading the body with the
    // mark still open and then returning `CompleteMarker::empty()` dropped the declaration's marker altogether.
    // Measured on `struct A { A(int f) : x(f) { } };`: `Declaration@11..26` with `CompoundStat@26..42` as a following
    // sibling, so every constructor's parameters were invisible in its own body.
    let declaration = match finish_init_declarator(p, m, declarator_from) {
        Ok(declaration) => declaration,
        Err(err) => {
            p.close_marks_above(base);
            return Err(err);
        }
    };

    // A body, or its `;`. A declarator whose parameter list has been read is a *function*, so the brace after
    // it is a definition rather than a braced initializer.
    if p.current_token() == CppTokenKind::LeftBrace {
        let wrapped = declaration.precede(p, CppSyntaxKind::Declaration);
        if let Err(err) = parse_compound_stat(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(wrapped.complete(p));
    }

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

    Ok(declaration)
}

/// Is the qualified name at the cursor followed by an `=`, making this a `using` **alias**?
///
/// `using Base::method;` and `using Base::Alias = T;` begin the same way, and only the word at the end of the
/// name decides: an alias introduces a *type* and needs the type parser, while a using-declaration introduces a
/// name and does not. The scan walks the whole name — segments, template arguments and all — because the `=`
/// can be arbitrarily far away.
fn a_qualified_name_is_followed_by_an_equals(p: &CppParser) -> bool {
    for kind in p.peek_token_kind_at(0..96) {
        match kind {
            CppTokenKind::Assign => return true,
            // Anything that ends the statement or the name: there is no `=` in this one.
            CppTokenKind::Semicolon
            | CppTokenKind::LeftBrace
            | CppTokenKind::RightBrace
            | CppTokenKind::Eof
            | CppTokenKind::None => return false,
            _ => {}
        }
    }

    false
}

/// Parse a `using` declaration or directive, and `using` aliases.
pub fn parse_using_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::UsingDecl);

    expect_token(p, CppTokenKind::UsingKeyword)?;

    if matches!(p.current_token_text(), "namespace") {
        let directive = p.mark(CppSyntaxKind::UsingDirective);
        p.bump();
        parse_name(p)?;
        let _ = expect_semicolon(p);
        directive.complete(p);
        return Ok(m.complete(p));
    }

    // `using enum E;` — C++20's using-enum-declaration (libstdc++'s `compare:710`). The `enum` keyword is the
    // whole evidence and it is unambiguous: an alias is `using NAME = …`, and the name of a using-*declaration*
    // cannot be the keyword `enum`. What follows is the enum's **name** — an identifier or a qualified name —
    // and it is read as one name, exactly like `using ns::f;` below: there is no type and no declarator here.
    //
    // Nothing is *recorded* about it, and that is deliberate: the declaration introduces the enum's
    // **enumerators** into the scope, not a type name, and this parser records only what a name is — see the
    // comment on the alias form. Recording `E` as a type would be recording something that was already true.
    if p.current_token() == CppTokenKind::EnumKeyword {
        p.bump();
        if let Err(err) = parse_name(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        if let Err(err) = expect_semicolon(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // `using typename Base::value_type;` — a using-declaration that names a **type** of a dependent base. The
    // keyword is the whole evidence, as `enum` is above: an alias is `using NAME = …`. MSVC's `<atomic>` writes
    // it in every specialization of `_Atomic_integral`. Left to the alias reading it failed with `expected a name`
    // that nobody reported, and the class body it stood in lost every member after it.
    if p.current_token() == CppTokenKind::TypenameKeyword {
        p.bump();
        if let Err(err) = parse_name(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        if let Err(err) = expect_semicolon(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // `using Alias = Type;` — an alias introduces a type name, and the parser needs it for the same reason a
    // `class` name is needed: `Alias a(1);` is a declaration and `f(1);` is a call.
    //
    // A using-*declaration* (`using ns::f;`) introduces whatever `f` already was, which this table cannot know,
    // so only the alias form is recorded. Recording the other would be recording a name as a type on the
    // strength of nothing.
    let alias_name = if p.current_token() == CppTokenKind::Identifier {
        Some(p.current_token_text().to_string())
    } else {
        None
    };

    // A using-*declaration*: `using ns::f;`, `using Base::method;`. What is introduced is the last segment of
    // a qualified name, and there is no type and no declarator — so the qualified name is read as **one** name
    // and the statement ends there.
    //
    // Read as a type-id instead, as it was, `Base::method` split into a type and a declarator: the type parser
    // walks `Base::` as a nested name specifier and then takes `method` for the declarator's name, and the
    // semicolon afterwards is a parameter list that never comes. The statement was reported as broken, and the
    // only spelling that worked was one qualifying a *type* — which is the alias form, not this one.
    if p.current_token() == CppTokenKind::Identifier
        && p.peek_next_token() == CppTokenKind::Scope
        && !a_qualified_name_is_followed_by_an_equals(p)
    {
        let name = p.mark(CppSyntaxKind::NameExpr);
        p.bump(); // the first segment
        // The rest of the name, in a node of its own *inside* this one: `parse_name` opens a `NameExpr` for
        // what it reads, and a consumer asking a `NameExpr` for its text gets the text of its own tokens — so
        // wrapping the tail directly would report the first segment as the name and the qualifier as
        // everything else. `using ns::f;` introduces `f`, and this is what makes the tree say so.
        let rest = p.mark(CppSyntaxKind::NameExpr);
        if let Err(err) = types::parse_name(p) {
            rest.undo(p);
            name.undo(p);
            p.close_marks_above(base);
            return Err(err);
        }
        rest.complete(p);
        name.complete(p);

        if let Err(err) = expect_semicolon(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

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

    // An attribute on the alias's name: `using T [[deprecated]] = int;`. Between the name and the `=`, which is
    // the same position an attribute takes on any other declarator — see `finish_init_declarator` — and the one
    // this rule does not share with it, because an alias has no declarator node of its own.
    if let Err(err) = types::parse_attribute_specifiers(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // …and the **macro** spelling of the same attribute, which is what `type_traits` writes and what the standard
    // library spells nearly every other deprecation with:
    //
    // ```cpp
    //   template<class _Tp, size_t _Len>
    //     using aligned_storage_t _GLIBCXX23_DEPRECATED
    //       = typename aligned_storage<_Len, _Alignof<_Tp>>::type;
    // ```
    //
    // A name between an alias's own name and its `=` cannot be anything else — the next token is the `=` or it is
    // not an alias — so it is read by [`eat_a_macro_suffix`], the same reader the declarator's suffixes use, and
    // which already knows a macro invocation with arguments from one without.
    while eat_a_macro_suffix(p) {}

    // The type's **suffixes**: `using Arr = int[4];`, `using Fn = int(char);`, `using P = int(*)[4];`.
    //
    // A type-id reads the abstract declarator — the pointers, references and cv-qualifiers — and stops
    // before the array and function parts, because everywhere else a type-id appears those belong to
    // whatever encloses it. In an alias there is nothing enclosing it: the `=` was the last thing before
    // the type and the `;` is the last thing after it, so anything left is part of the type.
    //
    // That asymmetry is why `typedef int Arr[4];` worked while `using Arr = int[4];` did not — the typedef
    // rule reaches the suffixes through `parse_declarator`, and this rule had no equivalent step.
    //
    // The definition is read **once per branch** (`#if A = X; #else = Y; #endif`), which is how
    // `make_integer_sequence` is written; see [`parse_a_definition_per_branch`].
    let mut declared = false;
    let ended = parse_a_definition_per_branch(p, |p| {
        if !declared {
            if let Some(name) = &alias_name {
                p.declare_type_name(name);
            }
            declared = true;
        }

        // **`MACRO name` — a type-id that is one identifier, with another one after it.**
        //
        // An alias has **no declarator**, so `using A = X Y;` declares nothing: an identifier standing after the
        // type-id can only be the name the type-id was cut short of. That is what makes this the one place the
        // shape resolves without guessing — `X Y;` in a declaration is a type and a declarator, and the same
        // tokens here are one type.
        //
        // **Both halves of the condition are measured.** `_STD` is a macro — `yvals.h` defines it as `::std::`,
        // and a file parsed on its own has not read that header — so `/array`'s aliases arrive as two identifiers
        // in a row, the type-id ends at `_STD`, the specifier sequence takes that for the type, and the real name
        // becomes a nested `Declaration` from recovery: the class summarised to **one** fact, none of its members
        // were facts, and the 2000 lines after it produced nothing.
        //
        // Taking *any* identifier that followed was the first attempt and it cost `<vector>` dearly — 538
        // declarations covering the file became 96 covering half — because an alias there reaches a type this
        // rule had already read correctly and the extra read consumed what came after. Requiring the type-id to
        // have been **exactly one identifier** is what separates the two: a macro prefix is a lone identifier,
        // while `unsigned int` and `_Ty*` are not.
        //
        // Counted over **non-trivia tokens**, because whitespace is a token in this lexer: `_STD rt` is three
        // tokens and one name. The first version compared raw indices and so never fired at all — measured, the
        // alias's `type_of` stayed `_STD` and `<array>` did not move.
        let before_the_target = p.current_token_index();
        parse_type_id(p)?;
        let consumed: Vec<CppTokenKind> = (before_the_target..p.current_token_index())
            .map(|at| p.token_kind_at(at))
            .filter(|kind| !is_declaration_trivia(*kind))
            .collect();
        let the_target_was_one_name =
            matches!(consumed.as_slice(), [CppTokenKind::Identifier]) && !p.has_error();

        // **…and the second spelling of the same thing: a calling convention.** `void __CC(void*)` is a function
        // type whose convention is a macro, and the type-id stops at `__CC` for the same reason it stops at
        // `_STD` — the macro is defined in a header this file has not read. Here the target has already ended in
        // something else (`void*`, `void`), so the "one name" test above does not fire and the alias was left
        // with `__CC(const void*);` hanging off it and no `;` to end on.
        //
        // ```cpp
        // using _Destroy_fn = void __CLRCALL_PURE_OR_CDECL(void*) _NOEXCEPT_FNPTR;   // <any>
        // using _Copy_fn    = void* __CLRCALL_PURE_OR_CDECL(const void*);
        // ```
        //
        // The discriminator is the **`(` after the identifier**: `T MACRO(args)` is a function type, while
        // `unsigned int` and `_Ty*` — the shapes the narrow test was written for — have nothing of the sort. It
        // is what keeps this from re-introducing the fault that cost `<vector>` 442 declarations.
        let a_convention_follows = p.current_token() == CppTokenKind::Identifier
            && p.peek_token_kind_at(1..4).first().is_some_and(|_| {
                (1..4).any(|at| {
                    p.token_kind_at(p.current_token_index() + at) == CppTokenKind::LeftParen
                })
            });

        if (the_target_was_one_name || a_convention_follows)
            && p.current_token() == CppTokenKind::Identifier
        {
            parse_type_id(p)?;
        }

        if (p.current_token() == CppTokenKind::LeftBracket
            || p.current_token() == CppTokenKind::LeftParen)
            && let Err(err) = types::parse_declarator_suffixes(p)
        {
            return Err(err);
        }

        Ok(CompleteMarker::empty())
    });

    match ended {
        Err(err) => {
            p.close_marks_above(base);
            return Err(err);
        }
        // `true` means the branch's own `;` was the declaration's, so there is nothing left to ask for.
        Ok(ended) if !ended => {
            if let Err(err) = expect_semicolon(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }
        Ok(_) => {}
    }

    Ok(m.complete(p))
}

/// **One definition per branch**: `#if … = X; #else … = Y; #endif`.
///
/// Two constructs are written this way in libstdc++, and in both the *name* is read before any of it — so the
/// directive arrives between the name and its `=`, which is a position where nothing else can stand:
///
/// ```cpp
/// template<typename _Tp, _Tp _Num>
///   using make_integer_sequence                     // bits/utility.h:174
/// #if __has_builtin(__make_integer_seq)
///       = __make_integer_seq<integer_sequence, _Tp, _Num>;
/// #else
///       = integer_sequence<_Tp, __integer_pack(_Num)...>;
/// #endif
///
/// template<typename _Tp>
///   concept __is_signed_int128                      // bits/iterator_concepts.h:615
/// #if __SIZEOF_INT128__
///       = same_as<_Tp, __int128>;
/// #else
///       = false;
/// #endif
/// ```
///
/// `payload` reads everything after the `=` **except** the `;`, which is the branch's own. The return value says
/// whether that `;` was consumed here: it is when a definition was read and ended with one, and the caller then
/// has nothing left to ask for — while a declaration that never reached a `=` still needs its `;` reported the
/// ordinary way.
fn parse_a_definition_per_branch(
    p: &mut CppParser,
    mut payload: impl FnMut(&mut CppParser) -> ParseResult,
) -> Result<bool, CppParseError> {
    let mut ended_with_a_semicolon = false;

    loop {
        // A directive **before** the `=`, and the one that closes a branch and opens the next.
        while p.current_token() == CppTokenKind::Hash {
            stats::parse_preprocessor_directive(p)?;
        }

        if p.current_token() != CppTokenKind::Assign {
            break;
        }
        p.bump();

        payload(p)?;

        if p.current_token() != CppTokenKind::Semicolon {
            ended_with_a_semicolon = false;
            break;
        }
        p.bump();
        ended_with_a_semicolon = true;
    }

    Ok(ended_with_a_semicolon)
}

/// Parse a `typedef` declaration: `typedef int MyInt;`, `typedef WCHAR *PWCHAR, *LPWCH;`.
///
/// # The list, and why it is not one declarator
///
/// A `typedef` is a declaration specifier, so what follows it is an ordinary **init-declarator-list**: C and C++
/// headers introduce several names in one line everywhere, and the pointer aliases in particular are always
/// written this way:
///
/// ```cpp
/// typedef WCHAR *PWCHAR, *LPWCH, *PWCH;      winnt.h, and this shape appears hundreds of times in it
/// typedef struct _GUID *LPGUID, GUID, *PGUID;
/// ```
///
/// This rule read exactly **one** declarator and then insisted on `;`, so every one of those lines failed at the
/// comma. The cost was not the line: the failure left the rest of the declaration to the recovery, which is where
/// `winnt.h`'s 417 errors came from — and, through them, the loss of eight `#endif`s that made the whole file's
/// conditional nesting unusable. One loop.
///
/// Each declarator introduces its **own** name, and each is recorded as a type name: without that, `PWCHAR p;`
/// later in the file reads as an expression rather than as a declaration.
pub fn parse_typedef_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::TypedefDecl);

    expect_token(p, CppTokenKind::TypedefKeyword)?;

    // The rest is a declaration without the keyword, so reuse the same machinery.
    if let Err(err) = types::parse_decl_specifier_seq(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    loop {
        // `typedef int Integer;` makes `Integer` a type name, which is the whole point of the declaration — and
        // the name is what the declarator introduces, so it is read from there rather than from the specifiers.
        // Read off the events the declarator produces, because it is not always the token under the cursor:
        // `*PWCHAR` puts it after a `*`, `(*F)(int)` inside parentheses.
        let declarator_from = p.current_event_count();

        if let Err(err) = types::parse_declarator(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        if let Some(name) = p.the_name_a_declarator_introduced(declarator_from) {
            p.declare_type_name(&name);
        }

        // **Attributes written after the declarator**, which this rule was missing while the ordinary
        // declaration path had them (see the note in `finish_init_declarator`). GCC's own intrinsic headers are
        // where it shows, eight of them in the closure, and it is the same construct their whole type zoo is
        // built from:
        //
        // ```c
        // typedef int __v4si_u __attribute__ ((__vector_size__ (16), __may_alias__, __aligned__ (1)));
        // typedef short __v32hi __attribute__ ((__vector_size__ (64)));
        // typedef int v4 [[deprecated]];                       // the standard spelling fails the same way
        // ```
        //
        // Both spellings go through [`types::parse_attribute_specifiers`], which is the point of that
        // rule reading all three spellings into one node: the position is the same, so this is one line rather
        // than one per compiler. Without it the `;` was never reached — the attribute was rubble and the
        // declaration reported `expected ;` against its own name.
        if let Err(err) = types::parse_attribute_specifiers(p) {
            p.close_marks_above(base);
            return Err(err);
        }

        // **One initializer for the list, not one per declarator**: `typedef int A, B;` has no `=` at all, and
        // `typedef int *p = nullptr;` is the one shape where an `=` may follow a typedef's declarator — which the
        // ordinary declaration rule reads with the same rule, because it is the same grammar.
        if p.current_token() == CppTokenKind::Assign
            && let Err(err) = parse_initializer_clause(p)
        {
            p.close_marks_above(base);
            return Err(err);
        }

        if p.current_token() != CppTokenKind::Comma {
            break;
        }
        p.bump();
    }

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

    Ok(m.complete(p))
}

/// Parse a `static_assert(...)` declaration.
pub fn parse_static_assert(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::DeclStat);

    expect_token(p, CppTokenKind::StaticAssertKeyword)?;

    if p.current_token() == CppTokenKind::LeftParen {
        p.bump();
        if let Err(err) = parse_expr(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        // The message is optional in C++17 and later.
        if p.current_token() == CppTokenKind::Comma {
            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::RightParen) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

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

    Ok(m.complete(p))
}

/// Parse a namespace definition: `namespace a::b { ... }` or `namespace a = b;`.
///
/// # The attribute between the keyword and the name
///
/// C++17 spells a namespace definition as `namespace attribute-specifier-seq(opt) identifier { … }`, and MSVC's
/// own STL uses the slot: `cstdint:55` is `namespace _DEPRECATE_TR1_NAMESPACE tr1 {`, where the macro is
/// `[[deprecated("warning STL4002: …")]]` (`yvals_core.h:908`). Read against the **cooked** stream — which is
/// what the compiler sees and what the `cstdint` line actually means — the declaration arrives as
/// `namespace [[deprecated(…)]] tr1 {`, so a rule that does not read the attribute reports
/// `expected primary expression` at the first `[`, and everything after it in the header is an error node.
///
/// It is also spellable in the file's own text (`namespace [[deprecated]] a { }`), which is the shape the test
/// asserts — a gap that only the cooked reading shows is still a gap, but a gap that *only* shows there is much
/// easier to lose.
pub fn parse_namespace_declaration(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::NamespaceDecl);

    expect_token(p, CppTokenKind::NamespaceKeyword)?;

    // `at_an_attribute` is the guard that makes this safe: an ordinary name is not an attribute, so the name and
    // the `_GLIBCXX_VISIBILITY(default)` head below are untouched by it — only `[[…]]`, `__attribute__((…))` and
    // `__declspec(…)` are read, and all three are attributes at exactly this position.
    let _ = types::parse_attribute_specifiers(p);

    // A namespace alias: `namespace fs = std::filesystem;`
    if p.current_token() == CppTokenKind::Identifier && p.peek_next_token() == CppTokenKind::Assign
    {
        p.bump();
        p.bump();
        parse_name(p)?;
        let _ = expect_semicolon(p);
        return Ok(m.complete(p));
    }

    // An anonymous namespace.
    if p.current_token() != CppTokenKind::LeftBrace {
        // `inline` before the name is part of the declaration; the parser reaches this with it
        // already consumed as a specifier, so an identifier here is the name.
        if p.current_token() == CppTokenKind::Identifier {
            // **A nested namespace definition may spell `inline` on an inner segment.** C++17's grammar
            // (`namespace A::B`) allows `inline` only in front of the whole name, but GCC's own `std` module
            // writes it on every segment —
            //
            // ```cpp
            // export namespace std::inline literals::inline chrono_literals { … }      // bits/std.cc:837
            // ```
            //
            // — and GCC accepts it. `parse_name` stops at the `inline` with "expected a name", so the whole
            // declaration failed, and each of the four such blocks in `bits/std.cc` was a parse error (measured:
            // 4 errors in that file, all of them here).
            if a_segment_below_is_inline(p) {
                parse_a_nested_namespace_name(p);
            } else {
                parse_name(p)?;
            }
        }
    }

    // A macro invocation between the name and the `{`. See the rule for why this is read by shape.
    if p.current_token() != CppTokenKind::LeftBrace {
        eat_namespace_head_macros(p);
    }

    if p.current_token() == CppTokenKind::LeftBrace {
        if let Err(err) = parse_stats_block(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    let _ = expect_semicolon(p);
    Ok(m.complete(p))
}

/// **Is there an `inline` in front of an inner segment of a nested namespace definition** — `A::inline B`?
///
/// The scan is the name grammar itself (`Identifier (:: Identifier)*`), so a `::` that starts something else —
/// `namespace A::B` where `B` is missing — is not claimed, and the ordinary name rule reports it as before.
fn a_segment_below_is_inline(p: &CppParser) -> bool {
    let mut at = 1usize; // past the first segment, which the caller has in hand
    while p.peek_token_kind_at(at..at + 1).as_slice() == [CppTokenKind::Scope] {
        at += 1;
        if p.peek_token_kind_at(at..at + 1).as_slice() == [CppTokenKind::InlineKeyword] {
            return true;
        }
        if p.peek_token_kind_at(at..at + 1).as_slice() != [CppTokenKind::Identifier] {
            return false;
        }
        at += 1;
    }
    false
}

/// Read a nested namespace name as **one flat `NameExpr`** — the shape `parse_name` builds for `A::B` — while
/// accepting an `inline` in front of any segment. See the call site for the file this comes from.
fn parse_a_nested_namespace_name(p: &mut CppParser) {
    let name = p.mark(CppSyntaxKind::NameExpr);
    loop {
        if p.current_token() == CppTokenKind::InlineKeyword {
            p.bump();
        }
        if p.current_token() != CppTokenKind::Identifier {
            break;
        }
        p.bump();
        if p.current_token() != CppTokenKind::Scope {
            break;
        }
        p.bump();
    }
    name.complete(p);
}

/// Read the macro-shaped tokens that may sit between a namespace's name and its `{`.
///
/// `namespace std _GLIBCXX_VISIBILITY(default) {` is how **every** libstdc++ header opens — the measured closure
/// has it in one header after another, and it is the first thing in the file — and `_GLIBCXX_VISIBILITY(V)`
/// expands to *nothing at all* on the toolchain this was measured on (`bits/c++config.h` defines
/// `_GLIBCXX_PSEUDO_VISIBILITY(V)` empty there; it is `__attribute__((__visibility__("default")))` only where the
/// toolchain has visibility attributes). So the head the compiler sees is `namespace std {`, and what stands
/// between the name and the brace is a macro invocation. Not reading it cost *the whole file*: the head failed,
/// and every declaration after it came out as an error node — 190 diagnostics in `bits/stl_algobase.h` alone.
///
/// # Why by shape, and not by a table
///
/// The name is `#define`d in `c++config.h`, an **included** header, so nothing the parser can be handed knows it:
/// this file's own `MacroNames` never saw the definition, and the external hook (`symbols.rs`) is not wired to a
/// file's includes — where that connection is called out as the expensive layer it is.
/// What *is* knowable here is the shape, and the shape settles it: **no valid C++ has anything between a
/// namespace's name and its `{`** — the two readings are `namespace std {` and an error — so accepting a macro
/// costs nothing, which is the fallback side of the rule: both readings are wrong, so pick the cheaper one.
///
/// # What it does not accept
///
/// A name, or a name and one balanced group, and nothing else. And the scan is **abandoned unless it ends on
/// `{`**: a head that does not close where this expects gives every token back, and the declaration rule then
/// reports exactly what it reported before. That is what keeps a typo — `namespace std ;` — from being read as a
/// namespace with a macro in it.
fn eat_namespace_head_macros(p: &mut CppParser) -> bool {
    let checkpoint = p.checkpoint();
    let mut ate_anything = false;

    while p.current_token() == CppTokenKind::Identifier {
        p.bump();
        ate_anything = true;

        if p.current_token() == CppTokenKind::LeftParen {
            // The group is the invocation's argument list. The same reader a class-member macro call uses, so the
            // two cannot come to disagree about where an invocation ends.
            if parse_balanced_token_group(p, CppSyntaxKind::ArgumentList).is_err() {
                p.rollback(checkpoint);
                return false;
            }
        }
    }

    if !ate_anything || p.current_token() != CppTokenKind::LeftBrace {
        p.rollback(checkpoint);
        return false;
    }

    true
}

/// Parse a `{ ... }` block whose contents are declarations, reusing the statement machinery.
fn parse_stats_block(p: &mut CppParser) -> ParseResult {
    let _base = p.open_marks();
    let m = p.mark(CppSyntaxKind::CompoundStat);

    expect_token(p, CppTokenKind::LeftBrace)?;
    parse_stats(p);

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

    Ok(m.complete(p))
}

/// Parse the block of a linkage specification: `extern "C" { void f(); }`.
///
/// The linkage itself — the `extern` and its string — has already been consumed as a decl-specifier by
/// [`types::parse_decl_specifier_seq`], so what is left is the block. It is a namespace-shaped
/// construct rather than a statement block: everything inside is a declaration, and the names it introduces
/// are visible afterwards, which is why it is parsed by the declaration rule rather than
/// [`parse_stats_block`].
///
/// # Why it does not enter a scope, although every other brace does
///
/// A linkage specification is **not** a scope for names — C++ says the declarations inside it are visible
/// outside exactly as if the block were not there, and only their *language linkage* is affected. So the two
/// things every other braced construct does here are wrong for it, and it does neither:
///
/// * no name scope, so a type declared inside is a type name afterwards (what the standard says);
/// * no *body*, which is what `is_inside_a_body` reports — and this one had teeth. Entering a scope made the
///   parser believe it was inside a body, and the macro-from-a-header rules (`at_a_macro_that_stands_for_a_
///   declaration`, `a_macro_definition_follows`) refuse inside a body by design. Most of libstdc++ is written
///   inside `extern "C++" { namespace std { … } }`, so `_GLIBCXX_BEGIN_NAMESPACE_VERSION` was read as an ordinary
///   name and the declaration after it as an expression: the first error of `cwchar` was
///   ``expected `;` after expression`` at `using ::wint_t;`, and `cstdlib` failed the same way at `using ::div_t;`.
pub fn parse_linkage_block(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::CompoundStat);

    expect_token(p, CppTokenKind::LeftBrace)?;

    // A *block* rather than a class body: `extern "C" { int bits : 3; }` is not a member declaration, and the
    // innermost brace is what the bit-field rule asks about. That question is about the brace, not about scopes,
    // which is why this one stays.
    p.enter_block_body();

    // **The brace debt**, the same one the class body keeps and `parse_stats` keeps for statements — the third
    // container that reads declarations until a `}`, and the third time this file pays for the same thing. A
    // declaration that fails after consuming a `{` leaves the block one brace short, and the next `}` (which
    // closes *that declaration*) would end the linkage block instead. See `parse_class_body_members` for the whole
    // argument.
    let mut unclosed_braces = 0isize;

    while p.current_token() != CppTokenKind::RightBrace || unclosed_braces > 0 {
        if p.is_eof() {
            break;
        }

        // A `}` with a debt outstanding closes the declaration that was abandoned, not this block.
        if p.current_token() == CppTokenKind::RightBrace {
            // The same guard the class body needed — see `parse_class_body_members`: the loop's condition was checked
            // before the trivia was emitted, so a comment before the closing brace arrives here with no debt, and
            // taking the brace would end the block nowhere and read on past it.
            if unclosed_braces <= 0 {
                break;
            }
            unclosed_braces -= 1;
            let error = p.mark(CppSyntaxKind::ErrorNode);
            p.bump();
            error.complete(p);
            continue;
        }

        // **A directive is not a declaration**, and this loop has to say so. Every C header in the world writes
        // its linkage block with the conditional *inside* it:
        //
        // ```cpp
        // #ifdef __cplusplus
        // extern "C" {
        // #endif
        // …
        // #ifdef __cplusplus
        // }
        // #endif
        // ```
        //
        // which is `winnt.h`'s shape at line 11 and every MinGW header's after it. Without this branch the `#endif`
        // went to `parse_declaration`, failed, got wrapped in an `ErrorNode` **one token wide**, and `endif` was
        // then read as the next declaration's *type name*: `endif int x;` is a declaration of `x` with type
        // `endif int`. From there nothing could close the block — the `}` that ends the linkage was consumed by
        // some later declaration — so the loop ran to the end of the file: one `CompoundStat` covering 387 000
        // bytes of `winnt.h`, every directive inside it an `ErrorNode`, and *eight* `#endif`s that the directive
        // scanner never saw. Measured on the 455-file closure: this one construct is why the whole file's
        // conditional nesting was unusable, which is what the branch rule needs.
        if p.current_token() == CppTokenKind::Hash {
            // A directive that does not read is not a reason to lose the block.
            let directive_base = p.open_marks();
            if let Err(err) = stats::parse_preprocessor_directive(p) {
                p.end_marks_to(directive_base);
                p.push_error(err);
            }
            continue;
        }

        let member_base = p.open_marks();
        let before = p.current_token_index();
        let before_events = p.current_event_count();
        if parse_declaration(p).is_err() {
            // **With their end events**, for the third time in this file's history (see `end_marks_to`): a
            // declaration that fails *after* consuming tokens — and inside a linkage
            // block there are hundreds of them — would otherwise leave an unpaired `NodeStart` that the tree
            // builder balances at the **end of the stream**. The price is not one declaration: the failed one
            // swallows every declaration after it, which swallows the `}` that closes the linkage block, which
            // swallows the rest of the file. `winnt.h` came out as sixty nested `TypedefDecl`s all ending at EOF,
            // and with them the whole file's directive structure — which is what made its conditional nesting
            // unusable for the macro layer.
            unclosed_braces += p.brace_balance_since(before_events).max(0);
            p.end_marks_to(member_base);
            // Always advance: a declaration that consumed nothing would spin this loop forever. A `{` among the
            // tokens that nothing claimed is charged, because it opens something this declaration never finished.
            if p.current_token_index() == before {
                if p.current_token() == CppTokenKind::LeftBrace {
                    unclosed_braces += 1;
                }
                let error = p.mark(CppSyntaxKind::ErrorNode);
                p.bump();
                error.complete(p);
            }
        }
    }

    p.leave_block_body();

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

    let _ = base;
    Ok(m.complete(p))
}

/// Is the cursor on `extern` followed by a string literal — the head of a linkage specification?
///
/// Whether the declaration this appears in really is a specifier of one. `extern "C"` is the only form of
/// `extern` that is followed by a string, so the test is exact rather than a heuristic: an ordinary
/// `extern int x;` cannot reach it.
pub fn starts_a_linkage_specification(p: &CppParser) -> bool {
    p.current_token() == CppTokenKind::ExternKeyword
        && matches!(
            p.peek_token_kind_at(1..2).first(),
            Some(&CppTokenKind::StringLiteral)
        )
}

/// Parse a linkage specification: `extern "C" void f();` or `extern "C" { ... }`.
///
/// It is a declaration of its own rather than a specifier of the one after it, and that is what this rule
/// exists to express. Both grammars are legal C++, so the choice is about what the tree means:
///
/// * as a **specifier**, the declaration node would wrap a whole nested declaration, so `extern "C" void f();`
///   would be a `Declaration` whose `DeclSpecifierSeq` contains another `Declaration`, and a consumer walking
///   top-level declarations would find `f` one level deeper than everything else. The trailing `;` would then
///   have to be consumed by one of the two, and whichever one did not would report it as missing;
/// * as a **declaration**, the node says what the construct is — `extern "C"` applies to a declaration — and
///   the declaration it introduces is its child, so both readings a consumer wants ("what does this linkage
///   cover?" and "what is declared here?") are one level from the top.
fn parse_linkage_specification(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Declaration);

    let specifiers = p.mark(CppSyntaxKind::DeclSpecifierSeq);
    let linkage = p.mark(CppSyntaxKind::ExternSpec);
    p.bump(); // `extern`
    p.bump(); // the string literal
    linkage.complete(p);
    specifiers.complete(p);

    if p.current_token() == CppTokenKind::LeftBrace {
        if let Err(err) = parse_linkage_block(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    // One declaration shares the linkage, and its own `;` ends the whole construct — which is why nothing
    // here looks for a second one.
    if let Err(err) = parse_declaration(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}