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
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
//! Bytecode VM execution.
//!
//! The stack-based dispatch loop executes a validated [`Chunk`] produced by
//! [`crate::compile`] and preserves the observable behavior of the
//! tree-walking evaluator in `nybl-lang`. The public surface includes
//! one-shot [`run`] / [`execute`] calls, the lower-level [`Vm`], and
//! persistent [`NyblInstance`] programs.
//!
//! # Stack model
//!
//! All runtime values live on a single internal slot stack. A slot is
//! either a [`Value`], an in-progress `for`-loop iterator, or an
//! in-progress `repeat` counter. Iterators and counters are sidecar
//! items pushed by [`Instr::MakeIter`] / [`Instr::MakeRepeatCount`]
//! and consumed by [`Instr::IterNext`] / [`Instr::RepeatNext`] on
//! exhaustion or [`Instr::PopLoopState`] on `break`; only bytecode that
//! participates in iteration ever sees them, so the rest of the dispatch
//! loop treats the stack as a stack of `Value`.
//!
//! # Frames
//!
//! Each function call — including the top-level program — runs in its
//! own internal frame. A frame owns its chunk (wrapped in `Rc` so repeated
//! calls share the compiled code), its instruction pointer, and its
//! lexical scope stack. Returning from a function pops the frame and
//! truncates the value stack back to the frame's base in case the body
//! left anything behind.
//!
//! # Resource limits
//!
//! [`NyblLimits`] is enforced exactly as in the tree-walker:
//!
//! - A tick fires at every bytecode dispatch. It bumps `steps`,
//! checks `max_steps`, checks its explicit
//! [`nybl::memory::MemoryContext`],
//! and invokes [`NyblHost::on_tick`]. `max_memory` is shared with the
//! tree-walker via the per-value allocation tracking in
//! [`nybl::memory`], so no VM-specific bookkeeping is needed.
//! - The VM scales `max_steps` internally so a single
//! source-level step, which typically maps to several bytecode ops,
//! still fits under the tree-walker's calibration of
//! `NyblLimits::standard()` / `NyblLimits::demo()`.
#[cfg(all(feature = "no_std", not(feature = "std")))]
use alloc::{
format,
rc::Rc,
string::{String, ToString},
vec,
vec::Vec,
};
#[cfg(any(feature = "std", not(feature = "no_std")))]
use std::rc::Rc;
use core::cell::{Cell, RefCell};
#[cfg(all(feature = "no_std", not(feature = "std")))]
use alloc::collections::{BTreeMap, BTreeSet};
#[cfg(any(feature = "std", not(feature = "no_std")))]
use std::collections::{BTreeMap, BTreeSet};
use nybl::builtins::{self, error, error_fatal_with_hint, error_with_hint};
use nybl::error::{NyblError, NyblWarning};
use nybl::methods;
use nybl::ops;
use nybl::parser::{ParamMode, Visibility};
use nybl::value::{FnBody, NyblFn, NyblFnOrigin, Value};
use nybl::{EntryPoint, NyblHost, NyblLimits};
use crate::chunk::{
CallSiteIdx, CaptureSource, Chunk, CodeOffset, Constant, EnumConstructShape, EnumIdx,
EnumVariantShape, FnDef, FnIdx, Instr, InterpPart, LoopStateKind, NameIdx, NamespaceRef,
PatternIdx, PlaceIdx, PlaceProjectionRecipe, RefArgTarget, SlotIdx, StructIdx,
};
/// Hard cap on call depth; matches the tree-walker.
const MAX_CALL_DEPTH: usize = 64;
/// `max_steps` is a source-level budget. One source-level statement
/// typically maps to several bytecode instructions, so the dispatch
/// loop gets a proportionally larger internal budget. Calibrated so
/// that `while true { }` still halts under `NyblLimits::demo()` and
/// small programs like fizzbuzz don't exhaust `standard()`.
const STEP_SCALE: u64 = 8;
/// Memory-limit check cadence. Checked every `1 << N` ticks; a
/// power-of-two window lets us AND with a mask instead of
/// dividing. 256 is a sweet spot — detection still lands within
/// microseconds of the limit being breached, and a tight
/// arithmetic loop reads the explicit account once per 256 instructions
/// instead of every instruction.
const TICK_MEMCHECK_MASK: u64 = 0xFF;
/// Maximum slot vecs kept on the freelist. Deep recursion with
/// varying slot counts could otherwise grow this unboundedly.
/// `MAX_CALL_DEPTH` (64) plus a little headroom is plenty — any
/// extra allocations just go back through the global allocator
/// like before.
const SLOTS_FREELIST_CAP: usize = 128;
// ─── Stack slot ────────────────────────────────────────────────────
enum Slot {
Value(Value),
/// Remaining items in reverse order — `pop()` yields the next one.
/// Eager fast path for `for x in <array | string | dict>`.
Iter(Vec<Value>),
/// Iterator protocol state: holds a value whose `.next()`
/// method returns `Iter::Next(v)` / `Iter::Done`. Produced
/// when the for-loop's iterable is a `Value::Iter` or a
/// user type; the `IterNext` opcode dispatches `.next()`
/// through the regular method path.
IterObject(Value),
/// Remaining iterations for a `repeat` loop.
Repeat(i64),
}
// ─── Frame ─────────────────────────────────────────────────────────
struct FrameScopeBases {
types: usize,
aliases: usize,
}
struct FunctionFrameContext {
scope_bases: FrameScopeBases,
function_module: Option<String>,
lexical_context: Rc<ModuleLexicalContext>,
}
struct Frame {
chunk: Rc<Chunk>,
ip: usize,
/// Flat slot array for this function's compile-time-resolved
/// locals (params + every `let` / `for-in` variable assigned
/// a slot). `LoadLocal(slot)` / `StoreLocal(slot)` read and
/// write directly into this vec — the VM's hot path for
/// variable access. Empty for module-top-level frames and
/// match-body sub-scopes where slot resolution doesn't apply.
slots: Vec<Value>,
/// Slow-path BTreeMap scope stack. Used for module-top-level
/// bindings, match-pattern bindings, captures snapshotted
/// into lambdas, and anything else that reaches `LoadVar` /
/// `DefineLocal` / `StoreVar`. Function frames that stay on
/// the fast path never push into this at runtime.
scopes: Vec<BTreeMap<String, Value>>,
/// Number of value scopes owned by the frame at entry. `PopScope`
/// may only remove scopes above this floor: the top-level frame and
/// closures retain their initial scope, while named-function and method
/// frames start at zero.
scope_base: usize,
/// Lazily inserted protected value scope for assignments that shadow an
/// inherited declaration alias. It lives for the whole call even when
/// the assignment occurs inside a nested runtime scope.
has_declaration_overlay: bool,
/// Protected depth of the VM-wide `type_bindings` stack at frame entry.
/// Runtime scopes live above this depth and are paired with `scopes`.
/// Function exit truncates back to the caller depth so an early return
/// cannot leak type scopes whose `PopScope` was skipped.
type_scope_base: usize,
/// Protected depth of the VM-wide module-alias/imported-callable stacks at
/// frame entry. Function lookup sees frame zero plus frames at/above it.
alias_scope_base: usize,
stack_base: usize,
is_function: bool,
/// Defining module for named-function and module-exported closure bodies.
/// Used to resolve private sibling function bindings from the module cache.
function_module: Option<String>,
/// Immutable defining-module namespace shared by every call to this
/// function. Mutable block/function-local declarations remain in the VM
/// stacks above `alias_scope_base`.
lexical_context: Rc<ModuleLexicalContext>,
/// How this frame's return value should be transformed
/// before being pushed for the caller. See [`FrameWrap`].
wrap: FrameWrap,
defining_environment_module: Option<String>,
/// Names copied into this closure from an enclosing frame. They remain
/// readable values but are never legal explicit `ref` targets.
captured_names: BTreeSet<String>,
/// Calls whose callee and static fences have passed preflight while their
/// ordinary argument expressions are still being evaluated.
prepared_calls: Vec<PreparedCall>,
/// Copy-out records owned by this invocation. They are committed only by
/// the normal-return path and are otherwise dropped during unwind.
pending_write_backs: Vec<PendingWriteBack>,
/// Exact declaration invoked for a direct named-function frame. Bare
/// self-recursion resolves here before host/name dispatch.
current_function_entry: Option<Rc<FnEntry>>,
}
impl Frame {
fn top(chunk: Chunk, lexical_context: Rc<ModuleLexicalContext>) -> Self {
let scopes = vec![BTreeMap::new()];
Self {
chunk: Rc::new(chunk),
ip: 0,
slots: Vec::new(),
scope_base: scopes.len(),
has_declaration_overlay: false,
scopes,
// The builtin type-binding map is the top frame's protected base.
type_scope_base: 1,
alias_scope_base: 1,
stack_base: 0,
is_function: false,
function_module: None,
lexical_context,
wrap: FrameWrap::None,
defining_environment_module: None,
captured_names: BTreeSet::new(),
prepared_calls: Vec::new(),
pending_write_backs: Vec::new(),
current_function_entry: None,
}
}
fn function(
chunk: Rc<Chunk>,
slots: Vec<Value>,
scopes: Vec<BTreeMap<String, Value>>,
stack_base: usize,
context: FunctionFrameContext,
wrap: FrameWrap,
) -> Self {
Self {
chunk,
ip: 0,
slots,
scope_base: scopes.len(),
has_declaration_overlay: false,
scopes,
type_scope_base: context.scope_bases.types,
alias_scope_base: context.scope_bases.aliases,
stack_base,
is_function: true,
function_module: context.function_module,
lexical_context: context.lexical_context,
wrap,
defining_environment_module: None,
captured_names: BTreeSet::new(),
prepared_calls: Vec::new(),
pending_write_backs: Vec::new(),
current_function_entry: None,
}
}
fn caller_type_scope_depth(&self) -> usize {
if self.is_function {
self.type_scope_base.saturating_sub(1)
} else {
self.type_scope_base
}
}
}
/// Post-processing applied to a frame's return value / error at
/// the moment it resumes the caller. Most frames don't need
/// any — only callable-dispatch helpers (`try_call`, Result's
/// `map` / `map_err`) set this so the engine can wrap the
/// closure's bare return value without the user having to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FrameWrap {
/// Plain return — push the value as-is.
None,
/// `try_call(f)` landing pad: wrap a clean return in
/// `Result::Ok(v)`; a non-fatal error unwinds to this frame
/// and pushes `Result::Err(RuntimeError { … })` instead.
/// Fatal errors still bypass the trap — see
/// `NyblError::is_fatal`.
TryCall { line: u32 },
/// `r.map(f)` landing pad: wrap the clean return in
/// `Result::Ok(v)`. Errors in `f` propagate unchanged.
ResultOk { line: u32 },
/// `r.map_err(f)` landing pad: wrap the clean return in
/// `Result::Err(v)`. Errors in `f` propagate unchanged.
ResultErr { line: u32 },
/// `MakeIter` landing pad for user-typed iterables: the
/// frame ran the user's `.iter()` method; its return value
/// should become a `Slot::IterObject` on the caller's
/// stack instead of the usual `Slot::Value`.
IterStart,
/// `IterNext` landing pad for user-typed iterators: the
/// frame ran the user's `.next()` method. Inspect the
/// return (expected `Iter::Next(x)` / `Iter::Done`) and
/// either push `x` (so the subsequent slot store picks it
/// up) or pop the iterator and jump to the exit target.
IterAdvance(crate::chunk::CodeOffset),
}
/// Destructured view of a value returned from an iterator's
/// `.next()` method — either `Iter::Next(v)`, `Iter::Done`, or
/// anything else (user bug, surfaced as a runtime error).
enum IterStep {
Next(Value),
Done,
Malformed,
}
fn unwrap_iter_step(v: &Value) -> IterStep {
let e = match v {
Value::EnumVariant(e) => e,
_ => return IterStep::Malformed,
};
if e.type_name() != "Iter" {
return IterStep::Malformed;
}
match (e.variant(), e.payload()) {
("Next", nybl::value::EnumPayload::Tuple(items)) if items.len() == 1 => {
IterStep::Next(items[0].clone())
}
("Done", nybl::value::EnumPayload::Unit) => IterStep::Done,
_ => IterStep::Malformed,
}
}
struct FnEntry {
exact_self_name: Option<String>,
params: Vec<String>,
param_modes: Vec<ParamMode>,
chunk: Rc<Chunk>,
module_path: String,
declaration_alias_names: BTreeSet<String>,
}
enum PreparedCallable {
User(Rc<FnEntry>),
/// Value-only named declarations retain the language's established
/// host-before-user-function dispatch. Ref-aware declarations stay
/// `User` so their mode metadata can drive transactional staging.
HostThenUser {
name: String,
entry: Rc<FnEntry>,
},
Closure(Rc<NyblFn>),
UserMethod {
entry: Rc<FnEntry>,
receiver: Value,
receiver_target: Option<NamespaceRef>,
receiver_place: Option<ResolvedPlace>,
},
DeferredMethod {
receiver: Value,
method: String,
nested_place: bool,
},
NamedMethodInPlace {
target: NamespaceRef,
method: String,
},
PlaceMethodInPlace {
place: ResolvedPlace,
method: String,
},
/// Builtins and host callables are value-only. Host arity is intentionally
/// deferred because the embedding trait does not expose signature metadata.
NamedFallback(String),
}
impl PreparedCallable {
fn named_user(name: &str, entry: Rc<FnEntry>) -> Self {
if entry.param_modes.iter().all(|mode| *mode != ParamMode::Ref) {
Self::HostThenUser {
name: name.to_string(),
entry,
}
} else {
Self::User(entry)
}
}
}
#[derive(Clone, PartialEq, Eq)]
enum ResolvedRefTarget {
Slot {
frame: usize,
slot: SlotIdx,
},
Scope {
frame: usize,
scope: usize,
name: String,
},
}
#[derive(Clone)]
enum ResolvedPlaceProjection {
Index(Value),
Field(String),
}
#[derive(Clone)]
struct ResolvedPlace {
target: ResolvedRefTarget,
root_recipe: NamespaceRef,
root_name: String,
root: Value,
projections: Vec<ResolvedPlaceProjection>,
}
struct PreparedRef {
param: usize,
recipe: RefArgTarget,
index_count: usize,
}
enum PreparedReceiverRef {
Binding(NamespaceRef),
Place(ResolvedPlace),
}
struct PreparedCall {
site: CallSiteIdx,
callable: PreparedCallable,
display_name: String,
refs: Vec<PreparedRef>,
receiver_ref: Option<PreparedReceiverRef>,
value_count: usize,
ref_index_count: usize,
}
struct PendingWriteBack {
parameter: usize,
place: ResolvedPlace,
}
/// Structural equality check for two enum-variant lists.
/// Used when the same module is resolved via two paths so a
/// re-import is idempotent rather than an error.
///
/// Matches the walker's `variants_equivalent` rule: variant
/// order + names must match, tuple variants compare by arity
/// only (payload names are positional stubs with no runtime
/// meaning), struct variants still require matching field
/// names.
fn shapes_match(a: &[(String, EnumVariantShape)], b: &[(String, EnumVariantShape)]) -> bool {
if a.len() != b.len() {
return false;
}
a.iter().zip(b.iter()).all(|((an, av), (bn, bv))| {
if an != bn {
return false;
}
match (av, bv) {
(EnumVariantShape::Unit, EnumVariantShape::Unit) => true,
(EnumVariantShape::Tuple(fa), EnumVariantShape::Tuple(fb)) => fa.len() == fb.len(),
(EnumVariantShape::Struct(fa), EnumVariantShape::Struct(fb)) => fa == fb,
_ => false,
}
})
}
type TypeKey = (String, String);
type RuntimeEnumVariants = Vec<(String, EnumVariantShape)>;
type StructTypeTable = BTreeMap<TypeKey, Vec<String>>;
type EnumTypeTable = BTreeMap<TypeKey, RuntimeEnumVariants>;
type BuiltinTypeTables = (StructTypeTable, EnumTypeTable, BTreeMap<String, String>);
type ModuleStructDef = (TypeKey, Vec<String>);
type ModuleEnumDef = (TypeKey, RuntimeEnumVariants);
type ModuleMethodDef = (TypeKey, String, Rc<FnEntry>);
/// Seed a VM's type tables with the engine-wide builtin shapes
/// (`Result`, `RuntimeError`). Same source of truth as the walker
/// — both engines read `nybl::builtins::builtin_*` so they can
/// never drift out of sync.
///
/// Returns:
/// - `struct_defs` keyed by `(module_path, type_name)`, with the
/// builtin entry under `<builtin>`;
/// - `enum_defs` keyed the same way;
/// - an outer-scope type_bindings map pointing each builtin's
/// bare name at `<builtin>` so user code resolves `Result::Ok`
/// without an explicit `use`.
fn seed_builtin_types() -> BuiltinTypeTables {
use nybl::parser::VariantKind;
let builtin_mp = nybl::value::BUILTIN_MODULE_PATH.to_string();
let mut struct_defs: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
let mut enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>> =
BTreeMap::new();
let mut bindings: BTreeMap<String, String> = BTreeMap::new();
struct_defs.insert(
(builtin_mp.clone(), String::from("RuntimeError")),
nybl::builtins::builtin_runtime_error_fields(),
);
bindings.insert(String::from("RuntimeError"), builtin_mp.clone());
let variants: Vec<(String, EnumVariantShape)> = nybl::builtins::builtin_result_variants()
.into_iter()
.map(|v| {
let shape = match v.kind {
VariantKind::Unit => EnumVariantShape::Unit,
VariantKind::Tuple(fs) => EnumVariantShape::Tuple(fs),
VariantKind::Struct(fs) => EnumVariantShape::Struct(fs),
};
(v.name, shape)
})
.collect();
enum_defs.insert((builtin_mp.clone(), String::from("Result")), variants);
bindings.insert(String::from("Result"), builtin_mp.clone());
let iter_variants: Vec<(String, EnumVariantShape)> = nybl::builtins::builtin_iter_variants()
.into_iter()
.map(|v| {
let shape = match v.kind {
VariantKind::Unit => EnumVariantShape::Unit,
VariantKind::Tuple(fs) => EnumVariantShape::Tuple(fs),
VariantKind::Struct(fs) => EnumVariantShape::Struct(fs),
};
(v.name, shape)
})
.collect();
enum_defs.insert((builtin_mp.clone(), String::from("Iter")), iter_variants);
bindings.insert(String::from("Iter"), builtin_mp);
(struct_defs, enum_defs, bindings)
}
/// Cached result of loading a module. `Loading` is the
/// in-progress sentinel for circular-import detection; `Loaded`
/// carries every top-level export — bindings, struct/enum
/// decls, and methods — so the importer can rebuild the
/// module's visible surface without re-evaluating it.
#[allow(clippy::large_enum_variant)]
enum ImportSlot {
Loading,
Loaded(ModuleArtifacts),
}
#[derive(Clone)]
struct ModuleArtifacts {
/// Whether the module opted into an explicit `pub { ... }` allow-list.
/// Legacy modules retain underscore/selective compatibility rules.
explicit_surface: bool,
/// Top-level `let` bindings, reified as `Value`s. Fns live
/// in `fn_decls` instead so the importer can register them
/// in `self.functions` for cross-fn call resolution.
bindings: Vec<(String, Value)>,
/// Declaring module and binding for every exported value. Facades retain
/// this provenance so their live execution environment can borrow the
/// authoritative handle rather than cloning a stale snapshot.
binding_origins: BTreeMap<String, BindingOrigin>,
/// Top-level `fn` declarations. The importer copies each
/// into its own `self.functions` table AND pushes a
/// `Value::Fn` into the current scope so first-class use
/// (`let g = some_imported_fn`) still works.
fn_decls: Vec<(String, Rc<FnEntry>)>,
/// Struct-type declarations introduced by the module,
/// keyed by their full identity `(module_path, type_name)`.
struct_defs: Vec<ModuleStructDef>,
/// Enum-type declarations introduced by the module, same
/// keying as `struct_defs`.
enum_defs: Vec<ModuleEnumDef>,
/// `((module_path, type_name), method_name, FnEntry)` for
/// every method the module declared on its own types.
methods: Vec<ModuleMethodDef>,
/// Public type names exposed by this module and their declaration origins.
type_exports: BTreeMap<String, String>,
/// Exported values that remain module namespaces after value-level winner
/// resolution. Values retain their original path and selected surface.
module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>>,
/// Private module-owned context restored for calls declared in this
/// module. This is intentionally separate from the exported surface.
lexical_context: Rc<ModuleLexicalContext>,
}
#[derive(Clone, Default)]
struct ModuleLexicalContext {
type_bindings: Rc<BTreeMap<String, String>>,
module_aliases: Rc<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
imported_functions: Rc<BTreeMap<String, Rc<FnEntry>>>,
}
/// Import cache shared across nested VMs so recursive imports
/// resolve exactly once per top-level run.
type ImportCache = Rc<RefCell<BTreeMap<String, ImportSlot>>>;
type LiveValueEnvironments = Rc<RefCell<BTreeMap<String, BTreeMap<String, Value>>>>;
type BindingOrigin = (String, String);
fn snapshot_module_bindings(
top_scope: &BTreeMap<String, Value>,
binding_origins: &BTreeMap<String, BindingOrigin>,
module_path: &str,
imports: &ImportCache,
line: u32,
) -> Result<Vec<(String, Value)>, NyblError> {
// Re-exported value bindings can reuse their origin's already-external
// snapshot. Named functions are intentionally absent from `bindings`
// (their callable metadata lives in `fn_decls`), so those are snapshot
// locally with the module's own values instead.
let forwarded: BTreeMap<String, Value> = {
let imports = imports.borrow();
top_scope
.keys()
.filter_map(|name| {
let origin = binding_origins.get(name)?;
if origin.0 == module_path && origin.1 == *name {
return None;
}
let ImportSlot::Loaded(origin_module) = imports.get(&origin.0)? else {
return None;
};
origin_module
.bindings
.iter()
.find(|(origin_name, _)| origin_name == &origin.1)
.map(|(_, value)| (name.clone(), value.clone()))
})
.collect()
};
let local: BTreeMap<String, Value> = top_scope
.iter()
.filter(|(name, _)| !forwarded.contains_key(*name))
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
let mut local_snapshots: BTreeMap<String, Value> =
Value::__compatibility_snapshot_bindings(&local, line)?
.into_iter()
.collect();
top_scope
.keys()
.map(|name| {
let value = forwarded
.get(name)
.cloned()
.or_else(|| local_snapshots.remove(name))
.ok_or_else(|| {
error(line, format!("Missing compatibility snapshot for `{name}`"))
})?;
Ok((name.clone(), value))
})
.collect()
}
type LiveBindingOrigins = Rc<RefCell<BTreeMap<String, BTreeMap<String, BindingOrigin>>>>;
#[derive(Clone)]
struct ModuleRuntime {
imports: ImportCache,
environments: LiveValueEnvironments,
origins: LiveBindingOrigins,
}
impl ModuleRuntime {
fn empty() -> Self {
Self {
imports: Rc::new(RefCell::new(BTreeMap::new())),
environments: Rc::new(RefCell::new(BTreeMap::new())),
origins: Rc::new(RefCell::new(BTreeMap::new())),
}
}
}
fn take_live_environment(
environments: &LiveValueEnvironments,
module_path: &str,
origins: &BTreeMap<String, BindingOrigin>,
) -> BTreeMap<String, Value> {
let mut environments = environments.borrow_mut();
let mut environment = environments.remove(module_path).unwrap_or_default();
for (binding, (origin_module, origin_binding)) in origins {
if origin_module == module_path && origin_binding == binding {
continue;
}
if let Some(value) = environments
.get_mut(origin_module)
.and_then(|origin| origin.remove(origin_binding))
{
environment.insert(binding.clone(), value);
}
}
environment
}
fn put_live_environment(
environments: &LiveValueEnvironments,
module_path: &str,
mut environment: BTreeMap<String, Value>,
origins: &BTreeMap<String, BindingOrigin>,
) {
let mut environments = environments.borrow_mut();
for (binding, (origin_module, origin_binding)) in origins {
if origin_module == module_path && origin_binding == binding {
continue;
}
if let Some(value) = environment.remove(binding) {
environments
.entry(origin_module.clone())
.or_default()
.insert(origin_binding.clone(), value);
}
}
environments.insert(module_path.to_string(), environment);
}
// ─── Next action ───────────────────────────────────────────────────
enum Next {
/// Keep fetching the next instruction.
Continue,
/// End the program (top-level `Halt`).
Halt,
}
// ─── VM ────────────────────────────────────────────────────────────
/// Stack machine that executes a compiled [`Chunk`].
pub struct Vm<'h, H: NyblHost + ?Sized> {
frames: Vec<Frame>,
stack: Vec<Slot>,
/// User-declared functions, keyed by name. Wrapped in `Rc`
/// so the call path can take a cheap handle (one refcount
/// bump) instead of cloning the params `Vec<String>` and
/// re-taking the chunk `Rc` on every invocation — a hot
/// path that ran ~500 000 times in `fib(28)`.
functions: BTreeMap<String, Rc<FnEntry>>,
host: &'h mut H,
steps: u64,
step_budget: u64,
rand_state: u64,
imports: ImportCache,
imported_here: Vec<BTreeSet<String>>,
limits: NyblLimits,
/// Module this VM is running — tags newly declared types
/// with their full identity so two modules declaring the
/// same name remain distinct. `<root>` at the top level,
/// the dot-joined module path inside a `use`'d module's
/// sub-VM.
current_module: String,
/// Declared struct types, keyed by full identity
/// `(module_path, type_name)`. Populated by
/// `DefineStruct` (which tags with `current_module`) and
/// merged from imported modules via `exec_use`.
struct_defs: BTreeMap<(String, String), Vec<String>>,
/// Declared enum types, same `(module_path, type_name)`
/// keying as `struct_defs`.
enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>>,
/// User-defined methods. Outer key is the receiver type's
/// full identity `(module_path, type_name)`; inner is the
/// method name. A method declared for `paint.Color` doesn't
/// fire on `other.Color` — identity is strict.
user_methods: BTreeMap<(String, String), BTreeMap<String, Rc<FnEntry>>>,
/// Public type projection for the module currently executing.
type_exports: BTreeMap<String, String>,
/// Parallel scope-stack for bare-name type and module-alias
/// resolution. Pushed / popped in lockstep with frame scopes,
/// plus a fresh frame at fn-call entry so a fn's own type
/// decls are isolated from the caller's scope. `<builtin>`
/// types seed scope 0.
type_bindings: Vec<BTreeMap<String, String>>,
/// Module-level aliases. Unlike value scope, these persist
/// across function boundaries so namespaced references
/// inside fn bodies (`p.Color::Red` in a pattern) can still
/// resolve to the aliased module.
module_aliases: Vec<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
/// Non-aliased imported callables, paired with lexical scope frames.
imported_functions: Vec<BTreeMap<String, Rc<FnEntry>>>,
/// Current module namespace. Rebuilt only when top-level declarations or
/// imports change; calls clone this single Rc handle.
root_lexical_context: Rc<ModuleLexicalContext>,
/// Freelist of cleared slot vecs from popped frames. Every
/// fn call needs a fresh `Vec<Value>` sized to `slot_count`
/// — allocating a new one per call was ~500k small heap
/// allocations under `fib(28)`. On return we truncate + park;
/// next call grabs one, resizes in place.
slots_freelist: Vec<Vec<Value>>,
root_function_visibility: BTreeMap<u32, Visibility>,
abi_declarations: Vec<(String, Rc<FnEntry>)>,
function_origin: NyblFnOrigin,
memory: nybl::memory::MemoryContext,
live_value_environments: LiveValueEnvironments,
binding_origins: BTreeMap<String, BindingOrigin>,
live_binding_origins: LiveBindingOrigins,
/// Non-fatal runtime diagnostics accumulated across the root VM and any
/// nested module VMs. Only a public operation boundary writes them.
runtime_warnings: Vec<NyblWarning>,
}
struct VmState {
frames: Vec<Frame>,
stack: Vec<Slot>,
functions: BTreeMap<String, Rc<FnEntry>>,
rand_state: u64,
imports: ImportCache,
imported_here: Vec<BTreeSet<String>>,
current_module: String,
struct_defs: BTreeMap<(String, String), Vec<String>>,
enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>>,
user_methods: BTreeMap<(String, String), BTreeMap<String, Rc<FnEntry>>>,
type_exports: BTreeMap<String, String>,
type_bindings: Vec<BTreeMap<String, String>>,
module_aliases: Vec<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
imported_functions: Vec<BTreeMap<String, Rc<FnEntry>>>,
root_lexical_context: Rc<ModuleLexicalContext>,
slots_freelist: Vec<Vec<Value>>,
root_function_visibility: BTreeMap<u32, Visibility>,
abi_declarations: Vec<(String, Rc<FnEntry>)>,
function_origin: NyblFnOrigin,
live_value_environments: LiveValueEnvironments,
binding_origins: BTreeMap<String, BindingOrigin>,
live_binding_origins: LiveBindingOrigins,
runtime_warnings: Vec<NyblWarning>,
}
/// A loaded bytecode program whose globals and module state survive calls.
pub struct NyblInstance {
state: Option<VmState>,
entries: Vec<EntryPoint>,
limits: NyblLimits,
in_operation: Cell<bool>,
memory: nybl::memory::MemoryContext,
}
impl<'h, H: NyblHost + ?Sized> Vm<'h, H> {
/// Construct a VM from trusted bytecode.
///
/// Embedders executing a hand-built or deserialized [`Chunk`] should use
/// [`execute`], which validates structural bytecode invariants first.
pub fn new(chunk: Chunk, host: &'h mut H, limits: NyblLimits) -> Self {
let memory = nybl::memory::MemoryContext::__new(limits.max_memory);
Self::new_internal(
chunk,
host,
limits,
ModuleRuntime::empty(),
String::from(nybl::value::ROOT_MODULE_PATH),
BTreeMap::new(),
NyblFnOrigin::__instance("vm"),
memory,
)
}
#[allow(clippy::too_many_arguments)]
fn new_internal(
chunk: Chunk,
host: &'h mut H,
limits: NyblLimits,
module_runtime: ModuleRuntime,
current_module: String,
root_function_visibility: BTreeMap<u32, Visibility>,
function_origin: NyblFnOrigin,
memory: nybl::memory::MemoryContext,
) -> Self {
let step_budget = limits.max_steps.saturating_mul(STEP_SCALE);
let (struct_defs, enum_defs, builtin_bindings) = seed_builtin_types();
let root_lexical_context = Rc::new(ModuleLexicalContext {
type_bindings: Rc::new(builtin_bindings.clone()),
module_aliases: Rc::new(BTreeMap::new()),
imported_functions: Rc::new(BTreeMap::new()),
});
// The top frame resolves directly through the VM's live scope maps.
// Keeping another strong reference to the root lexical context would
// force copy-on-write publication to clone on every declaration.
let top = Frame::top(chunk, Rc::new(ModuleLexicalContext::default()));
Self {
frames: vec![top],
stack: Vec::new(),
functions: BTreeMap::new(),
host,
steps: 0,
step_budget,
rand_state: 0,
imports: module_runtime.imports,
imported_here: vec![BTreeSet::new()],
limits,
current_module,
struct_defs,
enum_defs,
user_methods: BTreeMap::new(),
type_exports: BTreeMap::new(),
type_bindings: vec![builtin_bindings],
module_aliases: vec![BTreeMap::new()],
imported_functions: vec![BTreeMap::new()],
root_lexical_context,
slots_freelist: Vec::new(),
root_function_visibility,
abi_declarations: Vec::new(),
function_origin,
memory,
live_value_environments: module_runtime.environments,
binding_origins: BTreeMap::new(),
live_binding_origins: module_runtime.origins,
runtime_warnings: Vec::new(),
}
}
fn into_state(self) -> VmState {
VmState {
frames: self.frames,
stack: self.stack,
functions: self.functions,
rand_state: self.rand_state,
imports: self.imports,
imported_here: self.imported_here,
current_module: self.current_module,
struct_defs: self.struct_defs,
enum_defs: self.enum_defs,
user_methods: self.user_methods,
type_exports: self.type_exports,
type_bindings: self.type_bindings,
module_aliases: self.module_aliases,
imported_functions: self.imported_functions,
root_lexical_context: self.root_lexical_context,
slots_freelist: self.slots_freelist,
root_function_visibility: self.root_function_visibility,
abi_declarations: self.abi_declarations,
function_origin: self.function_origin,
live_value_environments: self.live_value_environments,
binding_origins: self.binding_origins,
live_binding_origins: self.live_binding_origins,
runtime_warnings: self.runtime_warnings,
}
}
fn from_state(
state: VmState,
host: &'h mut H,
limits: NyblLimits,
memory: nybl::memory::MemoryContext,
) -> Self {
Self {
frames: state.frames,
stack: state.stack,
functions: state.functions,
host,
steps: 0,
step_budget: limits.max_steps.saturating_mul(STEP_SCALE),
rand_state: state.rand_state,
imports: state.imports,
imported_here: state.imported_here,
limits,
current_module: state.current_module,
struct_defs: state.struct_defs,
enum_defs: state.enum_defs,
user_methods: state.user_methods,
type_exports: state.type_exports,
type_bindings: state.type_bindings,
module_aliases: state.module_aliases,
imported_functions: state.imported_functions,
root_lexical_context: state.root_lexical_context,
slots_freelist: state.slots_freelist,
root_function_visibility: state.root_function_visibility,
abi_declarations: state.abi_declarations,
function_origin: state.function_origin,
memory,
live_value_environments: state.live_value_environments,
binding_origins: state.binding_origins,
live_binding_origins: state.live_binding_origins,
runtime_warnings: state.runtime_warnings,
}
}
fn restore_instance_baseline(&mut self) {
while self.frames.len() > 1 {
let mut frame = self.frames.pop().expect("frame present");
self.store_frame_defining_environment(&mut frame);
if !frame.slots.is_empty() {
self.return_slots(frame.slots);
}
}
self.restore_active_defining_environment();
self.stack.clear();
if let Some(root) = self.frames.first_mut() {
root.scopes.truncate(root.scope_base);
}
self.type_bindings.truncate(1);
self.module_aliases.truncate(1);
self.imported_functions.truncate(1);
self.imported_here.truncate(1);
}
/// Grab a slot vec from the freelist or allocate a fresh one,
/// then size it to `len` with `Value::None` placeholders.
/// Callers write their args into the first few entries after
/// calling this.
fn take_slots(&mut self, len: usize) -> Vec<Value> {
let mut v = self.slots_freelist.pop().unwrap_or_default();
if v.capacity() < len {
v.reserve(len - v.capacity());
}
v.resize(len, Value::None);
v
}
/// Return a slot vec to the freelist after a frame pops. We
/// clear (not deallocate) so the next call reuses the backing
/// allocation. Capped so a pathological call graph doesn't
/// grow unbounded memory.
fn return_slots(&mut self, mut slots: Vec<Value>) {
if self.slots_freelist.len() >= SLOTS_FREELIST_CAP {
return;
}
slots.clear();
self.slots_freelist.push(slots);
}
pub fn run(mut self) -> Result<(), NyblError> {
let result = (|| {
let mut last_line: u32 = 0;
while let Some((instr, line)) = self.fetch() {
last_line = line;
// Tick errors (resource-limit violations) are always
// fatal, so `unwind_to_try_call` will short-circuit
// them. The path still goes through the helper so
// the two error paths behave identically.
if let Err(err) = self.tick(line) {
let err = self.attach_frame_module_context(err);
self.unwind_to_try_call(err)?;
continue;
}
match self.dispatch(instr, line) {
Ok(Next::Continue) => {}
Ok(Next::Halt) => break,
Err(err) => {
let err = self.attach_frame_module_context(err);
self.unwind_to_try_call(err)?;
}
}
}
// Programs that allocate past the memory limit and then
// finish in fewer ticks than the periodic memory-check
// cadence (see `TICK_MEMCHECK_MASK`) would otherwise slip
// through silently. Catch them here — cheap, and a
// program ending always runs this exactly once.
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
last_line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
Ok(())
})();
self.write_runtime_warnings();
result
}
/// Deliver accumulated warnings once at an externally visible execution
/// boundary. The Vec exists in no_std builds too; only stderr delivery is
/// unavailable there.
fn write_runtime_warnings(&mut self) {
#[cfg(any(feature = "std", not(feature = "no_std")))]
for warning in self.runtime_warnings.drain(..) {
eprintln!("warning: {}", warning.message);
}
#[cfg(all(feature = "no_std", not(feature = "std")))]
self.runtime_warnings.clear();
}
// ─── Fetch / ip ──────────────────────────────────────────────
#[inline]
fn fetch(&mut self) -> Option<(Instr, u32)> {
let frame = self.frames.last_mut()?;
if frame.ip >= frame.chunk.code.len() {
return None;
}
let instr = frame.chunk.code[frame.ip];
let line = frame.chunk.lines[frame.ip];
frame.ip += 1;
Some((instr, line))
}
fn jump(&mut self, target: CodeOffset) {
if let Some(frame) = self.frames.last_mut() {
frame.ip = target.0 as usize;
}
}
// ─── Tick ────────────────────────────────────────────────────
#[inline]
fn tick(&mut self, line: u32) -> Result<(), NyblError> {
self.steps += 1;
if self.steps > self.step_budget {
// Fatal — `try_call` can't catch this or the
// step-limit sandbox invariant would break.
//
// Which instruction the budget trips on is an accident
// of step-count phase (and differs from the walker's
// per-statement accounting), so report the outermost
// active source loop's header instead — the walker does
// the same, keeping the two engines' error lines
// aligned.
return Err(error_fatal_with_hint(
self.active_loop_line().unwrap_or(line),
"Your code took too many steps (possible infinite loop)",
"Check your loops — make sure they have a condition that eventually stops them.",
));
}
// Reading the explicit memory account is cheap in absolute
// terms, but done every instruction it dominates a tight
// arithmetic loop.
// Allocations enter through `Value::Clone` /
// constructors, so we only need to notice when the
// counter crosses the limit. Checking every 256 ticks
// caps detection latency at ~256 instructions worth of
// allocations — negligible for a hard cap that's already
// elastic by a few MB.
if self.steps & TICK_MEMCHECK_MASK == 0 && self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
self.host.on_tick()?;
Ok(())
}
/// Header line of the outermost source loop the VM is currently
/// executing, scanning call frames outermost-first. For the
/// active frame `ip - 1` is the instruction being ticked; for a
/// caller frame it is the `Call` that entered the callee, so a
/// budget trip inside a loop-free callee still resolves to the
/// calling loop. `None` when no frame is inside a loop (e.g.
/// branching recursion exhausting the budget). See
/// [`Chunk::outermost_loop_line`] for why outermost.
fn active_loop_line(&self) -> Option<u32> {
self.frames.iter().find_map(|frame| {
let offset = CodeOffset(frame.ip.saturating_sub(1) as u32);
frame.chunk.outermost_loop_line(offset)
})
}
// ─── Stack helpers ───────────────────────────────────────────
#[inline]
fn push_value(&mut self, v: Value) {
self.stack.push(Slot::Value(v));
}
#[inline]
fn pop_value(&mut self, line: u32) -> Result<Value, NyblError> {
match self.stack.pop() {
Some(Slot::Value(v)) => Ok(v),
Some(_) => Err(error(line, "VM: expected value on stack")),
None => Err(error(line, "VM: stack underflow")),
}
}
#[inline]
fn peek_value(&self, line: u32) -> Result<&Value, NyblError> {
match self.stack.last() {
Some(Slot::Value(v)) => Ok(v),
Some(_) => Err(error(line, "VM: expected value on stack")),
None => Err(error(line, "VM: stack underflow")),
}
}
fn pop_n_values(&mut self, n: usize, line: u32) -> Result<Vec<Value>, NyblError> {
if self.stack.len() < n {
return Err(error(line, "VM: stack underflow"));
}
let start = self.stack.len() - n;
let mut out = Vec::with_capacity(n);
for slot in self.stack.drain(start..) {
match slot {
Slot::Value(v) => out.push(v),
_ => return Err(error(line, "VM: expected value on stack")),
}
}
Ok(out)
}
// ─── Scope ───────────────────────────────────────────────────
fn current_scopes_mut(&mut self) -> &mut Vec<BTreeMap<String, Value>> {
&mut self.frames.last_mut().expect("frame present").scopes
}
fn current_scopes(&self) -> &Vec<BTreeMap<String, Value>> {
&self.frames.last().expect("frame present").scopes
}
fn push_scope(&mut self) {
self.current_scopes_mut().push(BTreeMap::new());
// Type bindings parallel value scopes so inline type
// decls inside a block vanish on block exit, same rule
// the walker applies.
self.type_bindings.push(BTreeMap::new());
self.module_aliases.push(BTreeMap::new());
self.imported_functions.push(BTreeMap::new());
self.imported_here.push(BTreeSet::new());
}
fn pop_scope(&mut self) {
let popped = {
let frame = self.frames.last_mut().expect("frame present");
if frame.scopes.len() > frame.scope_base {
frame.scopes.pop();
true
} else {
false
}
};
if popped {
let type_scope_base = self.frames.last().expect("frame present").type_scope_base;
debug_assert!(
self.type_bindings.len() > type_scope_base,
"value and type scope stacks must stay paired"
);
if self.type_bindings.len() > type_scope_base {
self.type_bindings.pop();
self.module_aliases.pop();
self.imported_functions.pop();
self.imported_here.pop();
}
}
}
/// Push a function-like frame together with its protected type-binding
/// scope. Keeping this transition in one helper prevents constructors for
/// named functions, closures, methods, and iterator methods from drifting.
fn push_function_frame(
&mut self,
chunk: Rc<Chunk>,
slots: Vec<Value>,
scopes: Vec<BTreeMap<String, Value>>,
stack_base: usize,
function_module: Option<String>,
wrap: FrameWrap,
) {
self.park_active_defining_environment();
let defining_environment = function_module.as_ref().map(|module| {
let origins = self.binding_origins_for(module);
take_live_environment(&self.live_value_environments, module, &origins)
});
let mut scopes = scopes;
if let Some(environment) = defining_environment {
scopes.insert(0, environment);
// Runtime declarations/imports belong to the call, never to the
// defining module environment parked below it.
scopes.push(BTreeMap::new());
}
let lexical_context = function_module
.as_deref()
.map(|module| self.module_lexical_context(module))
.unwrap_or_else(|| Rc::clone(&self.root_lexical_context));
let type_scope_base = self.type_bindings.len() + 1;
let alias_scope_base = self.module_aliases.len();
self.module_aliases.push(BTreeMap::new());
self.imported_functions.push(BTreeMap::new());
self.imported_here.push(BTreeSet::new());
let mut frame = Frame::function(
chunk,
slots,
scopes,
stack_base,
FunctionFrameContext {
scope_bases: FrameScopeBases {
types: type_scope_base,
aliases: alias_scope_base,
},
function_module,
lexical_context,
},
wrap,
);
frame.defining_environment_module = frame.function_module.clone();
self.frames.push(frame);
self.type_bindings.push(BTreeMap::new());
}
fn apply_entry_alias_context(&mut self, entry: &FnEntry) {
let frame = self.frames.last_mut().expect("callee frame");
let mut context = (*frame.lexical_context).clone();
Rc::make_mut(&mut context.module_aliases)
.retain(|name, _| entry.declaration_alias_names.contains(name));
frame.lexical_context = Rc::new(context);
}
fn park_active_defining_environment(&mut self) {
let active_module = self.frames.last().and_then(|frame| {
frame
.defining_environment_module
.clone()
.or_else(|| (!frame.is_function).then(|| self.current_module.clone()))
});
let Some(module) = active_module else {
return;
};
let environment = self
.frames
.last_mut()
.and_then(|frame| frame.scopes.first_mut())
.map(core::mem::take)
.unwrap_or_default();
let origins = self.binding_origins_for(&module);
put_live_environment(
&self.live_value_environments,
&module,
environment,
&origins,
);
self.live_binding_origins
.borrow_mut()
.insert(module, origins);
}
fn store_frame_defining_environment(&mut self, frame: &mut Frame) {
let Some(module) = frame.defining_environment_module.as_ref() else {
return;
};
let origins = self.binding_origins_for(module);
if !self.live_value_environments.borrow().contains_key(module) {
let environment = frame
.scopes
.first_mut()
.map(core::mem::take)
.unwrap_or_default();
put_live_environment(&self.live_value_environments, module, environment, &origins);
}
self.live_binding_origins
.borrow_mut()
.insert(module.clone(), origins);
}
fn restore_active_defining_environment(&mut self) {
let active_module = self.frames.last().and_then(|frame| {
frame
.defining_environment_module
.clone()
.or_else(|| (!frame.is_function).then(|| self.current_module.clone()))
});
let Some(module) = active_module else {
return;
};
if !self.live_value_environments.borrow().contains_key(&module) {
return;
}
let origins = self.binding_origins_for(&module);
let environment = take_live_environment(&self.live_value_environments, &module, &origins);
if let Some(scope) = self
.frames
.last_mut()
.and_then(|frame| frame.scopes.first_mut())
{
*scope = environment;
}
}
fn module_alias(&self, name: &str) -> Option<&Rc<nybl::value::NyblModule>> {
let floor = self
.frames
.last()
.filter(|frame| frame.is_function)
.map(|frame| frame.alias_scope_base);
self.module_aliases
.iter()
.enumerate()
.rev()
.filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
.find_map(|(_, frame)| frame.get(name))
.or_else(|| {
self.frames
.last()
.and_then(|frame| frame.lexical_context.module_aliases.get(name))
})
}
fn module_binding(&self, module: &nybl::value::NyblModule, name: &str) -> Option<Value> {
// The import-time snapshot is the module object's capability surface.
// Live-environment lookup refreshes values within that surface; it
// must never turn an unselected or private binding into a new member.
if !module.bindings.iter().any(|(binding, _)| binding == name) {
return None;
}
if let Some((active_module, environment)) = self.frames.last().and_then(|frame| {
let active_module = frame
.defining_environment_module
.as_deref()
.or_else(|| (!frame.is_function).then_some(self.current_module.as_str()))?;
Some((active_module, frame.scopes.first()?))
}) {
if module.path == active_module
&& let Some(value) = environment.get(name)
{
return Some(value.clone());
}
let (origin_module, origin_binding) = module.__binding_origin(name);
if origin_module == active_module
&& let Some(value) = environment.get(&origin_binding)
{
return Some(value.clone());
}
let active_origins = self.binding_origins_for(active_module);
if let Some(active_binding) =
active_origins
.iter()
.find_map(|(active_binding, active_origin)| {
(active_origin.0 == origin_module && active_origin.1 == origin_binding)
.then_some(active_binding)
})
&& let Some(value) = environment.get(active_binding)
{
return Some(value.clone());
}
}
module.__binding(name)
}
fn binding_origins_for(&self, module: &str) -> BTreeMap<String, BindingOrigin> {
if module == self.current_module {
return self.binding_origins.clone();
}
self.live_binding_origins
.borrow()
.get(module)
.cloned()
.unwrap_or_default()
}
fn live_origin_value(&self, origin: &BindingOrigin) -> Option<Value> {
if let Some((active_module, environment)) = self.frames.last().and_then(|frame| {
let active_module = frame
.defining_environment_module
.as_deref()
.or_else(|| (!frame.is_function).then_some(self.current_module.as_str()))?;
Some((active_module, frame.scopes.first()?))
}) {
if active_module == origin.0
&& let Some(value) = environment.get(&origin.1)
{
return Some(value.clone());
}
let active_origins = self.binding_origins_for(active_module);
if let Some(binding) = active_origins
.iter()
.find_map(|(binding, candidate)| (candidate == origin).then_some(binding))
&& let Some(value) = environment.get(binding)
{
return Some(value.clone());
}
}
self.live_value_environments
.borrow()
.get(&origin.0)
.and_then(|environment| environment.get(&origin.1))
.cloned()
}
fn imported_function(&self, name: &str) -> Option<&Rc<FnEntry>> {
let floor = self
.frames
.last()
.filter(|frame| frame.is_function)
.map(|frame| frame.alias_scope_base);
self.imported_functions
.iter()
.enumerate()
.rev()
.filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
.find_map(|(_, frame)| frame.get(name))
.or_else(|| {
self.frames
.last()
.and_then(|frame| frame.lexical_context.imported_functions.get(name))
})
}
fn is_module_top_scope(&self) -> bool {
self.frames
.last()
.is_some_and(|frame| !frame.is_function && frame.scopes.len() == frame.scope_base)
}
fn define_local(&mut self, name: String, value: Value) {
if self.current_scopes().is_empty() {
self.current_scopes_mut().push(BTreeMap::new());
}
if let Some(scope) = self.current_scopes_mut().last_mut() {
scope.insert(name, value);
}
}
fn sync_top_level_module_alias(
&mut self,
name: String,
module: Option<Rc<nybl::value::NyblModule>>,
) {
if !self.is_module_top_scope() {
return;
}
let aliases = self.module_aliases.last_mut().expect("module alias scope");
if let Some(module) = module {
aliases.insert(name.clone(), Rc::clone(&module));
self.publish_root_module_alias(name, Some(module));
} else {
aliases.remove(&name);
self.publish_root_module_alias(name, None);
}
}
/// `lookup_var`, but pull the name from the current chunk by
/// index. Avoids an `Rc::clone` + separate borrow at the call
/// site — the dispatch loop's hottest read path.
fn lookup_var_by_idx(&self, idx: NameIdx) -> Option<&Value> {
let frame = self.frames.last()?;
let name = frame.chunk.name(idx);
for scope in frame.scopes.iter().rev() {
if let Some(v) = scope.get(name) {
return Some(v);
}
}
if frame.is_function
&& frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
{
return self
.frames
.first()
.and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(name)));
}
None
}
fn lookup_var_mut_by_idx(&mut self, idx: NameIdx) -> Option<&mut Value> {
let (name, uses_root) = {
let frame = self.frames.last()?;
(
frame.chunk.name(idx).to_string(),
frame.is_function
&& frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH),
)
};
let current_index = self.frames.len().checked_sub(1)?;
if current_index == 0 {
return self.frames[0]
.scopes
.iter_mut()
.rev()
.find_map(|scope| scope.get_mut(&name));
}
let (earlier, current) = self.frames.split_at_mut(current_index);
for scope in current[0].scopes.iter_mut().rev() {
if let Some(value) = scope.get_mut(&name) {
return Some(value);
}
}
if uses_root {
return earlier.first_mut().and_then(|root| {
root.scopes
.iter_mut()
.rev()
.find_map(|scope| scope.get_mut(&name))
});
}
None
}
fn set_existing(&mut self, name: &str, value: Value) -> bool {
for scope in self.current_scopes_mut().iter_mut().rev() {
// Writing through `get_mut` keeps the existing key
// allocation in place — we'd otherwise pay a fresh
// `String` alloc per loop iteration for every
// `StoreVar` in a tight loop (e.g. `i = i + 1`).
if let Some(slot) = scope.get_mut(name) {
*slot = value;
return true;
}
}
if self.frames.last().is_some_and(|frame| {
frame.is_function
&& frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
}) && let Some(slot) = self.frames.first_mut().and_then(|root| {
root.scopes
.iter_mut()
.rev()
.find_map(|scope| scope.get_mut(name))
}) {
*slot = value;
return true;
}
false
}
/// `set_existing`, but pull the name from the current chunk
/// by index. Splits the frame's `&mut` into a `&Rc<Chunk>`
/// (for the name slice) and `&mut scopes` (for the walk)
/// using field-level borrow splitting — no `Rc::clone`.
fn set_existing_by_idx(&mut self, idx: NameIdx, value: Value) -> bool {
let current_index = self.frames.len() - 1;
let name = self.frames[current_index].chunk.name(idx).to_string();
for scope in self.frames[current_index].scopes.iter_mut().rev() {
if let Some(slot) = scope.get_mut(&name) {
*slot = value;
return true;
}
}
let uses_root = self.frames[current_index].is_function
&& self.frames[current_index].function_module.as_deref()
== Some(nybl::value::ROOT_MODULE_PATH);
if self.frames[current_index].is_function
&& self.frames[current_index]
.lexical_context
.module_aliases
.contains_key(&name)
{
let frame = &mut self.frames[current_index];
let overlay_scope = if frame.has_declaration_overlay {
frame.scope_base - 1
} else {
let scope = frame.scope_base;
frame.scopes.insert(scope, BTreeMap::new());
frame.scope_base += 1;
frame.has_declaration_overlay = true;
scope
};
frame
.scopes
.get_mut(overlay_scope)
.expect("alias overlay scope")
.insert(name, value);
return true;
}
if uses_root
&& let Some(slot) = self.frames[0]
.scopes
.iter_mut()
.rev()
.find_map(|scope| scope.get_mut(&name))
{
*slot = value;
return true;
}
false
}
// ─── "Did you mean?" candidate collectors ─────────────────
//
// Same pattern as the walker: gather every name the user
// could plausibly have meant so `nybl::suggest::did_you_mean`
// picks the closest one. VM-specific quirk: the scope stack
// is per-frame, so we only scan the current frame's scopes
// rather than the whole interpreter's.
/// Names reachable when an identifier is used as a value —
/// locals in the enclosing scopes plus user fn declarations.
fn value_candidates_hint(&self, target: &str) -> Option<String> {
let mut candidates: Vec<String> = Vec::new();
for scope in self.current_scopes() {
for k in scope.keys() {
candidates.push(k.clone());
}
}
for name in self.functions.keys() {
candidates.push(name.clone());
}
nybl::suggest::did_you_mean(target, candidates)
}
/// Names reachable in a call position: user fns plus core
/// builtins. Host builtins stay with the host's own
/// `function_hint()` (the call site falls back to that path
/// when no user-level suggestion fits).
fn callable_candidates_hint(&self, target: &str) -> Option<String> {
let mut candidates: Vec<String> = self.functions.keys().cloned().collect();
for b in nybl::suggest::CORE_CALLABLE_BUILTINS {
candidates.push((*b).to_string());
}
nybl::suggest::did_you_mean(target, candidates)
}
fn active_module_path(&self) -> &str {
self.frames
.last()
.and_then(|frame| frame.function_module.as_deref())
.unwrap_or(&self.current_module)
}
fn module_lexical_context(&self, module_path: &str) -> Rc<ModuleLexicalContext> {
if module_path == self.current_module {
return Rc::clone(&self.root_lexical_context);
}
let cache = self.imports.borrow();
match cache.get(module_path) {
Some(ImportSlot::Loaded(artifacts)) => Rc::clone(&artifacts.lexical_context),
_ => Rc::new(ModuleLexicalContext::default()),
}
}
fn publish_root_type_binding(&mut self, name: String, origin: String) {
let context = Rc::make_mut(&mut self.root_lexical_context);
Rc::make_mut(&mut context.type_bindings).insert(name, origin);
}
fn publish_root_module_alias(
&mut self,
name: String,
module: Option<Rc<nybl::value::NyblModule>>,
) {
let context = Rc::make_mut(&mut self.root_lexical_context);
let aliases = Rc::make_mut(&mut context.module_aliases);
if let Some(module) = module {
aliases.insert(name, module);
} else {
aliases.remove(&name);
}
}
fn publish_root_imported_function(&mut self, name: String, function: Rc<FnEntry>) {
let context = Rc::make_mut(&mut self.root_lexical_context);
Rc::make_mut(&mut context.imported_functions).insert(name, function);
}
/// Resolve module-owned sibling functions from cached module artifacts
/// before falling back to caller-visible functions. This preserves module
/// function environments without making alias imports publish bare names.
#[inline]
fn lookup_function_entry(&self, name: &str) -> Option<Rc<FnEntry>> {
let frame = self.frames.last()?;
let defining_module = frame.function_module.as_deref();
if let Some(module_path) = defining_module
&& module_path != nybl::value::ROOT_MODULE_PATH
{
let cache = self.imports.borrow();
if let Some(ImportSlot::Loaded(artifacts)) = cache.get(module_path)
&& let Some((_, entry)) = artifacts
.fn_decls
.iter()
.find(|(candidate, _)| candidate == name)
{
return Some(entry.clone());
}
}
// Alias-free named calls dominate real programs. Avoid probing every
// empty runtime import scope and then the empty defining-module map
// before reaching `self.functions`. The moment any active import map
// contains a callable, keep the full lookup below so a block/function
// import can still shadow a same-named declared function.
let import_floor = if frame.is_function {
frame.alias_scope_base
} else {
0
};
let runtime_imports_empty = self.imported_functions[import_floor..]
.iter()
.all(BTreeMap::is_empty);
if runtime_imports_empty && frame.lexical_context.imported_functions.is_empty() {
if let Some(module_path) = defining_module {
return self
.functions
.get(name)
.filter(|entry| entry.module_path == module_path)
.cloned();
}
return self.functions.get(name).cloned();
}
if let Some(entry) = self.imported_function(name) {
return Some(entry.clone());
}
if let Some(module_path) = defining_module
&& let Some(entry) = self
.functions
.get(name)
.filter(|entry| entry.module_path == module_path)
{
return Some(entry.clone());
}
if defining_module.is_none_or(|path| path == self.current_module) {
self.functions.get(name).cloned()
} else {
None
}
}
// ─── Dispatch ────────────────────────────────────────────────
#[inline]
fn dispatch(&mut self, instr: Instr, line: u32) -> Result<Next, NyblError> {
match instr {
// ─── Literals ─────────────────────────────────────────
Instr::LoadConst(idx) => {
let value = match self.current_chunk().constant(idx) {
Constant::Int(n) => Value::Int(*n),
Constant::Number(n) => Value::Number(*n),
Constant::Str(s) => Value::__new_str_in(s.clone(), &self.memory),
};
self.push_value(value);
}
Instr::LoadNone => self.push_value(Value::None),
Instr::LoadTrue => self.push_value(Value::Bool(true)),
Instr::LoadFalse => self.push_value(Value::Bool(false)),
// ─── Variables ────────────────────────────────────────
Instr::LoadVar(n) => {
// Fast path: look the name up by index so both
// the chunk borrow and the scope walk happen in
// one helper — no `Rc::clone` and no intermediate
// owned `String`. A tight loop with 3 `LoadVar`s
// per iteration previously paid one `Rc::clone`
// per access here.
if let Some(v) = self.lookup_var_by_idx(n).cloned() {
self.push_value(v);
} else {
// Slow path: fall back to the named-fn
// registry so `fn fib(...) {...}; let g = fib`
// yields a real `Value::Fn`. Only then do we
// need the name as a `&str` / `String`.
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let name = chunk.name(n);
if let Some(module) = self.module_alias(name).cloned() {
self.push_value(Value::Module(module));
return Ok(Next::Continue);
}
let fn_entry = self.lookup_function_entry(name);
if let Some(entry) = fn_entry {
let params = entry.params.clone();
let chunk_rc = entry.chunk.clone();
let body: Rc<dyn core::any::Any + 'static> = chunk_rc;
let v = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
params,
entry.param_modes.clone(),
Vec::new(),
body,
Some(name.to_string()),
Some(entry.module_path.clone()),
self.function_origin.clone(),
0,
line,
)
.map(Value::Fn)?;
self.push_value(v);
} else {
// "did you mean?" first, else the generic
// "use `let`" nudge. Mirrors the walker's
// behaviour for consistency across engines.
let hint = self.value_candidates_hint(name).unwrap_or_else(|| {
"Did you forget to create it with `let`?".to_string()
});
return Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(name),
hint,
));
}
}
}
Instr::DefineLocal(n) => {
// `define_local` takes an owned `String` because
// it inserts into the scope map — can't skip the
// allocation here.
let name = self.current_chunk().name(n).to_string();
let v = self.pop_value(line)?;
let module = match &v {
Value::Module(module) => Some(Rc::clone(module)),
_ => None,
};
if self.is_module_top_scope()
&& let Some(origin) = self.binding_origins.get(&name).cloned()
&& (origin.0 != self.current_module || origin.1 != name)
&& let Some(previous) = self
.current_scopes_mut()
.last_mut()
.and_then(|scope| scope.remove(&name))
{
self.live_value_environments
.borrow_mut()
.entry(origin.0)
.or_default()
.insert(origin.1, previous);
}
self.define_local(name.clone(), v);
if self.is_module_top_scope() {
self.binding_origins
.insert(name.clone(), (self.current_module.clone(), name.clone()));
}
self.sync_top_level_module_alias(name, module);
}
Instr::StoreVar(n) => {
// Fast path: look the target up by index so we
// neither `Rc::clone` nor allocate the name.
let v = self.pop_value(line)?;
let module = match &v {
Value::Module(module) => Some(Rc::clone(module)),
_ => None,
};
let top_level_name = self
.is_module_top_scope()
.then(|| self.current_chunk().name(n).to_string());
let runtime_alias_without_value_binding = {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let name = chunk.name(n);
self.lookup_var_by_idx(n).is_none() && self.module_alias(name).is_some()
};
if runtime_alias_without_value_binding {
let name = self.current_chunk().name(n).to_string();
self.define_local(name, v);
return Ok(Next::Continue);
}
if !self.set_existing_by_idx(n, v) {
// Cold path: synthesise the error with the
// name — allocation is fine here.
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let name = chunk.name(n);
return Err(error_with_hint(
line,
format!("Variable `{name}` doesn't exist yet"),
format!("Use `let` to create a new variable: let {name} = ..."),
));
}
if let Some(name) = top_level_name {
self.sync_top_level_module_alias(name, module);
}
}
Instr::CompoundAssign { target, op } => {
let rhs = self.pop_value(line)?;
let runtime_alias_without_value_binding = match target {
crate::chunk::AssignBack::Name(name_idx) => {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
self.lookup_var_by_idx(name_idx).is_none()
&& self.module_alias(chunk.name(name_idx)).is_some()
}
crate::chunk::AssignBack::Slot(_) => false,
};
let current = match target {
crate::chunk::AssignBack::Slot(slot) => self
.frames
.last()
.and_then(|frame| frame.slots.get(slot.0 as usize))
.cloned()
.ok_or_else(|| error(line, "VM: local slot out of range"))?,
crate::chunk::AssignBack::Name(name_idx) => {
if let Some(value) = self.lookup_var_by_idx(name_idx).cloned() {
value
} else {
let chunk =
Rc::clone(&self.frames.last().expect("frame present").chunk);
let name = chunk.name(name_idx);
if let Some(module) = self.module_alias(name).cloned() {
Value::Module(module)
} else {
return Err(error(
line,
nybl::error_messages::variable_not_found(name),
));
}
}
}
};
let value = apply_in_place_assign(op, rhs, line, &self.memory, || Ok(current))?;
match target {
crate::chunk::AssignBack::Slot(slot) => {
let target = self
.frames
.last_mut()
.expect("frame present")
.slots
.get_mut(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
*target = value;
}
crate::chunk::AssignBack::Name(name) => {
if runtime_alias_without_value_binding {
let name = self.current_chunk().name(name).to_string();
self.define_local(name, value);
return Ok(Next::Continue);
}
if !self.set_existing_by_idx(name, value) {
let chunk =
Rc::clone(&self.frames.last().expect("frame present").chunk);
return Err(error(
line,
nybl::error_messages::variable_not_found(chunk.name(name)),
));
}
}
}
}
// ─── Slot-based locals (fast path) ───────────────────
Instr::LoadLocal(slot) => {
// Direct vec index — no hashing, no string compare.
// Slots are pre-sized at call time from the
// enclosing `FnDef::slot_count`, so an out-of-range
// read can only happen on miscompiled bytecode.
let frame = self.frames.last().expect("frame present");
let v = frame
.slots
.get(slot.0 as usize)
.cloned()
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
self.push_value(v);
}
Instr::StoreLocal(slot) => {
let v = self.pop_value(line)?;
let frame = self.frames.last_mut().expect("frame present");
let i = slot.0 as usize;
if i < frame.slots.len() {
frame.slots[i] = v;
} else {
return Err(error(line, "VM: local slot out of range"));
}
}
// ─── Superinstructions ───────────────────────────────
Instr::AddLocals(a, b) => {
// Typed fast path: Int + Int → Int, no Value
// variant match and no stack push/pop for the
// operands. `fib`'s recursive body and every
// `total = total + i` loop go through here.
let frame = self.frames.last().expect("frame present");
let av = frame
.slots
.get(a.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let bv = frame
.slots
.get(b.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let result = match (av, bv) {
(Value::Int(x), Value::Int(y)) => x
.checked_add(*y)
.map(Value::Int)
.map_or_else(|| ops::add_in(av, bv, line, &self.memory), Ok)?,
// Cold path: delegate to the generic Value
// adder. Covers Number, String concat, array
// concat, etc.
_ => ops::add_in(av, bv, line, &self.memory)?,
};
self.push_value(result);
}
Instr::LtLocals(a, b) => {
let frame = self.frames.last().expect("frame present");
let av = frame
.slots
.get(a.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let bv = frame
.slots
.get(b.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let result = match (av, bv) {
(Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
_ => ops::lt_in(av, bv, line, &self.memory)?,
};
self.push_value(result);
}
Instr::IncLocalInt(slot, k) => {
// `slot += k` for small-int `k`, the `i = i + 1`
// idiom. Fast path: Int → Int with overflow
// check. On non-Int, build an Int value and
// dispatch through generic add so `x = x + 1`
// still works when `x` is a Number.
let memory = &self.memory;
let frame = self.frames.last_mut().expect("frame present");
let i = slot.0 as usize;
let current = frame
.slots
.get(i)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let new = match current {
Value::Int(x) => x.checked_add(k as i64).map(Value::Int).map_or_else(
|| ops::add_in(current, &Value::Int(k as i64), line, memory),
Ok,
)?,
_ => ops::add_in(current, &Value::Int(k as i64), line, memory)?,
};
frame.slots[i] = new;
}
Instr::LoadLocalAddInt(slot, k) => {
// Push `slots[slot] + k`. Covers `array[i + 1]` after the
// compiler folds a small-int literal into the op.
let frame = self.frames.last().expect("frame present");
let v = frame
.slots
.get(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let result = match v {
Value::Int(x) => x.checked_add(k as i64).map(Value::Int).map_or_else(
|| ops::add_in(v, &Value::Int(k as i64), line, &self.memory),
Ok,
)?,
_ => ops::add_in(v, &Value::Int(k as i64), line, &self.memory)?,
};
self.push_value(result);
}
Instr::LtLocalInt(slot, k) => {
// Push `slots[slot] < k` — the `n < 2` base-case
// test in `fib` and every bounded `while i < K`
// loop.
let frame = self.frames.last().expect("frame present");
let v = frame
.slots
.get(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let result = match v {
Value::Int(x) => Value::Bool(*x < k as i64),
_ => ops::lt_in(v, &Value::Int(k as i64), line, &self.memory)?,
};
self.push_value(result);
}
// ─── Scope ────────────────────────────────────────────
Instr::PushScope => self.push_scope(),
Instr::PopScope => self.pop_scope(),
// ─── Stack ────────────────────────────────────────────
Instr::Pop => {
if self.stack.pop().is_none() {
return Err(error(line, "VM: stack underflow"));
}
}
Instr::Dup => {
let v = self.peek_value(line)?.clone();
self.push_value(v);
}
Instr::Dup2 => {
let len = self.stack.len();
if len < 2 {
return Err(error(line, "VM: stack underflow"));
}
let b = match &self.stack[len - 1] {
Slot::Value(v) => v.clone(),
_ => return Err(error(line, "VM: expected value on stack")),
};
let a = match &self.stack[len - 2] {
Slot::Value(v) => v.clone(),
_ => return Err(error(line, "VM: expected value on stack")),
};
self.push_value(a);
self.push_value(b);
}
// ─── Binary ops ───────────────────────────────────────
Instr::Add => self.binary_tracked(line, ops::add_in)?,
Instr::Sub => self.binary(line, ops::sub)?,
Instr::Mul => self.binary_tracked(line, ops::mul_in)?,
Instr::Div => self.binary(line, ops::div)?,
Instr::Rem => self.binary(line, ops::rem)?,
Instr::Eq => self.binary_infallible(line, |a, b, _| Ok(ops::eq(a, b)))?,
Instr::NotEq => self.binary_infallible(line, |a, b, _| Ok(ops::not_eq(a, b)))?,
Instr::Lt => self.binary(line, ops::lt)?,
Instr::Gt => self.binary(line, ops::gt)?,
Instr::LtEq => self.binary(line, ops::lt_eq)?,
Instr::GtEq => self.binary(line, ops::gt_eq)?,
// ─── Unary ops ────────────────────────────────────────
Instr::Neg => {
let v = self.pop_value(line)?;
self.push_value(ops::neg(&v, line)?);
}
Instr::Not => {
let v = self.pop_value(line)?;
self.push_value(ops::not(&v));
}
Instr::TruthyToBool => {
let v = self.pop_value(line)?;
self.push_value(Value::Bool(v.is_truthy()));
}
// ─── Indexing ─────────────────────────────────────────
Instr::GetIndex => {
let idx = self.pop_value(line)?;
let obj = self.pop_value(line)?;
self.push_value(ops::index_get_in(&obj, &idx, line, &self.memory)?);
}
Instr::SetIndex => {
let val = self.pop_value(line)?;
let idx = self.pop_value(line)?;
let mut obj = self.pop_value(line)?;
ops::index_set_in(&mut obj, &idx, val, line, &self.memory)?;
self.push_value(obj);
}
Instr::SetIndexInPlace { target, op } => {
let idx = self.pop_value(line)?;
let rhs = self.pop_value(line)?;
let memory = self.memory.clone();
match target {
crate::chunk::AssignBack::Slot(slot) => {
let value = self
.frames
.last_mut()
.expect("frame present")
.slots
.get_mut(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let val = apply_in_place_assign(op, rhs, line, &memory, || {
ops::index_get_in(value, &idx, line, &memory)
})?;
ops::index_set_in(value, &idx, val, line, &memory)?;
}
crate::chunk::AssignBack::Name(name_idx) => {
let name = self.current_chunk().name(name_idx).to_string();
if self.lookup_var_mut_by_idx(name_idx).is_none() {
if let Some(module) = self.module_alias(&name).cloned() {
let mut value = Value::Module(module);
let val = apply_in_place_assign(op, rhs, line, &memory, || {
ops::index_get_in(&value, &idx, line, &memory)
})?;
ops::index_set_in(&mut value, &idx, val, line, &memory)?;
return Ok(Next::Continue);
}
let hint = self.value_candidates_hint(&name).unwrap_or_else(|| {
"Did you forget to create it with `let`?".to_string()
});
return Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(&name),
hint,
));
}
let value = self
.lookup_var_mut_by_idx(name_idx)
.expect("binding checked above");
let val = apply_in_place_assign(op, rhs, line, &memory, || {
ops::index_get_in(value, &idx, line, &memory)
})?;
ops::index_set_in(value, &idx, val, line, &memory)?;
}
}
}
Instr::AssignPlace { place, op } => {
let index_count = self
.current_chunk()
.place(place)
.projections
.iter()
.filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
.count();
let indices = self.pop_n_values(index_count, line)?;
let rhs = self.pop_value(line)?;
let resolved =
self.resolve_place_internal(place, indices, 0, line, false, false)?;
if nybl::naming::is_constant_name(&resolved.root_name) {
return Err(nybl::error_messages::constant_mutation_error(
&resolved.root_name,
line,
));
}
let value = apply_in_place_assign(op, rhs, line, &self.memory, || {
self.place_value_from(&resolved.root, &resolved.projections, line)
})?;
let mut root = resolved.root.clone();
self.write_place_value(&mut root, &resolved.projections, value, line)?;
self.store_resolved_target(&resolved.target, root, line)?;
}
// ─── String interpolation ────────────────────────────
Instr::StringInterp(idx) => {
let recipe_parts = Rc::clone(&self.current_chunk().interp(idx).parts);
self.push_value(self.build_interp(&recipe_parts, line)?);
}
// ─── Collections ──────────────────────────────────────
Instr::MakeArray(n) => {
let items = self.pop_n_values(n as usize, line)?;
self.push_value(Value::__try_new_array_in(items, line, &self.memory)?);
}
Instr::MakeDict(n) => {
let flat = self.pop_n_values((n as usize) * 2, line)?;
let mut entries: Vec<(String, Value)> = Vec::with_capacity(n as usize);
let mut iter = flat.into_iter();
while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
let key_str = match &key {
Value::Str(s) => s.as_str().to_string(),
other => {
return Err(error(
line,
format!("Dict keys must be strings, got {}", other.type_name()),
));
}
};
drop(key);
entries.push((key_str, val));
}
self.push_value(Value::__try_new_dict_in(entries, line, &self.memory)?);
}
// ─── Calls ────────────────────────────────────────────
Instr::Call { name, argc } => {
return self.call(name, argc as usize, line);
}
Instr::CallValue { argc } => {
return self.call_value(argc as usize, line);
}
Instr::PrepareCall { name, site } => {
self.prepare_named_call(name, site, line)?;
}
Instr::PrepareCallValue { site } => {
let callee = self.pop_value(line)?;
self.prepare_value_call(callee, site, line)?;
}
Instr::PrepareMethodValue {
method,
site,
nested_place,
} => {
let receiver = self.pop_value(line)?;
self.prepare_method_call(receiver, None, None, method, site, nested_place, line)?;
}
Instr::PrepareMethodNamed {
target,
method,
site,
} => {
self.prepare_named_method_call(target, method, site, line)?;
}
Instr::PrepareMethodPlace {
place,
method,
site,
} => {
let index_count = self
.current_chunk()
.place(place)
.projections
.iter()
.filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
.count();
let indices = self.pop_n_values(index_count, line)?;
let resolved = self.resolve_place(place, indices, 0, line)?;
let receiver =
self.place_value_from(&resolved.root, &resolved.projections, line)?;
self.prepare_method_call(receiver, None, Some(resolved), method, site, true, line)?;
}
Instr::CallPrepared { site } => {
return self.call_prepared(site, line);
}
Instr::CallMethod {
method,
argc,
assign_back_to,
nested_place,
} => {
return self.call_method(method, argc as usize, assign_back_to, nested_place, line);
}
Instr::CallMethodInPlace {
target,
method,
argc,
} => {
return self.call_method_in_place(target, method, argc as usize, line);
}
// ─── Functions ────────────────────────────────────────
Instr::DefineFn(idx) => {
self.define_fn(idx);
}
Instr::MakeLambda(idx) => {
self.make_lambda(idx, line)?;
}
Instr::Return => {
let v = self.pop_value(line)?;
return self.do_return(v, line);
}
Instr::ReturnNone => {
return self.do_return(Value::None, line);
}
// ─── Iteration / repeat ──────────────────────────────
Instr::MakeIter => {
let mut v = self.pop_value(line)?;
// Fast path: Array / Str / Dict materialise eagerly
// into a `Slot::Iter(Vec<_>)`. Every other iterable
// goes through the protocol — either wraps a
// `Value::Iter` directly, or dispatches the user's
// `.iter()` method and lands the result via
// `FrameWrap::IterStart`.
match &mut v {
Value::Array(arr) => {
let mut items = arr.__take_in(&self.memory);
drop(v);
items.reverse();
self.stack.push(Slot::Iter(items));
}
Value::Str(s) => {
let mut items: Vec<Value> = s
.chars()
.map(|c| Value::__new_str_in(c.to_string(), &self.memory))
.collect();
drop(v);
items.reverse();
self.stack.push(Slot::Iter(items));
}
Value::Dict(d) => {
let mut items: Vec<Value> = d
.iter()
.map(|(k, _)| Value::__new_str_in(k.clone(), &self.memory))
.collect();
drop(v);
items.reverse();
self.stack.push(Slot::Iter(items));
}
Value::Iter(_) => {
// Already an iterator — use as-is.
self.stack.push(Slot::IterObject(v));
}
Value::Struct(_) | Value::EnumVariant(_) => {
// Dispatch user `.iter()`. The result
// lands on the stack as a Slot::IterObject
// via `FrameWrap::IterStart`.
let iterable = v;
self.dispatch_iter_method(
iterable,
"iter",
Vec::new(),
FrameWrap::IterStart,
line,
)?;
}
_ => {
return Err(error(
line,
nybl::error_messages::cant_iterate_over(v.type_name()),
));
}
}
}
Instr::IterNext { target } => {
match self.stack.last_mut() {
Some(Slot::Iter(items)) => {
let next = items.pop();
match next {
Some(item) => self.push_value(item),
None => {
self.stack.pop();
self.jump(target);
}
}
}
Some(Slot::IterObject(iter_val)) => {
// Synchronous fast-path for the built-in
// iterator: `iter_method::next` runs in
// Rust, no bytecode frame push required.
if matches!(iter_val, Value::Iter(_)) {
let iter_clone = iter_val.clone();
let (result, _) = methods::iter_method_in(
&iter_clone,
"next",
&[],
line,
&self.memory,
)?;
match unwrap_iter_step(&result) {
IterStep::Next(v) => self.push_value(v),
IterStep::Done => {
self.stack.pop();
self.jump(target);
}
IterStep::Malformed => {
return Err(error(
line,
format!(
"`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
result.inspect()
),
));
}
}
} else {
// User-typed iterator — dispatch
// `.next()` through the normal method
// path. The return value is handled
// in `do_return` under `IterAdvance`.
let iter_clone = iter_val.clone();
self.dispatch_iter_method(
iter_clone,
"next",
Vec::new(),
FrameWrap::IterAdvance(target),
line,
)?;
}
}
_ => return Err(error(line, "VM: expected iterator on stack")),
}
}
Instr::MakeRepeatCount => {
let v = self.pop_value(line)?;
let n = match v {
Value::Int(n) => n,
Value::Number(n) => n as i64,
other => {
return Err(error(
line,
format!("repeat needs a number, but got {}", other.type_name()),
));
}
};
self.stack.push(Slot::Repeat(n.max(0)));
}
Instr::RepeatNext { target } => {
let done = match self.stack.last_mut() {
Some(Slot::Repeat(n)) => {
if *n > 0 {
*n -= 1;
false
} else {
true
}
}
_ => return Err(error(line, "VM: expected repeat counter on stack")),
};
if done {
self.stack.pop();
self.jump(target);
}
}
Instr::PopLoopState(kind) => {
let matches_kind = matches!(
(kind, self.stack.last()),
(
LoopStateKind::Iterator,
Some(Slot::Iter(_) | Slot::IterObject(_)),
) | (LoopStateKind::Repeat, Some(Slot::Repeat(_)))
);
if !matches_kind {
let expected = match kind {
LoopStateKind::Iterator => "iterator",
LoopStateKind::Repeat => "repeat counter",
};
return Err(error(
line,
format!("VM: expected {expected} loop state on stack"),
));
}
self.stack.pop();
}
// ─── Control flow ─────────────────────────────────────
Instr::Jump(t) => self.jump(t),
Instr::JumpIfFalse(t) => {
let v = self.pop_value(line)?;
if !v.is_truthy() {
self.jump(t);
}
}
Instr::JumpIfFalsePeek(t) => {
let truthy = self.peek_value(line)?.is_truthy();
if !truthy {
self.jump(t);
}
}
Instr::JumpIfTruePeek(t) => {
let truthy = self.peek_value(line)?.is_truthy();
if truthy {
self.jump(t);
}
}
// ─── Modules ─────────────────────────────────────────
Instr::Use(idx) => {
let spec = self.current_chunk().use_spec(idx).clone();
self.exec_use(&spec, line)?;
}
// ─── User-defined types ──────────────────────────────
Instr::DefineStruct(idx) => self.define_struct(idx, line)?,
Instr::DefineEnum(idx) => self.define_enum(idx, line)?,
Instr::DefineMethod {
type_name,
method_name,
fn_idx,
} => self.define_method(type_name, method_name, fn_idx),
Instr::ValidateStructConstruct {
namespace,
type_name,
fields,
} => {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
self.validate_struct_construct(
namespace.map(|namespace| chunk.namespace_ref(namespace)),
chunk.name(type_name),
chunk.construct_fields(fields),
line,
)?;
}
Instr::ValidateEnumConstruct {
namespace,
type_name,
variant,
shape,
fields,
} => {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
self.validate_enum_construct(
namespace.map(|namespace| chunk.namespace_ref(namespace)),
chunk.name(type_name),
chunk.name(variant),
shape,
chunk.construct_fields(fields),
line,
)?;
}
Instr::ConstructStruct {
namespace,
type_name,
count,
} => {
let namespace =
namespace.map(|namespace| self.current_chunk().namespace_ref(namespace));
self.construct_struct(namespace, type_name, count as usize, line)?;
}
Instr::ConstructEnum {
namespace,
type_name,
variant,
shape,
} => {
let namespace =
namespace.map(|namespace| self.current_chunk().namespace_ref(namespace));
self.construct_enum(namespace, type_name, variant, shape, line)?;
}
Instr::FieldGet(n) => {
let field = self.current_chunk().name(n).to_string();
let obj = self.pop_value(line)?;
self.push_value(self.field_get(&obj, &field, line)?);
}
Instr::FieldSet(n) => {
let field = self.current_chunk().name(n).to_string();
let val = self.pop_value(line)?;
let obj = self.pop_value(line)?;
self.push_value(self.field_set(obj, &field, val, line)?);
}
Instr::FieldSetInPlace { target, field, op } => {
let field = self.current_chunk().name(field).to_string();
let rhs = self.pop_value(line)?;
let memory = self.memory.clone();
let value = match target {
crate::chunk::AssignBack::Slot(slot) => self
.frames
.last_mut()
.expect("frame present")
.slots
.get_mut(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?,
crate::chunk::AssignBack::Name(name_idx) => {
let name = self.current_chunk().name(name_idx).to_string();
if self.lookup_var_mut_by_idx(name_idx).is_none() {
if let Some(module) = self.module_alias(&name).cloned() {
let value = Value::Module(module);
let val = apply_in_place_assign(op, rhs, line, &memory, || {
self.field_get(&value, &field, line)
})?;
self.field_set(value, &field, val, line)?;
return Ok(Next::Continue);
}
let hint = self.value_candidates_hint(&name).unwrap_or_else(|| {
"Did you forget to create it with `let`?".to_string()
});
return Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(&name),
hint,
));
}
self.lookup_var_mut_by_idx(name_idx)
.expect("binding checked above")
}
};
match value {
Value::Struct(structure) => {
let type_name = structure.type_name().to_string();
let val = apply_in_place_assign(op, rhs, line, &memory, || {
structure.field(&field).cloned().ok_or_else(|| {
error(
line,
nybl::error_messages::struct_has_no_field(&type_name, &field),
)
})
})?;
if !structure.__try_set_field_in(&field, val, line, &memory)? {
return Err(error(
line,
nybl::error_messages::struct_has_no_field(&type_name, &field),
));
}
}
other => {
return Err(error(
line,
nybl::error_messages::cant_assign_field(&field, other.type_name()),
));
}
}
}
// ─── Pattern matching ───────────────────────────────
Instr::MatchFail { pattern, on_fail } => {
self.match_fail(pattern, on_fail, line)?;
}
Instr::MatchExhausted => {
return Err(error(line, "No match arm matched the scrutinee"));
}
// ─── try ─────────────────────────────────────────────
Instr::TryUnwrap => {
return self.try_unwrap(line);
}
// ─── Termination ──────────────────────────────────────
Instr::Halt => return Ok(Next::Halt),
}
Ok(Next::Continue)
}
// ─── Binary helpers ──────────────────────────────────────────
fn binary(
&mut self,
line: u32,
op: fn(&Value, &Value, u32) -> Result<Value, NyblError>,
) -> Result<(), NyblError> {
let b = self.pop_value(line)?;
let a = self.pop_value(line)?;
self.push_value(op(&a, &b, line)?);
Ok(())
}
fn binary_tracked(
&mut self,
line: u32,
op: fn(&Value, &Value, u32, &nybl::memory::MemoryContext) -> Result<Value, NyblError>,
) -> Result<(), NyblError> {
let b = self.pop_value(line)?;
let a = self.pop_value(line)?;
self.push_value(op(&a, &b, line, &self.memory)?);
Ok(())
}
fn binary_infallible(
&mut self,
line: u32,
op: fn(&Value, &Value, u32) -> Result<Value, NyblError>,
) -> Result<(), NyblError> {
let b = self.pop_value(line)?;
let a = self.pop_value(line)?;
self.push_value(op(&a, &b, line)?);
Ok(())
}
// ─── String interpolation ────────────────────────────────────
fn build_interp(&self, parts: &[InterpPart], line: u32) -> Result<Value, NyblError> {
let mut result = String::new();
for part in parts {
match part {
InterpPart::Literal(s) => result.push_str(s),
InterpPart::Local(slot) => {
let v = self
.frames
.last()
.and_then(|frame| frame.slots.get(slot.0 as usize))
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
result.push_str(&format!("{v}"));
}
InterpPart::Name(name_idx) => {
let name = self.current_chunk().name(*name_idx);
if let Some(value) = self.lookup_var_by_idx(*name_idx) {
result.push_str(&format!("{value}"));
} else if let Some(module) = self.module_alias(name) {
result.push_str(&format!("{}", Value::Module(Rc::clone(module))));
} else {
return Err(error(line, nybl::error_messages::variable_not_found(name)));
}
}
}
}
Ok(Value::__new_str_in(result, &self.memory))
}
// ─── Chunk accessor ──────────────────────────────────────────
fn current_chunk(&self) -> &Chunk {
&self.frames.last().expect("frame present").chunk
}
// ─── Calls ───────────────────────────────────────────────────
fn prepare_named_call(
&mut self,
name_idx: NameIdx,
site: CallSiteIdx,
line: u32,
) -> Result<(), NyblError> {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let name = chunk.name(name_idx).to_string();
let scoped = self
.current_scopes()
.iter()
.rev()
.find_map(|scope| scope.get(&name))
.cloned();
let callable = if let Some(value) = scoped {
match value {
Value::Fn(function) => PreparedCallable::Closure(function),
other => {
return Err(error(
line,
format!("`{name}` is a {}, not a function", other.type_name()),
));
}
}
} else if let Some(entry) = self
.frames
.last()
.and_then(|frame| frame.current_function_entry.as_ref())
.filter(|entry| entry.exact_self_name.as_deref() == Some(name.as_str()))
.cloned()
{
PreparedCallable::User(entry)
} else if let Some(module) = self
.frames
.last()
.and_then(|frame| frame.lexical_context.module_aliases.get(&name).cloned())
{
return Err(error(
line,
format!(
"`{name}` is a {}, not a function",
Value::Module(module).type_name()
),
));
} else if let Some(entry) = self.imported_function(&name).cloned() {
PreparedCallable::User(entry)
} else if self.frames.last().is_some_and(|frame| {
frame.is_function
&& frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
}) {
match self
.frames
.first()
.and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(&name)))
.cloned()
{
Some(Value::Fn(function)) => PreparedCallable::Closure(function),
Some(other) => {
return Err(error(
line,
format!("`{name}` is a {}, not a function", other.type_name()),
));
}
None => self
.lookup_function_entry(&name)
.map(|entry| PreparedCallable::named_user(&name, entry))
.unwrap_or_else(|| PreparedCallable::NamedFallback(name.clone())),
}
} else {
self.lookup_function_entry(&name)
.map(|entry| PreparedCallable::named_user(&name, entry))
.unwrap_or_else(|| PreparedCallable::NamedFallback(name.clone()))
};
self.preflight_call(callable, name, site, line)
}
fn prepare_value_call(
&mut self,
callee: Value,
site: CallSiteIdx,
line: u32,
) -> Result<(), NyblError> {
match callee {
Value::Fn(function) => {
let display = function.self_name.as_deref().unwrap_or("fn").to_string();
self.preflight_call(PreparedCallable::Closure(function), display, site, line)
}
other => Err(error(
line,
nybl::error_messages::cant_call_a(other.type_name()),
)),
}
}
#[allow(clippy::too_many_arguments)]
fn prepare_method_call(
&mut self,
receiver: Value,
receiver_target: Option<NamespaceRef>,
receiver_place: Option<ResolvedPlace>,
method_idx: NameIdx,
site: CallSiteIdx,
nested_place: bool,
line: u32,
) -> Result<(), NyblError> {
let method = self.current_chunk().name(method_idx).to_string();
if let Value::Module(module) = &receiver {
// Universal common methods win over same-named exports.
if matches!(method.as_str(), "type" | "to_str" | "inspect") {
return self.preflight_call(
PreparedCallable::DeferredMethod {
receiver,
method: method.clone(),
nested_place,
},
method,
site,
line,
);
}
let callee = self.module_binding(module, &method).ok_or_else(|| {
error(
line,
format!("`{method}` isn't exported from `{}`", module.path),
)
})?;
return self.prepare_value_call(callee, site, line);
}
let type_key = match &receiver {
Value::Struct(value) => Some((
value.module_path().to_string(),
value.type_name().to_string(),
)),
Value::EnumVariant(value) => Some((
value.module_path().to_string(),
value.type_name().to_string(),
)),
_ => None,
};
if let Some(type_key) = type_key
&& let Some(entry) = self
.user_methods
.get(&type_key)
.and_then(|methods| methods.get(&method))
.cloned()
{
return self.preflight_call(
PreparedCallable::UserMethod {
entry,
receiver,
receiver_target,
receiver_place,
},
format!("{}.{}", type_key.1, method),
site,
line,
);
}
if methods::is_mutating_collection_receiver(&receiver, &method)
&& let Some(place) = receiver_place
{
return self.preflight_call(
PreparedCallable::PlaceMethodInPlace {
place,
method: method.clone(),
},
method,
site,
line,
);
}
if nested_place && receiver_place.is_none() {
methods::reject_nested_array_mutation(&receiver, &method, line)?;
}
self.preflight_call(
PreparedCallable::DeferredMethod {
receiver,
method: method.clone(),
nested_place,
},
method,
site,
line,
)
}
fn prepare_named_method_call(
&mut self,
target: NamespaceRef,
method_idx: NameIdx,
site: CallSiteIdx,
line: u32,
) -> Result<(), NyblError> {
let method = self.current_chunk().name(method_idx).to_string();
let receiver_name = self.current_chunk().name(target.name_idx()).to_string();
let receiver = match target.slot_idx() {
Some(slot) => self
.frames
.last()
.and_then(|frame| frame.slots.get(slot.0 as usize))
.cloned()
.ok_or_else(|| error(line, "VM: local slot out of range"))?,
None => {
let value = self
.current_scopes()
.iter()
.rev()
.find_map(|scope| scope.get(&receiver_name))
.cloned();
match value {
Some(value) => value,
None => {
if let Some(entry) = self.lookup_function_entry(&receiver_name) {
let body: Rc<dyn core::any::Any + 'static> = entry.chunk.clone();
let function =
NyblFn::try_new_compiled_in_module_with_origin_and_modes(
entry.params.clone(),
entry.param_modes.clone(),
Vec::new(),
body,
Some(receiver_name.clone()),
Some(entry.module_path.clone()),
self.function_origin.clone(),
0,
line,
)?;
return self.prepare_method_call(
Value::Fn(function),
None,
None,
method_idx,
site,
false,
line,
);
}
if let Some(module) = self.module_alias(&receiver_name).cloned() {
return self.prepare_method_call(
Value::Module(module),
None,
None,
method_idx,
site,
false,
line,
);
}
let hint =
self.value_candidates_hint(&receiver_name)
.unwrap_or_else(|| {
"Did you forget to create it with `let`?".to_string()
});
return Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(&receiver_name),
hint,
));
}
}
}
};
if methods::is_mutating_collection_receiver(&receiver, &method) {
return self.preflight_call(
PreparedCallable::NamedMethodInPlace {
target,
method: method.clone(),
},
method,
site,
line,
);
}
self.prepare_method_call(receiver, Some(target), None, method_idx, site, false, line)
}
fn preflight_call(
&mut self,
callable: PreparedCallable,
display_name: String,
site_idx: CallSiteIdx,
line: u32,
) -> Result<(), NyblError> {
let site = self.current_chunk().call_site(site_idx).clone();
if let PreparedCallable::NamedFallback(name) = &callable {
validate_named_builtin_arity(name, site.arg_modes.len(), line)?;
}
let expected_modes: Option<&[ParamMode]> = match &callable {
PreparedCallable::User(entry) | PreparedCallable::HostThenUser { entry, .. } => {
Some(&entry.param_modes)
}
PreparedCallable::Closure(function) => Some(&function.param_modes),
PreparedCallable::UserMethod {
entry,
receiver_target,
receiver_place,
..
} => {
validate_user_arity(
&display_name,
&entry.param_modes,
site.arg_modes.len() + 1,
true,
line,
)?;
if entry.param_modes.first() == Some(&ParamMode::Ref)
&& receiver_target.is_none()
&& receiver_place.is_none()
{
let mut error =
NyblError::runtime("a `ref` method receiver must be a mutable place", line);
error.friendly_hint = Some(
"Store the value in a `let` binding, or call through one of its fields or indexes."
.to_string(),
);
return Err(error);
}
Some(&entry.param_modes[1..])
}
PreparedCallable::NamedFallback(_)
| PreparedCallable::DeferredMethod { .. }
| PreparedCallable::NamedMethodInPlace { .. }
| PreparedCallable::PlaceMethodInPlace { .. } => None,
};
if let Some(expected) = expected_modes {
validate_user_call_modes(&display_name, expected, &site.arg_modes, line)?;
} else if let Some((index, _)) = site
.arg_modes
.iter()
.enumerate()
.find(|(_, mode)| **mode == ParamMode::Ref)
{
return Err(call_mode_error(
line,
&display_name,
index,
ParamMode::Value,
));
}
if matches!(
&callable,
PreparedCallable::NamedMethodInPlace { .. }
| PreparedCallable::PlaceMethodInPlace { .. }
) || matches!(
&callable,
PreparedCallable::DeferredMethod { receiver, .. }
if !matches!(receiver, Value::Host(_))
) {
validate_builtin_method_arity(&display_name, site.arg_modes.len(), line)?;
}
if let PreparedCallable::NamedMethodInPlace { target, method } = &callable {
let receiver_name = self.current_chunk().name(target.name_idx());
methods::reject_constant_array_mutation(receiver_name, method, line)?;
if target.slot_idx().is_none()
&& self
.frames
.last()
.is_some_and(|frame| frame.captured_names.contains(receiver_name))
{
return Err(nybl::ref_params::captured_ref_target(1, line));
}
}
if let PreparedCallable::PlaceMethodInPlace { place, method } = &callable {
methods::reject_constant_array_mutation(&place.root_name, method, line)?;
self.validate_mutable_resolved_target(&place.target, &place.root_name, 0, line)?;
}
let receiver_ref = match &callable {
PreparedCallable::UserMethod {
entry,
receiver_target,
receiver_place,
..
} if entry.param_modes.first() == Some(&ParamMode::Ref) => {
if let Some(place) = receiver_place {
self.validate_mutable_resolved_target(
&place.target,
&place.root_name,
0,
line,
)?;
Some(PreparedReceiverRef::Place(place.clone()))
} else {
let recipe = receiver_target.expect("mutable receiver target was preflighted");
let name = self.current_chunk().name(recipe.name_idx());
if nybl::naming::is_constant_name(name) {
return Err(nybl::error_messages::constant_mutation_error(name, line));
}
if recipe.slot_idx().is_none()
&& self
.frames
.last()
.is_some_and(|frame| frame.captured_names.contains(name))
{
return Err(nybl::ref_params::captured_ref_target(1, line));
}
Some(PreparedReceiverRef::Binding(recipe))
}
}
_ => None,
};
let mut seen = BTreeSet::new();
if let Some(receiver) = &receiver_ref {
let identity = match receiver {
PreparedReceiverRef::Binding(recipe) => match recipe.slot_idx() {
Some(slot) => (0_u8, slot.0),
None => (1_u8, recipe.name_idx().0),
},
PreparedReceiverRef::Place(place) => match place.root_recipe.slot_idx() {
Some(slot) => (0_u8, slot.0),
None => (1_u8, place.root_recipe.name_idx().0),
},
};
seen.insert(identity);
}
let mut refs = Vec::new();
for (index, (mode, target)) in site
.arg_modes
.iter()
.zip(site.ref_targets.iter())
.enumerate()
{
if *mode != ParamMode::Ref {
continue;
}
let recipe = match target {
Some(RefArgTarget::Binding(recipe)) => RefArgTarget::Binding(*recipe),
Some(RefArgTarget::Place(place)) => RefArgTarget::Place(*place),
Some(RefArgTarget::Invalid) | None => {
return Err(invalid_ref_target_error(line, index));
}
};
let root = match recipe {
RefArgTarget::Binding(root) => root,
RefArgTarget::Place(place) => self.current_chunk().place(place).root,
RefArgTarget::Invalid => unreachable!(),
};
let name = self.current_chunk().name(root.name_idx());
if nybl::naming::is_constant_name(name) {
return Err(nybl::error_messages::constant_mutation_error(name, line));
}
if root.slot_idx().is_none()
&& self
.frames
.last()
.is_some_and(|frame| frame.captured_names.contains(name))
{
return Err(nybl::ref_params::captured_ref_target(index + 1, line));
}
let root_exists = match root.slot_idx() {
Some(slot) => self
.frames
.last()
.is_some_and(|frame| frame.slots.get(slot.0 as usize).is_some()),
None => self
.current_scopes()
.iter()
.rev()
.any(|scope| scope.contains_key(name)),
};
if !root_exists {
return Err(invalid_ref_target_error(line, index));
}
let identity = match root.slot_idx() {
Some(slot) => (0_u8, slot.0),
None => (1_u8, root.name_idx().0),
};
if !seen.insert(identity) {
return Err(duplicate_ref_target_error(line));
}
refs.push(PreparedRef {
param: index,
recipe,
index_count: match recipe {
RefArgTarget::Place(place) => self
.current_chunk()
.place(place)
.projections
.iter()
.filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
.count(),
RefArgTarget::Binding(_) | RefArgTarget::Invalid => 0,
},
});
}
let value_count = site
.arg_modes
.iter()
.filter(|mode| **mode == ParamMode::Value)
.count();
let ref_index_count = refs.iter().map(|prepared| prepared.index_count).sum();
self.frames
.last_mut()
.expect("frame present")
.prepared_calls
.push(PreparedCall {
site: site_idx,
callable,
display_name,
refs,
receiver_ref,
value_count,
ref_index_count,
});
Ok(())
}
fn call_prepared(&mut self, site: CallSiteIdx, line: u32) -> Result<Next, NyblError> {
let prepared = self
.frames
.last_mut()
.expect("frame present")
.prepared_calls
.pop()
.ok_or_else(|| error(line, "VM: missing prepared call"))?;
if prepared.site != site {
return Err(error(line, "VM: prepared call-site mismatch"));
}
let stacked = self.pop_n_values(prepared.value_count + prepared.ref_index_count, line)?;
let (ordinary, ref_indices) = stacked.split_at(prepared.value_count);
let modes = self.current_chunk().call_site(site).arg_modes.clone();
let param_offset = usize::from(matches!(
&prepared.callable,
PreparedCallable::UserMethod { .. }
));
let mut ordinary = ordinary.iter().cloned();
let mut full_args: Vec<Option<Value>> =
core::iter::repeat_with(|| None).take(modes.len()).collect();
for (index, mode) in modes.iter().enumerate() {
if *mode == ParamMode::Value {
full_args[index] = ordinary.next();
}
}
let mut pending =
Vec::with_capacity(prepared.refs.len() + usize::from(prepared.receiver_ref.is_some()));
let receiver_snapshot = if let Some(recipe) = prepared.receiver_ref {
let place = match recipe {
PreparedReceiverRef::Binding(recipe) => {
let (target, root) = self.resolve_ref_target(recipe, 0, line)?;
ResolvedPlace {
target,
root_recipe: recipe,
root_name: self.current_chunk().name(recipe.name_idx()).to_string(),
root,
projections: Vec::new(),
}
}
PreparedReceiverRef::Place(place) => self.refresh_resolved_place(place, line)?,
};
let snapshot = self.place_value_from(&place.root, &place.projections, line)?;
pending.push(PendingWriteBack {
parameter: 0,
place,
});
Some(snapshot)
} else {
None
};
let mut ref_index_offset = 0;
for prepared_ref in prepared.refs {
let next_offset = ref_index_offset + prepared_ref.index_count;
let indices = ref_indices[ref_index_offset..next_offset].to_vec();
ref_index_offset = next_offset;
let place =
self.resolve_ref_recipe(prepared_ref.recipe, indices, prepared_ref.param, line)?;
let snapshot = self.place_value_from(&place.root, &place.projections, line)?;
if pending
.iter()
.any(|write_back: &PendingWriteBack| write_back.place.target == place.target)
{
return Err(duplicate_ref_target_error(line));
}
full_args[prepared_ref.param] = Some(snapshot);
pending.push(PendingWriteBack {
parameter: prepared_ref.param + param_offset,
place,
});
}
let args = full_args
.into_iter()
.map(|value| value.ok_or_else(|| error(line, "VM: incomplete prepared arguments")))
.collect::<Result<Vec<_>, _>>()?;
let before = self.frames.len();
let next = match prepared.callable {
PreparedCallable::User(entry) => self.enter_user_fn_args(entry, args, line)?,
PreparedCallable::HostThenUser { name, entry } => {
if let Some(result) = self.host.call(&name, &args, line) {
self.push_value(result?);
return Ok(Next::Continue);
}
self.enter_user_fn_args(entry, args, line)?
}
PreparedCallable::Closure(function) => self.call_closure(&function, args, line)?,
PreparedCallable::UserMethod {
entry, receiver, ..
} => {
let mut method_args = Vec::with_capacity(args.len() + 1);
method_args.push(receiver_snapshot.unwrap_or(receiver));
method_args.extend(args);
self.enter_user_fn_args(entry, method_args, line)?
}
PreparedCallable::DeferredMethod {
receiver,
method,
nested_place,
} => {
debug_assert!(pending.is_empty());
return self.dispatch_method(receiver, &method, args, None, nested_place, line);
}
PreparedCallable::NamedMethodInPlace { target, method } => {
debug_assert!(pending.is_empty());
return self.call_method_in_place_args(target, &method, args, line);
}
PreparedCallable::PlaceMethodInPlace { place, method } => {
debug_assert!(pending.is_empty());
return self.call_method_at_place(place, &method, args, line);
}
PreparedCallable::NamedFallback(name) => {
debug_assert!(pending.is_empty());
return self.invoke_named_fallback(&name, args, line);
}
};
if !pending.is_empty() {
if self.frames.len() != before + 1 {
return Err(error(
line,
format!(
"VM: `{}` did not enter a function frame",
prepared.display_name
),
));
}
self.frames
.last_mut()
.expect("callee frame")
.pending_write_backs = pending;
}
Ok(next)
}
fn resolve_ref_target(
&self,
recipe: NamespaceRef,
position: usize,
line: u32,
) -> Result<(ResolvedRefTarget, Value), NyblError> {
self.resolve_target(recipe, position, line, true)
}
fn resolve_target(
&self,
recipe: NamespaceRef,
position: usize,
line: u32,
reject_capture: bool,
) -> Result<(ResolvedRefTarget, Value), NyblError> {
let frame_index = self.frames.len().saturating_sub(1);
let frame = self.frames.last().expect("frame present");
if let Some(slot) = recipe.slot_idx() {
let value = frame
.slots
.get(slot.0 as usize)
.cloned()
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
return Ok((
ResolvedRefTarget::Slot {
frame: frame_index,
slot,
},
value,
));
}
let name = frame.chunk.name(recipe.name_idx()).to_string();
if reject_capture && frame.captured_names.contains(&name) {
return Err(nybl::ref_params::captured_ref_target(position + 1, line));
}
for (scope_index, scope) in frame.scopes.iter().enumerate().rev() {
if let Some(value) = scope.get(&name) {
return Ok((
ResolvedRefTarget::Scope {
frame: frame_index,
scope: scope_index,
name,
},
value.clone(),
));
}
}
Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(&name),
"Did you forget to create it with `let`?",
))
}
fn validate_mutable_resolved_target(
&self,
target: &ResolvedRefTarget,
root_name: &str,
position: usize,
line: u32,
) -> Result<(), NyblError> {
if nybl::naming::is_constant_name(root_name) {
return Err(nybl::error_messages::constant_mutation_error(
root_name, line,
));
}
if let ResolvedRefTarget::Scope { frame, name, .. } = target
&& self
.frames
.get(*frame)
.is_some_and(|frame| frame.captured_names.contains(name))
{
return Err(nybl::ref_params::captured_ref_target(position + 1, line));
}
Ok(())
}
fn resolved_target_value(
&self,
target: &ResolvedRefTarget,
line: u32,
) -> Result<Value, NyblError> {
match target {
ResolvedRefTarget::Slot { frame, slot } => self
.frames
.get(*frame)
.and_then(|frame| frame.slots.get(slot.0 as usize))
.cloned()
.ok_or_else(|| error(line, "VM: mutable place slot is no longer live")),
ResolvedRefTarget::Scope { frame, scope, name } => self
.frames
.get(*frame)
.and_then(|frame| frame.scopes.get(*scope))
.and_then(|scope| scope.get(name))
.cloned()
.ok_or_else(|| error(line, "VM: mutable place binding is no longer live")),
}
}
fn store_resolved_target(
&mut self,
target: &ResolvedRefTarget,
value: Value,
line: u32,
) -> Result<(), NyblError> {
match target {
ResolvedRefTarget::Slot { frame, slot } => {
let target = self
.frames
.get_mut(*frame)
.and_then(|frame| frame.slots.get_mut(slot.0 as usize))
.ok_or_else(|| error(line, "VM: mutable place slot is no longer live"))?;
*target = value;
}
ResolvedRefTarget::Scope { frame, scope, name } => {
let target = self
.frames
.get_mut(*frame)
.and_then(|frame| frame.scopes.get_mut(*scope))
.and_then(|scope| scope.get_mut(name))
.ok_or_else(|| error(line, "VM: mutable place binding is no longer live"))?;
*target = value;
}
}
Ok(())
}
fn resolve_ref_recipe(
&self,
recipe: RefArgTarget,
indices: Vec<Value>,
position: usize,
line: u32,
) -> Result<ResolvedPlace, NyblError> {
match recipe {
RefArgTarget::Binding(root) => {
let (target, value) = self.resolve_ref_target(root, position, line)?;
Ok(ResolvedPlace {
target,
root_recipe: root,
root_name: self.current_chunk().name(root.name_idx()).to_string(),
root: value,
projections: Vec::new(),
})
}
RefArgTarget::Place(place) => self.resolve_place(place, indices, position, line),
RefArgTarget::Invalid => Err(invalid_ref_target_error(line, position)),
}
}
fn resolve_place(
&self,
place: PlaceIdx,
indices: Vec<Value>,
position: usize,
line: u32,
) -> Result<ResolvedPlace, NyblError> {
self.resolve_place_internal(place, indices, position, line, true, true)
}
fn resolve_place_internal(
&self,
place: PlaceIdx,
indices: Vec<Value>,
position: usize,
line: u32,
reject_capture: bool,
validate_path: bool,
) -> Result<ResolvedPlace, NyblError> {
let recipe = self.current_chunk().place(place);
let root_recipe = recipe.root;
let root_name = self
.current_chunk()
.name(root_recipe.name_idx())
.to_string();
let (target, root) = self.resolve_target(root_recipe, position, line, reject_capture)?;
let mut indices = indices.into_iter();
let mut projections = Vec::with_capacity(recipe.projections.len());
for projection in &recipe.projections {
projections.push(match projection {
PlaceProjectionRecipe::Index => ResolvedPlaceProjection::Index(
indices
.next()
.ok_or_else(|| error(line, "VM: missing mutable-place index"))?,
),
PlaceProjectionRecipe::Field(field) => {
ResolvedPlaceProjection::Field(self.current_chunk().name(*field).to_string())
}
});
}
if indices.next().is_some() {
return Err(error(line, "VM: too many mutable-place indices"));
}
let resolved = ResolvedPlace {
target,
root_recipe,
root_name,
root,
projections,
};
if validate_path {
let _ = self.place_value_from(&resolved.root, &resolved.projections, line)?;
}
Ok(resolved)
}
fn refresh_resolved_place(
&self,
mut place: ResolvedPlace,
line: u32,
) -> Result<ResolvedPlace, NyblError> {
place.root = self.resolved_target_value(&place.target, line)?;
let _ = self.place_value_from(&place.root, &place.projections, line)?;
Ok(place)
}
fn place_value_from(
&self,
root: &Value,
projections: &[ResolvedPlaceProjection],
line: u32,
) -> Result<Value, NyblError> {
let mut value = root.clone();
for projection in projections {
value = match projection {
ResolvedPlaceProjection::Index(index) => {
ops::index_get_in(&value, index, line, &self.memory)?
}
ResolvedPlaceProjection::Field(field) => match &value {
Value::Struct(structure) => {
structure.field(field).cloned().ok_or_else(|| {
error(
line,
nybl::error_messages::struct_has_no_field(
structure.type_name(),
field,
),
)
})?
}
other => {
return Err(error(
line,
nybl::error_messages::cant_assign_field(field, other.type_name()),
));
}
},
};
}
Ok(value)
}
fn write_place_value(
&self,
root: &mut Value,
projections: &[ResolvedPlaceProjection],
value: Value,
line: u32,
) -> Result<(), NyblError> {
let Some((projection, tail)) = projections.split_first() else {
*root = value;
return Ok(());
};
if tail.is_empty() {
return match projection {
ResolvedPlaceProjection::Index(index) => {
ops::index_set_in(root, index, value, line, &self.memory)
}
ResolvedPlaceProjection::Field(field) => {
self.set_place_field(root, field, value, line)
}
};
}
let mut child = match projection {
ResolvedPlaceProjection::Index(index) => {
ops::index_get_in(root, index, line, &self.memory)?
}
ResolvedPlaceProjection::Field(_) => {
self.place_value_from(root, core::slice::from_ref(projection), line)?
}
};
self.write_place_value(&mut child, tail, value, line)?;
match projection {
ResolvedPlaceProjection::Index(index) => {
ops::index_set_in(root, index, child, line, &self.memory)
}
ResolvedPlaceProjection::Field(field) => self.set_place_field(root, field, child, line),
}
}
fn set_place_field(
&self,
root: &mut Value,
field: &str,
value: Value,
line: u32,
) -> Result<(), NyblError> {
match root {
Value::Struct(structure) => {
let type_name = structure.type_name().to_string();
if structure.__try_set_field_in(field, value, line, &self.memory)? {
Ok(())
} else {
Err(error(
line,
nybl::error_messages::struct_has_no_field(&type_name, field),
))
}
}
other => Err(error(
line,
nybl::error_messages::cant_assign_field(field, other.type_name()),
)),
}
}
fn enter_user_fn_args(
&mut self,
entry: Rc<FnEntry>,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
if self.frames.len().saturating_sub(1) >= MAX_CALL_DEPTH {
return Err(error_with_hint(
line,
"Too many nested function calls (possible infinite recursion)",
"Check that your recursive function has a base case that stops calling itself.",
));
}
let args = self.pack_rest_arguments(args, &entry.param_modes, line)?;
let slot_count = entry.chunk.slot_count as usize;
let mut slots = self.take_slots(slot_count);
for (index, arg) in args.into_iter().enumerate() {
let slot = entry
.chunk
.parameter_slots
.get(index)
.ok_or_else(|| error(line, "VM: parameter slot metadata is incomplete"))?;
slots[slot.0 as usize] = arg;
}
self.push_function_frame(
entry.chunk.clone(),
slots,
Vec::new(),
self.stack.len(),
Some(entry.module_path.clone()),
FrameWrap::None,
);
self.frames
.last_mut()
.expect("callee frame")
.current_function_entry = Some(Rc::clone(&entry));
self.apply_entry_alias_context(&entry);
Ok(Next::Continue)
}
fn pack_rest_arguments(
&self,
mut args: Vec<Value>,
modes: &[ParamMode],
line: u32,
) -> Result<Vec<Value>, NyblError> {
if modes.last() != Some(&ParamMode::Rest) {
return Ok(args);
}
let fixed = modes.len().saturating_sub(1);
let extras = args.split_off(fixed);
let rest = Value::__try_new_array_in(extras, line, &self.memory)?;
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
args.push(rest);
Ok(args)
}
fn invoke_named_fallback(
&mut self,
name: &str,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
match name {
"range" => {
let value =
builtins::builtin_range_in(&args, line, &mut self.rand_state, &self.memory)?;
self.push_value(value);
return Ok(Next::Continue);
}
"rand" => {
let value = builtins::builtin_rand(&args, line, &mut self.rand_state)?;
self.push_value(value);
return Ok(Next::Continue);
}
"print" => {
let message = nybl::formatting::__format_values_in(&args, " ", line, &self.memory)?;
self.host.on_print(&message);
if let Some(error) = self.host.print_error(line) {
return Err(error);
}
self.push_value(Value::None);
return Ok(Next::Continue);
}
"try_call" => return self.builtin_try_call(args, line),
"panic" => {
let value = builtins::builtin_panic(&args, line)?;
self.push_value(value);
return Ok(Next::Continue);
}
_ => {}
}
let host_result = self.host.call(name, &args, line);
if let Some(result) = host_result {
self.push_value(result?);
return Ok(Next::Continue);
}
if let Some(hint) = self.callable_candidates_hint(name) {
return Err(error_with_hint(
line,
nybl::error_messages::function_not_found(name),
hint,
));
}
let host_hint = self.host.function_hint().to_string();
Err(if host_hint.is_empty() {
error(line, nybl::error_messages::function_not_found(name))
} else {
error_with_hint(
line,
nybl::error_messages::function_not_found(name),
host_hint,
)
})
}
fn call(&mut self, name_idx: NameIdx, argc: usize, line: u32) -> Result<Next, NyblError> {
// Borrow the name out of the chunk without allocating a
// fresh `String` per call — `fib(25)` dispatches this
// path ~75 000 times and even one small allocation per
// call shows up in profiles. Holding a local `Rc<Chunk>`
// keeps the name slice valid for the whole body.
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let name: &str = chunk.name(name_idx);
// Check lexical shadowing first (a `let f = fn() {...}`
// must win over a same-named builtin / user fn). We peek
// rather than clone so the common case — no shadow —
// pays nothing.
let current_value = self
.current_scopes()
.iter()
.rev()
.find_map(|scope| scope.get(name))
.cloned();
if let Some(value) = current_value {
let args = self.pop_n_values(argc, line)?;
return match &value {
Value::Fn(f) => {
let f = Rc::clone(f);
drop(value);
self.call_closure(&f, args, line)
}
other => Err(error(
line,
format!("`{}` is a {}, not a function", name, other.type_name()),
)),
};
}
// A defining-module declaration alias is a protected value binding.
// Keep the borrowed local peek above as the hot path, then consult the
// lexical context only when no local/parameter shadows the name. Clone
// the module handle solely on this rare alias-call error path.
let declaration_alias = self.frames.last().and_then(|frame| {
if frame.lexical_context.module_aliases.is_empty() {
None
} else {
frame.lexical_context.module_aliases.get(name).cloned()
}
});
if let Some(module) = declaration_alias {
let _args = self.pop_n_values(argc, line)?;
return Err(error(
line,
format!(
"`{}` is a {}, not a function",
name,
Value::Module(module).type_name()
),
));
}
if let Some(entry) = self.imported_function(name).cloned() {
validate_user_arity(name, &entry.param_modes, argc, false, line)?;
drop(chunk);
return self.enter_user_fn(entry, argc, line);
}
if self.frames.last().is_some_and(|frame| {
frame.is_function
&& frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
}) {
let root_value = self
.frames
.first()
.and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(name)))
.cloned();
if let Some(value) = root_value {
let args = self.pop_n_values(argc, line)?;
return match &value {
Value::Fn(function) => {
let function = Rc::clone(function);
self.call_closure(&function, args, line)
}
other => Err(error(
line,
format!("`{}` is a {}, not a function", name, other.type_name()),
)),
};
}
}
// User-fn hot path: if `name` is a declared fn and no
// local shadow exists, pop args straight into the new
// frame's scope — no intermediate `Vec<Value>` allocation
// per call. Callsite profile on `fib(28)` showed this
// path taking ~90 % of all dispatched calls; eliminating
// the per-call `Vec` cost takes ~500 000 small heap
// allocations off the table.
//
// SAFETY-of-reorder: we've already ruled out lexical
// shadowing above, so moving the user-fn check in front
// of builtins / host matches the "let wins over fn; fn
// wins over builtin" ordering the walker uses. (Walker:
// locals checked at Call site, then call_function
// matches builtins — a user-defined `fn print` never
// reaches this path because `print` isn't in the
// walker's `functions` table before `fn print` runs.
// Same here: DefineFn populates `self.functions` only
// for user-declared names, so builtins like `range`,
// `print` don't collide.)
if let Some(entry) = self.lookup_function_entry(name) {
// Argc check before we touch the stack so error
// messages match the walker's `name` wording.
validate_user_arity(name, &entry.param_modes, argc, false, line)?;
drop(chunk);
return self.enter_user_fn(entry, argc, line);
}
// Everything from here down needs the args as a
// contiguous slice, so pay the `Vec` cost once.
let args = self.pop_n_values(argc, line)?;
// 1. Global builtins — the narrow set that can't be
// expressed as methods on a receiver (variadic,
// constructor-shape, session-stateful, or takes a
// callable). Everything that used to live here is now
// a method; see `methods::common_method` and
// `methods::numeric_method`.
match name {
"range" => {
let v =
builtins::builtin_range_in(&args, line, &mut self.rand_state, &self.memory)?;
self.push_value(v);
return Ok(Next::Continue);
}
"rand" => {
let v = builtins::builtin_rand(&args, line, &mut self.rand_state)?;
self.push_value(v);
return Ok(Next::Continue);
}
"print" => {
let message = nybl::formatting::__format_values_in(&args, " ", line, &self.memory)?;
self.host.on_print(&message);
if let Some(error) = self.host.print_error(line) {
return Err(error);
}
self.push_value(Value::None);
return Ok(Next::Continue);
}
"try_call" => return self.builtin_try_call(args, line),
"panic" => {
// `builtin_panic` always returns `Err`; the `Ok`
// arm is unreachable, but matching keeps the
// compiler happy and keeps this branch symmetric
// with the other builtins.
let v = builtins::builtin_panic(&args, line)?;
self.push_value(v);
return Ok(Next::Continue);
}
_ => {}
}
// 2. Host-provided builtins.
let host_result = self.host.call(name, &args, line);
if let Some(result) = host_result {
let v = result?;
self.push_value(v);
return Ok(Next::Continue);
}
// Nothing left to try — the name is unresolved. The
// user-fn fast path above already handled the success
// case; we only reach here when no declared fn matches
// either, so we can go straight to the "did you mean?"
// / host-hint path.
if let Some(hint) = self.callable_candidates_hint(name) {
return Err(error_with_hint(
line,
nybl::error_messages::function_not_found(name),
hint,
));
}
let host_hint = self.host.function_hint().to_string();
Err(if host_hint.is_empty() {
error(line, nybl::error_messages::function_not_found(name))
} else {
error_with_hint(
line,
nybl::error_messages::function_not_found(name),
host_hint,
)
})
}
/// Fast path for user-defined function calls: pop `argc`
/// args straight off the value stack into the new frame's
/// parameter scope, and push the frame. No intermediate
/// `Vec<Value>`. Assumes the caller has already validated
/// `argc == entry.params.len()` so the per-call error
/// message can include the target name.
fn enter_user_fn(
&mut self,
entry: Rc<FnEntry>,
argc: usize,
line: u32,
) -> Result<Next, NyblError> {
if entry.param_modes.last() == Some(&ParamMode::Rest) {
let args = self.pop_n_values(argc, line)?;
return self.enter_user_fn_args(entry, args, line);
}
if self.frames.len().saturating_sub(1) >= MAX_CALL_DEPTH {
return Err(error_with_hint(
line,
"Too many nested function calls (possible infinite recursion)",
"Check that your recursive function has a base case that stops calling itself.",
));
}
if self.stack.len() < argc {
return Err(error(line, "VM: stack underflow"));
}
// Build the frame's flat slot array. Positional arguments rebind their
// canonical language slots in source order; the rest of `slot_count`
// is pre-seeded with `None` so later `StoreLocal`s land in-bounds.
// Backing allocation comes from the freelist when possible — ~500k
// per-call heap allocs under `fib(28)` fold into a steady-state set of
// ~MAX_CALL_DEPTH reused vecs.
let slot_count = entry.chunk.slot_count as usize;
let mut slots = self.take_slots(slot_count);
let start = self.stack.len() - argc;
for i in 0..argc {
let slot = core::mem::replace(&mut self.stack[start + i], Slot::Value(Value::None));
match slot {
Slot::Value(v) => {
let parameter_slot =
entry.chunk.parameter_slots.get(i).ok_or_else(|| {
error(line, "VM: parameter slot metadata is incomplete")
})?;
slots[parameter_slot.0 as usize] = v;
}
_ => {
self.stack.truncate(start);
self.return_slots(slots);
return Err(error(line, "VM: expected value on stack"));
}
}
}
self.stack.truncate(start);
self.push_function_frame(
entry.chunk.clone(),
slots,
// Function frames don't use the BTreeMap scope stack
// on the fast path — captures are on the `Value::Fn`
// itself (handled in `call_closure`), and all locals
// live in `slots`. An empty `scopes` vec is cheap to
// allocate and keeps `LoadVar` / `DefineLocal` from
// panicking if they still get emitted (they shouldn't
// inside a fn body, but the fallback is safe).
Vec::new(),
self.stack.len(),
Some(entry.module_path.clone()),
FrameWrap::None,
);
self.frames
.last_mut()
.expect("callee frame")
.current_function_entry = Some(Rc::clone(&entry));
self.apply_entry_alias_context(&entry);
// A fresh type_bindings frame scopes any type decl
// inside this fn to the fn body itself — same rule
// as push_scope / pop_scope for block scoping. On
// `do_return` we pop this frame.
Ok(Next::Continue)
}
/// Dispatch a value-based call: the callee sits on top of the
/// `argc` args. Pops all `argc + 1` slots,
/// expects the callee to be a `Value::Fn`, and delegates to
/// `call_closure`.
fn call_value(&mut self, argc: usize, line: u32) -> Result<Next, NyblError> {
let callee = self.pop_value(line)?;
let args = self.pop_n_values(argc, line)?;
self.invoke_value(callee, args, line)
}
/// Invoke an already-evaluated callable with already-popped
/// args. Shared between `Instr::CallValue` and the
/// `Value::Module` fast path in `call_method` (where
/// `m.foo(...)` resolves the fn through a module field
/// lookup rather than going through the stack callee slot).
fn invoke_value(
&mut self,
callee: Value,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
match &callee {
Value::Fn(f) => {
let f = Rc::clone(f);
drop(callee);
self.call_closure(&f, args, line)
}
other => Err(error(
line,
nybl::error_messages::cant_call_a(other.type_name()),
)),
}
}
fn call_method(
&mut self,
method_idx: NameIdx,
argc: usize,
assign_back_to: Option<crate::chunk::AssignBack>,
nested_place: bool,
line: u32,
) -> Result<Next, NyblError> {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let method = chunk.name(method_idx);
let obj = self.pop_value(line)?;
let args = self.pop_n_values(argc, line)?;
self.dispatch_method(obj, method, args, assign_back_to, nested_place, line)
}
fn call_method_in_place(
&mut self,
target: crate::chunk::NamespaceRef,
method_idx: NameIdx,
argc: usize,
line: u32,
) -> Result<Next, NyblError> {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let method = chunk.name(method_idx);
let args = self.pop_n_values(argc, line)?;
self.call_method_in_place_args(target, method, args, line)
}
fn call_method_in_place_args(
&mut self,
target: crate::chunk::NamespaceRef,
method: &str,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let memory = self.memory.clone();
let receiver_idx = target.name_idx();
let receiver_name = chunk.name(receiver_idx);
// The compiler only emits this instruction for a bare identifier and
// a built-in mutating method name. Resolve the binding after argument
// evaluation, matching the walker/AOT order. Arrays and dicts take
// the direct path; every other value is cloned once for ordinary
// dispatch so a user type is still free to define a method named
// `push`, `pop`, etc.
let (fallback, assign_back) = match target.slot_idx() {
Some(slot) => {
let value = self
.frames
.last_mut()
.expect("frame present")
.slots
.get_mut(slot.0 as usize)
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
if methods::is_mutating_collection_receiver(value, method) {
methods::reject_constant_array_mutation(receiver_name, method, line)?;
let result = methods::transactional_collection_method_in(
value, method, args, line, &memory,
)?;
self.push_value(result);
return Ok(Next::Continue);
}
(value.clone(), crate::chunk::AssignBack::Slot(slot))
}
None => {
if self.lookup_var_mut_by_idx(receiver_idx).is_none() {
if let Some(module) = self.module_alias(receiver_name).cloned() {
return self.dispatch_method(
Value::Module(module),
method,
args,
None,
false,
line,
);
}
let hint = self
.value_candidates_hint(receiver_name)
.unwrap_or_else(|| "Did you forget to create it with `let`?".to_string());
return Err(error_with_hint(
line,
nybl::error_messages::variable_not_found(receiver_name),
hint,
));
}
let value = self
.lookup_var_mut_by_idx(receiver_idx)
.expect("binding checked above");
if methods::is_mutating_collection_receiver(value, method) {
methods::reject_constant_array_mutation(receiver_name, method, line)?;
let result = methods::transactional_collection_method_in(
value, method, args, line, &memory,
)?;
self.push_value(result);
return Ok(Next::Continue);
}
(value.clone(), crate::chunk::AssignBack::Name(receiver_idx))
}
};
self.dispatch_method(fallback, method, args, Some(assign_back), false, line)
}
fn call_method_at_place(
&mut self,
place: ResolvedPlace,
method: &str,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
let place = self.refresh_resolved_place(place, line)?;
let mut receiver = self.place_value_from(&place.root, &place.projections, line)?;
methods::reject_constant_array_mutation(&place.root_name, method, line)?;
let result = methods::transactional_collection_method_in(
&mut receiver,
method,
args,
line,
&self.memory,
)?;
let mut root = place.root.clone();
self.write_place_value(&mut root, &place.projections, receiver, line)?;
self.store_resolved_target(&place.target, root, line)?;
self.push_value(result);
Ok(Next::Continue)
}
fn dispatch_method(
&mut self,
obj: Value,
method: &str,
args: Vec<Value>,
assign_back_to: Option<crate::chunk::AssignBack>,
nested_place: bool,
line: u32,
) -> Result<Next, NyblError> {
// `m.foo(args)` on a module alias: there's no struct /
// enum receiver — `m` is a `Value::Module` whose `foo`
// export is a callable. Look it up and dispatch through
// the regular call-by-value path.
//
// Before falling through to the binding lookup, check
// whether the method name is one of the common methods
// (`type`, `to_str`, `inspect`). Those work on every
// value, including `Value::Module`, and shouldn't be
// gated by whether the module happens to export that
// name.
if let Value::Module(ref m) = obj {
if let Some(result) =
methods::common_method_in(&obj, method, &args, line, &self.memory)?
{
self.push_value(result.0);
return Ok(Next::Continue);
}
if let Some(callee) = self.module_binding(m, method) {
drop(obj);
return self.invoke_value(callee, args, line);
}
return Err(error(
line,
format!("`{}` isn't exported from `{}`", method, m.path),
));
}
// User-method dispatch comes first — any method declared
// on the receiver's full type identity wins over the
// built-in method of the same name, matching the walker.
// Dispatch is strict: `fn paint.Color.shade(self)` never
// fires on `other.Color` even though the bare name is
// the same.
let user_type_key: Option<(String, String)> = match &obj {
Value::Struct(s) => Some((s.module_path().to_string(), s.type_name().to_string())),
Value::EnumVariant(e) => Some((e.module_path().to_string(), e.type_name().to_string())),
_ => None,
};
if let Some(type_key) = user_type_key {
let entry = self
.user_methods
.get(&type_key)
.and_then(|m| m.get(method))
.cloned();
if let Some(entry) = entry {
validate_user_arity(
&format!("{}.{}", type_key.1, method),
&entry.param_modes,
args.len() + 1,
true,
line,
)?;
let mut method_args = Vec::with_capacity(args.len() + 1);
method_args.push(obj);
method_args.extend(args);
self.enter_user_fn_args(entry, method_args, line)?;
// Legacy `CallMethod` only reaches value-only methods. Calls
// with a `ref` receiver or explicit ref arguments use the
// prepared-call path above, which owns their atomic
// write-backs. Keep the legacy assignment recipe unused here.
let _ = assign_back_to;
return Ok(Next::Continue);
}
}
if nested_place {
methods::reject_nested_array_mutation(&obj, method, line)?;
}
// `type` / `to_str` / `inspect` work on every value —
// dispatch them ahead of the type-specific tables so
// walker / VM / AOT agree on the common method surface.
if let Some((ret, _)) = methods::common_method_in(&obj, method, &args, line, &self.memory)?
{
self.push_value(ret);
return Ok(Next::Continue);
}
// Built-in `Result` combinators. Pure methods (`is_ok`,
// `unwrap`, …) return through the regular path; callable-
// taking ones (`map`, `map_err`, `and_then`) push a
// closure frame with a `FrameWrap` that wraps the return
// in `Ok`/`Err` or passes it through.
if methods::is_builtin_result(&obj) {
if let Some(v) = methods::result_method(&obj, method, &args, line)? {
self.push_value(v);
return Ok(Next::Continue);
}
if let Some(kind) = methods::is_result_callable_method(method) {
return self.call_result_callable_method(obj, kind, method, args, line);
}
}
let (ret, mutated) = match &obj {
Value::Array(arr) => methods::array_method_in(arr, method, &args, line, &self.memory)?,
Value::Str(s) => {
methods::string_method_in(s.as_str(), method, &args, line, &self.memory)?
}
Value::Dict(entries) => {
methods::dict_method_in(entries, method, &args, line, &self.memory)?
}
Value::Int(_) | Value::Number(_) => methods::numeric_method(&obj, method, &args, line)?,
Value::Bool(_) => methods::bool_method(&obj, method, &args, line)?,
Value::Iter(_) => methods::iter_method_in(&obj, method, &args, line, &self.memory)?,
Value::Host(value) => {
let result = self.host.call_method(value, method, &args, line);
match result {
Some(result) => (result?, None),
None => {
return Err(error(
line,
nybl::error_messages::no_such_method(obj.type_name(), method),
));
}
}
}
_ => {
return Err(error(
line,
nybl::error_messages::no_such_method(obj.type_name(), method),
));
}
};
if methods::is_mutating_method(method)
&& let (Some(target), Some(new_obj)) = (assign_back_to, mutated)
{
match target {
crate::chunk::AssignBack::Slot(slot) => {
let frame = self.frames.last_mut().expect("frame present");
let i = slot.0 as usize;
if i < frame.slots.len() {
frame.slots[i] = new_obj;
}
// Out-of-range slot: silently drop the
// mutation. The compiler only emits
// `Slot(i)` for a slot it knows exists,
// so this branch is effectively a
// miscompile guard.
}
crate::chunk::AssignBack::Name(var_idx) => {
let var_name = self.current_chunk().name(var_idx).to_string();
self.set_existing(&var_name, new_obj);
}
}
}
self.push_value(ret);
Ok(Next::Continue)
}
fn define_struct(&mut self, idx: StructIdx, line: u32) -> Result<(), NyblError> {
let def = self.current_chunk().struct_def(idx).clone();
let mut seen = BTreeSet::new();
for field in &def.fields {
if !seen.insert(field.clone()) {
return Err(error(
line,
format!("Struct `{}` has duplicate field `{}`", def.name, field),
));
}
}
// Type identity is `(current_module, def.name)`. Two
// different modules declaring the same name coexist at
// distinct registry keys; same-module redecl is a no-op
// on matching shape and an error otherwise.
let key = (self.current_module.clone(), def.name.clone());
if let Some(existing) = self.struct_defs.get(&key) {
if existing == &def.fields {
self.bind_local_type(&def.name);
return Ok(());
}
return Err(error(
line,
format!("Struct `{}` is already declared", def.name),
));
}
self.struct_defs.insert(key, def.fields);
self.bind_local_type(&def.name);
Ok(())
}
fn define_enum(&mut self, idx: EnumIdx, line: u32) -> Result<(), NyblError> {
let def = self.current_chunk().enum_def(idx).clone();
let variants: Vec<(String, EnumVariantShape)> = def
.variants
.into_iter()
.map(|v| (v.name, v.shape))
.collect();
let key = (self.current_module.clone(), def.name.clone());
if let Some(existing) = self.enum_defs.get(&key) {
if shapes_match(existing, &variants) {
self.bind_local_type(&def.name);
return Ok(());
}
return Err(error(
line,
format!("Enum `{}` is already declared", def.name),
));
}
let mut seen_variants = BTreeSet::new();
for (variant, shape) in &variants {
if !seen_variants.insert(variant.clone()) {
return Err(error(
line,
format!("Enum `{}` has duplicate variant `{}`", def.name, variant),
));
}
let fields = match shape {
EnumVariantShape::Unit => continue,
EnumVariantShape::Tuple(fields) | EnumVariantShape::Struct(fields) => fields,
};
let mut seen_fields = BTreeSet::new();
for field in fields {
if !seen_fields.insert(field.clone()) {
return Err(error(
line,
format!(
"Enum variant `{}::{}` has duplicate field `{}`",
def.name, variant, field
),
));
}
}
}
self.enum_defs.insert(key, variants);
self.bind_local_type(&def.name);
Ok(())
}
/// Bind a declared type's bare name in the current
/// `type_bindings` frame so subsequent references resolve
/// to *this* module's version.
fn bind_local_type(&mut self, name: &str) {
if let Some(scope) = self.type_bindings.last_mut() {
scope.insert(name.to_string(), self.current_module.clone());
}
if self.is_module_top_scope() {
self.type_exports
.insert(name.to_string(), self.current_module.clone());
self.publish_root_type_binding(name.to_string(), self.current_module.clone());
}
}
fn define_method(&mut self, type_name: NameIdx, method_name: NameIdx, fn_idx: FnIdx) {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let type_name_s = chunk.name(type_name).to_string();
let method_name_s = chunk.name(method_name).to_string();
let fn_def = chunk.function(fn_idx);
let entry = Rc::new(FnEntry {
exact_self_name: None,
params: fn_def.params.clone(),
param_modes: fn_def.param_modes.clone(),
chunk: Rc::clone(&fn_def.chunk),
module_path: self.current_module.clone(),
declaration_alias_names: self
.frames
.last()
.expect("defining frame")
.lexical_context
.module_aliases
.keys()
.cloned()
.collect(),
});
// Methods attach to the *full* receiver-type identity.
// A method declared inside `paint` for `Color` only
// fires on `paint.Color` values, not on same-named
// types from other modules.
let key = (self.current_module.clone(), type_name_s);
self.user_methods
.entry(key)
.or_default()
.insert(method_name_s, entry);
}
fn construct_struct(
&mut self,
namespace: Option<crate::chunk::NamespaceRef>,
type_name: NameIdx,
count: usize,
line: u32,
) -> Result<(), NyblError> {
let type_name_s = self.current_chunk().name(type_name).to_string();
// Resolve the source-level reference to its full type
// identity before validating the shape. `namespace`
// means `ns.Type { ... }`; bare means the scope walker
// looks up `Type` in `type_bindings`.
let module_path = match namespace {
Some(namespace) => self.resolve_namespaced_type(namespace, &type_name_s, line)?,
None => self.resolve_type_ref(None, &type_name_s).ok_or_else(|| {
error(
line,
nybl::error_messages::struct_not_declared(&type_name_s),
)
})?,
};
let key = (module_path.clone(), type_name_s.clone());
let decl = self
.struct_defs
.get(&key)
.ok_or_else(|| {
error(
line,
nybl::error_messages::struct_not_declared(&type_name_s),
)
})?
.clone();
let flat = self.pop_n_values(count * 2, line)?;
let mut provided: BTreeMap<String, Value> = BTreeMap::new();
let mut iter = flat.into_iter();
while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
let key_str = match &key {
Value::Str(s) => s.as_str().to_string(),
other => {
return Err(error(
line,
format!(
"Struct field names must be strings, got {}",
other.type_name()
),
));
}
};
drop(key);
if provided.contains_key(&key_str) {
return Err(error(
line,
format!("Field `{key_str}` specified twice in `{type_name_s}` construction"),
));
}
if !decl.iter().any(|d| d == &key_str) {
let msg = nybl::error_messages::struct_has_no_field(&type_name_s, &key_str);
let err =
match nybl::suggest::did_you_mean(&key_str, decl.iter().map(|s| s.as_str())) {
Some(hint) => error_with_hint(line, msg, hint),
None => error(line, msg),
};
return Err(err);
}
provided.insert(key_str, val);
}
let mut fields: Vec<(String, Value)> = Vec::with_capacity(decl.len());
for d in &decl {
match provided.remove(d) {
Some(v) => fields.push((d.clone(), v)),
None => {
return Err(error(
line,
format!("Missing field `{d}` in `{type_name_s}` construction"),
));
}
}
}
self.push_value(Value::__try_new_struct_in(
module_path,
type_name_s,
fields,
line,
&self.memory,
)?);
Ok(())
}
fn validate_struct_construct(
&self,
namespace: Option<crate::chunk::NamespaceRef>,
type_name: &str,
provided: &[String],
line: u32,
) -> Result<(), NyblError> {
let module_path = match namespace {
Some(namespace) => self.resolve_namespaced_type(namespace, type_name, line)?,
None => self
.resolve_type_ref(None, type_name)
.ok_or_else(|| error(line, nybl::error_messages::struct_not_declared(type_name)))?,
};
let declared = self
.struct_defs
.get(&(module_path, type_name.to_string()))
.ok_or_else(|| error(line, nybl::error_messages::struct_not_declared(type_name)))?;
for (index, field) in provided.iter().enumerate() {
if provided[..index].contains(field) {
return Err(error(
line,
format!("Field `{field}` specified twice in `{type_name}` construction"),
));
}
if !declared.contains(field) {
let message = nybl::error_messages::struct_has_no_field(type_name, field);
return match nybl::suggest::did_you_mean(
field,
declared.iter().map(|name| name.as_str()),
) {
Some(hint) => Err(error_with_hint(line, message, hint)),
None => Err(error(line, message)),
};
}
}
for field in declared {
if !provided.contains(field) {
return Err(error(
line,
format!("Missing field `{field}` in `{type_name}` construction"),
));
}
}
Ok(())
}
fn validate_enum_construct(
&self,
namespace: Option<crate::chunk::NamespaceRef>,
type_name: &str,
variant: &str,
shape: EnumConstructShape,
provided: &[String],
line: u32,
) -> Result<(), NyblError> {
let module_path = match namespace {
Some(namespace) => self.resolve_namespaced_type(namespace, type_name, line)?,
None => self
.resolve_type_ref(None, type_name)
.ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(type_name)))?,
};
let variants = self
.enum_defs
.get(&(module_path, type_name.to_string()))
.ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(type_name)))?;
let declared = variants
.iter()
.find(|(name, _)| name == variant)
.map(|(_, shape)| shape)
.ok_or_else(|| {
let message = nybl::error_messages::enum_has_no_variant(type_name, variant);
match nybl::suggest::did_you_mean(
variant,
variants.iter().map(|(name, _)| name.as_str()),
) {
Some(hint) => error_with_hint(line, message, hint),
None => error(line, message),
}
})?;
match (declared, shape) {
(EnumVariantShape::Unit, EnumConstructShape::Unit) => Ok(()),
(EnumVariantShape::Tuple(fields), EnumConstructShape::Tuple(argc)) => {
if fields.len() == argc as usize {
Ok(())
} else {
Err(error(
line,
format!(
"`{}::{}` expects {} argument{}, but got {}",
type_name,
variant,
fields.len(),
if fields.len() == 1 { "" } else { "s" },
argc
),
))
}
}
(EnumVariantShape::Struct(fields), EnumConstructShape::Struct(_)) => {
for (index, field) in provided.iter().enumerate() {
if provided[..index].contains(field) {
return Err(error(
line,
format!("Field `{field}` specified twice in `{type_name}::{variant}`"),
));
}
if !fields.contains(field) {
return Err(error(
line,
nybl::error_messages::variant_has_no_field(type_name, variant, field),
));
}
}
for field in fields {
if !provided.contains(field) {
return Err(error(
line,
format!(
"Missing field `{field}` in `{type_name}::{variant}` construction"
),
));
}
}
Ok(())
}
(EnumVariantShape::Unit, _) => Err(error(
line,
format!("Variant `{type_name}::{variant}` takes no payload"),
)),
(EnumVariantShape::Tuple(_), _) => Err(error(
line,
format!("Variant `{type_name}::{variant}` expects positional arguments `(…)`"),
)),
(EnumVariantShape::Struct(_), _) => Err(error(
line,
format!("Variant `{type_name}::{variant}` expects named fields `{{ … }}`"),
)),
}
}
fn construct_enum(
&mut self,
namespace: Option<crate::chunk::NamespaceRef>,
type_name: NameIdx,
variant: NameIdx,
shape: EnumConstructShape,
line: u32,
) -> Result<(), NyblError> {
let type_name_s = self.current_chunk().name(type_name).to_string();
let variant_s = self.current_chunk().name(variant).to_string();
let module_path = match namespace {
Some(namespace) => self.resolve_namespaced_type(namespace, &type_name_s, line)?,
None => self.resolve_type_ref(None, &type_name_s).ok_or_else(|| {
error(line, nybl::error_messages::enum_not_declared(&type_name_s))
})?,
};
let key = (module_path.clone(), type_name_s.clone());
let decl = self
.enum_defs
.get(&key)
.ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(&type_name_s)))?
.clone();
let variant_decl = decl
.iter()
.find(|(n, _)| n == &variant_s)
.cloned()
.ok_or_else(|| {
let msg = nybl::error_messages::enum_has_no_variant(&type_name_s, &variant_s);
match nybl::suggest::did_you_mean(&variant_s, decl.iter().map(|(n, _)| n.as_str()))
{
Some(hint) => error_with_hint(line, msg, hint),
None => error(line, msg),
}
})?;
match (&variant_decl.1, shape) {
(EnumVariantShape::Unit, EnumConstructShape::Unit) => {
self.push_value(Value::__new_enum_unit_in(
module_path,
type_name_s,
variant_s,
&self.memory,
));
}
(EnumVariantShape::Tuple(fields), EnumConstructShape::Tuple(argc)) => {
if fields.len() as u32 != argc {
return Err(error(
line,
format!(
"`{}::{}` expects {} argument{}, but got {}",
type_name_s,
variant_s,
fields.len(),
if fields.len() == 1 { "" } else { "s" },
argc
),
));
}
let items = self.pop_n_values(argc as usize, line)?;
self.push_value(Value::__try_new_enum_tuple_in(
module_path,
type_name_s,
variant_s,
items,
line,
&self.memory,
)?);
}
(EnumVariantShape::Struct(decl_fields), EnumConstructShape::Struct(count)) => {
let flat = self.pop_n_values(count as usize * 2, line)?;
let mut provided: BTreeMap<String, Value> = BTreeMap::new();
let mut iter = flat.into_iter();
while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
let key_str = match &key {
Value::Str(s) => s.as_str().to_string(),
_ => {
return Err(error(
line,
"Enum struct-variant field names must be strings",
));
}
};
drop(key);
if provided.contains_key(&key_str) {
return Err(error(
line,
format!(
"Field `{key_str}` specified twice in `{type_name_s}::{variant_s}`"
),
));
}
if !decl_fields.iter().any(|d| d == &key_str) {
return Err(error(
line,
nybl::error_messages::variant_has_no_field(
&type_name_s,
&variant_s,
&key_str,
),
));
}
provided.insert(key_str, val);
}
let mut fields: Vec<(String, Value)> = Vec::with_capacity(decl_fields.len());
for d in decl_fields {
match provided.remove(d) {
Some(v) => fields.push((d.clone(), v)),
None => {
return Err(error(
line,
format!(
"Missing field `{d}` in `{type_name_s}::{variant_s}` construction"
),
));
}
}
}
self.push_value(Value::__try_new_enum_struct_in(
module_path,
type_name_s,
variant_s,
fields,
line,
&self.memory,
)?);
}
(EnumVariantShape::Unit, _) => {
return Err(error(
line,
format!("Variant `{type_name_s}::{variant_s}` takes no payload"),
));
}
(EnumVariantShape::Tuple(_), _) => {
return Err(error(
line,
format!(
"Variant `{type_name_s}::{variant_s}` expects positional arguments `(…)`"
),
));
}
(EnumVariantShape::Struct(_), _) => {
return Err(error(
line,
format!("Variant `{type_name_s}::{variant_s}` expects named fields `{{ … }}`"),
));
}
}
Ok(())
}
fn field_get(&self, obj: &Value, field: &str, line: u32) -> Result<Value, NyblError> {
match obj {
Value::Struct(s) => s.field(field).cloned().ok_or_else(|| {
let msg = nybl::error_messages::struct_has_no_field(s.type_name(), field);
let names = s.fields().iter().map(|(k, _)| k.as_str());
match nybl::suggest::did_you_mean(field, names) {
Some(hint) => error_with_hint(line, msg, hint),
None => error(line, msg),
}
}),
Value::EnumVariant(e) => e.field(field).cloned().ok_or_else(|| {
error(
line,
nybl::error_messages::variant_has_no_field(e.type_name(), e.variant(), field),
)
}),
Value::Module(m) => {
if let Some(v) = self.module_binding(m, field) {
return Ok(v);
}
if m.has_type(field) {
return Err(error(
line,
format!("`{}` in `{}` is a type, not a value", field, m.path),
));
}
Err(error(
line,
format!("`{}` isn't exported from `{}`", field, m.path),
))
}
other => Err(error(
line,
nybl::error_messages::cant_read_field(field, other.type_name()),
)),
}
}
fn field_set(
&self,
mut obj: Value,
field: &str,
value: Value,
line: u32,
) -> Result<Value, NyblError> {
// Mutate the owned value and return it to the generic opcode caller.
// Named-field assignment uses `FieldSetInPlace` instead so its
// receiver stays off the stack and cannot spuriously trigger a detach.
match &mut obj {
Value::Struct(boxed) => {
let type_name = boxed.type_name().to_string();
if !boxed.__try_set_field_in(field, value, line, &self.memory)? {
return Err(error(
line,
nybl::error_messages::struct_has_no_field(&type_name, field),
));
}
Ok(obj)
}
other => Err(error(
line,
nybl::error_messages::cant_assign_field(field, other.type_name()),
)),
}
}
/// Handle a `MatchFail` instruction: pop the scrutinee and
/// attempt to match it against the pattern at `pattern`. On
/// success, install the captured bindings into the current
/// scope and fall through. On failure, jump to `on_fail`.
///
/// Delegates to `nybl::pattern_matches_in` so the VM behaves
/// exactly like the tree-walker on every pattern shape.
fn match_fail(
&mut self,
pattern: PatternIdx,
on_fail: CodeOffset,
line: u32,
) -> Result<(), NyblError> {
let value = self.pop_value(line)?;
// `pattern` refers to a slot in the *currently executing*
// chunk's pattern pool; clone the shared handle rather than hold a
// frame borrow while mutating `self` to install bindings.
let recipe = self.current_chunk().pattern(pattern).clone();
let mut bindings: Vec<(String, Value)> = Vec::new();
// Build a resolver snapshot from the current frame's
// value scopes plus the VM-level type_bindings and
// alias map. Patterns referring to `Color::Red` or
// `m.Color::Red` thread through this so the matcher can
// compare the value's full identity.
let frame = self.frames.last().expect("frame present");
let frame_scopes = &frame.scopes;
let type_bindings = &self.type_bindings;
let module_aliases = &self.module_aliases;
let resolver = |ns: Option<&str>, tn: &str| -> Option<String> {
if let Some(ns) = ns
&& let Some(slot) = recipe
.namespaces
.iter()
.find(|(name, _)| name == ns)
.map(|(_, namespace)| namespace)
.and_then(|namespace| namespace.slot_idx())
{
return match frame.slots.get(slot.0 as usize) {
Some(Value::Module(module)) => module.type_origin(tn).map(str::to_string),
_ => None,
};
}
resolve_type_in_frame(frame, frame_scopes, type_bindings, module_aliases, ns, tn)
};
let matched = nybl::pattern_matches_in(
&recipe.pattern,
&value,
&mut bindings,
&resolver,
&self.memory,
);
if matched {
for (name, v) in bindings {
self.define_local(name, v);
}
} else {
self.jump(on_fail);
}
Ok(())
}
/// Implement `try`: pop the top value and inspect the
/// `Ok` / `Err` shape.
///
/// - `Ok(v)` (single tuple payload) / `Ok` (unit) → push the
/// unwrapped value (`v` or `Value::None`) and continue.
/// - `Err(...)` → act like `Return` from the current frame,
/// carrying the whole `Err` variant as the returned value.
/// If the current frame is the top-level program, raise a
/// runtime error instead (there's no fn to return from).
/// - Anything else → runtime error.
///
/// Mirrors the walker's `eval_try` so all three engines agree
/// on the same shape recognition rules.
fn try_unwrap(&mut self, line: u32) -> Result<Next, NyblError> {
let value = self.pop_value(line)?;
match &value {
Value::EnumVariant(ev) if ev.variant() == "Ok" => {
use nybl::value::EnumPayload;
let payload = match ev.payload() {
EnumPayload::Tuple(items) if items.len() == 1 => items[0].clone(),
EnumPayload::Unit => Value::None,
EnumPayload::Tuple(items) => {
return Err(error(
line,
format!(
"try: Ok variant must carry exactly one value, got {}",
items.len()
),
));
}
EnumPayload::Struct(_) => {
return Err(error(
line,
"try: Ok variant must carry a single positional value, not named fields",
));
}
};
self.push_value(payload);
Ok(Next::Continue)
}
Value::EnumVariant(ev) if ev.variant() == "Err" => {
let current_is_fn = self.frames.last().map(|f| f.is_function).unwrap_or(false);
if !current_is_fn {
return Err(nybl::error_messages::top_level_try_error(line));
}
// Fast-return with the Err value: identical path
// to an ordinary `return err`.
self.do_return(value, line)
}
other => Err(error(
line,
format!(
"try expected a Result-shaped value (Ok/Err variant), got {}",
other.type_name()
),
)),
}
}
fn define_fn(&mut self, idx: FnIdx) {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let fn_def = chunk.function(idx);
let name = fn_def.name.clone();
let entry = Rc::new(FnEntry {
exact_self_name: Some(name.clone()),
params: fn_def.params.clone(),
param_modes: fn_def.param_modes.clone(),
chunk: Rc::clone(&fn_def.chunk),
module_path: self.active_module_path().to_string(),
declaration_alias_names: self
.frames
.last()
.expect("defining frame")
.lexical_context
.module_aliases
.keys()
.cloned()
.collect(),
});
self.functions.insert(name.clone(), Rc::clone(&entry));
if self.is_module_top_scope()
&& self.current_module == nybl::value::ROOT_MODULE_PATH
&& let Some(visibility) = self.root_function_visibility.get(&idx.0).copied()
{
self.abi_declarations
.retain(|(existing, _)| existing != &name);
if visibility == Visibility::Public {
self.abi_declarations.push((name, entry));
}
}
}
/// Materialise a lambda expression as a `Value::Fn`. Each
/// `CaptureSource` in the lambda's `FnDef` tells us exactly
/// where to read the captured value from the enclosing frame
/// — no "flatten every binding in sight" pass, and no
/// over-capture of out-of-scope slots.
fn make_lambda(&mut self, idx: FnIdx, line: u32) -> Result<(), NyblError> {
let chunk = Rc::clone(&self.frames.last().expect("frame present").chunk);
let fn_def = chunk.function(idx);
let captures = self.snapshot_captures_for(fn_def);
let compiled_chunk = Rc::clone(&fn_def.chunk);
let body: Rc<dyn core::any::Any + 'static> = compiled_chunk;
let value = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
fn_def.params.clone(),
fn_def.param_modes.clone(),
captures,
body,
None,
Some(self.active_module_path().to_string()),
self.function_origin.clone(),
0,
line,
)
.map(Value::Fn)?;
self.push_value(value);
Ok(())
}
/// Package the captures for a lambda according to its
/// compile-time `capture_sources`. `ParentSlot(n)` reads slot
/// `n` from the enclosing frame; `ParentScope(name)` walks
/// the enclosing frame's BTreeMap scope stack to find the
/// binding.
///
/// A missing `ParentScope` binding is skipped rather than
/// represented by `Value::None`. Absence and a binding whose
/// value is genuinely `none` are observably different: leaving
/// an absent name uncaptured lets the lambda body's normal
/// `LoadVar` / call path resolve a named function or report
/// `Variable not found`.
fn snapshot_captures_for(&self, fn_def: &FnDef) -> Vec<(String, Value)> {
let frame = self.frames.last().expect("frame present");
let mut out = Vec::with_capacity(fn_def.capture_names.len());
for (name, source) in fn_def
.capture_names
.iter()
.zip(fn_def.capture_sources.iter())
{
match source {
CaptureSource::ParentSlot(slot) => {
let v = frame
.slots
.get(slot.0 as usize)
.cloned()
.unwrap_or(Value::None);
out.push((name.clone(), v));
}
CaptureSource::ParentScope(look_name) => {
let mut found = None;
let defining_environment_floor =
usize::from(frame.defining_environment_module.is_some());
for scope in frame.scopes.iter().skip(defining_environment_floor).rev() {
if let Some(v) = scope.get(look_name.as_str()) {
found = Some(v.clone());
break;
}
}
if let Some(v) = found {
out.push((name.clone(), v));
}
}
};
}
out
}
/// Call a `Value::Fn` by pushing a new frame whose scope holds
/// the closure's captures plus its parameters (plus the
/// closure itself under `self_name`, when present, so
/// self-reference works without a separate pathway).
fn call_closure(
&mut self,
func: &Rc<NyblFn>,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
if !func.__is_allowed_by(&self.function_origin, "vm") {
return Err(error(
line,
"This function belongs to a different Nybl engine instance",
));
}
// The body must be a VM-compiled chunk. Walker-created
// `Value::Fn`s would carry `FnBody::Ast` and don't belong
// in the VM.
let chunk: Rc<Chunk> = match &func.body {
FnBody::Compiled(any) => match Rc::clone(any).downcast::<Chunk>() {
Ok(c) => c,
Err(_) => {
return Err(error(
line,
"Closure body wasn't compiled by the bytecode VM",
));
}
},
FnBody::Ast(_) => {
return Err(error(
line,
"Closure body wasn't compiled for the VM — use `nybl::run` to execute tree-walker closures",
));
}
};
let display_name = func.self_name.as_deref().unwrap_or("fn");
validate_user_arity(display_name, &func.param_modes, args.len(), false, line)?;
let args = self.pack_rest_arguments(args, &func.param_modes, line)?;
if self.frames.len().saturating_sub(1) >= MAX_CALL_DEPTH {
return Err(error_with_hint(
line,
"Too many nested function calls (possible infinite recursion)",
"Check that your recursive function has a base case that stops calling itself.",
));
}
// Lambda params + locals go into the flat `slots` array
// (same fast path as named fns). Captures and the
// `self_name` self-reference stay on the BTreeMap scope
// stack — they're looked up by name at the compile-time
// fallback path (`LoadVar`) because the compiler can't
// resolve them to slots from inside the lambda body.
let slot_count = chunk.slot_count as usize;
let mut slots = self.take_slots(slot_count);
for (i, arg) in args.into_iter().enumerate() {
let slot = chunk
.parameter_slots
.get(i)
.ok_or_else(|| error(line, "VM: parameter slot metadata is incomplete"))?;
slots[slot.0 as usize] = arg;
}
let mut scope = BTreeMap::new();
for (name, value) in &func.captures {
scope.insert(name.clone(), value.clone());
}
if let Some(self_name) = &func.self_name {
scope.insert(self_name.clone(), Value::Fn(Rc::clone(func)));
}
self.push_function_frame(
chunk,
slots,
vec![scope],
self.stack.len(),
func.module_path.clone(),
FrameWrap::None,
);
if let Some(frame) = self.frames.last_mut() {
frame.captured_names = func.captures.iter().map(|(name, _)| name.clone()).collect();
}
Ok(Next::Continue)
}
/// Execute a `use` statement. Dispatches the four shapes
/// (glob / selective / aliased / selective + aliased) against
/// the module's exported bindings. Types register globally
/// on every form; the distinction is in how the caller sees
/// the module's *values and fns* (flat in their scope vs.
/// behind a namespace binding).
fn exec_use(&mut self, spec: &crate::chunk::UseSpec, line: u32) -> Result<(), NyblError> {
let refresh_root_context = self.is_module_top_scope();
let path = spec.path.as_str();
let items = spec.items.as_deref();
let alias = spec.alias.as_deref();
let is_plain_glob = items.is_none() && alias.is_none();
if is_plain_glob
&& self
.imported_here
.last()
.is_some_and(|imports| imports.contains(path))
{
return Ok(());
}
// A lazily evaluated dependency may import the module that is
// currently executing. Move that active environment into the shared
// registry for the duration of loading so the nested VM observes and
// updates the one authoritative handle rather than a cached snapshot.
self.park_active_defining_environment();
let loaded = self.load_module(path, line);
self.restore_active_defining_environment();
let artifacts = loaded?;
// Types always register under their *full identity*
// `(module_path, type_name)`. Two modules declaring the
// same name now coexist at distinct keys; same-key
// reinsertion is idempotent on matching shape and a
// hard error otherwise (means the module was re-loaded
// with different source).
for (key, fields) in &artifacts.struct_defs {
if let Some(existing) = self.struct_defs.get(key) {
if existing == fields {
continue;
}
return Err(error(
line,
format!(
"Type `{}` from `{}` reloaded with different fields",
key.1, key.0
),
));
}
self.struct_defs.insert(key.clone(), fields.clone());
}
for (key, variants) in &artifacts.enum_defs {
if let Some(existing) = self.enum_defs.get(key) {
if shapes_match(existing, variants) {
continue;
}
return Err(error(
line,
format!(
"Type `{}` from `{}` reloaded with different variants",
key.1, key.0
),
));
}
self.enum_defs.insert(key.clone(), variants.clone());
}
for (type_key, method_name, entry) in &artifacts.methods {
self.user_methods
.entry(type_key.clone())
.or_default()
.insert(method_name.clone(), entry.clone());
}
// Gather the module's value-level exports as a single
// name-keyed list. Fn declarations produce both a
// scope-visible `Value::Fn` and a `self.functions` entry;
// plain let bindings contribute just the value.
let mut exports: Vec<(String, Value)> =
Vec::with_capacity(artifacts.fn_decls.len() + artifacts.bindings.len());
let mut fn_entries: BTreeMap<String, Rc<FnEntry>> = BTreeMap::new();
for (name, entry) in &artifacts.fn_decls {
if artifacts
.bindings
.iter()
.any(|(binding, _)| binding == name)
{
continue;
}
let chunk_rc: Rc<Chunk> = entry.chunk.clone();
let body: Rc<dyn core::any::Any + 'static> = chunk_rc;
let value = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
entry.params.clone(),
entry.param_modes.clone(),
Vec::new(),
body,
Some(name.clone()),
Some(entry.module_path.clone()),
self.function_origin.clone(),
0,
line,
)
.map(Value::Fn)?;
exports.push((name.clone(), value));
fn_entries.insert(name.clone(), entry.clone());
}
for (name, value) in &artifacts.bindings {
exports.push((name.clone(), value.clone()));
}
// Functions and values are stored separately inside module artifacts,
// but a flat import exposes one namespace. Sorting the combined
// projection makes warning order match the walker and generated AOT.
exports.sort_by(|(left, _), (right, _)| left.cmp(right));
// Selective filter: ensure every listed name exists, then
// retain only the listed exports.
if let Some(list) = items {
let available: BTreeSet<&str> = exports.iter().map(|(k, _)| k.as_str()).collect();
for wanted in list {
if !available.contains(wanted.as_str())
&& !artifacts.type_exports.contains_key(wanted)
{
return Err(error(
line,
format!("`{wanted}` isn't exported from `{path}` (selective import)"),
));
}
}
let listed: BTreeSet<String> = list.iter().cloned().collect();
exports.retain(|(k, _)| listed.contains(k));
fn_entries.retain(|name, _| listed.contains(name));
}
// Decide which of the module's declared type names the
// caller sees by bare name. Selective = exactly the
// listed items that are types; glob = all public
// (non-`_`-prefixed) types; aliased = none at bare name
// (only reachable through the alias).
let exposed_types: BTreeMap<String, String> = match items {
Some(list) => artifacts
.type_exports
.iter()
.filter(|(name, _)| list.iter().any(|item| item == *name))
.map(|(name, origin)| (name.clone(), origin.clone()))
.collect(),
None => artifacts
.type_exports
.iter()
.filter(|(name, _)| {
artifacts.explicit_surface || alias.is_some() || !nybl::naming::is_private(name)
})
.map(|(name, origin)| (name.clone(), origin.clone()))
.collect(),
};
if let Some(alias_name) = alias {
// Aliased form: pack the exports into a Value::Module
// and bind it under the alias. The alias lives in the
// current frame's top scope. Function values retain
// their defining module, so sibling calls resolve
// through cached module artifacts without publishing
// bare names in this caller.
let frame_has = self
.frames
.last()
.and_then(|f| f.scopes.last())
.map(|s| s.contains_key(alias_name))
.unwrap_or(false);
let imported_function_has = self
.imported_functions
.last()
.is_some_and(|functions| functions.contains_key(alias_name));
if frame_has || self.functions.contains_key(alias_name) || imported_function_has {
return Err(error(
line,
format!("`{alias_name}` is already bound — can't use it as a module alias"),
));
}
let live_bindings = exports
.iter()
.map(|(name, _)| {
let origin = artifacts
.binding_origins
.get(name)
.cloned()
.unwrap_or_else(|| (path.to_string(), name.clone()));
(name.clone(), origin)
})
.collect();
let module_rc = nybl::value::NyblModule::__try_new_live_with_type_exports(
path.to_string(),
exports,
nybl::value::NyblTypeExports::from_origins(exposed_types),
live_bindings,
Rc::clone(&self.live_value_environments),
line,
)?;
// Bind the alias three ways:
// 1. as Value::Module in the current value scope
// (immediate `m.helper(x)` at the use site);
// 2. in `module_aliases` so it survives the
// fresh-scope reset at fn call boundaries;
// 3. in `type_bindings` so patterns + construction
// resolve `m.Type` inside fn bodies.
let module_value = Value::Module(Rc::clone(&module_rc));
if let Some(frame) = self.frames.last_mut()
&& let Some(scope) = frame.scopes.last_mut()
{
scope.insert(alias_name.to_string(), module_value);
}
self.module_aliases
.last_mut()
.expect("module alias scope")
.insert(alias_name.to_string(), Rc::clone(&module_rc));
if let Some(scope) = self.type_bindings.last_mut() {
scope.insert(alias_name.to_string(), path.to_string());
}
if refresh_root_context {
self.publish_root_module_alias(alias_name.to_string(), Some(Rc::clone(&module_rc)));
self.publish_root_type_binding(alias_name.to_string(), path.to_string());
}
} else {
// Flat form (glob / selective). Glob skips
// `_`-prefixed names (privacy); selective doesn't
// (the user explicitly asked).
let skip_private = items.is_none() && !artifacts.explicit_surface;
let module_top_scope = self.is_module_top_scope();
for (name, mut value) in exports {
if skip_private && nybl::naming::is_private(&name) {
continue;
}
let clashes = self
.frames
.last()
.and_then(|f| f.scopes.last())
.map(|s| s.contains_key(&name))
.unwrap_or(false)
|| (module_top_scope && self.functions.contains_key(&name))
// Slot-allocated locals / params never appear in
// dynamic scope maps. Their shared lexical-scope
// index plus this use site's binding frontier keeps
// the same first-definition-wins check logarithmic.
|| self.local_scope_shadows(spec.local_scope, &name);
if clashes {
if is_plain_glob {
self.runtime_warnings.push(NyblWarning::at(
nybl::error_messages::glob_shadow_warning(&name, path),
line,
));
}
continue;
}
if let Some(entry) = fn_entries.remove(&name) {
self.imported_functions
.last_mut()
.expect("imported function scope")
.insert(name.clone(), Rc::clone(&entry));
if module_top_scope {
self.publish_root_imported_function(name.clone(), entry);
}
}
let module = artifacts.module_exports.get(&name).cloned();
let origin = artifacts
.binding_origins
.get(&name)
.cloned()
.unwrap_or_else(|| (path.to_string(), name.clone()));
if module_top_scope {
self.binding_origins.insert(name.clone(), origin.clone());
if (origin.0 != self.current_module || origin.1 != name)
&& let Some(authoritative) = self
.live_value_environments
.borrow_mut()
.get_mut(&origin.0)
.and_then(|environment| environment.remove(&origin.1))
{
value = authoritative;
}
} else if let Some(current) = self.live_origin_value(&origin) {
value = current;
}
if let Some(frame) = self.frames.last_mut()
&& let Some(scope) = frame.scopes.last_mut()
{
scope.insert(name.clone(), value);
}
if let Some(module) = module {
self.module_aliases
.last_mut()
.expect("module alias scope")
.insert(name.clone(), Rc::clone(&module));
if module_top_scope {
self.publish_root_module_alias(name, Some(module));
}
}
}
// Bring the module's exposed types in by bare name
// too — `Color::Red` now resolves to *this*
// module's Color. First-win on conflict matches the
// value-binding rule.
for (type_name, origin) in &exposed_types {
let already_bound = self
.type_bindings
.last()
.map(|s| s.contains_key(type_name))
.unwrap_or(false);
if already_bound {
continue;
}
if let Some(scope) = self.type_bindings.last_mut() {
scope.insert(type_name.clone(), origin.clone());
}
if module_top_scope {
self.type_exports
.entry(type_name.clone())
.or_insert_with(|| origin.clone());
self.publish_root_type_binding(type_name.clone(), origin.clone());
}
}
}
if is_plain_glob {
self.imported_here
.last_mut()
.expect("import scope")
.insert(path.to_string());
}
Ok(())
}
fn local_scope_shadows(
&self,
snapshot: Option<crate::chunk::LocalScopeSnapshot>,
name: &str,
) -> bool {
let Some(snapshot) = snapshot else {
return false;
};
let chunk = self.current_chunk();
let scope = &chunk.local_scopes[snapshot.scope.0 as usize];
scope
.entries
.binary_search_by(|entry| chunk.name(entry.name).cmp(name))
.is_ok_and(|index| scope.entries[index].first_binding < snapshot.binding_count)
}
/// Validate `ns.Type` — confirm `ns` binds a `Value::Module`
/// whose type exports include `type_name`. Used by
/// namespaced struct-literal / variant-ctor dispatch.
fn resolve_namespaced_type(
&self,
namespace: crate::chunk::NamespaceRef,
type_name: &str,
line: u32,
) -> Result<String, NyblError> {
let name = self.current_chunk().name(namespace.name_idx());
let Some(slot) = namespace.slot_idx() else {
self.validate_namespaced_type(name, type_name, line)?;
return self.resolve_type_ref(Some(name), type_name).ok_or_else(|| {
error(
line,
format!("`{type_name}` isn't a type exported from `{name}`"),
)
});
};
let value = self
.frames
.last()
.and_then(|frame| frame.slots.get(slot.0 as usize))
.ok_or_else(|| error(line, "VM: local slot out of range"))?;
let module = match value {
Value::Module(module) => module,
other => {
return Err(error(
line,
format!(
"`{name}` is a {}, not a module alias — can't reach `{type_name}` through it",
other.type_name()
),
));
}
};
module
.type_origin(type_name)
.map(str::to_string)
.ok_or_else(|| {
error(
line,
format!("`{type_name}` isn't a type exported from `{}`", module.path),
)
})
}
fn validate_namespaced_type(
&self,
ns: &str,
type_name: &str,
line: u32,
) -> Result<(), NyblError> {
// Prefer a local value-scope binding (catches
// shadowing), but fall back to the VM-level module
// alias map so namespaced references inside fn bodies
// still resolve — the fn frame's value scopes don't
// carry the caller's aliases.
let frame = self
.frames
.last()
.ok_or_else(|| error(line, "VM: no frame for namespaced type access"))?;
for scope in frame.scopes.iter().rev() {
if let Some(v) = scope.get(ns) {
let module = match v {
Value::Module(m) => m,
other => {
return Err(error(
line,
format!(
"`{}` is a {}, not a module alias — can't reach `{}` through it",
ns,
other.type_name(),
type_name
),
));
}
};
if !module.has_type(type_name) {
return Err(error(
line,
format!(
"`{}` isn't a type exported from `{}`",
type_name, module.path
),
));
}
return Ok(());
}
}
if let Some(module) = self.module_alias(ns) {
if !module.has_type(type_name) {
return Err(error(
line,
format!(
"`{}` isn't a type exported from `{}`",
type_name, module.path
),
));
}
return Ok(());
}
Err(error(line, format!("`{ns}` isn't a module alias in scope")))
}
/// Resolve a source-level type reference to its declaring
/// module. Shared scope walker between construction,
/// pattern matching, and namespace validation: keeps
/// resolution rules centralised.
fn resolve_type_ref(&self, namespace: Option<&str>, type_name: &str) -> Option<String> {
let frame = self.frames.last()?;
resolve_type_in_frame(
frame,
&frame.scopes,
&self.type_bindings,
&self.module_aliases,
namespace,
type_name,
)
}
fn load_module(&mut self, path: &str, line: u32) -> Result<ModuleArtifacts, NyblError> {
{
let cache = self.imports.borrow();
if let Some(ImportSlot::Loaded(bindings)) = cache.get(path) {
return Ok(bindings.clone());
}
if let Some(ImportSlot::Loading) = cache.get(path) {
return Err(error(
line,
format!("Circular import: module `{path}` is still loading"),
));
}
}
let resolved = self.host.resolve_module(path);
let source = match resolved {
Some(Ok(s)) => s,
Some(Err(e)) => return Err(e),
None => {
return Err(error(line, format!("Module `{path}` not found")));
}
};
self.imports
.borrow_mut()
.insert(path.to_string(), ImportSlot::Loading);
let result = self
.evaluate_module(path, &source)
.map_err(|error| error.with_module_source(path, source.as_str()));
match result {
Ok(bindings) => {
self.imports
.borrow_mut()
.insert(path.to_string(), ImportSlot::Loaded(bindings.clone()));
Ok(bindings)
}
Err(e) => {
self.imports.borrow_mut().remove(path);
Err(e)
}
}
}
/// Parse, compile, and execute a module in a nested VM that
/// shares the import cache and limits. Returns the module's
/// top-level `(name, Value)` bindings, with named fns reified
/// as `Value::Fn` carrying VM-compiled chunks so the caller's
/// `Call` / `CallValue` paths can dispatch them directly.
fn evaluate_module(
&mut self,
module_path: &str,
source: &str,
) -> Result<ModuleArtifacts, NyblError> {
let stmts = nybl::parse(source)?;
let chunk = crate::compile(&stmts)?;
let public_surface = chunk.public_surface.clone();
let module_runtime = ModuleRuntime {
imports: Rc::clone(&self.imports),
environments: Rc::clone(&self.live_value_environments),
origins: Rc::clone(&self.live_binding_origins),
};
let limits = self.limits.clone();
let mut sub = Vm::new_internal(
chunk,
self.host,
limits,
module_runtime,
module_path.to_string(),
BTreeMap::new(),
self.function_origin.clone(),
self.memory.clone(),
);
let module_result = sub.run_internal();
// Nested module VMs are an implementation detail of the root
// operation. Preserve their diagnostics (including transitive ones)
// and defer stderr delivery to that operation's public boundary.
self.runtime_warnings.append(&mut sub.runtime_warnings);
if let Err(module_error) = module_result {
sub.restore_instance_baseline();
let failed_environment = sub
.frames
.first_mut()
.and_then(|frame| frame.scopes.first_mut())
.map(core::mem::take)
.unwrap_or_default();
put_live_environment(
&sub.live_value_environments,
module_path,
failed_environment,
&sub.binding_origins,
);
// Forwarded bindings have been returned to their declaration
// modules; the failed facade's partial state must not survive.
sub.live_value_environments.borrow_mut().remove(module_path);
sub.live_binding_origins.borrow_mut().remove(module_path);
return Err(module_error);
}
// Collect top-level lets from the module frame's one
// remaining scope…
let mut bindings = match sub
.frames
.first()
.and_then(|frame| frame.scopes.first())
.map(|scope| {
snapshot_module_bindings(scope, &sub.binding_origins, module_path, &sub.imports, 0)
})
.transpose()
{
Ok(bindings) => bindings.unwrap_or_default(),
Err(snapshot_error) => {
let failed_environment = sub
.frames
.first_mut()
.and_then(|frame| frame.scopes.first_mut())
.map(core::mem::take)
.unwrap_or_default();
put_live_environment(
&sub.live_value_environments,
module_path,
failed_environment,
&sub.binding_origins,
);
sub.live_value_environments.borrow_mut().remove(module_path);
sub.live_binding_origins.borrow_mut().remove(module_path);
return Err(snapshot_error);
}
};
let live_environment = sub
.frames
.first_mut()
.and_then(|frame| frame.scopes.first_mut())
.map(core::mem::take)
.unwrap_or_default();
let binding_origins = sub.binding_origins.clone();
put_live_environment(
&sub.live_value_environments,
module_path,
live_environment,
&binding_origins,
);
sub.live_binding_origins
.borrow_mut()
.insert(module_path.to_string(), binding_origins.clone());
// Named fn entries go out separately so the importer
// can register them in `self.functions` for bare-ident
// call resolution. Reified `Value::Fn`s for the same
// fns are synthesised at the import site (see
// `exec_import`).
let mut fn_decls: Vec<(String, Rc<FnEntry>)> = sub.functions.into_iter().collect();
// Type decls & methods come along for the ride — the
// importer needs them so pattern-matching and
// construction against the module's types works
// without re-declaration. Engine builtins (<builtin>
// module path) are already seeded in the importer, so
// we filter them out to avoid duplicating the entries.
let builtin_mp = nybl::value::BUILTIN_MODULE_PATH;
let struct_defs: Vec<ModuleStructDef> = sub
.struct_defs
.into_iter()
.filter(|((mp, _), _)| mp != builtin_mp)
.collect();
let enum_defs: Vec<ModuleEnumDef> = sub
.enum_defs
.into_iter()
.filter(|((mp, _), _)| mp != builtin_mp)
.collect();
let mut methods: Vec<ModuleMethodDef> = Vec::new();
for (type_key, by_method) in sub.user_methods {
for (method_name, entry) in by_method {
methods.push((type_key.clone(), method_name, entry));
}
}
let all_module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>> = bindings
.iter()
.filter_map(|(name, value)| match value {
Value::Module(module) => Some((name.clone(), Rc::clone(module))),
_ => None,
})
.collect();
let mut lexical_context = Rc::try_unwrap(core::mem::take(&mut sub.root_lexical_context))
.unwrap_or_else(|context| (*context).clone());
lexical_context.module_aliases = Rc::new(all_module_exports.clone());
let lexical_context = Rc::new(lexical_context);
let mut type_exports = sub.type_exports;
let explicit_surface = public_surface.is_some();
if let Some(names) = public_surface {
let names: BTreeSet<String> = names.into_iter().collect();
bindings.retain(|(name, _)| names.contains(name));
fn_decls.retain(|(name, _)| names.contains(name));
type_exports.retain(|name, _| names.contains(name));
}
let module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>> = bindings
.iter()
.filter_map(|(name, value)| match value {
Value::Module(module) => Some((name.clone(), Rc::clone(module))),
_ => None,
})
.collect();
Ok(ModuleArtifacts {
explicit_surface,
bindings,
binding_origins,
fn_decls,
struct_defs,
enum_defs,
methods,
type_exports,
module_exports,
lexical_context,
})
}
/// Like `run` but keeps `self` around afterwards so the
/// caller can inspect the module's final state. Used by
/// `evaluate_module`.
fn run_internal(&mut self) -> Result<(), NyblError> {
while let Some((instr, line)) = self.fetch() {
if let Err(err) = self.tick(line) {
let err = self.attach_frame_module_context(err);
self.unwind_to_try_call(err)?;
continue;
}
match self.dispatch(instr, line) {
Ok(Next::Continue) => {}
Ok(Next::Halt) => break,
Err(err) => {
let err = self.attach_frame_module_context(err);
self.unwind_to_try_call(err)?;
}
}
}
Ok(())
}
fn do_return(&mut self, value: Value, line: u32) -> Result<Next, NyblError> {
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
if self.frames.last().is_some_and(|frame| !frame.is_function) {
drop(value);
let frame = self.frames.last_mut().expect("frame present");
frame.ip = frame.chunk.code.len();
frame.scopes.truncate(frame.scope_base);
self.stack.clear();
self.type_bindings.truncate(frame.type_scope_base);
self.module_aliases.truncate(frame.alias_scope_base);
self.imported_functions.truncate(frame.alias_scope_base);
self.imported_here.truncate(frame.alias_scope_base);
return Ok(Next::Halt);
}
// Pop the current frame, truncate any frame-local stack
// residue, and push the return value for the caller.
let mut frame = self.frames.pop().expect("frame present");
self.store_frame_defining_environment(&mut frame);
self.restore_active_defining_environment();
self.stack.truncate(frame.stack_base);
// Drop the function's protected type-binding scope plus any runtime
// scopes skipped by an early return. Top-level return preserves the
// builtin map while discarding any open runtime scopes.
self.type_bindings.truncate(frame.caller_type_scope_depth());
self.module_aliases.truncate(frame.alias_scope_base);
self.imported_functions.truncate(frame.alias_scope_base);
self.imported_here.truncate(frame.alias_scope_base);
// Iterator-protocol landing pads get their own return
// handling — they don't just push the value; they
// manipulate the caller's stack (and maybe jump) to
// continue the for-loop.
match frame.wrap {
FrameWrap::IterStart => {
// User `.iter()` returned `value`. Stash it on
// the stack as the iterator object for the
// matching `IterNext` instruction to consume.
self.stack.push(Slot::IterObject(value));
return Ok(Next::Continue);
}
FrameWrap::IterAdvance(target) => {
// User `.next()` returned `value`; dispatch:
// Iter::Next(x) → push x so the following
// StoreLocal/DefineLocal binds the loop var.
// Iterator object stays on the stack under x.
// Iter::Done → pop the iterator, jump exit.
// malformed → raise.
match unwrap_iter_step(&value) {
IterStep::Next(x) => {
drop(value);
self.push_value(x);
return Ok(Next::Continue);
}
IterStep::Done => {
drop(value);
self.stack.pop();
self.jump(target);
return Ok(Next::Continue);
}
IterStep::Malformed => {
let msg = format!(
"`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
value.inspect()
);
// The returning frame no longer has a
// meaningful "current line" — use the
// top frame's instruction line as the
// best approximation. 0 is fine if we're
// returning to the top-level frame.
let caller_line = self
.frames
.last()
.and_then(|f| {
let idx = f.ip.saturating_sub(1);
f.chunk.lines.get(idx).copied()
})
.unwrap_or(0);
return Err(error(caller_line, msg));
}
}
}
_ => {}
}
// Apply the frame-level return wrapper: `try_call` wraps
// in `Result::Ok`, `r.map` / `r.map_err` wrap the closure
// result in Ok / Err respectively. Plain frames pass the
// value through untouched.
let final_value = match frame.wrap {
FrameWrap::None => value,
FrameWrap::TryCall { line } => {
builtins::make_try_call_ok_in(value, line, &self.memory)?
}
FrameWrap::ResultOk { line } => methods::make_result_ok_in(value, line, &self.memory)?,
FrameWrap::ResultErr { line } => {
methods::make_result_err_in(value, line, &self.memory)?
}
FrameWrap::IterStart | FrameWrap::IterAdvance(_) => {
unreachable!("handled above")
}
};
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
// All fallible return processing is complete. Validate every resolved
// target before the first store, then perform the infallible copy-out
// as one user-observable commit.
self.commit_frame_write_backs(&frame, line)?;
// Recycle the slot vec only after copy-out has read the staged ref
// parameters.
if !frame.slots.is_empty() {
self.return_slots(core::mem::take(&mut frame.slots));
}
if frame.is_function {
self.push_value(final_value);
Ok(Next::Continue)
} else {
// Return at top level: behave like Halt (matches tree-walker,
// which silently accepts Signal::Return at program scope).
drop(final_value);
Ok(Next::Halt)
}
}
fn commit_frame_write_backs(&mut self, frame: &Frame, line: u32) -> Result<(), NyblError> {
if frame.pending_write_backs.is_empty() {
return Ok(());
}
let mut values = Vec::with_capacity(frame.pending_write_backs.len());
for pending in &frame.pending_write_backs {
let parameter_slot = frame
.chunk
.parameter_slots
.get(pending.parameter)
.ok_or_else(|| error(line, "VM: ref parameter metadata is incomplete"))?;
let value = frame
.slots
.get(parameter_slot.0 as usize)
.cloned()
.ok_or_else(|| error(line, "VM: ref parameter slot out of range"))?;
let mut root = self.resolved_target_value(&pending.place.target, line)?;
self.write_place_value(&mut root, &pending.place.projections, value, line)?;
values.push(root);
}
for (pending, value) in frame.pending_write_backs.iter().zip(values) {
self.store_resolved_target(&pending.place.target, value, line)?;
}
Ok(())
}
/// Implement the `try_call(f)` builtin. Validates the arg
/// shape, dispatches to `call_closure` to push a frame for
/// `f`, and marks that frame with `FrameWrap::TryCall` so
/// the outcome (whether a normal return or a non-fatal
/// error) gets wrapped in a `Result::Ok`/`Result::Err`
/// before returning to the original `try_call` caller.
fn builtin_try_call(&mut self, args: Vec<Value>, line: u32) -> Result<Next, NyblError> {
if args.len() != 1 {
return Err(error(
line,
format!("`try_call` expects 1 argument, but got {}", args.len()),
));
}
let mut iter = args.into_iter();
let callable = iter.next().unwrap();
let func = match &callable {
Value::Fn(f) => Rc::clone(f),
other => {
return Err(error(
line,
format!("`try_call` expects a function, got {}", other.type_name()),
));
}
};
drop(callable);
if let Err(err) = self.call_closure(&func, Vec::new(), line) {
if err.is_fatal {
return Err(err);
}
self.push_value(builtins::make_try_call_err_in(&err, &self.memory));
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
return Ok(Next::Continue);
}
// The frame we just pushed is the one that should
// participate in the try_call wrap/catch dance.
if let Some(frame) = self.frames.last_mut() {
frame.wrap = FrameWrap::TryCall { line };
}
Ok(Next::Continue)
}
/// Dispatch `receiver.method(args)` as a user-method call
/// for the iterator protocol. Pushes a bytecode frame with
/// `wrap` attached so the return value lands on the caller's
/// stack with the right post-processing. Returns a clean
/// "iterable doesn't have a .iter() method" error when the
/// user type doesn't implement the protocol.
fn dispatch_iter_method(
&mut self,
receiver: Value,
method: &str,
extra_args: Vec<Value>,
wrap: FrameWrap,
line: u32,
) -> Result<(), NyblError> {
let type_key: Option<(String, String)> = match &receiver {
Value::Struct(s) => Some((s.module_path().to_string(), s.type_name().to_string())),
Value::EnumVariant(e) => Some((e.module_path().to_string(), e.type_name().to_string())),
_ => None,
};
let key = type_key.ok_or_else(|| {
error(
line,
nybl::error_messages::cant_iterate_over(receiver.type_name()),
)
})?;
let entry = self
.user_methods
.get(&key)
.and_then(|m| m.get(method))
.cloned()
.ok_or_else(|| {
error(
line,
format!(
"`{}` doesn't have a `.{}()` method — can't iterate",
key.1, method
),
)
})?;
validate_user_arity(
&format!("{}.{}", key.1, method),
&entry.param_modes,
extra_args.len() + 1,
true,
line,
)?;
let mut args = Vec::with_capacity(extra_args.len() + 1);
args.push(receiver);
args.extend(extra_args);
self.enter_user_fn_args(Rc::clone(&entry), args, line)?;
self.frames.last_mut().expect("callee frame").wrap = wrap;
self.apply_entry_alias_context(&entry);
Ok(())
}
/// Handle `r.map(f)`, `r.map_err(f)`, `r.and_then(f)` for a
/// built-in `Result`. `map` / `map_err` push a closure frame
/// marked with a `FrameWrap` that wraps the closure's return
/// value in `Ok` / `Err`; the short-circuit branch (map on
/// Err, map_err on Ok) skips the call and pushes the passed-
/// through Result directly. `and_then` trusts the closure to
/// return a Result and pushes the call with no wrap.
fn call_result_callable_method(
&mut self,
obj: Value,
kind: methods::ResultCallableKind,
method: &str,
args: Vec<Value>,
line: u32,
) -> Result<Next, NyblError> {
use methods::{ResultCallableKind, make_result_err_in, make_result_ok_in};
if args.len() != 1 {
return Err(error(
line,
format!("`{}` expects 1 argument, but got {}", method, args.len()),
));
}
let mut args_iter = args.into_iter();
let callable = args_iter.next().unwrap();
let (is_ok, payload) = match &obj {
Value::EnumVariant(e) => {
let payload = match e.payload() {
nybl::value::EnumPayload::Tuple(items) if items.len() == 1 => items[0].clone(),
_ => {
return Err(error(
line,
format!("malformed Result::{} payload", e.variant()),
));
}
};
(e.variant() == "Ok", payload)
}
_ => return Err(error(line, "Result method called on non-Result")),
};
drop(obj);
match kind {
ResultCallableKind::Map => {
if !is_ok {
// Err passes through unchanged — no closure call.
let value = make_result_err_in(payload, line, &self.memory)?;
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
self.push_value(value);
return Ok(Next::Continue);
}
let func = match &callable {
Value::Fn(f) => Rc::clone(f),
other => {
return Err(error(
line,
format!("`map` expects a function, got {}", other.type_name()),
));
}
};
drop(callable);
self.call_closure(&func, vec![payload], line)?;
if let Some(frame) = self.frames.last_mut() {
frame.wrap = FrameWrap::ResultOk { line };
}
Ok(Next::Continue)
}
ResultCallableKind::MapErr => {
if is_ok {
let value = make_result_ok_in(payload, line, &self.memory)?;
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
self.push_value(value);
return Ok(Next::Continue);
}
let func = match &callable {
Value::Fn(f) => Rc::clone(f),
other => {
return Err(error(
line,
format!("`map_err` expects a function, got {}", other.type_name()),
));
}
};
drop(callable);
self.call_closure(&func, vec![payload], line)?;
if let Some(frame) = self.frames.last_mut() {
frame.wrap = FrameWrap::ResultErr { line };
}
Ok(Next::Continue)
}
ResultCallableKind::AndThen => {
if !is_ok {
let value = make_result_err_in(payload, line, &self.memory)?;
if self.memory.__exceeded() {
return Err(error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
self.push_value(value);
return Ok(Next::Continue);
}
let func = match &callable {
Value::Fn(f) => Rc::clone(f),
other => {
return Err(error(
line,
format!("`and_then` expects a function, got {}", other.type_name()),
));
}
};
drop(callable);
// Closure is expected to return a Result — no
// wrapping. The result flows back via the normal
// `do_return` path (`FrameWrap::None`).
self.call_closure(&func, vec![payload], line)
}
}
}
/// Attach the raising frame's defining module to an escaping
/// runtime error. The error's line numbers refer to the chunk
/// of the frame that raised it, so the frame's
/// `function_module` — the fn's *defining* module — is the
/// source the error must render against, no matter which file
/// the call chain started in. Root-declared fns attach the
/// root sentinel ([`nybl::value::ROOT_MODULE_PATH`]), which
/// renders as plain root source but keeps an enclosing module
/// fn (e.g. one invoking a root callback) from claiming the
/// error later. Deepest context wins: an error that already
/// carries a context (a nested module VM's load boundary, or
/// an earlier pass through this helper) is left untouched.
///
/// Top-of-program frames have no `function_module`; their
/// errors stay uncontexted here and, for a module's top-level
/// code, pick up their context (with source) at the
/// `load_module` boundary instead.
fn attach_frame_module_context(&self, err: NyblError) -> NyblError {
if err.source_context.is_some() || err.is_try_return {
return err;
}
match self
.frames
.last()
.and_then(|frame| frame.function_module.as_deref())
{
Some(module) => err.with_module(module),
None => err,
}
}
/// Propagate a non-fatal error up through any number of fn
/// frames until we find a `FrameWrap::TryCall` landing pad.
/// On success, truncates the frame stack and value stack
/// back to the wrapper's base, pushes a
/// `Result::Err(RuntimeError { … })` for the outer caller,
/// and returns `Ok(())` so the dispatch loop keeps going.
///
/// Returns `Err(err)` (untouched) when:
/// - the error is fatal (resource-limit violation), or
/// - no enclosing `try_call` frame exists.
fn unwind_to_try_call(&mut self, err: NyblError) -> Result<(), NyblError> {
if err.is_fatal {
return Err(err);
}
let wrap_idx = match self
.frames
.iter()
.rposition(|f| matches!(f.wrap, FrameWrap::TryCall { .. }))
{
Some(i) => i,
None => return Err(err),
};
let wrapper_stack_base = self.frames[wrap_idx].stack_base;
let wrapper_line = match self.frames[wrap_idx].wrap {
FrameWrap::TryCall { line } => line,
_ => unreachable!("try_call frame selected by wrapper kind"),
};
// Drain the unwound frames through the freelist instead
// of `truncate`, so their slot vecs get recycled.
while self.frames.len() > wrap_idx {
let mut frame = self.frames.pop().expect("frame present");
self.store_frame_defining_environment(&mut frame);
self.type_bindings.truncate(frame.caller_type_scope_depth());
self.module_aliases.truncate(frame.alias_scope_base);
self.imported_functions.truncate(frame.alias_scope_base);
self.imported_here.truncate(frame.alias_scope_base);
if !frame.slots.is_empty() {
self.return_slots(frame.slots);
}
}
self.restore_active_defining_environment();
self.stack.truncate(wrapper_stack_base);
self.push_value(builtins::make_try_call_err_in(&err, &self.memory));
if self.memory.__exceeded() {
Err(error_fatal_with_hint(
wrapper_line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
))
} else {
Ok(())
}
}
}
fn resolve_type_in_frame(
frame: &Frame,
value_scopes: &[BTreeMap<String, Value>],
type_scopes: &[BTreeMap<String, String>],
module_aliases: &[BTreeMap<String, Rc<nybl::value::NyblModule>>],
namespace: Option<&str>,
type_name: &str,
) -> Option<String> {
if let Some(namespace) = namespace {
for scope in value_scopes.iter().rev() {
if let Some(value) = scope.get(namespace) {
return match value {
Value::Module(module) => module.type_origin(type_name).map(str::to_string),
_ => None,
};
}
}
let floor = frame.is_function.then_some(frame.alias_scope_base);
for (index, aliases) in module_aliases.iter().enumerate().rev() {
if floor.is_some_and(|floor| index < floor) {
continue;
}
if let Some(module) = aliases.get(namespace) {
return module.type_origin(type_name).map(str::to_string);
}
}
return frame
.lexical_context
.module_aliases
.get(namespace)
.and_then(|module| module.type_origin(type_name).map(str::to_string));
}
let floor = frame
.is_function
.then_some(frame.type_scope_base.saturating_sub(1));
for (index, bindings) in type_scopes.iter().enumerate().rev() {
if floor.is_some_and(|floor| index < floor) {
continue;
}
if let Some(module_path) = bindings.get(type_name) {
return Some(module_path.clone());
}
}
frame.lexical_context.type_bindings.get(type_name).cloned()
}
fn apply_in_place_assign<F>(
op: crate::chunk::InPlaceAssignOp,
rhs: Value,
line: u32,
memory: &nybl::memory::MemoryContext,
current: F,
) -> Result<Value, NyblError>
where
F: FnOnce() -> Result<Value, NyblError>,
{
use crate::chunk::InPlaceAssignOp;
if op == InPlaceAssignOp::Eq {
return Ok(rhs);
}
let left = current()?;
match op {
InPlaceAssignOp::Eq => unreachable!(),
InPlaceAssignOp::Add => ops::add_in(&left, &rhs, line, memory),
InPlaceAssignOp::Sub => ops::sub_in(&left, &rhs, line, memory),
InPlaceAssignOp::Mul => ops::mul_in(&left, &rhs, line, memory),
InPlaceAssignOp::Div => ops::div_in(&left, &rhs, line, memory),
InPlaceAssignOp::Rem => ops::rem_in(&left, &rhs, line, memory),
}
}
impl NyblInstance {
/// Compile and execute a program once, retaining its VM state for calls.
pub fn load(
source: &str,
host: &mut dyn NyblHost,
limits: &NyblLimits,
) -> Result<Self, NyblError> {
let statements = nybl::parse(source)?;
let compiled = crate::compiler::compile_program(&statements)?;
crate::validate_chunk(&compiled.chunk)?;
let memory = nybl::memory::MemoryContext::__new(limits.max_memory);
let mut vm = Vm::new_internal(
compiled.chunk,
host,
limits.clone(),
ModuleRuntime::empty(),
nybl::value::ROOT_MODULE_PATH.to_string(),
compiled.root_function_visibility,
NyblFnOrigin::__instance("vm"),
memory.clone(),
);
let execution = vm.run_internal();
vm.write_runtime_warnings();
execution?;
if memory.__exceeded() {
return Err(instance_memory_error());
}
let entries = vm
.abi_declarations
.iter()
.map(|(name, target)| {
let required = nybl::ref_params::required_arity(&target.param_modes);
if target.param_modes.last() == Some(&ParamMode::Rest) {
EntryPoint::__new_variadic(name.clone(), required)
} else {
EntryPoint::__new(name.clone(), required)
}
})
.collect();
Ok(Self {
state: Some(vm.into_state()),
entries,
limits: limits.clone(),
in_operation: Cell::new(false),
memory,
})
}
pub fn entry_points(&self) -> &[EntryPoint] {
&self.entries
}
pub fn call(
&mut self,
name: &str,
args: &[Value],
host: &mut dyn NyblHost,
) -> Result<Value, NyblError> {
let _operation = VmOperationGuard::begin(&self.in_operation)?;
let state = self.state.as_ref().expect("instance state present");
let target = state
.abi_declarations
.iter()
.find(|(entry_name, _)| entry_name == name)
.map(|(_, target)| Rc::clone(target))
.ok_or_else(|| error(0, format!("Public entry point `{name}` was not found")))?;
validate_user_arity(name, &target.param_modes, args.len(), false, 0)?;
nybl::ref_params::validate_call_modes(
name,
&target.param_modes,
&vec![ParamMode::Value; args.len()],
0,
)?;
if self.memory.__exceeded() {
return Err(instance_memory_error());
}
let state = self.state.take().expect("instance state present");
let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
let result = {
for argument in args {
vm.push_value(argument.clone());
}
let execution = vm
.enter_user_fn(target, args.len(), 0)
.and_then(|_| vm.run_internal());
let value = execution.and_then(|_| vm.pop_value(0));
vm.restore_instance_baseline();
if self.memory.__exceeded() {
Err(instance_memory_error())
} else {
value
}
};
vm.write_runtime_warnings();
self.state = Some(vm.into_state());
result
}
pub fn call_value(
&mut self,
callable: &Value,
args: &[Value],
host: &mut dyn NyblHost,
) -> Result<Value, NyblError> {
let _operation = VmOperationGuard::begin(&self.in_operation)?;
let function = match callable {
Value::Fn(function) => Rc::clone(function),
other => {
return Err(error(
0,
format!("expected function, got {}", other.type_name()),
));
}
};
let state = self.state.as_ref().expect("instance state present");
if !function.__is_allowed_by(&state.function_origin, "vm") {
return Err(error(
0,
"This function belongs to a different Nybl engine instance",
));
}
let display_name = function.self_name.as_deref().unwrap_or("fn");
validate_user_arity(display_name, &function.param_modes, args.len(), false, 0)?;
nybl::ref_params::validate_call_modes(
display_name,
&function.param_modes,
&vec![ParamMode::Value; args.len()],
0,
)?;
if self.memory.__exceeded() {
return Err(instance_memory_error());
}
let state = self.state.take().expect("instance state present");
let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
let result = {
let execution = vm
.call_closure(&function, args.to_vec(), 0)
.and_then(|_| vm.run_internal());
let value = execution.and_then(|_| vm.pop_value(0));
vm.restore_instance_baseline();
if self.memory.__exceeded() {
Err(instance_memory_error())
} else {
value
}
};
vm.write_runtime_warnings();
self.state = Some(vm.into_state());
result
}
}
fn instance_memory_error() -> NyblError {
NyblError::fatal("Memory limit exceeded", 0)
}
fn call_mode_error(
line: u32,
callable: &str,
zero_based_position: usize,
expected: ParamMode,
) -> NyblError {
let position = zero_based_position + 1;
match expected {
ParamMode::Ref => error_with_hint(
line,
format!("argument {position} to `{callable}` must be passed with `ref`"),
format!("Write `ref` before argument {position}."),
),
ParamMode::Value => error_with_hint(
line,
format!("argument {position} to `{callable}` is a value parameter and can't use `ref`"),
format!("Remove `ref` from argument {position}."),
),
ParamMode::Rest => error_with_hint(
line,
format!("argument {position} to `{callable}` is a value parameter and can't use `ref`"),
format!("Remove `ref` from argument {position}."),
),
}
}
fn validate_user_arity(
callable: &str,
expected: &[ParamMode],
actual: usize,
including_self: bool,
line: u32,
) -> Result<(), NyblError> {
let has_rest = expected.last() == Some(&ParamMode::Rest);
let minimum = expected.len().saturating_sub(usize::from(has_rest));
if (has_rest && actual >= minimum) || (!has_rest && actual == minimum) {
return Ok(());
}
let self_suffix = if including_self {
" (including `self`)"
} else {
""
};
let expectation = if has_rest {
format!(
"at least {minimum} argument{}",
if minimum == 1 { "" } else { "s" }
)
} else {
format!("{minimum} argument{}", if minimum == 1 { "" } else { "s" })
};
Err(error(
line,
format!("`{callable}` expects {expectation}{self_suffix}, but got {actual}"),
))
}
fn validate_user_call_modes(
callable: &str,
expected: &[ParamMode],
actual: &[ParamMode],
line: u32,
) -> Result<(), NyblError> {
validate_user_arity(callable, expected, actual.len(), false, line)?;
let fixed = expected
.len()
.saturating_sub(usize::from(expected.last() == Some(&ParamMode::Rest)));
for (index, mode) in actual.iter().enumerate() {
let expected_mode = expected.get(index).copied().unwrap_or(ParamMode::Value);
let expected_mode = if index >= fixed || expected_mode == ParamMode::Rest {
ParamMode::Value
} else {
expected_mode
};
if *mode != expected_mode {
return Err(call_mode_error(line, callable, index, expected_mode));
}
}
Ok(())
}
fn invalid_ref_target_error(line: u32, zero_based_position: usize) -> NyblError {
error_with_hint(
line,
format!(
"`ref` argument {} must name a mutable variable",
zero_based_position + 1
),
"Assign the value to a `let` variable, then pass that variable with `ref`.",
)
}
fn duplicate_ref_target_error(line: u32) -> NyblError {
error_with_hint(
line,
"the same variable can't be passed to more than one `ref` parameter",
"Use a distinct variable for each `ref` argument.",
)
}
fn validate_named_builtin_arity(name: &str, count: usize, line: u32) -> Result<(), NyblError> {
let expected = match name {
"rand" | "try_call" | "panic" => Some((1, 1)),
"range" => Some((1, 3)),
"print" => None,
_ => return Ok(()),
};
if let Some((min, max)) = expected
&& (count < min || count > max)
{
let expectation = if min == max {
format!("{} argument{}", min, if min == 1 { "" } else { "s" })
} else {
format!("{min} to {max} arguments")
};
return Err(error(
line,
format!("`{name}` expects {expectation}, but got {count}"),
));
}
Ok(())
}
fn validate_builtin_method_arity(method: &str, count: usize, line: u32) -> Result<(), NyblError> {
let Some(expected) = methods::builtin_method_arity(method) else {
return Ok(());
};
if count != expected {
return Err(error(
line,
format!(
"`.{method}()` needs {expected} argument{}",
if expected == 1 { "" } else { "s" }
),
));
}
Ok(())
}
struct VmOperationGuard<'a>(&'a Cell<bool>);
impl<'a> VmOperationGuard<'a> {
fn begin(flag: &'a Cell<bool>) -> Result<Self, NyblError> {
if flag.replace(true) {
return Err(error(0, "A Nybl instance cannot be re-entered"));
}
Ok(Self(flag))
}
}
impl Drop for VmOperationGuard<'_> {
fn drop(&mut self) {
self.0.set(false);
}
}
// ─── Public entry points ──────────────────────────────────────────
/// Execute a pre-compiled [`Chunk`] against the supplied host.
///
/// The chunk is structurally validated before the VM starts, so malformed
/// hand-built or deserialized bytecode is reported as a [`NyblError`] rather
/// than panicking or silently jumping beyond the instruction stream.
pub fn execute<H: NyblHost>(
chunk: Chunk,
host: &mut H,
limits: &NyblLimits,
) -> Result<(), NyblError> {
crate::validate_chunk(&chunk)?;
let vm = Vm::new(chunk, host, limits.clone());
vm.run()
}
/// Parse, compile, and run Nybl source.
///
/// This mirrors [`nybl::run`] but routes through the bytecode VM.
pub fn run<H: NyblHost>(source: &str, host: &mut H, limits: &NyblLimits) -> Result<(), NyblError> {
let stmts = nybl::parse(source)?;
let chunk = crate::compile(&stmts)?;
execute(chunk, host, limits)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct SilentHost;
impl NyblHost for SilentHost {
fn call(
&mut self,
_name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
None
}
}
#[test]
fn named_call_uses_host_once_then_exact_self_recursion_bypasses_it() {
struct Host {
calls: usize,
prints: Vec<String>,
}
impl NyblHost for Host {
fn call(
&mut self,
name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
if name != "f" {
return None;
}
self.calls += 1;
(self.calls > 1).then_some(Ok(Value::Int(99)))
}
fn on_print(&mut self, message: &str) {
self.prints.push(message.to_string());
}
}
let mut host = Host {
calls: 0,
prints: Vec::new(),
};
run(
"fn f(n) { if n == 0 { return 1 } return f(n - 1) }\nprint(f(2))",
&mut host,
&NyblLimits::standard(),
)
.unwrap();
assert_eq!(host.calls, 1);
assert_eq!(host.prints, ["1"]);
}
#[test]
fn method_bare_name_resolves_named_function_not_method_self() {
struct PrintHost(Vec<String>);
impl NyblHost for PrintHost {
fn call(
&mut self,
_name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
None
}
fn on_print(&mut self, message: &str) {
self.0.push(message.to_string());
}
}
let mut host = PrintHost(Vec::new());
run(
"struct S {}\nfn m() { return 7 }\nfn S.m(self) { return m() }\nlet value = S {}\nprint(value.m())",
&mut host,
&NyblLimits::standard(),
)
.unwrap();
assert_eq!(host.0, ["7"]);
}
#[test]
fn sequential_broken_loops_leave_the_value_stack_balanced() {
let mut source = String::new();
for _ in 0..128 {
source.push_str("for item in [1, 2, 3] { break }\n");
source.push_str("repeat 3 { break }\n");
}
let program = nybl::parse(&source).expect("parse");
let chunk = crate::compile(&program).expect("compile");
let mut host = SilentHost;
let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
vm.run_internal().expect("execute");
assert!(
vm.stack.is_empty(),
"clean completion left {} loop sidecars on the value stack",
vm.stack.len()
);
}
#[test]
fn loop_control_leaves_value_and_type_scope_stacks_balanced() {
let source = r#"repeat 2048 {
if true { continue }
}
for outer in [1, 2] {
repeat 3 {
while true {
if true { break }
}
let label = match outer {
n if n < 0 => "negative",
_ => "positive",
}
if outer == 1 { continue }
break
}
}"#;
let program = nybl::parse(source).expect("parse");
let chunk = crate::compile(&program).expect("compile");
let mut host = SilentHost;
let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
vm.run_internal().expect("execute");
let frame = vm.frames.last().expect("top frame");
assert_eq!(frame.scopes.len(), frame.scope_base);
assert_eq!(vm.type_bindings.len(), frame.type_scope_base);
assert!(
vm.stack.is_empty(),
"clean completion left {} values or loop sidecars",
vm.stack.len()
);
}
#[test]
fn frame_scope_floors_preserve_base_scopes_and_pair_type_scopes() {
let mut host = SilentHost;
let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
// A redundant PopScope cannot remove the top-level binding map.
vm.pop_scope();
assert_eq!(vm.frames.last().unwrap().scopes.len(), 1);
assert_eq!(vm.type_bindings.len(), 1);
vm.push_scope();
vm.pop_scope();
assert_eq!(vm.frames.last().unwrap().scopes.len(), 1);
assert_eq!(vm.type_bindings.len(), 1);
// Named-function frames start with no value scope, but their first
// pushed runtime scope is removable. Function exit also discards all
// still-open type scopes, as an early return requires.
vm.push_function_frame(
Rc::new(Chunk::new()),
Vec::new(),
Vec::new(),
0,
None,
FrameWrap::None,
);
vm.pop_scope();
assert_eq!(vm.frames.last().unwrap().scopes.len(), 0);
assert_eq!(vm.type_bindings.len(), 2);
vm.push_scope();
vm.pop_scope();
assert_eq!(vm.frames.last().unwrap().scopes.len(), 0);
assert_eq!(vm.type_bindings.len(), 2);
vm.push_scope();
vm.push_scope();
vm.do_return(Value::None, 0).expect("return");
assert_eq!(vm.frames.len(), 1);
assert_eq!(vm.type_bindings.len(), 1);
// Closure frames retain their capture map while removing a match
// scope above it.
let mut captures = BTreeMap::new();
captures.insert(String::from("captured"), Value::Int(10));
vm.push_function_frame(
Rc::new(Chunk::new()),
Vec::new(),
vec![captures],
vm.stack.len(),
None,
FrameWrap::None,
);
vm.push_scope();
vm.pop_scope();
let frame = vm.frames.last().unwrap();
assert_eq!(frame.scopes.len(), 1);
assert!(matches!(
frame.scopes[0].get("captured"),
Some(Value::Int(10))
));
assert_eq!(vm.type_bindings.len(), 2);
// Error unwinding must remove both the try-call frame and a nested
// function's still-open runtime scopes, restoring the top-level type
// depth exactly.
vm.do_return(Value::None, 0).expect("closure return");
vm.push_function_frame(
Rc::new(Chunk::new()),
Vec::new(),
Vec::new(),
vm.stack.len(),
None,
FrameWrap::TryCall { line: 1 },
);
vm.push_scope();
vm.push_function_frame(
Rc::new(Chunk::new()),
Vec::new(),
Vec::new(),
vm.stack.len(),
None,
FrameWrap::None,
);
vm.push_scope();
vm.unwind_to_try_call(error(1, "boom")).expect("unwind");
assert_eq!(vm.frames.len(), 1);
assert_eq!(vm.type_bindings.len(), 1);
}
#[test]
fn named_call_frames_share_one_module_context() {
let mut host = SilentHost;
let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
let root_context = Rc::clone(&vm.root_lexical_context);
vm.push_function_frame(
Rc::new(Chunk::new()),
Vec::new(),
Vec::new(),
0,
Some(nybl::value::ROOT_MODULE_PATH.to_string()),
FrameWrap::None,
);
assert!(Rc::ptr_eq(
&vm.frames.last().unwrap().lexical_context,
&root_context
));
assert_eq!(vm.type_bindings.len(), 2);
assert_eq!(vm.module_aliases.len(), 2);
assert_eq!(vm.imported_functions.len(), 2);
assert!(vm.type_bindings[1].is_empty());
assert!(vm.module_aliases[1].is_empty());
assert!(vm.imported_functions[1].is_empty());
}
#[test]
fn root_type_publication_reuses_unique_context_storage() {
const DECLARATIONS: usize = 1_024;
let mut host = SilentHost;
let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
let context = Rc::as_ptr(&vm.root_lexical_context);
let bindings = Rc::as_ptr(&vm.root_lexical_context.type_bindings);
for index in 0..DECLARATIONS {
vm.bind_local_type(&format!("Type{index}"));
}
assert_eq!(Rc::as_ptr(&vm.root_lexical_context), context);
assert_eq!(Rc::as_ptr(&vm.root_lexical_context.type_bindings), bindings);
assert_eq!(
vm.root_lexical_context.type_bindings.len(),
DECLARATIONS + 3
);
}
#[test]
fn restored_lexical_snapshot_forks_without_leaking_abandoned_changes() {
let mut host = SilentHost;
let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
vm.publish_root_type_binding("A".to_string(), "root".to_string());
let snapshot = Rc::clone(&vm.root_lexical_context);
vm.publish_root_type_binding("B".to_string(), "leaked".to_string());
vm.root_lexical_context = Rc::clone(&snapshot);
vm.publish_root_type_binding("C".to_string(), "root".to_string());
assert_eq!(
vm.root_lexical_context.type_bindings.get("A"),
Some(&"root".to_string())
);
assert!(!vm.root_lexical_context.type_bindings.contains_key("B"));
assert_eq!(
vm.root_lexical_context.type_bindings.get("C"),
Some(&"root".to_string())
);
}
#[test]
fn repeated_publication_replaces_in_place_without_retaining_history() {
let mut host = SilentHost;
let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
let bindings = Rc::as_ptr(&vm.root_lexical_context.type_bindings);
for index in 0..1_000 {
vm.publish_root_type_binding("Repeated".to_string(), index.to_string());
}
assert_eq!(Rc::as_ptr(&vm.root_lexical_context.type_bindings), bindings);
assert_eq!(vm.root_lexical_context.type_bindings.len(), 4);
assert_eq!(
vm.root_lexical_context.type_bindings.get("Repeated"),
Some(&"999".to_string())
);
}
#[test]
fn capture_snapshot_distinguishes_missing_from_bound_none() {
let program = nybl::parse(
r#"let present = none
let read = fn() { return [missing, present] }"#,
)
.expect("parse");
let chunk = crate::compile(&program).expect("compile");
let lambda = chunk.functions[0].clone();
let mut host = SilentHost;
let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
vm.define_local("present".to_string(), Value::None);
let captures = vm.snapshot_captures_for(&lambda);
assert_eq!(captures.len(), 1, "missing bindings must not be invented");
assert_eq!(captures[0].0, "present");
assert!(matches!(captures[0].1, Value::None));
}
struct RetainingHost {
retained: Option<Value>,
}
impl NyblHost for RetainingHost {
fn call(
&mut self,
name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
if name != "retain_large" {
return None;
}
self.retained = Some(Value::new_str("x".repeat(16 * 1024)));
Some(Ok(Value::None))
}
}
#[test]
fn instance_leaves_host_allocations_untracked_and_checks_final_returns() {
let limits = NyblLimits {
max_steps: 100,
max_memory: 32,
};
let mut host = RetainingHost { retained: None };
let mut instance = NyblInstance::load(
"pub fn host_only() { retain_large() }\npub fn too_large() { return \"abcdefghijklmnopqrstuvwxyz0123456789\" }",
&mut host,
&limits,
)
.unwrap();
instance.call("host_only", &[], &mut host).unwrap();
assert!(host.retained.is_some());
assert_eq!(instance.memory.__used(), 0);
let error = instance.call("too_large", &[], &mut host).unwrap_err();
assert!(error.is_fatal);
assert!(error.message.contains("Memory limit"));
assert_eq!(instance.memory.__used(), 0);
instance.call("host_only", &[], &mut host).unwrap();
}
struct ExternalValueHost {
value: Option<Value>,
}
impl NyblHost for ExternalValueHost {
fn call(
&mut self,
name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
(name == "take_external").then(|| Ok(self.value.take().unwrap_or(Value::None)))
}
}
#[test]
fn external_values_are_free_until_detach_and_memory_poison_is_fail_fast() {
let external = Value::new_array((0..256).map(Value::Int).collect());
let limits = NyblLimits {
max_steps: 100,
max_memory: 64,
};
let mut host = ExternalValueHost {
value: Some(external),
};
let mut instance = NyblInstance::load(
"let stored = none\npub fn keep() { stored = take_external() }\npub fn mutate() { stored.push(256) }\npub fn harmless() { return 1 }",
&mut host,
&limits,
)
.unwrap();
instance.call("keep", &[], &mut host).unwrap();
assert_eq!(instance.memory.__used(), 0);
let mutation_error = instance.call("mutate", &[], &mut host).unwrap_err();
assert!(mutation_error.is_fatal);
assert!(instance.memory.__used() > limits.max_memory);
let poisoned = instance.call("harmless", &[], &mut host).unwrap_err();
assert!(poisoned.is_fatal);
assert!(poisoned.message.contains("Memory limit"));
}
#[test]
fn returned_receipts_release_on_last_drop_and_instances_do_not_cross_charge() {
let mut host = SilentHost;
let source = "pub fn make(x) { return [x, x, x, x] }\npub fn harmless() { return none }";
let limits = NyblLimits::standard();
let mut first = NyblInstance::load(source, &mut host, &limits).unwrap();
let mut second = NyblInstance::load(source, &mut host, &limits).unwrap();
let first_value = first.call("make", &[Value::Int(1)], &mut host).unwrap();
let first_bytes = first.memory.__used();
assert!(first_bytes > 0);
assert_eq!(second.memory.__used(), 0);
first.call("harmless", &[], &mut host).unwrap();
assert_eq!(first.memory.__used(), first_bytes);
let first_clone = first_value.clone();
drop(first_value);
assert_eq!(first.memory.__used(), first_bytes);
let second_value = second.call("make", &[Value::Int(2)], &mut host).unwrap();
let second_bytes = second.memory.__used();
assert!(second_bytes > 0);
assert_eq!(first.memory.__used(), first_bytes);
drop(first_clone);
assert_eq!(first.memory.__used(), 0);
assert_eq!(second.memory.__used(), second_bytes);
drop(second_value);
assert_eq!(second.memory.__used(), 0);
}
struct HookAllocatingHost {
retained: RefCell<Vec<Value>>,
}
impl HookAllocatingHost {
fn retain_large(&self) {
self.retained
.borrow_mut()
.push(Value::new_str("x".repeat(16 * 1024)));
}
}
impl NyblHost for HookAllocatingHost {
fn call(
&mut self,
name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
self.retain_large();
(name == "host_value").then_some(Ok(Value::None))
}
fn on_print(&mut self, _message: &str) {
self.retain_large();
}
fn function_hint(&self) -> &str {
self.retain_large();
"host hint"
}
fn on_tick(&mut self) -> Result<(), NyblError> {
self.retain_large();
Ok(())
}
fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
self.retain_large();
(name == "hook").then(|| Ok(String::new()))
}
}
#[test]
fn every_instance_host_hook_leaves_accounting_unchanged() {
let limits = NyblLimits {
max_steps: 100,
max_memory: 64,
};
let mut host = HookAllocatingHost {
retained: RefCell::new(Vec::new()),
};
let mut instance = NyblInstance::load(
"use hook\npub fn print_it() { print(\"ok\") }\npub fn host_it() { host_value() }\npub fn hint_it() { missing() }",
&mut host,
&limits,
)
.unwrap();
assert_eq!(instance.memory.__used(), 0);
instance.call("print_it", &[], &mut host).unwrap();
instance.call("host_it", &[], &mut host).unwrap();
let error = instance.call("hint_it", &[], &mut host).unwrap_err();
assert!(!error.is_fatal);
assert!(
error
.friendly_hint
.as_deref()
.is_some_and(|hint| hint.contains("host hint"))
);
assert_eq!(instance.memory.__used(), 0);
assert!(host.retained.borrow().len() >= 8);
}
#[test]
fn same_instance_reentry_rejection_precedes_target_and_arity_checks() {
let mut host = SilentHost;
let mut instance =
NyblInstance::load("pub fn entry() {}", &mut host, &NyblLimits::standard()).unwrap();
instance.in_operation.set(true);
let error = instance
.call("missing", &[Value::None], &mut host)
.unwrap_err();
instance.in_operation.set(false);
assert_eq!(error.line, Some(0));
assert!(error.message.contains("cannot be re-entered"));
}
struct MapModuleHost {
modules: BTreeMap<String, String>,
}
impl NyblHost for MapModuleHost {
fn call(
&mut self,
_name: &str,
_args: &[Value],
_line: u32,
) -> Option<Result<Value, NyblError>> {
None
}
fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
self.modules.get(name).cloned().map(Ok)
}
}
#[test]
fn vm_module_compilation_error_retains_transitive_source_context() {
let root_source = "use outer";
let inner_source = "let okay = 1\nlet broken =";
let mut host = MapModuleHost {
modules: BTreeMap::from([
("outer".to_string(), "use inner\nlet outer = 1".to_string()),
("inner".to_string(), inner_source.to_string()),
]),
};
let error = crate::run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
let context = error.source_context.as_ref().expect("module context");
assert_eq!(context.module_path, "inner");
assert_eq!(context.source.as_deref(), Some(inner_source));
let rendered = error.render(root_source);
assert!(rendered.contains("in module `inner` at line 2"));
assert!(rendered.contains("let broken ="));
assert!(!rendered.contains("1 | use outer"));
}
#[test]
fn module_compatibility_snapshots_do_not_force_named_cow_detaches() {
let mut host = MapModuleHost {
modules: BTreeMap::from([
(
"leaf".to_string(),
"let items = [1, 2, 3]\nfn pop() { items.pop() }".to_string(),
),
(
"facade".to_string(),
"use leaf\nfn pop() { items.pop() }".to_string(),
),
]),
};
let mut instance = NyblInstance::load(
"use leaf as leaf\nuse facade as facade\npub fn facade_pop() { facade.pop() }\npub fn direct_pop() { leaf.pop() }",
&mut host,
&NyblLimits::standard(),
)
.unwrap();
let loaded_bytes = instance.memory.__used();
assert!(loaded_bytes > 0);
instance.call("facade_pop", &[], &mut host).unwrap();
assert_eq!(instance.memory.__used(), loaded_bytes);
instance.call("direct_pop", &[], &mut host).unwrap();
assert_eq!(instance.memory.__used(), loaded_bytes);
}
#[test]
fn facade_fanout_reuses_the_origin_compatibility_snapshot() {
const FACADES: usize = 8;
let items = (0..256)
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(", ");
let mut modules = BTreeMap::from([(
"leaf".to_string(),
format!("let items = [{items}]\nfn size() {{ return items.len() }}"),
)]);
let mut source = String::new();
for index in 0..FACADES {
modules.insert(format!("facade{index}"), "use leaf".to_string());
source.push_str(&format!("use facade{index} as f{index}\n"));
source.push_str(&format!("let size{index} = f{index}.size()\n"));
}
let mut host = MapModuleHost { modules };
let instance = NyblInstance::load(&source, &mut host, &NyblLimits::standard()).unwrap();
let imports = instance.state.as_ref().unwrap().imports.borrow();
let ImportSlot::Loaded(leaf) = imports.get("leaf").unwrap() else {
panic!("leaf should be loaded")
};
let leaf_items = &leaf
.bindings
.iter()
.find(|(name, _)| name == "items")
.unwrap()
.1;
for index in 0..FACADES {
let ImportSlot::Loaded(facade) = imports.get(&format!("facade{index}")).unwrap() else {
panic!("facade should be loaded")
};
let facade_items = &facade
.bindings
.iter()
.find(|(name, _)| name == "items")
.unwrap()
.1;
assert!(leaf_items.__shares_backing_with(facade_items));
}
}
#[test]
fn recursive_module_snapshots_do_not_retain_replaced_instance_receipts() {
let mut host = MapModuleHost {
modules: BTreeMap::from([(
"leaf".to_string(),
"let items = [[\"abcdefghijklmnopqrstuvwxyz0123456789\"]]\nlet captured = \"zyxwvutsrqponmlkjihgfedcba9876543210\"\nlet callback = fn() { return captured }\nfn clear() { items = []; captured = none; callback = none }"
.to_string(),
)]),
};
let mut instance = NyblInstance::load(
"use leaf as leaf\npub fn clear() { leaf.clear() }",
&mut host,
&NyblLimits::standard(),
)
.unwrap();
let loaded_bytes = instance.memory.__used();
assert!(loaded_bytes > 0);
instance.call("clear", &[], &mut host).unwrap();
let cleared_bytes = instance.memory.__used();
assert!(cleared_bytes < loaded_bytes);
let mut empty_host = MapModuleHost {
modules: BTreeMap::from([(
"leaf".to_string(),
"let items = []\nlet captured = none\nlet callback = none\nfn clear() { items = []; captured = none; callback = none }"
.to_string(),
)]),
};
let empty = NyblInstance::load(
"use leaf as leaf\npub fn clear() { leaf.clear() }",
&mut empty_host,
&NyblLimits::standard(),
)
.unwrap();
assert_eq!(cleared_bytes, empty.memory.__used());
}
struct WrappingModuleHost {
modules: BTreeMap<String, String>,
}
impl NyblHost for WrappingModuleHost {
fn call(
&mut self,
name: &str,
args: &[Value],
line: u32,
) -> Option<Result<Value, NyblError>> {
if name != "wrap" {
return None;
}
Some(
nybl::value::NyblModule::try_new(
"host.wrapper".to_string(),
vec![("child".to_string(), args[0].clone())],
Vec::new(),
line,
)
.map(Value::Module),
)
}
fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
self.modules.get(name).cloned().map(Ok)
}
}
#[test]
fn module_snapshots_externalize_host_module_binding_graphs() {
let root = "use leaf as leaf\npub fn clear() { leaf.clear() }";
let mut host = WrappingModuleHost {
modules: BTreeMap::from([(
"leaf".to_string(),
"let child = [\"abcdefghijklmnopqrstuvwxyz0123456789\"]\nlet wrapped = wrap(child)\nfn clear() { child = none; wrapped = none }"
.to_string(),
)]),
};
let mut instance = NyblInstance::load(root, &mut host, &NyblLimits::standard()).unwrap();
let loaded_bytes = instance.memory.__used();
assert!(loaded_bytes > 0);
instance.call("clear", &[], &mut host).unwrap();
let cleared_bytes = instance.memory.__used();
assert!(cleared_bytes < loaded_bytes);
let mut empty_host = WrappingModuleHost {
modules: BTreeMap::from([(
"leaf".to_string(),
"let child = none\nlet wrapped = none\nfn clear() { child = none; wrapped = none }"
.to_string(),
)]),
};
let empty = NyblInstance::load(root, &mut empty_host, &NyblLimits::standard()).unwrap();
assert_eq!(cleared_bytes, empty.memory.__used());
}
}