cinrs-core 0.1.0

The C front end behind the cinrs crate: lexer, preprocessor, parser, semantic analysis, code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
//! A recursive-descent parser for the whole C99 grammar.
//!
//! # The lexer hack
//!
//! C cannot be parsed without knowing which identifiers are `typedef` names:
//! `T * x;` is a declaration when `T` names a type and a multiplication
//! otherwise, and `(T)-1` is a cast rather than a subtraction. The parser
//! therefore keeps a stack of scopes recording, for every
//! identifier it declares, whether it was introduced by `typedef` or as an
//! ordinary object. Lookups walk the stack from the innermost scope out, so an
//! ordinary declaration properly shadows an outer `typedef`.
//!
//! # Declarator resolution
//!
//! Declarators are turned into a [`Type`] tree as they are parsed, using the
//! classic "parse the suffixes first, then recurse into the parenthesised
//! declarator" trick. That is what makes `int (*fp[3])(void)` come out as
//! *array of 3 pointer to function(void) returning int* rather than as an
//! opaque chain that sema would have to interpret again.
//!
//! # Standards
//!
//! The grammar is C23's, and the [`Standard`] the unit was compiled with
//! gates the parts of it a block's own revision does not have. Which way a
//! construct is gated
//! depends on how C spelled it: the C11 keywords all start with an
//! underscore, which C99 reserves, so the lexer recognises them everywhere
//! and the parser reports "'_Static_assert' requires C11 or later" instead of
//! a syntax error; the C23 keywords are ordinary identifiers before C23 — the
//! bundled `<stdbool.h>` writes `#define bool _Bool` — so they are gated
//! where the *name* turns out not to mean anything, here and in
//! [sema](crate::sema).
//!
//! # Error recovery
//!
//! A syntax error aborts the current external declaration (`Err(Bail)`
//! unwinds to the top level), which then synchronises on the next `;` or `}`
//! at nesting depth zero and keeps going. That way one compilation reports one
//! error per broken declaration instead of stopping at the first.

use std::collections::HashMap;

use crate::ast::*;
use crate::capture::SourceRange;
use crate::diag::{Diagnostic, Diagnostics};
use crate::gnu;
use crate::ir::{INT128_TYPEDEF_NAMES, VA_LIST_NAMES};
use crate::lex::{Keyword, Punct, StrKind, StrLit, TokenKind};
use crate::pp::{Origin, PackMap, Token};
use crate::{Gating, Options, Standard};

/// The spelling of `_Noreturn` that every standard accepts.
///
/// `_Noreturn` itself is a C11 keyword, and a `c99!` block that includes the
/// bundled `<stdlib.h>` must not be told that its `exit` declaration needs a
/// newer standard. The headers therefore write this name, which is a
/// declaration specifier in every mode and means exactly what `_Noreturn`
/// means.
pub const NORETURN_BUILTIN: &str = "__cinrs_noreturn";

/// An integer constant expression the parser synthesises.
fn int_expr(value: u128, range: SourceRange) -> Expr {
    Expr {
        kind: ExprKind::Int(crate::lex::IntLit {
            value,
            base: crate::lex::NumBase::Decimal,
            unsigned: false,
            long: crate::lex::LongKind::None,
            text: value.to_string(),
        }),
        range,
    }
}

/// Signals that the current external declaration cannot be parsed further.
#[derive(Debug)]
#[must_use]
pub struct Bail;

type PResult<T> = Result<T, Bail>;

/// Whether an identifier names a type or an object.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SymKind {
    Typedef,
    Ordinary,
}

/// One lexical scope's contribution to the lexer hack.
#[derive(Default)]
struct Scope {
    syms: HashMap<String, SymKind>,
}

/// Parses a token list into a [`TranslationUnit`].
///
/// The tokens are the [preprocessor](crate::pp)'s, so there are no directives
/// left to see and every range already points where a diagnostic should land —
/// at the invocation, for a token a macro produced.
///
/// `unit_range` is the range the whole translation unit covers — normally
/// [`crate::Source::root_range`]. The token list must end with
/// [`TokenKind::Eof`].
/// Diagnostics are pushed into `diags`; the returned tree is a best effort and
/// may contain [`TypeKind::Error`]/[`StmtKind::Error`] placeholders.
pub fn parse(
    tokens: &[Token],
    unit_range: SourceRange,
    packing: &PackMap,
    options: &Options,
    diags: &mut Diagnostics,
) -> TranslationUnit {
    // The preprocessor always ends its output with EOF, but the parser indexes
    // on that promise, so make it true rather than trust it.
    let patched: Vec<Token>;
    let tokens: &[Token] = if tokens.last().is_some_and(Token::is_eof) {
        tokens
    } else {
        patched = tokens
            .iter()
            .cloned()
            .chain(std::iter::once(Token {
                kind: TokenKind::Eof,
                range: SourceRange::at(unit_range.end),
                origin: Origin::Source,
            }))
            .collect();
        &patched
    };
    let last_range = tokens.first().map_or(unit_range, |t| t.range);
    // `__builtin_va_list` names a type wherever it appears, which the parser
    // has to know before it can tell `__builtin_va_list *p;` from a
    // multiplication. It is the one name the compiler owns; `va_list` itself
    // is an ordinary identifier that the bundled `<stdarg.h>` `typedef`s to
    // it, exactly as GCC's own header does.
    let mut builtins = Scope::default();
    for name in VA_LIST_NAMES {
        builtins.syms.insert((*name).to_owned(), SymKind::Typedef);
    }
    // `__int128_t` and `__uint128_t` are the compiler's own names for the two
    // 128-bit types, exactly as they are in GCC; `__int128` itself is a
    // keyword the preprocessor hands over.
    for (name, _) in INT128_TYPEDEF_NAMES {
        builtins.syms.insert((*name).to_owned(), SymKind::Typedef);
    }
    let mut parser = Parser {
        tokens,
        pos: 0,
        diags,
        scopes: vec![builtins],
        standard: options.standard,
        gating: options.gating(),
        in_extension: false,
        packing,
        last_range,
        depth: 0,
        records: Vec::new(),
        enums: Vec::new(),
        typeofs: Vec::new(),
        label_addrs: 0,
    };
    parser.parse_translation_unit(unit_range)
}

/// How deeply one construct may nest before the parser gives up.
///
/// Recursive descent turns nesting in the input into stack frames, and a
/// procedural macro that overflows the stack takes the whole compiler down
/// with no useful message. Pathologically nested input becomes a diagnostic
/// instead.
///
/// What it bounds is the *nesting* of the tree and never the length of
/// anything. `a + b + c + …`, `a, b, c, …` and `a && b && …` are
/// left-associative, so each operand is a sibling rather than a level, and
/// the parser, [`crate::sema`] and [`crate::codegen`] all walk such a chain
/// iteratively: its length is bounded by memory alone, which is what lets a
/// logical source line hold the 4095 characters C23 5.2.5.2p1 asks for. Three
/// constructs are the other way round and *are* charged here, because each
/// operator is one more level of a tree every pass has to walk:
///
/// * the right-associative `a ? b : c ? d : e` and `a = b = c`
///   ([`Parser::parse_conditional_expr`],
///   [`Parser::parse_assignment_expr`]);
/// * a run of postfix operators, `p->a->b->c` and `a[i][j][k]`
///   ([`Parser::parse_postfix_suffixes`]), where each one is a place inside
///   the last.
///
/// 200 is three times the 63 levels of nesting C23 5.2.5.2p1 asks for and
/// close to Clang's own `-fbracket-depth` default of 256. Measured on an
/// unoptimised build against the 8 MiB `rustc` gives macro expansion, code
/// generation survives about 5000 levels of a conditional chain and about 450
/// of a `->` chain, which is the tightest of them; the margin is therefore
/// twofold at worst and twentyfold at best.
const MAX_RECURSION_DEPTH: u32 = 200;

/// How many labels one statement may carry.
///
/// A label chain is parsed iteratively, so it costs the parser nothing — but
/// each label is still a level of the tree that sema, the CFG lowering and
/// code generation walk recursively, and something has to bound that. C23
/// 5.2.5.2p1 asks for 1023 `case` labels in one `switch`; this is four times
/// that, and a chain longer than it is a diagnostic rather than a crash.
const MAX_LABEL_CHAIN: usize = 4096;

/// One label of a chain, held while the statement it labels is parsed.
enum PendingLabel {
    /// `name:`
    Ident { label: Ident },
    /// `case value:`, and GNU's `case low ... high:`.
    Case { value: Expr, upper: Option<Expr> },
    /// `default:`
    Default,
}

struct Parser<'a> {
    tokens: &'a [Token],
    pos: usize,
    diags: &'a mut Diagnostics,
    scopes: Vec<Scope>,
    /// Which revision's grammar to accept; see [`Parser::require_standard`].
    standard: Standard,
    /// How that revision gates a newer one's features.
    gating: Gating,
    /// Whether `__extension__` has switched the gates off for the declaration
    /// being parsed; see [`Parser::require_standard`].
    in_extension: bool,
    /// What `#pragma pack` was asking for, by token position.
    packing: &'a PackMap,
    /// Range of the most recently consumed token, used to close node ranges.
    last_range: SourceRange,
    /// Current recursion depth; reset at every external declaration.
    depth: u32,
    /// The `struct`/`union` specifiers seen so far; see [`RecordSpecId`].
    records: Vec<RecordSpec>,
    /// The `enum` specifiers seen so far.
    enums: Vec<EnumSpec>,
    /// The `typeof` operands seen so far.
    typeofs: Vec<TypeofOperand>,
    /// How many `&&label` operands have been parsed.
    ///
    /// A function that takes a label's address has to be lowered through a
    /// [control-flow graph](crate::cfg), because the value of `&&label` *is*
    /// the state number the label stands for. That decision is made from the
    /// statements of the body ([`crate::sema::Sema::needs_cfg`]), and
    /// `&&label` is an expression — it can sit in an initialiser, a call
    /// argument or a `static` table — so the one place that sees all of them
    /// is here. Counting rather than flagging is what lets a nested function
    /// definition put the count back where it found it, so that its own
    /// `&&label` says nothing about the function it was written in.
    label_addrs: u32,
}

// ---------------------------------------------------------------------------
// token helpers
// ---------------------------------------------------------------------------

impl Parser<'_> {
    fn peek(&self) -> &Token {
        &self.tokens[self.pos]
    }

    fn nth(&self, n: usize) -> &Token {
        let i = (self.pos + n).min(self.tokens.len() - 1);
        &self.tokens[i]
    }

    fn cur_range(&self) -> SourceRange {
        self.peek().range
    }

    fn describe_cur(&self) -> String {
        self.peek().kind.describe()
    }

    fn at_eof(&self) -> bool {
        self.peek().is_eof()
    }

    fn at_punct(&self, p: Punct) -> bool {
        self.peek().is_punct(p)
    }

    fn at_keyword(&self, k: Keyword) -> bool {
        self.peek().is_keyword(k)
    }

    fn advance(&mut self) {
        self.last_range = self.tokens[self.pos].range;
        if self.pos + 1 < self.tokens.len() {
            self.pos += 1;
        }
    }

    fn bump_range(&mut self) -> SourceRange {
        let range = self.cur_range();
        self.advance();
        range
    }

    fn eat_punct(&mut self, p: Punct) -> Option<SourceRange> {
        self.at_punct(p).then(|| self.bump_range())
    }

    fn eat_keyword(&mut self, k: Keyword) -> Option<SourceRange> {
        self.at_keyword(k).then(|| self.bump_range())
    }

    fn eat_ident(&mut self) -> Option<Ident> {
        let name = self.peek().ident()?.to_owned();
        let range = self.bump_range();
        Some(Ident { name, range })
    }

    fn error(&mut self, range: SourceRange, message: impl Into<String>) {
        self.diags.error(range, message);
    }

    fn error_bail(&mut self, range: SourceRange, message: impl Into<String>) -> Bail {
        self.diags.error(range, message);
        Bail
    }

    fn expect_punct(&mut self, p: Punct, ctx: &str) -> PResult<SourceRange> {
        if self.at_punct(p) {
            return Ok(self.bump_range());
        }
        let range = self.cur_range();
        let found = self.describe_cur();
        Err(self.error_bail(
            range,
            format!("expected '{}'{ctx}, found {found}", p.as_str()),
        ))
    }

    fn expect_ident(&mut self, ctx: &str) -> PResult<Ident> {
        if let Some(id) = self.eat_ident() {
            return Ok(id);
        }
        let range = self.cur_range();
        let found = self.describe_cur();
        Err(self.error_bail(range, format!("expected identifier{ctx}, found {found}")))
    }

    /// Range from `start` up to and including the last consumed token.
    fn span_to_here(&self, start: SourceRange) -> SourceRange {
        start.join(self.last_range)
    }

    /// Enters one level of recursion.
    ///
    /// The counter is only decremented on the success path; an error unwinds
    /// all the way to the top level, which resets it.
    fn enter(&mut self) -> PResult<()> {
        self.depth += 1;
        if self.depth > MAX_RECURSION_DEPTH {
            let range = self.cur_range();
            return Err(self.error_bail(range, "this construct nests too deeply"));
        }
        Ok(())
    }

    /// Leaves one level of recursion.
    fn leave(&mut self) {
        self.depth = self.depth.saturating_sub(1);
    }

    /// Reports a construct the block's own standard does not have.
    ///
    /// Parsing continues either way: the shape of the code is known, and
    /// carrying on means one diagnostic that says exactly what to change
    /// instead of a cascade of syntax errors after it.
    ///
    /// `__extension__` switches the gate off for the declaration it is written
    /// in, which is exactly what it means in GCC — "this is an extension and I
    /// know it". It is what the bundled headers put in front of their
    /// `long long` declarations, so that `#include <stdlib.h>` in a `c89!`
    /// block declares `llabs` instead of reporting the header, and it is
    /// available to a program that wants the same bargain.
    fn require_standard(&mut self, needed: Standard, what: &str, range: SourceRange) {
        if self.in_extension {
            return;
        }
        if let Some(message) = self.gating.requires(what, needed) {
            self.error(range, message);
        }
    }

    /// Reports a keyword the block's own standard does not have.
    fn require_keyword(&mut self, k: Keyword, range: SourceRange) {
        let needed = k.since();
        self.require_standard(needed, &format!("'{}'", k.as_str()), range);
    }

    /// The gate message for the identifier at the current position, if a
    /// newer revision would have made it a keyword.
    fn newer_keyword_here(&self) -> Option<String> {
        self.gating.newer_keyword(self.peek().ident()?)
    }

    /// Whether this block has the GNU leniencies; see
    /// [`Sema::gnu_leniency`](crate::sema).
    fn gnu_leniency(&self) -> bool {
        self.gating.dialect.is_gnu()
    }

    /// The note that names the entry point which would have accepted what
    /// [`Parser::gnu_leniency`] just refused.
    fn gnu_note(&self) -> String {
        format!(
            "GCC accepts this with a warning; write {} for the same leniency",
            self.gating.standard.macro_name_in(crate::Dialect::Gnu)
        )
    }

    /// Reports a GNU-only leniency the strict entry points refuse.
    fn error_gnu(&mut self, range: SourceRange, message: impl Into<String>) {
        let note = self.gnu_note();
        self.diags
            .push(Diagnostic::error(range, message).with_note(note));
    }
}

// ---------------------------------------------------------------------------
// scopes / the lexer hack
// ---------------------------------------------------------------------------

impl Parser<'_> {
    fn push_scope(&mut self) {
        self.scopes.push(Scope::default());
    }

    fn pop_scope(&mut self) {
        self.scopes.pop();
    }

    fn declare(&mut self, name: &str, kind: SymKind) {
        if let Some(scope) = self.scopes.last_mut() {
            scope.syms.insert(name.to_owned(), kind);
        }
    }

    /// Whether `name` currently names a type.
    fn is_typedef_name(&self, name: &str) -> bool {
        for scope in self.scopes.iter().rev() {
            if let Some(kind) = scope.syms.get(name) {
                return *kind == SymKind::Typedef;
            }
        }
        false
    }
}

// ---------------------------------------------------------------------------
// C23 attributes and `_Static_assert`
// ---------------------------------------------------------------------------

impl Parser<'_> {
    /// Whether an attribute specifier sequence starts here.
    ///
    /// Both spellings count: C23's `[[…]]` and GNU's `__attribute__((…))`,
    /// which mean the same things and are parsed by the same code.
    fn at_attributes(&self) -> bool {
        (self.at_punct(Punct::LBracket) && self.nth(1).is_punct(Punct::LBracket))
            || self.at_keyword(Keyword::Attribute)
    }

    /// Consumes every attribute specifier here, keeping what is acted on.
    ///
    /// An attribute the front end does not know is dropped, which C23
    /// 6.7.13.1p3 explicitly allows and which is what GCC does with a warning
    /// this crate has no way to raise; one it knows but cannot honour —
    /// `alias`, `weakref`, `vector_size` — is refused, because ignoring it
    /// would change what the program means. `weak` and `cleanup` are refused
    /// too, but only where they would mean something, so the decision is
    /// sema's rather than this pass's.
    fn parse_attributes(&mut self) -> PResult<Attributes> {
        let mut attrs = Attributes::default();
        loop {
            if self.at_keyword(Keyword::Attribute) {
                let start = self.bump_range();
                self.expect_punct(Punct::LParen, " after '__attribute__'")?;
                self.expect_punct(Punct::LParen, " after '__attribute__('")?;
                self.parse_attribute_list(&mut attrs, Punct::RParen)?;
                self.expect_punct(Punct::RParen, " to close '__attribute__'")?;
                self.expect_punct(Punct::RParen, " to close '__attribute__'")?;
                let _ = start;
                continue;
            }
            if self.at_punct(Punct::LBracket) && self.nth(1).is_punct(Punct::LBracket) {
                let start = self.cur_range();
                self.require_standard(Standard::C23, "an attribute specifier", start);
                self.advance(); // `[`
                self.advance(); // `[`
                self.parse_attribute_list(&mut attrs, Punct::RBracket)?;
                self.expect_punct(Punct::RBracket, " to close an attribute specifier")?;
                self.expect_punct(Punct::RBracket, " to close an attribute specifier")?;
                continue;
            }
            return Ok(attrs);
        }
    }

    /// `name (args)? , name (args)? , …`, up to `close`.
    fn parse_attribute_list(&mut self, attrs: &mut Attributes, close: Punct) -> PResult<()> {
        loop {
            if self.at_punct(close) || self.at_eof() {
                return Ok(());
            }
            // An empty element is legal in GNU's list: `__attribute__((,))`.
            if self.eat_punct(Punct::Comma).is_some() {
                continue;
            }
            self.parse_one_attribute(attrs, close)?;
            if self.eat_punct(Punct::Comma).is_none() {
                return Ok(());
            }
        }
    }

    /// One attribute, with its argument clause if it has one.
    fn parse_one_attribute(&mut self, attrs: &mut Attributes, close: Punct) -> PResult<()> {
        let start = self.cur_range();
        // The name may be a keyword — `__attribute__((const))`, `[[noreturn]]`
        // — and C23 allows a `vendor::` prefix, which is skipped.
        let mut name = match &self.peek().kind {
            TokenKind::Ident(name) => name.clone(),
            TokenKind::Keyword(k) => k.as_str().to_owned(),
            _ => {
                let found = self.describe_cur();
                return Err(self.error_bail(start, format!("expected an attribute, found {found}")));
            }
        };
        self.advance();
        // `[[cinrs::safe]]`: this crate's own namespace, whose names are read
        // from a table of their own.
        let mut ours = false;
        if self.at_punct(Punct::Colon) && self.nth(1).is_punct(Punct::Colon) {
            self.advance();
            self.advance();
            let prefix = std::mem::take(&mut name);
            name = match &self.peek().kind {
                TokenKind::Ident(name) => name.clone(),
                TokenKind::Keyword(k) => k.as_str().to_owned(),
                _ => {
                    let found = self.describe_cur();
                    return Err(
                        self.error_bail(start, format!("expected an attribute, found {found}"))
                    );
                }
            };
            self.advance();
            // Only the GNU namespace and this crate's own name attributes this
            // front end knows; anything else is another vendor's and is
            // ignored.
            if prefix == "cinrs" {
                if gnu::cinrs_attribute(&name).is_none() {
                    self.skip_attribute_args()?;
                    let range = self.span_to_here(start);
                    self.error(
                        range,
                        format!(
                            "unknown 'cinrs' attribute '{name}'; the ones this crate has are {}",
                            Self::list_of_names(gnu::CINRS_ATTRIBUTES)
                        ),
                    );
                    return Ok(());
                }
                ours = true;
            } else if prefix != "gnu" && prefix != "clang" {
                self.skip_attribute_args()?;
                return Ok(());
            }
        }

        let known = if ours {
            gnu::cinrs_attribute(&name)
        } else {
            gnu::attribute(&name)
        };
        // Only three attributes have arguments this front end reads; every
        // other clause may hold anything at all — `format(printf, 1, 2)` names
        // a *mode* rather than a value — and is skipped as balanced tokens.
        match known {
            Some(gnu::Attribute::Aligned) => {
                let alignment = if self.at_punct(Punct::LParen) {
                    self.advance();
                    let expr = self.parse_conditional_expr()?;
                    self.expect_punct(Punct::RParen, " after the alignment")?;
                    AlignmentKind::Expr(expr)
                } else {
                    // Bare `aligned` asks for the biggest alignment any type on
                    // the target needs, which is 16 on every ABI here.
                    AlignmentKind::Expr(int_expr(16, start))
                };
                let range = self.span_to_here(start);
                attrs.aligned = Some(Alignment {
                    kind: alignment,
                    from_attribute: true,
                    range,
                });
                return Ok(());
            }
            Some(gnu::Attribute::Deprecated) => {
                let message = self.attribute_string()?;
                let range = self.span_to_here(start);
                attrs.deprecated = Some(Spanned::new(message, range));
                return Ok(());
            }
            Some(gnu::Attribute::Cleanup) => {
                // The argument is an identifier naming a function, and nothing
                // else: GCC's own two diagnostics are "cleanup argument not an
                // identifier" and "cleanup argument not a function", and only
                // sema can tell the second one.
                let func = self.attribute_identifier()?;
                let range = self.span_to_here(start);
                attrs.cleanup = Some(Cleanup { func, range });
                return Ok(());
            }
            Some(gnu::Attribute::Mode) => {
                // The argument names a machine mode — `QI`, `DI`, `word` —
                // and GCC accepts the `__QI__` spelling of each as well.
                let mode = self.attribute_identifier()?;
                let range = self.span_to_here(start);
                match mode {
                    Some(mode) => attrs.mode = Some(Spanned::new(mode.name, range)),
                    None => self.error(range, "'mode' takes one machine mode name"),
                }
                return Ok(());
            }
            Some(gnu::Attribute::Section) => {
                let name = self.attribute_string()?;
                let range = self.span_to_here(start);
                match name {
                    Some(name) => attrs.section = Some(Spanned::new(name, range)),
                    None => self.error(range, "'section' takes one string literal"),
                }
                return Ok(());
            }
            _ => {}
        }
        self.skip_attribute_args()?;
        let range = self.span_to_here(start);
        match known {
            Some(gnu::Attribute::Noreturn) => attrs.noreturn = attrs.noreturn.or(Some(range)),
            Some(gnu::Attribute::AlwaysInline) => {
                attrs.always_inline = attrs.always_inline.or(Some(range));
            }
            Some(gnu::Attribute::NoInline) => attrs.noinline = attrs.noinline.or(Some(range)),
            Some(gnu::Attribute::Cold) => attrs.cold = attrs.cold.or(Some(range)),
            // GCC's `hot` is the opposite of `cold`, and the two cancel.
            Some(gnu::Attribute::Hot) => attrs.cold = None,
            Some(gnu::Attribute::Packed) => attrs.packed = attrs.packed.or(Some(range)),
            Some(gnu::Attribute::Constructor) => {
                attrs.constructor = attrs.constructor.or(Some(range));
            }
            Some(gnu::Attribute::Destructor) => {
                attrs.destructor = attrs.destructor.or(Some(range));
            }
            Some(gnu::Attribute::Safe) => attrs.safe = attrs.safe.or(Some(range)),
            // Only sema knows whether a definition follows, and that is the
            // whole of the question `weak` asks; see `Sema::reject_weak`.
            Some(gnu::Attribute::Weak) => attrs.weak = attrs.weak.or(Some(range)),
            // A statement attribute with nothing to say here: a `switch` group
            // falls through in the generated Rust either way.
            Some(gnu::Attribute::Fallthrough) | Some(gnu::Attribute::Ignored) => {}
            Some(gnu::Attribute::Unsupported) => {
                let reason = gnu::unsupported_reason(&name).unwrap_or("is not supported");
                self.error(range, format!("'{name}' {reason}"));
            }
            // Everything above was handled; an unknown attribute is ignored,
            // as C23 requires.
            _ => {}
        }
        let _ = close;
        Ok(())
    }

    /// The single identifier an attribute's argument clause holds, if that is
    /// what it holds; whatever else is there is skipped as balanced tokens.
    fn attribute_identifier(&mut self) -> PResult<Option<Ident>> {
        if !self.at_punct(Punct::LParen) {
            return Ok(None);
        }
        self.advance();
        let name = match &self.peek().kind {
            TokenKind::Ident(name) => {
                let ident = Ident {
                    name: name.clone(),
                    range: self.cur_range(),
                };
                self.advance();
                // `cleanup(f, g)` is not an identifier argument either.
                self.at_punct(Punct::RParen).then_some(ident)
            }
            _ => None,
        };
        let mut depth = 1i32;
        while depth > 0 && !self.at_eof() {
            if self.at_punct(Punct::LParen) {
                depth += 1;
            } else if self.at_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    self.advance();
                    break;
                }
            }
            self.advance();
        }
        Ok(name)
    }

    /// The single string literal an attribute's argument clause holds, if it
    /// has one at all.
    fn attribute_string(&mut self) -> PResult<Option<String>> {
        if !self.at_punct(Punct::LParen) {
            return Ok(None);
        }
        self.advance();
        let mut text = None;
        if let TokenKind::Str(lit) = self.peek().kind.clone() {
            let range = self.cur_range();
            let literal = self.parse_string_literal(lit, range);
            if let ExprKind::Str(lit) = literal.kind {
                text = String::from_utf8(lit.values.iter().map(|v| *v as u8).collect()).ok();
            }
        }
        // Anything else — a priority, an unknown option — is skipped.
        let mut depth = 1i32;
        while depth > 0 && !self.at_eof() {
            if self.at_punct(Punct::LParen) {
                depth += 1;
            } else if self.at_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    self.advance();
                    break;
                }
            }
            self.advance();
        }
        Ok(text)
    }

    /// Skips a balanced argument clause without looking inside it.
    fn skip_attribute_args(&mut self) -> PResult<()> {
        if !self.at_punct(Punct::LParen) {
            return Ok(());
        }
        let start = self.cur_range();
        let mut depth = 0i32;
        while !self.at_eof() {
            if self.at_punct(Punct::LParen) {
                depth += 1;
            } else if self.at_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    self.advance();
                    return Ok(());
                }
            }
            self.advance();
        }
        Err(self.error_bail(start, "unterminated attribute argument list"))
    }

    /// `'a'`, `'a' and 'b'`, `'a', 'b' and 'c'` — how a diagnostic lists the
    /// names it would have accepted.
    fn list_of_names(names: &[&str]) -> String {
        let quoted: Vec<String> = names.iter().map(|name| format!("'{name}'")).collect();
        match quoted.split_last() {
            None => String::new(),
            Some((last, [])) => last.clone(),
            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
        }
    }

    /// Whether a `_Static_assert` declaration starts here.
    fn at_static_assert(&self) -> bool {
        matches!(
            self.peek().keyword(),
            Some(Keyword::StaticAssert | Keyword::StaticAssertName)
        )
    }

    /// `_Static_assert ( constant-expression , "message" ) ;`, whose message
    /// C23 makes optional.
    fn parse_static_assert(&mut self) -> PResult<StaticAssert> {
        let start = self.cur_range();
        let keyword = self.peek().keyword().expect("the caller checked");
        self.require_keyword(keyword, start);
        self.advance();
        let name = keyword.as_str();
        self.expect_punct(Punct::LParen, &format!(" after '{name}'"))?;
        let cond = self.parse_conditional_expr()?;
        let mut message = None;
        if self.eat_punct(Punct::Comma).is_some() {
            let range = self.cur_range();
            let TokenKind::Str(first) = self.peek().kind.clone() else {
                let found = self.describe_cur();
                return Err(self.error_bail(
                    range,
                    format!("expected a string literal as the message of '{name}', found {found}"),
                ));
            };
            let literal = self.parse_string_literal(first, range);
            if let ExprKind::Str(lit) = literal.kind {
                message = Some(lit.text);
            }
        } else {
            self.require_standard(
                Standard::C23,
                &format!("'{name}' without a message"),
                self.span_to_here(start),
            );
        }
        self.expect_punct(Punct::RParen, &format!(" to close '{name}'"))?;
        self.expect_punct(Punct::Semi, &format!(" after '{name}'"))?;
        Ok(StaticAssert {
            cond,
            message,
            range: self.span_to_here(start),
        })
    }
}

// ---------------------------------------------------------------------------
// top level
// ---------------------------------------------------------------------------

impl Parser<'_> {
    fn parse_translation_unit(&mut self, range: SourceRange) -> TranslationUnit {
        let mut items = Vec::new();
        while !self.at_eof() {
            let before = self.pos;
            self.depth = 0;
            // A stray `;` at file scope. C's grammar has no empty external
            // declaration — 6.9p1 is a *declaration* or a function definition,
            // and C23 6.7p1 did not add one — but GCC accepts it with only a
            // pedantic warning ("ISO C does not allow extra ';' outside of a
            // function"), and a macro whose expansion already ends in `;`
            // being written with one after it is common enough that seven of
            // the torture suite's cases do it. The GNU dialects accept it; the
            // strict ones keep the error.
            if self.at_punct(Punct::Semi) {
                let range = self.bump_range();
                if !self.gnu_leniency() {
                    self.error_gnu(range, "expected a declaration, found ';'");
                }
                continue;
            }
            match self.parse_external_decl() {
                Ok(item) => items.push(item),
                Err(Bail) => self.recover_top_level(before),
            }
            if self.pos == before {
                self.advance();
            }
        }
        TranslationUnit {
            items,
            records: std::mem::take(&mut self.records),
            enums: std::mem::take(&mut self.enums),
            typeofs: std::mem::take(&mut self.typeofs),
            range,
        }
    }

    /// How deeply nested in brackets the current position is, relative to the
    /// token at `start`.
    fn depth_from(&self, start: usize) -> i32 {
        let mut depth = 0i32;
        for tok in &self.tokens[start.min(self.pos)..self.pos] {
            match &tok.kind {
                TokenKind::Punct(Punct::LBrace | Punct::LParen | Punct::LBracket) => depth += 1,
                TokenKind::Punct(Punct::RBrace | Punct::RParen | Punct::RBracket) => depth -= 1,
                _ => {}
            }
        }
        depth.max(0)
    }

    /// Skips forward to just past the `;` or `}` that ends the external
    /// declaration that started at token `decl_start`.
    ///
    /// Starting from the nesting depth the error was found at (rather than
    /// from zero) is what keeps a single broken statement inside a function
    /// body from producing a cascade of errors for the rest of the body.
    fn recover_top_level(&mut self, decl_start: usize) {
        let mut depth = self.depth_from(decl_start);
        while !self.at_eof() {
            match &self.peek().kind {
                TokenKind::Punct(Punct::LBrace | Punct::LParen | Punct::LBracket) => {
                    depth += 1;
                    self.advance();
                }
                TokenKind::Punct(Punct::RBrace | Punct::RParen | Punct::RBracket) => {
                    let paren = self.at_punct(Punct::RParen) || self.at_punct(Punct::RBracket);
                    depth -= 1;
                    self.advance();
                    if depth <= 0 {
                        // `struct S { int x };` — swallow the `;` that closes
                        // the declaration so that it is not mistaken for the
                        // start of the next one.
                        if self.eat_punct(Punct::Semi).is_some() {
                            return;
                        }
                        // A declarator's own `)` or `]` closing is not the end
                        // of the declaration: `void f(<error>) { … }` still
                        // owes a body, and reporting its `{` as a stray one
                        // would be a second error for one mistake. Keep
                        // scanning and let the body's `}` finish the job.
                        if paren && self.at_punct(Punct::LBrace) {
                            depth = 0;
                            continue;
                        }
                        return;
                    }
                }
                TokenKind::Punct(Punct::Semi) => {
                    self.advance();
                    if depth <= 0 {
                        return;
                    }
                }
                _ => self.advance(),
            }
        }
    }

    fn parse_external_decl(&mut self) -> PResult<ExternalDecl> {
        let start = self.cur_range();
        // `__extension__` marks what follows as a GNU extension and asks for
        // the diagnostics about using one to be held back, which here means
        // the gates a `c89!` block puts on what C99 added. Every external
        // declaration starts afresh, so the flag never outlives the one it
        // was written in — including down an error path.
        self.in_extension = false;
        while self.eat_keyword(Keyword::Extension).is_some() {
            self.in_extension = true;
        }
        let attrs = self.parse_attributes()?;
        if self.at_static_assert() {
            return Ok(ExternalDecl::StaticAssert(self.parse_static_assert()?));
        }
        let mut specs = self.parse_decl_specifiers(true)?;
        specs.attrs.merge(attrs);
        specs.noreturn = specs.noreturn.or(specs.attrs.noreturn);

        if let Some(semi) = self.eat_punct(Punct::Semi) {
            return Ok(ExternalDecl::Decl(Decl {
                specifiers: specs,
                declarators: Vec::new(),
                range: start.join(semi),
            }));
        }

        let mut first = self.parse_declarator(specs.base.clone(), false)?;
        self.parse_declarator_tail(&mut first)?;

        let looks_like_definition = matches!(first.ty.kind, TypeKind::Function(_))
            && (self.at_punct(Punct::LBrace) || self.starts_declaration());
        if looks_like_definition && !specs.is_typedef() {
            return self.finish_function_def(specs, first, start);
        }

        let decl = self.finish_declaration(specs, Some(first), start)?;
        Ok(ExternalDecl::Decl(decl))
    }

    /// `__asm__("symbol")` and `__attribute__((…))`, which may follow any
    /// declarator and in that order.
    fn parse_declarator_tail(&mut self, declarator: &mut DeclaratorResult) -> PResult<()> {
        loop {
            if self.at_keyword(Keyword::Asm) {
                let start = self.cur_range();
                self.advance();
                self.expect_punct(Punct::LParen, " after 'asm'")?;
                let range = self.cur_range();
                let TokenKind::Str(lit) = self.peek().kind.clone() else {
                    let found = self.describe_cur();
                    return Err(self.error_bail(
                        range,
                        format!("expected the symbol name as a string literal, found {found}"),
                    ));
                };
                let literal = self.parse_string_literal(lit, range);
                self.expect_punct(Punct::RParen, " after the symbol name")?;
                if let ExprKind::Str(lit) = literal.kind
                    && let Ok(name) =
                        String::from_utf8(lit.values.iter().map(|v| *v as u8).collect())
                {
                    declarator.asm_label = Some(Spanned::new(name, self.span_to_here(start)));
                }
                continue;
            }
            if self.at_attributes() {
                let attrs = self.parse_attributes()?;
                declarator.attrs.merge(attrs);
                continue;
            }
            return Ok(());
        }
    }

    /// The declaration list of an old-style definition — `int a, b;` between
    /// `f(a, b)` and the body.
    ///
    /// A static assertion is a declaration, so the grammar admits one here and
    /// C99 6.9.1p6 then forbids it: every declaration in the list has to
    /// declare one of the parameters, and a static assertion declares nothing.
    /// Saying so and reading on is one error for one mistake — giving up here
    /// would report the body's `{` as a stray one as well, which is two.
    fn parse_kr_declaration_list(&mut self) -> PResult<Vec<Decl>> {
        let mut decls = Vec::new();
        loop {
            if self.at_static_assert() {
                let range = self.cur_range();
                self.error(
                    range,
                    "a static assertion is not allowed in the declaration list of an old-style \
                     function definition; every declaration there has to declare one of the \
                     parameters (C99 6.9.1p6)",
                );
                self.parse_static_assert()?;
                continue;
            }
            if !self.starts_declaration() {
                return Ok(decls);
            }
            decls.push(self.parse_declaration()?);
        }
    }

    fn finish_function_def(
        &mut self,
        specs: DeclSpecifiers,
        declarator: DeclaratorResult,
        start: SourceRange,
    ) -> PResult<ExternalDecl> {
        let Some(name) = declarator.name.clone() else {
            return Err(self.error_bail(declarator.range, "function definition requires a name"));
        };
        self.declare(&name.name, SymKind::Ordinary);

        // Parameters (and old-style parameter declarations) share a scope with
        // the body's outermost block.
        self.push_scope();
        if let TypeKind::Function(ft) = &declarator.ty.kind {
            for param in &ft.params {
                if let Some(pname) = &param.name {
                    self.scopes
                        .last_mut()
                        .expect("scope stack is never empty")
                        .syms
                        .insert(pname.name.clone(), SymKind::Ordinary);
                }
            }
            for kr in &ft.kr_names {
                self.scopes
                    .last_mut()
                    .expect("scope stack is never empty")
                    .syms
                    .insert(kr.name.clone(), SymKind::Ordinary);
            }
        }

        let kr_decls = match self.parse_kr_declaration_list() {
            Ok(decls) => decls,
            Err(bail) => {
                self.pop_scope();
                return Err(bail);
            }
        };

        let before = self.label_addrs;
        let body = match self.parse_compound_stmt() {
            Ok(body) => body,
            Err(bail) => {
                self.pop_scope();
                return Err(bail);
            }
        };
        self.pop_scope();

        Ok(ExternalDecl::Function(FunctionDef {
            specifiers: specs,
            name,
            ty: declarator.ty,
            kr_decls,
            attrs: declarator.attrs,
            asm_label: declarator.asm_label,
            body,
            uses_label_addrs: self.label_addrs != before,
            range: self.span_to_here(start),
        }))
    }

    /// Parses `declarator (= initializer)? (, declarator (= initializer)?)* ;`.
    fn finish_declaration(
        &mut self,
        specs: DeclSpecifiers,
        first: Option<DeclaratorResult>,
        start: SourceRange,
    ) -> PResult<Decl> {
        let is_typedef = specs.is_typedef();
        let mut declarators = Vec::new();
        let mut pending = first;
        loop {
            let mut declarator = match pending.take() {
                Some(d) => d,
                None => {
                    let mut d = self.parse_declarator(specs.base.clone(), false)?;
                    self.parse_declarator_tail(&mut d)?;
                    d
                }
            };
            if let Some(name) = &declarator.name {
                let kind = if is_typedef {
                    SymKind::Typedef
                } else {
                    SymKind::Ordinary
                };
                self.declare(&name.name.clone(), kind);
            }
            let init = if self.eat_punct(Punct::Assign).is_some() {
                Some(self.parse_initializer()?)
            } else {
                None
            };
            // GCC lets the attributes come after the initialiser too.
            if self.at_attributes() {
                let attrs = self.parse_attributes()?;
                declarator.attrs.merge(attrs);
            }
            let range = self.span_to_here(declarator.range);
            declarators.push(InitDeclarator {
                name: declarator.name,
                ty: declarator.ty,
                init,
                attrs: declarator.attrs,
                asm_label: declarator.asm_label,
                range,
            });
            if self.eat_punct(Punct::Comma).is_none() {
                break;
            }
        }
        let semi = self.expect_punct(Punct::Semi, " after declaration")?;
        Ok(Decl {
            specifiers: specs,
            declarators,
            range: start.join(semi),
        })
    }

    /// Parses a declaration that cannot be a function definition.
    ///
    /// A K&R parameter declaration list and a `for` clause are the two places
    /// that use it — neither may hold a definition, and in the K&R list the
    /// `{` that follows opens the body of the function being defined, not a
    /// nested one. A block item goes through
    /// [`Parser::parse_block_declaration`], which may find GNU's nested
    /// function definition instead.
    fn parse_declaration(&mut self) -> PResult<Decl> {
        // `__extension__` covers the declaration it is written on, so one
        // nested inside another — a local in the body of a function whose
        // definition carries it — starts afresh, and the enclosing one gets
        // its answer back whichever way this goes.
        let enclosing = std::mem::take(&mut self.in_extension);
        let result = self.parse_declaration_inner();
        self.in_extension = enclosing;
        result
    }

    fn parse_declaration_inner(&mut self) -> PResult<Decl> {
        let (specs, start) = self.parse_declaration_head()?;
        if let Some(semi) = self.eat_punct(Punct::Semi) {
            return Ok(Decl {
                specifiers: specs,
                declarators: Vec::new(),
                range: start.join(semi),
            });
        }
        self.finish_declaration(specs, None, start)
    }

    /// The `__extension__`s, attributes and declaration specifiers that a
    /// declaration — and a nested function definition, which begins as one —
    /// opens with, and where they began.
    fn parse_declaration_head(&mut self) -> PResult<(DeclSpecifiers, SourceRange)> {
        let start = self.cur_range();
        while self.eat_keyword(Keyword::Extension).is_some() {
            self.in_extension = true;
        }
        let attrs = self.parse_attributes()?;
        let mut specs = self.parse_decl_specifiers(true)?;
        specs.attrs.merge(attrs);
        specs.noreturn = specs.noreturn.or(specs.attrs.noreturn);
        Ok((specs, start))
    }

    /// Parses a block item that begins like a declaration.
    ///
    /// Block scope is the one place where what looks like a declaration may
    /// really be a function *definition*: GNU's nested functions. See
    /// [`Parser::parse_nested_function`].
    fn parse_block_declaration(&mut self) -> PResult<BlockItem> {
        let enclosing = std::mem::take(&mut self.in_extension);
        let result = self.parse_block_declaration_inner();
        self.in_extension = enclosing;
        result
    }

    fn parse_block_declaration_inner(&mut self) -> PResult<BlockItem> {
        let (specs, start) = self.parse_declaration_head()?;
        if let Some(semi) = self.eat_punct(Punct::Semi) {
            return Ok(BlockItem::Decl(Decl {
                specifiers: specs,
                declarators: Vec::new(),
                range: start.join(semi),
            }));
        }
        // The first declarator is taken here rather than left to
        // [`Parser::finish_declaration`], because it is the declarator that
        // says whether this is a declaration at all.
        let mut first = self.parse_declarator(specs.base.clone(), false)?;
        self.parse_declarator_tail(&mut first)?;
        if self.at_nested_function_body(&specs, &first) {
            return self
                .parse_nested_function(specs, first, start)
                .map(BlockItem::NestedFunction);
        }
        self.finish_declaration(specs, Some(first), start)
            .map(BlockItem::Decl)
    }

    /// Whether the block-scope declaration just read is really the head of a
    /// GNU nested function definition — `int f(void) { int g(int x) { … } }`.
    ///
    /// The shape is a named function declarator followed by the body, either
    /// straight away or after a K&R parameter declaration list. Insisting that
    /// the `{` really be there is what keeps a plain missing semicolon —
    /// `int g(int)` and then `int x;` — reported as the missing semicolon it
    /// is.
    fn at_nested_function_body(
        &self,
        specs: &DeclSpecifiers,
        declarator: &DeclaratorResult,
    ) -> bool {
        declarator.name.is_some()
            && !specs.is_typedef()
            && matches!(declarator.ty.kind, TypeKind::Function(_))
            && (self.at_punct(Punct::LBrace) || self.at_kr_declaration_list())
    }

    /// Whether a K&R parameter declaration list and then a body follow the
    /// declarator: `g(a) int a; { … }`.
    ///
    /// A lookahead, over tokens only — each declaration runs to the `;` that
    /// is not inside brackets, and what has to come after the last of them is
    /// the `{`.
    fn at_kr_declaration_list(&self) -> bool {
        let mut n = 0;
        while self.starts_decl_specifier(n) {
            let mut depth = 0i32;
            loop {
                let tok = self.nth(n);
                if tok.is_eof() {
                    return false;
                }
                n += 1;
                match &tok.kind {
                    TokenKind::Punct(Punct::LBrace | Punct::LParen | Punct::LBracket) => depth += 1,
                    TokenKind::Punct(Punct::RBrace | Punct::RParen | Punct::RBracket) => {
                        depth -= 1;
                        if depth < 0 {
                            return false;
                        }
                    }
                    TokenKind::Punct(Punct::Semi) if depth == 0 => break,
                    _ => {}
                }
            }
        }
        n > 0 && self.nth(n).is_punct(Punct::LBrace)
    }

    /// Parses a GNU nested function definition, body and all.
    ///
    /// The shape is a function definition written where a declaration may
    /// stand, so this is [`Parser::finish_function_def`] with two differences:
    /// the name is declared in the *enclosing block*, which is the scope GNU
    /// gives it and which is what lets the body call the function
    /// recursively, and the result is a block item rather than an external
    /// declaration. Semantic analysis lifts it out; see
    /// `Sema::nested_function_def`.
    fn parse_nested_function(
        &mut self,
        specs: DeclSpecifiers,
        declarator: DeclaratorResult,
        start: SourceRange,
    ) -> PResult<FunctionDef> {
        let name = declarator
            .name
            .clone()
            .expect("at_nested_function_body requires a name");
        self.declare(&name.name, SymKind::Ordinary);

        // Parameters (and old-style parameter declarations) share a scope with
        // the body's outermost block.
        self.push_scope();
        if let TypeKind::Function(ft) = &declarator.ty.kind {
            for param in &ft.params {
                if let Some(pname) = &param.name {
                    self.scopes
                        .last_mut()
                        .expect("scope stack is never empty")
                        .syms
                        .insert(pname.name.clone(), SymKind::Ordinary);
                }
            }
            for kr in &ft.kr_names {
                self.scopes
                    .last_mut()
                    .expect("scope stack is never empty")
                    .syms
                    .insert(kr.name.clone(), SymKind::Ordinary);
            }
        }

        let kr_decls = match self.parse_kr_declaration_list() {
            Ok(decls) => decls,
            Err(bail) => {
                self.pop_scope();
                return Err(bail);
            }
        };

        let before = self.label_addrs;
        let body = match self.parse_compound_stmt() {
            Ok(body) => body,
            Err(bail) => {
                self.pop_scope();
                return Err(bail);
            }
        };
        self.pop_scope();
        let uses_label_addrs = self.label_addrs != before;
        // A nested function's `&&label` names a label of its *own* body, so
        // the count goes back to what the enclosing function had.
        self.label_addrs = before;

        Ok(FunctionDef {
            specifiers: specs,
            name,
            ty: declarator.ty,
            kr_decls,
            attrs: declarator.attrs,
            asm_label: declarator.asm_label,
            body,
            uses_label_addrs,
            range: self.span_to_here(start),
        })
    }
}

// ---------------------------------------------------------------------------
// declaration specifiers
// ---------------------------------------------------------------------------

/// Counters for the combinable type-specifier keywords.
#[derive(Default)]
struct SpecCounts {
    void: u32,
    char: u32,
    short: u32,
    int: u32,
    long: u32,
    float: u32,
    double: u32,
    signed: u32,
    unsigned: u32,
    bool: u32,
    complex: u32,
    imaginary: u32,
    int128: u32,
}

impl SpecCounts {
    fn any(&self) -> bool {
        self.void
            + self.char
            + self.short
            + self.int
            + self.long
            + self.float
            + self.double
            + self.signed
            + self.unsigned
            + self.bool
            + self.complex
            + self.imaginary
            + self.int128
            > 0
    }
}

impl Parser<'_> {
    /// Whether the current token can begin a declaration.
    fn starts_declaration(&self) -> bool {
        self.starts_decl_specifier(0)
    }

    /// Whether the current token can begin a declarator.
    ///
    /// Only asked where there were no declaration specifiers at all, to tell
    /// `f() { … }` — implicit `int`, and a diagnostic that says so from C99 on
    /// — from a stray token that begins nothing.
    fn starts_declarator(&self) -> bool {
        let tok = self.peek();
        tok.ident().is_some() || tok.is_punct(Punct::Star) || tok.is_punct(Punct::LParen)
    }

    /// Whether the token `n` positions ahead can begin a declaration
    /// specifier (or, for a type name, a specifier-qualifier list).
    fn starts_decl_specifier(&self, n: usize) -> bool {
        let tok = self.nth(n);
        if let Some(k) = tok.keyword() {
            return matches!(
                k,
                Keyword::Typedef
                    | Keyword::Extern
                    | Keyword::Static
                    | Keyword::Auto
                    | Keyword::Register
                    | Keyword::Const
                    | Keyword::Volatile
                    | Keyword::Restrict
                    | Keyword::Inline
                    | Keyword::Void
                    | Keyword::Char
                    | Keyword::Short
                    | Keyword::Int
                    | Keyword::Long
                    | Keyword::Float
                    | Keyword::Double
                    | Keyword::Signed
                    | Keyword::Unsigned
                    | Keyword::Bool
                    | Keyword::Complex
                    | Keyword::Imaginary
                    | Keyword::Struct
                    | Keyword::Union
                    | Keyword::Enum
                    | Keyword::Alignas
                    | Keyword::AlignasName
                    | Keyword::Atomic
                    | Keyword::BitInt
                    | Keyword::Noreturn
                    | Keyword::ThreadLocal
                    | Keyword::ThreadLocalName
                    | Keyword::Constexpr
                    | Keyword::Typeof
                    | Keyword::TypeofUnqual
                    | Keyword::BoolName
                    | Keyword::Attribute
                    | Keyword::Extension
                    | Keyword::TypeofGnu
                    | Keyword::TypeofUnqualGnu
                    | Keyword::AutoType
                    | Keyword::ThreadGnu
                    | Keyword::Int128
                    | Keyword::InlineGnu
                    | Keyword::RestrictGnu
            );
        }
        match tok.ident() {
            Some(NORETURN_BUILTIN) => true,
            // A label such as `done:` must not look like a declaration even
            // when it happens to share a name with a `typedef`.
            Some(name) => self.is_typedef_name(name) && !self.nth(n + 1).is_punct(Punct::Colon),
            None => false,
        }
    }

    fn eat_type_qualifier(&mut self) -> Option<TypeQualifiers> {
        let keyword = self.peek().keyword()?;
        let q = match keyword {
            Keyword::Const => TypeQualifiers {
                is_const: true,
                ..TypeQualifiers::NONE
            },
            Keyword::Volatile => TypeQualifiers {
                is_volatile: true,
                ..TypeQualifiers::NONE
            },
            Keyword::Restrict | Keyword::RestrictGnu => TypeQualifiers {
                is_restrict: true,
                ..TypeQualifiers::NONE
            },
            // `_Atomic` with a parenthesised type name after it is a type
            // *specifier* — `_Atomic(int) x;` — and is parsed where the
            // specifiers are; everywhere else the keyword is a qualifier.
            Keyword::Atomic if !self.at_atomic_specifier(0) => TypeQualifiers {
                is_atomic: true,
                ..TypeQualifiers::NONE
            },
            _ => return None,
        };
        // `restrict` is C99's (N448); `__restrict` is reserved and works in
        // every entry point, exactly as it does in GCC's own `-std=c89`.
        if keyword == Keyword::Restrict {
            let range = self.cur_range();
            self.require_standard(Standard::C99, "'restrict'", range);
        }
        if keyword == Keyword::Atomic {
            let range = self.cur_range();
            self.require_keyword(Keyword::Atomic, range);
        }
        self.advance();
        Some(q)
    }

    /// Whether the `_Atomic` at offset `n` is the `_Atomic (type-name)` form.
    ///
    /// C11 6.7.2.4p4 draws the line exactly here: the keyword is a type
    /// specifier when it is followed by a parenthesised type name and a type
    /// qualifier otherwise, which is what makes `int * _Atomic (*p)(void)` a
    /// qualified pointer to a function rather than a syntax error.
    fn at_atomic_specifier(&self, n: usize) -> bool {
        self.nth(n).is_keyword(Keyword::Atomic)
            && self.nth(n + 1).is_punct(Punct::LParen)
            && self.starts_decl_specifier(n + 2)
    }

    fn parse_type_qualifiers(&mut self) -> TypeQualifiers {
        let mut quals = TypeQualifiers::NONE;
        while let Some(q) = self.eat_type_qualifier() {
            quals = quals.merge(q);
        }
        quals
    }

    /// Parses a declaration-specifier list (or, with `allow_storage == false`,
    /// a specifier-qualifier list).
    fn parse_decl_specifiers(&mut self, allow_storage: bool) -> PResult<DeclSpecifiers> {
        let start = self.cur_range();
        let mut storage: Option<Spanned<StorageClass>> = None;
        let mut thread_local: Option<SourceRange> = None;
        let mut inline = false;
        let mut noreturn: Option<SourceRange> = None;
        let mut alignas: Vec<Alignment> = Vec::new();
        let mut attributes = Attributes::default();
        let mut quals = TypeQualifiers::NONE;
        let mut counts = SpecCounts::default();
        let mut tag: Option<Type> = None;
        let mut typedef_name: Option<Ident> = None;
        let mut auto_type: Option<SourceRange> = None;
        // Where the C23 `auto` was written, which is *not* the same question
        // as what [`DeclSpecifiers::storage`] holds; see the storage-class
        // branch below.
        let mut auto_kw: Option<SourceRange> = None;
        let mut consumed_any = false;

        loop {
            let has_type = counts.any() || tag.is_some() || typedef_name.is_some();
            // C23 allows an attribute specifier sequence among the specifiers,
            // and GNU's `__attribute__((…))` goes in the same places.
            if self.at_attributes() {
                let attrs = self.parse_attributes()?;
                noreturn = noreturn.or(attrs.noreturn);
                attributes.merge(attrs);
                consumed_any = true;
                continue;
            }
            if self.at_keyword(Keyword::Extension) {
                self.advance();
                self.in_extension = true;
                consumed_any = true;
                continue;
            }
            if let Some(k) = self.peek().keyword() {
                // `_Thread_local` is not a storage class of its own: C11
                // 6.7.1p2 lets it sit beside `static` or `extern`, and at
                // block scope 6.7.1p3 requires one of them.
                if matches!(
                    k,
                    Keyword::ThreadLocal | Keyword::ThreadLocalName | Keyword::ThreadGnu
                ) {
                    let range = self.bump_range();
                    self.require_keyword(k, range);
                    consumed_any = true;
                    if !allow_storage {
                        self.error(
                            range,
                            format!("storage class '{}' is not allowed here", k.as_str()),
                        );
                    } else if thread_local.is_none() {
                        thread_local = Some(range);
                    }
                    continue;
                }
                let storage_class = match k {
                    Keyword::Typedef => Some(StorageClass::Typedef),
                    Keyword::Extern => Some(StorageClass::Extern),
                    Keyword::Static => Some(StorageClass::Static),
                    Keyword::Auto => Some(StorageClass::Auto),
                    Keyword::Register => Some(StorageClass::Register),
                    Keyword::Constexpr => Some(StorageClass::Constexpr),
                    _ => None,
                };
                if let Some(sc) = storage_class {
                    let range = self.bump_range();
                    self.require_keyword(k, range);
                    consumed_any = true;
                    // C23 6.7.1p2 keeps "at most one storage-class specifier"
                    // but makes `auto` the exception: it "may appear with all
                    // the others, except `typedef`". That is what
                    // `static auto c = 1UL;` is — an object with static
                    // storage duration whose type is inferred — and the
                    // exception is symmetric, so `auto static c = 1UL;` says
                    // the same thing. `auto` therefore does not claim the one
                    // slot: it is remembered in `auto_kw`, which is what
                    // decides the inference below, and yields the slot to the
                    // specifier that decides the storage duration whichever
                    // side of it that one was written.
                    let c23_auto = allow_storage
                        && self.standard >= Standard::C23
                        && (sc == StorageClass::Auto
                            || matches!(
                                storage,
                                Some(Spanned {
                                    node: StorageClass::Auto,
                                    ..
                                })
                            ))
                        && sc != StorageClass::Typedef
                        && !matches!(
                            storage,
                            Some(Spanned {
                                node: StorageClass::Typedef,
                                ..
                            })
                        );
                    // 6.7.1p2's other exception, in the same clause:
                    // `constexpr` "may appear with `auto`, `register` or
                    // `static`" — and with nothing else, so `extern
                    // constexpr` and `typedef constexpr` stay violations, and
                    // `thread_local` is refused where it is checked. The three
                    // it pairs with say where the object would *live* and
                    // `constexpr` says it is a constant instead, which is what
                    // decides the declaration here, so `constexpr` takes the
                    // slot from whichever side it was written.
                    let pairs_with_constexpr = |s: StorageClass| {
                        matches!(
                            s,
                            StorageClass::Static | StorageClass::Register | StorageClass::Auto
                        )
                    };
                    let c23_constexpr = allow_storage
                        && self.standard >= Standard::C23
                        && match (sc, storage.as_ref().map(|s| s.node)) {
                            (StorageClass::Constexpr, Some(prev)) => pairs_with_constexpr(prev),
                            (other, Some(StorageClass::Constexpr)) => pairs_with_constexpr(other),
                            _ => false,
                        };
                    if sc == StorageClass::Auto {
                        auto_kw = auto_kw.or(Some(range));
                    }
                    if !allow_storage {
                        self.error(
                            range,
                            format!("storage class '{}' is not allowed here", sc.as_str()),
                        );
                    } else if c23_constexpr {
                        if sc == StorageClass::Constexpr {
                            storage = Some(Spanned::new(sc, range));
                        }
                    } else if c23_auto {
                        // A specifier that is *not* `auto` takes the slot, so
                        // `auto` written first gives way and `auto` written
                        // second leaves what is already there alone. With
                        // nothing else in the declaration `auto` keeps it, as
                        // it did before C23.
                        if sc != StorageClass::Auto || storage.is_none() {
                            storage = Some(Spanned::new(sc, range));
                        }
                    } else if let Some(prev) = &storage {
                        self.error(
                            range,
                            format!(
                                "cannot combine storage class '{}' with '{}'",
                                sc.as_str(),
                                prev.node.as_str()
                            ),
                        );
                    } else {
                        storage = Some(Spanned::new(sc, range));
                    }
                    continue;
                }
                if let Some(q) = self.eat_type_qualifier() {
                    quals = quals.merge(q);
                    consumed_any = true;
                    continue;
                }
                if matches!(k, Keyword::Inline | Keyword::InlineGnu) {
                    let range = self.bump_range();
                    // C99 added `inline` (N741); `__inline__` is GCC's
                    // spelling of it and needs no entry point.
                    if k == Keyword::Inline {
                        self.require_standard(Standard::C99, "'inline'", range);
                    }
                    inline = true;
                    consumed_any = true;
                    continue;
                }
                if k == Keyword::Noreturn {
                    let range = self.bump_range();
                    self.require_keyword(k, range);
                    noreturn = noreturn.or(Some(range));
                    consumed_any = true;
                    continue;
                }
                if matches!(k, Keyword::Alignas | Keyword::AlignasName) {
                    // C11 6.7.5p6 allows several, and makes the strictest of
                    // them the one that holds; sema is where that is decided,
                    // since only it can evaluate the operands.
                    let spec = self.parse_alignment_specifier(k)?;
                    alignas.push(spec);
                    consumed_any = true;
                    continue;
                }
                // GNU's `__auto_type`, which is C23's `auto` under another
                // name and needs no entry point of its own.
                if k == Keyword::AutoType {
                    let range = self.bump_range();
                    auto_type = auto_type.or(Some(range));
                    consumed_any = true;
                    continue;
                }
                if matches!(
                    k,
                    Keyword::Typeof
                        | Keyword::TypeofUnqual
                        | Keyword::TypeofGnu
                        | Keyword::TypeofUnqualGnu
                ) {
                    let ty = self.parse_typeof_specifier(k)?;
                    if tag.is_some() || has_type {
                        self.error(ty.range, "two or more data types in declaration specifiers");
                    } else {
                        tag = Some(ty);
                    }
                    consumed_any = true;
                    continue;
                }
                // `_Atomic ( type-name )`, the type-specifier form (C11
                // 6.7.2.4). The qualifier form was taken by
                // `eat_type_qualifier` above, so only this one gets here.
                if k == Keyword::Atomic {
                    let range = self.bump_range();
                    self.require_keyword(k, range);
                    self.expect_punct(Punct::LParen, " after '_Atomic'")?;
                    let inner = self.parse_type_name()?;
                    self.expect_punct(Punct::RParen, " after the type name")?;
                    if tag.is_some() || has_type {
                        self.error(range, "two or more data types in declaration specifiers");
                    } else {
                        tag = Some(inner.ty);
                    }
                    quals = quals.merge(TypeQualifiers {
                        is_atomic: true,
                        ..TypeQualifiers::NONE
                    });
                    consumed_any = true;
                    continue;
                }
                // `_BitInt` is parsed so that the diagnostic is about it
                // rather than about the tokens that follow.
                if k == Keyword::BitInt {
                    let range = self.bump_range();
                    self.error(range, format!("'{}' is not supported yet", k.as_str()));
                    if self.at_punct(Punct::LParen) {
                        self.advance();
                        let _ = self.parse_conditional_expr()?;
                        self.expect_punct(Punct::RParen, " after the operand")?;
                    }
                    // Recover as `int`, so that the declaration does not also
                    // complain about a missing type specifier.
                    counts.int += 1;
                    consumed_any = true;
                    continue;
                }
                let counter = match k {
                    Keyword::Void => Some(&mut counts.void),
                    Keyword::Char => Some(&mut counts.char),
                    Keyword::Short => Some(&mut counts.short),
                    Keyword::Int => Some(&mut counts.int),
                    Keyword::Long => Some(&mut counts.long),
                    Keyword::Float => Some(&mut counts.float),
                    Keyword::Double => Some(&mut counts.double),
                    Keyword::Signed => Some(&mut counts.signed),
                    Keyword::Unsigned => Some(&mut counts.unsigned),
                    Keyword::Bool | Keyword::BoolName => Some(&mut counts.bool),
                    Keyword::Complex => Some(&mut counts.complex),
                    Keyword::Imaginary => Some(&mut counts.imaginary),
                    Keyword::Int128 => Some(&mut counts.int128),
                    _ => None,
                };
                if let Some(c) = counter {
                    *c += 1;
                    self.advance();
                    consumed_any = true;
                    continue;
                }
                if matches!(k, Keyword::Struct | Keyword::Union) {
                    let ty = self.parse_record_specifier()?;
                    if tag.is_some() || has_type {
                        self.error(ty.range, "two or more data types in declaration specifiers");
                    } else {
                        tag = Some(ty);
                    }
                    consumed_any = true;
                    continue;
                }
                if k == Keyword::Enum {
                    let ty = self.parse_enum_specifier()?;
                    if tag.is_some() || has_type {
                        self.error(ty.range, "two or more data types in declaration specifiers");
                    } else {
                        tag = Some(ty);
                    }
                    consumed_any = true;
                    continue;
                }
                break;
            }

            // The spelling of `_Noreturn` that every standard accepts, which
            // is what the bundled headers mark `exit` and `abort` with: they
            // are read by `c99!` blocks too, where `_Noreturn` itself would be
            // an error.
            if self.peek().ident() == Some(NORETURN_BUILTIN) {
                let range = self.bump_range();
                noreturn = noreturn.or(Some(range));
                consumed_any = true;
                continue;
            }

            // An extended floating type: `__float128`, `_Float128`, the rest
            // of TS 18661-3's set. None of them is a type specifier here, and
            // without this they would look like an identifier and turn one
            // refusal into "type specifier missing" plus whatever follows.
            if !has_type
                && let Some(name) = self.peek().ident()
                && let Some(what) = extended_float_type(name)
            {
                let range = self.cur_range();
                return Err(self.error_bail(
                    range,
                    format!(
                        "'{name}' is not supported: {what} has no Rust type to become, and \
                         mapping it onto 'double' would compute and pass the wrong values"
                    ),
                ));
            }

            // A `typedef` name is a type specifier only while we do not have
            // one yet; otherwise it is the declarator's identifier.
            let is_typedef_use = match self.peek().ident() {
                Some(name) => !has_type && self.is_typedef_name(name),
                None => false,
            };
            if is_typedef_use {
                let id = self.eat_ident().expect("checked above");
                typedef_name = Some(id);
                consumed_any = true;
                continue;
            }
            break;
        }

        if !consumed_any {
            let range = self.cur_range();
            // A name a newer revision would have made a keyword is almost
            // always that keyword rather than a declaration nobody finished
            // writing, and saying so is the difference between a fix and a
            // puzzle.
            if let Some(message) = self.newer_keyword_here() {
                return Err(self.error_bail(range, message));
            }
            // A declaration with no specifiers at all is an `int` one —
            // `f() { … }` and `(*fp)();` at file scope are the common
            // shapes — so the declarator is parsed and `build_base_type`
            // supplies the type, which is where C89's implicit `int` is
            // accepted and every later revision's "type specifier missing"
            // comes from. Anything that cannot begin a declarator is still
            // nothing at all.
            if !self.starts_declarator() {
                let found = self.describe_cur();
                return Err(
                    self.error_bail(range, format!("expected a declaration, found {found}"))
                );
            }
        }

        // With nothing consumed the specifiers are where the declarator
        // begins, which is where a diagnostic about the implicit `int` has to
        // point.
        let specs_range = if consumed_any {
            self.span_to_here(start)
        } else {
            self.cur_range()
        };
        // C23's `auto x = e;` and GNU's `__auto_type x = e;`: a declaration
        // with no type specifier at all takes its type from the initialiser.
        let no_type = !counts.any() && tag.is_none() && typedef_name.is_none();
        let inferred = no_type
            && (auto_type.is_some() || (self.standard >= Standard::C23 && auto_kw.is_some()));
        let base = if inferred {
            Type::new(TypeKind::Auto, quals, specs_range)
        } else {
            self.build_base_type(&counts, tag, typedef_name, quals, specs_range)
        };
        // `__attribute__((aligned(N)))` on a declaration says exactly what
        // `_Alignas(N)` says, so the two go through one path.
        if let Some(aligned) = attributes.aligned.clone() {
            alignas.push(aligned);
        }

        Ok(DeclSpecifiers {
            storage,
            thread_local,
            inline,
            noreturn,
            alignas,
            attrs: attributes,
            base,
            range: specs_range,
        })
    }

    /// `_Alignas ( constant-expression )` or `_Alignas ( type-name )`.
    fn parse_alignment_specifier(&mut self, keyword: Keyword) -> PResult<Alignment> {
        let start = self.cur_range();
        self.require_keyword(keyword, start);
        self.advance();
        let name = keyword.as_str();
        self.expect_punct(Punct::LParen, &format!(" after '{name}'"))?;
        let kind = if self.starts_declaration() {
            AlignmentKind::Type(Box::new(self.parse_type_name()?))
        } else {
            AlignmentKind::Expr(self.parse_conditional_expr()?)
        };
        self.expect_punct(Punct::RParen, &format!(" after the operand of '{name}'"))?;
        Ok(Alignment {
            kind,
            from_attribute: false,
            range: self.span_to_here(start),
        })
    }

    /// `typeof ( expression )` or `typeof ( type-name )`.
    ///
    /// `typeof_unqual` parses the same way and differs in one thing: it takes
    /// the *unqualified* type of the operand. Of the qualifiers, only
    /// `_Atomic` is part of a resolved type here — `const` on a pointee is not
    /// a top-level qualifier, and `volatile` and `restrict` say nothing to the
    /// generated Rust — so `_Atomic` is what the unqualified form drops.
    fn parse_typeof_specifier(&mut self, keyword: Keyword) -> PResult<Type> {
        let start = self.cur_range();
        self.require_keyword(keyword, start);
        self.advance();
        let name = keyword.as_str();
        self.expect_punct(Punct::LParen, &format!(" after '{name}'"))?;
        let operand = if self.starts_declaration() {
            TypeofOperand::Type(self.parse_type_name()?)
        } else {
            TypeofOperand::Expr(self.parse_expr()?)
        };
        self.expect_punct(Punct::RParen, &format!(" after the operand of '{name}'"))?;
        let range = self.span_to_here(start);
        let id = self.add_typeof(operand);
        let unqual = matches!(keyword, Keyword::TypeofUnqual | Keyword::TypeofUnqualGnu);
        Ok(Type::plain(TypeKind::Typeof { id, unqual }, range))
    }

    fn build_base_type(
        &mut self,
        counts: &SpecCounts,
        tag: Option<Type>,
        typedef_name: Option<Ident>,
        quals: TypeQualifiers,
        range: SourceRange,
    ) -> Type {
        if let Some(mut ty) = tag {
            if counts.any() || typedef_name.is_some() {
                self.error(range, "two or more data types in declaration specifiers");
            }
            ty.qualifiers = ty.qualifiers.merge(quals);
            return ty;
        }
        if let Some(name) = typedef_name {
            if counts.any() {
                self.error(range, "two or more data types in declaration specifiers");
            }
            return Type::new(TypeKind::Typedef(name), quals, range);
        }
        if !counts.any() {
            // C89 6.5.2: a declaration with no type specifier declares an
            // `int`. C99 removed the rule (N635) and GCC diagnoses it in every
            // later mode, GNU dialects included, so this is the standard
            // rather than the dialect talking.
            if !self.gating.implicit_int() {
                self.error(
                    range,
                    "type specifier missing; C99 does not support implicit 'int'",
                );
            }
            return Type::new(
                TypeKind::Int {
                    sign: Sign::Signed,
                    size: IntSize::Int,
                },
                quals,
                range,
            );
        }
        if counts.bool > 0 {
            self.require_standard(Standard::C99, "'_Bool'", range);
        }
        if counts.complex > 0 {
            self.require_standard(Standard::C99, "'_Complex'", range);
        }
        if counts.imaginary > 0 {
            self.require_standard(Standard::C99, "'_Imaginary'", range);
        }
        if counts.long > 1 {
            self.require_standard(Standard::C99, "'long long'", range);
        }
        // `_Complex int`, `_Complex char`, `__complex__ long` — GCC's complex
        // *integer* types, which are an extension of their own and which
        // nothing in the generated Rust could be. Saying so beats the
        // "cannot combine 'char' with other type specifiers" the chain below
        // would otherwise produce.
        if (counts.complex > 0 || counts.imaginary > 0)
            && counts.float == 0
            && counts.double == 0
            && counts.int
                + counts.char
                + counts.short
                + counts.long
                + counts.signed
                + counts.unsigned
                + counts.int128
                + counts.bool
                + counts.void
                > 0
        {
            self.error(
                range,
                "a complex integer type is a GNU extension that cinrs does not support; \
                 the complex types are 'float _Complex', 'double _Complex' and \
                 'long double _Complex'",
            );
            let kind = if counts.complex > 0 {
                TypeKind::Complex(FloatSize::Double)
            } else {
                TypeKind::Imaginary(FloatSize::Double)
            };
            return Type::new(kind, quals, range);
        }

        let sign = if counts.unsigned > 0 {
            Some(Sign::Unsigned)
        } else if counts.signed > 0 {
            Some(Sign::Signed)
        } else {
            None
        };
        if counts.signed > 0 && counts.unsigned > 0 {
            self.error(range, "cannot combine 'signed' with 'unsigned'");
        }

        let kind = if counts.void > 0 {
            if counts.void > 1 || counts.any_besides(&["void"]) {
                self.error(range, "cannot combine 'void' with other type specifiers");
            }
            TypeKind::Void
        } else if counts.bool > 0 {
            if counts.any_besides(&["_Bool"]) {
                self.error(range, "cannot combine '_Bool' with other type specifiers");
            }
            TypeKind::Bool
        } else if counts.char > 0 {
            if counts.any_besides(&["char", "signed", "unsigned"]) {
                self.error(range, "cannot combine 'char' with other type specifiers");
            }
            TypeKind::Char(sign)
        } else if counts.float > 0 || counts.double > 0 {
            let size = if counts.float > 0 {
                if counts.double > 0 {
                    self.error(range, "cannot combine 'float' with 'double'");
                }
                if counts.long > 0 {
                    self.error(range, "cannot combine 'long' with 'float'");
                }
                FloatSize::Float
            } else if counts.long > 0 {
                FloatSize::LongDouble
            } else {
                FloatSize::Double
            };
            if sign.is_some() {
                self.error(
                    range,
                    "cannot combine 'signed' or 'unsigned' with a floating type",
                );
            }
            if counts.complex > 0 {
                TypeKind::Complex(size)
            } else if counts.imaginary > 0 {
                TypeKind::Imaginary(size)
            } else {
                TypeKind::Float(size)
            }
        } else if counts.complex > 0 || counts.imaginary > 0 {
            // `__complex__ x;` on its own means `double _Complex` in GNU C,
            // and saying so gets the honest "complex types are not supported"
            // rather than a complaint about a missing type specifier.
            if counts.complex > 0 {
                TypeKind::Complex(FloatSize::Double)
            } else {
                TypeKind::Imaginary(FloatSize::Double)
            }
        } else if counts.int128 > 0 {
            // GCC's `__int128` combines with `signed` and `unsigned` and with
            // nothing else — not even `int`.
            if counts.int128 > 1 || counts.any_besides(&["__int128", "signed", "unsigned"]) {
                self.error(
                    range,
                    "cannot combine '__int128' with other type specifiers",
                );
            }
            TypeKind::Int {
                sign: sign.unwrap_or(Sign::Signed),
                size: IntSize::Int128,
            }
        } else {
            let size = if counts.short > 0 {
                if counts.long > 0 {
                    self.error(range, "cannot combine 'short' with 'long'");
                }
                IntSize::Short
            } else {
                match counts.long {
                    0 => IntSize::Int,
                    1 => IntSize::Long,
                    2 => IntSize::LongLong,
                    _ => {
                        self.error(range, "'long long long' is too long for cinrs");
                        IntSize::LongLong
                    }
                }
            };
            TypeKind::Int {
                sign: sign.unwrap_or(Sign::Signed),
                size,
            }
        };

        Type::new(kind, quals, range)
    }
}

impl SpecCounts {
    /// Whether any counter outside `allowed` is non-zero.
    fn any_besides(&self, allowed: &[&str]) -> bool {
        let all: [(&str, u32); 13] = [
            ("__int128", self.int128),
            ("void", self.void),
            ("char", self.char),
            ("short", self.short),
            ("int", self.int),
            ("long", self.long),
            ("float", self.float),
            ("double", self.double),
            ("signed", self.signed),
            ("unsigned", self.unsigned),
            ("_Bool", self.bool),
            ("_Complex", self.complex),
            ("_Imaginary", self.imaginary),
        ];
        all.iter()
            .any(|(name, count)| *count > 0 && !allowed.contains(name))
    }
}

// ---------------------------------------------------------------------------
// struct / union / enum
// ---------------------------------------------------------------------------

impl Parser<'_> {
    /// Stores a `struct`/`union` specifier and hands back its id.
    fn add_record(&mut self, spec: RecordSpec) -> RecordSpecId {
        let id = RecordSpecId(self.records.len() as u32);
        self.records.push(spec);
        id
    }

    /// Stores an `enum` specifier and hands back its id.
    fn add_enum(&mut self, spec: EnumSpec) -> EnumSpecId {
        let id = EnumSpecId(self.enums.len() as u32);
        self.enums.push(spec);
        id
    }

    /// Stores a `typeof` operand and hands back its id.
    fn add_typeof(&mut self, operand: TypeofOperand) -> TypeofId {
        let id = TypeofId(self.typeofs.len() as u32);
        self.typeofs.push(operand);
        id
    }

    /// A `struct`/`union` specifier, whose body may hold more of them.
    ///
    /// The nesting is counted: a member list is parsed by a recursive call, so
    /// a specifier nested past [`MAX_RECURSION_DEPTH`] is a diagnostic rather
    /// than a stack overflow. C23 5.2.5.2p1 asks for 63 levels.
    fn parse_record_specifier(&mut self) -> PResult<Type> {
        self.enter()?;
        let result = self.parse_record_specifier_inner();
        self.leave();
        result
    }

    fn parse_record_specifier_inner(&mut self) -> PResult<Type> {
        let start = self.cur_range();
        // What `#pragma pack` was asking for *here* is what applies to this
        // record; a pragma written after it changes nothing about it.
        let pack = self.packing.at(self.pos);
        let kind = match self.peek().keyword() {
            Some(Keyword::Struct) => RecordKind::Struct,
            Some(Keyword::Union) => RecordKind::Union,
            _ => unreachable!("caller checked the keyword"),
        };
        self.advance();
        let mut attrs = self.parse_attributes()?;
        let name = self.eat_ident();
        let mut asserts = Vec::new();
        let fields = if self.at_punct(Punct::LBrace) {
            let (fields, found) = self.parse_struct_body()?;
            asserts = found;
            Some(fields)
        } else {
            if name.is_none() {
                let range = self.cur_range();
                let found = self.describe_cur();
                return Err(self.error_bail(
                    range,
                    format!(
                        "expected identifier or '{{' after '{}', found {found}",
                        kind.as_str()
                    ),
                ));
            }
            None
        };
        // GCC lets `__attribute__((packed))` come after the member list too,
        // which is where most code writes it.
        if self.at_attributes() {
            let after = self.parse_attributes()?;
            attrs.merge(after);
        }
        let range = self.span_to_here(start);
        let id = self.add_record(RecordSpec {
            kind,
            name,
            fields,
            asserts,
            attrs,
            pack,
            range,
        });
        Ok(Type::plain(TypeKind::Record(id), range))
    }

    /// The member list of a `struct` or `union`, and the `_Static_assert`
    /// declarations written among the members.
    fn parse_struct_body(&mut self) -> PResult<(Vec<FieldDecl>, Vec<StaticAssert>)> {
        self.expect_punct(Punct::LBrace, " to open a member list")?;
        let mut fields = Vec::new();
        let mut asserts = Vec::new();
        while !self.at_punct(Punct::RBrace) && !self.at_eof() {
            let before = self.pos;
            // A stray `;` is harmless; skip it.
            if self.eat_punct(Punct::Semi).is_some() {
                continue;
            }
            if self.at_static_assert() {
                asserts.push(self.parse_static_assert()?);
                continue;
            }
            let start = self.cur_range();
            while self.eat_keyword(Keyword::Extension).is_some() {
                self.in_extension = true;
            }
            let leading = self.parse_attributes()?;
            let mut specs = self.parse_decl_specifiers(false)?;
            specs.attrs.merge(leading);

            if self.at_punct(Punct::Semi) {
                // An anonymous struct/union member: C11 6.7.2.1p13.
                let range = self.span_to_here(start);
                self.require_standard(Standard::C11, "an anonymous struct or union member", range);
                fields.push(FieldDecl {
                    ty: specs.base.clone(),
                    attrs: specs.attrs.clone(),
                    specifiers: specs,
                    name: None,
                    bit_width: None,
                    range,
                });
                self.expect_punct(Punct::Semi, " after member declaration")?;
                continue;
            }

            loop {
                let (name, ty, dstart, mut attrs) = if self.at_punct(Punct::Colon) {
                    (
                        None,
                        specs.base.clone(),
                        self.cur_range(),
                        Attributes::default(),
                    )
                } else {
                    let mut d = self.parse_declarator(specs.base.clone(), true)?;
                    self.parse_declarator_tail(&mut d)?;
                    (d.name, d.ty, d.range, d.attrs)
                };
                let bit_width = if self.eat_punct(Punct::Colon).is_some() {
                    Some(self.parse_conditional_expr()?)
                } else {
                    None
                };
                // A member's attributes may follow its width.
                if self.at_attributes() {
                    let after = self.parse_attributes()?;
                    attrs.merge(after);
                }
                attrs.merge(specs.attrs.clone());
                let range = self.span_to_here(dstart);
                fields.push(FieldDecl {
                    specifiers: specs.clone(),
                    name,
                    ty,
                    bit_width,
                    attrs,
                    range,
                });
                if self.eat_punct(Punct::Comma).is_none() {
                    break;
                }
            }
            self.expect_punct(Punct::Semi, " after member declaration")?;
            if self.pos == before {
                self.advance();
            }
        }
        self.expect_punct(Punct::RBrace, " to close a member list")?;
        Ok((fields, asserts))
    }

    fn parse_enum_specifier(&mut self) -> PResult<Type> {
        let start = self.cur_range();
        self.advance(); // `enum`
        // An attribute specifier sequence is allowed here and ignored.
        let _ = self.parse_attributes()?;
        let name = self.eat_ident();
        // C23's fixed underlying type: `enum E : unsigned char { … }`.
        //
        // The `:` only introduces one when a type follows it. Among the members
        // of a record, `enum E : 3;` is an unnamed bit-field of the
        // enumeration's type — which C has had for far longer — and the width
        // is an expression, never a type.
        let underlying = if self.at_punct(Punct::Colon) && self.starts_decl_specifier(1) {
            let colon = self.bump_range();
            self.require_standard(Standard::C23, "an enum with a fixed underlying type", colon);
            let specs = self.parse_decl_specifiers(false)?;
            Some(specs.base)
        } else {
            None
        };
        let enumerators = if self.at_punct(Punct::LBrace) {
            self.advance();
            let mut list = Vec::new();
            while !self.at_punct(Punct::RBrace) && !self.at_eof() {
                let ename = self.expect_ident(" in enumerator list")?;
                self.declare(&ename.name.clone(), SymKind::Ordinary);
                // An attribute specifier sequence is allowed here and ignored.
                let _ = self.parse_attributes()?;
                let value = if self.eat_punct(Punct::Assign).is_some() {
                    Some(self.parse_conditional_expr()?)
                } else {
                    None
                };
                let range = self.span_to_here(ename.range);
                list.push(Enumerator {
                    name: ename,
                    value,
                    range,
                });
                let Some(comma) = self.eat_punct(Punct::Comma) else {
                    break;
                };
                if self.at_punct(Punct::RBrace) {
                    self.require_standard(
                        Standard::C99,
                        "a trailing comma in an enumerator list",
                        comma,
                    );
                }
            }
            self.expect_punct(Punct::RBrace, " to close an enumerator list")?;
            Some(list)
        } else {
            if name.is_none() {
                let range = self.cur_range();
                let found = self.describe_cur();
                return Err(self.error_bail(
                    range,
                    format!("expected identifier or '{{' after 'enum', found {found}"),
                ));
            }
            None
        };
        let range = self.span_to_here(start);
        let id = self.add_enum(EnumSpec {
            name,
            enumerators,
            underlying,
            range,
        });
        Ok(Type::plain(TypeKind::Enum(id), range))
    }
}

// ---------------------------------------------------------------------------
// declarators
// ---------------------------------------------------------------------------

/// The outcome of parsing one declarator.
#[derive(Clone, Debug)]
pub struct DeclaratorResult {
    /// The declared name, absent for an abstract declarator.
    pub name: Option<Ident>,
    /// The type the declarator builds from the base type.
    pub ty: Type,
    /// What `__attribute__((…))` on the declarator asked for.
    pub attrs: Attributes,
    /// The symbol `__asm__("name")` renamed it to.
    pub asm_label: Option<Spanned<String>>,
    /// Where the declarator was written.
    pub range: SourceRange,
}

impl Parser<'_> {
    /// Parses a declarator, applying it to `base`.
    ///
    /// With `allow_abstract` the identifier may be omitted, which is what
    /// parameter declarations and type names need.
    fn parse_declarator(&mut self, base: Type, allow_abstract: bool) -> PResult<DeclaratorResult> {
        self.enter()?;
        let result = self.parse_declarator_inner(base, allow_abstract);
        self.leave();
        result
    }

    fn parse_declarator_inner(
        &mut self,
        base: Type,
        allow_abstract: bool,
    ) -> PResult<DeclaratorResult> {
        let start = self.cur_range();
        // GNU allows an attribute at the head of a declarator, which is where
        // a calling convention is usually written.
        let leading = self.parse_attributes()?;
        let mut ty = base;

        // `* qual* ` repeated: the leftmost `*` becomes the innermost pointer,
        // so `int * const * p` is "pointer to const pointer to int".
        while self.at_punct(Punct::Star) {
            let star = self.bump_range();
            let mut quals = self.parse_type_qualifiers();
            // GNU allows `int * __attribute__((x)) p;` and mixes the two.
            while self.at_attributes() {
                let _ = self.parse_attributes()?;
                quals = quals.merge(self.parse_type_qualifiers());
            }
            let range = self.span_to_here(star);
            ty = Type::new(TypeKind::Pointer(Box::new(ty)), quals, range);
        }

        if self.at_punct(Punct::LParen) && self.is_grouping_paren() {
            let save = self.pos;
            let balanced = self.skip_balanced_parens();
            if !balanced {
                let range = self.cur_range();
                return Err(self.error_bail(range, "unbalanced '(' in declarator"));
            }
            let rparen = self.pos - 1;
            ty = self.parse_type_suffix(ty)?;
            let after = self.pos;
            self.pos = save + 1;
            let inner = self.parse_declarator(ty, allow_abstract)?;
            if self.pos != rparen {
                let range = self.cur_range();
                let found = self.describe_cur();
                return Err(self.error_bail(
                    range,
                    format!("expected ')' after declarator, found {found}"),
                ));
            }
            self.pos = after;
            self.last_range = self.tokens[after - 1].range;
            let mut attrs = inner.attrs;
            attrs.merge(leading);
            return Ok(DeclaratorResult {
                name: inner.name,
                ty: inner.ty,
                attrs,
                asm_label: inner.asm_label,
                range: self.span_to_here(start),
            });
        }

        let name = match self.eat_ident() {
            Some(id) => Some(id),
            None if allow_abstract => None,
            None => {
                let range = self.cur_range();
                let found = self.describe_cur();
                return Err(self.error_bail(
                    range,
                    format!("expected identifier in declarator, found {found}"),
                ));
            }
        };
        // C23 allows an attribute specifier sequence after the declared name
        // (`int x [[deprecated]];`), and so does GNU.
        let mut attrs = self.parse_attributes()?;
        attrs.merge(leading);
        let ty = self.parse_type_suffix(ty)?;
        Ok(DeclaratorResult {
            name,
            ty,
            attrs,
            asm_label: None,
            range: self.span_to_here(start),
        })
    }

    /// At a `(` that begins a direct-declarator: does it group a nested
    /// declarator, or is it a parameter list?
    ///
    /// An attribute may stand at the head of either — `int (__attribute__((x))
    /// *)(void)` groups a declarator and `int (__attribute__((x)) int)` is a
    /// parameter list — so the question is asked of what follows it.
    fn is_grouping_paren(&self) -> bool {
        let after = self.after_attributes(1);
        !self.nth(after).is_punct(Punct::RParen) && !self.starts_decl_specifier(after)
    }

    /// The offset of the first token after any attribute specifiers at `n`.
    ///
    /// Used for lookahead only, so it never reports: an unbalanced clause
    /// stops at the end of the input and the caller's own parse reports it.
    fn after_attributes(&self, mut n: usize) -> usize {
        loop {
            let brackets =
                self.nth(n).is_punct(Punct::LBracket) && self.nth(n + 1).is_punct(Punct::LBracket);
            if !self.nth(n).is_keyword(Keyword::Attribute) && !brackets {
                return n;
            }
            let (open, close) = if brackets {
                (Punct::LBracket, Punct::RBracket)
            } else {
                (Punct::LParen, Punct::RParen)
            };
            let mut i = if brackets { n } else { n + 1 };
            let mut depth = 0i32;
            while !self.nth(i).is_eof() {
                if self.nth(i).is_punct(open) {
                    depth += 1;
                } else if self.nth(i).is_punct(close) {
                    depth -= 1;
                    if depth == 0 {
                        i += 1;
                        break;
                    }
                }
                i += 1;
            }
            if i <= n {
                return n;
            }
            n = i;
        }
    }

    /// From the current `(`, skips to just past its matching `)`.
    fn skip_balanced_parens(&mut self) -> bool {
        let mut depth = 0i32;
        while !self.at_eof() {
            if self.at_punct(Punct::LParen) {
                depth += 1;
            } else if self.at_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    self.advance();
                    return true;
                }
            }
            self.advance();
        }
        false
    }

    /// Parses the `[...]` and `(...)` suffixes of a direct-declarator.
    ///
    /// The remaining suffixes are resolved *before* wrapping, so `int a[3][4]`
    /// becomes "array of 3 array of 4 int" rather than the other way round.
    fn parse_type_suffix(&mut self, ty: Type) -> PResult<Type> {
        if let Some(lb) = self.eat_punct(Punct::LBracket) {
            let mut is_static = false;
            let mut quals = TypeQualifiers::NONE;
            loop {
                if self.at_keyword(Keyword::Static) {
                    self.advance();
                    is_static = true;
                    continue;
                }
                match self.eat_type_qualifier() {
                    Some(q) => quals = quals.merge(q),
                    None => break,
                }
            }
            if is_static {
                self.require_standard(
                    Standard::C99,
                    "'static' in an array parameter declarator",
                    lb,
                );
            }
            let size = if self.at_punct(Punct::RBracket) {
                ArraySize::Unspecified
            } else if self.at_punct(Punct::Star) && self.nth(1).is_punct(Punct::RBracket) {
                let star = self.bump_range();
                self.require_standard(Standard::C99, "'[*]'", star);
                ArraySize::Star
            } else {
                ArraySize::Expr(Box::new(self.parse_assignment_expr()?))
            };
            let rb = self.expect_punct(Punct::RBracket, " after array bound")?;
            let elem = self.parse_type_suffix(ty)?;
            return Ok(Type::plain(
                TypeKind::Array {
                    elem: Box::new(elem),
                    size,
                    qualifiers: quals,
                    is_static,
                },
                lb.join(rb),
            ));
        }

        if let Some(lp) = self.eat_punct(Punct::LParen) {
            let list = self.parse_param_list()?;
            let rp = self.expect_punct(Punct::RParen, " after parameter list")?;
            let ret = self.parse_type_suffix(ty)?;
            return Ok(Type::plain(
                TypeKind::Function(Box::new(FunctionType {
                    ret,
                    params: list.params,
                    variadic: list.ellipsis.is_some(),
                    ellipsis: list.ellipsis,
                    has_prototype: list.has_prototype,
                    kr_names: list.kr_names,
                    old_style: false,
                })),
                lp.join(rp),
            ));
        }

        Ok(ty)
    }

    fn parse_param_list(&mut self) -> PResult<ParamList> {
        if self.at_punct(Punct::RParen) {
            return Ok(ParamList::default());
        }
        // `(void)` — an explicitly empty prototype.
        if self.at_keyword(Keyword::Void) && self.nth(1).is_punct(Punct::RParen) {
            self.advance();
            return Ok(ParamList {
                has_prototype: true,
                ..ParamList::default()
            });
        }
        // An old-style identifier list: `int f(a, b)`.
        let kr = match self.peek().ident() {
            Some(name) => !self.is_typedef_name(name),
            None => false,
        };
        if kr {
            let mut names = Vec::new();
            loop {
                names.push(self.expect_ident(" in parameter list")?);
                if self.eat_punct(Punct::Comma).is_none() {
                    break;
                }
            }
            return Ok(ParamList {
                kr_names: names,
                ..ParamList::default()
            });
        }

        // Parameter names are visible to later parameters' declarators, so
        // they get their own scope.
        self.push_scope();
        let result = self.parse_prototype_params();
        self.pop_scope();
        result
    }

    fn parse_prototype_params(&mut self) -> PResult<ParamList> {
        let mut params = Vec::new();
        let mut ellipsis = None;
        loop {
            if self.at_punct(Punct::Ellipsis) {
                ellipsis = Some(self.bump_range());
                break;
            }
            let start = self.cur_range();
            let specs = self.parse_decl_specifiers(true)?;
            let declarator = self.parse_declarator(specs.base.clone(), true)?;
            if let Some(name) = &declarator.name {
                self.declare(&name.name.clone(), SymKind::Ordinary);
            }
            let range = self.span_to_here(start);
            // A parameter is not an object whose scope a `cleanup` could hang
            // on: it is the caller's value, and GCC drops the attribute with
            // "'cleanup' attribute ignored". Dropping it silently would change
            // what the program does.
            for cleanup in [&declarator.attrs.cleanup, &specs.attrs.cleanup]
                .into_iter()
                .flatten()
            {
                self.error(
                    cleanup.range,
                    "'cleanup' attribute ignored on a parameter: it calls the function when \
                     the object goes out of scope, and only an object with automatic storage \
                     duration ever does",
                );
            }
            params.push(ParamDecl {
                specifiers: specs,
                name: declarator.name,
                ty: declarator.ty,
                range,
            });
            if self.eat_punct(Punct::Comma).is_none() {
                break;
            }
        }
        Ok(ParamList {
            params,
            ellipsis,
            has_prototype: true,
            kr_names: Vec::new(),
        })
    }

    fn parse_type_name(&mut self) -> PResult<TypeName> {
        let start = self.cur_range();
        let specs = self.parse_decl_specifiers(false)?;
        let declarator = self.parse_declarator(specs.base.clone(), true)?;
        if let Some(name) = &declarator.name {
            let range = name.range;
            self.error(range, "a type name must not declare an identifier");
        }
        Ok(TypeName {
            specifiers: specs,
            ty: declarator.ty,
            range: self.span_to_here(start),
        })
    }
}

/// The pieces of a parsed parameter list.
#[derive(Default)]
struct ParamList {
    params: Vec<ParamDecl>,
    /// Where `...` was written, if it was.
    ellipsis: Option<SourceRange>,
    has_prototype: bool,
    kr_names: Vec<Ident>,
}

// ---------------------------------------------------------------------------
// initialisers
// ---------------------------------------------------------------------------

impl Parser<'_> {
    fn parse_initializer(&mut self) -> PResult<Initializer> {
        self.enter()?;
        let result = self.parse_initializer_inner();
        self.leave();
        result
    }

    fn parse_initializer_inner(&mut self) -> PResult<Initializer> {
        if self.at_punct(Punct::LBrace) {
            let start = self.cur_range();
            let items = self.parse_initializer_list()?;
            return Ok(Initializer {
                kind: InitializerKind::List(items),
                range: self.span_to_here(start),
            });
        }
        let expr = self.parse_assignment_expr()?;
        Ok(Initializer {
            range: expr.range,
            kind: InitializerKind::Expr(expr),
        })
    }

    fn parse_initializer_list(&mut self) -> PResult<Vec<InitItem>> {
        let brace = self.expect_punct(Punct::LBrace, " to open an initializer list")?;
        if self.at_punct(Punct::RBrace) {
            // `= {}` zero-initialises anything; before C23 an initializer list
            // had to hold at least one initializer.
            let range = brace.join(self.cur_range());
            self.require_standard(Standard::C23, "an empty initializer", range);
        }
        let mut items = Vec::new();
        while !self.at_punct(Punct::RBrace) && !self.at_eof() {
            let start = self.cur_range();
            let mut designators = Vec::new();
            // The obsolete `name:` designator GNU still accepts, which is what
            // pre-C99 code writes for `.name =`.
            let mut old_style = false;
            if self.peek().ident().is_some() && self.nth(1).is_punct(Punct::Colon) {
                let field = self.eat_ident().expect("checked above");
                self.advance();
                designators.push(Designator::Field(field));
                old_style = true;
            }
            loop {
                if old_style {
                    break;
                }
                if self.eat_punct(Punct::Dot).is_some() {
                    let field = self.expect_ident(" after '.' in designator")?;
                    designators.push(Designator::Field(field));
                } else if self.eat_punct(Punct::LBracket).is_some() {
                    let index = self.parse_conditional_expr()?;
                    // GNU's range designator, `[low ... high] = v`.
                    if self.eat_punct(Punct::Ellipsis).is_some() {
                        let high = self.parse_conditional_expr()?;
                        self.expect_punct(Punct::RBracket, " after array designator")?;
                        designators.push(Designator::Range(index, high));
                    } else {
                        self.expect_punct(Punct::RBracket, " after array designator")?;
                        designators.push(Designator::Index(index));
                    }
                } else {
                    break;
                }
            }
            if !designators.is_empty() {
                // C99's own form and GCC's older `name:` one alike: before
                // C99 an initializer list was positional and nothing else.
                let at = self.span_to_here(start);
                self.require_standard(Standard::C99, "a designated initializer", at);
            }
            if !designators.is_empty() && !old_style {
                self.expect_punct(Punct::Assign, " after designator")?;
            }
            let init = self.parse_initializer()?;
            items.push(InitItem {
                designators,
                init,
                range: self.span_to_here(start),
            });
            if self.eat_punct(Punct::Comma).is_none() {
                break;
            }
        }
        self.expect_punct(Punct::RBrace, " to close an initializer list")?;
        Ok(items)
    }
}

// ---------------------------------------------------------------------------
// statements
// ---------------------------------------------------------------------------

impl Parser<'_> {
    fn parse_compound_stmt(&mut self) -> PResult<Block> {
        let start = self.expect_punct(Punct::LBrace, " to open a block")?;
        self.push_scope();
        // GNU's `__label__ a, b;` declares labels local to the block. Every
        // label already has function scope here and no two may share a name,
        // so the declaration is accepted and changes nothing.
        let mut local_labels = Vec::new();
        while self.at_keyword(Keyword::Label) {
            self.advance();
            loop {
                match self.expect_ident(" in a '__label__' declaration") {
                    Ok(name) => local_labels.push(name),
                    Err(bail) => {
                        self.pop_scope();
                        return Err(bail);
                    }
                }
                if self.eat_punct(Punct::Comma).is_none() {
                    break;
                }
            }
            if let Err(bail) = self.expect_punct(Punct::Semi, " after '__label__'") {
                self.pop_scope();
                return Err(bail);
            }
        }
        let mut items = Vec::new();
        // C89 6.6.2: a block is declarations *then* statements. C99 mixed the
        // two (N740), and the gate is here rather than in sema because it is
        // the block's shape that says which one this is.
        let mut saw_statement = false;
        while !self.at_punct(Punct::RBrace) && !self.at_eof() {
            let before = self.pos;
            if saw_statement && self.starts_declaration() {
                let at = self.cur_range();
                self.require_standard(Standard::C99, "a declaration after a statement", at);
            }
            let item = if self.at_static_assert() {
                self.parse_static_assert().map(BlockItem::StaticAssert)
            } else {
                // An attribute sequence here belongs either to a declaration
                // or to a statement, and only what follows says which; taking
                // it first is what lets `[[fallthrough]];` be a statement.
                match self.parse_attributes() {
                    Ok(attrs) => {
                        if self.starts_declaration() {
                            self.parse_block_declaration().map(|mut item| {
                                // The sequence belongs to the declaration —
                                // or to the GNU nested function definition —
                                // that follows it, exactly as one written
                                // among the specifiers does, which is where
                                // `parse_declaration_head` finds the same
                                // attributes at file scope.
                                let specifiers = match &mut item {
                                    BlockItem::Decl(decl) => Some(&mut decl.specifiers),
                                    BlockItem::NestedFunction(def) => Some(&mut def.specifiers),
                                    _ => None,
                                };
                                if let Some(specifiers) = specifiers {
                                    specifiers.noreturn = specifiers.noreturn.or(attrs.noreturn);
                                    specifiers.attrs.merge(attrs);
                                }
                                item
                            })
                        } else {
                            self.parse_stmt().map(BlockItem::Stmt)
                        }
                    }
                    Err(bail) => Err(bail),
                }
            };
            match item {
                Ok(item) => {
                    saw_statement |= matches!(item, BlockItem::Stmt(_));
                    items.push(item);
                }
                Err(bail) => {
                    self.pop_scope();
                    return Err(bail);
                }
            }
            if self.pos == before {
                self.advance();
            }
        }
        self.pop_scope();
        let end = self.expect_punct(Punct::RBrace, " to close a block")?;
        Ok(Block {
            items,
            local_labels,
            range: start.join(end),
        })
    }

    fn parse_stmt(&mut self) -> PResult<Stmt> {
        self.enter()?;
        let result = self.parse_stmt_inner();
        self.leave();
        result
    }

    /// Parses a statement, taking the labels in front of it iteratively.
    ///
    /// `case 0: case 1: … case 1022: break;` is one statement under 1023
    /// labels, and C23 5.2.5.2p1 asks for exactly that many. Recursing per
    /// label would spend a stack frame — and a level of the recursion guard —
    /// on each of them, so the run is collected into a list and folded into
    /// the tree afterwards. What the tree looks like does not change.
    fn parse_stmt_inner(&mut self) -> PResult<Stmt> {
        let mut labels: Vec<(PendingLabel, SourceRange)> = Vec::new();
        let start = loop {
            let start = self.cur_range();
            // A statement may carry attributes of its own: `[[fallthrough]];`,
            // `__attribute__((fallthrough));`, `[[likely]] if (…)`. They are
            // consumed and dropped — a `switch` group falls through either way.
            let _ = self.parse_attributes()?;
            // `__extension__ stmt` asks for the pedantic warnings to be held
            // back; there are none.
            while self.eat_keyword(Keyword::Extension).is_some() {}

            // `label:`
            let label = if self.peek().ident().is_some() && self.nth(1).is_punct(Punct::Colon) {
                let label = self.eat_ident().expect("checked above");
                self.advance(); // `:`
                PendingLabel::Ident { label }
            } else if self.at_keyword(Keyword::Case) {
                self.advance();
                let value = self.parse_conditional_expr()?;
                // GNU's `case low ... high:`, which is one label for every
                // value in the range.
                let upper = if self.eat_punct(Punct::Ellipsis).is_some() {
                    Some(self.parse_conditional_expr()?)
                } else {
                    None
                };
                self.expect_punct(Punct::Colon, " after 'case' label")?;
                PendingLabel::Case { value, upper }
            } else if self.at_keyword(Keyword::Default) {
                self.advance();
                self.expect_punct(Punct::Colon, " after 'default' label")?;
                PendingLabel::Default
            } else {
                break start;
            };
            labels.push((label, start));
            if labels.len() > MAX_LABEL_CHAIN {
                let range = self.cur_range();
                return Err(self.error_bail(
                    range,
                    format!("more than {MAX_LABEL_CHAIN} labels on one statement"),
                ));
            }
        };

        if !labels.is_empty() {
            return self.finish_labeled_stmt(labels);
        }
        self.parse_unlabeled_stmt(start)
    }

    /// A statement with the labels — and the attributes — already taken.
    ///
    /// `start` is where the statement began, attributes included, which is
    /// where its range starts.
    fn parse_unlabeled_stmt(&mut self, start: SourceRange) -> PResult<Stmt> {
        // Inline assembly, which has no honest translation. Recognising the
        // whole statement is what turns it into one clear diagnostic.
        if self.at_keyword(Keyword::Asm) {
            return self.parse_asm_stmt();
        }

        if self.at_punct(Punct::LBrace) {
            let block = self.parse_compound_stmt()?;
            return Ok(Stmt {
                range: block.range,
                kind: StmtKind::Compound(block),
            });
        }

        if let Some(k) = self.peek().keyword() {
            match k {
                Keyword::If => return self.parse_if_stmt(),
                Keyword::Switch => {
                    self.advance();
                    self.expect_punct(Punct::LParen, " after 'switch'")?;
                    let cond = self.parse_expr()?;
                    self.expect_punct(Punct::RParen, " after switch condition")?;
                    let body = self.parse_stmt()?;
                    return Ok(Stmt {
                        kind: StmtKind::Switch {
                            cond,
                            body: Box::new(body),
                        },
                        range: self.span_to_here(start),
                    });
                }
                Keyword::While => {
                    self.advance();
                    self.expect_punct(Punct::LParen, " after 'while'")?;
                    let cond = self.parse_expr()?;
                    self.expect_punct(Punct::RParen, " after loop condition")?;
                    let body = self.parse_stmt()?;
                    return Ok(Stmt {
                        kind: StmtKind::While {
                            cond,
                            body: Box::new(body),
                        },
                        range: self.span_to_here(start),
                    });
                }
                Keyword::Do => {
                    self.advance();
                    let body = self.parse_stmt()?;
                    self.expect_keyword(Keyword::While, " after 'do' body")?;
                    self.expect_punct(Punct::LParen, " after 'while'")?;
                    let cond = self.parse_expr()?;
                    self.expect_punct(Punct::RParen, " after loop condition")?;
                    self.expect_punct(Punct::Semi, " after 'do' statement")?;
                    return Ok(Stmt {
                        kind: StmtKind::DoWhile {
                            body: Box::new(body),
                            cond,
                        },
                        range: self.span_to_here(start),
                    });
                }
                Keyword::For => return self.parse_for_stmt(),
                Keyword::Goto => {
                    self.advance();
                    // GNU's computed `goto *expr;`, whose operand is a label
                    // address rather than a label name.
                    if self.eat_punct(Punct::Star).is_some() {
                        let target = self.parse_expr()?;
                        self.expect_punct(Punct::Semi, " after 'goto' statement")?;
                        return Ok(Stmt {
                            kind: StmtKind::GotoPtr(target),
                            range: self.span_to_here(start),
                        });
                    }
                    let label = self.expect_ident(" after 'goto'")?;
                    self.expect_punct(Punct::Semi, " after 'goto' statement")?;
                    return Ok(Stmt {
                        kind: StmtKind::Goto(label),
                        range: self.span_to_here(start),
                    });
                }
                Keyword::Continue => {
                    self.advance();
                    self.expect_punct(Punct::Semi, " after 'continue'")?;
                    return Ok(Stmt {
                        kind: StmtKind::Continue,
                        range: self.span_to_here(start),
                    });
                }
                Keyword::Break => {
                    self.advance();
                    self.expect_punct(Punct::Semi, " after 'break'")?;
                    return Ok(Stmt {
                        kind: StmtKind::Break,
                        range: self.span_to_here(start),
                    });
                }
                Keyword::Return => {
                    self.advance();
                    let value = if self.at_punct(Punct::Semi) {
                        None
                    } else {
                        Some(self.parse_expr()?)
                    };
                    self.expect_punct(Punct::Semi, " after 'return' statement")?;
                    return Ok(Stmt {
                        kind: StmtKind::Return(value),
                        range: self.span_to_here(start),
                    });
                }
                _ => {}
            }
        }

        if let Some(semi) = self.eat_punct(Punct::Semi) {
            return Ok(Stmt {
                kind: StmtKind::Expr(None),
                range: semi,
            });
        }

        let expr = self.parse_expr()?;
        self.expect_punct(Punct::Semi, " after expression")?;
        Ok(Stmt {
            kind: StmtKind::Expr(Some(expr)),
            range: self.span_to_here(start),
        })
    }

    /// Parses what a run of labels labels, and folds the run into the tree.
    ///
    /// The list is never empty; see [`Parser::parse_stmt_inner`].
    fn finish_labeled_stmt(&mut self, labels: Vec<(PendingLabel, SourceRange)>) -> PResult<Stmt> {
        // C23 lets a label stand before a declaration and at the very end of a
        // compound statement; before that it had to label a statement. Either
        // way the label itself labels nothing, so it takes a null statement and
        // whatever follows is parsed on its own.
        // N2508 is about *every* label, `case` and `default` included: `switch
        // (x) { case 1: }` and `case 1: _Static_assert(1, "");` are both what
        // it made legal, and `C23/n2508.c` writes both.
        let colon = self.last_range;
        let (_, label_start) = labels.last().expect("a label chain is never empty");
        let what = if self.at_punct(Punct::RBrace) {
            Some("a label at the end of a compound statement")
        } else if self.starts_declaration() || self.at_static_assert() {
            Some("a label before a declaration")
        } else {
            None
        };
        let trailing = what.map(|what| (what, label_start.join(colon), colon));
        let mut stmt = match trailing {
            Some((what, at, colon)) => {
                self.require_standard(Standard::C23, what, at);
                Stmt {
                    kind: StmtKind::Expr(None),
                    range: colon,
                }
            }
            None => {
                let start = self.cur_range();
                self.parse_unlabeled_stmt(start)?
            }
        };
        let end = self.last_range;
        for (label, start) in labels.into_iter().rev() {
            let body = Box::new(stmt);
            let kind = match label {
                PendingLabel::Ident { label, .. } => StmtKind::Labeled { label, body },
                PendingLabel::Case { value, upper } => StmtKind::Case { value, upper, body },
                PendingLabel::Default => StmtKind::Default { body },
            };
            stmt = Stmt {
                kind,
                range: start.join(end),
            };
        }
        Ok(stmt)
    }

    /// `asm [qualifiers] ( … ) ;` — an inline assembly statement.
    ///
    /// Rust has `core::arch::asm!`, but its operand constraints are a language
    /// of their own and mapping GCC's onto them is a project rather than a
    /// feature; half a translation of assembly would be worse than none. The
    /// whole statement is consumed so that the diagnostic is about the `asm`
    /// rather than about the tokens inside it.
    fn parse_asm_stmt(&mut self) -> PResult<Stmt> {
        let start = self.cur_range();
        self.advance();
        // `volatile`, `inline` and `goto` may qualify it.
        while matches!(
            self.peek().keyword(),
            Some(
                Keyword::Volatile
                    | Keyword::Const
                    | Keyword::Inline
                    | Keyword::InlineGnu
                    | Keyword::Goto
            )
        ) {
            self.advance();
        }
        if self.at_punct(Punct::LParen) {
            self.skip_attribute_args()?;
        }
        self.eat_punct(Punct::Semi);
        let range = self.span_to_here(start);
        self.error(range, "inline assembly is not supported");
        Ok(Stmt {
            kind: StmtKind::Error,
            range,
        })
    }

    fn parse_if_stmt(&mut self) -> PResult<Stmt> {
        let start = self.cur_range();
        self.advance(); // `if`
        self.expect_punct(Punct::LParen, " after 'if'")?;
        let cond = self.parse_expr()?;
        self.expect_punct(Punct::RParen, " after if condition")?;
        let then_branch = Box::new(self.parse_stmt()?);
        let else_branch = if self.eat_keyword(Keyword::Else).is_some() {
            Some(Box::new(self.parse_stmt()?))
        } else {
            None
        };
        Ok(Stmt {
            kind: StmtKind::If {
                cond,
                then_branch,
                else_branch,
            },
            range: self.span_to_here(start),
        })
    }

    fn parse_for_stmt(&mut self) -> PResult<Stmt> {
        let start = self.cur_range();
        self.advance(); // `for`
        self.expect_punct(Punct::LParen, " after 'for'")?;
        // C99 allows a declaration here; it scopes to the loop.
        self.push_scope();
        let result = (|parser: &mut Self| {
            let init = if parser.at_punct(Punct::Semi) {
                parser.advance();
                ForInit::None
            } else if parser.at_static_assert() {
                // A static assertion is a declaration and takes its own `;`
                // with it; see [`ForInit::StaticAssert`].
                ForInit::StaticAssert(parser.parse_static_assert()?)
            } else if parser.starts_declaration() {
                let at = parser.cur_range();
                parser.require_standard(Standard::C99, "a declaration in a 'for' clause", at);
                ForInit::Decl(Box::new(parser.parse_declaration()?))
            } else {
                let expr = parser.parse_expr()?;
                parser.expect_punct(Punct::Semi, " after 'for' initializer")?;
                ForInit::Expr(expr)
            };
            let cond = if parser.at_punct(Punct::Semi) {
                None
            } else {
                Some(parser.parse_expr()?)
            };
            parser.expect_punct(Punct::Semi, " after 'for' condition")?;
            let step = if parser.at_punct(Punct::RParen) {
                None
            } else {
                Some(parser.parse_expr()?)
            };
            parser.expect_punct(Punct::RParen, " after 'for' clauses")?;
            let body = parser.parse_stmt()?;
            Ok(StmtKind::For {
                init,
                cond,
                step,
                body: Box::new(body),
            })
        })(self);
        self.pop_scope();
        Ok(Stmt {
            kind: result?,
            range: self.span_to_here(start),
        })
    }

    fn expect_keyword(&mut self, k: Keyword, ctx: &str) -> PResult<SourceRange> {
        if self.at_keyword(k) {
            return Ok(self.bump_range());
        }
        let range = self.cur_range();
        let found = self.describe_cur();
        Err(self.error_bail(
            range,
            format!("expected '{}'{ctx}, found {found}", k.as_str()),
        ))
    }
}

// ---------------------------------------------------------------------------
// expressions
// ---------------------------------------------------------------------------

/// Binding power of the binary operators, tightest last.
fn binary_op(kind: &TokenKind) -> Option<(BinaryOp, u8)> {
    let TokenKind::Punct(p) = kind else {
        return None;
    };
    Some(match p {
        Punct::PipePipe => (BinaryOp::LogOr, 1),
        Punct::AmpAmp => (BinaryOp::LogAnd, 2),
        Punct::Pipe => (BinaryOp::BitOr, 3),
        Punct::Caret => (BinaryOp::BitXor, 4),
        Punct::Amp => (BinaryOp::BitAnd, 5),
        Punct::EqEq => (BinaryOp::Eq, 6),
        Punct::Ne => (BinaryOp::Ne, 6),
        Punct::Lt => (BinaryOp::Lt, 7),
        Punct::Gt => (BinaryOp::Gt, 7),
        Punct::Le => (BinaryOp::Le, 7),
        Punct::Ge => (BinaryOp::Ge, 7),
        Punct::Shl => (BinaryOp::Shl, 8),
        Punct::Shr => (BinaryOp::Shr, 8),
        Punct::Plus => (BinaryOp::Add, 9),
        Punct::Minus => (BinaryOp::Sub, 9),
        Punct::Star => (BinaryOp::Mul, 10),
        Punct::Slash => (BinaryOp::Div, 10),
        Punct::Percent => (BinaryOp::Rem, 10),
        _ => return None,
    })
}

/// The compound operator of an assignment token, if it is one.
fn assign_op(kind: &TokenKind) -> Option<Option<BinaryOp>> {
    let TokenKind::Punct(p) = kind else {
        return None;
    };
    Some(match p {
        Punct::Assign => None,
        Punct::StarAssign => Some(BinaryOp::Mul),
        Punct::SlashAssign => Some(BinaryOp::Div),
        Punct::PercentAssign => Some(BinaryOp::Rem),
        Punct::PlusAssign => Some(BinaryOp::Add),
        Punct::MinusAssign => Some(BinaryOp::Sub),
        Punct::ShlAssign => Some(BinaryOp::Shl),
        Punct::ShrAssign => Some(BinaryOp::Shr),
        Punct::AmpAssign => Some(BinaryOp::BitAnd),
        Punct::CaretAssign => Some(BinaryOp::BitXor),
        Punct::PipeAssign => Some(BinaryOp::BitOr),
        _ => return None,
    })
}

impl Parser<'_> {
    /// `expression` — including the comma operator.
    pub(crate) fn parse_expr(&mut self) -> PResult<Expr> {
        self.enter()?;
        let result = self.parse_expr_inner();
        self.leave();
        result
    }

    /// `a, b, c, …` — the comma operator, which is left-associative.
    ///
    /// Taken in a loop, so the length of the chain costs the parser no stack;
    /// sema and code generation walk it iteratively too, so it costs them
    /// none either and nothing but memory bounds it. See
    /// [`MAX_RECURSION_DEPTH`].
    fn parse_expr_inner(&mut self) -> PResult<Expr> {
        let mut lhs = self.parse_assignment_expr()?;
        while self.eat_punct(Punct::Comma).is_some() {
            let rhs = self.parse_assignment_expr()?;
            let range = lhs.range.join(rhs.range);
            lhs = Expr {
                kind: ExprKind::Comma {
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                range,
            };
        }
        Ok(lhs)
    }

    /// `assignment-expression`, which is right associative.
    ///
    /// `a = b = c` is taken in a loop and folded from the right afterwards, so
    /// the parser itself never recurses down the chain — but what it folds is
    /// `Assign(a, Assign(b, c))`, one level of *nesting* per operator, and
    /// nesting is what [`MAX_RECURSION_DEPTH`] is for. Each operator is
    /// therefore charged to the same counter `((((…))))` is charged to, and
    /// released again however the chain ends.
    fn parse_assignment_expr(&mut self) -> PResult<Expr> {
        let mut charged = 0u32;
        let result = self.assignment_chain(&mut charged);
        for _ in 0..charged {
            self.leave();
        }
        result
    }

    /// [`Parser::parse_assignment_expr`], reporting the nesting it charged.
    fn assignment_chain(&mut self, charged: &mut u32) -> PResult<Expr> {
        let mut pending: Vec<(Expr, Option<BinaryOp>)> = Vec::new();
        let mut value = loop {
            let lhs = self.parse_conditional_expr()?;
            let Some(op) = assign_op(&self.peek().kind) else {
                break lhs;
            };
            self.advance();
            self.enter()?;
            *charged += 1;
            pending.push((lhs, op));
        };
        for (lhs, op) in pending.into_iter().rev() {
            let range = lhs.range.join(value.range);
            value = Expr {
                kind: ExprKind::Assign {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(value),
                },
                range,
            };
        }
        Ok(value)
    }

    /// `conditional-expression`, whose `else` operand is another one.
    ///
    /// `a ? b : c ? d : e` is taken in a loop and folded from the right, for
    /// the reason [`Parser::parse_assignment_expr`] is — and, for the same
    /// reason, each operator is charged to [`MAX_RECURSION_DEPTH`]: the tree
    /// it builds nests one level per operator, and every pass after this one
    /// has to walk it.
    fn parse_conditional_expr(&mut self) -> PResult<Expr> {
        let mut charged = 0u32;
        let result = self.conditional_chain(&mut charged);
        for _ in 0..charged {
            self.leave();
        }
        result
    }

    /// [`Parser::parse_conditional_expr`], reporting the nesting it charged.
    fn conditional_chain(&mut self, charged: &mut u32) -> PResult<Expr> {
        #[allow(clippy::type_complexity)]
        let mut pending: Vec<(Expr, Option<Box<Expr>>)> = Vec::new();
        let mut value = loop {
            let cond = self.parse_binary_expr(1)?;
            if self.eat_punct(Punct::Question).is_none() {
                break cond;
            }
            // GNU's `a ?: b`: the middle operand is the condition itself, and
            // the condition is evaluated exactly once.
            let then_expr = if self.at_punct(Punct::Colon) {
                None
            } else {
                Some(Box::new(self.parse_expr()?))
            };
            self.expect_punct(Punct::Colon, " in conditional expression")?;
            self.enter()?;
            *charged += 1;
            pending.push((cond, then_expr));
        };
        for (cond, then_expr) in pending.into_iter().rev() {
            let range = cond.range.join(value.range);
            value = Expr {
                kind: ExprKind::Conditional {
                    cond: Box::new(cond),
                    then_expr,
                    else_expr: Box::new(value),
                },
                range,
            };
        }
        Ok(value)
    }

    /// The binary operators, by precedence climbing.
    ///
    /// Every level is left-associative, so a run of one operator is a loop
    /// rather than recursion and its length costs no stack — here or in the
    /// passes after it; the recursion is over the ten *precedence levels*.
    /// See [`MAX_RECURSION_DEPTH`].
    fn parse_binary_expr(&mut self, min_prec: u8) -> PResult<Expr> {
        let mut lhs = self.parse_cast_expr()?;
        while let Some((op, prec)) = binary_op(&self.peek().kind) {
            if prec < min_prec {
                break;
            }
            self.advance();
            let rhs = self.parse_binary_expr(prec + 1)?;
            let range = lhs.range.join(rhs.range);
            lhs = Expr {
                kind: ExprKind::Binary {
                    op,
                    lhs: Box::new(lhs),
                    rhs: Box::new(rhs),
                },
                range,
            };
        }
        Ok(lhs)
    }

    /// Whether a `(` at the current position introduces a type name — that is,
    /// whether this is a cast or a compound literal rather than a
    /// parenthesised expression.
    fn at_paren_type_name(&self) -> bool {
        if !self.at_punct(Punct::LParen) {
            return false;
        }
        // `__extension__` prefixes a declaration *and* an expression, so it
        // says nothing about which of the two a parenthesis opens; what comes
        // after it does. `(__extension__ 1.0iF)` — which is how GCC's own
        // `<complex.h>` spells `_Complex_I` — is a parenthesised constant, and
        // `(__extension__ long long)x` is a cast.
        let mut n = 1;
        while self.nth(n).keyword() == Some(Keyword::Extension) {
            n += 1;
        }
        self.starts_decl_specifier(n)
    }

    fn parse_cast_expr(&mut self) -> PResult<Expr> {
        self.enter()?;
        let result = self.parse_cast_expr_inner();
        self.leave();
        result
    }

    fn parse_cast_expr_inner(&mut self) -> PResult<Expr> {
        if !self.at_paren_type_name() {
            return self.parse_unary_expr();
        }
        let start = self.cur_range();
        self.advance(); // `(`
        let ty = self.parse_type_name()?;
        self.expect_punct(Punct::RParen, " after type name")?;
        if self.at_punct(Punct::LBrace) {
            // `(T){ ... }` is a compound literal, i.e. a postfix expression.
            let at = self.span_to_here(start);
            self.require_standard(Standard::C99, "a compound literal", at);
            let items = self.parse_initializer_list()?;
            let expr = Expr {
                kind: ExprKind::CompoundLiteral {
                    ty: Box::new(ty),
                    init: items,
                },
                range: self.span_to_here(start),
            };
            return self.parse_postfix_suffixes(expr);
        }
        let expr = self.parse_cast_expr()?;
        let range = start.join(expr.range);
        Ok(Expr {
            kind: ExprKind::Cast {
                ty: Box::new(ty),
                expr: Box::new(expr),
            },
            range,
        })
    }

    fn parse_unary_expr(&mut self) -> PResult<Expr> {
        let start = self.cur_range();

        if let Some(p) = match &self.peek().kind {
            TokenKind::Punct(p) => Some(*p),
            _ => None,
        } {
            let unary = match p {
                Punct::Amp => Some(UnaryOp::AddrOf),
                Punct::Star => Some(UnaryOp::Deref),
                Punct::Plus => Some(UnaryOp::Plus),
                Punct::Minus => Some(UnaryOp::Minus),
                Punct::Tilde => Some(UnaryOp::BitNot),
                Punct::Bang => Some(UnaryOp::LogNot),
                _ => None,
            };
            if let Some(op) = unary {
                self.advance();
                let operand = self.parse_cast_expr()?;
                let range = start.join(operand.range);
                return Ok(Expr {
                    kind: ExprKind::Unary {
                        op,
                        operand: Box::new(operand),
                    },
                    range,
                });
            }
            // GNU's `&&label`, the address of a label of this function. It is
            // an rvalue of type `void *` and the only operand `goto *` has;
            // `&&` can never open an expression otherwise, so there is nothing
            // to disambiguate.
            if p == Punct::AmpAmp {
                self.advance();
                let label = self.expect_ident(" after '&&'")?;
                self.label_addrs += 1;
                let range = start.join(label.range);
                return Ok(Expr {
                    kind: ExprKind::LabelAddr(label),
                    range,
                });
            }
            if matches!(p, Punct::PlusPlus | Punct::MinusMinus) {
                self.advance();
                let op = if p == Punct::PlusPlus {
                    IncDec::Inc
                } else {
                    IncDec::Dec
                };
                let operand = self.parse_unary_expr()?;
                let range = start.join(operand.range);
                return Ok(Expr {
                    kind: ExprKind::PreIncDec {
                        op,
                        operand: Box::new(operand),
                    },
                    range,
                });
            }
        }

        if self.at_keyword(Keyword::Sizeof) {
            self.advance();
            if self.at_paren_type_name() {
                self.advance(); // `(`
                let ty = self.parse_type_name()?;
                self.expect_punct(Punct::RParen, " after type name")?;
                if self.at_punct(Punct::LBrace) {
                    // `sizeof (T){ ... }` measures a compound literal.
                    let at = self.span_to_here(start);
                    self.require_standard(Standard::C99, "a compound literal", at);
                    let items = self.parse_initializer_list()?;
                    let literal = Expr {
                        kind: ExprKind::CompoundLiteral {
                            ty: Box::new(ty),
                            init: items,
                        },
                        range: self.span_to_here(start),
                    };
                    let operand = self.parse_postfix_suffixes(literal)?;
                    let range = start.join(operand.range);
                    return Ok(Expr {
                        kind: ExprKind::SizeofExpr(Box::new(operand)),
                        range,
                    });
                }
                return Ok(Expr {
                    kind: ExprKind::SizeofType(Box::new(ty)),
                    range: self.span_to_here(start),
                });
            }
            let operand = self.parse_unary_expr()?;
            let range = start.join(operand.range);
            return Ok(Expr {
                kind: ExprKind::SizeofExpr(Box::new(operand)),
                range,
            });
        }

        // `__extension__ expr` holds back the pedantic warnings there are none
        // of. `__real__` and `__imag__` are GNU's two halves of a complex
        // value, and sema types them: each is an lvalue whenever its operand
        // is, and each has a meaning on a *real* operand too.
        if self.eat_keyword(Keyword::Extension).is_some() {
            return self.parse_unary_expr();
        }
        if let Some(k @ (Keyword::RealGnu | Keyword::ImagGnu)) = self.peek().keyword() {
            self.advance();
            let operand = self.parse_cast_expr()?;
            let range = start.join(operand.range);
            return Ok(Expr {
                kind: ExprKind::ComplexPart {
                    real: k == Keyword::RealGnu,
                    operand: Box::new(operand),
                },
                range,
            });
        }

        if let Some(k @ (Keyword::Alignof | Keyword::AlignofName | Keyword::AlignofGnu)) =
            self.peek().keyword()
        {
            self.require_keyword(k, start);
            self.advance();
            if self.at_paren_type_name() {
                self.advance(); // `(`
                let ty = self.parse_type_name()?;
                self.expect_punct(Punct::RParen, " after type name")?;
                return Ok(Expr {
                    kind: ExprKind::AlignofType(Box::new(ty)),
                    range: self.span_to_here(start),
                });
            }
            // `_Alignof expr` is GCC's extension, which C never standardised;
            // accepting it costs nothing and `_Alignof(x)` is what people
            // write when `x` is an object.
            let operand = self.parse_unary_expr()?;
            let range = start.join(operand.range);
            return Ok(Expr {
                kind: ExprKind::AlignofExpr(Box::new(operand)),
                range,
            });
        }

        if self.at_va_arg() {
            return self.parse_va_arg();
        }
        if self.at_builtin("__builtin_offsetof") {
            return self.parse_offsetof();
        }
        if self.at_builtin("__builtin_types_compatible_p") {
            return self.parse_types_compatible();
        }
        if self.at_builtin("__builtin_choose_expr") {
            return self.parse_choose_expr();
        }

        self.parse_postfix_expr()
    }

    /// `__builtin_types_compatible_p(T1, T2)`, whose operands are type names.
    fn parse_types_compatible(&mut self) -> PResult<Expr> {
        let start = self.cur_range();
        self.advance(); // the name
        self.advance(); // `(`
        let lhs = self.parse_type_name()?;
        self.expect_punct(
            Punct::Comma,
            " after the first type of '__builtin_types_compatible_p'",
        )?;
        let rhs = self.parse_type_name()?;
        self.expect_punct(
            Punct::RParen,
            " after the second type of '__builtin_types_compatible_p'",
        )?;
        let expr = Expr {
            kind: ExprKind::TypesCompatible {
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
            },
            range: self.span_to_here(start),
        };
        self.parse_postfix_suffixes(expr)
    }

    /// `__builtin_choose_expr(c, a, b)`, whose unchosen operand is never even
    /// type checked — which is why it needs the parser's help.
    fn parse_choose_expr(&mut self) -> PResult<Expr> {
        let start = self.cur_range();
        self.advance(); // the name
        self.advance(); // `(`
        let cond = self.parse_assignment_expr()?;
        self.expect_punct(
            Punct::Comma,
            " after the condition of '__builtin_choose_expr'",
        )?;
        let then_expr = self.parse_assignment_expr()?;
        self.expect_punct(Punct::Comma, " in '__builtin_choose_expr'")?;
        let else_expr = self.parse_assignment_expr()?;
        self.expect_punct(Punct::RParen, " to close '__builtin_choose_expr'")?;
        let expr = Expr {
            kind: ExprKind::ChooseExpr {
                cond: Box::new(cond),
                then_expr: Box::new(then_expr),
                else_expr: Box::new(else_expr),
            },
            range: self.span_to_here(start),
        };
        self.parse_postfix_suffixes(expr)
    }

    /// Whether the next tokens invoke the named builtin.
    ///
    /// The `__builtin_` names are reserved, so no declaration can turn one
    /// back into an ordinary identifier; without the check the type name each
    /// of them takes would not parse as an expression.
    fn at_builtin(&self, name: &str) -> bool {
        self.peek().ident() == Some(name) && self.nth(1).is_punct(Punct::LParen)
    }

    /// Whether the next tokens are a `va_arg(…)` invocation.
    fn at_va_arg(&self) -> bool {
        self.at_builtin("__builtin_va_arg")
    }

    /// `__builtin_offsetof(T, member-designator)`, the special form
    /// `offsetof` is.
    ///
    /// C99 7.17p3's member designator is an identifier followed by any number
    /// of `.member` and `[expr]` steps, so that `offsetof(struct S, a[2].b)`
    /// names the offset of a member of an element of a member. Sema folds the
    /// whole path to one constant.
    fn parse_offsetof(&mut self) -> PResult<Expr> {
        let start = self.cur_range();
        self.advance(); // `__builtin_offsetof`
        self.advance(); // `(`
        let ty = self.parse_type_name()?;
        self.expect_punct(Punct::Comma, " after the type of 'offsetof'")?;
        let member = self.expect_ident(" as the member of 'offsetof'")?;
        let mut path = Vec::new();
        loop {
            if self.eat_punct(Punct::Dot).is_some() {
                path.push(Designator::Field(self.expect_ident(
                    " after '.' in the member designator of 'offsetof'",
                )?));
                continue;
            }
            if self.eat_punct(Punct::LBracket).is_some() {
                path.push(Designator::Index(self.parse_expr()?));
                self.expect_punct(
                    Punct::RBracket,
                    " after the subscript in the member designator of 'offsetof'",
                )?;
                continue;
            }
            break;
        }
        self.expect_punct(Punct::RParen, " after the member of 'offsetof'")?;
        let expr = Expr {
            kind: ExprKind::OffsetOf {
                ty: Box::new(ty),
                member,
                path,
            },
            range: self.span_to_here(start),
        };
        self.parse_postfix_suffixes(expr)
    }

    /// `va_arg(ap, T)`, whose second argument is a type name.
    fn parse_va_arg(&mut self) -> PResult<Expr> {
        let start = self.cur_range();
        self.advance(); // `va_arg`
        self.advance(); // `(`
        let ap = self.parse_assignment_expr()?;
        self.expect_punct(Punct::Comma, " after the argument list of 'va_arg'")?;
        let ty = self.parse_type_name()?;
        self.expect_punct(Punct::RParen, " after the type of 'va_arg'")?;
        let expr = Expr {
            kind: ExprKind::VaArg {
                ap: Box::new(ap),
                ty: Box::new(ty),
            },
            range: self.span_to_here(start),
        };
        self.parse_postfix_suffixes(expr)
    }

    fn parse_postfix_expr(&mut self) -> PResult<Expr> {
        let primary = self.parse_primary_expr()?;
        self.parse_postfix_suffixes(primary)
    }

    /// The `[…]`, `(…)`, `.x`, `->x`, `++` and `--` that follow an operand.
    ///
    /// A run of them is left-associative in the source and *nested* in the
    /// tree — `p->a->b` is a member of a member — and code generation walks
    /// that nesting recursively, so each suffix taken is charged to
    /// [`MAX_RECURSION_DEPTH`]. It is the tightest of the three constructs
    /// charged there: a `->` chain is what overflows first, at about 450.
    fn parse_postfix_suffixes(&mut self, expr: Expr) -> PResult<Expr> {
        let mut charged = 0u32;
        let result = self.postfix_suffixes(expr, &mut charged);
        for _ in 0..charged {
            self.leave();
        }
        result
    }

    /// [`Parser::parse_postfix_suffixes`], reporting the nesting it charged.
    fn postfix_suffixes(&mut self, mut expr: Expr, charged: &mut u32) -> PResult<Expr> {
        let mut suffixes = 0usize;
        loop {
            // Nothing is charged for an operand with no suffix at all, so
            // that the 63 levels of parenthesised expression C23 5.2.5.2p1
            // asks for keep the whole budget to themselves.
            if suffixes > 0 {
                self.enter()?;
                *charged += 1;
            }
            suffixes += 1;
            if self.eat_punct(Punct::LBracket).is_some() {
                let index = self.parse_expr()?;
                let rb = self.expect_punct(Punct::RBracket, " after subscript")?;
                expr = Expr {
                    range: expr.range.join(rb),
                    kind: ExprKind::Index {
                        base: Box::new(expr),
                        index: Box::new(index),
                    },
                };
                continue;
            }
            if self.eat_punct(Punct::LParen).is_some() {
                let mut args = Vec::new();
                if !self.at_punct(Punct::RParen) {
                    loop {
                        args.push(self.parse_assignment_expr()?);
                        if self.eat_punct(Punct::Comma).is_none() {
                            break;
                        }
                    }
                }
                let rp = self.expect_punct(Punct::RParen, " after argument list")?;
                expr = Expr {
                    range: expr.range.join(rp),
                    kind: ExprKind::Call {
                        callee: Box::new(expr),
                        args,
                    },
                };
                continue;
            }
            let arrow = if self.at_punct(Punct::Dot) {
                false
            } else if self.at_punct(Punct::Arrow) {
                true
            } else if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
                let op = if self.at_punct(Punct::PlusPlus) {
                    IncDec::Inc
                } else {
                    IncDec::Dec
                };
                let range = expr.range.join(self.bump_range());
                expr = Expr {
                    kind: ExprKind::PostIncDec {
                        op,
                        operand: Box::new(expr),
                    },
                    range,
                };
                continue;
            } else {
                break;
            };
            self.advance();
            let field = self.expect_ident(if arrow { " after '->'" } else { " after '.'" })?;
            expr = Expr {
                range: expr.range.join(field.range),
                kind: ExprKind::Member {
                    base: Box::new(expr),
                    arrow,
                    field,
                },
            };
        }
        Ok(expr)
    }

    /// `_Generic ( controlling-expression , type : value , … )` — C11 6.5.1.1.
    ///
    /// Every association is parsed; only the chosen one is checked, which is
    /// what makes `_Generic` usable for a type the other arms would refuse.
    fn parse_generic_selection(&mut self) -> PResult<Expr> {
        let start = self.cur_range();
        self.require_keyword(Keyword::Generic, start);
        self.advance();
        self.expect_punct(Punct::LParen, " after '_Generic'")?;
        let controlling = self.parse_assignment_expr()?;
        let mut assocs = Vec::new();
        while self.eat_punct(Punct::Comma).is_some() {
            let astart = self.cur_range();
            let ty = if self.eat_keyword(Keyword::Default).is_some() {
                None
            } else {
                Some(self.parse_type_name()?)
            };
            self.expect_punct(Punct::Colon, " after the type of a '_Generic' association")?;
            let value = self.parse_assignment_expr()?;
            assocs.push(GenericAssoc {
                ty,
                value,
                range: self.span_to_here(astart),
            });
        }
        let rparen = self.expect_punct(Punct::RParen, " to close '_Generic'")?;
        if assocs.is_empty() {
            self.error(
                start.join(rparen),
                "'_Generic' requires at least one association",
            );
        }
        Ok(Expr {
            kind: ExprKind::Generic {
                controlling: Box::new(controlling),
                assocs,
            },
            range: start.join(rparen),
        })
    }

    fn parse_primary_expr(&mut self) -> PResult<Expr> {
        let range = self.cur_range();
        match self.peek().kind.clone() {
            TokenKind::Keyword(Keyword::Generic) => self.parse_generic_selection(),
            TokenKind::Keyword(k @ (Keyword::True | Keyword::False)) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Bool(k == Keyword::True),
                    range,
                })
            }
            TokenKind::Keyword(Keyword::Nullptr) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Nullptr,
                    range,
                })
            }
            TokenKind::Ident(name) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Ident(Ident { name, range }),
                    range,
                })
            }
            TokenKind::Int(lit) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Int(lit),
                    range,
                })
            }
            TokenKind::Float(lit) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Float(lit),
                    range,
                })
            }
            TokenKind::Char(lit) => {
                self.advance();
                Ok(Expr {
                    kind: ExprKind::Char(lit),
                    range,
                })
            }
            TokenKind::Str(first) => Ok(self.parse_string_literal(first, range)),
            TokenKind::Punct(Punct::LParen) => {
                self.advance();
                // GNU's statement expression, `({ … })`: a compound statement
                // where an expression goes, whose value is the value of the
                // last expression statement in it.
                if self.at_punct(Punct::LBrace) {
                    let block = self.parse_compound_stmt()?;
                    let rp =
                        self.expect_punct(Punct::RParen, " to close a statement expression")?;
                    return Ok(Expr {
                        kind: ExprKind::StmtExpr(Box::new(block)),
                        range: range.join(rp),
                    });
                }
                let inner = self.parse_expr()?;
                let rp = self.expect_punct(Punct::RParen, " after parenthesized expression")?;
                Ok(Expr {
                    kind: inner.kind,
                    range: range.join(rp),
                })
            }
            _ => {
                let found = self.describe_cur();
                Err(self.error_bail(range, format!("expected expression, found {found}")))
            }
        }
    }

    /// Concatenates adjacent string literals, as translation phase 6 does.
    ///
    /// C11 6.4.5p5 gives the result the prefix of whichever half has one; two
    /// *different* prefixes have no meaning (and C23's N2594 deleted the last
    /// of the wording that gave them one), so that is a diagnostic. An
    /// unprefixed half being absorbed is re-encoded, because its elements are
    /// the UTF-8 bytes of the source and the result's are code units.
    fn parse_string_literal(&mut self, first: StrLit, first_range: SourceRange) -> Expr {
        self.advance();
        let mut kind = first.kind;
        let mut values = first.values;
        let mut text = first.text;
        let mut range = first_range;
        while let TokenKind::Str(next) = self.peek().kind.clone() {
            let piece_range = self.cur_range();
            if next.kind != kind {
                if kind == StrKind::Narrow {
                    values = recode_from_narrow(&values, next.kind);
                    kind = next.kind;
                } else if next.kind != StrKind::Narrow {
                    self.error(
                        piece_range,
                        format!(
                            "cannot concatenate a '{}' string literal with a '{}' one",
                            kind.prefix(),
                            next.kind.prefix()
                        ),
                    );
                }
            }
            if next.kind == kind || next.kind != StrKind::Narrow {
                values.extend_from_slice(&next.values);
            } else {
                values.extend(recode_from_narrow(&next.values, kind));
            }
            text.push(' ');
            text.push_str(&next.text);
            range = range.join(piece_range);
            self.advance();
        }
        Expr {
            kind: ExprKind::Str(StrLit { kind, values, text }),
            range,
        }
    }
}

/// Whether a name is one of the extended floating types, and how to describe
/// it.
///
/// GCC's `__float128` and `__fp16`, and TS 18661-3's `_FloatN` / `_FloatNx`
/// set, which C23 made optional in Annex H. None of them is here: `f32` and
/// `f64` are Rust's only two floating types on a stable compiler, `f16` and
/// `f128` are unstable, and the 80-bit `long double` an x86 `_Float64x` really
/// is has no Rust type at all. They are recognised so that a *declaration* of
/// one — which is all a header ever writes, and only behind a
/// `__GNUC_PREREQ` that this crate's `__GNUC__` does not meet — is one clear
/// refusal rather than an "implicit int" cascade.
fn extended_float_type(name: &str) -> Option<&'static str> {
    match name {
        "__float128" | "_Float128" | "_Float128x" => Some("binary128"),
        "_Float64x" => Some("the extended-precision type behind 'long double'"),
        "__fp16" | "_Float16" => Some("binary16"),
        "__bf16" | "__bfloat16" => Some("bfloat16"),
        // `_Float32` and `_Float64` are `float` and `double` in every format
        // this crate models, but they are still distinct *types* to C, and a
        // `_Generic` over them would answer differently.
        "_Float32" | "_Float32x" => Some("the TS 18661-3 spelling of a binary32 type"),
        "_Float64" => Some("the TS 18661-3 spelling of a binary64 type"),
        _ => None,
    }
}

/// Re-encodes the UTF-8 bytes of an unprefixed literal as elements of `kind`.
///
/// `"é" L"x"` is one wide literal of two characters, not of the two bytes the
/// `é` was written as.
fn recode_from_narrow(values: &[u32], kind: StrKind) -> Vec<u32> {
    if kind == StrKind::Narrow || kind == StrKind::Utf8 {
        return values.to_vec();
    }
    let bytes: Vec<u8> = values.iter().map(|v| *v as u8).collect();
    let text = String::from_utf8_lossy(&bytes);
    let mut out = Vec::with_capacity(values.len());
    for ch in text.chars() {
        let value = ch as u32;
        if kind == StrKind::Utf16 && value > 0xffff {
            let v = value - 0x1_0000;
            out.push(0xd800 + (v >> 10));
            out.push(0xdc00 + (v & 0x3ff));
        } else {
            out.push(value);
        }
    }
    out
}