cpp_parser 0.2.0

A lossless C++ parser over the preprocessed text: the tree every layer above it reads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
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
use crate::{
    grammar::{
        ParseResult,
        cpp::{decls, stats, types},
    },
    kind::{CppSyntaxKind, CppTokenKind},
    parser::{CppParser, MarkerEventContainer},
    parser_error::CppParseError,
    symbols::SymbolKind,
};

use super::{at_requires, expect_token};

/// 操作符优先级定义
/// 数值越高,优先级越高
///
/// `p` is consulted for one thing: whether a `>` at the cursor is a greater-than operator or the `>` that closes
/// the template-argument-list the cursor is in. See [`CppParser::greater_than_is_an_operator`], which is the
/// standard's rule — the **first non-nested** `>` closes the list — expressed as the bracket depth a list began at
/// against the bracket depth now.
///
/// **The parentheses are what make it a comparison, and getting that wrong is what this file used to do.** The
/// question was once spelled "is a template argument list open at all", on the belief that `C<(1) >= 2>` was
/// accepted while `C<(1 > 2)>` was not. That belief is false, and `cl.exe` settles it: `bc<(1 > 2)>` reports
/// `C2974` — *"`T`: the template argument is invalid, a type was expected"* — which is a **semantic** error about
/// `1 > 2` not being a type, and **no syntax error at all**. The grammar has to parse it, and it does once the
/// `>` inside the parentheses is an operator again.
///
/// **Only the two spellings that are a closer are ever refused**, and only at a depth where they close: `>` and
/// `>>`. `>=` and `>>=` contain a `>` but are not one, and g++ reads them as operators even where a list is open —
/// `C<sizeof(int) >= 4>` is accepted, and `enable_if_t<(__i >= sizeof...(_Types))>` is written that way in
/// `bits/tuple`. Nothing is lost by allowing them: the list still closes, because an argument that ends at a `>=`
/// at the top level of the list is a **type**, and a type argument is read by the type reading, which stops before
/// it and leaves the `>=` to [`crate::grammar::cpp::types::split_closing_angle`] — the reading `C<D<int>= 3>`
/// needs, and the one g++ reports as "'`>=` should be '`> =`' to terminate a template argument list".
fn get_operator_precedence(p: &CppParser, token: CppTokenKind) -> Option<u8> {
    // **The `>>>` that closes a CUDA launch configuration is not an operator.** Inside the configuration the
    // expressions are ordinary ones — `a > b` compares and `a >> b` shifts — so what has to stop the loop is the
    // *run of three*, which no C++ operator is spelled with. See
    // [`CppParser::at_the_end_of_a_launch_configuration`].
    if matches!(token, CppTokenKind::Greater | CppTokenKind::RightShift)
        && p.at_the_end_of_a_launch_configuration()
    {
        return None;
    }
    // A C++ **alternative operator spelling** arrives as an `Identifier`, because the lexer has no keyword for
    // it — so it is recognised by its text and then treated as the operator it stands for. Doing it here, at the
    // one place that asks "is this a binary operator", is what makes `and`, `bitand` and the rest work without
    // a token kind each; see [`the_alternative_operator`].
    let token = the_alternative_operator(p, token).unwrap_or(token);

    if matches!(token, CppTokenKind::Greater | CppTokenKind::RightShift)
        && !p.greater_than_is_an_operator()
    {
        return None;
    }

    match token {
        // 赋值运算 — 优先级最低,且**右结合**:`a = b = c` 是 `a = (b = c)`。
        //
        // 这一族之前完全不在表里,后果远不止"少一种运算符":`a = b;` 解析出的 `BinaryExpr` 在 `=` 处
        // 停止,于是**表达式语句**以 "expected `;` after expression" 失败,声明/表达式的回溯也救不了
        // 它 —— 表达式读法自己就没读完整。任何含赋值或复合赋值的语句都受影响,这在真实代码里几乎是
        // 每一行。
        CppTokenKind::Assign
        | CppTokenKind::PlusAssign
        | CppTokenKind::MinusAssign
        | CppTokenKind::StarAssign
        | CppTokenKind::SlashAssign
        | CppTokenKind::PercentAssign
        | CppTokenKind::AmpersandAssign
        | CppTokenKind::PipeAssign
        | CppTokenKind::CaretAssign
        | CppTokenKind::LeftShiftAssign
        | CppTokenKind::RightShiftAssign => Some(1),

        // 注意这里**没有**逗号运算符。它确实是 C++ 里优先级最低的二元运算符,但在这个 parser 里加入它是
        // 有害的:实参列表和初始化列表都用逗号分隔,而一个认得逗号的表达式规则会把分隔符吃掉 —— 于是
        // `g(1, 2)` 变成"一个实参的调用",这正是 `get_args().len()` 从 2 变 1 的原因。
        //
        // 要支持逗号表达式,容器规则必须显式声明"读到逗号为止",那是另一处改动。在那之前,少一个几乎没人
        // 写的运算符,好过吃掉所有实参分隔符。
        // 逻辑或
        CppTokenKind::LogicalOr => Some(4),

        // 逻辑与
        CppTokenKind::LogicalAnd => Some(5),

        // 按位或
        CppTokenKind::Pipe => Some(6),

        // 按位异或
        CppTokenKind::Caret => Some(7),

        // 按位与 — 注意与一元 `&` 的区别:作为二元运算符时它在表里,由优先级爬升决定
        CppTokenKind::Ampersand => Some(8),

        // 相等性运算
        CppTokenKind::Equal | CppTokenKind::NotEqual => Some(9),

        // 关系运算
        CppTokenKind::Less
        | CppTokenKind::LessEqual
        | CppTokenKind::Greater
        | CppTokenKind::GreaterEqual
        | CppTokenKind::Spaceship => Some(10),

        // 移位运算
        CppTokenKind::LeftShift | CppTokenKind::RightShift => Some(11),

        // 加法、减法
        CppTokenKind::Plus | CppTokenKind::Minus => Some(12),

        // 乘法、除法、模运算 - 最高优先级
        CppTokenKind::Star | CppTokenKind::Slash | CppTokenKind::Percent => Some(13),

        // 指向成员的指针: `a.*b`、`p->*b`。标准里 pm-expression 是 multiplicative-expression 的**下一层**,
        // 也就是比乘法结合得更紧 —— `p->*h * n` 是 `(p->*h) * n` —— 所以排在 13 之上。
        //
        // 两个 token 一直在词法器里(`.*` 与 `->*`),表达式层却没人接: `(this->*handle)(args)` 报
        // `expected ), but get ->*`,而那是**成员函数指针的唯一解引用写法**。`CodeActionService.cpp` 就是它。
        CppTokenKind::DotStar | CppTokenKind::ArrowStar => Some(14),

        _ => None,
    }
}

/// The operator a C++ **alternative spelling** stands for, when the cursor is on one.
///
/// `<iso646.h>` and the standard's own table give every operator an alphabetic spelling, and they are real C++ —
/// not an extension — so a parser that ignores them rejects code that compiles. They arrive as `Identifier`
/// tokens because the lexer has no keyword for them, and this is where the text becomes the operator.
///
/// Recognised at the two places that need it rather than by rewriting the token stream: the binary table
/// ([`get_operator_precedence`], which every caller reaches) and the unary and primary rules, which must know
/// that `not` and `compl` are operators before they try to read a name. Rewriting the tokens would be one place
/// instead of three, and it would also change what the token *is* — `and` would report itself as `&&`, and a
/// consumer printing the operator would print a token the file never contained. The tree keeps the text either
/// way, so the shape is what has to be got right.
///
/// The two primary-position names, `not_eq` and the assignment spellings, are here so that the table and the
/// unary rule answer consistently; `not_eq(a, b)` is the one that *looked* like it already worked, and only
/// because `not_eq` was being read as a function name.
fn the_alternative_operator(p: &CppParser, token: CppTokenKind) -> Option<CppTokenKind> {
    if token != CppTokenKind::Identifier {
        return None;
    }

    Some(match p.current_token_text() {
        "and" => CppTokenKind::LogicalAnd,
        "or" => CppTokenKind::LogicalOr,
        "not" => CppTokenKind::LogicalNot,
        "bitand" => CppTokenKind::Ampersand,
        "bitor" => CppTokenKind::Pipe,
        "xor" => CppTokenKind::Caret,
        "compl" => CppTokenKind::Tilde,
        "not_eq" => CppTokenKind::NotEqual,
        "and_eq" => CppTokenKind::AmpersandAssign,
        "or_eq" => CppTokenKind::PipeAssign,
        "xor_eq" => CppTokenKind::CaretAssign,
        _ => return None,
    })
}

/// Does this `throw` have no operand — the `throw;` of a rethrow, or one ending a construct?
///
/// The operand is optional in exactly the positions where a `throw` can end: before a `;`, a `)`, a `]`, a `}`,
/// a `,`, a `:`, or the end of the file. Anywhere else an operand is written and has to be read.
fn throw_has_no_operand(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::Semicolon
            | CppTokenKind::RightParen
            | CppTokenKind::RightBracket
            | CppTokenKind::RightBrace
            | CppTokenKind::Comma
            | CppTokenKind::Colon
            | CppTokenKind::Eof
            | CppTokenKind::None
    )
}

/// Is this operator one a fold expression can use?
///
/// Every binary operator in the table except the assignment family — which does not fold — so the test is
/// written as "is a binary operator with a precedence above the assignment family", and the exclusions are the
/// ones C++ makes. Deriving it from the table rather than listing the operators a second time is what keeps the
/// two from disagreeing, and it is why `and`, `bitand` and the rest fold without being mentioned here.
fn is_fold_operator(p: &CppParser, token: CppTokenKind) -> bool {
    matches!(get_operator_precedence(p, token), Some(precedence) if precedence > 1)
}

/// Is this operator right-associative?
///
/// Only the assignment family is, and getting it wrong is a shape rather than an error: `a = b = c` read as
/// left-associative produces `(a = b) = c`, which is not a thing anyone writes and is not what the source says.
fn is_right_associative(token: CppTokenKind) -> bool {
    is_assignment_operator(token)
}

/// Is this one of the assignment operators — `=` and the ten compound forms?
///
/// The list has two readers and they must agree: associativity, and the right operand's being an
/// initializer-clause rather than an expression. An operator in one list and not the other is a shape bug in
/// `x += {1}` that no error message would point at.
fn is_assignment_operator(token: CppTokenKind) -> bool {
    matches!(
        token,
        CppTokenKind::Assign
            | CppTokenKind::PlusAssign
            | CppTokenKind::MinusAssign
            | CppTokenKind::StarAssign
            | CppTokenKind::SlashAssign
            | CppTokenKind::PercentAssign
            | CppTokenKind::AmpersandAssign
            | CppTokenKind::PipeAssign
            | CppTokenKind::CaretAssign
            | CppTokenKind::LeftShiftAssign
            | CppTokenKind::RightShiftAssign
    )
}

/// 解析表达式的主要入口点
pub fn parse_expr(p: &mut CppParser) -> ParseResult {
    parse_expr_up_to(p, Level::Full, true)
}

/// An expression **without** the comma operator, for a rule that spells the commas itself.
///
/// The comma is the one operator whose separators belong to the *container* rather than to the expression, so
/// every rule that reads a comma-separated list has to use a reader that stops below it. The complete list of
/// those rules is kept with [`Level`], which is also where the reason the comma is not in the operator table is
/// written down.
///
/// It is the same shape of exclusion as [`parse_expr_without_pack_expansion`], one operator along: that one
/// exists because a rule spells a `...` itself, this one because a rule spells a `,`.
///
/// The **pack expansion is still read**, and that half is not symmetry — it is required. `g(args...)` is a pack
/// expansion *as an element of an argument list*, so an element reader that stopped at the ellipsis would leave
/// the `...` for the list to trip over. That is exactly what happened when this was first written without it.
pub fn parse_assignment_expr(p: &mut CppParser) -> ParseResult {
    parse_expr_up_to(p, Level::Assignment, true)
}

/// One argument of a call: an expression, or a **braced-init-list**.
///
/// `v.push_back({1, 2})` and `f({})` are ordinary C++ and were a gap of exactly the kind the assignment rule
/// had: the grammar's argument is an *initializer-clause*, wider than an expression, and a `{` in argument
/// position cannot begin anything else — so the token picks the reading and there is no ambiguity to resolve.
///
/// It is not folded into [`parse_assignment_expr`] because that reader is also the element reader for lists
/// where a `{` means something else: `int a[] = {1, 2}` reads its elements with it, and a braced-init-list read
/// there would nest a second `InitListExpr` inside the first. The call arm is the only list whose elements may
/// be braces, so the choice belongs to the call arm.
pub fn parse_argument(p: &mut CppParser) -> ParseResult {
    if p.current_token() == CppTokenKind::LeftBrace {
        return decls::parse_braced_initializer(p);
    }

    parse_assignment_expr(p)
}

/// Read the argument list of a call — and, when the arguments are **not expressions at all**, keep them as tokens.
///
/// The second half is the whole reason this is a function rather than four lines in the call arm. A macro's
/// arguments are the macro's own tokens, and a macro written in an *included* header is not in any table this
/// parser is handed: libstdc++ writes
///
/// ```text
/// if constexpr (__is_same(const volatile _Tp, const volatile void))                    // bits/new:234
/// return __reference_constructs_from_temporary(_Elements, _Up&&) …                     // tuple:922
/// _GLIBCXX_TYPEID(typename std::iterator_traits<_Iterator>::value_type);               // bits/formatter.h:485
/// _MM_REDUCE_OPERATOR_BASIC_EPI16 (+);                                                 // avx512vlbwintrin.h:4992
/// ```
///
/// — a *call* whose argument is a type, a qualifier or a bare operator, which is nothing the expression grammar
/// can read. The reading that fits is the one the macro rules already use: a balanced group of raw tokens, kept
/// under an `ArgumentList` node (see [`decls::parse_balanced_token_group`]).
///
/// # The criterion, and what it costs
///
/// The **preference comes first and its failure is what is handled**: arguments are expressions until that
/// reading fails, and only then are they tokens.
/// Nothing about the callee is consulted, because nothing about it is knowable: the macro's `#define` is in
/// another file.
///
/// The cost is real, and it is why this is a fallback and not a rule: `f(1 +)`, a genuinely broken call, is read
/// as a macro's arguments and reported by nobody. No shape separates the two cases — the arguments of a macro
/// *are* arbitrary tokens — so the choice is between the diagnostic on the broken call and every use of the
/// macro, and the census measurement is what settled it on the second.
pub fn parse_call_arguments(p: &mut CppParser) -> ParseResult {
    expect_token(p, CppTokenKind::LeftParen)?;

    // Each argument is read *below* the comma operator, because the commas here are the list's own — see
    // [`parse_assignment_expr`]. It is [`parse_argument`] rather than that reader directly, so that a
    // braced-init-list is an argument (`v.push_back({1, 2})`).
    if p.current_token() != CppTokenKind::RightParen {
        parse_argument(p)?;
        while p.current_token() == CppTokenKind::Comma {
            p.bump(); // consume ','
            parse_argument(p)?;
        }
    }

    expect_token(p, CppTokenKind::RightParen)?;
    Ok(crate::parser::CompleteMarker::empty())
}

/// An expression that must **not** swallow a `{` as a braced initializer, for a constraint.
///
/// This exists for one construct and one failure: a requires-clause sits between a declarator and the body of a
/// definition, so the `{` after the constraint opens the *body* —
///
/// ```text
/// template <typename T> void f(T t) requires C<T> { }
///                                            ^ the constraint ends here
/// ```
///
/// — while the expression grammar reads a `{` after an expression as C++11's list-initialisation of a temporary
/// (`Vec<int>{1, 2}`). Left alone, `requires C<T> { }` came out as a constraint of `C<T>{}` with the body
/// missing.
///
/// A constraint can never need a braced initializer: `requires C<T> { }` as a *definition* is the only reading
/// that has a body, and a constraint that really wants one writes it in parentheses — `requires (C<T>{})`. So
/// refusing the reading here takes nothing away.
///
/// The marker is on the parser rather than passed down, because it has to hold for the **whole** constraint: a
/// `{` after any part of it belongs to the same body, however deeply the expression nests.
pub fn parse_constraint_expr(p: &mut CppParser) -> ParseResult {
    let previous = p.enter_constraint();
    // A constraint is a *logical-or-expression* ([temp.pre]): `||` is the loosest operator it can hold. Anything
    // looser belongs to what the clause is written on — the `=` of `V() requires C<T> = default;` and
    // `void f() requires C<T> = delete;`, which read as an assignment to `C<T>` left the declaration without a
    // clause and without a body.
    let result = parse_binary_expr_with_precedence(p, 4);
    p.leave_constraint(previous);
    result
}

/// The expression inside the braces of a **compound requirement**: `{ expr } noexcept -> type`.
///
/// It is the ordinary expression reader with the trailing-`noexcept` reading refused — see
/// [`CppParser::is_in_a_constraint`], which the postfix rule consults for it. A `noexcept` directly after the
/// expression belongs to the *requirement*:
///
/// ```text
/// { t.f() } noexcept -> int;   the call, and then the requirement's exception specification
/// { t.f() noexcept }           … the same tokens, and the `noexcept` is still the requirement's
/// ```
///
/// Without the refusal the postfix loop takes `noexcept` as part of the expression, the requirement ends there,
/// and the `}` that was meant to close the compound requirement has nothing left to close — which came out as
/// `expected }` against the requirement's own closing brace.
fn parse_requirement_expression(p: &mut CppParser) -> ParseResult {
    let previous = p.enter_constraint();
    let result = parse_expr(p);
    p.leave_constraint(previous);
    result
}

/// [`parse_expr`] without the trailing-`...` reading, for the one rule that spells the ellipsis itself.
///
/// `case 2 ... 4:` is a GNU range whose `...` comes after an expression, exactly where a pack expansion's does.
/// The case rule reads the low bound, then the `...`, then the high bound — so it has to be given an expression
/// reader that stops before the ellipsis, or the range's own punctuation is consumed as part of the bound.
///
/// Exposed rather than kept private because the caller is in another module, and the alternative — the case rule
/// looking for a `...` that `parse_expr` has already taken — is not a rule at all.
pub fn parse_expr_without_pack_expansion(p: &mut CppParser) -> ParseResult {
    parse_expr_up_to(p, Level::Full, false)
}

/// How far up the precedence ladder an expression reader goes.
///
/// The ladder, loosest first: `,` then the assignment family then `?:` then the binary operators then the unary
/// and postfix ones. A *container* — an argument list, a braced initializer, a capture list — separates its
/// elements with a comma, and the comma is the only operator whose separators belong to the container rather
/// than to the expression. So every such rule reads **one element** at [`Level::Assignment`], and
/// [`Level::Full`] is reserved for the positions where a comma really is an operator.
///
/// # Why the comma is not in `get_operator_precedence`
///
/// Because that table is consulted by `parse_binary_expr_with_precedence`, which every list rule reaches
/// through its elements. A comma in it would make `f(a, b)` one argument and `{1, 2}` one element — the
/// containers have no way to opt out, so the operator has to live above the level they stop at.
///
/// # The rules that read one element
///
/// This list is the deliverable of the maintenance convention about shared entry points: changing what an
/// expression reader consumes changes every rule that spells that token itself, and `cargo test` being green
/// does not prove none of them broke.
///
/// | Rule | The list it separates |
/// |---|---|
/// | `parse_postfix_suffixes` (call arm) | call arguments |
/// | `decls::parse_expression_list` | parenthesised initialisers, base clauses, member initialisers |
/// | `decls::parse_initializer_clause` | braced-initializer elements |
/// | `exprs::parse_capture` | lambda init-capture initialisers |
/// | `decls::finish_init_declarator` (bit-field arm) | bit-field widths |
/// | `decls::parse_template_parameter` (default-argument arm) | template parameters |
/// | `types::parse_template_argument` (expression fallback) | template arguments |
///
/// The call arm reads each element with [`parse_argument`] rather than [`parse_assignment_expr`] directly,
/// because an argument may also be a braced-init-list — and that choice belongs to the *call* arm. See
/// [`parse_argument`] for why the other lists must not make it.
///
/// # Checking the table
///
/// Each row claims something a test cannot see — that a *specific* rule calls the reader it names — so the table
/// has to be checkable by hand, and it was, row by row, when the last row turned out to be wrong: the template
/// argument's expression fallback still called [`parse_expr`] while this table said it read one element
/// (`S<3, 4>` was one argument, with no diagnostic). The check is a grep of the rule for
/// the reader it calls, and the rows that pass it are: the call arm ([`parse_argument`]), `parse_expression_list`,
/// `parse_initializer_clause`, [`parse_capture`], the bit-field arm of `finish_init_declarator`, the
/// default-argument arm of `parse_template_parameter`, and `parse_template_argument` — all
/// [`parse_assignment_expr`]. A row added from here on is worth checking the same way **before** it is written,
/// not after a corpus probe finds the defect it describes.
///
/// **Every entry after the first four was added because something failed**, which is the argument for writing
/// this table before changing the reader rather than after it:
///
/// * the **bit-field width** is not a list of expressions in the usual sense — `int bits : 3;` is one
///   constant-expression — but the *members* are comma-separated, so `unsigned flags : 1, spare : 7;` is two
///   fields and a width reader that took the comma swallowed the second;
/// * the **default argument of a template parameter** is the same shape one level down:
///   `template <typename T, int N = 3, typename... Rest>` is three parameters, and the third disappeared into
///   the default of the second. Found by the **corpus** rather than by a test, and the diagnostic pointed at the
///   `typename` of the *first* parameter — three declarations away from the comma that was eaten;
/// * a **template argument**'s expression fallback is the third of the shape: `Grid<T, 3>::fill` is a qualified
///   name whose template arguments are comma-separated, and a fallback reader that took the comma left the list
///   without its second argument. This one contradicts what the next paragraph used to claim about template
///   arguments — the *type* reading does stop at a comma, and the *expression* fallback did not.
///
/// Deliberately **not** on the list, with the reason each one differs:
///
/// * Structured binding name lists, declarator lists, parameter lists, `using`-declarator lists, enumerator
///   lists — no expressions, so they never reach either reader.
/// * `alignas(...)`, `decltype(...)`, `noexcept(...)`, `explicit(...)`, array bounds, the GNU case range — the
///   payload *is* a full expression, and an array bound or a case label with a comma in it is the author's
///   problem rather than the grammar's.
/// * `parse_expression_statement` and the `for` header — a comma there is the comma operator, which is the
///   whole point.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Level {
    /// Everything, including the comma operator.
    Full,
    /// Up to and including the assignment family — one element of a comma-separated list.
    Assignment,
}

/// Read an expression down to `level`, optionally reading a trailing `...` as a pack expansion.
fn parse_expr_up_to(p: &mut CppParser, level: Level, pack_expansion: bool) -> ParseResult {
    let _phase = crate::parser::phases::during("expression");
    let mut expr = parse_ternary_expr(p)?;

    if level == Level::Full {
        // The comma operator: the loosest of all, left-associative, and a `BinaryExpr` like every other
        // operator. Folded left in a loop rather than given a precedence number, for the reason in [`Level`].
        //
        // The right operand is a **ternary** expression and not another comma one, which is what makes the
        // operator left-associative: `a, b, c` folds as `(a, b), c`.
        while p.current_token() == CppTokenKind::Comma {
            let m = expr.precede(p, CppSyntaxKind::BinaryExpr);
            p.bump(); // `,`
            parse_ternary_expr(p)?;
            expr = m.complete(p);
        }
    }

    // A **pack expansion**: `g(args...)`, `std::tuple<Ts...>`, `h(f(x)...)`. The `...` follows the pattern it
    // expands, and the pattern is an expression — which is why it is read here, at the one place every
    // expression reaches, rather than in each of the list rules that can contain one.
    //
    // The alternative was to teach the argument list, the template argument list and the initializer list to
    // each look for a `...` after what they read. That is four copies of one rule, and the three that were
    // written later would be the ones to get it wrong.
    //
    // Nothing else is taken away by this. Where a `...` follows an expression and is *not* an expansion — the
    // `args...` of a declarator, the `...` of an old-style variadic parameter — the expression is not read by
    // this rule at all: `Args&&... args` has no expression in it, and `int f(int a, ...)` has the ellipsis
    // after a comma rather than after an expression.
    //
    // It applies at **both levels**, because an element of a list can be a pack expansion: `g(args...)` is one.
    if pack_expansion && p.current_token() == CppTokenKind::Ellipsis {
        let expansion = expr.precede(p, CppSyntaxKind::PackExpansionExpr);
        p.bump(); // `...`
        return Ok(expansion.complete(p));
    }

    Ok(expr)
}

/// 解析三元表达式 (condition ? true_expr : false_expr)
fn parse_ternary_expr(p: &mut CppParser) -> ParseResult {
    let mut expr = parse_binary_expr_with_precedence(p, 0)?;

    if p.current_token() == CppTokenKind::Question {
        // **How many conditionals were open when this conditional began** — taken here, before the true branch is
        // read, because the `# if` of the per-branch spelling is consumed *by the true expression* (its
        // operator-position seam reads it, since no operator follows it and it opens no branch). A snapshot taken
        // at the seam below would already include it and the tail's comparison would come out even.
        let conditionals_when_the_conditional_began = p.open_conditionals();

        let m = expr.precede(p, CppSyntaxKind::TernaryExpr);
        p.bump(); // consume '?'

        // **The GNU elvis operator, `a ?: b`** — the middle operand is the condition, written once. It is not C++,
        // and glibc and the Linux headers use it heavily (`#define min(a, b) ((a) < (b) ?: (b))`), so a parse of
        // those files has to accept it: a `:` where the true expression would be means the true expression is
        // absent, and the `:` is asked for below as it always is.
        //
        // Nothing is synthesised into the tree. A consumer that reads the middle operand finds none, which is the
        // honest shape of the syntax — the value `a ?: b` yields is `a`, and a duplicate of the condition's tokens
        // would be a second copy of text the file wrote once.
        if p.current_token() != CppTokenKind::Colon {
            parse_expr(p)?; // true expression
        }

        // **A directive between the two branches**, which is the seam every other list rule already has, in the
        // one position a *conditional* is conditioned in — and the standard library writes it that way, because
        // the two spellings of the `: 1 << …` branch are what the conditional is choosing:
        //
        // ```cpp
        //     return __len > (_Max_align::value / 2)          // type_traits:2269
        //          ? _Max_align::value
        // # if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_clzg)
        //          : 1 << (__SIZE_WIDTH__ - __builtin_clzg(__len - 1u));
        // # else
        //          : 1 << (__LLONG_WIDTH__ - __builtin_clzll(__len - 1ull));
        // # endif
        // ```
        //
        // A `#` where the `:` should be cannot be anything else — the conditional has both of its branches or it
        // is not one — so the directive is read as the node it is and the `:` is asked for again. Without it the
        // file reported ``expected :, but get #`` against the `# if` itself.
        //
        // Only **between** the branches, and not before the `?`: there the directive belongs to whatever
        // construct is being conditioned (`_GLIBCXX_NOEXCEPT_IF(…)` and the template-parameter seam are read by
        // their own rules), and a directive read here would be one they can no longer see.
        //
        // The count is asked of the **directive rule** rather than kept here, and that is the point: the true
        // expression above *is* an expression, and its operator-position seam consumes a `# if` on its way past —
        // so a count kept by this function would have to know about every rule that can read a directive between
        // here and there. See [`CppParser::open_conditionals`], and the snapshot at the top of this arm.
        while p.current_token() == CppTokenKind::Hash {
            stats::parse_preprocessor_directive(p)?;
        }

        expect_token(p, CppTokenKind::Colon)?;
        parse_ternary_expr(p)?; // false expression

        // **The `:` branch written once per branch** — the same file, four lines on:
        //
        // ```cpp
        //     return __len > (_Max_align::value / 2)          // type_traits:2269
        //          ? _Max_align::value
        // # if _GLIBCXX_USE_BUILTIN_TRAIT(__builtin_clzg)
        //          : 1 << (__SIZE_WIDTH__ - __builtin_clzg(__len - 1u));
        // # else
        //          : 1 << (__LLONG_WIDTH__ - __builtin_clzll(__len - 1ull));
        // # endif
        // ```
        //
        // Each branch writes the `:` **and the `;` that ends the statement** — the conditional is a *return*, and
        // the two spellings are two complete returns as far as the preprocessor is concerned. So the `;` after the
        // false expression is this branch's, and the next branch's `:` follows it; the conditional reads both
        // spellings, and the statement is told the terminator came from a branch
        // ([`CppParser::note_the_terminator_came_from_a_branch`]).
        //
        // The gate is the one the parameter list and the argument list use, for the same reason: a `;` followed by
        // an `#else`/`#elif`, **and** a conditional this conditional opened inside itself. Without the second
        // condition, `#if X a ? b : c; #else a ? d : e; #endif` would have the next branch's statement read as
        // another `:` branch.
        let mut read_a_branch_of_the_tail = false;
        while p.open_conditionals() > conditionals_when_the_conditional_began
            && let Some(writes_the_terminator) = decls::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 {
                stats::parse_preprocessor_directive(p)?;
            }

            expect_token(p, CppTokenKind::Colon)?;
            parse_ternary_expr(p)?;
        }

        if read_a_branch_of_the_tail && p.current_token() == CppTokenKind::Semicolon {
            p.bump();
        }

        expr = m.complete(p);
    }

    Ok(expr)
}

/// 使用优先级爬升算法解析二元表达式
/// min_prec: 当前最小优先级
fn parse_binary_expr_with_precedence(p: &mut CppParser, min_prec: u8) -> ParseResult {
    let mut left = parse_unary_expr(p, true)?;

    // A **fold expression** whose operator is at the cursor. Three spellings, and the `...` is what tells them
    // apart:
    //
    // ```text
    // (ts + ...)        a left fold    the `...` is the operator's right operand
    // (... + ts)        a right fold   the `...` is the left operand, read by the primary rule
    // (ts + ... + init) a binary fold  **both** sides of the `...` are written
    // ```
    //
    // The right fold needs nothing here: `...` arrives as the left operand and the loop below builds the same
    // shape with the sides swapped, which is exactly what a right fold is.
    //
    // # Why the binary fold has to be handled in this one place
    //
    // Because returning after the `...` leaves the **second operator** for the caller, and a caller that is a
    // parenthesised expression then reports ``expected )`` at it. Measured on MSVC's `<type_traits>`:
    // `constexpr unsigned char _Classify_category = _Comparison_category{(... | ... | ...)};` — one token the
    // grammar did not accept cost far more than one expression, because the recovery from it left a `{` unclosed
    // and the enclosing `namespace vc_attributes` (from `sourceannotations.h`) swallowed the rest of the
    // translation unit. That is what made `std::basic_string` a member of `vc_attributes` and `std::string`
    // unanswerable in every file that included `<string>`.
    if is_fold_operator(p, p.current_token())
        && p.peek_next_token() == CppTokenKind::Ellipsis
        && let Some(prec) = get_operator_precedence(p, p.joined_operator_at_the_cursor().0)
        && prec >= min_prec
    {
        let operator = p.current_token();
        let m = left.precede(p, CppSyntaxKind::BinaryExpr);
        p.bump(); // the operator
        let fold = p.mark(CppSyntaxKind::FoldExpr);
        p.bump(); // `...`
        fold.complete(p);

        // The second half of a **binary** fold, and only when the operator repeats: `+ ... +`. A different
        // operator after the `...` is not a fold continuation, and the loop below reads it as the ordinary next
        // term of the chain.
        if is_fold_operator(p, p.current_token())
            && p.current_token() == operator
            && let Some(prec) = get_operator_precedence(p, p.joined_operator_at_the_cursor().0)
            && prec >= min_prec
        {
            p.bump(); // the operator again
            parse_binary_expr_with_precedence(p, prec + 1)?;
            return Ok(m.complete(p));
        }

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

    // **A directive where the next operator goes**, which is how a *term* of an expression is written once per
    // branch — the shape `tr1/riemann_zeta.tcc:179` has:
    //
    // ```cpp
    //   __zeta *= std::pow(_Tp(2) * __numeric_constants<_Tp>::__pi(), __s)
    //          * std::sin(__numeric_constants<_Tp>::__pi_2() * __s)
    // #if _GLIBCXX_USE_C99_MATH_TR1
    //          * std::exp(_GLIBCXX_MATH_NS::lgamma(_Tp(1) - __s))
    // #else
    //          * std::exp(__log_gamma(_Tp(1) - __s))
    // #endif
    //          / __numeric_constants<_Tp>::__pi();
    // ```
    //
    // Both branches write the **same operator** with a different operand, and the expression continues after the
    // `#endif`, so the directive is read as the node it is and the loop looks for the operator again. A `#` in
    // this position cannot be anything else: an expression has no `#`, and the loop is where an operator — or the
    // end of the expression — is what the tokens say next.
    //
    // **What this reads and what it does not.** The tokens of *both* branches end up in one chain
    // (`… * exp(A) * exp(B) / …`), which is not what either branch says — the branches are alternatives, and this
    // reading has no way to say so, because an expression is one tree and the two operands are two. It is
    // lossless, it is silent, and it attaches every token to the construct that owns it; the alternative is a
    // file that does not parse at all, which is what this file did (the first error was ``expected `;` after
    // expression`` against the `#if`). The same trade is documented for a macro's arguments.
    loop {
        // Read the directives **only when they are this expression's**. Two things can follow them, and each is a
        // different owner:
        //
        // * an **operator** — then they are the seam above: the next term of the chain is written once per branch
        //   (`tr1/riemann_zeta.tcc:179`), and the chain continues;
        // * **nothing an operator** — then the expression is over, and whether the directives belong to it depends
        //   on which directive they are. An `#else`/`#elif` opens **another instance of the construct that
        //   surrounds this expression**, and that construct's own seam is what reads it (`bits/stl_algobase.h:906`
        //   is a declaration whose initializer is written per branch, and it can only see the `#else` if the
        //   expression leaves it alone). Anything else — an `#endif`, an `#if` of the next conditional — closes
        //   what is around the expression, and the closer that follows it (`)`, `,`, `;`) is what the *caller*
        //   expects to see next, so the expression takes the directives and stops:
        //
        // ```cpp
        //   const bool __simple = ((__is_integer<_V>::__value      // bits/stl_algobase.h:1237
        // #if _GLIBCXX_USE_BUILTIN_TRAIT(__is_pointer)
        //                 || __is_pointer(_V)
        // #endif
        // #if __glibcxx_byte && …
        //                 || is_same_v<_V, byte>
        // #endif
        //                  ) && __memcmpable<_II1, _II2>::__value);
        // ```
        //
        // — where the `#endif`s stand *inside* the parentheses, between the last operand and the `)`.
        if p.current_token() == CppTokenKind::Hash {
            let checkpoint = p.checkpoint();
            let mut opens_another_branch = false;

            while p.current_token() == CppTokenKind::Hash {
                if matches!(p.peek_token_text_at(1), "else" | "elif") {
                    opens_another_branch = true;
                }
                stats::parse_preprocessor_directive(p)?;
            }

            let an_operator_follows =
                get_operator_precedence(p, p.joined_operator_at_the_cursor().0)
                    .is_some_and(|prec| prec >= min_prec);
            if !an_operator_follows {
                if opens_another_branch {
                    p.rollback(checkpoint);
                }
                break;
            }
        }

        let Some(prec) = get_operator_precedence(p, p.joined_operator_at_the_cursor().0) else {
            break;
        };
        if prec < min_prec {
            break;
        }

        // The operator, and **how many tokens the lexer left it in** — `>>`, `>>=` and `>=` arrive broken up, so
        // the cursor has to advance over every part. See [`CppParser::joined_operator_at_the_cursor`]: one
        // question ("is this an operator") with one answer, instead of a `RightShift` handed out whole and three
        // angle scanners left to remember that it was two brackets.
        let (operator, spans) = p.joined_operator_at_the_cursor();
        let m = left.precede(p, CppSyntaxKind::BinaryExpr);
        for _ in 0..spans {
            p.bump(); // consume operator
        }

        // The right operand of an **assignment** is an *initializer-clause*, which is a wider rule than an
        // expression: `x = {1, 2};` assigns a braced-init-list, and a `{` cannot begin an expression at all.
        // There is nothing to disambiguate here — only a rule that was missing.
        //
        // It produces the same `InitListExpr` a declaration's initializer produces; the two differ only in the
        // grammar production that reached it, and both are a consumer's answer to "what is being assigned?".
        if is_assignment_operator(operator) && p.current_token() == CppTokenKind::LeftBrace {
            decls::parse_braced_initializer(p)?;
            left = m.complete(p);
            continue;
        }

        // 左结合运算符用 `prec + 1`,右结合用 `prec` —— 差值就是"是否允许同级运算符继续往右吃"。
        // C++ 里只有赋值族是右结合,见 [`is_right_associative`]。
        let next_min_prec = if is_right_associative(operator) {
            prec
        } else {
            prec + 1
        };
        parse_binary_expr_with_precedence(p, next_min_prec)?;

        left = m.complete(p);
    }

    Ok(left)
}

/// 解析一元表达式
///
/// `fold_operand` says whether a bare `...` may be read as a fold expression's operand here. It is true only
/// inside parentheses, which is where a fold is written; see the `Ellipsis` arm of [`parse_primary_expr`].
fn parse_unary_expr(p: &mut CppParser, fold_operand: bool) -> ParseResult {
    // **A directive where an operand goes.** The loop in [`parse_binary_expr_with_precedence`] reads the directives
    // that stand where the next **operator** goes (`a * exp(A) #else * exp(B) #endif`); this is the other half — the
    // branch written before its **operand**, which is how a condition chooses one term per compilation:
    //
    // ```cpp
    //   if (&__ti == &_Sp_make_shared_tag::_S_ti()
    //       ||
    // #if __cpp_rtti
    //       __ti == typeid(_Sp_make_shared_tag)
    // #else
    //       _Sp_make_shared_tag::_S_eq(__ti)
    // #endif
    //      )
    // ```
    //
    // Read by shape, like the operator-position seam, and for the same reason: an expression has no `#`, so a `#`
    // where an operand is expected can only be a directive.
    //
    // **What refusing it cost.** `bits/shared_ptr_base.h:639` is exactly that `if`, inside `_M_get_deleter` of
    // `_Sp_counted_ptr_inplace`. The operand rule refused the `#`, the recovery took the `)` for part of the
    // expression, and the class body ended at the `if`: every declaration after it — `__shared_ptr` included — became
    // a member of `_Sp_counted_ptr_inplace`, `__shared_ptr` lost its base clause, and `shared_ptr` lost
    // `__shared_ptr_access`'s `operator*`/`operator->` with it. Six "`shared_ptr` again" reports, one `#`.
    //
    // What this reads and what it does not is the operator seam's trade, told there: the tokens of both branches end
    // up in one chain, which is not what either branch says, and it is lossless, silent, and attaches every token to
    // the construct that owns it.
    while p.current_token() == CppTokenKind::Hash {
        stats::parse_preprocessor_directive(p)?;
    }

    // An **alternative spelling** of a unary operator — `not x`, `compl x` — reaches here as an identifier, so
    // it is mapped before the match. In operand position a name would otherwise start a primary expression, and
    // `not x` would be read as two adjacent expressions.
    let token = the_alternative_operator(p, p.current_token()).unwrap_or(p.current_token());

    match token {
        CppTokenKind::LogicalNot
        | CppTokenKind::Tilde
        | CppTokenKind::Plus
        | CppTokenKind::Minus
        | CppTokenKind::PlusPlus
        | CppTokenKind::MinusMinus
        | CppTokenKind::Star
        | CppTokenKind::Ampersand => {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // consume unary operator
            parse_unary_expr(p, fold_operand)?; // parse operand recursively
            Ok(m.complete(p))
        }
        // `co_await e` — a unary operator, and the only one whose operand is an awaitable rather than a value.
        //
        // A keyword rather than a punctuation token, which is the whole reason it needed saying: `co_await` was
        // already in [`is_expression_keyword`] — the list that keeps the *name* branch from swallowing it — but
        // no rule consumed it, so the expression parser reported `expected primary expression` against a token
        // it had just been told to expect. Being in that list is a promise that some rule handles it.
        CppTokenKind::CoAwaitKeyword => {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // consume 'co_await'
            parse_unary_expr(p, fold_operand)?; // the awaitable
            Ok(m.complete(p))
        }
        // A **throw-expression**: `x = throw 1;`, `cond ? throw 1 : 2`, `return throw 1;`.
        //
        // `throw` is a unary operator in these positions, and it is the one whose operand may be **absent** —
        // `throw;` rethrows, and that spelling is a *statement* whose rule already existed. Having both is not
        // redundancy: the statement rule reads a throw at the start of a statement and produces a `ThrowStat`,
        // which is the node a consumer wants there; this arm reads one wherever a *value* is expected, which is
        // every other position, and produces an expression.
        //
        // Without it the expression parser reported `expected primary expression` at `throw` — a keyword it had
        // been told to expect by [`is_expression_keyword`] and for which no expression rule existed. Being on
        // that list is a promise that some rule handles it; see also `co_await`, which was missing for the same
        // reason.
        CppTokenKind::ThrowKeyword => {
            let m = p.mark(CppSyntaxKind::ThrowExpr);
            p.bump(); // `throw`

            // The operand is optional: `throw;` is a rethrow. An operand is read only when one is there, so that
            // `cond ? throw 1 : 2` does not look for a `1` that belongs to some other rule.
            if !throw_has_no_operand(p) {
                parse_unary_expr(p, fold_operand)?;
            }
            Ok(m.complete(p))
        }

        // A **requires-expression** (C++20): `requires (params) { requirements }`.
        //
        // It is a `bool`-valued expression whose body lists things that must be *well-formed* rather than
        // operations to perform, which is why it has a rule of its own rather than being a call or a block.
        //
        // Two tests, because `requires` is contextual and one is not enough: the **spelling** says the word is
        // there, and `starts_a_requires_expression` says what follows is a body rather than the argument list of
        // a call. A call to a function named `requires` — `requires(x)` — therefore keeps its reading and reaches
        // the name branch below, which is the point of the word being an identifier at all.
        //
        // The arm used to be keyed on a keyword token, and the word was listed in [`is_expression_keyword`] to
        // keep the name branch from swallowing it. That list is for keywords some *other* rule consumes; with the
        // word lexed as an identifier the arm below is what claims it, and the entry is gone with the keyword.
        // **C++/CLI's `gcnew` and C++/CX's `ref new`** — MSVC's managed dialects, which its **own** headers write:
        //
        // ```cpp
        //   throw gcnew System::ArgumentNullException(_EXCEPTION_NULLPTR);   // marshal_atl.h:73
        //   throw ref new OutOfMemoryException;                             // collection.h:39
        // ```
        //
        // Both are the construct `new` already is: `gcnew` is one keyword, `ref new` is a `ref` that says the
        // allocation is a managed one. `gcnew` is reserved to the implementation, and `ref` is only taken when the
        // **next** token is `new`, so `int ref = 1;` keeps parsing as a variable.
        CppTokenKind::Identifier
            if p.current_token_text() == "ref"
                && p.peek_next_token() == CppTokenKind::NewKeyword =>
        {
            p.bump(); // `ref`
            parse_unary_expr(p, fold_operand)
        }
        CppTokenKind::Identifier if p.current_token_text() == "gcnew" => parse_new_expr(p),
        CppTokenKind::Identifier if at_requires(p) && starts_a_requires_expression(p) => {
            parse_requires_expression(p)
        }

        // `noexcept(expr)` — an operator only when it has its **payload**, and the payload is what tells it from
        // the exception specification of a function: `void f() noexcept` and `void f() noexcept(true)` are the
        // same keyword, and only the parenthesis separates them.
        //
        // A conditional arm rather than an unconditional one, for that reason: reading a bare `noexcept` as an
        // expression would take the specification away from the declaration rule that owns it. With the
        // parenthesis required, the two readings cannot collide — no expression is a bare `noexcept`, and no
        // exception specification is `noexcept(...)` *in operand position*.
        //
        // `NoexceptKeyword` was already in [`is_expression_keyword`] — the list that keeps the name branch from
        // swallowing it — with no rule consuming it, which is the same empty promise `co_await`, `throw` and
        // `requires` each turned out to be.
        CppTokenKind::NoexceptKeyword if p.peek_next_token() == CppTokenKind::LeftParen => {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // `noexcept`
            parse_unary_expr(p, fold_operand)?; // the payload, parentheses and all
            Ok(m.complete(p))
        }

        CppTokenKind::SizeofKeyword | CppTokenKind::AlignofKeyword => {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // consume 'sizeof' / 'alignof'

            // `sizeof...(Ts)` — the operator that counts a pack, and the one spelling where a `...` sits
            // between the keyword and its parentheses. The lexer produces `sizeof` and `...` as two tokens
            // rather than one, which is why this needed saying: the `...` was reported as an unexpected token
            // after a `sizeof` that had already finished reading its operand.
            //
            // The operand is always parenthesised, and it is a *name* rather than a type — `sizeof...(int)` is
            // not a thing. It goes through the parenthesised-expression rule, so the tree says the operand is
            // an expression, which is what it is.
            let counts_a_pack = p.current_token() == CppTokenKind::Ellipsis;
            if counts_a_pack {
                p.bump(); // `...`
            }

            if p.current_token() == CppTokenKind::LeftParen {
                p.bump(); // consume '('
                parse_type_id_or_expression(p)?;
                expect_token(p, CppTokenKind::RightParen)?;
            } else if !counts_a_pack {
                // `sizeof x` — the operand of the unparenthesised form is an expression, never a type.
                parse_unary_expr(p, fold_operand)?;
            }

            Ok(m.complete(p))
        }
        CppTokenKind::TypeidKeyword => {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // consume 'typeid'
            expect_token(p, CppTokenKind::LeftParen)?;
            parse_type_id_or_expression(p)?;
            expect_token(p, CppTokenKind::RightParen)?;
            // **The suffixes after a `typeid` are the expression's**, and `typeid(x).name()` is the spelling every
            // reader of `typeid` writes: it asks the *type* for a property. Read as a plain unary expression, the
            // `typeid` node was complete at its `)`, so the `.name()` had no rule left and the statement was
            // reported `expected ; after expression` — measured on `classes.cpp:162` in the C++ corpus, the one
            // place the corpus uses it.
            let completed = m.complete(p);
            parse_postfix_suffixes(p, completed)
        }
        // A C-style cast **is not read here**. The same arm exists one rule down
        // ([`parse_primary_expr`]'s `LeftParen if is_a_type_in_parentheses`), because a `(` that is not a cast is
        // a *parenthesised expression* — and this rule's `_` arm reaches that one. There used to be a second copy
        // here, and the two copies disagreed about the one thing that matters:
        //
        // ```cpp
        // bool b = (V<T>(x));      the type reading takes `V<T>(x)` for a *function type*, the `)` matches, and
        //                          then no operand follows
        // ```
        //
        // The copy below rolled back and read the group as the expression it is. The copy here reported a missing
        // operand instead — a hard error, from a *preference* the rule had already decided could be wrong — so the
        // same tokens parsed or failed depending on which of the two saw them first: `(V<T>(x))` was rubble,
        // `(W<T>(x))` (an unknown name, where the guard says "not a type") was fine. That is maintenance
        // convention #14 exactly — the second copy is where the exception gets forgotten — and the fix is to keep
        // the one that has it.
        // `new`, with everything that can follow it: placement arguments, a type, array bounds and an
        // initializer — and then the postfix suffixes, because `new Widget(1)->run()` is one expression.
        //
        // This used to hand off to [`parse_postfix_expr`], which reads a *value* — and a type is not one, so
        // `new int[4]` reported `expected primary expression` at the `int` and `new Widget(1, 2)` silently
        // read `Widget(1, 2)` as a call, which is a different construct with the same tokens. Nothing in the
        // grammar can read a type except the type rules, so this is where they have to be called.
        CppTokenKind::NewKeyword => parse_new_expr(p),
        // `::new` — the **global** allocation function, spelled with a leading `::`. The qualification is not
        // decoration: an unqualified `new` inside a class finds that class's `operator new`, and `::new` is how a
        // program says "the global one", so the `::` is kept inside the `NewExpr` rather than dropped.
        //
        // It needs an arm because `::` is otherwise the start of a *qualified name*: the name branch claimed it
        // and reported ``expected a name after `::` `` at the `new`, after which the recovery swallowed the whole
        // allocation as one flat name node — not merely the wrong node, but no structure at all. Measured on the
        // closure of six standard headers: 41 occurrences in 13 files, all of them this shape (`std::construct_at`
        // in `bits/stl_construct.h`, the allocators, `std::exception_ptr`, `std::pmr`), and it is the first error
        // of several of those files.
        CppTokenKind::Scope if p.peek_next_token() == CppTokenKind::NewKeyword => parse_new_expr(p),
        // **`::delete` — the sibling of `::new`, one line further down the standard's own grammar.**
        //
        // [expr.delete] spells the production `::opt delete cast-expression`, so a leading `::` is part of the
        // construct rather than a qualifier on anything — it names the **global** `operator delete`, which a
        // class's own `operator delete` would otherwise hide. The two arms are the same fact: `::` is otherwise
        // the start of a *qualified name*, the name branch claims it, and the error is the identical
        // ``expected a name after `::` ``. That arm's note already records the shape for `new`; this one is the
        // half that was missing.
        //
        // Measured: MSVC's `<any>:62` writes
        //
        // ```cpp
        // ::delete static_cast<_Ty*>(_Target);
        // ```
        //
        // so `void f(S* p) { ::delete p; }` was unparsable — and `cl.exe` accepts all of `::delete p`,
        // `::delete[] p` and `::delete` on a value. It is the whole of the one remaining diagnostic in `<any>`.
        CppTokenKind::Scope if p.peek_next_token() == CppTokenKind::DeleteKeyword => {
            parse_delete_expr(p, fold_operand)
        }
        CppTokenKind::DeleteKeyword => parse_delete_expr(p, fold_operand),

        // **A compiler keyword standing where an operand goes** — `__extension__`, the spelling GCC uses to say
        // "this is an extension, do not warn about it in a `-pedantic` build", and it is written *inside*
        // expressions rather than only in declarations:
        //
        // ```cpp
        //         __ret = __extension__ _S_nd<unsigned __int128>(__urng,   // bits/uniform_int_dist.h:318
        //                                __u64erange);
        // ```
        //
        // It is the implementation's own name ([`an_implementation_keyword`]), so reading it as one costs no
        // ordinary name: the arm below would otherwise take it for the operand's *name* and leave the real operand
        // as two expressions in a row — which is how that file reported ``expected `;` after expression`` against
        // the `__extension__` itself. Stepped over, with the node the specifier sequence gives it, and the operand
        // asked for again.
        _ if types::at_an_implementation_keyword(p) => {
            types::parse_an_implementation_keyword(p);
            parse_unary_expr(p, fold_operand)
        }

        _ => parse_postfix_expr(p, fold_operand),
    }
}

/// Parse what stands inside `sizeof(...)`, `typeid(...)` or a cast's parentheses: a type, or an expression.
///
/// The two grammars overlap completely — `(int)`, `(int*)` and `(x)` are all well-formed readings — and the
/// tokens do not choose between them, so this is a bounded backtrack with a rule for which reading to *try*:
/// the type goes first, because it is the one that can be refused. A name alone parses as both, and for
/// `sizeof(x)` the answer barely matters; for `(int)x` it decides whether the construct is a cast at all,
/// since the expression reading of `(int)` is not an expression and fails.
///
/// # Why the type-id must not stop at one name here
///
/// [`types::parse_type_id`] uses the same sequence as a declaration, where a second name is the
/// declarator. That is what is wanted: `sizeof(unsigned long)` and `(MyType)x` both need the type to be read
/// in full, and a `sizeof` of a variable is not a declaration, so there is no declarator to protect.
///
/// Exposed for the grammar of `alignas`, which has the same ambiguity in the same place: `alignas(int)` holds a
/// type-id and `alignas(16)` an expression, and nothing in the tokens tells them apart without trying.
pub fn parse_type_id_or_expression(p: &mut CppParser) -> ParseResult {
    let checkpoint = p.checkpoint();
    let before = p.current_token_index();

    // "It parsed and consumed something" is not enough to accept the type reading: a type-id can **stop early**,
    // and a name on its own is a complete type-id. `sizeof(a[0])` was read as the type `a` — the reading
    // succeeded, the cursor was left on the `[`, and the caller then reported `expected )` against it. The same
    // for `sizeof(a.b)`, `sizeof(a + b)`, `sizeof(a())` and `typeid(a[0])`: every `sizeof` whose operand is
    // anything but a bare name or a keyword type failed, which in C is most of them.
    //
    // What settles it is where the reading *stopped*: the payload ends at the `)`, so a type-id that did not
    // reach it was not the reading. Anything else — an operator, an index, a member access, a call — is an
    // expression, and the rollback hands it to that rule.
    //
    // A type-id that *does* swallow the whole payload stays the type reading, which is the case the rule exists
    // for: `sizeof(int[4])` is an array type rather than an index, and `sizeof(unsigned long)` is two keywords
    // rather than a comparison.
    if types::parse_type_id(p).is_ok()
        && p.current_token_index() > before
        && p.current_token() == CppTokenKind::RightParen
    {
        return Ok(crate::parser::CompleteMarker::empty());
    }

    p.rollback(checkpoint);
    parse_expr(p)
}

/// Does the `(` at the cursor open a C-style cast rather than a parenthesised expression?
///
/// The question is asked before the parenthesis is consumed, and it is asked precisely, because unlike every
/// other decision in this grammar the *wrong* answer is not recoverable by the parse itself: `(a)` parses as a
/// type-id — one name, no declarator — so a rule that tried the type reading whenever it could would turn
/// every parenthesised variable into a cast of `a`. That is how `x = (a);` came back as `expected primary
/// expression` against its own `)`, and how `(a && b)` became a cast of `b` to `a&&`.
///
/// Two shapes are certain, and only two:
///
/// * a **keyword type** — `(int)x`, `(const char*)p`, `(unsigned long)n`. No expression begins with `int`.
/// * a **name the file declared to be a type**, followed by something a cast can carry — `(MyType)x`,
///   `(MyType*)p`, `(ns::T)x`, `(Vec<int>)v`. The type table's one job, and the reason it exists.
///
/// # The third shape, and why the operators are otherwise not used
///
/// `*`, `&` and `&&` after a name look like they discriminate — a cast has a pointer or reference type, and an
/// expression has an operator — and on their own they do not: `(a && b)` is a conjunction, `(a * b)` a product.
/// All three tokens mean both things in the two grammars, and C++ settles them by looking the name up, which is
/// what the type table does.
///
/// But **a pointer operator has nothing on its left**, and that is visible. In `(MyType*)p` the `*` sits
/// immediately before the `)`, so it cannot be a binary operator — there is no right operand. `(a * b)` and
/// `(a* b)` both have one. So a `*`, `&` or `&&` **closing** the parentheses is the third certain shape, and it
/// needs no type table at all: this is what makes `(MyType*)p` readable in a file that never declares `MyType`,
/// and it is a **rule** rather than the trade-off it was once recorded as.
///
/// Everything else — `(a)`, `(a + 1)`, `((a))`, `(f(x))`, `(a && b)`, `(a * b)` — belongs to the
/// parenthesised-expression rule, which is where it now goes.
fn is_a_type_in_parentheses(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::LeftParen {
        return false;
    }

    // A `template` disambiguator *inside* the parentheses settles it the other way: `(T::template f<U>)x`
    // cannot be a cast, because a cast's type-id has no such keyword in it — `template` appears only in a name
    // being *used*, so the parentheses hold an expression. Without this the `::` in the name would claim the
    // cast reading and the mode's payload would be reported as a missing operand.
    //
    // Only the window up to the matching `)` is scanned, and only for the keyword: a `(` in the window means
    // the parentheses hold a call like `f(T::template g<U>())`, whose own `::` is not this parenthesis's.
    for kind in p.peek_token_kind_at(1..64) {
        match kind {
            CppTokenKind::RightParen | CppTokenKind::LeftParen => break,
            CppTokenKind::TemplateKeyword => return false,
            _ => {}
        }
    }

    if closes_with_a_pointer_operator(p) {
        return true;
    }

    // The fourth certain shape, and the one the type table was standing in for: **an operand follows the
    // parentheses**. Two operands in a row is not an expression in any grammar, so if the token after the `)` can
    // only *begin* one, the parentheses cannot have been a parenthesised expression at all — they held a type:
    //
    // ```text
    // (size_t)size     the `)` is followed by an identifier
    // (MyType)1.5      … or by a literal
    // (T)new U         … or by a keyword no binary operator spells
    // ```
    //
    // This is what makes a cast to a name the file never declares readable without lookup, and the shapes it adds
    // are the common ones in C: `(size_t)size`, `(char *)malloc(...)`, `(lua_State *)L`. It was recorded as a
    // deliberate trade-off ("only name lookup tells `(MyType)` from `(MyType)`") and that judgement was wrong for
    // the same reason the pointer form's was: what follows the `)` is evidence, and it needs no table.
    //
    // Three exclusions, each because the token *is* ambiguous rather than because it is inconvenient:
    //
    // * `(` — `(f)(x)` is a call, and reading it as a cast of `x` to `f` is the one reading that loses the callee;
    // * `*`, `&`, `+`, `-`, `++`, `--` — every one of them is a binary operator too, so `(a) - b` is a subtraction;
    // * `[` — `(a)[b]` is an index of the parenthesised expression.
    if an_operand_is_decisive(p) && an_operand_follows_the_parentheses(p) {
        return true;
    }

    match p.peek_token_kind_at(1..2).first() {
        Some(&kind) if types::is_type_specifier_keyword(kind) => true,
        Some(&CppTokenKind::Identifier) => {
            // The name must be one the file declares to be a type: a name alone is the token a type and an
            // expression share, and reading every `(a)` as a cast is the mistake this check exists to avoid.
            //
            // The `)` above already answered this for the shapes where an operand follows it; what is left here is
            // a name in front of something a *cast* carries and an expression does not — and the *parse* settles
            // the rest: a cast whose operand fails to parse is rewound and read as a parenthesised expression. See
            // the cast branch in `parse_primary_expr`.
            //
            // The **caller's table** is consulted last, and it is what makes `(Widget)x` a cast for a `Widget` from
            // a header — the case the file-local table cannot answer. A `Function` or `Variable` answer refuses the
            // cast, which is the direction the local table cannot express at all.
            let name = p.peek_token_text_at(1);
            p.is_a_known_type_name(name)
                || p.symbol_kind(name)
                    .is_some_and(|kind| matches!(kind, SymbolKind::Type | SymbolKind::Template))
        }
        // **No arm for a leading `::`.**
        //
        // A global-qualified name looked like certain evidence — `::std::string` can only be a type, surely — and
        // it is not, because the same `::` starts a global-qualified **expression**:
        //
        // ```text
        // (::x)              a parenthesised expression — and it was read as a cast type instead
        // (::abs(x) > 1)     the same, in the shape a real file writes: `SymSpell.cpp` line 155
        // (::MyType)x        a cast, and the operand after the `)` is what says so — see the check above
        // ```
        //
        // An arm here answered "cast" for the first two, and the cast reading then demanded an operand that was
        // never written: `(::x);` reported `expected primary expression` at its own `;`, and `(::abs(x) > 1)`
        // reported `expected ), but get >`. Every cast that is really a cast has an operand after the `)`, which
        // the operand check above already answers for — including a cast to a qualified type the file has never
        // heard of, `(::std::string)x`. What it deliberately leaves out is the ambiguous operator case, and that
        // reading is the same one an unqualified name gets: `(T)*p` is a multiplication, which is the cheaper
        // mistake (see `operators.rs` and T1).
        _ => false,
    }
}

// Is the "an operand follows" evidence **usable here**?
//
// Two rules consult that evidence — the cast's `)` ([`is_a_type_in_parentheses`]) and the template-id's `>`
// ([`parse_primary_expr`]'s name branch) — and both need the same exception, which is why the question is asked
// once, here.
//
// Inside a **clause**, the token after the construct may be the *declaration* the clause constrains rather than
// a stray operand, and that declaration usually begins with a type — an identifier or a keyword:
//
// ```text
// template <typename T> requires C<T> T value = T{};       after the template-id
// template <typename T> requires (C<T>) T value = T{};     after the parenthesised constraint
// ```
//
// Reading `C<T>` back, or taking `(C<T>) T` for a cast, leaves the clause eating the declaration's own type.
//
// **Parentheses are what tell the two cases apart**, and it is not a guess: a `ParenExpr` that is still open means
// the *constraint itself* is still going, so an operand there cannot be a declaration —
// `requires (N < 0 || N > 3)` is the shape — while at the clause's top level the operand can only be what
// follows the clause.
// **Reads the template-id at the cursor, or puts the tokens back.**
//
// `true` when the `<` really began arguments and they are now part of the name; `false` when it was a comparison,
// in which case every token the attempt consumed has been rolled back and the caller must end the name.
//
// Extracted from the name loop because two places in it need the same reading — the ordinary turn of the loop, and
// the run of names a macro prefix leaves behind (`MACRO name<targs>(…)`, where the `<` arrives **after** the run
// has taken the name and the loop is about to end). Writing it twice would be two readers for one shape, free to
// disagree about which `<` is a template-id.
//
// The `false` answer is not "it did not parse": `n < 0 || n > 100000` parses perfectly well as `n<0 || n>`, so

/// **Can this token not follow an expression?** — `N<3> struct`, where the `struct` proves the `<` was a comparison.
///
/// A template-id in an expression is followed by something that can continue one: an operator, a `(` of a call, a
/// `.`, a `;`, a `)`. A **declaration or statement keyword** cannot, and that is the whole of this test. Measured:
/// `template<typename _UIntType, int __w, bool = __w < std::numeric_limits<_UIntType>::digits>` in GCC 15`s
/// `tr1/random.h` — a *comparison* whose `>` closes the template parameter list — was read as `__w<…>`, leaving the
/// list without a terminator: `expected , or > in template parameter list` at the `struct` after it.
fn cannot_follow_an_expression(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::StructKeyword
            | CppTokenKind::ClassKeyword
            | CppTokenKind::UnionKeyword
            | CppTokenKind::EnumKeyword
            | CppTokenKind::NamespaceKeyword
            | CppTokenKind::TemplateKeyword
            | CppTokenKind::TypedefKeyword
            | CppTokenKind::UsingKeyword
            | CppTokenKind::ExternKeyword
            | CppTokenKind::StaticAssertKeyword
            | CppTokenKind::StaticKeyword
            | CppTokenKind::FriendKeyword
            | CppTokenKind::InlineKeyword
            | CppTokenKind::VirtualKeyword
            | CppTokenKind::ExplicitKeyword
            | CppTokenKind::ReturnKeyword
            | CppTokenKind::IfKeyword
            | CppTokenKind::ForKeyword
            | CppTokenKind::WhileKeyword
            | CppTokenKind::PublicKeyword
            | CppTokenKind::PrivateKeyword
            | CppTokenKind::ProtectedKeyword
    )
}

/// what settles it is the token **after** the list — an operand there cannot follow a template-id. See
/// [`starts_an_operand`], which is where that rule is written.
fn read_a_template_id_here(p: &mut CppParser) -> bool {
    let before_the_arguments = p.checkpoint();
    let read = types::parse_template_argument_list(p);

    // The operand rule is suspended **inside a clause**, except when the operand is inside parentheses that are
    // still open — see [`an_operand_is_decisive`], which is the same question the cast rule asks about its own `)`.
    let an_operand_ends_the_constraint = an_operand_is_decisive(p) && starts_an_operand(p, 0);

    // **…and only outside a constraint.** Inside one, a declaration keyword after the id is exactly what follows:
    // `template <typename T> requires C<T> struct S { };` ends the clause with `struct`, so the keyword guard would
    // refuse the template-id the clause is made of.
    if read.is_err()
        || an_operand_ends_the_constraint
        || (an_operand_is_decisive(p) && cannot_follow_an_expression(p))
    {
        p.rollback(before_the_arguments);
        return false;
    }
    true
}

fn an_operand_is_decisive(p: &CppParser) -> bool {
    !p.is_in_a_constraint() || p.is_open(CppSyntaxKind::ParenExpr)
}

/// **The identifier written before the cursor**, skipping the trivia between them.
///
/// The name a macro's second half follows. Trivia is a token in this lexer, so `_STD name<` has a whitespace
/// token between the two words and a lookbehind of one is not enough. `None` at the start of the file.
fn macro_name_before(p: &CppParser) -> Option<String> {
    let mut index = p.current_token_index();
    while index > 0 {
        index -= 1;
        let text = p.token_text_at(index);
        if !text.trim().is_empty() {
            return Some(text.to_string());
        }
    }
    None
}

/// Does the `<` at the cursor open a **template argument list that a `(` immediately follows**?
///
/// The question a run of names has to answer before it may take one more: `_STD _Convert_size<size_type>(_Length)`
/// is one qualified name and a call, while `vector<int> v` is a type and a declarator, and the two are the same
/// tokens up to the `>`. What separates them is **what comes after the list closes** — a `(` — and that is a fact
/// about the tokens rather than about the names, which is why this needs no table.
///
/// Bounded, and each bound has a reason:
///
/// * the window is [`TEMPLATE_ARGUMENT_WINDOW`] tokens. A template argument list longer than a screenful is not
///   what this rule is for, and the rule may say "not this shape" without cost: the reading it declines is the one
///   the parser had before it existed;
/// * the scan **stops at a `;`, `{` or `}`**, which cannot occur inside a template argument list. Without that, a
///   file whose `<` was a comparison would have the scan run to the end of the window looking for a `>` that
///   belongs to something else entirely — `a < b;` would consume the next statement in the search;
/// * a **`(`** at depth zero ends it too, and for the same reason: `f(a < b, c > d)` is a comparison in a call,
///   and reading it as a template-id would swallow the call's parentheses.
///
/// `>>` needs no case of its own: the lexer leaves each `>` on its own token (`CppLexer::tokenize`), which is the
/// same property the template parameter list reader relies on.
fn a_template_id_here_is_called(p: &CppParser) -> bool {
    let window = p.peek_token_kind_at(1..TEMPLATE_ARGUMENT_WINDOW);
    let mut depth = 0usize;

    for (index, kind) in window.iter().enumerate() {
        match kind {
            CppTokenKind::Less => depth += 1,
            CppTokenKind::Greater => {
                if depth == 0 {
                    return false;
                }
                depth -= 1;
                if depth == 0 {
                    // **The list closed here** — and the answer is the token after it, which is why the window is
                    // read one past the `>` rather than stopping at it.
                    return window.get(index + 1) == Some(&CppTokenKind::LeftParen);
                }
            }
            // Not a template argument list at all: a statement or a block boundary cannot appear inside one.
            CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace => {
                return false;
            }
            // A `(` before the list closed: this `<` was a comparison inside a call.
            CppTokenKind::LeftParen if depth == 0 => return false,
            _ => {}
        }
    }

    false
}

/// **How far a `<` is followed looking for the `>` that closes it and the `(` that must follow.**
///
/// Generous enough for the arguments MSVC's headers write — `_Convert_size<size_type>`, `_Refancy_maybe_null<_Tptr>`,
/// `_Max_limit<difference_type>` are all one or two tokens — and short enough that the scan is a fixed cost on a
/// question asked once per name in a run.
const TEMPLATE_ARGUMENT_WINDOW: usize = 8;

/// Does a token that can only **begin an operand** follow the `)` matching the `(` at the cursor?
///
/// See [`is_a_type_in_parentheses`], which is the only caller: the answer is what turns `(size_t)size` into a cast
/// without a type table. The scan is bounded and depth-tracked: it walks to the `)` that closes *this* `(`, so a
/// nested call or a parenthesised subexpression inside does not end it early.
fn an_operand_follows_the_parentheses(p: &CppParser) -> bool {
    let mut depth = 0isize;
    // Where the token after the group that closes the cursor's `(` stands, once it is known.
    let mut after_the_group = None;

    for (index, kind) in p.peek_token_kind_at(1..128).iter().enumerate() {
        match kind {
            CppTokenKind::LeftParen => depth += 1,
            CppTokenKind::RightParen => {
                depth -= 1;
                if depth < 0 {
                    // This is the `)` that closes the cursor's `(`; the token after it is the question.
                    after_the_group = Some(index + 2);
                    break;
                }
            }
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
    }

    let Some(mut offset) = after_the_group else {
        return false;
    };

    // **…but a run of further groups is stepped over first**, because that is how a cast of a cast is written:
    //
    // ```cpp
    // (__v32bf)(__m512bh) _mm512_setzero_si512 ()          // bits/avx10_2-512minmaxintrin.h:40
    // (T)(U) 1
    // ```
    //
    // The question is asked about the token after the *last* of them, and the answer is the same one: an operand
    // there means the first parentheses held a type, because `(T)(U) 1` and `(f)(a) 1` are not expressions — two
    // operands in a row is not a thing, and neither is an operand after a call. A bare `(f)(a)` (nothing after)
    // still reads as the call it is, and so does `(f)(a)(b)`, because what follows the last group there is `;`.
    //
    // The `(` exclusion in `starts_an_operand` is what makes this safe to do by scanning: the token that would
    // make a *continuation* ambiguous is exactly the one being stepped over, and only a run of them is skipped —
    // never a single group followed by something that could be a call's argument.
    while p.peek_token_kind_at(offset..offset + 1).first() == Some(&CppTokenKind::LeftParen) {
        let mut inner = 0isize;
        let mut closed = false;

        for (index, kind) in p.peek_token_kind_at(offset..128).iter().enumerate() {
            match kind {
                CppTokenKind::LeftParen => inner += 1,
                CppTokenKind::RightParen => {
                    inner -= 1;
                    if inner == 0 {
                        offset += index + 1;
                        closed = true;
                        break;
                    }
                }
                CppTokenKind::Eof | CppTokenKind::None => return false,
                _ => {}
            }
        }

        if !closed {
            return false;
        }
    }

    starts_an_operand(p, offset) || a_braced_initialiser_follows(p, offset)
}

/// Does a **braced initialiser** follow at `offset` — C99's *array-typed* compound literal?
///
/// ```c
/// const char *text = (const char[]){"compound"};
/// int n = ((int[]){1, 2})[index];
/// ```
///
/// The type name ends in `[]`, so no `*` closes the group and no ordinary operand follows; the whole construct was
/// reported `expected primary expression` at the type (measured on a nine-file C corpus, `aggregates.c`'s one syntax
/// error — and the reason every member of that file went unoffered).
///
/// **Here rather than in [`starts_an_operand`]**, which also answers whether a `<…>` is a template argument list:
/// `Vec<int[4]>{}` is a braced initialisation of a template-id, and counting `{` as an operand there turned its `<` into
/// a comparison — measured, `an_array_type_is_read_as_a_type_and_an_index_as_an_expression` went red.
fn a_braced_initialiser_follows(p: &CppParser, offset: usize) -> bool {
    p.peek_token_kind_at(offset..offset + 1).first() == Some(&CppTokenKind::LeftBrace)
}

/// Does the significant token `offset` places ahead of the cursor **begin an operand**?
///
/// The one question two decisions share, and in both it is the deciding evidence rather than a hint:
///
/// * a **cast** — `(size_t)size`: an operand after the `)` means the parentheses held a type, because two
///   operands in a row is not an expression in any grammar;
/// * a **template-id** — `a < b > c`: an operand after the `>` means the `<` was a comparison, because a
///   template-id cannot be followed by one either.
///
/// The set is deliberately narrow: a token that can begin an operand *and* appear as an infix operator is left
/// out, because in that case both readings are valid expressions and the cast or template reading would take
/// working code apart. What is left is a token that has no other job:
///
/// * an **identifier** and a **literal** — `x`, `1.5`, `"s"`, `'c'`, `true`, `nullptr`, `1_km`;
/// * a **keyword that is only ever a prefix** — `sizeof`, `new`, `throw`, `noexcept(...)`, `co_await`;
/// * `!`, `~`, `this` — unary, and `this` is an operand.
///
/// Left out, with the reason each one needs:
///
/// | token | why not |
/// |---|---|
/// | `(` | `(f)(x)` is a call, and `A<B>(x)` a functional cast — both are continuations |
/// | `*` `&` `+` `-` `++` `--` | each is a binary operator as well as a prefix — `(a) - b` is a subtraction |
/// | `[` | `(a)[b]` is an index, and `A<B>[0]`… is not, but the token itself cannot say so |
/// | `,` `;` `)` `]` `}` `:` `?` | they *end* something rather than begin an operand |
fn starts_an_operand(p: &CppParser, offset: usize) -> bool {
    matches!(
        p.peek_token_kind_at(offset..offset + 1).first(),
        Some(
            CppTokenKind::Identifier
                | CppTokenKind::IntegerLiteral
                | CppTokenKind::FloatingLiteral
                | CppTokenKind::StringLiteral
                | CppTokenKind::CharLiteral
                | CppTokenKind::UserDefinedLiteral
                | CppTokenKind::TrueKeyword
                | CppTokenKind::FalseKeyword
                | CppTokenKind::NullptrKeyword
                | CppTokenKind::ThisKeyword
                | CppTokenKind::LogicalNot
                | CppTokenKind::Tilde
                | CppTokenKind::SizeofKeyword
                | CppTokenKind::AlignofKeyword
                | CppTokenKind::TypeidKeyword
                | CppTokenKind::NewKeyword
                | CppTokenKind::DeleteKeyword
                | CppTokenKind::ThrowKeyword
                | CppTokenKind::CoAwaitKeyword
                | CppTokenKind::NoexceptKeyword
        )
    )
}

/// Do the parentheses at the cursor close with a `*`, `&` or `&&` that a **type** ended with?
///
/// The one shape that decides a cast without the type table, and it is decided by what is *missing*: a binary
/// operator needs a right operand, so a pointer or reference operator immediately before the `)` cannot be one.
///
/// ```text
/// (MyType*)p    `*` closes the parentheses  -> no right operand -> a type
/// (a * b)       `*` has `b` after it        -> an operator       -> an expression
/// (a* b)        same, however it is spaced
/// ```
///
/// The name in front still has to look like a name, which is what the second half checks: `(a*)` with `a` a
/// plain undeclared name is the same shape as `(MyType*)`, and the two cannot be told apart — so it takes the
/// same reading, and a cast of a name is far likelier there than a multiplication with its right operand
/// missing, which is not well formed at all.
fn closes_with_a_pointer_operator(p: &CppParser) -> bool {
    // The window up to the matching `)`. A `(` inside it means the parentheses hold a call, whose own tokens are
    // not this parenthesis's business.
    let mut contents = Vec::new();
    for kind in p.peek_token_kind_at(1..64) {
        match kind {
            CppTokenKind::RightParen => break,
            CppTokenKind::LeftParen => return false,
            other => contents.push(other),
        }
    }

    // `*`, `&`, `&&` and the cv-qualified spellings `* const`, `& const`.
    let mut last = contents.len();
    while last > 0
        && matches!(
            contents[last - 1],
            CppTokenKind::ConstKeyword | CppTokenKind::VolatileKeyword
        )
    {
        last -= 1;
    }

    last > 0
        && matches!(
            contents[last - 1],
            CppTokenKind::Star | CppTokenKind::Ampersand | CppTokenKind::LogicalAnd
        )
}

/// Parse a `new` expression: `new T`, `new T[4]`, `new T(1, 2)`, `new T{1}`, `new (buf) T()`, `::new (buf) T()`.
///
/// The node is a [`CppSyntaxKind::NewExpr`] rather than the `UnaryExpr` this used to produce, because `new`
/// is not an operator applied to an operand: its operand is a *type*, and the parentheses that follow it are a
/// constructor call rather than a grouping. `UnaryExpr(NewKeyword, CallExpr(Widget, 1, 2))` — which is what the
/// old rule built for `new Widget(1, 2)` — says the operand is a call, which is a different construct.
///
/// The leading `::` is optional and is read here rather than in the caller's arm, so that the qualification is
/// part of the allocation node it qualifies instead of a sibling of it. The caller decides *whether* this rule
/// gets the expression — see [`parse_unary_expr`], which is the only place that can see the two tokens together.
fn parse_new_expr(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::NewExpr);

    if p.current_token() == CppTokenKind::Scope {
        p.bump(); // `::`
    }
    p.bump(); // `new`

    if let Err(err) = parse_new_type_and_initializer(p) {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = parse_new_declarator_suffixes(p) {
        p.close_marks_above(base);
        return Err(err);
    }
    if let Err(err) = parse_new_initializer(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    // `new Widget(1)->run()` and `new int[4][i]` are one expression, so the postfix loop continues from the
    // allocation rather than from whatever follows it.
    let allocation = m.complete(p);
    parse_postfix_suffixes(p, allocation)
}

/// Parse the type a `new` expression allocates, with the placement arguments that may precede it.
///
/// `new` is the one expression whose operand is a **type**, and the type grammar is the only thing that can
/// read one. What makes it awkward rather than trivial is that `new` also takes an optional parenthesised
/// *expression* before the type — placement new, `new (buffer) Widget()` — so the `(` at the cursor is either
/// the start of the allocation type's own declarator or a placement list, and the tokens do not say which:
///
/// ```text
/// new (buf) Widget()     placement: the parentheses hold an expression
/// new (Widget)()         no placement: the parentheses hold a type, and are the initializer
/// ```
///
/// # How the two are told apart
///
/// A cheap check first, then a backtrack for what it cannot decide. The check claims only the shapes that
/// *cannot* be a type — a list with a comma in it, or an element that starts with a literal or a call — which
/// is what both of the placement forms that appear in practice look like: `new (buf, size) Widget()` and
/// `new (1) Widget()`. Everything else is genuinely ambiguous, because `(buf)` and `(Widget)` are the same
/// token sequence, so it is settled by trying: the placement reading is attempted, and if no type follows the
/// parentheses the whole attempt is rewound and the type reading takes them instead.
///
/// The rollback is why the speculative region starts *before* the parentheses rather than after them: in
/// `new (Widget)()` the placement reading consumes `(Widget)`, finds `(` where the type should be, and the
/// rewind has to put back both the parentheses and the expression node built inside them.
fn parse_new_type_and_initializer(p: &mut CppParser) -> ParseResult {
    if p.current_token() == CppTokenKind::LeftParen {
        let checkpoint = p.checkpoint();

        if placement_arguments_at(p) {
            let placement = p.mark(CppSyntaxKind::ArgumentList);
            decls::parse_expression_list(p, CppTokenKind::RightParen)?;
            placement.complete(p);
            return parse_a_type_here(p);
        }

        // The parentheses could be either, so the type reading is tried *with* them — which is the reading
        // that makes `new (Widget)(1)` an allocation of `Widget` initialised with `1`, and the one the
        // placement reading cannot produce because it would leave the type nowhere to be.
        //
        // The placement reading is then only available when the type reading refuses, and the two are
        // distinguished by the whole statement rather than by the parentheses: `new (buf) Widget()` fails here
        // at the type — `(buf) Widget` is not a type — and `new (Widget)(1)` succeeds.
        if parse_a_type_here(p).is_ok() {
            return Ok(crate::parser::CompleteMarker::empty());
        }
        p.rollback(checkpoint);

        // `new (buf) Widget()`: a placement list, and then the type it allocates.
        let placement = p.mark(CppSyntaxKind::ArgumentList);
        decls::parse_expression_list(p, CppTokenKind::RightParen)?;
        placement.complete(p);
    }

    parse_a_type_here(p)
}

/// Parse a type-id at the cursor, requiring that it consume something.
///
/// [`types::parse_type_id`] succeeds having consumed nothing when there is no type, which is the correct
/// answer for a caller that only has to *attach* a type and is the wrong one here: `new` with no type is not a
/// `new` at all. The progress check turns "it parsed" into "there was a type".
/// Parse a type-id at the cursor, requiring that it consume something.
///
/// [`types::parse_type_id_with`] succeeds having consumed nothing when there is no type, which is the
/// correct answer for a caller that only has to *attach* a type and the wrong one here: `new` with no type is
/// not a `new` at all. The progress check turns "it parsed" into "there was a type".
///
/// `a_name_may_be_a_type` is `false` and that is the whole reason this wrapper exists: in a `new`, the
/// parentheses before the type may be a **placement list**, so `new (Widget)(1)` and `new (Widget*)()` must be
/// told apart by whether `Widget` is a type the file declares — not by whether it looks like one. See
/// [`types::parse_type_id_with`].
fn parse_a_type_here(p: &mut CppParser) -> ParseResult {
    let before = p.current_token_index();

    types::parse_type_id_for_an_allocation(p)?;
    if p.current_token_index() == before {
        return Err(CppParseError::syntax_error_from(
            &t!("expected a type to allocate"),
            p.current_token_range(),
        ));
    }

    Ok(crate::parser::CompleteMarker::empty())
}

/// Are the parentheses at the cursor certainly a placement-argument list rather than the start of a type?
///
/// Only the two shapes that cannot be a type are claimed — see [`parse_new_type_and_initializer`] for why the
/// rest is left to a backtrack. Answered as "cannot be a type" rather than "is an expression" so that the
/// answer stays stable as the type grammar grows: every token it learns to read only makes this *more* often
/// false, which is the safe direction — a placement list read as a type fails the parse and is rewound, while
/// a type read as a placement list would consume the allocation's own type as an expression.
fn placement_arguments_at(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::LeftParen {
        return false;
    }

    // The tokens of the list, with the opening `(` dropped so that position 0 is the first element's first
    // token. That is what makes "is this token at an element start?" a question about the previous token.
    let scan = p.peek_token_kind_at(1..64);
    let mut depth = 0isize;

    for (position, kind) in scan.iter().enumerate() {
        match kind {
            // A `(` where a type would have to be is a call, and a call is a value — so this is the
            // `new (buf()) T()` form. Checked before the bracket arm below, which counts the same token as
            // nesting.
            CppTokenKind::LeftParen if at_element_start(&scan, position) => return true,
            CppTokenKind::LeftParen | CppTokenKind::LeftBracket | CppTokenKind::LeftBrace => {
                depth += 1
            }
            CppTokenKind::RightParen | CppTokenKind::RightBracket | CppTokenKind::RightBrace => {
                if depth == 0 {
                    return false;
                }
                depth -= 1;
            }
            // A comma at the list's own depth separates elements rather than nesting, and two elements cannot
            // be one type-id.
            CppTokenKind::Comma if depth == 0 => return true,
            // An element that begins with a literal is a value. `new (p, size) T()` is the form this catches.
            CppTokenKind::IntegerLiteral
            | CppTokenKind::FloatingLiteral
            | CppTokenKind::StringLiteral
            | CppTokenKind::CharLiteral
            | CppTokenKind::UserDefinedLiteral
            | CppTokenKind::TrueKeyword
            | CppTokenKind::FalseKeyword
            | CppTokenKind::NullptrKeyword
                if at_element_start(&scan, position) =>
            {
                return true;
            }
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
    }

    false
}

/// Is the token at `position` the first of an element of the list being scanned?
///
/// The list's first token is one, and so is the token after a top-level `,`. Anything else is in the middle of
/// an element, which is what keeps `(Widget)` from being read as a value: its `W` is an identifier at an
/// element start, and identifiers are not evidence — they are the token that a type and an expression share.
fn at_element_start(scan: &[CppTokenKind], position: usize) -> bool {
    position == 0 || scan.get(position - 1) == Some(&CppTokenKind::Comma)
}

/// Parse the array bounds of a `new` expression: the `[4]` of `new int[4]`, or the `[]` of `new int[]`.
///
/// The bound is optional in both directions: `new int[]` is an array of unknown bound, and a `new` of a
/// non-array type has no brackets at all. A `new int[2][3]` is two bounds, which is why this is a loop rather
/// than one branch.
fn parse_new_declarator_suffixes(p: &mut CppParser) -> ParseResult {
    while p.current_token() == 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);
    }

    Ok(crate::parser::CompleteMarker::empty())
}

/// Parse the initializer a `new` expression may carry: `new Widget(1, 2)`, `new int{3}`.
///
/// An empty `()` is kept as an initializer rather than dropped: `new Widget()` and `new Widget` are the same
/// allocation, and keeping the parentheses is what lets a consumer tell "value-initialised explicitly" from
/// "default-initialised", which is a distinction C++ makes and a formatter has to preserve.
fn parse_new_initializer(p: &mut CppParser) -> ParseResult {
    match p.current_token() {
        CppTokenKind::LeftParen => {
            let init = p.mark(CppSyntaxKind::Initializer);
            if let Err(err) = decls::parse_expression_list(p, CppTokenKind::RightParen) {
                init.undo(p);
                return Err(err);
            }
            init.complete(p);
        }
        CppTokenKind::LeftBrace => {
            let init = p.mark(CppSyntaxKind::Initializer);
            if let Err(err) = decls::parse_braced_initializer(p) {
                init.undo(p);
                return Err(err);
            }
            init.complete(p);
        }
        _ => {}
    }

    Ok(crate::parser::CompleteMarker::empty())
}

/// 解析后缀表达式 (函数调用、数组访问、成员访问、后增后减等)
fn parse_postfix_expr(p: &mut CppParser, fold_operand: bool) -> ParseResult {
    let expr = parse_primary_expr(p, fold_operand)?;
    parse_postfix_suffixes(p, expr)
}

/// The suffixes that may follow a complete expression: calls, indexes, member access, `++`/`--`.
///
/// Split out from [`parse_postfix_expr`] because one construct reaches it with an expression already in hand:
/// [`parse_new_expr`] parses `new T(args)` as an allocation and then has to keep reading, since
/// `new Widget(1)->run()` is one expression and `new int[4][i]` another. Having two copies of the suffix loop
/// is how the two would come to disagree about what a suffix is.
///
/// `expr` must be a completed node; it is re-parented by whichever suffix is found.
fn parse_postfix_suffixes(
    p: &mut CppParser,
    mut expr: crate::parser::CompleteMarker,
) -> ParseResult {
    loop {
        match p.current_token() {
            CppTokenKind::LeftParen => {
                // 函数调用
                let m = expr.precede(p, CppSyntaxKind::CallExpr);

                // 解析参数列表。The listed reading is [`parse_call_arguments`]; the fallback below is the other
                // half of that rule — a macro's arguments are tokens, not expressions, and a call whose
                // arguments do not read is the only place the two can be told apart.
                let before_the_arguments = p.checkpoint();
                if parse_call_arguments(p).is_err() {
                    p.rollback(before_the_arguments);
                    decls::parse_balanced_token_group(p, CppSyntaxKind::ArgumentList)?;
                }

                expr = m.complete(p);
            }
            // **An attribute after a constraint ends it.** An expression cannot write `[[` — the second `[` has
            // nothing to read as an operand — so when one is there, the constraint is over and what follows belongs
            // to the declaration. MSVC's standard library writes exactly that:
            //
            // ```cpp
            // template <class _Ty, _Tuple_like _Tuple> requires _Can_make_from_tuple<_Ty, _Tuple>
            // [[nodiscard]] constexpr _Ty make_from_tuple(_Tuple&& _Tpl) noexcept { … }
            // ```
            //
            // Without this the subscript rule claimed the `[`, the constraint failed to parse, the requires-clause
            // was refused, and the *declaration* failed with it — leaving the recovery to swallow the rest of the
            // unit. Measured: most of the 27 errors left in a 2.1 MB translation unit were this one shape.
            //
            // **Only inside a constraint.** Saying it for every expression was tried and three tests failed at
            // once, because a `[[` in operand position is a real subscript of a real array:
            // `template <typename _Tp, int _Nm> constexpr bool d<_Tp[_Nm]> = true;` is a partial specialization
            // over an array, and refusing the subscript there lost the `ArrayType` — a wrong tree, silently. A
            // constraint is the one position where no subscript can be followed by an attribute, because the
            // attribute is what ends the constraint.
            CppTokenKind::LeftBracket
                if p.is_in_a_constraint()
                    && p.peek_next_token() == CppTokenKind::LeftBracket
                    && p.peek_token_kind_at(1..3).last() == Some(&CppTokenKind::Identifier) =>
            {
                break;
            }
            CppTokenKind::LeftBracket => {
                // 数组访问
                let m = expr.precede(p, CppSyntaxKind::IndexExpr);
                p.bump(); // consume '['
                parse_expr(p)?;
                expect_token(p, CppTokenKind::RightBracket)?;
                expr = m.complete(p);
            }
            CppTokenKind::Dot | CppTokenKind::Arrow => {
                // 成员访问
                let m = expr.precede(p, CppSyntaxKind::IndexExpr);
                let operator_range = p.current_token_range();
                p.bump(); // consume '.' or '->'

                // **A member name that starts on the next line is not this access's member.** A reader typing
                // `p->` leaves the operator at the end of a line, and the recovery used to take the next
                // statement's first identifier as the member name: measured, `p->\n\n    Widget w;\n    w.` parsed
                // as one `ExpressionStat "p->\n\n    Widget"`, the declaration of `w` disappeared, and the
                // completion after `w.` answered nothing while a hover on `w` said it was not declared.
                //
                // Legal C++ allows the break — and every formatter puts it *before* the operator (`.member` at
                // the start of a line), not after it — so a member on the next line is a shape no real file has
                // and an incomplete edit is the shape millions of files have. The access simply ends here and
                // the missing-name branch below says what is missing.
                let same_line = p.lines_between(
                    operator_range.end_offset(),
                    p.current_token_range().start_offset,
                ) == 0;

                // `decltype(t)::template rebind<U>` and `x.template rebind<U>` are the same disambiguator as the
                // one in the qualified-name loop below: `template` marks the `<` after the name as the start of
                // template arguments. It is accepted in both positions or neither, because which of the two a
                // reader meets depends only on whether the object has a name.
                if same_line
                    && p.current_token() == CppTokenKind::TemplateKeyword
                    && matches!(
                        p.peek_next_token(),
                        CppTokenKind::Identifier | CppTokenKind::OperatorKeyword
                    )
                {
                    p.bump(); // `template`
                }

                // **A qualified member name**: `this->Base::store(v)`, `p->Outer<T>::Inner::f()`,
                // `x.Base::template f<T>()`. Each segment before a `::` is part of the name, and it is the last one
                // that is the member. MSVC's `<atomic>` writes `const_cast<atomic*>(this)->_Base::store(_Value)`
                // in thirty places, and every one of them was `expected ;`.
                while same_line && p.current_token() == CppTokenKind::Identifier {
                    if p.peek_next_token() == CppTokenKind::Less {
                        // A template-id qualifier, `Outer<T>::f`: kept only when a `::` follows the arguments, which
                        // is what separates it from a comparison written after a member access.
                        let before_the_qualifier = p.checkpoint();
                        p.bump();
                        if types::parse_template_argument_list(p).is_err()
                            || p.current_token() != CppTokenKind::Scope
                        {
                            p.rollback(before_the_qualifier);
                            break;
                        }
                    } else if p.peek_next_token() == CppTokenKind::Scope {
                        p.bump(); // the qualifier
                    } else {
                        break;
                    }
                    p.bump(); // `::`
                    if p.current_token() == CppTokenKind::TemplateKeyword
                        && matches!(
                            p.peek_next_token(),
                            CppTokenKind::Identifier | CppTokenKind::OperatorKeyword
                        )
                    {
                        p.bump(); // `template`
                    }
                }

                if same_line && p.current_token() == CppTokenKind::Identifier {
                    p.bump();
                    // The member's template arguments, when it has any — `x.template f<int>()` needs the
                    // arguments to be *attached* here, because `f<int>()` read as a comparison would compare
                    // `x.template f` against `int` and then call `()` on the result.
                    //
                    // The same `<` ambiguity as in the name branch, decided the same way: read them, and keep them
                    // only if what follows can follow a template-id. `a.b < c > d` is a comparison written after a
                    // member access, and the member is `b` — so the rollback here rewinds to just after the name,
                    // not to the `.b`, and the comparison rule then sees the whole `a.b < c > d`.
                    if types::could_start_template_arguments(p) {
                        let before_the_arguments = p.checkpoint();
                        let read = types::parse_template_argument_list(p);

                        if read.is_err() || starts_an_operand(p, 0) {
                            p.rollback(before_the_arguments);
                        }
                    }
                } else if same_line && p.current_token() == CppTokenKind::OperatorKeyword {
                    // An **explicit call to a member operator**: `x.operator<(...)`, `x.operator->()`,
                    // `x.operator std::string_view()`. The name after a `.` is an operator name as much as a
                    // member name is, and the same reader a declaration's operator name goes through is what
                    // reads it — see [`types::parse_operator_name_here`], which is exposed for exactly
                    // this: one answer to "what is an operator name" rather than two.
                    types::parse_operator_name_here(p)?;
                    // `x.template operator()<I>(args)`: the explicit template arguments of a call operator.
                    if types::could_start_template_arguments(p) {
                        let before_the_arguments = p.checkpoint();
                        let read = types::parse_template_argument_list(p);
                        if read.is_err() || starts_an_operand(p, 0) {
                            p.rollback(before_the_arguments);
                        }
                    }
                } else if same_line && p.current_token() == CppTokenKind::Tilde {
                    // A **pseudo-destructor call**: `p->~T()`, `x.~basic_string()`, `x.~int()`.
                    //
                    // `~name` is how a destructor is spelled, in an expression as much as in a declaration, and what
                    // follows may be a name, a qualified name, a template-id — or, the case that was missing, a
                    // **builtin type**. The standard's rule is that after `~` stands a `type-name`, and `int` is one
                    // while being no identifier at all. Measured before this: `x.~int()` stopped at the `int` with
                    // `expected ';' after expression`, while `x.~T()` and `x.~S()` parsed — the branch below accepted
                    // only `Identifier | Scope`, so it matched nothing, left an empty `NameExpr` behind, and the
                    // statement layer then had a `~` with no name.
                    p.bump(); // `~`
                    if p.current_token() == CppTokenKind::Identifier
                        || p.current_token() == CppTokenKind::Scope
                        || starter_of_a_builtin_type(p.current_token())
                    {
                        let name = p.mark(CppSyntaxKind::NameExpr);
                        if p.current_token() == CppTokenKind::Scope {
                            p.bump();
                        }
                        // **A builtin type is the whole name.** `~unsigned` is one type-name and not a name with
                        // something after it, so there is nothing for the loop below to walk — taking its token and
                        // completing is the same shape the identifier path ends in.
                        if starter_of_a_builtin_type(p.current_token()) {
                            p.bump();
                            name.complete(p);
                            continue;
                        }
                        while same_line && p.current_token() == CppTokenKind::Identifier {
                            p.bump();
                            // **The name's template arguments**, the same `<` ambiguity the identifier branch above
                            // resolves the same way: read them and keep them only if what follows can follow a
                            // template-id. Without this the `<` of `x.~A<int>()` was left standing, the expression
                            // rule read it as a comparison, and `int` became an operand with no primary expression —
                            // measured, `expected primary expression` at the `int`.
                            if types::could_start_template_arguments(p) {
                                let before_the_arguments = p.checkpoint();
                                let read = types::parse_template_argument_list(p);
                                if read.is_err() || starts_an_operand(p, 0) {
                                    p.rollback(before_the_arguments);
                                }
                            }
                            if p.current_token() == CppTokenKind::Scope {
                                p.bump();
                                continue;
                            }
                            break;
                        }
                        name.complete(p);
                    }
                } else {
                    // **Nothing is written after the operator**, which is the state a completion is asked in and
                    // the commonest thing a user's cursor is found in the middle of. The member name is mandatory
                    // here, but returning `Err` is the wrong way to say so: an `Err` out of `parse_expr` reaches
                    // the statement layer as a failed statement, and the recovery that follows consumes the `}`
                    // that closes the block — so `w.` at the end of a body pushed every declaration written after
                    // the body *into* the body.
                    //
                    // A zero-width `MissingNode` says the same thing without giving up the expression: the member
                    // access is complete, its object and operator are in the tree for a cursor to be resolved
                    // against, and the user is told what is missing. It is the pattern `parse_compound_stat` uses
                    // for a missing `}`, for the same reason — a position being edited is not a failed construct.
                    p.emit_missing_node();
                    p.push_error(CppParseError::syntax_error_from(
                        &t!("expected identifier after member access operator"),
                        p.current_token_range(),
                    ));
                    expr = m.complete(p);
                    // Nothing else can follow that is a suffix of *this* expression: the next token is whatever
                    // ended the statement. Leaving the loop here is what keeps the error local.
                    break;
                }

                expr = m.complete(p);
            }
            CppTokenKind::PlusPlus | CppTokenKind::MinusMinus => {
                // 后增/后减
                let m = expr.precede(p, CppSyntaxKind::UnaryExpr);
                p.bump(); // consume '++' or '--'
                expr = m.complete(p);
            }
            // A braced initializer after an expression: `Vec<int>{1, 2}`, `std::string{"x"}`,
            // `std::pair<int, int>{1, 2}`.
            //
            // This is C++11's list-initialisation of a *temporary*, and it is the one place a `{` follows an
            // expression rather than opening a block. Reading it here rather than in the primary rule is what
            // makes the type optional to the parser: `Vec<int>` is a name or a template-id that the expression
            // grammar already reads, and all that was missing was the braces after it.
            //
            // A `{` that is *not* this — the block of a lambda, a compound statement after a declaration —
            // never reaches the loop, because the lambda consumes its own body and a statement's `{` is the
            // next statement rather than a suffix of this expression.
            //
            // **Except inside a constraint**, where the `{` belongs to the definition the constraint is written
            // on. See [`CppParser::is_in_a_constraint`]: `requires C<T> { }` would otherwise come out as a
            // constraint of `C<T>{}` with the body missing.
            //
            // **…and except where a `{` cannot be that body**, which is two places and the same argument both
            // times: the exception is about what *can* stand here, not about being lenient.
            //
            // * **inside a compound requirement's braces** — the `{` is nested in the requirement's own `{ }`, so
            //   it cannot be the definition's body;
            // * **inside parentheses** — `requires (D{1} < D{2})` still has its `)` to come, and a definition's
            //   body never arrives before the clause's own parenthesis closes. [`an_operand_is_decisive`] asks the
            //   identical question about the identical token and answers it with the same `is_open(ParenExpr)`.
            //
            // The parenthesised spelling was measured, not reasoned about: `<chrono>` and `<filesystem>` both write
            // `requires (!treat_as_floating_point_v<…> && _Duration{1} < days{1})`, and without this arm the `{`
            // was refused, the clause reported ``expected `)`, but get `{` `` and everything after it in the
            // declaration went with it — three each, from one construct in a shared header.
            //
            // **…and inside a compound requirement's braces**, where the `{` cannot be that body: it is
            // nested inside the requirement's own `{ }`, and the reading it gets is the ordinary one for a `{`
            // after an expression:
            //
            // ```cpp
            // { _Begin{}(__t) } -> bidirectional_iterator;        // bits/ranges_base.h:214
            // ```
            //
            // There the `{` after `_Begin` is a **list-initialised temporary** and the `(__t)` that follows calls
            // it — read as the requirement's closing brace instead, the rule reported `expected }, but get {` and
            // every requirement after it in the body became rubble (24 diagnostics in `bits/ranges_base.h`). The
            // `Requirement` node is open exactly while the cursor is inside those braces, which is what makes the
            // question answerable without a second flag.
            CppTokenKind::LeftBrace
                if !p.is_in_a_constraint()
                    || p.is_open(CppSyntaxKind::Requirement)
                    || p.is_open(CppSyntaxKind::ParenExpr) =>
            {
                let marks_before = p.open_marks();
                let m = expr.precede(p, CppSyntaxKind::InitListExpr);
                if let Err(err) = decls::parse_braced_initializer(p) {
                    // The node is closed as if its `}` had been present, which is the same recovery every other
                    // rule uses and is *not* the same as dropping it: `precede` may have re-parented the events
                    // of the expression already parsed into this node, and a marker left open over them would
                    // leave a forward reference the tree builder cannot resolve. Detaching the node without an
                    // event is what the mutation tests catch, and closing it is what keeps the braces in the
                    // tree as an initializer that is merely incomplete.
                    p.close_marks_above(marks_before);
                    return Err(err);
                }
                expr = m.complete(p);
            }
            // **A CUDA kernel launch.** `k<<<grid, block>>>(a, b)` is not C++ at all — `<<<` is `<<` and `<` — and
            // only a CUDA unit may read it that way ([`CppParser::cuda`]): in ordinary C++ the same tokens are three
            // shifts and a syntax error, so a project that never saw `nvcc` keeps exactly the parse it had.
            //
            // The configuration is an `ArgumentList` of its own because it is not a call's argument list: it holds 2
            // to 4 comma-separated *expressions* (`grid`, `block`, `shared memory bytes`, `stream`), and a consumer
            // that wants them must be able to tell them from the call's.
            CppTokenKind::LeftShift if p.cuda() && p.peek_next_token() == CppTokenKind::Less => {
                let m = expr.precede(p, CppSyntaxKind::CudaLaunchExpr);
                p.bump(); // `<<`
                expect_token(p, CppTokenKind::Less)?; // the third `<`
                let configuration = p.mark(CppSyntaxKind::ArgumentList);
                loop {
                    parse_assignment_expr(p)?;
                    if p.current_token() != CppTokenKind::Comma {
                        break;
                    }
                    p.bump();
                }
                configuration.complete(p);
                // **`>>>` is lexed as three `>`**, not as `>>` and `>`: the lexer's longest match for `>>` is the
                // shift operator, and it only reaches that length when the third `>` is not there. Both spellings are
                // accepted, because which one the lexer produced is its business rather than the grammar's.
                // The closing bracket is three `>` tokens, and the expressions above stop *before* it — see
                // `get_operator_precedence`. Consuming them is therefore unambiguous here.
                if p.at_the_end_of_a_launch_configuration() {
                    p.bump();
                    p.bump();
                    p.bump();
                } else {
                    expect_token(p, CppTokenKind::Greater)?;
                }
                // The call itself, when the launch has arguments written — `k<<<1, 1>>>()` and `k<<<1, 1>>>` are
                // both legal, and the second is the one a reader writes when the kernel takes nothing.
                if p.current_token() == CppTokenKind::LeftParen {
                    let before_the_arguments = p.checkpoint();
                    if parse_call_arguments(p).is_err() {
                        p.rollback(before_the_arguments);
                        decls::parse_balanced_token_group(p, CppSyntaxKind::ArgumentList)?;
                    }
                }
                expr = m.complete(p);
            }
            _ => break,
        }
    }

    Ok(expr)
}

/// 解析主表达式 (标识符、字面量、括号表达式等)
///
/// `fold_operand` is threaded down from [`parse_parenthesized_expression`] and is what licenses a bare `...` to
/// be an operand; anywhere else it is refused so that the constructs which spell `...` themselves keep it.
/// Is the token at the cursor a `decltype` that begins a **qualified name** — `decltype(x)::type`?
///
/// `false` for every token that is not a `decltype`, so it can be read as "is *this* the qualified spelling" at
/// both places that have to agree about it: the functional-conversion arm must **decline** when it is `true`, and
/// the name arm must **take** the tokens when it is.
///
/// The `::` has to be found by **matching the `decltype`'s own parentheses**, because the payload may contain
/// them: `decltype(f(a))::type`. No `peek` can do it — the parser has no "token after the matching bracket"
/// lookahead, which is the same reason [`decls::index_after_the_group`] counts rather than peeks.
fn a_decltype_that_begins_a_qualified_name(p: &CppParser) -> bool {
    if p.current_token() != CppTokenKind::DecltypeKeyword {
        return false;
    }

    if p.peek_next_token() != CppTokenKind::LeftParen {
        return false;
    }

    let mut index = decls::next_significant_index(p, p.current_token_index());
    let mut depth = 0isize;

    while index < p.token_count() {
        match p.token_kind_at(index) {
            CppTokenKind::LeftParen => depth += 1,
            CppTokenKind::RightParen => {
                depth -= 1;
                if depth == 0 {
                    let after = decls::next_significant_index(p, index);
                    return p.token_kind_at(after) == CppTokenKind::Scope;
                }
            }
            CppTokenKind::Eof | CppTokenKind::None => return false,
            _ => {}
        }
        index += 1;
    }

    false
}

/// `delete p`, `delete[] p`, and either of them written `::`-qualified.
///
/// The leading `::` is optional in the production ([expr.delete]: `::opt delete cast-expression`) and it is
/// **kept inside the node**, the same way [`parse_new_expr`] keeps `::new`'s: what it selects is the global
/// `operator delete`, which is a different function from a class's own, so dropping it would be dropping the
/// only thing it says.
///
/// Shared by the two arms in [`parse_primary_expr`] — `delete` and `::delete` — because the reading after the
/// keyword is the same and a second copy is where the next spelling gets forgotten.
fn parse_delete_expr(p: &mut CppParser, fold_operand: bool) -> ParseResult {
    let m = p.mark(CppSyntaxKind::UnaryExpr);

    if p.current_token() == CppTokenKind::Scope {
        p.bump(); // the global one
    }
    expect_token(p, CppTokenKind::DeleteKeyword)?;

    // `delete[] p` — the array form, which is a different `operator delete[]`.
    if p.current_token() == CppTokenKind::LeftBracket {
        p.bump();
        expect_token(p, CppTokenKind::RightBracket)?;
    }

    parse_unary_expr(p, fold_operand)?;
    Ok(m.complete(p))
}

fn parse_primary_expr(p: &mut CppParser, fold_operand: bool) -> ParseResult {
    match p.current_token() {
        // 字面量
        CppTokenKind::IntegerLiteral
        | CppTokenKind::FloatingLiteral
        | CppTokenKind::StringLiteral
        | CppTokenKind::CharLiteral
        | CppTokenKind::TrueKeyword
        | CppTokenKind::FalseKeyword
        | CppTokenKind::NullptrKeyword
        // A **user-defined literal** — `1_km`, `"a"_km`, `'c'_x` — is a literal like any other here. The lexer
        // produces the kind precisely so the parser will not read it as a plain number, and nothing was reading
        // it at all: the arm was missing, so `auto x = 1_km;` reported `expected primary expression` against a
        // token the lexer had gone out of its way to name.
        | CppTokenKind::UserDefinedLiteral => {
            let m = p.mark(CppSyntaxKind::LiteralExpr);
            let is_a_string = p.current_token() == CppTokenKind::StringLiteral;
            p.bump();

            // **Adjacent string literals are one literal**, which is translation phase 6 rather than a grammar
            // rule: `"a" "b"` concatenates, and the standard writes the run as a single *string-literal* sequence.
            // Reading the first and stopping left the rest for whatever came next, so
            //
            //     const char *s = "a" "b";
            //
            // ended its initialiser after `"a"` and reported `expected ;` against `"b"`. Nothing about the shape
            // is rare — it is how every long message in C and C++ is wrapped across lines, which is where this was
            // found (a LuaJIT host file, ten adjacent literals in one initialiser).
            //
            // They stay inside the one `LiteralExpr` node, because one string is what they produce. A literal
            // carrying a **user-defined suffix** is a different kind of thing — `"a"_km` is a call to
            // `operator""_km` rather than a string — so it ends the run instead of joining it.
            //
            // An **identifier** joins the run as well, and that is a statement about the preprocessor rather than
            // about the grammar: `"compiler[" COMPILER_ID "]"` is one string once `COMPILER_ID` has been expanded,
            // and a string literal followed by a name is not valid C++ in any other reading. This parser does not
            // run the preprocessor, so a macro in the middle of a message is the shape it has to accept — it is
            // how every CMake-generated and hand-written diagnostic string is spelled.
            // A **directive inside the run** is skipped the way the preprocessor would, and it is the shape a
            // generated file writes a message with a conditional middle in:
            //
            // ```c
            // const char* info = "["
            // #if defined(__clang__)
            //   "ON"
            // #else
            //   "OFF"
            // #endif
            //   "]";
            // ```
            //
            // The directive is emitted as the node it is — the tree stays lossless and a consumer can see it — and
            // the run continues past it. Nothing else can be meant by a `#` *here*: a string literal followed by a
            // directive is not C++ in any other reading, while a stray `#` anywhere else in an expression is still
            // reported, which is what keeps this from hiding real errors.
            while is_a_string
                && matches!(
                    p.current_token(),
                    CppTokenKind::StringLiteral
                        | CppTokenKind::Identifier
                        | CppTokenKind::Hash
                )
            {
                if p.current_token() == CppTokenKind::Hash {
                    stats::parse_preprocessor_directive(p)?;
                } else {
                    p.bump();
                }
            }

            Ok(m.complete(p))
        }

        // A **functional-notation conversion with a keyword type**: `bool(x)`, `int(y)`, `double(n)`.
        //
        // The same conversion as `(bool)x`, written the other way round, and it is everywhere a value is
        // normalised — `root.AddChild("code_style_check", bool(lint["codeStyle"]))` in a real file, which is where
        // this was found. A type keyword is neither an identifier nor in [`is_expression_keyword`], so no arm
        // matched it at all and the expression rule reported `expected primary expression` against the keyword
        // itself.
        //
        // **Two payloads, not one**: the braced spelling is the same construct — C++11's `T{…}`, and the way a
        // default-constructed value is written in generic code (`size_t{}`, `int{}`, `bool{true}`). Only the
        // parenthesis form was read here, so `int{}` had **no reading at all** in an expression: `return int{};`,
        // `g(int{})` and `auto a = int{};` all reported `expected primary expression` against the keyword, while
        // `size_t{}` — the same construct with a *name* — read. The `typename` arm below has taken both spellings
        // since it was written; the reader for the payload ([`parse_functional_payload`]) has taken both all along,
        // which is what makes this a guard rather than a rule.
        //
        // **A `{` here cannot be a declaration.** A simple-declaration needs a declarator, and `int{}`/`int{1}` has
        // none — so the expression reading is the only one the standard offers, and the declaration rule (which
        // runs first, and refuses an initialiser with no name to initialise) has already declined. `int(x);` is a
        // different matter and stays the declaration it is: there the parenthesised name is a declarator.
        // **…and `decltype(…)` is excepted, because a `::` after it makes it a *name* rather than a conversion.**
        // `decltype` is lexed as a type keyword, so this arm claimed it first and `decltype(v)::max` never reached
        // the name rule below — the `::` was left with nothing to continue. See
        // [`a_decltype_here_continues_a_name`], which is `true` for every other keyword here and only asks the
        // question `decltype` has an answer to.
        kind if types::is_type_specifier_keyword(kind)
            && matches!(
                p.peek_next_token(),
                CppTokenKind::LeftParen | CppTokenKind::LeftBrace
            )
            && !a_decltype_that_begins_a_qualified_name(p) =>
        {
            let m = p.mark(CppSyntaxKind::CastExpr);

            // The type is the **keyword and nothing else**. Handing these tokens to `parse_type_id` looks like the
            // obvious reuse and is wrong: a type-id continues with an *abstract declarator*, so it read `bool(x)`
            // as the function type "bool taking x" — a perfectly good type — and then had no `(` left for the
            // payload, reporting `expected (, but get ;` against the token after it. Functional notation takes a
            // simple-type-specifier, which is one word; every spelling with more than one is either invalid or a
            // declaration (`unsigned long(x)` declares a function).
            let the_type = p.mark(CppSyntaxKind::BuiltinType);
            p.bump();
            the_type.complete(p);

            // The payload, which may be **empty**: `int()`, `bool()` — a default-constructed temporary, and the
            // same reader the `typename` arm below uses. See [`parse_functional_payload`].
            if let Err(err) = parse_functional_payload(p) {
                m.undo(p);
                return Err(err);
            }
            Ok(m.complete(p))
        }

        // A **`typename`-qualified type used as a functional conversion**: `typename T::type{}`,
        // `typename T::type(x)`.
        //
        // A dependent name needs the keyword before it can be read as a type at all, and the standard allows a
        // typename-specifier wherever a simple-type-specifier may stand — the functional-notation conversion is one
        // of those places. libstdc++ writes it inside a condition, which is where it matters most
        // (`bits/basic_string.h:3944`):
        //
        // ```cpp
        // if _GLIBCXX17_CONSTEXPR (typename _Alloc_traits::is_always_equal{})
        // ```
        //
        // Without this arm `typename` reached the expression rule and nothing claimed it: `expected primary
        // expression` against the keyword, and the `if` — with everything after it — went with it.
        //
        // The type is read as a **name**, not as a type-id, and that is deliberate: a type-id continues with an
        // abstract declarator, so it would swallow the very parentheses this expression is made of —
        // `typename T::f(int)` would come out as one function *type* with no payload left. A functional conversion
        // takes a simple-type-specifier, which is a name.
        CppTokenKind::TypenameKeyword
            if matches!(
                p.peek_token_kind_at(1..2).first(),
                Some(&CppTokenKind::Identifier)
            ) =>
        {
            let m = p.mark(CppSyntaxKind::CastExpr);
            p.bump(); // `typename`

            let the_type = p.mark(CppSyntaxKind::TypenameType);
            if let Err(err) = types::parse_name(p) {
                the_type.undo(p);
                m.undo(p);
                return Err(err);
            }
            the_type.complete(p);

            // The payload: a parenthesised argument list — **possibly empty** (`typename T::type()`) — or a
            // braced one. It is not optional: without one these tokens are not an expression at all, so the arm
            // fails and the caller's other readings get their turn.
            if let Err(err) = parse_functional_payload(p) {
                m.undo(p);
                return Err(err);
            }

            Ok(m.complete(p))
        }

        // A name, possibly qualified (`std::vector`), and possibly a template-id
        // (`std::vector<int>`). Both forms appear as expressions — `std::move(x)`,
        // `std::vector<int>::size_type` — so the expression grammar has to accept them, not just the
        // type grammar.
        //
        // `operator` begins one too, and it is the *first* token of the name rather than a segment after a `::`:
        // `operator<=>(a, b)` in a requires-expression body is a call to the operator function, and the standard
        // library asks exactly that question (`compare`, `bits/ranges_cmp.h`). The segment loop below already read
        // an operator name in every position *except* this one — it is reached for `Foo::operator+()` but not for
        // a bare `operator+()`, because the arm's pattern did not include the keyword.
        // **A named cast**: `static_cast<T>(e)`, and the three others, which have the same shape.
        //
        // The shape is `keyword < type-id > ( expression )`, and every part of it is required: the `<` is what
        // separates the cast from a functional conversion, the `>` closes the type, and the parentheses hold the one
        // expression being converted. A pack expansion may follow the whole thing —
        // `static_cast<Ts&&>(args)...` — which the caller's own suffix rule takes.
        //
        // The four keywords were ordinary **identifiers** until this round, and the cost was invisible because
        // nothing errored: `static_cast<int>(x)` lexed as `static_cast` `<` `int` `>` `(` `x` `)` and parsed as a
        // comparison chain. Measured on MSVC's `<vector>`/`<xutility>`: 39 `auto` declarations refused with
        // `UnknownType("static_cast<size_t>")` and the like — the payload being the *left half of a comparison*
        // rather than a type, which is what gave the misreading away.
        CppTokenKind::StaticCastKeyword
        | CppTokenKind::DynamicCastKeyword
        | CppTokenKind::ConstCastKeyword
        | CppTokenKind::ReinterpretCastKeyword => {
            let m = p.mark(CppSyntaxKind::CastExpr);
            p.bump(); // the keyword

            let parsed = expect_token(p, CppTokenKind::Less)
                .and_then(|_| types::parse_type_id(p))
                .and_then(|_| expect_token(p, CppTokenKind::Greater))
                .and_then(|_| expect_token(p, CppTokenKind::LeftParen))
                // **The operand may be empty**: `static_cast<T>()` is a value-initialisation, and refusing it
                // would make this arm fail on a construct the grammar has to read.
                .and_then(|_| {
                    if p.current_token() == CppTokenKind::RightParen {
                        Ok(())
                    } else {
                        parse_expr(p).map(|_| ())
                    }
                })
                .and_then(|_| expect_token(p, CppTokenKind::RightParen));

            match parsed {
                Ok(()) => Ok(m.complete(p)),
                Err(err) => {
                    m.undo(p);
                    Err(err)
                }
            }
        }

        // **GNU's `&&label`** — the address of a label, which is the value a computed `goto` jumps to:
        //
        // ```c
        // static void *const TABLE[] = {&&state_zero, &&state_one};
        // goto *TABLE[state];
        // ```
        //
        // `&&` in expression position is otherwise a syntax error (it is the short-circuit operator and has no left
        // operand here), so this arm takes nothing away from a program that parses. Measured on a nine-file C corpus:
        // two of `gnu.c`'s four syntax errors, `expected primary expression` at the `&&` and then `expected ;, but get *`
        // at the `goto`.
        CppTokenKind::LogicalAnd
            if p.peek_next_token() == CppTokenKind::Identifier
                && p.language()
                    .support(crate::features::Feature::LabelsAsValues) =>
        {
            let m = p.mark(CppSyntaxKind::UnaryExpr);
            p.bump(); // `&&`
            p.bump(); // the label's name
            Ok(m.complete(p))
        }

        // **C11's `_Generic ( … )` before any name is read**, because it *starts* like a name: the arm below takes every
        // identifier, so an arm placed after it is never reached — which is exactly where this rule was first written,
        // and the file kept reporting `expected `;`` while the rule looked present. `_Generic` is a contextual keyword
        // (no token kind names it) and `_Generic (` is a shape no ordinary name position has: a name followed by an
        // argument list is a call, and C11 says this one is a selection.
        CppTokenKind::Identifier
            if p.current_token_text() == "_Generic"
                && p.peek_next_token() == CppTokenKind::LeftParen
                && p.language()
                    .support(crate::features::Feature::GenericSelection) =>
        {
            parse_generic_selection(p)
        }

        CppTokenKind::Identifier
        | CppTokenKind::Scope
        | CppTokenKind::OperatorKeyword
        | CppTokenKind::DecltypeKeyword
            if !is_expression_keyword(p)
                && (p.current_token() != CppTokenKind::DecltypeKeyword
                    || a_decltype_that_begins_a_qualified_name(p)) =>
        {
            let base = p.open_marks();
            let m = p.mark(CppSyntaxKind::IdentifierExpr);

            // A leading `::` makes the name fully qualified.
            if p.current_token() == CppTokenKind::Scope {
                p.bump();
            }

            loop {
                // A segment of the name. `~Foo` and `operator+` are segments too — they are how a destructor and
                // an operator are named — and refusing them is what made `Foo::~Foo()` and `Foo::operator+()`
                // report `expected a name after '::'` against perfectly ordinary definitions. Both are written
                // *after* a `::`, so nothing else can be at this position.
                //
                // `template` is the third member of that family: a *disambiguator*, not a name. In
                // `T::template rebind<U>` it says the `<` that follows `rebind` starts template arguments
                // rather than a comparison, which is the only thing that can be known about a name in a
                // template before its arguments are known. It is a keyword in this lexer rather than an
                // identifier, so the segment loop used to refuse it outright.
                if p.current_token() == CppTokenKind::TemplateKeyword {
                    p.bump();
                    // The keyword is followed by the name it qualifies, and by nothing else — `T::template ;` is
                    // not a name. Requiring the name keeps the keyword from standing in for one.
                    if !matches!(
                        p.current_token(),
                        CppTokenKind::Identifier
                            | CppTokenKind::OperatorKeyword
                            | CppTokenKind::Tilde
                    ) {
                        p.close_marks_above(base);
                        return Err(CppParseError::syntax_error_from(
                            &t!("expected a name after `template`"),
                            p.current_token_range(),
                        ));
                    }
                }

                match p.current_token() {
                    CppTokenKind::Identifier => p.bump(),
                    // **`decltype(expr)` as the *first segment* of a qualified name** — `decltype(v)::max`.
                    //
                    // A `decltype-specifier` names a type, so it stands where a namespace or a class does and the
                    // `::` after it continues the same name. The arm above already reads the *type* spelling of
                    // this (`types::parse_name` has had its own `decltype` segment since `<format>` needed
                    // `typename decltype(__pc)::iterator`), and the expression grammar did not — so
                    //
                    // ```cpp
                    // constexpr auto _Forever = (decltype(_Abs_time)::max)();      // <thread>: _Abs_time's type
                    // ```
                    //
                    // reported `expected ), but get ::` against the `::`, and that was the last diagnostic on the
                    // 3.3 MB cooked `<vector>` stream.
                    //
                    // **This arm is only reachable when a `::` follows** — see
                    // [`a_decltype_here_continues_a_name`] — and that guard is the whole reason it is written here
                    // rather than by adding `decltype` to the pattern outright. A bare `decltype(v)` currently
                    // reads as the functional conversion `CastExpr`, which is a shape consumers already see and a
                    // change nothing asked for; only the qualified spelling is new.
                    //
                    // The payload is read by the **expression** rule, not the type rule: `decltype(v)` and
                    // `decltype(f())` are expressions, and only `decltype(auto)` is not. `types::parse_name` asks
                    // the same question the same way.
                    CppTokenKind::DecltypeKeyword if p.peek_next_token() == CppTokenKind::LeftParen => {
                        p.bump(); // `decltype`
                        p.bump(); // `(`
                        let payload = if p.current_token() == CppTokenKind::AutoKeyword {
                            types::parse_type_id(p).map(|_| ())
                        } else {
                            parse_expr(p).map(|_| ())
                        };
                        if let Err(err) =
                            payload.and_then(|()| expect_token(p, CppTokenKind::RightParen))
                        {
                            p.close_marks_above(base);
                            return Err(err);
                        }
                    }
                    CppTokenKind::Tilde => {
                        p.bump();
                        if p.current_token() == CppTokenKind::Identifier {
                            p.bump();
                        }
                        break;
                    }
                    CppTokenKind::OperatorKeyword => {
                        types::parse_operator_name_here(p)?;
                        break;
                    }
                    _ => {
                        p.close_marks_above(base);
                        return Err(CppParseError::syntax_error_from(
                            &t!("expected a name after `::`"),
                            p.current_token_range(),
                        ));
                    }
                }

                // A template-id: `vector<int>`.
                //
                // The `<` is also the less-than operator, and the two readings are told apart **speculatively**:
                // read the argument list, and keep it only if it is a template-id in more than the sense of
                // having parsed.
                //
                // "It parsed" is not evidence enough, and that is the whole subtlety. `n < 0 || n > 100000` reads
                // perfectly well as the template-id `n<0 || n>` — the argument is the expression `0 || n` and the
                // `>` closes the list — so a rule that fell back only on *failure* kept the wrong reading and then
                // reported the leftover `100000` as an error. The token **after** the list is what settles it: an
                // operand there cannot follow a template-id, exactly as one after a `)` cannot follow a
                // parenthesised expression. See [`starts_an_operand`].
                //
                // The lookahead stays, as a cheap *rejection*: `a < b;` is a comparison and there is no reason to
                // build and throw away an argument list to find that out. Correctness does not rest on it —
                // everything it accepts is checked below — which also means it no longer has to be exact.
                if p.current_token() == CppTokenKind::Less
                    && types::could_start_template_arguments(p)
                    && !read_a_template_id_here(p) {
                        break;
                    }

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

                // **`MACRO name` — a name written after a macro this file has not seen.**
                //
                // `_STD f()`, `_NODISCARD const T& f()`, `_EXPORT_STD _NODISCARD inline wstring f()` — every
                // standard-library header writes its names this way, and the macros are defined in `<yvals.h>`,
                // which a file parsed on its own has not read. The prefix therefore arrives as a plain
                // **identifier** and the name follows it: two identifiers in a row with no `::` between them.
                //
                // That is not a guess between two readings. Two adjacent identifiers cannot both be segments of
                // one name in C++, and they cannot be two expressions either — there is no operator between them
                // — so the second continues a name the file could not spell. Refusing it stopped the expression
                // at the first identifier, and whatever enclosed the expression then reported against the second:
                //
                // ```text
                // if (!_STD g()) { }        expected `)` against `g`
                // while (_STD g()) { }      the same
                // return _STD f(x);         expected `;` against `f`
                // _STD g(p, [] { })         the declaration reading derailed inside the parameter list
                // ```
                //
                // Each one failed the statement it stood in, and the failure took the declaration written after
                // that statement's function with it. Measured across MSVC's headers, this is the single largest
                // cause of a file stopping early: `<vector>` read 10% of itself before it and all of it after,
                // and `<xmemory>`, `<iterator>`, `<type_traits>`, `<ranges>` and `<utility>` the same.
                //
                // **Narrowed to the call shape**, and the narrowing is measured rather than cautious. Taking any
                // identifier after an expression turned `X Y` into one name wherever the declaration reading had
                // already given up, and the cost was not local: MSVC's `<xmemory>` summarised 536 declarations
                // covering the whole file before it and 266 covering a fifth after. What the standard library
                // actually writes is a **call**, so the run is taken only when a `(` follows it:
                //
                // ```text
                // _STD f()          taken — the shape every header writes
                // _STD f(p, [] { }) taken, and it is where <format> stopped
                // return _STD f(x); taken
                // C<T> T value      **not** taken — no `(`, and `T` is the declaration's own type
                // ```
                // **And the same shape with the parentheses moved**, which is the idiom the standard library uses
                // to stop a function-like macro from eating the call:
                //
                // ```cpp
                // return (_STD min) (_Hw_threads * _Oversubscription_multiplier, _Size_count);   // <execution>
                // return (_STD min) (_Size, static_cast<size_type>(_Mysize - _Off));             // <xstring>
                // ```
                //
                // `(_STD min)` is a parenthesised qualified name, so after `_STD` the next token is `min` and the
                // one after *that* is `)`, not `(` — and the narrowing above, which exists to protect `X Y` as a
                // type and a declarator, refused it. Measured, this one shape is most of what the worst files were
                // losing: `<execution>` summarised 4% of itself and `<xstring>` 12%, and their raw readings report
                // `expected ), but get identifier — min` as the first error each.
                //
                // **All three tokens are required**, and the third is not decoration: `(_STD min) (…)` is the
                // idiom, and it is what a name inside parentheses is *for*. Taking any `X Y)` inside parentheses —
                // the first version — cost `<vector>` its whole file: 538 declarations covering it became 157
                // covering half, because a parenthesised declarator (`(Widget w)`) and a parenthesised type
                // (`sizeof(T)`, `decltype(a) b`) both reach this rule with an identifier after an identifier and a
                // `)` after that. Requiring the `(` to follow is what says "this pair is a name and a call" rather
                // than "this pair is whatever the file happened to write".
                // **All three tokens are required, and they are asked for in one lookahead** — `)` and then `(`.
                // `(_STD min) (…)` is the idiom, and the call is what a name inside parentheses is *for*. Two
                // measurements stand behind the third token:
                //
                // * taking any `X Y)` inside parentheses cost `<vector>` its whole file — 538 declarations covering
                //   it became 157 covering half — because a parenthesised declarator and a parenthesised type
                //   (`sizeof(T)`, `decltype(a) b`) both reach this rule with a `)` after the second name;
                // * and asking for the two tokens **separately** silently did nothing, because the whitespace
                //   between `)` and `(` in `(_STD min) (…)` is a token in this lexer. The window is one call so
                //   that the skipping is the parser's business rather than a caller's arithmetic.
                // **…and the same call with template arguments in between.**
                //
                // ```cpp
                // _Ptr = _STD _Refancy_maybe_null<_Tptr>(const_cast<value_type*>(_It));   // <vector>
                // const auto _Count = _STD _Convert_size<size_type>(_Length);
                // ```
                //
                // The name is not followed by `(` but by `<`, so neither test above fires and the run stops one
                // token short — after which the specifier sequence holds a name it cannot use, the declaration
                // fails, and everything after it in the file goes unread. Measured **490 times across the 102
                // headers**, which makes it the most common macro spelling in the standard library.
                //
                // **Only after a name has already been taken**, and that is the whole of the narrowing. The shape
                // being read is `MACRO name<targs>(…)` — two identifiers in a row with the second carrying
                // arguments — so the `<` case may only fire where the **first** identifier is already in hand.
                // Firing it on the first identifier instead reads `T<U>(v)` as a name, and that spelling is a
                // declaration in every file that meets it: measured, `<xmemory>` fell from a whole file to a fifth
                // of one, `<chrono>` to one line in a hundred, and `<mdspan>` and `<expected>` the same. Those
                // files are what says the rule is about the **pair** and not about the `<`.
                let mut taken = 0usize;
                while an_operand_is_decisive(p)
                    && p.current_token() == CppTokenKind::Identifier
                    && match p.peek_token_kind_at(1..3).as_slice() {
                        [CppTokenKind::LeftParen, ..] => true,
                        [CppTokenKind::RightParen, CppTokenKind::LeftParen] => {
                            p.is_open(CppSyntaxKind::ParenExpr)
                        }
                        // **The `<` is taken when the name it follows is a macro's second half**, and the question
                        // is now asked of the **environment** rather than of the spelling.
                        //
                        // What the spelling could not do, measured four ways before this became possible: `_STD
                        // _Convert_size<size_type>(…)` (a macro, a name and a call) and `_STD declval<_Alloc&>()` (a
                        // macro, a name used as a template argument) are identical up to the `<` — same spelling,
                        // same position, same nesting — so every rule keyed on how the words are written took
                        // MSVC's `<xmemory>` from 582 declarations covering the file to 153 covering a fifth, and
                        // left `<chrono>` at a hundredth of itself. The two differ in **what the first name is**,
                        // and only the include closure knows that.
                        //
                        // `taken > 0` is the fallback and not the rule: with no environment — a buffer parsed on
                        // its own — the reading is the one that keeps the most files whole, and the name already in
                        // hand is the only evidence there is. With one, the `<` is taken wherever the word before
                        // it is really a macro, which is both shapes.
                        [CppTokenKind::Less, ..] => {
                            let the_prefix_is_a_macro = macro_name_before(p)
                                .map(|name| {
                                    // **The environment can only add evidence, never take the fallback away.**
                                    //
                                    // What it knows is the macros a file **includes** — `IncludedMacro`'s own
                                    // definition is "a macro the file *includes* rather than writes" — so a name the
                                    // file defines itself is `Some(false)` there, and reading that as "not a macro"
                                    // hid `_STD` in every file that spells its own:
                                    //
                                    // ```text
                                    // #define _STD ::std::
                                    // void t() { _STD f<A>(); }   → `expected ; after expression` at `f`
                                    // ```
                                    //
                                    // The spelling is what a file's own defines leave as evidence, and it is the
                                    // reading this rule had before an environment could be passed at all.
                                    p.is_a_macro(&name) == Some(true) || types::written_like_a_macro(&name)
                                })
                                .unwrap_or(taken > 0);
                            the_prefix_is_a_macro && a_template_id_here_is_called(p)
                        }
                        _ => false,
                    }
                {
                    p.bump();
                    taken += 1;
                }

                // **A `<` at the cursor is the rest of this name, not the end of it.**
                //
                // The run above takes `_STD f` and leaves `<A>` at the cursor, and ending the name here handed those
                // arguments to nobody: every macro-prefixed template-id in the standard library became a name, a
                // stray `<`, and a parse error. Measured on the smallest spelling of it:
                //
                // ```text
                // void t() { g<A&>(); }       0 errors   — no macro prefix, so the run never fires
                // void t() { _STD f<A>(); }   1 error    — the run fires, and the arguments were dropped
                // ```
                //
                // The arguments are read **here** rather than by letting the loop turn again: the loop's template-id
                // step sits above this one, so a `continue` would re-enter at the top and meet the segment match with
                // a `<` it has no arm for — measured, one error per ordinary `for (i = 0; i < n; i++)` in the crate's
                // own test suite.
                if p.current_token() == CppTokenKind::Less
                    && types::could_start_template_arguments(p)
                {
                    read_a_template_id_here(p);
                }
                break;
            }

            Ok(m.complete(p))
        }

        // A C-style cast, or a parenthesised expression. `(int)x` and `(x)` are the same first three tokens,
        // and the type reading has to be tried first because it is the one that can be refused — but it has to
        // be *asked* first as well, or every parenthesised expression would become a cast of a name.
        //
        // Hence two stages: the cheap check says whether a cast is worth trying, and the try itself says
        // whether it worked. A cast that fails is not an error — it is a parenthesised expression, and the
        // rewind hands the tokens to that rule. That is what keeps the check from having to be exact: it only
        // has to avoid the common `(a)`, `(a + b)`, `((a))` shapes, and everything it cannot decide is settled
        // by the parse. `struct Widget {}; (Widget){1}` is the case that made this worth doing: the check says
        // cast, the cast finds no operand, and the expression reading takes over.
        CppTokenKind::LeftParen if is_a_type_in_parentheses(p) => {
            let checkpoint = p.checkpoint();
            let m = p.mark(CppSyntaxKind::CastExpr);
            p.bump(); // `(`

            let parsed = types::parse_type_id(p)
                .and_then(|_| expect_token(p, CppTokenKind::RightParen))
                // The operand of a cast is a unary expression, which is what keeps `(int)a + b` a sum of a cast
                // and `b` rather than a cast of `a + b`.
                //
                // **…or a braced initializer, which is C99's compound literal** — the one shape a C project meets
                // constantly. `(Object){ .type = kObjectTypeString }` is how neovim's own `CSTR_AS_OBJ` is written,
                // and every use of it was reported `expected primary expression` (five in `src/nvim/main.c` alone,
                // measured with `CPPLS_DIAGNOSTICS=1` on the neovim checkout). A braced initializer is not an
                // expression, so the unary rule could not read it, the cast arm rolled back, and the
                // parenthesised-expression rule then failed on the same tokens.
                .and_then(|_| {
                    if p.current_token() == CppTokenKind::LeftBrace {
                        decls::parse_braced_initializer(p)
                    } else {
                        parse_unary_expr(p, false)
                    }
                });

            match parsed {
                Ok(_) => Ok(m.complete(p)),
                Err(_) => {
                    // Not a cast after all: the whole attempt — node, tokens and events — goes back.
                    p.rollback(checkpoint);
                    parse_parenthesized_expression(p)
                }
            }
        }

        // A parenthesized expression: `(a + b)`, `(x)`, `(f())`.
        //
        // This was simply missing, and nothing about it is subtle — `x = (a + b);` reported "expected primary
        // expression" at the `(`. It went unnoticed because the parenthesised forms the corpus reached were
        // all *statement* parentheses — `if (x)`, `f(a)` — which the statement and postfix rules consume
        // themselves, so only an expression that begins with `(` ever got here.
        //
        // A `(` in an expression is never a declarator: the declaration reading is tried first and rewound
        // before the expression grammar runs, so anything still standing at a `(` here is being *used*.
        //
        // A **comma** inside the parentheses is the comma operator, and the expression rule does not have it —
        // see the comment on the operator table. `(a, b)` therefore does not parse yet, which is the same gap
        // and not a second one.
        CppTokenKind::LeftParen => parse_parenthesized_expression(p),

        // A lambda: `[capture](params) -> type { body }`.
        //
        // Decided by a shape check before anything is consumed, because `[` in an expression is otherwise an
        // index — and the two are told apart by what follows the `]`: a lambda continues with `(`, `{`, or a
        // qualifier, while an index has an expression in front of it and an operator after.
        CppTokenKind::LeftBracket if starts_a_lambda(p) => parse_lambda(p),

        // **A Clang block literal**: `^(int n) { … }` — the closure syntax Apple's APIs are written with.
        //
        // A `^` in *operand* position can only be this: the XOR operator has a left operand, so a caret where an
        // expression begins is the block's own token. The node is a `LambdaExpr` — a block is an anonymous function
        // with no capture list, which is the closest thing this grammar has, and the analysis then treats it as the
        // closure it is. Nothing is invented: the `^`, the parameter list and the body are the file's own tokens.
        CppTokenKind::Caret => parse_block_literal(p),

        // `this`
        CppTokenKind::ThisKeyword => {
            let m = p.mark(CppSyntaxKind::ThisExpr);
            p.bump();
            Ok(m.complete(p))
        }

        // A `...` in operand position. There is exactly one construct that writes it there — a **fold
        // expression** — and in both of its spellings the ellipsis is an operand of the binary operator beside
        // it: `(ts + ...)` reads as `BinaryExpr(ts, +, FoldExpr(...))` and `(... + ts)` as
        // `BinaryExpr(FoldExpr(...), +, ts)`.
        //
        // Read as a primary expression rather than special-cased in the binary rule, which is what makes both
        // spellings work through one piece of code: the left fold needs no handling at all once the `...` can
        // be an operand.
        //
        // # Why the flag
        //
        // A `...` as an operand is only legal inside the parentheses of a fold, and reading it anywhere else
        // takes tokens away from constructs that spell the same three dots. `case 2 ... 4:` is the one that
        // proved it: the case rule reads an expression and *then* looks for the range's `...`, and with this arm
        // unconditional the ellipsis was swallowed as part of the first expression — the range syntax broke,
        // and it broke in the corpus rather than in a test, which is where a regression like this should
        // surface.
        CppTokenKind::Ellipsis if fold_operand => {
            let m = p.mark(CppSyntaxKind::FoldExpr);
            p.bump();
            Ok(m.complete(p))
        }

        // **C11's `_Generic ( assignment-expression , association , … )`** — see [`parse_generic_selection`].
        //
        // `_Generic` is a *contextual* keyword: no token kind names it, so the arm is an identifier whose text is the
        // spelling and whose next token is a `(`, which no ordinary identifier position can be. The feature is the
        // language's — C11, and a C++ compiler takes it as an extension only where a vendor says so — so a C++17 file
        // that writes `_Generic` still sees it as a call, which is what it is there.
        CppTokenKind::Identifier
            if p.current_token_text() == "_Generic"
                && p.peek_next_token() == CppTokenKind::LeftParen
                && p.language()
                    .support(crate::features::Feature::GenericSelection) =>
        {
            parse_generic_selection(p)
        }

        _ => Err(CppParseError::syntax_error_from(
            &t!("expected primary expression"),
            p.current_token_range(),
        )),
    }
}

/// **C11's generic selection** — `_Generic ( assignment-expression , association , … )`.
///
/// ```text
/// _Generic((value), int: "int", double: "double", default: "other")
/// ```
///
/// An association is a *type-name* and an expression, or `default` and an expression. The type-name is read by
/// [`types::parse_type_id`], which is what a `sizeof` and a cast use, so `char*` and `const char*` — the two the corpus
/// writes — are read by the same rule that reads them anywhere else. Each expression is read at
/// [`Level::Assignment`], so the comma that separates associations stays the separator rather than becoming the comma
/// operator: `_Generic(x, int: a, default: c)` is two associations, and a reader that took the comma would see one.
fn parse_generic_selection(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::GenericSelectionExpr);
    p.bump(); // `_Generic`
    expect_token(p, CppTokenKind::LeftParen)?;

    // The controlling expression.
    parse_assignment_expr(p)?;

    while p.current_token() == CppTokenKind::Comma {
        p.bump();
        // `default : expression`, or `type-name : expression`. `default` is a keyword, so which arm this is needs no
        // lookahead: a type-name can never begin with it.
        if p.current_token() == CppTokenKind::DefaultKeyword {
            p.bump();
        } else {
            types::parse_type_id(p)?;
        }
        expect_token(p, CppTokenKind::Colon)?;
        parse_assignment_expr(p)?;
    }

    if let Err(err) = expect_token(p, CppTokenKind::RightParen) {
        p.push_error(err);
    }
    Ok(m.complete(p))
}

/// Parse `( expression )` as a node of its own, keeping the parentheses.
///
/// Shared by the two paths that reach a `(` in expression position: the plain parenthesised expression, and a
/// cast attempt that failed and has to be read that way instead. Two copies of this rule would be how they
/// come to disagree about what a parenthesised expression is.
///
/// This is also the only place a **fold expression** can be written, so it is the only place that licenses a
/// bare `...` as an operand — see the `Ellipsis` arm of [`parse_primary_expr`]. The trailing-`...` *expansion*
/// reading is still available, because the two are told apart by position rather than by a flag: a fold's `...`
/// is an **operand**, so it arrives at the primary rule, while an expansion's follows a completed expression.
/// The payload of a **functional-notation conversion**: `(a, b)` — possibly empty — or `{a, b}`.
///
/// Empty parentheses are a payload, and that is the whole reason this exists. `int()`, `bool()` and
/// `typename T::type()` are default-constructed temporaries — the commonest functional conversion there is, and
/// what `bits/stl_iterator_base_types.h:242` returns:
///
/// ```cpp
/// __iterator_category(const _Iter&)
/// { return typename iterator_traits<_Iter>::iterator_category(); }
/// ```
///
/// [`parse_parenthesized_expression`] refuses them, correctly: it reads an *expression*, and `)` is not one. The
/// group is read here as a `ParenExpr` with no children, which is what it is — a call with no arguments — so a
/// consumer sees the same node for `f()` and for `int()`.
fn parse_functional_payload(p: &mut CppParser) -> ParseResult {
    if p.current_token() == CppTokenKind::LeftBrace {
        return decls::parse_braced_initializer(p);
    }

    let m = p.mark(CppSyntaxKind::ParenExpr);
    expect_token(p, CppTokenKind::LeftParen)?;

    if p.current_token() != CppTokenKind::RightParen
        && let Err(err) = parse_expr_up_to(p, Level::Full, true)
    {
        m.undo(p);
        return Err(err);
    }

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

    Ok(m.complete(p))
}

/// **A parenthesized expression**, and the GNU statement expression that is written the same way.
///
/// ```text
/// (a + b)                      a parenthesised expression
/// ({ int a = 1; a; })          GNU: **a compound statement as an expression** — the value is the last statement
/// ```
///
/// The second is not C++ and is everywhere in C: glibc's `assert` on some targets, the Linux headers' `__safe_…`
/// macros, and any header written with `#define max(a, b) ({ … })`. A `{` where the expression would be can only be
/// that statement, so it is read as one — the node keeps the braces and the statements, and a consumer that wants the
/// value reads the last statement, which is what the extension means.
fn parse_parenthesized_expression(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::ParenExpr);
    expect_token(p, CppTokenKind::LeftParen)?;

    // **The GNU statement expression**, decided at the one token that tells it apart.
    if p.current_token() == CppTokenKind::LeftBrace {
        if let Err(err) = crate::grammar::cpp::stats::parse_compound_stat(p) {
            m.undo(p);
            return Err(err);
        }
        if let Err(err) = expect_token(p, CppTokenKind::RightParen) {
            m.undo(p);
            return Err(err);
        }
        return Ok(m.complete(p));
    }

    if let Err(err) = parse_expr_up_to(p, Level::Full, true) {
        m.undo(p);
        return Err(err);
    }
    if let Err(err) = expect_token(p, CppTokenKind::RightParen) {
        m.undo(p);
        return Err(err);
    }
    // **A parenthesised compound literal** — `((Object){ .type = … })` — is *not* read here yet,
    // and the `{` after a `)` is why: it is a function body in `void f() requires (x) { }` and a
    // braced initializer in `((Object){ 1 })`, and telling them apart needs the *contents* of the
    // parentheses rather than the token after them. The version of this that accepted every `{`
    // broke both concepts fixtures above (`requires (sizeof(T) > 1) { }`), which is the honest
    // outcome: a rule that cannot tell a body from an initializer must not guess.
    Ok(m.complete(p))
}

/// **A Clang block literal** — `^(int n) { … }` — as a `LambdaExpr`.
///
/// ```text
/// ^(int n) { return n; }        a block with parameters
/// ^{ return 1; }                one that takes nothing
/// ```
///
/// The parameter list is optional and its parentheses are the ones the declaration grammar already knows, so this
/// reads them with `parse_parameter_list` rather than with a second copy of that rule. A block *type*
/// (`void (^handler)(void)`) is a different construct and was already parseable — it is a declarator, not an
/// expression — which is why only the literal needed this.
fn parse_block_literal(p: &mut CppParser) -> ParseResult {
    let m = p.mark(CppSyntaxKind::LambdaExpr);
    p.bump(); // `^`

    if p.current_token() == CppTokenKind::LeftParen
        && let Err(err) = crate::grammar::cpp::decls::parse_parameter_list(p)
    {
        m.undo(p);
        return Err(err);
    }

    // The same directive seam a lambda body has: `#if` between the head and the body is a real spelling.
    while p.current_token() == CppTokenKind::Hash {
        if let Err(err) = crate::grammar::cpp::stats::parse_preprocessor_directive(p) {
            m.undo(p);
            return Err(err);
        }
    }

    if let Err(err) = crate::grammar::cpp::stats::parse_compound_stat(p) {
        m.undo(p);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Keywords that look like a name start to the dispatch above but are their own expression forms.
///
/// `nullptr` is handled as a literal; the rest are parsed as unary or postfix operators. Listing
/// them here keeps the name branch from swallowing them.
fn is_expression_keyword(p: &CppParser) -> bool {
    matches!(
        p.current_token(),
        CppTokenKind::NullptrKeyword
            | CppTokenKind::SizeofKeyword
            | CppTokenKind::AlignofKeyword
            | CppTokenKind::TypeidKeyword
            | CppTokenKind::NewKeyword
            | CppTokenKind::DeleteKeyword
            | CppTokenKind::ThrowKeyword
            | CppTokenKind::CoAwaitKeyword
    )
}

/// Is the `requires` at the cursor the start of a **requires-expression**?
///
/// `requires` is a *contextual* keyword: it is also a perfectly good identifier, and the standard allows a
/// program to use it as one. So the token alone says nothing and what follows it does — a requires-expression is
/// always `requires` followed by a parameter list or the body:
///
/// ```text
/// requires { g(); }        the body alone
/// requires (T t) { ... }   parameters, then the body
/// requires = 1;            a variable named `requires`
/// requires(x);             a call to a function named `requires`
/// ```
///
/// A `(` is the one needing care, because `requires(x);` is a call. The lookahead walks the parenthesised part
/// and asks whether a `{` follows it — a body, which a call cannot have. Asking rather than assuming is what
/// keeps the identifier reading available.
fn starts_a_requires_expression(p: &CppParser) -> bool {
    match p.peek_token_kind_at(1..2).first() {
        Some(&CppTokenKind::LeftBrace) => true,
        Some(&CppTokenKind::LeftParen) => {
            // Walk to the matching `)` of the parameter list and ask whether a body follows it.
            let mut depth = 0isize;
            let mut offset = 1usize;
            for kind in p.peek_token_kind_at(1..128) {
                offset += 1;
                match kind {
                    CppTokenKind::LeftParen => depth += 1,
                    CppTokenKind::RightParen => {
                        depth -= 1;
                        if depth == 0 {
                            return p.peek_token_kind_at(offset..offset + 1).as_slice()
                                == [CppTokenKind::LeftBrace];
                        }
                    }
                    _ => {}
                }
            }
            false
        }
        _ => false,
    }
}

/// Parse a requires-expression: `requires (params) { requirement... }`.
pub(super) fn starter_of_a_builtin_type(kind: CppTokenKind) -> bool {
    matches!(
        kind,
        // `bool` is a `BoolLiteral` in this lexer rather than a keyword of its own — measured, the keyword table says
        // `"bool" => CppTokenKind::BoolLiteral` — so the type and the literal share a kind and both belong here.
        CppTokenKind::BoolLiteral
            | CppTokenKind::CharKeyword
            | CppTokenKind::ShortKeyword
            | CppTokenKind::IntKeyword
            | CppTokenKind::LongKeyword
            | CppTokenKind::SignedKeyword
            | CppTokenKind::UnsignedKeyword
            | CppTokenKind::FloatKeyword
            | CppTokenKind::DoubleKeyword
            | CppTokenKind::VoidKeyword
            | CppTokenKind::DecltypeKeyword
    )
}

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

    p.bump(); // `requires`

    // The parameter list, when it is written. A requires-expression's parameters are the ordinary ones —
    // `requires(T t)`, `requires(std::vector<int> v)` — so the parameter rule is reused rather than re-spelled.
    if p.current_token() == CppTokenKind::LeftParen
        && let Err(err) = decls::parse_parameter_list(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

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

    // The body: one requirement per `;`. A requirement may hold anything an expression can, so the `;` is what
    // says where each one ends.
    while p.current_token() != CppTokenKind::RightBrace && !p.is_eof() {
        // A **directive between requirements**, which is the same seam as the nine records
        // for statements and declarations, and the last place it was missing. libstdc++ writes the two
        // alternatives of one requirement in two branches — `bits/alloc_traits.h:140` is the file this was found
        // in:
        //
        // ```cpp
        // template<typename _Tp, typename... _Args>
        //   static constexpr bool __can_construct_at
        //     = requires (_Tp* __p, _Args&&... __args) {
        // #if __cpp_constexpr_dynamic_alloc
        //         std::construct_at(__p, std::forward<_Args>(__args)...);
        // #else
        //         ::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
        // #endif
        //       };
        // ```
        //
        // A `#` here cannot be anything else: a requirement begins with an expression, a `typename`, a `{`, a
        // nested `requires` — or a directive. Read it as the node it is and ask again about the token that follows,
        // exactly as `parse_braced_initializer` does between the elements of a table.
        //
        // **What the missing seam cost** is worth keeping: the whole member failed, and the failure then ate the
        // class's own `}` — so every member after it was read at *namespace* scope and the file's only diagnostic
        // appeared 900 lines later, on the leftover `}` at the end. One seam, one file.
        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_requirement(p) {
            p.close_marks_above(base);
            return Err(err);
        }
        if p.current_token() == CppTokenKind::Semicolon {
            p.bump();
            continue;
        }
        break;
    }

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

    Ok(m.complete(p))
}

/// One requirement of a requires-expression's body.
///
/// The four kinds the standard lists, and the shape of each is what tells them apart at the cursor:
///
/// ```text
/// t.f();                       simple      — an expression
/// typename T::value_type;      type        — a `typename` name
/// { t.f() } noexcept -> int;   compound    — a braced expression, then the exceptions and the result type
/// requires C<T>;               nested      — a requires-clause of its own, which is why it nests
/// ```
///
/// All four become one [`CppSyntaxKind::Requirement`] node: they share a position and a `;`, and what differs is
/// inside.
fn parse_requirement(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::Requirement);

    match p.current_token() {
        // A nested requirement: `requires C<T>;`. The clause rule is shared with the declaration side, which is
        // the whole reason `requires` nests — the two spell the same thing.
        //
        // The guard is what keeps the *identifier* reading available here as well: `requires;` is a simple
        // requirement whose expression is a name, and the clause rule consumes nothing on it. `requires(x);` reads
        // as a nested requirement, which is the standard's own reading of those tokens.
        CppTokenKind::Identifier if at_requires(p) && decls::starts_a_requires_clause(p) => {
            if let Err(err) = decls::parse_requires_clause(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

        // A type requirement: `typename T::value_type;`. Also the `template`-disambiguated spelling
        // `typename T::template rebind<U>;`, which is why this goes through the type-id rule.
        CppTokenKind::TypenameKeyword => {
            if let Err(err) = types::parse_type_id(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }

        // A compound requirement: `{ expr } noexcept -> type;`.
        CppTokenKind::LeftBrace => {
            p.bump(); // `{`
            // The braced part is an expression **up to the `}`**, so the reader has to stop there — and it must
            // also stop before a `noexcept`, because that token belongs to the *requirement* rather than to the
            // expression: `{ t.f() noexcept }` is a call whose exceptions are specified, not a call with
            // `noexcept` in it. `parse_requirement_expression` is the reader that stops at both.
            if let Err(err) = parse_requirement_expression(p) {
                p.close_marks_above(base);
                return Err(err);
            }
            if let Err(err) = expect_token(p, CppTokenKind::RightBrace) {
                p.close_marks_above(base);
                return Err(err);
            }

            // The optional exception specification, which may carry a condition: `noexcept(false)`.
            if p.current_token() == CppTokenKind::NoexceptKeyword {
                let specification = p.mark(CppSyntaxKind::NoexceptSpec);
                p.bump();
                if p.current_token() == CppTokenKind::LeftParen {
                    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);
                    }
                }
                specification.complete(p);
            }

            // The optional result type: `-> int`, `-> std::same_as<T>`.
            if p.current_token() == CppTokenKind::Arrow {
                let trailing = p.mark(CppSyntaxKind::TrailingReturnType);
                p.bump(); // `->`
                if let Err(err) = types::parse_type_id(p) {
                    trailing.undo(p);
                    p.close_marks_above(base);
                    return Err(err);
                }
                trailing.complete(p);
            }
        }

        // A simple requirement: an expression that has to be well-formed.
        _ => {
            if let Err(err) = parse_expr(p) {
                p.close_marks_above(base);
                return Err(err);
            }
        }
    }

    Ok(m.complete(p))
}

/// Does the `[` at the cursor introduce a lambda rather than an index expression?
///
/// The two are the same token and there is no name in front to help, so the decision is made from what follows
/// the matching `]`:
///
/// ```text
/// [x]        { return x; }      a lambda: capture list, then the body
/// [x]        (int y) { ... }    a lambda: capture list, then the parameters
/// [x]        mutable { ... }    a lambda: a qualifier may sit between them
/// arr[i]                        an index — the `[` has an expression before it
/// ```
///
/// A `]` followed by anything else is not a lambda introducer, and the caller's index reading takes it. The scan
/// is bounded and does not descend: a capture list cannot contain an unbalanced `]`, so the first one closes it.
fn starts_a_lambda(p: &CppParser) -> bool {
    use CppTokenKind::{
        Ampersand, Arrow, Assign, Caret, CharLiteral, Colon, Comma, Dot, Ellipsis, Equal,
        FalseKeyword, FloatingLiteral, Greater, GreaterEqual, Identifier, IntegerLiteral,
        LeftBrace, LeftBracket, LeftParen, LeftShift, Less, LessEqual, LogicalAnd, LogicalNot,
        LogicalOr, Minus, MinusMinus, MutableKeyword, NoexceptKeyword, NotEqual, NullptrKeyword,
        Percent, Pipe, Plus, PlusPlus, Question, RightBracket, RightParen, RightShift, Scope,
        Slash, Star, StringLiteral, ThisKeyword, Tilde, TrueKeyword,
    };

    // The capture list's own contents, so that a malformed one stops the reading rather than swallowing the
    // rest of the expression. Relative offsets: `0` is the `[` at the cursor, so the scan starts at `1`.
    //
    // The set is "anything an init-capture's initialiser can be made of", and it has to be that wide because
    // `[value = total + 1]` is one capture whose initialiser is an ordinary expression: its *operators* are as
    // much a part of the list as its names. Allowing too little is how this came to read `[value` as an index —
    // the `+` was not in the set, so the `[` was declared not to be a lambda introducer and the index rule took
    // the tokens instead.
    //
    // Allowing too much costs nothing here: the second half of the check is what actually decides, and it asks
    // about the token *after* the `]`. `arr[i] + 1` passes this scan and is still an index, because what follows
    // the bracket is `+` rather than `(`, `{` or a qualifier.
    let mut next_after_the_list = None;
    for (offset, kind) in p.peek_token_kind_at(1..64).into_iter().enumerate() {
        match kind {
            Identifier
            | Comma
            | Ampersand
            | Assign
            | Ellipsis
            | ThisKeyword
            | Star
            | Scope
            // An init-capture's initialiser, which is an expression: its literals, its parentheses, and the
            // operators between them.
            | IntegerLiteral
            | FloatingLiteral
            | StringLiteral
            | CharLiteral
            | TrueKeyword
            | FalseKeyword
            | NullptrKeyword
            | LeftParen
            | RightParen
            | LeftBracket
            | Plus
            | Minus
            | Slash
            | Percent
            | Caret
            | Pipe
            | Tilde
            | LogicalNot
            | LogicalAnd
            | LogicalOr
            | Equal
            | NotEqual
            | Less
            | Greater
            | LessEqual
            | GreaterEqual
            | LeftShift
            | RightShift
            | PlusPlus
            | MinusMinus
            | Arrow
            | Dot
            | Question
            | Colon => {}
            RightBracket => {
                next_after_the_list = p.peek_token_kind_at(offset + 2..offset + 3).first().copied();
                break;
            }
            // Anything else cannot appear in a capture list at all — a `;`, a `)`, a `}` — so this `[` was not
            // the start of one.
            _ => return false,
        }
    }

    // What follows decides, and only two things can: the parameters or the body, with the qualifiers that may
    // sit between them.
    //
    // A template parameter list is a third, for a C++20 generic lambda (`[]<typename T>(T t) { }`), and adding
    // it here is the whole of what that form needed: the list is parsed by the same rule a class template uses.
    // The reading is greedy — `[x] < y` is a comparison that this will now call a lambda — and that is the same
    // direction as every other decision in this file: the capture list has to be followed by *something* that
    // can continue a lambda, and a `<` directly after a `]` in an expression is far more often a lambda's
    // template head than a comparison against a capture list that nothing has used yet.
    matches!(
        next_after_the_list,
        Some(LeftParen)
            | Some(LeftBrace)
            | Some(MutableKeyword)
            | Some(NoexceptKeyword)
            | Some(Arrow)
            | Some(Less)
    )
}

/// Parse a lambda expression: `[capture](params) qualifiers -> type { body }`.
///
/// Everything after the capture list is optional, and the body is required — which is what makes the shape check
/// in [`starts_a_lambda`] safe to trust.
fn parse_lambda(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::LambdaExpr);

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

    // The template parameter list of a C++20 generic lambda, when it is written: `[]<typename T>(T t) { }`.
    // It sits between the capture list and the parameters, and it is the same list a class template spells
    // after `template` — hence the shared rule, and hence the `template` keyword being optional rather than
    // required here.
    if matches!(
        p.current_token(),
        CppTokenKind::Less | CppTokenKind::TemplateKeyword
    ) {
        if p.current_token() == CppTokenKind::TemplateKeyword {
            p.bump();
        }
        if let Err(err) = decls::parse_template_parameter_list(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    // The parameter list, when it is written. A lambda's parameters are the same grammar as a function's, and
    // reusing the rule is what makes a default argument, a pack or a `std::function` parameter work here too.
    if p.current_token() == CppTokenKind::LeftParen
        && let Err(err) = decls::parse_parameter_list(p)
    {
        p.close_marks_above(base);
        return Err(err);
    }

    // `mutable`, `constexpr`, `consteval`, `noexcept`, `-> type`, and the attributes that may appear among them.
    types::eat_function_qualifiers(p);

    // The body. A lambda's body is a compound statement like any other, so it is parsed by the statement rule —
    // which is also what keeps `return` and every other statement inside it working.
    if let Err(err) = stats::parse_compound_stat(p) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// Parse a lambda's capture list: the `[` … `]` at the cursor.
///
/// Kept as its own node so that a consumer can see what a lambda *captures* — the names, the `&` that makes a
/// capture by reference, `this`, and the initialisers of an init-capture — without walking the raw tokens of the
/// whole lambda to find them.
fn parse_capture_list(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::LambdaCaptureList);

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

    while p.current_token() != CppTokenKind::RightBracket && !p.is_eof() {
        // A capture is a name or `name = initializer`. The initializer is read below the comma operator for the
        // same reason an argument is: the commas separate captures. See [`parse_assignment_expr`].
        if let Err(err) = parse_capture(p) {
            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, CppTokenKind::RightBracket) {
        p.close_marks_above(base);
        return Err(err);
    }

    Ok(m.complete(p))
}

/// One capture: `x`, `&x`, `this`, `*this`, `=`, `&`, `...`, or `x = expr`.
fn parse_capture(p: &mut CppParser) -> ParseResult {
    let base = p.open_marks();
    let m = p.mark(CppSyntaxKind::LambdaCapture);

    // The sigil, when there is one. `&` alone captures everything by reference and `=` everything by copy, so
    // neither has to be followed by a name — and `*this` is a capture of the object by copy.
    if matches!(
        p.current_token(),
        CppTokenKind::Ampersand | CppTokenKind::Star
    ) {
        p.bump();
    }

    // **A pack capture puts the `...` first** (C++20): `[... copies = values]` — `std::apply`'s forwarding lambda is
    // written exactly that way. The other spelling, `[args...]`, is read by the trailing `...` below; both capture a
    // pack, and the standard's `init-capture` is the leading one. Read without it, the capture list ended at
    // `copies`, the `]` was never reached, and the whole lambda came back as `expected primary expression` at its
    // `[` — measured on `lambdas.cpp:46` of the C++ corpus.
    if p.current_token() == CppTokenKind::Ellipsis {
        p.bump();
    }

    // The capture itself: a name, `this`, `...`, or the `=` of a by-copy default. None of them is required —
    // `[&]` and `[=]` are complete captures on their own — so this is one optional token, not a chain of cases.
    if matches!(
        p.current_token(),
        CppTokenKind::ThisKeyword
            | CppTokenKind::Ellipsis
            | CppTokenKind::Assign
            | CppTokenKind::Identifier
    ) {
        p.bump();
    }

    // A pack expansion in the capture list: `[args...]`, the spelling a variadic forwarding lambda needs. The
    // `...` follows the name it expands, which is the same shape an expression's expansion has — but this rule
    // reads the capture itself rather than an expression, so the `...` of `args...` reached the list's `]` unmet
    // and the whole `[` was read as a subscript instead.
    if p.current_token() == CppTokenKind::Ellipsis {
        p.bump();
    }

    // An init-capture: `x = std::move(other)`, or `...args = pack`. Read below the comma operator, since the
    // comma after it separates the next capture.
    if p.current_token() == CppTokenKind::Assign {
        p.bump();
        if let Err(err) = parse_assignment_expr(p) {
            p.close_marks_above(base);
            return Err(err);
        }
    }

    Ok(m.complete(p))
}