llvm-native-core 0.1.14

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! Builtin Header Definitions — compiler-provided standard library
//! headers.
//!
//! Clang ships builtin definitions for several standard C headers so
//! that a bare-metal or freestanding environment can compile standard
//! C programs without requiring a full C library installation.  The
//! definitions here match the behaviour of Clang's `lib/clang/*/include`
//! directory.
//!
//! Headers covered:
//! - `<stddef.h>`  — size_t, ptrdiff_t, NULL, offsetof, max_align_t,
//!   wchar_t, nullptr_t
//! - `<stdint.h>`  — exact-width integers, limits, size_max
//! - `<stdbool.h>` — bool, true, false
//! - `<stdarg.h>`  — va_list, va_start, va_arg, va_end, va_copy
//! - `<limits.h>`  — integer limits
//! - `<float.h>`   — floating-point characteristics
//! - `<iso646.h>`  — alternative operator spellings
//!
//! Additionally, compiler builtins for memory, type traits, overflow
//! arithmetic, and branch prediction hints are provided.
//!
//! Clean-room behavioural reconstruction from ISO C11/C17 and published
//! Clang documentation.  No LLVM/Clang source code is consulted.

use std::collections::HashMap;

// ═══════════════════════════════════════════════════════════════════════════
// Builtin Header Kind
// ═══════════════════════════════════════════════════════════════════════════

/// All builtin headers that the compiler can supply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinHeader {
    Stddef,
    Stdint,
    Stdbool,
    Stdarg,
    Limits,
    Float,
    Iso646,
    /// `<stdatomic.h>` — C11 atomics
    Stdatomic,
    /// `<stdalign.h>` — C11 alignas/alignof
    Stdalign,
    /// `<stdnoreturn.h>` — C11 noreturn
    Stdnoreturn,
    /// `<tgmath.h>` — type-generic math (stub)
    Tgmath,
    /// `<unwind.h>` — unwinding support
    Unwind,
    /// `<float.h>` extension: `<cfloat>` / `<float.h>` for C++
    Cfloat,
}

impl BuiltinHeader {
    /// The filename as it appears in `#include <...>`.
    pub fn filename(&self) -> &'static str {
        match self {
            Self::Stddef => "stddef.h",
            Self::Stdint => "stdint.h",
            Self::Stdbool => "stdbool.h",
            Self::Stdarg => "stdarg.h",
            Self::Limits => "limits.h",
            Self::Float => "float.h",
            Self::Iso646 => "iso646.h",
            Self::Stdatomic => "stdatomic.h",
            Self::Stdalign => "stdalign.h",
            Self::Stdnoreturn => "stdnoreturn.h",
            Self::Tgmath => "tgmath.h",
            Self::Unwind => "unwind.h",
            Self::Cfloat => "cfloat",
        }
    }

    /// Whether this header is standard in C89.
    pub fn is_c89(&self) -> bool {
        matches!(
            self,
            Self::Stddef | Self::Stdarg | Self::Limits | Self::Float
        )
    }

    /// Whether this header is standard in C99.
    pub fn is_c99(&self) -> bool {
        matches!(
            self,
            Self::Stddef
                | Self::Stdint
                | Self::Stdbool
                | Self::Stdarg
                | Self::Limits
                | Self::Float
                | Self::Iso646
                | Self::Tgmath
        )
    }

    /// Whether this header is standard in C11.
    pub fn is_c11(&self) -> bool {
        matches!(
            self,
            Self::Stddef
                | Self::Stdint
                | Self::Stdbool
                | Self::Stdarg
                | Self::Limits
                | Self::Float
                | Self::Iso646
                | Self::Stdatomic
                | Self::Stdalign
                | Self::Stdnoreturn
                | Self::Tgmath
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Builtin Header Generator
// ═══════════════════════════════════════════════════════════════════════════

/// Generates the content of compiler-provided builtin headers.
///
/// The generator knows about the target's pointer width, endianness,
/// and other properties that influence header content (e.g.  whether
/// `long` is 32 or 64 bits, the size of `wchar_t`).
#[derive(Debug, Clone)]
pub struct BuiltinHeaderGenerator {
    /// Target pointer width in bits (32 or 64).
    pub pointer_width: u32,
    /// Target `long` width in bits.
    pub long_width: u32,
    /// Target `long long` width in bits.
    pub long_long_width: u32,
    /// Target `wchar_t` width in bits (16 on Windows, 32 on most Unix).
    pub wchar_width: u32,
    /// Whether the target is little-endian.
    pub little_endian: bool,
    /// Target `int` width in bits.
    pub int_width: u32,
    /// Target `short` width in bits.
    pub short_width: u32,
    /// Target `char` width in bits (typically 8).
    pub char_width: u32,
    /// Whether `char` is signed.
    pub char_is_signed: bool,
    /// Maximum alignment in bytes for the target.
    pub max_alignment: u32,
    /// Whether to emit `__int128` support.
    pub has_int128: bool,
}

impl BuiltinHeaderGenerator {
    /// Create a generator for a typical x86-64 Linux target.
    pub fn new_x86_64_linux() -> Self {
        Self {
            pointer_width: 64,
            long_width: 64,
            long_long_width: 64,
            wchar_width: 32,
            little_endian: true,
            int_width: 32,
            short_width: 16,
            char_width: 8,
            char_is_signed: true,
            max_alignment: 16,
            has_int128: true,
        }
    }

    /// Create a generator for a typical 32-bit ARM target.
    pub fn new_arm_linux() -> Self {
        Self {
            pointer_width: 32,
            long_width: 32,
            long_long_width: 64,
            wchar_width: 32,
            little_endian: true,
            int_width: 32,
            short_width: 16,
            char_width: 8,
            char_is_signed: false, // ARM AAPCS: char is unsigned
            max_alignment: 8,
            has_int128: false,
        }
    }

    /// Create a generator for a typical AArch64 target.
    pub fn new_aarch64_linux() -> Self {
        Self {
            pointer_width: 64,
            long_width: 64,
            long_long_width: 64,
            wchar_width: 32,
            little_endian: true,
            int_width: 32,
            short_width: 16,
            char_width: 8,
            char_is_signed: false,
            max_alignment: 16,
            has_int128: true,
        }
    }

    /// Create a generator for a 32-bit x86 target.
    pub fn new_x86_linux() -> Self {
        Self {
            pointer_width: 32,
            long_width: 32,
            long_long_width: 64,
            wchar_width: 32,
            little_endian: true,
            int_width: 32,
            short_width: 16,
            char_width: 8,
            char_is_signed: true,
            max_alignment: 16,
            has_int128: false,
        }
    }

    // ── Full header content ──────────────────────────────────────────────

    /// Generate the content of a given builtin header.
    pub fn generate(&self, header: BuiltinHeader) -> String {
        match header {
            BuiltinHeader::Stddef => self.generate_stddef(),
            BuiltinHeader::Stdint => self.generate_stdint(),
            BuiltinHeader::Stdbool => self.generate_stdbool(),
            BuiltinHeader::Stdarg => self.generate_stdarg(),
            BuiltinHeader::Limits => self.generate_limits(),
            BuiltinHeader::Float => self.generate_float(),
            BuiltinHeader::Iso646 => self.generate_iso646(),
            BuiltinHeader::Stdatomic => self.generate_stdatomic(),
            BuiltinHeader::Stdalign => self.generate_stdalign(),
            BuiltinHeader::Stdnoreturn => self.generate_stdnoreturn(),
            BuiltinHeader::Tgmath => self.generate_tgmath(),
            BuiltinHeader::Unwind => self.generate_unwind(),
            BuiltinHeader::Cfloat => self.generate_float(), // same as float.h
        }
    }

    /// Generate all builtin headers at once, returning a map
    /// from filename to content.
    pub fn generate_all(&self) -> HashMap<String, String> {
        let mut map = HashMap::new();
        let all = [
            BuiltinHeader::Stddef,
            BuiltinHeader::Stdint,
            BuiltinHeader::Stdbool,
            BuiltinHeader::Stdarg,
            BuiltinHeader::Limits,
            BuiltinHeader::Float,
            BuiltinHeader::Iso646,
            BuiltinHeader::Stdatomic,
            BuiltinHeader::Stdalign,
            BuiltinHeader::Stdnoreturn,
            BuiltinHeader::Tgmath,
        ];
        for h in &all {
            map.insert(h.filename().to_string(), self.generate(*h));
        }
        map
    }

    // ── <stddef.h> ───────────────────────────────────────────────────────

    fn generate_stddef(&self) -> String {
        let mut s = String::new();

        // Include guard
        s.push_str("#ifndef __STDDEF_H\n");
        s.push_str("#define __STDDEF_H\n\n");

        // ── Common definitions ────────────────────────────────────────
        s.push_str("#if defined(__need_size_t) || defined(__need_ptrdiff_t) \\\n");
        s.push_str("    || defined(__need_wchar_t) || defined(__need_NULL) \\\n");
        s.push_str("    || defined(__need_max_align_t) || !defined(__STDDEF_H)\n");
        s.push_str("#define __STDDEF_H\n\n");

        // size_t
        s.push_str("#if !defined(__size_t_defined)\n");
        s.push_str("#define __size_t_defined\n");
        if self.pointer_width == 64 {
            s.push_str("typedef unsigned long size_t;\n");
        } else {
            s.push_str("typedef unsigned int size_t;\n");
        }
        s.push_str("#endif\n\n");

        // ptrdiff_t
        s.push_str("#if !defined(__ptrdiff_t_defined)\n");
        s.push_str("#define __ptrdiff_t_defined\n");
        if self.pointer_width == 64 {
            s.push_str("typedef long ptrdiff_t;\n");
        } else {
            s.push_str("typedef int ptrdiff_t;\n");
        }
        s.push_str("#endif\n\n");

        // NULL
        s.push_str("#if !defined(NULL)\n");
        s.push_str("#if defined(__cplusplus)\n");
        s.push_str("#if __cplusplus >= 201103L\n");
        s.push_str("#define NULL nullptr\n");
        s.push_str("#else\n");
        s.push_str("#define NULL 0\n");
        s.push_str("#endif\n");
        s.push_str("#else\n");
        s.push_str("#define NULL ((void*)0)\n");
        s.push_str("#endif\n");
        s.push_str("#endif\n\n");

        // offsetof
        s.push_str("#if !defined(offsetof)\n");
        s.push_str("#define offsetof(type, member) ");
        s.push_str("__builtin_offsetof(type, member)\n");
        s.push_str("#endif\n\n");

        // max_align_t
        s.push_str("#if !defined(__max_align_t_defined)\n");
        s.push_str("#define __max_align_t_defined\n");
        s.push_str("typedef struct {\n");
        if self.max_alignment >= 16 {
            s.push_str("  long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));\n");
            s.push_str("  long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));\n");
        } else if self.max_alignment >= 8 {
            s.push_str("  long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));\n");
            s.push_str(
                "  double __max_align_d __attribute__((__aligned__(__alignof__(double))));\n",
            );
        } else {
            s.push_str("  long __max_align_l __attribute__((__aligned__(__alignof__(long))));\n");
            s.push_str(
                "  double __max_align_d __attribute__((__aligned__(__alignof__(double))));\n",
            );
        }
        s.push_str("} max_align_t;\n");
        s.push_str("#endif\n\n");

        // wchar_t
        s.push_str("#if !defined(__wchar_t_defined)\n");
        s.push_str("#define __wchar_t_defined\n");
        if self.wchar_width == 16 {
            s.push_str("#ifndef __cplusplus\n");
            s.push_str("typedef unsigned short wchar_t;\n");
            s.push_str("#endif\n");
        } else {
            s.push_str("#ifndef __cplusplus\n");
            s.push_str("typedef int wchar_t;\n");
            s.push_str("#endif\n");
        }
        s.push_str("#endif\n\n");

        // nullptr_t (C23, C++11)
        s.push_str("#if !defined(__nullptr_t_defined)\n");
        s.push_str("#define __nullptr_t_defined\n");
        s.push_str("#if defined(__cplusplus) && __cplusplus >= 201103L\n");
        s.push_str("typedef decltype(nullptr) nullptr_t;\n");
        s.push_str("#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L\n");
        s.push_str("typedef typeof(nullptr) nullptr_t;\n");
        s.push_str("#endif\n");
        s.push_str("#endif\n\n");

        // unreachable (C23)
        s.push_str("#if !defined(unreachable)\n");
        s.push_str("#define unreachable() __builtin_unreachable()\n");
        s.push_str("#endif\n\n");

        s.push_str("#endif /* __STDDEF_H */\n");
        s
    }

    // ── <stdint.h> ───────────────────────────────────────────────────────

    fn generate_stdint(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDINT_H\n");
        s.push_str("#define __STDINT_H\n\n");

        // Include limits for integer widths if needed
        s.push_str("#ifndef __INT_WIDTH_STANDARD\n");
        s.push_str("#define __INT_WIDTH_STANDARD\n");
        s.push_str("#define __INT8_WIDTH__ 8\n");
        s.push_str("#define __INT16_WIDTH__ 16\n");
        s.push_str("#define __INT32_WIDTH__ 32\n");
        s.push_str("#define __INT64_WIDTH__ 64\n");
        s.push_str("#endif\n\n");

        // ── Exact-width integers ───────────────────────────────────────
        s.push_str("/* Exact-width integer types */\n");
        s.push_str("typedef signed char      int8_t;\n");
        s.push_str("typedef short            int16_t;\n");
        s.push_str("typedef int              int32_t;\n");
        if self.has_int128 {
            s.push_str("typedef long             int64_t;\n");
            s.push_str("#ifdef __SIZEOF_INT128__\n");
            s.push_str("typedef __int128          int128_t;\n");
            s.push_str("#endif\n");
        } else {
            s.push_str("typedef long long        int64_t;\n");
        }
        s.push_str("\n");
        s.push_str("typedef unsigned char      uint8_t;\n");
        s.push_str("typedef unsigned short     uint16_t;\n");
        s.push_str("typedef unsigned int       uint32_t;\n");
        if self.has_int128 {
            s.push_str("typedef unsigned long      uint64_t;\n");
            s.push_str("#ifdef __SIZEOF_INT128__\n");
            s.push_str("typedef unsigned __int128  uint128_t;\n");
            s.push_str("#endif\n");
        } else {
            s.push_str("typedef unsigned long long uint64_t;\n");
        }
        s.push_str("\n");

        // ── Minimum-width integers ─────────────────────────────────────
        s.push_str("/* Minimum-width integer types */\n");
        s.push_str("typedef signed char       int_least8_t;\n");
        s.push_str("typedef short             int_least16_t;\n");
        s.push_str("typedef int               int_least32_t;\n");
        if self.long_width >= 64 {
            s.push_str("typedef long              int_least64_t;\n");
        } else {
            s.push_str("typedef long long         int_least64_t;\n");
        }
        s.push_str("\n");
        s.push_str("typedef unsigned char      uint_least8_t;\n");
        s.push_str("typedef unsigned short     uint_least16_t;\n");
        s.push_str("typedef unsigned int       uint_least32_t;\n");
        if self.long_width >= 64 {
            s.push_str("typedef unsigned long      uint_least64_t;\n");
        } else {
            s.push_str("typedef unsigned long long uint_least64_t;\n");
        }
        s.push_str("\n");

        // ── Fastest minimum-width integers ─────────────────────────────
        s.push_str("/* Fastest minimum-width integer types */\n");
        s.push_str("typedef signed char       int_fast8_t;\n");
        s.push_str("typedef int               int_fast16_t;\n");
        s.push_str("typedef int               int_fast32_t;\n");
        if self.pointer_width == 64 {
            s.push_str("typedef long              int_fast64_t;\n");
        } else {
            s.push_str("typedef long long         int_fast64_t;\n");
        }
        s.push_str("\n");
        s.push_str("typedef unsigned char      uint_fast8_t;\n");
        s.push_str("typedef unsigned int       uint_fast16_t;\n");
        s.push_str("typedef unsigned int       uint_fast32_t;\n");
        if self.pointer_width == 64 {
            s.push_str("typedef unsigned long      uint_fast64_t;\n");
        } else {
            s.push_str("typedef unsigned long long uint_fast64_t;\n");
        }
        s.push_str("\n");

        // ── Pointer-sized integers ─────────────────────────────────────
        s.push_str("/* Integer types capable of holding object pointers */\n");
        if self.pointer_width == 64 {
            s.push_str("typedef long              intptr_t;\n");
            s.push_str("typedef unsigned long     uintptr_t;\n");
        } else {
            s.push_str("typedef int               intptr_t;\n");
            s.push_str("typedef unsigned int      uintptr_t;\n");
        }
        s.push_str("\n");

        // ── Greatest-width integers ────────────────────────────────────
        s.push_str("/* Greatest-width integer types */\n");
        if self.has_int128 {
            s.push_str("#ifdef __SIZEOF_INT128__\n");
            s.push_str("typedef __int128          intmax_t;\n");
            s.push_str("typedef unsigned __int128 uintmax_t;\n");
            s.push_str("#else\n");
            s.push_str("typedef long long         intmax_t;\n");
            s.push_str("typedef unsigned long long uintmax_t;\n");
            s.push_str("#endif\n");
        } else {
            s.push_str("typedef long long         intmax_t;\n");
            s.push_str("typedef unsigned long long uintmax_t;\n");
        }
        s.push_str("\n");

        // ── Limits of exact-width integers ─────────────────────────────
        s.push_str("/* Limits of exact-width integer types */\n");
        s.push_str("#define INT8_MIN   (-128)\n");
        s.push_str("#define INT8_MAX   (127)\n");
        s.push_str("#define UINT8_MAX  (255)\n\n");

        s.push_str("#define INT16_MIN  (-32768)\n");
        s.push_str("#define INT16_MAX  (32767)\n");
        s.push_str("#define UINT16_MAX (65535)\n\n");

        s.push_str("#define INT32_MIN  (-2147483647 - 1)\n");
        s.push_str("#define INT32_MAX  (2147483647)\n");
        s.push_str("#define UINT32_MAX (4294967295U)\n\n");

        if self.long_width >= 64 {
            s.push_str("#define INT64_MIN  (-9223372036854775807L - 1L)\n");
            s.push_str("#define INT64_MAX  (9223372036854775807L)\n");
            s.push_str("#define UINT64_MAX (18446744073709551615UL)\n\n");
        } else {
            s.push_str("#define INT64_MIN  (-9223372036854775807LL - 1LL)\n");
            s.push_str("#define INT64_MAX  (9223372036854775807LL)\n");
            s.push_str("#define UINT64_MAX (18446744073709551615ULL)\n\n");
        }

        // ── Limits of minimum-width integers ───────────────────────────
        s.push_str("/* Limits of minimum-width integer types */\n");
        s.push_str("#define INT_LEAST8_MIN   INT8_MIN\n");
        s.push_str("#define INT_LEAST8_MAX   INT8_MAX\n");
        s.push_str("#define UINT_LEAST8_MAX  UINT8_MAX\n\n");

        s.push_str("#define INT_LEAST16_MIN  INT16_MIN\n");
        s.push_str("#define INT_LEAST16_MAX  INT16_MAX\n");
        s.push_str("#define UINT_LEAST16_MAX UINT16_MAX\n\n");

        s.push_str("#define INT_LEAST32_MIN  INT32_MIN\n");
        s.push_str("#define INT_LEAST32_MAX  INT32_MAX\n");
        s.push_str("#define UINT_LEAST32_MAX UINT32_MAX\n\n");

        s.push_str("#define INT_LEAST64_MIN  INT64_MIN\n");
        s.push_str("#define INT_LEAST64_MAX  INT64_MAX\n");
        s.push_str("#define UINT_LEAST64_MAX UINT64_MAX\n\n");

        // ── Limits of fastest minimum-width integers ───────────────────
        s.push_str("/* Limits of fastest minimum-width integer types */\n");
        s.push_str("#define INT_FAST8_MIN   INT8_MIN\n");
        s.push_str("#define INT_FAST8_MAX   INT8_MAX\n");
        s.push_str("#define UINT_FAST8_MAX  UINT8_MAX\n\n");

        s.push_str("#define INT_FAST16_MIN  INT32_MIN\n");
        s.push_str("#define INT_FAST16_MAX  INT32_MAX\n");
        s.push_str("#define UINT_FAST16_MAX UINT32_MAX\n\n");

        s.push_str("#define INT_FAST32_MIN  INT32_MIN\n");
        s.push_str("#define INT_FAST32_MAX  INT32_MAX\n");
        s.push_str("#define UINT_FAST32_MAX UINT32_MAX\n\n");

        s.push_str("#define INT_FAST64_MIN  INT64_MIN\n");
        s.push_str("#define INT_FAST64_MAX  INT64_MAX\n");
        s.push_str("#define UINT_FAST64_MAX UINT64_MAX\n\n");

        // ── Limits of pointer-sized integers ───────────────────────────
        s.push_str("/* Limits of pointer-sized integer types */\n");
        if self.pointer_width == 64 {
            s.push_str("#define INTPTR_MIN  INT64_MIN\n");
            s.push_str("#define INTPTR_MAX  INT64_MAX\n");
            s.push_str("#define UINTPTR_MAX UINT64_MAX\n\n");
        } else {
            s.push_str("#define INTPTR_MIN  INT32_MIN\n");
            s.push_str("#define INTPTR_MAX  INT32_MAX\n");
            s.push_str("#define UINTPTR_MAX UINT32_MAX\n\n");
        }

        // ── Limits of greatest-width integers ──────────────────────────
        s.push_str("/* Limits of greatest-width integer types */\n");
        s.push_str("#define INTMAX_MIN  INT64_MIN\n");
        s.push_str("#define INTMAX_MAX  INT64_MAX\n");
        s.push_str("#define UINTMAX_MAX UINT64_MAX\n\n");

        // ── Limits of other integer types ──────────────────────────────
        s.push_str("/* Limits of other integer types */\n");

        // PTRDIFF_WIDTH, SIZE_MAX, etc.
        if self.pointer_width == 64 {
            s.push_str("#define PTRDIFF_MIN INT64_MIN\n");
            s.push_str("#define PTRDIFF_MAX INT64_MAX\n\n");
            s.push_str("#define SIZE_MAX UINT64_MAX\n\n");
        } else {
            s.push_str("#define PTRDIFF_MIN INT32_MIN\n");
            s.push_str("#define PTRDIFF_MAX INT32_MAX\n\n");
            s.push_str("#define SIZE_MAX UINT32_MAX\n\n");
        }

        // WCHAR_MIN, WCHAR_MAX
        if self.wchar_width == 16 {
            if self.char_is_signed {
                s.push_str("#define WCHAR_MIN (-32767 - 1)\n");
                s.push_str("#define WCHAR_MAX (32767)\n\n");
            } else {
                s.push_str("#define WCHAR_MIN (0)\n");
                s.push_str("#define WCHAR_MAX (65535)\n\n");
            }
        } else {
            if self.char_is_signed {
                s.push_str("#define WCHAR_MIN (-2147483647 - 1)\n");
                s.push_str("#define WCHAR_MAX (2147483647)\n\n");
            } else {
                s.push_str("#define WCHAR_MIN (0)\n");
                s.push_str("#define WCHAR_MAX (4294967295U)\n\n");
            }
        }

        // WINT_MIN, WINT_MAX
        s.push_str("#define WINT_MIN INT32_MIN\n");
        s.push_str("#define WINT_MAX INT32_MAX\n\n");

        // SIG_ATOMIC_MIN/MAX
        s.push_str("#define SIG_ATOMIC_MIN INT32_MIN\n");
        s.push_str("#define SIG_ATOMIC_MAX INT32_MAX\n\n");

        // ── Macros for integer constant expressions ────────────────────
        s.push_str("/* Macros for integer constant expressions */\n");
        s.push_str("#define INT8_C(c)  c\n");
        s.push_str("#define INT16_C(c) c\n");
        s.push_str("#define INT32_C(c) c\n");
        if self.long_width >= 64 {
            s.push_str("#define INT64_C(c) c ## L\n");
        } else {
            s.push_str("#define INT64_C(c) c ## LL\n");
        }
        s.push_str("#define INTMAX_C(c) c ## LL\n\n");

        s.push_str("#define UINT8_C(c)  c\n");
        s.push_str("#define UINT16_C(c) c\n");
        s.push_str("#define UINT32_C(c) c ## U\n");
        if self.long_width >= 64 {
            s.push_str("#define UINT64_C(c) c ## UL\n");
        } else {
            s.push_str("#define UINT64_C(c) c ## ULL\n");
        }
        s.push_str("#define UINTMAX_C(c) c ## ULL\n\n");

        s.push_str("#endif /* __STDINT_H */\n");
        s
    }

    // ── <stdbool.h> ──────────────────────────────────────────────────────

    fn generate_stdbool(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDBOOL_H\n");
        s.push_str("#define __STDBOOL_H\n\n");

        s.push_str("#ifndef __cplusplus\n\n");

        s.push_str("#define bool  _Bool\n");
        s.push_str("#define true  1\n");
        s.push_str("#define false 0\n\n");

        s.push_str("#else /* __cplusplus */\n\n");

        s.push_str("/* In C++, bool/true/false are keywords */\n");
        s.push_str("#define __bool_true_false_are_defined 1\n\n");

        s.push_str("#endif /* __cplusplus */\n\n");

        s.push_str("#define __bool_true_false_are_defined 1\n\n");

        s.push_str("#endif /* __STDBOOL_H */\n");
        s
    }

    // ── <stdarg.h> ───────────────────────────────────────────────────────

    fn generate_stdarg(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDARG_H\n");
        s.push_str("#define __STDARG_H\n\n");

        // va_list is compiler-provided
        s.push_str("/* va_list is provided by the compiler */\n");
        s.push_str("typedef __builtin_va_list va_list;\n\n");

        // va_start
        s.push_str("#define va_start(ap, param) ");
        s.push_str("__builtin_va_start(ap, param)\n\n");

        // va_arg
        s.push_str("#define va_arg(ap, type) ");
        s.push_str("__builtin_va_arg(ap, type)\n\n");

        // va_end
        s.push_str("#define va_end(ap) ");
        s.push_str("__builtin_va_end(ap)\n\n");

        // va_copy
        s.push_str("#define va_copy(dest, src) ");
        s.push_str("__builtin_va_copy(dest, src)\n\n");

        // __va_copy (legacy)
        s.push_str("/* Legacy synonym */\n");
        s.push_str("#ifndef __va_copy\n");
        s.push_str("#define __va_copy(dest, src) ");
        s.push_str("__builtin_va_copy(dest, src)\n");
        s.push_str("#endif\n\n");

        s.push_str("#endif /* __STDARG_H */\n");
        s
    }

    // ── <limits.h> ───────────────────────────────────────────────────────

    fn generate_limits(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __LIMITS_H\n");
        s.push_str("#define __LIMITS_H\n\n");

        // ── char widths ────────────────────────────────────────────────
        s.push_str("/* Number of bits in a character */\n");
        s.push_str("#define CHAR_BIT 8\n\n");

        // ── signed char limits ─────────────────────────────────────────
        s.push_str("/* Minimum and maximum values a 'signed char' can hold */\n");
        s.push_str("#define SCHAR_MIN (-128)\n");
        s.push_str("#define SCHAR_MAX 127\n\n");

        // ── unsigned char limits ───────────────────────────────────────
        s.push_str("/* Maximum value an 'unsigned char' can hold */\n");
        s.push_str("#define UCHAR_MAX 255\n\n");

        // ── char limits (depends on signedness) ────────────────────────
        s.push_str("/* Minimum and maximum values a 'char' can hold */\n");
        if self.char_is_signed {
            s.push_str("#define CHAR_MIN  SCHAR_MIN\n");
            s.push_str("#define CHAR_MAX  SCHAR_MAX\n\n");
        } else {
            s.push_str("#define CHAR_MIN  0\n");
            s.push_str("#define CHAR_MAX  UCHAR_MAX\n\n");
        }

        // ── short limits ───────────────────────────────────────────────
        s.push_str("/* Minimum and maximum values a 'short int' can hold */\n");
        if self.short_width == 16 {
            s.push_str("#define SHRT_MIN  (-32768)\n");
            s.push_str("#define SHRT_MAX  32767\n\n");
        } else {
            s.push_str("#define SHRT_MIN  (-32767 - 1)\n");
            s.push_str("#define SHRT_MAX  32767\n\n");
        }

        // ── unsigned short limits ──────────────────────────────────────
        s.push_str("/* Maximum value an 'unsigned short int' can hold */\n");
        if self.short_width == 16 {
            s.push_str("#define USHRT_MAX 65535\n\n");
        } else {
            s.push_str("#define USHRT_MAX 4294967295\n\n");
        }

        // ── int limits ─────────────────────────────────────────────────
        s.push_str("/* Minimum and maximum values an 'int' can hold */\n");
        if self.int_width == 32 {
            s.push_str("#define INT_MIN   (-2147483647 - 1)\n");
            s.push_str("#define INT_MAX   2147483647\n\n");
        } else if self.int_width == 16 {
            s.push_str("#define INT_MIN   (-32768)\n");
            s.push_str("#define INT_MAX   32767\n\n");
        } else {
            s.push_str("#define INT_MIN   (-32767 - 1)\n");
            s.push_str("#define INT_MAX   32767\n\n");
        }

        // ── unsigned int limits ────────────────────────────────────────
        s.push_str("/* Maximum value an 'unsigned int' can hold */\n");
        if self.int_width == 32 {
            s.push_str("#define UINT_MAX  4294967295U\n\n");
        } else {
            s.push_str("#define UINT_MAX  65535U\n\n");
        }

        // ── long limits ────────────────────────────────────────────────
        s.push_str("/* Minimum and maximum values a 'long int' can hold */\n");
        if self.long_width == 64 {
            s.push_str("#define LONG_MIN  (-9223372036854775807L - 1L)\n");
            s.push_str("#define LONG_MAX  9223372036854775807L\n\n");
        } else {
            s.push_str("#define LONG_MIN  (-2147483647L - 1L)\n");
            s.push_str("#define LONG_MAX  2147483647L\n\n");
        }

        // ── unsigned long limits ───────────────────────────────────────
        s.push_str("/* Maximum value an 'unsigned long int' can hold */\n");
        if self.long_width == 64 {
            s.push_str("#define ULONG_MAX 18446744073709551615UL\n\n");
        } else {
            s.push_str("#define ULONG_MAX 4294967295UL\n\n");
        }

        // ── long long limits ───────────────────────────────────────────
        s.push_str("/* Minimum and maximum values a 'long long int' can hold */\n");
        s.push_str("#define LLONG_MIN (-9223372036854775807LL - 1LL)\n");
        s.push_str("#define LLONG_MAX 9223372036854775807LL\n\n");

        // ── unsigned long long limits ──────────────────────────────────
        s.push_str("/* Maximum value an 'unsigned long long int' can hold */\n");
        s.push_str("#define ULLONG_MAX 18446744073709551615ULL\n\n");

        // ── Multibyte character limits ─────────────────────────────────
        s.push_str("#ifndef MB_LEN_MAX\n");
        s.push_str("#define MB_LEN_MAX 16\n");
        s.push_str("#endif\n\n");

        // ── POSIX extensions ───────────────────────────────────────────
        s.push_str("/* POSIX extensions */\n");
        if self.pointer_width == 64 {
            s.push_str("#define SSIZE_MAX LONG_MAX\n\n");
        } else {
            s.push_str("#define SSIZE_MAX INT_MAX\n\n");
        }

        s.push_str("#endif /* __LIMITS_H */\n");
        s
    }

    // ── <float.h> ────────────────────────────────────────────────────────

    fn generate_float(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __FLOAT_H\n");
        s.push_str("#define __FLOAT_H\n\n");

        // ── Characteristics of floating types ──────────────────────────
        s.push_str("/* Characteristics of floating-point types */\n\n");

        // float
        s.push_str("/* float */\n");
        s.push_str("#define FLT_RADIX 2\n");
        s.push_str("#define FLT_MANT_DIG 24\n");
        s.push_str("#define FLT_DIG 6\n");
        s.push_str("#define FLT_MIN_EXP (-125)\n");
        s.push_str("#define FLT_MIN_10_EXP (-37)\n");
        s.push_str("#define FLT_MAX_EXP 128\n");
        s.push_str("#define FLT_MAX_10_EXP 38\n");
        s.push_str("#define FLT_MIN 1.17549435082228750796873653722224568e-38F\n");
        s.push_str("#define FLT_MAX 3.40282346638528859811704183484516925e+38F\n");
        s.push_str("#define FLT_EPSILON 1.1920928955078125e-07F\n");
        s.push_str("#define FLT_TRUE_MIN 1.40129846432481707092372958328991613e-45F\n");
        s.push_str("#define FLT_HAS_SUBNORM 1\n");
        s.push_str("#define FLT_EVAL_METHOD 0\n");
        s.push_str("#define FLT_DECIMAL_DIG 9\n\n");

        // double
        s.push_str("/* double */\n");
        s.push_str("#define DBL_MANT_DIG 53\n");
        s.push_str("#define DBL_DIG 15\n");
        s.push_str("#define DBL_MIN_EXP (-1021)\n");
        s.push_str("#define DBL_MIN_10_EXP (-307)\n");
        s.push_str("#define DBL_MAX_EXP 1024\n");
        s.push_str("#define DBL_MAX_10_EXP 308\n");
        s.push_str("#define DBL_MIN 2.22507385850720138309023271733240406e-308\n");
        s.push_str("#define DBL_MAX 1.79769313486231570814527423731704357e+308\n");
        s.push_str("#define DBL_EPSILON 2.22044604925031308084726333618164062e-16\n");
        s.push_str("#define DBL_TRUE_MIN 4.94065645841246544176568792868221372e-324\n");
        s.push_str("#define DBL_HAS_SUBNORM 1\n");
        s.push_str("#define DBL_DECIMAL_DIG 17\n\n");

        // long double (80-bit x87 for x86; 128-bit for others)
        s.push_str("/* long double */\n");
        if self.pointer_width == 64 && self.little_endian {
            // x86-64 with 80-bit long double
            s.push_str("#define LDBL_MANT_DIG 64\n");
            s.push_str("#define LDBL_DIG 18\n");
            s.push_str("#define LDBL_MIN_EXP (-16381)\n");
            s.push_str("#define LDBL_MIN_10_EXP (-4931)\n");
            s.push_str("#define LDBL_MAX_EXP 16384\n");
            s.push_str("#define LDBL_MAX_10_EXP 4932\n");
            s.push_str("#define LDBL_MIN 3.36210314311209350626267781732175260e-4932L\n");
            s.push_str("#define LDBL_MAX 1.18973149535723176502126385303097021e+4932L\n");
            s.push_str("#define LDBL_EPSILON 1.08420217248550443400745280086994171e-19L\n");
            s.push_str("#define LDBL_TRUE_MIN 3.64519953188247460252840593361941982e-4951L\n");
            s.push_str("#define LDBL_HAS_SUBNORM 1\n");
            s.push_str("#define LDBL_DECIMAL_DIG 21\n\n");
        } else {
            // IEEE 128-bit or double-double
            s.push_str("#define LDBL_MANT_DIG 113\n");
            s.push_str("#define LDBL_DIG 33\n");
            s.push_str("#define LDBL_MIN_EXP (-16381)\n");
            s.push_str("#define LDBL_MIN_10_EXP (-4931)\n");
            s.push_str("#define LDBL_MAX_EXP 16384\n");
            s.push_str("#define LDBL_MAX_10_EXP 4932\n");
            s.push_str("#define LDBL_MIN 3.36210314311209350626267781732175260e-4932L\n");
            s.push_str("#define LDBL_MAX 1.18973149535723176502126385303097021e+4932L\n");
            s.push_str("#define LDBL_EPSILON 1.92592994438723585305597794258492732e-34L\n");
            s.push_str("#define LDBL_TRUE_MIN 6.47517511943802511092443895822764655e-4966L\n");
            s.push_str("#define LDBL_HAS_SUBNORM 1\n");
            s.push_str("#define LDBL_DECIMAL_DIG 36\n\n");
        }

        s.push_str("#endif /* __FLOAT_H */\n");
        s
    }

    // ── <iso646.h> ───────────────────────────────────────────────────────

    fn generate_iso646(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __ISO646_H\n");
        s.push_str("#define __ISO646_H\n\n");

        s.push_str("#ifndef __cplusplus\n\n");

        s.push_str("/* Alternative spellings for operators (ISO 646) */\n");
        s.push_str("#define and    &&\n");
        s.push_str("#define and_eq &=\n");
        s.push_str("#define bitand &\n");
        s.push_str("#define bitor  |\n");
        s.push_str("#define compl  ~\n");
        s.push_str("#define not    !\n");
        s.push_str("#define not_eq !=\n");
        s.push_str("#define or     ||\n");
        s.push_str("#define or_eq  |=\n");
        s.push_str("#define xor    ^\n");
        s.push_str("#define xor_eq ^=\n\n");

        s.push_str("#endif /* __cplusplus */\n\n");

        s.push_str("#endif /* __ISO646_H */\n");
        s
    }

    // ── <stdatomic.h> ────────────────────────────────────────────────────

    fn generate_stdatomic(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDATOMIC_H\n");
        s.push_str("#define __STDATOMIC_H\n\n");

        s.push_str("/* Atomic types and operations are compiler builtins */\n\n");

        s.push_str("typedef enum {\n");
        s.push_str("  memory_order_relaxed = __ATOMIC_RELAXED,\n");
        s.push_str("  memory_order_consume = __ATOMIC_CONSUME,\n");
        s.push_str("  memory_order_acquire = __ATOMIC_ACQUIRE,\n");
        s.push_str("  memory_order_release = __ATOMIC_RELEASE,\n");
        s.push_str("  memory_order_acq_rel = __ATOMIC_ACQ_REL,\n");
        s.push_str("  memory_order_seq_cst = __ATOMIC_SEQ_CST\n");
        s.push_str("} memory_order;\n\n");

        s.push_str("#define ATOMIC_BOOL_LOCK_FREE   2\n");
        s.push_str("#define ATOMIC_CHAR_LOCK_FREE   2\n");
        s.push_str("#define ATOMIC_CHAR16_T_LOCK_FREE 2\n");
        s.push_str("#define ATOMIC_CHAR32_T_LOCK_FREE 2\n");
        s.push_str("#define ATOMIC_WCHAR_T_LOCK_FREE 2\n");
        s.push_str("#define ATOMIC_SHORT_LOCK_FREE  2\n");
        s.push_str("#define ATOMIC_INT_LOCK_FREE    2\n");
        s.push_str("#define ATOMIC_LONG_LOCK_FREE   2\n");
        s.push_str("#define ATOMIC_LLONG_LOCK_FREE  2\n");
        s.push_str("#define ATOMIC_POINTER_LOCK_FREE 2\n\n");

        s.push_str("#define atomic_init(obj, value) __c11_atomic_init(obj, value)\n");
        s.push_str("#define atomic_load(obj) __c11_atomic_load(obj, memory_order_seq_cst)\n");
        s.push_str(
            "#define atomic_store(obj, val) __c11_atomic_store(obj, val, memory_order_seq_cst)\n",
        );
        s.push_str("#define atomic_exchange(obj, val) __c11_atomic_exchange(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_compare_exchange_strong(obj, exp, val) __c11_atomic_compare_exchange_strong(obj, exp, val, memory_order_seq_cst, memory_order_seq_cst)\n");
        s.push_str("#define atomic_compare_exchange_weak(obj, exp, val) __c11_atomic_compare_exchange_weak(obj, exp, val, memory_order_seq_cst, memory_order_seq_cst)\n");
        s.push_str("#define atomic_fetch_add(obj, val) __c11_atomic_fetch_add(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_fetch_sub(obj, val) __c11_atomic_fetch_sub(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_fetch_and(obj, val) __c11_atomic_fetch_and(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_fetch_or(obj, val)  __c11_atomic_fetch_or(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_fetch_xor(obj, val) __c11_atomic_fetch_xor(obj, val, memory_order_seq_cst)\n");
        s.push_str("#define atomic_thread_fence(order) __c11_atomic_thread_fence(order)\n");
        s.push_str("#define atomic_signal_fence(order) __c11_atomic_signal_fence(order)\n\n");

        s.push_str("#endif /* __STDATOMIC_H */\n");
        s
    }

    // ── <stdalign.h> ─────────────────────────────────────────────────────

    fn generate_stdalign(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDALIGN_H\n");
        s.push_str("#define __STDALIGN_H\n\n");

        s.push_str("#ifndef __cplusplus\n\n");

        s.push_str("/* alignas and alignof for C */\n");
        s.push_str("#define alignas _Alignas\n");
        s.push_str("#define alignof _Alignof\n\n");

        s.push_str("#define __alignas_is_defined 1\n");
        s.push_str("#define __alignof_is_defined 1\n\n");

        s.push_str("#endif /* __cplusplus */\n\n");

        s.push_str("#endif /* __STDALIGN_H */\n");
        s
    }

    // ── <stdnoreturn.h> ──────────────────────────────────────────────────

    fn generate_stdnoreturn(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __STDNORETURN_H\n");
        s.push_str("#define __STDNORETURN_H\n\n");

        s.push_str("#ifndef __cplusplus\n\n");

        s.push_str("/* noreturn for C */\n");
        s.push_str("#define noreturn _Noreturn\n\n");

        s.push_str("#endif /* __cplusplus */\n\n");

        s.push_str("#endif /* __STDNORETURN_H */\n");
        s
    }

    // ── <tgmath.h> ───────────────────────────────────────────────────────

    fn generate_tgmath(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __TGMATH_H\n");
        s.push_str("#define __TGMATH_H\n\n");

        s.push_str("/* Type-generic math is handled by compiler builtins */\n");
        s.push_str("#if __has_builtin(__builtin_tgmath)\n\n");

        // sin
        s.push_str("#define sin(x)   __builtin_tgmath(sinf, sin, sinl, x)\n");
        s.push_str("#define cos(x)   __builtin_tgmath(cosf, cos, cosl, x)\n");
        s.push_str("#define tan(x)   __builtin_tgmath(tanf, tan, tanl, x)\n");
        s.push_str("#define asin(x)  __builtin_tgmath(asinf, asin, asinl, x)\n");
        s.push_str("#define acos(x)  __builtin_tgmath(acosf, acos, acosl, x)\n");
        s.push_str("#define atan(x)  __builtin_tgmath(atanf, atan, atanl, x)\n");
        s.push_str("#define atan2(y,x) __builtin_tgmath(atan2f, atan2, atan2l, y, x)\n");
        s.push_str("#define sinh(x)  __builtin_tgmath(sinhf, sinh, sinhl, x)\n");
        s.push_str("#define cosh(x)  __builtin_tgmath(coshf, cosh, coshl, x)\n");
        s.push_str("#define tanh(x)  __builtin_tgmath(tanhf, tanh, tanhl, x)\n");
        s.push_str("#define exp(x)   __builtin_tgmath(expf, exp, expl, x)\n");
        s.push_str("#define log(x)   __builtin_tgmath(logf, log, logl, x)\n");
        s.push_str("#define log10(x) __builtin_tgmath(log10f, log10, log10l, x)\n");
        s.push_str("#define sqrt(x)  __builtin_tgmath(sqrtf, sqrt, sqrtl, x)\n");
        s.push_str("#define fabs(x)  __builtin_tgmath(fabsf, fabs, fabsl, x)\n");
        s.push_str("#define pow(x,y) __builtin_tgmath(powf, pow, powl, x, y)\n");
        s.push_str("#define ceil(x)  __builtin_tgmath(ceilf, ceil, ceill, x)\n");
        s.push_str("#define floor(x) __builtin_tgmath(floorf, floor, floorl, x)\n");
        s.push_str("#define fmod(x,y) __builtin_tgmath(fmodf, fmod, fmodl, x, y)\n\n");

        s.push_str("#endif /* __has_builtin(__builtin_tgmath) */\n\n");

        s.push_str("#endif /* __TGMATH_H */\n");
        s
    }

    // ── <unwind.h> ───────────────────────────────────────────────────────

    fn generate_unwind(&self) -> String {
        let mut s = String::new();

        s.push_str("#ifndef __UNWIND_H\n");
        s.push_str("#define __UNWIND_H\n\n");

        s.push_str("#ifdef __clang__\n\n");
        s.push_str("/* Unwinding types and functions */\n");
        s.push_str("typedef unsigned _Unwind_Word __attribute__((__mode__(__word__)));\n");
        if self.pointer_width == 64 {
            s.push_str("typedef unsigned _Unwind_Ptr __attribute__((__mode__(__DI__)));\n");
        } else {
            s.push_str("typedef unsigned _Unwind_Ptr __attribute__((__mode__(__SI__)));\n");
        }
        s.push_str(
            "typedef unsigned _Unwind_Exception_Class __attribute__((__mode__(__DI__)));\n\n",
        );

        s.push_str("struct _Unwind_Exception;\n");
        s.push_str("struct _Unwind_Context;\n\n");

        s.push_str("typedef void (*_Unwind_Exception_Cleanup_Fn)");
        s.push_str("(_Unwind_Reason_Code reason, struct _Unwind_Exception *exc);\n\n");

        s.push_str("struct _Unwind_Exception {\n");
        s.push_str("  _Unwind_Exception_Class exception_class;\n");
        s.push_str("  _Unwind_Exception_Cleanup_Fn exception_cleanup;\n");
        if self.pointer_width == 64 {
            s.push_str("  _Unwind_Word private_1;\n");
            s.push_str("  _Unwind_Word private_2;\n");
        } else {
            s.push_str("  _Unwind_Word private_1;\n");
        }
        s.push_str("} __attribute__((__aligned__));\n\n");

        s.push_str("typedef enum {\n");
        s.push_str("  _URC_NO_REASON = 0,\n");
        s.push_str("  _URC_FOREIGN_EXCEPTION_CAUGHT = 1,\n");
        s.push_str("  _URC_FATAL_PHASE2_ERROR = 2,\n");
        s.push_str("  _URC_FATAL_PHASE1_ERROR = 3,\n");
        s.push_str("  _URC_NORMAL_STOP = 4,\n");
        s.push_str("  _URC_END_OF_STACK = 5,\n");
        s.push_str("  _URC_HANDLER_FOUND = 6,\n");
        s.push_str("  _URC_INSTALL_CONTEXT = 7,\n");
        s.push_str("  _URC_CONTINUE_UNWIND = 8\n");
        s.push_str("} _Unwind_Reason_Code;\n\n");

        s.push_str("typedef enum {\n");
        s.push_str("  _UA_SEARCH_PHASE = 1,\n");
        s.push_str("  _UA_CLEANUP_PHASE = 2,\n");
        s.push_str("  _UA_HANDLER_FRAME = 4,\n");
        s.push_str("  _UA_FORCE_UNWIND = 8,\n");
        s.push_str("  _UA_END_OF_STACK = 16\n");
        s.push_str("} _Unwind_Action;\n\n");

        s.push_str("#endif /* __clang__ */\n\n");

        s.push_str("#endif /* __UNWIND_H */\n");
        s
    }
}

impl Default for BuiltinHeaderGenerator {
    fn default() -> Self {
        Self::new_x86_64_linux()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Compiler Builtin Declarations  (not header text, but semantic definitions)
// ═══════════════════════════════════════════════════════════════════════════

/// Semantic information for a compiler builtin function.
#[derive(Debug, Clone)]
pub struct BuiltinFunction {
    /// The builtin name (e.g. `"__builtin_alloca"`).
    pub name: String,
    /// How many operands the builtin takes.
    pub num_operands: usize,
    /// Whether the builtin returns a value.
    pub has_return: bool,
    /// Whether the builtin is pure (no side effects aside from its
    /// operands).
    pub is_pure: bool,
    /// Whether the builtin never returns (like `__builtin_unreachable`).
    pub is_noreturn: bool,
    /// Whether the builtin is const (no side effects, deterministic).
    pub is_const: bool,
    /// Whether the builtin is a "returns twice" function (e.g. `fork`,
    /// `setjmp`).
    pub returns_twice: bool,
    /// Category tag for grouping related builtins.
    pub category: BuiltinCategory,
}

/// Category of compiler builtin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinCategory {
    Memory,
    Math,
    String,
    Io,
    Atomic,
    Vector,
    TypeTrait,
    Overflow,
    Expect,
    ObjectSize,
    Prefetch,
    Trap,
    Other,
}

/// Registry of known compiler builtins with their semantics.
#[derive(Debug, Clone)]
pub struct BuiltinRegistry {
    builtins: HashMap<String, BuiltinFunction>,
}

impl BuiltinRegistry {
    pub fn new() -> Self {
        let mut reg = Self {
            builtins: HashMap::new(),
        };
        reg.register_defaults();
        reg
    }

    fn register(&mut self, name: &str, func: BuiltinFunction) {
        self.builtins.insert(name.to_string(), func);
    }

    fn register_defaults(&mut self) {
        // ── Memory builtins ─────────────────────────────────────────
        self.register(
            "__builtin_alloca",
            BuiltinFunction {
                name: "__builtin_alloca".into(),
                num_operands: 1,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
        self.register(
            "__builtin_alloca_with_align",
            BuiltinFunction {
                name: "__builtin_alloca_with_align".into(),
                num_operands: 2,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
        self.register(
            "__builtin_assume_aligned",
            BuiltinFunction {
                name: "__builtin_assume_aligned".into(),
                num_operands: 2,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
        self.register(
            "__builtin_memcpy",
            BuiltinFunction {
                name: "__builtin_memcpy".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
        self.register(
            "__builtin_memmove",
            BuiltinFunction {
                name: "__builtin_memmove".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
        self.register(
            "__builtin_memset",
            BuiltinFunction {
                name: "__builtin_memset".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );

        // ── Type trait builtins ─────────────────────────────────────
        self.register(
            "__builtin_types_compatible_p",
            BuiltinFunction {
                name: "__builtin_types_compatible_p".into(),
                num_operands: 2,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::TypeTrait,
            },
        );
        self.register(
            "__builtin_choose_expr",
            BuiltinFunction {
                name: "__builtin_choose_expr".into(),
                num_operands: 3,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::TypeTrait,
            },
        );
        self.register(
            "__builtin_is_constant_evaluated",
            BuiltinFunction {
                name: "__builtin_is_constant_evaluated".into(),
                num_operands: 0,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::TypeTrait,
            },
        );

        // ── Overflow builtins ───────────────────────────────────────
        self.register(
            "__builtin_add_overflow",
            BuiltinFunction {
                name: "__builtin_add_overflow".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );
        self.register(
            "__builtin_sub_overflow",
            BuiltinFunction {
                name: "__builtin_sub_overflow".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );
        self.register(
            "__builtin_mul_overflow",
            BuiltinFunction {
                name: "__builtin_mul_overflow".into(),
                num_operands: 3,
                has_return: true,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );
        self.register(
            "__builtin_add_overflow_p",
            BuiltinFunction {
                name: "__builtin_add_overflow_p".into(),
                num_operands: 3,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );
        self.register(
            "__builtin_sub_overflow_p",
            BuiltinFunction {
                name: "__builtin_sub_overflow_p".into(),
                num_operands: 3,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );
        self.register(
            "__builtin_mul_overflow_p",
            BuiltinFunction {
                name: "__builtin_mul_overflow_p".into(),
                num_operands: 3,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::Overflow,
            },
        );

        // ── Expect / likelihood builtins ────────────────────────────
        self.register(
            "__builtin_expect",
            BuiltinFunction {
                name: "__builtin_expect".into(),
                num_operands: 2,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Expect,
            },
        );
        self.register(
            "__builtin_expect_with_probability",
            BuiltinFunction {
                name: "__builtin_expect_with_probability".into(),
                num_operands: 3,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Expect,
            },
        );
        self.register(
            "__builtin_unpredictable",
            BuiltinFunction {
                name: "__builtin_unpredictable".into(),
                num_operands: 1,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Expect,
            },
        );

        // ── Object size / bounds checking ───────────────────────────
        self.register(
            "__builtin_object_size",
            BuiltinFunction {
                name: "__builtin_object_size".into(),
                num_operands: 2,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: true,
                returns_twice: false,
                category: BuiltinCategory::ObjectSize,
            },
        );
        self.register(
            "__builtin_dynamic_object_size",
            BuiltinFunction {
                name: "__builtin_dynamic_object_size".into(),
                num_operands: 2,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::ObjectSize,
            },
        );

        // ── Prefetch ────────────────────────────────────────────────
        self.register(
            "__builtin_prefetch",
            BuiltinFunction {
                name: "__builtin_prefetch".into(),
                num_operands: 3,
                has_return: false,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Prefetch,
            },
        );

        // ── Trap / unreachable ──────────────────────────────────────
        self.register(
            "__builtin_trap",
            BuiltinFunction {
                name: "__builtin_trap".into(),
                num_operands: 0,
                has_return: false,
                is_pure: false,
                is_noreturn: true,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Trap,
            },
        );
        self.register(
            "__builtin_unreachable",
            BuiltinFunction {
                name: "__builtin_unreachable".into(),
                num_operands: 0,
                has_return: false,
                is_pure: false,
                is_noreturn: true,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Trap,
            },
        );
        self.register(
            "__builtin_debugtrap",
            BuiltinFunction {
                name: "__builtin_debugtrap".into(),
                num_operands: 0,
                has_return: false,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Trap,
            },
        );

        // ── Miscellaneous ───────────────────────────────────────────
        self.register(
            "__builtin_return_address",
            BuiltinFunction {
                name: "__builtin_return_address".into(),
                num_operands: 1,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Other,
            },
        );
        self.register(
            "__builtin_frame_address",
            BuiltinFunction {
                name: "__builtin_frame_address".into(),
                num_operands: 1,
                has_return: true,
                is_pure: true,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Other,
            },
        );
        self.register(
            "__builtin___clear_cache",
            BuiltinFunction {
                name: "__builtin___clear_cache".into(),
                num_operands: 2,
                has_return: false,
                is_pure: false,
                is_noreturn: false,
                is_const: false,
                returns_twice: false,
                category: BuiltinCategory::Memory,
            },
        );
    }

    /// Look up a builtin by name.
    pub fn lookup(&self, name: &str) -> Option<&BuiltinFunction> {
        self.builtins.get(name)
    }

    /// Check whether a given function name is a known compiler builtin.
    pub fn is_builtin(&self, name: &str) -> bool {
        self.builtins.contains_key(name)
    }

    /// List all registered builtin names.
    pub fn builtin_names(&self) -> Vec<&String> {
        self.builtins.keys().collect()
    }

    /// Get the count of registered builtins.
    pub fn builtin_count(&self) -> usize {
        self.builtins.len()
    }
}

impl Default for BuiltinRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Builtin Header Include Resolver
// ═══════════════════════════════════════════════════════════════════════════

/// Resolves `#include` requests for compiler-provided builtin headers.
///
/// When the preprocessor encounters `#include <stddef.h>` and the
/// platform does not have a system header, the resolver provides the
/// compiler-generated content.
#[derive(Debug, Clone)]
pub struct BuiltinIncludeResolver {
    generator: BuiltinHeaderGenerator,
    cache: HashMap<String, String>,
}

impl BuiltinIncludeResolver {
    pub fn new(generator: BuiltinHeaderGenerator) -> Self {
        Self {
            generator,
            cache: HashMap::new(),
        }
    }

    /// Look up the content of a builtin header by its include name.
    pub fn resolve(&mut self, header_name: &str) -> Option<&str> {
        // Normalise the header name
        let normalized = header_name
            .trim_matches('"')
            .trim_matches('<')
            .trim_matches('>');

        // Try all known builtin headers
        let all = [
            BuiltinHeader::Stddef,
            BuiltinHeader::Stdint,
            BuiltinHeader::Stdbool,
            BuiltinHeader::Stdarg,
            BuiltinHeader::Limits,
            BuiltinHeader::Float,
            BuiltinHeader::Iso646,
            BuiltinHeader::Stdatomic,
            BuiltinHeader::Stdalign,
            BuiltinHeader::Stdnoreturn,
            BuiltinHeader::Tgmath,
            BuiltinHeader::Unwind,
            BuiltinHeader::Cfloat,
        ];

        for h in &all {
            if h.filename() == normalized {
                let entry = self.cache.entry(h.filename().to_string());
                let content = entry.or_insert_with(|| self.generator.generate(*h));
                return Some(content.as_str());
            }
        }

        None
    }

    /// Check whether a given include name is a known builtin header.
    pub fn is_builtin_header(&self, header_name: &str) -> bool {
        let normalized = header_name
            .trim_matches('"')
            .trim_matches('<')
            .trim_matches('>');
        let all = [
            BuiltinHeader::Stddef,
            BuiltinHeader::Stdint,
            BuiltinHeader::Stdbool,
            BuiltinHeader::Stdarg,
            BuiltinHeader::Limits,
            BuiltinHeader::Float,
            BuiltinHeader::Iso646,
            BuiltinHeader::Stdatomic,
            BuiltinHeader::Stdalign,
            BuiltinHeader::Stdnoreturn,
            BuiltinHeader::Tgmath,
            BuiltinHeader::Unwind,
        ];
        all.iter().any(|h| h.filename() == normalized)
    }

    /// Pre-warm the cache with all known builtin headers.
    pub fn prewarm_cache(&mut self) {
        self.generator
            .generate_all()
            .into_iter()
            .for_each(|(k, v)| {
                self.cache.insert(k, v);
            });
    }

    /// Clear the cache (to pick up target changes).
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }
}

impl Default for BuiltinIncludeResolver {
    fn default() -> Self {
        Self::new(BuiltinHeaderGenerator::default())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builtin_header_filename() {
        assert_eq!(BuiltinHeader::Stddef.filename(), "stddef.h");
        assert_eq!(BuiltinHeader::Stdint.filename(), "stdint.h");
        assert_eq!(BuiltinHeader::Stdbool.filename(), "stdbool.h");
        assert_eq!(BuiltinHeader::Stdarg.filename(), "stdarg.h");
        assert_eq!(BuiltinHeader::Limits.filename(), "limits.h");
        assert_eq!(BuiltinHeader::Float.filename(), "float.h");
        assert_eq!(BuiltinHeader::Iso646.filename(), "iso646.h");
    }

    #[test]
    fn test_builtin_header_categories() {
        assert!(BuiltinHeader::Stddef.is_c89());
        assert!(BuiltinHeader::Limits.is_c89());
        assert!(!BuiltinHeader::Stdbool.is_c89());
        assert!(BuiltinHeader::Stdbool.is_c99());
        assert!(BuiltinHeader::Stdatomic.is_c11());
        assert!(!BuiltinHeader::Stdatomic.is_c89());
    }

    #[test]
    fn test_generate_stddef_x86_64() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stddef);
        assert!(content.contains("typedef unsigned long size_t;"));
        assert!(content.contains("typedef long ptrdiff_t;"));
        assert!(content.contains("__builtin_offsetof"));
        assert!(content.contains("max_align_t"));
        assert!(content.contains("NULL"));
    }

    #[test]
    fn test_generate_stdint_x86_64() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdint);
        assert!(content.contains("int8_t"));
        assert!(content.contains("uint64_t"));
        assert!(content.contains("INT32_MAX"));
        assert!(content.contains("SIZE_MAX"));
    }

    #[test]
    fn test_generate_stdbool() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdbool);
        assert!(content.contains("#define bool  _Bool"));
        assert!(content.contains("#define true  1"));
        assert!(content.contains("#define false 0"));
        assert!(content.contains("__bool_true_false_are_defined"));
    }

    #[test]
    fn test_generate_stdarg() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdarg);
        assert!(content.contains("__builtin_va_list"));
        assert!(content.contains("__builtin_va_start"));
        assert!(content.contains("__builtin_va_arg"));
        assert!(content.contains("__builtin_va_end"));
        assert!(content.contains("__builtin_va_copy"));
    }

    #[test]
    fn test_generate_limits_x86_64() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Limits);
        assert!(content.contains("CHAR_BIT"));
        assert!(content.contains("SCHAR_MIN"));
        assert!(content.contains("LONG_MAX"));
        assert!(content.contains("ULLONG_MAX"));
    }

    #[test]
    fn test_generate_limits_arm() {
        let gen = BuiltinHeaderGenerator::new_arm_linux();
        let content = gen.generate(BuiltinHeader::Limits);
        assert!(content.contains("CHAR_MIN  0")); // unsigned char on ARM
        assert!(content.contains("LONG_MAX  2147483647L"));
    }

    #[test]
    fn test_generate_float() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Float);
        assert!(content.contains("FLT_RADIX 2"));
        assert!(content.contains("FLT_MANT_DIG"));
        assert!(content.contains("DBL_EPSILON"));
        assert!(content.contains("LDBL_MANT_DIG"));
    }

    #[test]
    fn test_generate_iso646() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Iso646);
        assert!(content.contains("#define and    &&"));
        assert!(content.contains("#define or     ||"));
        assert!(content.contains("#define not    !"));
        assert!(content.contains("#define xor    ^"));
    }

    #[test]
    fn test_generate_stdatomic() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdatomic);
        assert!(content.contains("memory_order_seq_cst"));
        assert!(content.contains("ATOMIC_BOOL_LOCK_FREE"));
        assert!(content.contains("__c11_atomic_init"));
    }

    #[test]
    fn test_generate_stdalign() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdalign);
        assert!(content.contains("#define alignas _Alignas"));
        assert!(content.contains("#define alignof _Alignof"));
    }

    #[test]
    fn test_generate_stdnoreturn() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdnoreturn);
        assert!(content.contains("#define noreturn _Noreturn"));
    }

    #[test]
    fn test_generate_tgmath() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Tgmath);
        assert!(content.contains("__builtin_tgmath"));
        assert!(content.contains("sin"));
        assert!(content.contains("sqrt"));
    }

    #[test]
    fn test_generate_unwind() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Unwind);
        assert!(content.contains("_Unwind_Exception"));
        assert!(content.contains("_Unwind_Reason_Code"));
        assert!(content.contains("_URC_END_OF_STACK"));
    }

    #[test]
    fn test_generate_all() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let map = gen.generate_all();
        assert!(map.contains_key("stddef.h"));
        assert!(map.contains_key("stdint.h"));
        assert!(map.contains_key("stdbool.h"));
        assert!(map.contains_key("stdarg.h"));
        assert!(map.contains_key("limits.h"));
        assert!(map.contains_key("float.h"));
    }

    #[test]
    fn test_builtin_registry_memory() {
        let reg = BuiltinRegistry::new();
        let ba = reg.lookup("__builtin_alloca").unwrap();
        assert_eq!(ba.num_operands, 1);
        assert!(ba.has_return);

        let bm = reg.lookup("__builtin_memcpy").unwrap();
        assert_eq!(bm.num_operands, 3);
        assert_eq!(bm.category, BuiltinCategory::Memory);
    }

    #[test]
    fn test_builtin_registry_type_trait() {
        let reg = BuiltinRegistry::new();
        let bt = reg.lookup("__builtin_types_compatible_p").unwrap();
        assert!(bt.is_const);
        assert_eq!(bt.category, BuiltinCategory::TypeTrait);

        let bc = reg.lookup("__builtin_choose_expr").unwrap();
        assert_eq!(bc.num_operands, 3);
    }

    #[test]
    fn test_builtin_registry_overflow() {
        let reg = BuiltinRegistry::new();
        let ba = reg.lookup("__builtin_add_overflow").unwrap();
        assert_eq!(ba.category, BuiltinCategory::Overflow);
        assert_eq!(ba.num_operands, 3);

        let bm = reg.lookup("__builtin_mul_overflow").unwrap();
        assert_eq!(bm.category, BuiltinCategory::Overflow);

        assert!(reg.lookup("__builtin_sub_overflow").is_some());
    }

    #[test]
    fn test_builtin_registry_expect() {
        let reg = BuiltinRegistry::new();
        let be = reg.lookup("__builtin_expect").unwrap();
        assert_eq!(be.category, BuiltinCategory::Expect);
        assert!(be.is_pure);

        let bp = reg.lookup("__builtin_expect_with_probability").unwrap();
        assert_eq!(bp.num_operands, 3);
    }

    #[test]
    fn test_builtin_registry_trap() {
        let reg = BuiltinRegistry::new();
        let bt = reg.lookup("__builtin_trap").unwrap();
        assert!(bt.is_noreturn);

        let bu = reg.lookup("__builtin_unreachable").unwrap();
        assert!(bu.is_noreturn);
    }

    #[test]
    fn test_builtin_registry_count() {
        let reg = BuiltinRegistry::new();
        assert!(reg.builtin_count() >= 20);
    }

    #[test]
    fn test_builtin_registry_is_builtin() {
        let reg = BuiltinRegistry::new();
        assert!(reg.is_builtin("__builtin_memset"));
        assert!(!reg.is_builtin("nonexistent_func"));
    }

    #[test]
    fn test_builtin_include_resolver_resolve() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let mut resolver = BuiltinIncludeResolver::new(gen);
        let content = resolver.resolve("stddef.h").unwrap();
        assert!(content.contains("size_t"));
    }

    #[test]
    fn test_builtin_include_resolver_is_builtin_header() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let resolver = BuiltinIncludeResolver::new(gen);
        assert!(resolver.is_builtin_header("stddef.h"));
        assert!(resolver.is_builtin_header("stdint.h"));
        assert!(!resolver.is_builtin_header("stdio.h")); // not a builtin
    }

    #[test]
    fn test_builtin_include_resolver_cache() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let mut resolver = BuiltinIncludeResolver::new(gen);
        // First call triggers generation
        let _c1 = resolver.resolve("stddef.h").unwrap();
        // Second call should use cache
        let _c2 = resolver.resolve("stddef.h").unwrap();
    }

    #[test]
    fn test_generator_new_aarch64() {
        let gen = BuiltinHeaderGenerator::new_aarch64_linux();
        assert_eq!(gen.pointer_width, 64);
        assert!(!gen.char_is_signed); // ARM variant
    }

    #[test]
    fn test_generator_new_x86() {
        let gen = BuiltinHeaderGenerator::new_x86_linux();
        assert_eq!(gen.pointer_width, 32);
        assert_eq!(gen.long_width, 32);
        let content = gen.generate(BuiltinHeader::Stdint);
        // 32-bit targets use long long for int64
        assert!(content.contains("long long"));
    }

    #[test]
    fn test_builtin_header_attributes() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stddef);
        assert!(content.contains("__attribute__((__aligned__"));
    }

    #[test]
    fn test_generate_float_double_epsilon() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Float);
        assert!(content.contains("DBL_EPSILON"));
        assert!(content.contains("FLT_EPSILON"));
    }

    #[test]
    fn test_generate_stdint_constant_macros_x86_64() {
        let gen = BuiltinHeaderGenerator::new_x86_64_linux();
        let content = gen.generate(BuiltinHeader::Stdint);
        // On 64-bit, int64 uses L suffix
        assert!(content.contains("INT64_C(c) c ## L"));
    }

    #[test]
    fn test_generate_stdint_ptr_x86_32() {
        let gen = BuiltinHeaderGenerator::new_x86_linux();
        let content = gen.generate(BuiltinHeader::Stdint);
        assert!(content.contains("typedef int               intptr_t;"));
    }
}