sapphire-lang 0.8.0

Gradually typed scripting language where every value is an object and types are optional, checked at runtime
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
use crate::ast::{Block, Expr, MatchArm, MethodDef, Pattern, StringPart, TypeExpr};
use crate::chunk::{Chunk, Constant, Function, OpCode, RuntimeType, UpvalueDef};
use crate::token::TokenKind;
use crate::value::Value;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::rc::Rc;

// ── Error ─────────────────────────────────────────────────────────────────────

#[derive(Debug, PartialEq)]
pub struct CompileError {
    pub message: String,
    pub line: u32,
    pub column: u32,
}

impl fmt::Display for CompileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[line {}:{}] compile error: {}",
            self.line, self.column, self.message
        )
    }
}

fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let m = b.len();
    let mut prev: Vec<usize> = (0..=m).collect();
    let mut curr = vec![0usize; m + 1];
    for (i, &ca) in a.iter().enumerate() {
        curr[0] = i + 1;
        for (j, &cb) in b.iter().enumerate() {
            let cost = if ca == cb { 0 } else { 1 };
            curr[j + 1] = (curr[j] + 1).min(prev[j + 1] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[m]
}

fn suggest_name<'a>(name: &str, candidates: &[&'a str]) -> Option<&'a str> {
    let threshold = (name.len() / 3).max(2);
    candidates
        .iter()
        .map(|&c| (c, levenshtein(name, c)))
        .filter(|(_, dist)| *dist <= threshold)
        .min_by_key(|(_, dist)| *dist)
        .map(|(c, _)| c)
}

// ── Per-function compiler state ───────────────────────────────────────────────

struct LocalInfo {
    name: String,
    /// True once another closure has captured this local as an upvalue.
    captured: bool,
}

struct UpvalueInfo {
    is_local: bool, // local in the immediately enclosing scope
    index: usize,
}

/// Tracks the context needed to compile `break`/`next` inside a while loop.
struct LoopCtx {
    /// Instruction index of the loop condition check (target for `next`).
    start: usize,
    /// Indices of `Jump(0)` placeholders emitted for `break` — patched after the loop.
    break_jumps: Vec<usize>,
}

struct FunctionState {
    chunk: Chunk,
    current_line: u32,
    current_column: u32,
    locals: Vec<LocalInfo>,
    upvalue_defs: Vec<UpvalueInfo>,
    name: String,
    arity: usize,
    /// When compiling a class/instance method, the method name for bare `super`.
    super_method_name: Option<String>,
    /// Stack of active while-loop contexts, innermost last.
    loop_stack: Vec<LoopCtx>,
    return_type: Option<RuntimeType>,
}

impl FunctionState {
    fn new(name: &str, arity: usize, line: u32) -> Self {
        FunctionState {
            chunk: Chunk::new(),
            current_line: line,
            current_column: 1,
            locals: Vec::new(),
            upvalue_defs: Vec::new(),
            name: name.to_string(),
            arity,
            super_method_name: None,
            loop_stack: Vec::new(),
            return_type: None,
        }
    }
}

// ── Compiler ──────────────────────────────────────────────────────────────────

/// A stack of `FunctionState`s, one per nesting level.  The top of the stack
/// is the function currently being compiled.
struct Compiler {
    states: Vec<FunctionState>,
    /// When true (REPL mode), top-level variable assignments and definitions
    /// are stored as globals rather than stack slots.
    global_mode: bool,
    /// True when the file contains at least one `import` statement.  Enables
    /// `GetGlobal` fallback for unresolved variable references so that names
    /// defined in imported files (which run as globals) are accessible.
    has_imports: bool,
    /// Class names from outermost to innermost while compiling nested `class` bodies.
    /// Used to resolve bare uppercase names as class constants before globals.
    enclosing_class_stack: Vec<String>,
    /// Type alias map collected in a pre-pass; used when encoding type annotations.
    type_aliases: HashMap<String, TypeExpr>,
    /// Interfaces are checked statically only, so their annotations erase at runtime.
    interfaces: HashSet<String>,
}

impl Compiler {
    fn new() -> Self {
        Compiler {
            states: Vec::new(),
            global_mode: false,
            has_imports: false,
            enclosing_class_stack: Vec::new(),
            type_aliases: HashMap::new(),
            interfaces: HashSet::new(),
        }
    }

    fn new_with_imports() -> Self {
        Compiler {
            states: Vec::new(),
            global_mode: false,
            has_imports: true,
            enclosing_class_stack: Vec::new(),
            type_aliases: HashMap::new(),
            interfaces: HashSet::new(),
        }
    }

    fn new_repl() -> Self {
        Compiler {
            states: Vec::new(),
            global_mode: true,
            has_imports: false,
            enclosing_class_stack: Vec::new(),
            type_aliases: HashMap::new(),
            interfaces: HashSet::new(),
        }
    }

    // ── Public entry points ───────────────────────────────────────────────────

    /// Compile a top-level program (arity 0, anonymous).
    pub fn compile(exprs: &[Expr]) -> Result<Rc<Function>, CompileError> {
        let has_imports = exprs.iter().any(|e| matches!(e, Expr::Import { .. }));
        let mut c = if has_imports {
            Compiler::new_with_imports()
        } else {
            Compiler::new()
        };
        c.collect_type_aliases(exprs);
        c.push_fn("", 0, 0);
        c.compile_body(exprs)?;
        Ok(c.pop_fn())
    }

    /// Compile a REPL snippet: top-level variables go to globals instead of
    /// stack slots, so they persist across successive `eval()` calls.
    pub fn compile_repl(exprs: &[Expr]) -> Result<Rc<Function>, CompileError> {
        let mut c = Compiler::new_repl();
        c.collect_type_aliases(exprs);
        c.push_fn("", 0, 0);
        c.compile_body(exprs)?;
        Ok(c.pop_fn())
    }

    fn collect_type_aliases(&mut self, exprs: &[Expr]) {
        for e in exprs {
            match e {
                Expr::TypeAlias { name, type_expr } => {
                    self.type_aliases.insert(name.clone(), type_expr.clone());
                }
                Expr::Interface { name, .. } => {
                    self.interfaces.insert(name.clone());
                }
                _ => {}
            }
        }
    }

    /// Resolve a TypeExpr by expanding any named aliases.
    fn resolve_type_expr(&self, te: &TypeExpr) -> TypeExpr {
        match te {
            TypeExpr::Named(n) => {
                if let Some(expanded) = self.type_aliases.get(n) {
                    self.resolve_type_expr(expanded)
                } else {
                    te.clone()
                }
            }
            TypeExpr::Apply(name, args) => TypeExpr::Apply(
                name.clone(),
                args.iter().map(|a| self.resolve_type_expr(a)).collect(),
            ),
            TypeExpr::Union(arms) => {
                let resolved: Vec<TypeExpr> =
                    arms.iter().map(|a| self.resolve_type_expr(a)).collect();
                let mut flat = Vec::new();
                for arm in resolved {
                    match arm {
                        TypeExpr::Union(inner) => flat.extend(inner),
                        other => flat.push(other),
                    }
                }
                if flat.len() == 1 {
                    flat.remove(0)
                } else {
                    TypeExpr::Union(flat)
                }
            }
            TypeExpr::Literal(_) => te.clone(),
            TypeExpr::Any => TypeExpr::Any,
        }
    }

    // ── Function stack ────────────────────────────────────────────────────────

    fn push_fn(&mut self, name: &str, arity: usize, line: u32) {
        let inherit_super = self.states.last().and_then(|s| s.super_method_name.clone());
        self.states.push(FunctionState::new(name, arity, line));
        if let Some(sm) = inherit_super {
            self.state_mut().super_method_name = Some(sm);
        }
    }

    fn pop_fn(&mut self) -> Rc<Function> {
        let state = self.states.pop().unwrap();
        Rc::new(Function {
            name: state.name,
            arity: state.arity,
            super_method_name: state.super_method_name,
            chunk: state.chunk,
            upvalue_defs: state
                .upvalue_defs
                .into_iter()
                .map(|uv| UpvalueDef {
                    is_local: uv.is_local,
                    index: uv.index,
                })
                .collect(),
            return_type: state.return_type,
        })
    }

    fn state(&self) -> &FunctionState {
        self.states.last().unwrap()
    }

    fn state_mut(&mut self) -> &mut FunctionState {
        self.states.last_mut().unwrap()
    }

    // ── Body compilation (shared between top-level and functions) ─────────────

    /// Compile a list of expressions, treating the last as an implicit return value (Ruby-style).
    fn compile_body(&mut self, exprs: &[Expr]) -> Result<(), CompileError> {
        let (last, rest) = match exprs.split_last() {
            Some(pair) => pair,
            None => {
                self.emit(OpCode::Nil);
                self.emit(OpCode::Return);
                return Ok(());
            }
        };
        self.stmts(rest)?;
        match last {
            Expr::Function { name, .. } => {
                self.expr(last)?;
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(name.clone()));
                self.emit(OpCode::Constant(idx));
                self.emit(OpCode::Return);
            }
            e if !Self::is_stmt_form(e) => {
                self.expr(last)?;
                self.emit(OpCode::Return);
            }
            other => {
                self.stmt(other)?;
                self.emit(OpCode::Nil);
                self.emit(OpCode::Return);
            }
        }
        Ok(())
    }

    /// Branch body for `if` / `begin`: leave one value on the stack (no `Return`).
    fn compile_branch(&mut self, exprs: &[Expr]) -> Result<(), CompileError> {
        match exprs.split_last() {
            None => {
                self.emit(OpCode::Nil);
            }
            Some((last, rest)) => {
                self.stmts(rest)?;
                match last {
                    e if !Self::is_stmt_form(e) => {
                        self.expr(last)?;
                    }
                    other => {
                        self.stmt(other)?;
                        self.emit(OpCode::Nil);
                    }
                }
            }
        }
        Ok(())
    }

    fn is_stmt_form(expr: &Expr) -> bool {
        matches!(
            expr,
            Expr::While { .. }
                | Expr::Return(_)
                | Expr::Break(_)
                | Expr::Next(_)
                | Expr::Raise(_)
                | Expr::MultiAssign { .. }
                | Expr::Import { .. }
                | Expr::TypeAlias { .. }
                | Expr::Interface { .. }
        )
    }

    // ── Statement-shaped expressions (also used from `expr()` for value position) ──

    fn stmt(&mut self, stmt: &Expr) -> Result<(), CompileError> {
        match stmt {
            Expr::Return(expr) => {
                self.expr(expr)?;
                self.emit(OpCode::NonLocalReturn);
            }

            Expr::While { condition, body } => {
                // Pre-declare any variables that are first introduced in the body so
                // that subsequent iterations reuse the same stack slot (SetLocal) rather
                // than pushing a new slot each time.
                self.hoist_while_locals(body);

                let loop_start = self.state().chunk.code.len();

                self.expr(condition.as_ref())?;
                let exit_jump = self.emit_jump(OpCode::JumpIfFalse(0));

                self.state_mut().loop_stack.push(LoopCtx {
                    start: loop_start,
                    break_jumps: vec![],
                });
                self.stmts(body)?;
                let ctx = self.state_mut().loop_stack.pop().unwrap();

                self.emit_loop(loop_start);
                self.patch_jump(exit_jump);

                for jump_idx in ctx.break_jumps {
                    self.patch_jump(jump_idx);
                }
            }

            Expr::Raise(expr) => {
                self.expr(expr)?;
                self.emit(OpCode::Raise);
            }

            Expr::Break(expr) => {
                self.expr(expr)?;
                if self.state().loop_stack.is_empty() {
                    self.emit(OpCode::Break);
                } else {
                    // Inside a while loop: discard the value, jump to after the loop.
                    self.emit(OpCode::Pop);
                    let jump_idx = self.emit_jump(OpCode::Jump(0));
                    self.state_mut()
                        .loop_stack
                        .last_mut()
                        .unwrap()
                        .break_jumps
                        .push(jump_idx);
                }
            }

            Expr::Next(expr) => {
                self.expr(expr)?;
                if self.state().loop_stack.is_empty() {
                    self.emit(OpCode::Next);
                } else {
                    // Inside a while loop: discard the value, jump back to condition.
                    self.emit(OpCode::Pop);
                    let start = self.state().loop_stack.last().unwrap().start;
                    self.emit_loop(start);
                }
            }

            Expr::MultiAssign { names, values } => {
                if names.len() != values.len() {
                    return Err(self.error(format!(
                        "expected {} value(s), got {}",
                        names.len(),
                        values.len()
                    )));
                }
                // Resolve each name as an existing local/upvalue, or pre-allocate
                // a new nil slot.  Using Ok(slot) for locals and Err(idx) for upvalues.
                let mut targets: Vec<Result<usize, usize>> = Vec::with_capacity(names.len());
                let depth = self.states.len() - 1;
                for name in names {
                    if let Some(slot) = self.resolve_local(depth, name) {
                        targets.push(Ok(slot));
                    } else if let Some(idx) = self.resolve_upvalue(depth, name) {
                        targets.push(Err(idx));
                    } else {
                        // New variable: push nil as its stack slot, then register.
                        let slot = self.state().locals.len();
                        self.emit(OpCode::Nil);
                        self.state_mut().locals.push(LocalInfo {
                            name: name.clone(),
                            captured: false,
                        });
                        targets.push(Ok(slot));
                    }
                }
                // Evaluate all RHS before any assignment (enables `a, b = b, a`).
                for val_expr in values {
                    self.expr(val_expr)?;
                }
                // Assign top-of-stack first so RHS values go to the right variables.
                for t in targets.into_iter().rev() {
                    match t {
                        Ok(slot) => {
                            self.emit(OpCode::SetLocal(slot));
                            self.emit(OpCode::Pop);
                        }
                        Err(idx) => {
                            self.emit(OpCode::SetUpvalue(idx));
                            self.emit(OpCode::Pop);
                        }
                    }
                }
            }

            Expr::Import { path } => {
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(path.clone()));
                self.emit(OpCode::Import(idx));
            }

            Expr::TypeAlias { .. } => {
                // Type aliases are compile-time only; no bytecode emitted.
            }

            Expr::Interface { .. } => {
                // Interfaces are compile-time only; no bytecode emitted.
            }

            e => {
                let is_new_local = self.is_new_local_assign(e);
                // In global mode, function/class defs emit SetGlobal (peek) instead of
                // leaving the value as a new local slot, so we must Pop afterwards.
                let defines_binding =
                    !self.global_mode && matches!(e, Expr::Function { .. } | Expr::Class { .. });
                self.expr(e)?;
                if !is_new_local && !defines_binding {
                    self.emit(OpCode::Pop);
                }
            }
        }
        Ok(())
    }

    // ── Expressions ───────────────────────────────────────────────────────────

    fn expr(&mut self, expr: &Expr) -> Result<(), CompileError> {
        match expr {
            Expr::Return(_) | Expr::Break(_) | Expr::Next(_) | Expr::Raise(_) => self.stmt(expr),

            Expr::While { .. } | Expr::MultiAssign { .. } | Expr::Import { .. } => {
                self.stmt(expr)?;
                self.emit(OpCode::Nil);
                Ok(())
            }

            Expr::TypeAlias { .. } | Expr::Interface { .. } => {
                self.stmt(expr)?;
                self.emit(OpCode::Nil);
                Ok(())
            }

            Expr::Literal(val) => self.literal(val),

            Expr::Grouping(inner) => self.expr(inner),

            Expr::Unary { op, right } => {
                self.state_mut().current_line = op.line as u32;
                self.state_mut().current_column = op.column as u32;
                self.expr(right)?;
                match &op.kind {
                    TokenKind::Minus => self.emit(OpCode::Negate),
                    TokenKind::Bang => self.emit(OpCode::Not),
                    TokenKind::Tilde => self.emit(OpCode::BitNot),
                    other => {
                        return Err(self.error(format!("unsupported unary operator '{:?}'", other)));
                    }
                }
                Ok(())
            }

            Expr::Binary { left, op, right } => {
                self.state_mut().current_line = op.line as u32;
                self.state_mut().current_column = op.column as u32;
                // Short-circuit operators: evaluate only the left side first.
                match &op.kind {
                    TokenKind::AmpAmp => {
                        // `a and b`: if a is falsy keep a as result; else result is b.
                        self.expr(left)?;
                        let jump = self.emit_jump(OpCode::JumpIfFalseKeep(0));
                        self.expr(right)?;
                        self.patch_jump(jump);
                        return Ok(());
                    }
                    TokenKind::PipePipe => {
                        // `a or b`: if a is truthy keep a as result; else result is b.
                        self.expr(left)?;
                        let jump = self.emit_jump(OpCode::JumpIfTrueKeep(0));
                        self.expr(right)?;
                        self.patch_jump(jump);
                        return Ok(());
                    }
                    _ => {}
                }
                self.expr(left)?;
                self.expr(right)?;
                match &op.kind {
                    TokenKind::Plus => self.emit(OpCode::Add),
                    TokenKind::Minus => self.emit(OpCode::Sub),
                    TokenKind::Star => self.emit(OpCode::Mul),
                    TokenKind::Slash => self.emit(OpCode::Div),
                    TokenKind::Percent => self.emit(OpCode::Mod),
                    TokenKind::Amp => self.emit(OpCode::BitAnd),
                    TokenKind::Pipe => self.emit(OpCode::BitOr),
                    TokenKind::Caret => self.emit(OpCode::BitXor),
                    TokenKind::LessLess => self.emit(OpCode::Shl),
                    TokenKind::GreaterGreater => self.emit(OpCode::Shr),
                    TokenKind::EqEq => self.emit(OpCode::Equal),
                    TokenKind::BangEq => self.emit(OpCode::NotEqual),
                    TokenKind::Less => self.emit(OpCode::Less),
                    TokenKind::LessEq => self.emit(OpCode::LessEqual),
                    TokenKind::Greater => self.emit(OpCode::Greater),
                    TokenKind::GreaterEq => self.emit(OpCode::GreaterEqual),
                    other => {
                        return Err(
                            self.error(format!("unsupported binary operator '{:?}'", other))
                        );
                    }
                }
                Ok(())
            }

            Expr::Variable(name) => {
                let depth = self.states.len() - 1;
                if let Some(slot) = self.resolve_local(depth, name) {
                    self.emit(OpCode::GetLocal(slot));
                } else if let Some(idx) = self.resolve_upvalue(depth, name) {
                    self.emit(OpCode::GetUpvalue(idx));
                } else if self.global_mode
                    || self.has_imports
                    || name.starts_with(|c: char| c.is_uppercase())
                {
                    self.emit_maybe_lexical_or_global(name);
                } else {
                    let candidates: Vec<&str> = self
                        .states
                        .iter()
                        .flat_map(|s| s.locals.iter().map(|l| l.name.as_str()))
                        .collect();
                    let msg = match suggest_name(name, &candidates) {
                        Some(suggestion) => format!(
                            "undefined variable '{}' — did you mean '{}'?",
                            name, suggestion
                        ),
                        None => format!("undefined variable '{}'", name),
                    };
                    return Err(self.error(msg));
                }
                Ok(())
            }

            Expr::Assign { name, value } => {
                self.expr(value)?;
                let depth = self.states.len() - 1;
                if let Some(slot) = self.resolve_local(depth, name) {
                    self.emit(OpCode::SetLocal(slot));
                } else if let Some(idx) = self.resolve_upvalue(depth, name) {
                    self.emit(OpCode::SetUpvalue(idx));
                } else if self.global_mode && depth == 0 {
                    // REPL top-level: persist as a global (peek semantics — TOS stays).
                    let idx = self
                        .state_mut()
                        .chunk
                        .add_constant(Constant::Str(name.clone()));
                    self.emit(OpCode::SetGlobal(idx));
                } else {
                    // First use of this name: allocate a new stack slot.
                    self.state_mut().locals.push(LocalInfo {
                        name: name.clone(),
                        captured: false,
                    });
                }
                Ok(())
            }

            Expr::SelfExpr => {
                self.emit(OpCode::GetSelf);
                Ok(())
            }

            Expr::Call {
                callee,
                args,
                block,
            } => {
                // Method call: `obj.method(args)` or `obj.method(args) { |x| ... }`
                if let Expr::Get {
                    object,
                    name,
                    line: get_line,
                } = callee.as_ref()
                {
                    if *get_line > 0 {
                        self.state_mut().current_line = *get_line as u32;
                    }
                    if name == "new" && block.is_none() {
                        // Class construction: `ClassName.new(field: val, ...)`
                        self.expr(object)?;
                        for arg in args {
                            let arg_name = arg.name.clone().unwrap_or_default();
                            let ni = self.state_mut().chunk.add_constant(Constant::Str(arg_name));
                            self.emit(OpCode::Constant(ni));
                            self.expr(&arg.value)?;
                        }
                        self.emit(OpCode::NewInstance(args.len()));
                    } else if let Some(blk) = block {
                        self.expr(object)?;
                        for arg in args {
                            self.expr(&arg.value)?;
                        }
                        self.compile_block(blk)?;
                        let ni = self
                            .state_mut()
                            .chunk
                            .add_constant(Constant::Str(name.clone()));
                        self.emit(OpCode::InvokeWithBlock(ni, args.len()));
                    } else {
                        // Regular method invocation
                        self.expr(object)?;
                        for arg in args {
                            self.expr(&arg.value)?;
                        }
                        let ni = self
                            .state_mut()
                            .chunk
                            .add_constant(Constant::Str(name.clone()));
                        self.emit(OpCode::Invoke(ni, args.len()));
                    }
                    return Ok(());
                }
                // Implicit self dispatch: if the callee is a bare name that can't be
                // resolved as a local/upvalue, but `self` is in scope (we're inside a
                // method body), rewrite as `self.name(args)`.
                if let Expr::Variable(name) = callee.as_ref() {
                    let depth = self.states.len() - 1;
                    let is_unresolved = self.resolve_local(depth, name).is_none()
                        && self.resolve_upvalue(depth, name).is_none();
                    let self_in_scope = self.resolve_local(depth, "self").is_some();
                    if is_unresolved && self_in_scope {
                        self.emit(OpCode::GetSelf);
                        let arg_count = args.len();
                        for arg in args {
                            self.expr(&arg.value)?;
                        }
                        let ni = self
                            .state_mut()
                            .chunk
                            .add_constant(Constant::Str(name.clone()));
                        if let Some(blk) = block {
                            self.compile_block(blk)?;
                            self.emit(OpCode::InvokeWithBlock(ni, arg_count));
                        } else {
                            self.emit(OpCode::Invoke(ni, arg_count));
                        }
                        return Ok(());
                    }
                }
                // Plain function call (with or without block)
                self.expr(callee)?;
                let arg_count = args.len();
                for arg in args {
                    self.expr(&arg.value)?;
                }
                if let Some(blk) = block {
                    self.compile_block(blk)?;
                    self.emit(OpCode::CallWithBlock(arg_count));
                } else {
                    self.emit(OpCode::Call(arg_count));
                }
                Ok(())
            }

            Expr::Yield { args } => {
                let n = args.len();
                for a in args {
                    self.expr(&a.value)?;
                }
                self.emit(OpCode::Yield(n));
                Ok(())
            }

            Expr::Get {
                object,
                name,
                line: get_line,
            } => {
                if *get_line > 0 {
                    self.state_mut().current_line = *get_line as u32;
                }
                self.expr(object)?;
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(name.clone()));
                self.emit(OpCode::GetField(idx));
                Ok(())
            }

            Expr::SafeGet {
                object,
                name,
                line: get_line,
            } => {
                if *get_line > 0 {
                    self.state_mut().current_line = *get_line as u32;
                }
                self.expr(object)?;
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(name.clone()));
                self.emit(OpCode::GetFieldSafe(idx));
                Ok(())
            }

            Expr::Set {
                object,
                name,
                value,
            } => {
                self.expr(object)?;
                self.expr(value)?;
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(name.clone()));
                self.emit(OpCode::SetField(idx));
                Ok(())
            }

            Expr::ListLit(elems) => {
                let n = elems.len();
                for e in elems {
                    self.expr(e)?;
                }
                self.emit(OpCode::BuildList(n));
                Ok(())
            }

            Expr::MapLit(pairs) => {
                let n = pairs.len();
                for (key, val_expr) in pairs {
                    let idx = self
                        .state_mut()
                        .chunk
                        .add_constant(Constant::Str(key.clone()));
                    self.emit(OpCode::Constant(idx));
                    self.expr(val_expr)?;
                }
                self.emit(OpCode::BuildMap(n));
                Ok(())
            }

            Expr::Range { from, to } => {
                self.expr(from)?;
                self.expr(to)?;
                self.emit(OpCode::BuildRange);
                Ok(())
            }

            Expr::Index { object, index } => {
                self.expr(object)?;
                self.expr(index)?;
                self.emit(OpCode::Index);
                Ok(())
            }

            Expr::IndexSet {
                object,
                index,
                value,
            } => {
                self.expr(object)?;
                self.expr(index)?;
                self.expr(value)?;
                self.emit(OpCode::IndexSet);
                Ok(())
            }

            Expr::StringInterp(parts) => {
                let n = parts.len();
                for part in parts {
                    match part {
                        StringPart::Lit(s) => {
                            let idx = self
                                .state_mut()
                                .chunk
                                .add_constant(Constant::Str(s.clone()));
                            self.emit(OpCode::Constant(idx));
                        }
                        StringPart::Expr(inner) => {
                            self.expr(inner)?;
                        }
                    }
                }
                self.emit(OpCode::BuildString(n));
                Ok(())
            }

            Expr::Super {
                args,
                forward_args,
                block: _,
            } => {
                if *forward_args && !args.is_empty() {
                    return Err(self.error("internal: bare super with non-empty args".to_string()));
                }
                self.emit(OpCode::GetSelf);
                let arg_count = if *forward_args {
                    let st = self.state();
                    let arity = st.arity;
                    for slot in 1..=arity {
                        self.emit(OpCode::GetLocal(slot));
                    }
                    arity
                } else {
                    for arg in args {
                        self.expr(&arg.value)?;
                    }
                    args.len()
                };
                let method_name = self.state().super_method_name.clone().ok_or_else(|| {
                    self.error("`super` is only valid inside a class method".to_string())
                })?;
                let name_idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(method_name));
                self.emit(OpCode::SuperInvoke(name_idx, arg_count));
                Ok(())
            }

            Expr::Print(inner) => {
                self.expr(inner)?;
                self.emit(OpCode::Print);
                Ok(())
            }

            Expr::Class {
                name,
                type_params,
                superclass,
                includes,
                is_module,
                is_abstract,
                fields,
                methods,
                nested,
                constants,
            } => {
                self.compile_class(
                    name,
                    type_params,
                    superclass.as_deref(),
                    includes,
                    *is_module,
                    *is_abstract,
                    fields,
                    methods,
                    nested,
                    constants,
                    true,
                )?;
                Ok(())
            }

            Expr::Function {
                name,
                type_params,
                params,
                return_type,
                body,
            } => {
                let line = self.state().current_line;
                let arity = params.len();
                let fn_tvars: std::collections::HashSet<String> =
                    type_params.iter().cloned().collect();

                self.push_fn(name, arity, line);
                self.state_mut().return_type = return_type.as_ref().and_then(|te| {
                    let erased = erase_type_vars(&self.resolve_type_expr(te), &fn_tvars);
                    self.type_expr_runtime(Some(&erased))
                });
                // Slot 0 = the function itself — enables direct recursion by name.
                self.state_mut().locals.push(LocalInfo {
                    name: name.clone(),
                    captured: false,
                });
                for p in params {
                    self.state_mut().locals.push(LocalInfo {
                        name: p.name.clone(),
                        captured: false,
                    });
                }
                self.compile_body(body)?;
                let func = self.pop_fn();

                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Function(func));
                self.emit(OpCode::Closure(idx));

                if self.global_mode && self.states.len() == 1 {
                    // REPL top-level: store in globals, don't allocate a stack slot.
                    let ni = self
                        .state_mut()
                        .chunk
                        .add_constant(Constant::Str(name.clone()));
                    self.emit(OpCode::SetGlobal(ni));
                } else {
                    // The closure value on the stack becomes this local's slot.
                    self.state_mut().locals.push(LocalInfo {
                        name: name.clone(),
                        captured: false,
                    });
                }
                Ok(())
            }

            Expr::If {
                condition,
                then_branch,
                else_branch,
            } => {
                self.expr(condition)?;
                let jif = self.emit_jump(OpCode::JumpIfFalse(0));
                self.compile_branch(then_branch)?;
                match else_branch {
                    Some(else_stmts) => {
                        let jelse = self.emit_jump(OpCode::Jump(0));
                        self.patch_jump(jif);
                        self.compile_branch(else_stmts)?;
                        self.patch_jump(jelse);
                    }
                    None => {
                        let jend = self.emit_jump(OpCode::Jump(0));
                        self.patch_jump(jif);
                        self.emit(OpCode::Nil);
                        self.patch_jump(jend);
                    }
                }
                Ok(())
            }

            Expr::Match { scrutinee, arms } => self.compile_match(scrutinee, arms),

            Expr::Begin {
                body,
                rescue_var,
                rescue_body,
                else_body,
            } => self.compile_begin_expr(body, rescue_var, rescue_body, else_body),

            Expr::Lambda { params, body } => {
                let line = self.state().current_line;
                let arity = params.len();
                self.push_fn("<lambda>", arity, line);
                // Slot 0 = the closure itself (mirrors named-function convention).
                self.state_mut().locals.push(LocalInfo {
                    name: "<lambda>".to_string(),
                    captured: false,
                });
                for p in params {
                    self.state_mut().locals.push(LocalInfo {
                        name: p.clone(),
                        captured: false,
                    });
                }
                self.compile_body(body)?;
                let func = self.pop_fn();
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Function(func));
                self.emit(OpCode::Closure(idx));
                Ok(())
            }

            #[allow(unreachable_patterns)]
            other => Err(self.error(format!(
                "expression not yet supported by compiler: {:?}",
                std::mem::discriminant(other)
            ))),
        }
    }

    fn literal(&mut self, val: &Value) -> Result<(), CompileError> {
        match val {
            Value::Bool(true) => {
                self.emit(OpCode::True);
                Ok(())
            }
            Value::Bool(false) => {
                self.emit(OpCode::False);
                Ok(())
            }
            Value::Nil => {
                self.emit(OpCode::Nil);
                Ok(())
            }
            Value::Int(n) => {
                let idx = self.state_mut().chunk.add_constant(Constant::Int(*n));
                self.emit(OpCode::Constant(idx));
                Ok(())
            }
            Value::Float(n) => {
                let idx = self.state_mut().chunk.add_constant(Constant::Float(*n));
                self.emit(OpCode::Constant(idx));
                Ok(())
            }
            Value::Str(s) => {
                let idx = self
                    .state_mut()
                    .chunk
                    .add_constant(Constant::Str(s.clone()));
                self.emit(OpCode::Constant(idx));
                Ok(())
            }
        }
    }

    // ── Variable resolution ───────────────────────────────────────────────────

    /// Look up `name` as a local in the function at `depth` (index into `states`).
    /// Returns the stack slot index if found.
    fn resolve_local(&self, depth: usize, name: &str) -> Option<usize> {
        self.states[depth]
            .locals
            .iter()
            .rposition(|l| l.name == name)
    }

    /// Resolve `name` as an upvalue visible from the function at `depth`.
    /// If found in a parent scope, the necessary `UpvalueDef` entries are added
    /// and the captured locals are marked.  Returns the upvalue index.
    fn resolve_upvalue(&mut self, depth: usize, name: &str) -> Option<usize> {
        if depth == 0 {
            return None; // top-level scope: no enclosing function
        }
        let parent = depth - 1;

        // Is it a local in the immediately enclosing function?
        if let Some(local_idx) = self.resolve_local(parent, name) {
            self.states[parent].locals[local_idx].captured = true;
            return Some(self.add_upvalue(depth, true, local_idx));
        }

        // Is it an upvalue in the enclosing function (transitive capture)?
        if let Some(upvalue_idx) = self.resolve_upvalue(parent, name) {
            return Some(self.add_upvalue(depth, false, upvalue_idx));
        }

        None
    }

    /// Add an upvalue descriptor to the function at `depth`, deduplicating.
    fn add_upvalue(&mut self, depth: usize, is_local: bool, index: usize) -> usize {
        let existing = self.states[depth]
            .upvalue_defs
            .iter()
            .position(|uv| uv.is_local == is_local && uv.index == index);
        if let Some(i) = existing {
            return i;
        }
        let i = self.states[depth].upvalue_defs.len();
        self.states[depth]
            .upvalue_defs
            .push(UpvalueInfo { is_local, index });
        i
    }

    /// True when `expr` is an assignment to a name that is neither an existing
    /// local nor an upvalue — i.e. it will create a new stack slot.
    fn is_new_local_assign(&self, expr: &Expr) -> bool {
        let depth = self.states.len() - 1;
        if self.global_mode && depth == 0 {
            // At the top level in global mode, assigns go to globals via SetGlobal
            // (peek semantics), so the value stays on the stack and stmt must Pop it.
            return false;
        }
        if let Expr::Assign { name, .. } = expr {
            self.resolve_local(depth, name).is_none() && !self.would_be_upvalue(depth, name)
        } else {
            false
        }
    }

    /// Pre-declare variables that are first introduced in a while body (including
    /// under `if` / nested `while` / `begin`), emitting `Nil` for each so they occupy
    /// a fixed stack slot before the loop's condition is checked.  This prevents
    /// subsequent iterations from pushing a new stack slot instead of updating the
    /// existing one, and keeps inner locals from being allocated mid-loop (which
    /// would shift slots and break nested control flow).
    fn hoist_while_locals(&mut self, body: &[Expr]) {
        if self.global_mode {
            return; // globals use SetGlobal, not stack slots
        }
        for stmt in body {
            self.hoist_while_locals_in_stmt(stmt);
        }
    }

    fn hoist_while_locals_maybe_declare(&mut self, name: &str) {
        let depth = self.states.len() - 1;
        if self.resolve_local(depth, name).is_none() && !self.would_be_upvalue(depth, name) {
            self.emit(OpCode::Nil);
            self.state_mut().locals.push(LocalInfo {
                name: name.to_string(),
                captured: false,
            });
        }
    }

    fn hoist_while_locals_in_stmt(&mut self, stmt: &Expr) {
        match stmt {
            Expr::Assign { name, .. } => {
                self.hoist_while_locals_maybe_declare(name);
            }
            Expr::MultiAssign { names, .. } => {
                for name in names {
                    self.hoist_while_locals_maybe_declare(name);
                }
            }
            Expr::If {
                then_branch,
                else_branch,
                ..
            } => {
                for e in then_branch {
                    self.hoist_while_locals_in_stmt(e);
                }
                if let Some(else_stmts) = else_branch {
                    for e in else_stmts {
                        self.hoist_while_locals_in_stmt(e);
                    }
                }
            }
            Expr::While { body, .. } => {
                for e in body {
                    self.hoist_while_locals_in_stmt(e);
                }
            }
            Expr::Begin {
                body,
                rescue_body,
                else_body,
                ..
            } => {
                for e in body {
                    self.hoist_while_locals_in_stmt(e);
                }
                for e in rescue_body {
                    self.hoist_while_locals_in_stmt(e);
                }
                for e in else_body {
                    self.hoist_while_locals_in_stmt(e);
                }
            }
            // New scopes: do not hoist through closures or class bodies.
            // Match arm bindings are scoped per-arm; don't hoist them.
            Expr::Lambda { .. }
            | Expr::Function { .. }
            | Expr::Class { .. }
            | Expr::Interface { .. }
            | Expr::Match { .. } => {}
            _ => {}
        }
    }

    /// Pure (non-mutating) upvalue check used by `is_new_local_assign`.
    fn would_be_upvalue(&self, depth: usize, name: &str) -> bool {
        if depth == 0 {
            return false;
        }
        let parent = depth - 1;
        self.resolve_local(parent, name).is_some() || self.would_be_upvalue(parent, name)
    }

    // ── Emit helpers ──────────────────────────────────────────────────────────

    /// Uppercase names inside a class body resolve as class constants along the lexical
    /// nesting chain (`GetLexicalConstant`); otherwise use `GetGlobal`.
    fn emit_maybe_lexical_or_global(&mut self, name: &str) {
        let uppercase = name.starts_with(|c: char| c.is_uppercase());
        if uppercase && !self.enclosing_class_stack.is_empty() {
            let enclosing = self.enclosing_class_stack.clone();
            let name_idx = self
                .state_mut()
                .chunk
                .add_constant(Constant::Str(name.to_string()));
            let scope_idx = self
                .state_mut()
                .chunk
                .add_constant(Constant::LexicalClassScope {
                    enclosing_classes: enclosing,
                    name_idx,
                });
            self.emit(OpCode::GetLexicalConstant(scope_idx));
        } else {
            let idx = self
                .state_mut()
                .chunk
                .add_constant(Constant::Str(name.to_string()));
            self.emit(OpCode::GetGlobal(idx));
        }
    }

    fn emit(&mut self, op: OpCode) {
        let line = self.state().current_line;
        self.state_mut().chunk.write(op, line);
    }

    fn emit_jump(&mut self, op: OpCode) -> usize {
        let idx = self.state().chunk.code.len();
        self.emit(op);
        idx
    }

    fn emit_loop(&mut self, loop_start: usize) {
        let offset = self.state().chunk.code.len() + 1 - loop_start;
        self.emit(OpCode::Loop(offset));
    }

    fn patch_jump(&mut self, jump_idx: usize) {
        self.state_mut().chunk.patch_jump(jump_idx);
    }

    /// Compile `match scrutinee { pattern => { body } ... }` as an expression.
    fn compile_match(&mut self, scrutinee: &Expr, arms: &[MatchArm]) -> Result<(), CompileError> {
        // Evaluate the scrutinee; the pushed value IS the stack slot for this local.
        // We do NOT emit SetLocal/Pop — the value stays at stack[base + scrutinee_slot].
        self.expr(scrutinee)?;
        let scrutinee_slot = self.state().locals.len();
        self.state_mut().locals.push(LocalInfo {
            name: "__match__".to_string(),
            captured: false,
        });

        let mut end_jumps: Vec<usize> = Vec::new();

        for arm in arms {
            let fail_jumps = match &arm.patterns[..] {
                [Pattern::Binding(name)] => {
                    // Binding arm: rename the scrutinee slot so guard/body can reference it.
                    self.state_mut().locals[scrutinee_slot].name = name.clone();
                    let mut fjs = Vec::new();
                    if let Some(guard) = &arm.guard {
                        self.expr(guard)?;
                        fjs.push(self.emit_jump(OpCode::JumpIfFalse(0)));
                        // JumpIfFalse pops bool. On fail: stack = [..., scrutinee]. ✓
                    }
                    fjs
                }
                _ => self.compile_arm_check(arm, scrutinee_slot)?,
            };

            self.compile_branch(&arm.body)?;
            end_jumps.push(self.emit_jump(OpCode::Jump(0)));

            for j in fail_jumps {
                self.patch_jump(j);
            }

            // Restore the scrutinee slot name for subsequent arms.
            self.state_mut().locals[scrutinee_slot].name = "__match__".to_string();
        }

        for j in end_jumps {
            self.patch_jump(j);
        }

        // Keep "__match__" in locals so subsequent slot allocations remain consistent.
        // The scrutinee value stays on the stack as an orphaned slot for the frame lifetime.
        Ok(())
    }

    /// Emit bytecode to check whether the scrutinee matches `arm` (non-binding arms only).
    /// Returns jump indices to patch to the NEXT arm start.
    /// After this returns (arm matched), stack = [..., scrutinee]. No extra value on top.
    fn compile_arm_check(
        &mut self,
        arm: &MatchArm,
        scrutinee_slot: usize,
    ) -> Result<Vec<usize>, CompileError> {
        let mut fail_jumps: Vec<usize> = Vec::new();

        if arm.patterns.len() > 1 {
            // OR pattern — use `Not + JumpIfFalse` so ALL paths leave a clean stack.
            // For non-last patterns: if original bool is True → Not→False → JumpIfFalse
            //   jumps to body_entry (popping False). Stack: [scrutinee]. ✓
            // For the last pattern: JumpIfFalse normally — pops bool; False → fail jump.
            let last_idx = arm.patterns.len() - 1;
            let mut body_jumps: Vec<usize> = Vec::new();
            for (i, pat) in arm.patterns.iter().enumerate() {
                self.emit_pattern_test(pat, scrutinee_slot)?;
                if i < last_idx {
                    self.emit(OpCode::Not);
                    body_jumps.push(self.emit_jump(OpCode::JumpIfFalse(0)));
                } else {
                    fail_jumps.push(self.emit_jump(OpCode::JumpIfFalse(0)));
                }
            }
            for j in body_jumps {
                self.patch_jump(j);
            }
            // Stack: [scrutinee] in all taken-arm paths. ✓
        } else {
            // Single pattern — emit test, JumpIfFalse pops bool; no extra Pop needed.
            self.emit_pattern_test(&arm.patterns[0], scrutinee_slot)?;
            fail_jumps.push(self.emit_jump(OpCode::JumpIfFalse(0)));
            // Stack after JumpIfFalse (arm matched): [scrutinee]. ✓
        }

        Ok(fail_jumps)
    }

    /// Emit instructions that leave a Bool on the stack: true iff the scrutinee
    /// at `scrutinee_slot` matches `pattern`.
    /// Stack effect: net +1 (the bool). The scrutinee slot is untouched.
    fn emit_pattern_test(
        &mut self,
        pattern: &Pattern,
        scrutinee_slot: usize,
    ) -> Result<(), CompileError> {
        match pattern {
            Pattern::Wildcard | Pattern::Binding(_) => {
                // Wildcard always matches; Binding is handled by compile_match directly.
                self.emit(OpCode::True);
            }

            Pattern::Literal(val) => {
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.literal(val)?;
                self.emit(OpCode::Equal);
            }

            Pattern::Type(name) => {
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.emit(OpCode::IsA(name.clone()));
            }

            Pattern::Range(low, high) => {
                // scrutinee >= low && scrutinee <= high
                // JumpIfFalseKeep: on True pops the bool; on False keeps False and jumps.
                // So after JumpIfFalseKeep on the True path, stack = [scrutinee] with NO extra Pop needed.
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.literal(low)?;
                self.emit(OpCode::GreaterEqual);
                let jfalse = self.emit_jump(OpCode::JumpIfFalseKeep(0));
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.literal(high)?;
                self.emit(OpCode::LessEqual);
                self.patch_jump(jfalse);
            }

            Pattern::List(sub_patterns) => {
                let n = sub_patterns.len();
                let mut fail_jumps: Vec<usize> = Vec::new();

                // JumpIfFalseKeep semantics: truthy → pop TOS and fall through;
                // falsy → keep TOS (False) and jump. No extra Pop needed on the success path.

                // 1. Is a List?
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.emit(OpCode::IsA("List".to_string()));
                fail_jumps.push(self.emit_jump(OpCode::JumpIfFalseKeep(0)));

                // 2. Correct length?
                self.emit(OpCode::GetLocal(scrutinee_slot));
                self.emit(OpCode::ListLen);
                let n_const = self.state_mut().chunk.add_constant(Constant::Int(n as i64));
                self.emit(OpCode::Constant(n_const));
                self.emit(OpCode::Equal);
                fail_jumps.push(self.emit_jump(OpCode::JumpIfFalseKeep(0)));

                // 3. Each element: load inline (no temp local), consume element with check.
                for (i, sub_pat) in sub_patterns.iter().enumerate() {
                    self.emit(OpCode::GetLocal(scrutinee_slot));
                    let i_const =
                        self.state_mut().chunk.add_constant(Constant::Int(i as i64));
                    self.emit(OpCode::Constant(i_const));
                    self.emit(OpCode::Index); // TOS = element (temporary)
                    self.emit_list_element_check(sub_pat)?; // consumes TOS, pushes bool
                    fail_jumps.push(self.emit_jump(OpCode::JumpIfFalseKeep(0)));
                }

                self.emit(OpCode::True);

                for j in fail_jumps {
                    self.patch_jump(j);
                }
            }
        }
        Ok(())
    }

    /// Given an element value on TOS, emit a pattern check that CONSUMES the element
    /// and pushes a Bool result.  Used for list sub-patterns only.
    /// (Binding sub-patterns in lists are treated as Wildcard for now.)
    fn emit_list_element_check(&mut self, pattern: &Pattern) -> Result<(), CompileError> {
        match pattern {
            Pattern::Wildcard | Pattern::Binding(_) => {
                self.emit(OpCode::Pop); // discard element
                self.emit(OpCode::True);
            }
            Pattern::Literal(val) => {
                self.literal(val)?; // push literal
                self.emit(OpCode::Equal); // pops element + literal, pushes bool
            }
            Pattern::Type(name) => {
                self.emit(OpCode::IsA(name.clone())); // pops element, pushes bool
            }
            Pattern::Range(low, high) => {
                // elem is TOS; we need it twice (once per bound). Do not register as a
                // named local — that would corrupt locals.len() across loop iterations.
                let elem_pos = self.state().locals.len();
                // Push a copy so GreaterEqual can consume it without losing the original.
                self.emit(OpCode::GetLocal(elem_pos)); // [elem, elem_copy]
                self.literal(low)?;                    // [elem, elem_copy, low]
                self.emit(OpCode::GreaterEqual);       // [elem, bool1] — copy consumed
                // JumpIfFalse pops bool1 on both branches, leaving [elem] either way.
                let first_fail = self.emit_jump(OpCode::JumpIfFalse(0));
                // True path: [elem]  →  check elem <= high
                self.literal(high)?;                   // [elem, high]
                self.emit(OpCode::LessEqual);          // [bool2] — elem consumed
                let end_jump = self.emit_jump(OpCode::Jump(0));
                // False path: [elem]  →  discard elem, push False
                self.patch_jump(first_fail);
                self.emit(OpCode::Pop);
                self.emit(OpCode::False);
                self.patch_jump(end_jump);
                // Both paths: TOS = bool, original elem consumed.
            }
            Pattern::List(_) => {
                // Nested list patterns not supported in this implementation.
                self.emit(OpCode::Pop);
                self.emit(OpCode::True);
            }
        }
        Ok(())
    }

    /// Compile `begin … rescue … else … end` as an expression: one value on the stack.
    ///
    /// On success, if `else_body` is non-empty the Ruby value is the else branch (body’s
    /// value is discarded).
    fn compile_begin_expr(
        &mut self,
        body: &[Expr],
        rescue_var: &Option<String>,
        rescue_body: &[Expr],
        else_body: &[Expr],
    ) -> Result<(), CompileError> {
        let rescue_var_slot = if let Some(name) = rescue_var {
            let slot = self.state().locals.len();
            self.state_mut().locals.push(LocalInfo {
                name: name.clone(),
                captured: false,
            });
            self.emit(OpCode::Nil);
            slot
        } else {
            usize::MAX
        };

        // Track locals before body so we can pad the rescue path later.
        let locals_before_body = self.state().locals.len();

        // Check BEFORE compiling body: is_new_local_assign checks whether the name is already
        // registered — after body compilation it would be, giving a false negative.
        let body_creates_new_local_result =
            body.last().is_some_and(|e| self.is_new_local_assign(e));

        let begin_idx = self.emit_begin_rescue(rescue_var_slot);

        self.compile_branch(body)?;

        let new_body_locals = self.state().locals.len() - locals_before_body;

        // If body ends with a new-local assign, TOS IS the local's stack slot (no SetLocal
        // was emitted — the push IS the slot). Push a copy so the begin expression's result
        // is a fresh value sitting above all the local slots.
        if body_creates_new_local_result {
            let slot = self.state().locals.len() - 1;
            self.emit(OpCode::GetLocal(slot));
        }

        self.emit(OpCode::PopRescue);
        let jump_over_rescue = self.emit_jump(OpCode::Jump(0));

        self.patch_rescue(begin_idx);

        // On the rescue path the stack is truncated back to pre-body height, losing any
        // slots that were allocated for body locals. Emit Nils to restore those slots so the
        // compiler's locals list stays in sync with the runtime stack layout.
        for _ in 0..new_body_locals {
            self.emit(OpCode::Nil);
        }

        self.compile_branch(rescue_body)?;

        let jump_over_else = self.emit_jump(OpCode::Jump(0));

        self.patch_jump(jump_over_rescue);

        if !else_body.is_empty() {
            self.emit(OpCode::Pop);
            self.compile_branch(else_body)?;
        }

        self.patch_jump(jump_over_else);

        Ok(())
    }

    fn emit_begin_rescue(&mut self, rescue_var_slot: usize) -> usize {
        let idx = self.state().chunk.code.len();
        self.emit(OpCode::BeginRescue {
            handler_offset: 0,
            rescue_var_slot,
        });
        idx
    }

    fn patch_rescue(&mut self, begin_idx: usize) {
        self.state_mut().chunk.patch_rescue(begin_idx);
    }

    /// Compile a block literal into a closure and push it onto the stack.
    /// The block's params become local slots 1..n (slot 0 is the closure itself).
    fn compile_block(&mut self, block: &Block) -> Result<(), CompileError> {
        let line = self.state().current_line;
        let arity = block.params.len();
        self.push_fn("<block>", arity, line);
        // Slot 0 = closure (anonymous; blocks don't recurse by name).
        self.state_mut().locals.push(LocalInfo {
            name: String::new(),
            captured: false,
        });
        for p in &block.params {
            self.state_mut().locals.push(LocalInfo {
                name: p.clone(),
                captured: false,
            });
        }
        self.compile_body(&block.body)?;
        let func = self.pop_fn();
        let idx = self
            .state_mut()
            .chunk
            .add_constant(Constant::Function(func));
        self.emit(OpCode::Closure(idx));
        Ok(())
    }

    fn stmts(&mut self, exprs: &[Expr]) -> Result<(), CompileError> {
        for e in exprs {
            self.stmt(e)?;
        }
        Ok(())
    }

    /// Compile a class definition: emit each method as a closure, then emit
    /// `DefClass` which collects them into a Class value stored as a local.
    ///
    /// `bind` — when `true` (normal top-level class), store the result in a
    /// named local/global slot.  When `false` (nested class), leave the value
    /// on the stack for the enclosing `DefClass` to pick up.
    #[allow(clippy::too_many_arguments)]
    fn compile_class(
        &mut self,
        name: &str,
        class_type_params: &[String],
        superclass: Option<&Expr>,
        includes: &[String],
        is_module: bool,
        is_abstract: bool,
        fields: &[crate::ast::FieldDef],
        methods: &[MethodDef],
        nested: &[Expr],
        constants: &[(String, Box<Expr>)],
        bind: bool,
    ) -> Result<(), CompileError> {
        self.enclosing_class_stack.push(name.to_string());
        let result = self.compile_class_body(
            name,
            class_type_params,
            superclass,
            includes,
            is_module,
            is_abstract,
            fields,
            methods,
            nested,
            constants,
            bind,
        );
        self.enclosing_class_stack.pop();
        result
    }

    #[allow(clippy::too_many_arguments)]
    fn compile_class_body(
        &mut self,
        name: &str,
        class_type_params: &[String],
        superclass: Option<&Expr>,
        includes: &[String],
        is_module: bool,
        is_abstract: bool,
        fields: &[crate::ast::FieldDef],
        methods: &[MethodDef],
        nested: &[Expr],
        constants: &[(String, Box<Expr>)],
        bind: bool,
    ) -> Result<(), CompileError> {
        let line = self.state().current_line;

        let (instance_methods, class_methods): (Vec<&MethodDef>, Vec<&MethodDef>) =
            methods.iter().partition(|m| !m.class_method);

        for m in &instance_methods {
            if m.is_abstract && !is_abstract {
                return Err(self.error(format!(
                    "abstract method '{}' is only allowed in an abstract class",
                    m.name
                )));
            }
        }

        let concrete_instance: Vec<&MethodDef> = instance_methods
            .iter()
            .copied()
            .filter(|m| !m.is_abstract)
            .collect();
        let abstract_method_names: Vec<String> = instance_methods
            .iter()
            .filter(|m| m.is_abstract)
            .map(|m| m.name.clone())
            .collect();

        // Build the set of all type variables in scope for this class.
        let class_tvars: std::collections::HashSet<String> =
            class_type_params.iter().cloned().collect();

        // Emit class method closures first (DefClass pops them in order).
        // Slot 0 = `self` (the class object), not counted in arity.
        for method in &class_methods {
            let arity = method.params.len();
            self.push_fn(&method.name, arity, line);
            self.state_mut().super_method_name = Some(method.name.clone());
            let all_tvars: std::collections::HashSet<String> = class_tvars
                .iter()
                .chain(method.type_params.iter())
                .cloned()
                .collect();
            self.state_mut().return_type = method.return_type.as_ref().and_then(|te| {
                let erased = erase_type_vars(&self.resolve_type_expr(te), &all_tvars);
                self.type_expr_runtime(Some(&erased))
            });
            self.state_mut().locals.push(LocalInfo {
                name: "self".into(),
                captured: false,
            });
            for p in &method.params {
                self.state_mut().locals.push(LocalInfo {
                    name: p.name.clone(),
                    captured: false,
                });
            }
            self.compile_body(&method.body)?;
            let func = self.pop_fn();
            let fi = self
                .state_mut()
                .chunk
                .add_constant(Constant::Function(func));
            self.emit(OpCode::Closure(fi));
        }

        // Emit instance method closures (concrete only).
        for method in &concrete_instance {
            let arity = method.params.len();
            self.push_fn(&method.name, arity, line);
            self.state_mut().super_method_name = Some(method.name.clone());
            let all_tvars: std::collections::HashSet<String> = class_tvars
                .iter()
                .chain(method.type_params.iter())
                .cloned()
                .collect();
            self.state_mut().return_type = method.return_type.as_ref().and_then(|te| {
                let erased = erase_type_vars(&self.resolve_type_expr(te), &all_tvars);
                self.type_expr_runtime(Some(&erased))
            });
            self.state_mut().locals.push(LocalInfo {
                name: "self".into(),
                captured: false,
            });
            for p in &method.params {
                self.state_mut().locals.push(LocalInfo {
                    name: p.name.clone(),
                    captured: false,
                });
            }
            self.compile_body(&method.body)?;
            let func = self.pop_fn();
            let fi = self
                .state_mut()
                .chunk
                .add_constant(Constant::Function(func));
            self.emit(OpCode::Closure(fi));
        }

        // Emit nested class values (each leaves a Class value on the stack).
        let mut nested_class_names: Vec<String> = Vec::new();
        for nested_expr in nested {
            match nested_expr {
                Expr::Class {
                    name: nname,
                    type_params: ntparams,
                    superclass: nsuper,
                    includes: nincludes,
                    is_module: nmodule,
                    is_abstract: nabstract,
                    fields: nfields,
                    methods: nmethods,
                    nested: nnested,
                    constants: nconsts,
                } => {
                    nested_class_names.push(nname.clone());
                    self.compile_class(
                        nname,
                        ntparams,
                        nsuper.as_deref(),
                        nincludes,
                        *nmodule,
                        *nabstract,
                        nfields,
                        nmethods,
                        nnested,
                        nconsts,
                        false,
                    )?;
                }
                _ => {
                    return Err(
                        self.error("nested class body must be a class expression".to_string())
                    );
                }
            }
        }

        // Emit class constants (each leaves a value on the stack, stored in namespace).
        for (cname, cexpr) in constants {
            nested_class_names.push(cname.clone());
            self.expr(cexpr)?;
        }

        let resolved_includes = resolve_include_names(&self.enclosing_class_stack, includes);

        // Resolve superclass: static (simple Variable) vs dynamic (any other expr).
        let (static_super, superclass_dynamic) = match superclass {
            None => (None, false),
            Some(Expr::Variable(sname)) => (Some(sname.as_str()), false),
            Some(expr) => {
                // Dynamic: emit the expression — its value will be on TOS after
                // the nested class values, and DefClass will pop it.
                self.expr(expr)?;
                (None, true)
            }
        };

        let field_names: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
        let field_defaults: Vec<Option<Constant>> = fields
            .iter()
            .map(|f| match &f.default {
                Some(Expr::Literal(Value::Int(n))) => Some(Constant::Int(*n)),
                Some(Expr::Literal(Value::Float(n))) => Some(Constant::Float(*n)),
                Some(Expr::Literal(Value::Str(s))) => Some(Constant::Str(s.clone())),
                _ => None,
            })
            .collect();
        let method_names: Vec<String> = concrete_instance.iter().map(|m| m.name.clone()).collect();
        let private_methods: Vec<String> = concrete_instance
            .iter()
            .filter(|m| m.private)
            .map(|m| m.name.clone())
            .collect();
        let class_method_names: Vec<String> =
            class_methods.iter().map(|m| m.name.clone()).collect();
        let desc_idx = self.state_mut().chunk.add_constant(Constant::ClassDesc {
            name: name.to_string(),
            superclass: static_super.map(|s| s.to_string()),
            superclass_dynamic,
            is_module,
            is_abstract,
            abstract_method_names,
            includes: resolved_includes,
            field_names,
            field_defaults,
            method_names,
            private_methods,
            class_method_names,
            nested_class_names,
        });
        self.emit(OpCode::DefClass(desc_idx));

        if !bind {
            // Nested class: leave the Class value on the stack; the enclosing
            // DefClass will drain it.
            return Ok(());
        }

        if self.global_mode && self.states.len() == 1 {
            // REPL top-level: store in globals, don't allocate a stack slot.
            let ni = self
                .state_mut()
                .chunk
                .add_constant(Constant::Str(name.to_string()));
            self.emit(OpCode::SetGlobal(ni));
        } else {
            // Store the class value in a local slot named after the class.
            self.state_mut().locals.push(LocalInfo {
                name: name.to_string(),
                captured: false,
            });
        }
        Ok(())
    }

    fn error(&self, message: String) -> CompileError {
        CompileError {
            message,
            line: self.state().current_line,
            column: self.state().current_column,
        }
    }
}

// Re-export compile as the public API.
pub fn compile(exprs: &[Expr]) -> Result<Rc<Function>, CompileError> {
    Compiler::compile(exprs)
}

pub fn compile_repl(exprs: &[Expr]) -> Result<Rc<Function>, CompileError> {
    Compiler::compile_repl(exprs)
}

fn resolve_include_names(enclosing_stack: &[String], includes: &[String]) -> Vec<String> {
    let mut out = Vec::with_capacity(includes.len());
    for inc in includes {
        let resolved = if inc.contains('.') {
            let mut parts: Vec<&str> = inc.split('.').collect();
            let Some(last) = parts.pop() else {
                continue;
            };
            let mut keys: Vec<String> = Vec::new();
            for ec in enclosing_stack {
                keys.push(ec.clone());
            }
            for p in parts {
                keys.push(p.to_string());
            }
            keys.push(last.to_string());
            keys.join(".")
        } else {
            inc.clone()
        };
        out.push(resolved);
    }
    out
}

/// Replace any Named type that is a type variable with `Any` so the compiler
/// emits no runtime check for it.  Call before `type_expr_runtime`.
fn erase_type_vars(te: &TypeExpr, type_vars: &std::collections::HashSet<String>) -> TypeExpr {
    match te {
        TypeExpr::Named(n) if type_vars.contains(n.as_str()) => TypeExpr::Any,
        TypeExpr::Apply(n, args) => TypeExpr::Apply(
            n.clone(),
            args.iter().map(|a| erase_type_vars(a, type_vars)).collect(),
        ),
        TypeExpr::Union(arms) => {
            TypeExpr::Union(arms.iter().map(|a| erase_type_vars(a, type_vars)).collect())
        }
        other => other.clone(),
    }
}

/// Convert an optional `TypeExpr` to a runtime-checkable representation.
/// Returns `None` for absent annotations and `TypeExpr::Any`.
fn type_expr_runtime(te: Option<&TypeExpr>) -> Option<RuntimeType> {
    match te {
        Some(TypeExpr::Named(n)) => Some(RuntimeType::Named(n.clone())),
        Some(TypeExpr::Apply(n, _)) => Some(RuntimeType::Named(n.clone())),
        Some(TypeExpr::Literal(v)) => Some(RuntimeType::Literal(v.clone())),
        Some(TypeExpr::Any) | None => None,
        Some(TypeExpr::Union(arms)) => {
            let parts: Vec<RuntimeType> = arms
                .iter()
                .filter_map(|a| type_expr_runtime(Some(a)))
                .collect();
            if parts.is_empty() {
                None
            } else {
                Some(RuntimeType::Union(parts))
            }
        }
    }
}

impl Compiler {
    fn type_expr_runtime(&self, te: Option<&TypeExpr>) -> Option<RuntimeType> {
        match te {
            Some(TypeExpr::Named(n)) | Some(TypeExpr::Apply(n, _))
                if self.interfaces.contains(n) =>
            {
                None
            }
            Some(TypeExpr::Union(arms)) => {
                let parts: Vec<RuntimeType> = arms
                    .iter()
                    .filter_map(|a| self.type_expr_runtime(Some(a)))
                    .collect();
                if parts.is_empty() {
                    None
                } else {
                    Some(RuntimeType::Union(parts))
                }
            }
            other => type_expr_runtime(other),
        }
    }
}