tishlang_vm 1.13.2

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

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

#[cfg(not(feature = "send-values"))]
use std::rc::Rc;
use tishlang_core::VmRef;

use tishlang_ast::{BinOp, UnaryOp};
use tishlang_builtins::array as arr_builtins;
use tishlang_builtins::construct as construct_builtin;
use tishlang_builtins::globals as globals_builtins;
use tishlang_builtins::math as math_builtins;
use tishlang_builtins::string as str_builtins;
use tishlang_bytecode::{u8_to_binop, u8_to_unaryop, Chunk, Constant, Opcode, NO_REST_PARAM};
use tishlang_core::{
    merge_object_data, object_get, object_has, object_set, NativeFn, ObjectData, ObjectMap, Value,
};

/// Wrap a closure in the right shared pointer for the current build.
/// Under `send-values` that's `Arc<dyn Fn + Send + Sync>`; otherwise it's
/// plain `Rc<dyn Fn>`. Call sites can stay ignorant of the distinction.
#[cfg(feature = "send-values")]
#[inline]
fn make_native_fn<F>(f: F) -> NativeFn
where
    F: Fn(&[Value]) -> Value + Send + Sync + 'static,
{
    Arc::new(f)
}

#[cfg(not(feature = "send-values"))]
#[inline]
fn make_native_fn<F>(f: F) -> NativeFn
where
    F: Fn(&[Value]) -> Value + 'static,
{
    Rc::new(f)
}

// Array / string / object methods have the same shape as `NativeFn`, which
// is already feature-gated (`Rc<dyn Fn>` vs `Arc<dyn Fn + Send + Sync>`).
// Alias to that so the VM picks the right pointer type automatically.
type ArrayMethodFn = NativeFn;

/// Feature names enabled for this VM run (`tish run --feature …`). `full` enables every optional capability.
#[cfg_attr(
    not(any(
        feature = "fs",
        feature = "http",
        feature = "promise",
        feature = "timers",
        feature = "process",
        feature = "ws"
    )),
    allow(dead_code)
)]
#[inline]
fn value_object_from_map(m: ObjectMap) -> Value {
    Value::Object(VmRef::new(ObjectData::from_strings(m)))
}

#[cfg(any(
    feature = "fs",
    feature = "http",
    feature = "promise",
    feature = "timers",
    feature = "process",
    feature = "ws"
))]
#[inline]
fn cap_allows(enabled: &HashSet<String>, name: &str) -> bool {
    enabled.contains("full") || enabled.contains(name)
}

/// Capabilities linked into this `tishlang_vm` binary (compile-time). Used by [`Vm::new`] and `run()`.
pub fn all_compiled_capabilities() -> HashSet<String> {
    #[allow(unused_mut)]
    let mut s = HashSet::new();
    #[cfg(feature = "http")]
    s.insert("http".to_string());
    #[cfg(feature = "promise")]
    s.insert("promise".to_string());
    #[cfg(feature = "timers")]
    s.insert("timers".to_string());
    #[cfg(feature = "fs")]
    s.insert("fs".to_string());
    #[cfg(feature = "process")]
    s.insert("process".to_string());
    #[cfg(feature = "regex")]
    s.insert("regex".to_string());
    #[cfg(feature = "ws")]
    s.insert("ws".to_string());
    s
}

/// Look up built-in module export for LoadNativeExport. Returns None if unknown or feature disabled.
#[cfg_attr(
    not(any(
        feature = "fs",
        feature = "http",
        feature = "promise",
        feature = "timers",
        feature = "process",
        feature = "ws"
    )),
    allow(unused_variables)
)]
fn get_builtin_export(enabled: &HashSet<String>, spec: &str, export_name: &str) -> Option<Value> {
    #[cfg(feature = "fs")]
    if spec == "tish:fs" && cap_allows(enabled, "fs") {
        return match export_name {
            "readFile" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::read_file(args)
            })),
            "writeFile" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::write_file(args)
            })),
            "fileExists" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::file_exists(args)
            })),
            "isDir" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::is_dir(args)
            })),
            "readDir" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::read_dir(args)
            })),
            "mkdir" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::mkdir(args)
            })),
            _ => None,
        };
    }
    #[cfg(feature = "http")]
    if spec == "tish:http" && cap_allows(enabled, "http") {
        return match export_name {
            // Bytecode compiler lowers `await expr` to `tish:http.await(promise)` (see tish_bytecode compiler).
            "await" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::await_promise(args.first().cloned().unwrap_or(Value::Null))
            })),
            "fetch" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::fetch_promise(args.to_vec())
            })),
            "fetchAll" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::fetch_all_promise(args.to_vec())
            })),
            "Promise" => Some(tishlang_runtime::promise_object()),
            "serve" => Some(Value::native(|args: &[Value]| {
                // Phase-1 item 2: support `serve(port, { handler, onWorker })`
                // in addition to `serve(port, handler)`. When an options
                // object is given and onWorker is a function, invoke it with
                // worker id 0 and expect it to return the request handler.
                let raw = args.get(1).cloned().unwrap_or(Value::Null);
                let handler_value = match raw {
                    Value::Function(_) => raw,
                    Value::Object(ref obj) => {
                        let obj_ref = obj.borrow();
                        if let Some(Value::Function(on_worker)) =
                            obj_ref.strings.get(&std::sync::Arc::from("onWorker")).cloned()
                        {
                            let args_for_init = [Value::Number(0.0)];
                            on_worker(&args_for_init)
                        } else if let Some(h) =
                            obj_ref.strings.get(&std::sync::Arc::from("handler")).cloned()
                        {
                            h
                        } else {
                            Value::Null
                        }
                    }
                    _ => Value::Null,
                };
                if let Value::Function(f) = handler_value {
                    tishlang_runtime::http_serve(args, move |req_args| f(req_args))
                } else {
                    Value::Null
                }
            })),
            _ => None,
        };
    }
    #[cfg(all(feature = "promise", not(feature = "http")))]
    if spec == "tish:http" && cap_allows(enabled, "promise") {
        return match export_name {
            "Promise" => Some(tishlang_runtime::promise_object()),
            "await" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::await_promise(args.first().cloned().unwrap_or(Value::Null))
            })),
            _ => None,
        };
    }
    #[cfg(feature = "timers")]
    if spec == "tish:timers" && cap_allows(enabled, "timers") {
        return match export_name {
            "setTimeout" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::timer_set_timeout(args)
            })),
            "setInterval" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::timer_set_interval(args)
            })),
            "clearTimeout" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::timer_clear_timeout(args)
            })),
            "clearInterval" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::timer_clear_interval(args)
            })),
            _ => None,
        };
    }
    #[cfg(feature = "process")]
    if spec == "tish:process" && cap_allows(enabled, "process") {
        return match export_name {
            "exit" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::process_exit(args)
            })),
            "cwd" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::process_cwd(args)
            })),
            "exec" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::process_exec(args)
            })),
            "argv" => Some(Value::Array(VmRef::new(
                std::env::args().map(|s| Value::String(s.into())).collect(),
            ))),
            "env" => Some(value_object_from_map(
                std::env::vars()
                    .map(|(k, v)| (Arc::from(k.as_str()), Value::String(v.into())))
                    .collect(),
            )),
            "process" => {
                let mut m = ObjectMap::default();
                m.insert(
                    "exit".into(),
                    Value::native(|args: &[Value]| tishlang_runtime::process_exit(args)),
                );
                m.insert(
                    "cwd".into(),
                    Value::native(|args: &[Value]| tishlang_runtime::process_cwd(args)),
                );
                m.insert(
                    "exec".into(),
                    Value::native(|args: &[Value]| tishlang_runtime::process_exec(args)),
                );
                m.insert(
                    "argv".into(),
                    Value::Array(VmRef::new(
                        std::env::args().map(|s| Value::String(s.into())).collect(),
                    )),
                );
                m.insert(
                    "env".into(),
                    value_object_from_map(
                        std::env::vars()
                            .map(|(k, v)| (Arc::from(k.as_str()), Value::String(v.into())))
                            .collect(),
                    ),
                );
                Some(value_object_from_map(m))
            }
            _ => None,
        };
    }
    #[cfg(feature = "ws")]
    if spec == "tish:ws" && cap_allows(enabled, "ws") {
        return match export_name {
            "WebSocket" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::web_socket_client(args)
            })),
            "Server" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::web_socket_server_construct(args)
            })),
            "wsSend" => Some(Value::native(|args: &[Value]| {
                Value::Bool(tishlang_runtime::ws_send_native(
                    args.first().unwrap_or(&Value::Null),
                    &args
                        .get(1)
                        .map(|v| v.to_display_string())
                        .unwrap_or_default(),
                ))
            })),
            "wsBroadcast" => Some(Value::native(|args: &[Value]| {
                tishlang_runtime::ws_broadcast_native(args)
            })),
            _ => None,
        };
    }
    None
}

/// Console output: println! on native, web_sys::console on wasm
#[cfg(not(feature = "wasm"))]
fn vm_log(s: &str) {
    println!("{}", s);
}
#[cfg(not(feature = "wasm"))]
fn vm_log_err(s: &str) {
    eprintln!("{}", s);
}
#[cfg(feature = "wasm")]
fn vm_log(s: &str) {
    #[wasm_bindgen::prelude::wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        fn log(s: &str);
    }
    log(s);
}
#[cfg(feature = "wasm")]
fn vm_log_err(s: &str) {
    #[wasm_bindgen::prelude::wasm_bindgen]
    extern "C" {
        #[wasm_bindgen(js_namespace = console)]
        fn error(s: &str);
    }
    error(s);
}

/// Initialize default globals (console, Math, JSON, etc.)
#[allow(unused_variables)]
fn init_globals(enabled: &HashSet<String>) -> ObjectMap {
    let mut g = ObjectMap::default();

    let mut console = ObjectMap::default();
    console.insert(
        "debug".into(),
        Value::native(|args: &[Value]| {
            let s =
                tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors());
            vm_log(&s);
            Value::Null
        }),
    );
    console.insert(
        "log".into(),
        Value::native(|args: &[Value]| {
            let s =
                tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors());
            vm_log(&s);
            Value::Null
        }),
    );
    console.insert(
        "info".into(),
        Value::native(|args: &[Value]| {
            let s =
                tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors());
            vm_log(&s);
            Value::Null
        }),
    );
    console.insert(
        "warn".into(),
        Value::native(|args: &[Value]| {
            let s =
                tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors());
            vm_log_err(&s);
            Value::Null
        }),
    );
    console.insert(
        "error".into(),
        Value::native(|args: &[Value]| {
            let s =
                tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors());
            vm_log_err(&s);
            Value::Null
        }),
    );
    g.insert("console".into(), value_object_from_map(console));

    let mut math = ObjectMap::default();
    math.insert(
        "abs".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.abs())
        }),
    );
    math.insert(
        "sqrt".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.sqrt())
        }),
    );
    math.insert(
        "floor".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.floor())
        }),
    );
    math.insert(
        "ceil".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.ceil())
        }),
    );
    math.insert(
        "round".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.round())
        }),
    );
    math.insert(
        "random".into(),
        Value::native(|_| Value::Number(rand::random::<f64>())),
    );
    math.insert(
        "min".into(),
        Value::native(|args: &[Value]| {
            let nums: Vec<f64> = args.iter().filter_map(|v| v.as_number()).collect();
            Value::Number(nums.into_iter().fold(f64::NAN, |a, b| a.min(b)))
        }),
    );
    math.insert(
        "max".into(),
        Value::native(|args: &[Value]| {
            let nums: Vec<f64> = args.iter().filter_map(|v| v.as_number()).collect();
            Value::Number(nums.into_iter().fold(f64::NAN, |a, b| a.max(b)))
        }),
    );
    math.insert(
        "pow".into(),
        Value::native(|args: &[Value]| math_builtins::pow(args)),
    );
    math.insert(
        "sin".into(),
        Value::native(|args: &[Value]| math_builtins::sin(args)),
    );
    math.insert(
        "cos".into(),
        Value::native(|args: &[Value]| math_builtins::cos(args)),
    );
    math.insert(
        "tan".into(),
        Value::native(|args: &[Value]| math_builtins::tan(args)),
    );
    math.insert(
        "log".into(),
        Value::native(|args: &[Value]| math_builtins::log(args)),
    );
    math.insert(
        "exp".into(),
        Value::native(|args: &[Value]| math_builtins::exp(args)),
    );
    math.insert(
        "sign".into(),
        Value::native(|args: &[Value]| math_builtins::sign(args)),
    );
    math.insert(
        "trunc".into(),
        Value::native(|args: &[Value]| math_builtins::trunc(args)),
    );
    // Trig/hypot not covered by `math_builtins`; needed by the 3D engine's
    // camera + character-controller math (atan2/hypot) on the wasm VM, where
    // (unlike `--target js`) there is no host `Math` to fall through to.
    math.insert(
        "atan2".into(),
        Value::native(|args: &[Value]| {
            let y = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            let x = args.get(1).and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(y.atan2(x))
        }),
    );
    math.insert(
        "atan".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.atan())
        }),
    );
    math.insert(
        "asin".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.asin())
        }),
    );
    math.insert(
        "acos".into(),
        Value::native(|args: &[Value]| {
            let n = args.first().and_then(|v| v.as_number()).unwrap_or(f64::NAN);
            Value::Number(n.acos())
        }),
    );
    math.insert(
        "hypot".into(),
        Value::native(|args: &[Value]| {
            let nums: Vec<f64> = args.iter().filter_map(|v| v.as_number()).collect();
            let sum_sq: f64 = nums.iter().map(|n| n * n).sum();
            Value::Number(sum_sq.sqrt())
        }),
    );
    math.insert("PI".into(), Value::Number(std::f64::consts::PI));
    math.insert("E".into(), Value::Number(std::f64::consts::E));
    g.insert("Math".into(), value_object_from_map(math));

    let mut json = ObjectMap::default();
    json.insert(
        "parse".into(),
        Value::native(|args: &[Value]| {
            let s = args
                .first()
                .map(|v| v.to_display_string())
                .unwrap_or_default();
            tishlang_core::json_parse(&s).unwrap_or(Value::Null)
        }),
    );
    json.insert(
        "stringify".into(),
        Value::native(|args: &[Value]| {
            let v = args.first().unwrap_or(&Value::Null);
            Value::String(tishlang_core::json_stringify(v).into())
        }),
    );
    g.insert("JSON".into(), value_object_from_map(json));

    g.insert(
        "parseInt".into(),
        Value::native(|args: &[Value]| globals_builtins::parse_int(args)),
    );
    g.insert(
        "parseFloat".into(),
        Value::native(|args: &[Value]| globals_builtins::parse_float(args)),
    );
    g.insert(
        "encodeURI".into(),
        Value::native(|args: &[Value]| globals_builtins::encode_uri(args)),
    );
    g.insert(
        "decodeURI".into(),
        Value::native(|args: &[Value]| globals_builtins::decode_uri(args)),
    );
    g.insert(
        "htmlEscape".into(),
        Value::native(|args: &[Value]| {
            tishlang_builtins::string::escape_html(args.first().unwrap_or(&Value::Null))
        }),
    );
    g.insert(
        "Boolean".into(),
        Value::native(|args: &[Value]| globals_builtins::boolean(args)),
    );
    g.insert(
        "isFinite".into(),
        Value::native(|args: &[Value]| globals_builtins::is_finite(args)),
    );
    g.insert(
        "isNaN".into(),
        Value::native(|args: &[Value]| globals_builtins::is_nan(args)),
    );
    g.insert("Infinity".into(), Value::Number(f64::INFINITY));
    g.insert("NaN".into(), Value::Number(f64::NAN));
    g.insert(
        "typeof".into(),
        Value::native(|args: &[Value]| {
            let v = args.first().unwrap_or(&Value::Null);
            Value::String(v.type_name().into())
        }),
    );
    g.insert(
        "Symbol".into(),
        tishlang_builtins::symbol::symbol_object(),
    );

    // Date - at minimum Date.now() for timing
    let mut date = ObjectMap::default();
    date.insert(
        "now".into(),
        Value::native(|_args: &[Value]| {
            let ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as f64;
            Value::Number(ms)
        }),
    );
    g.insert("Date".into(), value_object_from_map(date));

    g.insert(
        "Uint8Array".into(),
        construct_builtin::uint8_array_constructor_value(),
    );
    g.insert(
        "AudioContext".into(),
        construct_builtin::audio_context_constructor_value(),
    );

    // Object methods - delegate to tishlang_builtins::globals
    let mut object_methods = ObjectMap::default();
    object_methods.insert(
        "assign".into(),
        Value::native(|args: &[Value]| globals_builtins::object_assign(args)),
    );
    object_methods.insert(
        "fromEntries".into(),
        Value::native(|args: &[Value]| globals_builtins::object_from_entries(args)),
    );
    object_methods.insert(
        "keys".into(),
        Value::native(|args: &[Value]| globals_builtins::object_keys(args)),
    );
    object_methods.insert(
        "values".into(),
        Value::native(|args: &[Value]| globals_builtins::object_values(args)),
    );
    object_methods.insert(
        "entries".into(),
        Value::native(|args: &[Value]| globals_builtins::object_entries(args)),
    );
    g.insert("Object".into(), value_object_from_map(object_methods));

    // Array.isArray
    let mut array_static = ObjectMap::default();
    array_static.insert(
        "isArray".into(),
        Value::native(|args: &[Value]| globals_builtins::array_is_array(args)),
    );
    g.insert("Array".into(), value_object_from_map(array_static));

    // String(value) as callable + String.fromCharCode
    let string_convert_fn = Value::native(|args: &[Value]| globals_builtins::string_convert(args));
    let mut string_static = ObjectMap::default();
    string_static.insert(
        "fromCharCode".into(),
        Value::native(|args: &[Value]| globals_builtins::string_from_char_code(args)),
    );
    string_static.insert(Arc::from("__call"), string_convert_fn);
    g.insert("String".into(), value_object_from_map(string_static));

    // JSX / Lattish: stubs for bytecode VM when no DOM (e.g. console). Override via set_global in browser.
    g.insert("h".into(), Value::native(|_args: &[Value]| Value::Null));
    g.insert(
        "Fragment".into(),
        value_object_from_map(ObjectMap::default()),
    );
    g.insert(
        "createRoot".into(),
        Value::native(|_args: &[Value]| {
            let mut render_obj = ObjectMap::default();
            render_obj.insert(
                "render".into(),
                Value::native(|_args: &[Value]| Value::Null),
            );
            value_object_from_map(render_obj)
        }),
    );
    g.insert(
        "useState".into(),
        Value::native(|args: &[Value]| {
            let init = args.first().cloned().unwrap_or(Value::Null);
            let arr = vec![init, Value::native(|_| Value::Null)];
            Value::Array(VmRef::new(arr))
        }),
    );
    let mut document_obj = ObjectMap::default();
    document_obj.insert("body".into(), Value::Null);
    g.insert("document".into(), value_object_from_map(document_obj));

    #[cfg(feature = "process")]
    if cap_allows(enabled, "process") {
        let mut process_obj = ObjectMap::default();
        process_obj.insert(
            "exit".into(),
            Value::native(|args: &[Value]| tishlang_runtime::process_exit(args)),
        );
        process_obj.insert(
            "cwd".into(),
            Value::native(|args: &[Value]| tishlang_runtime::process_cwd(args)),
        );
        process_obj.insert(
            "exec".into(),
            Value::native(|args: &[Value]| tishlang_runtime::process_exec(args)),
        );
        process_obj.insert(
            "argv".into(),
            Value::Array(VmRef::new(
                std::env::args().map(|s| Value::String(s.into())).collect(),
            )),
        );
        process_obj.insert(
            "env".into(),
            value_object_from_map(
                std::env::vars()
                    .map(|(k, v)| (Arc::from(k.as_str()), Value::String(v.into())))
                    .collect(),
            ),
        );
        g.insert("process".into(), value_object_from_map(process_obj));
    }

    #[cfg(feature = "timers")]
    if cap_allows(enabled, "timers") {
        g.insert(
            "setTimeout".into(),
            Value::native(|args: &[Value]| tishlang_runtime::timer_set_timeout(args)),
        );
        g.insert(
            "clearTimeout".into(),
            Value::native(|args: &[Value]| tishlang_runtime::timer_clear_timeout(args)),
        );
        g.insert(
            "setInterval".into(),
            Value::native(|args: &[Value]| tishlang_runtime::timer_set_interval(args)),
        );
        g.insert(
            "clearInterval".into(),
            Value::native(|args: &[Value]| tishlang_runtime::timer_clear_interval(args)),
        );
    }

    #[cfg(feature = "http")]
    if cap_allows(enabled, "http") {
        g.insert(
            "fetch".into(),
            Value::native(|args: &[Value]| tishlang_runtime::fetch_promise(args.to_vec())),
        );
        g.insert(
            "fetchAll".into(),
            Value::native(|args: &[Value]| tishlang_runtime::fetch_all_promise(args.to_vec())),
        );
        g.insert(
            "registerStaticRoute".into(),
            Value::native(|args: &[Value]| {
                let path = match args.first() {
                    Some(Value::String(s)) => s.to_string(),
                    _ => return Value::Null,
                };
                let body = match args.get(1) {
                    Some(Value::String(s)) => s.as_bytes().to_vec(),
                    _ => return Value::Null,
                };
                let ct = match args.get(2) {
                    Some(Value::String(s)) => s.to_string(),
                    _ => "application/octet-stream".to_string(),
                };
                tishlang_runtime::register_static_route(&path, &body, &ct);
                Value::Null
            }),
        );
        g.insert(
            "serve".into(),
            Value::native(|args: &[Value]| {
                // Phase-1 item 2 (see tish:http.serve above for full docs).
                let raw = args.get(1).cloned().unwrap_or(Value::Null);
                let handler_value = match raw {
                    Value::Function(_) => raw,
                    Value::Object(ref obj) => {
                        let obj_ref = obj.borrow();
                        if let Some(Value::Function(on_worker)) =
                            obj_ref.strings.get(&std::sync::Arc::from("onWorker")).cloned()
                        {
                            let args_for_init = [Value::Number(0.0)];
                            on_worker(&args_for_init)
                        } else if let Some(h) =
                            obj_ref.strings.get(&std::sync::Arc::from("handler")).cloned()
                        {
                            h
                        } else {
                            Value::Null
                        }
                    }
                    _ => Value::Null,
                };
                if let Value::Function(f) = handler_value {
                    tishlang_runtime::http_serve(args, move |req_args| f(req_args))
                } else {
                    Value::Null
                }
            }),
        );
    }

    #[cfg(any(feature = "http", feature = "promise"))]
    if cap_allows(enabled, "http") || cap_allows(enabled, "promise") {
        g.insert("Promise".into(), tishlang_runtime::promise_object());
    }

    g
}

/// Shared scope for closure capture (parent frame's locals).
type ScopeMap = VmRef<ObjectMap>;

/// Options for the convenience [`run_with_options`] helper (one-shot VM run from the CLI).
#[derive(Clone, Debug, Default)]
pub struct VmRunOptions {
    /// When true and not inside a nested chunk (`enclosing` is `None`), top-level [`Opcode::DeclareVar`]
    /// also writes to globals so the REPL keeps bindings across input lines.
    pub repl_mode: bool,
    /// Enabled capabilities for this run (e.g. `fs`, `http`, `full`). Empty = none (secure default).
    pub capabilities: HashSet<String>,
}

pub struct Vm {
    stack: Vec<Value>,
    scope: ObjectMap,
    /// Enclosing scope for closures (captured parent frame locals).
    enclosing: Option<ScopeMap>,
    globals: VmRef<ObjectMap>,
    /// Capabilities for `LoadNativeExport` and globals such as `process` / `serve`.
    capabilities: Arc<HashSet<String>>,
    /// Externally registered native modules, keyed by import spec (e.g.
    /// `"cargo:tish_pg"`). Populated by embedders before `run` (see
    /// [`register_native_module`]). Phase-2 item 11: unblocks `cargo:`
    /// imports on the cranelift and llvm backends which run this VM.
    native_modules: VmRef<HashMap<String, VmRef<ObjectMap>>>,
}

impl Vm {
    /// VM with every capability that exists in this `tishlang_vm` build (embedders, tests, `run()`).
    pub fn new() -> Self {
        Self::with_capabilities_arc(Arc::new(all_compiled_capabilities()))
    }

    /// VM with an explicit capability set (e.g. from `tish run --feature …`).
    pub fn with_capabilities(capabilities: HashSet<String>) -> Self {
        Self::with_capabilities_arc(Arc::new(capabilities))
    }

    fn with_capabilities_arc(capabilities: Arc<HashSet<String>>) -> Self {
        Self {
            stack: Vec::new(),
            scope: ObjectMap::default(),
            enclosing: None,
            globals: VmRef::new(init_globals(capabilities.as_ref())),
            capabilities,
            native_modules: VmRef::new(HashMap::new()),
        }
    }

    /// Register an externally-supplied native module under a `cargo:`-style
    /// spec (e.g. `"cargo:tish_pg"`). The `exports` map is what
    /// `LoadNativeExport` will index into when user code imports from this
    /// spec. Intended to be called by the `tishlang_cranelift_runtime` /
    /// `tishlang_llvm` link step, or by external embedders that want to
    /// expose Rust crates to `.tish` programs running on the bytecode VM.
    pub fn register_native_module(&mut self, spec: impl Into<String>, exports: ObjectMap) {
        self.native_modules
            .borrow_mut()
            .insert(spec.into(), VmRef::new(exports));
    }

    pub fn get_global(&self, name: &str) -> Option<Value> {
        self.globals.borrow().get(name).cloned()
    }

    pub fn set_global(&mut self, name: Arc<str>, value: Value) {
        self.globals.borrow_mut().insert(name, value);
    }

    /// Names of all globals (for REPL bare-word tab completion).
    pub fn global_names(&self) -> Vec<String> {
        self.globals
            .borrow()
            .keys()
            .map(|k| k.as_ref().to_string())
            .collect()
    }

    fn read_u16(code: &[u8], ip: &mut usize) -> u16 {
        let a = code[*ip] as u16;
        let b = code[*ip + 1] as u16;
        *ip += 2;
        (a << 8) | b
    }

    fn read_i16(code: &[u8], ip: &mut usize) -> i16 {
        Self::read_u16(code, ip) as i16
    }

    /// Pop innermost try handler, truncate stack, push thrown value, jump to catch.
    fn unwind_throw(
        try_handlers: &mut Vec<(usize, usize)>,
        stack: &mut Vec<Value>,
        ip: &mut usize,
        v: Value,
    ) -> Result<(), String> {
        let (catch_ip, stack_len) = try_handlers
            .pop()
            .ok_or_else(|| format!("Uncaught throw: {}", v.to_display_string()))?;
        stack.truncate(stack_len);
        stack.push(v);
        *ip = catch_ip;
        Ok(())
    }

    pub fn run(&mut self, chunk: &Chunk) -> Result<Value, String> {
        self.run_with_options(chunk, false)
    }

    /// Run a chunk using this VM's capability set. `repl_mode` persists top-level `let` across REPL lines.
    pub fn run_with_options(&mut self, chunk: &Chunk, repl_mode: bool) -> Result<Value, String> {
        self.run_chunk(chunk, &chunk.nested, &[], repl_mode)
    }

    fn run_chunk(
        &mut self,
        chunk: &Chunk,
        nested: &[Chunk],
        args: &[Value],
        repl_mode: bool,
    ) -> Result<Value, String> {
        let code = &chunk.code;
        let constants = &chunk.constants;
        let names = &chunk.names;

        let mut ip = 0;
        let local_scope: ScopeMap = VmRef::new(ObjectMap::default());
        {
            let mut ls = local_scope.borrow_mut();
            let param_count = chunk.param_count as usize;
            if chunk.rest_param_index != NO_REST_PARAM {
                let ri = chunk.rest_param_index as usize;
                for (i, name) in chunk.names.iter().take(param_count).enumerate() {
                    if i < ri {
                        let v = args.get(i).cloned().unwrap_or(Value::Null);
                        ls.insert(Arc::clone(name), v);
                    } else if i == ri {
                        let rest_arr: Vec<Value> = args.iter().skip(ri).cloned().collect();
                        ls.insert(Arc::clone(name), Value::Array(VmRef::new(rest_arr)));
                    }
                }
            } else {
                for (i, name) in chunk.names.iter().take(param_count).enumerate() {
                    if let Some(v) = args.get(i) {
                        ls.insert(Arc::clone(name), v.clone());
                    }
                }
            }
        }
        let mut try_handlers: Vec<(usize, usize)> = vec![];
        let mut block_undo_stack: Vec<Vec<(Arc<str>, Option<Value>)>> = vec![];

        loop {
            if ip >= code.len() {
                break;
            }
            let op = code[ip];
            ip += 1;
            if op == Opcode::Nop as u8 {
                continue;
            }
            let opcode = Opcode::from_u8(op).ok_or_else(|| format!("Unknown opcode: {}", op))?;

            match opcode {
                Opcode::Nop => {}
                Opcode::LoadConst => {
                    let idx = Self::read_u16(code, &mut ip);
                    let c = constants
                        .get(idx as usize)
                        .ok_or_else(|| format!("Constant index out of bounds: {}", idx))?;
                    let v = match c {
                        Constant::Number(n) => Value::Number(*n),
                        Constant::String(s) => Value::String(Arc::clone(s)),
                        Constant::Bool(b) => Value::Bool(*b),
                        Constant::Null => Value::Null,
                        Constant::Closure(nested_idx) => {
                            let inner = nested
                                .get(*nested_idx)
                                .ok_or_else(|| "Nested chunk index out of bounds".to_string())?;
                            let inner_clone = inner.clone();
                            let globals = self.globals.clone();
                            let enclosing = Some(local_scope.clone());
                            let capabilities = Arc::clone(&self.capabilities);
                            let native_modules = self.native_modules.clone();
                            Value::native(move |args: &[Value]| {
                                let mut vm = Vm {
                                    stack: Vec::new(),
                                    scope: ObjectMap::default(),
                                    enclosing: enclosing.clone(),
                                    globals: globals.clone(),
                                    capabilities: Arc::clone(&capabilities),
                                    native_modules: native_modules.clone(),
                                };
                                vm.run_chunk(&inner_clone, &inner_clone.nested, args, false)
                                    .unwrap_or(Value::Null)
                            })
                        }
                    };
                    self.stack.push(v);
                }
                Opcode::LoadVar => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = local_scope
                        .borrow()
                        .get(name.as_ref())
                        .cloned()
                        .or_else(|| {
                            self.enclosing
                                .as_ref()
                                .and_then(|e| e.borrow().get(name.as_ref()).cloned())
                        })
                        .or_else(|| self.scope.get(name.as_ref()).cloned())
                        .or_else(|| self.globals.borrow().get(name.as_ref()).cloned())
                        .ok_or_else(|| format!("Undefined variable: {}", name))?;
                    self.stack.push(v);
                }
                Opcode::StoreVar => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    // Update innermost scope that has the variable (matches interpreter Scope.assign)
                    if local_scope.borrow().contains_key(name.as_ref()) {
                        local_scope.borrow_mut().insert(Arc::clone(name), v);
                    } else if self
                        .enclosing
                        .as_ref()
                        .map(|e| e.borrow().contains_key(name.as_ref()))
                        .unwrap_or(false)
                    {
                        let en = self.enclosing.as_ref().unwrap();
                        en.borrow_mut().insert(Arc::clone(name), v);
                    } else if self.scope.contains_key(name.as_ref()) {
                        self.scope.insert(Arc::clone(name), v);
                    } else if self.globals.borrow().contains_key(name.as_ref()) {
                        self.globals.borrow_mut().insert(Arc::clone(name), v);
                    } else {
                        // New variable: at top level (no enclosing) store in globals so REPL persists across lines
                        if self.enclosing.is_none() {
                            self.globals.borrow_mut().insert(Arc::clone(name), v);
                        } else {
                            local_scope.borrow_mut().insert(Arc::clone(name), v);
                        }
                    }
                }
                Opcode::DeclareVar => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    if let Some(frame) = block_undo_stack.last_mut() {
                        let old = local_scope.borrow().get(name.as_ref()).cloned();
                        frame.push((Arc::clone(name), old));
                    }
                    // REPL: persist top-level bindings only (not block-locals shadowing globals).
                    if repl_mode && self.enclosing.is_none() && block_undo_stack.is_empty() {
                        self.globals
                            .borrow_mut()
                            .insert(Arc::clone(name), v.clone());
                    }
                    local_scope.borrow_mut().insert(Arc::clone(name), v);
                }
                Opcode::DeclareVarPlain => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    if repl_mode && self.enclosing.is_none() && block_undo_stack.is_empty() {
                        self.globals
                            .borrow_mut()
                            .insert(Arc::clone(name), v.clone());
                    }
                    local_scope.borrow_mut().insert(Arc::clone(name), v);
                }
                Opcode::EnterBlock => {
                    block_undo_stack.push(Vec::new());
                }
                Opcode::ExitBlock => {
                    let frame = block_undo_stack
                        .pop()
                        .ok_or_else(|| "ExitBlock without matching EnterBlock".to_string())?;
                    for (name, old) in frame.into_iter().rev() {
                        let mut ls = local_scope.borrow_mut();
                        match old {
                            Some(prev) => {
                                ls.insert(name, prev);
                            }
                            None => {
                                ls.remove(name.as_ref());
                            }
                        }
                    }
                }
                Opcode::LoadGlobal => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = self
                        .globals
                        .borrow()
                        .get(name.as_ref())
                        .cloned()
                        .ok_or_else(|| format!("Undefined global: {}", name))?;
                    self.stack.push(v);
                }
                Opcode::StoreGlobal => {
                    let idx = Self::read_u16(code, &mut ip);
                    let name = names
                        .get(idx as usize)
                        .ok_or_else(|| format!("Name index out of bounds: {}", idx))?;
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    self.globals.borrow_mut().insert(Arc::clone(name), v);
                }
                Opcode::Pop => {
                    self.stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                }
                Opcode::PopN => {
                    let n = Self::read_u16(code, &mut ip) as usize;
                    for _ in 0..n {
                        self.stack
                            .pop()
                            .ok_or_else(|| "Stack underflow".to_string())?;
                    }
                }
                Opcode::Dup => {
                    let v = self
                        .stack
                        .last()
                        .ok_or_else(|| "Stack underflow".to_string())?
                        .clone();
                    self.stack.push(v);
                }
                Opcode::Call => {
                    let argc = Self::read_u16(code, &mut ip) as usize;
                    let mut args = Vec::with_capacity(argc);
                    for _ in 0..argc {
                        args.push(
                            self.stack
                                .pop()
                                .ok_or_else(|| "Stack underflow in call".to_string())?,
                        );
                    }
                    args.reverse();
                    let callee = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow: no callee".to_string())?;
                    let f = match &callee {
                        Value::Function(f) => f.clone(),
                        Value::Object(o) => {
                            if let Some(Value::Function(call_fn)) =
                                o.borrow().strings.get("__call")
                            {
                                call_fn.clone()
                            } else {
                                return Err(format!(
                                    "Call of non-function: {}",
                                    callee.type_name()
                                ));
                            }
                        }
                        _ => {
                            return Err(format!("Call of non-function: {}", callee.type_name()));
                        }
                    };
                    let result = f(&args);
                    self.stack.push(result);
                }
                Opcode::CallSpread => {
                    let callee = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow: no callee in CallSpread".to_string())?;
                    let args_array = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow in CallSpread".to_string())?;
                    let args: Vec<Value> = match &args_array {
                        Value::Array(a) => a.borrow().clone(),
                        _ => {
                            return Err(format!(
                                "CallSpread: args must be array, got {}",
                                args_array.to_display_string()
                            ));
                        }
                    };
                    let f = match &callee {
                        Value::Function(f) => f.clone(),
                        Value::Object(o) => {
                            if let Some(Value::Function(call_fn)) =
                                o.borrow().strings.get("__call")
                            {
                                call_fn.clone()
                            } else {
                                return Err(format!(
                                    "Call of non-function: {}",
                                    callee.type_name()
                                ));
                            }
                        }
                        _ => {
                            return Err(format!("Call of non-function: {}", callee.type_name()));
                        }
                    };
                    let result = f(&args);
                    self.stack.push(result);
                }
                Opcode::Construct => {
                    let argc = Self::read_u16(code, &mut ip) as usize;
                    let mut args = Vec::with_capacity(argc);
                    for _ in 0..argc {
                        args.push(
                            self.stack
                                .pop()
                                .ok_or_else(|| "Stack underflow in construct".to_string())?,
                        );
                    }
                    args.reverse();
                    let callee = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow: no callee for construct".to_string())?;
                    let result = construct_builtin::construct(&callee, &args);
                    self.stack.push(result);
                }
                Opcode::ConstructSpread => {
                    let callee = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow: callee in ConstructSpread".to_string())?;
                    let args_array = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow in ConstructSpread".to_string())?;
                    let args: Vec<Value> = match &args_array {
                        Value::Array(a) => a.borrow().clone(),
                        _ => {
                            return Err(format!(
                                "ConstructSpread: args must be array, got {}",
                                args_array.to_display_string()
                            ));
                        }
                    };
                    let result = construct_builtin::construct(&callee, &args);
                    self.stack.push(result);
                }
                Opcode::Return => {
                    let v = self.stack.pop().unwrap_or(Value::Null);
                    return Ok(v);
                }
                Opcode::Jump => {
                    let offset = Self::read_i16(code, &mut ip) as isize;
                    ip = (ip as isize + offset).max(0) as usize;
                }
                Opcode::JumpIfFalse => {
                    let offset = Self::read_i16(code, &mut ip) as isize;
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    if !v.is_truthy() {
                        ip = (ip as isize + offset).max(0) as usize;
                    }
                }
                Opcode::JumpBack => {
                    let dist = Self::read_u16(code, &mut ip) as usize;
                    ip = ip.saturating_sub(dist);
                }
                Opcode::BinOp => {
                    let op_u8 = Self::read_u16(code, &mut ip) as u8;
                    let r = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let l = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let op =
                        u8_to_binop(op_u8).ok_or_else(|| format!("Unknown binop: {}", op_u8))?;
                    let result = eval_binop(op, &l, &r)?;
                    self.stack.push(result);
                }
                Opcode::UnaryOp => {
                    let op_u8 = Self::read_u16(code, &mut ip) as u8;
                    let o = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let op = u8_to_unaryop(op_u8)
                        .ok_or_else(|| format!("Unknown unary op: {}", op_u8))?;
                    let result = eval_unary(op, &o)?;
                    self.stack.push(result);
                }
                Opcode::GetMember => {
                    let idx = Self::read_u16(code, &mut ip);
                    let key = names
                        .get(idx as usize)
                        .ok_or_else(|| "Name index out of bounds".to_string())?;
                    let obj = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let v = get_member(&obj, key)?;
                    self.stack.push(v);
                }
                Opcode::GetMemberOptional => {
                    let idx = Self::read_u16(code, &mut ip);
                    let key = names
                        .get(idx as usize)
                        .ok_or_else(|| "Name index out of bounds".to_string())?;
                    let obj = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let v = get_member(&obj, key).unwrap_or(Value::Null);
                    self.stack.push(v);
                }
                Opcode::SetMember => {
                    let idx = Self::read_u16(code, &mut ip);
                    let key = names
                        .get(idx as usize)
                        .ok_or_else(|| "Name index out of bounds".to_string())?;
                    let val = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let obj = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    set_member(&obj, key, val.clone())?;
                    self.stack.push(val); // assignment yields value
                }
                Opcode::GetIndex => {
                    let idx_val = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let obj = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let v = get_index(&obj, &idx_val)?;
                    self.stack.push(v);
                }
                Opcode::SetIndex => {
                    // Stack: [obj, idx, val, val] (Dup of val for expression result).
                    // Pop val (dup), val, idx, obj; use (obj, idx, val) for set_index; leave val on stack.
                    let dup_val = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let val = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let idx_val = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let obj = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    set_index(&obj, &idx_val, val.clone())?;
                    self.stack.push(dup_val); // assignment yields the assigned value
                }
                Opcode::NewArray => {
                    let n = Self::read_u16(code, &mut ip) as usize;
                    let mut elems = Vec::with_capacity(n);
                    for _ in 0..n {
                        elems.push(
                            self.stack
                                .pop()
                                .ok_or_else(|| "Stack underflow".to_string())?,
                        );
                    }
                    elems.reverse();
                    self.stack.push(Value::Array(VmRef::new(elems)));
                }
                Opcode::NewObject => {
                    let n = Self::read_u16(code, &mut ip) as usize;
                    let mut map = ObjectMap::with_capacity(n.max(1));
                    for _ in 0..n {
                        let val = self
                            .stack
                            .pop()
                            .ok_or_else(|| "Stack underflow".to_string())?;
                        let key_val = self
                            .stack
                            .pop()
                            .ok_or_else(|| "Stack underflow".to_string())?;
                        let key = key_val.to_display_string().into();
                        map.insert(key, val);
                    }
                    self.stack.push(value_object_from_map(map));
                }
                Opcode::EnterTry => {
                    let offset = Self::read_u16(code, &mut ip) as usize;
                    let catch_ip = ip + offset;
                    try_handlers.push((catch_ip, self.stack.len()));
                }
                Opcode::ExitTry => {
                    try_handlers.pop();
                }
                Opcode::ConcatArray => {
                    let right = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let left = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let (mut a, b) = (
                        match &left {
                            Value::Array(arr) => arr.borrow().clone(),
                            _ => {
                                return Err(format!(
                                    "ConcatArray: left must be array, got {}",
                                    left.to_display_string()
                                ));
                            }
                        },
                        match &right {
                            Value::Array(arr) => arr.borrow().clone(),
                            _ => {
                                return Err(format!(
                                    "ConcatArray: right must be array, got {}",
                                    right.to_display_string()
                                ));
                            }
                        },
                    );
                    a.extend(b);
                    self.stack.push(Value::Array(VmRef::new(a)));
                }
                Opcode::MergeObject => {
                    let right = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let left = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    match (&left, &right) {
                        (Value::Object(l), Value::Object(r)) => {
                            let merged = merge_object_data(l, r);
                            self.stack.push(Value::Object(VmRef::new(merged)));
                        }
                        _ => {
                            return Err(format!(
                                "MergeObject: expected two objects, got {} and {}",
                                left.to_display_string(),
                                right.to_display_string()
                            ));
                        }
                    }
                }
                Opcode::ArraySortNumeric => {
                    let operand = Self::read_u16(code, &mut ip);
                    let asc = operand == 0;
                    let arr = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let result = if asc {
                        arr_builtins::sort_numeric_asc(&arr)
                    } else {
                        arr_builtins::sort_numeric_desc(&arr)
                    };
                    self.stack.push(result);
                }
                Opcode::ArraySortByProperty => {
                    let prop_idx = Self::read_u16(code, &mut ip);
                    let asc = Self::read_u16(code, &mut ip) == 0;
                    let arr = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let prop = constants
                        .get(prop_idx as usize)
                        .and_then(|c| {
                            if let Constant::String(s) = c {
                                Some(s.as_ref())
                            } else {
                                None
                            }
                        })
                        .unwrap_or("");
                    let result = arr_builtins::sort_by_property_numeric(&arr, prop, asc);
                    self.stack.push(result);
                }
                Opcode::ArrayMapIdentity => {
                    let arr = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let result = match &arr {
                        Value::Array(a) => Value::Array(VmRef::new(a.borrow().clone())),
                        _ => Value::Null,
                    };
                    self.stack.push(result);
                }
                Opcode::ArrayMapBinOp => {
                    let binop_u8 = code[ip];
                    ip += 1;
                    let const_idx = Self::read_u16(code, &mut ip);
                    let param_left = code[ip] == 0; // 0 = param on left (x op const), 1 = param on right (const op x)
                    ip += 1;
                    let binop = u8_to_binop(binop_u8)
                        .ok_or_else(|| format!("Unknown binop in ArrayMapBinOp: {}", binop_u8))?;
                    let arr = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let const_val = constants
                        .get(const_idx as usize)
                        .map(|c| c.to_value())
                        .unwrap_or(Value::Null);
                    let result = if let Value::Array(a) = &arr {
                        let arr_borrow = a.borrow();
                        let mapped: Vec<Value> = arr_borrow
                            .iter()
                            .map(|v| {
                                let l: Value = if param_left {
                                    (*v).clone()
                                } else {
                                    const_val.clone()
                                };
                                let r: Value = if param_left {
                                    const_val.clone()
                                } else {
                                    (*v).clone()
                                };
                                eval_binop(binop, &l, &r).unwrap_or(Value::Null)
                            })
                            .collect();
                        Value::Array(VmRef::new(mapped))
                    } else {
                        Value::Null
                    };
                    self.stack.push(result);
                }
                Opcode::ArrayFilterBinOp => {
                    let binop_u8 = code[ip];
                    ip += 1;
                    let const_idx = Self::read_u16(code, &mut ip);
                    let param_left = code[ip] == 0; // 0 = param on left (x op const), 1 = param on right (const op x)
                    ip += 1;
                    let binop = u8_to_binop(binop_u8).ok_or_else(|| {
                        format!("Unknown binop in ArrayFilterBinOp: {}", binop_u8)
                    })?;
                    let arr = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    let const_val = constants
                        .get(const_idx as usize)
                        .map(|c| c.to_value())
                        .unwrap_or(Value::Null);
                    let result = if let Value::Array(a) = &arr {
                        let arr_borrow = a.borrow();
                        let filtered: Vec<Value> = arr_borrow
                            .iter()
                            .filter(|v| {
                                let l: Value = if param_left {
                                    (*v).clone()
                                } else {
                                    const_val.clone()
                                };
                                let r: Value = if param_left {
                                    const_val.clone()
                                } else {
                                    (*v).clone()
                                };
                                let b = eval_binop(binop, &l, &r).unwrap_or(Value::Null);
                                b.is_truthy()
                            })
                            .cloned()
                            .collect();
                        Value::Array(VmRef::new(filtered))
                    } else {
                        Value::Null
                    };
                    self.stack.push(result);
                }
                Opcode::Throw => {
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow".to_string())?;
                    Self::unwind_throw(&mut try_handlers, &mut self.stack, &mut ip, v)?;
                }
                Opcode::AwaitPromise => {
                    let v = self
                        .stack
                        .pop()
                        .ok_or_else(|| "Stack underflow in AwaitPromise".to_string())?;
                    #[cfg(any(feature = "http", feature = "promise"))]
                    {
                        use tishlang_core::Value as V;
                        match v {
                            V::Promise(p) => match p.block_until_settled() {
                                Ok(val) => self.stack.push(val),
                                Err(rej) => {
                                    Self::unwind_throw(
                                        &mut try_handlers,
                                        &mut self.stack,
                                        &mut ip,
                                        rej,
                                    )?;
                                }
                            },
                            other => self.stack.push(tishlang_runtime::await_promise(other)),
                        }
                    }
                    #[cfg(not(any(feature = "http", feature = "promise")))]
                    {
                        self.stack.push(v);
                    }
                }
                Opcode::LoadNativeExport => {
                    let spec_idx = Self::read_u16(code, &mut ip);
                    let export_idx = Self::read_u16(code, &mut ip);
                    let spec = match constants.get(spec_idx as usize) {
                        Some(Constant::String(s)) => s.as_ref(),
                        _ => {
                            return Err(
                                "LoadNativeExport: spec constant out of bounds or not string"
                                    .to_string(),
                            );
                        }
                    };
                    let export_name = match constants.get(export_idx as usize) {
                        Some(Constant::String(s)) => s.as_ref(),
                        _ => {
                            return Err("LoadNativeExport: export_name constant out of bounds or not string".to_string());
                        }
                    };
                    // Phase-2 item 11: consult externally registered native
                    // modules (populated via `Vm::register_native_module`)
                    // before falling through to the built-in lookup. Embedders
                    // on the cranelift / llvm backends that want to expose
                    // `cargo:…` Rust crates should register the module's
                    // exports map before calling `vm.run(chunk)`.
                    let from_registry: Option<Value> = if spec.starts_with("cargo:") {
                        let regs = self.native_modules.borrow();
                        regs.get(spec)
                            .and_then(|m| m.borrow().get(&Arc::from(export_name)).cloned())
                    } else {
                        None
                    };
                    let v = from_registry
                        .or_else(|| get_builtin_export(self.capabilities.as_ref(), spec, export_name))
                        .ok_or_else(|| {
                            if spec.starts_with("cargo:") {
                                format!(
                                    "cargo:{} is not registered on the bytecode VM. Embedders must call Vm::register_native_module before run(). Spec: {} export: {}",
                                    spec.trim_start_matches("cargo:"),
                                    spec,
                                    export_name,
                                )
                            } else {
                                format!(
                                    "Built-in module '{}' does not export '{}' or capability not enabled for this run. Use e.g. tish run --feature fs (or full). The tish binary must also be built with that capability linked in.",
                                    spec, export_name
                                )
                            }
                        })?;
                    self.stack.push(v);
                }
                Opcode::Closure | Opcode::LoadThis => {
                    return Err(format!("Unhandled opcode: {:?}", opcode));
                }
            }
        }

        #[cfg(feature = "timers")]
        if cap_allows(self.capabilities.as_ref(), "timers") {
            tishlang_runtime::drain_timers();
        }

        Ok(self.stack.pop().unwrap_or(Value::Null))
    }
}

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

/// Rough byte capacity for string coercion (matches hot paths like `"x" + n + "ms"`).
fn estimate_string_concat_len(v: &Value) -> usize {
    match v {
        Value::String(s) => s.len(),
        Value::Number(_) => 24,
        Value::Bool(_) => 5,
        Value::Null => 4,
        _ => 32,
    }
}

/// Append JS-style string conversion without an intermediate `String` per operand (unlike
/// `format!("{}{}", a.to_display_string(), b.to_display_string())`, which triple-allocates).
fn append_value_for_string_concat(out: &mut String, v: &Value) {
    use std::fmt::Write;
    match v {
        Value::Number(n) => {
            if n.is_nan() {
                out.push_str("NaN");
            } else if *n == f64::INFINITY {
                out.push_str("Infinity");
            } else if *n == f64::NEG_INFINITY {
                out.push_str("-Infinity");
            } else {
                let _ = write!(out, "{n}");
            }
        }
        Value::String(s) => out.push_str(s.as_ref()),
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::Null => out.push_str("null"),
        _ => out.push_str(&v.to_display_string()),
    }
}

fn eval_binop(op: BinOp, l: &Value, r: &Value) -> Result<Value, String> {
    use tishlang_ast::BinOp::*;
    use tishlang_core::Value::*;
    let ln = l.as_number().unwrap_or(f64::NAN);
    let rn = r.as_number().unwrap_or(f64::NAN);
    match op {
        Add => {
            if matches!(l, Value::String(_)) || matches!(r, Value::String(_)) {
                let cap = estimate_string_concat_len(l) + estimate_string_concat_len(r);
                let mut buf = std::string::String::with_capacity(cap);
                append_value_for_string_concat(&mut buf, l);
                append_value_for_string_concat(&mut buf, r);
                Ok(String(buf.into()))
            } else {
                Ok(Number(ln + rn))
            }
        }
        Sub => Ok(Number(ln - rn)),
        Mul => Ok(Number(ln * rn)),
        Div => Ok(Number(if rn == 0.0 { f64::NAN } else { ln / rn })),
        Mod => Ok(Number(if rn == 0.0 { f64::NAN } else { ln % rn })),
        Pow => Ok(Number(ln.powf(rn))),
        Eq => Ok(Bool(l.strict_eq(r))),
        Ne => Ok(Bool(!l.strict_eq(r))),
        StrictEq => Ok(Bool(l.strict_eq(r))),
        StrictNe => Ok(Bool(!l.strict_eq(r))),
        Lt => Ok(Bool(ln < rn)),
        Le => Ok(Bool(ln <= rn)),
        Gt => Ok(Bool(ln > rn)),
        Ge => Ok(Bool(ln >= rn)),
        And => Ok(Bool(l.is_truthy() && r.is_truthy())),
        Or => Ok(Bool(l.is_truthy() || r.is_truthy())),
        BitAnd => Ok(Number((ln as i32 & rn as i32) as f64)),
        BitOr => Ok(Number((ln as i32 | rn as i32) as f64)),
        BitXor => Ok(Number((ln as i32 ^ rn as i32) as f64)),
        Shl => Ok(Number(((ln as i32) << (rn as i32)) as f64)),
        Shr => Ok(Number(((ln as i32) >> (rn as i32)) as f64)),
        In => Ok(Bool(match r {
            Value::Object(_) => object_has(r, l),
            Value::Array(a) => {
                let key_s: Arc<str> = match l {
                    Value::String(s) => Arc::clone(s),
                    Value::Number(n) => n.to_string().into(),
                    _ => l.to_display_string().into(),
                };
                if key_s.as_ref() == "length" {
                    true
                } else if let Ok(idx) = key_s.parse::<usize>() {
                    idx < a.borrow().len()
                } else {
                    false
                }
            }
            _ => false,
        })),
    }
}

fn eval_unary(op: UnaryOp, o: &Value) -> Result<Value, String> {
    use tishlang_ast::UnaryOp::*;
    use tishlang_core::Value::*;
    match op {
        Not => Ok(Bool(!o.is_truthy())),
        Neg => Ok(Number(-o.as_number().unwrap_or(f64::NAN))),
        Pos => Ok(Number(o.as_number().unwrap_or(f64::NAN))),
        BitNot => Ok(Number(!(o.as_number().unwrap_or(0.0) as i32) as f64)),
        Void => Ok(Null),
    }
}

fn get_member(obj: &Value, key: &Arc<str>) -> Result<Value, String> {
    match obj {
        Value::Object(m) => {
            let map = m.borrow();
            map.strings
                .get(key.as_ref())
                .cloned()
                .ok_or_else(|| format!("Property '{}' not found", key))
        }
        Value::Array(a) => {
            let key_s = key.as_ref();
            if let Ok(idx) = key_s.parse::<usize>() {
                let arr = a.borrow();
                return arr
                    .get(idx)
                    .cloned()
                    .ok_or_else(|| "Index out of bounds".to_string());
            }
            if key_s == "length" {
                return Ok(Value::Number(a.borrow().len() as f64));
            }
            let a_clone = a.clone();
            let method: ArrayMethodFn = match key_s {
                "push" => make_native_fn(move |args: &[Value]| {
                    arr_builtins::push(&Value::Array(a_clone.clone()), args)
                }),
                "pop" => make_native_fn(move |_args: &[Value]| {
                    arr_builtins::pop(&Value::Array(a_clone.clone()))
                }),
                "shift" => make_native_fn(move |_args: &[Value]| {
                    arr_builtins::shift(&Value::Array(a_clone.clone()))
                }),
                "unshift" => make_native_fn(move |args: &[Value]| {
                    arr_builtins::unshift(&Value::Array(a_clone.clone()), args)
                }),
                "reverse" => make_native_fn(move |_args: &[Value]| {
                    arr_builtins::reverse(&Value::Array(a_clone.clone()))
                }),
                "shuffle" => make_native_fn(move |_args: &[Value]| {
                    arr_builtins::shuffle(&Value::Array(a_clone.clone()))
                }),
                "slice" => make_native_fn(move |args: &[Value]| {
                    let start = args.first().unwrap_or(&Value::Null);
                    let end = args.get(1).unwrap_or(&Value::Null);
                    arr_builtins::slice(&Value::Array(a_clone.clone()), start, end)
                }),
                "concat" => make_native_fn(move |args: &[Value]| {
                    arr_builtins::concat(&Value::Array(a_clone.clone()), args)
                }),
                "join" => make_native_fn(move |args: &[Value]| {
                    let sep = args.first().unwrap_or(&Value::Null);
                    arr_builtins::join(&Value::Array(a_clone.clone()), sep)
                }),
                "indexOf" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    arr_builtins::index_of(&Value::Array(a_clone.clone()), search)
                }),
                "includes" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let from = args.get(1);
                    arr_builtins::includes(&Value::Array(a_clone.clone()), search, from)
                }),
                "map" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::map(&Value::Array(a_clone.clone()), &cb)
                }),
                "filter" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::filter(&Value::Array(a_clone.clone()), &cb)
                }),
                "reduce" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    let init = args.get(1).cloned().unwrap_or(Value::Null);
                    arr_builtins::reduce(&Value::Array(a_clone.clone()), &cb, &init)
                }),
                "forEach" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::for_each(&Value::Array(a_clone.clone()), &cb)
                }),
                "find" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::find(&Value::Array(a_clone.clone()), &cb)
                }),
                "findIndex" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::find_index(&Value::Array(a_clone.clone()), &cb)
                }),
                "some" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::some(&Value::Array(a_clone.clone()), &cb)
                }),
                "every" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::every(&Value::Array(a_clone.clone()), &cb)
                }),
                "flat" => make_native_fn(move |args: &[Value]| {
                    let depth = args.first().unwrap_or(&Value::Number(1.0));
                    arr_builtins::flat(&Value::Array(a_clone.clone()), depth)
                }),
                "flatMap" => make_native_fn(move |args: &[Value]| {
                    let cb = args.first().cloned().unwrap_or(Value::Null);
                    arr_builtins::flat_map(&Value::Array(a_clone.clone()), &cb)
                }),
                "sort" => make_native_fn(move |args: &[Value]| {
                    let cmp = args.first();
                    if let Some(Value::Function(_)) = cmp {
                        arr_builtins::sort_with_comparator(
                            &Value::Array(a_clone.clone()),
                            cmp.unwrap(),
                        )
                    } else {
                        arr_builtins::sort_default(&Value::Array(a_clone.clone()))
                    }
                }),
                "splice" => make_native_fn(move |args: &[Value]| {
                    let start = args.first().unwrap_or(&Value::Null);
                    let delete_count = args.get(1).map(|v| v as &Value);
                    let items: Vec<Value> = args.get(2..).unwrap_or(&[]).to_vec();
                    arr_builtins::splice(
                        &Value::Array(a_clone.clone()),
                        start,
                        delete_count,
                        &items,
                    )
                }),
                _ => return Err(format!("Property '{}' not found", key)),
            };
            Ok(Value::Function(method))
        }
        Value::String(s) => {
            let key_s = key.as_ref();
            if let Ok(idx) = key_s.parse::<usize>() {
                return match s.chars().nth(idx) {
                    Some(c) => Ok(Value::String(Arc::from(c.to_string()))),
                    None => Err("Index out of bounds".to_string()),
                };
            }
            if key_s == "length" {
                return Ok(Value::Number(s.chars().count() as f64));
            }
            let s_clone: Arc<str> = Arc::clone(s);
            let method: ArrayMethodFn = match key_s {
                "indexOf" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let from = args.get(1);
                    str_builtins::index_of(&Value::String(Arc::clone(&s_clone)), search, from)
                }),
                "lastIndexOf" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let position = args.get(1).cloned().unwrap_or(Value::Number(f64::INFINITY));
                    str_builtins::last_index_of(
                        &Value::String(Arc::clone(&s_clone)),
                        search,
                        &position,
                    )
                }),
                "includes" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let from = args.get(1);
                    str_builtins::includes(&Value::String(Arc::clone(&s_clone)), search, from)
                }),
                "slice" => make_native_fn(move |args: &[Value]| {
                    let start = args.first().unwrap_or(&Value::Null);
                    let end = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::slice(&Value::String(Arc::clone(&s_clone)), start, end)
                }),
                "substring" => make_native_fn(move |args: &[Value]| {
                    let start = args.first().unwrap_or(&Value::Null);
                    let end = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::substring(&Value::String(Arc::clone(&s_clone)), start, end)
                }),
                "split" => make_native_fn(move |args: &[Value]| {
                    let sep = args.first().unwrap_or(&Value::Null);
                    str_builtins::split(&Value::String(Arc::clone(&s_clone)), sep)
                }),
                "trim" => make_native_fn(move |_args: &[Value]| {
                    str_builtins::trim(&Value::String(Arc::clone(&s_clone)))
                }),
                "toUpperCase" => make_native_fn(move |_args: &[Value]| {
                    str_builtins::to_upper_case(&Value::String(Arc::clone(&s_clone)))
                }),
                "toLowerCase" => make_native_fn(move |_args: &[Value]| {
                    str_builtins::to_lower_case(&Value::String(Arc::clone(&s_clone)))
                }),
                "startsWith" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    str_builtins::starts_with(&Value::String(Arc::clone(&s_clone)), search)
                }),
                "endsWith" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    str_builtins::ends_with(&Value::String(Arc::clone(&s_clone)), search)
                }),
                "replace" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let replacement = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::replace(&Value::String(Arc::clone(&s_clone)), search, replacement)
                }),
                "replaceAll" => make_native_fn(move |args: &[Value]| {
                    let search = args.first().unwrap_or(&Value::Null);
                    let replacement = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::replace_all(
                        &Value::String(Arc::clone(&s_clone)),
                        search,
                        replacement,
                    )
                }),
                "charAt" => make_native_fn(move |args: &[Value]| {
                    let idx = args.first().unwrap_or(&Value::Null);
                    str_builtins::char_at(&Value::String(Arc::clone(&s_clone)), idx)
                }),
                "charCodeAt" => make_native_fn(move |args: &[Value]| {
                    let idx = args.first().unwrap_or(&Value::Null);
                    str_builtins::char_code_at(&Value::String(Arc::clone(&s_clone)), idx)
                }),
                "repeat" => make_native_fn(move |args: &[Value]| {
                    let count = args.first().unwrap_or(&Value::Null);
                    str_builtins::repeat(&Value::String(Arc::clone(&s_clone)), count)
                }),
                "padStart" => make_native_fn(move |args: &[Value]| {
                    let target_len = args.first().unwrap_or(&Value::Null);
                    let pad = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::pad_start(&Value::String(Arc::clone(&s_clone)), target_len, pad)
                }),
                "padEnd" => make_native_fn(move |args: &[Value]| {
                    let target_len = args.first().unwrap_or(&Value::Null);
                    let pad = args.get(1).unwrap_or(&Value::Null);
                    str_builtins::pad_end(&Value::String(Arc::clone(&s_clone)), target_len, pad)
                }),
                _ => return Err(format!("Property '{}' not found", key)),
            };
            Ok(Value::Function(method))
        }
        #[cfg(any(feature = "http", feature = "promise"))]
        Value::Promise(p) => match key.as_ref() {
            "then" => {
                let pc = Arc::clone(p);
                Ok(Value::native(move |args| {
                    tishlang_runtime::promise_instance_then(&pc, args)
                }))
            }
            "catch" => {
                let pc = Arc::clone(p);
                Ok(Value::native(move |args| {
                    tishlang_runtime::promise_instance_catch(&pc, args)
                }))
            }
            _ => Err(format!("Property '{}' not found", key)),
        },
        _ => Err(format!(
            "Cannot read property '{}' of {}",
            key,
            obj.type_name()
        )),
    }
}

fn set_member(obj: &Value, key: &Arc<str>, val: Value) -> Result<(), String> {
    match obj {
        Value::Object(m) => {
            m.borrow_mut().strings.insert(Arc::clone(key), val);
            Ok(())
        }
        Value::Array(a) => {
            let idx: usize = key.as_ref().parse().unwrap_or(0);
            let mut arr = a.borrow_mut();
            if idx < arr.len() {
                arr[idx] = val;
            } else {
                arr.resize(idx + 1, Value::Null);
                arr[idx] = val;
            }
            Ok(())
        }
        _ => Err(format!("Cannot set property of {}", obj.type_name())),
    }
}

fn get_index(obj: &Value, idx: &Value) -> Result<Value, String> {
    match obj {
        Value::Array(a) => {
            let i = match idx {
                Value::Number(n) => *n as usize,
                _ => {
                    return Err(format!(
                        "Array index must be number, got {}",
                        idx.type_name()
                    ));
                }
            };
            Ok(a
                .borrow()
                .get(i)
                .cloned()
                .unwrap_or(Value::Null))
        }
        Value::String(s) => {
            let i = match idx {
                Value::Number(n) => {
                    let n = *n;
                    if n < 0.0 || n.fract() != 0.0 {
                        return Err(format!(
                            "String index must be non-negative integer, got {}",
                            n
                        ));
                    }
                    let i = n as usize;
                    let len = s.chars().count();
                    if i >= len {
                        return Err("Index out of bounds".to_string());
                    }
                    i
                }
                _ => {
                    return Err(format!(
                        "String index must be number, got {}",
                        idx.type_name()
                    ));
                }
            };
            match s.chars().nth(i) {
                Some(c) => Ok(Value::String(Arc::from(c.to_string()))),
                None => Err("Index out of bounds".to_string()),
            }
        }
        Value::Object(_) => object_get(obj, idx).ok_or_else(|| {
            format!(
                "Property '{}' not found",
                idx.to_display_string()
            )
        }),
        #[cfg(any(feature = "http", feature = "promise"))]
        Value::Promise(_) => {
            let key_arc: std::sync::Arc<str> = match idx {
                Value::String(s) => std::sync::Arc::clone(s),
                _ => {
                    return Err(format!(
                        "Promise bracket access requires a string key, got {}",
                        idx.type_name()
                    ));
                }
            };
            get_member(obj, &key_arc)
        },
        _ => Err(format!(
            "Cannot read property '{}' of {}",
            idx.to_display_string(),
            obj.type_name()
        )),
    }
}

fn set_index(obj: &Value, idx: &Value, val: Value) -> Result<(), String> {
    match obj {
        Value::Array(a) => {
            let i = match idx {
                Value::Number(n) => *n as usize,
                _ => {
                    return Err(format!(
                        "Array index must be number, got {}",
                        idx.type_name()
                    ));
                }
            };
            let mut arr = a.borrow_mut();
            while arr.len() <= i {
                arr.push(Value::Null);
            }
            arr[i] = val;
            Ok(())
        }
        Value::Object(_) => object_set(obj, idx, val),
        _ => Err(format!("Cannot set property of {}", obj.type_name())),
    }
}

/// Run a chunk with every capability linked into this `tishlang_vm` build (tests, embedders).
pub fn run(chunk: &Chunk) -> Result<Value, String> {
    let mut vm = Vm::new();
    vm.run_with_options(chunk, false)
}

/// Run a chunk with options (e.g. REPL persistence for top-level declarations).
pub fn run_with_options(chunk: &Chunk, opts: VmRunOptions) -> Result<Value, String> {
    let mut vm = Vm::with_capabilities(opts.capabilities);
    vm.run_with_options(chunk, opts.repl_mode)
}