buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
// ===============================================================================
// BUILDLANG CODE GENERATOR - MID-LEVEL IR
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Mid-level Intermediate Representation (MIR).
//!
//! MIR is a control-flow graph based representation that sits between the AST
//! and target-specific code generation. It uses SSA (Static Single Assignment)
//! form for easier optimization and analysis.
//!
//! ## Design
//!
//! - Functions are represented as control-flow graphs
//! - Each basic block contains a sequence of statements and a terminator
//! - Values are in SSA form (each value assigned exactly once)
//! - Types are explicit and fully resolved

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use crate::lexer::Span;

// ============================================================================
// SERIALIZATION: VERSIONED INTERLINGUA ENVELOPE
// ============================================================================

/// Schema string identifying the MIR interlingua wire format.
///
/// This is the durable, versioned contract for serialized MIR. Bump the
/// `/vN` suffix on any breaking change to the on-the-wire shape so consumers
/// can reject or migrate incompatible payloads.
pub const MIR_SCHEMA: &str = "buildlang.mir/v1";
const MIR_SCHEMA_V0: &str = "buildlang.mir/v0";

/// A versioned envelope wrapping a [`MirModule`] for serialization.
///
/// The envelope is the canonical interchange form of MIR: it carries the
/// [`MIR_SCHEMA`] tag alongside the module so that a deserializer can verify
/// it is reading a format it understands before reconstructing the graph.
///
/// Round-trip is lossless: `from_json(to_json(m)) == m` for any module
/// (floats, including non-finite and `-0.0`, are preserved bit-exact).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirModuleEnvelope {
    /// Format tag; always [`MIR_SCHEMA`] when produced by this compiler.
    pub schema: String,
    /// The wrapped MIR module.
    pub module: MirModule,
}

impl MirModuleEnvelope {
    /// Wrap a borrowed module in a versioned envelope (clones the module).
    pub fn wrap(module: &MirModule) -> Self {
        Self {
            schema: MIR_SCHEMA.to_string(),
            module: module.clone(),
        }
    }

    /// Wrap an owned module in a versioned envelope.
    pub fn new(module: MirModule) -> Self {
        Self {
            schema: MIR_SCHEMA.to_string(),
            module,
        }
    }

    /// Serialize this envelope to pretty-printed JSON.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Serialize this envelope to compact JSON.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Deserialize an envelope from JSON, accepting the previous v0 wire shape
    /// and normalizing it to the current schema tag.
    pub fn from_json(json: &str) -> Result<Self, String> {
        let mut envelope: Self = serde_json::from_str(json).map_err(|err| err.to_string())?;
        if envelope.schema == MIR_SCHEMA_V0 {
            envelope.schema = MIR_SCHEMA.to_string();
            return Ok(envelope);
        }
        if envelope.schema != MIR_SCHEMA {
            return Err(format!(
                "unsupported MIR schema '{}', expected '{}' or '{}'",
                envelope.schema, MIR_SCHEMA, MIR_SCHEMA_V0
            ));
        }
        Ok(envelope)
    }
}

/// Lossless `f64` serde: store the raw IEEE-754 bit pattern as a `u64`.
///
/// The implementation lives in [`crate::serde_float`], the single source of
/// truth shared with the Build Data Format (`buildlang.bdf/v0`), so a float
/// embedded in either the MIR or BDF wire form encodes identically. Encoding
/// the bit pattern guarantees every `f64` (including `NaN` payloads, `±∞`,
/// `-0.0`, and subnormals) round-trips bit-exact.
use crate::serde_float as lossless_f64;

// ============================================================================
// MODULE STRUCTURE
// ============================================================================

/// Vtable definition for trait object dynamic dispatch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirVtable {
    /// Trait name.
    pub trait_name: Arc<str>,
    /// Concrete type name.
    pub type_name: Arc<str>,
    /// Method entries: (method_name, mangled_function_name, fn_sig with void* self).
    pub methods: Vec<(Arc<str>, Arc<str>, MirFnSig)>,
}

/// A MIR module (compilation unit).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirModule {
    /// Module name.
    pub name: Arc<str>,
    /// Functions.
    pub functions: Vec<MirFunction>,
    /// Global variables.
    pub globals: Vec<MirGlobal>,
    /// Type definitions.
    pub types: Vec<MirTypeDef>,
    /// String literals.
    pub strings: Vec<Arc<str>>,
    /// External declarations.
    pub externals: Vec<MirExternal>,
    /// Vtable definitions for dynamic dispatch.
    pub vtables: Vec<MirVtable>,
    /// Trait method signatures: trait_name → [(method_name, fn_sig)].
    pub trait_methods: HashMap<Arc<str>, Vec<(Arc<str>, MirFnSig)>>,
    /// Shader uniform declarations (#[uniform] on module-level constants).
    pub uniforms: Vec<MirUniform>,
    /// Structs marked `#[repr(C)]`. The C export header defines these and
    /// forward-declares any other struct an export reaches through a pointer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub repr_c: Vec<Arc<str>>,
}

/// A shader uniform declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirUniform {
    /// Uniform name.
    pub name: Arc<str>,
    /// Uniform type.
    pub ty: MirType,
    /// Default value.
    pub default: Option<MirConst>,
}

impl MirModule {
    /// Create a new MIR module.
    pub fn new(name: impl Into<Arc<str>>) -> Self {
        Self {
            name: name.into(),
            functions: Vec::new(),
            globals: Vec::new(),
            types: Vec::new(),
            strings: Vec::new(),
            externals: Vec::new(),
            vtables: Vec::new(),
            trait_methods: HashMap::new(),
            uniforms: Vec::new(),
            repr_c: Vec::new(),
        }
    }

    /// Add a function.
    pub fn add_function(&mut self, func: MirFunction) {
        self.functions.push(func);
    }

    /// Add a global variable.
    pub fn add_global(&mut self, global: MirGlobal) {
        self.globals.push(global);
    }

    /// Find a global variable by name.
    pub fn find_global(&self, name: &str) -> Option<&MirGlobal> {
        self.globals.iter().find(|g| g.name.as_ref() == name)
    }

    /// Add a type definition.
    pub fn add_type(&mut self, ty: MirTypeDef) {
        self.types.push(ty);
    }

    /// Intern a string literal and return its index.
    pub fn intern_string(&mut self, s: impl Into<Arc<str>>) -> u32 {
        let s = s.into();
        if let Some(idx) = self.strings.iter().position(|x| x.as_ref() == s.as_ref()) {
            idx as u32
        } else {
            let idx = self.strings.len() as u32;
            self.strings.push(s);
            idx
        }
    }

    /// Find a function by name.
    pub fn find_function(&self, name: &str) -> Option<&MirFunction> {
        self.functions.iter().find(|f| f.name.as_ref() == name)
    }
}

// ============================================================================
// FUNCTIONS
// ============================================================================

/// GPU shader stage for graphics pipeline functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ShaderStage {
    /// Vertex shader stage.
    Vertex,
    /// Fragment (pixel) shader stage.
    Fragment,
    /// Compute shader stage.
    Compute,
}

/// Descriptor binding kind for shader resources.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BindingKind {
    /// Uniform buffer (constant data from CPU).
    UniformBuffer(Arc<str>),
    /// 2D texture (sampled image).
    Texture2D,
    /// Sampler (texture filtering/addressing).
    Sampler,
    /// Storage buffer (read/write from GPU).
    StorageBuffer(Arc<str>),
}

/// A shader resource binding (descriptor set + binding index).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShaderBinding {
    /// Descriptor set index.
    pub set: u32,
    /// Binding index within the set.
    pub binding: u32,
    /// What kind of resource this binding represents.
    pub kind: BindingKind,
    /// The MIR type of the bound resource.
    pub ty: MirType,
}

/// A MIR function.
///
/// `PartialEq` is implemented manually (see below) rather than derived: it
/// excludes `spans`, which is in-memory-only debug/diagnostic data and must
/// not affect structural/serialization-round-trip equality.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MirFunction {
    /// Function name.
    pub name: Arc<str>,
    /// Function signature.
    pub sig: MirFnSig,
    /// Basic blocks (None for declarations).
    pub blocks: Option<Vec<MirBlock>>,
    /// Local variables.
    pub locals: Vec<MirLocal>,
    /// Is this function public?
    pub is_public: bool,
    /// Linkage type.
    pub linkage: Linkage,
    /// Optional GPU shader stage (vertex, fragment, compute).
    pub shader_stage: Option<ShaderStage>,
    /// Shader resource bindings (uniform buffers, textures, samplers).
    pub bindings: Vec<ShaderBinding>,
    /// Backing C header for a foreign declaration, from an extern block's
    /// `header "..."` clause. When set, the C backend emits an `#include` for
    /// this header and trusts it for the prototype instead of synthesizing an
    /// `extern` declaration. Skipped during serialization when absent so MIR
    /// for non-FFI functions is unchanged and remains backward compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_header: Option<Arc<str>>,
    /// Library to link for a foreign declaration, from an extern block's
    /// `link "..."` clause. The build driver passes it to the C compiler
    /// (`-lname` for gcc/clang/cc, `name.lib` for MSVC). Skipped during
    /// serialization when absent so non-FFI MIR stays backward compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_lib: Option<Arc<str>>,
    /// C source compiled into the same translation unit, from an extern
    /// block's `source "..."` clause (an absolute path). Skipped when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_source: Option<Arc<str>>,
    /// Whether this function is a C-ABI export (an `extern "C" fn` definition).
    /// Exports get external linkage and are declared in the generated C header
    /// so other languages can call them. Skipped when false.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_c_export: bool,
    /// Source spans for statements/terminators, keyed by (block position,
    /// index). In-memory only: populated at lowering, consumed by the MIR
    /// linear checker immediately after, and NOT serialized (the linear
    /// check runs before any MIR serialization, so the serializable-MIR
    /// contract is untouched). Excluded from `PartialEq` for the same reason.
    #[serde(skip, default)]
    pub spans: MirSpanTable,
}

impl PartialEq for MirFunction {
    fn eq(&self, other: &Self) -> bool {
        // Deliberately excludes `spans`: an in-memory-only diagnostic
        // side-table that must not affect structural/round-trip equality
        // (e.g. a module deserialized from JSON has an empty `spans` table
        // by construction and must still compare equal to the original).
        self.name == other.name
            && self.sig == other.sig
            && self.blocks == other.blocks
            && self.locals == other.locals
            && self.is_public == other.is_public
            && self.linkage == other.linkage
            && self.shader_stage == other.shader_stage
            && self.bindings == other.bindings
            && self.link_header == other.link_header
            && self.link_lib == other.link_lib
            && self.link_source == other.link_source
            && self.is_c_export == other.is_c_export
    }
}

/// Source spans for MIR statements/terminators, keyed by block/position.
///
/// In-memory only (see [`MirFunction::spans`]): populated at lowering and
/// consumed by the MIR-phase linear checker for diagnostics. Never
/// serialized and never affects [`MirFunction`] equality.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MirSpanTable {
    /// Span of the statement at `(block id, statement index)` in its block.
    pub stmt: HashMap<(u32, usize), Span>,
    /// Span of the terminator of the block with this id.
    pub terminator: HashMap<u32, Span>,
}

impl MirFunction {
    /// Create a new function.
    pub fn new(name: impl Into<Arc<str>>, sig: MirFnSig) -> Self {
        Self {
            name: name.into(),
            sig,
            blocks: None, // Start as declaration, add_block() makes it a definition
            locals: Vec::new(),
            is_public: false,
            linkage: Linkage::Internal,
            shader_stage: None,
            bindings: Vec::new(),
            link_header: None,
            link_lib: None,
            link_source: None,
            is_c_export: false,
            spans: MirSpanTable::default(),
        }
    }

    /// Create a function declaration (no body).
    pub fn declaration(name: impl Into<Arc<str>>, sig: MirFnSig) -> Self {
        Self {
            name: name.into(),
            sig,
            blocks: None,
            locals: Vec::new(),
            is_public: false,
            linkage: Linkage::External,
            shader_stage: None,
            bindings: Vec::new(),
            link_header: None,
            link_lib: None,
            link_source: None,
            is_c_export: false,
            spans: MirSpanTable::default(),
        }
    }

    /// Check if this is a declaration (no body).
    pub fn is_declaration(&self) -> bool {
        self.blocks.is_none()
    }

    /// Get the entry block.
    pub fn entry_block(&self) -> Option<&MirBlock> {
        self.blocks.as_ref().and_then(|b| b.first())
    }

    /// Get a block by ID.
    pub fn block(&self, id: BlockId) -> Option<&MirBlock> {
        self.blocks.as_ref().and_then(|b| b.get(id.0 as usize))
    }

    /// Get a mutable block by ID.
    pub fn block_mut(&mut self, id: BlockId) -> Option<&mut MirBlock> {
        self.blocks.as_mut().and_then(|b| b.get_mut(id.0 as usize))
    }

    /// Add a new block and return its ID.
    pub fn add_block(&mut self, block: MirBlock) -> BlockId {
        if let Some(blocks) = &mut self.blocks {
            let id = BlockId(blocks.len() as u32);
            blocks.push(block);
            id
        } else {
            self.blocks = Some(vec![block]);
            BlockId(0)
        }
    }

    /// Add a local variable and return its ID.
    pub fn add_local(&mut self, local: MirLocal) -> LocalId {
        let id = LocalId(self.locals.len() as u32);
        self.locals.push(local);
        id
    }
}

/// Function signature.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MirFnSig {
    /// Parameter types.
    pub params: Vec<MirType>,
    /// Return type.
    pub ret: MirType,
    /// Is this variadic?
    pub is_variadic: bool,
    /// Calling convention.
    pub calling_conv: CallingConv,
}

impl MirFnSig {
    /// Create a new function signature.
    pub fn new(params: Vec<MirType>, ret: MirType) -> Self {
        Self {
            params,
            ret,
            is_variadic: false,
            calling_conv: CallingConv::Build,
        }
    }
}

/// Calling convention.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CallingConv {
    /// Default BuildLang calling convention.
    Build,
    /// C calling convention.
    C,
    /// Fast calling convention.
    Fast,
    /// Cold calling convention (rarely called).
    Cold,
}

/// Linkage type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Linkage {
    /// Internal (private to the module).
    Internal,
    /// External (visible to other modules).
    External,
    /// Weak (can be overridden).
    Weak,
    /// Link once (merged across modules).
    LinkOnce,
}

// ============================================================================
// BASIC BLOCKS
// ============================================================================

/// A basic block ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BlockId(pub u32);

impl BlockId {
    /// The entry block ID.
    pub const ENTRY: Self = Self(0);
}

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

/// A basic block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirBlock {
    /// Block ID.
    pub id: BlockId,
    /// Optional label.
    pub label: Option<Arc<str>>,
    /// Statements in the block.
    pub stmts: Vec<MirStmt>,
    /// Block terminator.
    pub terminator: Option<MirTerminator>,
}

impl MirBlock {
    /// Create a new basic block.
    pub fn new(id: BlockId) -> Self {
        Self {
            id,
            label: None,
            stmts: Vec::new(),
            terminator: None,
        }
    }

    /// Create a labeled block.
    pub fn with_label(id: BlockId, label: impl Into<Arc<str>>) -> Self {
        Self {
            id,
            label: Some(label.into()),
            stmts: Vec::new(),
            terminator: None,
        }
    }

    /// Add a statement.
    pub fn push_stmt(&mut self, stmt: MirStmt) {
        self.stmts.push(stmt);
    }

    /// Set the terminator.
    pub fn set_terminator(&mut self, term: MirTerminator) {
        self.terminator = Some(term);
    }
}

// ============================================================================
// LOCALS AND VALUES
// ============================================================================

/// A local variable ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LocalId(pub u32);

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

/// A local variable declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirLocal {
    /// Local ID.
    pub id: LocalId,
    /// Optional name (for debugging).
    pub name: Option<Arc<str>>,
    /// Type.
    pub ty: MirType,
    /// Is this mutable?
    pub is_mut: bool,
    /// Is this a function parameter?
    pub is_param: bool,
    /// Type annotations (e.g., "ColorSpace:Linear", "Precision:Half").
    /// Preserved from the source type system for shader output.
    pub annotations: Vec<Arc<str>>,
}

impl MirLocal {
    /// Create a new local.
    pub fn new(id: LocalId, ty: MirType) -> Self {
        Self {
            id,
            name: None,
            ty,
            is_mut: false,
            is_param: false,
            annotations: Vec::new(),
        }
    }

    /// Create a named local.
    pub fn named(id: LocalId, name: impl Into<Arc<str>>, ty: MirType) -> Self {
        Self {
            id,
            name: Some(name.into()),
            ty,
            is_mut: false,
            is_param: false,
            annotations: Vec::new(),
        }
    }
}

/// A value (operand).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MirValue {
    /// Reference to a local.
    Local(LocalId),
    /// Constant value.
    Const(MirConst),
    /// Global reference.
    Global(Arc<str>),
    /// Function reference.
    Function(Arc<str>),
}

impl fmt::Display for MirValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MirValue::Local(id) => write!(f, "{}", id),
            MirValue::Const(c) => write!(f, "{}", c),
            MirValue::Global(name) => write!(f, "@{}", name),
            MirValue::Function(name) => write!(f, "@{}", name),
        }
    }
}

// ============================================================================
// STATEMENTS
// ============================================================================

/// A MIR statement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirStmt {
    /// The kind of statement.
    pub kind: MirStmtKind,
}

impl MirStmt {
    /// Create a new statement.
    pub fn new(kind: MirStmtKind) -> Self {
        Self { kind }
    }

    /// Create an assignment statement.
    pub fn assign(dest: LocalId, value: MirRValue) -> Self {
        Self::new(MirStmtKind::Assign { dest, value })
    }

    /// Create a storage_live statement.
    pub fn storage_live(local: LocalId) -> Self {
        Self::new(MirStmtKind::StorageLive(local))
    }

    /// Create a storage_dead statement.
    pub fn storage_dead(local: LocalId) -> Self {
        Self::new(MirStmtKind::StorageDead(local))
    }

    /// Create a no-op statement.
    pub fn nop() -> Self {
        Self::new(MirStmtKind::Nop)
    }
}

/// Kind of MIR statement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MirStmtKind {
    /// Assignment: `local = rvalue`
    Assign { dest: LocalId, value: MirRValue },

    /// Store through a pointer: `*ptr = value`
    DerefAssign { ptr: LocalId, value: MirRValue },

    /// Store to a field through a pointer: `ptr->field = value`
    FieldDerefAssign {
        ptr: LocalId,
        field_name: Arc<str>,
        value: MirRValue,
    },

    /// Store to a field on a local struct: `local.field = value`
    FieldAssign {
        base: LocalId,
        field_name: Arc<str>,
        value: MirRValue,
    },

    /// Indexed store into a slice/array/pointer base: `base[index] = value`.
    /// `base` is the collection value (a slice/array parameter lowers to
    /// `Ptr(Slice/Array)`), `index` selects the element, `elem_ty` is the element
    /// type. Added for GPU compute kernels writing `out[i] = ...` into a
    /// StorageBuffer; the C backend lowers it to `base[index] = value;` and the
    /// SPIR-V backend to `OpAccessChain` + `OpStore` into the runtime array.
    /// Without this, an indexed write to a slice parameter fell through every
    /// `lower_assign` arm and was silently dropped.
    IndexStore {
        base: MirValue,
        index: MirValue,
        elem_ty: MirType,
        value: MirRValue,
    },

    /// Store to a module global / mutable static: `GLOBAL = value`.
    /// MIR `Assign` targets only locals, so a write to a module-level global is
    /// represented here. Lowered from `lower_assign` when the assignment target
    /// is a bare identifier that names a global rather than a local.
    GlobalStore { name: Arc<str>, value: MirRValue },

    /// GPU compute workgroup barrier (`workgroupBarrier()`): a void side effect
    /// that synchronizes every invocation in the workgroup and makes shared
    /// (`Workgroup`-class) memory writes visible across the workgroup. Added in
    /// Phase 4a. On the SPIR-V backend this lowers to `OpControlBarrier` with
    /// Workgroup execution + memory scope and AcquireRelease|WorkgroupMemory
    /// semantics; the CPU / non-GPU backends treat it as a no-op (a single-
    /// threaded scalar cross-check needs no barrier).
    WorkgroupBarrier,

    /// Storage live (local becomes valid).
    StorageLive(LocalId),

    /// Storage dead (local becomes invalid).
    StorageDead(LocalId),

    /// No-op (placeholder).
    Nop,
}

/// A right-hand value (rvalue).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MirRValue {
    /// Use a value directly.
    Use(MirValue),

    /// Binary operation.
    BinaryOp {
        op: BinOp,
        left: MirValue,
        right: MirValue,
    },

    /// Unary operation.
    UnaryOp { op: UnaryOp, operand: MirValue },

    /// Create a reference.
    Ref { is_mut: bool, place: MirPlace },

    /// Address of.
    AddressOf { is_mut: bool, place: MirPlace },

    /// The address of a module global or mutable static: `&GLOBAL`. A place
    /// is rooted at a local, so a store into a field or an element of a
    /// global (`TABLE.w[i] = v`) and a borrow of it (`&mut TABLE`) take this
    /// address into a pointer local and project from `*ptr`. Before it
    /// existed the borrow pointed at a copy of the global and the store was
    /// refused (G35). The destination local has the type `Ptr(global type)`.
    AddressOfGlobal { is_mut: bool, name: Arc<str> },

    /// Cast.
    Cast {
        kind: CastKind,
        value: MirValue,
        ty: MirType,
    },

    /// Aggregate (tuple, struct, array).
    Aggregate {
        kind: AggregateKind,
        operands: Vec<MirValue>,
    },

    /// Array repeat: `[value; count]`
    Repeat { value: MirValue, count: u64 },

    /// Discriminant read (for enums).
    Discriminant(MirPlace),

    /// Length of slice/array.
    Len(MirPlace),

    /// Null check.
    NullaryOp(NullaryOp, MirType),

    /// Struct field access: `base.field_name`
    FieldAccess {
        base: MirValue,
        field_name: Arc<str>,
        field_ty: MirType,
    },

    /// Enum variant field access: `base.data.VariantName._N`
    VariantField {
        base: MirValue,
        variant_name: Arc<str>,
        field_index: u32,
        field_ty: MirType,
    },

    /// Array index access: `base[index]`
    IndexAccess {
        base: MirValue,
        index: MirValue,
        elem_ty: MirType,
    },

    /// Dereference a pointer: `*ptr`
    Deref { ptr: MirValue, pointee_ty: MirType },

    /// Sample a texture at given coordinates: `texture_sample(tex, sampler, uv)`
    TextureSample {
        texture: MirValue,
        sampler: MirValue,
        coords: MirValue,
    },
}

/// A place (lvalue).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirPlace {
    /// The base local.
    pub local: LocalId,
    /// Projections (field access, indexing, etc.).
    pub projections: Vec<PlaceProjection>,
}

impl MirPlace {
    /// Create a simple place from a local.
    pub fn local(id: LocalId) -> Self {
        Self {
            local: id,
            projections: Vec::new(),
        }
    }

    /// Add a field projection. Carries the field NAME as well as the ordinal
    /// index and type. The C and Rust backends render a place lvalue by name
    /// (`x.field`), because both emit named-field structs; LLVM GEP uses the
    /// ordinal index.
    pub fn field(mut self, idx: u32, name: Arc<str>, ty: MirType) -> Self {
        self.projections.push(PlaceProjection::Field(idx, name, ty));
        self
    }

    /// Add an index projection.
    pub fn index(mut self, idx: LocalId) -> Self {
        self.projections.push(PlaceProjection::Index(idx));
        self
    }

    /// Add a deref projection.
    pub fn deref(mut self) -> Self {
        self.projections.push(PlaceProjection::Deref);
        self
    }
}

/// Place projection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PlaceProjection {
    /// Dereference.
    Deref,
    /// Field access: ordinal index, field name, and field type.
    Field(u32, Arc<str>, MirType),
    /// Array/slice index.
    Index(LocalId),
    /// Constant index.
    ConstantIndex { offset: u64, from_end: bool },
    /// Subslice.
    Subslice { from: u64, to: u64, from_end: bool },
    /// Downcast (enum variant).
    Downcast(u32),
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BinOp {
    // Arithmetic
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    /// Exponentiation (base ** exponent)
    Pow,
    // Bitwise
    BitAnd,
    BitOr,
    BitXor,
    Shl,
    Shr,
    // Comparison
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    // Checked arithmetic (returns (result, overflow))
    AddChecked,
    SubChecked,
    MulChecked,
    // Wrapping arithmetic
    AddWrapping,
    SubWrapping,
    MulWrapping,
    // Saturating arithmetic
    AddSaturating,
    SubSaturating,
    MulSaturating,
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UnaryOp {
    /// Logical not (boolean complement). Lowers to C `!`.
    Not,
    /// Bitwise not (integer complement). Lowers to C `~`.
    BitNot,
    /// Arithmetic negation.
    Neg,
}

/// Cast kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CastKind {
    /// Integer to integer.
    IntToInt,
    /// Float to float.
    FloatToFloat,
    /// Integer to float.
    IntToFloat,
    /// Float to integer.
    FloatToInt,
    /// Pointer to integer.
    PtrToInt,
    /// Integer to pointer.
    IntToPtr,
    /// Pointer to pointer.
    PtrToPtr,
    /// Function to pointer.
    FnToPtr,
    /// Transmute (reinterpret bits).
    Transmute,
}

/// Aggregate kinds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AggregateKind {
    /// Array.
    Array(MirType),
    /// Tuple.
    Tuple,
    /// Struct.
    Struct(Arc<str>),
    /// Enum variant: (enum_name, discriminant, variant_name).
    Variant(Arc<str>, u32, Arc<str>),
    /// Closure.
    Closure(Arc<str>),
}

/// Nullary operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NullaryOp {
    /// Size of type.
    SizeOf,
    /// Alignment of type.
    AlignOf,
    /// GPU compute built-in global thread index component (`gl_GlobalInvocationID`).
    /// The `u32` selects the component: 0 = x, 1 = y, 2 = z. On the SPIR-V
    /// backend this reads the `GlobalInvocationId` built-in; on the C backend
    /// (the CPU cross-check path) it reads the ambient per-thread index the
    /// dispatch driver supplies.
    ThreadIndex(u32),
    /// GPU compute built-in LOCAL invocation index component
    /// (`gl_LocalInvocationID`): the lane's position WITHIN its workgroup. The
    /// `u32` selects the component (0 = x, 1 = y, 2 = z). SPIR-V reads the
    /// `LocalInvocationId` built-in. Added in Phase 4a for workgroup-shared
    /// reductions (`scratch[lid]`).
    LocalInvocationId(u32),
    /// GPU compute built-in WORKGROUP index component (`gl_WorkgroupID`): which
    /// workgroup this invocation belongs to. The `u32` selects the component
    /// (0 = x, 1 = y, 2 = z). SPIR-V reads the `WorkgroupId` built-in. Added in
    /// Phase 4a so a per-workgroup partial can be written to `out[wid]`.
    WorkgroupId(u32),
}

// ============================================================================
// TERMINATORS
// ============================================================================

/// Block terminator.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MirTerminator {
    /// Unconditional goto.
    Goto(BlockId),

    /// Conditional branch.
    If {
        cond: MirValue,
        then_block: BlockId,
        else_block: BlockId,
    },

    /// Multi-way branch (switch).
    Switch {
        value: MirValue,
        targets: Vec<(MirConst, BlockId)>,
        default: BlockId,
    },

    /// Function call.
    Call {
        func: MirValue,
        args: Vec<MirValue>,
        dest: Option<LocalId>,
        target: Option<BlockId>,
        unwind: Option<BlockId>,
    },

    /// Return from function.
    Return(Option<MirValue>),

    /// Unreachable code.
    Unreachable,

    /// Drop a value.
    Drop {
        place: MirPlace,
        target: BlockId,
        unwind: Option<BlockId>,
    },

    /// Assert condition.
    Assert {
        cond: MirValue,
        expected: bool,
        msg: Arc<str>,
        target: BlockId,
        unwind: Option<BlockId>,
    },

    /// Resume unwinding.
    Resume,

    /// Abort execution.
    Abort,
}

// ============================================================================
// TYPES
// ============================================================================

/// MIR type.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MirType {
    /// Void (unit).
    Void,
    /// Boolean.
    Bool,
    /// Integer.
    Int(IntSize, bool), // (size, signed)
    /// Float.
    Float(FloatSize),
    /// Pointer.
    Ptr(Box<MirType>),
    /// Array.
    Array(Box<MirType>, u64),
    /// Slice (fat pointer).
    Slice(Box<MirType>),
    /// Struct.
    Struct(Arc<str>),
    /// Function pointer.
    FnPtr(Box<MirFnSig>),
    /// Never type.
    Never,
    /// SIMD Vector type (element type, lane count).
    Vector(Box<MirType>, u32),
    /// 2D Texture (sampled image) - element type is the texel format (e.g. f32 for RGBA float).
    Texture2D(Box<MirType>),
    /// Opaque sampler type (for texture sampling).
    Sampler,
    /// Combined sampled image type (texture + sampler).
    SampledImage(Box<MirType>),
    /// Trait object: fat pointer (data_ptr: *void, vtable_ptr: *VTable).
    /// The Arc<str> is the trait name.
    TraitObject(Arc<str>),
    /// Dynamic array Vec<T>: heap-allocated handle wrapping BuildVec.
    Vec(Box<MirType>),
    /// HashMap<K, V>: heap-allocated handle wrapping BuildHashMap.
    Map(Box<MirType>, Box<MirType>),
    /// Option<T>: tagged optional value with a statically known payload type.
    Option(Box<MirType>),
    /// Tuple type: (T0, T1, ...).
    Tuple(Vec<MirType>),
}

/// A C-identifier-safe name for a type, used for the per-value-type HashMap
/// wrappers (`build_hmap_get_val_<name>`). Lowering names the call and the C
/// backend names the definition with this one function, so the two always
/// agree. Before M4 they used different spellings for every type but a few,
/// and `HashMap<str, u64>` or `HashMap<str, (i64, f64)>` failed to build.
pub fn map_value_mangle(ty: &MirType) -> String {
    fn clean(text: &str) -> String {
        text.chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
            .collect()
    }
    match ty {
        MirType::Void => "void".to_string(),
        MirType::Bool => "bool".to_string(),
        MirType::Int(size, signed) => {
            let bits = match size {
                IntSize::I8 => "8",
                IntSize::I16 => "16",
                IntSize::I32 => "32",
                IntSize::I64 => "64",
                IntSize::I128 => "128",
                IntSize::ISize => "size",
            };
            format!("{}{}", if *signed { "i" } else { "u" }, bits)
        }
        MirType::Float(FloatSize::F32) => "f32".to_string(),
        MirType::Float(FloatSize::F64) => "f64".to_string(),
        MirType::Ptr(inner) => format!("ptr_{}", map_value_mangle(inner)),
        MirType::Array(elem, n) => format!("arr{}_{}", n, map_value_mangle(elem)),
        MirType::Slice(elem) => format!("slice_{}", map_value_mangle(elem)),
        MirType::Struct(name) => format!("s_{}", clean(name)),
        MirType::Vec(elem) => format!("vec_{}", map_value_mangle(elem)),
        MirType::Map(k, v) => format!("map_{}_{}", map_value_mangle(k), map_value_mangle(v)),
        MirType::Option(inner) => format!("opt_{}", map_value_mangle(inner)),
        MirType::Tuple(elems) => {
            let parts: Vec<String> = elems.iter().map(map_value_mangle).collect();
            format!("tup{}_{}", elems.len(), parts.join("_"))
        }
        other => clean(&format!("{other:?}")),
    }
}

impl MirType {
    /// Create an i8 type.
    pub fn i8() -> Self {
        MirType::Int(IntSize::I8, true)
    }
    /// Create an i16 type.
    pub fn i16() -> Self {
        MirType::Int(IntSize::I16, true)
    }
    /// Create an i32 type.
    pub fn i32() -> Self {
        MirType::Int(IntSize::I32, true)
    }
    /// Create an i64 type.
    pub fn i64() -> Self {
        MirType::Int(IntSize::I64, true)
    }
    /// Create a u8 type.
    pub fn u8() -> Self {
        MirType::Int(IntSize::I8, false)
    }
    /// Create a u16 type.
    pub fn u16() -> Self {
        MirType::Int(IntSize::I16, false)
    }
    /// Create a u32 type.
    pub fn u32() -> Self {
        MirType::Int(IntSize::I32, false)
    }
    /// Create a u64 type.
    pub fn u64() -> Self {
        MirType::Int(IntSize::I64, false)
    }
    /// Create an isize type.
    pub fn isize() -> Self {
        MirType::Int(IntSize::ISize, true)
    }
    /// Create a usize type.
    pub fn usize() -> Self {
        MirType::Int(IntSize::ISize, false)
    }
    /// Create an f32 type.
    pub fn f32() -> Self {
        MirType::Float(FloatSize::F32)
    }
    /// Create an f64 type.
    pub fn f64() -> Self {
        MirType::Float(FloatSize::F64)
    }

    /// Create a vector type.
    pub fn vector(elem: MirType, lanes: u32) -> Self {
        MirType::Vector(Box::new(elem), lanes)
    }

    /// Create a 128-bit vector of 4 f32s (for SSE/NEON).
    pub fn v4f32() -> Self {
        MirType::vector(MirType::f32(), 4)
    }
    /// Create a 256-bit vector of 8 f32s (for AVX).
    pub fn v8f32() -> Self {
        MirType::vector(MirType::f32(), 8)
    }
    /// Create a 128-bit vector of 2 f64s.
    pub fn v2f64() -> Self {
        MirType::vector(MirType::f64(), 2)
    }
    /// Create a 256-bit vector of 4 f64s.
    pub fn v4f64() -> Self {
        MirType::vector(MirType::f64(), 4)
    }
    /// Create a 128-bit vector of 4 i32s.
    pub fn v4i32() -> Self {
        MirType::vector(MirType::i32(), 4)
    }
    /// Create a 256-bit vector of 8 i32s.
    pub fn v8i32() -> Self {
        MirType::vector(MirType::i32(), 8)
    }
    /// Create a 128-bit vector of 16 i8s.
    pub fn v16i8() -> Self {
        MirType::vector(MirType::i8(), 16)
    }
    /// Create a 256-bit vector of 32 i8s.
    pub fn v32i8() -> Self {
        MirType::vector(MirType::i8(), 32)
    }

    /// Create a 2D texture type with the given element type.
    pub fn texture2d(elem: MirType) -> Self {
        MirType::Texture2D(Box::new(elem))
    }
    /// Create a sampler type.
    pub fn sampler() -> Self {
        MirType::Sampler
    }
    /// Create a combined sampled image type.
    pub fn sampled_image(elem: MirType) -> Self {
        MirType::SampledImage(Box::new(elem))
    }

    /// Create a tuple type.
    pub fn tuple(elems: Vec<MirType>) -> Self {
        MirType::Tuple(elems)
    }

    /// Generate the canonical C typedef name for a tuple type.
    /// The C name of a slice of `elem`: one named `{ T* ptr; size_t len; }`
    /// per element type, so every `&[T]` in a program is the same C type.
    pub fn slice_type_name(elem: &MirType) -> Arc<str> {
        Arc::from(format!("BlSlice_{}", map_value_mangle(elem)))
    }

    pub fn tuple_type_name(elems: &[MirType]) -> Arc<str> {
        let parts: Vec<&str> = elems
            .iter()
            .map(|t| match t {
                MirType::Void => "void",
                MirType::Bool => "bool",
                MirType::Int(IntSize::I8, true) => "i8",
                MirType::Int(IntSize::I16, true) => "i16",
                MirType::Int(IntSize::I32, true) => "i32",
                MirType::Int(IntSize::I64, true) => "i64",
                MirType::Int(IntSize::I128, true) => "i128",
                MirType::Int(IntSize::ISize, true) => "isize",
                MirType::Int(IntSize::I8, false) => "u8",
                MirType::Int(IntSize::I16, false) => "u16",
                MirType::Int(IntSize::I32, false) => "u32",
                MirType::Int(IntSize::I64, false) => "u64",
                MirType::Int(IntSize::I128, false) => "u128",
                MirType::Int(IntSize::ISize, false) => "usize",
                MirType::Float(FloatSize::F32) => "f32",
                MirType::Float(FloatSize::F64) => "f64",
                MirType::Ptr(_) => "ptr",
                MirType::Struct(name) => name.as_ref(),
                MirType::Option(_) => "option",
                _ => "unknown",
            })
            .collect();
        Arc::from(format!("Tuple_{}", parts.join("_")))
    }

    /// Check if this is a signed integer.
    pub fn is_signed(&self) -> bool {
        matches!(self, MirType::Int(_, true))
    }

    /// Check if this is an integer type.
    pub fn is_integer(&self) -> bool {
        matches!(self, MirType::Int(_, _))
    }

    /// Check if this is a float type.
    pub fn is_float(&self) -> bool {
        matches!(self, MirType::Float(_))
    }

    /// Check if this is a pointer type.
    pub fn is_pointer(&self) -> bool {
        matches!(self, MirType::Ptr(_))
    }

    /// Get the size in bits.
    pub fn bit_size(&self, ptr_size: u32) -> Option<u32> {
        match self {
            MirType::Void => Some(0),
            MirType::Bool => Some(8),
            MirType::Int(size, _) => Some(size.bits(ptr_size)),
            MirType::Float(size) => Some(size.bits()),
            MirType::Ptr(_) => Some(ptr_size),
            MirType::Array(elem, count) => elem.bit_size(ptr_size).map(|s| s * (*count as u32)),
            MirType::Slice(_) => Some(ptr_size * 2), // ptr + len
            MirType::Struct(_) => None,              // Need type info
            MirType::FnPtr(_) => Some(ptr_size),
            MirType::Never => Some(0),
            MirType::Vector(elem, lanes) => elem.bit_size(ptr_size).map(|s| s * lanes),
            MirType::Texture2D(_) | MirType::Sampler | MirType::SampledImage(_) => {
                None // Opaque GPU types - no CPU bit size
            }
            MirType::TraitObject(_) => Some(ptr_size * 2), // Fat pointer: data + vtable
            MirType::Vec(_) => Some(ptr_size),             // BuildVecHandle is a pointer
            MirType::Map(_, _) => Some(ptr_size),          // BuildMapHandle is a pointer
            MirType::Option(_) => None,                    // Runtime tagged union.
            MirType::Tuple(elems) => {
                let mut total = 0u32;
                for e in elems {
                    total += e.bit_size(ptr_size)?;
                }
                Some(total)
            }
        }
    }
}

impl fmt::Display for MirType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MirType::Void => write!(f, "void"),
            MirType::Bool => write!(f, "bool"),
            MirType::Int(size, signed) => {
                let prefix = if *signed { "i" } else { "u" };
                match size {
                    IntSize::I8 => write!(f, "{}8", prefix),
                    IntSize::I16 => write!(f, "{}16", prefix),
                    IntSize::I32 => write!(f, "{}32", prefix),
                    IntSize::I64 => write!(f, "{}64", prefix),
                    IntSize::I128 => write!(f, "{}128", prefix),
                    IntSize::ISize => write!(f, "{}size", prefix),
                }
            }
            MirType::Float(size) => match size {
                FloatSize::F32 => write!(f, "f32"),
                FloatSize::F64 => write!(f, "f64"),
            },
            MirType::Ptr(inner) => write!(f, "*{}", inner),
            MirType::Array(elem, len) => write!(f, "[{}; {}]", elem, len),
            MirType::Slice(elem) => write!(f, "[{}]", elem),
            MirType::Struct(name) => write!(f, "{}", name),
            MirType::FnPtr(sig) => {
                write!(f, "fn(")?;
                for (i, p) in sig.params.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", p)?;
                }
                write!(f, ") -> {}", sig.ret)
            }
            MirType::Never => write!(f, "!"),
            MirType::Vector(elem, lanes) => write!(f, "<{} x {}>", lanes, elem),
            MirType::Texture2D(elem) => write!(f, "texture2d<{}>", elem),
            MirType::Sampler => write!(f, "sampler"),
            MirType::SampledImage(elem) => write!(f, "sampled_image<{}>", elem),
            MirType::TraitObject(name) => write!(f, "dyn {}", name),
            MirType::Vec(elem) => write!(f, "Vec<{}>", elem),
            MirType::Map(key, val) => write!(f, "HashMap<{}, {}>", key, val),
            MirType::Option(inner) => write!(f, "Option<{}>", inner),
            MirType::Tuple(elems) => {
                write!(f, "(")?;
                for (i, e) in elems.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", e)?;
                }
                write!(f, ")")
            }
        }
    }
}

/// Integer sizes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum IntSize {
    I8,
    I16,
    I32,
    I64,
    I128,
    ISize,
}

impl IntSize {
    /// Get size in bits.
    pub fn bits(&self, ptr_size: u32) -> u32 {
        match self {
            IntSize::I8 => 8,
            IntSize::I16 => 16,
            IntSize::I32 => 32,
            IntSize::I64 => 64,
            IntSize::I128 => 128,
            IntSize::ISize => ptr_size,
        }
    }
}

/// Float sizes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FloatSize {
    F32,
    F64,
}

impl FloatSize {
    /// Get size in bits.
    pub fn bits(&self) -> u32 {
        match self {
            FloatSize::F32 => 32,
            FloatSize::F64 => 64,
        }
    }
}

// ============================================================================
// CONSTANTS
// ============================================================================

/// MIR constant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MirConst {
    /// Boolean.
    Bool(bool),
    /// Integer.
    Int(i128, MirType),
    /// Unsigned integer.
    Uint(u128, MirType),
    /// Float. The value is serialized via its raw IEEE-754 bit pattern so that
    /// every `f64` (including `NaN`, `±∞`, `-0.0`, and subnormals) round-trips
    /// bit-exact through JSON.
    Float(#[serde(with = "lossless_f64")] f64, MirType),
    /// String (index into string table).
    Str(u32),
    /// Byte string.
    ByteStr(Vec<u8>),
    /// Null pointer.
    Null(MirType),
    /// Unit value.
    Unit,
    /// Zero-initialized value.
    Zeroed(MirType),
    /// Undefined value.
    Undef(MirType),
    /// Struct constant: (struct_name, field_values).
    Struct(Arc<str>, Vec<MirConst>),
    /// Fixed array constant: (element type, element values), one value per
    /// element. The initializer of a `static` or `const` of array type (G34).
    Array(MirType, Vec<MirConst>),
}

impl fmt::Display for MirConst {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MirConst::Bool(b) => write!(f, "{}", b),
            MirConst::Int(v, ty) => write!(f, "{}{}", v, ty),
            MirConst::Uint(v, ty) => write!(f, "{}{}", v, ty),
            MirConst::Float(v, ty) => write!(f, "{}{}", v, ty),
            MirConst::Str(idx) => write!(f, "str#{}", idx),
            MirConst::ByteStr(bytes) => write!(f, "b\"{}\"", bytes.len()),
            MirConst::Null(ty) => write!(f, "null:{}", ty),
            MirConst::Unit => write!(f, "()"),
            MirConst::Zeroed(ty) => write!(f, "zeroed:{}", ty),
            MirConst::Undef(ty) => write!(f, "undef:{}", ty),
            MirConst::Struct(name, fields) => {
                write!(f, "{}{{", name)?;
                for (i, fv) in fields.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", fv)?;
                }
                write!(f, "}}")
            }
            MirConst::Array(elem, values) => {
                write!(f, "[")?;
                for (i, v) in values.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", v)?;
                }
                write!(f, "]:{}", elem)
            }
        }
    }
}

// ============================================================================
// GLOBALS
// ============================================================================

/// Global variable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirGlobal {
    /// Name.
    pub name: Arc<str>,
    /// Type.
    pub ty: MirType,
    /// Initial value.
    pub init: Option<MirConst>,
    /// Is mutable?
    pub is_mut: bool,
    /// Linkage.
    pub linkage: Linkage,
    /// Whether this global is only an external declaration (a foreign
    /// `static` from an extern block). Such globals are referenced, never
    /// defined: the C backend either relies on the declared `header` or emits
    /// a bare `extern` declaration instead of a definition.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_extern_decl: bool,
    /// Backing C header for a foreign static, from the extern block's
    /// `header "..."` clause.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_header: Option<Arc<str>>,
    /// Library to link for a foreign static, from the extern block's
    /// `link "..."` clause.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link_lib: Option<Arc<str>>,
}

impl MirGlobal {
    /// Create a new global.
    pub fn new(name: impl Into<Arc<str>>, ty: MirType) -> Self {
        Self {
            name: name.into(),
            ty,
            init: None,
            is_mut: false,
            linkage: Linkage::Internal,
            is_extern_decl: false,
            link_header: None,
            link_lib: None,
        }
    }
}

/// External declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirExternal {
    /// Name.
    pub name: Arc<str>,
    /// Kind.
    pub kind: ExternalKind,
}

/// Kind of external.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ExternalKind {
    /// External function.
    Function(MirFnSig),
    /// External global.
    Global(MirType),
}

// ============================================================================
// TYPE DEFINITIONS
// ============================================================================

/// Type definition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirTypeDef {
    /// Name.
    pub name: Arc<str>,
    /// Kind.
    pub kind: TypeDefKind,
}

/// Kind of type definition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TypeDefKind {
    /// Struct.
    Struct {
        fields: Vec<(Option<Arc<str>>, MirType)>,
        packed: bool,
    },
    /// Union.
    Union { variants: Vec<(Arc<str>, MirType)> },
    /// Enum.
    Enum {
        discriminant_ty: MirType,
        variants: Vec<MirEnumVariant>,
    },
}

/// Enum variant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MirEnumVariant {
    /// Variant name.
    pub name: Arc<str>,
    /// Discriminant value.
    pub discriminant: i128,
    /// Fields.
    pub fields: Vec<(Option<Arc<str>>, MirType)>,
}

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

    // =========================================================================
    // MIR TYPE TESTS
    // =========================================================================

    #[test]
    fn test_mir_type_display() {
        assert_eq!(format!("{}", MirType::i32()), "i32");
        assert_eq!(format!("{}", MirType::u64()), "u64");
        assert_eq!(format!("{}", MirType::f32()), "f32");
        assert_eq!(format!("{}", MirType::Bool), "bool");
        assert_eq!(
            format!("{}", MirType::Ptr(Box::new(MirType::i32()))),
            "*i32"
        );
        assert_eq!(format!("{}", MirType::Void), "void");
        assert_eq!(format!("{}", MirType::Never), "!");
    }

    #[test]
    fn test_mir_type_constructors() {
        assert_eq!(MirType::i8(), MirType::Int(IntSize::I8, true));
        assert_eq!(MirType::i16(), MirType::Int(IntSize::I16, true));
        assert_eq!(MirType::i32(), MirType::Int(IntSize::I32, true));
        assert_eq!(MirType::i64(), MirType::Int(IntSize::I64, true));
        assert_eq!(MirType::u8(), MirType::Int(IntSize::I8, false));
        assert_eq!(MirType::u16(), MirType::Int(IntSize::I16, false));
        assert_eq!(MirType::u32(), MirType::Int(IntSize::I32, false));
        assert_eq!(MirType::u64(), MirType::Int(IntSize::I64, false));
        assert_eq!(MirType::isize(), MirType::Int(IntSize::ISize, true));
        assert_eq!(MirType::usize(), MirType::Int(IntSize::ISize, false));
        assert_eq!(MirType::f32(), MirType::Float(FloatSize::F32));
        assert_eq!(MirType::f64(), MirType::Float(FloatSize::F64));
    }

    #[test]
    fn test_mir_type_predicates() {
        assert!(MirType::i32().is_integer());
        assert!(MirType::u64().is_integer());
        assert!(!MirType::f32().is_integer());
        assert!(!MirType::Bool.is_integer());

        assert!(MirType::f32().is_float());
        assert!(MirType::f64().is_float());
        assert!(!MirType::i32().is_float());

        assert!(MirType::i32().is_signed());
        assert!(!MirType::u32().is_signed());

        assert!(MirType::Ptr(Box::new(MirType::i32())).is_pointer());
        assert!(!MirType::i32().is_pointer());
    }

    #[test]
    fn test_mir_type_bit_size() {
        let ptr_size = 64;
        assert_eq!(MirType::Void.bit_size(ptr_size), Some(0));
        assert_eq!(MirType::Bool.bit_size(ptr_size), Some(8));
        assert_eq!(MirType::i8().bit_size(ptr_size), Some(8));
        assert_eq!(MirType::i16().bit_size(ptr_size), Some(16));
        assert_eq!(MirType::i32().bit_size(ptr_size), Some(32));
        assert_eq!(MirType::i64().bit_size(ptr_size), Some(64));
        assert_eq!(
            MirType::Int(IntSize::I128, true).bit_size(ptr_size),
            Some(128)
        );
        assert_eq!(MirType::f32().bit_size(ptr_size), Some(32));
        assert_eq!(MirType::f64().bit_size(ptr_size), Some(64));
        assert_eq!(
            MirType::Ptr(Box::new(MirType::i32())).bit_size(ptr_size),
            Some(64)
        );
        assert_eq!(MirType::isize().bit_size(ptr_size), Some(64));
    }

    #[test]
    fn test_int_size_bits() {
        assert_eq!(IntSize::I8.bits(64), 8);
        assert_eq!(IntSize::I16.bits(64), 16);
        assert_eq!(IntSize::I32.bits(64), 32);
        assert_eq!(IntSize::I64.bits(64), 64);
        assert_eq!(IntSize::I128.bits(64), 128);
        assert_eq!(IntSize::ISize.bits(64), 64);
        assert_eq!(IntSize::ISize.bits(32), 32);
    }

    #[test]
    fn test_float_size_bits() {
        assert_eq!(FloatSize::F32.bits(), 32);
        assert_eq!(FloatSize::F64.bits(), 64);
    }

    // =========================================================================
    // MIR MODULE TESTS
    // =========================================================================

    #[test]
    fn test_mir_module() {
        let mut module = MirModule::new("test");
        let idx = module.intern_string("hello");
        assert_eq!(idx, 0);
        assert_eq!(module.intern_string("hello"), 0); // Same string
        assert_eq!(module.intern_string("world"), 1); // Different string
    }

    #[test]
    fn test_mir_module_add_function() {
        let mut module = MirModule::new("test");
        let sig = MirFnSig::new(vec![MirType::i32()], MirType::i32());
        let func = MirFunction::new("my_func", sig);
        module.add_function(func);

        assert_eq!(module.functions.len(), 1);
        assert_eq!(module.functions[0].name.as_ref(), "my_func");
    }

    #[test]
    fn test_mir_module_add_global() {
        let mut module = MirModule::new("test");
        let global = MirGlobal::new("my_global", MirType::i32());
        module.add_global(global);

        assert_eq!(module.globals.len(), 1);
        assert_eq!(module.globals[0].name.as_ref(), "my_global");
    }

    // =========================================================================
    // MIR FUNCTION TESTS
    // =========================================================================

    #[test]
    fn test_mir_function_new() {
        let sig = MirFnSig::new(vec![MirType::i32(), MirType::i64()], MirType::Bool);
        let func = MirFunction::new("test_func", sig);

        assert_eq!(func.name.as_ref(), "test_func");
        assert_eq!(func.sig.params.len(), 2);
        assert_eq!(func.sig.ret, MirType::Bool);
        assert!(func.blocks.is_none());
    }

    #[test]
    fn test_mir_function_is_declaration() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut func = MirFunction::new("decl_func", sig);

        assert!(func.is_declaration());

        func.add_block(MirBlock::new(BlockId::ENTRY));
        assert!(!func.is_declaration());
    }

    #[test]
    fn test_mir_function_add_block() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        let mut func = MirFunction::new("test", sig);

        func.add_block(MirBlock::new(BlockId(0)));
        func.add_block(MirBlock::new(BlockId(1)));

        assert_eq!(func.blocks.as_ref().unwrap().len(), 2);
    }

    // =========================================================================
    // MIR BLOCK TESTS
    // =========================================================================

    #[test]
    fn test_mir_block_new() {
        let block = MirBlock::new(BlockId(5));
        assert_eq!(block.id.0, 5);
        assert!(block.label.is_none());
        assert!(block.stmts.is_empty());
        assert!(block.terminator.is_none());
    }

    #[test]
    fn test_mir_block_with_label() {
        let block = MirBlock::with_label(BlockId(0), "entry");
        assert_eq!(block.label.as_ref().unwrap().as_ref(), "entry");
    }

    #[test]
    fn test_mir_block_push_stmt() {
        let mut block = MirBlock::new(BlockId(0));
        block.push_stmt(MirStmt::nop());
        block.push_stmt(MirStmt::nop());

        assert_eq!(block.stmts.len(), 2);
    }

    #[test]
    fn test_mir_block_set_terminator() {
        let mut block = MirBlock::new(BlockId(0));
        assert!(block.terminator.is_none());

        block.set_terminator(MirTerminator::Return(None));
        assert!(block.terminator.is_some());
    }

    // =========================================================================
    // MIR STATEMENT TESTS
    // =========================================================================

    #[test]
    fn test_mir_stmt_assign() {
        let stmt = MirStmt::assign(
            LocalId(0),
            MirRValue::Use(MirValue::Const(MirConst::Bool(true))),
        );
        match stmt.kind {
            MirStmtKind::Assign { dest, .. } => assert_eq!(dest.0, 0),
            _ => panic!("Expected Assign"),
        }
    }

    #[test]
    fn test_mir_stmt_nop() {
        let stmt = MirStmt::nop();
        assert!(matches!(stmt.kind, MirStmtKind::Nop));
    }

    // =========================================================================
    // MIR VALUE TESTS
    // =========================================================================

    #[test]
    fn test_mir_value_local() {
        let val = MirValue::Local(LocalId(42));
        match val {
            MirValue::Local(id) => assert_eq!(id.0, 42),
            _ => panic!("Expected Local"),
        }
    }

    #[test]
    fn test_mir_value_const_int() {
        let val = MirValue::Const(MirConst::Int(123, MirType::i32()));
        match val {
            MirValue::Const(MirConst::Int(v, ty)) => {
                assert_eq!(v, 123);
                assert_eq!(ty, MirType::i32());
            }
            _ => panic!("Expected Const Int"),
        }
    }

    // =========================================================================
    // MIR CONST TESTS
    // =========================================================================

    #[test]
    fn test_mir_const_display() {
        assert_eq!(format!("{}", MirConst::Bool(true)), "true");
        assert_eq!(format!("{}", MirConst::Bool(false)), "false");
        assert_eq!(format!("{}", MirConst::Int(42, MirType::i32())), "42i32");
        assert_eq!(format!("{}", MirConst::Uint(100, MirType::u64())), "100u64");
        assert_eq!(format!("{}", MirConst::Str(0)), "str#0");
        assert_eq!(format!("{}", MirConst::Unit), "()");
        assert_eq!(
            format!(
                "{}",
                MirConst::Struct(
                    Arc::from("Color"),
                    vec![
                        MirConst::Float(1.0, MirType::f64()),
                        MirConst::Float(0.5, MirType::f64()),
                        MirConst::Float(0.0, MirType::f64()),
                    ],
                )
            ),
            "Color{1f64, 0.5f64, 0f64}",
        );
    }

    // =========================================================================
    // MIR TERMINATOR TESTS
    // =========================================================================

    #[test]
    fn test_mir_terminator_return() {
        let term = MirTerminator::Return(Some(MirValue::Const(MirConst::Int(0, MirType::i32()))));
        match term {
            MirTerminator::Return(Some(_)) => {}
            _ => panic!("Expected Return with value"),
        }
    }

    #[test]
    fn test_mir_terminator_goto() {
        let term = MirTerminator::Goto(BlockId(5));
        match term {
            MirTerminator::Goto(id) => assert_eq!(id.0, 5),
            _ => panic!("Expected Goto"),
        }
    }

    #[test]
    fn test_mir_terminator_if() {
        let term = MirTerminator::If {
            cond: MirValue::Const(MirConst::Bool(true)),
            then_block: BlockId(1),
            else_block: BlockId(2),
        };
        match term {
            MirTerminator::If {
                then_block,
                else_block,
                ..
            } => {
                assert_eq!(then_block.0, 1);
                assert_eq!(else_block.0, 2);
            }
            _ => panic!("Expected If"),
        }
    }

    // =========================================================================
    // MIR RVALUE TESTS
    // =========================================================================

    #[test]
    fn test_mir_rvalue_binary_op() {
        let rvalue = MirRValue::BinaryOp {
            op: BinOp::Add,
            left: MirValue::Local(LocalId(0)),
            right: MirValue::Local(LocalId(1)),
        };
        match rvalue {
            MirRValue::BinaryOp { op, .. } => assert_eq!(op, BinOp::Add),
            _ => panic!("Expected BinaryOp"),
        }
    }

    #[test]
    fn test_mir_rvalue_unary_op() {
        let rvalue = MirRValue::UnaryOp {
            op: UnaryOp::Neg,
            operand: MirValue::Local(LocalId(0)),
        };
        match rvalue {
            MirRValue::UnaryOp { op, .. } => assert_eq!(op, UnaryOp::Neg),
            _ => panic!("Expected UnaryOp"),
        }
    }

    // =========================================================================
    // MIR GLOBAL TESTS
    // =========================================================================

    #[test]
    fn test_mir_global_new() {
        let global = MirGlobal::new("my_var", MirType::i64());
        assert_eq!(global.name.as_ref(), "my_var");
        assert_eq!(global.ty, MirType::i64());
        assert!(!global.is_mut);
        assert!(global.init.is_none());
    }

    // =========================================================================
    // MIR FN SIG TESTS
    // =========================================================================

    #[test]
    fn test_mir_fn_sig_new() {
        let sig = MirFnSig::new(vec![MirType::i32(), MirType::f64()], MirType::Bool);
        assert_eq!(sig.params.len(), 2);
        assert_eq!(sig.params[0], MirType::i32());
        assert_eq!(sig.params[1], MirType::f64());
        assert_eq!(sig.ret, MirType::Bool);
        assert!(!sig.is_variadic);
    }

    #[test]
    fn test_mir_fn_sig_void() {
        let sig = MirFnSig::new(vec![], MirType::Void);
        assert!(sig.params.is_empty());
        assert_eq!(sig.ret, MirType::Void);
    }

    // =========================================================================
    // BLOCK ID TESTS
    // =========================================================================

    #[test]
    fn test_block_id_entry() {
        assert_eq!(BlockId::ENTRY.0, 0);
    }

    // =========================================================================
    // LOCAL ID TESTS
    // =========================================================================

    #[test]
    fn test_local_id() {
        let id = LocalId(10);
        assert_eq!(id.0, 10);
    }
}