ion-core 0.2.1

Embeddable scripting language with a bytecode VM
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
//! AST → Bytecode compiler for the Ion VM.

use crate::ast::*;
use crate::bytecode::{Chunk, Op};
use crate::error::IonError;
use crate::value::{FnChunkCache, Value};

/// A local variable tracked at compile time for stack-slot resolution.
#[derive(Debug, Clone)]
struct Local {
    name: String,
    depth: usize,
}

pub struct Compiler {
    chunk: Chunk,
    /// Precompiled function body chunks, keyed by fn_id.
    pub fn_chunks: FnChunkCache,
    /// Whether the next expression is in tail position (for TCO).
    in_tail_position: bool,
    /// Compile-time local variable tracking for stack-slot resolution.
    locals: Vec<Local>,
    /// Current scope depth.
    scope_depth: usize,
    /// Whether locals must also be defined in env (needed when closures exist).
    needs_env_locals: bool,
    /// Pending break jump offsets to patch when loop ends.
    break_jumps: Vec<usize>,
    /// Loop start offset for continue jumps (used by while/loop).
    continue_target: Option<usize>,
    /// Whether we're inside a for-loop (break needs iterator cleanup, continue needs scope cleanup).
    in_for_loop: bool,
    /// Scope depth at the start of the current loop (for break/continue scope cleanup).
    loop_scope_depth: usize,
}

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

impl Compiler {
    pub fn new() -> Self {
        Self {
            chunk: Chunk::new(),
            fn_chunks: FnChunkCache::new(),
            in_tail_position: false,
            locals: Vec::new(),
            scope_depth: 0,
            needs_env_locals: true, // conservative default for top-level
            break_jumps: Vec::new(),
            continue_target: None,
            in_for_loop: false,
            loop_scope_depth: 0,
        }
    }

    /// Check if a list of statements contains any closures (lambdas or inner fn decls).
    fn stmts_have_closures(stmts: &[Stmt]) -> bool {
        for stmt in stmts {
            match &stmt.kind {
                StmtKind::FnDecl { body: _, .. } => {
                    // Inner fn decl itself is a closure; also check its body
                    return true;
                    // Note: we don't need to recurse — just the presence of a fn decl
                    // in the current scope means outer locals might be captured
                }
                StmtKind::ExprStmt { expr, .. } if Self::expr_has_closures(expr) => {
                    return true;
                }
                StmtKind::Let { value, .. } if Self::expr_has_closures(value) => {
                    return true;
                }
                StmtKind::For { body, iter, .. } => {
                    if Self::expr_has_closures(iter) {
                        return true;
                    }
                    if Self::stmts_have_closures(body) {
                        return true;
                    }
                }
                StmtKind::While { cond, body } => {
                    if Self::expr_has_closures(cond) {
                        return true;
                    }
                    if Self::stmts_have_closures(body) {
                        return true;
                    }
                }
                StmtKind::Loop { body } if Self::stmts_have_closures(body) => {
                    return true;
                }
                StmtKind::Return { value: Some(e) } if Self::expr_has_closures(e) => {
                    return true;
                }
                StmtKind::Assign { value, .. } if Self::expr_has_closures(value) => {
                    return true;
                }
                StmtKind::WhileLet { expr, body, .. } => {
                    if Self::expr_has_closures(expr) {
                        return true;
                    }
                    if Self::stmts_have_closures(body) {
                        return true;
                    }
                }
                _ => {}
            }
        }
        false
    }

    fn expr_has_closures(expr: &Expr) -> bool {
        match &expr.kind {
            ExprKind::Lambda { .. } => true,
            ExprKind::If {
                cond,
                then_body,
                else_body,
            } => {
                Self::expr_has_closures(cond)
                    || Self::stmts_have_closures(then_body)
                    || else_body
                        .as_ref()
                        .is_some_and(|b| Self::stmts_have_closures(b))
            }
            ExprKind::Block(stmts) => Self::stmts_have_closures(stmts),
            ExprKind::Call { func, args } => {
                Self::expr_has_closures(func)
                    || args.iter().any(|a| Self::expr_has_closures(&a.value))
            }
            ExprKind::MethodCall { expr, args, .. } => {
                Self::expr_has_closures(expr)
                    || args.iter().any(|a| Self::expr_has_closures(&a.value))
            }
            ExprKind::BinOp { left, right, .. } => {
                Self::expr_has_closures(left) || Self::expr_has_closures(right)
            }
            ExprKind::UnaryOp { expr, .. } => Self::expr_has_closures(expr),
            ExprKind::PipeOp { left, right } => {
                Self::expr_has_closures(left) || Self::expr_has_closures(right)
            }
            ExprKind::Match { expr, arms } => {
                Self::expr_has_closures(expr)
                    || arms.iter().any(|a| Self::expr_has_closures(&a.body))
            }
            ExprKind::List(items) => items.iter().any(|e| match e {
                ListEntry::Elem(expr) | ListEntry::Spread(expr) => Self::expr_has_closures(expr),
            }),
            ExprKind::Tuple(items) => items.iter().any(Self::expr_has_closures),
            ExprKind::ListComp {
                expr, iter, cond, ..
            } => {
                Self::expr_has_closures(expr)
                    || Self::expr_has_closures(iter)
                    || cond.as_ref().is_some_and(|c| Self::expr_has_closures(c))
            }
            ExprKind::IfLet {
                expr,
                then_body,
                else_body,
                ..
            } => {
                Self::expr_has_closures(expr)
                    || Self::stmts_have_closures(then_body)
                    || else_body
                        .as_ref()
                        .is_some_and(|b| Self::stmts_have_closures(b))
            }
            ExprKind::TryCatch { body, handler, .. } => {
                Self::stmts_have_closures(body) || Self::stmts_have_closures(handler)
            }
            ExprKind::LoopExpr(stmts) => Self::stmts_have_closures(stmts),
            ExprKind::Range { start, end, .. } => {
                Self::expr_has_closures(start) || Self::expr_has_closures(end)
            }
            ExprKind::Dict(entries) => entries.iter().any(|e| match e {
                DictEntry::KeyValue(k, v) => {
                    Self::expr_has_closures(k) || Self::expr_has_closures(v)
                }
                DictEntry::Spread(expr) => Self::expr_has_closures(expr),
            }),
            ExprKind::DictComp {
                key,
                value,
                iter,
                cond,
                ..
            } => {
                Self::expr_has_closures(key)
                    || Self::expr_has_closures(value)
                    || Self::expr_has_closures(iter)
                    || cond.as_ref().is_some_and(|c| Self::expr_has_closures(c))
            }
            ExprKind::FieldAccess { expr, .. }
            | ExprKind::Try(expr)
            | ExprKind::SomeExpr(expr)
            | ExprKind::OkExpr(expr)
            | ExprKind::ErrExpr(expr) => Self::expr_has_closures(expr),
            ExprKind::Index { expr, index } => {
                Self::expr_has_closures(expr) || Self::expr_has_closures(index)
            }
            ExprKind::Slice {
                expr, start, end, ..
            } => {
                Self::expr_has_closures(expr)
                    || start.as_ref().is_some_and(|s| Self::expr_has_closures(s))
                    || end.as_ref().is_some_and(|e| Self::expr_has_closures(e))
            }
            ExprKind::FStr(parts) => parts.iter().any(|p| match p {
                FStrPart::Expr(e) => Self::expr_has_closures(e),
                _ => false,
            }),
            ExprKind::StructConstruct { fields, spread, .. } => {
                fields.iter().any(|(_, e)| Self::expr_has_closures(e))
                    || spread.as_ref().is_some_and(|s| Self::expr_has_closures(s))
            }
            _ => false,
        }
    }

    /// Try to constant-fold a binary operation on two literal operands.
    #[cfg(feature = "optimize")]
    fn try_fold_binop(left: &Expr, op: &BinOp, right: &Expr) -> Option<Value> {
        match (&left.kind, op, &right.kind) {
            // Int op Int
            (ExprKind::Int(a), BinOp::Add, ExprKind::Int(b)) => {
                Some(Value::Int(a.wrapping_add(*b)))
            }
            (ExprKind::Int(a), BinOp::Sub, ExprKind::Int(b)) => {
                Some(Value::Int(a.wrapping_sub(*b)))
            }
            (ExprKind::Int(a), BinOp::Mul, ExprKind::Int(b)) => {
                Some(Value::Int(a.wrapping_mul(*b)))
            }
            (ExprKind::Int(a), BinOp::Div, ExprKind::Int(b)) if *b != 0 => Some(Value::Int(a / b)),
            (ExprKind::Int(a), BinOp::Mod, ExprKind::Int(b)) if *b != 0 => Some(Value::Int(a % b)),
            (ExprKind::Int(a), BinOp::Eq, ExprKind::Int(b)) => Some(Value::Bool(a == b)),
            (ExprKind::Int(a), BinOp::Ne, ExprKind::Int(b)) => Some(Value::Bool(a != b)),
            (ExprKind::Int(a), BinOp::Lt, ExprKind::Int(b)) => Some(Value::Bool(a < b)),
            (ExprKind::Int(a), BinOp::Gt, ExprKind::Int(b)) => Some(Value::Bool(a > b)),
            (ExprKind::Int(a), BinOp::Le, ExprKind::Int(b)) => Some(Value::Bool(a <= b)),
            (ExprKind::Int(a), BinOp::Ge, ExprKind::Int(b)) => Some(Value::Bool(a >= b)),
            (ExprKind::Int(a), BinOp::BitAnd, ExprKind::Int(b)) => Some(Value::Int(a & b)),
            (ExprKind::Int(a), BinOp::BitOr, ExprKind::Int(b)) => Some(Value::Int(a | b)),
            (ExprKind::Int(a), BinOp::BitXor, ExprKind::Int(b)) => Some(Value::Int(a ^ b)),
            (ExprKind::Int(a), BinOp::Shl, ExprKind::Int(b)) if (0..64).contains(b) => {
                Some(Value::Int(a << (*b as u32)))
            }
            (ExprKind::Int(a), BinOp::Shr, ExprKind::Int(b)) if (0..64).contains(b) => {
                Some(Value::Int(a >> (*b as u32)))
            }
            // Float op Float
            (ExprKind::Float(a), BinOp::Add, ExprKind::Float(b)) => Some(Value::Float(a + b)),
            (ExprKind::Float(a), BinOp::Sub, ExprKind::Float(b)) => Some(Value::Float(a - b)),
            (ExprKind::Float(a), BinOp::Mul, ExprKind::Float(b)) => Some(Value::Float(a * b)),
            (ExprKind::Float(a), BinOp::Div, ExprKind::Float(b)) => Some(Value::Float(a / b)),
            (ExprKind::Float(a), BinOp::Mod, ExprKind::Float(b)) => Some(Value::Float(a % b)),
            // Int op Float / Float op Int
            (ExprKind::Int(a), BinOp::Add, ExprKind::Float(b)) => Some(Value::Float(*a as f64 + b)),
            (ExprKind::Float(a), BinOp::Add, ExprKind::Int(b)) => Some(Value::Float(a + *b as f64)),
            (ExprKind::Int(a), BinOp::Sub, ExprKind::Float(b)) => Some(Value::Float(*a as f64 - b)),
            (ExprKind::Float(a), BinOp::Sub, ExprKind::Int(b)) => Some(Value::Float(a - *b as f64)),
            (ExprKind::Int(a), BinOp::Mul, ExprKind::Float(b)) => Some(Value::Float(*a as f64 * b)),
            (ExprKind::Float(a), BinOp::Mul, ExprKind::Int(b)) => Some(Value::Float(a * *b as f64)),
            (ExprKind::Int(a), BinOp::Div, ExprKind::Float(b)) => Some(Value::Float(*a as f64 / b)),
            (ExprKind::Float(a), BinOp::Div, ExprKind::Int(b)) => Some(Value::Float(a / *b as f64)),
            // String concat
            (ExprKind::Str(a), BinOp::Add, ExprKind::Str(b)) => {
                let mut s = a.clone();
                s.push_str(b);
                Some(Value::Str(s))
            }
            // Bool logic
            (ExprKind::Bool(a), BinOp::And, ExprKind::Bool(b)) => Some(Value::Bool(*a && *b)),
            (ExprKind::Bool(a), BinOp::Or, ExprKind::Bool(b)) => Some(Value::Bool(*a || *b)),
            (ExprKind::Bool(a), BinOp::Eq, ExprKind::Bool(b)) => Some(Value::Bool(a == b)),
            (ExprKind::Bool(a), BinOp::Ne, ExprKind::Bool(b)) => Some(Value::Bool(a != b)),
            _ => None,
        }
    }

    /// Try to constant-fold a unary operation on a literal operand.
    #[cfg(feature = "optimize")]
    fn try_fold_unary(op: &UnaryOp, inner: &Expr) -> Option<Value> {
        match (op, &inner.kind) {
            (UnaryOp::Neg, ExprKind::Int(v)) => Some(Value::Int(-v)),
            (UnaryOp::Neg, ExprKind::Float(v)) => Some(Value::Float(-v)),
            (UnaryOp::Not, ExprKind::Bool(v)) => Some(Value::Bool(!v)),
            _ => None,
        }
    }

    /// Check if a statement is terminal (control never continues past it).
    #[cfg(feature = "optimize")]
    fn stmt_is_terminal(stmt: &Stmt) -> bool {
        matches!(
            &stmt.kind,
            StmtKind::Return { .. } | StmtKind::Break { .. } | StmtKind::Continue
        )
    }

    /// Resolve a local variable name to its slot index (searching innermost first).
    fn resolve_local(&self, name: &str) -> Option<usize> {
        for (i, local) in self.locals.iter().enumerate().rev() {
            if local.name == name {
                return Some(i);
            }
        }
        None
    }

    /// Add a local variable to the compile-time tracking.
    fn add_local(&mut self, name: String, _mutable: bool) {
        self.locals.push(Local {
            name,
            depth: self.scope_depth,
        });
    }

    /// Begin a new compile-time scope and emit PushScope.
    fn begin_scope(&mut self, line: usize) {
        self.scope_depth += 1;
        self.chunk.emit_op(Op::PushScope, line);
    }

    /// Emit a variable read (GetLocalSlot or GetGlobal).
    fn emit_get_var(&mut self, name: &str, line: usize) {
        if let Some(slot) = self.resolve_local(name) {
            self.chunk.emit_op_u16(Op::GetLocalSlot, slot as u16, line);
        } else {
            let idx = self.chunk.add_constant(Value::Str(name.to_string()));
            self.chunk.emit_op_u16(Op::GetGlobal, idx, line);
        }
    }

    /// Define a new local variable. When closures exist, also stores in env.
    /// The value must be on top of the stack.
    fn emit_define_local(&mut self, name: &str, mutable: bool, line: usize) {
        self.add_local(name.to_string(), mutable);
        if self.needs_env_locals {
            // Dup value: one copy for env (closure capture), one for slot
            self.chunk.emit_op(Op::Dup, line);
            let idx = self.chunk.add_constant(Value::Str(name.to_string()));
            self.chunk.emit_op_u16(Op::DefineLocal, idx, line);
            self.chunk.emit(if mutable { 1 } else { 0 }, line);
        }
        self.chunk
            .emit_op_u8(Op::DefineLocalSlot, if mutable { 1 } else { 0 }, line);
    }

    /// Emit a variable write (SetLocalSlot or SetGlobal).
    fn emit_set_var(&mut self, name: &str, line: usize) {
        if let Some(slot) = self.resolve_local(name) {
            self.chunk.emit_op_u16(Op::SetLocalSlot, slot as u16, line);
        } else {
            let idx = self.chunk.add_constant(Value::Str(name.to_string()));
            self.chunk.emit_op_u16(Op::SetGlobal, idx, line);
        }
    }

    /// End the current compile-time scope, emit PopScope.
    fn end_scope(&mut self, line: usize) {
        while let Some(local) = self.locals.last() {
            if local.depth < self.scope_depth {
                break;
            }
            self.locals.pop();
        }
        self.scope_depth -= 1;
        self.chunk.emit_op(Op::PopScope, line);
    }

    pub fn compile_program(mut self, program: &Program) -> Result<(Chunk, FnChunkCache), IonError> {
        let len = program.stmts.len();
        for (i, stmt) in program.stmts.iter().enumerate() {
            let is_last = i == len - 1;
            match &stmt.kind {
                StmtKind::ExprStmt { expr, has_semi } => {
                    self.compile_expr(expr)?;
                    if is_last && !has_semi {
                        // Keep the value as the program result
                    } else {
                        self.chunk.emit_op(Op::Pop, stmt.span.line);
                    }
                }
                _ => {
                    self.compile_stmt(stmt)?;
                    if is_last {
                        // Statements produce Unit as the program result
                        self.chunk.emit_op(Op::Unit, stmt.span.line);
                    }
                }
            }
            #[cfg(feature = "optimize")]
            if !is_last && Self::stmt_is_terminal(stmt) {
                break;
            }
        }
        if program.stmts.is_empty() {
            self.chunk.emit_op(Op::Unit, 0);
        }
        self.chunk.emit_op(Op::Return, 0);
        #[cfg(feature = "optimize")]
        self.chunk.peephole_optimize();
        Ok((self.chunk, self.fn_chunks))
    }

    fn compile_stmt(&mut self, stmt: &Stmt) -> Result<(), IonError> {
        let line = stmt.span.line;
        match &stmt.kind {
            StmtKind::Let {
                mutable,
                pattern,
                type_ann,
                value,
            } => {
                self.compile_expr(value)?;
                if let Some(ann) = type_ann {
                    let type_name = Self::type_ann_to_string(ann);
                    let idx = self.chunk.add_constant(Value::Str(type_name));
                    self.chunk.emit_op_u16(Op::CheckType, idx, line);
                }
                self.compile_let_pattern(pattern, *mutable, line)?;
            }
            StmtKind::ExprStmt { expr, .. } => {
                self.compile_expr(expr)?;
                self.chunk.emit_op(Op::Pop, line);
            }
            StmtKind::FnDecl { name, params, body } => {
                self.compile_fn_decl(name, params, body, line)?;
            }
            StmtKind::For {
                pattern,
                iter,
                body,
            } => {
                self.compile_for(pattern, iter, body, line)?;
            }
            StmtKind::While { cond, body } => {
                self.compile_while(cond, body, line)?;
            }
            StmtKind::Loop { body } => {
                self.compile_loop(body, line)?;
            }
            StmtKind::Break { value } => {
                if self.continue_target.is_none() {
                    return Err(IonError::runtime(
                        ion_str!("break outside of loop").to_string(),
                        line,
                        0,
                    ));
                }
                if let Some(expr) = value {
                    self.compile_expr(expr)?;
                } else {
                    self.chunk.emit_op(Op::Unit, line);
                }
                // Pop all scopes back to the loop's scope level
                for _ in self.loop_scope_depth..self.scope_depth {
                    self.chunk.emit_op(Op::PopScope, line);
                }
                if self.in_for_loop {
                    self.chunk.emit_op(Op::IterDrop, line);
                }
                let jump = self.chunk.emit_jump(Op::Jump, line);
                self.break_jumps.push(jump);
            }
            StmtKind::Continue => {
                if let Some(target) = self.continue_target {
                    // Pop all scopes back to the loop's scope level
                    for _ in self.loop_scope_depth..self.scope_depth {
                        self.chunk.emit_op(Op::PopScope, line);
                    }
                    if self.in_for_loop {
                        // For-loop: push Unit placeholder for IterNext
                        self.chunk.emit_op(Op::Unit, line);
                    }
                    let offset = self.chunk.len() - target + 3;
                    self.chunk.emit_op_u16(Op::Loop, offset as u16, line);
                } else {
                    return Err(IonError::runtime(
                        ion_str!("continue outside of loop").to_string(),
                        line,
                        0,
                    ));
                }
            }
            StmtKind::Return { value } => {
                if let Some(expr) = value {
                    let saved = self.in_tail_position;
                    self.in_tail_position = true;
                    self.compile_expr(expr)?;
                    self.in_tail_position = saved;
                } else {
                    self.chunk.emit_op(Op::Unit, line);
                }
                self.chunk.emit_op(Op::Return, line);
            }
            StmtKind::Assign { target, op, value } => {
                self.compile_assign(target, op, value, line)?;
                self.chunk.emit_op(Op::Pop, line); // discard assignment result
            }
            StmtKind::Use { .. } => {
                // Use statements modify global scope at runtime — bail to tree-walk
                return Err(IonError::runtime(
                    ion_str!("use statements not yet supported in VM"),
                    line,
                    0,
                ));
            }
            StmtKind::WhileLet {
                pattern,
                expr,
                body,
            } => {
                let saved_breaks = std::mem::take(&mut self.break_jumps);
                let saved_in_for = self.in_for_loop;
                let saved_loop_depth = self.loop_scope_depth;
                self.in_for_loop = false;
                self.loop_scope_depth = self.scope_depth;
                let saved_continue = self.continue_target.take();

                let loop_start = self.chunk.len();
                self.continue_target = Some(loop_start);

                // Evaluate expression
                self.compile_expr(expr)?;

                // Test pattern
                self.chunk.emit_op(Op::Dup, line); // keep value for binding
                self.compile_pattern_test(pattern, line)?;

                let exit_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true

                // Pattern matched — bind and execute body
                self.begin_scope(line);
                self.compile_pattern_bind(pattern, line)?;
                for stmt in body {
                    self.compile_stmt(stmt)?;
                    #[cfg(feature = "optimize")]
                    if Self::stmt_is_terminal(stmt) {
                        break;
                    }
                }
                self.end_scope(line);

                let offset = self.chunk.len() - loop_start + 3;
                self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

                self.chunk.patch_jump(exit_jump);
                self.chunk.emit_op(Op::Pop, line); // pop false
                self.chunk.emit_op(Op::Pop, line); // pop the duped value

                for jump in &self.break_jumps {
                    self.chunk.patch_jump(*jump);
                }
                self.break_jumps = saved_breaks;
                self.continue_target = saved_continue;
                self.in_for_loop = saved_in_for;
                self.loop_scope_depth = saved_loop_depth;
            }
        }
        Ok(())
    }

    fn compile_expr(&mut self, expr: &Expr) -> Result<(), IonError> {
        let line = expr.span.line;
        let col = expr.span.col;
        // Save tail position — only Call, If, Block, Match, IfLet propagate it
        let was_tail = self.in_tail_position;
        self.in_tail_position = false;
        match &expr.kind {
            ExprKind::Int(n) => {
                self.chunk.emit_constant(Value::Int(*n), line);
            }
            ExprKind::Float(n) => {
                self.chunk.emit_constant(Value::Float(*n), line);
            }
            ExprKind::Bool(b) => {
                self.chunk
                    .emit_op(if *b { Op::True } else { Op::False }, line);
            }
            ExprKind::Str(s) => {
                self.chunk.emit_constant(Value::Str(s.clone()), line);
            }
            ExprKind::Bytes(b) => {
                self.chunk.emit_constant(Value::Bytes(b.clone()), line);
            }
            ExprKind::Unit => {
                self.chunk.emit_op(Op::Unit, line);
            }
            ExprKind::None => {
                self.chunk.emit_op(Op::None, line);
            }
            ExprKind::SomeExpr(inner) => {
                self.compile_expr(inner)?;
                self.chunk.emit_op(Op::WrapSome, line);
            }
            ExprKind::OkExpr(inner) => {
                self.compile_expr(inner)?;
                self.chunk.emit_op(Op::WrapOk, line);
            }
            ExprKind::ErrExpr(inner) => {
                self.compile_expr(inner)?;
                self.chunk.emit_op(Op::WrapErr, line);
            }

            ExprKind::Ident(name) => {
                if let Some(slot) = self.resolve_local(name) {
                    self.chunk.emit_op_u16(Op::GetLocalSlot, slot as u16, line);
                } else {
                    let idx = self.chunk.add_constant(Value::Str(name.clone()));
                    self.chunk.emit_op_u16(Op::GetGlobal, idx, line);
                }
            }

            ExprKind::ModulePath(segments) => {
                // Load root module as global, then chain GetField for each segment
                let root_idx = self.chunk.add_constant(Value::Str(segments[0].clone()));
                self.chunk.emit_op_u16(Op::GetGlobal, root_idx, line);
                for seg in &segments[1..] {
                    let idx = self.chunk.add_constant(Value::Str(seg.clone()));
                    self.chunk.emit_op_u16_span(Op::GetField, idx, line, col);
                }
            }

            ExprKind::BinOp { left, op, right } => {
                // Constant folding: evaluate at compile time if both sides are literals
                #[cfg(feature = "optimize")]
                let folded = Self::try_fold_binop(left, op, right);
                #[cfg(not(feature = "optimize"))]
                let folded: Option<Value> = None;
                if let Some(val) = folded {
                    self.chunk.emit_constant(val, line);
                } else {
                    match op {
                        BinOp::And => {
                            self.compile_expr(left)?;
                            let jump = self.chunk.emit_jump(Op::And, line);
                            self.chunk.emit_op(Op::Pop, line);
                            self.compile_expr(right)?;
                            self.chunk.patch_jump(jump);
                        }
                        BinOp::Or => {
                            self.compile_expr(left)?;
                            let jump = self.chunk.emit_jump(Op::Or, line);
                            self.chunk.emit_op(Op::Pop, line);
                            self.compile_expr(right)?;
                            self.chunk.patch_jump(jump);
                        }
                        _ => {
                            self.compile_expr(left)?;
                            self.compile_expr(right)?;
                            match op {
                                BinOp::Add => self.chunk.emit_op_span(Op::Add, line, col),
                                BinOp::Sub => self.chunk.emit_op_span(Op::Sub, line, col),
                                BinOp::Mul => self.chunk.emit_op_span(Op::Mul, line, col),
                                BinOp::Div => self.chunk.emit_op_span(Op::Div, line, col),
                                BinOp::Mod => self.chunk.emit_op_span(Op::Mod, line, col),
                                BinOp::Eq => self.chunk.emit_op(Op::Eq, line),
                                BinOp::Ne => self.chunk.emit_op(Op::NotEq, line),
                                BinOp::Lt => self.chunk.emit_op(Op::Lt, line),
                                BinOp::Gt => self.chunk.emit_op(Op::Gt, line),
                                BinOp::Le => self.chunk.emit_op(Op::LtEq, line),
                                BinOp::Ge => self.chunk.emit_op(Op::GtEq, line),
                                BinOp::BitAnd => self.chunk.emit_op(Op::BitAnd, line),
                                BinOp::BitOr => self.chunk.emit_op(Op::BitOr, line),
                                BinOp::BitXor => self.chunk.emit_op(Op::BitXor, line),
                                BinOp::Shl => self.chunk.emit_op(Op::Shl, line),
                                BinOp::Shr => self.chunk.emit_op(Op::Shr, line),
                                _ => unreachable!(),
                            }
                        }
                    }
                }
            }

            ExprKind::UnaryOp { op, expr: inner } => {
                #[cfg(feature = "optimize")]
                let folded = Self::try_fold_unary(op, inner);
                #[cfg(not(feature = "optimize"))]
                let folded: Option<Value> = None;
                if let Some(val) = folded {
                    self.chunk.emit_constant(val, line);
                } else {
                    self.compile_expr(inner)?;
                    match op {
                        UnaryOp::Neg => self.chunk.emit_op_span(Op::Neg, line, col),
                        UnaryOp::Not => self.chunk.emit_op_span(Op::Not, line, col),
                    }
                }
            }

            ExprKind::If {
                cond,
                then_body,
                else_body,
            } => {
                // Condition is not in tail position (already cleared)
                self.compile_expr(cond)?;
                let then_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop condition
                self.begin_scope(line);
                // Both branches inherit tail position
                self.in_tail_position = was_tail;
                self.compile_block_expr(then_body, line)?;
                self.end_scope(line);
                let else_jump = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(then_jump);
                self.chunk.emit_op(Op::Pop, line); // pop condition
                if let Some(else_stmts) = else_body {
                    self.begin_scope(line);
                    self.in_tail_position = was_tail;
                    self.compile_block_expr(else_stmts, line)?;
                    self.end_scope(line);
                } else {
                    self.chunk.emit_op(Op::Unit, line);
                }
                self.chunk.patch_jump(else_jump);
            }

            ExprKind::Block(stmts) => {
                self.begin_scope(line);
                self.in_tail_position = was_tail;
                self.compile_block_expr(stmts, line)?;
                self.end_scope(line);
            }

            ExprKind::Call { func, args } => {
                let has_named = args.iter().any(|a| a.name.is_some());
                // Sub-expressions are not in tail position (already cleared above)
                self.compile_expr(func)?;
                for arg in args {
                    self.compile_expr(&arg.value)?;
                }
                if has_named {
                    // Emit CallNamed: total_args, named_count, then (position, name_idx) pairs
                    let named: Vec<(u8, u16)> = args
                        .iter()
                        .enumerate()
                        .filter_map(|(i, a)| {
                            a.name
                                .as_ref()
                                .map(|n| (i as u8, self.chunk.add_constant(Value::Str(n.clone()))))
                        })
                        .collect();
                    self.chunk.emit_op(Op::CallNamed, line);
                    self.chunk.emit(args.len() as u8, line);
                    self.chunk.emit(named.len() as u8, line);
                    for (pos, name_idx) in named {
                        self.chunk.emit(pos, line);
                        self.chunk.emit((name_idx >> 8) as u8, line);
                        self.chunk.emit(name_idx as u8, line);
                    }
                } else {
                    #[cfg(feature = "optimize")]
                    let op = if was_tail { Op::TailCall } else { Op::Call };
                    #[cfg(not(feature = "optimize"))]
                    let op = Op::Call;
                    self.chunk.emit_op_u8_span(op, args.len() as u8, line, col);
                }
            }

            ExprKind::List(items) => {
                let has_spread = items.iter().any(|e| matches!(e, ListEntry::Spread(_)));
                if has_spread {
                    // Build empty list, then append/extend entries one by one
                    self.chunk.emit_op_u16(Op::BuildList, 0, line);
                    for entry in items {
                        match entry {
                            ListEntry::Elem(expr) => {
                                self.compile_expr(expr)?;
                                self.chunk.emit_op(Op::ListAppend, line);
                            }
                            ListEntry::Spread(expr) => {
                                self.compile_expr(expr)?;
                                self.chunk.emit_op(Op::ListExtend, line);
                            }
                        }
                    }
                } else {
                    // Fast path: no spreads, use BuildList directly
                    for entry in items {
                        if let ListEntry::Elem(expr) = entry {
                            self.compile_expr(expr)?;
                        }
                    }
                    self.chunk
                        .emit_op_u16(Op::BuildList, items.len() as u16, line);
                }
            }

            ExprKind::Tuple(items) => {
                for item in items {
                    self.compile_expr(item)?;
                }
                self.chunk
                    .emit_op_u16(Op::BuildTuple, items.len() as u16, line);
            }

            ExprKind::Dict(entries) => {
                let has_spread = entries.iter().any(|e| matches!(e, DictEntry::Spread(_)));
                if has_spread {
                    // Build empty dict, then insert/merge entries one by one
                    self.chunk.emit_op_u16(Op::BuildDict, 0, line);
                    for entry in entries {
                        match entry {
                            DictEntry::KeyValue(k, v) => {
                                self.compile_expr(k)?;
                                self.compile_expr(v)?;
                                self.chunk.emit_op(Op::DictInsert, line);
                            }
                            DictEntry::Spread(expr) => {
                                self.compile_expr(expr)?;
                                self.chunk.emit_op(Op::DictMerge, line);
                            }
                        }
                    }
                } else {
                    // Fast path: no spreads, use BuildDict directly
                    let count = entries.len() as u16;
                    for entry in entries {
                        if let DictEntry::KeyValue(k, v) = entry {
                            self.compile_expr(k)?;
                            self.compile_expr(v)?;
                        }
                    }
                    self.chunk.emit_op_u16(Op::BuildDict, count, line);
                }
            }

            ExprKind::FieldAccess { expr: inner, field } => {
                self.compile_expr(inner)?;
                let idx = self.chunk.add_constant(Value::Str(field.clone()));
                self.chunk.emit_op_u16_span(Op::GetField, idx, line, col);
            }

            ExprKind::Index { expr: inner, index } => {
                self.compile_expr(inner)?;
                self.compile_expr(index)?;
                self.chunk.emit_op_span(Op::GetIndex, line, col);
            }

            ExprKind::Slice {
                expr: inner,
                start,
                end,
                inclusive,
            } => {
                self.compile_expr(inner)?;
                let mut flags: u8 = 0;
                if let Some(s) = start {
                    self.compile_expr(s)?;
                    flags |= 1; // has_start
                }
                if let Some(e) = end {
                    self.compile_expr(e)?;
                    flags |= 2; // has_end
                }
                if *inclusive {
                    flags |= 4; // inclusive
                }
                self.chunk.emit_op_u8(Op::Slice, flags, line);
            }

            ExprKind::MethodCall {
                expr: inner,
                method,
                args,
            } => {
                self.compile_expr(inner)?;
                for arg in args {
                    self.compile_expr(&arg.value)?;
                }
                let idx = self.chunk.add_constant(Value::Str(method.clone()));
                self.chunk.emit_op_u16_span(Op::MethodCall, idx, line, col);
                self.chunk.emit_span(args.len() as u8, line, col);
            }

            ExprKind::Lambda { params, body } => {
                // Build lambda body as a single expression statement for tree-walk fallback
                let body_stmt = Stmt {
                    kind: StmtKind::ExprStmt {
                        expr: *body.clone(),
                        has_semi: false,
                    },
                    span: expr.span,
                };
                // Precompile lambda body
                let mut fn_compiler = Compiler::new();
                fn_compiler.in_tail_position = true;
                fn_compiler.needs_env_locals = Self::expr_has_closures(body);
                // Pre-register parameters as locals
                for p in params {
                    fn_compiler.add_local(p.clone(), false);
                }
                // When closures exist, also define params in env so they can be captured
                if fn_compiler.needs_env_locals {
                    for (i, p) in params.iter().enumerate() {
                        fn_compiler
                            .chunk
                            .emit_op_u16(Op::GetLocalSlot, i as u16, line);
                        let idx = fn_compiler.chunk.add_constant(Value::Str(p.clone()));
                        fn_compiler.chunk.emit_op_u16(Op::DefineLocal, idx, line);
                        fn_compiler.chunk.emit(0, line);
                    }
                }
                fn_compiler.compile_expr(body)?;
                fn_compiler.chunk.emit_op(Op::Return, line);
                #[cfg(feature = "optimize")]
                fn_compiler.chunk.peephole_optimize();
                let compiled_chunk = fn_compiler.chunk;
                self.fn_chunks.extend(fn_compiler.fn_chunks);

                let fn_value = Value::Fn(crate::value::IonFn::new(
                    "<lambda>".to_string(),
                    params
                        .iter()
                        .map(|n| crate::ast::Param {
                            name: n.clone(),
                            default: None,
                        })
                        .collect(),
                    vec![body_stmt],
                    std::collections::HashMap::new(),
                ));
                // Associate precompiled chunk with fn_id
                if let Value::Fn(ref ion_fn) = fn_value {
                    self.fn_chunks.insert(ion_fn.fn_id, compiled_chunk);
                }
                let fn_idx = self.chunk.add_constant(fn_value);
                self.chunk.emit_op_u16(Op::Closure, fn_idx, line);
            }

            ExprKind::FStr(parts) => {
                for part in parts {
                    match part {
                        FStrPart::Literal(s) => {
                            self.chunk.emit_constant(Value::Str(s.clone()), line);
                        }
                        FStrPart::Expr(expr) => {
                            self.compile_expr(expr)?;
                        }
                    }
                }
                self.chunk
                    .emit_op_u16(Op::BuildFString, parts.len() as u16, line);
            }

            ExprKind::PipeOp { left, right } => {
                // Desugar: left |> right(args)  →  right(left, args)
                // Compile func first, then piped value as first arg, then other args
                match &right.kind {
                    ExprKind::Call { func, args } => {
                        self.compile_expr(func)?;
                        self.compile_expr(left)?; // piped value = first arg
                        for arg in args {
                            self.compile_expr(&arg.value)?;
                        }
                        self.chunk
                            .emit_op_u8(Op::Call, (args.len() + 1) as u8, line);
                    }
                    _ => {
                        // bare function: left |> func  →  func(left)
                        self.compile_expr(right)?;
                        self.compile_expr(left)?;
                        self.chunk.emit_op_u8(Op::Call, 1, line);
                    }
                }
            }

            ExprKind::Try(inner) => {
                self.compile_expr(inner)?;
                self.chunk.emit_op(Op::Try, line);
            }

            ExprKind::Range {
                start,
                end,
                inclusive,
            } => {
                self.compile_expr(start)?;
                self.compile_expr(end)?;
                self.chunk
                    .emit_op_u8(Op::BuildRange, if *inclusive { 1 } else { 0 }, line);
            }

            ExprKind::LoopExpr(body) => {
                self.compile_loop(body, line)?;
            }

            ExprKind::Match {
                expr: subject,
                arms,
            } => {
                self.compile_match(subject, arms, line)?;
            }

            ExprKind::ListComp {
                expr: item_expr,
                pattern,
                iter,
                cond,
            } => {
                self.compile_list_comp(item_expr, pattern, iter, cond.as_deref(), line)?;
            }

            ExprKind::DictComp {
                key,
                value,
                pattern,
                iter,
                cond,
            } => {
                self.compile_dict_comp(key, value, pattern, iter, cond.as_deref(), line)?;
            }

            ExprKind::IfLet {
                pattern,
                expr: inner,
                then_body,
                else_body,
            } => {
                // Evaluate the expression (not in tail position — already cleared)
                self.compile_expr(inner)?;

                // Test pattern
                self.chunk.emit_op(Op::Dup, line); // keep value for binding
                self.compile_pattern_test(pattern, line)?;

                let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true

                // Pattern matched — bind variables in new scope
                self.begin_scope(line);
                self.compile_pattern_bind(pattern, line)?;
                self.in_tail_position = was_tail;
                self.compile_block_expr(then_body, line)?;
                self.end_scope(line);

                let end_jump = self.chunk.emit_jump(Op::Jump, line);

                self.chunk.patch_jump(else_jump);
                self.chunk.emit_op(Op::Pop, line); // pop false
                self.chunk.emit_op(Op::Pop, line); // pop the duped value

                if let Some(else_stmts) = else_body {
                    self.begin_scope(line);
                    self.in_tail_position = was_tail;
                    self.compile_block_expr(else_stmts, line)?;
                    self.end_scope(line);
                } else {
                    self.chunk.emit_op(Op::Unit, line);
                }

                self.chunk.patch_jump(end_jump);
            }

            // Features that fall back to tree-walk for now
            ExprKind::StructConstruct {
                name,
                fields,
                spread,
            } => {
                if let Some(spread_expr) = spread {
                    self.compile_expr(spread_expr)?;
                    for (fname, fexpr) in fields {
                        self.chunk.emit_constant(Value::Str(fname.clone()), line);
                        self.compile_expr(fexpr)?;
                    }
                    let type_idx = self.chunk.add_constant(Value::Str(name.clone()));
                    let field_count = (0x8000 | fields.len()) as u16;
                    self.chunk.emit_op(Op::ConstructStruct, line);
                    self.chunk.emit((type_idx >> 8) as u8, line);
                    self.chunk.emit((type_idx & 0xff) as u8, line);
                    self.chunk.emit((field_count >> 8) as u8, line);
                    self.chunk.emit((field_count & 0xff) as u8, line);
                } else {
                    for (fname, fexpr) in fields {
                        self.chunk.emit_constant(Value::Str(fname.clone()), line);
                        self.compile_expr(fexpr)?;
                    }
                    let type_idx = self.chunk.add_constant(Value::Str(name.clone()));
                    let count = fields.len() as u16;
                    self.chunk.emit_op(Op::ConstructStruct, line);
                    self.chunk.emit((type_idx >> 8) as u8, line);
                    self.chunk.emit((type_idx & 0xff) as u8, line);
                    self.chunk.emit((count >> 8) as u8, line);
                    self.chunk.emit((count & 0xff) as u8, line);
                }
            }
            ExprKind::EnumVariant { enum_name, variant } => {
                let enum_idx = self.chunk.add_constant(Value::Str(enum_name.clone()));
                let variant_idx = self.chunk.add_constant(Value::Str(variant.clone()));
                self.chunk.emit_op(Op::ConstructEnum, line);
                self.chunk.emit((enum_idx >> 8) as u8, line);
                self.chunk.emit((enum_idx & 0xff) as u8, line);
                self.chunk.emit((variant_idx >> 8) as u8, line);
                self.chunk.emit((variant_idx & 0xff) as u8, line);
                self.chunk.emit(0u8, line);
            }
            ExprKind::EnumVariantCall {
                enum_name,
                variant,
                args,
            } => {
                for arg in args {
                    self.compile_expr(arg)?;
                }
                let enum_idx = self.chunk.add_constant(Value::Str(enum_name.clone()));
                let variant_idx = self.chunk.add_constant(Value::Str(variant.clone()));
                self.chunk.emit_op(Op::ConstructEnum, line);
                self.chunk.emit((enum_idx >> 8) as u8, line);
                self.chunk.emit((enum_idx & 0xff) as u8, line);
                self.chunk.emit((variant_idx >> 8) as u8, line);
                self.chunk.emit((variant_idx & 0xff) as u8, line);
                self.chunk.emit(args.len() as u8, line);
            }

            #[cfg(feature = "concurrency")]
            ExprKind::AsyncBlock(_)
            | ExprKind::SpawnExpr(_)
            | ExprKind::AwaitExpr(_)
            | ExprKind::SelectExpr(_) => {
                return Err(IonError::runtime(
                    ion_str!("concurrency not supported in bytecode VM").to_string(),
                    line,
                    col,
                ));
            }
            #[cfg(not(feature = "concurrency"))]
            ExprKind::AsyncBlock(_)
            | ExprKind::SpawnExpr(_)
            | ExprKind::AwaitExpr(_)
            | ExprKind::SelectExpr(_) => {
                return Err(IonError::runtime(
                    ion_str!("concurrency not available").to_string(),
                    line,
                    col,
                ));
            }

            ExprKind::TryCatch { body, var, handler } => {
                // TryBegin catch_offset  (jump to catch block on error)
                let try_begin_patch = self.chunk.emit_jump(Op::TryBegin, line);

                // Compile try body
                self.begin_scope(line);
                let old_tail = self.in_tail_position;
                self.in_tail_position = false;
                for (i, stmt) in body.iter().enumerate() {
                    if i == body.len() - 1 {
                        if let crate::ast::StmtKind::ExprStmt { expr, .. } = &stmt.kind {
                            self.compile_expr(expr)?;
                        } else {
                            self.compile_stmt(stmt)?;
                            self.chunk.emit_op(Op::Unit, line);
                        }
                    } else {
                        self.compile_stmt(stmt)?;
                    }
                }
                if body.is_empty() {
                    self.chunk.emit_op(Op::Unit, line);
                }
                self.in_tail_position = old_tail;
                self.end_scope(line);

                // TryEnd jump_offset  (no error: pop handler, jump over catch)
                let try_end_patch = self.chunk.emit_jump(Op::TryEnd, line);

                // Patch TryBegin to point here (catch block start)
                self.chunk.patch_jump(try_begin_patch);

                // Catch block: error message string is on stack
                self.begin_scope(line);
                self.emit_define_local(var, false, line);
                for (i, stmt) in handler.iter().enumerate() {
                    if i == handler.len() - 1 {
                        if let crate::ast::StmtKind::ExprStmt { expr, .. } = &stmt.kind {
                            self.compile_expr(expr)?;
                        } else {
                            self.compile_stmt(stmt)?;
                            self.chunk.emit_op(Op::Unit, line);
                        }
                    } else {
                        self.compile_stmt(stmt)?;
                    }
                }
                if handler.is_empty() {
                    self.chunk.emit_op(Op::Unit, line);
                }
                self.end_scope(line);

                // Patch TryEnd jump to skip catch block
                self.chunk.patch_jump(try_end_patch);
            }
        }
        self.in_tail_position = was_tail;
        Ok(())
    }

    fn compile_block_expr(&mut self, stmts: &[Stmt], line: usize) -> Result<(), IonError> {
        if stmts.is_empty() {
            self.chunk.emit_op(Op::Unit, line);
            return Ok(());
        }
        let len = stmts.len();
        let saved_tail = self.in_tail_position;
        for (i, stmt) in stmts.iter().enumerate() {
            let is_last = i == len - 1;
            // Only the last expression (without semicolon) inherits tail position
            if !is_last {
                self.in_tail_position = false;
            } else {
                self.in_tail_position = saved_tail;
            }
            match &stmt.kind {
                StmtKind::ExprStmt { expr, has_semi } => {
                    if is_last && *has_semi {
                        self.in_tail_position = false;
                    }
                    self.compile_expr(expr)?;
                    if is_last && !has_semi {
                        // Keep value
                    } else {
                        self.chunk.emit_op(Op::Pop, stmt.span.line);
                    }
                }
                _ => {
                    self.in_tail_position = false;
                    self.compile_stmt(stmt)?;
                    if is_last {
                        self.chunk.emit_op(Op::Unit, stmt.span.line);
                    }
                }
            }
            // Dead code elimination: skip remaining statements after terminal
            #[cfg(feature = "optimize")]
            if !is_last && Self::stmt_is_terminal(stmt) {
                break;
            }
        }
        self.in_tail_position = saved_tail;
        Ok(())
    }

    fn type_ann_to_string(ann: &TypeAnn) -> String {
        match ann {
            TypeAnn::Simple(name) => name.clone(),
            TypeAnn::Option(inner) => format!("Option<{}>", Self::type_ann_to_string(inner)),
            TypeAnn::Result(ok, err) => format!(
                "Result<{}, {}>",
                Self::type_ann_to_string(ok),
                Self::type_ann_to_string(err)
            ),
            TypeAnn::List(inner) => format!("list<{}>", Self::type_ann_to_string(inner)),
            TypeAnn::Dict(k, v) => format!(
                "dict<{}, {}>",
                Self::type_ann_to_string(k),
                Self::type_ann_to_string(v)
            ),
        }
    }

    fn compile_let_pattern(
        &mut self,
        pattern: &Pattern,
        mutable: bool,
        line: usize,
    ) -> Result<(), IonError> {
        match pattern {
            Pattern::Ident(name) => {
                self.emit_define_local(name, mutable, line);
            }
            Pattern::Tuple(pats) => {
                // Value is on stack. Destructure it.
                for (i, pat) in pats.iter().enumerate() {
                    self.chunk.emit_op(Op::Dup, line);
                    self.chunk.emit_constant(Value::Int(i as i64), line);
                    self.chunk.emit_op(Op::GetIndex, line);
                    self.compile_let_pattern(pat, mutable, line)?;
                }
                self.chunk.emit_op(Op::Pop, line); // pop the original tuple
            }
            Pattern::List(pats, rest) => {
                for (i, pat) in pats.iter().enumerate() {
                    self.chunk.emit_op(Op::Dup, line);
                    self.chunk.emit_constant(Value::Int(i as i64), line);
                    self.chunk.emit_op(Op::GetIndex, line);
                    self.compile_let_pattern(pat, mutable, line)?;
                }
                if let Some(rest_pat) = rest {
                    self.chunk.emit_op(Op::Dup, line);
                    self.chunk
                        .emit_constant(Value::Int(pats.len() as i64), line);
                    self.chunk.emit_op_u8(Op::Slice, 1, line); // has_start only
                    self.compile_let_pattern(rest_pat, mutable, line)?;
                }
                self.chunk.emit_op(Op::Pop, line);
            }
            Pattern::Wildcard => {
                self.chunk.emit_op(Op::Pop, line);
            }
            _ => {
                return Err(IonError::runtime(
                    ion_str!("complex pattern not yet supported in bytecode VM let").to_string(),
                    line,
                    0,
                ));
            }
        }
        Ok(())
    }

    fn compile_fn_decl(
        &mut self,
        name: &str,
        params: &[Param],
        body: &[Stmt],
        line: usize,
    ) -> Result<(), IonError> {
        // Compile function body into a separate chunk
        let mut fn_compiler = Compiler::new();
        fn_compiler.in_tail_position = true;
        // Only dual-define locals if body contains closures
        fn_compiler.needs_env_locals = Self::stmts_have_closures(body);
        // Pre-register parameters as locals (they'll be pushed by the VM)
        for param in params {
            fn_compiler.add_local(param.name.clone(), false);
        }
        // When closures exist, also define params in env so they can be captured
        if fn_compiler.needs_env_locals {
            for (i, param) in params.iter().enumerate() {
                fn_compiler
                    .chunk
                    .emit_op_u16(Op::GetLocalSlot, i as u16, line);
                let idx = fn_compiler
                    .chunk
                    .add_constant(Value::Str(param.name.clone()));
                fn_compiler.chunk.emit_op_u16(Op::DefineLocal, idx, line);
                fn_compiler.chunk.emit(0, line); // not mutable
            }
        }
        fn_compiler.compile_block_expr(body, line)?;
        fn_compiler.chunk.emit_op(Op::Return, line);
        #[cfg(feature = "optimize")]
        fn_compiler.chunk.peephole_optimize();
        let compiled_chunk = fn_compiler.chunk;
        // Collect any nested function chunks
        self.fn_chunks.extend(fn_compiler.fn_chunks);

        let fn_value = Value::Fn(crate::value::IonFn::new(
            name.to_string(),
            params.to_vec(),
            body.to_vec(), // Keep AST body for tree-walk fallback
            std::collections::HashMap::new(),
        ));
        // Extract fn_id to associate with precompiled chunk
        if let Value::Fn(ref ion_fn) = fn_value {
            self.fn_chunks.insert(ion_fn.fn_id, compiled_chunk);
        }

        // Define the function in the current scope
        self.chunk.emit_constant(fn_value, line);
        self.emit_define_local(name, false, line);
        Ok(())
    }

    fn compile_for(
        &mut self,
        pattern: &Pattern,
        iter: &Expr,
        body: &[Stmt],
        line: usize,
    ) -> Result<(), IonError> {
        // Save outer loop context
        let saved_breaks = std::mem::take(&mut self.break_jumps);
        let saved_continue = self.continue_target.take();
        let saved_in_for = self.in_for_loop;
        let saved_loop_depth = self.loop_scope_depth;
        self.in_for_loop = true;
        self.loop_scope_depth = self.scope_depth;

        // Evaluate the iterator expression
        self.compile_expr(iter)?;

        // Convert to iterable (the VM will handle this)
        self.chunk.emit_op(Op::IterInit, line);

        let loop_start = self.chunk.len();
        self.continue_target = Some(loop_start);

        // Get next item or jump to end
        let exit_jump = self.chunk.emit_jump(Op::IterNext, line);

        // Bind pattern
        self.begin_scope(line);
        self.compile_let_pattern(pattern, false, line)?;

        // Execute body (with dead code elimination)
        for stmt in body {
            self.compile_stmt(stmt)?;
            #[cfg(feature = "optimize")]
            if Self::stmt_is_terminal(stmt) {
                break;
            }
        }
        self.end_scope(line);

        // Push placeholder for IterNext to pop on next iteration
        self.chunk.emit_op(Op::Unit, line);

        // Loop back
        let offset = self.chunk.len() - loop_start + 3;
        self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

        self.chunk.patch_jump(exit_jump);
        // Pop the iterator placeholder
        self.chunk.emit_op(Op::Pop, line);

        // Patch all break jumps to after the loop
        for jump in &self.break_jumps {
            self.chunk.patch_jump(*jump);
        }

        // Restore outer loop context
        self.break_jumps = saved_breaks;
        self.continue_target = saved_continue;
        self.in_for_loop = saved_in_for;
        self.loop_scope_depth = saved_loop_depth;
        Ok(())
    }

    fn compile_while(&mut self, cond: &Expr, body: &[Stmt], line: usize) -> Result<(), IonError> {
        let saved_breaks = std::mem::take(&mut self.break_jumps);
        let saved_continue = self.continue_target.take();
        let saved_in_for = self.in_for_loop;
        let saved_loop_depth = self.loop_scope_depth;
        self.in_for_loop = false;
        self.loop_scope_depth = self.scope_depth;

        let loop_start = self.chunk.len();
        self.continue_target = Some(loop_start);

        self.compile_expr(cond)?;
        let exit_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
        self.chunk.emit_op(Op::Pop, line); // pop condition

        self.begin_scope(line);
        for stmt in body {
            self.compile_stmt(stmt)?;
            #[cfg(feature = "optimize")]
            if Self::stmt_is_terminal(stmt) {
                break;
            }
        }
        self.end_scope(line);

        let offset = self.chunk.len() - loop_start + 3;
        self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

        self.chunk.patch_jump(exit_jump);
        self.chunk.emit_op(Op::Pop, line); // pop condition

        for jump in &self.break_jumps {
            self.chunk.patch_jump(*jump);
        }
        self.break_jumps = saved_breaks;
        self.continue_target = saved_continue;
        self.in_for_loop = saved_in_for;
        self.loop_scope_depth = saved_loop_depth;
        Ok(())
    }

    fn compile_loop(&mut self, body: &[Stmt], line: usize) -> Result<(), IonError> {
        let saved_breaks = std::mem::take(&mut self.break_jumps);
        let saved_continue = self.continue_target.take();
        let saved_in_for = self.in_for_loop;
        let saved_loop_depth = self.loop_scope_depth;
        self.in_for_loop = false;
        self.loop_scope_depth = self.scope_depth;

        let loop_start = self.chunk.len();
        self.continue_target = Some(loop_start);

        self.begin_scope(line);
        for stmt in body {
            self.compile_stmt(stmt)?;
            #[cfg(feature = "optimize")]
            if Self::stmt_is_terminal(stmt) {
                break;
            }
        }
        self.end_scope(line);

        let offset = self.chunk.len() - loop_start + 3;
        self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

        for jump in &self.break_jumps {
            self.chunk.patch_jump(*jump);
        }
        self.break_jumps = saved_breaks;
        self.continue_target = saved_continue;
        self.in_for_loop = saved_in_for;
        self.loop_scope_depth = saved_loop_depth;
        Ok(())
    }

    fn compile_assign(
        &mut self,
        target: &AssignTarget,
        op: &AssignOp,
        value: &Expr,
        line: usize,
    ) -> Result<(), IonError> {
        match target {
            AssignTarget::Ident(name) => {
                match op {
                    AssignOp::Eq => {
                        self.compile_expr(value)?;
                    }
                    AssignOp::PlusEq | AssignOp::MinusEq | AssignOp::StarEq | AssignOp::SlashEq => {
                        self.emit_get_var(name, line);
                        self.compile_expr(value)?;
                        match op {
                            AssignOp::PlusEq => self.chunk.emit_op(Op::Add, line),
                            AssignOp::MinusEq => self.chunk.emit_op(Op::Sub, line),
                            AssignOp::StarEq => self.chunk.emit_op(Op::Mul, line),
                            AssignOp::SlashEq => self.chunk.emit_op(Op::Div, line),
                            _ => unreachable!(),
                        }
                    }
                }
                self.emit_set_var(name, line);
            }
            AssignTarget::Index(obj_expr, index_expr) => {
                // For index assignment, we need to:
                // 1. Get the container, 2. Modify it, 3. Write it back
                // This only works when obj_expr is an Ident (variable)
                let var_name = match &obj_expr.kind {
                    ExprKind::Ident(name) => name.clone(),
                    _ => {
                        return Err(IonError::runtime(
                            ion_str!("index assignment only supported on variables").to_string(),
                            line,
                            0,
                        ))
                    }
                };

                // Get the container
                self.compile_expr(obj_expr)?;
                self.compile_expr(index_expr)?;

                // Compute new value
                match op {
                    AssignOp::Eq => {
                        self.compile_expr(value)?;
                    }
                    _ => {
                        // Get old value for compound assignment
                        self.compile_expr(obj_expr)?;
                        self.compile_expr(index_expr)?;
                        self.chunk.emit_op(Op::GetIndex, line);
                        self.compile_expr(value)?;
                        match op {
                            AssignOp::PlusEq => self.chunk.emit_op(Op::Add, line),
                            AssignOp::MinusEq => self.chunk.emit_op(Op::Sub, line),
                            AssignOp::StarEq => self.chunk.emit_op(Op::Mul, line),
                            AssignOp::SlashEq => self.chunk.emit_op(Op::Div, line),
                            _ => unreachable!(),
                        }
                    }
                }

                // Stack: [..., obj, index, new_value]
                self.chunk.emit_op(Op::SetIndex, line);
                // SetIndex returns the modified container — write it back
                self.emit_set_var(&var_name, line);
            }
            AssignTarget::Field(obj_expr, field) => {
                let var_name = match &obj_expr.kind {
                    ExprKind::Ident(name) => name.clone(),
                    _ => {
                        return Err(IonError::runtime(
                            ion_str!("field assignment only supported on variables").to_string(),
                            line,
                            0,
                        ))
                    }
                };

                self.compile_expr(obj_expr)?;

                match op {
                    AssignOp::Eq => {
                        self.compile_expr(value)?;
                    }
                    _ => {
                        self.chunk.emit_op(Op::Dup, line);
                        let get_idx = self.chunk.add_constant(Value::Str(field.clone()));
                        self.chunk.emit_op_u16(Op::GetField, get_idx, line);
                        self.compile_expr(value)?;
                        match op {
                            AssignOp::PlusEq => self.chunk.emit_op(Op::Add, line),
                            AssignOp::MinusEq => self.chunk.emit_op(Op::Sub, line),
                            AssignOp::StarEq => self.chunk.emit_op(Op::Mul, line),
                            AssignOp::SlashEq => self.chunk.emit_op(Op::Div, line),
                            _ => unreachable!(),
                        }
                    }
                }

                // Stack: [..., obj, new_value]
                let field_idx = self.chunk.add_constant(Value::Str(field.clone()));
                self.chunk.emit_op_u16(Op::SetField, field_idx, line);
                // SetField returns the modified container — write it back
                self.emit_set_var(&var_name, line);
            }
        }
        Ok(())
    }

    /// Compile a function body to a standalone chunk (for VM-native function execution).
    pub fn compile_fn_body(
        mut self,
        params: &[Param],
        body: &[Stmt],
        line: usize,
    ) -> Result<Chunk, IonError> {
        self.in_tail_position = true;
        self.needs_env_locals = Self::stmts_have_closures(body);
        // Pre-register parameters as locals
        for param in params {
            self.add_local(param.name.clone(), false);
        }
        // When closures exist, also define params in env so they can be captured
        if self.needs_env_locals {
            for (i, param) in params.iter().enumerate() {
                self.chunk.emit_op_u16(Op::GetLocalSlot, i as u16, line);
                let idx = self.chunk.add_constant(Value::Str(param.name.clone()));
                self.chunk.emit_op_u16(Op::DefineLocal, idx, line);
                self.chunk.emit(0, line); // not mutable
            }
        }
        self.compile_block_expr(body, line)?;
        self.chunk.emit_op(Op::Return, line);
        Ok(self.chunk)
    }

    fn compile_match(
        &mut self,
        subject: &Expr,
        arms: &[MatchArm],
        line: usize,
    ) -> Result<(), IonError> {
        let was_tail = self.in_tail_position;
        // Store subject in a hidden temp variable (not in tail position)
        self.begin_scope(line);
        self.in_tail_position = false;
        self.compile_expr(subject)?;
        let tmp_name = "__match_subject__";
        self.emit_define_local(tmp_name, false, line);
        let subject_slot = self.locals.len() - 1;

        let mut end_jumps = Vec::new();

        for arm in arms {
            // Load subject for pattern test
            self.chunk
                .emit_op_u16(Op::GetLocalSlot, subject_slot as u16, line);

            // Emit pattern test — consumes subject copy, pushes bool
            self.compile_pattern_test(&arm.pattern, line)?;

            // If guard exists, test it too (only if pattern matched)
            if let Some(guard) = &arm.guard {
                let skip_guard = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true
                self.compile_expr(guard)?;
                let after_guard = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(skip_guard);
                // false stays on stack — jump lands here
                self.chunk.patch_jump(after_guard);
            }

            let next_arm = self.chunk.emit_jump(Op::JumpIfFalse, line);
            self.chunk.emit_op(Op::Pop, line); // pop true

            // Bind pattern variables in new scope
            self.begin_scope(line);
            self.chunk
                .emit_op_u16(Op::GetLocalSlot, subject_slot as u16, line);
            self.compile_pattern_bind(&arm.pattern, line)?;

            // Compile arm body — inherits tail position
            self.in_tail_position = was_tail;
            self.compile_expr(&arm.body)?;
            self.end_scope(line);

            end_jumps.push(self.chunk.emit_jump(Op::Jump, line));

            self.chunk.patch_jump(next_arm);
            self.chunk.emit_op(Op::Pop, line); // pop false
        }

        // No arm matched — runtime error (matches interpreter behavior)
        self.chunk.emit_op(Op::MatchEnd, line);

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

        self.end_scope(line); // pop the match subject scope
        Ok(())
    }

    /// Compile a pattern test: consumes the value on stack, pushes bool.
    fn compile_pattern_test(&mut self, pattern: &Pattern, line: usize) -> Result<(), IonError> {
        match pattern {
            Pattern::Wildcard | Pattern::Ident(_) => {
                self.chunk.emit_op(Op::Pop, line); // consume value
                self.chunk.emit_op(Op::True, line); // always matches
            }
            Pattern::Int(n) => {
                self.chunk.emit_constant(Value::Int(*n), line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::Float(n) => {
                self.chunk.emit_constant(Value::Float(*n), line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::Bool(b) => {
                self.chunk
                    .emit_op(if *b { Op::True } else { Op::False }, line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::Str(s) => {
                self.chunk.emit_constant(Value::Str(s.clone()), line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::Bytes(b) => {
                self.chunk.emit_constant(Value::Bytes(b.clone()), line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::None => {
                // Check if value is Option(None)
                self.chunk.emit_op(Op::None, line);
                self.chunk.emit_op(Op::Eq, line);
            }
            Pattern::Some(inner) => {
                // Test: is it Some(x)? Use MatchArm opcode for complex patterns
                // For now, test structurally: use a simpler encoding
                // We'll use the MatchBegin/MatchArm opcodes repurposed:
                // Actually, let's just emit inline checks.
                // Stack has value. We need to check if it's Some(_) and test inner.
                self.chunk.emit_op_u8(Op::MatchBegin, 1, line); // 1 = test Some
                let fail_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true
                                                   // Now unwrap the Some and test inner pattern
                self.chunk.emit_op_u8(Op::MatchArm, 1, line); // 1 = unwrap Some
                self.compile_pattern_test(inner, line)?;
                let end = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(fail_jump);
                // false stays
                self.chunk.patch_jump(end);
            }
            Pattern::Ok(inner) => {
                self.chunk.emit_op_u8(Op::MatchBegin, 2, line); // 2 = test Ok
                let fail_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line);
                self.chunk.emit_op_u8(Op::MatchArm, 2, line); // 2 = unwrap Ok
                self.compile_pattern_test(inner, line)?;
                let end = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(fail_jump);
                self.chunk.patch_jump(end);
            }
            Pattern::Err(inner) => {
                self.chunk.emit_op_u8(Op::MatchBegin, 3, line); // 3 = test Err
                let fail_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line);
                self.chunk.emit_op_u8(Op::MatchArm, 3, line); // 3 = unwrap Err
                self.compile_pattern_test(inner, line)?;
                let end = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(fail_jump);
                self.chunk.patch_jump(end);
            }
            Pattern::Tuple(pats) => {
                // Check: is it a tuple of the right length, and do all sub-patterns match?
                self.chunk.emit_op_u8(Op::MatchBegin, 4, line); // 4 = test Tuple
                self.chunk.emit(pats.len() as u8, line); // expected length
                let fail_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true
                                                   // Test each element
                for (i, pat) in pats.iter().enumerate() {
                    // Load the subject again and index into it
                    self.chunk.emit_op_u8(Op::MatchArm, 4, line); // 4 = get tuple element
                    self.chunk.emit(i as u8, line);
                    self.compile_pattern_test(pat, line)?;
                    let sub_fail = self.chunk.emit_jump(Op::JumpIfFalse, line);
                    self.chunk.emit_op(Op::Pop, line); // pop true, continue
                    if i == pats.len() - 1 {
                        // All matched
                        self.chunk.emit_op(Op::True, line);
                    }
                    // Patch sub_fail to push false and skip remaining
                    let sub_end = self.chunk.emit_jump(Op::Jump, line);
                    self.chunk.patch_jump(sub_fail);
                    // false stays on stack
                    self.chunk.patch_jump(sub_end);
                }
                if pats.is_empty() {
                    self.chunk.emit_op(Op::True, line);
                }
                let end = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(fail_jump);
                // false stays
                self.chunk.patch_jump(end);
            }
            Pattern::List(pats, rest) => {
                // Check: is it a list with at least pats.len() elements (or exact if no rest)?
                let has_rest = rest.is_some();
                self.chunk.emit_op_u8(Op::MatchBegin, 5, line); // 5 = test List
                self.chunk.emit(pats.len() as u8, line); // min/exact length
                self.chunk.emit(if has_rest { 1 } else { 0 }, line); // has_rest flag
                let fail_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
                self.chunk.emit_op(Op::Pop, line); // pop true
                                                   // Test each element pattern
                for (i, pat) in pats.iter().enumerate() {
                    self.chunk.emit_op_u8(Op::MatchArm, 5, line); // 5 = get list element
                    self.chunk.emit(i as u8, line);
                    self.compile_pattern_test(pat, line)?;
                    let sub_fail = self.chunk.emit_jump(Op::JumpIfFalse, line);
                    self.chunk.emit_op(Op::Pop, line); // pop true
                    if i == pats.len() - 1 {
                        self.chunk.emit_op(Op::True, line);
                    }
                    let sub_end = self.chunk.emit_jump(Op::Jump, line);
                    self.chunk.patch_jump(sub_fail);
                    self.chunk.patch_jump(sub_end);
                }
                if pats.is_empty() {
                    self.chunk.emit_op(Op::True, line);
                }
                let end = self.chunk.emit_jump(Op::Jump, line);
                self.chunk.patch_jump(fail_jump);
                self.chunk.patch_jump(end);
            }
            _ => {
                // For complex patterns (EnumVariant, Struct), fall back
                return Err(IonError::runtime(
                    ion_str!("complex pattern not yet supported in bytecode VM match").to_string(),
                    line,
                    0,
                ));
            }
        }
        Ok(())
    }

    /// Bind pattern variables: consumes value on stack.
    fn compile_pattern_bind(&mut self, pattern: &Pattern, line: usize) -> Result<(), IonError> {
        match pattern {
            Pattern::Wildcard => {
                self.chunk.emit_op(Op::Pop, line);
            }
            Pattern::Ident(name) => {
                self.emit_define_local(name, false, line);
            }
            Pattern::Int(_)
            | Pattern::Float(_)
            | Pattern::Bool(_)
            | Pattern::Str(_)
            | Pattern::Bytes(_)
            | Pattern::None => {
                self.chunk.emit_op(Op::Pop, line); // no bindings for literals
            }
            Pattern::Some(inner) => {
                // Unwrap the Some value
                self.chunk.emit_op_u8(Op::MatchArm, 1, line); // unwrap Some
                self.compile_pattern_bind(inner, line)?;
            }
            Pattern::Ok(inner) => {
                self.chunk.emit_op_u8(Op::MatchArm, 2, line); // unwrap Ok
                self.compile_pattern_bind(inner, line)?;
            }
            Pattern::Err(inner) => {
                self.chunk.emit_op_u8(Op::MatchArm, 3, line); // unwrap Err
                self.compile_pattern_bind(inner, line)?;
            }
            Pattern::Tuple(pats) => {
                for (i, pat) in pats.iter().enumerate() {
                    self.chunk.emit_op(Op::Dup, line); // dup tuple
                    self.chunk.emit_constant(Value::Int(i as i64), line);
                    self.chunk.emit_op(Op::GetIndex, line);
                    self.compile_pattern_bind(pat, line)?;
                }
                self.chunk.emit_op(Op::Pop, line); // pop tuple
            }
            Pattern::List(pats, rest) => {
                // Bind each element
                for (i, pat) in pats.iter().enumerate() {
                    self.chunk.emit_op(Op::Dup, line); // dup list
                    self.chunk.emit_constant(Value::Int(i as i64), line);
                    self.chunk.emit_op(Op::GetIndex, line);
                    self.compile_pattern_bind(pat, line)?;
                }
                // If there's a rest pattern, bind the remaining elements
                if let Some(rest_pat) = rest {
                    self.chunk.emit_op(Op::Dup, line); // dup list
                                                       // Slice from pats.len() to end
                    self.chunk
                        .emit_constant(Value::Int(pats.len() as i64), line);
                    // Use Slice with has_start only
                    self.chunk.emit_op_u8(Op::Slice, 1, line); // flags: has_start=1
                    self.compile_pattern_bind(rest_pat, line)?;
                }
                self.chunk.emit_op(Op::Pop, line); // pop list
            }
            _ => {
                return Err(IonError::runtime(
                    ion_str!("complex pattern binding not yet supported in bytecode VM")
                        .to_string(),
                    line,
                    0,
                ));
            }
        }
        Ok(())
    }

    fn compile_list_comp(
        &mut self,
        item_expr: &Expr,
        pattern: &Pattern,
        iter: &Expr,
        cond: Option<&Expr>,
        line: usize,
    ) -> Result<(), IonError> {
        // Build an empty list, then iterate and append
        self.chunk.emit_op_u16(Op::BuildList, 0, line); // empty list on stack

        // Evaluate iterator
        self.compile_expr(iter)?;
        self.chunk.emit_op(Op::IterInit, line);

        let loop_start = self.chunk.len();
        let exit_jump = self.chunk.emit_jump(Op::IterNext, line);

        // Bind pattern in scope
        self.begin_scope(line);
        self.compile_let_pattern(pattern, false, line)?;

        // If there's a condition, check it
        if let Some(cond_expr) = cond {
            self.compile_expr(cond_expr)?;
            let skip_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
            self.chunk.emit_op(Op::Pop, line); // pop true

            // Compile item expression and append
            self.compile_expr(item_expr)?;
            self.chunk.emit_op(Op::ListAppend, line);

            let after = self.chunk.emit_jump(Op::Jump, line);
            self.chunk.patch_jump(skip_jump);
            self.chunk.emit_op(Op::Pop, line); // pop false
            self.chunk.patch_jump(after);
        } else {
            // Compile item expression and append
            self.compile_expr(item_expr)?;
            self.chunk.emit_op(Op::ListAppend, line);
        }

        self.end_scope(line);

        // Push placeholder for IterNext to pop on next iteration
        self.chunk.emit_op(Op::Unit, line);

        // Loop back
        let offset = self.chunk.len() - loop_start + 3;
        self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

        self.chunk.patch_jump(exit_jump);
        self.chunk.emit_op(Op::Pop, line); // pop exhausted iterator placeholder
                                           // List is still on stack
        Ok(())
    }

    fn compile_dict_comp(
        &mut self,
        key_expr: &Expr,
        value_expr: &Expr,
        pattern: &Pattern,
        iter: &Expr,
        cond: Option<&Expr>,
        line: usize,
    ) -> Result<(), IonError> {
        // Build an empty dict, then iterate and insert
        self.chunk.emit_op_u16(Op::BuildDict, 0, line);

        self.compile_expr(iter)?;
        self.chunk.emit_op(Op::IterInit, line);

        let loop_start = self.chunk.len();
        let exit_jump = self.chunk.emit_jump(Op::IterNext, line);

        self.begin_scope(line);
        self.compile_let_pattern(pattern, false, line)?;

        if let Some(cond_expr) = cond {
            self.compile_expr(cond_expr)?;
            let skip_jump = self.chunk.emit_jump(Op::JumpIfFalse, line);
            self.chunk.emit_op(Op::Pop, line);

            self.compile_expr(key_expr)?;
            self.compile_expr(value_expr)?;
            self.chunk.emit_op(Op::DictInsert, line);

            let after = self.chunk.emit_jump(Op::Jump, line);
            self.chunk.patch_jump(skip_jump);
            self.chunk.emit_op(Op::Pop, line);
            self.chunk.patch_jump(after);
        } else {
            self.compile_expr(key_expr)?;
            self.compile_expr(value_expr)?;
            self.chunk.emit_op(Op::DictInsert, line);
        }

        self.end_scope(line);

        // Push placeholder for IterNext to pop on next iteration
        self.chunk.emit_op(Op::Unit, line);

        let offset = self.chunk.len() - loop_start + 3;
        self.chunk.emit_op_u16(Op::Loop, offset as u16, line);

        self.chunk.patch_jump(exit_jump);
        self.chunk.emit_op(Op::Pop, line);
        Ok(())
    }
}