cinrs-core 0.2.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
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
//! The C99 preprocessor: translation phase 4.
//!
//! The preprocessor sits between the [lexer](crate::lex) and the
//! [parser](crate::parse). It consumes the lexer's tokens together with their
//! `bol` / `preceded_by_space` flags, executes the directives it finds and
//! replaces macro invocations, and hands the parser a [`Token`] list that
//! contains no `#` directives at all.
//!
//! # Token origin
//!
//! Every token the preprocessor emits carries an [`Origin`]:
//!
//! * [`Origin::Source`] — the token was written where it is, and its
//!   [`Token::range`] is its own.
//! * [`Origin::Expansion`] — the token came out of a macro's replacement list,
//!   and its range is the range of the *invocation*, not of the `#define`.
//!
//! That distinction is the whole point. A diagnostic — ours or `rustc`'s on
//! the code we generate — must land on something the user wrote, and the
//! `#define` is not where the mistake is being made. Tokens that came from a
//! macro *argument* keep their own ranges, because the argument *was* written
//! at the call site; only the replacement list's own tokens, and the tokens
//! `#` and `##` synthesise, are re-pointed at the invocation.
//!
//! A procedural macro cannot emit secondary spans, so the "which macro was
//! that?" half of the story is appended to the message instead:
//! [`Expansions::annotate`] adds `note: in expansion of macro 'X'` to every
//! diagnostic that lands inside an invocation.
//!
//! # Hide sets
//!
//! Macro replacement follows Dave Prosser's algorithm, the one the standard's
//! rescanning rules were written from. Each token carries a *hide set*: the
//! names of the macros whose expansion it came out of. A name is not replaced
//! again while it is in its own hide set, which is what stops
//!
//! ```c
//! #define foo (4 + foo)
//! ```
//!
//! from running forever while still letting `foo` be replaced somewhere else.
//! For a function-like macro the hide set of the result is
//! `(HS(name) ∩ HS(')')) ∪ {name}`, which is what makes the standard's
//! `f(2 * (f)(z))` example come out right.
//!
//! # The `# #` rule
//!
//! Rust's own lexer refuses `##` in raw-token mode ("reserved multi-hash
//! token"), so a `c99!` block written as raw Rust tokens cannot spell the
//! token-pasting operator. It can spell `a # # b`, and in a *replacement list*
//! a `#` immediately followed by another `#` is ill-formed C anyway — `#` must
//! be followed by a macro parameter — so this preprocessor reads two adjacent
//! `#` tokens in a replacement list as the `##` operator. The rule applies in
//! every input mode, so a macro written with `# #` means the same thing whether
//! it is passed as raw tokens or inside a string literal.
//!
//! # `#include`
//!
//! A header is read at the point the directive is reached, lexed, and pushed
//! onto a stack of open files; the tokens it produces are the tokens the
//! parser sees next. Each file has its own text, its own line numbering and
//! its own idea of what `__FILE__` says, and each is placed in a range of the
//! global offset space of its own, so that a position identifies both a file
//! and a place in it. The [`Preprocessed::included`] list is what a caller
//! adds to its [source map](crate::SourceMap) afterwards, in the order the
//! files were opened; the preprocessor cannot do it itself, because it runs on
//! a thread where a `proc_macro2::Span` cannot follow it.
//!
//! Where a header is looked for — and why the system directories are never
//! looked in — is [`crate::include`]. Reading one twice is avoided the two
//! usual ways: `#pragma once`, and the classic include-guard optimisation. A
//! file that includes itself with neither eventually nests too deeply and is
//! reported.
//!
//! A conditional group a header leaves open ends with the header rather than
//! running on into whatever included it, and is reported against the file that
//! opened it.
//!
//! ## The `cinrs` pragmas
//!
//! ```c
//! #pragma cinrs target "i686-unknown-linux-gnu"
//! #pragma cinrs include_path "vendor/include"
//! #pragma cinrs system_include first
//! #pragma cinrs link "mylib"
//! #pragma cinrs export
//! #pragma cinrs safe gcd fact
//! #pragma cinrs no_std
//! #pragma cinrs crate "crate::vendor::cinrs"
//! ```
//!
//! `target` picks the data model the unit is translated for, overriding
//! `CINRS_TARGET`; `include_path` adds a directory to the search path (relative
//! paths resolve against `CARGO_MANIFEST_DIR`); `system_include` puts the
//! platform's own include directories on that path, after the bundled headers
//! or — with `first` — before them (see [`crate::include`]); `link` adds
//! `#[link(name = "mylib")]` on an `extern` block of its own; `export` gives
//! everything with external linkage a real C symbol, so that another unit can
//! link to it; `safe` generates those functions without `unsafe`, so that
//! `rustc` checks them (see [`crate::sema::check_safe`]); `no_std` takes the
//! `Vec`s a variable length array or `alloca` needs from `alloc` rather than
//! from `std`; and `crate` says where the `cinrs` facade crate is, for the
//! generated code that names the runtime. Being
//! directives rather than attributes or macro arguments is what makes them
//! mean the same thing in raw-token and in string-literal input. An unknown
//! `#pragma cinrs` option is an error; every other pragma is ignored, as
//! 6.10.6 asks. `doc/pragmas.md` is the reference page.
//!
//! `target` is the one that cannot be handled where it stands: the predefined
//! macros are built from the model before the first directive is read, so
//! [`scan_target_pragma`] finds it *lexically*, before preprocessing, and the
//! handler here only checks that what it finds agrees. Which is why the pragma
//! has to be written in the unit's own text, ahead of any `#include` or `#if`;
//! anywhere else is a diagnostic rather than a silent half-measure.
//!
//! # What the later revisions add
//!
//! `__VA_OPT__(…)`, `#elifdef` and `#elifndef` are C23's, and are accepted in
//! a [`Standard::C23`] block; an older one is told which macro would have
//! them. `true` and `false` are keywords there too, so an `#if` reads them as
//! 1 and 0 rather than turning them into 0 like any other identifier (C23
//! 6.10.1p6). `#embed` and `__has_embed` are C23's as well: the directive is
//! replaced by the bytes of a file, written as a comma-separated list of
//! `unsigned char` values, and the resource is reported in
//! [`Preprocessed::embedded_files`] so that editing it rebuilds the crate.
//!
//! # Predefined macros
//!
//! | Macro | Value |
//! | --- | --- |
//! | `__STDC__` | `1` |
//! | `__STDC_HOSTED__` | `1` |
//! | `__STDC_VERSION__` | the revision: `199901L`, `201112L`, `201710L` or `202311L`; undefined in `c89!` and `gnu89!` |
//! | `__cinrs__`, `__CINRS__` | `1` |
//! | `__CINRS_MAJOR__`, `__CINRS_MINOR__`, `__CINRS_PATCH__` | the version of `cinrs-core` |
//! | `__GNUC__`, `__GNUC_MINOR__`, `__GNUC_PATCHLEVEL__` | `14`, `2`, `0` |
//! | `__VERSION__` | `"14.2.0 (cinrs <version>)"` |
//! | `__FILE__` | the invoking `.rs` file's path, or `"<c99!>"` |
//! | `__LINE__` | the line of the invoking `.rs` file |
//! | `__DATE__` | `"??? ?? ????"` |
//! | `__TIME__` | `"??:??:??"` |
//!
//! `__FILE__` and `__LINE__` are computed from the position they are *used*
//! at, so inside a header they name the header and the line in it, and a macro
//! defined in `<assert.h>` that mentions them reports the line the assertion
//! is written on.
//!
//! `__DATE__` and `__TIME__` are deliberately fixed placeholders: a build has
//! to be reproducible, and a macro that expanded to the wall clock would make
//! the generated code differ between two builds of the same source.
//!
//! `__LINE__` is a line of the `.rs` file the invocation is written in
//! whenever the compiler tells us where that is — the captured C text
//! remembers which line of its `.rs` file it starts on — and a line inside the
//! C text itself otherwise (a `TokenStream` built from a string in a unit
//! test, for instance).
//!
//! ## `#line`
//!
//! `#line N` and `#line N "name"` (6.10.4), and GCC's `# N "name" flags…` line
//! marker, do what they say: the line after the directive is line N, counting
//! up per physical line from there, and `__FILE__` is the given name until the
//! next directive or the end of that file. The macro-expanded form is
//! supported too — `#line line`, with `line` a macro — and the numbering is
//! per file, so a `#line` inside a header ends with the header. In the
//! macro's own text a `#line` replaces the `.rs`-line convention above from
//! the next line to the end of the block, which is exactly what a program that
//! writes one is asking for.
//!
//! **Nothing else moves.** A diagnostic — this crate's or `rustc`'s — still
//! points at the token that was really written, in the file it was really
//! written in, because that is the position the user can look at; making the
//! caret land on the C is the reason the whole pipeline carries spans.
//! `__BASE_FILE__` names the file the translation unit started in and is not
//! affected either; `__FILE_NAME__` is `__FILE__` without the directory, so it
//! is.
//!
//! On top of those comes a small, deliberately short set of target
//! description macros derived from the machine this crate was compiled for and
//! from [`TargetModel`]: the architecture
//! (`__x86_64__`, `__aarch64__`, …), the operating system (`__linux__`,
//! `__unix__`, `_WIN32`, `__APPLE__`, …), the data model (`__LP64__`,
//! `__ILP32__`, `__CHAR_UNSIGNED__`, `__SIZEOF_INT__` and friends,
//! `__CHAR_BIT__`) and the byte order (`__BYTE_ORDER__`).
//!
//! As a compiler, cinrs says it is GCC 14.2 — `__GNUC__` is what the world's
//! version gates test, and 4.2.1 turned real programs away or onto their slow
//! paths — and says who it really is with `__CINRS__`. The GNU macros a header
//! tests for are defined where cinrs does what they promise
//! (`__GNUC_STDC_INLINE__`, `__GCC_HAVE_SYNC_COMPARE_AND_SWAP_n`, the
//! `__GCC_ATOMIC_*` family, `__BIGGEST_ALIGNMENT__`), `__GCC_IEC_559` and
//! `__GCC_IEC_559_COMPLEX` are `0` because Annexes F and G are not claimed, and
//! the rest are left out on purpose: `__OPTIMIZE__` and `__NO_INLINE__`,
//! `__GCC_ASM_FLAG_OUTPUTS__` (flag outputs are refused),
//! `__SIZEOF_FLOAT128__`, `__PRAGMA_REDEFINE_EXTNAME` and `__clang__`.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::capture::{Pos, SourceRange};
use crate::diag::{Diagnostic, Diagnostics};
use crate::include;
use crate::lex::{
    self, IntLit, Keyword, LexOptions, LongKind, NumBase, Punct, StrKind, StrLit, TokenKind,
};
use crate::target::{Arch, Env, Os, TargetModel, TargetSource};
use crate::{Dialect, Gating, Options, Standard};

// ---------------------------------------------------------------------------
// the tokens the parser sees
// ---------------------------------------------------------------------------

/// One macro expansion a token came out of.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Expansion {
    /// The macro's name.
    pub name: String,
    /// The range of the invocation: the name for an object-like macro, the
    /// name through the closing `)` for a function-like one.
    pub invocation: SourceRange,
    /// Where the macro's name was written in its `#define`.
    pub definition: SourceRange,
    /// The expansion this one was produced inside, if any.
    pub parent: Option<Arc<Expansion>>,
}

/// Where a preprocessed token came from.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub enum Origin {
    /// The token was written where [`Token::range`] says it was.
    #[default]
    Source,
    /// The token came out of a macro's replacement list; [`Token::range`] is
    /// the range of the invocation.
    Expansion(Arc<Expansion>),
}

impl Origin {
    /// The expansion this token came out of, if any.
    pub fn expansion(&self) -> Option<&Arc<Expansion>> {
        match self {
            Origin::Source => None,
            Origin::Expansion(e) => Some(e),
        }
    }
}

/// A preprocessed C token: what the parser consumes.
///
/// Deliberately shaped like [`lex::Token`] minus the flags the preprocessor
/// needed and plus the [`Origin`] it produced, so that the parser's view of a
/// token did not have to change.
#[derive(Clone, PartialEq, Debug)]
pub struct Token {
    /// What the token is.
    pub kind: TokenKind,
    /// Where to blame: the token's own range, or the range of the macro
    /// invocation it came out of.
    pub range: SourceRange,
    /// How the token got here.
    pub origin: Origin,
}

impl Token {
    /// The keyword this token is, if any.
    pub fn keyword(&self) -> Option<lex::Keyword> {
        match &self.kind {
            TokenKind::Keyword(k) => Some(*k),
            _ => None,
        }
    }

    /// Whether this token is the given punctuator.
    pub fn is_punct(&self, p: Punct) -> bool {
        self.kind == TokenKind::Punct(p)
    }

    /// Whether this token is the given keyword.
    pub fn is_keyword(&self, k: lex::Keyword) -> bool {
        self.kind == TokenKind::Keyword(k)
    }

    /// Whether this token ends the input.
    pub fn is_eof(&self) -> bool {
        self.kind == TokenKind::Eof
    }

    /// The identifier this token is, if any.
    pub fn ident(&self) -> Option<&str> {
        match &self.kind {
            TokenKind::Ident(name) => Some(name),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// the expansion map
// ---------------------------------------------------------------------------

/// Every macro invocation the preprocessor replaced, so that a diagnostic
/// landing inside one can say which macro it was.
///
/// A procedural macro has exactly one span per diagnostic and no way to add a
/// second one, so the extra context has to travel in the message text.
#[derive(Clone, Default, Debug)]
pub struct Expansions {
    /// One entry per expansion, in the order they happened, which puts an
    /// outer macro before the inner ones it produced.
    entries: Vec<ExpansionSite>,
}

/// Where one macro was invoked, and where it was defined.
#[derive(Clone, Debug)]
struct ExpansionSite {
    invocation: SourceRange,
    name: String,
    definition: SourceRange,
}

impl Expansions {
    fn record(&mut self, range: SourceRange, name: &str, definition: SourceRange) {
        self.entries.push(ExpansionSite {
            invocation: range,
            name: name.to_owned(),
            definition,
        });
    }

    /// The macro whose invocation most tightly encloses `pos`.
    fn enclosing(&self, pos: Pos) -> Option<&ExpansionSite> {
        let mut best: Option<&ExpansionSite> = None;
        for entry in &self.entries {
            if entry.invocation.start > pos || entry.invocation.end < pos {
                continue;
            }
            // The narrowest invocation wins; ties go to the one recorded
            // first, which is the outermost of a nest sharing one range.
            match best {
                Some(b) if b.invocation.len() <= entry.invocation.len() => {}
                _ => best = Some(entry),
            }
        }
        best
    }

    /// Adds `note: in expansion of macro 'X', defined at line N` to every
    /// diagnostic that landed inside a macro invocation.
    ///
    /// Called once per pass, on the diagnostics that pass produced, so that no
    /// diagnostic is ever annotated twice.
    pub fn annotate(&self, diags: &mut Diagnostics) {
        if self.entries.is_empty() {
            return;
        }
        for diag in diags.items_mut() {
            if let Some(site) = self.enclosing(diag.range.start) {
                diag.notes.push(crate::diag::Note {
                    message: format!("in expansion of macro '{}', defined", site.name),
                    range: Some(site.definition),
                });
            }
        }
    }

    /// Whether any macro was expanded at all.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

// ---------------------------------------------------------------------------
// hide sets
// ---------------------------------------------------------------------------

/// The set of macro names a token must not be replaced by again.
///
/// Tiny by construction — a handful of names at most — so a sorted vector
/// behind an `Arc` beats a hash set, and the `None` case makes the common
/// "no hide set at all" free.
#[derive(Clone, Default, PartialEq, Eq, Debug)]
struct HideSet(Option<Arc<Vec<String>>>);

impl HideSet {
    fn contains(&self, name: &str) -> bool {
        match &self.0 {
            None => false,
            Some(names) => names.iter().any(|n| n == name),
        }
    }

    fn add(&self, name: &str) -> HideSet {
        if self.contains(name) {
            return self.clone();
        }
        let mut names = match &self.0 {
            None => Vec::with_capacity(1),
            Some(names) => (**names).clone(),
        };
        names.push(name.to_owned());
        HideSet(Some(Arc::new(names)))
    }

    /// The names in both sets, which is what a function-like macro's result
    /// hides (6.10.3.4, via Prosser).
    fn intersect(&self, other: &HideSet) -> HideSet {
        let (Some(a), Some(b)) = (&self.0, &other.0) else {
            return HideSet::default();
        };
        let names: Vec<String> = a.iter().filter(|n| b.contains(n)).cloned().collect();
        if names.is_empty() {
            HideSet::default()
        } else {
            HideSet(Some(Arc::new(names)))
        }
    }

    /// Every name of `other`, added to this set.
    fn union(&self, other: &HideSet) -> HideSet {
        let Some(names) = &other.0 else {
            return self.clone();
        };
        let mut out = self.clone();
        for name in names.iter() {
            out = out.add(name);
        }
        out
    }
}

// ---------------------------------------------------------------------------
// the preprocessor's own token
// ---------------------------------------------------------------------------

/// A token inside the preprocessor: the lexer's, plus a hide set and an origin.
///
/// `space`, `pad` and `trail` are GCC's "padding" (see [`Lead`]) folded into
/// the tokens it separates. `space` is whether white space precedes the token
/// as things stand. `pad` answers the same question for the case where the
/// white-space status of a macro name or parameter is put in front of the
/// token: `None` when nothing but that status would count, `Some(b)` when an
/// expansion to nothing sits between the two, and it is `b` that counts once
/// that status says "no white space". `trail` is the padding that follows the
/// token, handed on to whichever token is read next.
#[derive(Clone, Debug)]
struct PTok {
    kind: TokenKind,
    range: SourceRange,
    bol: bool,
    space: bool,
    pad: Option<bool>,
    trail: Option<Lead>,
    origin: Origin,
    hide: HideSet,
    errors: Vec<Diagnostic>,
}

impl PTok {
    fn from_lexed(tok: &lex::Token) -> Self {
        Self {
            kind: tok.kind.clone(),
            range: tok.range,
            bol: tok.bol,
            space: tok.preceded_by_space,
            pad: None,
            trail: None,
            origin: Origin::Source,
            hide: HideSet::default(),
            errors: tok.errors.clone(),
        }
    }

    /// Puts the white-space status of the macro name or parameter this token
    /// now stands for in front of it (6.10.3.2p2's "white space before the
    /// first preprocessing token … is deleted", as GCC implements it): the
    /// first token of a replacement or of a substituted argument is spaced
    /// like the name or parameter it replaced, not like it was written.
    fn lead_with(&mut self, space: bool, pad: Option<bool>) {
        let under = self.pad.unwrap_or(false);
        self.space = space || under;
        self.pad = pad.map(|p| p || under).or(self.pad);
    }
}

/// The padding an expansion to nothing leaves behind, folded to what it does
/// to the next token.
///
/// GCC marks where a macro or argument was with padding tokens: one carrying
/// the name's or parameter's white-space status in front, one carrying none
/// behind. The next real token is spaced like the first padding in front of
/// it, except that padding without white space is forgotten by a following
/// padding that carries no status at all. Every run of padding ending in the
/// status-less kind comes down to "white space if `space`, or if the token
/// has it" — and, for [`PTok::pad`], "if `pad`, or if the token has it".
#[derive(Clone, Copy, Debug)]
struct Lead {
    space: bool,
    pad: bool,
}

impl Lead {
    /// What a name or parameter with this status leaves behind when it
    /// expands to nothing, `inner` being the padding its expansion left.
    fn of_empty(space: bool, pad: Option<bool>, inner: Option<Lead>) -> Self {
        let inner_pad = inner.is_some_and(|l| l.pad);
        Self {
            space: space || inner_pad,
            pad: pad.unwrap_or(false) || inner_pad,
        }
    }

    /// `first`, then `then`.
    fn join(first: Option<Lead>, then: Option<Lead>) -> Option<Lead> {
        match (first, then) {
            (Some(a), Some(b)) => Some(Lead {
                space: a.space || b.space,
                pad: a.pad || b.space,
            }),
            (a, b) => a.or(b),
        }
    }

    fn apply(self, tok: &mut PTok) {
        let own = tok.space;
        tok.space = self.space || own;
        tok.pad = Some(self.pad || own);
    }
}

impl PTok {
    fn is_eof(&self) -> bool {
        self.kind == TokenKind::Eof
    }

    fn is_punct(&self, p: Punct) -> bool {
        self.kind == TokenKind::Punct(p)
    }

    fn name(&self) -> Option<&str> {
        self.kind.macro_name()
    }

    fn spelling(&self) -> &str {
        self.kind.spelling()
    }
}

// ---------------------------------------------------------------------------
// macro definitions
// ---------------------------------------------------------------------------

/// A macro the preprocessor synthesises rather than stores tokens for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Builtin {
    /// `__LINE__`, whose value depends on where it is used.
    Line,
    /// `__FILE__`, likewise: inside an `#include`d file it names the header.
    File,
    /// `__FILE_NAME__` — GNU's `__FILE__` without the directory.
    FileName,
    /// `__INCLUDE_LEVEL__` — how many `#include`s deep the use is.
    IncludeLevel,
    /// `__COUNTER__` — a fresh integer at every use.
    Counter,
}

/// One `#define`.
#[derive(Debug)]
struct MacroDef {
    /// The parameter names, or `None` for an object-like macro.
    params: Option<Vec<String>>,
    /// Whether the parameter list ended with `...`.
    variadic: bool,
    /// The name GNU's `#define log(fmt, args...)` gave the variable arguments,
    /// which is then another spelling of `__VA_ARGS__`.
    va_name: Option<String>,
    /// The replacement list.
    body: Vec<PTok>,
    /// Where the macro's name was written.
    name_range: SourceRange,
    /// Whether this macro was built in rather than written by the user.
    predefined: bool,
    /// Which set of headers the `#define` was written in; see [`DefSite`].
    site: DefSite,
    /// The value this macro computes, for the ones that are not just tokens.
    builtin: Option<Builtin>,
}

impl MacroDef {
    /// Whether two definitions are the same one, as 6.10.3p2 requires:
    /// the same kind, the same parameter spellings, and replacement lists that
    /// agree token for token *and* on where the white space was.
    fn same_as(&self, other: &MacroDef) -> bool {
        if self.params != other.params
            || self.variadic != other.variadic
            || self.va_name != other.va_name
        {
            return false;
        }
        if self.body.len() != other.body.len() {
            return false;
        }
        self.body
            .iter()
            .zip(&other.body)
            .enumerate()
            .all(|(i, (a, b))| a.spelling() == b.spelling() && (i == 0 || a.space == b.space))
    }

    /// The index of the parameter `name` stands for, `__VA_ARGS__` included.
    fn param_index(&self, name: &str) -> Option<usize> {
        let params = self.params.as_ref()?;
        if let Some(i) = params.iter().position(|p| p == name) {
            return Some(i);
        }
        let variable = name == VA_ARGS || self.va_name.as_deref() == Some(name);
        (self.variadic && variable).then_some(params.len())
    }

    /// The index the variable arguments occupy, if there are any.
    fn va_index(&self) -> Option<usize> {
        self.variadic
            .then(|| self.params.as_ref().map_or(0, Vec::len))
    }
}

/// The pieces of a parsed macro parameter list.
struct ParamList {
    params: Vec<String>,
    variadic: bool,
    va_name: Option<String>,
    /// How many tokens the list occupied, including its parentheses.
    used: usize,
}

const VA_ARGS: &str = "__VA_ARGS__";

/// C23's conditional-expansion operator (6.10.5.2).
const VA_OPT: &str = "__VA_OPT__";

/// C99's `_Pragma` operator (6.10.9).
const PRAGMA_OPERATOR: &str = "_Pragma";

/// Undoes what `#` did: `L"a\"b\\c"` becomes `a"b\c`.
fn destringize(text: &str) -> String {
    let inner = text
        .strip_prefix("L\"")
        .or_else(|| text.strip_prefix('"'))
        .and_then(|rest| rest.strip_suffix('"'))
        .unwrap_or(text);
    let mut out = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some(next @ ('"' | '\\')) => out.push(next),
            Some(next) => {
                out.push('\\');
                out.push(next);
            }
            None => out.push('\\'),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// limits
// ---------------------------------------------------------------------------

/// How deeply argument pre-expansion may nest.
///
/// Hide sets already make runaway recursion impossible, but a macro whose
/// arguments are themselves deeply nested invocations turns into recursion in
/// *this* code, which runs inside a compiler that must not be taken down by a
/// stack overflow.
const MAX_EXPANSION_DEPTH: u32 = 200;

/// How deeply `#include` may nest.
///
/// A header that includes itself is the ordinary way to reach this, and it is
/// always a mistake — the include guard that would have stopped it is missing.
/// The limit is a count of open files rather than a recursion limit: the
/// preprocessor reads a nested file iteratively, so nothing here is at risk of
/// a stack overflow, but a program that never stops including is still a
/// program that never finishes compiling.
const MAX_INCLUDE_DEPTH: usize = 200;

/// `__STDC_EMBED_NOT_FOUND__`, the answer `__has_embed` gives for a resource
/// that is not there or that carries a parameter this does not have.
const EMBED_NOT_FOUND: u128 = 0;
/// `__STDC_EMBED_FOUND__`: the resource exists and has at least one byte.
const EMBED_FOUND: u128 = 1;
/// `__STDC_EMBED_EMPTY__`: the resource exists and `#embed` would produce
/// nothing from it.
const EMBED_EMPTY: u128 = 2;

/// The `__has_…` operators `Pp::has_operator` answers and GCC 15
/// also defines, which `#ifdef` and `defined` therefore report as defined.
const HAS_OPERATORS: &[&str] = &[
    "__has_include",
    "__has_include_next",
    "__has_attribute",
    "__has_c_attribute",
    "__has_builtin",
    "__has_feature",
    "__has_extension",
    "__has_embed",
];

/// How many tokens one translation unit's macro expansion may produce.
///
/// `#define A B B` repeated thirty times is a legal program whose expansion
/// does not fit in memory. Refusing it with a diagnostic beats spending the
/// rest of the build on it.
const MAX_EXPANDED_TOKENS: usize = 4_000_000;

// ---------------------------------------------------------------------------
// entry point
// ---------------------------------------------------------------------------

/// What the preprocessor needs to know about the text it is running over.
#[derive(Clone, Debug)]
pub struct Context {
    /// The C source text, which `#error` and `#include <…>` read back
    /// verbatim.
    pub text: String,
    /// The global offset of `text`'s first byte.
    pub base: Pos,
    /// What `__FILE__` expands to.
    pub file_name: String,
    /// The line `text`'s own line 1 sits on; see the [module docs](self).
    pub first_line: usize,
    /// The directory an `#include "…"` written in this text looks in first —
    /// the directory of the invoking `.rs` file. `None` when the compiler will
    /// not say where that is.
    pub dir: Option<std::path::PathBuf>,
    /// The global offset the first `#include`d file is placed at.
    ///
    /// The preprocessor allocates the offsets of the files it opens, because
    /// it runs where a [`SourceMap`](crate::SourceMap) cannot follow it; see
    /// [`crate::SourceMap::next_base`].
    pub next_base: Pos,
    /// The `#pragma cinrs target` directives [`scan_target_pragma`] already
    /// read out of `text`, so that the preprocessor does not report one twice
    /// and can tell a header's from the unit's own.
    pub target_pragmas: TargetPragmas,
}

impl Context {
    /// A context for `text` with nothing known about where it came from.
    pub fn new(text: impl Into<String>, base: Pos) -> Self {
        let text = text.into();
        // One byte of gap, exactly as `SourceMap::add_file` leaves, so that the
        // end of one file is never the start of the next.
        let next_base = base
            .saturating_add(text.len() as Pos)
            .saturating_add(FILE_GAP);
        Self {
            text,
            base,
            file_name: DEFAULT_FILE_NAME.to_owned(),
            first_line: 1,
            dir: None,
            next_base,
            target_pragmas: TargetPragmas::default(),
        }
    }
}

/// The gap left between two files in the global offset space.
///
/// It must match [`crate::SourceMap`]'s, since the preprocessor allocates the
/// offsets and the map hands out the spans for them.
const FILE_GAP: Pos = 1;

/// What `__FILE__` expands to when the compiler will not say where the
/// invocation is.
pub const DEFAULT_FILE_NAME: &str = "<c99!>";

/// One file `#include` brought in, for the caller to add to its source map.
#[derive(Clone, Debug)]
pub struct IncludedFile {
    /// What diagnostics call it: `include/foo.h`, or `<cinrs>/stdio.h` for a
    /// bundled header.
    pub name: String,
    /// Its text.
    pub text: String,
    /// The global offset its text starts at.
    pub base: Pos,
    /// The `#include` directive that pulled it in, which is where a diagnostic
    /// inside it points.
    pub directive: SourceRange,
}

/// What `#embed`'s parameters asked for (C23 6.10.3.2–6.10.3.5).
#[derive(Clone, Debug, Default)]
struct EmbedParams {
    /// `limit(N)`: at most this many bytes of the resource.
    limit: Option<usize>,
    /// `prefix(…)`: tokens before the bytes, when there are any.
    prefix: Vec<PTok>,
    /// `suffix(…)`: tokens after them, likewise.
    suffix: Vec<PTok>,
    /// `if_empty(…)`: the whole expansion when there are none.
    if_empty: Vec<PTok>,
}

/// One function `#pragma cinrs safe` named.
///
/// The pragma is the spelling that works in every entry point and in
/// string-literal input, so it names its functions rather than being written on
/// one; whether a name is a function of this unit at all is
/// [sema's](crate::sema::check_safe) question, and the range is what its
/// diagnostic points at.
#[derive(Clone, Debug)]
pub struct SafeName {
    /// The identifier as written.
    pub name: String,
    /// Where it was written.
    pub range: SourceRange,
}

/// Everything one run of the preprocessor produced.
#[derive(Debug)]
pub struct Preprocessed {
    /// The token list, always ending with [`TokenKind::Eof`].
    pub tokens: Vec<Token>,
    /// The macro invocations that were replaced.
    pub expansions: Expansions,
    /// The files `#include` opened, in the order they were opened, which is
    /// also the order they must be added to a source map: a file is always
    /// listed after the one whose directive pulled it in.
    pub included: Vec<IncludedFile>,
    /// The absolute paths of the *user* headers that were read, for rebuild
    /// tracking. A bundled header cannot change without the crate changing, so
    /// it is not listed.
    pub user_headers: Vec<std::path::PathBuf>,
    /// The absolute paths of the resources `#embed` read, for the same reason
    /// and by the same route — except that they are bytes rather than text, so
    /// the expansion tracks them with `include_bytes!`.
    pub embedded_files: Vec<std::path::PathBuf>,
    /// The libraries `#pragma cinrs link` asked for, in the order asked.
    pub link_libraries: Vec<String>,
    /// The functions `#pragma cinrs safe` named, in the order named.
    pub safe_functions: Vec<SafeName>,
    /// Whether `#pragma cinrs export` asked for real C symbols.
    pub export: bool,
    /// Whether `#pragma cinrs no_std` said the expansion goes into a
    /// `#![no_std]` crate.
    pub no_std: bool,
    /// The Rust path `#pragma cinrs crate` gave the `cinrs` facade crate,
    /// which the generated code names when it needs the runtime.
    pub crate_path: Option<String>,
    /// Every `#pragma pack` the unit wrote, as `(token index, alignment)`.
    ///
    /// A pragma is not a token, so the change is recorded against the position
    /// in [`Preprocessed::tokens`] it takes effect at; [`PackMap`] answers what
    /// was in force where a `struct` was defined.
    pub pack_events: Vec<(usize, Option<u32>)>,
    /// Every `#pragma GCC target` the unit wrote, as `(token index, names)`.
    ///
    /// Recorded the same way [`Preprocessed::pack_events`] is, and read the
    /// same way: [`TargetOptionMap`] answers what was in force where a
    /// function was defined.
    pub target_events: Vec<(usize, Vec<(String, SourceRange)>)>,
}

/// What `#pragma pack` asked for, at every point of the token list.
#[derive(Clone, Debug, Default)]
pub struct PackMap {
    events: Vec<(usize, Option<u32>)>,
}

/// What `#pragma GCC target` asked for, at every point of the token list.
///
/// GCC's directive applies to the functions *defined* after it, so the answer
/// depends on where in the stream the definition stands — exactly as
/// [`PackMap`]'s does for a `struct`. An empty list is the usual answer: the
/// map is empty unless the unit wrote the directive at all.
#[derive(Clone, Debug, Default)]
pub struct TargetOptionMap {
    events: Vec<(usize, Vec<(String, SourceRange)>)>,
}

impl TargetOptionMap {
    /// Builds the map from the preprocessor's events, which are in order.
    pub fn new(events: Vec<(usize, Vec<(String, SourceRange)>)>) -> Self {
        Self { events }
    }

    /// Whether any `#pragma GCC target` was written at all.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// The instruction sets in force at token `index`.
    pub fn at(&self, index: usize) -> &[(String, SourceRange)] {
        let at = self.events.partition_point(|(pos, _)| *pos <= index);
        self.events[..at]
            .last()
            .map_or(&[][..], |(_, names)| names.as_slice())
    }
}

impl PackMap {
    /// Builds the map from the preprocessor's events, which are in order.
    pub fn new(events: Vec<(usize, Option<u32>)>) -> Self {
        Self { events }
    }

    /// Whether any `#pragma pack` was written at all.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// The maximum member alignment in force at token `index`.
    pub fn at(&self, index: usize) -> Option<u32> {
        let at = self.events.partition_point(|(pos, _)| *pos <= index);
        self.events[..at].last().and_then(|(_, value)| *value)
    }
}

/// Runs the preprocessor over a lexed translation unit.
///
/// The returned list always ends with [`TokenKind::Eof`]. Problems the lexer
/// found are reported here: what is wrong with a token itself only when that
/// token survives, and what is wrong with the *text* — its spelling, and the
/// comments before it — as soon as the token is read. Neither is reported for a
/// group skipped by `#if 0`, whose text is never read at all and may hold
/// anything.
pub fn preprocess(
    tokens: &[lex::Token],
    ctx: &Context,
    options: &Options,
    diags: &mut Diagnostics,
) -> Preprocessed {
    let mut pp = Pp::new(tokens, ctx, options, diags);
    pp.run();
    Preprocessed {
        tokens: pp.out,
        expansions: pp.expansions,
        included: pp.included,
        user_headers: pp.user_headers,
        embedded_files: pp.embedded_files,
        link_libraries: pp.link_libraries,
        safe_functions: pp.safe_functions,
        export: pp.export,
        no_std: pp.no_std,
        crate_path: pp.crate_path,
        pack_events: pp.pack_events,
        target_events: pp.target_events,
    }
}

/// What [`scan_target_pragma`] found, which the preprocessor needs in order
/// not to report the same directive twice.
#[derive(Clone, Debug, Default)]
pub struct TargetPragmas {
    /// Where each `#pragma cinrs target` in the unit's own text begins — the
    /// offset of its `#`, which is where the preprocessor's own range for a
    /// directive starts too.
    pub at: Vec<Pos>,
    /// Whether one of them really chose the model. False when there was none,
    /// and false when there was one that has already been reported.
    pub applied: bool,
}

impl TargetPragmas {
    /// Whether the directive at `range` is one the scan read.
    fn scanned(&self, range: SourceRange) -> bool {
        self.at.contains(&range.start)
    }
}

/// Finds `#pragma cinrs target "<triple>"` in a freshly lexed unit and puts the
/// model it names into `options`.
///
/// This runs *before* the preprocessor, and has to. Everything the
/// preprocessor does with the model — the hundred-odd predefined macros, and
/// therefore which branch every `#if` and every bundled header takes — is
/// settled when it starts, so a pragma handled where it stands would arrive
/// too late to mean what it says. Reading it lexically is the price: the
/// directive is recognised by its shape, in the unit's own text, whether or
/// not a conditional group would later have skipped it, and a second one
/// naming a different triple is an error rather than a last-one-wins.
///
/// The preprocessor sees the same directives again during the real run —
/// `Pp::target_pragma` is where — which is what catches the two cases this
/// scan cannot serve: a `target` pragma the scan never read, because it is in
/// a header or came out of `_Pragma`, and one written after an `#include` or
/// an `#if` that the old model had already answered.
///
/// The caller must lex the text again when the model changed: how wide
/// `wchar_t` is decides what `L'…'` may hold.
pub fn scan_target_pragma(
    tokens: &[lex::Token],
    options: &mut Options,
    diags: &mut Diagnostics,
) -> (TargetPragmas, bool) {
    let mut found = TargetPragmas::default();
    let mut chosen: Option<(String, SourceRange)> = None;
    let mut failed = false;
    for (i, hash) in tokens.iter().enumerate() {
        // `# pragma cinrs target "…"`, the directive spelled out; the lexer
        // marks the token that begins a logical line.
        if !hash.bol || !hash.is_punct(Punct::Hash) {
            continue;
        }
        // Five tokens are enough for `pragma cinrs target "…"` and the one
        // trailing token the diagnostic complains about; a `#define` whose
        // replacement list runs to a hundred is not walked to the end just to
        // discover it is not this.
        let words: Vec<&lex::Token> = tokens[i + 1..]
            .iter()
            .take_while(|t| !t.bol && !matches!(t.kind, TokenKind::Eof))
            .take(5)
            .collect();
        let [pragma, cinrs, option, rest @ ..] = words.as_slice() else {
            continue;
        };
        if pragma.ident() != Some("pragma")
            || cinrs.ident() != Some("cinrs")
            || option.ident() != Some("target")
        {
            continue;
        }
        found.at.push(hash.range.start);
        let range = SourceRange::new(hash.range.start, option.range.end);
        let Some(triple) = target_pragma_triple(rest, range, diags) else {
            failed = true;
            continue;
        };
        match &chosen {
            // The same triple twice says the same thing twice, which is no
            // mistake at all.
            Some((first, _)) if *first == triple => {}
            Some((first, _)) => {
                diags.error(
                    range,
                    format!(
                        "this unit is already translated for '{first}' by an earlier \
                         #pragma cinrs target"
                    ),
                );
                failed = true;
            }
            None => chosen = Some((triple, range)),
        }
    }
    let Some((triple, range)) = chosen.filter(|_| !failed) else {
        return (found, false);
    };
    let source = TargetSource::Pragma(triple);
    match TargetModel::from_triple(source.triple().expect("Pragma carries its triple")) {
        Ok(model) => {
            let relex = options.target != model;
            options.target = model;
            options.target_source = source;
            found.applied = true;
            (found, relex)
        }
        Err(unknown) => {
            diags.error(range, unknown.message(&source));
            (found, false)
        }
    }
}

/// The one string literal `#pragma cinrs target` takes, as the pre-scan reads
/// it. The messages match [`Pp::pragma_string`]'s, since the same mistake must
/// read the same whichever pass notices it.
fn target_pragma_triple(
    rest: &[&lex::Token],
    range: SourceRange,
    diags: &mut Diagnostics,
) -> Option<String> {
    let Some(tok) = rest.first() else {
        diags.error(range, "#pragma cinrs target needs a string literal");
        return None;
    };
    let TokenKind::Str(lit) = &tok.kind else {
        diags.error(
            tok.range,
            format!(
                "#pragma cinrs target needs a string literal, found {}",
                tok.kind.describe()
            ),
        );
        return None;
    };
    let Some(bytes) = lit.as_bytes() else {
        diags.error(
            tok.range,
            "#pragma cinrs target does not take a wide string literal",
        );
        return None;
    };
    let value = String::from_utf8_lossy(&bytes).into_owned();
    if value.is_empty() {
        diags.error(tok.range, "#pragma cinrs target was given an empty string");
        return None;
    }
    if let Some(extra) = rest.get(1) {
        diags.error(
            extra.range,
            format!(
                "unexpected {} after #pragma cinrs target",
                extra.kind.describe()
            ),
        );
    }
    Some(value)
}

// ---------------------------------------------------------------------------
// the machine
// ---------------------------------------------------------------------------

/// One `#if` / `#ifdef` / `#ifndef` group.
struct Cond {
    /// Where the directive that opened the group is.
    range: SourceRange,
    /// Whether the enclosing group was itself being processed.
    outer_active: bool,
    /// Whether a branch has already been taken.
    taken: bool,
    /// Whether the branch now open is being processed.
    active: bool,
    /// Whether `#else` has been seen.
    seen_else: bool,
}

/// What one `#line` — or one GCC line marker — did to a file's numbering.
///
/// See [`Pp::line_directive`]. Only `__LINE__` and `__FILE__` are affected:
/// a diagnostic still points at the token that was really written, which is the
/// whole point of this crate.
struct LineDirective {
    /// The zero-based index of the *physical* line the directive is written on.
    at: usize,
    /// The number the next physical line is given.
    line: usize,
    /// What `__FILE__` says from that line on: the name the directive gave, or
    /// the one in force when it was written.
    name: String,
}

/// One file the preprocessor has read, kept for as long as positions inside it
/// can still be reported.
struct FileEntry {
    /// The text, which `#error` and `#include` read back verbatim.
    text: String,
    /// The global offset of its first byte.
    base: Pos,
    /// File-local byte offsets at which each line starts.
    line_starts: Vec<u32>,
    /// The line of the enclosing `.rs` file its own line 1 sits on; 1 for a
    /// header, which counts its own lines.
    first_line: usize,
    /// What `__FILE__` says inside it.
    name: String,
    /// The `#line` directives it has executed so far, in the order they were
    /// reached — which is the order of their positions, since a file is only
    /// ever read forwards.
    lines: Vec<LineDirective>,
}

impl FileEntry {
    fn new(text: String, base: Pos, first_line: usize, name: String) -> Self {
        let mut line_starts = vec![0u32];
        for (i, b) in text.bytes().enumerate() {
            if b == b'\n' {
                line_starts.push(i as u32 + 1);
            }
        }
        Self {
            text,
            base,
            line_starts,
            first_line: first_line.max(1),
            name,
            lines: Vec::new(),
        }
    }

    /// The zero-based index of the physical line `local` sits on.
    fn physical_line(&self, local: Pos) -> usize {
        self.line_starts
            .partition_point(|start| *start <= local)
            .saturating_sub(1)
    }

    /// The `#line` in force on physical line `index`, if there is one.
    ///
    /// A directive takes effect on the line *after* itself, so its own line
    /// still counts the way the one before it did.
    fn directive_for(&self, index: usize) -> Option<&LineDirective> {
        let after = self.lines.partition_point(|d| d.at < index);
        self.lines[..after].last()
    }

    /// The line `local` sits on, counted the way `__LINE__` counts.
    fn line_of(&self, local: Pos) -> usize {
        let index = self.physical_line(local);
        match self.directive_for(index) {
            // The directive named the line after itself; every line after that
            // one counts up from there.
            Some(d) => d.line + (index - d.at - 1),
            None => self.first_line + index,
        }
    }

    /// The name `__FILE__` reports for `local`.
    fn name_of(&self, local: Pos) -> &str {
        match self.directive_for(self.physical_line(local)) {
            Some(d) => &d.name,
            None => &self.name,
        }
    }
}

/// A file that is open: being read right now, or waiting for the `#include`
/// inside it to finish.
struct OpenFile {
    /// The whole file, lexed once.
    input: Vec<PTok>,
    /// Where in `input` the next unread token is.
    pos: usize,
    /// Where an `#include "…"` written in it looks first.
    origin: include::Origin,
    /// The search entry it was found under, which is where an `#include_next`
    /// written in it goes on *after*. `None` for the unit's own text and for a
    /// header no search found.
    found_in: Option<include::Entry>,
    /// What identifies it for `#pragma once` and the include-guard
    /// optimisation: its canonical path, or the name of a bundled header.
    key: String,
    /// How many conditional groups were open when it was entered, so that one
    /// it leaves unterminated is reported against it rather than leaking into
    /// the file that included it.
    cond_base: usize,
    /// Which set of headers this file belongs to, for [`Pp::define`]'s one rule
    /// about a macro two of them both define.
    site: DefSite,
}

/// Which set of headers a `#define` was written in.
///
/// It matters for exactly one thing: a macro that a bundled header and one of
/// the platform's own *both* define. The two describe the same C library, so
/// where they disagree it is a disagreement about spelling rather than about
/// the platform — glibc writes `CLOCKS_PER_SEC` as `((__clock_t) 1000000)` and
/// the bundled `<time.h>` writes `1000000` — and the platform's own copy is the
/// authoritative one. See [`Pp::define`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DefSite {
    /// The translation unit itself, or a header the program supplied.
    Program,
    /// One of the [bundled headers](include::BUNDLED).
    Bundled,
    /// One of the platform's own headers.
    Platform,
}

impl DefSite {
    /// Which of the two definitions of one macro to keep, when a bundled header
    /// and a platform header disagree about it. `None` when this is not that
    /// situation and the disagreement is a real one.
    fn resolves(previous: Self, next: Self) -> Option<Self> {
        match (previous, next) {
            (DefSite::Bundled, DefSite::Platform) | (DefSite::Platform, DefSite::Bundled) => {
                Some(DefSite::Platform)
            }
            _ => None,
        }
    }
}

struct Pp<'a> {
    /// Every file read so far, in the order they were opened.
    files: Vec<FileEntry>,
    /// The files being read, outermost first.
    open: Vec<OpenFile>,
    /// Tokens produced by macro replacement, innermost last.
    pending: Vec<PTok>,
    /// The padding waiting for the next token read (see [`Lead`]).
    carry: Option<Lead>,
    out: Vec<Token>,
    macros: HashMap<String, Arc<MacroDef>>,
    conds: Vec<Cond>,
    diags: &'a mut Diagnostics,
    expansions: Expansions,
    /// Lexer problems already reported, so that a macro used twice does not
    /// report the same bad token in its body twice.
    reported: HashSet<(Pos, Pos, String)>,
    /// The global offset of the root file, where anything with no position of
    /// its own is reported.
    base: Pos,
    lex_options: LexOptions,
    /// How a construct of a newer revision is gated, and whether the plain GNU
    /// spellings are on.
    gating: Gating,
    depth: u32,
    /// Tokens still allowed to come out of macro replacement.
    budget: usize,
    /// Set once the budget ran out; stops all further replacement.
    aborted: bool,
    // -- `#include` ---------------------------------------------------------
    /// Where the next included file's text is placed.
    next_base: Pos,
    /// The included files, for the caller's source map.
    included: Vec<IncludedFile>,
    /// The directories headers are looked for in.
    search: include::SearchPaths,
    /// The files `#pragma once` has closed for good.
    once: HashSet<String>,
    /// The stacks `#pragma push_macro("X")` pushed, by macro name.
    macro_stacks: HashMap<String, Vec<Option<Arc<MacroDef>>>>,
    /// The identifiers `#pragma GCC poison` made unusable.
    poisoned: HashSet<String>,
    /// The next value `__COUNTER__` expands to.
    counter: u64,
    /// The member alignment `#pragma pack` is currently asking for.
    pack: Option<u32>,
    /// What `#pragma pack(push)` saved.
    pack_stack: Vec<Option<u32>>,
    /// Every change of that value, by the index in `out` it takes effect at.
    pack_events: Vec<(usize, Option<u32>)>,
    /// The instruction sets `#pragma GCC target` is currently asking for, in
    /// GCC's spelling and with the range of the directive that named each.
    target_features: Vec<(String, SourceRange)>,
    /// What `#pragma GCC push_options` saved.
    target_stack: Vec<Vec<(String, SourceRange)>>,
    /// Every change of that list, by the index in `out` it takes effect at.
    target_events: Vec<(usize, Vec<(String, SourceRange)>)>,
    /// The name of the outermost file, which `__BASE_FILE__` reports.
    base_file: String,
    /// The include guard of a file that has one: its name, and the macro that
    /// makes reading it again pointless.
    guards: HashMap<String, String>,
    /// The absolute paths of the user headers that were read.
    user_headers: Vec<std::path::PathBuf>,
    /// The absolute paths of the resources `#embed` read.
    embedded_files: Vec<std::path::PathBuf>,
    /// The libraries `#pragma cinrs link` asked for.
    link_libraries: Vec<String>,
    /// The functions `#pragma cinrs safe` named.
    safe_functions: Vec<SafeName>,
    /// Set by `#pragma cinrs export`.
    export: bool,
    /// Set by `#pragma cinrs no_std`.
    no_std: bool,
    /// The Rust path `#pragma cinrs crate` gave the facade crate.
    crate_path: Option<String>,
    /// Where the data model in force came from, which is what a
    /// `#pragma cinrs target` the scan never read is reported against.
    target_source: TargetSource,
    /// The data model in force, which is what the platform's own include
    /// directories are chosen from — and refused for, on a cross build.
    target: crate::target::TargetModel,
    /// The `target` pragmas [`scan_target_pragma`] already dealt with.
    target_pragmas: TargetPragmas,
    /// Whether anything has yet been decided *by* the data model: a header
    /// opened, or an `#if` evaluated. A `#pragma cinrs target` after that
    /// point cannot mean what it says, so it is reported.
    model_observed: bool,
}

impl<'a> Pp<'a> {
    fn new(
        tokens: &[lex::Token],
        ctx: &'a Context,
        options: &Options,
        diags: &'a mut Diagnostics,
    ) -> Self {
        let root = FileEntry::new(
            ctx.text.clone(),
            ctx.base,
            ctx.first_line,
            ctx.file_name.clone(),
        );
        let mut input: Vec<PTok> = tokens.iter().map(PTok::from_lexed).collect();
        if input.is_empty() {
            input.push(eof_token(ctx.base));
        }
        let mut pp = Pp {
            files: vec![root],
            open: vec![OpenFile {
                input,
                pos: 0,
                origin: match &ctx.dir {
                    Some(dir) => include::Origin::Dir(dir.clone()),
                    None => include::Origin::Unknown,
                },
                found_in: None,
                key: ctx.file_name.clone(),
                cond_base: 0,
                site: DefSite::Program,
            }],
            pending: Vec::new(),
            carry: None,
            out: Vec::new(),
            macros: HashMap::new(),
            conds: Vec::new(),
            diags,
            expansions: Expansions::default(),
            reported: HashSet::new(),
            base: ctx.base,
            lex_options: options.into(),
            gating: options.gating(),
            depth: 0,
            budget: MAX_EXPANDED_TOKENS,
            aborted: false,
            next_base: ctx.next_base,
            included: Vec::new(),
            search: include::SearchPaths::new(&options.include_paths),
            once: HashSet::new(),
            macro_stacks: HashMap::new(),
            poisoned: HashSet::new(),
            counter: 0,
            pack: None,
            pack_stack: Vec::new(),
            pack_events: Vec::new(),
            target_features: Vec::new(),
            target_stack: Vec::new(),
            target_events: Vec::new(),
            base_file: ctx.file_name.clone(),
            guards: HashMap::new(),
            user_headers: Vec::new(),
            embedded_files: Vec::new(),
            link_libraries: Vec::new(),
            safe_functions: Vec::new(),
            export: false,
            no_std: false,
            crate_path: None,
            target_source: options.target_source.clone(),
            target: options.target,
            target_pragmas: ctx.target_pragmas.clone(),
            model_observed: false,
        };
        pp.define_predefined(options);
        // The crate-wide switch, which `#pragma cinrs system_include` in the
        // unit turns on again with the mode it wants. Reported against the
        // whole unit, there being nothing in the C to point at — the same
        // place a bad `CINRS_TARGET` is reported.
        if options.system_include.is_on() {
            let range = SourceRange::new(ctx.base, ctx.base + ctx.text.len() as Pos);
            pp.enable_system_include(options.system_include, range);
        }
        pp
    }

    // -- reading ------------------------------------------------------------

    /// The file being read.
    fn cur(&self) -> &OpenFile {
        self.open
            .last()
            .expect("the root file is only closed when the run ends")
    }

    fn cur_mut(&mut self) -> &mut OpenFile {
        self.open
            .last_mut()
            .expect("the root file is only closed when the run ends")
    }

    /// The file's next token, which is its end-of-file token once it has run
    /// out.
    fn ahead(&self) -> &PTok {
        let file = self.cur();
        &file.input[file.pos]
    }

    /// The next token without consuming it, or `None` when replacement output
    /// has run out and the caller may not read the file itself.
    fn peek(&self, allow_input: bool) -> Option<&PTok> {
        if let Some(t) = self.pending.last() {
            return Some(t);
        }
        allow_input.then(|| self.ahead())
    }

    /// The next token, consumed.
    ///
    /// Reading never crosses a file boundary: at the end of an `#include`d
    /// file this keeps answering with that file's end-of-file token, so that a
    /// macro invocation left unfinished there is reported instead of quietly
    /// swallowing what follows the directive. [`Pp::run`] is what closes a
    /// file.
    ///
    /// Reading a token out of the file is also where what is wrong with its
    /// *text* is reported, whatever becomes of the token itself: the comment
    /// before it was written, and an ill-formed universal character name is
    /// ill-formed where it stands (6.4.3p2), so neither waits to see whether
    /// the token reaches the output, is the name of a macro that replaces it,
    /// or is an argument the macro drops. Every UCN in Clang's own
    /// `C99/n717.c` is written as the argument of a macro that expands to
    /// nothing, and each one still has to be diagnosed. What is wrong with the
    /// *token* waits: a stray `\` or `$` is a preprocessing token like any
    /// other until something tries to parse it (6.4p3). Nothing here runs over
    /// a skipped group — [`Pp::run`] discards those tokens without reading
    /// them — and `Pp::reported` keeps a token that is read and then also
    /// emitted, or read twice, to one diagnostic.
    fn bump(&mut self, allow_input: bool) -> Option<PTok> {
        if let Some(t) = self.pending.pop() {
            return Some(self.arrive(t));
        }
        if !allow_input {
            return None;
        }
        let tok = self.ahead().clone();
        if !tok.is_eof() {
            self.cur_mut().pos += 1;
        }
        self.report_lexical_errors(&tok);
        Some(self.arrive(tok))
    }

    /// A token as it is read: the padding before it is applied, and the
    /// padding after it waits for the next one.
    fn arrive(&mut self, mut tok: PTok) -> PTok {
        if let Some(lead) = self.carry.take() {
            lead.apply(&mut tok);
        }
        self.carry = tok.trail.take();
        tok
    }

    /// Whether the file's next token opens a directive.
    fn at_directive(&self) -> bool {
        let tok = self.ahead();
        tok.bol && tok.is_punct(Punct::Hash)
    }

    fn skipping(&self) -> bool {
        self.conds.last().is_some_and(|c| !c.active)
    }

    // -- the main loop ------------------------------------------------------

    fn run(&mut self) {
        loop {
            // Directives, the end of a file and skipped groups are all
            // properties of the *file*, so they are only looked at once
            // everything macro replacement produced has been dealt with.
            if self.pending.is_empty() {
                if self.ahead().is_eof() {
                    if self.open.len() > 1 {
                        self.close_file();
                        continue;
                    }
                    self.finish();
                    return;
                }
                if self.at_directive() {
                    self.directive();
                    continue;
                }
                if self.skipping() {
                    // A skipped group is not even lexically C: discard its
                    // tokens without looking at them, and without reporting
                    // anything.
                    self.cur_mut().pos += 1;
                    continue;
                }
            }
            let Some(tok) = self.bump(true) else {
                unreachable!("reading the file is always allowed here");
            };
            if tok.is_eof() {
                // Handled above; nothing puts an end-of-file token into the
                // replacement output.
                continue;
            }
            if tok.name().is_some() && self.try_expand(&tok, true) {
                continue;
            }
            if tok.name() == Some(PRAGMA_OPERATOR) && self.pragma_operator(&tok) {
                continue;
            }
            self.emit(tok);
        }
    }

    /// C99's `_Pragma ( string-literal )`, which is a pragma written where an
    /// expression could go — and therefore the only way a *macro* can produce
    /// one.
    ///
    /// Returns whether it really was one: the name on its own is an ordinary
    /// identifier.
    ///
    /// Its operand is macro-replaced first, as GCC and Clang do and as the
    /// rescan of a replacement list containing `_Pragma` would anyway: that is
    /// what makes `_Pragma(STRINGIFY(GCC target(T)))` — CRoaring's and
    /// simdjson's way of opening a target region from a macro — a pragma. The
    /// `(` may come out of a macro too. When the operand is not one string
    /// literal, the whole parenthesised operand is consumed with the one
    /// error, so none of it reaches the parser.
    fn pragma_operator(&mut self, tok: &PTok) -> bool {
        if !self
            .peek_expanded()
            .is_some_and(|t| t.is_punct(Punct::LParen))
        {
            return false;
        }
        self.require_standard(Standard::C99, "'_Pragma'", tok.range);
        self.bump(true);
        let mut operand = Vec::new();
        let mut depth = 0usize;
        let mut closed = false;
        loop {
            if self.peek_expanded().is_none_or(PTok::is_eof)
                || (self.pending.is_empty() && self.at_directive())
            {
                // The operand never closes before the file (or the next
                // directive) does; neither is swallowed.
                break;
            }
            let Some(t) = self.bump(true) else {
                break;
            };
            if t.is_punct(Punct::LParen) {
                depth += 1;
            } else if t.is_punct(Punct::RParen) {
                if depth == 0 {
                    closed = true;
                    break;
                }
                depth -= 1;
            }
            operand.push(t);
        }
        if !closed {
            self.diags.error(tok.range, "missing ')' after '_Pragma'");
            return true;
        }
        let text = match operand.as_slice() {
            [
                PTok {
                    kind: TokenKind::Str(lit),
                    ..
                },
            ] => destringize(&lit.text),
            _ => {
                self.diags
                    .error(tok.range, "'_Pragma' takes one string literal");
                return true;
            }
        };
        // The destringized text is a directive line without its `#pragma`, so
        // it is lexed and handed to the same code the directive uses. The
        // tokens are placed at the `_Pragma` itself, which is where a
        // diagnostic about them belongs.
        let tokens: Vec<PTok> = lex::lex_text(&text, tok.range.start, &self.lex_options)
            .iter()
            .filter(|t| !matches!(t.kind, TokenKind::Eof))
            .map(PTok::from_lexed)
            .collect();
        self.pragma(&tokens, tok.range);
        true
    }

    /// The next token after macro replacement, left unconsumed: names that
    /// invoke a macro are replaced (their replacement goes back onto the
    /// stream, exactly as the main loop's rescan would put it) until a token
    /// that is not one comes up. Neither the end of the file nor a directive
    /// line is read past.
    fn peek_expanded(&mut self) -> Option<&PTok> {
        loop {
            if self.pending.is_empty() && (self.ahead().is_eof() || self.at_directive()) {
                return self.peek(true);
            }
            let mut tok = self.bump(true)?;
            if tok.name().is_some() && self.try_expand(&tok, true) {
                continue;
            }
            // Unread: the padding after it goes back with it.
            tok.trail = self.carry.take();
            self.pending.push(tok);
            return self.peek(true);
        }
    }

    /// Leaves an `#include`d file, reporting the conditionals it left open.
    fn close_file(&mut self) {
        // A header's own end-of-file token goes nowhere — only the unit's
        // reaches the output — so this is the last chance to say what the text
        // at the end of it did wrong. An `#include`d file that ends in a `//`
        // comment is the case: there is no token after it to carry the
        // diagnostic anywhere else.
        if !self.skipping() {
            let eof = self.ahead().clone();
            self.report_lexical_errors(&eof);
        }
        let base = self.cur().cond_base;
        for cond in self.conds.drain(base..).collect::<Vec<_>>() {
            self.diags
                .error(cond.range, "unterminated conditional directive");
        }
        self.open.pop();
    }

    /// Reports what never closed and emits the end-of-input token.
    fn finish(&mut self) {
        // A conditional the unit never closed is an error, and the group it
        // opened is still a skipped one: what the lexer found in the text it
        // swallowed is not reported, exactly as inside a closed `#if 0`.
        let skipped = self.skipping();
        for cond in std::mem::take(&mut self.conds) {
            self.diags
                .error(cond.range, "unterminated conditional directive");
        }
        let file = self.cur();
        let mut eof = file.input[file.input.len() - 1].clone();
        if skipped {
            eof.errors.clear();
        }
        self.emit(eof);
    }

    fn emit(&mut self, mut tok: PTok) {
        self.report_errors(&tok);
        if matches!(tok.kind, TokenKind::Error(_)) {
            // Not a C token at all: reported above, and dropped so that the
            // parser never has to have an opinion about it.
            return;
        }
        // The GNU keywords are recognised *here*, on the way to the parser,
        // rather than in the lexer: until this point `__attribute__` is an
        // ordinary identifier, so `#define __attribute__(x)` — which every
        // portability header writes — defines and expands a macro of that
        // name, and `#ifdef __restrict` answers about the name that was
        // written.
        if let TokenKind::Ident(name) = &tok.kind {
            if self.poisoned.contains(name) {
                let range = tok.range;
                let name = name.clone();
                self.diags.error(
                    range,
                    format!("attempt to use the poisoned identifier '{name}'"),
                );
            }
            if let Some(keyword) = gnu_keyword(name, self.gating.dialect) {
                tok.kind = TokenKind::Keyword(keyword);
            }
        }
        self.out.push(Token {
            kind: tok.kind,
            range: tok.range,
            origin: tok.origin,
        });
    }

    /// Reports the problems the lexer attached to a token that survived.
    fn report_errors(&mut self, tok: &PTok) {
        self.report_token_diags(tok, false);
    }

    /// Reports only what is wrong with the *text* a token was formed from — its
    /// spelling, and the comments before it — which stands whether or not the
    /// token goes anywhere; see [`Diagnostic::lexical`].
    fn report_lexical_errors(&mut self, tok: &PTok) {
        self.report_token_diags(tok, true);
    }

    fn report_token_diags(&mut self, tok: &PTok, lexical_only: bool) {
        for diag in &tok.errors {
            if lexical_only && !diag.lexical {
                continue;
            }
            let key = (diag.range.start, diag.range.end, diag.message.clone());
            if self.reported.insert(key) {
                self.diags.push(diag.clone());
            }
        }
    }

    /// The file a position is in.
    ///
    /// Every file ever opened stays in `files`, and their bases only ever
    /// increase, so a position identifies one of them even after it has been
    /// left — which is what a diagnostic about a macro defined in a header
    /// that was closed long ago needs.
    fn file_at(&self, pos: Pos) -> &FileEntry {
        &self.files[self.file_index(pos)]
    }

    /// The index in `files` of the file a position is in.
    fn file_index(&self, pos: Pos) -> usize {
        self.files
            .partition_point(|f| f.base <= pos)
            .saturating_sub(1)
    }

    /// A position's offset within its own file.
    fn local_pos(file: &FileEntry, pos: Pos) -> Pos {
        pos.saturating_sub(file.base).min(file.text.len() as Pos)
    }

    /// The line number `__LINE__` reports for a position.
    fn line_of(&self, pos: Pos) -> usize {
        let file = self.file_at(pos);
        file.line_of(Self::local_pos(file, pos))
    }

    /// The name `__FILE__` reports for a position.
    fn file_name_of(&self, pos: Pos) -> &str {
        let file = self.file_at(pos);
        file.name_of(Self::local_pos(file, pos))
    }

    /// The verbatim source text between two positions.
    fn raw_text(&self, from: Pos, to: Pos) -> &str {
        let file = self.file_at(from);
        let start = from.saturating_sub(file.base) as usize;
        let end = to.saturating_sub(file.base) as usize;
        file.text.get(start..end).unwrap_or("")
    }
}

/// The GNU keyword an identifier spells, if it spells one.
///
/// Everything with a leading double underscore is available in every entry
/// point, exactly as it is in GCC's `-std=c99`: the names are reserved, so
/// nothing a program may legally call its own is taken away. The two *plain*
/// spellings GCC keeps for its `gnu*` modes — `typeof` and `asm` — need a GNU
/// dialect, and `typeof` is already a keyword of its own in `c23!`.
fn gnu_keyword(name: &str, dialect: Dialect) -> Option<Keyword> {
    let keyword = match name {
        "__inline" | "__inline__" => Keyword::InlineGnu,
        "__const" | "__const__" => Keyword::Const,
        "__signed" | "__signed__" => Keyword::Signed,
        "__volatile" | "__volatile__" => Keyword::Volatile,
        "__restrict" | "__restrict__" => Keyword::RestrictGnu,
        "__complex__" | "__complex" => Keyword::Complex,
        "__attribute" | "__attribute__" => Keyword::Attribute,
        "__extension__" => Keyword::Extension,
        "__alignof" | "__alignof__" => Keyword::AlignofGnu,
        "__typeof" | "__typeof__" => Keyword::TypeofGnu,
        "__typeof_unqual__" | "__typeof_unqual" => Keyword::TypeofUnqualGnu,
        "__asm" | "__asm__" => Keyword::Asm,
        "__label__" => Keyword::Label,
        "__auto_type" => Keyword::AutoType,
        "__thread" => Keyword::ThreadGnu,
        "__int128" => Keyword::Int128,
        "__real" | "__real__" => Keyword::RealGnu,
        "__imag" | "__imag__" => Keyword::ImagGnu,
        "asm" if dialect.is_gnu() => Keyword::Asm,
        "typeof" if dialect.is_gnu() => Keyword::TypeofGnu,
        _ => return None,
    };
    Some(keyword)
}

/// The end-of-file token an empty file still has to produce.
fn eof_token(base: Pos) -> PTok {
    PTok {
        kind: TokenKind::Eof,
        range: SourceRange::at(base),
        bol: true,
        space: true,
        pad: None,
        trail: None,
        origin: Origin::Source,
        hide: HideSet::default(),
        errors: Vec::new(),
    }
}

// ---------------------------------------------------------------------------
// macro replacement
// ---------------------------------------------------------------------------

/// The arguments of one function-like invocation.
struct Args {
    /// The arguments as written.
    raw: Vec<Vec<PTok>>,
    /// The arguments after full macro replacement, computed on demand: an
    /// argument used only by `#` or `##` must never be expanded, and expanding
    /// an unused one could report an error the program does not contain.
    /// The padding its expansion ended with comes with it.
    expanded: Vec<Option<(Vec<PTok>, Option<Lead>)>>,
}

impl Args {
    fn new(raw: Vec<Vec<PTok>>) -> Self {
        Self {
            expanded: vec![None; raw.len()],
            raw,
        }
    }

    fn get(&self, index: usize) -> &[PTok] {
        self.raw.get(index).map_or(&[], Vec::as_slice)
    }
}

/// One element of a replacement list under construction.
///
/// The placemarker is the standard's own device (6.10.3.3p2): it stands where
/// an empty argument was, so that `a ## b` with an empty `b` pastes into `a`
/// rather than into whatever came next. It keeps the white-space status of
/// the parameter it replaced, which spaces whatever it is pasted to; and
/// padding is what an argument that expanded to nothing leaves (see
/// [`Lead`]).
enum Piece {
    Tok(PTok),
    Placemarker { space: bool, pad: Option<bool> },
    Padding(Lead),
}

impl Pp<'_> {
    /// Replaces `tok` if it invokes a macro, pushing the result back onto the
    /// stream so that it is rescanned.
    ///
    /// `allow_input` says whether the `(` of a function-like invocation may be
    /// read from the file. It is false while an argument is being
    /// pre-expanded, where the standard says the argument behaves as if it
    /// were the whole rest of the file.
    fn try_expand(&mut self, tok: &PTok, allow_input: bool) -> bool {
        if self.aborted {
            return false;
        }
        let Some(name) = tok.name() else {
            return false;
        };
        if tok.hide.contains(name) {
            // Painted blue: the token was produced by this very macro, and the
            // hide set travels with it, so it stays unreplaceable for good.
            return false;
        }
        let Some(def) = self.macros.get(name).cloned() else {
            return false;
        };
        let name = name.to_owned();

        if let Some(builtin) = def.builtin {
            let value = self.builtin_token(builtin, tok, &def, &name);
            let after = self.carry.take();
            self.push_pending(vec![value], tok, None, after);
            return true;
        }

        let Some(params) = &def.params else {
            // The padding that followed the name follows its replacement.
            let after = self.carry.take();
            let hide = tok.hide.add(&name);
            let exp = self.expansion_of(&name, tok.range, &def, tok);
            let mut args = Args::new(Vec::new());
            let (body, rest) = self.subst(&def, &mut args, &hide, tok.range, &exp);
            self.push_pending(body, tok, rest, after);
            if !def.predefined {
                self.expansions.record(tok.range, &name, def.name_range);
            }
            return true;
        };

        // A function-like macro's name is only an invocation when the very
        // next token is `(`.
        if !self
            .peek(allow_input)
            .is_some_and(|t| t.is_punct(Punct::LParen))
        {
            return false;
        }
        let params = params.clone();
        self.bump(allow_input);

        let Some((mut raw, rparen)) = self.collect_args(&def, &params, tok.range, allow_input)
        else {
            return true;
        };
        // The padding before the `(` and inside the list is gone with them;
        // what followed the `)` follows the replacement.
        let after = self.carry.take();
        let invocation = tok.range.join(rparen.range);
        if !self.check_arity(&def, &params, raw.len(), &name, invocation) {
            return true;
        }
        if def.variadic {
            // C99 asks for one more argument than there are parameters; GCC
            // and everyone who writes `LOG("done")` disagree, so `...` is
            // allowed to match nothing and `__VA_ARGS__` is then empty.
            while raw.len() <= params.len() {
                raw.push(Vec::new());
            }
        }

        let hide = tok.hide.intersect(&rparen.hide).add(&name);
        let exp = self.expansion_of(&name, invocation, &def, tok);
        let mut args = Args::new(raw);
        let (body, rest) = self.subst(&def, &mut args, &hide, invocation, &exp);
        self.push_pending(body, tok, rest, after);
        if !def.predefined {
            self.expansions.record(invocation, &name, def.name_range);
        }
        true
    }

    fn expansion_of(
        &self,
        name: &str,
        invocation: SourceRange,
        def: &MacroDef,
        tok: &PTok,
    ) -> Arc<Expansion> {
        Arc::new(Expansion {
            name: name.to_owned(),
            invocation,
            definition: def.name_range,
            parent: tok.origin.expansion().cloned(),
        })
    }

    /// Pushes the replacement of `name` back onto the stream, innermost first.
    ///
    /// `rest` is the padding the replacement ended with and `after` the
    /// padding that followed the invocation (see [`Lead`]).
    fn push_pending(
        &mut self,
        mut toks: Vec<PTok>,
        name: &PTok,
        rest: Option<Lead>,
        after: Option<Lead>,
    ) {
        if self.budget < toks.len() {
            if !self.aborted {
                let range = toks.first().map_or(SourceRange::at(self.base), |t| t.range);
                self.diags
                    .error(range, "macro expansion produced too many tokens");
                self.aborted = true;
            }
            return;
        }
        self.budget -= toks.len();
        let Some(first) = toks.first_mut() else {
            // Nothing left but padding, for the token read next.
            let empty = Lead::of_empty(name.space, name.pad, rest);
            self.carry = Lead::join(Some(empty), after);
            return;
        };
        // The replacement stands where the invocation did, so it inherits
        // its spacing — and it can never open a directive.
        first.lead_with(name.space, name.pad);
        first.bol = false;
        let last = toks.last_mut().expect("not empty");
        last.trail = Lead::join(Lead::join(last.trail, rest), after);
        self.pending.extend(toks.into_iter().rev());
    }

    /// Collects a function-like invocation's arguments, returning them
    /// together with the `)` that closed the list.
    fn collect_args(
        &mut self,
        def: &MacroDef,
        params: &[String],
        name_range: SourceRange,
        allow_input: bool,
    ) -> Option<(Vec<Vec<PTok>>, PTok)> {
        let mut args: Vec<Vec<PTok>> = vec![Vec::new()];
        let mut depth = 0u32;
        loop {
            // Running out of tokens is the same failure whether the file ended
            // or the argument being pre-expanded did.
            let Some(mut tok) = self.bump(allow_input).filter(|t| !t.is_eof()) else {
                self.diags.error(
                    name_range,
                    "unterminated argument list of a function-like macro",
                );
                return None;
            };
            if tok.is_punct(Punct::LParen) {
                depth += 1;
            } else if tok.is_punct(Punct::RParen) {
                if depth == 0 {
                    // `f()` for a macro that takes nothing is no argument at
                    // all, rather than one empty one.
                    if !def.variadic && params.is_empty() && args.len() == 1 && args[0].is_empty() {
                        args.clear();
                    }
                    return Some((args, tok));
                }
                depth -= 1;
            } else if tok.is_punct(Punct::Comma)
                && depth == 0
                && (!def.variadic || args.len() <= params.len())
            {
                args.push(Vec::new());
                continue;
            }
            let arg = args.last_mut().expect("the argument list is never empty");
            if arg.is_empty() {
                // Padding in front of an argument is not part of it.
                tok.pad = None;
            }
            arg.push(tok);
        }
    }

    /// Checks the number of arguments against the parameter list, reporting a
    /// mismatch at the invocation and answering whether to go on.
    ///
    /// An invocation whose arity is wrong expands to nothing: the error has
    /// been reported, and substituting made-up arguments would only add
    /// syntax errors on top of it.
    fn check_arity(
        &mut self,
        def: &MacroDef,
        params: &[String],
        given: usize,
        name: &str,
        invocation: SourceRange,
    ) -> bool {
        let wanted = params.len();
        let ok = if def.variadic {
            given >= wanted
        } else {
            given == wanted
        };
        if ok {
            return true;
        }
        let message = if given < wanted {
            let least = if def.variadic { "at least " } else { "" };
            format!("macro '{name}' requires {least}{wanted} arguments, but only {given} given")
        } else {
            format!("macro '{name}' passed {given} arguments, but takes just {wanted}")
        };
        self.diags.push(
            Diagnostic::error(invocation, message)
                .with_note_at(def.name_range, format!("macro '{name}' defined")),
        );
        false
    }

    /// Builds a replacement list: the standard's `subst`, placemarkers and all.
    ///
    /// The padding the list ends with — an argument at its end that expanded
    /// to nothing — comes back beside it.
    fn subst(
        &mut self,
        def: &MacroDef,
        args: &mut Args,
        hide: &HideSet,
        invocation: SourceRange,
        exp: &Arc<Expansion>,
    ) -> (Vec<PTok>, Option<Lead>) {
        // `__VA_OPT__` is resolved first, so that everything below sees an
        // ordinary replacement list.
        let expanded;
        let body: &[PTok] = match expand_va_opt(def, args) {
            Some(tokens) => {
                expanded = tokens;
                &expanded
            }
            None => &def.body,
        };
        let mut pieces: Vec<Piece> = Vec::with_capacity(body.len());
        let mut i = 0;
        while i < body.len() {
            let tok = &body[i];

            // `# parameter` — stringification.
            if def.params.is_some()
                && tok.is_punct(Punct::Hash)
                && let Some(next) = body.get(i + 1)
                && let Some(index) = next.name().and_then(|n| def.param_index(n))
            {
                let kind = self.stringify(args.get(index));
                pieces.push(Piece::Tok(self.synthetic(kind, tok, invocation, exp)));
                i += 2;
                continue;
            }

            // GNU's comma elision, `printf(fmt, ## __VA_ARGS__)`: the `##`
            // between a comma and the variable arguments deletes the comma
            // when the invocation passed none, and pastes nothing when it
            // passed some. The arguments are still an operand of `##`, though,
            // so they go in *unexpanded* (6.10.3.3p2) and are replaced only on
            // the rescan: `E(S_, ONE)` with `E(f, ...) f(0, ## __VA_ARGS__)`
            // hands `S_` the tokens `0, ONE`, as in GCC and Clang.
            // `__VA_OPT__` is C23's way of saying the same thing.
            if tok.is_punct(Punct::Comma)
                && body.get(i + 1).is_some_and(|t| t.is_punct(Punct::HashHash))
                && let Some(index) = body
                    .get(i + 2)
                    .and_then(PTok::name)
                    .and_then(|n| def.param_index(n))
                && Some(index) == def.va_index()
            {
                let arg = args.get(index);
                if !arg.is_empty() {
                    let mut comma = tok.clone();
                    comma.range = invocation;
                    comma.origin = Origin::Expansion(exp.clone());
                    pieces.push(Piece::Tok(comma));
                    // The arguments keep their own spacing after the comma,
                    // as in GCC.
                    pieces.extend(arg.iter().cloned().map(Piece::Tok));
                }
                i += 3;
                continue;
            }

            // `## something` — pasting.
            if tok.is_punct(Punct::HashHash)
                && let Some(next) = body.get(i + 1)
            {
                let rhs = paste_operand(def, args, next);
                self.paste_pieces(&mut pieces, rhs, invocation, exp);
                i += 2;
                continue;
            }

            // A parameter: `##` on either side keeps it unexpanded.
            // Either way the argument's first token is spaced like the
            // parameter it replaces (6.10.3.2p2): in `(b)`, `V(1, 2)`'s ` 2`
            // comes out as `(2)`.
            if let Some(index) = tok.name().and_then(|n| def.param_index(n)) {
                let raw = body.get(i + 1).is_some_and(|t| t.is_punct(Punct::HashHash));
                if raw {
                    let mut arg = args.get(index).to_vec();
                    if let Some(first) = arg.first_mut() {
                        first.lead_with(tok.space, tok.pad);
                        pieces.extend(arg.into_iter().map(Piece::Tok));
                    } else {
                        pieces.push(Piece::Placemarker {
                            space: tok.space,
                            pad: tok.pad,
                        });
                    }
                } else {
                    let (arg, rest) = self.expanded_arg(args, index);
                    push_expanded(&mut pieces, arg, rest, Some(tok));
                }
                i += 1;
                continue;
            }

            let mut copy = tok.clone();
            // The replacement list was written in the `#define`, but it stands
            // where the invocation is, and that is where a diagnostic belongs.
            copy.range = invocation;
            copy.origin = Origin::Expansion(exp.clone());
            pieces.push(Piece::Tok(copy));
            i += 1;
        }

        let mut carry: Option<Lead> = None;
        let mut out = Vec::with_capacity(pieces.len());
        for piece in pieces {
            match piece {
                Piece::Tok(mut t) => {
                    if let Some(lead) = carry.take() {
                        lead.apply(&mut t);
                    }
                    t.hide = t.hide.union(hide);
                    out.push(t);
                }
                Piece::Placemarker { space, pad } => {
                    carry = Lead::join(carry, Some(Lead::of_empty(space, pad, None)));
                }
                Piece::Padding(lead) => carry = Lead::join(carry, Some(lead)),
            }
        }
        (out, carry)
    }

    /// Pastes the last piece built so far onto the first of `rhs`.
    fn paste_pieces(
        &mut self,
        pieces: &mut Vec<Piece>,
        mut rhs: Vec<Piece>,
        invocation: SourceRange,
        exp: &Arc<Expansion>,
    ) {
        if rhs.is_empty() {
            return;
        }
        let head = rhs.remove(0);
        let left = pieces.pop();
        let joined = match (left, head) {
            (None, head) => head,
            // What an empty left operand leaves is spaced like its parameter.
            (Some(Piece::Placemarker { space, pad }), Piece::Tok(mut head)) => {
                head.lead_with(space, pad);
                Piece::Tok(head)
            }
            (Some(left @ Piece::Placemarker { .. }), Piece::Placemarker { .. }) => left,
            (Some(left), Piece::Placemarker { .. }) => left,
            (Some(left @ Piece::Padding(_)), head) | (Some(left), head @ Piece::Padding(_)) => {
                // Not produced: an argument beside `##` is never expanded.
                pieces.push(left);
                head
            }
            (Some(Piece::Tok(l)), Piece::Tok(r)) => match self.paste(&l, &r, invocation) {
                Some(kind) => Piece::Tok(self.synthetic(kind, &l, invocation, exp)),
                None => {
                    // Already reported; keep both halves so that the rest of
                    // the expansion still makes some kind of sense.
                    pieces.push(Piece::Tok(l));
                    Piece::Tok(r)
                }
            },
        };
        pieces.push(joined);
        pieces.extend(rhs);
    }

    /// Concatenates two spellings and lexes the result.
    fn paste(&mut self, lhs: &PTok, rhs: &PTok, invocation: SourceRange) -> Option<TokenKind> {
        let text = format!("{}{}", lhs.spelling(), rhs.spelling());
        if text.is_empty() {
            return None;
        }
        let tokens = lex::lex_text(&text, 0, &self.lex_options);
        let valid = tokens.len() == 2
            && tokens[0].errors.is_empty()
            && !matches!(tokens[0].kind, TokenKind::Error(_))
            && tokens[0].range.end as usize == text.len();
        if !valid {
            self.diags.error(
                invocation,
                format!(
                    "pasting '{}' and '{}' does not give a valid token",
                    lhs.spelling(),
                    rhs.spelling()
                ),
            );
            return None;
        }
        Some(tokens[0].kind.clone())
    }

    /// A token that `#` or `##` made up, standing at the invocation.
    fn synthetic(
        &self,
        kind: TokenKind,
        like: &PTok,
        invocation: SourceRange,
        exp: &Arc<Expansion>,
    ) -> PTok {
        PTok {
            kind,
            range: invocation,
            bol: false,
            space: like.space,
            pad: like.pad,
            trail: None,
            origin: Origin::Expansion(exp.clone()),
            hide: like.hide.clone(),
            errors: Vec::new(),
        }
    }

    /// An argument after full macro replacement, computed once.
    fn expanded_arg(&mut self, args: &mut Args, index: usize) -> (Vec<PTok>, Option<Lead>) {
        if let Some(Some(done)) = args.expanded.get(index) {
            return done.clone();
        }
        let raw = args.get(index).to_vec();
        let done = self.expand_padded(raw);
        if let Some(slot) = args.expanded.get_mut(index) {
            *slot = Some(done.clone());
        }
        done
    }

    /// Fully replaces the macros in a self-contained token sequence.
    ///
    /// "Self-contained" is the point: 6.10.3.1 says an argument is expanded as
    /// if it were the whole rest of the file, so a function-like macro name at
    /// its end does not reach out for a `(` that follows the invocation.
    fn expand_sequence(&mut self, toks: Vec<PTok>) -> Vec<PTok> {
        self.expand_padded(toks).0
    }

    /// [`Pp::expand_sequence`], with the padding the sequence ended with.
    fn expand_padded(&mut self, toks: Vec<PTok>) -> (Vec<PTok>, Option<Lead>) {
        if toks.is_empty() {
            return (toks, None);
        }
        self.depth += 1;
        if self.depth > MAX_EXPANSION_DEPTH {
            self.depth -= 1;
            if !self.aborted {
                let range = toks[0].range;
                self.diags.error(range, "macro arguments nest too deeply");
                self.aborted = true;
            }
            return (toks, None);
        }
        let saved = std::mem::replace(&mut self.pending, toks.into_iter().rev().collect());
        let saved_carry = self.carry.take();
        let mut out = Vec::new();
        while let Some(tok) = self.pending.pop() {
            let tok = self.arrive(tok);
            if tok.name().is_some() && self.try_expand(&tok, false) {
                continue;
            }
            out.push(tok);
        }
        let rest = self.carry.take();
        self.pending = saved;
        self.carry = saved_carry;
        self.depth -= 1;
        (out, rest)
    }

    /// The token a built-in macro stands for at this use.
    fn builtin_token(&mut self, builtin: Builtin, tok: &PTok, def: &MacroDef, name: &str) -> PTok {
        let kind = match builtin {
            Builtin::Line => {
                let line = self.line_of(tok.range.start) as u128;
                TokenKind::Int(IntLit {
                    value: line,
                    base: NumBase::Decimal,
                    unsigned: false,
                    long: LongKind::None,
                    text: line.to_string(),
                })
            }
            // Both of these read the position of the *use*, which is what
            // makes `assert(x)` — whose `__FILE__` and `__LINE__` are written
            // in <assert.h> — report the line the assertion is on.
            Builtin::File => {
                let file = self.file_name_of(tok.range.start).to_owned();
                string_token_kind(&file)
            }
            Builtin::FileName => {
                let file = self.file_name_of(tok.range.start);
                let base = file
                    .rsplit_once(['/', '\\'])
                    .map_or(file, |(_, base)| base)
                    .to_owned();
                string_token_kind(&base)
            }
            Builtin::IncludeLevel => int_token_kind((self.open.len() - 1) as u128),
            Builtin::Counter => {
                let value = self.counter;
                self.counter += 1;
                int_token_kind(u128::from(value))
            }
        };
        let exp = self.expansion_of(name, tok.range, def, tok);
        PTok {
            kind,
            range: tok.range,
            bol: false,
            space: tok.space,
            pad: tok.pad,
            trail: None,
            origin: Origin::Expansion(exp),
            hide: tok.hide.add(name),
            errors: Vec::new(),
        }
    }
}

/// Wraps `text` in quotes and re-lexes it as a C string literal.
///
/// Falling back to the raw bytes cannot normally happen — everything this is
/// handed was built to be a string literal — but a decoded value has to come
/// out either way.
fn relex_string(text: String, options: &LexOptions) -> TokenKind {
    let tokens = lex::lex_text(&text, 0, options);
    if tokens.len() == 2
        && tokens[0].errors.is_empty()
        && matches!(tokens[0].kind, TokenKind::Str(_))
        && tokens[0].range.end as usize == text.len()
    {
        return tokens[0].kind.clone();
    }
    let inner = text.trim_matches('"');
    TokenKind::Str(StrLit {
        kind: StrKind::Narrow,
        values: inner.bytes().map(u32::from).collect(),
        text,
    })
}

impl Pp<'_> {
    /// Turns an argument into the string literal `#` makes of it (6.10.3.2).
    ///
    /// White space between tokens becomes exactly one space and leading and
    /// trailing white space is dropped. A `"` or `\` is escaped only where the
    /// standard says it is — *inside* a character constant or a string literal
    /// — which is why `str(: @\n)` comes out as `": @\n"`, backslash intact,
    /// while `str("a\0b")` comes out as `"\"a\\0b\""`.
    ///
    /// The text is then lexed back, so the literal's decoded value is whatever
    /// a C compiler would make of the literal that was written.
    fn stringify(&self, arg: &[PTok]) -> TokenKind {
        let mut text = String::from('"');
        for (i, tok) in arg.iter().enumerate() {
            if i > 0 && tok.space {
                text.push(' ');
            }
            let quoted = matches!(tok.kind, TokenKind::Char(_) | TokenKind::Str(_));
            for c in tok.spelling().chars() {
                if quoted && (c == '"' || c == '\\') {
                    text.push('\\');
                }
                text.push(c);
            }
        }
        text.push('"');
        relex_string(text, &self.lex_options)
    }
}

/// The pieces the right-hand operand of `##` contributes.
///
/// A parameter here is *never* macro-replaced first (6.10.3.3p1), and an empty
/// argument leaves a placemarker so that the paste happens to whatever is on
/// the other side rather than to whatever comes next.
fn paste_operand(def: &MacroDef, args: &Args, tok: &PTok) -> Vec<Piece> {
    let Some(index) = tok.name().and_then(|n| def.param_index(n)) else {
        return vec![Piece::Tok(tok.clone())];
    };
    let arg = args.get(index);
    if arg.is_empty() {
        // Its spacing never counts: pasted to a token, it vanishes, and
        // pasted to another placemarker, that one is kept.
        return vec![Piece::Placemarker {
            space: tok.space,
            pad: tok.pad,
        }];
    }
    arg.iter().cloned().map(Piece::Tok).collect()
}

/// Adds an argument after macro replacement to a replacement list under
/// construction, spaced like the parameter it replaces when there is one, and
/// followed by the padding its expansion ended with.
fn push_expanded(
    pieces: &mut Vec<Piece>,
    mut arg: Vec<PTok>,
    rest: Option<Lead>,
    param: Option<&PTok>,
) {
    let Some(first) = arg.first_mut() else {
        let lead = match param {
            Some(p) => Some(Lead::of_empty(p.space, p.pad, rest)),
            None => rest,
        };
        if let Some(lead) = lead {
            pieces.push(Piece::Padding(lead));
        }
        return;
    };
    if let Some(p) = param {
        first.lead_with(p.space, p.pad);
    }
    let last = arg.last_mut().expect("not empty");
    last.trail = Lead::join(last.trail, rest);
    pieces.extend(arg.into_iter().map(Piece::Tok));
}

/// The largest line number `#line` may name (C99 6.10.4p3).
const MAX_LINE_NUMBER: u64 = 2_147_483_647;

/// The value of a `digit-sequence` token, which is what `#line` takes.
///
/// A *digit sequence* is not an integer constant: `#line 010` is line ten, not
/// line eight, and `#line 0x10`, `#line 1u` and `#line 1.0` are none of the
/// three. Reading the spelling rather than the lexer's value is what says so.
/// A sequence too long for the range check below comes back saturated, so it is
/// reported as out of range rather than as not a number at all.
fn digit_sequence(kind: &TokenKind) -> Option<u64> {
    let TokenKind::Int(lit) = kind else {
        return None;
    };
    if lit.text.is_empty() || !lit.text.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    Some(lit.text.parse::<u64>().unwrap_or(u64::MAX))
}

/// Whether a `#line`'s operands are already one of the two forms 6.10.4 gives,
/// in which case they are used as they stand rather than macro-replaced first.
fn is_line_form(rest: &[PTok]) -> bool {
    let Some(first) = rest.first() else {
        return false;
    };
    if digit_sequence(&first.kind).is_none() {
        return false;
    }
    match rest.len() {
        1 => true,
        2 => matches!(&rest[1].kind, TokenKind::Str(lit) if lit.kind == StrKind::Narrow),
        _ => false,
    }
}

/// The decimal integer token a built-in macro expands to.
fn int_token_kind(value: u128) -> TokenKind {
    TokenKind::Int(IntLit {
        value,
        base: NumBase::Decimal,
        unsigned: false,
        long: LongKind::None,
        text: value.to_string(),
    })
}

/// The narrow string literal token a predefined macro expands to.
fn string_token_kind(value: &str) -> TokenKind {
    TokenKind::Str(StrLit {
        kind: StrKind::Narrow,
        values: value.bytes().map(u32::from).collect(),
        text: quote_c_string(value),
    })
}

/// Wraps `text` in quotes, escaping what a C string literal cannot hold plain.
fn quote_c_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        if c == '"' || c == '\\' {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

// ---------------------------------------------------------------------------
// directives
// ---------------------------------------------------------------------------

impl Pp<'_> {
    /// Executes the directive the file's next token opens.
    fn directive(&mut self) {
        // Padding is about the spacing of text lines; a directive ends it.
        self.carry = None;
        let hash = self.ahead().clone();
        self.cur_mut().pos += 1;
        let start = self.cur().pos;
        while !self.ahead().is_eof() && !self.ahead().bol {
            self.cur_mut().pos += 1;
        }
        let file = self.cur();
        let line: Vec<PTok> = file.input[start..file.pos].to_vec();
        // The line is read here rather than through `Pp::bump`, so what is
        // wrong with its text is reported here too — most of all on the `#`
        // itself, which carries the comments of the line above it and is the
        // one token of a directive that can never carry anything else. Only
        // when the group is being processed: the text before an `#endif` that
        // closes a skipped group is inside it, and a skipped group may hold
        // anything at all.
        if !self.skipping() {
            self.report_lexical_errors(&hash);
            for tok in &line {
                self.report_lexical_errors(tok);
            }
        }

        let Some(first) = line.first() else {
            // The null directive, which does nothing at all.
            return;
        };
        let range = hash.range.join(first.range);
        let Some(name) = first.name() else {
            if matches!(first.kind, TokenKind::Int(_)) {
                // A GCC line marker, `# 42 "file.h" 1 3 4`: `#line` without the
                // keyword, with flags saying whether the compiler is entering
                // or leaving a file. The numbering is all this needs from it.
                if !self.skipping() {
                    self.line_directive(&line, range, true);
                }
                return;
            }
            if !self.skipping() {
                self.diags.error(
                    range,
                    format!(
                        "invalid preprocessing directive after '#': {}",
                        first.kind.describe()
                    ),
                );
            }
            return;
        };
        let rest = &line[1..];

        match name {
            "if" => self.open_cond(range, |pp| pp.eval_condition(rest, range)),
            "ifdef" | "ifndef" => {
                let want = name == "ifdef";
                self.open_cond(range, |pp| {
                    pp.macro_name_operand(rest, range, name)
                        .is_some_and(|n| pp.is_defined(&n) == want)
                });
            }
            "elif" => self.elif(range, "elif", |pp| pp.eval_condition(rest, range)),
            // C23's `#elifdef` / `#elifndef`, which say what
            // `#elif defined(X)` says.
            "elifdef" | "elifndef" => {
                self.require_standard(Standard::C23, &format!("'#{name}'"), range);
                let want = name == "elifdef";
                self.elif(range, name, |pp| {
                    pp.macro_name_operand(rest, range, name)
                        .is_some_and(|n| pp.is_defined(&n) == want)
                });
            }
            "else" => self.else_(rest, range),
            "endif" => self.endif(range),
            _ if self.skipping() => {
                // Inside a skipped group only the conditionals are tracked;
                // everything else is text, and text is not our business.
            }
            "define" => self.define(rest, range),
            "undef" => self.undef(rest, range),
            "include" => self.include(&line, range, false),
            // GNU's `#include_next`: the same search, taken up again after the
            // directory the file writing it was found in. A platform's
            // `<limits.h>` ends with one to reach the next `limits.h` on the
            // path rather than itself.
            "include_next" => self.include(&line, range, true),
            "error" => {
                let text = self.directive_text(&line, 1);
                let message = if text.is_empty() {
                    "#error".to_owned()
                } else {
                    format!("#error {text}")
                };
                self.diags.error(range, message);
            }
            "warning" => {
                let text = self.directive_text(&line, 1);
                self.diags.warning(range, format!("#warning {text}"));
            }
            "pragma" => self.pragma(rest, range),
            "embed" => {
                self.require_standard(Standard::C23, "'#embed'", range);
                self.embed(rest, range);
            }
            "line" => self.line_directive(rest, range, false),
            // `#ident "string"` and `#sccs` put a string into a section of the
            // object file that nothing here has; GCC ignores them too when the
            // target has no such section.
            "ident" | "sccs" => {}
            other => {
                self.diags
                    .error(range, format!("invalid preprocessing directive #{other}"));
            }
        }
    }

    /// `#line` (C99 6.10.4), and GCC's `# 42 "file.h" 1 3 4` line marker.
    ///
    /// Both say the same thing: the line after the directive is line N, and
    /// `__FILE__` is the name that follows until the next directive or the end
    /// of the file. The marker's trailing flags — which of "entering",
    /// "returning", "system header" and "extern C" applies — describe an
    /// `#include` that has already happened elsewhere, so they are read and
    /// dropped.
    ///
    /// **Only `__LINE__` and `__FILE__` move.** A diagnostic still points at
    /// the token that was really written, in the file it was really written
    /// in, because that is the position the user can look at — the whole
    /// reason this crate maps every token back to a `proc_macro2::Span`. A
    /// `#line` in generated C therefore renumbers what the *program* observes
    /// without hiding where the compiler found it.
    fn line_directive(&mut self, rest: &[PTok], range: SourceRange, marker: bool) {
        let what = if marker { "line marker" } else { "#line" };
        // 6.10.4p5: a `#line` matching neither of the two forms the grammar
        // gives has its tokens macro-replaced first, and the result must then
        // match one of them. c-testsuite's `00152` is `#line line`, with
        // `line` a macro for 1000.
        let expanded: Vec<PTok>;
        let toks: &[PTok] = if marker || is_line_form(rest) {
            rest
        } else {
            expanded = self.expand_sequence(rest.to_vec());
            &expanded
        };

        let Some(first) = toks.first() else {
            self.diags
                .error(range, format!("'{what}' requires a line number"));
            return;
        };
        let Some(digits) = digit_sequence(&first.kind) else {
            self.diags.error(
                first.range,
                format!(
                    "'{what}' requires a decimal line number, found {}",
                    first.kind.describe()
                ),
            );
            return;
        };
        // 6.10.4p3: the digit sequence shall not specify zero, nor a number
        // greater than 2147483647.
        if digits == 0 || digits > MAX_LINE_NUMBER {
            self.diags.error(
                first.range,
                format!(
                    "the line number of '{what}' must be between 1 and {MAX_LINE_NUMBER}, \
                     not {digits}"
                ),
            );
            return;
        }

        let mut used = 1;
        let mut name = None;
        if let Some(tok) = toks.get(1) {
            match &tok.kind {
                TokenKind::Str(lit) if lit.kind == StrKind::Narrow => {
                    name = Some(
                        lit.values
                            .iter()
                            .map(|v| char::from_u32(*v).unwrap_or('\u{fffd}'))
                            .collect::<String>(),
                    );
                    used = 2;
                }
                _ if marker => {}
                _ => {
                    self.diags.error(
                        tok.range,
                        format!(
                            "the file name of '{what}' must be an ordinary string literal, \
                             found {}",
                            tok.kind.describe()
                        ),
                    );
                    return;
                }
            }
        }
        // A marker's flags are digits the compiler that wrote it understood;
        // anything else on a `#line` is what GCC calls "extra tokens at end of
        // directive" and, like GCC, warns about rather than refuses.
        if !marker && toks.len() > used {
            self.diags.warning(
                toks[used].range,
                format!("extra tokens at the end of '{what}'"),
            );
        }
        self.set_line(range.start, digits as usize, name);
    }

    /// Records what a `#line` did to the file it was written in.
    fn set_line(&mut self, pos: Pos, line: usize, name: Option<String>) {
        let index = self.file_index(pos);
        let local = Self::local_pos(&self.files[index], pos);
        let file = &mut self.files[index];
        let at = file.physical_line(local);
        // Without a name of its own the directive keeps whichever one is in
        // force, which may itself have come from an earlier `#line`.
        let name = match name {
            Some(name) => name,
            None => file.name_of(local).to_owned(),
        };
        // The list is searched by binary search, so it has to stay sorted. A
        // file is only ever read forwards, so this drops nothing in practice.
        while file.lines.last().is_some_and(|d| d.at >= at) {
            file.lines.pop();
        }
        file.lines.push(LineDirective { at, line, name });
    }

    /// The raw source text of a directive line from its `skip`-th token on.
    ///
    /// `#error` has to reproduce what was written rather than a rendering of
    /// the tokens, and `#include <stdio.h>` will need the same thing: a
    /// header name in angle brackets is not one token either.
    fn directive_text(&self, line: &[PTok], skip: usize) -> String {
        let Some(first) = line.get(skip) else {
            return String::new();
        };
        let last = line.last().unwrap_or(first);
        self.raw_text(first.range.start, last.range.end)
            .trim()
            .to_owned()
    }

    /// `#pragma`.
    ///
    /// Every pragma this implementation does not know is silently ignored,
    /// which is what 6.10.6 asks for — with one exception: a `#pragma cinrs`
    /// is addressed to *us*, so an option we do not know is a mistake worth
    /// reporting rather than a hint some other compiler might understand.
    ///
    /// The ones it does know configure the unit:
    ///
    /// ```c
    /// #pragma cinrs include_path "vendor/include"
    /// #pragma cinrs link "m"
    /// #pragma cinrs export
    /// #pragma cinrs safe gcd fact
    /// #pragma cinrs no_std
    /// #pragma cinrs crate "crate::vendor::cinrs"
    /// ```
    ///
    /// They are directives rather than macro arguments or attributes so that
    /// they read the same, and mean the same, in raw-token and in
    /// string-literal input.
    fn pragma(&mut self, rest: &[PTok], range: SourceRange) {
        match rest.first().and_then(PTok::name) {
            Some("once") => {
                let key = self.cur_key();
                self.once.insert(key);
            }
            Some("cinrs") => self.cinrs_pragma(&rest[1..], range),
            Some("pack") => self.pack_pragma(&rest[1..], range),
            Some("push_macro") => self.push_macro_pragma(&rest[1..], range, true),
            Some("pop_macro") => self.push_macro_pragma(&rest[1..], range, false),
            Some("GCC") => self.gcc_pragma(&rest[1..], range),
            // `#pragma message`, `#pragma region` / `#pragma endregion`,
            // `#pragma weak` and everything else are ignored, which 6.10.6 is
            // explicit about. `weak` is the one worth knowing about: it asks
            // for weak linkage, which stable Rust cannot express at all, so
            // ignoring it is the same answer `__attribute__((weak))` gets —
            // see `doc/gnu-extensions.md`.
            _ => {}
        }
    }

    /// `#pragma GCC …`.
    fn gcc_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        match rest.first().and_then(PTok::name) {
            // A program that poisons a name means it never to be written
            // again, and honouring that costs one lookup per identifier.
            Some("poison") => {
                for tok in &rest[1..] {
                    match tok.name() {
                        Some(name) => {
                            self.poisoned.insert(name.to_owned());
                        }
                        None => self.diags.error(
                            tok.range,
                            format!(
                                "'#pragma GCC poison' takes identifiers, found {}",
                                tok.kind.describe()
                            ),
                        ),
                    }
                }
            }
            Some("error") => {
                let text = self.pragma_message(&rest[1..]);
                self.diags.error(range, format!("#pragma GCC error {text}"));
            }
            Some("warning") => {
                let text = self.pragma_message(&rest[1..]);
                self.diags
                    .warning(range, format!("#pragma GCC warning {text}"));
            }
            // `#pragma GCC target("avx2")` asks for an instruction set for
            // every function *defined* after it, which is the same request
            // `__attribute__((target("avx2")))` makes on one function.
            Some("target") => self.target_options_pragma(&rest[1..], range),
            // `push_options` saves the set in force and `pop_options` puts it
            // back; `reset_options` goes back to the command line's, which
            // here is the baseline. GCC's `optimize` and `push/pop` of it are
            // the same directives, and the optimisation half of them has
            // nothing to say to a front end that does not optimise.
            Some("push_options") => {
                let saved = self.target_features.clone();
                self.target_stack.push(saved);
            }
            Some("pop_options") => {
                if let Some(saved) = self.target_stack.pop() {
                    self.set_target_features(saved);
                }
            }
            Some("reset_options") => self.set_target_features(Vec::new()),
            // `diagnostic push/pop/ignored/warning/error`, `system_header`,
            // `visibility` and the rest: there are no warnings of ours to
            // suppress and no visibility to set, so they are accepted and
            // ignored.
            _ => {}
        }
    }

    /// `#pragma GCC target("avx2")` and `#pragma GCC target("sse4.2,popcnt")`.
    ///
    /// GCC's rule is that the options accumulate until a `pop_options` or a
    /// `reset_options`, and that they apply to the functions *defined* after
    /// the directive — not to the ones already defined, and not to
    /// declarations. That is what [`TargetOptionMap`] answers, against the
    /// position in the token stream the directive stood at.
    ///
    /// The names themselves are not checked here: they are checked once, in
    /// [sema](crate::sema), so that the attribute and the pragma give the same
    /// diagnostics in the same words.
    fn target_options_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        let mut names = self.target_features.clone();
        let mut found = false;
        for tok in rest {
            let TokenKind::Str(lit) = &tok.kind else {
                continue;
            };
            let Some(bytes) = lit.as_bytes() else {
                continue;
            };
            let text = String::from_utf8_lossy(&bytes).into_owned();
            for part in text.split(',') {
                let part = part.trim();
                if !part.is_empty() {
                    found = true;
                    if !names.iter().any(|(have, _)| have == part) {
                        names.push((part.to_owned(), tok.range));
                    }
                }
            }
        }
        if !found {
            self.diags.error(
                range,
                "#pragma GCC target needs a string literal naming an instruction set, as in \
                 #pragma GCC target(\"avx2\")"
                    .to_owned(),
            );
            return;
        }
        self.set_target_features(names);
    }

    /// Records a new set of instruction sets in force from here on.
    fn set_target_features(&mut self, names: Vec<(String, SourceRange)>) {
        self.sync_target_macros(&names);
        self.target_features = names.clone();
        let at = self.out.len();
        self.target_events.push((at, names));
    }

    /// Defines and undefines the feature macros — `__AVX2__`, `__AVX__`,
    /// `__SSE4_2__`, … — so that they say what the instruction sets in force
    /// are, as GCC's `#pragma GCC target` does for the rest of the file.
    ///
    /// The old set is worked out from the names in force until now, the new
    /// one from `names`, and only the difference is touched, so a
    /// `pop_options` takes back exactly what the popped `target` added and puts
    /// back what a `no-…` had taken away. Only x86 has these macros; on any
    /// other architecture the pragma defines nothing (and sema refuses it).
    /// `__attribute__((target))` on a function does not come here: GCC does
    /// not change the macros for one function either.
    fn sync_target_macros(&mut self, names: &[(String, SourceRange)]) {
        let baseline: &[&'static str] = match self.target.arch {
            Arch::X86_64 => &["__SSE__", "__SSE2__"],
            Arch::X86 => &[],
            _ => return,
        };
        fn spelled(list: &[(String, SourceRange)]) -> Vec<&str> {
            list.iter().map(|(n, _)| n.as_str()).collect()
        }
        let old = crate::x86::target_macros(baseline, &spelled(&self.target_features));
        let new = crate::x86::target_macros(baseline, &spelled(names));
        for gone in old.difference(&new) {
            self.macros.remove(*gone);
        }
        for added in new.difference(&old) {
            if !self.macros.contains_key(*added) {
                self.define_object(added, "1");
            }
        }
    }

    /// The text of a pragma that carries a message.
    fn pragma_message(&self, rest: &[PTok]) -> String {
        match rest.first() {
            Some(tok) => tok.spelling().to_owned(),
            None => String::new(),
        }
    }

    /// `#pragma push_macro("X")` and `#pragma pop_macro("X")`.
    ///
    /// MSVC's, and in GCC since 4.4: a header that has to redefine a macro for
    /// a few lines saves the old definition and puts it back. c-testsuite's
    /// `00206` is exactly that, and it is the reason this is here.
    fn push_macro_pragma(&mut self, rest: &[PTok], range: SourceRange, push: bool) {
        let what = if push { "push_macro" } else { "pop_macro" };
        // The name is a *string literal*, which is then read as an identifier.
        let inner = match rest {
            [tok] if tok.is_punct(Punct::LParen) => None,
            _ => rest
                .iter()
                .find_map(|tok| match &tok.kind {
                    TokenKind::Str(lit) => lit.as_bytes(),
                    _ => None,
                })
                .map(|bytes| String::from_utf8_lossy(&bytes).into_owned()),
        };
        let Some(name) = inner.filter(|name| !name.is_empty()) else {
            self.diags.error(
                range,
                format!("#pragma {what} needs a string literal naming a macro"),
            );
            return;
        };
        if push {
            let saved = self.macros.get(&name).cloned();
            self.macro_stacks.entry(name).or_default().push(saved);
            return;
        }
        match self.macro_stacks.get_mut(&name).and_then(Vec::pop) {
            Some(Some(def)) => {
                self.macros.insert(name, def);
            }
            Some(None) => {
                self.macros.remove(&name);
            }
            // GCC ignores a `pop_macro` with nothing pushed.
            None => {}
        }
    }

    /// `#pragma pack(…)`, which changes the alignment a record's members are
    /// laid out with until the next one.
    ///
    /// The value in effect where a `struct` is *defined* is what applies to it;
    /// [`Preprocessed::pack_events`] carries the changes to the parser, which
    /// records the one each specifier saw.
    fn pack_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        let bad = |pp: &mut Self, at: SourceRange| {
            pp.diags.error(
                at,
                "#pragma pack expects '(N)', '(push, N)', '(push)', '(pop)' or '()', \
                 where N is a power of two up to 16",
            );
        };
        if !rest.first().is_some_and(|t| t.is_punct(Punct::LParen))
            || !rest.last().is_some_and(|t| t.is_punct(Punct::RParen))
            || rest.len() < 2
        {
            bad(self, range);
            return;
        }
        let inner = &rest[1..rest.len() - 1];
        let value = |pp: &mut Self, tok: &PTok| -> Option<u32> {
            let TokenKind::Int(lit) = &tok.kind else {
                bad(pp, tok.range);
                return None;
            };
            let n = u32::try_from(lit.value)
                .ok()
                .filter(|n| n.is_power_of_two() && *n <= 16);
            if n.is_none() {
                bad(pp, tok.range);
            }
            n
        };
        let next = match inner {
            [] => Some(None),
            [tok] if tok.name() == Some("pop") => match self.pack_stack.pop() {
                Some(value) => Some(value),
                None => {
                    self.diags
                        .error(range, "#pragma pack(pop) with nothing pushed");
                    return;
                }
            },
            [tok] if tok.name() == Some("push") => {
                self.pack_stack.push(self.pack);
                Some(self.pack)
            }
            [tok] => value(self, tok).map(Some),
            [push, comma, tok] if push.name() == Some("push") && comma.is_punct(Punct::Comma) => {
                self.pack_stack.push(self.pack);
                value(self, tok).map(Some)
            }
            _ => {
                bad(self, range);
                return;
            }
        };
        let Some(next) = next else { return };
        self.pack = next;
        let at = self.out.len();
        self.pack_events.push((at, next));
    }

    /// The identity of the file being read, for `#pragma once`.
    fn cur_key(&self) -> String {
        self.cur().key.clone()
    }

    /// The `#pragma cinrs` options, for the diagnostics that list them.
    const OPTIONS: &'static str = "'target', 'include_path', 'system_include', 'link', \
                                   'export', 'safe', 'no_std' and 'crate'";

    /// `#pragma cinrs …`.
    fn cinrs_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        let Some(option) = rest.first() else {
            self.diags.error(
                range,
                format!("#pragma cinrs needs an option: {}", Self::OPTIONS),
            );
            return;
        };
        let name = option.name().unwrap_or_default();
        match name {
            // The scan before preprocessing already read this one and applied
            // it; all that is left is to say so when it cannot have worked.
            "target" => self.target_pragma(range),
            "include_path" | "link" | "crate" => {
                let Some(value) = self.pragma_string(&rest[1..], option.range, name) else {
                    return;
                };
                match name {
                    "include_path" => self.search.add_pragma(&value),
                    "link" => {
                        if !self.link_libraries.contains(&value) {
                            self.link_libraries.push(value);
                        }
                    }
                    _ => self.crate_pragma(value, rest[1].range),
                }
            }
            // A list of function names rather than one string: the spelling of
            // `[[cinrs::safe]]` that every entry point has, since `[[…]]` is
            // C23's and `__attribute__` cannot be written where the function
            // is not.
            "safe" => self.safe_pragma(&rest[1..], option.range),
            "system_include" => self.system_include_pragma(&rest[1..], option.range),
            // Unit-wide and argument-less: everything with external linkage
            // becomes a real C symbol, and the `Vec`s a variable length array
            // or `alloca` needs come from `alloc` rather than from `std`.
            "export" | "no_std" => {
                if let Some(extra) = rest.get(1) {
                    self.diags.error(
                        extra.range,
                        format!(
                            "unexpected {} after #pragma cinrs {name}, which takes no argument",
                            extra.kind.describe()
                        ),
                    );
                }
                if name == "export" {
                    self.export = true;
                } else {
                    self.no_std = true;
                }
            }
            other => {
                let what = if other.is_empty() {
                    option.kind.describe().to_owned()
                } else {
                    format!("'{other}'")
                };
                self.diags.error(
                    option.range,
                    format!(
                        "unknown #pragma cinrs option {what}; the options are {}",
                        Self::OPTIONS
                    ),
                );
            }
        }
    }

    /// `#pragma cinrs target "<triple>"`, seen a second time.
    ///
    /// [`scan_target_pragma`] read every one in the unit's own text before
    /// this pass began and either applied it or reported it, so there is
    /// nothing left to do — except in the two cases the scan cannot serve, and
    /// where silence would mean translating for the wrong machine:
    ///
    /// * the directive is one the scan never saw, because it is in a *header*
    ///   or came out of `_Pragma`, so the model it names was never applied;
    /// * it stands after an `#include` or an `#if`, both of which had already
    ///   been answered with the old model.
    ///
    /// A `target` inside a group `#if 0` skips is the mirror image — the scan
    /// applied it and this pass never sees it — which the module
    /// documentation says, and which is why this is the only pragma read
    /// twice.
    fn target_pragma(&mut self, range: SourceRange) {
        if !self.target_pragmas.scanned(range) {
            let now = match self.target_source.triple() {
                Some(triple) => format!("for '{triple}'"),
                None => format!("for the model {} named", self.target_source.as_str()),
            };
            self.diags.error(
                range,
                format!(
                    "'#pragma cinrs target' is read before preprocessing, so it has to be a \
                     directive in the unit's own text: a header's comes too late, and one \
                     out of '_Pragma' is never seen. This unit is being translated {now}"
                ),
            );
            return;
        }
        // The scan read this one. If it did not like it, it has said so
        // already and a second message would only get in the way.
        if !self.target_pragmas.applied {
            return;
        }
        if self.model_observed {
            self.diags.error(
                range,
                "'#pragma cinrs target' must come before every '#include' and '#if', which \
                 were already answered with the previous data model",
            );
        }
    }

    /// `#pragma cinrs safe f g h`, which asks for those functions to be
    /// generated without `unsafe`.
    ///
    /// It takes identifiers rather than a string so that it reads like the C it
    /// is naming, and any number of them, since a unit that marks one function
    /// usually marks several. A name that is not a function defined here is a
    /// mistake, and [`crate::sema::check_safe`] — which is the only pass that
    /// knows what the unit defines — says so.
    fn safe_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        if rest.is_empty() {
            self.diags.error(
                range,
                "#pragma cinrs safe needs the name of at least one function",
            );
            return;
        }
        for tok in rest {
            match tok.name() {
                Some(name) => self.safe_functions.push(SafeName {
                    name: name.to_owned(),
                    range: tok.range,
                }),
                None => self.diags.error(
                    tok.range,
                    format!(
                        "#pragma cinrs safe takes function names, found {}",
                        tok.kind.describe()
                    ),
                ),
            }
        }
    }

    /// `#pragma cinrs system_include` and `#pragma cinrs system_include first`,
    /// which put the platform's own include directories on the search path.
    ///
    /// Plain, they go *after* the bundled headers: the bundled `<stdio.h>`
    /// still wins, and only a header cinrs does not carry — `<sys/stat.h>`,
    /// `<pthread.h>`, `<dirent.h>` — comes from the platform. With `first`
    /// they go before, which is how a unit asks for the platform's own
    /// `<stdio.h>` and so for the real `FILE`.
    ///
    /// A bare word rather than a string, like `safe`'s function names, so that
    /// it reads as the switch it is; and like every other pragma this one is
    /// answered where it stands, so it has to come before the `#include`s it
    /// is meant to change.
    fn system_include_pragma(&mut self, rest: &[PTok], range: SourceRange) {
        let mode = match rest.first() {
            None => include::System::Last,
            Some(tok) if tok.name() == Some("first") => include::System::First,
            Some(tok) => {
                let what = match tok.name() {
                    Some(name) => format!("'{name}'"),
                    None => tok.kind.describe().to_owned(),
                };
                self.diags.error(
                    tok.range,
                    format!(
                        "unexpected {what} after #pragma cinrs system_include, which takes \
                         either nothing or 'first'"
                    ),
                );
                return;
            }
        };
        if let Some(extra) = rest.get(1) {
            self.diags.error(
                extra.range,
                format!(
                    "unexpected {} after #pragma cinrs system_include first",
                    extra.kind.describe()
                ),
            );
        }
        // Which directories the platform's headers live in is read off the
        // data model, so the model is settled from here on; see
        // `Pp::target_pragma`.
        self.model_observed = true;
        self.enable_system_include(mode, range);
    }

    /// Works out the platform's own include directories and puts them on the
    /// path, or says why there are none to put there.
    ///
    /// The one thing that can go wrong is a cross build with no
    /// [`include::SYSTEM_PATH_ENV_VAR`]: the default directories are the
    /// *host*'s, and a header laid out for another machine is worse than no
    /// header at all. See [`include::system_directories`].
    fn enable_system_include(&mut self, mode: include::System, range: SourceRange) {
        match include::system_directories(&self.target, &self.target_source) {
            Ok(dirs) => self.search.enable_system(mode, dirs),
            Err(message) => self.diags.error(range, message),
        }
    }

    /// `#pragma cinrs crate "::my_cinrs"`, which says where the `cinrs` facade
    /// crate is to be found.
    ///
    /// The generated code names it only where it needs the runtime — today
    /// that is a complex type, and nothing else — but it has to name it in
    /// full, because the expansion goes into a module of its own and cannot
    /// rely on anything being in scope there. The default is `::cinrs`; a
    /// dependency renamed in `Cargo.toml`, or one reached through a re-export,
    /// needs this.
    fn crate_pragma(&mut self, path: String, range: SourceRange) {
        if !crate::codegen::is_crate_path(&path) {
            self.diags.error(
                range,
                format!(
                    "'{path}' is not usable as a Rust path to a crate; write something like \
                     '::my_cinrs' or 'crate::vendor::cinrs'"
                ),
            );
            return;
        }
        if let Some(previous) = &self.crate_path
            && *previous != path
        {
            self.diags.error(
                range,
                format!(
                    "this unit already reaches the cinrs crate as '{previous}', by an earlier \
                     #pragma cinrs crate"
                ),
            );
            return;
        }
        self.crate_path = Some(path);
    }

    /// The single string literal a `#pragma cinrs` option takes.
    fn pragma_string(&mut self, rest: &[PTok], range: SourceRange, option: &str) -> Option<String> {
        let Some(tok) = rest.first() else {
            self.diags.error(
                range,
                format!("#pragma cinrs {option} needs a string literal"),
            );
            return None;
        };
        let TokenKind::Str(lit) = &tok.kind else {
            self.diags.error(
                tok.range,
                format!(
                    "#pragma cinrs {option} needs a string literal, found {}",
                    tok.kind.describe()
                ),
            );
            return None;
        };
        let Some(bytes) = lit.as_bytes() else {
            self.diags.error(
                tok.range,
                format!("#pragma cinrs {option} does not take a wide string literal"),
            );
            return None;
        };
        let value = String::from_utf8_lossy(&bytes).into_owned();
        if value.is_empty() {
            self.diags.error(
                tok.range,
                format!("#pragma cinrs {option} was given an empty string"),
            );
            return None;
        }
        if let Some(extra) = rest.get(1) {
            self.diags.error(
                extra.range,
                format!(
                    "unexpected {} after #pragma cinrs {option}",
                    extra.kind.describe()
                ),
            );
        }
        Some(value)
    }

    // -- #include -----------------------------------------------------------

    /// `#include <name>`, `#include "name"` and `#include MACRO` — and, with
    /// `next`, GNU's `#include_next`, which is the same thing looked for from
    /// the entry after the one the current file was found under.
    fn include(&mut self, line: &[PTok], range: SourceRange, next: bool) {
        // A header reads the model — every bundled one branches on `_WIN32`
        // or on `__SIZEOF_POINTER__` — so once one is opened the model is
        // settled; see `Pp::target_pragma`.
        self.model_observed = true;
        let Some((name, form)) = self.header_name(line, range) else {
            return;
        };
        if self.open.len() >= MAX_INCLUDE_DEPTH {
            self.diags.error(
                range,
                format!("#include nested too deeply (more than {MAX_INCLUDE_DEPTH} files)"),
            );
            return;
        }
        let origin = self.cur().origin.clone();
        let looked = if next {
            let current = self.cur().found_in.clone();
            include::resolve_next(&name, &origin, current.as_ref(), &self.search)
        } else {
            include::resolve(&name, form, &origin, &self.search)
        };
        let found = match looked {
            Ok(found) => found,
            Err(include::Error::Unreadable { path, error }) => {
                self.diags
                    .error(range, format!("cannot read '{path}': {error}"));
                return;
            }
            Err(include::Error::NotFound { searched }) => {
                let quoted = match form {
                    include::Form::Angled => format!("<{name}>"),
                    include::Form::Quoted => format!("\"{name}\""),
                };
                let message = match (next, searched.is_empty()) {
                    (false, _) => {
                        format!("{quoted} file not found; searched: {}", searched.join(", "))
                    }
                    (true, true) => format!(
                        "{quoted} file not found by #include_next; there is nothing after the \
                         place this file was found in"
                    ),
                    (true, false) => format!(
                        "{quoted} file not found by #include_next; searched: {}",
                        searched.join(", ")
                    ),
                };
                self.diags.error(range, message + &self.posix_hint(&name));
                return;
            }
        };

        // The two ways a file already read can be skipped without reading it
        // again: it said `#pragma once`, or it is wrapped in an include guard
        // whose macro is still defined.
        if self.once.contains(&found.key) {
            return;
        }
        if let Some(guard) = self.guards.get(&found.key)
            && self.macros.contains_key(guard)
        {
            return;
        }
        if let Some(path) = &found.path
            && !self.user_headers.contains(path)
        {
            self.user_headers.push(path.clone());
        }
        self.open_file(found, range);
    }

    /// What to add to a "file not found" for a POSIX header while the
    /// platform's own directories are switched off.
    ///
    /// The bundled set is ISO C; POSIX comes from the platform. A program that
    /// asks for `<unistd.h>` without saying so has not written a typo, it has
    /// left out one line — and the diagnostic that only lists the directories
    /// searched leaves the reader to work that out. Empty for every other name,
    /// and empty once the switch is on, where a missing POSIX header really is
    /// a missing file.
    fn posix_hint(&self, name: &str) -> String {
        if self.search.system_mode().is_on() || !include::is_posix_header(name) {
            return String::new();
        }
        format!(
            ". The bundled headers are ISO C; POSIX headers such as <{name}> come from the \
             platform, which '#pragma cinrs system_include' (or {}=1 in the environment) \
             switches on",
            include::SYSTEM_ENV_VAR
        )
    }

    // -- #embed -------------------------------------------------------------

    /// `#embed "resource"` and `#embed <resource>` (C23 6.10.3, N3017).
    ///
    /// The directive is replaced by the bytes of the resource, written as a
    /// comma-separated list of integer constants in the range of `unsigned
    /// char` — so that `unsigned char logo[] = {\n#embed "logo.png"\n};` is an
    /// array of the file. The four standard parameters shape the list:
    /// `limit(N)` takes only the first N bytes, `prefix(…)` and `suffix(…)`
    /// bracket a *non-empty* list, and `if_empty(…)` replaces an empty one.
    ///
    /// The tokens go through the ordinary pending queue, so they are rescanned
    /// for macros exactly as any other replacement is — and are charged
    /// against [`MAX_EXPANDED_TOKENS`] like any others, which puts the ceiling
    /// on a resource near two megabytes.
    fn embed(&mut self, rest: &[PTok], range: SourceRange) {
        let Some((name, form, after)) = self.embed_operand(rest, range) else {
            return;
        };
        let Some(params) = self.embed_parameters(&rest[after..], range, true) else {
            return;
        };
        let origin = self.cur().origin.clone();
        let found = match include::resolve_embed(&name, form, &origin, &self.search) {
            Ok(found) => found,
            Err(include::Error::Unreadable { path, error }) => {
                self.diags
                    .error(range, format!("cannot read '{path}': {error}"));
                return;
            }
            Err(include::Error::NotFound { searched }) => {
                let quoted = match form {
                    include::Form::Angled => format!("<{name}>"),
                    include::Form::Quoted => format!("\"{name}\""),
                };
                // There are no bundled resources, so unlike `#include` the
                // list of places looked in really can be empty.
                let where_ = if searched.is_empty() {
                    "there is nowhere to look; name a directory with \
                     `#pragma cinrs include_path`"
                        .to_owned()
                } else {
                    format!("searched: {}", searched.join(", "))
                };
                self.diags.error(
                    range,
                    format!("{quoted} resource not found for #embed; {where_}"),
                );
                return;
            }
        };
        if !self.embedded_files.contains(&found.path) {
            self.embedded_files.push(found.path.clone());
        }

        let take = params.limit.unwrap_or(found.bytes.len());
        let bytes = &found.bytes[..take.min(found.bytes.len())];
        let mut out: Vec<PTok> = Vec::new();
        if bytes.is_empty() {
            // 6.10.3.2: `if_empty` stands for the whole expansion, and the
            // prefix and suffix are not emitted at all.
            out.extend(params.if_empty);
        } else {
            out.extend(params.prefix);
            for (i, byte) in bytes.iter().enumerate() {
                if i > 0 {
                    out.push(self.embed_token(TokenKind::Punct(Punct::Comma), range));
                }
                out.push(self.embed_token(int_token_kind(u128::from(*byte)), range));
            }
            out.extend(params.suffix);
        }
        // The directive stands like a name preceded by white space.
        let at = self.embed_token(TokenKind::Punct(Punct::Comma), range);
        self.push_pending(out, &at, None, None);
    }

    /// The resource name an `#embed` names, how it was spelled, and how many
    /// of the directive's tokens it took.
    fn embed_operand(
        &mut self,
        rest: &[PTok],
        range: SourceRange,
    ) -> Option<(String, include::Form, usize)> {
        if let Some(found) = self.embed_name_of(rest) {
            return Some(found);
        }
        // 6.10.3p1 allows the whole operand to come out of a macro, exactly as
        // `#include`'s does.
        if !rest.is_empty() {
            let expanded = self.expand_sequence(rest.to_vec());
            if let Some((name, form, _)) = self.embed_name_of(&expanded) {
                // A macro cannot be followed by parameters here: the whole run
                // was replaced, so there is nothing of the original left to
                // read them from.
                return Some((name, form, rest.len()));
            }
        }
        self.diags
            .error(range, "#embed expects \"RESOURCE\" or <RESOURCE>");
        None
    }

    /// Reads a resource name off the front of a token run.
    fn embed_name_of(&self, toks: &[PTok]) -> Option<(String, include::Form, usize)> {
        match &toks.first()?.kind {
            // A quoted name is *not* a string literal's value: no escape
            // sequence is processed, so the spelling between the quotes is it.
            TokenKind::Str(lit) if lit.kind == lex::StrKind::Narrow => {
                let spelling = lit.text.as_str();
                let name = spelling
                    .strip_prefix('"')
                    .and_then(|s| s.strip_suffix('"'))
                    .unwrap_or(spelling);
                (!name.is_empty()).then(|| (name.to_owned(), include::Form::Quoted, 1))
            }
            TokenKind::Punct(Punct::Lt) => {
                let close = toks[1..].iter().position(|t| t.is_punct(Punct::Gt))? + 1;
                let raw = self
                    .raw_text(toks[0].range.end, toks[close].range.start)
                    .trim()
                    .to_owned();
                let name = if raw.is_empty() {
                    // The tokens came out of a macro and have no source text
                    // of their own; their spellings are the name.
                    let mut spelled = String::new();
                    for (i, tok) in toks[1..close].iter().enumerate() {
                        if i > 0 && tok.space {
                            spelled.push(' ');
                        }
                        spelled.push_str(tok.spelling());
                    }
                    spelled
                } else {
                    raw
                };
                (!name.is_empty()).then(|| (name, include::Form::Angled, close + 1))
            }
            _ => None,
        }
    }

    /// Reads `#embed`'s parameters, which follow the resource name.
    ///
    /// `report` says whether a parameter this implementation does not have is
    /// a diagnostic. It is for the *directive*, and is not for `__has_embed`:
    /// 6.10.1p5 answers "not found" for a parameter it cannot honour, which is
    /// how a program asks whether one is supported before writing it.
    fn embed_parameters(
        &mut self,
        mut rest: &[PTok],
        range: SourceRange,
        report: bool,
    ) -> Option<EmbedParams> {
        let mut params = EmbedParams::default();
        while let Some(first) = rest.first() {
            let Some(name) = first.name() else {
                if report {
                    self.diags.error(
                        first.range,
                        format!(
                            "expected an #embed parameter, found {}",
                            first.kind.describe()
                        ),
                    );
                }
                return None;
            };
            if rest.get(1).is_none_or(|t| !t.is_punct(Punct::LParen)) {
                if report {
                    self.diags.error(
                        first.range,
                        format!("#embed parameter '{name}' takes an argument list"),
                    );
                }
                return None;
            }
            // The matching `)`, counting nested parentheses.
            let mut depth = 0usize;
            let mut close = None;
            for (i, tok) in rest[1..].iter().enumerate() {
                if tok.is_punct(Punct::LParen) {
                    depth += 1;
                } else if tok.is_punct(Punct::RParen) {
                    depth -= 1;
                    if depth == 0 {
                        close = Some(i + 1);
                        break;
                    }
                }
            }
            let Some(close) = close else {
                if report {
                    self.diags.error(
                        first.range,
                        format!("unterminated argument list for '{name}'"),
                    );
                }
                return None;
            };
            let inner = &rest[2..close];
            // GCC spells every one of them both ways; the reserved form is
            // what a header uses so as not to collide with a user's macro.
            let plain = name
                .strip_prefix("__")
                .and_then(|n| n.strip_suffix("__"))
                .unwrap_or(name);
            match plain {
                "limit" => {
                    if inner.is_empty() {
                        if report {
                            self.diags
                                .error(first.range, "#embed 'limit' takes a constant expression");
                        }
                        return None;
                    }
                    let value = self.eval_expression(inner, range)?;
                    if value < 0 {
                        if report {
                            self.diags
                                .error(first.range, "#embed 'limit' cannot be negative");
                        }
                        return None;
                    }
                    params.limit = Some(usize::try_from(value).unwrap_or(usize::MAX));
                }
                "prefix" => params.prefix = inner.to_vec(),
                "suffix" => params.suffix = inner.to_vec(),
                "if_empty" => params.if_empty = inner.to_vec(),
                _ => {
                    if report {
                        self.diags
                            .error(first.range, format!("unknown #embed parameter '{name}'"));
                    }
                    return None;
                }
            }
            rest = &rest[close + 1..];
        }
        Some(params)
    }

    /// One token of an `#embed` expansion, standing where the directive was.
    fn embed_token(&self, kind: TokenKind, range: SourceRange) -> PTok {
        PTok {
            kind,
            range,
            bol: false,
            space: true,
            pad: None,
            trail: None,
            origin: Origin::Source,
            hide: HideSet::default(),
            errors: Vec::new(),
        }
    }

    /// Places a header's text in the offset space and starts reading it.
    fn open_file(&mut self, found: include::Resolved, directive: SourceRange) {
        let base = self.next_base;
        self.next_base = base
            .saturating_add(found.text.len() as Pos)
            .saturating_add(FILE_GAP);
        let mut input: Vec<PTok> = lex::lex_file(&found.text, base, &self.lex_options)
            .iter()
            .map(PTok::from_lexed)
            .collect();
        if input.is_empty() {
            input.push(eof_token(base));
        }
        if let Some(guard) = detect_include_guard(&input) {
            self.guards.insert(found.key.clone(), guard);
        }
        self.included.push(IncludedFile {
            name: found.name.clone(),
            text: found.text.clone(),
            base,
            directive,
        });
        self.files
            .push(FileEntry::new(found.text, base, 1, found.name));
        let site = if found.system {
            DefSite::Platform
        } else if matches!(found.origin, include::Origin::Bundled) {
            DefSite::Bundled
        } else {
            DefSite::Program
        };
        self.open.push(OpenFile {
            input,
            pos: 0,
            origin: found.origin,
            found_in: found.found_in,
            key: found.key,
            cond_base: self.conds.len(),
            site,
        });
    }

    /// The header name an `#include` names, and how it was spelled.
    ///
    /// `<stdio.h>` is not one token, so the name comes from the source text
    /// the directive covers rather than from the tokens. 6.10.2p4 also allows
    /// the whole thing to come out of a macro, which is what the second half
    /// handles: there is no source text to read then, so the name is rebuilt
    /// from the spellings of the tokens the macro produced.
    fn header_name(
        &mut self,
        line: &[PTok],
        range: SourceRange,
    ) -> Option<(String, include::Form)> {
        let text = self.directive_text(line, 1);
        if let Some(found) = parse_header_name(&text) {
            return Some(found);
        }
        if line.len() <= 1 {
            self.diags
                .error(range, "#include expects \"FILENAME\" or <FILENAME>");
            return None;
        }
        // `#include MACRO`: replace, then read the result back as text.
        let expanded = self.expand_sequence(line[1..].to_vec());
        let mut spelled = String::new();
        for (i, tok) in expanded.iter().enumerate() {
            if i > 0 && tok.space {
                spelled.push(' ');
            }
            spelled.push_str(tok.spelling());
        }
        if let Some(found) = parse_header_name(&spelled) {
            return Some(found);
        }
        self.diags.error(
            range,
            "#include expects \"FILENAME\" or <FILENAME>".to_owned(),
        );
        None
    }

    /// Reads the single macro name a directive takes.
    fn macro_name_operand(
        &mut self,
        rest: &[PTok],
        range: SourceRange,
        directive: &str,
    ) -> Option<String> {
        let Some(first) = rest.first() else {
            self.diags
                .error(range, format!("no macro name given in #{directive}"));
            return None;
        };
        let Some(name) = first.name() else {
            self.diags.error(
                first.range,
                format!(
                    "macro name must be an identifier, found {}",
                    first.kind.describe()
                ),
            );
            return None;
        };
        if name == "defined" {
            self.diags.error(
                first.range,
                format!("'defined' cannot be used as a macro name in #{directive}"),
            );
            return None;
        }
        Some(name.to_owned())
    }

    // -- conditionals -------------------------------------------------------

    /// Opens a conditional group, evaluating its controlling condition only
    /// when the enclosing group is being processed.
    fn open_cond(&mut self, range: SourceRange, test: impl FnOnce(&mut Self) -> bool) {
        let outer_active = !self.skipping();
        let value = outer_active && test(self);
        self.conds.push(Cond {
            range,
            outer_active,
            taken: value,
            active: outer_active && value,
            seen_else: false,
        });
    }

    /// Opens the next branch of a conditional group.
    ///
    /// `test` is only run when the branch could be taken at all, which is what
    /// makes `#elif 1/N` after a branch that already ran harmless — and what
    /// keeps `#elifdef` from reporting a missing name in a group nothing will
    /// read.
    fn elif(&mut self, range: SourceRange, directive: &str, test: impl FnOnce(&mut Self) -> bool) {
        let Some(cond) = self.conds.last() else {
            self.diags.error(range, format!("#{directive} without #if"));
            return;
        };
        if cond.seen_else {
            let seen = cond.range;
            self.diags.push(
                Diagnostic::error(range, format!("#{directive} after #else"))
                    .with_note_at(seen, "the conditional started"),
            );
            return;
        }
        let (outer_active, taken) = (cond.outer_active, cond.taken);
        let value = outer_active && !taken && test(self);
        let cond = self
            .conds
            .last_mut()
            .expect("the stack was not touched in between");
        cond.active = value;
        cond.taken |= value;
    }

    /// Reports a directive the block's own standard does not have.
    fn require_standard(&mut self, needed: Standard, what: &str, range: SourceRange) {
        if let Some(message) = self.gating.requires(what, needed) {
            self.diags.error(range, message);
        }
    }

    fn else_(&mut self, rest: &[PTok], range: SourceRange) {
        let Some(cond) = self.conds.last_mut() else {
            self.diags.error(range, "#else without #if");
            return;
        };
        if cond.seen_else {
            let seen = cond.range;
            self.diags.push(
                Diagnostic::error(range, "#else after #else")
                    .with_note_at(seen, "the conditional started"),
            );
            return;
        }
        cond.seen_else = true;
        cond.active = cond.outer_active && !cond.taken;
        cond.taken = true;
        let active = cond.active;
        if active && !rest.is_empty() {
            self.diags
                .warning(range, "extra tokens at the end of #else");
        }
    }

    fn endif(&mut self, range: SourceRange) {
        if self.conds.pop().is_none() {
            self.diags.error(range, "#endif without #if");
        }
    }

    // -- #define / #undef ---------------------------------------------------

    fn undef(&mut self, rest: &[PTok], range: SourceRange) {
        if let Some(name) = self.macro_name_operand(rest, range, "undef") {
            self.macros.remove(&name);
        }
    }

    fn define(&mut self, rest: &[PTok], range: SourceRange) {
        let Some(name_tok) = rest.first() else {
            self.diags.error(range, "no macro name given in #define");
            return;
        };
        let Some(name) = name_tok.name().map(str::to_owned) else {
            self.diags.error(
                name_tok.range,
                format!(
                    "macro name must be an identifier, found {}",
                    name_tok.kind.describe()
                ),
            );
            return;
        };
        if name == "defined" {
            self.diags
                .error(name_tok.range, "'defined' cannot be used as a macro name");
            return;
        }
        if name == VA_ARGS {
            self.diags.error(
                name_tok.range,
                "'__VA_ARGS__' can only appear in the replacement list of a variadic macro",
            );
            return;
        }

        // A `(` *immediately* after the name — no white space — makes the
        // macro function-like; `#define f (x)` is object-like and expands to
        // `(x)`.
        let mut rest = &rest[1..];
        let function_like = rest
            .first()
            .is_some_and(|t| t.is_punct(Punct::LParen) && !t.space);
        let (params, variadic, va_name) = if function_like {
            let Some(parsed) = self.parse_params(rest, range) else {
                return;
            };
            rest = &rest[parsed.used..];
            (Some(parsed.params), parsed.variadic, parsed.va_name)
        } else {
            (None, false, None)
        };

        let body = fuse_hash_hash(rest);
        let def = MacroDef {
            params,
            variadic,
            va_name,
            body,
            name_range: name_tok.range,
            predefined: false,
            site: self.cur().site,
            builtin: None,
        };
        if !self.check_body(&def, &name, range) {
            return;
        }

        if let Some(previous) = self.macros.get(&name)
            && !previous.predefined
            && !previous.same_as(&def)
        {
            // A bundled header and one of the platform's own are two
            // descriptions of the *same* C library, and with
            // `#pragma cinrs system_include` a program has both in play: it
            // includes the bundled `<time.h>`, and glibc's `<pthread.h>` then
            // reaches glibc's `bits/time.h`. Where the two spell one macro
            // differently — `CLOCKS_PER_SEC` is `1000000` here and
            // `((__clock_t) 1000000)` there — the disagreement is about
            // spelling, not about the platform, and the platform's own copy is
            // the authoritative one. So it wins, and nothing is reported.
            //
            // Every other pair is a real redefinition and keeps its
            // diagnostic, including a program that redefines a bundled macro:
            // that one is the program's mistake, not a mismatch between two
            // models of the same library.
            match DefSite::resolves(previous.site, def.site) {
                Some(DefSite::Platform) if def.site == DefSite::Platform => {}
                // The platform got there first; the bundled header stands
                // aside rather than overwriting it.
                Some(_) => return,
                None => {
                    self.diags.push(
                        Diagnostic::error(name_tok.range, format!("macro '{name}' redefined"))
                            .with_note_at(
                                previous.name_range,
                                format!("previous definition of '{name}' is"),
                            ),
                    );
                    return;
                }
            }
        }
        self.macros.insert(name, Arc::new(def));
    }

    /// Parses `( a, b, ... )`, or GNU's `( a, rest... )`.
    fn parse_params(&mut self, rest: &[PTok], range: SourceRange) -> Option<ParamList> {
        let mut params: Vec<String> = Vec::new();
        let mut variadic = false;
        let mut va_name = None;
        let mut i = 1; // past the `(`
        if rest.get(i).is_some_and(|t| t.is_punct(Punct::RParen)) {
            return Some(ParamList {
                params,
                variadic,
                va_name,
                used: i + 1,
            });
        }
        loop {
            let Some(tok) = rest.get(i) else {
                self.diags
                    .error(range, "missing ')' in the parameter list of a macro");
                return None;
            };
            if tok.is_punct(Punct::Ellipsis) {
                self.require_standard(Standard::C99, "a variadic macro", tok.range);
                variadic = true;
                i += 1;
                break;
            }
            let Some(name) = tok.name() else {
                self.diags.error(
                    tok.range,
                    format!(
                        "expected a macro parameter name, found {}",
                        tok.kind.describe()
                    ),
                );
                return None;
            };
            if name == VA_ARGS {
                self.diags.error(
                    tok.range,
                    "'__VA_ARGS__' cannot be used as a macro parameter name",
                );
                return None;
            }
            if params.iter().any(|p| p == name) {
                self.diags
                    .error(tok.range, format!("duplicate macro parameter '{name}'"));
                return None;
            }
            // GNU's named variable arguments: `args...` makes `args` another
            // spelling of `__VA_ARGS__` rather than one more parameter.
            if rest.get(i + 1).is_some_and(|t| t.is_punct(Punct::Ellipsis)) {
                self.require_standard(Standard::C99, "a variadic macro", tok.range);
                variadic = true;
                va_name = Some(name.to_owned());
                i += 2;
                break;
            }
            params.push(name.to_owned());
            i += 1;
            match rest.get(i) {
                Some(t) if t.is_punct(Punct::Comma) => i += 1,
                Some(t) if t.is_punct(Punct::RParen) => break,
                Some(t) => {
                    self.diags.error(
                        t.range,
                        format!(
                            "expected ',' or ')' in a macro parameter list, found {}",
                            t.kind.describe()
                        ),
                    );
                    return None;
                }
                None => {
                    self.diags
                        .error(range, "missing ')' in the parameter list of a macro");
                    return None;
                }
            }
        }
        match rest.get(i) {
            Some(t) if t.is_punct(Punct::RParen) => Some(ParamList {
                params,
                variadic,
                va_name,
                used: i + 1,
            }),
            _ => {
                self.diags
                    .error(range, "missing ')' in the parameter list of a macro");
                None
            }
        }
    }

    /// Checks the constraints a replacement list has to satisfy.
    fn check_body(&mut self, def: &MacroDef, name: &str, range: SourceRange) -> bool {
        let body = &def.body;
        if let Some(first) = body.first()
            && first.is_punct(Punct::HashHash)
        {
            self.diags.error(
                first.range,
                "'##' cannot appear at the start of a macro replacement list",
            );
            return false;
        }
        if let Some(last) = body.last()
            && last.is_punct(Punct::HashHash)
            && body.len() > 1
        {
            self.diags.error(
                last.range,
                "'##' cannot appear at the end of a macro replacement list",
            );
            return false;
        }
        for (i, tok) in body.iter().enumerate() {
            if def.params.is_some() && tok.is_punct(Punct::Hash) {
                let ok = body
                    .get(i + 1)
                    .and_then(PTok::name)
                    .is_some_and(|n| def.param_index(n).is_some());
                if !ok {
                    self.diags
                        .error(tok.range, "'#' must be followed by a macro parameter");
                    return false;
                }
            }
            if tok.name() == Some(VA_ARGS) && def.param_index(VA_ARGS).is_none() {
                self.diags.error(
                    tok.range,
                    "'__VA_ARGS__' can only appear in the replacement list of a variadic macro",
                );
                return false;
            }
            if tok.name() == Some(VA_OPT) && !self.check_va_opt(def, body, i) {
                return false;
            }
        }
        let _ = (name, range);
        true
    }

    /// Checks one `__VA_OPT__` in a replacement list.
    ///
    /// It has to be in a variadic macro, it has to be followed by a balanced
    /// `( … )`, its contents may neither begin nor end with `##` (C23
    /// 6.10.5.2p1, for the same reason a replacement list may not — there is
    /// nothing on that side to paste to), and — since the standard says so and
    /// since the expansion here is a single pass — it may not hold another
    /// one.
    fn check_va_opt(&mut self, def: &MacroDef, body: &[PTok], at: usize) -> bool {
        let tok = &body[at];
        if def.param_index(VA_ARGS).is_none() {
            self.diags.error(
                tok.range,
                "'__VA_OPT__' can only appear in the replacement list of a variadic macro",
            );
            return false;
        }
        self.require_standard(Standard::C23, "'__VA_OPT__'", tok.range);
        if !body.get(at + 1).is_some_and(|t| t.is_punct(Punct::LParen)) {
            self.diags
                .error(tok.range, "'__VA_OPT__' must be followed by '('");
            return false;
        }
        let mut depth = 0i32;
        let mut contents: Vec<&PTok> = Vec::new();
        for tok in &body[at + 1..] {
            if tok.is_punct(Punct::LParen) {
                depth += 1;
                // The `(` that opens the argument is not part of it.
                if depth == 1 {
                    continue;
                }
            } else if tok.is_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    return self.check_va_opt_contents(&contents);
                }
            } else if tok.name() == Some(VA_OPT) {
                self.diags
                    .error(tok.range, "'__VA_OPT__' cannot be nested inside another");
                return false;
            }
            contents.push(tok);
        }
        self.diags.error(
            tok.range,
            "unterminated '__VA_OPT__(' in a macro definition",
        );
        false
    }

    /// C23 6.10.5.2p1 for the token sequence inside a `__VA_OPT__( … )`.
    fn check_va_opt_contents(&mut self, contents: &[&PTok]) -> bool {
        for (end, tok) in [("start", contents.first()), ("end", contents.last())] {
            if let Some(tok) = tok
                && tok.is_punct(Punct::HashHash)
            {
                self.diags.error(
                    tok.range,
                    format!("'##' cannot appear at the {end} of a '__VA_OPT__' argument"),
                );
                return false;
            }
        }
        true
    }
}

/// Replaces every `__VA_OPT__( … )` in a replacement list with its contents,
/// or with nothing when the invocation passed no variable arguments (C23
/// 6.10.5.2).
///
/// Doing it before substitution rather than during it is what makes the rest
/// of the rules fall out: the contents are ordinary replacement-list tokens
/// afterwards, so `#` and `##` next to them, and the parameters inside them,
/// are handled by the code that was already there. `None` means the
/// replacement list has no `__VA_OPT__` and can be used as it stands.
fn expand_va_opt(def: &MacroDef, args: &Args) -> Option<Vec<PTok>> {
    let params = def.params.as_ref()?;
    if !def.variadic || !def.body.iter().any(|t| t.name() == Some(VA_OPT)) {
        return None;
    }
    // The variable arguments are the one past the named parameters; `subst`
    // is only reached once `try_expand` has padded the list out to that.
    let present = !args.get(params.len()).is_empty();
    let body = &def.body;
    let mut out: Vec<PTok> = Vec::with_capacity(body.len());
    let mut i = 0;
    while i < body.len() {
        let is_va_opt = body[i].name() == Some(VA_OPT)
            && body.get(i + 1).is_some_and(|t| t.is_punct(Punct::LParen));
        if !is_va_opt {
            out.push(body[i].clone());
            i += 1;
            continue;
        }
        let space = body[i].space;
        let mut depth = 0i32;
        let mut inner: Vec<PTok> = Vec::new();
        let mut j = i + 1;
        while j < body.len() {
            let tok = &body[j];
            j += 1;
            if tok.is_punct(Punct::LParen) {
                depth += 1;
                if depth == 1 {
                    continue;
                }
            } else if tok.is_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            inner.push(tok.clone());
        }
        if present {
            if let Some(first) = inner.first_mut() {
                // The expansion stands where `__VA_OPT__` did, spacing and all.
                first.space = space;
            }
            out.extend(inner);
        }
        i = j;
    }
    Some(out)
}

/// Reads `<name>` or `"name"` out of the text of an `#include` directive.
///
/// The name is taken verbatim, which is what 6.4.7 asks for: a `\` in a header
/// name is a directory separator on the platforms that use one, not the start
/// of an escape sequence. Anything after the closing delimiter is ignored, the
/// way every compiler ignores it.
fn parse_header_name(text: &str) -> Option<(String, include::Form)> {
    let text = text.trim();
    let (form, close) = match text.as_bytes().first()? {
        b'<' => (include::Form::Angled, '>'),
        b'"' => (include::Form::Quoted, '"'),
        _ => return None,
    };
    let rest = &text[1..];
    let end = rest.find(close)?;
    let name = &rest[..end];
    (!name.is_empty()).then(|| (name.to_owned(), form))
}

/// The macro an include guard is built on, if a file is nothing but one.
///
/// The classic optimisation (6.10.2, and every compiler since 1987): a file
/// whose whole contents are
///
/// ```c
/// #ifndef GUARD
/// #define GUARD
/// …
/// #endif
/// ```
///
/// need not be read again while `GUARD` is defined, because reading it would
/// produce nothing. Recognising it is what keeps a header included from twenty
/// places from being lexed twenty times — and, here, from taking twenty copies
/// of its text into the source map.
fn detect_include_guard(toks: &[PTok]) -> Option<String> {
    // `#ifndef NAME`, with nothing else on the line.
    if !(toks.first()?.bol && toks[0].is_punct(Punct::Hash)) {
        return None;
    }
    if toks.get(1)?.name()? != "ifndef" {
        return None;
    }
    let name = toks.get(2)?.name()?.to_owned();
    let after_ifndef = toks.get(3)?;
    if !after_ifndef.bol && !after_ifndef.is_eof() {
        return None;
    }
    // `#define NAME` immediately after it.
    if !after_ifndef.is_punct(Punct::Hash)
        || toks.get(4)?.name()? != "define"
        || toks.get(5)?.name()? != name
    {
        return None;
    }

    // The `#endif` that closes it must be the last thing in the file.
    let mut depth = 0i32;
    let mut i = 0;
    while i < toks.len() && !toks[i].is_eof() {
        if toks[i].bol && toks[i].is_punct(Punct::Hash) {
            match toks.get(i + 1).and_then(PTok::name) {
                Some("if" | "ifdef" | "ifndef") => depth += 1,
                Some("endif") => {
                    depth -= 1;
                    if depth == 0 {
                        let mut j = i + 2;
                        while toks.get(j).is_some_and(|t| !t.bol && !t.is_eof()) {
                            j += 1;
                        }
                        return toks.get(j).is_none_or(PTok::is_eof).then_some(name);
                    }
                }
                _ => {}
            }
        }
        i += 1;
    }
    None
}

/// Applies the [`# #` rule](self#the----rule) to a replacement list.
fn fuse_hash_hash(rest: &[PTok]) -> Vec<PTok> {
    let mut body: Vec<PTok> = Vec::with_capacity(rest.len());
    let mut i = 0;
    while i < rest.len() {
        if rest[i].is_punct(Punct::Hash)
            && let Some(next) = rest.get(i + 1)
            && next.is_punct(Punct::Hash)
            && !next.bol
        {
            let mut fused = rest[i].clone();
            fused.kind = TokenKind::Punct(Punct::HashHash);
            fused.range = fused.range.join(next.range);
            body.push(fused);
            i += 2;
            continue;
        }
        body.push(rest[i].clone());
        i += 1;
    }
    if let Some(first) = body.first_mut() {
        // Leading white space is not part of a replacement list, and 6.10.3p2
        // compares two definitions on where their white space is.
        first.space = false;
    }
    body
}

// ---------------------------------------------------------------------------
// #if expressions
// ---------------------------------------------------------------------------

/// A value in an `#if` expression: `intmax_t` or `uintmax_t`, which C99 6.10.1
/// fixes as the only two types such an expression has.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Val {
    /// The value, held signed but normalised to whichever type `unsigned` says.
    v: i128,
    unsigned: bool,
}

impl Val {
    fn signed(v: i128) -> Val {
        Val {
            v: v as i64 as i128,
            unsigned: false,
        }
    }

    fn make(v: i128, unsigned: bool) -> Val {
        if unsigned {
            Val {
                v: (v as u64) as i128,
                unsigned,
            }
        } else {
            Val::signed(v)
        }
    }

    fn boolean(b: bool) -> Val {
        Val::signed(i128::from(b))
    }

    fn is_true(self) -> bool {
        self.v != 0
    }

    /// The value as it takes part in an operation of the given signedness.
    fn as_operand(self, unsigned: bool) -> i128 {
        if unsigned && self.v < 0 {
            self.v + (1i128 << 64)
        } else {
            self.v
        }
    }
}

impl Pp<'_> {
    /// Evaluates the controlling expression of an `#if` or `#elif`.
    fn eval_condition(&mut self, line: &[PTok], range: SourceRange) -> bool {
        // An `#if` may read `__SIZEOF_LONG__` or `_WIN32`, so from here on the
        // data model has been committed to; see `Pp::target_pragma`.
        self.model_observed = true;
        if line.is_empty() {
            self.diags.error(range, "#if with no expression");
            return false;
        }
        self.eval_expression(line, range)
            .is_some_and(|value| value != 0)
    }

    /// Evaluates a constant expression with the preprocessor's own arithmetic.
    ///
    /// `None` says something was wrong and has been reported. This is what
    /// `#if` asks a question of, and what `#embed`'s `limit(…)` parameter is.
    fn eval_expression(&mut self, line: &[PTok], range: SourceRange) -> Option<i128> {
        let prepared = self.resolve_defined(line, range)?;
        let mut expanded = self.expand_sequence(prepared);
        // A macro may expand to one of the `__has_…` operators — `#define
        // XXH_HAS_INCLUDE(x) __has_include(x)` is how headers guard their use,
        // and GCC answers the operator wherever it comes from — so those are
        // answered again after replacement. (`defined` produced by a macro is
        // undefined behaviour in 6.10.1p4; GCC evaluates it, and so does this.)
        if expanded.iter().any(|t| {
            t.name()
                .is_some_and(|n| n == "defined" || n.starts_with("__has_"))
        }) {
            expanded = self.resolve_defined(&expanded, range)?;
        }
        for tok in &expanded {
            let tok = tok.clone();
            self.report_errors(&tok);
        }
        let mut eval = Eval {
            toks: &expanded,
            pos: 0,
            fallback: range,
            errors: Vec::new(),
            depth: 0,
        };
        let value = eval.expression(true);
        if eval.errors.is_empty()
            && eval.pos < eval.toks.len()
            && let Some(tok) = eval.toks.get(eval.pos)
        {
            let found = tok.kind.describe();
            eval.errors.push(Diagnostic::error(
                tok.range,
                format!("unexpected {found} in a preprocessor expression"),
            ));
        }
        let failed = !eval.errors.is_empty();
        for diag in eval.errors {
            self.diags.push(diag);
        }
        (!failed).then_some(value.v)
    }

    /// Replaces every `defined X` and `defined(X)` with `1` or `0`.
    ///
    /// This happens before macro replacement, as 6.10.1p1 requires: the
    /// operand of `defined` is a name, not something a macro may rewrite.
    fn resolve_defined(&mut self, line: &[PTok], range: SourceRange) -> Option<Vec<PTok>> {
        let mut out = Vec::with_capacity(line.len());
        let mut i = 0;
        while i < line.len() {
            let tok = &line[i];
            // The `__has_…` family is answered here too, for the same reason
            // `defined` is: their operands are names and header names, not
            // things a macro may rewrite.
            if let Some(name) = tok.name()
                && name.starts_with("__has_")
            {
                let (value, end) = self.has_operator(name, line, i)?;
                let mut answer = tok.clone();
                answer.kind = int_token_kind(value);
                answer.hide = answer.hide.add(name);
                answer.errors.clear();
                out.push(answer);
                i = end;
                continue;
            }
            if tok.name() != Some("defined") {
                out.push(tok.clone());
                i += 1;
                continue;
            }
            let parenthesised = line.get(i + 1).is_some_and(|t| t.is_punct(Punct::LParen));
            let name_at = if parenthesised { i + 2 } else { i + 1 };
            let Some(name) = line.get(name_at).and_then(PTok::name) else {
                self.diags.error(
                    tok.range,
                    "operator 'defined' requires an identifier as its operand",
                );
                return None;
            };
            let defined = self.is_defined(name);
            let mut end = name_at + 1;
            if parenthesised {
                if !line.get(end).is_some_and(|t| t.is_punct(Punct::RParen)) {
                    self.diags.error(range, "missing ')' after 'defined'");
                    return None;
                }
                end += 1;
            }
            let mut value = tok.clone();
            value.kind = TokenKind::Int(IntLit {
                value: u128::from(defined),
                base: NumBase::Decimal,
                unsigned: false,
                long: LongKind::None,
                text: u8::from(defined).to_string(),
            });
            // Already answered: nothing here may be replaced again.
            value.hide = value.hide.add("defined");
            value.errors.clear();
            out.push(value);
            i = end;
        }
        Some(out)
    }

    /// Whether `name` counts as defined for `#ifdef`, `#ifndef`, `#elifdef`
    /// and `defined`: a macro, or one of the `__has_…` operators this
    /// preprocessor answers.
    ///
    /// GCC (since 10) defines its operators as special macros, and code that
    /// cares writes `#ifdef __has_include` before using one — xxHash's
    /// `XXH_HAS_INCLUDE`, `XXH_HAS_ATTRIBUTE` and `XXH_HAS_BUILTIN` are all
    /// built that way. An operator that is not answered here
    /// (`__has_cpp_attribute`, Clang's `__has_declspec_attribute`, which GCC
    /// does not define either) stays undefined.
    fn is_defined(&self, name: &str) -> bool {
        self.macros.contains_key(name) || HAS_OPERATORS.contains(&name)
    }

    /// Answers one `__has_…(…)` operator, returning its value and the index
    /// just past its closing `)`.
    ///
    /// Everything here is answered from `cinrs`'s own tables (see
    /// [`crate::gnu`]) rather than from GCC's, which is the point: a program
    /// that writes `#if __has_attribute(cleanup)` must be told *no*, because
    /// this implementation does not have it.
    fn has_operator(&mut self, name: &str, line: &[PTok], at: usize) -> Option<(u128, usize)> {
        let range = line[at].range;
        if !line.get(at + 1).is_some_and(|t| t.is_punct(Punct::LParen)) {
            // An identifier that is not an invocation is an ordinary one, and
            // 6.10.1p4 turns it into 0 like any other.
            return Some((0, at + 1));
        }
        let mut depth = 0i32;
        let mut end = at + 1;
        while end < line.len() {
            if line[end].is_punct(Punct::LParen) {
                depth += 1;
            } else if line[end].is_punct(Punct::RParen) {
                depth -= 1;
                if depth == 0 {
                    end += 1;
                    break;
                }
            }
            end += 1;
        }
        if depth != 0 {
            self.diags
                .error(range, format!("missing ')' after '{name}'"));
            return None;
        }
        let inner = &line[at + 2..end - 1];
        let value = match name {
            // The header name is spelled as it is in an `#include`, so it is
            // read out of the source text rather than out of the tokens.
            "__has_include" | "__has_include_next" => {
                let Some((header, form)) = self.operand_header_name(inner) else {
                    self.diags.error(
                        range,
                        format!("'{name}' expects \"FILENAME\" or <FILENAME>"),
                    );
                    return None;
                };
                // `__has_include_next` asks the question `#include_next`
                // answers: is there one *after* the place this file was found
                // in? Where there is no next place there is no next header,
                // and the answer is a plain no.
                let origin = self.cur().origin.clone();
                let found = if name == "__has_include_next" {
                    let current = self.cur().found_in.clone();
                    include::resolve_next(&header, &origin, current.as_ref(), &self.search)
                } else {
                    include::resolve(&header, form, &origin, &self.search)
                };
                u128::from(found.is_ok())
            }
            "__has_attribute" | "__has_declspec_attribute" => u128::from(
                inner
                    .first()
                    .and_then(PTok::name)
                    .is_some_and(crate::gnu::has_attribute),
            ),
            "__has_c_attribute" => inner
                .first()
                .and_then(PTok::name)
                .map_or(0, |n| u128::from(crate::gnu::has_c_attribute(n))),
            "__has_builtin" => u128::from(
                inner
                    .first()
                    .and_then(PTok::name)
                    .is_some_and(crate::gnu::has_builtin),
            ),
            "__has_feature" | "__has_extension" => u128::from(
                inner
                    .first()
                    .and_then(PTok::name)
                    .is_some_and(crate::gnu::has_feature),
            ),
            // C23 6.10.1p5: not found, found and empty, spelled with the same
            // three macros `<stdembed.h>` would have. Parameters after the
            // resource name are read so that an unknown one answers "not
            // found", which is what the clause asks for.
            "__has_embed" => {
                let Some((resource, form, after)) = self.embed_name_of(inner) else {
                    self.diags.error(
                        range,
                        format!("'{name}' expects \"RESOURCE\" or <RESOURCE>"),
                    );
                    return None;
                };
                let params = self.embed_parameters(&inner[after..], range, false);
                let origin = self.cur().origin.clone();
                match (
                    params,
                    include::resolve_embed(&resource, form, &origin, &self.search),
                ) {
                    (Some(params), Ok(found)) => {
                        let take = params.limit.unwrap_or(found.bytes.len());
                        if take == 0 || found.bytes.is_empty() {
                            EMBED_EMPTY
                        } else {
                            EMBED_FOUND
                        }
                    }
                    _ => EMBED_NOT_FOUND,
                }
            }
            _ => 0,
        };
        Some((value, end))
    }

    /// The header name written inside `__has_include(…)`.
    fn operand_header_name(&mut self, inner: &[PTok]) -> Option<(String, include::Form)> {
        let first = inner.first()?;
        let last = inner.last()?;
        let text = self.raw_text(first.range.start, last.range.end).trim();
        if let Some(found) = parse_header_name(text) {
            return Some(found);
        }
        // The name came out of a macro, so there is no source text to read: it
        // is rebuilt from the spellings, exactly as `#include MACRO` is.
        let expanded = self.expand_sequence(inner.to_vec());
        let mut spelled = String::new();
        for (i, tok) in expanded.iter().enumerate() {
            if i > 0 && tok.space {
                spelled.push(' ');
            }
            spelled.push_str(tok.spelling());
        }
        parse_header_name(&spelled)
    }
}

/// A recursive-descent evaluator over preprocessing tokens.
///
/// Separate from the parser's constant evaluator on purpose: this one works on
/// tokens rather than on an AST, has no types beyond `intmax_t`/`uintmax_t`,
/// turns every leftover identifier into `0`, and must not evaluate the
/// unreached arm of `&&`, `||` or `?:` — `#if defined(N) && 10/N` is a
/// perfectly ordinary thing to write.
struct Eval<'a> {
    toks: &'a [PTok],
    pos: usize,
    /// Where to report something that has no token of its own.
    fallback: SourceRange,
    errors: Vec<Diagnostic>,
    /// How deep the parentheses and `?:` are, so that `#if ((((…))))` becomes
    /// a diagnostic rather than a stack overflow inside a compiler.
    depth: u32,
}

/// How deeply an `#if` expression may nest; the parser's own limit, for the
/// same reason.
const MAX_EVAL_DEPTH: u32 = 200;

impl Eval<'_> {
    fn peek(&self) -> Option<&PTok> {
        self.toks.get(self.pos)
    }

    fn at(&self, p: Punct) -> bool {
        self.peek().is_some_and(|t| t.is_punct(p))
    }

    fn eat(&mut self, p: Punct) -> bool {
        if self.at(p) {
            self.pos += 1;
            return true;
        }
        false
    }

    fn range(&self) -> SourceRange {
        self.peek().map_or(self.fallback, |t| t.range)
    }

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

    /// `expr , expr` — the comma operator, which `#if` does allow.
    fn expression(&mut self, eval: bool) -> Val {
        self.depth += 1;
        if self.depth > MAX_EVAL_DEPTH {
            let range = self.range();
            self.error(range, "this preprocessor expression nests too deeply");
            // Consume the rest so that the caller's loops all terminate.
            self.pos = self.toks.len();
            self.depth -= 1;
            return Val::signed(0);
        }
        let mut value = self.conditional(eval);
        while self.eat(Punct::Comma) {
            value = self.conditional(eval);
        }
        self.depth -= 1;
        value
    }

    fn conditional(&mut self, eval: bool) -> Val {
        let cond = self.binary(0, eval);
        if !self.eat(Punct::Question) {
            return cond;
        }
        let take_then = cond.is_true();
        let then_value = self.expression(eval && take_then);
        if !self.eat(Punct::Colon) {
            let range = self.range();
            self.error(range, "expected ':' in a preprocessor expression");
            return cond;
        }
        let else_value = self.conditional(eval && !take_then);
        let (a, b) = (then_value, else_value);
        let unsigned = a.unsigned || b.unsigned;
        let picked = if take_then { a } else { b };
        Val::make(picked.as_operand(unsigned), unsigned)
    }

    /// Precedence climbing over the binary operators.
    fn binary(&mut self, min_prec: u8, eval: bool) -> Val {
        let mut lhs = self.unary(eval);
        loop {
            let Some((op, prec)) = self.peek().and_then(|t| binary_op(&t.kind)) else {
                return lhs;
            };
            if prec < min_prec {
                return lhs;
            }
            let op_range = self.range();
            self.pos += 1;
            // `&&` and `||` do not evaluate their right operand when the left
            // one already decides the answer.
            let rhs_eval = match op {
                BinOp::LogAnd => eval && lhs.is_true(),
                BinOp::LogOr => eval && !lhs.is_true(),
                _ => eval,
            };
            let rhs = self.binary(prec + 1, rhs_eval);
            lhs = self.apply(op, lhs, rhs, op_range, eval);
        }
    }

    fn apply(&mut self, op: BinOp, a: Val, b: Val, range: SourceRange, eval: bool) -> Val {
        use BinOp::*;
        if op == LogAnd {
            return Val::boolean(a.is_true() && b.is_true());
        }
        if op == LogOr {
            return Val::boolean(a.is_true() || b.is_true());
        }
        // The usual arithmetic conversions, in the only shape they have here:
        // if either operand is unsigned, both are.
        let unsigned = a.unsigned || b.unsigned;
        let (x, y) = (a.as_operand(unsigned), b.as_operand(unsigned));
        match op {
            Eq => Val::boolean(x == y),
            Ne => Val::boolean(x != y),
            Lt => Val::boolean(x < y),
            Gt => Val::boolean(x > y),
            Le => Val::boolean(x <= y),
            Ge => Val::boolean(x >= y),
            Add => Val::make(x.wrapping_add(y), unsigned),
            Sub => Val::make(x.wrapping_sub(y), unsigned),
            Mul => Val::make(x.wrapping_mul(y), unsigned),
            Div | Rem => {
                if y == 0 {
                    if eval {
                        self.error(range, "division by zero in a preprocessor expression");
                    }
                    return Val::make(0, unsigned);
                }
                let v = if op == Div {
                    x.wrapping_div(y)
                } else {
                    x.wrapping_rem(y)
                };
                Val::make(v, unsigned)
            }
            BitAnd => Val::make(x & y, unsigned),
            BitOr => Val::make(x | y, unsigned),
            BitXor => Val::make(x ^ y, unsigned),
            Shl => Val::make(x.wrapping_shl((y as u64 & 63) as u32), unsigned),
            Shr => {
                let count = (y as u64 & 63) as u32;
                if unsigned {
                    Val::make(((x as u64) >> count) as i128, unsigned)
                } else {
                    Val::make((x as i64 >> count) as i128, unsigned)
                }
            }
            LogAnd | LogOr => unreachable!("handled above"),
        }
    }

    fn unary(&mut self, eval: bool) -> Val {
        let range = self.range();
        if self.eat(Punct::Plus) {
            return self.unary(eval);
        }
        if self.eat(Punct::Minus) {
            let v = self.unary(eval);
            return Val::make(v.as_operand(v.unsigned).wrapping_neg(), v.unsigned);
        }
        if self.eat(Punct::Tilde) {
            let v = self.unary(eval);
            return Val::make(!v.as_operand(v.unsigned), v.unsigned);
        }
        if self.eat(Punct::Bang) {
            let v = self.unary(eval);
            return Val::boolean(!v.is_true());
        }
        if self.eat(Punct::LParen) {
            let v = self.expression(eval);
            if !self.eat(Punct::RParen) {
                let at = self.range();
                self.error(at, "expected ')' in a preprocessor expression");
            }
            return v;
        }
        self.primary(range)
    }

    fn primary(&mut self, range: SourceRange) -> Val {
        let Some(tok) = self.peek() else {
            self.error(range, "expected a value in a preprocessor expression");
            return Val::signed(0);
        };
        let value = match &tok.kind {
            TokenKind::Int(lit) => {
                // An `#if` has only `intmax_t` and `uintmax_t`; a constant is
                // unsigned when it says so or when it does not fit signed.
                let unsigned = lit.unsigned || lit.value > i64::MAX as u128;
                let too_large = lit.value > u64::MAX as u128;
                let value = Val::make((lit.value & u128::from(u64::MAX)) as i128, unsigned);
                if too_large {
                    let range = tok.range;
                    self.error(
                        range,
                        "integer constant is too large for a preprocessor expression",
                    );
                }
                value
            }
            TokenKind::Char(lit) => Val::signed(i128::from(lit.value)),
            TokenKind::Float(_) => {
                let range = tok.range;
                self.error(
                    range,
                    "a floating constant is not allowed in a preprocessor expression",
                );
                Val::signed(0)
            }
            TokenKind::Str(_) => {
                let range = tok.range;
                self.error(
                    range,
                    "a string literal is not allowed in a preprocessor expression",
                );
                Val::signed(0)
            }
            // C23 6.10.1p6: `true` and `false` are keywords there, and an
            // `#if` reads them as 1 and 0. Before C23 they are identifiers,
            // and the rule below turns them into 0 like any other.
            TokenKind::Keyword(lex::Keyword::True) => Val::signed(1),
            TokenKind::Keyword(lex::Keyword::False) => Val::signed(0),
            // 6.10.1p4: every identifier still standing after macro
            // replacement is replaced by 0.
            TokenKind::Ident(_) | TokenKind::Keyword(_) => Val::signed(0),
            other => {
                let range = tok.range;
                let found = other.describe();
                self.error(
                    range,
                    format!("unexpected {found} in a preprocessor expression"),
                );
                Val::signed(0)
            }
        };
        self.pos += 1;
        value
    }
}

/// The binary operators an `#if` expression may use.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum BinOp {
    LogOr,
    LogAnd,
    BitOr,
    BitXor,
    BitAnd,
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
    Shl,
    Shr,
    Add,
    Sub,
    Mul,
    Div,
    Rem,
}

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

// ---------------------------------------------------------------------------
// predefined macros
// ---------------------------------------------------------------------------

impl Standard {
    /// The value of `__STDC_VERSION__` for this revision, or `None` where the
    /// revision has none.
    ///
    /// C89 as published had no `__STDC_VERSION__` at all — Amendment 1 added
    /// it in 1995 — so `c89!` and `gnu89!` leave the macro undefined, which is
    /// what `gcc -std=c89` does and what a program testing
    /// `#ifdef __STDC_VERSION__` is looking for. `__STDC__` is still `1`.
    pub fn stdc_version(self) -> Option<&'static str> {
        Some(match self {
            Standard::C89 => return None,
            Standard::C99 => "199901L",
            Standard::C11 => "201112L",
            Standard::C17 => "201710L",
            Standard::C23 => "202311L",
        })
    }
}

impl Pp<'_> {
    fn define_predefined(&mut self, options: &Options) {
        self.define_object("__STDC__", "1");
        self.define_object("__STDC_HOSTED__", "1");
        if let Some(version) = options.standard.stdc_version() {
            self.define_object("__STDC_VERSION__", version);
        }
        // C11 6.10.8.3 makes four parts of the language optional and gives an
        // implementation a macro to say it left each one out. Two of them
        // depend on how this expansion was configured rather than on the
        // crate: complex arithmetic is absent when the `complex` feature is
        // off, in which case `_Complex` is a diagnostic and saying so turns
        // the gap into a conforming omission that a portable program can take
        // the other branch on; threads are absent on the targets whose C
        // library `<threads.h>` does not model, where that header is an
        // `#error` and the macro is what a program tests instead of hitting
        // it. The other two are *not* among them: `_Atomic`,
        // `<stdatomic.h>` and the `__atomic_*` builtins are all here, and so
        // are variable length arrays and the variably modified types built on
        // them — `int a[n][m]`, `int (*p)[n]`, `typedef int T[n]` and the
        // parameter forms — so neither `__STDC_NO_ATOMICS__` nor
        // `__STDC_NO_VLA__` is defined.
        //
        // `__STDC_IEC_559_COMPLEX__` is never defined either way: it claims
        // the whole of Annex G, and cinrs implements G.5.1's arithmetic
        // without claiming the rest of it.
        if !options.complex {
            self.define_object("__STDC_NO_COMPLEX__", "1");
        }
        if !threads_available(&options.target) {
            self.define_object("__STDC_NO_THREADS__", "1");
        }
        self.define_atomic_macros(options.target.max_scalar_align.min(8));
        // C11 7.28p2: these two say that `char16_t` and `char32_t` really are
        // UTF-16 and UTF-32, which is what the lexer encodes `u"…"` and `U"…"`
        // as. The value is the standard's own: the ISO/IEC 10646 revision the
        // encodings come from.
        self.define_object("__STDC_UTF_16__", "1");
        self.define_object("__STDC_UTF_32__", "1");
        // C23 6.10.1p5's three answers for `__has_embed`. GCC predefines them
        // in every mode it has, because a program that tests `__has_embed`
        // wants to compare against them whichever `-std=` it is compiled with.
        self.define_object("__STDC_EMBED_NOT_FOUND__", "0");
        self.define_object("__STDC_EMBED_FOUND__", "1");
        self.define_object("__STDC_EMBED_EMPTY__", "2");
        // Only a strict entry point is `-std=c99`; a GNU one is `-std=gnu99`.
        if !options.dialect.is_gnu() {
            self.define_object("__STRICT_ANSI__", "1");
        }
        // cinrs presents itself as GCC 14.2, because that is the version the
        // world's `__GNUC__` gates are written against: 4.2.1 (Clang's
        // habit) made libdeflate `#error` out ("gcc versions older than 4.9
        // are no longer supported") and switch its VPCLMULQDQ and AVX-VNNI
        // paths off, took xxHash's dispatcher off AVX2 and AVX-512
        // (`__GNUC__ > 4`), and sent glibc's `<math.h>` to its slow `_Generic`
        // fallback instead of `__builtin_isnan`. `__VERSION__` says both
        // things, GCC's number first because that is what a program parsing
        // it looks for, and `__CINRS__` below is the identity a program asks
        // for when it wants to know who really compiled it.
        self.define_object("__GNUC__", "14");
        self.define_object("__GNUC_MINOR__", "2");
        self.define_object("__GNUC_PATCHLEVEL__", "0");
        self.define_string(
            "__VERSION__",
            &format!("14.2.0 (cinrs {})", env!("CARGO_PKG_VERSION")),
        );
        self.define_object("__cinrs__", "1");
        self.define_object("__CINRS__", "1");
        self.define_object("__CINRS_MAJOR__", env!("CARGO_PKG_VERSION_MAJOR"));
        self.define_object("__CINRS_MINOR__", env!("CARGO_PKG_VERSION_MINOR"));
        self.define_object("__CINRS_PATCH__", env!("CARGO_PKG_VERSION_PATCH"));
        // What `inline` means, in GCC's words: C99's rules in every revision
        // that has them, GNU89's in `c89!` and `gnu89!`. cinrs models neither
        // set of external-definition rules — every definition becomes one
        // Rust function — and the two agree on the only thing a header asks
        // the macro for, which is how to spell an inline-only definition
        // (glibc's `__extern_inline`); `gnu_inline` is accepted either way.
        if matches!(options.standard, Standard::C89) {
            self.define_object("__GNUC_GNU_INLINE__", "1");
        } else {
            self.define_object("__GNUC_STDC_INLINE__", "1");
        }
        // GCC's intent for Annex F and Annex G, which glibc's
        // `<stdc-predef.h>` turns into `__STDC_IEC_559__` and
        // `__STDC_IEC_559_COMPLEX__` — and, read the other way, *claims* both
        // when these are undefined, as for a compiler older than 4.9. cinrs
        // claims neither (there is no `<fenv.h>`, and only G.5.1's arithmetic
        // of the complex annex), so the honest answer is `0`, which is what
        // GCC says under `-ffast-math`.
        self.define_object("__GCC_IEC_559", "0");
        self.define_object("__GCC_IEC_559_COMPLEX", "0");
        // What bare `__attribute__((aligned))` gives; see the parser.
        self.define_object("__BIGGEST_ALIGNMENT__", "16");
        // Fixed placeholders: a build has to give the same output twice.
        self.define_string("__DATE__", "??? ?? ????");
        self.define_string("__TIME__", "??:??:??");
        self.define_string("__TIMESTAMP__", "??? ??? ?? ??:??:?? ????");
        let base_file = self.base_file.clone();
        self.define_string("__BASE_FILE__", &base_file);
        self.define_builtin("__LINE__", Builtin::Line);
        self.define_builtin("__FILE__", Builtin::File);
        self.define_builtin("__FILE_NAME__", Builtin::FileName);
        self.define_builtin("__INCLUDE_LEVEL__", Builtin::IncludeLevel);
        self.define_builtin("__COUNTER__", Builtin::Counter);
        // GCC's `__builtin_LINE()`, `__builtin_FILE()` and
        // `__builtin_FUNCTION()` say what `__LINE__`, `__FILE__` and
        // `__func__` say; being macros rather than builtins is what makes
        // them report the *use* rather than the definition, exactly as GCC's
        // do for a default argument.
        self.define_function("__builtin_LINE", "__LINE__");
        self.define_function("__builtin_FILE", "__FILE__");
        self.define_function("__builtin_FUNCTION", "__func__");
        for (name, value) in target_macros(&options.target) {
            self.define_object(name, &value);
        }
    }

    /// The macros GCC predefines for the atomic builtins, in every mode.
    ///
    /// The six `__ATOMIC_*` values are the argument the `__atomic_*` family
    /// takes, and their numbering is GCC's own — `<stdatomic.h>`'s
    /// `memory_order` enumeration has the same values, because a program may
    /// pass either to either. The `__GCC_ATOMIC_*_LOCK_FREE` family answers
    /// `2`, "always lock free", for every type there is a Rust atomic of, and
    /// `<stdatomic.h>`'s `ATOMIC_*_LOCK_FREE` macros are defined from these.
    fn define_atomic_macros(&mut self, max_atomic: u64) {
        for (name, value) in [
            ("__ATOMIC_RELAXED", "0"),
            ("__ATOMIC_CONSUME", "1"),
            ("__ATOMIC_ACQUIRE", "2"),
            ("__ATOMIC_RELEASE", "3"),
            ("__ATOMIC_ACQ_REL", "4"),
            ("__ATOMIC_SEQ_CST", "5"),
        ] {
            self.define_object(name, value);
        }
        for name in [
            "__GCC_ATOMIC_BOOL_LOCK_FREE",
            "__GCC_ATOMIC_CHAR_LOCK_FREE",
            "__GCC_ATOMIC_CHAR8_T_LOCK_FREE",
            "__GCC_ATOMIC_CHAR16_T_LOCK_FREE",
            "__GCC_ATOMIC_CHAR32_T_LOCK_FREE",
            "__GCC_ATOMIC_WCHAR_T_LOCK_FREE",
            "__GCC_ATOMIC_SHORT_LOCK_FREE",
            "__GCC_ATOMIC_INT_LOCK_FREE",
            "__GCC_ATOMIC_LONG_LOCK_FREE",
            "__GCC_ATOMIC_LLONG_LOCK_FREE",
            "__GCC_ATOMIC_POINTER_LOCK_FREE",
        ] {
            self.define_object(name, "2");
        }
        // What `__atomic_test_and_set` writes, which GCC also predefines.
        self.define_object("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
        // The `__sync_*` family's own advertisement, which a program tests
        // before writing one of them. Eight bytes only where an eight-byte
        // object is aligned well enough for a lock-free instruction; see
        // `TargetModel::max_scalar_align`.
        for width in [1u64, 2, 4, 8] {
            if width <= max_atomic {
                self.define_object(
                    match width {
                        1 => "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1",
                        2 => "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2",
                        4 => "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4",
                        _ => "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8",
                    },
                    "1",
                );
            }
        }
    }

    /// Defines a predefined function-like macro that takes no arguments.
    fn define_function(&mut self, name: &str, body: &str) {
        let tokens = lex::lex_text(body, self.base, &self.lex_options);
        let body: Vec<PTok> = tokens
            .iter()
            .filter(|t| !matches!(t.kind, TokenKind::Eof))
            .map(PTok::from_lexed)
            .collect();
        self.macros.insert(
            name.to_owned(),
            Arc::new(MacroDef {
                params: Some(Vec::new()),
                variadic: false,
                va_name: None,
                body,
                name_range: SourceRange::at(self.base),
                predefined: true,
                site: DefSite::Program,
                builtin: None,
            }),
        );
    }

    /// Defines a predefined object-like macro from the C text of its body.
    fn define_object(&mut self, name: &str, body: &str) {
        let tokens = lex::lex_text(body, self.base, &self.lex_options);
        let body: Vec<PTok> = tokens
            .iter()
            .filter(|t| !matches!(t.kind, TokenKind::Eof))
            .map(PTok::from_lexed)
            .collect();
        self.insert_predefined(name, body, None);
    }

    /// Defines a predefined macro whose body is one string literal.
    fn define_string(&mut self, name: &str, value: &str) {
        let kind = string_token_kind(value);
        let body = vec![PTok {
            kind,
            range: SourceRange::at(self.base),
            bol: false,
            space: false,
            pad: None,
            trail: None,
            origin: Origin::Source,
            hide: HideSet::default(),
            errors: Vec::new(),
        }];
        self.insert_predefined(name, body, None);
    }

    fn define_builtin(&mut self, name: &str, builtin: Builtin) {
        self.insert_predefined(name, Vec::new(), Some(builtin));
    }

    fn insert_predefined(&mut self, name: &str, body: Vec<PTok>, builtin: Option<Builtin>) {
        self.macros.insert(
            name.to_owned(),
            Arc::new(MacroDef {
                params: None,
                variadic: false,
                va_name: None,
                body,
                name_range: SourceRange::at(self.base),
                predefined: true,
                site: DefSite::Program,
                builtin,
            }),
        );
    }
}

/// Whether the bundled `<threads.h>` declares anything on this target, which
/// is what decides `__STDC_NO_THREADS__` (C11 6.10.8.3).
///
/// The C11 thread types are blocks of bytes whose size belongs to the C
/// library rather than to C, so the header models the two libraries whose
/// layouts it knows — glibc and musl, both on Linux — and refuses everywhere
/// else: Apple's libSystem and the Microsoft UCRT have no `<threads.h>` at
/// all, and the BSDs, bionic and uClibc each lay the objects out their own
/// way. Where it refuses, the macro says so, which is what lets a portable
/// program take the other branch instead of hitting the `#error`.
fn threads_available(target: &TargetModel) -> bool {
    target.os == Os::Linux && matches!(target.env, Env::Gnu | Env::Musl)
}

/// The target description macros, every one of them derived from `target`.
///
/// Nothing here reads a `cfg!`: the model may be the host's or may be a
/// `CINRS_TARGET` away, and a macro that answered for the host while `sizeof`
/// answered for the target would send a header down the wrong branch — which
/// is exactly how the bundled `<errno.h>`, `<stdio.h>`, `<time.h>` and
/// `<wchar.h>` choose their platform, through `_WIN32` and `__APPLE__`.
///
/// Deliberately short. Anything a real header would test for that is not here
/// simply comes out as 0 in an `#if`, which is the behaviour a C program
/// written for an unknown compiler expects; claiming to *be* GCC or Clang
/// would invite code paths built on extensions this crate does not have.
fn target_macros(target: &TargetModel) -> Vec<(&'static str, String)> {
    // The architecture, the operating system and the object format; see
    // `TargetModel::macros`.
    let mut out: Vec<(&'static str, String)> = target.macros();
    let flag = |out: &mut Vec<(&'static str, String)>, name: &'static str| {
        out.push((name, "1".to_owned()))
    };

    // The data model, which is exactly what `TargetModel` describes.
    if target.ptr_bits == 64 && target.long_bits == 64 {
        flag(&mut out, "__LP64__");
        flag(&mut out, "_LP64");
    } else if target.ptr_bits == 32 && target.int_bits == 32 && target.long_bits == 32 {
        flag(&mut out, "__ILP32__");
        flag(&mut out, "_ILP32");
    }
    if !target.char_signed {
        flag(&mut out, "__CHAR_UNSIGNED__");
    }
    out.push(("__CHAR_BIT__", "8".to_owned()));
    out.push(("__SIZEOF_SHORT__", (target.short_bits / 8).to_string()));
    out.push(("__SIZEOF_INT__", (target.int_bits / 8).to_string()));
    out.push(("__SIZEOF_LONG__", (target.long_bits / 8).to_string()));
    out.push((
        "__SIZEOF_LONG_LONG__",
        (target.long_long_bits / 8).to_string(),
    ));
    out.push(("__SIZEOF_POINTER__", (target.ptr_bits / 8).to_string()));
    // The macro a program tests before writing `__int128`. GCC defines it
    // exactly where the type exists, which is on the 64-bit architectures, so
    // a program guarding on it takes the other branch on an ILP32 target
    // rather than meeting the diagnostic.
    if target.has_int128 {
        out.push(("__SIZEOF_INT128__", "16".to_owned()));
    }

    // The prefix the assembler puts in front of a C name, which GCC defines as
    // *nothing* on ELF and as `_` on Mach-O and on 32-bit COFF.
    //
    // It has to be here, empty body and all, because glibc builds every
    // large-file redirection out of it:
    //
    //     #define __ASMNAME(cname) __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
    //     #define __ASMNAME2(prefix, cname) __STRING (prefix) cname
    //     extern int open64 (…) __asm__ (__ASMNAME ("open64"));
    //
    // With the macro undefined, `__STRING` stringifies the *token* and the
    // symbol comes out as `__USER_LABEL_PREFIX__open64` — which compiles and
    // then fails to link, which is the worst kind of wrong. That is what
    // happened to SQLite under `#pragma cinrs system_include`, whose
    // `<fcntl.h>` and `<sys/stat.h>` are glibc's.
    out.push((
        "__USER_LABEL_PREFIX__",
        match (target.os, target.arch) {
            (Os::Darwin, _) => "_".to_owned(),
            // 32-bit COFF decorates; x86-64 PE does not.
            (Os::Windows, Arch::X86) => "_".to_owned(),
            _ => String::new(),
        },
    ));

    // Byte order, spelled the way GCC spells it.
    out.push(("__ORDER_LITTLE_ENDIAN__", "1234".to_owned()));
    out.push(("__ORDER_BIG_ENDIAN__", "4321".to_owned()));
    out.push(("__ORDER_PDP_ENDIAN__", "3412".to_owned()));
    let order = if target.big_endian { "4321" } else { "1234" };
    out.push(("__BYTE_ORDER__", order.to_owned()));
    // A `double`'s words are in the integers' order on every target modelled.
    out.push(("__FLOAT_WORD_ORDER__", order.to_owned()));
    limit_macros(target, &mut out);
    out
}

/// The largest value a signed type of `bits` bits holds, as a decimal string.
fn signed_max(bits: u32) -> String {
    ((1u128 << (bits - 1)) - 1).to_string()
}

/// The largest value an unsigned type of `bits` bits holds.
fn unsigned_max(bits: u32) -> String {
    (u128::MAX >> (128 - bits)).to_string()
}

/// GCC's `__INT_MAX__`, `__SIZE_TYPE__` and the rest of that family.
///
/// A great deal of portable C is written against these rather than against
/// `<limits.h>` and `<stdint.h>`, because they are available before any header
/// is included and are what those headers are written in terms of. GCC's own
/// torture suite uses `__INT_MAX__` in ninety-five files and `__SIZE_TYPE__`
/// in seventy, and a program that tests one of them and finds it undefined
/// does not fail to compile — it silently takes the wrong branch, which is
/// worse. So the whole family is defined here, from the same
/// [`TargetModel`] everything else is derived from.
///
/// The spellings of the *types* are GCC's own (`long unsigned int` rather than
/// `unsigned long`), because a program may paste one into a `typedef` and
/// diff the result, and the suffixes on the *values* are the ones that give
/// each constant the type its name says it has.
///
/// What is deliberately absent: `__OPTIMIZE__` (nothing here optimises) and
/// the `__INT8_C`-style function-like macros, which take an argument.
/// `__SIZEOF_INT128__` is not here but among the data-model macros, and only
/// on a target that has `__int128` at all.
fn limit_macros(target: &TargetModel, out: &mut Vec<(&'static str, String)>) {
    let int_bits = target.int_bits;
    let long_bits = target.long_bits;
    let llong_bits = target.long_long_bits;
    let ptr_bits = target.ptr_bits;

    // `size_t`, `ptrdiff_t` and `intptr_t` are the *narrowest* standard type
    // as wide as a pointer, which is how GCC picks them: `unsigned int` on
    // i686, `long unsigned int` on LP64, `long long unsigned int` on 64-bit
    // Windows, where `long` is only 32 bits.
    let (ptr_signed, ptr_unsigned, ptr_suffix) = if int_bits >= ptr_bits {
        ("int", "unsigned int", "")
    } else if long_bits >= ptr_bits {
        ("long int", "long unsigned int", "L")
    } else {
        ("long long int", "long long unsigned int", "LL")
    };
    // `intmax_t` is the widest standard integer type there is, which is
    // `long long` unless `long` is just as wide — GCC says `long int` on LP64
    // and `long long int` on i686 and on Windows. It does *not* follow the
    // pointer: an ILP32 target still has a 64-bit `intmax_t`, and C99 6.10.1
    // makes it the type all `#if` arithmetic is done in.
    let (max_signed, max_unsigned, max_suffix) = if long_bits >= llong_bits {
        ("long int", "long unsigned int", "L")
    } else {
        ("long long int", "long long unsigned int", "LL")
    };
    let max_bits = long_bits.max(llong_bits);

    let mut push = |name: &'static str, value: String| out.push((name, value));

    // The limits of the standard integer types.
    push("__SCHAR_MAX__", signed_max(8));
    push("__SHRT_MAX__", signed_max(target.short_bits));
    push("__INT_MAX__", signed_max(int_bits));
    push("__LONG_MAX__", format!("{}L", signed_max(long_bits)));
    push("__LONG_LONG_MAX__", format!("{}LL", signed_max(llong_bits)));

    // Their widths, which C23 added to <limits.h> and GCC has always had.
    // The two compilers do not spell the same set: GCC has
    // `__LONG_LONG_WIDTH__` and `__SCHAR_WIDTH__`, Clang has `__LLONG_WIDTH__`
    // and `__BOOL_WIDTH__`, and code in the wild tests whichever its author's
    // compiler had — `clang/test/C/drs/dr2xx.c` `#error`s out on
    // `__LLONG_WIDTH__` alone. So the *union* is defined, and the two
    // spellings of one width are one value by construction.
    push("__BOOL_WIDTH__", "1".to_owned());
    push("__SCHAR_WIDTH__", "8".to_owned());
    push("__SHRT_WIDTH__", target.short_bits.to_string());
    push("__INT_WIDTH__", int_bits.to_string());
    push("__LONG_WIDTH__", long_bits.to_string());
    push("__LONG_LONG_WIDTH__", llong_bits.to_string());
    push("__LLONG_WIDTH__", llong_bits.to_string());

    // The library types, and how wide each is.
    push("__SIZE_TYPE__", ptr_unsigned.to_owned());
    push(
        "__SIZE_MAX__",
        format!("{}U{ptr_suffix}", unsigned_max(ptr_bits)),
    );
    push("__SIZE_WIDTH__", ptr_bits.to_string());
    push("__SIZEOF_SIZE_T__", (ptr_bits / 8).to_string());
    push("__PTRDIFF_TYPE__", ptr_signed.to_owned());
    push(
        "__PTRDIFF_MAX__",
        format!("{}{ptr_suffix}", signed_max(ptr_bits)),
    );
    push("__PTRDIFF_WIDTH__", ptr_bits.to_string());
    push("__SIZEOF_PTRDIFF_T__", (ptr_bits / 8).to_string());
    push("__INTMAX_TYPE__", max_signed.to_owned());
    push(
        "__INTMAX_MAX__",
        format!("{}{max_suffix}", signed_max(max_bits)),
    );
    push("__INTMAX_WIDTH__", max_bits.to_string());
    push("__SIZEOF_INTMAX__", (max_bits / 8).to_string());
    push("__UINTMAX_TYPE__", max_unsigned.to_owned());
    push(
        "__UINTMAX_MAX__",
        format!("{}U{max_suffix}", unsigned_max(max_bits)),
    );
    push("__UINTMAX_WIDTH__", max_bits.to_string());
    push("__INTPTR_TYPE__", ptr_signed.to_owned());
    push(
        "__INTPTR_MAX__",
        format!("{}{ptr_suffix}", signed_max(ptr_bits)),
    );
    push("__INTPTR_WIDTH__", ptr_bits.to_string());
    push("__UINTPTR_TYPE__", ptr_unsigned.to_owned());
    push(
        "__UINTPTR_MAX__",
        format!("{}U{ptr_suffix}", unsigned_max(ptr_bits)),
    );
    push("__UINTPTR_WIDTH__", ptr_bits.to_string());
    push("__POINTER_WIDTH__", ptr_bits.to_string());

    // `wchar_t` and `wint_t`, which the bundled <stddef.h> and <wchar.h>
    // typedef from these very macros. Windows makes both 16 bits, Arm makes
    // `wchar_t` unsigned, and Apple makes `wint_t` an `int`.
    let wchar_bits = target.wchar_bits;
    let (wchar_type, wchar_max, wchar_min) = if target.wchar_signed {
        (
            if wchar_bits == 16 { "short int" } else { "int" },
            signed_max(wchar_bits),
            format!("(-{}-1)", signed_max(wchar_bits)),
        )
    } else {
        (
            if wchar_bits == 16 {
                "short unsigned int"
            } else {
                "unsigned int"
            },
            unsigned_max(wchar_bits),
            "0".to_owned(),
        )
    };
    push("__WCHAR_TYPE__", wchar_type.to_owned());
    push("__WCHAR_MAX__", wchar_max);
    push("__WCHAR_MIN__", wchar_min);
    push("__WCHAR_WIDTH__", wchar_bits.to_string());
    push("__SIZEOF_WCHAR_T__", (wchar_bits / 8).to_string());
    if !target.wchar_signed {
        push("__WCHAR_UNSIGNED__", "1".to_owned());
    }
    let wint_bits = target.wint_bits;
    push(
        "__WINT_TYPE__",
        match (target.wint_signed, wint_bits) {
            (true, 16) => "short int",
            (true, _) => "int",
            (false, 16) => "short unsigned int",
            (false, _) => "unsigned int",
        }
        .to_owned(),
    );
    push("__WINT_WIDTH__", wint_bits.to_string());
    push("__SIZEOF_WINT_T__", (wint_bits / 8).to_string());
    push("__SIG_ATOMIC_TYPE__", "int".to_owned());
    push("__SIG_ATOMIC_MAX__", signed_max(int_bits));
    push(
        "__SIG_ATOMIC_MIN__",
        format!("(-{}-1)", signed_max(int_bits)),
    );
    push("__SIG_ATOMIC_WIDTH__", int_bits.to_string());
    push("__CHAR16_TYPE__", "short unsigned int".to_owned());
    push("__CHAR32_TYPE__", "unsigned int".to_owned());

    // The floating types. `long double` is `double` here, and the values are
    // the ones `include/float.h` gives.
    push("__SIZEOF_FLOAT__", "4".to_owned());
    push("__SIZEOF_DOUBLE__", "8".to_owned());
    push("__SIZEOF_LONG_DOUBLE__", "8".to_owned());
    // Everything `<float.h>` says about a floating type, under the names GCC
    // gives it: a great deal of portable C tests `__DBL_MIN_EXP__` rather than
    // including the header, and a program that finds one of these undefined
    // does not fail to compile — it silently takes the wrong branch.
    // `execute/ieee/pr30704` is exactly that.
    push("__FLT_RADIX__", "2".to_owned());
    push("__FLT_EVAL_METHOD__", "0".to_owned());
    push("__FLT_EVAL_METHOD_TS_18661_3__", "0".to_owned());
    push("__FLT_MANT_DIG__", "24".to_owned());
    push("__FLT_DIG__", "6".to_owned());
    push("__FLT_MIN_EXP__", "(-125)".to_owned());
    push("__FLT_MIN_10_EXP__", "(-37)".to_owned());
    push("__FLT_MAX_EXP__", "128".to_owned());
    push("__FLT_MAX_10_EXP__", "38".to_owned());
    push("__FLT_DECIMAL_DIG__", "9".to_owned());
    push("__FLT_MAX__", "3.40282346638528859812e+38F".to_owned());
    push("__FLT_NORM_MAX__", "3.40282346638528859812e+38F".to_owned());
    push("__FLT_MIN__", "1.17549435082228750797e-38F".to_owned());
    push("__FLT_EPSILON__", "1.19209289550781250000e-7F".to_owned());
    push(
        "__FLT_DENORM_MIN__",
        "1.40129846432481707092e-45F".to_owned(),
    );
    push("__FLT_HAS_DENORM__", "1".to_owned());
    push("__FLT_HAS_INFINITY__", "1".to_owned());
    push("__FLT_HAS_QUIET_NAN__", "1".to_owned());
    push("__FLT_IS_IEC_60559__", "1".to_owned());
    push("__DBL_MANT_DIG__", "53".to_owned());
    push("__DBL_DIG__", "15".to_owned());
    push("__DBL_MIN_EXP__", "(-1021)".to_owned());
    push("__DBL_MIN_10_EXP__", "(-307)".to_owned());
    push("__DBL_MAX_EXP__", "1024".to_owned());
    push("__DBL_MAX_10_EXP__", "308".to_owned());
    push("__DBL_DECIMAL_DIG__", "17".to_owned());
    push("__DBL_MAX__", "1.79769313486231570815e+308".to_owned());
    push("__DBL_NORM_MAX__", "1.79769313486231570815e+308".to_owned());
    push("__DBL_MIN__", "2.22507385850720138309e-308".to_owned());
    push("__DBL_EPSILON__", "2.22044604925031308085e-16".to_owned());
    push(
        "__DBL_DENORM_MIN__",
        "4.94065645841246544177e-324".to_owned(),
    );
    push("__DBL_HAS_DENORM__", "1".to_owned());
    push("__DBL_HAS_INFINITY__", "1".to_owned());
    push("__DBL_HAS_QUIET_NAN__", "1".to_owned());
    push("__DBL_IS_IEC_60559__", "1".to_owned());
    // `long double` is `double` here — there is no portable Rust type with the
    // layout of an x87 extended double — so its family repeats `double`'s with
    // the suffix that gives each constant the type its name says it has, which
    // is what the bundled `<float.h>` does too.
    push("__LDBL_MANT_DIG__", "53".to_owned());
    push("__LDBL_DIG__", "15".to_owned());
    push("__LDBL_MIN_EXP__", "(-1021)".to_owned());
    push("__LDBL_MIN_10_EXP__", "(-307)".to_owned());
    push("__LDBL_MAX_EXP__", "1024".to_owned());
    push("__LDBL_MAX_10_EXP__", "308".to_owned());
    push("__LDBL_DECIMAL_DIG__", "17".to_owned());
    push("__DECIMAL_DIG__", "17".to_owned());
    push("__LDBL_MAX__", "1.79769313486231570815e+308L".to_owned());
    push(
        "__LDBL_NORM_MAX__",
        "1.79769313486231570815e+308L".to_owned(),
    );
    push("__LDBL_MIN__", "2.22507385850720138309e-308L".to_owned());
    push("__LDBL_EPSILON__", "2.22044604925031308085e-16L".to_owned());
    push(
        "__LDBL_DENORM_MIN__",
        "4.94065645841246544177e-324L".to_owned(),
    );
    push("__LDBL_HAS_DENORM__", "1".to_owned());
    push("__LDBL_HAS_INFINITY__", "1".to_owned());
    push("__LDBL_HAS_QUIET_NAN__", "1".to_owned());
    push("__LDBL_IS_IEC_60559__", "1".to_owned());

    // The exact-width types of <stdint.h>, which GCC's own <stdint.h> is
    // written in terms of. `int64_t` follows `long` wherever `long` is 64
    // bits, exactly as GCC has it.
    let (i64_type, u64_type, s64, u64) = if long_bits == 64 {
        ("long int", "long unsigned int", "L", "UL")
    } else {
        ("long long int", "long long unsigned int", "LL", "ULL")
    };
    let widths: [(
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        &'static str,
        u32,
    ); 4] = [
        ("8", "signed char", "unsigned char", "", "", 8),
        ("16", "short int", "short unsigned int", "", "", 16),
        ("32", "int", "unsigned int", "", "U", 32),
        ("64", i64_type, u64_type, s64, u64, 64),
    ];
    // The names have to be `'static`, so the four sets are written out rather
    // than built; the values still come from the loop above.
    const EXACT: [[&str; 8]; 4] = [
        [
            "__INT8_TYPE__",
            "__UINT8_TYPE__",
            "__INT8_MAX__",
            "__UINT8_MAX__",
            "__INT_LEAST8_TYPE__",
            "__UINT_LEAST8_TYPE__",
            "__INT_LEAST8_MAX__",
            "__UINT_LEAST8_MAX__",
        ],
        [
            "__INT16_TYPE__",
            "__UINT16_TYPE__",
            "__INT16_MAX__",
            "__UINT16_MAX__",
            "__INT_LEAST16_TYPE__",
            "__UINT_LEAST16_TYPE__",
            "__INT_LEAST16_MAX__",
            "__UINT_LEAST16_MAX__",
        ],
        [
            "__INT32_TYPE__",
            "__UINT32_TYPE__",
            "__INT32_MAX__",
            "__UINT32_MAX__",
            "__INT_LEAST32_TYPE__",
            "__UINT_LEAST32_TYPE__",
            "__INT_LEAST32_MAX__",
            "__UINT_LEAST32_MAX__",
        ],
        [
            "__INT64_TYPE__",
            "__UINT64_TYPE__",
            "__INT64_MAX__",
            "__UINT64_MAX__",
            "__INT_LEAST64_TYPE__",
            "__UINT_LEAST64_TYPE__",
            "__INT_LEAST64_MAX__",
            "__UINT_LEAST64_MAX__",
        ],
    ];
    for (names, (_, signed, unsigned, s_suffix, u_suffix, bits)) in EXACT.iter().zip(widths) {
        let smax = format!("{}{s_suffix}", signed_max(bits));
        let umax = format!("{}{u_suffix}", unsigned_max(bits));
        for at in [0, 4] {
            out.push((names[at], signed.to_owned()));
            out.push((names[at + 1], unsigned.to_owned()));
            out.push((names[at + 2], smax.clone()));
            out.push((names[at + 3], umax.clone()));
        }
    }

    // How wide each of those is. The `least` widths are exact by
    // construction; the `fast` ones follow the choice `include/stdint.h`
    // makes for the typedefs, so the macro and a `sizeof` on the type give
    // one answer. (`__BITINT_MAXWIDTH__` is deliberately absent: it is the
    // signal that `_BitInt` exists, and here it does not.)
    let fast_mid = if ptr_bits == 64 { "64" } else { "32" };
    for (name, value) in [
        ("__INT_LEAST8_WIDTH__", "8"),
        ("__INT_LEAST16_WIDTH__", "16"),
        ("__INT_LEAST32_WIDTH__", "32"),
        ("__INT_LEAST64_WIDTH__", "64"),
        ("__INT_FAST8_WIDTH__", "8"),
        ("__INT_FAST16_WIDTH__", fast_mid),
        ("__INT_FAST32_WIDTH__", fast_mid),
        ("__INT_FAST64_WIDTH__", "64"),
    ] {
        out.push((name, value.to_owned()));
    }
}