cjc-mir 0.1.9

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

pub mod cfg;
pub mod dominators;
pub mod escape;
pub mod inspect;
pub mod loop_analysis;
pub mod monomorph;
pub mod nogc_verify;
pub mod optimize;
pub mod reduction;
pub mod ssa;
pub mod ssa_loop_overlay;
pub mod ssa_optimize;
pub mod verify;

use cjc_ast::{BinOp, UnaryOp, Visibility};
use std::collections::BTreeMap;
pub use escape::AllocHint;

// ---------------------------------------------------------------------------
// IDs
// ---------------------------------------------------------------------------

/// Unique identifier for a MIR function within a [`MirProgram`].
///
/// Assigned sequentially during HIR-to-MIR lowering. The synthetic `__main`
/// entry function and lambda-lifted closures each receive their own ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MirFnId(pub u32);

/// Unique identifier for a basic block within a [`cfg::MirCfg`].
///
/// Block IDs are dense indices into `MirCfg::basic_blocks`. `BlockId(0)` is
/// always the entry block. IDs are assigned deterministically in creation order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BlockId(pub u32);

/// Unique identifier for a temporary value in the MIR.
///
/// Reserved for future use when MIR transitions to explicit temporaries
/// instead of named variables.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TempId(pub u32);

// ---------------------------------------------------------------------------
// Program
// ---------------------------------------------------------------------------

/// A MIR program is a collection of functions + struct defs + an entry point.
#[derive(Debug, Clone)]
pub struct MirProgram {
    pub functions: Vec<MirFunction>,
    pub struct_defs: Vec<MirStructDef>,
    pub enum_defs: Vec<MirEnumDef>,
    /// Top-level statements (let bindings, expr stmts) are collected into
    /// a synthetic `__main` function.
    pub entry: MirFnId,
}

/// A struct (or record/class) type definition at the MIR level.
///
/// Struct definitions carry through from HIR without modification.
/// The [`is_record`](MirStructDef::is_record) flag distinguishes immutable
/// value-type records from mutable class-style structs.
#[derive(Debug, Clone)]
pub struct MirStructDef {
    /// Name of the struct type.
    pub name: String,
    /// Fields as `(field_name, type_name)` pairs, in declaration order.
    pub fields: Vec<(String, String)>,
    /// True if this is a record (immutable value type).
    pub is_record: bool,
    /// Visibility of this struct definition.
    pub vis: Visibility,
}

/// An enum type definition at the MIR level.
///
/// Contains the enum name and its ordered list of variant definitions.
#[derive(Debug, Clone)]
pub struct MirEnumDef {
    /// Name of the enum type.
    pub name: String,
    /// Variant definitions in declaration order.
    pub variants: Vec<MirVariantDef>,
}

/// A single variant of a [`MirEnumDef`].
///
/// Each variant can carry zero or more positional fields identified by
/// their type names.
#[derive(Debug, Clone)]
pub struct MirVariantDef {
    /// Name of this variant.
    pub name: String,
    /// Positional field type names.
    pub fields: Vec<String>,
}

// ---------------------------------------------------------------------------
// Functions
// ---------------------------------------------------------------------------

/// A MIR function definition.
///
/// Contains both the tree-form [`MirBody`] and an optional CFG representation.
/// The tree-form body is canonical after lowering; the CFG is built on demand
/// via [`build_cfg`](MirFunction::build_cfg) for analyses that require
/// explicit control-flow edges (SSA, dominators, loop analysis).
///
/// Lambda-lifted closures and the synthetic `__main` entry function are
/// represented as regular `MirFunction` instances.
#[derive(Debug, Clone)]
pub struct MirFunction {
    /// Unique function ID within the program.
    pub id: MirFnId,
    /// Function name. Lambda-lifted closures use `__closure_N` names.
    /// Impl methods use `Target.method` qualified names.
    pub name: String,
    /// Generic type parameters as `(param_name, trait_bounds)` pairs.
    pub type_params: Vec<(String, Vec<String>)>,
    /// Function parameters in declaration order.
    pub params: Vec<MirParam>,
    /// Return type name, if explicitly annotated.
    pub return_type: Option<String>,
    /// Tree-form function body (statements + optional tail expression).
    pub body: MirBody,
    /// Whether this function is annotated with `@nogc`.
    /// When true, the [`nogc_verify`] module rejects any GC-triggering operations.
    pub is_nogc: bool,
    /// CFG representation of this function's body.
    /// Built lazily from tree-form `body` via `build_cfg()`.
    /// When present, this is the canonical representation for the CFG executor.
    pub cfg_body: Option<cfg::MirCfg>,
    /// Decorator names applied to this function (e.g., `@memoize`, `@trace`).
    pub decorators: Vec<String>,
    /// Visibility of this function definition.
    pub vis: Visibility,
    /// Tier-0 perf: total number of local slots used by this function
    /// (parameters + `let` bindings, including those in nested blocks).
    ///
    /// Populated by the slot-resolution pass in `HirToMir`. Used by the
    /// executor to size the call frame in one allocation rather than
    /// growing it incrementally. `0` means "no slot resolution was
    /// performed; fall back to name-based scope lookup."
    pub local_count: u32,
}

/// A function parameter at the MIR level.
///
/// Parameters carry their type annotation name and optional default value.
/// For lambda-lifted closures, capture parameters appear first with type
/// `"any"` (type-erased at MIR level).
#[derive(Debug, Clone)]
pub struct MirParam {
    /// Parameter name.
    pub name: String,
    /// Type annotation name (e.g., `"i64"`, `"f64"`, `"any"`).
    pub ty_name: String,
    /// Optional default value expression for this parameter.
    pub default: Option<MirExpr>,
    /// Variadic parameter: collects remaining args into an array.
    pub is_variadic: bool,
}

impl MirFunction {
    /// Build the CFG representation from the tree-form body.
    /// Stores the result in `cfg_body`.
    pub fn build_cfg(&mut self) {
        let cfg = cfg::CfgBuilder::build(&self.body);
        self.cfg_body = Some(cfg);
    }

    /// Return a reference to the CFG body, building it on demand if needed.
    ///
    /// Subsequent calls reuse the cached CFG. Prefer [`build_cfg`](Self::build_cfg)
    /// if you need to force a rebuild.
    pub fn cfg(&mut self) -> &cfg::MirCfg {
        if self.cfg_body.is_none() {
            self.build_cfg();
        }
        self.cfg_body.as_ref().unwrap()
    }
}

impl MirProgram {
    /// Build CFG for all functions in this program.
    pub fn build_all_cfgs(&mut self) {
        for func in &mut self.functions {
            func.build_cfg();
        }
    }
}

/// The body of a MIR function — a list of MIR statements.
/// In Milestone 2.0 we use a simplified tree-form (not full CFG with basic
/// blocks). This is extended to a proper CFG in Milestone 2.2+ for pattern
/// matching compilation.
#[derive(Debug, Clone)]
pub struct MirBody {
    pub stmts: Vec<MirStmt>,
    pub result: Option<Box<MirExpr>>,
}

// ---------------------------------------------------------------------------
// Statements
// ---------------------------------------------------------------------------

/// A MIR statement.
///
/// Statements represent side-effecting or control-flow operations in the
/// tree-form MIR body. In the CFG representation, control-flow statements
/// (`If`, `While`, `Break`, `Continue`) are compiled into basic block
/// terminators and edges.
#[derive(Debug, Clone)]
pub enum MirStmt {
    /// Variable binding: `let [mut] name = init;`
    ///
    /// The [`alloc_hint`](AllocHint) is populated by escape analysis after
    /// lowering to guide allocation strategy.
    Let {
        /// Binding name.
        name: String,
        /// Whether the binding is mutable.
        mutable: bool,
        /// Initializer expression.
        init: MirExpr,
        /// Escape analysis annotation. `None` before analysis runs.
        alloc_hint: Option<AllocHint>,
        /// Tier-0 perf (T0-b Stage 3): statically resolved frame slot for
        /// this binding, populated by the slot-resolution pass in
        /// `HirToMir`. `Some(slot)` when slot resolution was active for
        /// the enclosing function (the executor writes
        /// `frame[base + slot] = init_value`); `None` otherwise (the
        /// executor falls back to `self.define(name, val)` for `__main`,
        /// lambda-lifted closure bodies, and match arm bodies).
        slot: Option<u32>,
    },
    /// A standalone expression statement (e.g., function call, assignment).
    Expr(MirExpr),
    /// Conditional statement: `if cond { then } [else { else_ }]`.
    If {
        /// Condition expression (must evaluate to a boolean).
        cond: MirExpr,
        /// Body executed when the condition is true.
        then_body: MirBody,
        /// Optional body executed when the condition is false.
        else_body: Option<MirBody>,
    },
    /// While loop: `while cond { body }`.
    While {
        /// Loop condition expression.
        cond: MirExpr,
        /// Loop body.
        body: MirBody,
    },
    /// Return from the current function with an optional value.
    Return(Option<MirExpr>),
    /// Break out of the innermost enclosing loop.
    Break,
    /// Continue to the next iteration of the innermost enclosing loop.
    Continue,
    /// A `nogc { ... }` block where GC-triggering operations are forbidden.
    ///
    /// Verified by [`nogc_verify::verify_nogc`].
    NoGcBlock(MirBody),
}

// ---------------------------------------------------------------------------
// Expressions
// ---------------------------------------------------------------------------

/// A MIR expression node.
///
/// Wraps a [`MirExprKind`] discriminant. All MIR expressions are trees
/// (no sharing / DAG structure).
#[derive(Debug, Clone)]
pub struct MirExpr {
    /// The kind of this expression.
    pub kind: MirExprKind,
}

/// The discriminant for a MIR expression.
///
/// Covers literals, variables, operators, control flow, pattern matching,
/// closures, linalg opcodes, and container constructors. Each variant
/// corresponds to a distinct runtime operation in both the tree-walk
/// interpreter (`cjc-eval`) and the MIR executor (`cjc-mir-exec`).
#[derive(Debug, Clone)]
pub enum MirExprKind {
    /// 64-bit signed integer literal.
    IntLit(i64),
    /// 64-bit IEEE 754 floating-point literal.
    FloatLit(f64),
    /// Boolean literal (`true` or `false`).
    BoolLit(bool),
    /// UTF-8 string literal.
    StringLit(String),
    /// Byte string literal (`b"..."`).
    ByteStringLit(Vec<u8>),
    /// Single byte character literal (`b'x'`).
    ByteCharLit(u8),
    /// Raw string literal (`r"..."`).
    RawStringLit(String),
    /// Raw byte string literal (`rb"..."`).
    RawByteStringLit(Vec<u8>),
    /// Regex literal with pattern and flags.
    RegexLit {
        /// The regex pattern string.
        pattern: String,
        /// Regex flags (e.g., `"gi"`).
        flags: String,
    },
    /// Tensor literal: a 2D grid of expressions (rows x columns).
    TensorLit {
        /// Each inner `Vec` is one row of the tensor.
        rows: Vec<Vec<MirExpr>>,
    },
    /// NA (missing value) literal.
    NaLit,
    /// Variable reference by name (unresolved fallback path).
    ///
    /// Used for closures, captured variables, top-level/global references,
    /// and any case where the slot-resolution pass in `HirToMir` couldn't
    /// statically determine a slot. The executor falls back to walking
    /// the scope chain by name for these.
    Var(String),
    /// Tier-0 fast-path: variable reference resolved to a flat slot
    /// index into the current call frame.
    ///
    /// Emitted by `HirToMir` when the variable refers to a function-local
    /// binding (parameter or `let`) and the slot was resolvable
    /// statically. The executor reads directly from `frame[slot]` without
    /// touching the scope chain. The `name` field is retained for
    /// debugging and for the `MirExpr` printer; runtime dispatch uses
    /// `slot` only.
    ///
    /// See ADR-... (Tier-0 perf work) for the design rationale.
    VarLocal {
        /// Original binding name (debugging / printer use only).
        name: String,
        /// 0-indexed slot in the current call frame.
        /// `slot < MirFunction::local_count` is an invariant maintained
        /// by the lowering pass.
        slot: u32,
    },
    /// Binary operation.
    /// Binary operation.
    Binary {
        /// The binary operator.
        op: BinOp,
        /// Left-hand operand.
        left: Box<MirExpr>,
        /// Right-hand operand.
        right: Box<MirExpr>,
    },
    /// Unary operation (negation, logical not, bitwise not).
    Unary {
        /// The unary operator.
        op: UnaryOp,
        /// The operand.
        operand: Box<MirExpr>,
    },
    /// Function or closure call.
    Call {
        /// The callee expression (usually a [`Var`](MirExprKind::Var) or
        /// [`Field`](MirExprKind::Field) for method calls).
        callee: Box<MirExpr>,
        /// Positional arguments.
        args: Vec<MirExpr>,
    },
    /// Field access: `object.name`.
    Field {
        /// The object being accessed.
        object: Box<MirExpr>,
        /// Field name.
        name: String,
    },
    /// Single-index access: `object[index]`.
    Index {
        /// The collection being indexed.
        object: Box<MirExpr>,
        /// The index expression.
        index: Box<MirExpr>,
    },
    /// Multi-dimensional index access: `object[i, j, ...]`.
    MultiIndex {
        /// The collection being indexed.
        object: Box<MirExpr>,
        /// Index expressions for each dimension.
        indices: Vec<MirExpr>,
    },
    /// Assignment: `target = value`.
    Assign {
        /// Assignment target (variable, field, or index expression).
        target: Box<MirExpr>,
        /// Value being assigned.
        value: Box<MirExpr>,
    },
    /// Block expression: evaluates a [`MirBody`] and returns its result.
    Block(MirBody),
    /// Struct literal: `Name { field1: expr1, field2: expr2, ... }`.
    StructLit {
        /// Struct type name.
        name: String,
        /// Field initializers as `(name, value)` pairs.
        fields: Vec<(String, MirExpr)>,
    },
    /// Array literal: `[expr1, expr2, ...]`.
    ArrayLit(Vec<MirExpr>),
    /// Column reference in a data DSL context (e.g., `col("name")`).
    Col(String),
    /// Lambda expression (non-capturing).
    Lambda {
        /// Lambda parameters.
        params: Vec<MirParam>,
        /// Lambda body expression.
        body: Box<MirExpr>,
    },
    /// Create a closure: captures + a reference to the lifted function.
    /// At runtime, evaluates each capture expression and bundles them with
    /// the function name into a Closure value.
    MakeClosure {
        /// Name of the lambda-lifted top-level function.
        fn_name: String,
        /// Expressions that produce the captured values (evaluated at closure
        /// creation time). Order matches the extra leading params of the
        /// lifted function.
        captures: Vec<MirExpr>,
    },
    /// If expression: `if cond { then } [else { else_ }]`.
    ///
    /// Used as both a statement and an expression (the branch bodies can
    /// produce values).
    If {
        /// Condition expression.
        cond: Box<MirExpr>,
        /// Body evaluated when the condition is true.
        then_body: MirBody,
        /// Optional body evaluated when the condition is false.
        else_body: Option<MirBody>,
    },
    /// Match expression compiled as a decision tree.
    /// Each arm is tried in order; first matching arm's body is evaluated.
    Match {
        /// The value being matched against.
        scrutinee: Box<MirExpr>,
        /// Match arms in order of priority.
        arms: Vec<MirMatchArm>,
    },
    /// Enum variant literal constructor: `EnumName::Variant(fields...)`.
    VariantLit {
        /// Enum type name.
        enum_name: String,
        /// Variant name.
        variant: String,
        /// Positional field values.
        fields: Vec<MirExpr>,
    },
    /// Tuple literal: `(expr1, expr2, ...)`.
    TupleLit(Vec<MirExpr>),
    /// LU decomposition opcode.
    LinalgLU {
        /// Matrix operand.
        operand: Box<MirExpr>,
    },
    /// QR decomposition opcode.
    LinalgQR {
        /// Matrix operand.
        operand: Box<MirExpr>,
    },
    /// Cholesky decomposition opcode.
    LinalgCholesky {
        /// Matrix operand (must be symmetric positive-definite).
        operand: Box<MirExpr>,
    },
    /// Matrix inverse opcode.
    LinalgInv {
        /// Matrix operand.
        operand: Box<MirExpr>,
    },
    /// Broadcast a tensor to a target shape (zero-copy view with stride=0).
    Broadcast {
        /// Tensor operand to broadcast.
        operand: Box<MirExpr>,
        /// Target shape dimensions.
        target_shape: Vec<MirExpr>,
    },
    /// Unit/void value (no meaningful result).
    Void,
}

// ---------------------------------------------------------------------------
// Match / Pattern types (MIR level)
// ---------------------------------------------------------------------------

/// A match arm at MIR level: pattern + body.
#[derive(Debug, Clone)]
pub struct MirMatchArm {
    pub pattern: MirPattern,
    pub body: MirBody,
}

/// A pattern at MIR level.
#[derive(Debug, Clone)]
pub enum MirPattern {
    /// Wildcard: matches anything, binds nothing.
    Wildcard,
    /// Binding: matches anything, binds the value to a name.
    ///
    /// `slot` is populated by the slot-resolution pass in `HirToMir`
    /// (T0-b Stage 4). `Some(slot)` when the binding is inside a
    /// function whose body is slot-resolved (regular fn bodies, closure
    /// bodies). The executor writes both `frame[base + slot] = value`
    /// AND `self.define(name, value)` when binding. `None` for patterns
    /// outside any slot-resolved function (currently never -- match is
    /// only valid inside a function -- but kept for symmetry with the
    /// `MirStmt::Let.slot` rule).
    Binding { name: String, slot: Option<u32> },
    /// Literal patterns
    LitInt(i64),
    LitFloat(f64),
    LitBool(bool),
    LitString(String),
    /// Tuple destructuring
    Tuple(Vec<MirPattern>),
    /// Struct destructuring
    Struct {
        name: String,
        fields: Vec<(String, MirPattern)>,
    },
    /// Enum variant pattern
    Variant {
        enum_name: String,
        variant: String,
        fields: Vec<MirPattern>,
    },
}

// ===========================================================================
// HIR -> MIR Lowering
// ===========================================================================

use cjc_hir::*;

/// Lowers HIR into MIR.
///
/// Performs a single-pass traversal of the [`HirProgram`], converting each
/// HIR item into its MIR equivalent. During lowering:
///
/// - Top-level statements are collected into a synthetic `__main` function.
/// - Closures are lambda-lifted into top-level functions with extra leading
///   parameters for captured values, and replaced with [`MirExprKind::MakeClosure`].
/// - Impl methods are flattened to qualified `Target.method` names.
/// - Traits produce no MIR output (metadata only).
///
/// # Usage
///
/// ```rust,ignore
/// let mut lowering = HirToMir::new();
/// let mir_program = lowering.lower_program(&hir_program);
/// ```
pub struct HirToMir {
    next_fn_id: u32,
    next_lambda_id: u32,
    /// Lambda-lifted functions accumulated during lowering.
    /// These are appended to the MirProgram's function list.
    lifted_functions: Vec<MirFunction>,

    // ---------- Tier-0 perf (T0-b Stage 2) slot-resolution state ----------
    //
    // These fields are active only inside `lower_fn`. The synthetic `__main`
    // and lambda-lifted closures are NOT slot-resolved in Stage 2 (they keep
    // `local_count = 0` and emit `MirExprKind::Var` for every reference, which
    // makes the executor fall back to name-based scope lookup).
    /// Stack of lexical scopes mapping `name -> slot` for the current
    /// function being lowered. `BTreeMap` (not `HashMap`) preserves
    /// deterministic iteration if it ever leaks into output.
    scope_stack: Vec<BTreeMap<String, u32>>,
    /// Monotonic per-function slot counter. Never decrements when scopes
    /// pop, so a function with `if { let x } else { let y }` consumes two
    /// frame slots (one each). This trades a small space cost for a much
    /// simpler implementation.
    slot_counter: u32,
    /// When `false`, `Var` references stay as `Var(name)` instead of
    /// becoming `VarLocal { name, slot }`. Used to skip:
    /// - the `__main` synthetic function body
    /// - lambda-lifted closure bodies (deferred to Stage 4)
    /// - match arm bodies (pattern-bound names are not tracked here;
    ///   deferred to Stage 4. Emitting VarLocal with the outer slot would
    ///   work in Stage 2 (executor still does name lookup) but would bake
    ///   in a latent bug for Stage 3's frame-based reads.)
    slot_resolution_active: bool,
}

/// Snapshot of the slot tracker that can be saved / restored across a
/// nested lowering (closure body, match arm body, etc.).
#[derive(Debug)]
struct TrackerState {
    scope_stack: Vec<BTreeMap<String, u32>>,
    slot_counter: u32,
    slot_resolution_active: bool,
}

impl HirToMir {
    /// Create a new HIR-to-MIR lowering pass with fresh ID counters.
    pub fn new() -> Self {
        Self {
            next_fn_id: 0,
            next_lambda_id: 0,
            lifted_functions: Vec::new(),
            scope_stack: Vec::new(),
            slot_counter: 0,
            slot_resolution_active: false,
        }
    }

    fn fresh_fn_id(&mut self) -> MirFnId {
        let id = MirFnId(self.next_fn_id);
        self.next_fn_id += 1;
        id
    }

    fn fresh_lambda_name(&mut self) -> String {
        let name = format!("__closure_{}", self.next_lambda_id);
        self.next_lambda_id += 1;
        name
    }

    // -- Slot tracker helpers (Tier-0 perf, T0-b Stage 2) ------------------

    /// Begin tracking slots for a new function. Clears any previous state,
    /// pushes the initial scope, and assigns each parameter a sequential
    /// slot starting at 0.
    fn enter_function(&mut self, params: &[MirParam]) {
        self.scope_stack.clear();
        self.scope_stack.push(BTreeMap::new());
        self.slot_counter = 0;
        self.slot_resolution_active = true;
        for p in params {
            self.define_local(&p.name);
        }
    }

    /// Finish tracking slots for the current function and return the total
    /// slot count (= `MirFunction.local_count`). Resets the tracker.
    fn exit_function(&mut self) -> u32 {
        let count = self.slot_counter;
        self.scope_stack.clear();
        self.slot_counter = 0;
        self.slot_resolution_active = false;
        count
    }

    fn push_scope(&mut self) {
        if self.slot_resolution_active {
            self.scope_stack.push(BTreeMap::new());
        }
    }

    fn pop_scope(&mut self) {
        if self.slot_resolution_active {
            self.scope_stack.pop();
        }
    }

    /// Register `name` as a local in the top scope, assigning it the next
    /// available slot. Returns the assigned slot.
    fn define_local(&mut self, name: &str) -> u32 {
        let slot = self.slot_counter;
        if let Some(top) = self.scope_stack.last_mut() {
            top.insert(name.to_string(), slot);
        }
        self.slot_counter += 1;
        slot
    }

    /// Walk the scope stack from innermost outward, returning the slot for
    /// `name` if it is bound as a local. Returns `None` for top-level
    /// names, captured variables, function names, etc. — these emit
    /// `MirExprKind::Var(name)` and rely on the executor's scope-chain
    /// fallback.
    fn resolve_local(&self, name: &str) -> Option<u32> {
        if !self.slot_resolution_active {
            return None;
        }
        for scope in self.scope_stack.iter().rev() {
            if let Some(&slot) = scope.get(name) {
                return Some(slot);
            }
        }
        None
    }

    /// Snapshot the tracker so a nested lowering can run with its own
    /// (or disabled) state.
    fn save_tracker(&mut self) -> TrackerState {
        TrackerState {
            scope_stack: std::mem::take(&mut self.scope_stack),
            slot_counter: self.slot_counter,
            slot_resolution_active: self.slot_resolution_active,
        }
    }

    /// Restore a previously saved tracker state.
    fn restore_tracker(&mut self, saved: TrackerState) {
        self.scope_stack = saved.scope_stack;
        self.slot_counter = saved.slot_counter;
        self.slot_resolution_active = saved.slot_resolution_active;
    }

    /// Lower a HIR program to MIR.
    pub fn lower_program(&mut self, hir: &HirProgram) -> MirProgram {
        let mut functions = Vec::new();
        let mut struct_defs = Vec::new();
        let mut enum_defs = Vec::new();
        let mut main_stmts: Vec<MirStmt> = Vec::new();

        for item in &hir.items {
            match item {
                HirItem::Fn(f) => {
                    functions.push(self.lower_fn(f));
                }
                HirItem::Struct(s) => {
                    struct_defs.push(MirStructDef {
                        name: s.name.clone(),
                        fields: s.fields.clone(),
                        is_record: false,
                        vis: s.vis,
                    });
                }
                HirItem::Class(c) => {
                    struct_defs.push(MirStructDef {
                        name: c.name.clone(),
                        fields: c.fields.clone(),
                        is_record: false,
                        vis: c.vis,
                    });
                }
                HirItem::Record(r) => {
                    struct_defs.push(MirStructDef {
                        name: r.name.clone(),
                        fields: r.fields.clone(),
                        is_record: true,
                        vis: r.vis,
                    });
                }
                HirItem::Enum(e) => {
                    enum_defs.push(MirEnumDef {
                        name: e.name.clone(),
                        variants: e
                            .variants
                            .iter()
                            .map(|v| MirVariantDef {
                                name: v.name.clone(),
                                fields: v.fields.clone(),
                            })
                            .collect(),
                    });
                }
                HirItem::Let(l) => {
                    // __main has no slot tracker (Stage 2 left __main on
                    // name fallback). slot stays None; the executor will
                    // route this through self.define(name, val).
                    main_stmts.push(MirStmt::Let {
                        name: l.name.clone(),
                        mutable: l.mutable,
                        init: self.lower_expr(&l.init),
                        alloc_hint: None,
                        slot: None,
                    });
                }
                HirItem::Stmt(s) => {
                    main_stmts.push(self.lower_stmt(s));
                }
                HirItem::Impl(i) => {
                    for method in &i.methods {
                        // Register as qualified name: Target.method
                        let mut mir_fn = self.lower_fn(method);
                        mir_fn.name = format!("{}.{}", i.target, method.name);
                        functions.push(mir_fn);
                    }
                }
                HirItem::Trait(_) => {
                    // Traits are metadata only; no MIR output
                }
            }
        }

        // Create __main entry function from top-level statements
        let main_id = self.fresh_fn_id();
        functions.push(MirFunction {
            id: main_id,
            name: "__main".to_string(),
            type_params: vec![],
            params: vec![],
            return_type: None,
            body: MirBody {
                stmts: main_stmts,
                result: None,
            },
            is_nogc: false,
            cfg_body: None,
            decorators: vec![],
            vis: Visibility::Private,
            local_count: 0,
        });

        // Append all lambda-lifted functions
        functions.append(&mut self.lifted_functions);

        MirProgram {
            functions,
            struct_defs,
            enum_defs,
            entry: main_id,
        }
    }

    /// Lower a single HIR function definition to a [`MirFunction`].
    ///
    /// Assigns a fresh [`MirFnId`] and recursively lowers parameters, body
    /// statements, and the tail expression. Closures encountered within the
    /// body are lambda-lifted and accumulated in `self.lifted_functions`.
    pub fn lower_fn(&mut self, f: &HirFn) -> MirFunction {
        let id = self.fresh_fn_id();

        // Param defaults are evaluated AT CALL SITES in the caller's scope,
        // not inside the callee's frame. Lower them with the outer tracker
        // state (or whatever state is active when `lower_fn` is called).
        // We snapshot the tracker so `enter_function` below can claim a
        // fresh slot space for the callee body.
        let saved = self.save_tracker();

        let params: Vec<MirParam> = f
            .params
            .iter()
            .map(|p| MirParam {
                name: p.name.clone(),
                ty_name: p.ty_name.clone(),
                default: p.default.as_ref().map(|d| self.lower_expr(d)),
                is_variadic: p.is_variadic,
            })
            .collect();

        // Tier-0 perf (Stage 2): begin slot tracking for this function body.
        // Parameters are assigned slots 0..N in declaration order.
        self.enter_function(&params);
        let body = self.lower_block(&f.body);
        let local_count = self.exit_function();

        // Restore the outer tracker state (typically inactive for top-level
        // fns; may be active when `lower_fn` is invoked from an Impl method
        // iteration after a closure restore -- belt and suspenders).
        self.restore_tracker(saved);

        MirFunction {
            id,
            name: f.name.clone(),
            type_params: f.type_params.clone(),
            params,
            return_type: f.return_type.clone(),
            body,
            is_nogc: f.is_nogc,
            cfg_body: None,
            decorators: f.decorators.clone(),
            vis: f.vis,
            local_count,
        }
    }

    fn lower_block(&mut self, block: &HirBlock) -> MirBody {
        // Tier-0 perf: each block boundary opens a new lexical scope so that
        // shadowing `let` bindings consume distinct slots. The slot counter
        // does NOT reset on pop -- a function with `if { let x } else { let y }`
        // consumes two slots, not one. See `define_local` doc.
        self.push_scope();
        let stmts = block.stmts.iter().map(|s| self.lower_stmt(s)).collect();
        let result = block.expr.as_ref().map(|e| Box::new(self.lower_expr(e)));
        self.pop_scope();
        MirBody { stmts, result }
    }

    fn lower_stmt(&mut self, stmt: &HirStmt) -> MirStmt {
        match &stmt.kind {
            HirStmtKind::Let {
                name,
                mutable,
                init,
                ..
            } => {
                // Lower the initializer BEFORE binding `name` so the RHS
                // resolves to the outer (not the new) binding for shadowing
                // cases like `let x = x + 1`.
                let init = self.lower_expr(init);
                // Tier-0 perf (Stage 3): record the slot the executor will
                // write into. `Some` when slot resolution is active for
                // this function; `None` otherwise (e.g. inside match arm
                // bodies or closure bodies).
                let slot = if self.slot_resolution_active {
                    Some(self.define_local(name))
                } else {
                    None
                };
                MirStmt::Let {
                    name: name.clone(),
                    mutable: *mutable,
                    init,
                    alloc_hint: None,
                    slot,
                }
            }
            HirStmtKind::Expr(e) => MirStmt::Expr(self.lower_expr(e)),
            HirStmtKind::If(if_expr) => self.lower_if_stmt(if_expr),
            HirStmtKind::While { cond, body } => MirStmt::While {
                cond: self.lower_expr(cond),
                body: self.lower_block(body),
            },
            HirStmtKind::Return(e) => {
                MirStmt::Return(e.as_ref().map(|ex| self.lower_expr(ex)))
            }
            HirStmtKind::Break => MirStmt::Break,
            HirStmtKind::Continue => MirStmt::Continue,
            HirStmtKind::NoGcBlock(block) => MirStmt::NoGcBlock(self.lower_block(block)),
        }
    }

    /// Lower a HIR `if` expression to a [`MirStmt::If`].
    ///
    /// Nested `else if` chains are recursively lowered into nested
    /// [`MirStmt::If`] nodes wrapped in a [`MirBody`].
    pub fn lower_if_stmt(&mut self, if_expr: &HirIfExpr) -> MirStmt {
        let cond = self.lower_expr(&if_expr.cond);
        let then_body = self.lower_block(&if_expr.then_block);
        let else_body = if_expr.else_branch.as_ref().map(|eb| match eb {
            HirElseBranch::ElseIf(elif) => {
                // Nested if-else becomes a block containing the if stmt
                let nested = self.lower_if_stmt(elif);
                MirBody {
                    stmts: vec![nested],
                    result: None,
                }
            }
            HirElseBranch::Else(block) => self.lower_block(block),
        });
        MirStmt::If {
            cond,
            then_body,
            else_body,
        }
    }

    /// Lower a HIR expression to a [`MirExpr`].
    ///
    /// Handles all HIR expression kinds including closures (lambda-lifted),
    /// match expressions (compiled to [`MirExprKind::Match`] decision trees),
    /// and if-expressions.
    pub fn lower_expr(&mut self, expr: &HirExpr) -> MirExpr {
        let kind = match &expr.kind {
            HirExprKind::IntLit(v) => MirExprKind::IntLit(*v),
            HirExprKind::FloatLit(v) => MirExprKind::FloatLit(*v),
            HirExprKind::BoolLit(b) => MirExprKind::BoolLit(*b),
            HirExprKind::NaLit => MirExprKind::NaLit,
            HirExprKind::StringLit(s) => MirExprKind::StringLit(s.clone()),
            HirExprKind::ByteStringLit(bytes) => MirExprKind::ByteStringLit(bytes.clone()),
            HirExprKind::ByteCharLit(b) => MirExprKind::ByteCharLit(*b),
            HirExprKind::RawStringLit(s) => MirExprKind::RawStringLit(s.clone()),
            HirExprKind::RawByteStringLit(bytes) => MirExprKind::RawByteStringLit(bytes.clone()),
            HirExprKind::RegexLit { pattern, flags } => MirExprKind::RegexLit { pattern: pattern.clone(), flags: flags.clone() },
            HirExprKind::TensorLit { rows } => {
                let mir_rows = rows.iter().map(|row| {
                    row.iter().map(|e| self.lower_expr(e)).collect()
                }).collect();
                MirExprKind::TensorLit { rows: mir_rows }
            }
            HirExprKind::Var(name) => {
                // Tier-0 perf (Stage 2): if `name` is bound as a local
                // (parameter or `let`) in the current function, emit the
                // slot-resolved `VarLocal` variant. Otherwise fall back to
                // `Var(name)` (top-level function, captured variable,
                // pattern binding, or any reference outside an active
                // tracker).
                match self.resolve_local(name) {
                    Some(slot) => MirExprKind::VarLocal {
                        name: name.clone(),
                        slot,
                    },
                    None => MirExprKind::Var(name.clone()),
                }
            }
            HirExprKind::Binary { op, left, right } => MirExprKind::Binary {
                op: *op,
                left: Box::new(self.lower_expr(left)),
                right: Box::new(self.lower_expr(right)),
            },
            HirExprKind::Unary { op, operand } => MirExprKind::Unary {
                op: *op,
                operand: Box::new(self.lower_expr(operand)),
            },
            HirExprKind::Call { callee, args } => MirExprKind::Call {
                callee: Box::new(self.lower_expr(callee)),
                args: args.iter().map(|a| self.lower_expr(a)).collect(),
            },
            HirExprKind::Field { object, name } => MirExprKind::Field {
                object: Box::new(self.lower_expr(object)),
                name: name.clone(),
            },
            HirExprKind::Index { object, index } => MirExprKind::Index {
                object: Box::new(self.lower_expr(object)),
                index: Box::new(self.lower_expr(index)),
            },
            HirExprKind::MultiIndex { object, indices } => MirExprKind::MultiIndex {
                object: Box::new(self.lower_expr(object)),
                indices: indices.iter().map(|i| self.lower_expr(i)).collect(),
            },
            HirExprKind::Assign { target, value } => MirExprKind::Assign {
                target: Box::new(self.lower_expr(target)),
                value: Box::new(self.lower_expr(value)),
            },
            HirExprKind::Block(block) => MirExprKind::Block(self.lower_block(block)),
            HirExprKind::StructLit { name, fields } => MirExprKind::StructLit {
                name: name.clone(),
                fields: fields
                    .iter()
                    .map(|(n, e)| (n.clone(), self.lower_expr(e)))
                    .collect(),
            },
            HirExprKind::ArrayLit(elems) => {
                MirExprKind::ArrayLit(elems.iter().map(|e| self.lower_expr(e)).collect())
            }
            HirExprKind::Col(name) => MirExprKind::Col(name.clone()),
            HirExprKind::Lambda { params, body } => MirExprKind::Lambda {
                params: params
                    .iter()
                    .map(|p| MirParam {
                        name: p.name.clone(),
                        ty_name: p.ty_name.clone(),
                        default: p.default.as_ref().map(|d| self.lower_expr(d)),
                        is_variadic: p.is_variadic,
                    })
                    .collect(),
                body: Box::new(self.lower_expr(body)),
            },
            HirExprKind::Closure {
                params,
                body,
                captures,
            } => {
                // Lambda-lift: create a top-level function with extra
                // leading parameters for the captured values.
                let lifted_name = self.fresh_lambda_name();
                let lifted_id = self.fresh_fn_id();

                // Build params: captures first, then the original params.
                // Default expressions on params are evaluated in the OUTER
                // (call-site) scope, so lower them BEFORE saving the
                // tracker for the closure body.
                let mut lifted_params: Vec<MirParam> = captures
                    .iter()
                    .map(|c| MirParam {
                        name: c.name.clone(),
                        ty_name: "any".to_string(), // Type erasure at MIR level
                        default: None,
                        is_variadic: false,
                    })
                    .collect();
                for p in params {
                    lifted_params.push(MirParam {
                        name: p.name.clone(),
                        ty_name: p.ty_name.clone(),
                        default: p.default.as_ref().map(|d| self.lower_expr(d)),
                        is_variadic: p.is_variadic,
                    });
                }

                // The capture expressions are simple Var references in the
                // OUTER scope. Slot-resolve them while the outer tracker
                // is still active -- `MakeClosure` evaluates these every
                // time it runs to bundle them with the lifted function name.
                let capture_exprs: Vec<MirExpr> = captures
                    .iter()
                    .map(|c| {
                        let kind = match self.resolve_local(&c.name) {
                            Some(slot) => MirExprKind::VarLocal {
                                name: c.name.clone(),
                                slot,
                            },
                            None => MirExprKind::Var(c.name.clone()),
                        };
                        MirExpr { kind }
                    })
                    .collect();

                // Tier-0 perf (Stage 4): slot-resolve the lifted body just
                // like a regular function. The lifted params (captures
                // first, then original) get slots 0..N in declaration
                // order; lets inside the body get slots after. The
                // executor's `call_function` path pushes a frame on entry
                // and binds args (including captures, which the
                // `MakeClosure` mechanism prepends) into the frame slots.
                //
                // Snapshot the outer tracker so the closure body's slot
                // space is fresh -- nested closures and the outer fn
                // each get their own monotonic counter.
                let saved = self.save_tracker();
                self.enter_function(&lifted_params);

                let lifted_body = MirBody {
                    stmts: vec![],
                    result: Some(Box::new(self.lower_expr(body))),
                };

                let local_count = self.exit_function();
                self.restore_tracker(saved);

                self.lifted_functions.push(MirFunction {
                    id: lifted_id,
                    name: lifted_name.clone(),
                    type_params: vec![],
                    params: lifted_params,
                    return_type: None,
                    body: lifted_body,
                    is_nogc: false,
                    cfg_body: None,
                    decorators: vec![],
                    vis: Visibility::Private,
                    local_count,
                });

                MirExprKind::MakeClosure {
                    fn_name: lifted_name,
                    captures: capture_exprs,
                }
            }
            HirExprKind::Match { scrutinee, arms } => {
                // Scrutinee is evaluated in the OUTER scope -- lower with
                // tracker still active so it sees outer locals.
                let mir_scrutinee = Box::new(self.lower_expr(scrutinee));

                // Tier-0 perf (Stage 4): each arm opens its own lexical
                // scope. `lower_pattern` walks the pattern and assigns
                // a slot to every `Binding` via `define_local`, recording
                // the name -> slot mapping in the tracker so the arm
                // body's references resolve to those slots. Outer-scope
                // locals still resolve to outer slots. After the body is
                // lowered, the scope pops so the next arm starts fresh
                // (the slot counter is monotonic, so sibling arms get
                // distinct slot ranges -- same trade-off as sibling
                // `if`/`else` branches).
                let mir_arms = arms
                    .iter()
                    .map(|arm| {
                        self.push_scope();
                        let pattern = self.lower_pattern(&arm.pattern);
                        let body = MirBody {
                            stmts: vec![],
                            result: Some(Box::new(self.lower_expr(&arm.body))),
                        };
                        self.pop_scope();
                        MirMatchArm { pattern, body }
                    })
                    .collect();

                MirExprKind::Match {
                    scrutinee: mir_scrutinee,
                    arms: mir_arms,
                }
            }
            HirExprKind::TupleLit(elems) => {
                MirExprKind::TupleLit(elems.iter().map(|e| self.lower_expr(e)).collect())
            }
            HirExprKind::VariantLit {
                enum_name,
                variant,
                fields,
            } => MirExprKind::VariantLit {
                enum_name: enum_name.clone(),
                variant: variant.clone(),
                fields: fields.iter().map(|f| self.lower_expr(f)).collect(),
            },
            HirExprKind::If { cond, then_block, else_branch } => {
                let mir_cond = Box::new(self.lower_expr(cond));
                let mir_then = self.lower_block(then_block);
                let mir_else = else_branch.as_ref().map(|eb| match eb {
                    HirElseBranch::ElseIf(elif) => {
                        // Nested else-if: lower as MirStmt::If inside a MirBody
                        let nested = self.lower_if_stmt(elif);
                        MirBody {
                            stmts: vec![nested],
                            result: None,
                        }
                    }
                    HirElseBranch::Else(block) => self.lower_block(block),
                });
                MirExprKind::If {
                    cond: mir_cond,
                    then_body: mir_then,
                    else_body: mir_else,
                }
            }
            HirExprKind::Void => MirExprKind::Void,
        };
        MirExpr { kind }
    }

    /// Lower an HIR pattern to MIR, assigning slot indices to every
    /// `Binding` pattern found anywhere in the tree (recurses through
    /// `Tuple`, `Struct`, `Variant` patterns).
    ///
    /// Tier-0 perf (Stage 4): when slot resolution is active for the
    /// enclosing function, every `Binding` slot is `Some(slot)` and
    /// the slot tracker's scope_stack records the name -> slot mapping
    /// so subsequent variable references in the arm body resolve
    /// correctly. When slot resolution is inactive (only happens if a
    /// match expression is somehow encountered outside a fn body),
    /// bindings get `slot: None` and the executor falls back to
    /// name-only definition.
    ///
    /// IMPORTANT: this must be called AFTER `push_scope` and BEFORE
    /// the arm body is lowered, so the bindings are visible to the
    /// arm body's references via the scope_stack lookup.
    fn lower_pattern(&mut self, pat: &HirPattern) -> MirPattern {
        match &pat.kind {
            HirPatternKind::Wildcard => MirPattern::Wildcard,
            HirPatternKind::Binding(name) => {
                let slot = if self.slot_resolution_active {
                    Some(self.define_local(name))
                } else {
                    None
                };
                MirPattern::Binding {
                    name: name.clone(),
                    slot,
                }
            }
            HirPatternKind::LitInt(v) => MirPattern::LitInt(*v),
            HirPatternKind::LitFloat(v) => MirPattern::LitFloat(*v),
            HirPatternKind::LitBool(b) => MirPattern::LitBool(*b),
            HirPatternKind::LitString(s) => MirPattern::LitString(s.clone()),
            HirPatternKind::Tuple(pats) => MirPattern::Tuple(
                pats.iter().map(|p| self.lower_pattern(p)).collect(),
            ),
            HirPatternKind::Struct { name, fields } => MirPattern::Struct {
                name: name.clone(),
                fields: fields
                    .iter()
                    .map(|f| (f.name.clone(), self.lower_pattern(&f.pattern)))
                    .collect(),
            },
            HirPatternKind::Variant {
                enum_name,
                variant,
                fields,
            } => MirPattern::Variant {
                enum_name: enum_name.clone(),
                variant: variant.clone(),
                fields: fields.iter().map(|f| self.lower_pattern(f)).collect(),
            },
        }
    }
}

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

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn hir_id(n: u32) -> HirId {
        HirId(n)
    }

    fn hir_int(v: i64) -> HirExpr {
        HirExpr {
            kind: HirExprKind::IntLit(v),
            hir_id: hir_id(0),
        }
    }

    fn hir_var(name: &str) -> HirExpr {
        HirExpr {
            kind: HirExprKind::Var(name.to_string()),
            hir_id: hir_id(0),
        }
    }

    #[test]
    fn test_lower_hir_literal() {
        let mut lowering = HirToMir::new();
        let hir = hir_int(42);
        let mir = lowering.lower_expr(&hir);
        assert!(matches!(mir.kind, MirExprKind::IntLit(42)));
    }

    #[test]
    fn test_lower_hir_binary() {
        let mut lowering = HirToMir::new();
        let hir = HirExpr {
            kind: HirExprKind::Binary {
                op: BinOp::Add,
                left: Box::new(hir_int(1)),
                right: Box::new(hir_int(2)),
            },
            hir_id: hir_id(0),
        };
        let mir = lowering.lower_expr(&hir);
        match &mir.kind {
            MirExprKind::Binary { op, .. } => assert_eq!(*op, BinOp::Add),
            _ => panic!("expected Binary"),
        }
    }

    #[test]
    fn test_lower_hir_fn() {
        let mut lowering = HirToMir::new();
        let hir_fn = HirFn {
            name: "add".to_string(),
            type_params: vec![],
            params: vec![
                HirParam {
                    name: "a".to_string(),
                    ty_name: "i64".to_string(),
                    default: None,
                    is_variadic: false,
                    hir_id: hir_id(1),
                },
                HirParam {
                    name: "b".to_string(),
                    ty_name: "i64".to_string(),
                    default: None,
                    is_variadic: false,
                    hir_id: hir_id(2),
                },
            ],
            return_type: Some("i64".to_string()),
            body: HirBlock {
                stmts: vec![],
                expr: Some(Box::new(HirExpr {
                    kind: HirExprKind::Binary {
                        op: BinOp::Add,
                        left: Box::new(hir_var("a")),
                        right: Box::new(hir_var("b")),
                    },
                    hir_id: hir_id(3),
                })),
                hir_id: hir_id(4),
            },
            is_nogc: false,
            hir_id: hir_id(5),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        };
        let mir_fn = lowering.lower_fn(&hir_fn);
        assert_eq!(mir_fn.name, "add");
        assert_eq!(mir_fn.params.len(), 2);
        assert!(mir_fn.body.result.is_some());
    }

    #[test]
    fn test_lower_hir_program_entry() {
        let mut lowering = HirToMir::new();
        let hir = HirProgram {
            items: vec![
                HirItem::Let(HirLetDecl {
                    name: "x".to_string(),
                    mutable: false,
                    ty_name: None,
                    init: hir_int(42),
                    hir_id: hir_id(0),
                }),
                HirItem::Fn(HirFn {
                    name: "f".to_string(),
                    type_params: vec![],
                    params: vec![],
                    return_type: None,
                    body: HirBlock {
                        stmts: vec![],
                        expr: Some(Box::new(hir_var("x"))),
                        hir_id: hir_id(1),
                    },
                    is_nogc: false,
                    hir_id: hir_id(2),
                    decorators: vec![],
                    vis: cjc_ast::Visibility::Private,
                }),
            ],
        };
        let mir = lowering.lower_program(&hir);
        // Should have: function 'f' + synthetic __main
        assert_eq!(mir.functions.len(), 2);
        let main = mir.functions.iter().find(|f| f.name == "__main").unwrap();
        assert_eq!(main.body.stmts.len(), 1); // the let x = 42
        assert_eq!(mir.entry, main.id);
    }

    #[test]
    fn test_lower_hir_if_stmt() {
        let mut lowering = HirToMir::new();
        let hir_if = HirIfExpr {
            cond: Box::new(HirExpr {
                kind: HirExprKind::BoolLit(true),
                hir_id: hir_id(0),
            }),
            then_block: HirBlock {
                stmts: vec![],
                expr: Some(Box::new(hir_int(1))),
                hir_id: hir_id(1),
            },
            else_branch: Some(HirElseBranch::Else(HirBlock {
                stmts: vec![],
                expr: Some(Box::new(hir_int(2))),
                hir_id: hir_id(2),
            })),
            hir_id: hir_id(3),
        };
        let mir_stmt = lowering.lower_if_stmt(&hir_if);
        match &mir_stmt {
            MirStmt::If {
                then_body,
                else_body,
                ..
            } => {
                assert!(then_body.result.is_some());
                assert!(else_body.is_some());
            }
            _ => panic!("expected If"),
        }
    }

    #[test]
    fn test_lower_struct_def() {
        let mut lowering = HirToMir::new();
        let hir = HirProgram {
            items: vec![HirItem::Struct(HirStructDef {
                name: "Point".to_string(),
                fields: vec![
                    ("x".to_string(), "f64".to_string()),
                    ("y".to_string(), "f64".to_string()),
                ],
                hir_id: hir_id(0),
                vis: cjc_ast::Visibility::Private,
            })],
        };
        let mir = lowering.lower_program(&hir);
        assert_eq!(mir.struct_defs.len(), 1);
        assert_eq!(mir.struct_defs[0].name, "Point");
        assert_eq!(mir.struct_defs[0].fields.len(), 2);
    }

    // -----------------------------------------------------------------
    // Tier-0 perf (T0-b Stage 2) slot-resolution tests
    // -----------------------------------------------------------------
    //
    // These tests pin down the lowering's slot assignment rules so future
    // refactors can't silently break them. The runtime behavior is covered
    // by the existing parity + workspace tests; this module only checks
    // the structure of the lowered MIR.

    /// Build a minimal `HirFn` from a body expression plus param list.
    fn mk_fn(name: &str, params: Vec<(&str, &str)>, body_expr: HirExpr) -> HirFn {
        HirFn {
            name: name.to_string(),
            type_params: vec![],
            params: params
                .into_iter()
                .map(|(n, t)| HirParam {
                    name: n.to_string(),
                    ty_name: t.to_string(),
                    default: None,
                    is_variadic: false,
                    hir_id: hir_id(0),
                })
                .collect(),
            return_type: None,
            body: HirBlock {
                stmts: vec![],
                expr: Some(Box::new(body_expr)),
                hir_id: hir_id(0),
            },
            is_nogc: false,
            hir_id: hir_id(0),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        }
    }

    #[test]
    fn t0b_stage2_params_get_sequential_slots() {
        // `fn f(a, b, c) { a + b + c }` -- a/b/c get slots 0/1/2;
        // local_count = 3; body emits VarLocal for every reference.
        let mut lowering = HirToMir::new();
        let body = HirExpr {
            kind: HirExprKind::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr {
                    kind: HirExprKind::Binary {
                        op: BinOp::Add,
                        left: Box::new(hir_var("a")),
                        right: Box::new(hir_var("b")),
                    },
                    hir_id: hir_id(0),
                }),
                right: Box::new(hir_var("c")),
            },
            hir_id: hir_id(0),
        };
        let hir_fn = mk_fn("f", vec![("a", "i64"), ("b", "i64"), ("c", "i64")], body);
        let mir_fn = lowering.lower_fn(&hir_fn);

        assert_eq!(mir_fn.local_count, 3, "three params -> three slots");

        // Walk the body looking for VarLocal references.
        fn collect_var_locals(expr: &MirExpr, out: &mut Vec<(String, u32)>) {
            match &expr.kind {
                MirExprKind::VarLocal { name, slot } => out.push((name.clone(), *slot)),
                MirExprKind::Binary { left, right, .. } => {
                    collect_var_locals(left, out);
                    collect_var_locals(right, out);
                }
                _ => {}
            }
        }
        let mut found = Vec::new();
        collect_var_locals(mir_fn.body.result.as_ref().unwrap(), &mut found);
        assert_eq!(
            found,
            vec![
                ("a".to_string(), 0),
                ("b".to_string(), 1),
                ("c".to_string(), 2),
            ],
            "params should slot-resolve to their declaration order"
        );
    }

    #[test]
    fn t0b_stage2_let_binding_gets_next_slot_after_params() {
        // `fn f(a) { let b = a; b }` -- a slot 0, b slot 1, local_count 2.
        let mut lowering = HirToMir::new();
        let let_stmt = HirStmt {
            kind: HirStmtKind::Let {
                name: "b".to_string(),
                mutable: false,
                ty_name: None,
                init: hir_var("a"),
            },
            hir_id: hir_id(0),
        };
        let hir_fn = HirFn {
            name: "f".to_string(),
            type_params: vec![],
            params: vec![HirParam {
                name: "a".to_string(),
                ty_name: "i64".to_string(),
                default: None,
                is_variadic: false,
                hir_id: hir_id(0),
            }],
            return_type: None,
            body: HirBlock {
                stmts: vec![let_stmt],
                expr: Some(Box::new(hir_var("b"))),
                hir_id: hir_id(0),
            },
            is_nogc: false,
            hir_id: hir_id(0),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        };
        let mir_fn = lowering.lower_fn(&hir_fn);
        assert_eq!(mir_fn.local_count, 2);

        // The Let's init expression should resolve `a` to slot 0.
        match &mir_fn.body.stmts[0] {
            MirStmt::Let { init, .. } => match &init.kind {
                MirExprKind::VarLocal { name, slot } => {
                    assert_eq!(name, "a");
                    assert_eq!(*slot, 0);
                }
                other => panic!("expected VarLocal for `a`, got {other:?}"),
            },
            other => panic!("expected Let stmt, got {other:?}"),
        }
        // The body result should resolve `b` to slot 1.
        match &mir_fn.body.result.as_ref().unwrap().kind {
            MirExprKind::VarLocal { name, slot } => {
                assert_eq!(name, "b");
                assert_eq!(*slot, 1);
            }
            other => panic!("expected VarLocal for `b`, got {other:?}"),
        }
    }

    #[test]
    fn t0b_stage2_let_rhs_resolves_to_outer_for_shadowing() {
        // `fn f(x) { let x = x + 1; x }` -- the init's `x` must resolve
        // to the PARAMETER's slot (0), not the new let's slot.
        let mut lowering = HirToMir::new();
        let let_stmt = HirStmt {
            kind: HirStmtKind::Let {
                name: "x".to_string(),
                mutable: false,
                ty_name: None,
                init: HirExpr {
                    kind: HirExprKind::Binary {
                        op: BinOp::Add,
                        left: Box::new(hir_var("x")),
                        right: Box::new(hir_int(1)),
                    },
                    hir_id: hir_id(0),
                },
            },
            hir_id: hir_id(0),
        };
        let hir_fn = HirFn {
            name: "f".to_string(),
            type_params: vec![],
            params: vec![HirParam {
                name: "x".to_string(),
                ty_name: "i64".to_string(),
                default: None,
                is_variadic: false,
                hir_id: hir_id(0),
            }],
            return_type: None,
            body: HirBlock {
                stmts: vec![let_stmt],
                expr: Some(Box::new(hir_var("x"))),
                hir_id: hir_id(0),
            },
            is_nogc: false,
            hir_id: hir_id(0),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        };
        let mir_fn = lowering.lower_fn(&hir_fn);
        assert_eq!(mir_fn.local_count, 2, "param x (slot 0) + let x (slot 1)");

        // Init RHS: x + 1 -- `x` must be slot 0 (the param), not slot 1.
        match &mir_fn.body.stmts[0] {
            MirStmt::Let { init, .. } => match &init.kind {
                MirExprKind::Binary { left, .. } => match &left.kind {
                    MirExprKind::VarLocal { slot, .. } => assert_eq!(*slot, 0),
                    other => panic!("expected VarLocal in RHS, got {other:?}"),
                },
                other => panic!("expected Binary init, got {other:?}"),
            },
            other => panic!("expected Let stmt, got {other:?}"),
        }
        // Body result: `x` must be slot 1 (the new binding shadows the param).
        match &mir_fn.body.result.as_ref().unwrap().kind {
            MirExprKind::VarLocal { slot, .. } => assert_eq!(*slot, 1),
            other => panic!("expected VarLocal in body, got {other:?}"),
        }
    }

    #[test]
    fn t0b_stage2_main_function_not_slot_resolved() {
        // Top-level lets feed __main, which is NOT lowered through
        // `lower_fn`. local_count stays at 0 and references stay as Var.
        let mut lowering = HirToMir::new();
        let hir = HirProgram {
            items: vec![HirItem::Let(HirLetDecl {
                name: "x".to_string(),
                mutable: false,
                ty_name: None,
                init: hir_int(42),
                hir_id: hir_id(0),
            })],
        };
        let mir = lowering.lower_program(&hir);
        let main = mir.functions.iter().find(|f| f.name == "__main").unwrap();
        assert_eq!(main.local_count, 0, "__main left on name fallback in Stage 2");
    }

    #[test]
    fn t0b_stage2_unresolved_name_stays_as_var() {
        // `fn f() { undefined_global }` -- no local of that name; emit Var.
        let mut lowering = HirToMir::new();
        let hir_fn = mk_fn("f", vec![], hir_var("undefined_global"));
        let mir_fn = lowering.lower_fn(&hir_fn);
        assert_eq!(mir_fn.local_count, 0, "no params + no lets -> zero slots");

        match &mir_fn.body.result.as_ref().unwrap().kind {
            MirExprKind::Var(name) => assert_eq!(name, "undefined_global"),
            other => panic!(
                "expected Var(name) for unresolved reference, got {other:?}"
            ),
        }
    }

    #[test]
    fn t0b_stage4_closure_body_is_slot_resolved() {
        // `fn outer() { let x = 1; (|y| x + y) }` -- Stage 4 slot-resolves
        // the lifted closure body just like a regular function. The
        // lifted fn has params [capture x, param y] => local_count >= 2;
        // body references emit VarLocal for both `x` (capture, slot 0)
        // and `y` (param, slot 1).
        let mut lowering = HirToMir::new();
        let lambda_body = HirExpr {
            kind: HirExprKind::Binary {
                op: BinOp::Add,
                left: Box::new(hir_var("x")),
                right: Box::new(hir_var("y")),
            },
            hir_id: hir_id(0),
        };
        let closure = HirExpr {
            kind: HirExprKind::Closure {
                params: vec![HirParam {
                    name: "y".to_string(),
                    ty_name: "i64".to_string(),
                    default: None,
                    is_variadic: false,
                    hir_id: hir_id(0),
                }],
                body: Box::new(lambda_body),
                captures: vec![HirCapture {
                    name: "x".to_string(),
                    mode: CaptureMode::Ref,
                    hir_id: hir_id(0),
                }],
            },
            hir_id: hir_id(0),
        };
        let let_x = HirStmt {
            kind: HirStmtKind::Let {
                name: "x".to_string(),
                mutable: false,
                ty_name: None,
                init: hir_int(1),
            },
            hir_id: hir_id(0),
        };
        let outer = HirFn {
            name: "outer".to_string(),
            type_params: vec![],
            params: vec![],
            return_type: None,
            body: HirBlock {
                stmts: vec![let_x],
                expr: Some(Box::new(closure)),
                hir_id: hir_id(0),
            },
            is_nogc: false,
            hir_id: hir_id(0),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        };

        let _outer_mir = lowering.lower_fn(&outer);
        assert_eq!(lowering.lifted_functions.len(), 1);
        let lifted = &lowering.lifted_functions[0];
        // Stage 4: closures get a real local_count. The lifted params
        // are [x (capture), y (original)] -> 2 slots.
        assert_eq!(
            lifted.local_count, 2,
            "Stage 4 slot-resolves closure bodies; lifted params -> slots 0..N"
        );

        // Body of the lifted function: x + y. Both should be VarLocal
        // with `x` at slot 0 (first capture-param) and `y` at slot 1.
        match &lifted.body.result.as_ref().unwrap().kind {
            MirExprKind::Binary { left, right, .. } => {
                match &left.kind {
                    MirExprKind::VarLocal { name, slot } => {
                        assert_eq!(name, "x");
                        assert_eq!(*slot, 0, "capture-param `x` -> slot 0");
                    }
                    other => panic!(
                        "expected VarLocal for capture `x`, got {other:?}"
                    ),
                }
                match &right.kind {
                    MirExprKind::VarLocal { name, slot } => {
                        assert_eq!(name, "y");
                        assert_eq!(*slot, 1, "original param `y` -> slot 1");
                    }
                    other => {
                        panic!("expected VarLocal for param `y`, got {other:?}")
                    }
                }
            }
            other => panic!("expected Binary in closure body, got {other:?}"),
        }
    }

    #[test]
    fn t0b_stage2_capture_expr_in_outer_is_slot_resolved() {
        // The MakeClosure node's capture *expressions* run in the OUTER
        // scope -- they should slot-resolve. This is the closure-creation
        // hot path.
        //
        // `fn outer() { let x = 1; (|y| x + y) }` -- the MakeClosure's
        // captures vec contains a slot-resolved reference to `x`.
        let mut lowering = HirToMir::new();
        let lambda_body = HirExpr {
            kind: HirExprKind::Binary {
                op: BinOp::Add,
                left: Box::new(hir_var("x")),
                right: Box::new(hir_var("y")),
            },
            hir_id: hir_id(0),
        };
        let closure = HirExpr {
            kind: HirExprKind::Closure {
                params: vec![HirParam {
                    name: "y".to_string(),
                    ty_name: "i64".to_string(),
                    default: None,
                    is_variadic: false,
                    hir_id: hir_id(0),
                }],
                body: Box::new(lambda_body),
                captures: vec![HirCapture {
                    name: "x".to_string(),
                    mode: CaptureMode::Ref,
                    hir_id: hir_id(0),
                }],
            },
            hir_id: hir_id(0),
        };
        let let_x = HirStmt {
            kind: HirStmtKind::Let {
                name: "x".to_string(),
                mutable: false,
                ty_name: None,
                init: hir_int(1),
            },
            hir_id: hir_id(0),
        };
        let outer = HirFn {
            name: "outer".to_string(),
            type_params: vec![],
            params: vec![],
            return_type: None,
            body: HirBlock {
                stmts: vec![let_x],
                expr: Some(Box::new(closure)),
                hir_id: hir_id(0),
            },
            is_nogc: false,
            hir_id: hir_id(0),
            decorators: vec![],
            vis: cjc_ast::Visibility::Private,
        };

        let outer_mir = lowering.lower_fn(&outer);
        assert_eq!(outer_mir.local_count, 1, "outer fn has one let (x)");

        match &outer_mir.body.result.as_ref().unwrap().kind {
            MirExprKind::MakeClosure { captures, .. } => {
                assert_eq!(captures.len(), 1);
                match &captures[0].kind {
                    MirExprKind::VarLocal { name, slot } => {
                        assert_eq!(name, "x");
                        assert_eq!(*slot, 0);
                    }
                    other => panic!(
                        "expected VarLocal in MakeClosure capture, got {other:?}"
                    ),
                }
            }
            other => panic!("expected MakeClosure, got {other:?}"),
        }
    }

    #[test]
    fn t0b_stage2_nested_blocks_use_distinct_slots() {
        // `fn f() { if cond { let x = 1; x } else { let y = 2; y } }`
        // -- x and y must occupy different slots (counter is monotonic).
        let mut lowering = HirToMir::new();
        let then_block = HirBlock {
            stmts: vec![HirStmt {
                kind: HirStmtKind::Let {
                    name: "x".to_string(),
                    mutable: false,
                    ty_name: None,
                    init: hir_int(1),
                },
                hir_id: hir_id(0),
            }],
            expr: Some(Box::new(hir_var("x"))),
            hir_id: hir_id(0),
        };
        let else_block = HirBlock {
            stmts: vec![HirStmt {
                kind: HirStmtKind::Let {
                    name: "y".to_string(),
                    mutable: false,
                    ty_name: None,
                    init: hir_int(2),
                },
                hir_id: hir_id(0),
            }],
            expr: Some(Box::new(hir_var("y"))),
            hir_id: hir_id(0),
        };
        let if_expr = HirExpr {
            kind: HirExprKind::If {
                cond: Box::new(HirExpr {
                    kind: HirExprKind::BoolLit(true),
                    hir_id: hir_id(0),
                }),
                then_block,
                else_branch: Some(HirElseBranch::Else(else_block)),
            },
            hir_id: hir_id(0),
        };
        let hir_fn = mk_fn("f", vec![], if_expr);
        let mir_fn = lowering.lower_fn(&hir_fn);

        // Two distinct slots even though only one branch executes at runtime
        // -- slot counter never decrements.
        assert_eq!(
            mir_fn.local_count, 2,
            "shadowing across siblings consumes two slots"
        );
    }

    #[test]
    fn t0b_stage4_match_arm_pattern_bindings_get_slots() {
        // `fn f(outer) { match outer { inner => outer + inner } }`
        //
        // Stage 4: the pattern binding `inner` gets a slot (1, after
        // param `outer` at slot 0); references to `outer` and `inner`
        // in the arm body both slot-resolve. The pattern itself carries
        // the assigned slot so the executor knows where to write the
        // binding value.
        let mut lowering = HirToMir::new();
        let arm_body = HirExpr {
            kind: HirExprKind::Binary {
                op: BinOp::Add,
                left: Box::new(hir_var("outer")),
                right: Box::new(hir_var("inner")),
            },
            hir_id: hir_id(0),
        };
        let match_expr = HirExpr {
            kind: HirExprKind::Match {
                scrutinee: Box::new(hir_var("outer")),
                arms: vec![HirMatchArm {
                    pattern: HirPattern {
                        kind: HirPatternKind::Binding("inner".to_string()),
                        hir_id: hir_id(0),
                    },
                    body: arm_body,
                    hir_id: hir_id(0),
                }],
            },
            hir_id: hir_id(0),
        };
        let hir_fn = mk_fn("f", vec![("outer", "i64")], match_expr);
        let mir_fn = lowering.lower_fn(&hir_fn);

        // Param outer is slot 0; pattern binding inner is slot 1.
        // local_count is 2.
        assert_eq!(
            mir_fn.local_count, 2,
            "param outer (slot 0) + pattern binding inner (slot 1)"
        );

        match &mir_fn.body.result.as_ref().unwrap().kind {
            MirExprKind::Match { scrutinee, arms } => {
                // Scrutinee in outer scope -> VarLocal slot 0.
                match &scrutinee.kind {
                    MirExprKind::VarLocal { name, slot } => {
                        assert_eq!(name, "outer");
                        assert_eq!(*slot, 0);
                    }
                    other => {
                        panic!("scrutinee should slot-resolve, got {other:?}")
                    }
                }
                // Pattern itself carries slot.
                match &arms[0].pattern {
                    MirPattern::Binding { name, slot } => {
                        assert_eq!(name, "inner");
                        assert_eq!(
                            *slot,
                            Some(1),
                            "pattern binding -> slot 1"
                        );
                    }
                    other => panic!(
                        "expected Binding pattern, got {other:?}"
                    ),
                }
                // Arm body: both `outer` and `inner` are VarLocal.
                match &arms[0].body.result.as_ref().unwrap().kind {
                    MirExprKind::Binary { left, right, .. } => {
                        match &left.kind {
                            MirExprKind::VarLocal { name, slot } => {
                                assert_eq!(name, "outer");
                                assert_eq!(*slot, 0);
                            }
                            other => panic!(
                                "expected VarLocal for `outer`, got {other:?}"
                            ),
                        }
                        match &right.kind {
                            MirExprKind::VarLocal { name, slot } => {
                                assert_eq!(name, "inner");
                                assert_eq!(*slot, 1);
                            }
                            other => panic!(
                                "expected VarLocal for `inner`, got {other:?}"
                            ),
                        }
                    }
                    other => {
                        panic!("expected Binary in arm body, got {other:?}")
                    }
                }
            }
            other => panic!("expected Match, got {other:?}"),
        }
    }

    #[test]
    fn t0b_stage2_function_calls_dont_disturb_outer_slots() {
        // Lowering an inner `lower_fn` from inside an outer function (via
        // an Impl method, say) must save/restore the outer tracker.
        //
        // Here we manually trigger this by lowering two functions in
        // sequence; the second must have local_count = its own params,
        // not the first's.
        let mut lowering = HirToMir::new();
        let f1 = mk_fn("f1", vec![("a", "i64"), ("b", "i64")], hir_var("a"));
        let f2 = mk_fn("f2", vec![("x", "i64")], hir_var("x"));

        let m1 = lowering.lower_fn(&f1);
        let m2 = lowering.lower_fn(&f2);
        assert_eq!(m1.local_count, 2);
        assert_eq!(m2.local_count, 1, "f2 should not inherit f1's slot count");
    }
}