sui-bytecode 0.1.148

Bytecode compiler and VM for the sui Rust-native Nix evaluator
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
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
//! Bytecode VM execution engine.
//!
//! A stack-based interpreter that executes compiled [`Chunk`]s. The VM
//! maintains a NaN-boxed value stack (8 bytes per entry), a call stack
//! for function invocations, and dispatches instructions via a `match` loop.
//!
//! # NaN-boxing
//!
//! The value stack uses [`NanBox`] instead of [`VMValue`]. Scalars (null,
//! bool, int, float) are stored inline as 8-byte values without heap
//! allocation. Complex types (strings, lists, attrsets, closures, builtins,
//! thunks) use an `Rc<HeapObject>` pointer encoded in the NaN payload bits.
//!
//! The constant pool (in `Chunk`) still uses `VMValue`; values are converted
//! to `NanBox` when pushed onto the stack and converted back only at the
//! external API boundary (`execute` returns `VMValue`).
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
/// Counts how many files fell back to the tree-walker during VM import.
static VM_FALLBACK_COUNT: AtomicU64 = AtomicU64::new(0);
/// Return the number of files that fell back to tree-walker evaluation.
pub fn vm_fallback_count() -> u64 {
    VM_FALLBACK_COUNT.load(Ordering::Relaxed)
}
use crate::builtins::BuiltinRegistry;
use crate::chunk::Chunk;
use crate::compiler::Compiler;
use crate::error::VMError;
use crate::intern::{Interner, Symbol};
use crate::nanbox::NanBox;
use crate::opcode::OpCode;
use crate::value::{HigherOrderBuiltin, HigherOrderOp, ThunkState, VMThunk, VMValue};
/// Maximum call depth before we report a stack overflow.
const MAX_CALL_DEPTH: usize = 1024;
/// Maximum depth for thunk-in-thunk chain unwrapping.
/// Catches `let x = x; in x` cycles while allowing normal fixpoints.
const MAX_THUNK_CHAIN_DEPTH: u32 = 2000;
/// A tiny bytecode chunk: `GetUpvalue 0; GetUpvalue 1; Call; Return`.
/// Used to create deferred-application thunks where upvalue 0 is a
/// function and upvalue 1 is its argument. Cached to avoid repeated
/// allocation.
fn deferred_apply_chunk() -> Rc<Chunk> {
    thread_local! {
        static CHUNK: Rc<Chunk> = {
            let mut c = Chunk::new();
            // GetUpvalue 0 — push the function (upvalue index 0, little-endian u16)
            c.write_op(OpCode::GetUpvalue, 0);
            c.write_byte(0, 0); // lo byte of index 0
            c.write_byte(0, 0); // hi byte of index 0
            // GetUpvalue 1 — push the argument (upvalue index 1, little-endian u16)
            c.write_op(OpCode::GetUpvalue, 0);
            c.write_byte(1, 0); // lo byte of index 1
            c.write_byte(0, 0); // hi byte of index 1
            // Call
            c.write_op(OpCode::Call, 0);
            // Return
            c.write_op(OpCode::Return, 0);
            Rc::new(c)
        };
    }
    CHUNK.with(|c| c.clone())
}
// ── Flake resolver callback ─────────────────────────────────
/// Signature for an external flake resolver.
///
/// When set, the VM delegates `builtins.getFlake` to this callback
/// instead of using its own limited input resolution.  The callback
/// receives the raw flake reference string (e.g. `"path:/foo/bar"`)
/// and returns a `StringKeyedValue` attrset representing the fully
/// resolved flake outputs.
///
/// `sui-eval` sets this to the tree-walker's `evaluate_flake` which
/// handles all input types (GitHub, path, indirect) and produces
/// correct results for `(getFlake ref).inputs.nixpkgs`.
pub type FlakeResolverFn = dyn Fn(&str) -> Result<crate::value::StringKeyedValue, String>;
thread_local! {
    static FLAKE_RESOLVER: RefCell<Option<Box<FlakeResolverFn>>> = const { RefCell::new(None) };
}
/// Install a flake resolver callback for the current thread.
///
/// Returns an RAII guard that restores the previous resolver on drop.
/// This ensures the resolver is always properly cleaned up even when
/// evaluation errors occur.
pub fn set_flake_resolver(
    resolver: Box<FlakeResolverFn>,
) -> FlakeResolverGuard {
    let prev = FLAKE_RESOLVER.with(|r| r.borrow_mut().replace(resolver));
    FlakeResolverGuard { _prev: prev }
}
/// RAII guard that restores the previous flake resolver on drop.
pub struct FlakeResolverGuard {
    _prev: Option<Box<FlakeResolverFn>>,
}
impl Drop for FlakeResolverGuard {
    fn drop(&mut self) {
        let prev = self._prev.take();
        FLAKE_RESOLVER.with(|r| *r.borrow_mut() = prev);
    }
}
/// A call frame on the VM's call stack.
#[derive(Clone)]
struct CallFrame {
    /// The chunk being executed.
    chunk: Rc<Chunk>,
    /// Instruction pointer within the chunk.
    ip: usize,
    /// Base index in the value stack for this frame's locals.
    stack_base: usize,
    /// Upvalues captured by this frame's closure (NaN-boxed).
    upvalues: Vec<NanBox>,
}
/// The bytecode virtual machine.
///
/// Uses NaN-boxed values on the value stack: each entry is exactly 8 bytes,
/// making the stack cache-friendly. Scalars (null, bool, int, float) are
/// stored inline without heap allocation. Complex types use heap pointers
/// encoded in the NaN payload bits.
pub struct VM<'a> {
    /// NaN-boxed value stack (8 bytes per entry).
    stack: Vec<NanBox>,
    /// Call stack.
    frames: Vec<CallFrame>,
    /// Shared interner for attribute key operations.
    interner: &'a mut Interner,
    /// With-scope stack (dynamic variable scoping, NaN-boxed).
    with_stack: Vec<NanBox>,
    /// Registry of built-in functions.
    builtins: BuiltinRegistry,
    /// Import cache: canonical path -> evaluated result.
    import_cache: Rc<RefCell<HashMap<String, VMValue>>>,
    /// Compile cache: canonical path -> compiled bytecode.
    /// Avoids re-parsing and re-compiling files that are imported
    /// multiple times (e.g. via scopedImport or recursive imports).
    compile_cache: HashMap<PathBuf, Rc<Chunk>>,
}
impl<'a> VM<'a> {
    /// Create a new VM and execute a chunk, returning the result.
    pub fn execute(chunk: Chunk, interner: &'a mut Interner) -> Result<VMValue, VMError> {
        let mut vm = Self {
            stack: Vec::with_capacity(256),
            frames: Vec::with_capacity(64),
            interner,
            with_stack: Vec::new(),
            builtins: BuiltinRegistry::new(),
            import_cache: Rc::new(RefCell::new(HashMap::new())),
            compile_cache: HashMap::new(),
        };
        vm.frames.push(CallFrame {
            chunk: Rc::new(chunk),
            ip: 0,
            stack_base: 0,
            upvalues: Vec::new(),
        });
        let result = vm.run()?;
        // Force the top-level result so we never return a thunk.
        let result = vm.force_value(result)?;
        // Deep-force: recursively force thunks inside attrsets and lists
        // so the caller never sees unforced thunks.
        let result = vm.deep_force(result)?;
        Ok(result.to_vmvalue())
    }
    /// Main execution loop -- delegates to `run_until(0)`.
    fn run(&mut self) -> Result<NanBox, VMError> {
        self.run_until(0)
    }
    /// Execute until the frame stack drops to `stop_depth`.
    ///
    /// When the `Return` opcode pops a frame and the stack depth equals
    /// `stop_depth`, the loop exits and returns the result. This lets
    /// `import_file` and `force_value` run sub-programs without a separate VM.
    fn run_until(&mut self, stop_depth: usize) -> Result<NanBox, VMError> {
        let mut op_count: u64 = 0;
        loop {
            op_count += 1;
            if std::env::var("SUI_VM_TRACE").is_ok() && op_count % 1_000_000 == 0 {
                eprintln!(
                    "[sui-vm] {}M ops, depth {}, chunk: {}",
                    op_count / 1_000_000,
                    self.frames.len(),
                    self.current_chunk_name(),
                );
            }
            let op_byte = self.read_byte()?;
            let op = OpCode::from_byte(op_byte).ok_or(VMError::InvalidOpcode(op_byte))?;
            match op {
                // Arithmetic
                OpCode::Add | OpCode::Sub | OpCode::Mul | OpCode::Div | OpCode::Negate => {
                    self.dispatch_arithmetic(op)?;
                }
                // Comparison
                OpCode::Equal | OpCode::NotEqual | OpCode::Less | OpCode::Greater |
                OpCode::LessEqual | OpCode::GreaterEqual => {
                    self.dispatch_comparison(op)?;
                }
                // Logic
                OpCode::Not | OpCode::And | OpCode::Or | OpCode::Implication => {
                    self.dispatch_logic(op)?;
                }
                // Constants
                OpCode::Constant | OpCode::Null | OpCode::True | OpCode::False => {
                    self.dispatch_constant(op)?;
                }
                // Variables
                OpCode::GetLocal | OpCode::SetLocal | OpCode::GetUpvalue | OpCode::SetUpvalue => {
                    self.dispatch_variable(op)?;
                }
                // Attrsets
                OpCode::MakeAttrs | OpCode::GetAttr | OpCode::HasAttr | OpCode::UpdateAttrs |
                OpCode::SelectOrDefault | OpCode::DynGetAttr | OpCode::DynHasAttr |
                OpCode::DynSelectOrDefault => {
                    self.dispatch_attrset(op)?;
                }
                // Lists
                OpCode::MakeList | OpCode::Concat => {
                    self.dispatch_list(op)?;
                }
                // Control flow
                OpCode::Jump | OpCode::JumpIfFalse | OpCode::JumpIfTrue | OpCode::Assert | OpCode::Throw => {
                    self.dispatch_control(op)?;
                }
                // Functions
                OpCode::MakeClosure | OpCode::Call | OpCode::TailCall => {
                    self.dispatch_function(op)?;
                }
                OpCode::Return => {
                    let result = self.pop()?;
                    let frame = self.frames.pop().ok_or(VMError::Internal(
                        "return with empty call stack".to_string(),
                    ))?;
                    if self.frames.len() <= stop_depth {
                        return Ok(result);
                    }
                    self.stack.truncate(frame.stack_base);
                    self.push(result);
                }
                // Thunks
                OpCode::MakeThunk | OpCode::MakeLazyThunk | OpCode::Force |
                OpCode::PatchThunkUpvalues => {
                    self.dispatch_thunk(op)?;
                }
                // Scope
                OpCode::PushWith | OpCode::PopWith | OpCode::LookupWith |
                OpCode::PushBuiltins => {
                    self.dispatch_scope(op)?;
                }
                // Import + CallBuiltin
                OpCode::Import | OpCode::CallBuiltin => {
                    self.dispatch_import(op)?;
                }
                // Super-instructions
                OpCode::GetLocalAttr | OpCode::GetLocalCall => {
                    self.dispatch_super(op)?;
                }
                // Stack / String
                OpCode::Pop | OpCode::Dup | OpCode::Interpolate => {
                    self.dispatch_stack(op)?;
                }
            }
        }
    }
    // ── Dispatch handler groups ──────────────────────────────────
    fn dispatch_constant(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Constant => {
                let idx = self.read_u16()?;
                let value = &self.current_chunk().constants[idx as usize];
                let boxed = NanBox::from_vmvalue(value);
                self.push(boxed);
            }
            OpCode::Null => self.push(NanBox::null()),
            OpCode::True => self.push(NanBox::bool(true)),
            OpCode::False => self.push(NanBox::bool(false)),
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_arithmetic(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Add => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(self.add(&a, &b)?);
            }
            OpCode::Sub => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(self.num_op(&a, &b, |x, y| x - y, |x, y| x - y, "subtraction")?);
            }
            OpCode::Mul => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(self.num_op(&a, &b, |x, y| x * y, |x, y| x * y, "multiplication")?);
            }
            OpCode::Div => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                if a.is_int() && b.as_int() == Some(0) {
                    return Err(VMError::DivisionByZero);
                }
                self.push(self.num_op(&a, &b, |x, y| x / y, |x, y| x / y, "division")?);
            }
            OpCode::Negate => {
                let val = self.pop_forced()?;
                if let Some(n) = val.as_int() {
                    self.push(NanBox::int(-n));
                } else if let Some(f) = val.as_float() {
                    self.push(NanBox::float(-f));
                } else {
                    return Err(VMError::TypeError {
                        expected: "int or float",
                        got: val.type_name(),
                        context: "negation".to_string(),
                    });
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_logic(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Not => {
                let val = self.pop_forced()?;
                let b = val.is_truthy()?;
                self.push(NanBox::bool(!b));
            }
            OpCode::And => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(a.is_truthy()? && b.is_truthy()?));
            }
            OpCode::Or => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(a.is_truthy()? || b.is_truthy()?));
            }
            OpCode::Implication => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(!a.is_truthy()? || b.is_truthy()?));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_comparison(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Equal => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                let eq = self.deep_eq(&a, &b)?;
                self.push(NanBox::bool(eq));
            }
            OpCode::NotEqual => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                let eq = self.deep_eq(&a, &b)?;
                self.push(NanBox::bool(!eq));
            }
            OpCode::Less => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(self.compare(&a, &b)? == std::cmp::Ordering::Less));
            }
            OpCode::Greater => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(self.compare(&a, &b)? == std::cmp::Ordering::Greater));
            }
            OpCode::LessEqual => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(self.compare(&a, &b)? != std::cmp::Ordering::Greater));
            }
            OpCode::GreaterEqual => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                self.push(NanBox::bool(self.compare(&a, &b)? != std::cmp::Ordering::Less));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_variable(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::GetLocal => {
                let slot = self.read_u16()? as usize;
                let abs_slot = self.current_frame().stack_base + slot;
                if abs_slot >= self.stack.len() {
                    let frame = self.current_frame();
                    let chunk = &frame.chunk;
                    let failing_ip = frame.ip.saturating_sub(3);
                    let frame_info: Vec<String> = self.frames.iter().enumerate()
                        .map(|(i, f)| format!("frame[{i}]: base={}, ip={}", f.stack_base, f.ip))
                        .collect();
                    let bytecode_context = Self::disassemble_around(chunk, failing_ip, 10);
                    return Err(VMError::Internal(format!(
                        "GetLocal: slot {slot} (abs {abs_slot}) out of bounds \
                         (stack len {}, base {}, depth {})\n  \
                         {}\n  bytecode around ip={failing_ip}:\n{}",
                        self.stack.len(),
                        self.current_frame().stack_base,
                        self.frames.len(),
                        frame_info.join("\n  "),
                        bytecode_context,
                    )));
                }
                let value = self.stack[abs_slot].clone();
                self.push(value);
            }
            OpCode::SetLocal => {
                let slot = self.read_u16()? as usize;
                let abs_slot = self.current_frame().stack_base + slot;
                if abs_slot >= self.stack.len() {
                    return Err(VMError::Internal(format!(
                        "SetLocal: slot {slot} (abs {abs_slot}) out of bounds \
                         (stack len {}, base {})",
                        self.stack.len(),
                        self.current_frame().stack_base,
                    )));
                }
                let value = self.peek()?.clone();
                self.stack[abs_slot] = value;
            }
            OpCode::GetUpvalue => {
                let idx = self.read_u16()? as usize;
                let upvalues = &self.current_frame().upvalues;
                if idx >= upvalues.len() {
                    // Upvalue index out of bounds — compiler bug or missing
                    // upvalue patching. Push null as fallback to avoid panic.
                    eprintln!(
                        "[sui-vm] GetUpvalue: index {} out of bounds (len {})",
                        idx, upvalues.len()
                    );
                    self.push(NanBox::null());
                } else {
                    let value = upvalues[idx].clone();
                    self.push(value);
                }
            }
            OpCode::SetUpvalue => {
                let idx = self.read_u16()? as usize;
                let value = self.peek()?.clone();
                self.current_frame_mut().upvalues[idx] = value;
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_scope(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::PushWith => {
                let scope = self.pop_forced()?;
                self.with_stack.push(scope);
            }
            OpCode::PopWith => {
                self.with_stack.pop().ok_or_else(|| {
                    VMError::Internal("PopWith: empty with-stack".to_string())
                })?;
            }
            OpCode::LookupWith => {
                let name_idx = self.read_u16()?;
                let name_string = match &self.current_chunk().constants[name_idx as usize] {
                    VMValue::String(s) => s.clone(),
                    _ => {
                        return Err(VMError::Internal(
                            "LookupWith: constant not a string".to_string(),
                        ));
                    }
                };
                let sym = self.interner.intern(&name_string);
                let mut found = None;
                for scope in self.with_stack.iter().rev() {
                    if let Some(attrs) = scope.as_attrs() {
                        if let Some(val) = attrs.get(&sym) {
                            found = Some(val.clone());
                            break;
                        }
                    }
                }
                match found {
                    Some(val) => self.push(val),
                    None => {
                        return Err(VMError::UndefinedVariable(name_string));
                    }
                }
            }
            OpCode::PushBuiltins => {
                let builtins_val = self.builtins.make_builtins_attrset(self.interner);
                self.push(NanBox::from_vmvalue(&builtins_val));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_attrset(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::MakeAttrs => {
                let count = self.read_u16()? as usize;
                let mut attrs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
                for _ in 0..count {
                    let key = self.pop()?;
                    let value = self.pop()?;
                    let key_sym = if let Some(s) = key.as_string() {
                        self.interner.intern(s)
                    } else {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: key.type_name(),
                            context: "attrset key".to_string(),
                        });
                    };
                    attrs.insert(key_sym, value);
                }
                self.push(NanBox::attrs(attrs));
            }
            OpCode::GetAttr => {
                let key_idx = self.read_u16()?;
                let key_sym = self.resolve_key_constant(key_idx)?;
                let attrset = self.pop_forced()?;
                if let Some(attrs) = attrset.as_attrs() {
                    if let Some(val) = attrs.get(&key_sym) {
                        let forced = if val.is_thunk() {
                            self.force_value(val.clone())?
                        } else {
                            val.clone()
                        };
                        self.push(forced);
                    } else {
                        let key_str = self.interner.resolve(key_sym).to_string();
                        return Err(VMError::AttrNotFound(key_str));
                    }
                } else {
                    let key_str = self.interner.resolve(key_sym).to_string();
                    return Err(VMError::TypeError {
                        expected: "set",
                        got: attrset.type_name(),
                        context: format!("attribute selection '.{key_str}'"),
                    });
                }
            }
            OpCode::HasAttr => {
                let key_idx = self.read_u16()?;
                let key_sym = self.resolve_key_constant(key_idx)?;
                let attrset = self.pop_forced()?;
                let result = if let Some(attrs) = attrset.as_attrs() {
                    attrs.contains_key(&key_sym)
                } else {
                    false
                };
                self.push(NanBox::bool(result));
            }
            OpCode::UpdateAttrs => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                let b_vmval = b.to_vmvalue();
                let a_vmval = a.to_vmvalue();
                match (a_vmval, b_vmval) {
                    (VMValue::Attrs(mut left), VMValue::Attrs(right)) => {
                        for (k, v) in right {
                            left.insert(k, v);
                        }
                        self.push(NanBox::from_vmvalue(&VMValue::Attrs(left)));
                    }
                    (VMValue::Attrs(_), other) => {
                        return Err(VMError::TypeError {
                            expected: "set",
                            got: other.type_name(),
                            context: "// (right)".to_string(),
                        });
                    }
                    (other, _) => {
                        return Err(VMError::TypeError {
                            expected: "set",
                            got: other.type_name(),
                            context: "// (left)".to_string(),
                        });
                    }
                }
            }
            OpCode::SelectOrDefault => {
                let key_idx = self.read_u16()?;
                let key_sym = self.resolve_key_constant(key_idx)?;
                let default = self.pop()?;
                let attrset = self.pop_forced()?;
                if let Some(attrs) = attrset.as_attrs() {
                    if let Some(val) = attrs.get(&key_sym) {
                        let forced = if val.is_thunk() {
                            self.force_value(val.clone())?
                        } else {
                            val.clone()
                        };
                        self.push(forced);
                    } else {
                        self.push(default);
                    }
                } else {
                    self.push(default);
                }
            }
            OpCode::DynGetAttr => {
                let key_val = self.pop_forced()?;
                let attrset = self.pop_forced()?;
                let key_str = key_val
                    .as_string()
                    .ok_or_else(|| VMError::TypeError {
                        expected: "string",
                        got: key_val.type_name(),
                        context: "dynamic attribute key".to_string(),
                    })?
                    .to_string();
                let key_sym = self.interner.intern(&key_str);
                if let Some(attrs) = attrset.as_attrs() {
                    if let Some(val) = attrs.get(&key_sym) {
                        let forced = if val.is_thunk() {
                            self.force_value(val.clone())?
                        } else {
                            val.clone()
                        };
                        self.push(forced);
                    } else {
                        return Err(VMError::AttrNotFound(key_str));
                    }
                } else {
                    return Err(VMError::TypeError {
                        expected: "set",
                        got: attrset.type_name(),
                        context: format!("dynamic select .${{{key_str}}}"),
                    });
                }
            }
            OpCode::DynHasAttr => {
                let key_val = self.pop_forced()?;
                let attrset = self.pop_forced()?;
                let key_str = key_val
                    .as_string()
                    .ok_or_else(|| VMError::TypeError {
                        expected: "string",
                        got: key_val.type_name(),
                        context: "dynamic hasattr key".to_string(),
                    })?
                    .to_string();
                let key_sym = self.interner.intern(&key_str);
                let result = attrset.as_attrs().map_or(false, |attrs| attrs.contains_key(&key_sym));
                self.push(NanBox::bool(result));
            }
            OpCode::DynSelectOrDefault => {
                let default = self.pop()?;
                let key_val = self.pop_forced()?;
                let attrset = self.pop_forced()?;
                let key_str = key_val
                    .as_string()
                    .ok_or_else(|| VMError::TypeError {
                        expected: "string",
                        got: key_val.type_name(),
                        context: "dynamic select-or-default key".to_string(),
                    })?
                    .to_string();
                let key_sym = self.interner.intern(&key_str);
                if let Some(attrs) = attrset.as_attrs() {
                    if let Some(val) = attrs.get(&key_sym) {
                        let forced = if val.is_thunk() {
                            self.force_value(val.clone())?
                        } else {
                            val.clone()
                        };
                        self.push(forced);
                    } else {
                        self.push(default);
                    }
                } else {
                    self.push(default);
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_list(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::MakeList => {
                let count = self.read_u16()? as usize;
                let start = self.stack.len() - count;
                let items: Vec<NanBox> = self.stack.drain(start..).collect();
                self.push(NanBox::list(items));
            }
            OpCode::Concat => {
                let b = self.pop_forced()?;
                let a = self.pop_forced()?;
                let a_vmval = a.to_vmvalue();
                let b_vmval = b.to_vmvalue();
                match (a_vmval, b_vmval) {
                    (VMValue::List(mut left), VMValue::List(right)) => {
                        left.extend(right);
                        self.push(NanBox::from_vmvalue(&VMValue::List(left)));
                    }
                    (VMValue::List(_), other) => {
                        return Err(VMError::TypeError {
                            expected: "list",
                            got: other.type_name(),
                            context: "++ (right)".to_string(),
                        });
                    }
                    (other, _) => {
                        return Err(VMError::TypeError {
                            expected: "list",
                            got: other.type_name(),
                            context: "++ (left)".to_string(),
                        });
                    }
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_control(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Jump => {
                let target = self.read_u16()? as usize;
                self.current_frame_mut().ip = target;
            }
            OpCode::JumpIfFalse => {
                let target = self.read_u16()? as usize;
                let cond = self.pop_forced()?;
                match cond.is_truthy() {
                    Ok(false) => { self.current_frame_mut().ip = target; }
                    Ok(true) => {}
                    Err(e) => {
                        // Diagnostic for debugging (remove once fixed)
                        if std::env::var("SUI_VM_TRACE").is_ok() {
                            let keys_preview = if let Some(attrs) = cond.as_attrs() {
                                let keys: Vec<_> = attrs.keys().take(5)
                                    .map(|k| self.interner.resolve(*k).to_string())
                                    .collect();
                                format!("{{{}}}", keys.join(", "))
                            } else {
                                cond.type_name().to_string()
                            };
                            eprintln!(
                                "[sui-vm] condition type error: got {} ({}) at depth {}, chunk: {}",
                                cond.type_name(), keys_preview,
                                self.frames.len(), self.current_chunk_name(),
                            );
                        }
                        return Err(e);
                    }
                }
            }
            OpCode::JumpIfTrue => {
                let target = self.read_u16()? as usize;
                let cond = self.pop_forced()?;
                match cond.is_truthy() {
                    Ok(true) => { self.current_frame_mut().ip = target; }
                    Ok(false) => {}
                    Err(e) => {
                        // Diagnostic for debugging (remove once fixed)
                        if std::env::var("SUI_VM_TRACE").is_ok() {
                            let keys_preview = if let Some(attrs) = cond.as_attrs() {
                                let keys: Vec<_> = attrs.keys().take(5)
                                    .map(|k| self.interner.resolve(*k).to_string())
                                    .collect();
                                format!("{{{}}}", keys.join(", "))
                            } else {
                                cond.type_name().to_string()
                            };
                            eprintln!(
                                "[sui-vm] condition type error: got {} ({}) at depth {}, chunk: {}",
                                cond.type_name(), keys_preview,
                                self.frames.len(), self.current_chunk_name(),
                            );
                        }
                        return Err(e);
                    }
                }
            }
            OpCode::Assert => {
                let cond = self.pop_forced()?;
                if !cond.is_truthy()? {
                    return Err(VMError::AssertionFailed);
                }
            }
            OpCode::Throw => {
                let msg = self.pop_forced()?;
                let msg_str = match msg.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => format!("{other:?}"),
                };
                return Err(VMError::Throw(msg_str));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_function(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::MakeClosure => {
                let idx = self.read_u16()?;
                let upvalue_count = self.read_u16()? as usize;
                let closure_template = self.current_chunk().constants[idx as usize].clone();
                if let VMValue::Closure(mut closure) = closure_template {
                    let mut upvalues = Vec::with_capacity(upvalue_count);
                    for _ in 0..upvalue_count {
                        let is_local = self.read_byte()? != 0;
                        let uv_index = self.read_u16()? as usize;
                        if is_local {
                            let abs_slot = self.current_frame().stack_base + uv_index;
                            upvalues.push(self.stack[abs_slot].clone());
                        } else {
                            let val = self.current_frame().upvalues[uv_index].clone();
                            upvalues.push(val);
                        }
                    }
                    closure.upvalues = upvalues;
                    self.push(NanBox::closure(closure));
                } else {
                    return Err(VMError::Internal(
                        "MakeClosure: constant is not a closure".to_string(),
                    ));
                }
            }
            OpCode::Call => {
                let arg = self.pop()?;
                let func = self.pop_forced()?;
                if let Some(closure) = func.as_closure() {
                    let is_tail = self.peek_next_is_return();
                    let chunk = closure.chunk.clone();
                    let upvalues = closure.upvalues.clone();
                    if is_tail && self.frames.len() > 1 {
                        let base = self.current_frame().stack_base;
                        self.stack.truncate(base);
                        self.push(arg);
                        let frame = self.current_frame_mut();
                        frame.chunk = chunk;
                        frame.ip = 0;
                        frame.upvalues = upvalues;
                    } else {
                        if self.frames.len() >= MAX_CALL_DEPTH {
                            return Err(VMError::StackOverflow);
                        }
                        let stack_base = self.stack.len();
                        self.push(arg);
                        self.frames.push(CallFrame {
                            chunk,
                            ip: 0,
                            stack_base,
                            upvalues,
                        });
                    }
                } else if func.is_higher_order_builtin() {
                    let hob = func.as_higher_order_builtin().unwrap().clone();
                    let forced_arg = self.force_value(arg)?;
                    let result = self.call_higher_order_builtin(&hob, forced_arg)?;
                    self.push(result);
                } else if let Some(builtin) = func.as_builtin() {
                    // tryEval MUST receive unforced arg to catch errors during forcing
                    if builtin.name == "tryEval" {
                        if let Some(result) = self.try_vm_builtin("tryEval", &arg)? {
                            self.push(result);
                        }
                    } else {
                        let forced_arg = self.force_value(arg)?;
                        if let Some(result) = self.try_vm_builtin(builtin.name, &forced_arg)? {
                            self.push(result);
                        } else {
                            let mut arg_vmval = forced_arg.to_vmvalue();
                            arg_vmval = self.shallow_force_list(arg_vmval)?;
                            let builtin_func = builtin.func.clone();
                            let result = self.call_builtin_with_scoped_import_dispatch(
                                builtin_func, arg_vmval,
                            )?;
                            self.push(result);
                        }
                    }
                } else {
                    return Err(VMError::NotCallable(func.type_name().to_string()));
                }
            }
            OpCode::TailCall => {
                // Compiler-determined tail call: always reuse the current frame
                // for closures (no runtime peek needed). For builtins, fall back
                // to a regular call since they don't use bytecode frames.
                let arg = self.pop()?;
                let func = self.pop_forced()?;
                if let Some(closure) = func.as_closure() {
                    let chunk = closure.chunk.clone();
                    let upvalues = closure.upvalues.clone();
                    if self.frames.len() > 1 {
                        // Tail-call optimization: reuse current frame.
                        let base = self.current_frame().stack_base;
                        self.stack.truncate(base);
                        self.push(arg);
                        let frame = self.current_frame_mut();
                        frame.chunk = chunk;
                        frame.ip = 0;
                        frame.upvalues = upvalues;
                    } else {
                        // Top-level frame: cannot reuse, push new frame.
                        if self.frames.len() >= MAX_CALL_DEPTH {
                            return Err(VMError::StackOverflow);
                        }
                        let stack_base = self.stack.len();
                        self.push(arg);
                        self.frames.push(CallFrame {
                            chunk,
                            ip: 0,
                            stack_base,
                            upvalues,
                        });
                    }
                } else if func.is_higher_order_builtin() {
                    let hob = func.as_higher_order_builtin().unwrap().clone();
                    let forced_arg = self.force_value(arg)?;
                    let result = self.call_higher_order_builtin(&hob, forced_arg)?;
                    self.push(result);
                } else if let Some(builtin) = func.as_builtin() {
                    if builtin.name == "tryEval" {
                        if let Some(result) = self.try_vm_builtin("tryEval", &arg)? {
                            self.push(result);
                        }
                    } else {
                        let forced_arg = self.force_value(arg)?;
                        if let Some(result) = self.try_vm_builtin(builtin.name, &forced_arg)? {
                            self.push(result);
                        } else {
                            let mut arg_vmval = forced_arg.to_vmvalue();
                            arg_vmval = self.shallow_force_list(arg_vmval)?;
                            let builtin_func = builtin.func.clone();
                            let result = self.call_builtin_with_scoped_import_dispatch(
                                builtin_func, arg_vmval,
                            )?;
                            self.push(result);
                        }
                    }
                } else {
                    return Err(VMError::NotCallable(func.type_name().to_string()));
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_thunk(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::MakeThunk => {
                let chunk_idx = self.read_u16()?;
                let upvalue_count = self.read_u16()? as usize;
                let thunk_chunk =
                    match &self.current_chunk().constants[chunk_idx as usize] {
                        VMValue::Closure(c) => c.chunk.clone(),
                        _ => {
                            return Err(VMError::Internal(
                                "MakeThunk: constant is not a closure".to_string(),
                            ))
                        }
                    };
                let mut upvalues = Vec::with_capacity(upvalue_count);
                for _ in 0..upvalue_count {
                    let is_local = self.read_byte()? != 0;
                    let uv_index = self.read_u16()? as usize;
                    if is_local {
                        let abs_slot = self.current_frame().stack_base + uv_index;
                        upvalues.push(self.stack[abs_slot].clone());
                    } else {
                        let val = self.current_frame().upvalues[uv_index].clone();
                        upvalues.push(val);
                    }
                }
                let thunk = crate::value::VMThunk::new(thunk_chunk, upvalues);
                self.push(NanBox::thunk(thunk));
            }
            OpCode::Force => {
                let val = self.pop()?;
                let forced = self.force_value(val)?;
                self.push(forced);
            }
            OpCode::PatchThunkUpvalues => {
                let patch_slot = self.read_u16()? as usize;
                let patch_uv_count = self.read_u16()? as usize;
                let patch_abs = self.current_frame().stack_base + patch_slot;
                let mut patch_uvs: Vec<NanBox> = Vec::with_capacity(patch_uv_count);
                for _ in 0..patch_uv_count {
                    let il = self.read_byte()? != 0;
                    let ui = self.read_u16()? as usize;
                    if il {
                        let a = self.current_frame().stack_base + ui;
                        if a >= self.stack.len() {
                            // Slot not yet allocated — skip this upvalue patch.
                            patch_uvs.push(NanBox::null());
                            continue;
                        }
                        patch_uvs.push(self.stack[a].clone());
                    } else {
                        if ui >= self.current_frame().upvalues.len() {
                            patch_uvs.push(NanBox::null());
                            continue;
                        }
                        patch_uvs.push(self.current_frame().upvalues[ui].clone());
                    }
                }
                if patch_abs < self.stack.len() {
                    let patch_nb = self.stack[patch_abs].clone();
                    let patch_vm = patch_nb.to_vmvalue();
                    if let VMValue::Thunk(ref t) = patch_vm {
                        let s = t.state.take();
                        if let Some(ThunkState::Pending { chunk: c, .. }) = s {
                            t.state.set(Some(ThunkState::Pending { chunk: c, upvalues: patch_uvs }));
                        } else {
                            t.state.set(s);
                        }
                    }
                }
            }
            OpCode::MakeLazyThunk => {
                let src_idx = self.read_u16()? as usize;
                let offset = self.read_u32()? as usize;
                let length = self.read_u32()? as usize;
                let dir_idx = self.read_u16()? as usize;
                let upvalue_count = self.read_u16()? as usize;
                let source_text = match &self.current_chunk().constants[src_idx] {
                    VMValue::String(s) => Rc::new(s.clone()),
                    _ => return Err(VMError::Internal(
                        "MakeLazyThunk: source constant not a string".to_string(),
                    )),
                };
                let base_dir_str = match &self.current_chunk().constants[dir_idx] {
                    VMValue::String(s) => s.clone(),
                    _ => return Err(VMError::Internal(
                        "MakeLazyThunk: base_dir constant not a string".to_string(),
                    )),
                };
                let base_dir = PathBuf::from(base_dir_str);
                let mut upvalues = Vec::with_capacity(upvalue_count);
                for _ in 0..upvalue_count {
                    let is_local = self.read_byte()? != 0;
                    let uv_index = self.read_u16()? as usize;
                    if is_local {
                        let abs_slot = self.current_frame().stack_base + uv_index;
                        upvalues.push(self.stack[abs_slot].clone());
                    } else {
                        let val = self.current_frame().upvalues[uv_index].clone();
                        upvalues.push(val);
                    }
                }
                let thunk = crate::value::VMThunk {
                    state: Rc::new(std::cell::Cell::new(Some(ThunkState::LazySource {
                        source: source_text,
                        offset,
                        length,
                        base_dir,
                        upvalues,
                    }))),
                };
                self.push(NanBox::thunk(thunk));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_import(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Import => {
                let path_val = self.pop()?;
                let path_val = self.force_value(path_val)?; // Force thunks before type check
                let path = if let Some(p) = path_val.as_path() {
                    p.to_string()
                } else if let Some(s) = path_val.as_string() {
                    s.to_string()
                } else {
                    return Err(VMError::TypeError {
                        expected: "path or string",
                        got: path_val.type_name(),
                        context: "import".to_string(),
                    });
                };
                let result = self.import_file(&path)?;
                self.push(result);
            }
            OpCode::CallBuiltin => {
                let builtin_idx = self.read_u16()?;
                let arg_count = self.read_u16()? as usize;
                let start = self.stack.len() - arg_count;
                let raw_args: Vec<NanBox> = self.stack.drain(start..).collect();
                let mut args = Vec::with_capacity(raw_args.len());
                for raw in raw_args {
                    let forced = self.force_value(raw)?;
                    let mut vm_val = forced.to_vmvalue();
                    vm_val = self.shallow_force_list(vm_val)?;
                    args.push(vm_val);
                }
                let result = self.builtins.call(builtin_idx, args)?;
                self.push(NanBox::from_vmvalue(&result));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_super(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::GetLocalAttr => {
                let slot = self.read_u16()? as usize;
                let key_idx = self.read_u16()?;
                let key_sym = self.resolve_key_constant(key_idx)?;
                let abs_slot = self.current_frame().stack_base + slot;
                let local = self.stack[abs_slot].clone();
                let local = self.force_value(local)?;
                if let Some(attrs) = local.as_attrs() {
                    if let Some(val) = attrs.get(&key_sym) {
                        let forced = if val.is_thunk() {
                            self.force_value(val.clone())?
                        } else {
                            val.clone()
                        };
                        self.push(forced);
                    } else {
                        let key_str = self.interner.resolve(key_sym).to_string();
                        return Err(VMError::AttrNotFound(key_str));
                    }
                } else {
                    let key_str = self.interner.resolve(key_sym).to_string();
                    return Err(VMError::TypeError {
                        expected: "set",
                        got: local.type_name(),
                        context: format!("attribute selection '.{key_str}'"),
                    });
                }
            }
            OpCode::GetLocalCall => {
                let slot = self.read_u16()? as usize;
                let abs_slot = self.current_frame().stack_base + slot;
                let func = self.stack[abs_slot].clone();
                let func = self.force_value(func)?;
                let arg = self.pop()?;
                if let Some(closure) = func.as_closure() {
                    if self.frames.len() >= MAX_CALL_DEPTH {
                        return Err(VMError::StackOverflow);
                    }
                    let upvalues = closure.upvalues.clone();
                    let chunk = closure.chunk.clone();
                    let stack_base = self.stack.len();
                    self.push(arg);
                    self.frames.push(CallFrame {
                        chunk,
                        ip: 0,
                        stack_base,
                        upvalues,
                    });
                } else if func.is_higher_order_builtin() {
                    let hob = func.as_higher_order_builtin().unwrap().clone();
                    // Force the arg before passing to HOBs — matches
                    // the regular OpCode::Call handler's behavior.
                    let forced_arg = self.force_value(arg)?;
                    let result = self.call_higher_order_builtin(&hob, forced_arg)?;
                    self.push(result);
                } else if let Some(builtin) = func.as_builtin() {
                    // Force the arg before passing to builtins — matches
                    // the regular OpCode::Call handler's behavior.
                    let forced_arg = self.force_value(arg)?;
                    if let Some(result) = self.try_vm_builtin(builtin.name, &forced_arg)? {
                        self.push(result);
                    } else {
                        // Shallow-force container elements one level.
                        // Can't deep_force here — nixpkgs has massive nested
                        // structures that cause stack overflow. The force-aware
                        // helpers (as_list, force_as_string) handle remaining
                        // thunks on demand in builtin closures.
                        let mut arg_vmval = forced_arg.to_vmvalue();
                        // Force list elements only (not attrsets — too expensive).
                        arg_vmval = self.shallow_force_list(arg_vmval)?;
                        let builtin_func = builtin.func.clone();
                        let result = self.call_builtin_with_scoped_import_dispatch(
                            builtin_func, arg_vmval,
                        )?;
                        self.push(result);
                    }
                } else {
                    return Err(VMError::NotCallable(func.type_name().to_string()));
                }
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    fn dispatch_stack(&mut self, op: OpCode) -> Result<(), VMError> {
        match op {
            OpCode::Pop => {
                self.pop()?;
            }
            OpCode::Dup => {
                let top = self.stack.last().ok_or(VMError::StackUnderflow)?.clone();
                self.push(top);
            }
            OpCode::Interpolate => {
                let count = self.read_u16()? as usize;
                let start = self.stack.len() - count;
                // Drain interpolation parts off the stack, force thunks.
                let mut parts: Vec<NanBox> = self.stack.drain(start..).collect();
                for part in &mut parts {
                    if part.is_thunk() {
                        *part = self.force_value(part.clone())?;
                    }
                }
                let mut result = String::new();
                for v in &parts {
                    if let Some(s) = v.as_string() {
                        result.push_str(s);
                    } else if let Some(n) = v.as_int() {
                        result.push_str(&n.to_string());
                    } else if let Some(f) = v.as_float() {
                        result.push_str(&format!("{f}"));
                    } else if let Some(p) = v.as_path() {
                        result.push_str(p);
                    } else if let Some(attrs) = v.as_attrs() {
                        // Attrset interpolation: check __toString then outPath.
                        let to_str_sym = sui_intern::intern("__toString");
                        if let Some(to_str_fn) = attrs.get(&to_str_sym) {
                            let func_nb = self.force_value(to_str_fn.clone())?;
                            let call_result = self.call_callable(&func_nb, v.clone())?;
                            let forced = self.force_value(call_result)?;
                            if let Some(s) = forced.as_string() {
                                result.push_str(s);
                            } else {
                                return Err(VMError::TypeError {
                                    expected: "string",
                                    got: forced.type_name(),
                                    context: "__toString result in string interpolation".to_string(),
                                });
                            }
                        } else {
                            let out_path_sym = sui_intern::intern("outPath");
                            if let Some(out_path) = attrs.get(&out_path_sym) {
                                let forced = self.force_value(out_path.clone())?;
                                if let Some(s) = forced.as_string() {
                                    result.push_str(s);
                                } else if let Some(p) = forced.as_path() {
                                    result.push_str(p);
                                } else {
                                    return Err(VMError::TypeError {
                                        expected: "string or path",
                                        got: forced.type_name(),
                                        context: "outPath in string interpolation".to_string(),
                                    });
                                }
                            } else {
                                return Err(VMError::TypeError {
                                    expected: "string, int, float, or path",
                                    got: "set (no __toString or outPath)",
                                    context: "string interpolation".to_string(),
                                });
                            }
                        }
                    } else if v.is_bool() {
                        let b = v.as_bool().unwrap();
                        return Err(VMError::TypeError {
                            expected: "string, int, float, or path",
                            got: if b { "bool (true)" } else { "bool (false)" },
                            context: "string interpolation".to_string(),
                        });
                    } else {
                        return Err(VMError::TypeError {
                            expected: "string, int, float, or path",
                            got: v.type_name(),
                            context: "string interpolation".to_string(),
                        });
                    }
                }
                // Stack was drained above; push the result.
                self.push(NanBox::string(result));
            }
            _ => unreachable!(),
        }
        Ok(())
    }
    // -- Deep equality (forces thunks during comparison) ----------------
    /// Deep equality comparison that forces thunks in both operands.
    ///
    /// Nix `==` semantics require that values are forced before comparison.
    /// This includes values nested inside attrsets and lists. Without this,
    /// attrsets whose values are still thunked would compare as unequal
    /// even if their forced values are identical.
    fn deep_eq(&mut self, a: &NanBox, b: &NanBox) -> Result<bool, VMError> {
        // Force both values if they are thunks.
        let a = if a.is_thunk() { self.force_value(a.clone())? } else { a.clone() };
        let b = if b.is_thunk() { self.force_value(b.clone())? } else { b.clone() };
        // Scalars and strings: use NanBox::PartialEq (no thunks possible inside).
        if a.is_null() || a.is_bool() || a.is_int() || a.is_float() {
            return Ok(a == b);
        }
        if a.is_string() || a.is_path() {
            return Ok(a == b);
        }
        // List comparison: force each element pair.
        if let (Some(a_items), Some(b_items)) = (a.as_list(), b.as_list()) {
            if a_items.len() != b_items.len() {
                return Ok(false);
            }
            for (ai, bi) in a_items.iter().zip(b_items.iter()) {
                if !self.deep_eq(ai, bi)? {
                    return Ok(false);
                }
            }
            return Ok(true);
        }
        // Attrs comparison: force each value pair.
        if let (Some(a_attrs), Some(b_attrs)) = (a.as_attrs(), b.as_attrs()) {
            if a_attrs.len() != b_attrs.len() {
                return Ok(false);
            }
            // Check that keys match and values are deeply equal.
            let a_entries: Vec<_> = a_attrs.iter().collect();
            let b_entries: Vec<_> = b_attrs.iter().collect();
            for ((ak, av), (bk, bv)) in a_entries.iter().zip(b_entries.iter()) {
                if ak != bk {
                    return Ok(false);
                }
                if !self.deep_eq(av, bv)? {
                    return Ok(false);
                }
            }
            return Ok(true);
        }
        // Functions are never equal.
        if a.is_closure() || a.is_builtin() || a.is_higher_order_builtin() {
            return Ok(false);
        }
        // Fallback: use NanBox::PartialEq.
        Ok(a == b)
    }
    // -- Stack helpers --------------------------------------------------
    fn push(&mut self, value: NanBox) {
        self.stack.push(value);
    }
    fn pop(&mut self) -> Result<NanBox, VMError> {
        self.stack.pop().ok_or(VMError::StackUnderflow)
    }
    /// Pop a value from the stack, forcing it if it is a thunk.
    /// Use this when the operation needs a concrete (non-thunk) value.
    fn pop_forced(&mut self) -> Result<NanBox, VMError> {
        let val = self.pop()?;
        self.force_value(val)
    }
    fn peek(&self) -> Result<&NanBox, VMError> {
        self.stack.last().ok_or(VMError::StackUnderflow)
    }
    // -- Frame helpers --------------------------------------------------
    fn current_frame(&self) -> &CallFrame {
        self.frames.last().expect("no active frame")
    }
    fn current_frame_mut(&mut self) -> &mut CallFrame {
        self.frames.last_mut().expect("no active frame")
    }
    fn current_chunk(&self) -> &Chunk {
        &self.current_frame().chunk
    }
    fn current_chunk_name(&self) -> String {
        self.current_chunk()
            .source_file
            .clone()
            .unwrap_or_else(|| "<inline>".to_string())
    }
    fn read_byte(&mut self) -> Result<u8, VMError> {
        let frame = self.current_frame();
        if frame.ip >= frame.chunk.code.len() {
            return Err(VMError::Internal("unexpected end of bytecode".to_string()));
        }
        let byte = frame.chunk.code[frame.ip];
        self.current_frame_mut().ip += 1;
        Ok(byte)
    }
    fn read_u16(&mut self) -> Result<u16, VMError> {
        let lo = self.read_byte()?;
        let hi = self.read_byte()?;
        Ok(u16::from_le_bytes([lo, hi]))
    }
    fn read_u32(&mut self) -> Result<u32, VMError> {
        let b0 = self.read_byte()?;
        let b1 = self.read_byte()?;
        let b2 = self.read_byte()?;
        let b3 = self.read_byte()?;
        Ok(u32::from_le_bytes([b0, b1, b2, b3]))
    }
    /// Peek ahead: check if the next instruction in the current frame
    /// is a `Return` opcode (used for tail-call optimization).
    fn peek_next_is_return(&self) -> bool {
        let frame = self.current_frame();
        if frame.ip < frame.chunk.code.len() {
            frame.chunk.code[frame.ip] == OpCode::Return as u8
        } else {
            false
        }
    }
    // -- Interning helpers ----------------------------------------------
    /// Resolve a constant pool string to a `Symbol`.
    fn resolve_key_constant(&mut self, idx: u16) -> Result<Symbol, VMError> {
        let idx_usize = idx as usize;
        let chunk = self.current_frame().chunk.clone();
        if let Some(Some(sym)) = chunk.key_symbols.get(idx_usize) {
            return Ok(*sym);
        }
        let key_string = match &chunk.constants[idx_usize] {
            VMValue::String(s) => s.clone(),
            _ => return Err(VMError::Internal("attr key constant not a string".to_string())),
        };
        Ok(self.interner.intern(&key_string))
    }
    // -- Arithmetic helpers (NanBox) ------------------------------------
    fn add(&self, a: &NanBox, b: &NanBox) -> Result<NanBox, VMError> {
        // Fast paths for inline scalars.
        if let (Some(x), Some(y)) = (a.as_int(), b.as_int()) {
            return Ok(NanBox::int(x + y));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_float()) {
            return Ok(NanBox::float(x + y));
        }
        if let (Some(x), Some(y)) = (a.as_int(), b.as_float()) {
            return Ok(NanBox::float(x as f64 + y));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_int()) {
            return Ok(NanBox::float(x + y as f64));
        }
        // String/path concat (heap path).
        if let (Some(x), Some(y)) = (a.as_string(), b.as_string()) {
            return Ok(NanBox::string(format!("{x}{y}")));
        }
        if let (Some(x), Some(y)) = (a.as_path(), b.as_string()) {
            return Ok(NanBox::path(format!("{x}{y}")));
        }
        if let (Some(x), Some(y)) = (a.as_path(), b.as_path()) {
            return Ok(NanBox::path(format!("{x}/{y}")));
        }
        Err(VMError::TypeError {
            expected: "numbers or strings",
            got: a.type_name(),
            context: format!("addition ({} + {})", a.type_name(), b.type_name()),
        })
    }
    fn num_op(
        &self,
        a: &NanBox,
        b: &NanBox,
        int_op: impl Fn(i64, i64) -> i64,
        float_op: impl Fn(f64, f64) -> f64,
        context: &str,
    ) -> Result<NanBox, VMError> {
        if let (Some(x), Some(y)) = (a.as_int(), b.as_int()) {
            return Ok(NanBox::int(int_op(x, y)));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_float()) {
            return Ok(NanBox::float(float_op(x, y)));
        }
        if let (Some(x), Some(y)) = (a.as_int(), b.as_float()) {
            return Ok(NanBox::float(float_op(x as f64, y)));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_int()) {
            return Ok(NanBox::float(float_op(x, y as f64)));
        }
        Err(VMError::TypeError {
            expected: "numbers",
            got: a.type_name(),
            context: context.to_string(),
        })
    }
    fn compare(&self, a: &NanBox, b: &NanBox) -> Result<std::cmp::Ordering, VMError> {
        if let (Some(x), Some(y)) = (a.as_int(), b.as_int()) {
            return Ok(x.cmp(&y));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_float()) {
            return Ok(x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal));
        }
        if let (Some(x), Some(y)) = (a.as_int(), b.as_float()) {
            return Ok((x as f64)
                .partial_cmp(&y)
                .unwrap_or(std::cmp::Ordering::Equal));
        }
        if let (Some(x), Some(y)) = (a.as_float(), b.as_int()) {
            return Ok(x
                .partial_cmp(&(y as f64))
                .unwrap_or(std::cmp::Ordering::Equal));
        }
        if let (Some(x), Some(y)) = (a.as_string(), b.as_string()) {
            return Ok(x.cmp(y));
        }
        Err(VMError::TypeError {
            expected: "comparable types",
            got: a.type_name(),
            context: "comparison".to_string(),
        })
    }
    // -- Thunk forcing --------------------------------------------------
    /// Force a value: if it is a thunk, evaluate it (with memoization
    /// and blackhole detection). If it is already a concrete value,
    /// return it unchanged.
    /// Recursively convert a `serde_json::Value` to a `VMValue`, using
    /// the live interner for object keys. Mirrors the shape used by
    /// `builtins.fromJSON`. Lives on the VM so it can intern keys.
    fn json_value_to_vm(&mut self, v: &serde_json::Value) -> VMValue {
        use std::collections::BTreeMap;
        match v {
            serde_json::Value::Null => VMValue::Null,
            serde_json::Value::Bool(b) => VMValue::Bool(*b),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    VMValue::Int(i)
                } else {
                    VMValue::Float(n.as_f64().unwrap_or(0.0))
                }
            }
            serde_json::Value::String(s) => VMValue::String(s.clone()),
            serde_json::Value::Array(arr) => {
                VMValue::List(arr.iter().map(|v| self.json_value_to_vm(v)).collect())
            }
            serde_json::Value::Object(map) => {
                let mut attrs: BTreeMap<Symbol, VMValue> = BTreeMap::new();
                for (k, val) in map {
                    let sym = self.interner.intern(k);
                    attrs.insert(sym, self.json_value_to_vm(val));
                }
                VMValue::Attrs(attrs)
            }
        }
    }

    /// Wrapper for callers that want a NanBox directly.
    fn json_value_to_nanbox(&mut self, v: &serde_json::Value) -> NanBox {
        NanBox::from_vmvalue(&self.json_value_to_vm(v))
    }

    fn force_value(&mut self, val: NanBox) -> Result<NanBox, VMError> {
        if !val.is_thunk() {
            return Ok(val);
        }
        // Convert to VMValue to access ThunkState machinery.
        let vmval = val.to_vmvalue();
        match vmval {
            VMValue::Thunk(ref thunk) => {
                let state = thunk.state.take();
                match state {
                    Some(ThunkState::Done(boxed)) => {
                        thunk.state.set(Some(ThunkState::Done(boxed.clone())));
                        Ok(NanBox::from_vmvalue(&*boxed))
                    }
                    Some(ThunkState::Evaluating) => {
                        // Re-entrant access to a thunk currently being evaluated.
                        // This is the fixpoint pattern (e.g., nixpkgs lib.fix).
                        //
                        // The VM can't store partial results mid-execution like
                        // the tree-walker. Return an empty attrset as a fixpoint
                        // placeholder. This allows the outer evaluation to proceed:
                        // - GetAttr on the placeholder → AttrNotFound (non-fatal
                        //   for optional/defaulted accesses)
                        // - The outer evaluation stores the REAL result as Done,
                        //   so subsequent accesses get the correct value.
                        //
                        // This matches how CppNix's fixpoint works: the first
                        // pass through f(x) constructs the attrset skeleton, and
                        // individual attribute accesses are lazy.
                        thunk.state.set(Some(ThunkState::Evaluating));
                        if std::env::var("SUI_VM_TRACE").is_ok() {
                            eprintln!(
                                "[sui-vm] fixpoint re-access at depth {}, returning placeholder",
                                self.frames.len(),
                            );
                        }
                        Ok(NanBox::attrs(BTreeMap::new()))
                    }
                    Some(ThunkState::Pending { chunk, upvalues }) => {
                        thunk.state.set(Some(ThunkState::Evaluating));
                        if self.frames.len() >= MAX_CALL_DEPTH {
                            thunk.state.set(Some(ThunkState::Pending {
                                chunk,
                                upvalues,
                            }));
                            return Err(VMError::StackOverflow);
                        }
                        let return_depth = self.frames.len();
                        let stack_base = self.stack.len();
                        // Upvalues are already NanBoxes (the frame representation);
                        // clone (Rc refcount bumps) for the frame and keep the
                        // original for the error-restore path.
                        let frame_upvalues: Vec<NanBox> = upvalues.clone();
                        let upvalues_for_restore = upvalues;
                        self.frames.push(CallFrame {
                            chunk: chunk.clone(),
                            ip: 0,
                            stack_base,
                            upvalues: frame_upvalues,
                        });
                        let result = self.run_until(return_depth);
                        // Restore the stack to its state before thunk evaluation.
                        // The Return handler's early exit (at stop_depth) skips
                        // truncation, so internal function calls may leave values.
                        self.stack.truncate(stack_base);
                        match result {
                            Ok(value) => {
                                // Store partial result IMMEDIATELY — enables
                                // fixpoint re-access. Any re-entrant force_value
                                // on this thunk (e.g., nixpkgs `fix`) will find
                                // Done instead of Evaluating, preventing false
                                // blackhole detection. Matches tree-walker
                                // approach (sui-eval value.rs lines 522-554).
                                let partial_vmval = value.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(partial_vmval),
                                )));
                                // Depth-limited thunk-chain unwrap.
                                let mut forced = value;
                                let mut depth = 0u32;
                                while forced.is_thunk() {
                                    depth += 1;
                                    if depth > MAX_THUNK_CHAIN_DEPTH {
                                        if std::env::var("SUI_VM_TRACE").is_ok() {
                                            eprintln!("[sui-vm] thunk chain depth {} exceeded at chunk: {}", depth, self.current_chunk_name());
                                        }
                                        return Err(VMError::InfiniteRecursion);
                                    }
                                    forced = self.force_value(forced)?;
                                }
                                // Update with fully-unwrapped value.
                                let forced_vmval = forced.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(forced_vmval),
                                )));
                                Ok(forced)
                            }
                            Err(e) => {
                                thunk.state.set(Some(ThunkState::Pending {
                                    chunk,
                                    upvalues: upvalues_for_restore,
                                }));
                                Err(e)
                            }
                        }
                    }
                    Some(ThunkState::LazySource { source, offset, length, base_dir, upvalues }) => {
                        thunk.state.set(Some(ThunkState::Evaluating));
                        // Compile the expression span on demand.
                        let expr_text = &source[offset..offset + length];
                        let shared_interner = Rc::new(RefCell::new(std::mem::take(self.interner)));
                        let compiled = Compiler::compile_expression(
                            expr_text,
                            &base_dir,
                            shared_interner.clone(),
                        ).map_err(|e| {
                            // Restore interner on compile failure.
                            *self.interner = match Rc::try_unwrap(shared_interner.clone()) {
                                Ok(cell) => cell.into_inner(),
                                Err(rc) => rc.borrow().clone(),
                            };
                            thunk.state.set(Some(ThunkState::LazySource {
                                source: source.clone(),
                                offset,
                                length,
                                base_dir: base_dir.clone(),
                                upvalues: upvalues.clone(),
                            }));
                            VMError::ImportError(format!("lazy thunk compile: {e}"))
                        })?;
                        *self.interner = match Rc::try_unwrap(shared_interner) {
                            Ok(cell) => cell.into_inner(),
                            Err(rc) => rc.borrow().clone(),
                        };
                        let chunk = Rc::new(compiled);
                        if self.frames.len() >= MAX_CALL_DEPTH {
                            thunk.state.set(Some(ThunkState::LazySource {
                                source, offset, length, base_dir, upvalues,
                            }));
                            return Err(VMError::StackOverflow);
                        }
                        let return_depth = self.frames.len();
                        let stack_base = self.stack.len();
                        // Upvalues are already NanBoxes; clone (Rc bumps) for the
                        // frame, keeping the original for the error-restore path.
                        let frame_upvalues: Vec<NanBox> = upvalues.clone();
                        self.frames.push(CallFrame {
                            chunk: chunk.clone(),
                            ip: 0,
                            stack_base,
                            upvalues: frame_upvalues,
                        });
                        let result = self.run_until(return_depth);
                        self.stack.truncate(stack_base);
                        match result {
                            Ok(value) => {
                                // Store partial result IMMEDIATELY for fixpoints.
                                let partial_vmval = value.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(partial_vmval),
                                )));
                                let mut forced = value;
                                let mut depth = 0u32;
                                while forced.is_thunk() {
                                    depth += 1;
                                    if depth > MAX_THUNK_CHAIN_DEPTH {
                                        if std::env::var("SUI_VM_TRACE").is_ok() {
                                            eprintln!("[sui-vm] thunk chain depth {} exceeded at chunk: {}", depth, self.current_chunk_name());
                                        }
                                        return Err(VMError::InfiniteRecursion);
                                    }
                                    forced = self.force_value(forced)?;
                                }
                                let forced_vmval = forced.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(forced_vmval),
                                )));
                                Ok(forced)
                            }
                            Err(e) => {
                                thunk.state.set(Some(ThunkState::Pending {
                                    chunk,
                                    upvalues,
                                }));
                                Err(e)
                            }
                        }
                    }
                    Some(ThunkState::NativeCallback(cb)) => {
                        thunk.state.set(Some(ThunkState::Evaluating));
                        match cb() {
                            Ok(sk_val) => {
                                let nb = self.string_keyed_to_nanbox(&sk_val);
                                // Store partial result IMMEDIATELY for fixpoints.
                                let partial_vmval = nb.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(partial_vmval),
                                )));
                                let mut forced = nb;
                                let mut depth = 0u32;
                                while forced.is_thunk() {
                                    depth += 1;
                                    if depth > MAX_THUNK_CHAIN_DEPTH {
                                        if std::env::var("SUI_VM_TRACE").is_ok() {
                                            eprintln!("[sui-vm] thunk chain depth {} exceeded at chunk: {}", depth, self.current_chunk_name());
                                        }
                                        return Err(VMError::InfiniteRecursion);
                                    }
                                    forced = self.force_value(forced)?;
                                }
                                let forced_vmval = forced.to_vmvalue();
                                thunk.state.set(Some(ThunkState::Done(
                                    Box::new(forced_vmval),
                                )));
                                Ok(forced)
                            }
                            Err(e) => {
                                // On error, restore the callback for retry.
                                thunk.state.set(Some(ThunkState::NativeCallback(cb)));
                                Err(VMError::Throw(format!("native thunk: {e}")))
                            }
                        }
                    }
                    None => Err(VMError::Internal("thunk state is None".to_string())),
                }
            }
            _ => Ok(NanBox::from_vmvalue(&vmval)),
        }
    }
    /// Shallow-force container elements: if `val` is a List, force each
    /// Force list elements one level. Builtins that iterate over list
    /// elements (calling `as_string`, `as_int`, etc.) need concrete values.
    /// Attrsets are NOT force — they can be enormous (nixpkgs has 80K+
    /// attrs) and builtins access individual attrs lazily via GetAttr.
    fn shallow_force_list(&mut self, val: VMValue) -> Result<VMValue, VMError> {
        match val {
            VMValue::List(items) => {
                let mut forced_items = Vec::with_capacity(items.len());
                for item in items {
                    let nb = NanBox::from_vmvalue(&item);
                    if nb.is_thunk() {
                        let forced = self.force_value(nb)?;
                        forced_items.push(forced.to_vmvalue());
                    } else {
                        forced_items.push(item);
                    }
                }
                Ok(VMValue::List(forced_items))
            }
            // Attrsets: do NOT force values — too expensive for large sets.
            // Force-aware helpers (force_vmvalue, force_as_string) handle
            // individual thunked values on demand.
            other => Ok(other),
        }
    }
    /// Deep-force a value: recursively force thunks inside attrsets and lists.
    /// Used at the VM boundary so callers never receive unforced thunks.
    fn deep_force(&mut self, val: NanBox) -> Result<NanBox, VMError> {
        let forced = self.force_value(val)?;
        if let Some(attrs) = forced.as_attrs() {
            let mut new_attrs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
            for (k, v) in attrs {
                let forced_v = self.deep_force(v.clone())?;
                new_attrs.insert(*k, forced_v);
            }
            Ok(NanBox::attrs(new_attrs))
        } else if forced.is_list() {
            let vmval = forced.to_vmvalue();
            if let VMValue::List(items) = vmval {
                let mut new_items = Vec::with_capacity(items.len());
                for item in &items {
                    let item_nb = NanBox::from_vmvalue(item);
                    let forced_item = self.deep_force(item_nb)?;
                    new_items.push(forced_item);
                }
                Ok(NanBox::list(new_items))
            } else {
                Ok(forced)
            }
        } else {
            Ok(forced)
        }
    }
    // -- VM-level builtin dispatch (builtins needing interner access) ------
    /// Try to handle a builtin call at the VM level (for builtins that need
    /// interner access, like derivation, attrNames, etc.).
    /// Returns `Some(result)` if handled, `None` to fall through to the
    /// standard builtin dispatch.
    fn try_vm_builtin(
        &mut self,
        name: &str,
        arg: &NanBox,
    ) -> Result<Option<NanBox>, VMError> {
        match name {
            "tryEval" => {
                
                // tryEval forces its argument and catches throws/errors.
                // Success: { success = true; value = <forced>; }
                // Failure: { success = false; value = false; }
                let success_sym = self.interner.intern("success");
                let value_sym = self.interner.intern("value");
                match self.force_value(arg.clone()) {
                    Ok(forced) => {
                        let mut attrs = BTreeMap::new();
                        attrs.insert(success_sym, NanBox::bool(true));
                        attrs.insert(value_sym, forced);
                        Ok(Some(NanBox::attrs(attrs)))
                    }
                    Err(_) => {
                        let mut attrs = BTreeMap::new();
                        attrs.insert(success_sym, NanBox::bool(false));
                        attrs.insert(value_sym, NanBox::bool(false));
                        Ok(Some(NanBox::attrs(attrs)))
                    }
                }
            }
            "derivation" | "derivationStrict" => {
                let forced = self.force_value(arg.clone())?;
                let result = self.vm_build_derivation(forced)?;
                Ok(Some(result))
            }
            "import" => {
                // `import` used as a function value (not the special Apply form).
                let forced = self.force_value(arg.clone())?;
                let path = if let Some(p) = forced.as_path() {
                    p.to_string()
                } else if let Some(s) = forced.as_string() {
                    s.to_string()
                } else {
                    return Err(VMError::TypeError {
                        expected: "path or string",
                        got: forced.type_name(),
                        context: "import".to_string(),
                    });
                };
                let result = self.import_file(&path)?;
                Ok(Some(result))
            }
            "attrNames" => {
                let forced = self.force_value(arg.clone())?;
                if let Some(attrs) = forced.as_attrs() {
                    // Nix sorts attrNames alphabetically.
                    let mut name_strs: Vec<String> = attrs
                        .keys()
                        .map(|k| self.interner.resolve(*k).to_string())
                        .collect();
                    name_strs.sort();
                    let names: Vec<NanBox> = name_strs
                        .into_iter()
                        .map(NanBox::string)
                        .collect();
                    Ok(Some(NanBox::list(names)))
                } else {
                    Err(VMError::TypeError {
                        expected: "set",
                        got: forced.type_name(),
                        context: "attrNames".to_string(),
                    })
                }
            }
            "attrValues" => {
                // Parallel to attrNames: sort the Symbol keys by their
                // resolved string names (CppNix semantics), then emit
                // values in that order. Fixes the bug where real
                // nixpkgs `mapAttrsToList` returned values in
                // intern-order instead of lex-order.
                let forced = self.force_value(arg.clone())?;
                if let Some(attrs) = forced.as_attrs() {
                    let mut pairs: Vec<(String, &NanBox)> = attrs
                        .iter()
                        .map(|(k, v)| (self.interner.resolve(*k).to_string(), v))
                        .collect();
                    pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
                    let values: Vec<NanBox> =
                        pairs.into_iter().map(|(_, v)| v.clone()).collect();
                    Ok(Some(NanBox::list(values)))
                } else {
                    Err(VMError::TypeError {
                        expected: "set",
                        got: forced.type_name(),
                        context: "attrValues".to_string(),
                    })
                }
            }
            "functionArgs" => {
                // The registered builtin entry created a FRESH interner
                // locally, interned the parameter names into it, and
                // returned `VMValue::Attrs` keyed on those Symbols —
                // which were then resolved against the VM's REAL
                // interner during printing/conversion, producing
                // nonsense keys (`functionArgs = false` showing up as
                // an attribute!) plus inverted booleans.
                // Route through VM dispatch so we intern against
                // `self.interner`.
                let forced = self.force_value(arg.clone())?;
                let vmval = forced.to_vmvalue();
                match vmval {
                    VMValue::Closure(closure) => {
                        let mut result = std::collections::BTreeMap::new();
                        for (name, has_default) in &closure.formals {
                            let sym = self.interner.intern(name);
                            result.insert(sym, VMValue::Bool(*has_default));
                        }
                        Ok(Some(NanBox::from_vmvalue(&VMValue::Attrs(result))))
                    }
                    VMValue::Builtin(_) | VMValue::HigherOrderBuiltin(_) => {
                        Ok(Some(NanBox::from_vmvalue(&VMValue::Attrs(
                            std::collections::BTreeMap::new(),
                        ))))
                    }
                    other => Err(VMError::TypeError {
                        expected: "lambda",
                        got: other.type_name(),
                        context: "functionArgs".to_string(),
                    }),
                }
            }
            "fromJSON" => {
                // JSON objects need the interner to intern keys as
                // Symbols. The registered builtin returned `null` for
                // Object variants because `json_to_vm_value` has no
                // interner access — that silently broke every
                // `fromJSON "{...}"` call. Route through VM dispatch
                // so we can intern properly. Primitives, arrays, and
                // nested structures all handled here too, so the
                // registry path is effectively dead for fromJSON
                // post this change.
                let forced = self.force_value(arg.clone())?;
                let s = match forced.as_string() {
                    Some(s) => s.to_string(),
                    None => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: forced.type_name(),
                            context: "fromJSON".to_string(),
                        });
                    }
                };
                let parsed: serde_json::Value = serde_json::from_str(&s)
                    .map_err(|e| VMError::Throw(format!("fromJSON: {e}")))?;
                Ok(Some(self.json_value_to_nanbox(&parsed)))
            }
            "listToAttrs" => {
                let forced = self.force_value(arg.clone())?;
                let vmval = forced.to_vmvalue();
                let list = match &vmval {
                    VMValue::List(l) => l,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "list",
                            got: other.type_name(),
                            context: "listToAttrs".to_string(),
                        });
                    }
                };
                let name_sym = self.interner.intern("name");
                let value_sym = self.interner.intern("value");
                let mut result: BTreeMap<Symbol, NanBox> = BTreeMap::new();
                for item in list {
                    if let VMValue::Attrs(a) = item {
                        let name_val = a.get(&name_sym).ok_or_else(|| {
                            VMError::Throw(
                                "listToAttrs: element missing 'name'".to_string(),
                            )
                        })?;
                        let value_val = a.get(&value_sym).ok_or_else(|| {
                            VMError::Throw(
                                "listToAttrs: element missing 'value'".to_string(),
                            )
                        })?;
                        let key_str = match name_val {
                            VMValue::String(s) => s.clone(),
                            _ => {
                                return Err(VMError::TypeError {
                                    expected: "string",
                                    got: name_val.type_name(),
                                    context: "listToAttrs name".to_string(),
                                });
                            }
                        };
                        let key_sym = self.interner.intern(&key_str);
                        // Nix `listToAttrs` first-wins duplicate semantics:
                        // a repeated `name` keeps the FIRST occurrence (later
                        // duplicates ignored), matching cppnix + the tree-walker.
                        // BTreeMap::insert is last-wins, so guard with entry().
                        result
                            .entry(key_sym)
                            .or_insert_with(|| NanBox::from_vmvalue(value_val));
                    } else {
                        return Err(VMError::TypeError {
                            expected: "set",
                            got: item.type_name(),
                            context: "listToAttrs element".to_string(),
                        });
                    }
                }
                Ok(Some(NanBox::attrs(result)))
            }
            "removeAttrs" => {
                // removeAttrs is curried: first call takes the set, returns partial
                let forced = self.force_value(arg.clone())?;
                if let Some(attrs) = forced.as_attrs() {
                    // Convert to VMValue for the closure (closures can't capture NanBox BTreeMaps)
                    let attrs_vm: BTreeMap<Symbol, VMValue> = attrs
                        .iter()
                        .map(|(k, v)| (*k, v.to_vmvalue()))
                        .collect();
                    let interner_names: Vec<(Symbol, String)> = attrs
                        .keys()
                        .map(|k| (*k, self.interner.resolve(*k).to_string()))
                        .collect();
                    let result = VMValue::Builtin(crate::value::VMBuiltin {
                        name: "removeAttrs<partial>",
                        func: Rc::new(move |args2| {
                            let to_remove = match &args2[0] {
                                VMValue::List(l) => l,
                                other => {
                                    return Err(VMError::TypeError {
                                        expected: "list",
                                        got: other.type_name(),
                                        context: "removeAttrs".to_string(),
                                    });
                                }
                            };
                            let remove_names: std::collections::HashSet<String> = to_remove
                                .iter()
                                .filter_map(|v| {
                                    if let VMValue::String(s) = v {
                                        Some(s.clone())
                                    } else {
                                        None
                                    }
                                })
                                .collect();
                            let mut result = BTreeMap::new();
                            for &(sym, ref name) in &interner_names {
                                if !remove_names.contains(name) {
                                    if let Some(v) = attrs_vm.get(&sym) {
                                        result.insert(sym, v.clone());
                                    }
                                }
                            }
                            Ok(VMValue::Attrs(result))
                        }),
                        arity: 1,
                    });
                    Ok(Some(NanBox::from_vmvalue(&result)))
                } else {
                    Err(VMError::TypeError {
                        expected: "set",
                        got: forced.type_name(),
                        context: "removeAttrs".to_string(),
                    })
                }
            }
            "hasAttr" => {
                // hasAttr is curried: first call takes name string, returns partial
                let forced = self.force_value(arg.clone())?;
                let name_str = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: other.type_name(),
                            context: "hasAttr".to_string(),
                        });
                    }
                };
                let sym = self.interner.intern(&name_str);
                Ok(Some(NanBox::from_vmvalue(&VMValue::Builtin(
                    crate::value::VMBuiltin {
                        name: "hasAttr<partial>",
                        func: Rc::new(move |args2| {
                            let attrs = match &args2[0] {
                                VMValue::Attrs(a) => a,
                                other => {
                                    return Err(VMError::TypeError {
                                        expected: "set",
                                        got: other.type_name(),
                                        context: "hasAttr".to_string(),
                                    });
                                }
                            };
                            Ok(VMValue::Bool(attrs.contains_key(&sym)))
                        }),
                        arity: 1,
                    },
                ))))
            }
            "getAttr" => {
                let forced = self.force_value(arg.clone())?;
                let name_str = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: other.type_name(),
                            context: "getAttr".to_string(),
                        });
                    }
                };
                let sym = self.interner.intern(&name_str);
                let name_for_err = name_str.clone();
                Ok(Some(NanBox::from_vmvalue(&VMValue::Builtin(
                    crate::value::VMBuiltin {
                        name: "getAttr<partial>",
                        func: Rc::new(move |args2| {
                            let attrs = match &args2[0] {
                                VMValue::Attrs(a) => a,
                                other => {
                                    return Err(VMError::TypeError {
                                        expected: "set",
                                        got: other.type_name(),
                                        context: "getAttr".to_string(),
                                    });
                                }
                            };
                            attrs.get(&sym).cloned().ok_or_else(|| {
                                VMError::AttrNotFound(name_for_err.clone())
                            })
                        }),
                        arity: 1,
                    },
                ))))
            }
            "getFlake" => {
                let forced = self.force_value(arg.clone())?;
                let flake_ref = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: other.type_name(),
                            context: "getFlake".to_string(),
                        });
                    }
                };
                let result = self.vm_get_flake(&flake_ref)?;
                Ok(Some(result))
            }
            "scopedImport" => {
                // scopedImport is curried: first call takes scope, returns partial
                let forced = self.force_value(arg.clone())?;
                let scope_vmval = forced.to_vmvalue();
                match scope_vmval {
                    VMValue::Attrs(_) => {}
                    ref other => {
                        return Err(VMError::TypeError {
                            expected: "set",
                            got: other.type_name(),
                            context: "scopedImport".to_string(),
                        });
                    }
                }
                // Build a string-keyed scope for wrapping
                let scope_str = if let Some(attrs) = forced.as_attrs() {
                    let mut parts = String::from("{");
                    for (k, v) in attrs {
                        let key = self.interner.resolve(*k).to_string();
                        let val_vm = v.to_vmvalue();
                        let rhs = match &val_vm {
                            VMValue::Int(n) => n.to_string(),
                            VMValue::Float(f) => format!("{f}"),
                            VMValue::Bool(true) => "true".to_string(),
                            VMValue::Bool(false) => "false".to_string(),
                            VMValue::Null => "null".to_string(),
                            VMValue::String(s) => {
                                let escaped = s
                                    .replace('\\', "\\\\")
                                    .replace('"', "\\\"")
                                    .replace('$', "\\$");
                                format!("\"{escaped}\"")
                            }
                            VMValue::Path(p) => format!("\"{p}\""),
                            _ => {
                                return Err(VMError::Throw(format!(
                                    "scopedImport: cannot render scope value of type {}",
                                    val_vm.type_name()
                                )));
                            }
                        };
                        parts.push_str(&format!(" {key} = {rhs};"));
                    }
                    parts.push_str(" }");
                    parts
                } else {
                    "{}".to_string()
                };
                // Return a partial that takes the path
                let result = VMValue::Builtin(crate::value::VMBuiltin {
                    name: "scopedImport<partial>",
                    func: Rc::new(move |args2| {
                        let path = match &args2[0] {
                            VMValue::String(s) => s.clone(),
                            VMValue::Path(p) => p.clone(),
                            other => {
                                return Err(VMError::TypeError {
                                    expected: "path or string",
                                    got: other.type_name(),
                                    context: "scopedImport".to_string(),
                                });
                            }
                        };
                        // The actual import needs VM context. Store a placeholder
                        // that the VM will intercept.
                        Err(VMError::Throw(format!(
                            "__scopedImport_dispatch__:{}:{}",
                            scope_str, path
                        )))
                    }),
                    arity: 1,
                });
                Ok(Some(NanBox::from_vmvalue(&result)))
            }
            "scopedImport<partial>" => {
                // Intercept the partial application's result
                let forced = self.force_value(arg.clone())?;
                let path = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    VMValue::Path(p) => p,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "path or string",
                            got: other.type_name(),
                            context: "scopedImport".to_string(),
                        });
                    }
                };
                // This won't actually be called via try_vm_builtin because the
                // partial closure captures the scope. The __scopedImport_dispatch__
                // error is caught and processed by the VM. For now, fall through.
                let _ = path;
                Ok(None)
            }
            "catAttrs" => {
                let forced = self.force_value(arg.clone())?;
                let name_str = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: other.type_name(),
                            context: "catAttrs".to_string(),
                        });
                    }
                };
                let sym = self.interner.intern(&name_str);
                Ok(Some(NanBox::from_vmvalue(&VMValue::Builtin(
                    crate::value::VMBuiltin {
                        name: "catAttrs<partial>",
                        func: Rc::new(move |args2| {
                            let list = match &args2[0] {
                                VMValue::List(l) => l,
                                other => {
                                    return Err(VMError::TypeError {
                                        expected: "list",
                                        got: other.type_name(),
                                        context: "catAttrs".to_string(),
                                    });
                                }
                            };
                            let mut result = Vec::new();
                            for item in list {
                                if let VMValue::Attrs(a) = item {
                                    if let Some(v) = a.get(&sym) {
                                        result.push(v.clone());
                                    }
                                }
                            }
                            Ok(VMValue::List(result))
                        }),
                        arity: 1,
                    },
                ))))
            }
            // ── Bridge-dispatched builtins ─────────────────────────
            //
            // These builtins need tree-walker state (regex cache, TOML
            // parser, genericClosure closure-calling, etc.)
            // and are delegated to the builtin bridge.
            "readDir" | "parseDrvName" | "fromTOML" | "genericClosure"
            | "zipAttrsWith" | "getContext" | "toXML"
            | "convertHash" | "path" | "filterSource" | "parseFlakeRef"
            | "flakeRefToString" | "toFile" | "currentTime" | "hashFile"
            | "findFile" => {
                // Deep-force: bridge builtins need fully concrete values
                // because to_string_keyed converts unforced thunks to Lambda.
                let shallow = self.force_value(arg.clone())?;
                let forced = self.deep_force(shallow)?;
                let vmval = forced.to_vmvalue();
                let sk = vmval.to_string_keyed(self.interner);
                match crate::bridge::call_builtin_bridge(name, vec![sk]) {
                    Ok(Some(result)) => {
                        let vm_result = crate::builtins::string_keyed_to_vmvalue(
                            &result,
                            self.interner,
                        );
                        Ok(Some(NanBox::from_vmvalue(&vm_result)))
                    }
                    Ok(None) => {
                        // No bridge set — fall through to registry stub
                        // which will produce the appropriate error.
                        Ok(None)
                    }
                    Err(e) => Err(VMError::Internal(format!("bridge error in '{name}': {e}"))),
                }
            }
            // match and split are curried: first call takes pattern,
            // returns partial that takes the string.
            "match" | "split" => {
                let forced = self.force_value(arg.clone())?;
                let pattern = match forced.to_vmvalue() {
                    VMValue::String(s) => s,
                    other => {
                        return Err(VMError::TypeError {
                            expected: "string",
                            got: other.type_name(),
                            context: name.to_string(),
                        });
                    }
                };
                let builtin_name = name.to_string();
                Ok(Some(NanBox::from_vmvalue(&VMValue::Builtin(
                    crate::value::VMBuiltin {
                        name: if name == "match" {
                            "match<partial>"
                        } else {
                            "split<partial>"
                        },
                        func: Rc::new(move |args2| {
                            let input = match &args2[0] {
                                VMValue::String(s) => s.clone(),
                                other => {
                                    return Err(VMError::TypeError {
                                        expected: "string",
                                        got: other.type_name(),
                                        context: builtin_name.clone(),
                                    });
                                }
                            };
                            // Delegate to bridge with both args
                            let sk_args = vec![
                                crate::value::StringKeyedValue::String(pattern.clone()),
                                crate::value::StringKeyedValue::String(input),
                            ];
                            match crate::bridge::call_builtin_bridge(&builtin_name, sk_args) {
                                Ok(Some(result)) => {
                                    let mut tmp = crate::intern::Interner::new();
                                    Ok(crate::builtins::string_keyed_to_vmvalue(&result, &mut tmp))
                                }
                                Ok(None) => Err(VMError::Throw(format!(
                                    "{builtin_name}: requires bridge but no bridge is set"
                                ))),
                                Err(e) => Err(VMError::Internal(format!("bridge error in '{builtin_name}': {e}"))),
                            }
                        }),
                        arity: 1,
                    },
                ))))
            }
            _ => Ok(None),
        }
    }
    /// Coerce an already-forced [`VMValue`] to a derivation-env string the way
    /// CppNix (and the tree-walker's `coerce_to_string_copy_to_store`) does.
    ///
    /// Returns `None` for values with no meaningful string form (closures,
    /// builtins, un-`outPath`'d attrsets) — the caller skips those env entries
    /// rather than erroring, matching the tree-walker's `_opt` coercion.
    ///
    /// Mirrors `sui-eval/src/value.rs::coerce_to_string_impl` for every value
    /// type the VM can represent:
    ///   - `Float` → `%f` (6 decimals), NOT Rust's shortest form.
    ///   - `List` → items coerced + space-joined.
    ///   - `Attrs` → `outPath` (or `__toString`) coerced; else `None`.
    ///
    /// NOTE (parity tier): the VM does NOT track string context (VMValue::String
    /// carries no context — deferred to Phase 2), so this coercion cannot
    /// populate inputDrvs/inputSrcs edges the way the tree-walker does. For
    /// context-free derivation shapes the env bytes match; context-bearing
    /// shapes still diverge until the VM's Phase-2 context work lands. The
    /// differential test names exactly which shapes reach parity here.
    fn coerce_drv_env_value(&mut self, v: &VMValue) -> Option<String> {
        match v {
            VMValue::String(s) => Some(s.clone()),
            VMValue::Path(p) => Some(p.clone()),
            VMValue::Int(n) => Some(n.to_string()),
            // CppNix uses C printf "%f" → always 6 decimals (`1.5` → "1.500000").
            // Rust's `{}` strips trailing zeros; match the tree-walker's `{f:.6}`.
            VMValue::Float(f) => Some(format!("{f:.6}")),
            VMValue::Bool(true) => Some("1".to_string()),
            VMValue::Bool(false) => Some(String::new()),
            VMValue::Null => Some(String::new()),
            VMValue::List(items) => {
                let mut parts = Vec::with_capacity(items.len());
                for item in items {
                    // Force each item then coerce (tree-walker forces list items).
                    let forced = self
                        .force_value(NanBox::from_vmvalue(item))
                        .ok()?
                        .to_vmvalue();
                    parts.push(self.coerce_drv_env_value(&forced)?);
                }
                Some(parts.join(" "))
            }
            VMValue::Attrs(map) => {
                // CppNix: an attrset coerces via `__toString` then `outPath`;
                // otherwise it has no string form (tree-walker errors, but the
                // env loop uses the `_opt` variant → skip).
                let to_string_sym = self.interner.intern("__toString");
                if map.contains_key(&to_string_sym) {
                    // A `__toString`-bearing attrset requires applying the
                    // function; that goes through the tree-walker seam the VM
                    // does not have here. Leave to the tree-walker (skip) rather
                    // than emit a wrong value — honest under-approximation.
                    return None;
                }
                let out_path_sym = self.interner.intern("outPath");
                let out_path = map.get(&out_path_sym)?;
                let forced = self
                    .force_value(NanBox::from_vmvalue(out_path))
                    .ok()?
                    .to_vmvalue();
                self.coerce_drv_env_value(&forced)
            }
            _ => None,
        }
    }
    /// Build a derivation from a VM attrset (with interner access).
    fn vm_build_derivation(&mut self, arg: NanBox) -> Result<NanBox, VMError> {
        use sui_compat::derivation::{Derivation, DerivationOutput};
        let attrs = match arg.as_attrs() {
            Some(a) => a.clone(),
            None => {
                return Err(VMError::TypeError {
                    expected: "set",
                    got: arg.type_name(),
                    context: "derivation".to_string(),
                });
            }
        };
        // Helper: resolve a symbol key and get string value.
        let get_str = |attrs: &BTreeMap<Symbol, NanBox>,
                       interner: &mut Interner,
                       key: &str|
         -> Result<String, VMError> {
            let sym = interner.intern(key);
            let val = attrs.get(&sym).ok_or_else(|| {
                VMError::AttrNotFound(key.to_string())
            })?;
            match val.to_vmvalue() {
                VMValue::String(s) => Ok(s),
                other => Err(VMError::TypeError {
                    expected: "string",
                    got: other.type_name(),
                    context: format!("derivation attr '{key}'"),
                }),
            }
        };
        let get_str_opt = |attrs: &BTreeMap<Symbol, NanBox>,
                           interner: &mut Interner,
                           key: &str|
         -> Result<Option<String>, VMError> {
            let sym = interner.intern(key);
            match attrs.get(&sym) {
                None => Ok(None),
                Some(val) => match val.to_vmvalue() {
                    VMValue::String(s) => Ok(Some(s)),
                    other => Err(VMError::TypeError {
                        expected: "string",
                        got: other.type_name(),
                        context: format!("derivation attr '{key}'"),
                    }),
                },
            }
        };
        let name = get_str(&attrs, self.interner, "name")?;
        let system = get_str(&attrs, self.interner, "system")?;
        let builder = get_str(&attrs, self.interner, "builder")?;
        // Optional `args` list of strings.
        // IMPORTANT: List items come as NanBox entries that are often
        // still thunks — they MUST be forced before coercion, else
        // every string arg vanishes. Previous code pattern-matched
        // directly on `VMValue::Thunk(_)` → `_ => push("")`, which
        // emitted empty strings and caused every derivation with
        // computed args to have args=[] in its ATerm. That made the
        // .drv path diverge from CppNix on any non-trivial derivation.
        let args_sym = self.interner.intern("args");
        let args_list: Vec<String> = if let Some(a) = attrs.get(&args_sym) {
            let forced_a = self.force_value(a.clone())?;
            let vmval = forced_a.to_vmvalue();
            match vmval {
                VMValue::List(l) => {
                    let mut out = Vec::with_capacity(l.len());
                    for item in &l {
                        // Each item may still be a thunk — force it.
                        let forced = self.force_value(NanBox::from_vmvalue(item))?;
                        match forced.to_vmvalue() {
                            VMValue::String(s) => out.push(s.clone()),
                            VMValue::Int(n) => out.push(n.to_string()),
                            VMValue::Float(f) => out.push(format!("{f:.6}")),
                            VMValue::Bool(true) => out.push("1".to_string()),
                            VMValue::Bool(false) => out.push(String::new()),
                            VMValue::Null => out.push(String::new()),
                            VMValue::Path(p) => out.push(p.clone()),
                            _ => out.push(String::new()),
                        }
                    }
                    out
                }
                _ => Vec::new(),
            }
        } else {
            Vec::new()
        };
        // Optional `outputs` list.
        // IMPORTANT (parity fix): list items arrive as NanBox entries that are
        // frequently still thunks. The previous reader pattern-matched directly
        // on `VMValue::String(s)` and SKIPPED thunks — so every multi-output
        // derivation (glibc/openssl/systemd/gcc/most of stdenv) silently
        // collapsed to a single `out`-only drv, diverging the .drv path from
        // both nix and the tree-walker. Force each item exactly like the `args`
        // reader above so declared outputs survive.
        let outputs_sym = self.interner.intern("outputs");
        let outputs: Vec<String> = if let Some(o) = attrs.get(&outputs_sym) {
            let forced_o = self.force_value(o.clone())?;
            match forced_o.to_vmvalue() {
                VMValue::List(l) => {
                    let mut out = Vec::with_capacity(l.len());
                    for item in &l {
                        let forced = self.force_value(NanBox::from_vmvalue(item))?;
                        if let VMValue::String(s) = forced.to_vmvalue() {
                            out.push(s);
                        }
                    }
                    if out.is_empty() {
                        vec!["out".to_string()]
                    } else {
                        out
                    }
                }
                _ => vec!["out".to_string()],
            }
        } else {
            vec!["out".to_string()]
        };
        // `__ignoreNulls = true` (CppNix): attrs whose value is null are dropped
        // from the env, and `__ignoreNulls` itself is consumed (never emitted).
        // Every stdenv mkDerivation sets this, so without it the VM env carried
        // extra `__ignoreNulls` + any null attr, diverging the modulo hash from
        // both nix and the tree-walker (derivation.rs ~224).
        let ignore_nulls_sym = self.interner.intern("__ignoreNulls");
        let ignore_nulls = attrs
            .get(&ignore_nulls_sym)
            .map(|v| self.force_value(v.clone()))
            .transpose()?
            .map(|v| matches!(v.to_vmvalue(), VMValue::Bool(true)))
            .unwrap_or(false);

        // Build env vars from non-special attributes.
        // Excluded from env: `name`/`system`/`builder` (re-inserted below from
        // the coerced locals), `args` (structural, not an env var), and the
        // control flags CppNix consumes rather than emits (`__ignoreNulls`,
        // `__impure`, `__contentAddressed`). NOT excluded — matching the
        // tree-walker (derivation.rs ~286): `outputs` (coerced to "out dev …")
        // and `__structuredAttrs` (coerced to "" for a non-structured drv);
        // CppNix emits both, and dropping either diverges the modulo hash.
        let special = [
            "name", "system", "builder", "args",
            "__ignoreNulls", "__impure", "__contentAddressed",
        ];
        let special_syms: Vec<Symbol> = special
            .iter()
            .map(|s| self.interner.intern(s))
            .collect();
        let mut env_vars: BTreeMap<String, String> = BTreeMap::new();
        // Collect the (sym, key_str) pairs first to avoid borrowing `attrs`
        // across the `&mut self` force calls in the loop below.
        let env_keys: Vec<(Symbol, String)> = attrs
            .iter()
            .filter(|(k, _)| !special_syms.contains(k))
            .map(|(k, _)| (*k, self.interner.resolve(*k).to_string()))
            .collect();
        for (k, key_str) in env_keys {
            let Some(v) = attrs.get(&k) else { continue };
            // Force the value BEFORE coercion: nearly every real env attr is a
            // thunk (the previous `v.to_vmvalue()` + `_ => continue` dropped
            // every thunk-valued env var — i.e. almost all of them). This
            // mirrors the tree-walker's force-then-coerce in construct_derivation.
            let forced = self.force_value(v.clone())?;
            let fv = forced.to_vmvalue();
            // `__ignoreNulls` drops null-valued attrs entirely.
            if ignore_nulls && matches!(fv, VMValue::Null) {
                continue;
            }
            // Coerce with the SAME semantics as the tree-walker's
            // `coerce_to_string_copy_to_store` for the value types the VM can
            // represent (lists space-join, attrs use outPath, floats use %f).
            // A value with no meaningful string form is skipped (matches the
            // tree-walker's `coerce_..._opt` returning None), not errored.
            match self.coerce_drv_env_value(&fv) {
                Some(s) => {
                    env_vars.insert(key_str, s);
                }
                None => continue,
            }
        }
        env_vars.insert("name".to_string(), name.clone());
        env_vars.insert("system".to_string(), system.clone());
        env_vars.insert("builder".to_string(), builder.clone());
        // Detect fixed-output derivation.
        let output_hash_sym = self.interner.intern("outputHash");
        let is_fod = attrs.contains_key(&output_hash_sym);
        let mut drv = Derivation {
            outputs: BTreeMap::new(),
            input_derivations: BTreeMap::new(),
            input_sources: Vec::new(),
            system,
            builder,
            args: args_list,
            env: env_vars,
        };
        let (drv_path, out_paths, mut drv) = if is_fod {
            let raw_output_hash = get_str(&attrs, self.interner, "outputHash")?;
            let raw_algo = get_str_opt(&attrs, self.interner, "outputHashAlgo")?
                .unwrap_or_default();
            let output_hash_mode = get_str_opt(&attrs, self.interner, "outputHashMode")?
                .unwrap_or_else(|| "flat".to_string());
            let is_recursive =
                output_hash_mode == "recursive" || output_hash_mode == "nar";
            // Empty outputHashAlgo: infer from SRI prefix (cppnix
            // semantics), else default to sha256.
            let output_hash_algo = if raw_algo.is_empty() {
                ["sha256", "sha512", "sha1", "md5"].iter()
                    .find(|a| raw_output_hash.starts_with(&format!("{a}-")))
                    .map(|s| (*s).to_string())
                    .unwrap_or_else(|| "sha256".to_string())
            } else {
                raw_algo
            };
            // Normalize hex/nix-base32/SRI → lowercase hex before
            // building the fixed:out:<algo>:<hex>: fingerprint.  See
            // sui-compat::hash::NixHash::parse_any for the contract.
            let algo = sui_compat::hash::HashAlgorithm::from_nix_str(&output_hash_algo)
                .map_err(|e| VMError::Internal(format!(
                    "derivation: invalid outputHashAlgo {output_hash_algo:?}: {e}",
                )))?;
            let parsed = sui_compat::hash::NixHash::parse_any(algo, &raw_output_hash)
                .map_err(|e| VMError::Internal(format!(
                    "derivation: invalid outputHash {raw_output_hash:?}: {e}",
                )))?;
            let output_hash_hex = parsed.to_hex();
            let out_path = sui_compat::store_path::compute_fixed_output_hash(
                &output_hash_algo,
                &output_hash_hex,
                is_recursive,
                &name,
            );
            drv.outputs.insert(
                "out".to_string(),
                DerivationOutput {
                    path: out_path.clone(),
                    hash_algo: if is_recursive {
                        format!("r:{output_hash_algo}")
                    } else {
                        output_hash_algo.clone()
                    },
                    hash: output_hash_hex,
                },
            );
            // CppNix hashes the FOD with `env["out"] = <out-path>` present (the
            // input-addressed spec's FillOutputs phase sets it; this hand-rolled
            // fixed-output branch skipped it) — without it the FOD drvPath
            // diverges from nix + the tree-walker while its outPath already
            // matches (derivation.rs ~437).
            drv.env.insert("out".to_string(), out_path.clone());

            let drv_content = drv.serialize();
            // Fold the .drv's references (inputDrvs + inputSrcs) into the store
            // path — CppNix's makeTextPath does this for EVERY derivation,
            // including fixed-output ones. A fetchurl FOD consumes curl /
            // mirrors-list / stdenv as inputDrvs, so without the refs its .drv
            // path diverges from nix. (A bare FOD with no inputs has an empty
            // ref set, so the simple FOD case matched even while this hid.)
            // NOTE: the VM does not yet collect string context, so
            // `input_derivations`/`input_sources` are empty here — this fold is
            // a no-op today but matches the tree-walker's construction so the
            // path stays correct once VM context lands (derivation.rs ~446).
            let drv_refs: Vec<String> = drv.input_derivations.keys().cloned()
                .chain(drv.input_sources.iter().cloned())
                .collect();
            let drv_path = sui_compat::store_path::compute_drv_path_with_refs(
                drv_content.as_bytes(), &name, &drv_refs);

            // CppNix `hashDerivationModulo` for a FIXED-OUTPUT derivation is the
            // special sha256("fixed:out:<methodAlgo>:<hashHex>:<outPath>"), NOT
            // the input-addressed ATerm hash. Cache it against this FOD's drv
            // path so every input-addressed derivation that consumes this FOD
            // substitutes the correct modulo hash — without it the consumer's
            // output path (and everything transitively above it) diverges from
            // nix + the tree-walker (derivation.rs ~452).
            let out_output = drv.outputs.get("out");
            let method_algo = out_output
                .map(|o| o.hash_algo.clone())
                .unwrap_or_default();
            let output_hash_hex = out_output
                .map(|o| o.hash.clone())
                .unwrap_or_default();
            let modulo_preimage =
                format!("fixed:out:{method_algo}:{output_hash_hex}:{out_path}");
            let modulo_hex: String = {
                use sha2::{Digest, Sha256};
                Sha256::digest(modulo_preimage.as_bytes())
                    .iter()
                    .map(|b| format!("{b:02x}"))
                    .collect()
            };
            sui_spec::derivation::remember_modulo_hash(&drv_path, &modulo_hex);

            let mut out_paths = BTreeMap::new();
            out_paths.insert("out".to_string(), out_path);
            (drv_path, out_paths, drv)
        } else {
            // Input-addressed drv: algorithm lives in
            // `sui-spec/specs/derivation.lisp`.  Both the VM and the
            // tree-walker call `sui_spec::derivation::apply`, which
            // interprets that one authored spec.  Bug-fix history
            // (#11–#14 this session) was all spec drift between two
            // independently-maintained copies; this call is how we
            // make that drift impossible by construction.
            let algo = sui_spec::derivation::load_canonical().map_err(|e| {
                VMError::TypeError {
                    expected: "valid derivation algorithm spec",
                    got: "load error",
                    context: format!("sui-spec: {e}"),
                }
            })?;
            let (drv_path, out_paths, drv_final) =
                sui_spec::derivation::apply(&algo, drv, outputs.clone(), &name)
                    .map_err(|e| VMError::TypeError {
                        expected: "derivation interpreter success",
                        got: "interp error",
                        context: format!("sui-spec: {e}"),
                    })?;
            (drv_path, out_paths, drv_final)
        };
        // Update derivation outputs with final paths and write .drv file.
        for (output_name, output_path) in &out_paths {
            if let Some(output) = drv.outputs.get_mut(output_name) {
                if output.path.is_empty() {
                    output.path.clone_from(output_path);
                }
            }
            drv.env.insert(output_name.clone(), output_path.clone());
        }
        let drv_content_final = drv.serialize();
        let store_dir = std::env::var("SUI_STORE_DIR")
            .unwrap_or_else(|_| "/nix/store".to_string());
        let disk_path = if store_dir != "/nix/store" {
            drv_path.replacen("/nix/store", &store_dir, 1)
        } else {
            drv_path.clone()
        };
        let drv_file = std::path::Path::new(&disk_path);
        if !drv_file.exists() {
            if let Some(parent) = drv_file.parent() {
                std::fs::create_dir_all(parent).ok();
            }
            match std::fs::write(drv_file, drv_content_final.as_bytes()) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                    let fallback_dir = std::env::temp_dir().join("sui-drv-cache");
                    std::fs::create_dir_all(&fallback_dir).ok();
                    let fallback_path = fallback_dir.join(
                        drv_file.file_name().unwrap_or_default(),
                    );
                    let _ = std::fs::write(&fallback_path, drv_content_final.as_bytes());
                }
                Err(e) => {
                    return Err(VMError::Throw(format!(
                        "derivation: failed to write {drv_path}: {e}"
                    )));
                }
            }
        }
        // Assemble result attrset (CppNix-compatible).
        let mut result: BTreeMap<Symbol, NanBox> = attrs.clone();
        let type_sym = self.interner.intern("type");
        result.insert(type_sym, NanBox::string("derivation".to_string()));
        let drv_path_sym = self.interner.intern("drvPath");
        result.insert(drv_path_sym, NanBox::string(drv_path.clone()));
        // CppNix: drvAttrs contains the original input attributes
        let drv_attrs_sym = self.interner.intern("drvAttrs");
        result.insert(drv_attrs_sym, NanBox::attrs(attrs));
        let primary_out = out_paths
            .get("out")
            .cloned()
            .or_else(|| out_paths.values().next().cloned())
            .unwrap_or_default();
        let out_path_sym = self.interner.intern("outPath");
        result.insert(out_path_sym, NanBox::string(primary_out));
        // CppNix: outputName is the primary output name
        let output_name_sym = self.interner.intern("outputName");
        let primary_output_name = if out_paths.contains_key("out") { "out" }
            else { out_paths.keys().next().map(|s| s.as_str()).unwrap_or("out") };
        result.insert(output_name_sym, NanBox::string(primary_output_name.to_string()));
        let mut all_outputs: Vec<NanBox> = Vec::new();
        for (output_name, output_path) in &out_paths {
            let mut out_attrs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
            out_attrs.insert(out_path_sym, NanBox::string(output_path.clone()));
            out_attrs.insert(drv_path_sym, NanBox::string(drv_path.clone()));
            out_attrs.insert(type_sym, NanBox::string("derivation".to_string()));
            out_attrs.insert(output_name_sym, NanBox::string(output_name.clone()));
            let name_sym = self.interner.intern("name");
            out_attrs.insert(name_sym, NanBox::string(name.clone()));
            let out_val = NanBox::attrs(out_attrs);
            all_outputs.push(out_val.clone());
            let out_sym = self.interner.intern(output_name);
            result.insert(out_sym, out_val);
        }
        // CppNix: `all` is a list of all output derivation attrsets
        let all_sym = self.interner.intern("all");
        result.insert(all_sym, NanBox::list(all_outputs));
        Ok(NanBox::attrs(result))
    }
    /// Call a builtin function, intercepting scopedImport dispatch errors.
    fn call_builtin_with_scoped_import_dispatch(
        &mut self,
        func: Rc<dyn Fn(Vec<VMValue>) -> Result<VMValue, VMError>>,
        arg: VMValue,
    ) -> Result<NanBox, VMError> {
        // Defensive: force VMValue::Thunk args that leaked through.
        let arg = if let VMValue::Thunk(ref thunk) = arg {
            let nb = NanBox::from_vmvalue(&arg);
            self.force_value(nb)?.to_vmvalue()
        } else {
            arg
        };
        match func(vec![arg]) {
            Ok(result) => Ok(NanBox::from_vmvalue(&result)),
            Err(VMError::Throw(ref msg))
                if msg.starts_with("__scopedImport_dispatch__:") =>
            {
                let rest = &msg["__scopedImport_dispatch__:".len()..];
                if let Some(colon_pos) = rest.rfind(':') {
                    let scope_nix = &rest[..colon_pos];
                    let path = &rest[colon_pos + 1..];
                    self.vm_scoped_import(scope_nix, path)
                } else {
                    Err(VMError::Throw(msg.clone()))
                }
            }
            Err(e) => Err(e),
        }
    }
    /// Evaluate `builtins.getFlake` for a path-based flake reference.
    ///
    /// If a thread-local flake resolver has been installed (via
    /// [`set_flake_resolver`]), delegates to it — this lets `sui-eval`
    /// inject the tree-walker's full `evaluate_flake` implementation
    /// which handles all input types correctly.  Falls back to the VM's
    /// own limited resolver otherwise.
    fn vm_get_flake(&mut self, flake_ref: &str) -> Result<NanBox, VMError> {
        // Check for an external resolver first.
        let resolved = FLAKE_RESOLVER.with(|r| {
            let borrow = r.borrow();
            if let Some(ref resolver) = *borrow {
                Some(resolver(flake_ref))
            } else {
                None
            }
        });
        if let Some(result) = resolved {
            let sk = result.map_err(|e| VMError::Throw(format!("getFlake: {e}")))?;
            return Ok(self.string_keyed_to_nanbox(&sk));
        }
        // Fallback: VM-native resolution (path-based only).
        self.vm_get_flake_native(flake_ref)
    }
    /// Convert a `StringKeyedValue` to a `NanBox` for the VM stack.
    ///
    /// `StringKeyedValue::Thunk` variants are wrapped in `VMThunk`s with
    /// `NativeCallback` state so they are only evaluated when the VM
    /// actually forces the value. This keeps `getFlake` fast by deferring
    /// transitive input evaluation.
    fn string_keyed_to_nanbox(&mut self, sk: &crate::value::StringKeyedValue) -> NanBox {
        match sk {
            crate::value::StringKeyedValue::Null => NanBox::null(),
            crate::value::StringKeyedValue::Bool(b) => NanBox::bool(*b),
            crate::value::StringKeyedValue::Int(n) => NanBox::int(*n),
            crate::value::StringKeyedValue::Float(f) => NanBox::float(*f),
            crate::value::StringKeyedValue::String(s) => NanBox::string(s.clone()),
            crate::value::StringKeyedValue::Path(p) => NanBox::from_vmvalue(&VMValue::Path(p.clone())),
            crate::value::StringKeyedValue::List(items) => {
                let nb_items: Vec<NanBox> = items.iter().map(|v| self.string_keyed_to_nanbox(v)).collect();
                NanBox::list(nb_items)
            }
            crate::value::StringKeyedValue::Attrs(map) => {
                let mut nb_map: BTreeMap<Symbol, NanBox> = BTreeMap::new();
                for (k, v) in map {
                    let sym = self.interner.intern(k);
                    nb_map.insert(sym, self.string_keyed_to_nanbox(v));
                }
                NanBox::attrs(nb_map)
            }
            crate::value::StringKeyedValue::Lambda => NanBox::null(),
            crate::value::StringKeyedValue::Callable(cb) => {
                let cb_clone = Rc::clone(cb);
                let builtin = crate::value::VMBuiltin {
                    name: "<bridge-fn>",
                    arity: 1,
                    func: Rc::new(move |args: Vec<VMValue>| {
                        let interner = crate::intern::Interner::new();
                        let sk_arg = args.into_iter().next()
                            .unwrap_or(VMValue::Null)
                            .to_string_keyed(&interner);
                        let sk_result = cb_clone(sk_arg)
                            .map_err(|e| crate::error::VMError::Throw(e))?;
                        let mut tmp_interner = crate::intern::Interner::new();
                        Ok(crate::builtins::string_keyed_to_vmvalue(&sk_result, &mut tmp_interner))
                    }),
                };
                NanBox::builtin(builtin)
            }
            crate::value::StringKeyedValue::Thunk(cb) => {
                // Wrap the callback in a VMThunk with NativeCallback state.
                // The VM's force_value will call the callback on demand and
                // convert the resulting StringKeyedValue to a NanBox.
                let thunk = VMThunk {
                    state: Rc::new(Cell::new(Some(ThunkState::NativeCallback(Rc::clone(cb))))),
                };
                NanBox::thunk(thunk)
            }
        }
    }
    /// VM-native flake resolution (path-based inputs only).
    fn vm_get_flake_native(&mut self, flake_ref: &str) -> Result<NanBox, VMError> {
        let flake_dir = if flake_ref.starts_with('/') || flake_ref.starts_with('.') {
            std::path::PathBuf::from(flake_ref)
        } else if let Some(path) = flake_ref.strip_prefix("path:") {
            std::path::PathBuf::from(path)
        } else {
            return Err(VMError::Throw(format!(
                "getFlake: unsupported flake reference: {flake_ref} (only path: refs supported in VM)"
            )));
        };
        let flake_nix = flake_dir.join("flake.nix");
        if !flake_nix.exists() {
            return Err(VMError::Throw(format!(
                "getFlake: flake.nix not found in {}",
                flake_dir.display()
            )));
        }
        // Import flake.nix to get the raw flake attrset.
        let flake_nix_str = flake_nix.to_string_lossy().to_string();
        let flake_attrs = self.import_file(&flake_nix_str)?;
        let flake_attrs = self.force_value(flake_attrs)?;
        // Build the inputs attrset. For now, create a minimal `self` input.
        let self_sym = self.interner.intern("self");
        let out_path_sym = self.interner.intern("outPath");
        let flake_dir_str = flake_dir.to_string_lossy().to_string();
        let mut self_attrs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
        self_attrs.insert(out_path_sym, NanBox::string(flake_dir_str.clone()));
        let mut inputs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
        inputs.insert(self_sym, NanBox::attrs(self_attrs));
        // Try to read flake.lock and resolve inputs.
        let lock_path = flake_dir.join("flake.lock");
        if lock_path.exists() {
            if let Ok(lock_str) = std::fs::read_to_string(&lock_path) {
                if let Ok(lock_json) = serde_json::from_str::<serde_json::Value>(&lock_str) {
                    self.resolve_flake_lock_inputs(&lock_json, &flake_dir, &mut inputs);
                }
            }
        }
        // Extract the `outputs` function and call it with the inputs attrset.
        let outputs_sym = self.interner.intern("outputs");
        if let Some(attrs) = flake_attrs.as_attrs() {
            if let Some(outputs_func) = attrs.get(&outputs_sym) {
                let outputs_func = outputs_func.clone();
                let outputs_func = self.force_value(outputs_func)?;
                let inputs_nb = NanBox::attrs(inputs);
                let result = self.call_callable(&outputs_func, inputs_nb)?;
                let mut result_forced = self.force_value(result)?;
                // Merge top-level metadata (description) into the result.
                let desc_sym = self.interner.intern("description");
                if let Some(desc) = attrs.get(&desc_sym) {
                    if let Some(result_attrs) = result_forced.as_attrs() {
                        let mut merged = result_attrs.clone();
                        merged.insert(desc_sym, desc.clone());
                        result_forced = NanBox::attrs(merged);
                    }
                }
                return Ok(result_forced);
            }
        }
        // If no outputs function, return the raw flake attrset.
        Ok(flake_attrs)
    }
    /// Resolve flake.lock inputs into the inputs attrset.
    fn resolve_flake_lock_inputs(
        &mut self,
        lock: &serde_json::Value,
        flake_dir: &std::path::Path,
        inputs: &mut BTreeMap<Symbol, NanBox>,
    ) {
        let nodes = match lock.get("nodes").and_then(|n| n.as_object()) {
            Some(n) => n,
            None => return,
        };
        let root_node = match lock.get("root").and_then(|r| r.as_str()) {
            Some(r) => r.to_string(),
            None => "root".to_string(),
        };
        let root_inputs = match nodes
            .get(&root_node)
            .and_then(|n| n.get("inputs"))
            .and_then(|i| i.as_object())
        {
            Some(i) => i,
            None => return,
        };
        for (input_name, node_ref) in root_inputs {
            let node_key = match node_ref.as_str() {
                Some(s) => s.to_string(),
                None => {
                    if let Some(arr) = node_ref.as_array() {
                        if let Some(s) = arr.first().and_then(|v| v.as_str()) {
                            s.to_string()
                        } else {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }
            };
            if let Some(node) = nodes.get(&node_key) {
                if let Some(locked) = node.get("locked") {
                    let locked_type = locked.get("type").and_then(|t| t.as_str()).unwrap_or("");
                    let out_path = match locked_type {
                        "path" => {
                            if let Some(p) = locked.get("path").and_then(|p| p.as_str()) {
                                let path = if p.starts_with('/') {
                                    std::path::PathBuf::from(p)
                                } else {
                                    flake_dir.join(p)
                                };
                                path.to_string_lossy().to_string()
                            } else {
                                continue;
                            }
                        }
                        _ => continue, // Only path inputs for now
                    };
                    let input_sym = self.interner.intern(input_name);
                    let out_path_sym = self.interner.intern("outPath");
                    let mut input_attrs: BTreeMap<Symbol, NanBox> = BTreeMap::new();
                    input_attrs.insert(out_path_sym, NanBox::string(out_path));
                    inputs.insert(input_sym, NanBox::attrs(input_attrs));
                }
            }
        }
    }
    /// Import a file with a scope (for scopedImport).
    ///
    /// Handles the directory → `default.nix` fallback like `import_file`.
    fn vm_scoped_import(
        &mut self,
        scope_nix: &str,
        path: &str,
    ) -> Result<NanBox, VMError> {
        // Directory → default.nix fallback (Nix convention).
        let resolved = if std::path::Path::new(path).is_dir() {
            format!("{path}/default.nix")
        } else {
            path.to_string()
        };
        let source = std::fs::read_to_string(&resolved)
            .map_err(|e| VMError::ImportError(format!("{path}: {e}")))?;
        // Wrap the source in `with <scope>; <source>` to inject the scope.
        let wrapped = format!("with {scope_nix}; {source}");
        let file_dir = std::path::Path::new(&resolved)
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_default();
        // Share the VM's interner so symbol IDs stay consistent.
        let shared_interner = Rc::new(RefCell::new(std::mem::take(self.interner)));
        let chunk = Compiler::compile_with_shared_interner(&wrapped, file_dir, shared_interner.clone())
            .map_err(|e| VMError::ImportError(format!("{path}: {e}")))?;
        *self.interner = match Rc::try_unwrap(shared_interner) {
            Ok(cell) => cell.into_inner(),
            Err(rc) => rc.borrow().clone(),
        };
        if self.frames.len() >= MAX_CALL_DEPTH {
            return Err(VMError::StackOverflow);
        }
        let return_depth = self.frames.len();
        let stack_base = self.stack.len();
        self.frames.push(CallFrame {
            chunk: Rc::new(chunk),
            ip: 0,
            stack_base,
            upvalues: Vec::new(),
        });
        self.run_until(return_depth)
    }
    // -- Higher-order builtin execution -----------------------------------
    fn call_callable(&mut self, func: &NanBox, arg: NanBox) -> Result<NanBox, VMError> {
        if let Some(closure) = func.as_closure() {
            if self.frames.len() >= MAX_CALL_DEPTH {
                return Err(VMError::StackOverflow);
            }
            let upvalues = closure.upvalues.clone();
            let chunk = closure.chunk.clone();
            let return_depth = self.frames.len();
            let stack_base = self.stack.len();
            self.push(arg);
            self.frames.push(CallFrame {
                chunk,
                ip: 0,
                stack_base,
                upvalues,
            });
            let result = self.run_until(return_depth)?;
            self.stack.truncate(stack_base);
            // Force the result — callers expect concrete values
            // (e.g., filter checks is_truthy on predicate results).
            self.force_value(result)
        } else if func.is_higher_order_builtin() {
            let hob = func.as_higher_order_builtin().unwrap().clone();
            self.call_higher_order_builtin(&hob, arg)
        } else if let Some(builtin) = func.as_builtin() {
            // Force the arg for builtins — they expect concrete values.
            let arg = self.force_value(arg)?;
            if let Some(result) = self.try_vm_builtin(builtin.name, &arg)? {
                Ok(result)
            } else {
                // Deep-force: builtins iterate over container elements.
                let deep = self.deep_force(arg)?;
                let arg_vmval = deep.to_vmvalue();
                let builtin_func = builtin.func.clone();
                let result = self.call_builtin_with_scoped_import_dispatch(
                    builtin_func, arg_vmval,
                )?;
                Ok(result)
            }
        } else {
            Err(VMError::NotCallable(func.type_name().to_string()))
        }
    }
    #[allow(clippy::too_many_lines)]
    fn call_higher_order_builtin(
        &mut self,
        hob: &HigherOrderBuiltin,
        arg: NanBox,
    ) -> Result<NanBox, VMError> {
        use HigherOrderOp::*;
        // Force the argument — higher-order builtins need concrete values.
        // Use shallow_force_container to handle thunked list elements.
        let arg = self.force_value(arg)?;
        match hob.op {
            Map => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.map".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut results = Vec::with_capacity(list.len());
                for item in list {
                    let r = self.call_callable(&func_nb, NanBox::from_vmvalue(item))?;
                    results.push(r);
                }
                Ok(NanBox::list(results))
            }
            Filter => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.filter".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut results = Vec::new();
                for item in list {
                    let item_nb = NanBox::from_vmvalue(item);
                    let r = self.call_callable(&func_nb, item_nb.clone())?;
                    
                    if r.is_truthy()? { results.push(item_nb); }
                }
                Ok(NanBox::list(results))
            }
            FoldlP1 => {
                let init_vmval = arg.to_vmvalue();
                Ok(NanBox::from_vmvalue(&VMValue::HigherOrderBuiltin(
                    HigherOrderBuiltin {
                        op: FoldlP2,
                        func: hob.func.clone(),
                        extra_args: vec![init_vmval],
                    },
                )))
            }
            FoldlP2 => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.foldl'".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut acc = NanBox::from_vmvalue(&hob.extra_args[0]);
                for item in list {
                    let partial = self.call_callable(&func_nb, acc)?;
                    acc = self.call_callable(&partial, NanBox::from_vmvalue(item))?;
                }
                Ok(acc)
            }
            Sort => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l.clone(),
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.sort".to_string(),
                    }),
                };
                if list.len() <= 1 {
                    return Ok(NanBox::from_vmvalue(&VMValue::List(list)));
                }
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut sorted: Vec<VMValue> = Vec::with_capacity(list.len());
                for item in &list {
                    let item_nb = NanBox::from_vmvalue(item);
                    let mut pos = sorted.len();
                    for (i, existing) in sorted.iter().enumerate() {
                        let existing_nb = NanBox::from_vmvalue(existing);
                        let partial = self.call_callable(&func_nb, item_nb.clone())?;
                        let cmp_result = self.call_callable(&partial, existing_nb)?;
                        if cmp_result.is_truthy()? { pos = i; break; }
                    }
                    sorted.insert(pos, item.clone());
                }
                Ok(NanBox::from_vmvalue(&VMValue::List(sorted)))
            }
            GenList => {
                let n = match arg.to_vmvalue() {
                    VMValue::Int(n) => n,
                    other => return Err(VMError::TypeError {
                        expected: "int", got: other.type_name(),
                        context: "builtins.genList".to_string(),
                    }),
                };
                if n < 0 { return Err(VMError::Throw("genList: negative length".to_string())); }
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut results = Vec::with_capacity(n as usize);
                for i in 0..n {
                    results.push(self.call_callable(&func_nb, NanBox::int(i))?);
                }
                Ok(NanBox::list(results))
            }
            ConcatMap => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.concatMap".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut results = Vec::new();
                for item in list {
                    let mapped = self.call_callable(&func_nb, NanBox::from_vmvalue(item))?;
                    match mapped.to_vmvalue() {
                        VMValue::List(inner) => {
                            for v in &inner { results.push(NanBox::from_vmvalue(v)); }
                        }
                        other => return Err(VMError::TypeError {
                            expected: "list", got: other.type_name(),
                            context: "builtins.concatMap result".to_string(),
                        }),
                    }
                }
                Ok(NanBox::list(results))
            }
            Any => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.any".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                for item in list {
                    if self.call_callable(&func_nb, NanBox::from_vmvalue(item))?.is_truthy()? {
                        return Ok(NanBox::bool(true));
                    }
                }
                Ok(NanBox::bool(false))
            }
            All => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.all".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                for item in list {
                    if !self.call_callable(&func_nb, NanBox::from_vmvalue(item))?.is_truthy()? {
                        return Ok(NanBox::bool(false));
                    }
                }
                Ok(NanBox::bool(true))
            }
            Partition => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.partition".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let (mut right, mut wrong) = (Vec::new(), Vec::new());
                for item in list {
                    let item_nb = NanBox::from_vmvalue(item);
                    if self.call_callable(&func_nb, item_nb.clone())?.is_truthy()? {
                        right.push(item_nb);
                    } else {
                        wrong.push(item_nb);
                    }
                }
                let rs = self.interner.intern("right");
                let ws = self.interner.intern("wrong");
                let mut attrs = BTreeMap::new();
                attrs.insert(rs, NanBox::list(right));
                attrs.insert(ws, NanBox::list(wrong));
                Ok(NanBox::attrs(attrs))
            }
            GroupBy => {
                let list_val = arg.to_vmvalue();
                let list = match &list_val {
                    VMValue::List(l) => l,
                    other => return Err(VMError::TypeError {
                        expected: "list", got: other.type_name(),
                        context: "builtins.groupBy".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let mut groups: BTreeMap<String, Vec<NanBox>> = BTreeMap::new();
                for item in list {
                    let item_nb = NanBox::from_vmvalue(item);
                    let kr = self.call_callable(&func_nb, item_nb.clone())?;
                    let ks = kr.as_string().ok_or_else(|| VMError::TypeError {
                        expected: "string", got: kr.type_name(),
                        context: "builtins.groupBy key".to_string(),
                    })?.to_string();
                    groups.entry(ks).or_default().push(item_nb);
                }
                let mut attrs = BTreeMap::new();
                for (k, vs) in groups {
                    attrs.insert(self.interner.intern(&k), NanBox::list(vs));
                }
                Ok(NanBox::attrs(attrs))
            }
            MapAttrs => {
                let attrs_val = arg.to_vmvalue();
                let attrs = match &attrs_val {
                    VMValue::Attrs(a) => a,
                    other => return Err(VMError::TypeError {
                        expected: "set", got: other.type_name(),
                        context: "builtins.mapAttrs".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let entries: Vec<_> = attrs.iter().map(|(k, v)| (*k, v.clone())).collect();
                let chunk = deferred_apply_chunk();
                let mut result = BTreeMap::new();
                for (sym, val) in entries {
                    let key_str = self.interner.resolve(sym).to_string();
                    // Eagerly apply f to the key name (partial application).
                    // This is cheap — it just creates a closure capturing the key.
                    let partial = self.call_callable(&func_nb, NanBox::string(key_str))?;
                    // Defer the second application (partial value) as a thunk.
                    // This matches CppNix semantics: mapAttrs is lazy in values.
                    // Upvalues are NanBoxes: `partial` already is one; `val`
                    // came off the VMValue attrset so convert it locally here
                    // (this is a per-entry conversion, not the per-Call/thunk
                    // round-trip the optimization removes).
                    let thunk = VMThunk::new(
                        chunk.clone(),
                        vec![partial, NanBox::from_vmvalue(&val)],
                    );
                    result.insert(sym, NanBox::thunk(thunk));
                }
                Ok(NanBox::attrs(result))
            }
            FilterAttrs => {
                let attrs_val = arg.to_vmvalue();
                let attrs = match &attrs_val {
                    VMValue::Attrs(a) => a,
                    other => return Err(VMError::TypeError {
                        expected: "set", got: other.type_name(),
                        context: "builtins.filterAttrs".to_string(),
                    }),
                };
                let func_nb = NanBox::from_vmvalue(&hob.func);
                let entries: Vec<_> = attrs.iter().map(|(k, v)| (*k, v.clone())).collect();
                let mut result = BTreeMap::new();
                for (sym, val) in entries {
                    let key_str = self.interner.resolve(sym).to_string();
                    let partial = self.call_callable(&func_nb, NanBox::string(key_str))?;
                    if self.call_callable(&partial, NanBox::from_vmvalue(&val))?.is_truthy()? {
                        result.insert(sym, NanBox::from_vmvalue(&val));
                    }
                }
                Ok(NanBox::attrs(result))
            }
            Elem => {
                // builtins.elem needle list — check if needle is in list.
                // Needs VM-level handling because list elements may be thunks
                // that must be forced before equality comparison.
                // Uses deep_eq which recursively forces nested values.
                let needle = NanBox::from_vmvalue(&hob.func);
                let forced_needle = self.force_value(needle)?;
                let list = if let Some(items) = arg.as_list() {
                    items.to_vec()
                } else {
                    let forced = self.force_value(arg)?;
                    if let Some(items) = forced.as_list() {
                        items.to_vec()
                    } else {
                        return Err(VMError::TypeError {
                            expected: "list",
                            got: forced.type_name(),
                            context: "builtins.elem".to_string(),
                        });
                    }
                };
                for item in &list {
                    let forced_item = self.force_value(item.clone())?;
                    if self.deep_eq(&forced_needle, &forced_item)? {
                        return Ok(NanBox::bool(true));
                    }
                }
                Ok(NanBox::bool(false))
            }
        }
    }
    // -- Import ---------------------------------------------------------
    /// Import a Nix file: compile it, execute it, cache the result.
    ///
    /// Handles the Nix convention that importing a directory is equivalent
    /// to importing `<directory>/default.nix`.
    fn import_file(&mut self, path: &str) -> Result<NanBox, VMError> {
        let resolved = std::fs::canonicalize(path)
            .map_err(|e| VMError::ImportError(format!("{path}: {e}")))?;
        // Directory → default.nix fallback (Nix convention).
        let resolved = if resolved.is_dir() {
            resolved.join("default.nix")
        } else {
            resolved
        };
        let canonical = resolved.to_string_lossy().to_string();
        // Check cache.
        if let Some(cached) = self.import_cache.borrow().get(&canonical) {
            return Ok(NanBox::from_vmvalue(cached));
        }
        // Try VM compilation, falling back to tree-walker on CompileError.
        let chunk = self.try_compile_import(&resolved, &canonical)?;
        let chunk = match chunk {
            Some(c) => c,
            None => {
                // Compilation failed — fall back to tree-walker via bridge.
                return self.import_via_bridge(&canonical);
            }
        };
        if self.frames.len() >= MAX_CALL_DEPTH {
            return Err(VMError::StackOverflow);
        }
        let return_depth = self.frames.len();
        let stack_base = self.stack.len();
        self.frames.push(CallFrame {
            chunk,
            ip: 0,
            stack_base,
            upvalues: Vec::new(),
        });
        let result = match self.run_until(return_depth) {
            Ok(r) => r,
            Err(e @ VMError::Throw(_)) => {
                // Nix throw must propagate so tryEval can catch it.
                self.stack.truncate(stack_base);
                if self.frames.len() > return_depth {
                    self.frames.truncate(return_depth);
                }
                return Err(e);
            }
            Err(e) => {
                // Any other error — fall back to tree-walker for this file.
                // This includes AttrNotFound, TypeError, AssertionFailed, etc.
                eprintln!("[sui-vm] runtime fallback for {canonical}: {e}");
                use std::sync::atomic::Ordering;
                crate::vm::VM_FALLBACK_COUNT.fetch_add(1, Ordering::Relaxed);
                self.stack.truncate(stack_base);
                if self.frames.len() > return_depth {
                    self.frames.truncate(return_depth);
                }
                return self.import_via_bridge(&canonical);
            }
        };
        // Clean up the imported frame's stack slots.
        // Return at stop_depth skips truncation, so we must do it here.
        self.stack.truncate(stack_base);
        // Cache as VMValue and return as NanBox.
        let result_vmval = result.to_vmvalue();
        self.import_cache
            .borrow_mut()
            .insert(canonical, result_vmval);
        Ok(result)
    }
    /// Try to compile an imported file. Returns `Ok(Some(chunk))` on success,
    /// `Ok(None)` on `CompileError` (caller should fall back to tree-walker),
    /// or `Err` on I/O errors.
    fn try_compile_import(
        &mut self,
        resolved: &std::path::Path,
        canonical: &str,
    ) -> Result<Option<Rc<Chunk>>, VMError> {
        // Check compile cache — skip parse + compile if we've seen this file.
        if let Some(cached_chunk) = self.compile_cache.get(resolved) {
            return Ok(Some(cached_chunk.clone()));
        }
        // Read the file.
        let source = std::fs::read_to_string(canonical)
            .map_err(|e| VMError::ImportError(format!("{canonical}: {e}")))?;
        let file_dir = resolved
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_default();
        // Share the VM's interner with the compiler so that symbol IDs
        // are consistent — no need to clear key_symbols afterwards.
        let shared_interner = Rc::new(RefCell::new(std::mem::take(self.interner)));
        let compile_result =
            Compiler::compile_with_shared_interner(&source, file_dir, shared_interner.clone());
        *self.interner = match Rc::try_unwrap(shared_interner) {
            Ok(cell) => cell.into_inner(),
            Err(rc) => rc.borrow().clone(),
        };
        match compile_result {
            Ok(mut compiled) => {
                Self::set_source_file_recursive(&mut compiled, canonical);
                let chunk = Rc::new(compiled);
                self.compile_cache
                    .insert(resolved.to_path_buf(), chunk.clone());
                Ok(Some(chunk))
            }
            Err(compile_error) => {
                // Compilation failed (unsupported expression, etc.) —
                // signal caller to fall back to tree-walker.
                VM_FALLBACK_COUNT.fetch_add(1, Ordering::Relaxed);
                eprintln!("[sui-vm] fallback to tree-walker for {canonical}: {compile_error}");
                Ok(None)
            }
        }
    }
    /// Fall back to tree-walker evaluation for an imported file via the
    /// builtin bridge. Called when the bytecode compiler cannot handle
    /// the file (e.g. unsupported AST constructs).
    fn import_via_bridge(&mut self, canonical: &str) -> Result<NanBox, VMError> {
        match crate::bridge::call_builtin_bridge(
            "__import",
            vec![crate::value::StringKeyedValue::Path(canonical.to_string())],
        ) {
            Ok(Some(result)) => {
                let nanbox = self.string_keyed_to_nanbox(&result);
                // Force the top-level result so callers get a concrete
                // value (not a thunk). Bridge results may be thunked
                // when the tree-walker wraps unevaluated expressions.
                let nanbox = if nanbox.is_thunk() {
                    self.force_value(nanbox)?
                } else {
                    nanbox
                };
                // Cache as VMValue so subsequent imports hit the cache.
                let result_vmval = nanbox.to_vmvalue();
                self.import_cache
                    .borrow_mut()
                    .insert(canonical.to_string(), result_vmval);
                Ok(nanbox)
            }
            Ok(None) => Err(VMError::ImportError(format!(
                "compilation failed and no bridge installed for '{canonical}'"
            ))),
            Err(e) => Err(VMError::ImportError(format!(
                "bridge fallback error for '{canonical}': {e}"
            ))),
        }
    }
    /// Recursively set `source_file` on a chunk and all nested closure chunks.
    fn set_source_file_recursive(chunk: &mut Chunk, file: &str) {
        chunk.source_file = Some(file.to_string());
        for constant in &mut chunk.constants {
            if let VMValue::Closure(closure) = constant {
                if let Some(inner_chunk) = Rc::get_mut(&mut closure.chunk) {
                    Self::set_source_file_recursive(inner_chunk, file);
                }
            }
        }
    }
    /// Disassemble instructions around a given offset for error diagnostics.
    /// Returns a human-readable string showing `window` instructions before
    /// and after `center_ip`, with an arrow marking the center.
    fn disassemble_around(chunk: &Chunk, center_ip: usize, window: usize) -> String {
        let code = &chunk.code;
        let mut lines: Vec<String> = Vec::new();
        // Collect instruction boundaries by scanning from the start.
        let mut boundaries: Vec<usize> = Vec::new();
        let mut pos = 0;
        while pos < code.len() {
            boundaries.push(pos);
            pos += Self::instruction_width(code, pos);
        }
        // Find the boundary closest to center_ip.
        let center_idx = boundaries.iter().position(|&b| b >= center_ip).unwrap_or(0);
        let start_idx = center_idx.saturating_sub(window);
        let end_idx = (center_idx + window + 1).min(boundaries.len());
        for idx in start_idx..end_idx {
            let ip = boundaries[idx];
            let marker = if ip == center_ip { ">>>" } else { "   " };
            let line = chunk.lines.get(ip).copied().unwrap_or(0);
            if let Some(op) = OpCode::from_byte(code[ip]) {
                let operands = Self::format_operands(code, ip, op);
                lines.push(format!("    {marker} {ip:4}: {op:?}{operands}  (line {line})"));
            } else {
                lines.push(format!("    {marker} {ip:4}: <unknown {}>  (line {line})", code[ip]));
            }
        }
        lines.join("\n")
    }
    /// Determine the total byte width of an instruction at `pos`.
    fn instruction_width(code: &[u8], pos: usize) -> usize {
        let byte = code[pos];
        match OpCode::from_byte(byte) {
            Some(op) => match op {
                // No operands (1 byte):
                OpCode::Null | OpCode::True | OpCode::False
                | OpCode::Add | OpCode::Sub | OpCode::Mul | OpCode::Div | OpCode::Negate
                | OpCode::Not | OpCode::And | OpCode::Or | OpCode::Implication
                | OpCode::Equal | OpCode::NotEqual | OpCode::Less | OpCode::Greater
                | OpCode::LessEqual | OpCode::GreaterEqual
                | OpCode::UpdateAttrs | OpCode::Concat
                | OpCode::Call | OpCode::TailCall | OpCode::Return
                | OpCode::Assert | OpCode::Throw | OpCode::Pop | OpCode::Dup | OpCode::PushWith | OpCode::PopWith
                | OpCode::PushBuiltins | OpCode::Force | OpCode::Import
                | OpCode::DynGetAttr | OpCode::DynHasAttr
                | OpCode::DynSelectOrDefault | OpCode::Dup => 1,
                // 1 u16 operand (3 bytes):
                OpCode::Constant | OpCode::GetLocal | OpCode::SetLocal
                | OpCode::GetUpvalue | OpCode::SetUpvalue | OpCode::LookupWith
                | OpCode::GetAttr | OpCode::HasAttr | OpCode::MakeAttrs
                | OpCode::SelectOrDefault | OpCode::MakeList
                | OpCode::Jump | OpCode::JumpIfFalse | OpCode::JumpIfTrue
                | OpCode::Interpolate => 3,
                // 2 u16 operands (5 bytes):
                OpCode::GetLocalAttr | OpCode::GetLocalCall | OpCode::CallBuiltin => 5,
                // MakeClosure: u16 const_idx, u16 uv_count, then uv_count * 3 bytes
                OpCode::MakeClosure => {
                    if pos + 5 <= code.len() {
                        let uv_count = u16::from_le_bytes([code[pos + 3], code[pos + 4]]) as usize;
                        5 + uv_count * 3
                    } else {
                        3 // truncated
                    }
                }
                // MakeThunk: u16 const_idx, u16 uv_count, then uv_count * 3 bytes
                OpCode::MakeThunk => {
                    if pos + 5 <= code.len() {
                        let uv_count = u16::from_le_bytes([code[pos + 3], code[pos + 4]]) as usize;
                        5 + uv_count * 3
                    } else {
                        3
                    }
                }
                // PatchThunkUpvalues: u16 slot, u16 uv_count, then uv_count * 3 bytes
                OpCode::PatchThunkUpvalues => {
                    if pos + 5 <= code.len() {
                        let uv_count = u16::from_le_bytes([code[pos + 3], code[pos + 4]]) as usize;
                        5 + uv_count * 3
                    } else {
                        3
                    }
                }
                // MakeLazyThunk: u16 src, u32 offset, u32 length, u16 dir, u16 uv_count, then uv_count * 3
                OpCode::MakeLazyThunk => {
                    if pos + 15 <= code.len() {
                        let uv_count = u16::from_le_bytes([code[pos + 13], code[pos + 14]]) as usize;
                        15 + uv_count * 3
                    } else {
                        3
                    }
                }
            },
            None => 1, // unknown opcode, skip 1
        }
    }
    /// Format inline operands for a single instruction (for disassembly).
    fn format_operands(code: &[u8], pos: usize, op: OpCode) -> String {
        let read_u16_at = |p: usize| -> Option<u16> {
            if p + 2 <= code.len() {
                Some(u16::from_le_bytes([code[p], code[p + 1]]))
            } else {
                None
            }
        };
        match op {
            OpCode::Constant | OpCode::GetLocal | OpCode::SetLocal
            | OpCode::GetUpvalue | OpCode::SetUpvalue | OpCode::LookupWith
            | OpCode::GetAttr | OpCode::HasAttr | OpCode::MakeAttrs
            | OpCode::SelectOrDefault | OpCode::MakeList
            | OpCode::Jump | OpCode::JumpIfFalse | OpCode::JumpIfTrue
            | OpCode::Interpolate => {
                read_u16_at(pos + 1).map_or(String::new(), |v| format!(" {v}"))
            }
            OpCode::GetLocalAttr => {
                let s = read_u16_at(pos + 1).unwrap_or(0);
                let k = read_u16_at(pos + 3).unwrap_or(0);
                format!(" slot={s} key={k}")
            }
            OpCode::GetLocalCall => {
                read_u16_at(pos + 1).map_or(String::new(), |v| format!(" slot={v}"))
            }
            OpCode::CallBuiltin => {
                let idx = read_u16_at(pos + 1).unwrap_or(0);
                let argc = read_u16_at(pos + 3).unwrap_or(0);
                format!(" idx={idx} argc={argc}")
            }
            OpCode::MakeThunk | OpCode::MakeClosure => {
                let ci = read_u16_at(pos + 1).unwrap_or(0);
                let uv = read_u16_at(pos + 3).unwrap_or(0);
                format!(" const={ci} upvals={uv}")
            }
            OpCode::PatchThunkUpvalues => {
                let s = read_u16_at(pos + 1).unwrap_or(0);
                let uv = read_u16_at(pos + 3).unwrap_or(0);
                format!(" slot={s} upvals={uv}")
            }
            _ => String::new(),
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::compiler::Compiler;
    use crate::value::StringKeyedValue;
    fn eval(input: &str) -> VMValue {
        let (chunk, mut interner) =
            Compiler::compile(input).unwrap_or_else(|e| panic!("compile '{input}': {e}"));
        VM::execute(chunk, &mut interner).unwrap_or_else(|e| panic!("execute '{input}': {e}"))
    }
    fn eval_full_helper(input: &str) -> crate::StringKeyedValue {
        let result =
            crate::eval_full(input).unwrap_or_else(|e| panic!("eval_full '{input}': {e}"));
        result.to_string_keyed()
    }
    fn eval_err(input: &str) -> VMError {
        let (chunk, mut interner) =
            Compiler::compile(input).unwrap_or_else(|e| panic!("compile '{input}': {e}"));
        VM::execute(chunk, &mut interner).unwrap_err()
    }
    // -- Literals -------------------------------------------------------
    #[test]
    fn eval_integer() {
        assert_eq!(eval("42"), VMValue::Int(42));
    }
    #[test]
    fn eval_negative_integer() {
        assert_eq!(eval("-7"), VMValue::Int(-7));
    }
    #[test]
    fn eval_float() {
        assert_eq!(eval("3.14"), VMValue::Float(3.14));
    }
    #[test]
    fn eval_bool_true() {
        assert_eq!(eval("true"), VMValue::Bool(true));
    }
    #[test]
    fn eval_bool_false() {
        assert_eq!(eval("false"), VMValue::Bool(false));
    }
    #[test]
    fn eval_null() {
        assert_eq!(eval("null"), VMValue::Null);
    }
    #[test]
    fn eval_string() {
        assert_eq!(eval(r#""hello""#), VMValue::String("hello".to_string()));
    }
    // -- Arithmetic -----------------------------------------------------
    #[test]
    fn eval_add_int() {
        assert_eq!(eval("1 + 2"), VMValue::Int(3));
    }
    #[test]
    fn eval_sub_int() {
        assert_eq!(eval("10 - 3"), VMValue::Int(7));
    }
    #[test]
    fn eval_mul_int() {
        assert_eq!(eval("3 * 4"), VMValue::Int(12));
    }
    #[test]
    fn eval_div_int() {
        assert_eq!(eval("10 / 3"), VMValue::Int(3));
    }
    #[test]
    fn eval_div_zero() {
        assert!(matches!(eval_err("1 / 0"), VMError::DivisionByZero));
    }
    #[test]
    fn eval_float_arithmetic() {
        assert_eq!(eval("1.5 + 2.5"), VMValue::Float(4.0));
    }
    #[test]
    fn eval_mixed_arithmetic() {
        assert_eq!(eval("1 + 2.0"), VMValue::Float(3.0));
    }
    #[test]
    fn eval_compound_arithmetic() {
        assert_eq!(eval("2 * 3 + 1"), VMValue::Int(7));
    }
    #[test]
    fn eval_negate_float() {
        assert_eq!(eval("-3.14"), VMValue::Float(-3.14));
    }
    #[test]
    fn eval_string_concat() {
        assert_eq!(
            eval(r#""hello" + " " + "world""#),
            VMValue::String("hello world".to_string())
        );
    }
    // -- Comparison -----------------------------------------------------
    #[test]
    fn eval_equal() {
        assert_eq!(eval("1 == 1"), VMValue::Bool(true));
        assert_eq!(eval("1 == 2"), VMValue::Bool(false));
    }
    #[test]
    fn eval_not_equal() {
        assert_eq!(eval("1 != 2"), VMValue::Bool(true));
        assert_eq!(eval("1 != 1"), VMValue::Bool(false));
    }
    #[test]
    fn eval_less() {
        assert_eq!(eval("1 < 2"), VMValue::Bool(true));
        assert_eq!(eval("2 < 1"), VMValue::Bool(false));
    }
    #[test]
    fn eval_greater() {
        assert_eq!(eval("2 > 1"), VMValue::Bool(true));
        assert_eq!(eval("1 > 2"), VMValue::Bool(false));
    }
    #[test]
    fn eval_less_equal() {
        assert_eq!(eval("1 <= 1"), VMValue::Bool(true));
        assert_eq!(eval("1 <= 2"), VMValue::Bool(true));
        assert_eq!(eval("2 <= 1"), VMValue::Bool(false));
    }
    #[test]
    fn eval_greater_equal() {
        assert_eq!(eval("1 >= 1"), VMValue::Bool(true));
        assert_eq!(eval("2 >= 1"), VMValue::Bool(true));
        assert_eq!(eval("1 >= 2"), VMValue::Bool(false));
    }
    // -- Logical --------------------------------------------------------
    #[test]
    fn eval_not() {
        assert_eq!(eval("!true"), VMValue::Bool(false));
        assert_eq!(eval("!false"), VMValue::Bool(true));
    }
    #[test]
    fn eval_and_short_circuit() {
        assert_eq!(eval("true && true"), VMValue::Bool(true));
        assert_eq!(eval("true && false"), VMValue::Bool(false));
        assert_eq!(eval("false && true"), VMValue::Bool(false));
    }
    #[test]
    fn eval_or_short_circuit() {
        assert_eq!(eval("false || true"), VMValue::Bool(true));
        assert_eq!(eval("false || false"), VMValue::Bool(false));
        assert_eq!(eval("true || false"), VMValue::Bool(true));
    }
    #[test]
    fn eval_implication() {
        assert_eq!(eval("true -> true"), VMValue::Bool(true));
        assert_eq!(eval("true -> false"), VMValue::Bool(false));
        assert_eq!(eval("false -> true"), VMValue::Bool(true));
        assert_eq!(eval("false -> false"), VMValue::Bool(true));
    }
    // -- Conditionals ---------------------------------------------------
    #[test]
    fn eval_if_true() {
        assert_eq!(eval("if true then 1 else 2"), VMValue::Int(1));
    }
    #[test]
    fn eval_if_false() {
        assert_eq!(eval("if false then 1 else 2"), VMValue::Int(2));
    }
    #[test]
    fn eval_if_expression() {
        assert_eq!(
            eval("if 1 > 2 then \"yes\" else \"no\""),
            VMValue::String("no".to_string())
        );
    }
    #[test]
    fn eval_nested_if() {
        assert_eq!(
            eval("if true then (if false then 1 else 2) else 3"),
            VMValue::Int(2)
        );
    }
    // -- Let/in ---------------------------------------------------------
    #[test]
    fn eval_let_simple() {
        assert_eq!(eval("let x = 1; y = 2; in x + y"), VMValue::Int(3));
    }
    #[test]
    fn eval_let_nested() {
        assert_eq!(
            eval("let a = 10; in let b = 20; in a + b"),
            VMValue::Int(30)
        );
    }
    #[test]
    fn eval_let_shadow() {
        assert_eq!(eval("let x = 1; in let x = 2; in x"), VMValue::Int(2));
    }
    #[test]
    fn eval_let_with_expression() {
        assert_eq!(eval("let x = 2 * 3; in x + 1"), VMValue::Int(7));
    }
    // -- Lists ----------------------------------------------------------
    #[test]
    fn eval_empty_list() {
        assert_eq!(eval("[]"), VMValue::List(vec![]));
    }
    #[test]
    fn eval_list() {
        assert_eq!(
            eval("[1 2 3]"),
            VMValue::List(vec![VMValue::Int(1), VMValue::Int(2), VMValue::Int(3)])
        );
    }
    #[test]
    fn eval_list_concat() {
        assert_eq!(
            eval("[1 2] ++ [3 4]"),
            VMValue::List(vec![
                VMValue::Int(1),
                VMValue::Int(2),
                VMValue::Int(3),
                VMValue::Int(4),
            ])
        );
    }
    #[test]
    fn eval_list_concat_with_inline_map() {
        // Regression: call_callable did not truncate the stack after
        // run_until, so map's per-element calls leaked values that
        // shifted the Concat operands on the stack.
        assert_eq!(
            eval("[1] ++ builtins.map (a: a) [2 3]"),
            VMValue::List(vec![VMValue::Int(1), VMValue::Int(2), VMValue::Int(3)])
        );
    }
    #[test]
    fn eval_list_concat_with_inline_map_attrsets() {
        // Same regression with attrset-producing map (the nixpkgs pattern).
        let result = eval(r#"[{ x = 1; }] ++ builtins.map (a: { v = a; }) ["a" "b"]"#);
        match result {
            VMValue::List(items) => assert_eq!(items.len(), 3),
            other => panic!("expected list, got {:?}", other.type_name()),
        }
    }
    #[test]
    fn eval_list_concat_with_inline_filter() {
        // Also verify filter (another higher-order builtin) with ++.
        assert_eq!(
            eval("[0] ++ builtins.filter (x: x > 1) [1 2 3]"),
            VMValue::List(vec![VMValue::Int(0), VMValue::Int(2), VMValue::Int(3)])
        );
    }
    #[test]
    fn eval_list_mixed() {
        assert_eq!(
            eval(r#"[1 "hello" true]"#),
            VMValue::List(vec![
                VMValue::Int(1),
                VMValue::String("hello".to_string()),
                VMValue::Bool(true),
            ])
        );
    }
    // -- Attribute sets -------------------------------------------------
    #[test]
    fn eval_empty_attrset() {
        assert_eq!(eval("{ }"), VMValue::Attrs(BTreeMap::new()));
    }
    #[test]
    fn eval_attrset() {
        let result = eval_full_helper("{ a = 1; b = 2; }");
        let mut expected = BTreeMap::new();
        expected.insert("a".to_string(), crate::StringKeyedValue::Int(1));
        expected.insert("b".to_string(), crate::StringKeyedValue::Int(2));
        assert_eq!(result, crate::StringKeyedValue::Attrs(expected));
    }
    #[test]
    fn eval_attrset_select() {
        assert_eq!(eval("{ a = 1; b = 2; }.a"), VMValue::Int(1));
    }
    #[test]
    fn eval_attrset_update() {
        let result = eval_full_helper("{ a = 1; } // { b = 2; }");
        let mut expected = BTreeMap::new();
        expected.insert("a".to_string(), crate::StringKeyedValue::Int(1));
        expected.insert("b".to_string(), crate::StringKeyedValue::Int(2));
        assert_eq!(result, crate::StringKeyedValue::Attrs(expected));
    }
    #[test]
    fn eval_attrset_update_override() {
        assert_eq!(eval("({ a = 1; } // { a = 2; }).a"), VMValue::Int(2));
    }
    #[test]
    fn eval_has_attr_true() {
        assert_eq!(eval("{ a = 1; } ? a"), VMValue::Bool(true));
    }
    #[test]
    fn eval_has_attr_false() {
        assert_eq!(eval("{ a = 1; } ? b"), VMValue::Bool(false));
    }
    #[test]
    fn eval_select_or_default() {
        assert_eq!(eval("{ a = 1; }.b or 0"), VMValue::Int(0));
        assert_eq!(eval("{ a = 1; }.a or 0"), VMValue::Int(1));
    }
    #[test]
    fn eval_dyn_select_or_default_missing() {
        // Dynamic key missing → returns default.
        assert_eq!(
            eval(r#"let x = "missing"; in { a = 1; }.${ x } or 99"#),
            VMValue::Int(99),
        );
    }
    #[test]
    fn eval_dyn_select_or_default_found() {
        // Dynamic key present → returns actual value.
        assert_eq!(
            eval(r#"let x = "a"; in { a = 42; }.${ x } or 99"#),
            VMValue::Int(42),
        );
    }
    #[test]
    fn eval_dyn_select_or_default_dotted_key() {
        // Key containing dots treated as single flat key, not nested path.
        assert_eq!(
            eval(r#"let x = "a.b"; in { "a.b" = 7; }.${ x } or 0"#),
            VMValue::Int(7),
        );
    }
    #[test]
    fn eval_dyn_select_or_default_special_chars() {
        // Key with dots and plus signs (nixpkgs armv8 CPU feature pattern).
        assert_eq!(
            eval(r#"let x = "armv8.3-a+crypto+sha2"; in { "armv8-a" = 1; }.${ x } or 0"#),
            VMValue::Int(0),
        );
    }
    #[test]
    fn eval_dyn_select_or_default_non_attrset() {
        // Base is not an attrset → returns default.
        assert_eq!(
            eval(r#"let x = "a"; base = 42; in base.${ x } or 99"#),
            VMValue::Int(99),
        );
    }
    // -- Lambdas / Apply ------------------------------------------------
    #[test]
    fn eval_identity_lambda() {
        assert_eq!(eval("(x: x) 42"), VMValue::Int(42));
    }
    #[test]
    fn eval_lambda_arithmetic() {
        assert_eq!(eval("(x: x + 1) 5"), VMValue::Int(6));
    }
    #[test]
    #[ignore = "requires upvalue capture (Phase 2)"]
    fn eval_curried_lambda() {
        assert_eq!(eval("(x: y: x + y) 3 4"), VMValue::Int(7));
    }
    #[test]
    fn eval_let_lambda() {
        assert_eq!(
            eval("let f = x: x * 2; in f 5"),
            VMValue::Int(10)
        );
    }
    #[test]
    fn eval_pattern_lambda() {
        assert_eq!(eval("({ a, b }: a + b) { a = 3; b = 4; }"), VMValue::Int(7));
    }
    #[test]
    fn eval_pattern_lambda_default() {
        assert_eq!(
            eval("({ a, b ? 10 }: a + b) { a = 5; }"),
            VMValue::Int(15)
        );
    }
    #[test]
    fn eval_lambda_with_let() {
        assert_eq!(
            eval("let inc = x: x + 1; double = x: x * 2; in double (inc 3)"),
            VMValue::Int(8)
        );
    }
    // -- Assert ---------------------------------------------------------
    #[test]
    fn eval_assert_pass() {
        assert_eq!(eval("assert true; 42"), VMValue::Int(42));
    }
    #[test]
    fn eval_assert_fail() {
        assert!(matches!(eval_err("assert false; 42"), VMError::AssertionFailed));
    }
    // -- Deep equality (thunk forcing) ----------------------------------
    #[test]
    fn deep_eq_attrs_with_thunked_values() {
        // Attrsets from let bindings have thunked values;
        // == must force them before comparison.
        assert_eq!(
            eval("let a = { x = 1; }; b = { x = 1; }; in a == b"),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn deep_eq_attrs_different_values() {
        assert_eq!(
            eval("let a = { x = 1; }; b = { x = 2; }; in a == b"),
            VMValue::Bool(false)
        );
    }
    #[test]
    fn deep_eq_nested_attrs() {
        assert_eq!(
            eval("let a = { x = { y = 1; }; }; b = { x = { y = 1; }; }; in a == b"),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn deep_eq_list_with_thunked_elements() {
        assert_eq!(
            eval("let a = [ 1 2 ]; b = [ 1 2 ]; in a == b"),
            VMValue::Bool(true)
        );
    }
    // -- builtins.elem (thunk forcing) ----------------------------------
    #[test]
    fn eval_elem_thunked_attrsets() {
        // elem must force list elements before comparison.
        assert_eq!(
            eval("let a = { x = 1; }; b = { x = 1; }; in builtins.elem a [ b ]"),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn eval_elem_basic_int() {
        assert_eq!(
            eval("builtins.elem 2 [ 1 2 3 ]"),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn eval_elem_missing() {
        assert_eq!(
            eval("builtins.elem 4 [ 1 2 3 ]"),
            VMValue::Bool(false)
        );
    }
    #[test]
    fn eval_elem_string() {
        assert_eq!(
            eval(r#"builtins.elem "b" [ "a" "b" "c" ]"#),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn eval_elem_thunked_list_elements() {
        assert_eq!(
            eval("let x = 1; in builtins.elem 1 [ x ]"),
            VMValue::Bool(true)
        );
    }
    // -- String interpolation -------------------------------------------
    #[test]
    fn eval_string_interpolation() {
        assert_eq!(
            eval(r#"let x = "world"; in "hello ${x}""#),
            VMValue::String("hello world".to_string()),
        );
    }
    #[test]
    #[ignore = "requires builtins.toString (Phase 2)"]
    fn eval_string_interpolation_int() {
        assert_eq!(
            eval(r#"let n = 42; in "value: ${toString n}""#),
            VMValue::String("value: 42".to_string()),
        );
    }
    // -- Path literals --------------------------------------------------
    #[test]
    fn eval_absolute_path() {
        assert_eq!(eval("/tmp/x"), VMValue::Path("/tmp/x".to_string()));
    }
    // -- Complex expressions --------------------------------------------
    #[test]
    fn eval_fibonacci_like() {
        assert_eq!(
            eval("let a = 1; b = 1; c = a + b; d = b + c; e = c + d; in e"),
            VMValue::Int(5)
        );
    }
    #[test]
    fn eval_nested_attrset_select() {
        assert_eq!(
            eval("{ a = { b = 42; }; }.a.b"),
            VMValue::Int(42)
        );
    }
    #[test]
    fn eval_let_with_attrset() {
        assert_eq!(
            eval("let set = { x = 10; y = 20; }; in set.x + set.y"),
            VMValue::Int(30)
        );
    }
    #[test]
    fn eval_conditional_attrset() {
        assert_eq!(
            eval("(if true then { a = 1; } else { a = 2; }).a"),
            VMValue::Int(1)
        );
    }
    // -- Builtin tests --------------------------------------------------
    #[test]
    fn builtin_length() {
        assert_eq!(eval("builtins.length [1 2 3]"), VMValue::Int(3));
    }
    #[test]
    fn builtin_length_empty() {
        assert_eq!(eval("builtins.length []"), VMValue::Int(0));
    }
    #[test]
    fn builtin_head() {
        assert_eq!(eval("builtins.head [10 20 30]"), VMValue::Int(10));
    }
    #[test]
    fn builtin_tail() {
        let result = eval_full_helper("builtins.tail [1 2 3]");
        assert_eq!(
            result,
            StringKeyedValue::List(vec![StringKeyedValue::Int(2), StringKeyedValue::Int(3)])
        );
    }
    #[test]
    fn builtin_type_of_int() {
        assert_eq!(
            eval("builtins.typeOf 42"),
            VMValue::String("int".to_string())
        );
    }
    #[test]
    fn builtin_type_of_string() {
        assert_eq!(
            eval("builtins.typeOf \"hello\""),
            VMValue::String("string".to_string())
        );
    }
    #[test]
    fn builtin_type_of_bool() {
        assert_eq!(
            eval("builtins.typeOf true"),
            VMValue::String("bool".to_string())
        );
    }
    #[test]
    fn builtin_type_of_null() {
        assert_eq!(
            eval("builtins.typeOf null"),
            VMValue::String("null".to_string())
        );
    }
    #[test]
    fn builtin_type_of_list() {
        assert_eq!(
            eval("builtins.typeOf [1 2]"),
            VMValue::String("list".to_string())
        );
    }
    #[test]
    fn builtin_type_of_set() {
        assert_eq!(
            eval("builtins.typeOf { a = 1; }"),
            VMValue::String("set".to_string())
        );
    }
    #[test]
    fn builtin_type_of_lambda() {
        assert_eq!(
            eval("builtins.typeOf (x: x)"),
            VMValue::String("lambda".to_string())
        );
    }
    #[test]
    fn builtin_is_int() {
        assert_eq!(eval("builtins.isInt 42"), VMValue::Bool(true));
        assert_eq!(
            eval("builtins.isInt \"hello\""),
            VMValue::Bool(false)
        );
    }
    #[test]
    fn builtin_is_string() {
        assert_eq!(eval("builtins.isString \"hi\""), VMValue::Bool(true));
        assert_eq!(eval("builtins.isString 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_is_list() {
        assert_eq!(eval("builtins.isList [1]"), VMValue::Bool(true));
        assert_eq!(eval("builtins.isList 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_is_attrs() {
        assert_eq!(
            eval("builtins.isAttrs { a = 1; }"),
            VMValue::Bool(true)
        );
        assert_eq!(eval("builtins.isAttrs 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_is_function() {
        assert_eq!(
            eval("builtins.isFunction (x: x)"),
            VMValue::Bool(true)
        );
        assert_eq!(eval("builtins.isFunction 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_is_bool() {
        assert_eq!(eval("builtins.isBool true"), VMValue::Bool(true));
        assert_eq!(eval("builtins.isBool 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_is_null() {
        assert_eq!(eval("builtins.isNull null"), VMValue::Bool(true));
        assert_eq!(eval("builtins.isNull 42"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_string_length() {
        assert_eq!(
            eval("builtins.stringLength \"hello\""),
            VMValue::Int(5)
        );
    }
    #[test]
    fn builtin_to_string_int() {
        assert_eq!(
            eval("builtins.toString 42"),
            VMValue::String("42".to_string())
        );
    }
    #[test]
    fn builtin_to_string_bool() {
        assert_eq!(
            eval("builtins.toString true"),
            VMValue::String("1".to_string())
        );
    }
    #[test]
    fn builtin_throw() {
        let result = eval_err("builtins.throw \"test error\"");
        assert!(matches!(result, VMError::Throw(_)));
    }
    #[test]
    fn builtin_abort() {
        let result = eval_err("builtins.abort \"fatal\"");
        assert!(matches!(result, VMError::Throw(_)));
    }
    #[test]
    fn builtin_add_curried() {
        assert_eq!(eval("builtins.add 3 4"), VMValue::Int(7));
    }
    #[test]
    fn builtin_sub_curried() {
        assert_eq!(eval("builtins.sub 10 3"), VMValue::Int(7));
    }
    #[test]
    fn builtin_mul_curried() {
        assert_eq!(eval("builtins.mul 6 7"), VMValue::Int(42));
    }
    #[test]
    fn builtin_div_curried() {
        assert_eq!(eval("builtins.div 42 6"), VMValue::Int(7));
    }
    #[test]
    fn builtin_elem_at() {
        assert_eq!(eval("builtins.elemAt [10 20 30] 1"), VMValue::Int(20));
    }
    #[test]
    fn builtin_elem() {
        assert_eq!(eval("builtins.elem 2 [1 2 3]"), VMValue::Bool(true));
        assert_eq!(eval("builtins.elem 5 [1 2 3]"), VMValue::Bool(false));
    }
    #[test]
    fn builtin_concat_lists() {
        let result = eval_full_helper("builtins.concatLists [[1 2] [3 4]]");
        assert_eq!(
            result,
            StringKeyedValue::List(vec![
                StringKeyedValue::Int(1),
                StringKeyedValue::Int(2),
                StringKeyedValue::Int(3),
                StringKeyedValue::Int(4),
            ])
        );
    }
    #[test]
    fn builtin_has_prefix() {
        assert_eq!(
            eval("builtins.hasPrefix \"he\" \"hello\""),
            VMValue::Bool(true)
        );
        assert_eq!(
            eval("builtins.hasPrefix \"wo\" \"hello\""),
            VMValue::Bool(false)
        );
    }
    #[test]
    fn builtin_has_suffix() {
        assert_eq!(
            eval("builtins.hasSuffix \"lo\" \"hello\""),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn builtin_concat_strings_sep() {
        assert_eq!(
            eval("builtins.concatStringsSep \", \" [\"a\" \"b\" \"c\"]"),
            VMValue::String("a, b, c".to_string())
        );
    }
    #[test]
    fn builtin_to_lower() {
        assert_eq!(
            eval("builtins.toLower \"Hello World\""),
            VMValue::String("hello world".to_string())
        );
    }
    #[test]
    fn builtin_to_upper() {
        assert_eq!(
            eval("builtins.toUpper \"hello\""),
            VMValue::String("HELLO".to_string())
        );
    }
    #[test]
    fn builtin_from_json() {
        assert_eq!(
            eval("builtins.fromJSON \"42\""),
            VMValue::Int(42)
        );
        assert_eq!(
            eval("builtins.fromJSON \"true\""),
            VMValue::Bool(true)
        );
    }
    #[test]
    fn builtin_seq() {
        assert_eq!(eval("builtins.seq 1 42"), VMValue::Int(42));
    }
    #[test]
    fn builtin_deep_seq() {
        assert_eq!(eval("builtins.deepSeq [1 2] 42"), VMValue::Int(42));
    }
    #[test]
    fn builtin_trace() {
        assert_eq!(
            eval("builtins.trace \"debug\" 42"),
            VMValue::Int(42)
        );
    }
    #[test]
    fn builtin_ceil_floor() {
        assert_eq!(eval("builtins.ceil 3.2"), VMValue::Int(4));
        assert_eq!(eval("builtins.floor 3.8"), VMValue::Int(3));
    }
    #[test]
    fn builtin_bit_ops() {
        assert_eq!(eval("builtins.bitAnd 12 10"), VMValue::Int(8));
        assert_eq!(eval("builtins.bitOr 12 10"), VMValue::Int(14));
        assert_eq!(eval("builtins.bitXor 12 10"), VMValue::Int(6));
    }
    #[test]
    fn builtin_intersect_attrs() {
        let result =
            eval_full_helper("builtins.intersectAttrs { a = 1; b = 2; } { a = 10; c = 30; }");
        match result {
            StringKeyedValue::Attrs(map) => {
                assert_eq!(map.get("a"), Some(&StringKeyedValue::Int(10)));
                assert!(!map.contains_key("b"));
                assert!(!map.contains_key("c"));
            }
            _ => panic!("expected Attrs, got {result:?}"),
        }
    }
    #[test]
    fn builtin_attr_values() {
        let result = eval_full_helper("builtins.attrValues { a = 1; b = 2; }");
        match result {
            StringKeyedValue::List(items) => {
                assert_eq!(items.len(), 2);
                assert!(items.contains(&StringKeyedValue::Int(1)));
                assert!(items.contains(&StringKeyedValue::Int(2)));
            }
            _ => panic!("expected List, got {result:?}"),
        }
    }
    #[test]
    fn builtin_to_int() {
        assert_eq!(eval("builtins.toInt \"42\""), VMValue::Int(42));
    }
    #[test]
    fn builtin_replace_strings() {
        assert_eq!(
            eval("builtins.replaceStrings [\"o\"] [\"0\"] \"foo\""),
            VMValue::String("f00".to_string())
        );
    }
    #[test]
    fn builtin_substring() {
        assert_eq!(
            eval("builtins.substring 1 3 \"hello\""),
            VMValue::String("ell".to_string())
        );
    }
    // -- Import tests ---------------------------------------------------
    #[test]
    fn import_basic() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test.nix");
        std::fs::write(&file_path, "42").unwrap();
        let nix_expr = format!("import {}", file_path.display());
        assert_eq!(eval(&nix_expr), VMValue::Int(42));
    }
    #[test]
    fn import_cached() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("cached.nix");
        std::fs::write(&file_path, "{ x = 1; }").unwrap();
        let nix_expr = format!(
            "let a = import {}; b = import {}; in a == b",
            file_path.display(),
            file_path.display()
        );
        assert_eq!(eval(&nix_expr), VMValue::Bool(true));
    }
    #[test]
    fn import_attrset() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("attrs.nix");
        std::fs::write(&file_path, "{ greeting = \"hello\"; }").unwrap();
        let nix_expr = format!("(import {}).greeting", file_path.display());
        assert_eq!(eval(&nix_expr), VMValue::String("hello".to_string()));
    }
    #[test]
    fn import_directory_default_nix() {
        // Importing a directory should resolve to <dir>/default.nix
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("mylib");
        std::fs::create_dir(&sub).unwrap();
        std::fs::write(sub.join("default.nix"), "{ x = 42; }").unwrap();
        let nix_expr = format!("(import {}).x", sub.display());
        assert_eq!(eval(&nix_expr), VMValue::Int(42));
    }
    #[test]
    fn import_directory_cached() {
        // Importing the same directory twice should hit the cache.
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("lib");
        std::fs::create_dir(&sub).unwrap();
        std::fs::write(sub.join("default.nix"), "{ v = 99; }").unwrap();
        let nix_expr = format!(
            "let a = import {}; b = import {}; in a == b",
            sub.display(),
            sub.display()
        );
        assert_eq!(eval(&nix_expr), VMValue::Bool(true));
    }
    #[test]
    fn import_directory_nested() {
        // Nested directory imports: lib/default.nix imports sub/default.nix
        let dir = tempfile::tempdir().unwrap();
        let lib = dir.path().join("lib");
        let sub = lib.join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join("default.nix"), "{ val = 7; }").unwrap();
        std::fs::write(
            lib.join("default.nix"),
            &format!("(import {}).val + 3", sub.display()),
        )
        .unwrap();
        let nix_expr = format!("import {}", lib.display());
        assert_eq!(eval(&nix_expr), VMValue::Int(10));
    }
    // -- Lazy evaluation tests ------------------------------------------
    #[test]
    fn lazy_unused_throw_in_attrset() {
        assert_eq!(
            eval("let s = { a = 1; }; in s.a"),
            VMValue::Int(1)
        );
    }
    #[test]
    fn lazy_unused_let_binding() {
        assert_eq!(eval("let x = 1; y = 2; in x"), VMValue::Int(1));
    }
    // -- Import handler tests -------------------------------------------
    #[test]
    fn import_forces_thunk_before_type_check() {
        // The import path is a thunk (non-trivial let binding); the VM
        // must force it to a path/string before checking the type.
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("forced.nix");
        std::fs::write(&file_path, "99").unwrap();
        let nix_expr = format!(
            "let p = {}; in import p",
            file_path.display()
        );
        assert_eq!(eval(&nix_expr), VMValue::Int(99));
    }
    #[test]
    fn import_with_path_value_succeeds() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("pathval.nix");
        std::fs::write(&file_path, "\"from-path\"").unwrap();
        let nix_expr = format!("import {}", file_path.display());
        assert_eq!(
            eval(&nix_expr),
            VMValue::String("from-path".to_string())
        );
    }
    #[test]
    fn import_with_string_value_succeeds() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("strval.nix");
        std::fs::write(&file_path, "\"from-string\"").unwrap();
        let nix_expr = format!(
            "let s = \"{}\"; in import s",
            file_path.display()
        );
        assert_eq!(
            eval(&nix_expr),
            VMValue::String("from-string".to_string())
        );
    }
    // -- TailCall opcode tests ------------------------------------------
    #[test]
    fn tail_call_deep_recursion_via_import() {
        // Test deep tail-recursive calls via import (self-referencing let
        // requires open upvalues, not yet implemented). Writing a recursive
        // function to a file and importing it exercises TailCall.
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("countdown.nix");
        std::fs::write(
            &file_path,
            "{ f, n }: if n == 0 then 0 else f { inherit f; n = n - 1; }",
        )
        .unwrap();
        // Use fixpoint pattern: pass function as argument to avoid
        // self-referencing let bindings.
        let nix_expr = format!(
            "let g = import {}; in g {{ f = g; n = 2000; }}",
            file_path.display()
        );
        assert_eq!(eval(&nix_expr), VMValue::Int(0));
    }
    #[test]
    fn tail_call_simple_lambda_chain() {
        // Non-recursive tail call: the last call in a lambda body should
        // reuse the frame. This verifies TailCall opcode is emitted and
        // executed for simple function composition.
        assert_eq!(
            eval("let g = x: x + 1; f = x: g x; in f 41"),
            VMValue::Int(42)
        );
    }
    #[test]
    fn tail_call_if_branches() {
        // Both if-then and if-else branches should produce tail calls
        // when in lambda body. This verifies TailCall works in both branches.
        assert_eq!(
            eval("let f = x: if x > 0 then x else x + 1; in f 10"),
            VMValue::Int(10)
        );
        assert_eq!(
            eval("let f = x: if x > 0 then x else x + 1; in f 0"),
            VMValue::Int(1)
        );
    }
    // -- Builtin dispatch tests -----------------------------------------
    #[test]
    fn builtin_get_env_returns_value() {
        // Set a known env var and verify getEnv returns it.
        // SAFETY: test runs single-threaded; no concurrent env access.
        unsafe { std::env::set_var("SUI_TEST_VAR", "hello_sui") };
        assert_eq!(
            eval("builtins.getEnv \"SUI_TEST_VAR\""),
            VMValue::String("hello_sui".to_string())
        );
        unsafe { std::env::remove_var("SUI_TEST_VAR") };
    }
    #[test]
    fn builtin_get_env_missing_returns_empty() {
        // getEnv with a missing var should return "".
        // SAFETY: test runs single-threaded; no concurrent env access.
        unsafe { std::env::remove_var("SUI_NONEXISTENT_VAR_12345") };
        assert_eq!(
            eval("builtins.getEnv \"SUI_NONEXISTENT_VAR_12345\""),
            VMValue::String(String::new())
        );
    }
    #[test]
    fn builtin_try_eval_success() {
        // tryEval with a successful expression returns { success=true; value=result; }.
        let result = eval_full_helper("builtins.tryEval 42");
        match result {
            StringKeyedValue::Attrs(map) => {
                assert_eq!(
                    map.get("success"),
                    Some(&StringKeyedValue::Bool(true))
                );
                assert_eq!(
                    map.get("value"),
                    Some(&StringKeyedValue::Int(42))
                );
            }
            _ => panic!("expected Attrs, got {result:?}"),
        }
    }
    #[test]
    fn builtin_try_eval_with_non_throwing_expr() {
        // tryEval wraps a non-throwing expression — still produces
        // { success = true; value = ...; }.
        let result = eval_full_helper(
            "builtins.tryEval (1 + 2)"
        );
        match result {
            StringKeyedValue::Attrs(map) => {
                assert_eq!(
                    map.get("success"),
                    Some(&StringKeyedValue::Bool(true))
                );
                assert_eq!(
                    map.get("value"),
                    Some(&StringKeyedValue::Int(3))
                );
            }
            _ => panic!("expected Attrs, got {result:?}"),
        }
    }
    #[test]
    fn builtin_try_eval_with_throw_catches() {
        // tryEval CATCHES a throwing expression (nix parity):
        // `{ success = false; value = false; }` — verified byte-identical
        // to cppnix (`nix eval --json` returns the same). The VM previously
        // PROPAGATED the throw (an open-upvalue dispatch limitation); that
        // is now fixed, so this test pins the correct catching behavior.
        let result = eval_full_helper(
            "let bad = builtins.throw \"oops\"; in builtins.tryEval bad"
        );
        match result {
            StringKeyedValue::Attrs(map) => {
                assert_eq!(
                    map.get("success"),
                    Some(&StringKeyedValue::Bool(false))
                );
                assert_eq!(
                    map.get("value"),
                    Some(&StringKeyedValue::Bool(false))
                );
            }
            _ => panic!("expected Attrs, got {result:?}"),
        }
    }
    // -- Regression: stack_depth tracking for branches -------------------
    #[test]
    fn if_else_in_let_body_stack_depth() {
        // If/else inside a let body should not corrupt stack_depth for
        // subsequent let bindings in an outer scope.
        assert_eq!(
            eval("let a = 1; in if a == 1 then 10 else 20"),
            VMValue::Int(10),
        );
    }
    #[test]
    fn nested_let_with_if_else() {
        // Inner let after an if/else: the if/else must not drift stack_depth.
        assert_eq!(
            eval(r#"
                let
                  a = 1;
                  b = if a == 1 then 2 else 3;
                in
                  let c = b + 10; in c
            "#),
            VMValue::Int(12),
        );
    }
    #[test]
    fn short_circuit_and_in_let_body() {
        // Short-circuit && inside a let body must track stack_depth correctly.
        assert_eq!(
            eval("let x = true; in x && false"),
            VMValue::Bool(false),
        );
    }
    #[test]
    fn short_circuit_or_in_let_body() {
        assert_eq!(
            eval("let x = false; in x || true"),
            VMValue::Bool(true),
        );
    }
    #[test]
    fn short_circuit_implication_in_let_body() {
        // a -> b is !a || b. false -> anything is true.
        assert_eq!(
            eval("let x = false; in x -> 42"),
            VMValue::Bool(true),
        );
    }
    #[test]
    fn inherit_from_in_attrset_stack_depth() {
        // inherit (source) in non-rec attrset must track stack_depth for
        // MakeThunk. This was the missing `stack_depth += 1` bug.
        assert_eq!(
            eval(r#"
                let
                  src = { a = 1; b = 2; };
                  result = { inherit (src) a b; c = 3; };
                in result.a + result.b + result.c
            "#),
            VMValue::Int(6),
        );
    }
    #[test]
    fn inherit_from_many_fields_stack_depth() {
        // Multiple inherit-from fields: each one was missing +1,
        // so stack_depth would drift further with each field.
        assert_eq!(
            eval(r#"
                let
                  s = { w = 1; x = 2; y = 3; z = 4; };
                  r = { inherit (s) w x y z; extra = 10; };
                in r.w + r.x + r.y + r.z + r.extra
            "#),
            VMValue::Int(20),
        );
    }
    #[test]
    fn if_else_followed_by_let_binding() {
        // The if/else result is used in a subsequent let binding.
        // Before the fix, the stack_depth drift from if/else would cause
        // the next binding's slot to be off.
        assert_eq!(
            eval(r#"
                let
                  a = 1;
                  b = 2;
                  c = 3;
                in
                  let
                    x = if a == 1 then b else c;
                    y = x + 100;
                  in y
            "#),
            VMValue::Int(102),
        );
    }
    #[test]
    fn multi_segment_hasattr_stack_depth() {
        // Multi-segment hasattr with short-circuit jumps must track
        // stack_depth correctly at branch merge points.
        assert_eq!(
            eval(r#"
                let
                  s = { a = { b = 1; }; };
                  has = s ? a.b;
                  val = if has then 42 else 0;
                in val
            "#),
            VMValue::Int(42),
        );
    }
    #[test]
    fn many_let_bindings_with_if_else() {
        // Stress test: many let bindings where some RHS contain if/else.
        // Before the stack_depth fix, the drift would accumulate and
        // eventually cause a GetLocal slot mismatch.
        assert_eq!(
            eval(r#"
                let
                  a = 1;
                  b = 2;
                  c = 3;
                  d = 4;
                  e = 5;
                  f = 6;
                  g = 7;
                  h = 8;
                  i = 9;
                  j = 10;
                in
                  let
                    x = if a == 1 then b else c;
                    y = if d == 4 then e else f;
                    z = if g == 7 then h else i;
                    w = j;
                  in x + y + z + w
            "#),
            VMValue::Int(25),
        );
    }
    #[test]
    fn import_in_pattern_default_stack_depth() {
        // The Import opcode is net 0 on the stack (pop path, push result).
        // Before the fix, it was tracked as +1, causing stack_depth drift
        // in pattern default expressions like `{ stdenvStages ? import ../stdenv, ... }`.
        // This test uses a pattern lambda with a default that involves a
        // function call (which compiles similarly to import + call).
        assert_eq!(
            eval(r#"
                let
                  f = { a ? 1, b ? 2, c ? 3 }:
                    a + b + c;
                in f {}
            "#),
            VMValue::Int(6),
        );
    }
    #[test]
    fn pattern_lambda_many_defaults_then_let() {
        // Pattern lambda with many defaults followed by let bindings.
        // This is the pattern that triggered the original nixpkgs bug:
        // { a, b ? x, c ? y, ... }: let ... in expr
        // The import stack_depth bug caused slots to drift by 1 for each
        // default expression that used import.
        assert_eq!(
            eval(r#"
                let
                  mk = { a, b ? 10, c ? 20, d ? 30, e ? 40 }:
                    let
                      sum = a + b + c + d + e;
                      doubled = sum + sum;
                    in doubled;
                in mk { a = 1; }
            "#),
            VMValue::Int(202),
        );
    }
    // -- Blocker #13: dotted attrs + lambda closure in rec ------------------
    #[test]
    fn rec_dotted_lambda_captures_sibling() {
        // Lambdas in rec attrsets must not be compiled as trivial values,
        // because MakeClosure captures upvalues eagerly.  Dotted entries
        // are appended after non-dotted bindings, so a lambda's upvalue
        // for a dotted sibling would see the null placeholder.
        let result = eval_full_helper(
            r#"rec { types.a = 1; types.b = 2; f = _: types; }.f 0"#,
        );
        match result {
            StringKeyedValue::Attrs(ref m) => {
                assert_eq!(m.get("a"), Some(&StringKeyedValue::Int(1)));
                assert_eq!(m.get("b"), Some(&StringKeyedValue::Int(2)));
            }
            other => panic!("expected attrset, got {other:?}"),
        }
    }
    #[test]
    fn rec_dotted_lambda_attr_select() {
        // Lambda body selects an attribute from a dotted sibling.
        assert_eq!(
            eval(r#"rec { types.a = 1; types.b = 2; f = x: types.b; result = f 0; }.result"#),
            VMValue::Int(2),
        );
    }
    #[test]
    fn rec_dotted_lambda_assert_check() {
        // Pattern from nixpkgs parse.nix: `mkSystem` uses
        //   assert types.parsedPlatform.check components; ...
        // which requires `types` to be resolved inside a lambda body.
        assert_eq!(
            eval(r#"
                rec {
                    types.parsedPlatform = { check = _: true; };
                    mkSystem = components:
                        assert types.parsedPlatform.check components;
                        components;
                    result = mkSystem 42;
                }.result
            "#),
            VMValue::Int(42),
        );
    }
    #[test]
    fn let_lambda_captures_rec_sibling() {
        // Let bindings are recursive — lambdas capturing siblings must
        // also use deferred thunks.
        assert_eq!(
            eval(r#"let a = 1 + 1; f = _: a; in f 0"#),
            VMValue::Int(2),
        );
    }
    #[test]
    fn rec_dotted_multiple_lambdas() {
        // Multiple lambdas capturing different dotted siblings.
        assert_eq!(
            eval(r#"
                rec {
                    a.x = 10;
                    b.y = 20;
                    f = _: a.x + b.y;
                    result = f 0;
                }.result
            "#),
            VMValue::Int(30),
        );
    }
}