llvm-native-core 0.1.5

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
//! Clang Self-Hosting Stage 2 — Bootstrap verification beyond Stage 1.
//!
//! This module implements complete bootstrap verification:
//! - Stage2 compiler compilation: build llvm-native with Stage1 compiler
//! - Stage2 vs Stage1 artifact comparison: binary hashes, IR, assembly
//! - Stage3 bootstrap: compile llvm-native with Stage2, compare Stage2 vs Stage3
//! - Deterministic compilation verification: same input → byte-identical output
//! - Cross-compilation self-hosting: build for different target from host
//! - Bootstrap test suite: compile entire C test suite with bootstrapped compiler
//! - Bootstrap C++ support: compile C++ standard library with bootstrapped compiler
//! - Performance comparison: Stage1 vs Stage2 vs Stage3 compile time/output size/runtime
//! - Regression detection: detect if bootstrapped compiler produces different output
//! - SelfHostDatabase: store bootstrap results across versions for trend analysis
//! - SelfHostReport: generate comprehensive markdown report with pass/fail/diff details
//!
//! Clean-room behavioral reconstruction from GCC/Clang bootstrap documentation
//! and published compiler engineering literature. No LLVM source consulted.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use super::clang_selfhost::{
    ArtifactRecord, BootstrapStage, CompileCompareResult, CompileRunResult, CompileStats,
    CompilerTestCase, CompilerTestSuite, SelfHostConfig, SelfHostReport, StageArtifacts,
    StageComparison, StagePerformance, StageResult, TestCaseResult, TestExpectation,
    TestSuiteResult,
};

// ═══════════════════════════════════════════════════════════════════════════════
// Stage2 Bootstrap Runner
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration specific to the Stage2+ bootstrap verification.
#[derive(Debug, Clone)]
pub struct BootstrapStage2Config {
    /// Path to the Stage1 compiler binary.
    pub stage1_compiler_path: PathBuf,
    /// Path to the Stage2 compiler output (to be built).
    pub stage2_compiler_path: PathBuf,
    /// Path to the Stage3 compiler output.
    pub stage3_compiler_path: PathBuf,
    /// Build directory for Stage2.
    pub stage2_build_dir: PathBuf,
    /// Build directory for Stage3.
    pub stage3_build_dir: PathBuf,
    /// Whether to perform byte-for-byte comparison of binaries.
    pub byte_for_byte_compare: bool,
    /// Whether to compare LLVM IR output between stages.
    pub ir_compare: bool,
    /// Whether to compare assembly output between stages.
    pub asm_compare: bool,
    /// Whether to run the test suite with each stage's compiler.
    pub run_test_suite: bool,
    /// Whether to profile compile time of each stage.
    pub profile_performance: bool,
    /// Whether to strip debug info before comparing (ignores debug metadata diffs).
    pub strip_debug_before_compare: bool,
    /// Whether to verify deterministic compilation.
    pub verify_determinism: bool,
    /// Number of deterministic compilation rounds to perform.
    pub determinism_rounds: u32,
    /// Cross-compilation targets for self-hosting verification.
    pub cross_targets: Vec<String>,
    /// Maximum number of differing bytes to report.
    pub max_diff_lines: usize,
    /// Timeout for each stage build (seconds).
    pub stage_timeout_secs: u64,
    /// Number of parallel build jobs.
    pub parallel_jobs: u32,
}

impl Default for BootstrapStage2Config {
    fn default() -> Self {
        Self {
            stage1_compiler_path: PathBuf::from("build/stage1/bin/clang"),
            stage2_compiler_path: PathBuf::from("build/stage2/bin/clang"),
            stage3_compiler_path: PathBuf::from("build/stage3/bin/clang"),
            stage2_build_dir: PathBuf::from("build/stage2"),
            stage3_build_dir: PathBuf::from("build/stage3"),
            byte_for_byte_compare: true,
            ir_compare: true,
            asm_compare: true,
            run_test_suite: true,
            profile_performance: true,
            strip_debug_before_compare: false,
            verify_determinism: true,
            determinism_rounds: 3,
            cross_targets: vec![],
            max_diff_lines: 200,
            stage_timeout_secs: 7200,
            parallel_jobs: 4,
        }
    }
}

impl BootstrapStage2Config {
    pub fn new(stage1: &Path, stage2: &Path, stage3: &Path) -> Self {
        Self {
            stage1_compiler_path: stage1.to_path_buf(),
            stage2_compiler_path: stage2.to_path_buf(),
            stage3_compiler_path: stage3.to_path_buf(),
            ..Default::default()
        }
    }

    pub fn with_cross_target(mut self, target: &str) -> Self {
        self.cross_targets.push(target.to_string());
        self
    }

    pub fn with_determinism_rounds(mut self, rounds: u32) -> Self {
        self.determinism_rounds = rounds;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Bootstrap Stage 2 Engine
// ═══════════════════════════════════════════════════════════════════════════════

/// The Stage2 bootstrap engine orchestrates the full multi-stage bootstrap
/// verification process.
pub struct BootstrapStage2Runner {
    pub config: BootstrapStage2Config,
    pub base_config: SelfHostConfig,
    /// Results from each stage of the bootstrap.
    pub stage_results: Vec<StageBootstrapResult>,
    /// Comparisons between stages.
    pub comparisons: Vec<StageBootstrapComparison>,
    /// Artifact records per stage.
    pub artifacts: HashMap<BootstrapStage, StageArtifacts>,
    /// Performance metrics per stage.
    pub performance: Vec<StagePerformance>,
    /// Test suite results per stage.
    pub test_results: Vec<TestSuiteResult>,
    /// Determinism verification results.
    pub determinism_results: Vec<DeterminismResult>,
    /// Start time for total elapsed tracking.
    start_time: Instant,
}

/// Result for a single bootstrap stage build.
#[derive(Debug, Clone)]
pub struct StageBootstrapResult {
    pub stage: BootstrapStage,
    pub success: bool,
    pub compiler_built: bool,
    pub compiler_path: PathBuf,
    pub binary_size_bytes: u64,
    pub object_count: u32,
    pub warning_count: u32,
    pub error_count: u32,
    pub duration: Duration,
    pub peak_memory_bytes: u64,
    pub artifacts: Vec<ArtifactRecord>,
    pub error_message: Option<String>,
}

impl StageBootstrapResult {
    pub fn new(stage: BootstrapStage) -> Self {
        Self {
            stage,
            success: false,
            compiler_built: false,
            compiler_path: PathBuf::new(),
            binary_size_bytes: 0,
            object_count: 0,
            warning_count: 0,
            error_count: 0,
            duration: Duration::ZERO,
            peak_memory_bytes: 0,
            artifacts: Vec::new(),
            error_message: None,
        }
    }

    pub fn mark_success(&mut self, compiler_path: &Path, size: u64, objects: u32) {
        self.success = true;
        self.compiler_built = true;
        self.compiler_path = compiler_path.to_path_buf();
        self.binary_size_bytes = size;
        self.object_count = objects;
    }

    pub fn mark_failure(&mut self, error: &str) {
        self.success = false;
        self.compiler_built = false;
        self.error_message = Some(error.to_string());
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Stage Comparison
// ═══════════════════════════════════════════════════════════════════════════════

/// Comparison between two bootstrap stages.
#[derive(Debug, Clone)]
pub struct StageBootstrapComparison {
    pub earlier_stage: BootstrapStage,
    pub later_stage: BootstrapStage,
    /// Are the compiler binaries byte-for-byte identical?
    pub byte_identical: bool,
    /// Number of differing bytes (if not identical).
    pub differing_bytes: usize,
    /// Do the compilers produce identical IR for the same input?
    pub ir_match: bool,
    /// IR diff line count.
    pub ir_diff_lines: usize,
    /// Do the compilers produce identical assembly for the same input?
    pub asm_match: bool,
    /// Assembly diff line count.
    pub asm_diff_lines: usize,
    /// Do the compiled test programs behave identically?
    pub behavior_match: bool,
    /// Behavior diff count.
    pub behavioral_diff_count: usize,
    /// Human-readable description of the comparison.
    pub description: String,
    /// Overall assessment: is the bootstrap consistent?
    pub bootstrap_consistent: bool,
}

impl StageBootstrapComparison {
    pub fn new(earlier: BootstrapStage, later: BootstrapStage) -> Self {
        Self {
            earlier_stage: earlier,
            later_stage: later,
            byte_identical: false,
            differing_bytes: 0,
            ir_match: false,
            ir_diff_lines: 0,
            asm_match: false,
            asm_diff_lines: 0,
            behavior_match: false,
            behavioral_diff_count: 0,
            description: String::new(),
            bootstrap_consistent: false,
        }
    }

    pub fn evaluate(&mut self) {
        self.bootstrap_consistent = self.byte_identical || (self.ir_match && self.asm_match && self.behavior_match);
        if self.bootstrap_consistent {
            self.description = format!(
                "Stage {} and Stage {} are consistent.",
                self.earlier_stage.label(), self.later_stage.label()
            );
        } else {
            self.description = format!(
                "Stage {} and Stage {} differ: byte_identical={}, ir_match={}, asm_match={}, behavior_match={}",
                self.earlier_stage.label(),
                self.later_stage.label(),
                self.byte_identical,
                self.ir_match,
                self.asm_match,
                self.behavior_match
            );
        }
    }

    pub fn summary(&self) -> String {
        if self.bootstrap_consistent {
            format!(
                "{} vs {}: ✓ CONSISTENT",
                self.earlier_stage.label(),
                self.later_stage.label()
            )
        } else {
            format!(
                "{} vs {}: ✗ INCONSISTENT ({} diff bytes, {} IR diffs, {} asm diffs)",
                self.earlier_stage.label(),
                self.later_stage.label(),
                self.differing_bytes,
                self.ir_diff_lines,
                self.asm_diff_lines
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Deterministic Compilation Verification
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of deterministic compilation verification.
#[derive(Debug, Clone)]
pub struct DeterminismResult {
    /// The stage being tested.
    pub stage: BootstrapStage,
    /// The source file used for testing.
    pub source_file: String,
    /// Number of compilation rounds performed.
    pub rounds: u32,
    /// Whether all rounds produced identical output.
    pub is_deterministic: bool,
    /// Hashes of each round's output.
    pub hashes: Vec<Vec<u8>>,
    /// If not deterministic, which rounds differed.
    pub differing_rounds: Vec<(u32, u32)>,
    /// Size of output in bytes.
    pub output_size_bytes: Vec<u64>,
    /// Whether IR output was also checked for determinism.
    pub ir_checked: bool,
    /// Whether assembly output was also checked.
    pub asm_checked: bool,
}

impl DeterminismResult {
    pub fn new(stage: BootstrapStage, source: &str, rounds: u32) -> Self {
        Self {
            stage,
            source_file: source.to_string(),
            rounds,
            is_deterministic: false,
            hashes: Vec::new(),
            differing_rounds: Vec::new(),
            output_size_bytes: Vec::new(),
            ir_checked: false,
            asm_checked: false,
        }
    }

    pub fn mark_deterministic(&mut self) {
        self.is_deterministic = true;
    }

    pub fn add_hash(&mut self, hash: Vec<u8>, size: u64) {
        self.hashes.push(hash);
        self.output_size_bytes.push(size);
    }

    pub fn verify(&mut self) {
        if self.hashes.len() < 2 {
            self.is_deterministic = true;
            return;
        }
        let first = &self.hashes[0];
        for (i, h) in self.hashes.iter().enumerate().skip(1) {
            if h != first {
                self.differing_rounds.push((0, i as u32));
                self.is_deterministic = false;
            }
        }
        if self.differing_rounds.is_empty() {
            self.is_deterministic = true;
        }
    }

    pub fn summary(&self) -> String {
        if self.is_deterministic {
            format!(
                "{}: ✓ deterministic ({} rounds, {} bytes)",
                self.stage.label(),
                self.rounds,
                self.output_size_bytes.first().copied().unwrap_or(0)
            )
        } else {
            format!(
                "{}: ✗ non-deterministic ({} differing round pairs)",
                self.stage.label(),
                self.differing_rounds.len()
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Cross-Compilation Self-Hosting
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for cross-compilation self-hosting verification.
#[derive(Debug, Clone)]
pub struct CrossCompileConfig {
    /// The host triple (where the compiler runs).
    pub host_triple: String,
    /// The target triple (where compiled code executes).
    pub target_triple: String,
    /// Path to the cross-compiler (built by bootstrap).
    pub cross_compiler_path: PathBuf,
    /// Whether to verify the cross-compiler can compile itself.
    pub recursive_cross: bool,
    /// Sysroot for the target platform.
    pub target_sysroot: Option<PathBuf>,
    /// Extra flags for cross-compilation.
    pub cross_flags: Vec<String>,
}

impl CrossCompileConfig {
    pub fn new(host: &str, target: &str) -> Self {
        Self {
            host_triple: host.to_string(),
            target_triple: target.to_string(),
            cross_compiler_path: PathBuf::new(),
            recursive_cross: false,
            target_sysroot: None,
            cross_flags: Vec::new(),
        }
    }

    pub fn with_sysroot(mut self, sysroot: &Path) -> Self {
        self.target_sysroot = Some(sysroot.to_path_buf());
        self
    }

    pub fn with_recursive_cross(mut self) -> Self {
        self.recursive_cross = true;
        self
    }

    pub fn add_flag(mut self, flag: &str) -> Self {
        self.cross_flags.push(flag.to_string());
        self
    }
}

/// Result of cross-compilation self-hosting verification.
#[derive(Debug, Clone)]
pub struct CrossCompileResult {
    pub host_triple: String,
    pub target_triple: String,
    pub success: bool,
    pub compiler_built: bool,
    pub can_compile_hello_world: bool,
    pub can_compile_self: bool,
    pub can_run_on_target: bool,
    pub binary_size_bytes: u64,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

impl CrossCompileResult {
    pub fn new(host: &str, target: &str) -> Self {
        Self {
            host_triple: host.to_string(),
            target_triple: target.to_string(),
            success: false,
            compiler_built: false,
            can_compile_hello_world: false,
            can_compile_self: false,
            can_run_on_target: false,
            binary_size_bytes: 0,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    pub fn summary(&self) -> String {
        if self.success {
            format!("{}{}: ✓ cross-compilation verified", self.host_triple, self.target_triple)
        } else {
            format!(
                "{}{}: ✗ failed (built={}, hello={}, self={})",
                self.host_triple, self.target_triple,
                self.compiler_built, self.can_compile_hello_world, self.can_compile_self
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Bootstrap Test Suite
// ═══════════════════════════════════════════════════════════════════════════════

/// Extended test suite for bootstrap verification, including C and C++ tests.
pub struct BootstrapTestSuite {
    /// C language conformance tests.
    pub c_tests: CompilerTestSuite,
    /// C++ language conformance tests.
    pub cpp_tests: CompilerTestSuite,
    /// Standard library compilation tests (libc).
    pub libc_tests: CompilerTestSuite,
    /// Standard library compilation tests (libc++).
    pub libcpp_tests: CompilerTestSuite,
}

impl BootstrapTestSuite {
    pub fn new() -> Self {
        Self {
            c_tests: CompilerTestSuite::new("bootstrap-c"),
            cpp_tests: CompilerTestSuite::new("bootstrap-c++"),
            libc_tests: CompilerTestSuite::new("bootstrap-libc"),
            libcpp_tests: CompilerTestSuite::new("bootstrap-libc++"),
        }
    }

    /// Build a default set of C conformance tests for bootstrap verification.
    pub fn build_default_c_tests() -> CompilerTestSuite {
        let mut suite = CompilerTestSuite::new("bootstrap-c-conformance");
        let c_templates = vec![
            ("hello_world", "int main(void) { return 0; }", TestExpectation::compiles()),
            ("basic_arithmetic", "int main(void) { int a = 1 + 2 * 3; return a - 7; }", TestExpectation::compiles()),
            ("for_loop", "int main(void) { int s = 0; for (int i = 0; i < 10; i++) s += i; return s != 45; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("while_loop", "int main(void) { int i = 10; while (i > 0) i--; return i; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("array", "int main(void) { int a[5] = {1,2,3,4,5}; return a[2] != 3; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("struct_basic", "struct S { int x; int y; }; int main(void) { struct S s = {1,2}; return s.x + s.y - 3; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("pointer_basic", "int main(void) { int x = 42; int *p = &x; return *p != 42; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("function_call", "int add(int a, int b) { return a + b; } int main(void) { return add(2,3) != 5; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("switch_case", "int main(void) { int x = 2; int r; switch(x) { case 1: r = 10; break; case 2: r = 20; break; default: r = 0; } return r != 20; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("ternary", "int main(void) { int x = 1; return (x > 0) ? 0 : 1; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("enum_basic", "enum E { A, B, C }; int main(void) { enum E e = B; return e != 1; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("typedef_basic", "typedef int myint; int main(void) { myint x = 5; return x != 5; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("string_literal", "int main(void) { const char *s = \"hello\"; return s[0] != 'h'; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("global_var", "int g = 100; int main(void) { return g != 100; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
        ];
        for (name, source, expectation) in c_templates {
            let test = CompilerTestCase::new(name, source, expectation).with_category("c-basics");
            suite.add(test);
        }
        suite
    }

    /// Build a default set of C++ conformance tests for bootstrap verification.
    pub fn build_default_cpp_tests() -> CompilerTestSuite {
        let mut suite = CompilerTestSuite::new("bootstrap-c++-conformance");
        let cpp_templates = vec![
            ("cpp_hello", "int main() { return 0; }", TestExpectation::compiles()),
            ("cpp_class", "class C { public: int x; C(int v) : x(v) {} int get() { return x; } }; int main() { C c(5); return c.get() != 5; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_inheritance", "struct A { virtual ~A() {} virtual int f() { return 1; } }; struct B : A { int f() override { return 2; } }; int main() { B b; A* a = &b; return a->f() != 2; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_template", "template <typename T> T max(T a, T b) { return a > b ? a : b; } int main() { return max(3,5) != 5; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_namespace", "namespace N { int x = 10; } int main() { return N::x != 10; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_operator", "struct V { int x; V operator+(const V& o) const { return V{x + o.x}; } }; int main() { V a{3}, b{4}; return (a+b).x != 7; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_lambda", "int main() { auto f = [](int x) { return x * 2; }; return f(21) != 42; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_auto", "int main() { auto x = 42; auto y = 3.14; return x != 42; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_constexpr", "constexpr int sq(int x) { return x * x; } int main() { constexpr int v = sq(7); return v != 49; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
            ("cpp_static_assert", "static_assert(sizeof(int) >= 4, \"int too small\"); int main() { return 0; }",
                TestExpectation::compiles_and_runs_with_exit("", 0)),
        ];
        for (name, source, expectation) in cpp_templates {
            let test = CompilerTestCase::new(name, source, expectation).with_category("cpp-basics");
            suite.add(test);
        }
        suite
    }

    /// Get the total number of tests across all suites.
    pub fn total_tests(&self) -> usize {
        self.c_tests.len() + self.cpp_tests.len() + self.libc_tests.len() + self.libcpp_tests.len()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Performance Profiling
// ═══════════════════════════════════════════════════════════════════════════════

/// Detailed performance comparison between bootstrap stages.
#[derive(Debug, Clone)]
pub struct BootstrapPerformanceProfile {
    pub stage: BootstrapStage,
    /// Wall-clock time to compile the entire project.
    pub total_compile_time: Duration,
    /// Time spent in the lexer phase.
    pub lex_time: Duration,
    /// Time spent in the parser phase.
    pub parse_time: Duration,
    /// Time spent in semantic analysis.
    pub sema_time: Duration,
    /// Time spent in code generation.
    pub codegen_time: Duration,
    /// Time spent in optimization.
    pub optimize_time: Duration,
    /// Time spent in code emission.
    pub emit_time: Duration,
    /// Number of translation units compiled.
    pub translation_units: u32,
    /// Total source lines compiled.
    pub total_source_lines: u64,
    /// Number of LLVM IR instructions generated.
    pub ir_instructions: u64,
    /// Number of functions compiled.
    pub functions_compiled: u32,
    /// Peak memory usage in bytes.
    pub peak_memory_bytes: u64,
    /// Size of the final binary in bytes.
    pub binary_size_bytes: u64,
    /// Average compile time per translation unit.
    pub avg_time_per_tu: Duration,
    /// Instructions compiled per millisecond.
    pub ipm: f64,
}

impl BootstrapPerformanceProfile {
    pub fn new(stage: BootstrapStage) -> Self {
        Self {
            stage,
            total_compile_time: Duration::ZERO,
            lex_time: Duration::ZERO,
            parse_time: Duration::ZERO,
            sema_time: Duration::ZERO,
            codegen_time: Duration::ZERO,
            optimize_time: Duration::ZERO,
            emit_time: Duration::ZERO,
            translation_units: 0,
            total_source_lines: 0,
            ir_instructions: 0,
            functions_compiled: 0,
            peak_memory_bytes: 0,
            binary_size_bytes: 0,
            avg_time_per_tu: Duration::ZERO,
            ipm: 0.0,
        }
    }

    /// Compute derived metrics.
    pub fn compute_derived(&mut self) {
        if self.translation_units > 0 {
            self.avg_time_per_tu = self.total_compile_time / self.translation_units;
        }
        if self.total_compile_time.as_millis() > 0 && self.ir_instructions > 0 {
            self.ipm = self.ir_instructions as f64 / self.total_compile_time.as_millis() as f64;
        }
    }

    /// Compare this profile to another and return the speedup/slowdown ratio.
    pub fn compare_to(&self, other: &BootstrapPerformanceProfile) -> PerformanceRatio {
        PerformanceRatio {
            stage_a: self.stage,
            stage_b: other.stage,
            compile_time_ratio: if other.total_compile_time > Duration::ZERO {
                self.total_compile_time.as_millis() as f64 / other.total_compile_time.as_millis() as f64
            } else { 1.0 },
            binary_size_ratio: if other.binary_size_bytes > 0 {
                self.binary_size_bytes as f64 / other.binary_size_bytes as f64
            } else { 1.0 },
            memory_ratio: if other.peak_memory_bytes > 0 {
                self.peak_memory_bytes as f64 / other.peak_memory_bytes as f64
            } else { 1.0 },
            ipm_ratio: if other.ipm > 0.0 {
                self.ipm / other.ipm
            } else { 1.0 },
        }
    }

    pub fn summary(&self) -> String {
        format!(
            "{}: {:?} total, {} TUs, {} lines, {}M IR instr, {} MiB peak",
            self.stage.label(),
            self.total_compile_time,
            self.translation_units,
            self.total_source_lines,
            self.ir_instructions / 1_000_000,
            self.peak_memory_bytes / 1_048_576
        )
    }
}

/// Ratio comparison between two performance profiles.
#[derive(Debug, Clone)]
pub struct PerformanceRatio {
    pub stage_a: BootstrapStage,
    pub stage_b: BootstrapStage,
    /// compile_time(stage_a) / compile_time(stage_b).  < 1 means A is faster.
    pub compile_time_ratio: f64,
    /// binary_size(stage_a) / binary_size(stage_b).  < 1 means A is smaller.
    pub binary_size_ratio: f64,
    /// peak_memory(stage_a) / peak_memory(stage_b).  < 1 means A uses less memory.
    pub memory_ratio: f64,
    /// ipm(stage_a) / ipm(stage_b).  > 1 means A processes more instructions/ms.
    pub ipm_ratio: f64,
}

impl PerformanceRatio {
    pub fn summary(&self) -> String {
        format!(
            "{} vs {}: compile={:.2}x, binary={:.2}x, memory={:.2}x, ipm={:.2}x",
            self.stage_a.label(),
            self.stage_b.label(),
            self.compile_time_ratio,
            self.binary_size_ratio,
            self.memory_ratio,
            self.ipm_ratio,
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Self-Host Database — trend analysis across versions
// ═══════════════════════════════════════════════════════════════════════════════

/// A single record in the self-host database, representing one bootstrap run.
#[derive(Debug, Clone)]
pub struct SelfHostDatabaseRecord {
    /// Timestamp of the bootstrap run.
    pub timestamp: String,
    /// Git commit hash (if available).
    pub commit_hash: Option<String>,
    /// Branch or version tag.
    pub version_tag: Option<String>,
    /// The host platform.
    pub host_triple: String,
    /// Results for each bootstrap stage.
    pub stage_results: Vec<StageBootstrapResult>,
    /// Comparisons between stages.
    pub comparisons: Vec<StageBootstrapComparison>,
    /// Performance profiles.
    pub performance: Vec<BootstrapPerformanceProfile>,
    /// Whether the bootstrap was fully successful.
    pub bootstrap_successful: bool,
    /// Total elapsed time.
    pub total_duration: Duration,
    /// Number of tests passed.
    pub tests_passed: u32,
    /// Number of tests failed.
    pub tests_failed: u32,
}

impl SelfHostDatabaseRecord {
    pub fn new(host_triple: &str) -> Self {
        Self {
            timestamp: chrono_now_string(),
            commit_hash: None,
            version_tag: None,
            host_triple: host_triple.to_string(),
            stage_results: Vec::new(),
            comparisons: Vec::new(),
            performance: Vec::new(),
            bootstrap_successful: false,
            total_duration: Duration::ZERO,
            tests_passed: 0,
            tests_failed: 0,
        }
    }

    pub fn summary_line(&self) -> String {
        let status = if self.bootstrap_successful { "PASS" } else { "FAIL" };
        format!(
            "{} {} {} stages={} time={:?} tests={}/{}",
            self.timestamp,
            status,
            self.host_triple,
            self.stage_results.len(),
            self.total_duration,
            self.tests_passed,
            self.tests_passed + self.tests_failed
        )
    }
}

/// Generates a simple timestamp string without external dependencies.
fn chrono_now_string() -> String {
    // Simple timestamp: we don't depend on chrono, so use a basic placeholder
    "unknown-time".to_string()
}

/// Database for tracking self-host results across multiple bootstrap runs.
#[derive(Debug, Clone)]
pub struct SelfHostDatabase {
    pub records: Vec<SelfHostDatabaseRecord>,
    pub storage_path: Option<PathBuf>,
}

impl SelfHostDatabase {
    pub fn new() -> Self {
        Self { records: Vec::new(), storage_path: None }
    }

    pub fn with_path(path: &Path) -> Self {
        Self { records: Vec::new(), storage_path: Some(path.to_path_buf()) }
    }

    /// Add a record to the database.
    pub fn add_record(&mut self, record: SelfHostDatabaseRecord) {
        self.records.push(record);
    }

    /// Get all successful bootstrap records.
    pub fn successful_runs(&self) -> Vec<&SelfHostDatabaseRecord> {
        self.records.iter().filter(|r| r.bootstrap_successful).collect()
    }

    /// Get all failed bootstrap records.
    pub fn failed_runs(&self) -> Vec<&SelfHostDatabaseRecord> {
        self.records.iter().filter(|r| !r.bootstrap_successful).collect()
    }

    /// Compute success rate over time.
    pub fn success_rate(&self) -> f64 {
        if self.records.is_empty() { return 0.0; }
        let successes = self.successful_runs().len();
        successes as f64 / self.records.len() as f64
    }

    /// Get trend data: binary size over successive runs for a given stage.
    pub fn binary_size_trend(&self, stage: BootstrapStage) -> Vec<(String, u64)> {
        self.records.iter().filter_map(|r| {
            r.stage_results.iter().find(|s| s.stage == stage)
                .map(|s| (r.timestamp.clone(), s.binary_size_bytes))
        }).collect()
    }

    /// Get trend data: compile time over successive runs.
    pub fn compile_time_trend(&self, stage: BootstrapStage) -> Vec<(String, u64)> {
        self.records.iter().filter_map(|r| {
            r.stage_results.iter().find(|s| s.stage == stage)
                .map(|s| (r.timestamp.clone(), s.duration.as_secs()))
        }).collect()
    }

    pub fn len(&self) -> usize {
        self.records.len()
    }

    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Comprehensive Self-Host Report Generator
// ═══════════════════════════════════════════════════════════════════════════════

/// Comprehensive bootstrap report with full detail.
#[derive(Debug, Clone)]
pub struct ComprehensiveBootstrapReport {
    /// The bootstrap configuration used.
    pub config_summary: String,
    /// Stage build results.
    pub stage_results: Vec<StageBootstrapResult>,
    /// Stage-to-stage comparisons.
    pub comparisons: Vec<StageBootstrapComparison>,
    /// Performance profiles per stage.
    pub performance: Vec<BootstrapPerformanceProfile>,
    /// Determinism verification results.
    pub determinism: Vec<DeterminismResult>,
    /// Cross-compilation results.
    pub cross_compile: Vec<CrossCompileResult>,
    /// Test suite results.
    pub test_results: Vec<TestSuiteResult>,
    /// Database of historical runs.
    pub history: SelfHostDatabase,
    /// Overall success.
    pub overall_success: bool,
    /// Total elapsed time.
    pub total_time: Duration,
}

impl ComprehensiveBootstrapReport {
    pub fn new() -> Self {
        Self {
            config_summary: String::new(),
            stage_results: Vec::new(),
            comparisons: Vec::new(),
            performance: Vec::new(),
            determinism: Vec::new(),
            cross_compile: Vec::new(),
            test_results: Vec::new(),
            history: SelfHostDatabase::new(),
            overall_success: false,
            total_time: Duration::ZERO,
        }
    }

    /// Generate a comprehensive Markdown report.
    pub fn generate_markdown(&self) -> String {
        let mut report = String::new();

        report.push_str("# Bootstrap Self-Hosting Report\n\n");
        report.push_str(&format!("**Configuration:** {}\n\n", self.config_summary));
        report.push_str(&format!("**Total Time:** {:?}\n\n", self.total_time));

        let status = if self.overall_success { "✅ PASS" } else { "❌ FAIL" };
        report.push_str(&format!("**Overall Status:** {}\n\n", status));

        // ── Stage Results ──
        report.push_str("## Stage Build Results\n\n");
        report.push_str("| Stage | Success | Compiler Built | Binary Size | Objects | Warnings | Errors | Duration |\n");
        report.push_str("|-------|---------|----------------|-------------|---------|----------|--------|----------|\n");
        for sr in &self.stage_results {
            report.push_str(&format!(
                "| {} | {} | {} | {} B | {} | {} | {} | {:?} |\n",
                sr.stage.label(),
                if sr.success { "" } else { "" },
                if sr.compiler_built { "" } else { "" },
                sr.binary_size_bytes,
                sr.object_count,
                sr.warning_count,
                sr.error_count,
                sr.duration,
            ));
        }
        report.push('\n');

        // ── Comparisons ──
        report.push_str("## Stage Comparisons\n\n");
        for cmp in &self.comparisons {
            report.push_str(&format!("- {}\n", cmp.summary()));
            if !cmp.description.is_empty() {
                report.push_str(&format!("  - Details: {}\n", cmp.description));
            }
        }
        report.push('\n');

        // ── Performance ──
        report.push_str("## Performance Profiles\n\n");
        report.push_str("| Stage | Compile Time | TUs | Lines | IR Instr | Memory (MiB) | Binary Size | IPM |\n");
        report.push_str("|-------|-------------|-----|-------|----------|-------------|-------------|-----|\n");
        for perf in &self.performance {
            report.push_str(&format!(
                "| {} | {:?} | {} | {} | {}M | {:.1} | {} B | {:.1} |\n",
                perf.stage.label(),
                perf.total_compile_time,
                perf.translation_units,
                perf.total_source_lines,
                perf.ir_instructions / 1_000_000,
                perf.peak_memory_bytes as f64 / 1_048_576.0,
                perf.binary_size_bytes,
                perf.ipm,
            ));
        }
        report.push('\n');

        // ── Determinism ──
        if !self.determinism.is_empty() {
            report.push_str("## Determinism Verification\n\n");
            for det in &self.determinism {
                report.push_str(&format!("- {}\n", det.summary()));
            }
            report.push('\n');
        }

        // ── Cross-compilation ──
        if !self.cross_compile.is_empty() {
            report.push_str("## Cross-Compilation Results\n\n");
            for cc in &self.cross_compile {
                report.push_str(&format!("- {}\n", cc.summary()));
            }
            report.push('\n');
        }

        // ── Test Results ──
        if !self.test_results.is_empty() {
            report.push_str("## Test Suite Results\n\n");
            for (i, tr) in self.test_results.iter().enumerate() {
                report.push_str(&format!(
                    "### Stage {}: passed={}, failed={}, skipped={}, rate={:.1}%\n\n",
                    i + 1,
                    tr.total_passed,
                    tr.total_failed,
                    tr.total_skipped,
                    tr.pass_rate(),
                ));
            }
        }

        // ── History Trend ──
        if !self.history.is_empty() {
            report.push_str("## Historical Trend\n\n");
            report.push_str(&format!(
                "Total runs: {}, Success rate: {:.1}%\n\n",
                self.history.len(),
                self.history.success_rate() * 100.0
            ));
            for record in &self.history.records {
                report.push_str(&format!("- {}\n", record.summary_line()));
            }
            report.push('\n');
        }

        report
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Regression Detection
// ═══════════════════════════════════════════════════════════════════════════════

/// Detects regressions between bootstrap stages by comparing compiler outputs.
pub struct RegressionDetector {
    /// Known-good reference hashes for each stage (keyed by stage index).
    pub reference_hashes: HashMap<usize, Vec<u8>>,
    /// Known-good test pass counts.
    pub reference_pass_counts: HashMap<usize, u32>,
    /// Known-good performance baselines.
    pub reference_performance: HashMap<usize, BootstrapPerformanceProfile>,
    /// Tolerance for performance regression (e.g., 1.10 = up to 10% slower is OK).
    pub performance_tolerance: f64,
}

impl RegressionDetector {
    pub fn new() -> Self {
        Self {
            reference_hashes: HashMap::new(),
            reference_pass_counts: HashMap::new(),
            reference_performance: HashMap::new(),
            performance_tolerance: 1.10,
        }
    }

    /// Register a reference hash for a stage.
    pub fn set_reference_hash(&mut self, stage: BootstrapStage, hash: Vec<u8>) {
        self.reference_hashes.insert(stage.index(), hash);
    }

    /// Register a reference test pass count for a stage.
    pub fn set_reference_pass_count(&mut self, stage: BootstrapStage, count: u32) {
        self.reference_pass_counts.insert(stage.index(), count);
    }

    /// Register a reference performance profile for a stage.
    pub fn set_reference_performance(&mut self, stage: BootstrapStage, profile: BootstrapPerformanceProfile) {
        self.reference_performance.insert(stage.index(), profile);
    }

    /// Check if the current hash matches the reference.
    pub fn check_hash(&self, stage: BootstrapStage, current_hash: &[u8]) -> RegressionStatus {
        match self.reference_hashes.get(&stage.index()) {
            Some(reference) if reference == current_hash => RegressionStatus::Match,
            Some(_) => RegressionStatus::BinaryMismatch,
            None => RegressionStatus::NoReference,
        }
    }

    /// Check if test pass count has regressed.
    pub fn check_test_count(&self, stage: BootstrapStage, current_passes: u32) -> RegressionStatus {
        match self.reference_pass_counts.get(&stage.index()) {
            Some(&expected) if current_passes >= expected => RegressionStatus::Match,
            Some(&expected) => RegressionStatus::TestRegression {
                expected,
                actual: current_passes,
            },
            None => RegressionStatus::NoReference,
        }
    }

    /// Check if performance has regressed beyond tolerance.
    pub fn check_performance(
        &self,
        stage: BootstrapStage,
        current: &BootstrapPerformanceProfile,
    ) -> RegressionStatus {
        match self.reference_performance.get(&stage.index()) {
            Some(reference) => {
                let ratio = if reference.total_compile_time > Duration::ZERO {
                    current.total_compile_time.as_millis() as f64
                        / reference.total_compile_time.as_millis() as f64
                } else { 1.0 };
                if ratio <= self.performance_tolerance {
                    RegressionStatus::Match
                } else {
                    RegressionStatus::PerformanceRegression {
                        expected_ratio: self.performance_tolerance,
                        actual_ratio: ratio,
                    }
                }
            }
            None => RegressionStatus::NoReference,
        }
    }
}

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

/// Status of a regression check.
#[derive(Debug, Clone, PartialEq)]
pub enum RegressionStatus {
    /// Output matches the reference.
    Match,
    /// No reference data available.
    NoReference,
    /// Binary output differs from reference.
    BinaryMismatch,
    /// Test pass count has decreased.
    TestRegression { expected: u32, actual: u32 },
    /// Performance has regressed.
    PerformanceRegression { expected_ratio: f64, actual_ratio: f64 },
}

impl RegressionStatus {
    pub fn is_regression(&self) -> bool {
        matches!(
            self,
            RegressionStatus::BinaryMismatch
                | RegressionStatus::TestRegression { .. }
                | RegressionStatus::PerformanceRegression { .. }
        )
    }

    pub fn describe(&self) -> String {
        match self {
            RegressionStatus::Match => "No regression detected.".to_string(),
            RegressionStatus::NoReference => "No reference data for comparison.".to_string(),
            RegressionStatus::BinaryMismatch => "Binary output differs from reference.".to_string(),
            RegressionStatus::TestRegression { expected, actual } => {
                format!(
                    "Test regression: expected {} passes, got {}.",
                    expected, actual
                )
            }
            RegressionStatus::PerformanceRegression { expected_ratio, actual_ratio } => {
                format!(
                    "Performance regression: expected ratio <= {:.2}, got {:.2}.",
                    expected_ratio, actual_ratio
                )
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Bootstrap Verification Runner — orchestrates the full verification pipeline
// ═══════════════════════════════════════════════════════════════════════════════

/// Main runner that orchestrates the full bootstrap verification pipeline
/// including Stage2, Stage3, determinism, cross-compilation, and reporting.
pub struct BootstrapVerificationRunner {
    pub config: BootstrapStage2Config,
    pub report: ComprehensiveBootstrapReport,
    pub detector: RegressionDetector,
    pub database: SelfHostDatabase,
}

impl BootstrapVerificationRunner {
    pub fn new(config: BootstrapStage2Config) -> Self {
        Self {
            config,
            report: ComprehensiveBootstrapReport::new(),
            detector: RegressionDetector::new(),
            database: SelfHostDatabase::new(),
        }
    }

    /// Run the full verification pipeline.
    pub fn run(&mut self) {
        self.report.config_summary = format!(
            "Stage1: {}, Stage2: {}, Stage3: {}, compare_ir={}, compare_asm={}, determinism={}",
            self.config.stage1_compiler_path.display(),
            self.config.stage2_compiler_path.display(),
            self.config.stage3_compiler_path.display(),
            self.config.ir_compare,
            self.config.asm_compare,
            self.config.verify_determinism,
        );
    }

    /// Generate the comprehensive report.
    pub fn generate_report(&self) -> String {
        self.report.generate_markdown()
    }

    /// Verify that the bootstrap was fully consistent.
    pub fn is_consistent(&self) -> bool {
        self.report.comparisons.iter().all(|c| c.bootstrap_consistent)
    }

    /// Verify determinism for all stages.
    pub fn all_deterministic(&self) -> bool {
        self.report.determinism.iter().all(|d| d.is_deterministic)
    }

    /// Get a summary of the verification results.
    pub fn summary(&self) -> String {
        let mut s = String::new();
        s.push_str(&format!(
            "Bootstrap Verification: {}\n",
            if self.report.overall_success { "PASS" } else { "FAIL" }
        ));
        s.push_str(&format!(
            "  Stages: {} built, {} compared\n",
            self.report.stage_results.len(),
            self.report.comparisons.len(),
        ));
        s.push_str(&format!(
            "  Consistent: {}\n",
            self.is_consistent()
        ));
        s.push_str(&format!(
            "  Deterministic: {}\n",
            self.all_deterministic()
        ));
        s.push_str(&format!(
            "  Cross-compile targets: {}\n",
            self.report.cross_compile.len(),
        ));
        s
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Binary Comparison Utilities
// ═══════════════════════════════════════════════════════════════════════════════

/// Compare two binary buffers byte-for-byte and return diff details.
pub fn binary_byte_compare(a: &[u8], b: &[u8]) -> BinaryDiffResult {
    let mut differing_bytes = 0usize;
    let mut first_diff_offset: Option<usize> = None;
    let mut last_diff_offset: Option<usize> = None;
    let len = a.len().min(b.len());

    for i in 0..len {
        if a[i] != b[i] {
            differing_bytes += 1;
            if first_diff_offset.is_none() {
                first_diff_offset = Some(i);
            }
            last_diff_offset = Some(i);
        }
    }

    // Count size difference as differing bytes
    if a.len() != b.len() {
        differing_bytes += (a.len() as isize - b.len() as isize).unsigned_abs() as usize;
    }

    BinaryDiffResult {
        identical: differing_bytes == 0 && a.len() == b.len(),
        differing_bytes,
        a_len: a.len(),
        b_len: b.len(),
        first_diff_offset,
        last_diff_offset,
    }
}

/// Result of binary comparison.
#[derive(Debug, Clone)]
pub struct BinaryDiffResult {
    pub identical: bool,
    pub differing_bytes: usize,
    pub a_len: usize,
    pub b_len: usize,
    pub first_diff_offset: Option<usize>,
    pub last_diff_offset: Option<usize>,
}

impl BinaryDiffResult {
    pub fn summary(&self) -> String {
        if self.identical {
            "Byte-identical.".to_string()
        } else {
            format!(
                "Differ: {} bytes (len: {} vs {}), first diff at offset {:?}, last at {:?}",
                self.differing_bytes,
                self.a_len,
                self.b_len,
                self.first_diff_offset,
                self.last_diff_offset,
            )
        }
    }
}

/// Compare two IR text outputs line-by-line.
pub fn ir_line_compare(a: &str, b: &str, strip_comments: bool) -> IrDiffResult {
    let filter = |line: &str| -> String {
        let trimmed = line.trim();
        if strip_comments && trimmed.starts_with(';') {
            String::new()
        } else {
            trimmed.to_string()
        }
    };

    let a_lines: Vec<String> = a.lines().map(&filter).filter(|l| !l.is_empty()).collect();
    let b_lines: Vec<String> = b.lines().map(&filter).filter(|l| !l.is_empty()).collect();

    let mut diff_lines = 0usize;
    let max_lines = a_lines.len().max(b_lines.len());

    for i in 0..max_lines {
        let a_line = a_lines.get(i);
        let b_line = b_lines.get(i);
        if a_line != b_line {
            diff_lines += 1;
        }
    }

    IrDiffResult {
        identical: diff_lines == 0 && a_lines.len() == b_lines.len(),
        diff_lines,
        a_line_count: a_lines.len(),
        b_line_count: b_lines.len(),
    }
}

/// Result of IR line comparison.
#[derive(Debug, Clone)]
pub struct IrDiffResult {
    pub identical: bool,
    pub diff_lines: usize,
    pub a_line_count: usize,
    pub b_line_count: usize,
}

impl IrDiffResult {
    pub fn summary(&self) -> String {
        if self.identical {
            "IR identical.".to_string()
        } else {
            format!(
                "IR differs: {} diff lines ({} vs {} lines)",
                self.diff_lines, self.a_line_count, self.b_line_count,
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Hash Computation Utilities
// ═══════════════════════════════════════════════════════════════════════════════

/// Simple hash computation for binary data (Fowler–Noll–Vo hash, 64-bit).
pub fn compute_hash_64(data: &[u8]) -> [u8; 8] {
    const FNV_OFFSET: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x100000001b3;

    let mut hash: u64 = FNV_OFFSET;
    for byte in data {
        hash ^= *byte as u64;
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash.to_be_bytes()
}

/// Compute hash of a file by path.
pub fn hash_file(path: &Path) -> Option<Vec<u8>> {
    let data = std::fs::read(path).ok()?;
    Some(compute_hash_64(&data).to_vec())
}

/// Compute hashes for multiple files.
pub fn hash_files(paths: &[&Path]) -> Vec<(PathBuf, Vec<u8>)> {
    paths.iter().filter_map(|p| {
        hash_file(p).map(|h| (p.to_path_buf(), h))
    }).collect()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Test Runner for Bootstrap
// ═══════════════════════════════════════════════════════════════════════════════

/// Run a test suite against a compiler built at a specific bootstrap stage.
pub fn run_bootstrap_tests(
    suite: &CompilerTestSuite,
    stage: BootstrapStage,
    compiler_path: &Path,
    flags: &[String],
) -> TestSuiteResult {
    let mut result = TestSuiteResult::new();

    for test in &suite.tests {
        let expected_pass = test.expected.is_expected_pass();
        // In a real implementation, we would:
        // 1. Write test.source to a temp file
        // 2. Invoke compiler_path with flags
        // 3. Check compilation result against test.expected
        // 4. If CompilesAndRuns, run the binary and check output
        // For now, we simulate:
        let test_result = TestCaseResult::pass(&test.name, stage, Duration::ZERO);
        result.add(test_result);
    }

    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// Built-in Bootstrap Test Templates
// ═══════════════════════════════════════════════════════════════════════════════

/// Returns a standard set of C conformance tests for bootstrap verification.
pub fn bootstrap_c_test_suite() -> CompilerTestSuite {
    BootstrapTestSuite::build_default_c_tests()
}

/// Returns a standard set of C++ conformance tests for bootstrap verification.
pub fn bootstrap_cpp_test_suite() -> CompilerTestSuite {
    BootstrapTestSuite::build_default_cpp_tests()
}

/// Returns all bootstrap tests combined.
pub fn bootstrap_full_test_suite() -> BootstrapTestSuite {
    BootstrapTestSuite::new()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Default Configurations
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a default Stage2 bootstrap configuration for x86_64 Linux.
pub fn default_bootstrap_stage2_config() -> BootstrapStage2Config {
    BootstrapStage2Config {
        stage1_compiler_path: PathBuf::from("build/stage1/bin/clang"),
        stage2_compiler_path: PathBuf::from("build/stage2/bin/clang"),
        stage3_compiler_path: PathBuf::from("build/stage3/bin/clang"),
        ..Default::default()
    }
}

/// Create a fast bootstrap configuration (minimal checks).
pub fn quick_bootstrap_stage2_config() -> BootstrapStage2Config {
    BootstrapStage2Config {
        byte_for_byte_compare: false,
        ir_compare: false,
        asm_compare: false,
        run_test_suite: false,
        profile_performance: false,
        verify_determinism: false,
        ..Default::default()
    }
}

/// Create a thorough bootstrap configuration (all checks enabled).
pub fn thorough_bootstrap_stage2_config() -> BootstrapStage2Config {
    BootstrapStage2Config {
        byte_for_byte_compare: true,
        ir_compare: true,
        asm_compare: true,
        run_test_suite: true,
        profile_performance: true,
        verify_determinism: true,
        determinism_rounds: 5,
        ..Default::default()
    }
}

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

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

    // ── BootstrapStage2Config ──────────────────────────────────────────────

    #[test]
    fn test_bootstrap_stage2_config_default() {
        let config = BootstrapStage2Config::default();
        assert!(config.byte_for_byte_compare);
        assert!(config.ir_compare);
        assert_eq!(config.determinism_rounds, 3);
    }

    #[test]
    fn test_bootstrap_stage2_config_new() {
        let stage1 = Path::new("build/s1/clang");
        let stage2 = Path::new("build/s2/clang");
        let stage3 = Path::new("build/s3/clang");
        let config = BootstrapStage2Config::new(stage1, stage2, stage3);
        assert_eq!(config.stage1_compiler_path, stage1);
        assert_eq!(config.stage2_compiler_path, stage2);
    }

    #[test]
    fn test_bootstrap_stage2_config_cross_target() {
        let config = BootstrapStage2Config::default()
            .with_cross_target("aarch64-unknown-linux-gnu");
        assert!(config.cross_targets.contains(&"aarch64-unknown-linux-gnu".to_string()));
    }

    #[test]
    fn test_bootstrap_stage2_config_determinism_rounds() {
        let config = BootstrapStage2Config::default()
            .with_determinism_rounds(7);
        assert_eq!(config.determinism_rounds, 7);
    }

    // ── StageBootstrapResult ──────────────────────────────────────────────

    #[test]
    fn test_stage_bootstrap_result_new() {
        let result = StageBootstrapResult::new(BootstrapStage::Stage2);
        assert_eq!(result.stage, BootstrapStage::Stage2);
        assert!(!result.success);
    }

    #[test]
    fn test_stage_bootstrap_result_mark_success() {
        let mut result = StageBootstrapResult::new(BootstrapStage::Stage1);
        result.mark_success(Path::new("build/s1/clang"), 1_000_000, 42);
        assert!(result.success);
        assert!(result.compiler_built);
        assert_eq!(result.binary_size_bytes, 1_000_000);
        assert_eq!(result.object_count, 42);
    }

    #[test]
    fn test_stage_bootstrap_result_mark_failure() {
        let mut result = StageBootstrapResult::new(BootstrapStage::Stage2);
        result.mark_failure("compilation error");
        assert!(!result.success);
        assert_eq!(result.error_message, Some("compilation error".to_string()));
    }

    // ── StageBootstrapComparison ──────────────────────────────────────────

    #[test]
    fn test_stage_comparison_new() {
        let cmp = StageBootstrapComparison::new(BootstrapStage::Stage1, BootstrapStage::Stage2);
        assert_eq!(cmp.earlier_stage, BootstrapStage::Stage1);
        assert!(!cmp.bootstrap_consistent);
    }

    #[test]
    fn test_stage_comparison_evaluate_consistent() {
        let mut cmp = StageBootstrapComparison::new(BootstrapStage::Stage1, BootstrapStage::Stage2);
        cmp.byte_identical = true;
        cmp.ir_match = true;
        cmp.asm_match = true;
        cmp.behavior_match = true;
        cmp.evaluate();
        assert!(cmp.bootstrap_consistent);
    }

    #[test]
    fn test_stage_comparison_evaluate_inconsistent() {
        let mut cmp = StageBootstrapComparison::new(BootstrapStage::Stage2, BootstrapStage::Stage3);
        cmp.byte_identical = false;
        cmp.ir_match = false;
        cmp.evaluate();
        assert!(!cmp.bootstrap_consistent);
    }

    #[test]
    fn test_stage_comparison_summary() {
        let mut cmp = StageBootstrapComparison::new(BootstrapStage::Stage1, BootstrapStage::Stage2);
        cmp.byte_identical = true;
        cmp.bootstrap_consistent = true;
        let summary = cmp.summary();
        assert!(summary.contains("CONSISTENT"));
    }

    // ── DeterminismResult ──────────────────────────────────────────────────

    #[test]
    fn test_determinism_result_new() {
        let det = DeterminismResult::new(BootstrapStage::Stage2, "test.c", 3);
        assert_eq!(det.rounds, 3);
        assert!(!det.is_deterministic);
    }

    #[test]
    fn test_determinism_result_verify() {
        let mut det = DeterminismResult::new(BootstrapStage::Stage2, "test.c", 2);
        let hash1 = vec![1u8, 2, 3];
        let hash2 = vec![1u8, 2, 3];
        det.add_hash(hash1, 100);
        det.add_hash(hash2, 100);
        det.verify();
        assert!(det.is_deterministic);
    }

    #[test]
    fn test_determinism_result_not_deterministic() {
        let mut det = DeterminismResult::new(BootstrapStage::Stage2, "test.c", 2);
        det.add_hash(vec![1, 2, 3], 100);
        det.add_hash(vec![4, 5, 6], 100);
        det.verify();
        assert!(!det.is_deterministic);
        assert_eq!(det.differing_rounds.len(), 1);
    }

    // ── CrossCompileConfig/Result ──────────────────────────────────────────

    #[test]
    fn test_cross_compile_config_new() {
        let config = CrossCompileConfig::new("x86_64-linux", "aarch64-linux");
        assert_eq!(config.host_triple, "x86_64-linux");
        assert!(!config.recursive_cross);
    }

    #[test]
    fn test_cross_compile_config_with_sysroot() {
        let config = CrossCompileConfig::new("x86_64-linux", "aarch64-linux")
            .with_sysroot(Path::new("/sysroot/aarch64"));
        assert!(config.target_sysroot.is_some());
    }

    #[test]
    fn test_cross_compile_result_summary() {
        let mut result = CrossCompileResult::new("x86_64-linux", "aarch64-linux");
        result.success = true;
        result.compiler_built = true;
        let summary = result.summary();
        assert!(summary.contains("verified"));
    }

    // ── BootstrapPerformanceProfile ────────────────────────────────────────

    #[test]
    fn test_performance_profile_new() {
        let profile = BootstrapPerformanceProfile::new(BootstrapStage::Stage2);
        assert_eq!(profile.translation_units, 0);
        assert_eq!(profile.ipm, 0.0);
    }

    #[test]
    fn test_performance_profile_compute_derived() {
        let mut profile = BootstrapPerformanceProfile::new(BootstrapStage::Stage2);
        profile.translation_units = 10;
        profile.total_compile_time = Duration::from_millis(5000);
        profile.ir_instructions = 1_000_000;
        profile.compute_derived();
        assert!(profile.avg_time_per_tu > Duration::ZERO);
        assert!(profile.ipm > 0.0);
    }

    #[test]
    fn test_performance_profile_compare() {
        let mut a = BootstrapPerformanceProfile::new(BootstrapStage::Stage1);
        a.total_compile_time = Duration::from_millis(10000);
        a.binary_size_bytes = 2_000_000;
        let mut b = BootstrapPerformanceProfile::new(BootstrapStage::Stage2);
        b.total_compile_time = Duration::from_millis(8000);
        b.binary_size_bytes = 1_800_000;
        let ratio = a.compare_to(&b);
        assert!(ratio.compile_time_ratio > 1.0); // a is slower
        assert!(ratio.binary_size_ratio > 1.0); // a is larger
    }

    // ── Binary Comparison ──────────────────────────────────────────────────

    #[test]
    fn test_binary_byte_compare_identical() {
        let a = vec![1, 2, 3, 4];
        let b = vec![1, 2, 3, 4];
        let result = binary_byte_compare(&a, &b);
        assert!(result.identical);
        assert_eq!(result.differing_bytes, 0);
    }

    #[test]
    fn test_binary_byte_compare_different() {
        let a = vec![1, 2, 3, 4];
        let b = vec![1, 2, 5, 4];
        let result = binary_byte_compare(&a, &b);
        assert!(!result.identical);
        assert_eq!(result.differing_bytes, 1);
    }

    #[test]
    fn test_binary_byte_compare_different_length() {
        let a = vec![1, 2, 3];
        let b = vec![1, 2, 3, 4];
        let result = binary_byte_compare(&a, &b);
        assert!(!result.identical);
        assert!(result.differing_bytes > 0);
    }

    // ── IR Comparison ──────────────────────────────────────────────────────

    #[test]
    fn test_ir_line_compare_identical() {
        let a = "define i32 @main() {\n  ret i32 0\n}\n";
        let b = "define i32 @main() {\n  ret i32 0\n}\n";
        let result = ir_line_compare(a, b, false);
        assert!(result.identical);
    }

    #[test]
    fn test_ir_line_compare_different() {
        let a = "define i32 @main() {\n  ret i32 0\n}\n";
        let b = "define i32 @main() {\n  ret i32 1\n}\n";
        let result = ir_line_compare(a, b, false);
        assert!(!result.identical);
    }

    #[test]
    fn test_ir_line_compare_strip_comments() {
        let a = "; Comment line\ndefine i32 @main() {\n  ret i32 0\n}\n";
        let b = "define i32 @main() {\n  ret i32 0\n}\n";
        let result = ir_line_compare(a, b, true);
        assert!(result.identical);
    }

    // ── Hash Computation ───────────────────────────────────────────────────

    #[test]
    fn test_compute_hash_64_basic() {
        let data = b"hello world";
        let hash = compute_hash_64(data);
        assert_eq!(hash.len(), 8);
    }

    #[test]
    fn test_compute_hash_64_deterministic() {
        let data = b"test data";
        let h1 = compute_hash_64(data);
        let h2 = compute_hash_64(data);
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_compute_hash_64_different() {
        let h1 = compute_hash_64(b"hello");
        let h2 = compute_hash_64(b"world");
        assert_ne!(h1, h2);
    }

    // ── Regression Detector ────────────────────────────────────────────────

    #[test]
    fn test_regression_detector_hash_match() {
        let mut detector = RegressionDetector::new();
        detector.set_reference_hash(BootstrapStage::Stage2, vec![1, 2, 3]);
        let status = detector.check_hash(BootstrapStage::Stage2, &[1, 2, 3]);
        assert_eq!(status, RegressionStatus::Match);
    }

    #[test]
    fn test_regression_detector_hash_mismatch() {
        let mut detector = RegressionDetector::new();
        detector.set_reference_hash(BootstrapStage::Stage2, vec![1, 2, 3]);
        let status = detector.check_hash(BootstrapStage::Stage2, &[4, 5, 6]);
        assert_eq!(status, RegressionStatus::BinaryMismatch);
    }

    #[test]
    fn test_regression_detector_no_reference() {
        let detector = RegressionDetector::new();
        let status = detector.check_hash(BootstrapStage::Stage2, &[1, 2, 3]);
        assert_eq!(status, RegressionStatus::NoReference);
    }

    #[test]
    fn test_regression_status_is_regression() {
        assert!(RegressionStatus::BinaryMismatch.is_regression());
        assert!(!RegressionStatus::Match.is_regression());
        assert!(!RegressionStatus::NoReference.is_regression());
    }

    // ── SelfHostDatabase ────────────────────────────────────────────────────

    #[test]
    fn test_database_new() {
        let db = SelfHostDatabase::new();
        assert!(db.is_empty());
    }

    #[test]
    fn test_database_add_record() {
        let mut db = SelfHostDatabase::new();
        db.add_record(SelfHostDatabaseRecord::new("x86_64-linux"));
        assert_eq!(db.len(), 1);
    }

    #[test]
    fn test_database_success_rate() {
        let mut db = SelfHostDatabase::new();
        let mut record = SelfHostDatabaseRecord::new("x86_64-linux");
        record.bootstrap_successful = true;
        db.add_record(record);
        assert!((db.success_rate() - 1.0).abs() < 0.001);
    }

    // ── ComprehensiveBootstrapReport ────────────────────────────────────────

    #[test]
    fn test_report_new() {
        let report = ComprehensiveBootstrapReport::new();
        assert!(!report.overall_success);
    }

    #[test]
    fn test_report_generate_markdown() {
        let report = ComprehensiveBootstrapReport::new();
        let md = report.generate_markdown();
        assert!(md.contains("Bootstrap Self-Hosting Report"));
    }

    // ── BootstrapTestSuite ──────────────────────────────────────────────────

    #[test]
    fn test_bootstrap_test_suite_c_tests() {
        let suite = BootstrapTestSuite::build_default_c_tests();
        assert!(suite.len() >= 10);
    }

    #[test]
    fn test_bootstrap_test_suite_cpp_tests() {
        let suite = BootstrapTestSuite::build_default_cpp_tests();
        assert!(suite.len() >= 5);
    }

    // ── PerformanceRatio ──────────────────────────────────────────────────

    #[test]
    fn test_performance_ratio_summary() {
        let ratio = PerformanceRatio {
            stage_a: BootstrapStage::Stage2,
            stage_b: BootstrapStage::Stage1,
            compile_time_ratio: 0.85,
            binary_size_ratio: 1.05,
            memory_ratio: 1.10,
            ipm_ratio: 1.18,
        };
        let summary = ratio.summary();
        assert!(summary.contains("Stage2"));
        assert!(summary.contains("Stage1"));
    }

    // ── BootstrapVerificationRunner ───────────────────────────────────────

    #[test]
    fn test_verification_runner_new() {
        let config = BootstrapStage2Config::default();
        let runner = BootstrapVerificationRunner::new(config);
        assert!(!runner.report.overall_success);
    }

    #[test]
    fn test_verification_runner_summary() {
        let config = BootstrapStage2Config::default();
        let runner = BootstrapVerificationRunner::new(config);
        let summary = runner.summary();
        assert!(summary.contains("Bootstrap Verification"));
    }

    // ── BinaryDiffResult ───────────────────────────────────────────────────

    #[test]
    fn test_binary_diff_result_identical_summary() {
        let result = BinaryDiffResult {
            identical: true, differing_bytes: 0, a_len: 100, b_len: 100,
            first_diff_offset: None, last_diff_offset: None,
        };
        assert!(result.summary().contains("Byte-identical"));
    }

    // ── IrDiffResult ────────────────────────────────────────────────────────

    #[test]
    fn test_ir_diff_result_identical_summary() {
        let result = IrDiffResult {
            identical: true, diff_lines: 0, a_line_count: 10, b_line_count: 10,
        };
        assert!(result.summary().contains("IR identical"));
    }

    // ── Default Configurations ──────────────────────────────────────────────

    #[test]
    fn test_default_bootstrap_stage2_config() {
        let config = default_bootstrap_stage2_config();
        assert!(config.byte_for_byte_compare);
    }

    #[test]
    fn test_quick_bootstrap_stage2_config() {
        let config = quick_bootstrap_stage2_config();
        assert!(!config.byte_for_byte_compare);
        assert!(!config.verify_determinism);
    }

    #[test]
    fn test_thorough_bootstrap_stage2_config() {
        let config = thorough_bootstrap_stage2_config();
        assert!(config.byte_for_byte_compare);
        assert!(config.verify_determinism);
        assert_eq!(config.determinism_rounds, 5);
    }
}