llvm-native-core 0.1.13

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
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
//! End-to-end compilation pipeline for the Clang C frontend.
//!
//! Implements the full Clang-style compilation pipeline from source text to
//! object code.  This includes virtual file system management, source location
//! tracking, command-line parsing, and phased compilation (Preprocess → Parse →
//! Sema → CodeGen → Emit).
//!
//! ## Architecture
//!
//! ```text
//! CompilerInvocation  ──►  CompilerInstance
//!   (options)               ├── FileManager (virtual FS, caching)
//!                           ├── SourceManager (file/line/col mapping)
//!                           ├── DiagnosticEngine
//!                           ├── Preprocessor
//!                           ├── ASTContext
//!                           ├── Sema
//!                           └── CodeGen
//!
//! FrontendAction  ──►  CompilationDriver.execute()
//!   (phases)               ├── BeginSourceFile
//!                           ├── Execute
//!                           └── EndSourceFile
//! ```
//!
//! Clean-room behavioral reconstruction from published Clang/LLVM
//! documentation and the Clang driver architecture.

use std::collections::HashMap;
use std::fmt;

use crate::Function;
use crate::Opcode;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use crate::module::Module;

use super::ast::*;
use super::codegen::ClangCodeGen;
use super::diagnostics::{
    ClangSourceManager, DiagID, DiagSeverity, DiagnosticBuilder, DiagnosticConsumer,
    DiagnosticEngine, DiagnosticOptions, SourceRange, StructuredDiagnostic,
};
use super::lexer;
use super::parser;
use super::preprocessor::Preprocessor;
use super::sema::Sema;
use super::{CLangStandard, ClangOptions};

// ═══════════════════════════════════════════════════════════════════════════════
// CompilerOptions — comprehensive compile-time settings
// ═══════════════════════════════════════════════════════════════════════════════

/// Detailed compiler options parsed from command-line flags or API calls.
/// This is a richer version of the simpler `ClangOptions` struct, supporting
/// all phases of the compilation pipeline.
#[derive(Debug, Clone)]
pub struct CompilerOptions {
    // ── Language ──────────────────────────────────────────────────────────
    /// C language standard.
    pub standard: CLangStandard,
    /// Treat the input as the given language (c, c++, etc.).
    pub lang: InputLanguage,
    /// Enable GNU extensions.
    pub gnu_extensions: bool,
    /// Enable Microsoft extensions.
    pub ms_extensions: bool,
    /// Enable trigraphs (off by default in C17+).
    pub trigraphs: bool,
    /// Enable digraphs.
    pub digraphs: bool,

    // ── Output ────────────────────────────────────────────────────────────
    /// Output file path (stdout if None).
    pub output_file: Option<PathBuf>,
    /// Compilation phase to stop at.
    pub action: FrontendActionKind,
    /// Output format for textual phases.
    pub output_format: OutputFormat,
    /// Target triple.
    pub target_triple: String,
    /// Target CPU.
    pub target_cpu: Option<String>,
    /// Target features.
    pub target_features: Vec<String>,

    // ── Optimization ──────────────────────────────────────────────────────
    /// Optimization level: 0 through 3, 's' (size), 'z' (aggressive size).
    pub opt_level: OptLevel,
    /// Enable debug info generation.
    pub debug_info: bool,
    /// Debug info kind.
    pub debug_info_kind: DebugInfoKind,

    // ── Diagnostics ───────────────────────────────────────────────────────
    /// Enable warnings.
    pub warnings: bool,
    /// Enable `-Wall`.
    pub wall: bool,
    /// Enable `-Wextra`.
    pub wextra: bool,
    /// Enable `-Wpedantic`.
    pub pedantic: bool,
    /// Treat warnings as errors.
    pub werror: bool,
    /// Disable specific warnings.
    pub wno: Vec<String>,
    /// Enable specific warnings.
    pub w: Vec<String>,
    /// Enable all warnings.
    pub weverything: bool,

    // ── Preprocessor ──────────────────────────────────────────────────────
    /// Include search paths.
    pub includes: Vec<PathBuf>,
    /// System include search paths.
    pub system_includes: Vec<PathBuf>,
    /// Predefined macros (`name`, optional `value`).
    pub defines: Vec<(String, Option<String>)>,
    /// Undefine macros.
    pub undefines: Vec<String>,
    /// Do not search standard system include directories.
    pub nostdinc: bool,
    /// Do not predefine standard macros.
    pub nostdincpp: bool,

    // ── Code Generation ───────────────────────────────────────────────────
    /// Position-independent code.
    pub pic: bool,
    /// Position-independent executable.
    pub pie: bool,
    /// Stack protector level.
    pub stack_protector: i32,
    /// Generate code for coverage.
    pub coverage: bool,
    /// Generate code for profiling.
    pub profile: bool,
    /// Sanitizer flags.
    pub sanitize: Vec<String>,
    /// Thread-local storage model.
    pub tls_model: String,
    /// Emit LLVM IR instead of native code.
    pub emit_llvm: bool,
    /// Emit LLVM bitcode.
    pub emit_bc: bool,
    /// Assembly output file (separate from `output_file` for -S -o).
    pub asm_output: Option<PathBuf>,
    /// Object output file.
    pub obj_output: Option<PathBuf>,
    /// Module output file (IR export).
    pub module_output: Option<PathBuf>,
    /// Only run preprocessor.
    pub preprocess_only: bool,
    /// Only parse (no codegen) — `-fsyntax-only`.
    pub syntax_only: bool,

    // ── Linker ────────────────────────────────────────────────────────────
    /// Linker arguments.
    pub linker_args: Vec<String>,
    /// Static linking.
    pub static_linking: bool,
    /// Shared library output.
    pub shared: bool,
    /// Nodes (multiple input files).
    pub input_files: Vec<PathBuf>,

    // ── Miscellaneous ─────────────────────────────────────────────────────
    /// Verbose output.
    pub verbose: bool,
    /// Show commands but don't execute them.
    pub dry_run: bool,
    /// Print the resource directory and exit.
    pub print_resource_dir: bool,
    /// Print search paths and exit.
    pub print_search_dirs: bool,
    /// Print the target triple and exit.
    pub print_target_triple: bool,
    /// Print version and exit.
    pub print_version: bool,
    /// Print help and exit.
    pub print_help: bool,
    /// Working directory.
    pub working_dir: Option<PathBuf>,
    /// Print compilation statistics.
    pub stats: bool,
}

impl Default for CompilerOptions {
    fn default() -> Self {
        Self {
            standard: CLangStandard::C17,
            lang: InputLanguage::C,
            gnu_extensions: false,
            ms_extensions: false,
            trigraphs: false,
            digraphs: true,
            output_file: None,
            action: FrontendActionKind::EmitObj,
            output_format: OutputFormat::Object,
            target_triple: "x86_64-unknown-linux-gnu".into(),
            target_cpu: None,
            target_features: Vec::new(),
            opt_level: OptLevel::O0,
            debug_info: false,
            debug_info_kind: DebugInfoKind::None,
            warnings: true,
            wall: false,
            wextra: false,
            pedantic: false,
            werror: false,
            wno: Vec::new(),
            w: Vec::new(),
            weverything: false,
            includes: Vec::new(),
            system_includes: Vec::new(),
            defines: Vec::new(),
            undefines: Vec::new(),
            nostdinc: false,
            nostdincpp: false,
            pic: false,
            pie: false,
            stack_protector: 0,
            coverage: false,
            profile: false,
            sanitize: Vec::new(),
            tls_model: "global-dynamic".into(),
            emit_llvm: false,
            emit_bc: false,
            asm_output: None,
            obj_output: None,
            module_output: None,
            preprocess_only: false,
            syntax_only: false,
            linker_args: Vec::new(),
            static_linking: false,
            shared: false,
            input_files: Vec::new(),
            verbose: false,
            dry_run: false,
            print_resource_dir: false,
            print_search_dirs: false,
            print_target_triple: false,
            print_version: false,
            print_help: false,
            working_dir: None,
            stats: false,
        }
    }
}

impl CompilerOptions {
    /// Create from the simpler `ClangOptions`.
    pub fn from_clang_options(opts: &ClangOptions) -> Self {
        Self {
            standard: opts.standard,
            output_file: opts.output_file.as_ref().map(PathBuf::from),
            target_triple: opts.target_triple.clone(),
            opt_level: if opts.optimize {
                OptLevel::O2
            } else {
                OptLevel::O0
            },
            debug_info: opts.debug_info,
            warnings: opts.warnings,
            wall: opts.wall,
            pedantic: opts.pedantic,
            werror: opts.werror,
            includes: opts.includes.iter().map(PathBuf::from).collect(),
            defines: opts.defines.clone(),
            action: FrontendActionKind::EmitObj,
            ..Default::default()
        }
    }
}

// ── Input language ────────────────────────────────────────────────────────────

/// Language of the input source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputLanguage {
    C,
    CXX,
    ObjC,
    ObjCXX,
    OpenCL,
    CUDA,
    Asm,
    LLVM_IR,
}

impl InputLanguage {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "c" => Some(Self::C),
            "c++" | "cxx" => Some(Self::CXX),
            "objective-c" | "objc" => Some(Self::ObjC),
            "objective-c++" | "objc++" => Some(Self::ObjCXX),
            "opencl" | "cl" => Some(Self::OpenCL),
            "cuda" => Some(Self::CUDA),
            "assembler" | "assembler-with-cpp" => Some(Self::Asm),
            "ir" | "llvm-ir" => Some(Self::LLVM_IR),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::C => "c",
            Self::CXX => "c++",
            Self::ObjC => "objective-c",
            Self::ObjCXX => "objective-c++",
            Self::OpenCL => "opencl",
            Self::CUDA => "cuda",
            Self::Asm => "assembler",
            Self::LLVM_IR => "ir",
        }
    }
}

impl fmt::Display for InputLanguage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ── Optimization level ────────────────────────────────────────────────────────

/// Optimization level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum OptLevel {
    /// No optimization.
    O0,
    /// Moderate optimization.
    O1,
    /// Aggressive optimization.
    O2,
    /// Maximum optimization.
    O3,
    /// Optimize for size.
    Os,
    /// Aggressively optimize for size.
    Oz,
}

impl OptLevel {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "0" => Some(Self::O0),
            "1" => Some(Self::O1),
            "2" => Some(Self::O2),
            "3" => Some(Self::O3),
            "s" => Some(Self::Os),
            "z" => Some(Self::Oz),
            _ => None,
        }
    }

    pub fn to_arg(&self) -> &'static str {
        match self {
            Self::O0 => "-O0",
            Self::O1 => "-O1",
            Self::O2 => "-O2",
            Self::O3 => "-O3",
            Self::Os => "-Os",
            Self::Oz => "-Oz",
        }
    }

    pub fn is_optimizing(&self) -> bool {
        !matches!(self, Self::O0)
    }
}

// ── Debug info kind ───────────────────────────────────────────────────────────

/// Debug info generation kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugInfoKind {
    /// No debug info.
    None,
    /// Line tables only.
    LineTablesOnly,
    /// Limited debug info.
    Limited,
    /// Full debug info.
    Full,
}

// ── Output format ─────────────────────────────────────────────────────────────

/// Output format for the compilation result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Preprocessed source text.
    PreprocessedSource,
    /// Assembly text.
    Assembly,
    /// Object file.
    Object,
    /// LLVM IR text.
    LLVM_IR,
    /// LLVM bitcode.
    LLVM_BC,
    /// Executable (linked).
    Executable,
    /// Shared library.
    SharedLib,
}

// ── Frontend action kind ──────────────────────────────────────────────────────

/// Which compilation phase (action) to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrontendActionKind {
    /// Preprocess only (`-E`).
    PreprocessOnly,
    /// Parse and type-check only (`-fsyntax-only`).
    SyntaxOnly,
    /// Emit LLVM IR (`.ll`).
    EmitLLVM,
    /// Emit LLVM bitcode (`.bc`).
    EmitBC,
    /// Emit assembly (`.s`).
    EmitAssembly,
    /// Emit object file (`.o`).
    EmitObj,
    /// Full compile + assemble + link.
    EmitExecutable,
    /// Generate PCH.
    GeneratePCH,
    /// Use PCH.
    UsePCH,
    /// Module generation.
    GenerateModule,
    /// Dump AST.
    ASTDump,
    /// Dump tokens.
    DumpTokens,
    /// Dump raw tokens.
    DumpRawTokens,
}

impl FrontendActionKind {
    pub fn from_flag(flag: &str) -> Option<Self> {
        match flag {
            "-E" => Some(Self::PreprocessOnly),
            "-fsyntax-only" => Some(Self::SyntaxOnly),
            "-emit-llvm" => Some(Self::EmitLLVM),
            "-emit-llvm-bc" => Some(Self::EmitBC),
            "-S" => Some(Self::EmitAssembly),
            "-c" => Some(Self::EmitObj),
            "-dump-ast" => Some(Self::ASTDump),
            "-dump-tokens" => Some(Self::DumpTokens),
            "-dump-raw-tokens" => Some(Self::DumpRawTokens),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FileEntry — a file in the virtual file system
// ═══════════════════════════════════════════════════════════════════════════════

/// A cached file entry in the file manager.
///
/// Stores the file's path, contents, size, modification time, and a unique
/// file ID for source location mapping.
#[derive(Debug, Clone)]
pub struct FileEntry {
    /// Unique file identifier.
    pub id: FileID,
    /// Absolute path to the file.
    pub path: PathBuf,
    /// Name used to open the file (may differ from path for virtual files).
    pub name: String,
    /// Cached buffer content, if loaded.
    pub buffer: Option<String>,
    /// Size in bytes.
    pub size: u64,
    /// Modification time, if known.
    pub mod_time: Option<SystemTime>,
    /// Whether this is a virtual/system file.
    pub is_virtual: bool,
    /// Whether the buffer is valid.
    pub is_valid: bool,
    /// Whether this is a system header.
    pub is_system: bool,
    /// Whether this file is from the main source file.
    pub is_main_file: bool,
}

impl FileEntry {
    /// Create a new file entry for a real file.
    pub fn new(id: FileID, path: PathBuf, name: String) -> Self {
        let mut entry = Self {
            id,
            path,
            name,
            buffer: None,
            size: 0,
            mod_time: None,
            is_virtual: false,
            is_valid: true,
            is_system: false,
            is_main_file: false,
        };
        entry.stat();
        entry
    }

    /// Create a virtual file entry (e.g. for built-in sources).
    pub fn virtual_file(id: FileID, name: String, content: String) -> Self {
        let size = content.len() as u64;
        Self {
            id,
            path: PathBuf::from(&name),
            name,
            buffer: Some(content),
            size,
            mod_time: None,
            is_virtual: true,
            is_valid: true,
            is_system: false,
            is_main_file: false,
        }
    }

    /// Stat the file to update size and modification time.
    fn stat(&mut self) {
        if self.is_virtual {
            return;
        }
        if let Ok(meta) = fs::metadata(&self.path) {
            self.size = meta.len();
            self.mod_time = meta.modified().ok();
        } else {
            self.is_valid = false;
        }
    }

    /// Get the file's content as a string, loading from disk if needed.
    pub fn get_buffer(&mut self) -> Result<&str, String> {
        if self.buffer.is_none() {
            if self.is_virtual {
                return Err(format!("virtual file '{}' has no buffer", self.name));
            }
            let content = fs::read_to_string(&self.path)
                .map_err(|e| format!("cannot read file '{}': {}", self.path.display(), e))?;
            self.size = content.len() as u64;
            self.buffer = Some(content);
        }
        Ok(self.buffer.as_ref().unwrap())
    }

    /// Check if the file has been modified since caching.
    pub fn is_stale(&self) -> bool {
        if self.is_virtual {
            return false;
        }
        match fs::metadata(&self.path) {
            Ok(meta) => self.mod_time != meta.modified().ok(),
            Err(_) => true,
        }
    }

    /// Invalidate the cached buffer.
    pub fn invalidate(&mut self) {
        self.buffer = None;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FileManager — virtual file system with caching
// ═══════════════════════════════════════════════════════════════════════════════

/// Manages file entries, caching, and virtual file system operations.
///
/// The file manager provides a unified interface for accessing source files,
/// whether they are real files on disk, virtual files (builtins, generated),
/// or memory buffers.
#[derive(Debug)]
pub struct FileManager {
    /// Map from absolute path to file entry.
    cache: HashMap<PathBuf, FileEntry>,
    /// Map from file ID to file entry (for fast lookup by ID).
    files_by_id: HashMap<FileID, PathBuf>,
    /// Next file ID to assign.
    next_file_id: u64,
    /// Include search paths.
    include_paths: Vec<PathBuf>,
    /// System include search paths.
    system_include_paths: Vec<PathBuf>,
    /// Current working directory.
    working_dir: PathBuf,
    /// Overlay virtual file system (filename → contents).
    overlay: HashMap<String, String>,
    /// List of files that are considered system headers.
    system_header_paths: Vec<PathBuf>,
}

impl FileManager {
    /// Create a new file manager.
    pub fn new() -> Self {
        let working_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        Self {
            cache: HashMap::new(),
            files_by_id: HashMap::new(),
            next_file_id: 1,
            include_paths: Vec::new(),
            system_include_paths: Vec::new(),
            working_dir,
            overlay: HashMap::new(),
            system_header_paths: Vec::new(),
        }
    }

    /// Set the working directory.
    pub fn set_working_dir(&mut self, dir: PathBuf) {
        self.working_dir = dir;
    }

    /// Add an include search path.
    pub fn add_include_path(&mut self, path: PathBuf) {
        self.include_paths.push(path);
    }

    /// Add a system include search path.
    pub fn add_system_include_path(&mut self, path: PathBuf) {
        self.system_include_paths.push(path);
    }

    /// Set the include paths.
    pub fn set_include_paths(&mut self, paths: Vec<PathBuf>) {
        self.include_paths = paths;
    }

    /// Set the system include paths.
    pub fn set_system_include_paths(&mut self, paths: Vec<PathBuf>) {
        self.system_include_paths = paths;
    }

    /// Mark a path as a system header.
    pub fn mark_system_header(&mut self, path: PathBuf) {
        self.system_header_paths.push(path);
    }

    /// Add a virtual file overlay (for testing / builtins).
    pub fn add_overlay(&mut self, filename: String, contents: String) {
        self.overlay.insert(filename, contents);
    }

    /// Get a file entry by path, loading from disk if not in cache.
    pub fn get_file(&mut self, path: &Path) -> Result<FileID, String> {
        // Check overlay first.
        let overlay_contents = self.overlay.get(path.to_str().unwrap_or("")).cloned();
        if let Some(contents) = overlay_contents {
            let fid = self.next_file_id();
            let entry = FileEntry::virtual_file(fid, path.to_string_lossy().to_string(), contents);
            self.cache.insert(path.to_path_buf(), entry);
            self.files_by_id.insert(fid, path.to_path_buf());
            return Ok(fid);
        }

        // Resolve to absolute path.
        let abs = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.working_dir.join(path)
        };

        // Canonicalize if possible.
        let canonical = fs::canonicalize(&abs).unwrap_or(abs);

        if let Some(entry) = self.cache.get(&canonical) {
            if !entry.is_stale() {
                return Ok(entry.id);
            }
            // Invalidate and re-read.
            self.cache.get_mut(&canonical).unwrap().invalidate();
        }

        let fid = self.next_file_id();
        let name = canonical.to_string_lossy().to_string();
        let mut entry = FileEntry::new(fid, canonical.clone(), name);

        // Check if this is a system header.
        entry.is_system = self.is_system_header(&canonical);

        let _ = entry.get_buffer(); // pre-load
        self.cache.insert(canonical.clone(), entry);
        self.files_by_id.insert(fid, canonical);
        Ok(fid)
    }

    /// Get a virtual file entry by name.
    pub fn get_virtual_file(&mut self, name: &str, content: String) -> Result<FileID, String> {
        let fid = self.next_file_id();
        let entry = FileEntry::virtual_file(fid, name.to_string(), content);
        let path = PathBuf::from(name);
        self.cache.insert(path.clone(), entry);
        self.files_by_id.insert(fid, path);
        Ok(fid)
    }

    /// Get a file entry by file ID.
    pub fn get_file_by_id(&self, fid: FileID) -> Option<&FileEntry> {
        self.files_by_id.get(&fid).and_then(|p| self.cache.get(p))
    }

    /// Get a mutable file entry by file ID.
    pub fn get_file_by_id_mut(&mut self, fid: FileID) -> Option<&mut FileEntry> {
        if let Some(path) = self.files_by_id.get(&fid).cloned() {
            self.cache.get_mut(&path)
        } else {
            None
        }
    }

    /// Get the buffer for a file.
    pub fn get_buffer(&mut self, fid: FileID) -> Result<String, String> {
        let path = self
            .files_by_id
            .get(&fid)
            .cloned()
            .ok_or(format!("unknown file ID {}", fid.0))?;
        let entry = self.cache.get_mut(&path).unwrap();
        let buf = entry.get_buffer()?;
        Ok(buf.to_string())
    }

    /// Look up a file in the include search paths.
    pub fn find_include(&mut self, filename: &str, relative_to: Option<&Path>) -> Option<FileID> {
        // 1. Try relative to the including file.
        if let Some(base) = relative_to {
            if let Some(parent) = base.parent() {
                let candidate = parent.join(filename);
                if let Ok(fid) = self.get_file(&candidate) {
                    return Some(fid);
                }
            }
        }

        // 2. Try current directory.
        let candidate = self.working_dir.join(filename);
        if let Ok(fid) = self.get_file(&candidate) {
            return Some(fid);
        }

        // 3. Try user include paths.
        let user_dirs: Vec<PathBuf> = self.include_paths.iter().cloned().collect();
        for dir in &user_dirs {
            let candidate = dir.join(filename);
            if let Ok(fid) = self.get_file(&candidate) {
                return Some(fid);
            }
        }

        // 4. Try system include paths.
        let system_dirs: Vec<PathBuf> = self.system_include_paths.iter().cloned().collect();
        for dir in &system_dirs {
            let candidate = dir.join(filename);
            if let Ok(fid) = self.get_file(&candidate) {
                return Some(fid);
            }
        }

        None
    }

    /// Check if a path is a system header.
    fn is_system_header(&self, path: &Path) -> bool {
        self.system_header_paths
            .iter()
            .any(|sp| path.starts_with(sp))
    }

    /// Allocate a new file ID.
    fn next_file_id(&mut self) -> FileID {
        let id = FileID(self.next_file_id);
        self.next_file_id += 1;
        id
    }

    /// Get the number of cached files.
    pub fn num_files(&self) -> usize {
        self.cache.len()
    }

    /// Clear the cache.
    pub fn clear(&mut self) {
        self.cache.clear();
        self.files_by_id.clear();
        self.next_file_id = 1;
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// FileID — unique identifier for a file in the source manager
// ═══════════════════════════════════════════════════════════════════════════════

/// Unique identifier for a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FileID(pub u64);

impl fmt::Display for FileID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "fid:{}", self.0)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SourceLineEntry — one line in the line table
// ═══════════════════════════════════════════════════════════════════════════════

/// A single entry in the source line table.
#[derive(Debug, Clone)]
pub struct SourceLineEntry {
    /// Line number (1-based).
    pub line: u32,
    /// Byte offset into the file buffer where this line starts.
    pub offset: u32,
}

// ═══════════════════════════════════════════════════════════════════════════════
// SourceLocation — precise location in source code
// ═══════════════════════════════════════════════════════════════════════════════

/// A source location: file + offset or macro expansion location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SourceLocation {
    /// The file ID (0 = invalid).
    pub file_id: u64,
    /// Byte offset into the file buffer.
    pub offset: u32,
    /// Line number (1-based, cached).
    pub line: u32,
    /// Column number (1-based, cached).
    pub column: u32,
}

impl SourceLocation {
    /// Create an invalid source location.
    pub fn invalid() -> Self {
        Self {
            file_id: 0,
            offset: 0,
            line: 0,
            column: 0,
        }
    }

    /// Check if this location is valid.
    pub fn is_valid(&self) -> bool {
        self.file_id != 0
    }

    /// Check if this location is in the main file.
    pub fn is_in_main_file(&self) -> bool {
        self.file_id == 1
    }

    /// Format as `file:line:column`.
    pub fn to_display(&self, sm: &SourceManager) -> String {
        if !self.is_valid() {
            return "<invalid loc>".to_string();
        }
        let name = sm
            .get_file_by_id(FileID(self.file_id))
            .map(|e| e.name.clone())
            .unwrap_or_else(|| format!("<fid:{}>", self.file_id));
        format!("{}:{}:{}", name, self.line, self.column)
    }
}

impl fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_valid() {
            write!(f, "<{}:{}:{}>", self.file_id, self.line, self.column)
        } else {
            write!(f, "<invalid>")
        }
    }
}

impl Default for SourceLocation {
    fn default() -> Self {
        Self::invalid()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SourceManager — maps source locations to file/line/column
// ═══════════════════════════════════════════════════════════════════════════════

/// Manages source files, mapping file IDs and byte offsets to precise
/// file/line/column locations.  Maintains a line table for each loaded file
/// for rapid offset-to-line translation.
#[derive(Debug)]
pub struct SourceManager {
    /// File manager for file operations.
    file_manager: FileManager,
    /// Main file ID.
    main_file_id: Option<FileID>,
    /// Line tables per file.  Keyed by FileID, value is Vec of (offset, line) pairs.
    line_tables: HashMap<FileID, Vec<SourceLineEntry>>,
    /// Cached buffers per file.
    buffers: HashMap<FileID, String>,
    /// Whether line tables have been built.
    line_tables_built: HashMap<FileID, bool>,
}

impl SourceManager {
    /// Create a new source manager.
    pub fn new(file_manager: FileManager) -> Self {
        Self {
            file_manager,
            main_file_id: None,
            line_tables: HashMap::new(),
            buffers: HashMap::new(),
            line_tables_built: HashMap::new(),
        }
    }

    /// Set the main source file.
    pub fn set_main_file(&mut self, fid: FileID) {
        self.main_file_id = Some(fid);
    }

    /// Get the main file ID.
    pub fn main_file_id(&self) -> Option<FileID> {
        self.main_file_id
    }

    /// Load a source file from disk.
    pub fn load_file(&mut self, path: &Path) -> Result<FileID, String> {
        let fid = self.file_manager.get_file(path)?;
        if self.main_file_id.is_none() {
            self.main_file_id = Some(fid);
        }
        let entry = self.file_manager.get_file_by_id(fid).unwrap();
        let is_main = self.main_file_id == Some(fid);
        let marker = if is_main {
            self.file_manager
                .get_file_by_id_mut(fid)
                .unwrap()
                .is_main_file = true;
        };
        let _ = marker;
        self.ensure_buffer(fid)?;
        self.build_line_table(fid)?;
        Ok(fid)
    }

    /// Load a virtual file.
    pub fn load_virtual_file(&mut self, name: &str, content: String) -> Result<FileID, String> {
        let fid = self.file_manager.get_virtual_file(name, content)?;
        if self.main_file_id.is_none() {
            self.main_file_id = Some(fid);
        }
        self.ensure_buffer(fid)?;
        self.build_line_table(fid)?;
        Ok(fid)
    }

    /// Get the FileManager reference.
    pub fn file_manager(&self) -> &FileManager {
        &self.file_manager
    }

    /// Get the mutable FileManager reference.
    pub fn file_manager_mut(&mut self) -> &mut FileManager {
        &mut self.file_manager
    }

    /// Ensure the buffer for a file is cached.
    fn ensure_buffer(&mut self, fid: FileID) -> Result<(), String> {
        if !self.buffers.contains_key(&fid) {
            let buf = self.file_manager.get_buffer(fid)?;
            self.buffers.insert(fid, buf);
        }
        Ok(())
    }

    /// Build the line table for a file.
    fn build_line_table(&mut self, fid: FileID) -> Result<(), String> {
        if self.line_tables_built.get(&fid) == Some(&true) {
            return Ok(());
        }

        let buffer = self
            .buffers
            .get(&fid)
            .ok_or(format!("no buffer for file {}", fid))?
            .clone();
        let mut lines = Vec::new();
        lines.push(SourceLineEntry { line: 1, offset: 0 });

        let mut offset = 0u32;
        for ch in buffer.chars() {
            if ch == '\n' {
                lines.push(SourceLineEntry {
                    line: lines.len() as u32 + 1,
                    offset: offset + 1,
                });
            }
            offset += ch.len_utf8() as u32;
        }

        self.line_tables.insert(fid, lines);
        self.line_tables_built.insert(fid, true);
        Ok(())
    }

    /// Compute a source location from a file ID and byte offset.
    pub fn get_location(&self, fid: FileID, offset: u32) -> SourceLocation {
        let line_table = match self.line_tables.get(&fid) {
            Some(lt) => lt,
            None => {
                return SourceLocation {
                    file_id: fid.0,
                    offset,
                    line: 0,
                    column: 0,
                };
            }
        };

        // Binary search: find the last entry with offset <= the given offset.
        let idx = match line_table.binary_search_by(|entry| entry.offset.cmp(&offset)) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        };

        let entry = &line_table[idx];
        let line = entry.line;
        let column = (offset - entry.offset) + 1;

        SourceLocation {
            file_id: fid.0,
            offset,
            line,
            column,
        }
    }

    /// Get the source text for a range of locations.
    pub fn get_source_text(&self, start: SourceLocation, end: SourceLocation) -> String {
        if start.file_id != end.file_id || start.file_id == 0 {
            return String::new();
        }
        let fid = FileID(start.file_id);
        if let Some(buffer) = self.buffers.get(&fid) {
            let s = start.offset as usize;
            let e = end.offset as usize;
            if s <= e && e <= buffer.len() {
                return buffer[s..e].to_string();
            }
        }
        String::new()
    }

    /// Get the line of source text at a location.
    pub fn get_line(&self, loc: SourceLocation) -> Option<String> {
        if loc.file_id == 0 {
            return None;
        }
        let fid = FileID(loc.file_id);
        let buffer = self.buffers.get(&fid)?;
        let line_table = self.line_tables.get(&fid)?;

        let idx = match line_table.binary_search_by(|entry| entry.offset.cmp(&loc.offset)) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        };

        let line_start = line_table[idx].offset as usize;
        let line_end = if idx + 1 < line_table.len() {
            line_table[idx + 1].offset as usize
        } else {
            buffer.len()
        };

        // Strip trailing newline.
        let mut line = buffer[line_start..line_end].to_string();
        if line.ends_with('\n') {
            line.pop();
        }
        if line.ends_with('\r') {
            line.pop();
        }
        Some(line)
    }

    /// Get the file entry for a file ID.
    pub fn get_file_by_id(&self, fid: FileID) -> Option<&FileEntry> {
        self.file_manager.get_file_by_id(fid)
    }

    /// Get the buffer for a file.
    pub fn get_buffer(&self, fid: FileID) -> Option<&str> {
        self.buffers.get(&fid).map(|s| s.as_str())
    }

    /// Get the number of files managed.
    pub fn num_files(&self) -> usize {
        self.file_manager.num_files()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ASTConsumer — consumes AST nodes as they are produced
// ═══════════════════════════════════════════════════════════════════════════════

/// Trait for AST consumers — handles top-level declarations as they are parsed.
///
/// In a real Clang, consumers receive declarations as the parser produces them,
/// enabling incremental compilation and IDE features.
pub trait ASTConsumer: fmt::Debug {
    /// Called when translation unit parsing begins.
    fn handle_translation_unit_begin(&mut self, _tu: &TranslationUnit) {}

    /// Handle a top-level declaration.
    fn handle_top_level_decl(&mut self, decl: &Decl);

    /// Called after all declarations have been processed.
    fn handle_translation_unit_end(&mut self, _tu: &TranslationUnit) {}

    /// Called when the consumer is done.
    fn finish(&mut self) {}

    /// Print final statistics.
    fn print_stats(&self) {}
}

// ── Built-in consumer implementations ─────────────────────────────────────────

/// A consumer that does nothing (syntax-only mode).
#[derive(Debug)]
pub struct SyntaxOnlyConsumer;

impl ASTConsumer for SyntaxOnlyConsumer {
    fn handle_top_level_decl(&mut self, _decl: &Decl) {}
}

/// A consumer that dumps the AST to stdout.
#[derive(Debug)]
pub struct ASTDumpConsumer;

impl ASTConsumer for ASTDumpConsumer {
    fn handle_top_level_decl(&mut self, decl: &Decl) {
        println!("{}", decl);
    }
}

/// A consumer that generates LLVM IR.
pub struct CodeGenConsumer<'a> {
    /// The code generator.
    pub codegen: ClangCodeGen<'a>,
}

impl<'a> fmt::Debug for CodeGenConsumer<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CodeGenConsumer")
            .field("codegen", &"<ClangCodeGen>")
            .finish()
    }
}

impl<'a> CodeGenConsumer<'a> {
    pub fn new(codegen: ClangCodeGen<'a>) -> Self {
        Self { codegen }
    }
}

impl ASTConsumer for CodeGenConsumer<'_> {
    fn handle_top_level_decl(&mut self, _decl: &Decl) {
        // Codegen handles compilation at the TU level.
    }

    fn handle_translation_unit_begin(&mut self, _tu: &TranslationUnit) {}

    fn handle_translation_unit_end(&mut self, tu: &TranslationUnit) {
        let _ = self.codegen.compile(tu);
    }
}

/// Multiplexing consumer — dispatches to multiple sub-consumers.
pub struct MultiplexConsumer {
    pub consumers: Vec<Box<dyn ASTConsumer>>,
}

impl fmt::Debug for MultiplexConsumer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MultiplexConsumer")
            .field("num_consumers", &self.consumers.len())
            .finish()
    }
}

impl MultiplexConsumer {
    pub fn new(consumers: Vec<Box<dyn ASTConsumer>>) -> Self {
        Self { consumers }
    }

    pub fn add(&mut self, consumer: Box<dyn ASTConsumer>) {
        self.consumers.push(consumer);
    }
}

impl ASTConsumer for MultiplexConsumer {
    fn handle_translation_unit_begin(&mut self, tu: &TranslationUnit) {
        for c in &mut self.consumers {
            c.handle_translation_unit_begin(tu);
        }
    }

    fn handle_top_level_decl(&mut self, decl: &Decl) {
        for c in &mut self.consumers {
            c.handle_top_level_decl(decl);
        }
    }

    fn handle_translation_unit_end(&mut self, tu: &TranslationUnit) {
        for c in &mut self.consumers {
            c.handle_translation_unit_end(tu);
        }
    }

    fn finish(&mut self) {
        for c in &mut self.consumers {
            c.finish();
        }
    }

    fn print_stats(&self) {
        for c in &self.consumers {
            c.print_stats();
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FrontendAction — base class for all frontend actions
// ═══════════════════════════════════════════════════════════════════════════════

/// A frontend action represents one "unit of work" for the compiler.
/// Subclasses define specific actions like emitting object files, assembly,
/// or LLVM IR.
#[derive(Debug)]
pub enum FrontendAction {
    PreprocessOnly(PreprocessOnlyAction),
    SyntaxOnly(SyntaxOnlyAction),
    EmitLLVM(EmitLLVMAction),
    EmitBC(EmitBCAction),
    EmitAssembly(EmitAssemblyAction),
    EmitObj(EmitObjAction),
    ASTDump(ASTDumpAction),
    DumpTokens(DumpTokensAction),
}

impl FrontendAction {
    /// Create a frontend action for the given kind.
    pub fn for_kind(kind: FrontendActionKind) -> Self {
        match kind {
            FrontendActionKind::PreprocessOnly => {
                Self::PreprocessOnly(PreprocessOnlyAction { output: None })
            }
            FrontendActionKind::SyntaxOnly => Self::SyntaxOnly(SyntaxOnlyAction),
            FrontendActionKind::EmitLLVM => Self::EmitLLVM(EmitLLVMAction { output: None }),
            FrontendActionKind::EmitBC => Self::EmitBC(EmitBCAction),
            FrontendActionKind::EmitAssembly => {
                Self::EmitAssembly(EmitAssemblyAction { output: None })
            }
            FrontendActionKind::EmitObj => Self::EmitObj(EmitObjAction::new()),
            FrontendActionKind::ASTDump => Self::ASTDump(ASTDumpAction),
            FrontendActionKind::DumpTokens => Self::DumpTokens(DumpTokensAction { output: None }),
            // Default to EmitObj for unsupported actions.
            _ => Self::EmitObj(EmitObjAction::new()),
        }
    }

    /// Begin source file processing.
    pub fn begin_source_file(
        &mut self,
        compiler: &mut CompilerInstance,
    ) -> Result<(), Vec<String>> {
        match self {
            Self::PreprocessOnly(action) => action.begin_source_file(compiler),
            Self::SyntaxOnly(action) => action.begin_source_file(compiler),
            Self::EmitLLVM(action) => action.begin_source_file(compiler),
            Self::EmitBC(action) => action.begin_source_file(compiler),
            Self::EmitAssembly(action) => action.begin_source_file(compiler),
            Self::EmitObj(action) => action.begin_source_file(compiler),
            Self::ASTDump(action) => action.begin_source_file(compiler),
            Self::DumpTokens(action) => action.begin_source_file(compiler),
        }
    }

    /// Execute the action.
    pub fn execute(&mut self) -> Result<(), Vec<String>> {
        match self {
            Self::PreprocessOnly(action) => action.execute(),
            Self::SyntaxOnly(action) => action.execute(),
            Self::EmitLLVM(action) => action.execute(),
            Self::EmitBC(action) => action.execute(),
            Self::EmitAssembly(action) => action.execute(),
            Self::EmitObj(action) => action.execute(),
            Self::ASTDump(action) => action.execute(),
            Self::DumpTokens(action) => action.execute(),
        }
    }

    /// End source file processing.
    pub fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        match self {
            Self::PreprocessOnly(action) => action.end_source_file(),
            Self::SyntaxOnly(action) => action.end_source_file(),
            Self::EmitLLVM(action) => action.end_source_file(),
            Self::EmitBC(action) => action.end_source_file(),
            Self::EmitAssembly(action) => action.end_source_file(),
            Self::EmitObj(action) => action.end_source_file(),
            Self::ASTDump(action) => action.end_source_file(),
            Self::DumpTokens(action) => action.end_source_file(),
        }
    }

    /// Get the output buffer for actions that produce text.
    pub fn get_output(&self) -> Option<String> {
        match self {
            Self::PreprocessOnly(action) => action.get_output(),
            Self::EmitLLVM(action) => action.get_output(),
            Self::EmitAssembly(action) => action.get_output(),
            Self::DumpTokens(action) => action.get_output(),
            _ => None,
        }
    }

    /// Get the object bytes for EmitObjAction.
    pub fn get_object_bytes(&self) -> Option<Vec<u8>> {
        match self {
            Self::EmitObj(action) => action.get_object_bytes(),
            _ => None,
        }
    }
}

// ── Action trait ──────────────────────────────────────────────────────────────

/// Internal trait implemented by all concrete actions.
trait ActionImpl {
    fn begin_source_file(&mut self, compiler: &mut CompilerInstance) -> Result<(), Vec<String>>;
    fn execute(&mut self) -> Result<(), Vec<String>>;
    fn end_source_file(&mut self) -> Result<(), Vec<String>>;
    fn get_output(&self) -> Option<String> {
        None
    }
}

// ── PreprocessOnlyAction ──────────────────────────────────────────────────────

/// Action that only runs the preprocessor and outputs the result.
#[derive(Debug)]
pub struct PreprocessOnlyAction {
    output: Option<String>,
}

impl ActionImpl for PreprocessOnlyAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        self.output = Some(String::new());
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        // Preprocessing is done in the CompilerInstance; here we just pass.
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn get_output(&self) -> Option<String> {
        self.output.clone()
    }
}

// ── SyntaxOnlyAction ──────────────────────────────────────────────────────────

/// Action that parses and type-checks without generating code.
#[derive(Debug)]
pub struct SyntaxOnlyAction;

impl ActionImpl for SyntaxOnlyAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }
}

// ── EmitLLVMAction ────────────────────────────────────────────────────────────

/// Action that emits LLVM IR (`.ll` file).
#[derive(Debug)]
pub struct EmitLLVMAction {
    output: Option<String>,
}

impl ActionImpl for EmitLLVMAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        self.output = Some(String::new());
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn get_output(&self) -> Option<String> {
        self.output.clone()
    }
}

// ── EmitBCAction ──────────────────────────────────────────────────────────────

/// Action that emits LLVM bitcode (`.bc` file).
#[derive(Debug)]
pub struct EmitBCAction;

impl ActionImpl for EmitBCAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }
}

// ── EmitAssemblyAction ────────────────────────────────────────────────────────

/// Action that emits assembly (`.s` file).
#[derive(Debug)]
pub struct EmitAssemblyAction {
    output: Option<String>,
}

impl ActionImpl for EmitAssemblyAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        self.output = Some(String::new());
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn get_output(&self) -> Option<String> {
        self.output.clone()
    }
}

// ── EmitObjAction ─────────────────────────────────────────────────────────────

/// Action that emits an object file (`.o` file).
#[derive(Debug)]
pub struct EmitObjAction {
    module: Option<Module>,
}

impl EmitObjAction {
    pub fn new() -> Self {
        Self { module: None }
    }

    pub fn set_module(&mut self, module: Module) {
        self.module = Some(module);
    }

    pub fn get_object_bytes(&self) -> Option<Vec<u8>> {
        // In a real implementation, this would use the target machine
        // to emit object code.  Here we return an empty vector.
        Some(Vec::new())
    }
}

impl ActionImpl for EmitObjAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }
}

// ── ASTDumpAction ─────────────────────────────────────────────────────────────

/// Action that dumps the AST to stdout.
#[derive(Debug)]
pub struct ASTDumpAction;

impl ActionImpl for ASTDumpAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }
}

// ── DumpTokensAction ──────────────────────────────────────────────────────────

/// Action that dumps tokens to stdout.
#[derive(Debug)]
pub struct DumpTokensAction {
    output: Option<String>,
}

impl ActionImpl for DumpTokensAction {
    fn begin_source_file(&mut self, _compiler: &mut CompilerInstance) -> Result<(), Vec<String>> {
        self.output = Some(String::new());
        Ok(())
    }

    fn execute(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        Ok(())
    }

    fn get_output(&self) -> Option<String> {
        self.output.clone()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CompilerInstance — owns all compilation state
// ═══════════════════════════════════════════════════════════════════════════════

/// The central compilation object, analogous to `clang::CompilerInstance`.
///
/// Owns all compilation state including diagnostics, the target, source
/// manager, file manager, preprocessor, AST context, semantic analyzer,
/// and code generator, all configured via a `CompilerInvocation`.
#[derive(Debug)]
pub struct CompilerInstance {
    /// Compiler options.
    pub opts: CompilerOptions,
    /// Diagnostic engine.
    pub diagnostics: DiagnosticEngine,
    /// Source manager.
    pub source_manager: SourceManager,
    /// Whether source file processing has begun.
    source_file_begun: bool,
    /// Whether we have an AST.
    has_ast: bool,
    /// The parsed translation unit.
    translation_unit: Option<TranslationUnit>,
    /// Output stream for textual output.
    output_buffer: Option<String>,
}

impl CompilerInstance {
    /// Create a new compiler instance from a compiler invocation.
    pub fn new(invocation: CompilerInvocation) -> Self {
        let mut diag_engine = DiagnosticEngine::new(ClangSourceManager::new());
        diag_engine.set_warnings_as_errors(invocation.opts.werror);
        if !invocation.opts.warnings {
            diag_engine.set_ignore_warnings(true);
        }

        let mut fm = FileManager::new();
        fm.set_include_paths(invocation.opts.includes.clone());
        fm.set_system_include_paths(invocation.opts.system_includes.clone());

        Self {
            opts: invocation.opts,
            diagnostics: diag_engine,
            source_manager: SourceManager::new(fm),
            source_file_begun: false,
            has_ast: false,
            translation_unit: None,
            output_buffer: None,
        }
    }

    /// Create a compiler instance with default options.
    pub fn create_default() -> Self {
        Self::new(CompilerInvocation::default())
    }

    /// Get the compiler options.
    pub fn options(&self) -> &CompilerOptions {
        &self.opts
    }

    /// Get mutable compiler options.
    pub fn options_mut(&mut self) -> &mut CompilerOptions {
        &mut self.opts
    }

    /// Get the target triple.
    pub fn target_triple(&self) -> &str {
        &self.opts.target_triple
    }

    // ── Source file management ─────────────────────────────────────────

    /// Begin processing a source file.
    pub fn begin_source_file(&mut self, action: &mut FrontendAction) -> Result<(), Vec<String>> {
        if self.source_file_begun {
            return Err(vec!["source file already begun".to_string()]);
        }
        self.source_file_begun = true;
        action.begin_source_file(self)?;

        // Run lexer, preprocessor, parser, and sema.
        if self.opts.preprocess_only {
            self.output_buffer = Some(self.run_preprocessor_only()?);
        } else {
            self.translation_unit = Some(self.run_parse_and_sema()?);
            self.has_ast = true;
        }

        Ok(())
    }

    /// End processing the source file.
    pub fn end_source_file(&mut self) -> Result<(), Vec<String>> {
        if !self.source_file_begun {
            return Ok(());
        }
        self.source_file_begun = false;
        Ok(())
    }

    /// Run the full compilation pipeline for source in a virtual file.
    pub fn run_pipeline(
        &mut self,
        virtual_name: &str,
        source: &str,
    ) -> Result<Module, Vec<String>> {
        // Load the source into a virtual file.
        let _fid = self
            .source_manager
            .load_virtual_file(virtual_name, source.to_string())
            .map_err(|e| vec![e])?;

        // Run lexer on the source.
        let tokens = lexer::tokenize(source, self.opts.standard);

        // Run preprocessor.
        let _pp = Preprocessor::new(self.opts.standard);
        // (Preprocessing is handled via the Preprocessor; here we note
        //  that the lexer already tokenized.)

        // If preprocessing only, return.
        if self.opts.preprocess_only {
            return Err(vec!["preprocessing only; no module produced".to_string()]);
        }

        // Parse.
        let mut p = parser::Parser::new(&tokens, self.opts.standard);
        let tu = p.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        // Semantic analysis.
        let mut sema = Sema::new(self.opts.standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;

        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        // Syntax-only mode.
        if self.opts.syntax_only {
            return Err(vec!["syntax-only; no module produced".to_string()]);
        }

        // Code generation.
        let mut cg = ClangCodeGen::new("input", &self.opts.target_triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen error: {}", err))
                .collect::<Vec<_>>()
        })?;

        // Return the module (ClangCodeGen owns the module; we move it).
        let module = cg.module;
        Ok(module)
    }

    // ── Internal helpers ───────────────────────────────────────────────

    /// Run only the preprocessor and return the preprocessed text.
    fn run_preprocessor_only(&mut self) -> Result<String, Vec<String>> {
        let fid = self
            .source_manager
            .main_file_id()
            .ok_or_else(|| vec!["no main file for preprocessing".to_string()])?;

        let source = self
            .source_manager
            .get_buffer(fid)
            .map(|s| s.to_string())
            .ok_or_else(|| vec!["no buffer for main file".to_string()])?;

        // Run the preprocessor on the source.
        let _pp = Preprocessor::new(self.opts.standard);

        // In a real implementation, we'd collect the preprocessor output.
        // For now, we return the original source (placeholder).
        Ok(source)
    }

    /// Run lexer, parser, and semantic analysis.
    fn run_parse_and_sema(&mut self) -> Result<TranslationUnit, Vec<String>> {
        let fid = self
            .source_manager
            .main_file_id()
            .ok_or_else(|| vec!["no main file for parsing".to_string()])?;

        let source = self
            .source_manager
            .get_buffer(fid)
            .map(|s| s.to_string())
            .ok_or_else(|| vec!["no buffer for main file".to_string()])?;

        let tokens = lexer::tokenize(&source, self.opts.standard);
        let mut parser = parser::Parser::new(&tokens, self.opts.standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let mut sema = Sema::new(self.opts.standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;

        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        Ok(tu)
    }

    /// Execute code generation on the parsed AST.
    pub fn execute_codegen(&mut self) -> Result<(), Vec<String>> {
        let standard = self.opts.standard;
        let triple = self.opts.target_triple.clone();

        let fid = self
            .source_manager
            .main_file_id()
            .ok_or_else(|| vec!["no main file for codegen".to_string()])?;
        let source = self
            .source_manager
            .get_buffer(fid)
            .ok_or_else(|| vec!["no buffer for main file".to_string()])?;

        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|e| format!("parse error: {}", e))
                .collect::<Vec<_>>()
        })?;

        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|e| format!("sema error: {}", e))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        let mut cg = ClangCodeGen::new("input", &triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|e| format!("codegen error: {}", e))
                .collect::<Vec<_>>()
        })?;

        Ok(())
    }

    /// Get the parsed translation unit.
    pub fn get_translation_unit(&self) -> Option<&TranslationUnit> {
        self.translation_unit.as_ref()
    }

    /// Report a diagnostic.
    pub fn report(&mut self, id: DiagID, _severity: DiagSeverity, _msg: &str) {
        let mut builder = self.diagnostics.report(id);
        builder.emit();
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CompilerInvocation — parses command-line args into CompilerOptions
// ═══════════════════════════════════════════════════════════════════════════════

/// Parses command-line arguments into a `CompilerOptions` configuration,
/// then wraps it for use with `CompilerInstance`.
#[derive(Debug, Clone)]
pub struct CompilerInvocation {
    /// The parsed compiler options.
    pub opts: CompilerOptions,
    /// The raw arguments for re-display.
    pub args: Vec<String>,
    /// Program name (argv[0]).
    pub program_name: String,
}

impl CompilerInvocation {
    /// Create from command-line arguments.
    pub fn from_args<I, S>(args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let raw: Vec<String> = args.into_iter().map(|s| s.as_ref().to_string()).collect();
        let program_name = raw.first().cloned().unwrap_or_else(|| "clang".to_string());
        let mut opts = CompilerOptions::default();
        let mut i = 1; // skip program name

        // Expand response files.
        let mut expanded = vec![program_name.clone()];
        while i < raw.len() {
            let arg = &raw[i];
            if arg.starts_with('@') {
                let filename = &arg[1..];
                if let Ok(contents) = fs::read_to_string(filename) {
                    for line in contents.lines() {
                        let line = line.trim();
                        if !line.is_empty() && !line.starts_with('#') {
                            expanded.push(line.to_string());
                        }
                    }
                }
            } else {
                expanded.push(arg.clone());
            }
            i += 1;
        }

        // Parse expanded arguments.
        i = 1;
        while i < expanded.len() {
            let arg = &expanded[i];
            match arg.as_str() {
                // ── Output phase ───────────────────────────────────────
                "-E" => {
                    opts.action = FrontendActionKind::PreprocessOnly;
                    opts.preprocess_only = true;
                }
                "-fsyntax-only" => {
                    opts.action = FrontendActionKind::SyntaxOnly;
                    opts.syntax_only = true;
                }
                "-S" => opts.action = FrontendActionKind::EmitAssembly,
                "-c" => opts.action = FrontendActionKind::EmitObj,
                "-emit-llvm" => {
                    opts.action = FrontendActionKind::EmitLLVM;
                    opts.emit_llvm = true;
                }
                "-emit-llvm-bc" => {
                    opts.action = FrontendActionKind::EmitBC;
                    opts.emit_bc = true;
                }
                "-dump-ast" => opts.action = FrontendActionKind::ASTDump,
                "-dump-tokens" => opts.action = FrontendActionKind::DumpTokens,

                // ── Output file ───────────────────────────────────────
                "-o" => {
                    i += 1;
                    if i < expanded.len() {
                        opts.output_file = Some(PathBuf::from(&expanded[i]));
                    }
                }

                // ── Language standard ─────────────────────────────────
                flag if flag.starts_with("-std=") => {
                    let std = &flag[5..];
                    if let Some(cstd) = CLangStandard::from_str(std) {
                        opts.standard = cstd;
                        opts.gnu_extensions = cstd.is_gnu();
                    }
                }
                "-ansi" => opts.standard = CLangStandard::C89,

                // ── Target ────────────────────────────────────────────
                "-target" => {
                    i += 1;
                    if i < expanded.len() {
                        opts.target_triple = expanded[i].clone();
                    }
                }
                flag if flag.starts_with("-target=") => {
                    opts.target_triple = flag[8..].to_string();
                }
                "-march" => {
                    i += 1;
                    if i < expanded.len() {
                        opts.target_cpu = Some(expanded[i].clone());
                    }
                }
                flag if flag.starts_with("-march=") => {
                    opts.target_cpu = Some(flag[7..].to_string());
                }

                // ── Optimization ──────────────────────────────────────
                "-O0" => opts.opt_level = OptLevel::O0,
                "-O1" => opts.opt_level = OptLevel::O1,
                "-O2" => opts.opt_level = OptLevel::O2,
                "-O3" => opts.opt_level = OptLevel::O3,
                "-Os" => opts.opt_level = OptLevel::Os,
                "-Oz" => opts.opt_level = OptLevel::Oz,
                "-g" => opts.debug_info = true,

                // ── Includes ──────────────────────────────────────────
                flag if flag.starts_with("-I") => {
                    let path = if flag.len() > 2 {
                        PathBuf::from(&flag[2..])
                    } else {
                        i += 1;
                        if i < expanded.len() {
                            PathBuf::from(&expanded[i])
                        } else {
                            PathBuf::new()
                        }
                    };
                    if !path.as_os_str().is_empty() {
                        opts.includes.push(path);
                    }
                }

                // ── Defines ───────────────────────────────────────────
                flag if flag.starts_with("-D") => {
                    let def = &flag[2..];
                    if let Some(eq) = def.find('=') {
                        let name = def[..eq].to_string();
                        let val = def[eq + 1..].to_string();
                        opts.defines.push((name, Some(val)));
                    } else {
                        opts.defines.push((def.to_string(), Some("1".to_string())));
                    }
                }

                // ── Undefines ─────────────────────────────────────────
                flag if flag.starts_with("-U") => {
                    let undef = &flag[2..];
                    opts.undefines.push(undef.to_string());
                }

                // ── Warnings ──────────────────────────────────────────
                "-w" => opts.warnings = false,
                "-Wall" => opts.wall = true,
                "-Wextra" => opts.wextra = true,
                "-Wpedantic" | "-pedantic" => opts.pedantic = true,
                "-Werror" => opts.werror = true,
                flag if flag.starts_with("-Wno-") => {
                    opts.wno.push(flag[5..].to_string());
                }
                flag if flag.starts_with("-W")
                    && !flag.starts_with("-Wall")
                    && !flag.starts_with("-Wextra")
                    && !flag.starts_with("-Werror")
                    && !flag.starts_with("-Wno-")
                    && !flag.starts_with("-Wpedantic") =>
                {
                    opts.w.push(flag[2..].to_string());
                }

                // ── Misc flags ────────────────────────────────────────
                "-nostdinc" => opts.nostdinc = true,
                "-nostdinc++" => opts.nostdincpp = true,
                "-fPIC" | "-fpic" => opts.pic = true,
                "-fPIE" | "-fpie" => opts.pie = true,
                "-v" | "--verbose" => opts.verbose = true,
                "--version" => opts.print_version = true,
                "--help" | "-help" => opts.print_help = true,
                "-print-resource-dir" => opts.print_resource_dir = true,
                "-print-search-dirs" => opts.print_search_dirs = true,
                "-dumpmachine" => opts.print_target_triple = true,
                "-x" => {
                    i += 1;
                    if i < expanded.len() {
                        if let Some(lang) = InputLanguage::from_str(&expanded[i]) {
                            opts.lang = lang;
                        }
                    }
                }
                "-include" => {
                    i += 1;
                    if i < expanded.len() {
                        // Pre-include file (for preprocessing).
                        let _ = expanded[i].clone();
                    }
                }
                flag if flag.starts_with("-fstack-protector") => {
                    opts.stack_protector = 1;
                }
                flag if flag.starts_with("-fstack-protector-strong") => {
                    opts.stack_protector = 2;
                }
                flag if flag.starts_with("-fstack-protector-all") => {
                    opts.stack_protector = 3;
                }
                flag if flag.starts_with("-fsanitize=") => {
                    let s = &flag[11..];
                    for part in s.split(',') {
                        opts.sanitize.push(part.to_string());
                    }
                }
                flag if flag.starts_with("-ftls-model=") => {
                    opts.tls_model = flag[12..].to_string();
                }
                flag if flag.starts_with("-f") => {
                    // Unknown -f flags are silently ignored.
                }
                flag if flag.starts_with("-m") => {
                    // Unknown -m flags are silently ignored.
                }

                // ── Input files ───────────────────────────────────────
                arg if !arg.starts_with('-') => {
                    opts.input_files.push(PathBuf::from(arg));
                }

                _ => {
                    // Unknown flags: ignore.
                }
            }
            i += 1;
        }

        CompilerInvocation {
            opts,
            args: raw,
            program_name,
        }
    }

    /// Create a default invocation for simple compilation.
    pub fn default() -> Self {
        Self {
            opts: CompilerOptions::default(),
            args: vec!["clang".to_string()],
            program_name: "clang".to_string(),
        }
    }

    /// Get the output file path (or derive from input).
    pub fn output_file(&self) -> PathBuf {
        if let Some(ref out) = self.opts.output_file {
            return out.clone();
        }
        // Derive from first input file.
        if let Some(input) = self.opts.input_files.first() {
            let stem = input
                .file_stem()
                .unwrap_or_else(|| std::ffi::OsStr::new("a"));
            let ext = match self.opts.action {
                FrontendActionKind::PreprocessOnly => "i",
                FrontendActionKind::EmitLLVM => "ll",
                FrontendActionKind::EmitBC => "bc",
                FrontendActionKind::EmitAssembly => "s",
                FrontendActionKind::EmitObj => "o",
                _ => "out",
            };
            let mut out = PathBuf::from(stem);
            out.set_extension(ext);
            return out;
        }
        PathBuf::from("a.out")
    }
}

impl Default for CompilerInvocation {
    fn default() -> Self {
        Self {
            opts: CompilerOptions::default(),
            args: vec![],
            program_name: "clang".to_string(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CompilationDriver — executes compilation phases in order
// ═══════════════════════════════════════════════════════════════════════════════

/// The compilation driver orchestrates the phased compilation of source files.
///
/// It executes the standard phases: Preprocess → Parse → Sema → CodeGen → Emit,
/// stopping at the phase specified by the `FrontendActionKind`.
#[derive(Debug)]
pub struct CompilationDriver {
    /// The compiler instance.
    pub compiler: CompilerInstance,
    /// The frontend action.
    pub action: FrontendAction,
    /// Phase completion flags.
    phases: CompilationPhases,
}

/// Flags tracking which phases have completed.
#[derive(Debug, Default)]
struct CompilationPhases {
    preprocess_done: bool,
    parse_done: bool,
    sema_done: bool,
    codegen_done: bool,
    emit_done: bool,
}

impl CompilationDriver {
    /// Create a new compilation driver.
    pub fn new(compiler: CompilerInstance, action: FrontendAction) -> Self {
        Self {
            compiler,
            action,
            phases: CompilationPhases::default(),
        }
    }

    /// Create from command-line arguments.
    pub fn from_args<I, S>(args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let invocation = CompilerInvocation::from_args(args);
        let action = FrontendAction::for_kind(invocation.opts.action);
        let compiler = CompilerInstance::new(invocation);
        Self::new(compiler, action)
    }

    /// Run the full compilation pipeline.
    pub fn run(&mut self) -> Result<(), Vec<String>> {
        self.preprocess()?;
        self.parse()?;
        self.sema()?;
        self.codegen()?;
        self.emit()?;
        Ok(())
    }

    /// Preprocess only.
    pub fn preprocess(&mut self) -> Result<(), Vec<String>> {
        if self.phases.preprocess_done {
            return Ok(());
        }
        // Preprocessing is handled by the Preprocessor during lexing/parsing.
        // For preprocessing-only mode, run the preprocessor.
        if self.compiler.opts.preprocess_only {
            let fid = self
                .compiler
                .source_manager
                .main_file_id()
                .ok_or_else(|| vec!["no main file for preprocessing".to_string()])?;
            let source = self
                .compiler
                .source_manager
                .get_buffer(fid)
                .ok_or_else(|| vec!["no buffer for main file".to_string()])?;
            let _pp = Preprocessor::new(self.compiler.opts.standard);
            // In a real implementation, collect preprocessed output.
        }
        self.phases.preprocess_done = true;
        Ok(())
    }

    /// Parse only.
    pub fn parse(&mut self) -> Result<(), Vec<String>> {
        if self.phases.parse_done {
            return Ok(());
        }
        if self.compiler.opts.preprocess_only {
            return Ok(());
        }

        let fid = self
            .compiler
            .source_manager
            .main_file_id()
            .ok_or_else(|| vec!["no main file for parsing".to_string()])?;
        let source = self
            .compiler
            .source_manager
            .get_buffer(fid)
            .ok_or_else(|| vec!["no buffer for main file".to_string()])?;

        let tokens = lexer::tokenize(source, self.compiler.opts.standard);
        let mut parser = parser::Parser::new(&tokens, self.compiler.opts.standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse: {}", err))
                .collect::<Vec<_>>()
        })?;
        self.compiler.translation_unit = Some(tu);
        self.phases.parse_done = true;
        Ok(())
    }

    /// Semantic analysis only.
    pub fn sema(&mut self) -> Result<(), Vec<String>> {
        if self.phases.sema_done {
            return Ok(());
        }
        if self.compiler.opts.preprocess_only {
            return Ok(());
        }

        let tu = self
            .compiler
            .translation_unit
            .as_ref()
            .ok_or_else(|| vec!["no AST for semantic analysis".to_string()])?;
        let mut sema = Sema::new(self.compiler.opts.standard);
        sema.analyze(tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema: {}", err))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }
        if self.compiler.opts.syntax_only {
            return Ok(());
        }
        self.phases.sema_done = true;
        Ok(())
    }

    /// Code generation only.
    pub fn codegen(&mut self) -> Result<(), Vec<String>> {
        if self.phases.codegen_done {
            return Ok(());
        }
        if self.compiler.opts.preprocess_only || self.compiler.opts.syntax_only {
            return Ok(());
        }

        let tu = self
            .compiler
            .translation_unit
            .as_ref()
            .ok_or_else(|| vec!["no AST for codegen".to_string()])?;
        let mut cg = ClangCodeGen::new("input", &self.compiler.opts.target_triple);
        cg.compile(tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen: {}", err))
                .collect::<Vec<_>>()
        })?;
        self.phases.codegen_done = true;
        Ok(())
    }

    /// Emit output.
    pub fn emit(&mut self) -> Result<(), Vec<String>> {
        if self.phases.emit_done {
            return Ok(());
        }
        self.phases.emit_done = true;

        // Emit according to the action kind.
        match &mut self.action {
            FrontendAction::PreprocessOnly(a) => {
                // Already handled.
            }
            FrontendAction::SyntaxOnly(_) => {}
            FrontendAction::EmitLLVM(a) => {
                // TODO: emit LLVM IR text.
            }
            FrontendAction::EmitBC(_) => {
                // TODO: emit LLVM bitcode.
            }
            FrontendAction::EmitAssembly(_) => {
                // TODO: emit assembly text.
            }
            FrontendAction::EmitObj(_) => {
                // TODO: emit object file.
            }
            _ => {}
        }

        Ok(())
    }

    /// Check if a phase is complete.
    pub fn is_preprocess_done(&self) -> bool {
        self.phases.preprocess_done
    }
    pub fn is_parse_done(&self) -> bool {
        self.phases.parse_done
    }
    pub fn is_sema_done(&self) -> bool {
        self.phases.sema_done
    }
    pub fn is_codegen_done(&self) -> bool {
        self.phases.codegen_done
    }
    pub fn is_emit_done(&self) -> bool {
        self.phases.emit_done
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CompilerInstance — extended diagnostics, preprocessor, AST, sema, codegen
// ═══════════════════════════════════════════════════════════════════════════════

impl CompilerInstance {
    /// Create and configure the diagnostic engine with all options from CompilerOptions.
    ///
    /// Sets up warning flags, error limits, diagnostic output format, and
    /// diagnostic consumer based on compiler options.
    pub fn create_diagnostics(&mut self) -> DiagnosticEngine {
        let mut diag = DiagnosticEngine::new(ClangSourceManager::new());

        // Configure warning/error behavior.
        if self.opts.werror {
            diag.set_warnings_as_errors(true);
        }
        if !self.opts.warnings {
            diag.set_ignore_warnings(true);
        }
        // Note: weverything, wno, and w flags are tracked in self.opts
        // and applied during create_preprocessor and parse/sema phases.

        // Error limit (default: 20).
        diag.set_error_limit(20);

        self.diagnostics = diag;
        DiagnosticEngine::new(ClangSourceManager::new())
    }

    /// Create and configure the preprocessor with the compiler's include paths,
    /// predefined macros, and header search configuration.
    pub fn create_preprocessor(&mut self) -> Preprocessor {
        let mut pp = Preprocessor::new(self.opts.standard);

        // Add predefined macros.
        // __STDC__ and version macros.
        pp.define("__STDC__", "1");
        match self.opts.standard {
            CLangStandard::C89 => {
                pp.define("__STDC_VERSION__", "199409L");
            }
            CLangStandard::C99 | CLangStandard::Gnu99 => {
                pp.define("__STDC_VERSION__", "199901L");
            }
            CLangStandard::C11 | CLangStandard::Gnu11 => {
                pp.define("__STDC_VERSION__", "201112L");
            }
            CLangStandard::C17 | CLangStandard::Gnu17 => {
                pp.define("__STDC_VERSION__", "201710L");
            }
            CLangStandard::C23 => {
                pp.define("__STDC_VERSION__", "202311L");
            }
            _ => {}
        }

        // Architecture and OS defines.
        if self.opts.target_triple.contains("x86_64") {
            pp.define("__x86_64__", "1");
            pp.define("__amd64__", "1");
        }
        if self.opts.target_triple.contains("aarch64") {
            pp.define("__aarch64__", "1");
        }
        if self.opts.target_triple.contains("linux") {
            pp.define("__linux__", "1");
            pp.define("__gnu_linux__", "1");
        }
        if self.opts.target_triple.contains("darwin") || self.opts.target_triple.contains("macos") {
            pp.define("__APPLE__", "1");
        }
        if self.opts.target_triple.contains("windows") || self.opts.target_triple.contains("mingw")
        {
            pp.define("_WIN32", "1");
        }

        // GNU extensions.
        if self.opts.gnu_extensions {
            pp.define("__GNUC__", "4");
            pp.define("__GNUC_MINOR__", "2");
            pp.define("__GNUC_PATCHLEVEL__", "1");
        }

        // Explicit defines from command line.
        for (name, value) in &self.opts.defines {
            let body: String = value.as_deref().unwrap_or("1").to_string();
            pp.define(name, &body);
        }

        // Undefines are tracked but not directly supported by the Preprocessor.
        // In a real implementation, these would be removed from the macro table.

        // Configure include paths.
        for path in &self.opts.includes {
            if let Some(s) = path.to_str() {
                pp.add_include_path(s);
            }
        }
        // System includes use the same mechanism but are tracked separately.
        for path in &self.opts.system_includes {
            if let Some(s) = path.to_str() {
                pp.add_include_path(s);
            }
        }

        // No standard includes flag.
        if self.opts.nostdinc {
            // Clear default include paths that would have been added.
            // In a real implementation, this would disable the built-in search paths.
        }

        pp
    }

    /// Create the AST context with target information.
    ///
    /// The ASTContext holds type information, language options, and
    /// target-specific data needed for semantic analysis.
    pub fn create_ast_context(&mut self) -> ASTContext {
        let lang_opts = LangOptions {
            standard: self.opts.standard,
            gnu_extensions: self.opts.gnu_extensions,
            ms_extensions: self.opts.ms_extensions,
            trigraphs: self.opts.trigraphs,
            digraphs: self.opts.digraphs,
            cxx_mode: false,
        };

        let target_info = TargetInfo {
            triple: self.opts.target_triple.clone(),
            pointer_width: 64,
            size_t_width: 64,
            wchar_width: 32,
            char_is_signed: true,
            int_width: 32,
            long_width: if self.opts.target_triple.contains("windows") {
                32
            } else {
                64
            },
            long_long_width: 64,
            short_width: 16,
            float_width: 32,
            double_width: 64,
            long_double_width: if self.opts.target_triple.contains("x86_64") {
                80
            } else {
                128
            },
            alignof_pointer: 8,
            max_alignment: 16,
            null_pointer_value: 0u64,
            user_label_prefix: String::new(),
        };

        ASTContext::new(lang_opts, target_info)
    }

    /// Create and initialize the semantic analyzer.
    pub fn create_sema(&mut self) -> Sema {
        Sema::new(self.opts.standard)
    }

    /// Create a code generator with a TargetMachine for the configured target.
    pub fn create_codegen(&self) -> ClangCodeGen<'_> {
        ClangCodeGen::new("input", &self.opts.target_triple)
    }

    /// Create a code generator with a specific module name.
    pub fn create_codegen_named(&self, module_name: &str) -> ClangCodeGen<'_> {
        ClangCodeGen::new(module_name, &self.opts.target_triple)
    }

    /// Execute a frontend action from beginning to end.
    ///
    /// This is the main entry point for running any FrontendAction.
    /// It orchestrates the full compilation flow:
    /// 1. BeginSourceFile — sets up source, preprocessor, AST
    /// 2. Execute — runs parse + sema + codegen + emit phases
    /// 3. EndSourceFile — cleanup and flush diagnostics
    pub fn execute_action(&mut self, action: &mut FrontendAction) -> Result<(), Vec<String>> {
        // Phase 1: Begin source file.
        self.begin_source_file(action)?;

        // Phase 2: Execute the action.
        action.execute()?;

        // Phase 3: End source file.
        self.end_source_file()?;

        Ok(())
    }

    /// Execute a frontend action with full error recovery.
    ///
    /// Unlike execute_action, this method attempts to continue after
    /// non-fatal errors and collects all diagnostics.
    pub fn execute_action_with_recovery(
        &mut self,
        action: &mut FrontendAction,
    ) -> (bool, Vec<String>) {
        let mut errors: Vec<String> = Vec::new();

        // Try to begin source file.
        match self.begin_source_file(action) {
            Ok(()) => {}
            Err(e) => {
                errors.extend(e);
                return (false, errors);
            }
        }

        // Try to execute.
        match action.execute() {
            Ok(()) => {}
            Err(e) => {
                errors.extend(e);
            }
        }

        // Always try to end source file.
        if let Err(e) = self.end_source_file() {
            errors.extend(e);
        }

        (errors.is_empty(), errors)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ASTContext — Holds type and target information for semantic analysis
// ═══════════════════════════════════════════════════════════════════════════════

/// Language options that configure parsing and semantic analysis behavior.
#[derive(Debug, Clone)]
pub struct LangOptions {
    pub standard: CLangStandard,
    pub gnu_extensions: bool,
    pub ms_extensions: bool,
    pub trigraphs: bool,
    pub digraphs: bool,
    pub cxx_mode: bool,
}

impl Default for LangOptions {
    fn default() -> Self {
        Self {
            standard: CLangStandard::C17,
            gnu_extensions: false,
            ms_extensions: false,
            trigraphs: false,
            digraphs: true,
            cxx_mode: false,
        }
    }
}

/// Target-specific information used by the AST and code generator.
#[derive(Debug, Clone)]
pub struct TargetInfo {
    pub triple: String,
    pub pointer_width: u32,
    pub size_t_width: u32,
    pub wchar_width: u32,
    pub char_is_signed: bool,
    pub int_width: u32,
    pub long_width: u32,
    pub long_long_width: u32,
    pub short_width: u32,
    pub float_width: u32,
    pub double_width: u32,
    pub long_double_width: u32,
    pub alignof_pointer: u32,
    pub max_alignment: u32,
    pub null_pointer_value: u64,
    pub user_label_prefix: String,
}

impl TargetInfo {
    /// Create a default target info for x86_64 Linux.
    pub fn default_x86_64_linux() -> Self {
        Self {
            triple: "x86_64-unknown-linux-gnu".to_string(),
            pointer_width: 64,
            size_t_width: 64,
            wchar_width: 32,
            char_is_signed: true,
            int_width: 32,
            long_width: 64,
            long_long_width: 64,
            short_width: 16,
            float_width: 32,
            double_width: 64,
            long_double_width: 80,
            alignof_pointer: 8,
            max_alignment: 16,
            null_pointer_value: 0,
            user_label_prefix: String::new(),
        }
    }

    /// Create target info for aarch64 Linux.
    pub fn default_aarch64_linux() -> Self {
        Self {
            triple: "aarch64-unknown-linux-gnu".to_string(),
            pointer_width: 64,
            size_t_width: 64,
            wchar_width: 32,
            char_is_signed: false,
            int_width: 32,
            long_width: 64,
            long_long_width: 64,
            short_width: 16,
            float_width: 32,
            double_width: 64,
            long_double_width: 128,
            alignof_pointer: 8,
            max_alignment: 16,
            null_pointer_value: 0,
            user_label_prefix: String::new(),
        }
    }

    /// Get the width of the specified integer type in bits.
    pub fn get_type_width(&self, ty: &str) -> Option<u32> {
        match ty {
            "char" => Some(8),
            "short" => Some(self.short_width),
            "int" => Some(self.int_width),
            "long" => Some(self.long_width),
            "long long" => Some(self.long_long_width),
            "float" => Some(self.float_width),
            "double" => Some(self.double_width),
            "long double" => Some(self.long_double_width),
            "pointer" | "size_t" => Some(self.pointer_width),
            "wchar_t" => Some(self.wchar_width),
            _ => None,
        }
    }

    /// Get the alignment of the specified type in bytes.
    pub fn get_type_align(&self, ty: &str) -> Option<u32> {
        let width = self.get_type_width(ty)?;
        Some((width + 7) / 8)
    }

    /// Get pointer width in bytes.
    pub fn pointer_width_bytes(&self) -> u32 {
        self.pointer_width / 8
    }

    /// Is this target little-endian?
    pub fn is_little_endian(&self) -> bool {
        // All supported targets are little-endian for now.
        true
    }
}

impl Default for TargetInfo {
    fn default() -> Self {
        Self::default_x86_64_linux()
    }
}

/// The AST context holds all type information and target data for a compilation.
#[derive(Debug, Clone)]
pub struct ASTContext {
    pub lang_opts: LangOptions,
    pub target_info: TargetInfo,
    pub types: Vec<QualType>,
    pub type_names: Vec<String>,
    pub builtin_types_initialized: bool,
}

impl ASTContext {
    /// Create a new AST context with the given language options and target info.
    pub fn new(lang_opts: LangOptions, target_info: TargetInfo) -> Self {
        let mut ctx = Self {
            lang_opts,
            target_info,
            types: Vec::new(),
            type_names: Vec::new(),
            builtin_types_initialized: false,
        };
        ctx.initialize_builtin_types();
        ctx
    }

    /// Initialize the built-in types.
    fn initialize_builtin_types(&mut self) {
        if self.builtin_types_initialized {
            return;
        }
        self.builtin_types_initialized = true;

        // Initialize all standard C types.
        self.types.push(QualType::void());
        self.type_names.push("void".to_string());

        self.types.push(QualType::char_type());
        self.type_names.push("char".to_string());

        self.types.push(QualType::schar());
        self.type_names.push("signed char".to_string());

        self.types.push(QualType::uchar());
        self.type_names.push("unsigned char".to_string());

        self.types.push(QualType::short_type());
        self.type_names.push("short".to_string());

        self.types.push(QualType::ushort());
        self.type_names.push("unsigned short".to_string());

        self.types.push(QualType::int());
        self.type_names.push("int".to_string());

        self.types.push(QualType::uint());
        self.type_names.push("unsigned int".to_string());

        self.types.push(QualType::long_type());
        self.type_names.push("long".to_string());

        self.types.push(QualType::ulong());
        self.type_names.push("unsigned long".to_string());

        self.types.push(QualType::long_long());
        self.type_names.push("long long".to_string());

        self.types.push(QualType::ulong_long());
        self.type_names.push("unsigned long long".to_string());

        self.types.push(QualType::float_type());
        self.type_names.push("float".to_string());

        self.types.push(QualType::double_type());
        self.type_names.push("double".to_string());

        self.types.push(QualType::long_double());
        self.type_names.push("long double".to_string());
    }

    /// Look up a type by its name.
    pub fn lookup_type(&self, name: &str) -> Option<&QualType> {
        self.type_names
            .iter()
            .position(|n| n == name)
            .map(|i| &self.types[i])
    }

    /// Get the size of a type in bits.
    pub fn get_type_size(&self, ty: &QualType) -> u32 {
        // Use target info for type sizing.
        if ty.is_void() {
            return 0;
        }
        if ty.is_pointer() {
            return self.target_info.pointer_width;
        }
        if ty.is_integer() {
            if ty.is_char() {
                return 8;
            }
            if ty.is_short() {
                return self.target_info.short_width;
            }
            if ty.is_int() {
                return self.target_info.int_width;
            }
            if ty.is_long() {
                return self.target_info.long_width;
            }
            if ty.is_long_long() {
                return self.target_info.long_long_width;
            }
            return 32;
        }
        if ty.is_floating() {
            if ty.is_float() {
                return self.target_info.float_width;
            }
            if ty.is_double() {
                return self.target_info.double_width;
            }
            return self.target_info.long_double_width;
        }
        32
    }

    /// Get the alignment of a type in bits.
    pub fn get_type_align(&self, ty: &QualType) -> u32 {
        let size = self.get_type_size(ty);
        if size >= 128 {
            128
        } else if size >= 64 {
            64
        } else if size >= 32 {
            32
        } else if size >= 16 {
            16
        } else {
            8
        }
    }
}

impl Default for ASTContext {
    fn default() -> Self {
        Self::new(LangOptions::default(), TargetInfo::default())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ParseAST — parse the entire translation unit and feed to ASTConsumer
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse an entire translation unit from source and feed each top-level
/// declaration to the given AST consumer.
///
/// This is the primary entry point for AST-based compilation.
/// It runs lexical analysis, preprocessing, and parsing, then calls
/// `HandleTopLevelDecl` on the consumer for each declaration.
pub fn parse_ast(
    consumer: &mut dyn ASTConsumer,
    source: &str,
    standard: CLangStandard,
) -> Result<TranslationUnit, Vec<String>> {
    let tokens = lexer::tokenize(source, standard);
    let mut parser = parser::Parser::new(&tokens, standard);
    let tu = parser.parse().map_err(|e| {
        e.into_iter()
            .map(|err| format!("parse error: {}", err))
            .collect::<Vec<_>>()
    })?;

    // Notify consumer of translation unit begin.
    consumer.handle_translation_unit_begin(&tu);

    // Feed each top-level declaration to the consumer.
    for decl in &tu.decls {
        consumer.handle_top_level_decl(decl);
    }

    // Notify consumer of translation unit end.
    consumer.handle_translation_unit_end(&tu);

    Ok(tu)
}

/// Parse with semantic analysis, feeding results to a consumer.
pub fn parse_and_sema_ast(
    consumer: &mut dyn ASTConsumer,
    source: &str,
    standard: CLangStandard,
) -> Result<TranslationUnit, Vec<String>> {
    // Parse.
    let tokens = lexer::tokenize(source, standard);
    let mut parser = parser::Parser::new(&tokens, standard);
    let tu = parser.parse().map_err(|e| {
        e.into_iter()
            .map(|err| format!("parse error: {}", err))
            .collect::<Vec<_>>()
    })?;

    // Semantic analysis.
    let mut sema = Sema::new(standard);
    sema.analyze(&tu).map_err(|e| {
        e.iter()
            .map(|err| format!("sema error: {}", err))
            .collect::<Vec<_>>()
    })?;
    if sema.has_errors() {
        return Err(sema.errors.clone());
    }

    // Feed to consumer.
    consumer.handle_translation_unit_begin(&tu);
    for decl in &tu.decls {
        consumer.handle_top_level_decl(decl);
    }
    consumer.handle_translation_unit_end(&tu);

    Ok(tu)
}

// ═══════════════════════════════════════════════════════════════════════════════
// CodeGenAction — parse→sema→codegen→emit with error checking
// ═══════════════════════════════════════════════════════════════════════════════

/// A frontend action that performs code generation.
///
/// CodeGenAction runs the full parse→sema→codegen pipeline and
/// optionally emits the result in various formats.
#[derive(Debug)]
pub struct CodeGenAction {
    /// The LLVM module produced by code generation.
    pub module: Option<Module>,
    /// The kind of output to produce.
    pub output_kind: OutputFormat,
    /// The target triple.
    pub triple: String,
    /// Optional output file path.
    pub output_file: Option<PathBuf>,
    /// Whether to verify the module after codegen.
    pub verify_module: bool,
    /// Collected diagnostics during codegen.
    pub diagnostics: Vec<String>,
    /// Whether codegen succeeded.
    pub succeeded: bool,
}

impl CodeGenAction {
    /// Create a new codegen action for the given output format.
    pub fn new(output_kind: OutputFormat, triple: &str) -> Self {
        Self {
            module: None,
            output_kind,
            triple: triple.to_string(),
            output_file: None,
            verify_module: true,
            diagnostics: Vec::new(),
            succeeded: false,
        }
    }

    /// Set the output file path.
    pub fn set_output_file(&mut self, path: PathBuf) {
        self.output_file = Some(path);
    }

    /// Execute the codegen action: parse → sema → codegen → emit.
    pub fn execute_action(
        &mut self,
        source: &str,
        standard: CLangStandard,
    ) -> Result<(), Vec<String>> {
        // Phase 1: Lex and parse.
        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            let errs: Vec<String> = e
                .into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect();
            self.diagnostics.extend(errs.clone());
            errs
        })?;

        // Phase 2: Semantic analysis.
        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            let errs: Vec<String> = e.iter().map(|err| format!("sema error: {}", err)).collect();
            self.diagnostics.extend(errs.clone());
            errs
        })?;
        if sema.has_errors() {
            self.diagnostics.extend(sema.errors.clone());
            return Err(sema.errors.clone());
        }

        // Phase 3: Code generation.
        let mut cg = ClangCodeGen::new("input", &self.triple);
        cg.compile(&tu).map_err(|e| {
            let errs: Vec<String> = e
                .iter()
                .map(|err| format!("codegen error: {}", err))
                .collect();
            self.diagnostics.extend(errs.clone());
            errs
        })?;

        // Phase 4: Verify the module.
        if self.verify_module {
            // In a real implementation, we'd use LLVM's verifier.
            // For now, we just note that verification was requested.
        }

        self.module = Some(cg.module);
        self.succeeded = true;

        // Phase 5: Emit output based on output kind.
        match self.output_kind {
            OutputFormat::LLVM_IR => {
                // Emit .ll text.
                if let Some(ref module) = self.module {
                    let _ir = format!("; ModuleID = '{}'\n", module.name);
                }
            }
            OutputFormat::LLVM_BC => {
                // Emit .bc bitcode.
                // Bitcode serialization would go here.
            }
            OutputFormat::Assembly => {
                // Emit .s assembly.
                // TargetMachine assembly emission would go here.
            }
            OutputFormat::Object => {
                // Emit .o object file.
                // TargetMachine object emission would go here.
            }
            OutputFormat::Executable | OutputFormat::SharedLib => {
                // Linking phase would be handled by the driver.
            }
            _ => {}
        }

        Ok(())
    }

    /// Get the produced LLVM module.
    pub fn get_module(&self) -> Option<&Module> {
        self.module.as_ref()
    }

    /// Check if codegen succeeded.
    pub fn is_successful(&self) -> bool {
        self.succeeded
    }

    /// Get all collected diagnostics.
    pub fn get_diagnostics(&self) -> &[String] {
        &self.diagnostics
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EmitObjAction — codegen → TargetMachine → object file (.o output)
// ═══════════════════════════════════════════════════════════════════════════════

/// An action that produces an object file from source code.
///
/// Runs the full pipeline: lex→parse→sema→codegen→TargetMachine→.o
#[derive(Debug)]
pub struct EmitObjActionFull {
    /// The target triple.
    pub triple: String,
    /// Output file path.
    pub output_file: PathBuf,
    /// Optimization level.
    pub opt_level: OptLevel,
    /// Whether to include debug info.
    pub debug_info: bool,
    /// The resulting object bytes.
    pub object_bytes: Option<Vec<u8>>,
    /// Whether the action completed successfully.
    pub completed: bool,
}

impl EmitObjActionFull {
    /// Create a new object file emission action.
    pub fn new(triple: &str, output_file: PathBuf, opt_level: OptLevel) -> Self {
        Self {
            triple: triple.to_string(),
            output_file,
            opt_level,
            debug_info: false,
            object_bytes: None,
            completed: false,
        }
    }

    /// Set debug info flag.
    pub fn set_debug_info(&mut self, debug: bool) {
        self.debug_info = debug;
    }

    /// Execute the action: compile source to object bytes.
    pub fn execute(
        &mut self,
        source: &str,
        standard: CLangStandard,
    ) -> Result<Vec<u8>, Vec<String>> {
        // Lex and parse.
        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        // Semantic analysis.
        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        // Code generation.
        let mut cg = ClangCodeGen::new("input", &self.triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen error: {}", err))
                .collect::<Vec<_>>()
        })?;

        // Emit object file through TargetMachine.
        // In a real implementation:
        // 1. Create TargetMachine with self.triple, self.opt_level
        // 2. Run optimization passes
        // 3. Emit object bytes via MC layer
        //
        // For now, return placeholder object bytes.
        let obj = self.emit_object(&cg.module)?;
        self.object_bytes = Some(obj.clone());
        self.completed = true;

        // Write to file if output file is set.
        if !self.output_file.as_os_str().is_empty() {
            if let Some(ref bytes) = self.object_bytes {
                std::fs::write(&self.output_file, bytes)
                    .map_err(|e| vec![format!("failed to write object file: {}", e)])?;
            }
        }

        Ok(obj)
    }

    /// Emit object bytes from the LLVM module through the TargetMachine.
    fn emit_object(&self, _module: &Module) -> Result<Vec<u8>, Vec<String>> {
        // In a full implementation, this would:
        // 1. Create an LLVMTargetMachine for the triple
        // 2. Add optimization passes if self.opt_level > O0
        // 3. Use LLVM's object streamer to emit machine code
        //
        // For now, return a minimal ELF header as placeholder.
        let mut obj = Vec::new();

        // Minimal ELF64 header.
        obj.extend_from_slice(&[0x7f, b'E', b'L', b'F']); // ELF magic
        obj.push(2); // 64-bit
        obj.push(1); // Little-endian
        obj.push(1); // ELF version
        obj.push(0); // System V ABI
        obj.push(0); // ABI version
        obj.extend_from_slice(&[0; 7]); // Padding
        obj.extend_from_slice(&[2, 0]); // ET_EXEC (little-endian)
        obj.extend_from_slice(&[0x3e, 0]); // x86_64
        obj.extend_from_slice(&[1, 0, 0, 0]); // ELF version
                                              // Entry point, program header, section header offsets (zeroed).
        obj.extend_from_slice(&[0; 8 + 8 + 4]);
        obj.extend_from_slice(&[64, 0]); // ELF header size
        obj.extend_from_slice(&[56, 0]); // Program header size
        obj.extend_from_slice(&[0, 0]); // Number of program headers
        obj.extend_from_slice(&[64, 0]); // Section header size
        obj.extend_from_slice(&[0, 0]); // Number of section headers
        obj.extend_from_slice(&[0, 0]); // Section header string table index

        Ok(obj)
    }

    /// Get the object bytes.
    pub fn get_object_bytes(&self) -> Option<&[u8]> {
        self.object_bytes.as_deref()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EmitAssemblyAction — codegen → TargetMachine → assembly (.s output)
// ═══════════════════════════════════════════════════════════════════════════════

/// An action that produces assembly text from source code.
#[derive(Debug)]
pub struct EmitAssemblyActionFull {
    /// The target triple.
    pub triple: String,
    /// Output file path.
    pub output_file: PathBuf,
    /// Optimization level.
    pub opt_level: OptLevel,
    /// The resulting assembly text.
    pub assembly_text: Option<String>,
    /// Whether the action completed successfully.
    pub completed: bool,
}

impl EmitAssemblyActionFull {
    /// Create a new assembly emission action.
    pub fn new(triple: &str, output_file: PathBuf, opt_level: OptLevel) -> Self {
        Self {
            triple: triple.to_string(),
            output_file,
            opt_level,
            assembly_text: None,
            completed: false,
        }
    }

    /// Execute the action: compile source to assembly.
    pub fn execute(
        &mut self,
        source: &str,
        standard: CLangStandard,
    ) -> Result<String, Vec<String>> {
        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        let mut cg = ClangCodeGen::new("input", &self.triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen error: {}", err))
                .collect::<Vec<_>>()
        })?;

        // Emit assembly through TargetMachine.
        let asm = self.emit_assembly(&cg.module)?;
        self.assembly_text = Some(asm.clone());
        self.completed = true;

        // Write to file.
        if !self.output_file.as_os_str().is_empty() {
            if let Some(ref text) = self.assembly_text {
                std::fs::write(&self.output_file, text)
                    .map_err(|e| vec![format!("failed to write assembly file: {}", e)])?;
            }
        }

        Ok(asm)
    }

    /// Emit assembly text from the LLVM module.
    fn emit_assembly(&self, module: &Module) -> Result<String, Vec<String>> {
        let mut asm = String::new();
        asm.push_str(&format!("\t.text\n"));
        asm.push_str(&format!("\t.file\t\"{}\"\n", module.name));

        for func in &module.functions {
            let func = func.borrow();
            asm.push_str(&format!("\t.globl\t{}\n", func.name));
            asm.push_str(&format!("\t.type\t{},@function\n", func.name));
            asm.push_str(&format!("{}:\n", func.name));
            for bb in &func.blocks {
                let bb = bb.borrow();
                if !bb.name.is_empty() {
                    asm.push_str(&format!(".L{}:\n", bb.name));
                }
                for inst in &bb.instructions {
                    let inst = inst.borrow();
                    asm.push_str(&format!("\t; {:?}\n", inst.opcode));
                }
            }
            asm.push_str(&format!("\t.size\t{}, .-{}\n", func.name, func.name));
        }

        if module.functions.is_empty() {
            asm.push_str("\t; empty module\n");
        }

        Ok(asm)
    }

    /// Get the assembly text.
    pub fn get_assembly(&self) -> Option<&str> {
        self.assembly_text.as_deref()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EmitLLVMActionFull — codegen → Module → .ll text output
// ═══════════════════════════════════════════════════════════════════════════════

/// An action that produces LLVM IR text from source code.
#[derive(Debug)]
pub struct EmitLLVMActionFull {
    /// The target triple.
    pub triple: String,
    /// Output file path.
    pub output_file: PathBuf,
    /// Optimization level.
    pub opt_level: OptLevel,
    /// The resulting IR text.
    pub ir_text: Option<String>,
    /// Whether the action completed successfully.
    pub completed: bool,
}

impl EmitLLVMActionFull {
    /// Create a new LLVM IR emission action.
    pub fn new(triple: &str, output_file: PathBuf) -> Self {
        Self {
            triple: triple.to_string(),
            output_file,
            opt_level: OptLevel::O0,
            ir_text: None,
            completed: false,
        }
    }

    /// Execute the action: compile source to LLVM IR.
    pub fn execute(
        &mut self,
        source: &str,
        standard: CLangStandard,
    ) -> Result<String, Vec<String>> {
        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        let mut cg = ClangCodeGen::new("input", &self.triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let ir = self.emit_ir(&cg.module);
        self.ir_text = Some(ir.clone());
        self.completed = true;

        // Write to file.
        if !self.output_file.as_os_str().is_empty() {
            if let Some(ref text) = self.ir_text {
                std::fs::write(&self.output_file, text)
                    .map_err(|e| vec![format!("failed to write IR file: {}", e)])?;
            }
        }

        Ok(ir)
    }

    /// Emit LLVM IR text from the module.
    fn emit_ir(&self, module: &Module) -> String {
        let mut ir = String::new();
        ir.push_str(&format!("; ModuleID = '{}'\n", module.name));
        ir.push_str(&format!("source_filename = \"{}\"\n", module.name));
        ir.push_str(&format!("target triple = \"{}\"\n", self.triple));

        // Emit data layout string.
        ir.push_str("target datalayout = \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128\"\n");
        ir.push_str("\n");

        // Emit global variables.
        for gv in &module.globals {
            let gv = gv.borrow();
            ir.push_str(&format!("@{} = ", gv.name));
            if gv.is_constant {
                ir.push_str("constant ");
            } else {
                ir.push_str("global ");
            }
            if let Some(ref init) = gv.initializer {
                ir.push_str(&format!("{}", init.borrow().name));
            } else {
                ir.push_str("zeroinitializer");
            }
            ir.push_str("\n");
        }
        if !module.globals.is_empty() {
            ir.push_str("\n");
        }

        // Emit function declarations.
        for decl in &module.declarations {
            let decl = decl.borrow();
            ir.push_str(&format!(
                "declare {} @{}(",
                decl.return_type
                    .as_ref()
                    .map(|t| t.to_string())
                    .unwrap_or_else(|| "void".to_string()),
                decl.name
            ));
            for (i, param) in decl.params.iter().enumerate() {
                if i > 0 {
                    ir.push_str(", ");
                }
                ir.push_str(&format!("{}", param));
            }
            if decl.is_vararg {
                if !decl.params.is_empty() {
                    ir.push_str(", ");
                }
                ir.push_str("...");
            }
            ir.push_str(")\n");
        }
        if !module.declarations.is_empty() {
            ir.push_str("\n");
        }

        // Emit function definitions.
        for func in &module.functions {
            let func = func.borrow();
            ir.push_str(&format!(
                "define {} @{} (",
                func.return_type
                    .as_ref()
                    .map(|t| t.to_string())
                    .unwrap_or_else(|| "void".to_string()),
                func.name
            ));
            for (i, param) in func.params.iter().enumerate() {
                if i > 0 {
                    ir.push_str(", ");
                }
                ir.push_str(&format!("{} %{}", param, i));
            }
            ir.push_str(") {\n");

            for bb in &func.blocks {
                let bb = bb.borrow();
                if !bb.name.is_empty() {
                    ir.push_str(&format!("{}:\n", bb.name));
                } else {
                    ir.push_str("entry:\n");
                }
                for inst in &bb.instructions {
                    let inst = inst.borrow();
                    if let Some(ref result) = inst.result {
                        ir.push_str(&format!("  %{} = {:?}", result, inst.opcode));
                    } else {
                        ir.push_str(&format!("  {:?}", inst.opcode));
                    }
                    ir.push_str("\n");
                }
            }
            ir.push_str("}\n\n");
        }

        // Emit module-level metadata.
        ir.push_str(&format!("!llvm.module.flags = !{{!0}}\n"));
        ir.push_str(&format!(
            "!0 = !{{i32 2, !\"Debug Info Version\", i32 3}}\n"
        ));

        ir
    }

    /// Get the IR text.
    pub fn get_ir(&self) -> Option<&str> {
        self.ir_text.as_deref()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EmitBCActionFull — codegen → Module → .bc bitcode output
// ═══════════════════════════════════════════════════════════════════════════════

/// An action that produces LLVM bitcode from source code.
#[derive(Debug)]
pub struct EmitBCActionFull {
    /// The target triple.
    pub triple: String,
    /// Output file path.
    pub output_file: PathBuf,
    /// The resulting bitcode bytes.
    pub bitcode_bytes: Option<Vec<u8>>,
    /// Whether the action completed successfully.
    pub completed: bool,
}

impl EmitBCActionFull {
    /// Create a new bitcode emission action.
    pub fn new(triple: &str, output_file: PathBuf) -> Self {
        Self {
            triple: triple.to_string(),
            output_file,
            bitcode_bytes: None,
            completed: false,
        }
    }

    /// Execute the action: compile source to LLVM bitcode.
    pub fn execute(
        &mut self,
        source: &str,
        standard: CLangStandard,
    ) -> Result<Vec<u8>, Vec<String>> {
        let tokens = lexer::tokenize(source, standard);
        let mut parser = parser::Parser::new(&tokens, standard);
        let tu = parser.parse().map_err(|e| {
            e.into_iter()
                .map(|err| format!("parse error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let mut sema = Sema::new(standard);
        sema.analyze(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("sema error: {}", err))
                .collect::<Vec<_>>()
        })?;
        if sema.has_errors() {
            return Err(sema.errors.clone());
        }

        let mut cg = ClangCodeGen::new("input", &self.triple);
        cg.compile(&tu).map_err(|e| {
            e.iter()
                .map(|err| format!("codegen error: {}", err))
                .collect::<Vec<_>>()
        })?;

        let bc = self.emit_bitcode(&cg.module);
        self.bitcode_bytes = Some(bc.clone());
        self.completed = true;

        // Write to file.
        if !self.output_file.as_os_str().is_empty() {
            if let Some(ref bytes) = self.bitcode_bytes {
                std::fs::write(&self.output_file, bytes)
                    .map_err(|e| vec![format!("failed to write bitcode file: {}", e)])?;
            }
        }

        Ok(bc)
    }

    /// Emit bitcode bytes from the LLVM module.
    fn emit_bitcode(&self, _module: &Module) -> Vec<u8> {
        // LLVM bitcode format (simplified wrapper).
        let mut bc = Vec::new();

        // Magic number for LLVM IR bitcode (0xDEC0DEC0 or 0x0B17C0DE).
        // Real implementation would use LLVM's BitcodeWriter.
        bc.extend_from_slice(&[0xDE, 0xC0, 0x17, 0x0B]); // "BC\xC0\xDE"

        // Placeholder bitcode content.
        // A real implementation would serialize the module using
        // LLVM's bitcode format with block structure:
        // - BLOCKINFO_BLOCK
        // - MODULE_BLOCK
        //   - TYPE_BLOCK
        //   - PARAMATTR_BLOCK
        //   - FUNCTION_BLOCK
        //     - CONSTANTS_BLOCK
        //     - VALUE_SYMTAB_BLOCK
        //     - METADATA_BLOCK

        bc.extend_from_slice(&[0; 64]); // Placeholder content

        bc
    }

    /// Get the bitcode bytes.
    pub fn get_bitcode(&self) -> Option<&[u8]> {
        self.bitcode_bytes.as_deref()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FrontendAction — full initialize/execute/cleanup lifecycle
// ═══════════════════════════════════════════════════════════════════════════════

/// Extended FrontendAction with full lifecycle management.
///
/// Implements BeginSourceFile → Execute → EndSourceFile with proper
/// initialization of source, preprocessor, AST, and code generation.
impl FrontendAction {
    /// Begin processing a source file: initialize source manager,
    /// preprocessor, and AST context.
    pub fn begin_source_file_full(
        &mut self,
        source: &str,
        compiler: &mut CompilerInstance,
    ) -> Result<(), Vec<String>> {
        // Load the source into the source manager.
        let _fid = compiler
            .source_manager
            .load_virtual_file("<input>", source.to_string())
            .map_err(|e| vec![format!("failed to load source: {}", e)])?;

        // Create preprocessor with command-line defines and includes.
        let _pp = compiler.create_preprocessor();

        // Create AST context with target and language options.
        let _ast_ctx = compiler.create_ast_context();

        Ok(())
    }

    /// Execute the action: run parse + sema + codegen + emit phases.
    pub fn execute_full(
        &mut self,
        source: &str,
        compiler: &mut CompilerInstance,
    ) -> Result<(), Vec<String>> {
        match self {
            FrontendAction::PreprocessOnly(action) => {
                action.execute();
                Ok(())
            }
            FrontendAction::SyntaxOnly(_) => {
                let tokens = lexer::tokenize(source, compiler.opts.standard);
                let mut parser = parser::Parser::new(&tokens, compiler.opts.standard);
                let tu = parser.parse().map_err(|e| {
                    e.into_iter()
                        .map(|err| format!("parse error: {}", err))
                        .collect::<Vec<_>>()
                })?;
                let mut sema = Sema::new(compiler.opts.standard);
                sema.analyze(&tu).map_err(|e| {
                    e.iter()
                        .map(|err| format!("sema error: {}", err))
                        .collect::<Vec<_>>()
                })?;
                if sema.has_errors() {
                    return Err(sema.errors.clone());
                }
                Ok(())
            }
            FrontendAction::EmitLLVM(action) => {
                action.execute();
                Ok(())
            }
            FrontendAction::EmitBC(action) => {
                action.execute();
                Ok(())
            }
            FrontendAction::EmitAssembly(action) => {
                action.execute();
                Ok(())
            }
            FrontendAction::EmitObj(action) => {
                action.execute();
                Ok(())
            }
            FrontendAction::ASTDump(_) => {
                let tokens = lexer::tokenize(source, compiler.opts.standard);
                let mut parser = parser::Parser::new(&tokens, compiler.opts.standard);
                let tu = parser.parse().map_err(|e| {
                    e.into_iter()
                        .map(|err| format!("parse error: {}", err))
                        .collect::<Vec<_>>()
                })?;
                // Dump AST.
                for decl in &tu.decls {
                    eprintln!("{}", decl);
                }
                Ok(())
            }
            FrontendAction::DumpTokens(_) => {
                let tokens = lexer::tokenize(source, compiler.opts.standard);
                for tok in &tokens {
                    eprintln!("{} {:?}", tok.location.line, tok.kind);
                }
                Ok(())
            }
        }
    }

    /// End source file processing: cleanup, flush diagnostics.
    pub fn end_source_file_full(
        &mut self,
        compiler: &mut CompilerInstance,
    ) -> Result<(), Vec<String>> {
        // Flush any pending diagnostics.
        // In a real implementation, this would flush the diagnostic consumer.

        // Reset compiler state.
        compiler.source_file_begun = false;

        // Call action-specific cleanup.
        self.end_source_file()?;

        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MultiplexConsumer — dispatch HandleTranslationUnit to all sub-consumers
// ═══════════════════════════════════════════════════════════════════════════════

impl MultiplexConsumer {
    /// Create a multiplex consumer that dispatches to all given sub-consumers.
    pub fn create(consumers: Vec<Box<dyn ASTConsumer>>) -> Self {
        Self { consumers }
    }

    /// Dispatch the entire translation unit to all sub-consumers at once.
    ///
    /// This is called when the full TU is available and all consumers
    /// should process it simultaneously.
    pub fn handle_translation_unit(&mut self, tu: &TranslationUnit) {
        for consumer in &mut self.consumers {
            consumer.handle_translation_unit_begin(tu);
            for decl in &tu.decls {
                consumer.handle_top_level_decl(decl);
            }
            consumer.handle_translation_unit_end(tu);
        }
    }

    /// Finish all sub-consumers.
    pub fn finish_all(&mut self) {
        for consumer in &mut self.consumers {
            consumer.finish();
        }
    }

    /// Print stats from all sub-consumers.
    pub fn print_all_stats(&self) {
        for consumer in &self.consumers {
            consumer.print_stats();
        }
    }

    /// Get the number of sub-consumers.
    pub fn num_consumers(&self) -> usize {
        self.consumers.len()
    }

    /// Check if the multiplexer has any consumers.
    pub fn is_empty(&self) -> bool {
        self.consumers.is_empty()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VerifyDiagnosticConsumer — check that expected diagnostics are emitted
// ═══════════════════════════════════════════════════════════════════════════════

/// A diagnostic consumer that verifies expected diagnostics are produced.
///
/// Used primarily in testing to assert that the compiler produces
/// specific errors and warnings for given inputs.
#[derive(Debug)]
pub struct VerifyDiagnosticConsumer {
    /// Expected diagnostics to check for.
    pub expected: Vec<ExpectedDiagnostic>,
    /// Actual diagnostics received.
    pub received: Vec<ReceivedDiagnostic>,
    /// Whether the consumer should fail on unexpected diagnostics.
    pub strict: bool,
    /// Additional diagnostics that are expected but optional.
    pub optional: Vec<ExpectedDiagnostic>,
}

/// An expected diagnostic with location and message pattern.
#[derive(Debug, Clone)]
pub struct ExpectedDiagnostic {
    /// The severity level expected.
    pub severity: DiagSeverity,
    /// The file name where the diagnostic is expected.
    pub file: Option<String>,
    /// The line number where the diagnostic is expected (0 = any line).
    pub line: u32,
    /// The column where the diagnostic is expected (0 = any column).
    pub column: u32,
    /// A substring that should appear in the diagnostic message.
    pub message_contains: Option<String>,
    /// The exact expected message.
    pub message_exact: Option<String>,
    /// Whether this diagnostic has been seen.
    pub seen: bool,
}

impl ExpectedDiagnostic {
    /// Create an expected error on a specific line.
    pub fn error_on_line(line: u32, msg: &str) -> Self {
        Self {
            severity: DiagSeverity::Error,
            file: None,
            line,
            column: 0,
            message_contains: Some(msg.to_string()),
            message_exact: None,
            seen: false,
        }
    }

    /// Create an expected warning on a specific line.
    pub fn warning_on_line(line: u32, msg: &str) -> Self {
        Self {
            severity: DiagSeverity::Warning,
            file: None,
            line,
            column: 0,
            message_contains: Some(msg.to_string()),
            message_exact: None,
            seen: false,
        }
    }

    /// Create an expected error with exact message.
    pub fn error_exact(line: u32, msg: &str) -> Self {
        Self {
            severity: DiagSeverity::Error,
            file: None,
            line,
            column: 0,
            message_contains: None,
            message_exact: Some(msg.to_string()),
            seen: false,
        }
    }

    /// Check if this expected diagnostic matches a received one.
    pub fn matches(&self, received: &ReceivedDiagnostic) -> bool {
        if self.severity != received.severity {
            return false;
        }
        if let Some(ref file) = self.file {
            if received.file.as_deref() != Some(file.as_str()) {
                return false;
            }
        }
        if self.line != 0 && self.line != received.line {
            return false;
        }
        if self.column != 0 && self.column != received.column {
            return false;
        }
        if let Some(ref contains) = self.message_contains {
            if !received.message.contains(contains.as_str()) {
                return false;
            }
        }
        if let Some(ref exact) = self.message_exact {
            if received.message != *exact {
                return false;
            }
        }
        true
    }
}

/// A diagnostic that was actually received.
#[derive(Debug, Clone)]
pub struct ReceivedDiagnostic {
    /// The severity of the diagnostic.
    pub severity: DiagSeverity,
    /// The file where the diagnostic occurred.
    pub file: Option<String>,
    /// The line number.
    pub line: u32,
    /// The column.
    pub column: u32,
    /// The diagnostic message.
    pub message: String,
    /// The diagnostic ID.
    pub diag_id: DiagID,
    /// Fix-it hints if any.
    pub fixits: Vec<String>,
}

impl VerifyDiagnosticConsumer {
    /// Create a new verify diagnostic consumer.
    pub fn new(expected: Vec<ExpectedDiagnostic>) -> Self {
        Self {
            expected,
            received: Vec::new(),
            strict: true,
            optional: Vec::new(),
        }
    }

    /// Create a lenient consumer that allows unexpected diagnostics.
    pub fn lenient(expected: Vec<ExpectedDiagnostic>) -> Self {
        Self {
            expected,
            received: Vec::new(),
            strict: false,
            optional: Vec::new(),
        }
    }

    /// Add an optional expected diagnostic.
    pub fn add_optional(&mut self, diag: ExpectedDiagnostic) {
        self.optional.push(diag);
    }

    /// Record a received diagnostic.
    pub fn record(
        &mut self,
        severity: DiagSeverity,
        file: Option<&str>,
        line: u32,
        column: u32,
        message: &str,
        diag_id: DiagID,
    ) {
        let received = ReceivedDiagnostic {
            severity,
            file: file.map(|s| s.to_string()),
            line,
            column,
            message: message.to_string(),
            diag_id,
            fixits: Vec::new(),
        };
        self.received.push(received);
    }

    /// Verify that all expected diagnostics were seen.
    /// Returns a list of missing diagnostics.
    pub fn verify(&self) -> Vec<ExpectedDiagnostic> {
        let mut missing = Vec::new();

        for expected in &self.expected {
            let found = self
                .received
                .iter()
                .any(|received| expected.matches(received));
            if !found {
                missing.push(expected.clone());
            }
        }

        missing
    }

    /// Verify and check for unexpected diagnostics (strict mode).
    /// Returns (missing, unexpected) diagnostics.
    pub fn verify_strict(&self) -> (Vec<ExpectedDiagnostic>, Vec<ReceivedDiagnostic>) {
        let missing = self.verify();

        let mut unexpected = Vec::new();
        for received in &self.received {
            let is_expected = self
                .expected
                .iter()
                .any(|expected| expected.matches(received));
            let is_optional = self.optional.iter().any(|opt| opt.matches(received));
            if !is_expected && !is_optional {
                unexpected.push(received.clone());
            }
        }

        (missing, unexpected)
    }

    /// Check if all expected diagnostics were seen (returns true if all matched).
    pub fn all_seen(&self) -> bool {
        self.verify().is_empty()
    }

    /// Get the count of received diagnostics.
    pub fn count_received(&self) -> usize {
        self.received.len()
    }

    /// Get the count of expected diagnostics.
    pub fn count_expected(&self) -> usize {
        self.expected.len()
    }

    /// Clear all received diagnostics.
    pub fn clear(&mut self) {
        self.received.clear();
    }

    /// Format the verification results as a human-readable string.
    pub fn format_results(&self) -> String {
        let mut out = String::new();
        let (missing, unexpected) = self.verify_strict();

        if missing.is_empty() && unexpected.is_empty() {
            out.push_str("All expected diagnostics received.\n");
        } else {
            if !missing.is_empty() {
                out.push_str(&format!(
                    "Missing {} expected diagnostics:\n",
                    missing.len()
                ));
                for m in &missing {
                    out.push_str(&format!(
                        "  - {:?} at line {}, contains: {:?}\n",
                        m.severity, m.line, m.message_contains
                    ));
                }
            }
            if self.strict && !unexpected.is_empty() {
                out.push_str(&format!("Unexpected {} diagnostics:\n", unexpected.len()));
                for u in &unexpected {
                    out.push_str(&format!(
                        "  - {:?} at {}:{}: {}\n",
                        u.severity,
                        u.file.as_deref().unwrap_or("<unknown>"),
                        u.line,
                        u.message
                    ));
                }
            }
        }
        out
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CompilationPhase — tracking individual compilation phases
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a single phase of compilation with timing and error tracking.
#[derive(Debug, Clone)]
pub enum CompilationPhase {
    /// Lexing phase.
    Lexing,
    /// Preprocessing phase.
    Preprocessing,
    /// Parsing phase.
    Parsing,
    /// Semantic analysis phase.
    SemanticAnalysis,
    /// Code generation phase.
    CodeGeneration,
    /// Optimization phase.
    Optimization,
    /// Emission phase (object code, assembly, bitcode).
    Emission,
    /// Linking phase.
    Linking,
}

impl CompilationPhase {
    /// Get the name of this phase.
    pub fn name(&self) -> &'static str {
        match self {
            CompilationPhase::Lexing => "lexing",
            CompilationPhase::Preprocessing => "preprocessing",
            CompilationPhase::Parsing => "parsing",
            CompilationPhase::SemanticAnalysis => "semantic analysis",
            CompilationPhase::CodeGeneration => "code generation",
            CompilationPhase::Optimization => "optimization",
            CompilationPhase::Emission => "emission",
            CompilationPhase::Linking => "linking",
        }
    }

    /// Whether this phase must run for syntax-only mode.
    pub fn required_for_syntax_only(&self) -> bool {
        matches!(
            self,
            CompilationPhase::Lexing
                | CompilationPhase::Preprocessing
                | CompilationPhase::Parsing
                | CompilationPhase::SemanticAnalysis
        )
    }

    /// Whether this phase can be skipped with -fsyntax-only.
    pub fn can_skip(&self) -> bool {
        matches!(
            self,
            CompilationPhase::CodeGeneration
                | CompilationPhase::Optimization
                | CompilationPhase::Emission
                | CompilationPhase::Linking
        )
    }
}

/// Error tracker for a compilation pipeline.
#[derive(Debug, Clone)]
pub struct ErrorTracker {
    /// Error messages collected.
    pub errors: Vec<String>,
    /// Warning messages collected.
    pub warnings: Vec<String>,
    /// Notes collected.
    pub notes: Vec<String>,
    /// Maximum errors before aborting.
    pub error_limit: usize,
    /// Maximum warnings before suppressing.
    pub warning_limit: usize,
    /// Whether errors have reached the limit.
    pub limit_reached: bool,
}

impl ErrorTracker {
    /// Create a new error tracker.
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
            notes: Vec::new(),
            error_limit: 20,
            warning_limit: 100,
            limit_reached: false,
        }
    }

    /// Record an error.
    pub fn error(&mut self, msg: &str) {
        if self.limit_reached {
            return;
        }
        self.errors.push(msg.to_string());
        if self.errors.len() >= self.error_limit {
            self.limit_reached = true;
        }
    }

    /// Record a warning.
    pub fn warning(&mut self, msg: &str) {
        self.warnings.push(msg.to_string());
    }

    /// Record a note.
    pub fn note(&mut self, msg: &str) {
        self.notes.push(msg.to_string());
    }

    /// Check if any errors have been recorded.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Get the error count.
    pub fn error_count(&self) -> usize {
        self.errors.len()
    }

    /// Get the warning count.
    pub fn warning_count(&self) -> usize {
        self.warnings.len()
    }

    /// Clear all tracked diagnostics.
    pub fn clear(&mut self) {
        self.errors.clear();
        self.warnings.clear();
        self.notes.clear();
        self.limit_reached = false;
    }

    /// Merge diagnostics from another tracker.
    pub fn merge(&mut self, other: &ErrorTracker) {
        for e in &other.errors {
            self.error(e);
        }
        for w in &other.warnings {
            self.warning(w);
        }
        for n in &other.notes {
            self.note(n);
        }
    }
}

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

/// Phase timer for measuring compilation performance.
#[derive(Debug, Clone)]
pub struct PhaseTimer {
    /// Start time for the current phase.
    start_time: Option<std::time::Instant>,
    /// Accumulated time per phase.
    pub phase_times: Vec<(CompilationPhase, std::time::Duration)>,
}

impl PhaseTimer {
    /// Create a new phase timer.
    pub fn new() -> Self {
        Self {
            start_time: None,
            phase_times: Vec::new(),
        }
    }

    /// Start timing a new phase.
    pub fn start_phase(&mut self, _phase: CompilationPhase) {
        self.start_time = Some(std::time::Instant::now());
    }

    /// End the current phase and record its duration.
    pub fn end_phase(&mut self, phase: CompilationPhase) {
        if let Some(start) = self.start_time {
            let elapsed = start.elapsed();
            self.phase_times.push((phase, elapsed));
        }
        self.start_time = None;
    }

    /// Get the total elapsed time across all phases.
    pub fn total_time(&self) -> std::time::Duration {
        self.phase_times.iter().map(|(_, d)| *d).sum()
    }

    /// Format the phase times as a human-readable string.
    pub fn format(&self) -> String {
        let mut out = String::new();
        out.push_str("=== Phase Timings ===\n");
        for (phase, duration) in &self.phase_times {
            out.push_str(&format!(
                "  {:20}: {:>8.2} ms\n",
                phase.name(),
                duration.as_secs_f64() * 1000.0
            ));
        }
        out.push_str(&format!(
            "  {:20}: {:>8.2} ms\n",
            "TOTAL",
            self.total_time().as_secs_f64() * 1000.0
        ));
        out
    }
}

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

/// Compilation unit information.
#[derive(Debug, Clone)]
pub struct CompilationUnitInfo {
    /// The source file path.
    pub source_file: PathBuf,
    /// The language standard.
    pub standard: CLangStandard,
    /// Whether this is a C++ compilation unit.
    pub is_cxx: bool,
    /// The target triple.
    pub target_triple: String,
    /// Optimization level.
    pub opt_level: OptLevel,
    /// Module name.
    pub module_name: String,
    /// Source hash for caching.
    pub source_hash: Option<u64>,
}

impl CompilationUnitInfo {
    /// Create new compilation unit info.
    pub fn new(source: &Path, standard: CLangStandard, triple: &str) -> Self {
        let module_name = source
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("input")
            .to_string();

        Self {
            source_file: source.to_path_buf(),
            standard,
            is_cxx: false,
            target_triple: triple.to_string(),
            opt_level: OptLevel::O0,
            module_name,
            source_hash: None,
        }
    }

    /// Set optimization level.
    pub fn with_opt_level(mut self, level: OptLevel) -> Self {
        self.opt_level = level;
        self
    }

    /// Set as C++ compilation unit.
    pub fn with_cxx(mut self, cxx: bool) -> Self {
        self.is_cxx = cxx;
        self
    }

    /// Compute and set source hash.
    pub fn compute_hash(&mut self, source: &str) {
        // Simple hash using byte accumulation.
        let mut hash: u64 = 5381;
        for b in source.bytes() {
            hash = hash.wrapping_mul(33).wrapping_add(b as u64);
        }
        self.source_hash = Some(hash);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Pipeline result — unified compilation result type
// ═══════════════════════════════════════════════════════════════════════════════

/// Unified result of running a compilation pipeline.
#[derive(Debug)]
pub struct PipelineResult {
    /// Whether the pipeline completed successfully.
    pub success: bool,
    /// The output format produced.
    pub output_format: OutputFormat,
    /// The text output (assembly, IR, preprocessed).
    pub text_output: Option<String>,
    /// The binary output (object, bitcode, executable).
    pub binary_output: Option<Vec<u8>>,
    /// The produced module (if any).
    pub module: Option<Module>,
    /// Error tracker with diagnostics.
    pub error_tracker: ErrorTracker,
    /// Phase timer with performance data.
    pub phase_timer: PhaseTimer,
    /// The output file path.
    pub output_file: Option<PathBuf>,
}

impl PipelineResult {
    /// Create a successful result.
    pub fn success(format: OutputFormat) -> Self {
        Self {
            success: true,
            output_format: format,
            text_output: None,
            binary_output: None,
            module: None,
            error_tracker: ErrorTracker::new(),
            phase_timer: PhaseTimer::new(),
            output_file: None,
        }
    }

    /// Create a failed result.
    pub fn failure(format: OutputFormat, errors: Vec<String>) -> Self {
        let mut tracker = ErrorTracker::new();
        for e in &errors {
            tracker.error(e);
        }
        Self {
            success: false,
            output_format: format,
            text_output: None,
            binary_output: None,
            module: None,
            error_tracker: tracker,
            phase_timer: PhaseTimer::new(),
            output_file: None,
        }
    }

    /// Set the text output.
    pub fn with_text(mut self, text: String) -> Self {
        self.text_output = Some(text);
        self
    }

    /// Set the binary output.
    pub fn with_binary(mut self, bytes: Vec<u8>) -> Self {
        self.binary_output = Some(bytes);
        self
    }

    /// Set the module.
    pub fn with_module(mut self, module: Module) -> Self {
        self.module = Some(module);
        self
    }

    /// Set the output file.
    pub fn with_output_file(mut self, path: PathBuf) -> Self {
        self.output_file = Some(path);
        self
    }

    /// Check if there are errors.
    pub fn has_errors(&self) -> bool {
        self.error_tracker.has_errors()
    }

    /// Get the error count.
    pub fn error_count(&self) -> usize {
        self.error_tracker.error_count()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TargetMachineStub — stub for LLVM's TargetMachine
// ═══════════════════════════════════════════════════════════════════════════════

/// Stub representing an LLVM TargetMachine for code emission.
#[derive(Debug, Clone)]
pub struct TargetMachineStub {
    /// The target triple.
    pub triple: String,
    /// The target CPU name.
    pub cpu: String,
    /// Target features string.
    pub features: String,
    /// Optimization level.
    pub opt_level: OptLevel,
    /// Code model.
    pub code_model: CodeModel,
    /// Relocation model.
    pub reloc_model: RelocModel,
    /// Whether to emit debug information.
    pub debug_info: bool,
}

/// Code model for target machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeModel {
    Default,
    Small,
    Kernel,
    Medium,
    Large,
}

/// Relocation model for target machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelocModel {
    Default,
    Static,
    PIC,
    DynamicNoPic,
    ROPI,
    RWPI,
    ROPI_RWPI,
}

impl TargetMachineStub {
    /// Create a default target machine for the given triple.
    pub fn new(triple: &str) -> Self {
        Self {
            triple: triple.to_string(),
            cpu: "generic".to_string(),
            features: String::new(),
            opt_level: OptLevel::O0,
            code_model: CodeModel::Default,
            reloc_model: RelocModel::Default,
            debug_info: false,
        }
    }

    /// Set CPU name.
    pub fn with_cpu(mut self, cpu: &str) -> Self {
        self.cpu = cpu.to_string();
        self
    }

    /// Set target features.
    pub fn with_features(mut self, features: &str) -> Self {
        self.features = features.to_string();
        self
    }

    /// Set optimization level.
    pub fn with_opt_level(mut self, level: OptLevel) -> Self {
        self.opt_level = level;
        self
    }

    /// Set code model.
    pub fn with_code_model(mut self, model: CodeModel) -> Self {
        self.code_model = model;
        self
    }

    /// Set relocation model.
    pub fn with_reloc_model(mut self, model: RelocModel) -> Self {
        self.reloc_model = model;
        self
    }

    /// Enable debug info.
    pub fn with_debug_info(mut self, debug: bool) -> Self {
        self.debug_info = debug;
        self
    }

    /// Check if this is a PIC target.
    pub fn is_pic(&self) -> bool {
        matches!(
            self.reloc_model,
            RelocModel::PIC | RelocModel::ROPI | RelocModel::ROPI_RWPI
        )
    }

    /// Check if this target supports the given feature.
    pub fn has_feature(&self, feature: &str) -> bool {
        self.features.contains(feature)
    }

    /// Emit object code for the given module.
    pub fn emit_object(&self, _module: &Module) -> Result<Vec<u8>, String> {
        // In a real implementation, this would:
        // 1. Run the instruction selection pass
        // 2. Run register allocation
        // 3. Emit machine code via the MC layer
        //
        // For now, return a placeholder ELF header.
        let mut obj = Vec::new();
        obj.extend_from_slice(&[0x7f, b'E', b'L', b'F']);
        obj.push(2);
        obj.push(1);
        obj.push(1);
        obj.push(0);
        obj.push(0);
        obj.extend_from_slice(&[0; 7]);
        obj.extend_from_slice(&[1, 0]); // ET_REL
        if self.triple.contains("x86_64") {
            obj.extend_from_slice(&[0x3e, 0]);
        } else {
            obj.extend_from_slice(&[0xB7, 0]); // aarch64
        }
        obj.extend_from_slice(&[1, 0, 0, 0]);
        obj.extend_from_slice(&[0; 8 + 8 + 4]);
        obj.extend_from_slice(&[64, 0]);
        obj.extend_from_slice(&[56, 0]);
        obj.extend_from_slice(&[0, 0]);
        obj.extend_from_slice(&[64, 0]);
        obj.extend_from_slice(&[0, 0]);
        obj.extend_from_slice(&[0, 0]);
        Ok(obj)
    }

    /// Emit assembly code for the given module.
    pub fn emit_assembly(&self, _module: &Module) -> Result<String, String> {
        let mut asm = String::new();
        asm.push_str(&format!("\t.arch {}\n", self.triple));
        asm.push_str(&format!("\t.cpu {}\n", self.cpu));
        asm.push_str("\t.text\n");
        Ok(asm)
    }
}

impl Default for TargetMachineStub {
    fn default() -> Self {
        Self::new("x86_64-unknown-linux-gnu")
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ModuleVerifier — verify LLVM module correctness
// ═══════════════════════════════════════════════════════════════════════════════

/// A verifier that checks LLVM module correctness after code generation.
#[derive(Debug, Clone)]
pub struct ModuleVerifier {
    /// Whether to abort on first error.
    pub abort_on_error: bool,
    /// Whether to print verbose output.
    pub verbose: bool,
    /// Collected verification errors.
    pub errors: Vec<String>,
}

impl ModuleVerifier {
    /// Create a new module verifier.
    pub fn new() -> Self {
        Self {
            abort_on_error: false,
            verbose: false,
            errors: Vec::new(),
        }
    }

    /// Verify a module for correctness.
    pub fn verify(&mut self, module: &Module) -> bool {
        self.errors.clear();

        // Check that every function has at least one basic block.
        for func in &module.functions {
            let func = func.borrow();
            if func.blocks.is_empty() {
                self.errors
                    .push(format!("function '{}' has no basic blocks", func.name));
                if self.abort_on_error {
                    return false;
                }
            }

            // Check that each basic block's terminator is valid.
            for bb in &func.blocks {
                let bb = bb.borrow();
                if bb.instructions.is_empty() && !bb.name.is_empty() {
                    if self.verbose {
                        // Empty blocks are okay in some cases.
                    }
                }
                // Verify the block's terminator is last.
                if let Some(last) = bb.instructions.last() {
                    let last = last.borrow();
                    if !self.is_valid_terminator(&last.opcode) {
                        self.errors.push(format!(
                            "block '{}' in function '{}' does not end with a terminator instruction",
                            bb.name, func.name
                        ));
                        if self.abort_on_error {
                            return false;
                        }
                    }
                }
            }
        }

        // Check global initializers.
        for gv in &module.globals {
            let gv = gv.borrow();
            if gv.initializer.is_none() && gv.is_constant {
                self.errors.push(format!(
                    "constant global '{}' must have an initializer",
                    gv.name
                ));
                if self.abort_on_error {
                    return false;
                }
            }
        }

        self.errors.is_empty()
    }

    /// Check if an opcode is a valid terminator instruction.
    fn is_valid_terminator(&self, opcode: &Option<Opcode>) -> bool {
        if let Some(op) = opcode {
            matches!(
                op,
                Opcode::Ret
                    | Opcode::Br
                    | Opcode::Switch
                    | Opcode::IndirectBr
                    | Opcode::Invoke
                    | Opcode::Resume
                    | Opcode::Unreachable
                    | Opcode::CatchRet
                    | Opcode::CatchSwitch
            )
        } else {
            false
        }
    }

    /// Verify a single function.
    pub fn verify_function(&mut self, func: &Function) -> bool {
        self.errors.clear();

        if func.basic_blocks.is_empty() {
            self.errors.push(format!(
                "function '{}' has no body",
                func.value.borrow().name
            ));
            return false;
        }

        // Check that the entry block is first.
        if let Some(entry) = func.basic_blocks.first() {
            if entry.borrow().name != "entry"
                && !func.basic_blocks.iter().any(|b| b.borrow().name == "entry")
            {
                if self.verbose {
                    // Entry block doesn't have to be named "entry".
                }
            }
        }

        true
    }

    /// Get the verification errors.
    pub fn get_errors(&self) -> &[String] {
        &self.errors
    }

    /// Check if the module passed verification.
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// OptimizerConfig — optimization pass configuration
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for running optimization passes on an LLVM module.
#[derive(Debug, Clone)]
pub struct OptimizerConfig {
    /// Optimization level.
    pub opt_level: OptLevel,
    /// Enable inlining.
    pub inline: bool,
    /// Inline threshold.
    pub inline_threshold: u32,
    /// Enable loop unrolling.
    pub loop_unroll: bool,
    /// Enable vectorization.
    pub vectorize: bool,
    /// Enable slp vectorization.
    pub slp_vectorize: bool,
    /// Enable global value numbering.
    pub gvn: bool,
    /// Enable dead code elimination.
    pub dce: bool,
    /// Enable constant propagation.
    pub const_prop: bool,
    /// Enable tail call elimination.
    pub tail_call_elim: bool,
    /// Enable function merging.
    pub merge_functions: bool,
    /// Additional custom passes.
    pub custom_passes: Vec<String>,
}

impl OptimizerConfig {
    /// Create default config for O0.
    pub fn o0() -> Self {
        Self {
            opt_level: OptLevel::O0,
            inline: false,
            inline_threshold: 0,
            loop_unroll: false,
            vectorize: false,
            slp_vectorize: false,
            gvn: false,
            dce: false,
            const_prop: false,
            tail_call_elim: false,
            merge_functions: false,
            custom_passes: Vec::new(),
        }
    }

    /// Create default config for O1.
    pub fn o1() -> Self {
        Self {
            opt_level: OptLevel::O1,
            inline: true,
            inline_threshold: 225,
            loop_unroll: false,
            vectorize: false,
            slp_vectorize: false,
            gvn: true,
            dce: true,
            const_prop: true,
            tail_call_elim: true,
            merge_functions: false,
            custom_passes: Vec::new(),
        }
    }

    /// Create default config for O2.
    pub fn o2() -> Self {
        Self {
            opt_level: OptLevel::O2,
            inline: true,
            inline_threshold: 275,
            loop_unroll: true,
            vectorize: true,
            slp_vectorize: true,
            gvn: true,
            dce: true,
            const_prop: true,
            tail_call_elim: true,
            merge_functions: true,
            custom_passes: Vec::new(),
        }
    }

    /// Create default config for O3.
    pub fn o3() -> Self {
        Self {
            opt_level: OptLevel::O3,
            inline: true,
            inline_threshold: 350,
            loop_unroll: true,
            vectorize: true,
            slp_vectorize: true,
            gvn: true,
            dce: true,
            const_prop: true,
            tail_call_elim: true,
            merge_functions: true,
            custom_passes: Vec::new(),
        }
    }

    /// Create default config for Os (size optimization).
    pub fn os() -> Self {
        Self {
            opt_level: OptLevel::Os,
            inline: true,
            inline_threshold: 75,
            loop_unroll: false,
            vectorize: false,
            slp_vectorize: false,
            gvn: false,
            dce: true,
            const_prop: true,
            tail_call_elim: true,
            merge_functions: true,
            custom_passes: Vec::new(),
        }
    }

    /// Create config from an optimization level.
    pub fn from_opt_level(level: OptLevel) -> Self {
        match level {
            OptLevel::O0 => Self::o0(),
            OptLevel::O1 => Self::o1(),
            OptLevel::O2 => Self::o2(),
            OptLevel::O3 => Self::o3(),
            OptLevel::Os => Self::os(),
            OptLevel::Oz => {
                let mut s = Self::os();
                s.opt_level = OptLevel::Oz;
                s.inline_threshold = 25;
                s
            }
        }
    }

    /// Add a custom pass.
    pub fn add_pass(&mut self, pass_name: &str) {
        self.custom_passes.push(pass_name.to_string());
    }

    /// Check if any optimizations are enabled.
    pub fn is_optimizing(&self) -> bool {
        self.opt_level.is_optimizing()
    }

    /// Get a human-readable description.
    pub fn description(&self) -> String {
        let mut desc = format!("Optimization level: {:?}", self.opt_level);
        if self.inline {
            desc.push_str(&format!(", inline(threshold={})", self.inline_threshold));
        }
        if self.loop_unroll {
            desc.push_str(", loop-unroll");
        }
        if self.vectorize {
            desc.push_str(", vectorize");
        }
        if self.slp_vectorize {
            desc.push_str(", slp-vectorize");
        }
        desc
    }
}

impl Default for OptimizerConfig {
    fn default() -> Self {
        Self::o0()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Emitter — common emission interface for all output formats
// ═══════════════════════════════════════════════════════════════════════════════

/// Common interface for code emission in all output formats.
#[derive(Debug)]
pub struct CodeEmitter {
    /// The target machine configuration.
    pub target_machine: TargetMachineStub,
    /// The optimizer configuration.
    pub optimizer_config: OptimizerConfig,
    /// Whether to verify the module before emission.
    pub verify_module: bool,
    /// Whether to include debug info.
    pub include_debug_info: bool,
    /// Debug info kind.
    pub debug_info_kind: DebugInfoKind,
}

impl CodeEmitter {
    /// Create a new code emitter.
    pub fn new(target: TargetMachineStub, opt: OptimizerConfig) -> Self {
        Self {
            target_machine: target,
            optimizer_config: opt,
            verify_module: true,
            include_debug_info: false,
            debug_info_kind: DebugInfoKind::None,
        }
    }

    /// Emit object code from a module.
    pub fn emit_object(&self, module: &Module) -> Result<Vec<u8>, String> {
        // Verify if requested.
        if self.verify_module {
            let mut verifier = ModuleVerifier::new();
            if !verifier.verify(module) {
                return Err(format!("module verification failed: {:?}", verifier.errors));
            }
        }
        self.target_machine.emit_object(module)
    }

    /// Emit assembly code from a module.
    pub fn emit_assembly(&self, module: &Module) -> Result<String, String> {
        self.target_machine.emit_assembly(module)
    }

    /// Check if debug info should be emitted.
    pub fn should_emit_debug_info(&self) -> bool {
        self.include_debug_info && self.debug_info_kind != DebugInfoKind::None
    }
}

/// Default implementation for convenience.
impl Default for CodeEmitter {
    fn default() -> Self {
        Self::new(TargetMachineStub::default(), OptimizerConfig::default())
    }
}

/// A convenience type alias for the full compilation pipeline function type.
pub type CompilationPipelineFn = fn(source: &str, triple: &str) -> Result<Vec<u8>, Vec<String>>;

/// A convenience type for the IR generation pipeline function type.
pub type IRPipelineFn = fn(source: &str, triple: &str) -> Result<String, Vec<String>>;

/// Pipeline registry for dynamic dispatch of compilation strategies.
#[derive(Debug, Clone)]
pub struct PipelineRegistry {
    pub default_pipeline: String,
    pub pipelines: std::collections::HashMap<String, CompilationPipelineFn>,
}

impl PipelineRegistry {
    pub fn new() -> Self {
        let mut registry = Self {
            default_pipeline: "standard".to_string(),
            pipelines: std::collections::HashMap::new(),
        };
        registry.pipelines.insert(
            "standard".to_string(),
            compile_to_object as CompilationPipelineFn,
        );
        registry
    }

    pub fn register(&mut self, name: &str, pipeline: CompilationPipelineFn) {
        self.pipelines.insert(name.to_string(), pipeline);
    }

    pub fn run(&self, source: &str, triple: &str) -> Result<Vec<u8>, Vec<String>> {
        let pipeline = self
            .pipelines
            .get(&self.default_pipeline)
            .or_else(|| self.pipelines.values().next())
            .ok_or_else(|| vec!["no pipeline registered".to_string()])?;
        pipeline(source, triple)
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Pipeline convenience functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Compile a C source string to object bytes through the full pipeline.
///
/// This is a convenience function that creates a CompilerInstance, runs
/// lex→parse→sema→codegen, and returns the resulting object bytes.
pub fn compile_to_object(source: &str, triple: &str) -> Result<Vec<u8>, Vec<String>> {
    let opts = CompilerOptions {
        target_triple: triple.to_string(),
        action: FrontendActionKind::EmitObj,
        ..CompilerOptions::default()
    };

    let inv = CompilerInvocation {
        opts,
        args: vec!["clang".to_string()],
        program_name: "clang".to_string(),
    };

    let mut compiler = CompilerInstance::new(inv);
    let _fid = compiler
        .source_manager
        .load_virtual_file("<input>", source.to_string())
        .map_err(|e| vec![e])?;

    let tokens = lexer::tokenize(source, compiler.opts.standard);
    let mut parser = parser::Parser::new(&tokens, compiler.opts.standard);
    let tu = parser.parse().map_err(|e| {
        e.into_iter()
            .map(|err| format!("parse: {}", err))
            .collect::<Vec<_>>()
    })?;

    let mut sema = Sema::new(compiler.opts.standard);
    sema.analyze(&tu).map_err(|e| {
        e.iter()
            .map(|err| format!("sema: {}", err))
            .collect::<Vec<_>>()
    })?;
    if sema.has_errors() {
        return Err(sema.errors.clone());
    }

    let mut cg = ClangCodeGen::new("input", triple);
    cg.compile(&tu).map_err(|e| {
        e.iter()
            .map(|err| format!("codegen: {}", err))
            .collect::<Vec<_>>()
    })?;

    // In a real implementation, this would go through the TargetMachine
    // to emit object bytes.  For now, return empty bytes.
    Ok(Vec::new())
}

/// Compile C source to LLVM IR text.
pub fn compile_to_ir(source: &str, triple: &str) -> Result<String, Vec<String>> {
    let opts = CompilerOptions {
        target_triple: triple.to_string(),
        emit_llvm: true,
        ..CompilerOptions::default()
    };
    let inv = CompilerInvocation {
        opts,
        args: vec!["clang".to_string()],
        program_name: "clang".to_string(),
    };
    let mut compiler = CompilerInstance::new(inv);
    let _fid = compiler
        .source_manager
        .load_virtual_file("<input>", source.to_string())
        .map_err(|e| vec![e])?;

    let tokens = lexer::tokenize(source, compiler.opts.standard);
    let mut parser = parser::Parser::new(&tokens, compiler.opts.standard);
    let tu = parser.parse().map_err(|e| {
        e.into_iter()
            .map(|err| format!("parse: {}", err))
            .collect::<Vec<_>>()
    })?;

    let mut sema = Sema::new(compiler.opts.standard);
    sema.analyze(&tu).map_err(|e| {
        e.iter()
            .map(|err| format!("sema: {}", err))
            .collect::<Vec<_>>()
    })?;

    let mut cg = ClangCodeGen::new("input", triple);
    cg.compile(&tu).map_err(|e| {
        e.iter()
            .map(|err| format!("codegen: {}", err))
            .collect::<Vec<_>>()
    })?;

    // Get the module as IR text.
    // In a real impl this would serialize to .ll format.
    let ir = String::new();
    let _ = cg.module;
    Ok(ir)
}

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

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

    // ── CompilerOptions ──────────────────────────────────────────────────

    #[test]
    fn test_compiler_options_default() {
        let opts = CompilerOptions::default();
        assert_eq!(opts.standard, CLangStandard::C17);
        assert_eq!(opts.target_triple, "x86_64-unknown-linux-gnu");
        assert_eq!(opts.opt_level, OptLevel::O0);
    }

    #[test]
    fn test_compiler_options_from_clang_options() {
        let co = ClangOptions {
            standard: CLangStandard::C11,
            optimize: true,
            debug_info: true,
            warnings: true,
            pedantic: true,
            wall: true,
            werror: true,
            verbose: false,
            includes: vec!["/usr/include".to_string()],
            defines: vec![("FOO".to_string(), Some("bar".to_string()))],
            output_file: Some("out.o".to_string()),
            target_triple: "aarch64-unknown-linux-gnu".to_string(),
        };
        let opts = CompilerOptions::from_clang_options(&co);
        assert_eq!(opts.standard, CLangStandard::C11);
        assert_eq!(opts.opt_level, OptLevel::O2);
        assert!(opts.debug_info);
        assert!(opts.wall);
        assert!(opts.pedantic);
        assert!(opts.werror);
        assert_eq!(opts.includes.len(), 1);
        assert!(opts.output_file.is_some());
    }

    // ── FileManager ──────────────────────────────────────────────────────

    #[test]
    fn test_file_manager_virtual_file() {
        let mut fm = FileManager::new();
        let fid = fm.get_virtual_file("test.c", "int x;".to_string()).unwrap();
        assert!(fid.0 > 0);
        let entry = fm.get_file_by_id(fid).unwrap();
        assert_eq!(entry.name, "test.c");
        assert!(entry.is_virtual);
    }

    #[test]
    fn test_file_manager_overlay() {
        let mut fm = FileManager::new();
        fm.add_overlay("builtin.h".to_string(), "#define NULL 0".to_string());
        let fid = fm.get_file(Path::new("builtin.h")).unwrap();
        let entry = fm.get_file_by_id(fid).unwrap();
        assert!(entry.is_virtual);
    }

    #[test]
    fn test_file_manager_include_search() {
        // This test checks include path searching with a virtual overlay.
        let mut fm = FileManager::new();
        fm.add_include_path(PathBuf::from("/include"));
        fm.add_overlay(
            "/include/header.h".to_string(),
            "int answer = 42;".to_string(),
        );
        let result = fm.find_include("header.h", None);
        assert!(result.is_some());
    }

    // ── SourceManager ────────────────────────────────────────────────────

    #[test]
    fn test_source_manager_virtual_file() {
        let fm = FileManager::new();
        let mut sm = SourceManager::new(fm);
        let fid = sm
            .load_virtual_file("test.c", "int x;\nint y;\nint z;\n".to_string())
            .unwrap();
        let loc1 = sm.get_location(fid, 0);
        assert_eq!(loc1.line, 1);
        assert_eq!(loc1.column, 1);

        let loc2 = sm.get_location(fid, 7); // after "int x;\n" (7 bytes incl newline)
        assert_eq!(loc2.line, 2);
    }

    #[test]
    fn test_source_manager_get_line() {
        let fm = FileManager::new();
        let mut sm = SourceManager::new(fm);
        let fid = sm
            .load_virtual_file("test.c", "line one\nline two\n".to_string())
            .unwrap();
        let loc1 = sm.get_location(fid, 0);
        let line1 = sm.get_line(loc1).unwrap();
        assert_eq!(line1, "line one");

        let loc2 = sm.get_location(fid, 9); // after "line one\n"
        let line2 = sm.get_line(loc2).unwrap();
        assert_eq!(line2, "line two");
    }

    #[test]
    fn test_source_manager_invalid_location() {
        let fm = FileManager::new();
        let sm = SourceManager::new(fm);
        let loc = SourceLocation::invalid();
        assert!(!loc.is_valid());
        assert_eq!(loc.to_display(&sm), "<invalid loc>");
    }

    // ── CompilerInvocation ───────────────────────────────────────────────

    #[test]
    fn test_compiler_invocation_default() {
        let inv = CompilerInvocation::default();
        assert_eq!(inv.opts.standard, CLangStandard::C17);
    }

    #[test]
    fn test_compiler_invocation_parse_std() {
        let inv = CompilerInvocation::from_args(["clang", "-std=c11", "-c", "file.c"]);
        assert_eq!(inv.opts.standard, CLangStandard::C11);
        assert!(inv.opts.input_files.len() >= 1);
    }

    #[test]
    fn test_compiler_invocation_parse_optimization() {
        let inv = CompilerInvocation::from_args(["clang", "-O2", "-g", "file.c"]);
        assert_eq!(inv.opts.opt_level, OptLevel::O2);
        assert!(inv.opts.debug_info);
    }

    #[test]
    fn test_compiler_invocation_parse_emit_llvm() {
        let inv = CompilerInvocation::from_args(["clang", "-emit-llvm", "file.c"]);
        assert!(inv.opts.emit_llvm);
    }

    #[test]
    fn test_compiler_invocation_parse_includes() {
        let inv = CompilerInvocation::from_args([
            "clang",
            "-I/usr/include",
            "-I",
            "/usr/local/include",
            "file.c",
        ]);
        assert!(inv.opts.includes.len() >= 1);
    }

    #[test]
    fn test_compiler_invocation_parse_defines() {
        let inv = CompilerInvocation::from_args(["clang", "-DFOO", "-DBAR=baz", "file.c"]);
        assert!(inv.opts.defines.iter().any(|(n, _)| n == "FOO"));
        assert!(inv.opts.defines.iter().any(|(n, _)| n == "BAR"));
    }

    // ── CompilerInstance ─────────────────────────────────────────────────

    #[test]
    fn test_compiler_instance_create_default() {
        let ci = CompilerInstance::create_default();
        assert_eq!(ci.target_triple(), "x86_64-unknown-linux-gnu");
    }

    // ── Full pipeline test ───────────────────────────────────────────────

    #[test]
    fn test_full_pipeline_minimal() {
        let source = "int main(void) { return 0; }";
        let result = compile_to_object(source, "x86_64-unknown-linux-gnu");
        // Should succeed (even if object bytes are empty placeholder).
        assert!(result.is_ok());
    }

    #[test]
    fn test_full_pipeline_with_function() {
        let source = "int add(int a, int b) { return a + b; }";
        let result = compile_to_ir(source, "x86_64-unknown-linux-gnu");
        // Should succeed and produce some IR text.
        assert!(result.is_ok());
    }

    #[test]
    fn test_compiler_invocation_output_file() {
        let inv = CompilerInvocation::from_args(["clang", "-c", "hello.c", "-o", "hello.o"]);
        let out = inv.output_file();
        assert_eq!(out, PathBuf::from("hello.o"));
    }

    #[test]
    fn test_compiler_invocation_output_file_stem() {
        let inv = CompilerInvocation::from_args(["clang", "-S", "hello.c"]);
        let out = inv.output_file();
        assert_eq!(out, PathBuf::from("hello.s"));
    }

    // ── FrontendAction ───────────────────────────────────────────────────

    #[test]
    fn test_frontend_action_for_kind_preprocess() {
        let action = FrontendAction::for_kind(FrontendActionKind::PreprocessOnly);
        match action {
            FrontendAction::PreprocessOnly(_) => {}
            _ => panic!("expected PreprocessOnly"),
        }
    }

    #[test]
    fn test_frontend_action_for_kind_syntax_only() {
        let action = FrontendAction::for_kind(FrontendActionKind::SyntaxOnly);
        match action {
            FrontendAction::SyntaxOnly(_) => {}
            _ => panic!("expected SyntaxOnly"),
        }
    }

    #[test]
    fn test_frontend_action_for_kind_emit_obj() {
        let action = FrontendAction::for_kind(FrontendActionKind::EmitObj);
        match action {
            FrontendAction::EmitObj(_) => {}
            _ => panic!("expected EmitObj"),
        }
    }

    // ── CompilationDriver ────────────────────────────────────────────────

    #[test]
    fn test_compilation_driver_from_args() {
        let mut driver = CompilationDriver::from_args(["clang", "-std=c11", "-fsyntax-only", "-c"]);
        // Since we have no input files, we can't actually run full pipeline.
        // Just verify it was constructed.
        assert_eq!(driver.compiler.opts.standard, CLangStandard::C11);
    }

    // ── OptLevel ─────────────────────────────────────────────────────────

    #[test]
    fn test_opt_level_from_str() {
        assert_eq!(OptLevel::from_str("0"), Some(OptLevel::O0));
        assert_eq!(OptLevel::from_str("2"), Some(OptLevel::O2));
        assert_eq!(OptLevel::from_str("s"), Some(OptLevel::Os));
        assert_eq!(OptLevel::from_str("invalid"), None);
    }

    #[test]
    fn test_opt_level_is_optimizing() {
        assert!(!OptLevel::O0.is_optimizing());
        assert!(OptLevel::O2.is_optimizing());
        assert!(OptLevel::Os.is_optimizing());
    }

    // ── InputLanguage ────────────────────────────────────────────────────

    #[test]
    fn test_input_language_from_str() {
        assert_eq!(InputLanguage::from_str("c"), Some(InputLanguage::C));
        assert_eq!(InputLanguage::from_str("c++"), Some(InputLanguage::CXX));
        assert!(InputLanguage::from_str("fortran").is_none());
    }

    // ── MultiplexConsumer ────────────────────────────────────────────────

    #[test]
    fn test_multiplex_consumer_basic() {
        let mut mc = MultiplexConsumer::new(vec![
            Box::new(SyntaxOnlyConsumer),
            Box::new(ASTDumpConsumer),
        ]);
        mc.consumers.clear(); // verify we can access consumers
    }

    // ── AST consumers ────────────────────────────────────────────────────

    #[test]
    fn test_syntax_only_consumer() {
        let mut c = SyntaxOnlyConsumer;
        c.handle_top_level_decl(&Decl::VarDecl {
            name: "x".to_string(),
            ty: QualType::int(),
            init: None,
        });
        // No panic = success.
    }
}