vimlrs 0.1.2

Faithful Rust port of the Vimscript (VimL) interpreter, from the Neovim C eval engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
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
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
//! EXTENSION — NO `vendor/` COUNTERPART. The vimlrs analogue of zshrs's
//! `src/fusevm_bridge.rs`: pure fusevm plumbing, no operator logic. It only
//!   1. converts between [`typval_T`] and `fusevm::Value` (the refpool smuggle),
//!   2. holds the per-run bridge state (refpool, last result, echo sink),
//!   3. registers the `VIML_*` builtin handlers, each of which pops operands and
//!      calls the CANONICAL PORTS in `crate::ported::*` (never reimplementing
//!      VimL semantics here).
//!
//! Where a handler reconstructs logic the bytecode replaced (the `eval5`/`eval6`
//! arithmetic dispatch, the `eval7_leader` unary application, the `eval_index`
//! subscripts) it cites the `eval.c` lines, since those tree-walkers are not
//! ported (vimlrs replaces them with bytecode).
//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

use std::cell::RefCell;

use fusevm::{Value, VM};

use crate::compile_viml::compile_program;
use crate::ported::eval::encode::{encode_tv2echo, encode_tv2string};
use crate::ported::eval::fs::{
    f_browse, f_browsedir, f_chdir, f_delete, f_executable, f_exepath, f_expand, f_expandcmd,
    f_filecopy, f_filereadable, f_filewritable, f_finddir, f_findfile, f_fnamemodify, f_getcwd,
    f_getfperm, f_getfsize, f_getftime, f_getftype, f_glob, f_glob2regpat, f_globpath,
    f_haslocaldir, f_isabsolutepath, f_isdirectory, f_mkdir, f_pathshorten, f_readblob, f_readdir,
    f_readfile, f_rename, f_resolve, f_setfperm, f_simplify, f_tempname, f_writefile,
};
use crate::ported::eval::funcs::{
    f_abs, f_add, f_and, f_api_info, f_append, f_appendbufline, f_assert_equal, f_assert_exception,
    f_assert_false, f_assert_inrange, f_assert_match, f_assert_notequal, f_assert_notmatch,
    f_assert_report, f_assert_true, f_atan2, f_bufadd, f_bufexists, f_buflisted, f_bufload,
    f_bufloaded, f_bufname, f_bufnr, f_bufwinid, f_bufwinnr, f_byte2line, f_chanclose, f_changenr,
    f_chansend, f_char2nr, f_charcol, f_col, f_confirm, f_copy, f_ctxget, f_ctxpop, f_ctxpush,
    f_ctxset, f_ctxsize, f_cursor, f_debugbreak, f_deepcopy, f_deletebufline, f_dictwatcheradd,
    f_dictwatcherdel, f_did_filetype, f_empty, f_environ, f_escape, f_eventhandler, f_exists,
    f_feedkeys, f_flatten, f_flattennew, f_float2nr, f_fmod, f_fnameescape, f_foreground,
    f_funcref, f_function, f_garbagecollect, f_get, f_getbufinfo, f_getbufline, f_getbufoneline,
    f_getbufvar, f_getchangelist, f_getcharpos, f_getcharsearch, f_getcmdwintype, f_getcurpos,
    f_getcursorcharpos, f_getenv, f_getfontname, f_getjumplist, f_getline, f_getmarklist, f_getpid,
    f_getpos, f_getreg, f_getreginfo, f_getregion, f_getregionpos, f_getregtype, f_gettabinfo,
    f_gettabvar, f_gettabwinvar, f_gettagstack, f_gettext, f_getwininfo, f_getwinpos, f_getwinposx,
    f_getwinposy, f_getwinvar, f_has, f_has_key, f_hlID, f_hlexists, f_id, f_index, f_indexof,
    f_input, f_inputdialog, f_inputlist, f_inputrestore, f_inputsave, f_inputsecret, f_insert,
    f_interrupt, f_invert, f_isinf, f_islocked, f_isnan, f_items, f_jobpid, f_jobresize,
    f_jobstart, f_jobstop, f_jobwait, f_json_decode, f_json_encode, f_keys, f_keytrans,
    f_last_buffer_nr, f_len, f_libcall, f_libcallnr, f_line, f_line2byte, f_list2str, f_localtime,
    f_luaeval, f_match, f_matchbufline, f_matchend, f_matchlist, f_matchstr, f_matchstrlist,
    f_matchstrpos, f_max, f_menu_get, f_min, f_mode, f_msgpackdump, f_msgpackparse, f_nextnonblank,
    f_nr2char, f_or, f_perleval, f_pow, f_prevnonblank, f_printf, f_prompt_appendbuf,
    f_prompt_getinput, f_prompt_getprompt, f_prompt_setcallback, f_prompt_setinterrupt,
    f_prompt_setprompt, f_pum_getpos, f_pumvisible, f_py3eval, f_rand, f_range, f_reduce,
    f_reg_executing, f_reg_recorded, f_reg_recording, f_reltime, f_reltimefloat, f_reltimestr,
    f_repeat, f_reverse, f_rpcnotify, f_rpcrequest, f_rpcstart, f_rpcstop, f_rubyeval,
    f_screenattr, f_screenchar, f_screenchars, f_screencol, f_screenrow, f_screenstring, f_search,
    f_searchdecl, f_searchpair, f_searchpairpos, f_searchpos, f_serverlist, f_serverstart,
    f_serverstop, f_setbufline, f_setbufvar, f_setcharpos, f_setcharsearch, f_setcursorcharpos,
    f_setenv, f_setline, f_setpos, f_setreg, f_settabvar, f_settabwinvar, f_settagstack,
    f_setwinvar, f_sha256, f_shellescape, f_shiftwidth, f_sockconnect, f_soundfold, f_spellbadword,
    f_spellsuggest, f_split, f_srand, f_state, f_stdioopen, f_stdpath, f_str2float, f_strftime,
    f_strptime, f_submatch, f_substitute, f_swapfilelist, f_swapinfo, f_swapname, f_synID,
    f_synIDattr, f_synIDtrans, f_synconcealed, f_synstack, f_system, f_systemlist,
    f_tabpagebuflist, f_tabpagenr, f_tabpagewinnr, f_tagfiles, f_taglist, f_termopen, f_timer_info,
    f_timer_pause, f_timer_start, f_timer_stop, f_timer_stopall, f_type, f_values, f_virtcol,
    f_visualmode, f_wait, f_wildmenumode, f_win_execute, f_win_findbuf, f_win_getid, f_win_gettype,
    f_win_gotoid, f_win_id2tabwin, f_win_id2win, f_win_move_separator, f_win_move_statusline,
    f_win_screenpos, f_win_splitmove, f_winbufnr, f_wincol, f_windowsversion, f_winheight,
    f_winlayout, f_winline, f_winnr, f_winrestcmd, f_winrestview, f_winsaveview, f_winwidth,
    f_wordcount, f_xor, float_op_wrapper,
};
use crate::ported::eval::funcs::{
    f_argc, f_argidx, f_arglistid, f_argv, f_assert_equalfile, f_cindent, f_clearmatches,
    f_cmdcomplete_info, f_complete, f_complete_add, f_complete_check, f_complete_info,
    f_diff_filler, f_diff_hlID, f_digraph_get, f_digraph_getlist, f_digraph_set, f_digraph_setlist,
    f_foldclosed, f_foldclosedend, f_foldlevel, f_foldtext, f_foldtextresult, f_fullcommand,
    f_getchar, f_getcharmod, f_getcharstr, f_getcmdcomplpat, f_getcmdcompltype, f_getcmdline,
    f_getcmdpos, f_getcmdprompt, f_getcmdscreenpos, f_getcmdtype, f_getcompletion,
    f_getcompletiontype, f_getloclist, f_getmatches, f_getmousepos, f_getqflist, f_getscriptinfo,
    f_getstacktrace, f_hasmapto, f_highlight_exists, f_histadd, f_histdel, f_histget, f_histnr,
    f_hostname, f_iconv, f_indent, f_lispindent, f_maparg, f_mapcheck, f_maplist, f_mapset,
    f_matchadd, f_matchaddpos, f_matcharg, f_matchdelete, f_matchfuzzy, f_matchfuzzypos,
    f_menu_info, f_preinserted, f_pyeval, f_pyxeval, f_screenpos, f_searchcount, f_setcmdline,
    f_setcmdpos, f_setloclist, f_setmatches, f_setqflist, f_sign_define, f_sign_getdefined,
    f_sign_getplaced, f_sign_jump, f_sign_place, f_sign_placelist, f_sign_undefine, f_sign_unplace,
    f_sign_unplacelist, f_test_garbagecollect_now, f_test_write_list_log, f_undofile, f_undotree,
    f_virtcol2col, f_wildtrigger,
};
use crate::ported::eval::list::{
    f_count, f_extend, f_extendnew, f_filter, f_foreach, f_map, f_mapnew, f_remove,
    FILTER_MAP_CMD_HOOK, FILTER_MAP_EVAL_HOOK,
};
use crate::ported::eval::typval::{
    f_blob2list, f_join, f_list2blob, f_sort, f_uniq, tv_list_slice_or_index, CALL_FUNC_HOOK,
    FUNC_EXISTS_HOOK, SORT_FUNCREF_HOOK,
};
use crate::ported::eval::typval::{
    tv_get_float, tv_get_number_chk, tv_get_string, tv_list_alloc, tv_list_append_tv,
};
use crate::ported::eval::typval_defs_h::{
    blob_T, listitem_T, typval_T, typval_vval_union::*, varnumber_T, SpecialVarValue::*,
    VarLockStatus::VAR_UNLOCKED, VarType::*,
};
use crate::ported::eval::vars::{eval_variable, set_var, set_vim_var_string, vv::VV_EXCEPTION};
use crate::ported::eval_h::exprtype_T::{self, *};
use crate::ported::message;
use crate::ported::strings::{
    f_byteidx, f_byteidxcomp, f_charclass, f_charidx, f_getcellwidths, f_setcellwidths, f_slice,
    f_str2list, f_str2nr, f_strcharlen, f_strcharpart, f_strchars, f_strdisplaywidth, f_strgetchar,
    f_stridx, f_string, f_strlen, f_strpart, f_strridx, f_strtrans, f_strutf16len, f_strwidth,
    f_tolower, f_toupper, f_tr, f_trim, f_utf16idx,
};
use crate::viml_ast::Stmt;
use crate::viml_lexer::{CaseFlag, CmpOp, VimlError};
use crate::viml_parser::parse_expr;

// ── small typval_T constructors (carve-out helpers; not ported C) ──

fn tv_num(n: varnumber_T) -> typval_T {
    typval_T {
        v_type: VAR_NUMBER,
        v_lock: VAR_UNLOCKED,
        vval: v_number(n),
    }
}
fn tv_flt(f: f64) -> typval_T {
    typval_T {
        v_type: VAR_FLOAT,
        v_lock: VAR_UNLOCKED,
        vval: v_float(f),
    }
}
fn tv_str(s: String) -> typval_T {
    typval_T {
        v_type: VAR_STRING,
        v_lock: VAR_UNLOCKED,
        vval: v_string(s),
    }
}
fn tv_special() -> typval_T {
    typval_T {
        v_type: VAR_SPECIAL,
        v_lock: VAR_UNLOCKED,
        vval: v_special(kSpecialVarNull),
    }
}

// ── builtin op IDs (fusevm CallBuiltin space; AWK uses 1000–2999, VimL 3000+) ──

/// `getvar`: pop name → value.
pub const VIML_GETVAR: u16 = 3000;
/// `setvar`: pop name, value → store.
pub const VIML_SETVAR: u16 = 3001;
/// `truthy`: pop value → `Bool`.
pub const VIML_TRUTHY: u16 = 3002;
/// `boolnum`: pop value → `Int(0/1)`.
pub const VIML_BOOLNUM: u16 = 3003;
/// Coerce the value on top of the stack to an integer (`tv_get_number`), as
/// `range()`/`f_range` coerce their arguments. Used to hoist a non-literal
/// `range()` bound into a native counter loop.
pub const VIML_TONUMBER: u16 = 3004;
/// `+`
pub const VIML_ADD: u16 = 3010;
/// `-`
pub const VIML_SUB: u16 = 3011;
/// `*`
pub const VIML_MUL: u16 = 3012;
/// `/`
pub const VIML_DIV: u16 = 3013;
/// `%`
pub const VIML_MOD: u16 = 3014;
/// `.` / `..`
pub const VIML_CONCAT: u16 = 3015;
/// unary `-`
pub const VIML_NEG: u16 = 3016;
/// unary `+`
pub const VIML_UPLUS: u16 = 3017;
/// unary `!`
pub const VIML_NOT: u16 = 3018;
/// comparison id base; per-operator offset via [`cmp_id`].
pub const VIML_CMP_BASE: u16 = 3020;
// Ignore-case comparison ids = base + op + this offset. The match-case ids
// occupy 3020..=3029; this offset places the ic ids in the reserved gap
// 3030..=3039 (below the op cluster at 3050+ and the builtin-function ids at
// 3100+). Earlier values collided: `0x20` overlapped VIML_INDEX/SLICE/ECHO and
// `0x200` (=3532+) overlapped VIML_FN_GETCHAR…, so `==?` dispatched to those
// instead of comparing — leaving 3030..=3039 reserved for the ic family.
const VIML_CMP_IC_OFFSET: u16 = 10;
/// list constructor (argc = element count).
pub const VIML_MAKE_LIST: u16 = 3050;
/// dict constructor (argc = 2 × pairs).
pub const VIML_MAKE_DICT: u16 = 3051;
/// `base[index]`
pub const VIML_INDEX: u16 = 3052;
/// `base[from:to]`
pub const VIML_SLICE: u16 = 3053;
/// `let base[index] = value` — pop index, base, value; set base[index]=value.
pub const VIML_SETINDEX: u16 = 3054;
/// `let base[idx1:idx2] = list` — pop idx2, idx1, base, value; range-assign.
pub const VIML_SETRANGE: u16 = 3055;
/// Runtime type test for the ambiguous no-space `base.key`: pop value → `Bool`
/// (`true` iff it is a Dict). Drives the subscript-vs-concat branch selection.
pub const VIML_IS_DICT: u16 = 3056;
/// `:echo`
pub const VIML_ECHO: u16 = 3060;
/// `:echon`
pub const VIML_ECHON: u16 = 3061;
/// store the bare-expression result.
pub const VIML_SET_RESULT: u16 = 3062;
/// `$ENV`
pub const VIML_GETENV: u16 = 3063;
/// `&option`
pub const VIML_GETOPT: u16 = 3064;
/// `@reg`
pub const VIML_GETREG: u16 = 3065;
/// `:let @reg = …`
pub const VIML_SETREG: u16 = 3570;
/// `:let &opt = …`
pub const VIML_SETOPT: u16 = 3571;
/// `:let $ENV = …`
pub const VIML_SETENV: u16 = 3066;
/// `len()`
pub const VIML_FN_LEN: u16 = 3100;
/// `type()`
pub const VIML_FN_TYPE: u16 = 3101;
/// `string()`
pub const VIML_FN_STRING: u16 = 3102;
/// `empty()`
pub const VIML_FN_EMPTY: u16 = 3103;
/// `abs()`
pub const VIML_FN_ABS: u16 = 3104;
/// `str2nr()`
pub const VIML_FN_STR2NR: u16 = 3105;
/// `str2float()`
pub const VIML_FN_STR2FLOAT: u16 = 3106;
/// `float2nr()`
pub const VIML_FN_FLOAT2NR: u16 = 3107;
/// Second builtin-function batch (`funcs.c`): ids `3108..=3129`.
pub const VIML_FN_STRLEN: u16 = 3108;
/// `tolower()`
pub const VIML_FN_TOLOWER: u16 = 3109;
/// `toupper()`
pub const VIML_FN_TOUPPER: u16 = 3110;
/// `char2nr()`
pub const VIML_FN_CHAR2NR: u16 = 3111;
/// `nr2char()`
pub const VIML_FN_NR2CHAR: u16 = 3112;
/// `repeat()`
pub const VIML_FN_REPEAT: u16 = 3113;
/// `split()`
pub const VIML_FN_SPLIT: u16 = 3114;
/// `join()`
pub const VIML_FN_JOIN: u16 = 3115;
/// `range()`
pub const VIML_FN_RANGE: u16 = 3116;
/// `add()`
pub const VIML_FN_ADD: u16 = 3117;
/// `reverse()`
pub const VIML_FN_REVERSE: u16 = 3118;
/// `get()`
pub const VIML_FN_GET: u16 = 3119;
/// `has_key()`
pub const VIML_FN_HAS_KEY: u16 = 3120;
/// `keys()`
pub const VIML_FN_KEYS: u16 = 3121;
/// `values()`
pub const VIML_FN_VALUES: u16 = 3122;
/// `max()`
pub const VIML_FN_MAX: u16 = 3123;
/// `min()`
pub const VIML_FN_MIN: u16 = 3124;
/// `count()`
pub const VIML_FN_COUNT: u16 = 3125;
/// `index()`
pub const VIML_FN_INDEX: u16 = 3126;
/// `has()`
pub const VIML_FN_HAS: u16 = 3127;
/// `exists()`
pub const VIML_FN_EXISTS: u16 = 3128;
/// `printf()`
pub const VIML_FN_PRINTF: u16 = 3129;
/// `map()` — callback per element (string expr binds `v:val`/`v:key`, or funcref).
pub const VIML_FN_MAP: u16 = 3130;
/// `filter()` — keep elements whose callback is truthy.
pub const VIML_FN_FILTER: u16 = 3131;
/// `sort()` — default string sort, `'n'` numeric.
pub const VIML_FN_SORT: u16 = 3132;
/// `call()` — invoke a funcref/name with an argument list.
pub const VIML_FN_CALL: u16 = 3133;
/// `function()` — a Funcref to a named function.
pub const VIML_FN_FUNCTION: u16 = 3134;
/// Third builtin batch (`funcs.c`): float math, bitwise, string, list/dict —
/// ids `3135..=3158`.
pub const VIML_FN_SQRT: u16 = 3135;
/// `floor()`
pub const VIML_FN_FLOOR: u16 = 3136;
/// `ceil()`
pub const VIML_FN_CEIL: u16 = 3137;
/// `round()`
pub const VIML_FN_ROUND: u16 = 3138;
/// `trunc()`
pub const VIML_FN_TRUNC: u16 = 3139;
/// `log()`
pub const VIML_FN_LOG: u16 = 3140;
/// `exp()`
pub const VIML_FN_EXP: u16 = 3141;
/// `sin()`
pub const VIML_FN_SIN: u16 = 3142;
/// `cos()`
pub const VIML_FN_COS: u16 = 3143;
/// `pow()`
pub const VIML_FN_POW: u16 = 3144;
/// `and()`
pub const VIML_FN_AND: u16 = 3145;
/// `or()`
pub const VIML_FN_OR: u16 = 3146;
/// `xor()`
pub const VIML_FN_XOR: u16 = 3147;
/// `invert()`
pub const VIML_FN_INVERT: u16 = 3148;
/// `strchars()`
pub const VIML_FN_STRCHARS: u16 = 3149;
/// `strpart()`
pub const VIML_FN_STRPART: u16 = 3150;
/// `stridx()`
pub const VIML_FN_STRIDX: u16 = 3151;
/// `trim()`
pub const VIML_FN_TRIM: u16 = 3152;
/// `insert()`
pub const VIML_FN_INSERT: u16 = 3153;
/// `remove()`
pub const VIML_FN_REMOVE: u16 = 3154;
/// `extend()`
pub const VIML_FN_EXTEND: u16 = 3155;
/// `copy()`
pub const VIML_FN_COPY: u16 = 3156;
/// `items()`
pub const VIML_FN_ITEMS: u16 = 3157;
/// `uniq()`
pub const VIML_FN_UNIQ: u16 = 3158;
/// `matchstr()` — Vim-regex matched substring.
pub const VIML_FN_MATCHSTR: u16 = 3159;
/// `match()` — Vim-regex match index.
pub const VIML_FN_MATCH: u16 = 3160;
/// `substitute()` — Vim-regex replace.
pub const VIML_FN_SUBSTITUTE: u16 = 3161;
/// `matchlist()`
pub const VIML_FN_MATCHLIST: u16 = 3162;
/// `matchend()`
pub const VIML_FN_MATCHEND: u16 = 3163;
/// `strridx()`
pub const VIML_FN_STRRIDX: u16 = 3164;
/// `escape()`
pub const VIML_FN_ESCAPE: u16 = 3165;
/// `tr()`
pub const VIML_FN_TR: u16 = 3166;
/// `str2list()`
pub const VIML_FN_STR2LIST: u16 = 3167;
/// `list2str()`
pub const VIML_FN_LIST2STR: u16 = 3168;
/// `flatten()`
pub const VIML_FN_FLATTEN: u16 = 3169;
/// `reduce()` — fold a List with a funcref `f(acc, val)` (callback, bridge-side).
pub const VIML_FN_REDUCE: u16 = 3170;
/// `eval()` — evaluate a string as an expression (bridge-side).
pub const VIML_FN_EVAL: u16 = 3171;
/// `execute()` — run ex commands and capture their output (bridge-side).
pub const VIML_FN_EXECUTE: u16 = 3172;
/// `deepcopy()`
pub const VIML_FN_DEEPCOPY: u16 = 3173;
/// `fmod()`
pub const VIML_FN_FMOD: u16 = 3174;
/// `atan2()`
pub const VIML_FN_ATAN2: u16 = 3175;
/// `tan()`
pub const VIML_FN_TAN: u16 = 3176;
/// `atan()`
pub const VIML_FN_ATAN: u16 = 3177;
/// `asin()`
pub const VIML_FN_ASIN: u16 = 3178;
/// `acos()`
pub const VIML_FN_ACOS: u16 = 3179;
/// `sinh()`
pub const VIML_FN_SINH: u16 = 3180;
/// `cosh()`
pub const VIML_FN_COSH: u16 = 3181;
/// `tanh()`
pub const VIML_FN_TANH: u16 = 3182;
/// `log10()`
pub const VIML_FN_LOG10: u16 = 3183;
/// `:execute` statement: pop argc values, join with spaces, run as a command.
pub const VIML_EXEC_STMT: u16 = 3184;
/// `:set` statement: pop the argument string, apply via `option::do_set`.
pub const VIML_SET: u16 = 3185;
/// `:map`-family statement: pop the raw command line, apply via `do_map`.
pub const VIML_MAP: u16 = 3562;
/// `:command` statement: pop the args, define a user command via `ex_command`.
pub const VIML_COMMAND: u16 = 3563;
/// `:delcommand` statement: pop the name, delete via `ex_delcommand`.
pub const VIML_DELCOMMAND: u16 = 3564;
/// User-command invocation: pop the raw line, expand + run the replacement.
pub const VIML_USERCMD: u16 = 3565;
/// `:autocmd` statement: pop the args, register via `do_autocmd`.
pub const VIML_AUTOCMD: u16 = 3566;
/// `:augroup` statement: pop the name, set the group via `do_augroup`.
pub const VIML_AUGROUP: u16 = 3567;
/// `:doautocmd` statement: pop the args, fire matching autocommands.
pub const VIML_DOAUTOCMD: u16 = 3568;
/// `:[range]cmd` statement: pop the raw line, run it against the buffer.
pub const VIML_EXCMD: u16 = 3569;
/// `:colorscheme {name}` statement: pop the name, source `colors/{name}.vim`.
pub const VIML_COLORSCHEME: u16 = 3576;
/// `:highlight {args}` statement: pop the args, define a highlight group.
pub const VIML_HIGHLIGHT: u16 = 3577;
/// `:syntax {args}` statement: pop the args, forward to the host (else no-op).
pub const VIML_SYNTAX: u16 = 3578;
/// `:filetype {args}` statement: pop the args, forward to the host (else no-op).
pub const VIML_FILETYPE: u16 = 3579;
/// `:source {file}`: pop the filename, read and run it in the current scope.
pub const VIML_SOURCE: u16 = 3500;
/// `:unlet {name}`: pop the name, delete the variable.
pub const VIML_UNLET: u16 = 3501;
/// `:unlet base[index]` / `:unlet base.key`: pop index then container, remove
/// the List item or Dict entry in place.
pub const VIML_UNLET_INDEX: u16 = 3502;
/// `json_encode()`
pub const VIML_FN_JSON_ENCODE: u16 = 3186;
/// `json_decode()`
pub const VIML_FN_JSON_DECODE: u16 = 3187;
/// `strgetchar()`
pub const VIML_FN_STRGETCHAR: u16 = 3188;
/// `strcharpart()`
pub const VIML_FN_STRCHARPART: u16 = 3189;
/// `byteidx()`
pub const VIML_FN_BYTEIDX: u16 = 3190;
/// `charidx()`
pub const VIML_FN_CHARIDX: u16 = 3191;
/// `matchstrpos()`
pub const VIML_FN_MATCHSTRPOS: u16 = 3192;
/// `extendnew()`
pub const VIML_FN_EXTENDNEW: u16 = 3193;
/// `getenv()`
pub const VIML_FN_GETENV: u16 = 3194;
/// `setenv()`
pub const VIML_FN_SETENV: u16 = 3195;
/// `shellescape()`
pub const VIML_FN_SHELLESCAPE: u16 = 3196;
/// `isinf()`
pub const VIML_FN_ISINF: u16 = 3197;
/// `isnan()`
pub const VIML_FN_ISNAN: u16 = 3198;
/// `getpid()`
pub const VIML_FN_GETPID: u16 = 3199;
/// `localtime()`
pub const VIML_FN_LOCALTIME: u16 = 3200;
/// `soundfold()`
pub const VIML_FN_SOUNDFOLD: u16 = 3201;
/// `byteidxcomp()`
pub const VIML_FN_BYTEIDXCOMP: u16 = 3202;
/// `reltime()`
pub const VIML_FN_RELTIME: u16 = 3203;
/// `reltimestr()`
pub const VIML_FN_RELTIMESTR: u16 = 3204;
/// `reltimefloat()`
pub const VIML_FN_RELTIMEFLOAT: u16 = 3205;
/// `rand()`
pub const VIML_FN_RAND: u16 = 3206;
/// `srand()`
pub const VIML_FN_SRAND: u16 = 3207;
/// `strftime()`
pub const VIML_FN_STRFTIME: u16 = 3208;
/// `strptime()`
pub const VIML_FN_STRPTIME: u16 = 3209;
/// `pathshorten()`
pub const VIML_FN_PATHSHORTEN: u16 = 3210;
/// eval/fs.c filesystem builtins.
pub const VIML_FN_ISABSOLUTEPATH: u16 = 3219;
/// `simplify()`
pub const VIML_FN_SIMPLIFY: u16 = 3220;
/// `filereadable()`
pub const VIML_FN_FILEREADABLE: u16 = 3221;
/// `filewritable()`
pub const VIML_FN_FILEWRITABLE: u16 = 3222;
/// `isdirectory()`
pub const VIML_FN_ISDIRECTORY: u16 = 3223;
/// `getfsize()`
pub const VIML_FN_GETFSIZE: u16 = 3224;
/// `getftype()`
pub const VIML_FN_GETFTYPE: u16 = 3225;
/// `getftime()`
pub const VIML_FN_GETFTIME: u16 = 3226;
/// `getfperm()`
pub const VIML_FN_GETFPERM: u16 = 3227;
/// `setfperm()`
pub const VIML_FN_SETFPERM: u16 = 3228;
/// `getcwd()`
pub const VIML_FN_GETCWD: u16 = 3229;
/// `chdir()`
pub const VIML_FN_CHDIR: u16 = 3230;
/// `executable()`
pub const VIML_FN_EXECUTABLE: u16 = 3231;
/// `exepath()`
pub const VIML_FN_EXEPATH: u16 = 3232;
/// `tempname()`
pub const VIML_FN_TEMPNAME: u16 = 3233;
/// `mkdir()`
pub const VIML_FN_MKDIR: u16 = 3234;
/// `delete()`
pub const VIML_FN_DELETE: u16 = 3235;
/// `rename()`
pub const VIML_FN_RENAME: u16 = 3236;
/// `readfile()`
pub const VIML_FN_READFILE: u16 = 3237;
/// `writefile()`
pub const VIML_FN_WRITEFILE: u16 = 3238;
/// `fnamemodify()`
pub const VIML_FN_FNAMEMODIFY: u16 = 3239;
/// `filecopy()`
pub const VIML_FN_FILECOPY: u16 = 3240;
/// `haslocaldir()`
pub const VIML_FN_HASLOCALDIR: u16 = 3241;
/// `resolve()`
pub const VIML_FN_RESOLVE: u16 = 3242;
/// `glob2regpat()`
pub const VIML_FN_GLOB2REGPAT: u16 = 3243;
/// `readdir()`
pub const VIML_FN_READDIR: u16 = 3244;
/// `readblob()`
pub const VIML_FN_READBLOB: u16 = 3245;
/// `getreg()`
pub const VIML_FN_GETREG: u16 = 3246;
/// `getregtype()`
pub const VIML_FN_GETREGTYPE: u16 = 3247;
/// `getreginfo()`
pub const VIML_FN_GETREGINFO: u16 = 3248;
/// `setreg()`
pub const VIML_FN_SETREG: u16 = 3249;
/// `reg_recording()`
pub const VIML_FN_REG_RECORDING: u16 = 3250;
/// `reg_executing()`
pub const VIML_FN_REG_EXECUTING: u16 = 3251;
/// `reg_recorded()`
pub const VIML_FN_REG_RECORDED: u16 = 3252;
/// `gettext()`
pub const VIML_FN_GETTEXT: u16 = 3253;
/// `garbagecollect()`
pub const VIML_FN_GARBAGECOLLECT: u16 = 3254;
/// `funcref()`
pub const VIML_FN_FUNCREF: u16 = 3255;
/// `id()`
pub const VIML_FN_ID: u16 = 3256;
/// `indexof()`
pub const VIML_FN_INDEXOF: u16 = 3257;
/// `matchstrlist()`
pub const VIML_FN_MATCHSTRLIST: u16 = 3258;
/// `fnameescape()`
pub const VIML_FN_FNAMEESCAPE: u16 = 3259;
/// `shiftwidth()`
pub const VIML_FN_SHIFTWIDTH: u16 = 3260;
/// `mode()`
pub const VIML_FN_MODE: u16 = 3261;
/// `state()`
pub const VIML_FN_STATE: u16 = 3262;
/// `visualmode()`
pub const VIML_FN_VISUALMODE: u16 = 3263;
/// `pumvisible()`
pub const VIML_FN_PUMVISIBLE: u16 = 3264;
/// `wildmenumode()`
pub const VIML_FN_WILDMENUMODE: u16 = 3265;
/// `did_filetype()`
pub const VIML_FN_DID_FILETYPE: u16 = 3266;
/// `eventhandler()`
pub const VIML_FN_EVENTHANDLER: u16 = 3267;
/// `hlexists()`
pub const VIML_FN_HLEXISTS: u16 = 3268;
/// `windowsversion()`
pub const VIML_FN_WINDOWSVERSION: u16 = 3269;
/// `getfontname()`
pub const VIML_FN_GETFONTNAME: u16 = 3270;
/// `foreground()`
pub const VIML_FN_FOREGROUND: u16 = 3271;
/// `prompt_getprompt()`
pub const VIML_FN_PROMPT_GETPROMPT: u16 = 3272;
/// `pum_getpos()`
pub const VIML_FN_PUM_GETPOS: u16 = 3273;
/// `serverlist()`
pub const VIML_FN_SERVERLIST: u16 = 3274;
/// `getpos()`
pub const VIML_FN_GETPOS: u16 = 3275;
/// `getcharpos()`
pub const VIML_FN_GETCHARPOS: u16 = 3276;
/// `getcurpos()`
pub const VIML_FN_GETCURPOS: u16 = 3277;
/// `getcursorcharpos()`
pub const VIML_FN_GETCURSORCHARPOS: u16 = 3278;
/// `col()`
pub const VIML_FN_COL: u16 = 3279;
/// `charcol()`
pub const VIML_FN_CHARCOL: u16 = 3280;
/// `line()`
pub const VIML_FN_LINE: u16 = 3281;
/// `virtcol()`
pub const VIML_FN_VIRTCOL: u16 = 3282;
/// `screenrow()`
pub const VIML_FN_SCREENROW: u16 = 3283;
/// `screencol()`
pub const VIML_FN_SCREENCOL: u16 = 3284;
/// `screenchar()`
pub const VIML_FN_SCREENCHAR: u16 = 3285;
/// `screenattr()`
pub const VIML_FN_SCREENATTR: u16 = 3286;
/// `screenchars()`
pub const VIML_FN_SCREENCHARS: u16 = 3287;
/// `screenstring()`
pub const VIML_FN_SCREENSTRING: u16 = 3288;
/// `line2byte()`
pub const VIML_FN_LINE2BYTE: u16 = 3289;
/// `byte2line()`
pub const VIML_FN_BYTE2LINE: u16 = 3290;
/// `nextnonblank()`
pub const VIML_FN_NEXTNONBLANK: u16 = 3291;
/// `prevnonblank()`
pub const VIML_FN_PREVNONBLANK: u16 = 3292;
/// `wordcount()`
pub const VIML_FN_WORDCOUNT: u16 = 3293;
/// `getjumplist()`
pub const VIML_FN_GETJUMPLIST: u16 = 3294;
/// `getchangelist()`
pub const VIML_FN_GETCHANGELIST: u16 = 3295;
/// `getmarklist()`
pub const VIML_FN_GETMARKLIST: u16 = 3296;
/// `gettagstack()`
pub const VIML_FN_GETTAGSTACK: u16 = 3297;
/// `tagfiles()`
pub const VIML_FN_TAGFILES: u16 = 3298;
/// `taglist()`
pub const VIML_FN_TAGLIST: u16 = 3299;
/// `tabpagebuflist()`
pub const VIML_FN_TABPAGEBUFLIST: u16 = 3300;
/// `search()`
pub const VIML_FN_SEARCH: u16 = 3301;
/// `searchpos()`
pub const VIML_FN_SEARCHPOS: u16 = 3302;
/// `searchpair()`
pub const VIML_FN_SEARCHPAIR: u16 = 3303;
/// `searchpairpos()`
pub const VIML_FN_SEARCHPAIRPOS: u16 = 3304;
/// `searchdecl()`
pub const VIML_FN_SEARCHDECL: u16 = 3305;
/// `getcharsearch()`
pub const VIML_FN_GETCHARSEARCH: u16 = 3306;
/// `input()`
pub const VIML_FN_INPUT: u16 = 3307;
/// `inputsecret()`
pub const VIML_FN_INPUTSECRET: u16 = 3308;
/// `inputdialog()`
pub const VIML_FN_INPUTDIALOG: u16 = 3309;
/// `inputlist()`
pub const VIML_FN_INPUTLIST: u16 = 3310;
/// `inputsave()`
pub const VIML_FN_INPUTSAVE: u16 = 3311;
/// `inputrestore()`
pub const VIML_FN_INPUTRESTORE: u16 = 3312;
/// `confirm()`
pub const VIML_FN_CONFIRM: u16 = 3313;
/// `synID()`
pub const VIML_FN_SYNID: u16 = 3314;
/// `synIDtrans()`
pub const VIML_FN_SYNIDTRANS: u16 = 3315;
/// `synIDattr()`
pub const VIML_FN_SYNIDATTR: u16 = 3316;
/// `synstack()`
pub const VIML_FN_SYNSTACK: u16 = 3317;
/// `synconcealed()`
pub const VIML_FN_SYNCONCEALED: u16 = 3318;
/// `changenr()`
pub const VIML_FN_CHANGENR: u16 = 3319;
/// `swapname()`
pub const VIML_FN_SWAPNAME: u16 = 3320;
/// `swapfilelist()`
pub const VIML_FN_SWAPFILELIST: u16 = 3321;
/// `spellbadword()`
pub const VIML_FN_SPELLBADWORD: u16 = 3322;
/// `spellsuggest()`
pub const VIML_FN_SPELLSUGGEST: u16 = 3323;
/// `getregion()`
pub const VIML_FN_GETREGION: u16 = 3324;
/// `getregionpos()`
pub const VIML_FN_GETREGIONPOS: u16 = 3325;
/// `matchbufline()`
pub const VIML_FN_MATCHBUFLINE: u16 = 3326;
/// `menu_get()`
pub const VIML_FN_MENU_GET: u16 = 3327;
/// `timer_info()`
pub const VIML_FN_TIMER_INFO: u16 = 3328;
/// `timer_start()`
pub const VIML_FN_TIMER_START: u16 = 3329;
/// `timer_stop()`
pub const VIML_FN_TIMER_STOP: u16 = 3330;
/// `timer_pause()`
pub const VIML_FN_TIMER_PAUSE: u16 = 3331;
/// `timer_stopall()`
pub const VIML_FN_TIMER_STOPALL: u16 = 3332;
/// `setpos()`
pub const VIML_FN_SETPOS: u16 = 3333;
/// `setcharpos()`
pub const VIML_FN_SETCHARPOS: u16 = 3334;
/// `cursor()`
pub const VIML_FN_CURSOR: u16 = 3335;
/// `setcursorcharpos()`
pub const VIML_FN_SETCURSORCHARPOS: u16 = 3336;
/// `setcharsearch()`
pub const VIML_FN_SETCHARSEARCH: u16 = 3337;
/// `settagstack()`
pub const VIML_FN_SETTAGSTACK: u16 = 3338;
/// `assert_equal()`
pub const VIML_FN_ASSERT_EQUAL: u16 = 3339;
/// `assert_notequal()`
pub const VIML_FN_ASSERT_NOTEQUAL: u16 = 3340;
/// `assert_true()`
pub const VIML_FN_ASSERT_TRUE: u16 = 3341;
/// `assert_false()`
pub const VIML_FN_ASSERT_FALSE: u16 = 3342;
/// `assert_match()`
pub const VIML_FN_ASSERT_MATCH: u16 = 3343;
/// `assert_notmatch()`
pub const VIML_FN_ASSERT_NOTMATCH: u16 = 3344;
/// `assert_report()`
pub const VIML_FN_ASSERT_REPORT: u16 = 3345;
/// `assert_inrange()`
pub const VIML_FN_ASSERT_INRANGE: u16 = 3346;
/// `assert_exception()`
pub const VIML_FN_ASSERT_EXCEPTION: u16 = 3347;
/// `assert_fails()`
pub const VIML_FN_ASSERT_FAILS: u16 = 3348;
/// `system()`
pub const VIML_FN_SYSTEM: u16 = 3349;
/// `systemlist()`
pub const VIML_FN_SYSTEMLIST: u16 = 3350;
/// `environ()`
pub const VIML_FN_ENVIRON: u16 = 3351;
/// `slice()`
pub const VIML_FN_SLICE: u16 = 3352;
/// `strcharlen()`
pub const VIML_FN_STRCHARLEN: u16 = 3353;
/// `strtrans()`
pub const VIML_FN_STRTRANS: u16 = 3354;
/// `strwidth()`
pub const VIML_FN_STRWIDTH: u16 = 3355;
/// `strdisplaywidth()`
pub const VIML_FN_STRDISPLAYWIDTH: u16 = 3356;
/// `charclass()`
pub const VIML_FN_CHARCLASS: u16 = 3357;
/// `glob()`
pub const VIML_FN_GLOB: u16 = 3358;
/// `globpath()`
pub const VIML_FN_GLOBPATH: u16 = 3359;
/// `strutf16len()`
pub const VIML_FN_STRUTF16LEN: u16 = 3360;
/// `utf16idx()`
pub const VIML_FN_UTF16IDX: u16 = 3361;
/// `bufnr()`
pub const VIML_FN_BUFNR: u16 = 3362;
/// `bufexists()`
pub const VIML_FN_BUFEXISTS: u16 = 3363;
/// `buflisted()`
pub const VIML_FN_BUFLISTED: u16 = 3364;
/// `bufloaded()`
pub const VIML_FN_BUFLOADED: u16 = 3365;
/// `bufname()`
pub const VIML_FN_BUFNAME: u16 = 3366;
/// `bufwinnr()`
pub const VIML_FN_BUFWINNR: u16 = 3367;
/// `bufwinid()`
pub const VIML_FN_BUFWINID: u16 = 3368;
/// `winnr()`
pub const VIML_FN_WINNR: u16 = 3369;
/// `winbufnr()`
pub const VIML_FN_WINBUFNR: u16 = 3370;
/// `winwidth()`
pub const VIML_FN_WINWIDTH: u16 = 3371;
/// `winheight()`
pub const VIML_FN_WINHEIGHT: u16 = 3372;
/// `winlayout()`
pub const VIML_FN_WINLAYOUT: u16 = 3373;
/// `winline()`
pub const VIML_FN_WINLINE: u16 = 3374;
/// `wincol()`
pub const VIML_FN_WINCOL: u16 = 3375;
/// `winrestcmd()`
pub const VIML_FN_WINRESTCMD: u16 = 3376;
/// `tabpagenr()`
pub const VIML_FN_TABPAGENR: u16 = 3377;
/// `tabpagewinnr()`
pub const VIML_FN_TABPAGEWINNR: u16 = 3378;
/// `getline()`
pub const VIML_FN_GETLINE: u16 = 3379;
/// `getbufline()`
pub const VIML_FN_GETBUFLINE: u16 = 3380;
/// `getbufoneline()`
pub const VIML_FN_GETBUFONELINE: u16 = 3381;
/// `getbufinfo()`
pub const VIML_FN_GETBUFINFO: u16 = 3382;
/// `setline()`
pub const VIML_FN_SETLINE: u16 = 3383;
/// `setbufline()`
pub const VIML_FN_SETBUFLINE: u16 = 3384;
/// `append()`
pub const VIML_FN_APPEND: u16 = 3385;
/// `appendbufline()`
pub const VIML_FN_APPENDBUFLINE: u16 = 3386;
/// `deletebufline()`
pub const VIML_FN_DELETEBUFLINE: u16 = 3387;
/// `getwininfo()`
pub const VIML_FN_GETWININFO: u16 = 3388;
/// `gettabinfo()`
pub const VIML_FN_GETTABINFO: u16 = 3389;
/// `getwinpos()`
pub const VIML_FN_GETWINPOS: u16 = 3390;
/// `getwinposx()`
pub const VIML_FN_GETWINPOSX: u16 = 3391;
/// `getwinposy()`
pub const VIML_FN_GETWINPOSY: u16 = 3392;
/// `win_getid()`
pub const VIML_FN_WIN_GETID: u16 = 3393;
/// `win_id2win()`
pub const VIML_FN_WIN_ID2WIN: u16 = 3394;
/// `win_findbuf()`
pub const VIML_FN_WIN_FINDBUF: u16 = 3395;
/// `win_gotoid()`
pub const VIML_FN_WIN_GOTOID: u16 = 3396;
/// `win_gettype()`
pub const VIML_FN_WIN_GETTYPE: u16 = 3397;
/// `win_screenpos()`
pub const VIML_FN_WIN_SCREENPOS: u16 = 3398;
/// `expand()`
pub const VIML_FN_EXPAND: u16 = 3399;
/// `expandcmd()`
pub const VIML_FN_EXPANDCMD: u16 = 3400;
/// `win_id2tabwin()`
pub const VIML_FN_WIN_ID2TABWIN: u16 = 3401;
/// `win_splitmove()`
pub const VIML_FN_WIN_SPLITMOVE: u16 = 3402;
/// `win_move_separator()`
pub const VIML_FN_WIN_MOVE_SEPARATOR: u16 = 3403;
/// `win_move_statusline()`
pub const VIML_FN_WIN_MOVE_STATUSLINE: u16 = 3404;
/// `getcmdwintype()`
pub const VIML_FN_GETCMDWINTYPE: u16 = 3405;
/// `winrestview()`
pub const VIML_FN_WINRESTVIEW: u16 = 3406;
/// `winsaveview()`
pub const VIML_FN_WINSAVEVIEW: u16 = 3407;
/// `bufload()`
pub const VIML_FN_BUFLOAD: u16 = 3408;
/// `prompt_getinput()`
pub const VIML_FN_PROMPT_GETINPUT: u16 = 3409;
/// `prompt_setprompt()`
pub const VIML_FN_PROMPT_SETPROMPT: u16 = 3410;
/// `prompt_setcallback()`
pub const VIML_FN_PROMPT_SETCALLBACK: u16 = 3411;
/// `prompt_setinterrupt()`
pub const VIML_FN_PROMPT_SETINTERRUPT: u16 = 3412;
/// `interrupt()`
pub const VIML_FN_INTERRUPT: u16 = 3413;
/// `debugbreak()`
pub const VIML_FN_DEBUGBREAK: u16 = 3414;
/// `api_info()`
pub const VIML_FN_API_INFO: u16 = 3415;
/// `swapinfo()`
pub const VIML_FN_SWAPINFO: u16 = 3416;
/// `serverstart()`
pub const VIML_FN_SERVERSTART: u16 = 3417;
/// `serverstop()`
pub const VIML_FN_SERVERSTOP: u16 = 3418;
/// `getbufvar()`
pub const VIML_FN_GETBUFVAR: u16 = 3419;
/// `getwinvar()`
pub const VIML_FN_GETWINVAR: u16 = 3420;
/// `gettabvar()`
pub const VIML_FN_GETTABVAR: u16 = 3421;
/// `gettabwinvar()`
pub const VIML_FN_GETTABWINVAR: u16 = 3422;
/// `setbufvar()`
pub const VIML_FN_SETBUFVAR: u16 = 3423;
/// `setwinvar()`
pub const VIML_FN_SETWINVAR: u16 = 3424;
/// `settabvar()`
pub const VIML_FN_SETTABVAR: u16 = 3425;
/// `settabwinvar()`
pub const VIML_FN_SETTABWINVAR: u16 = 3426;
/// `jobstart()`
pub const VIML_FN_JOBSTART: u16 = 3427;
/// `jobpid()`
pub const VIML_FN_JOBPID: u16 = 3428;
/// `jobstop()`
pub const VIML_FN_JOBSTOP: u16 = 3429;
/// `jobwait()`
pub const VIML_FN_JOBWAIT: u16 = 3430;
/// `jobresize()`
pub const VIML_FN_JOBRESIZE: u16 = 3431;
/// `chanclose()`
pub const VIML_FN_CHANCLOSE: u16 = 3432;
/// `chansend()`
pub const VIML_FN_CHANSEND: u16 = 3433;
/// `feedkeys()`
pub const VIML_FN_FEEDKEYS: u16 = 3434;
/// `wait()`
pub const VIML_FN_WAIT: u16 = 3435;
/// `sockconnect()`
pub const VIML_FN_SOCKCONNECT: u16 = 3436;
/// `win_execute()`
pub const VIML_FN_WIN_EXECUTE: u16 = 3437;
/// `bufadd()`
pub const VIML_FN_BUFADD: u16 = 3438;
/// `ctxget()`
pub const VIML_FN_CTXGET: u16 = 3439;
/// `ctxpop()`
pub const VIML_FN_CTXPOP: u16 = 3440;
/// `ctxpush()`
pub const VIML_FN_CTXPUSH: u16 = 3441;
/// `ctxset()`
pub const VIML_FN_CTXSET: u16 = 3442;
/// `ctxsize()`
pub const VIML_FN_CTXSIZE: u16 = 3443;
/// `islocked()`
pub const VIML_FN_ISLOCKED: u16 = 3444;
/// `last_buffer_nr()`
pub const VIML_FN_LAST_BUFFER_NR: u16 = 3445;
/// `libcall()`
pub const VIML_FN_LIBCALL: u16 = 3446;
/// `libcallnr()`
pub const VIML_FN_LIBCALLNR: u16 = 3447;
/// `msgpackdump()`
pub const VIML_FN_MSGPACKDUMP: u16 = 3448;
/// `msgpackparse()`
pub const VIML_FN_MSGPACKPARSE: u16 = 3449;
/// `rpcnotify()`
pub const VIML_FN_RPCNOTIFY: u16 = 3450;
/// `rpcrequest()`
pub const VIML_FN_RPCREQUEST: u16 = 3451;
/// `rpcstart()`
pub const VIML_FN_RPCSTART: u16 = 3452;
/// `rpcstop()`
pub const VIML_FN_RPCSTOP: u16 = 3453;
/// `stdioopen()`
pub const VIML_FN_STDIOOPEN: u16 = 3454;
/// `submatch()`
pub const VIML_FN_SUBMATCH: u16 = 3455;
/// `prompt_appendbuf()`
pub const VIML_FN_PROMPT_APPENDBUF: u16 = 3456;
/// `py3eval()`
pub const VIML_FN_PY3EVAL: u16 = 3457;
/// `perleval()`
pub const VIML_FN_PERLEVAL: u16 = 3458;
/// `stdpath()`
pub const VIML_FN_STDPATH: u16 = 3459;
/// `keytrans()`
pub const VIML_FN_KEYTRANS: u16 = 3460;
/// `luaeval()`
pub const VIML_FN_LUAEVAL: u16 = 3461;
/// `rubyeval()`
pub const VIML_FN_RUBYEVAL: u16 = 3462;
/// `termopen()`
pub const VIML_FN_TERMOPEN: u16 = 3463;
/// `browse()`
pub const VIML_FN_BROWSE: u16 = 3464;
/// `browsedir()`
pub const VIML_FN_BROWSEDIR: u16 = 3465;
/// `finddir()`
pub const VIML_FN_FINDDIR: u16 = 3466;
/// `findfile()`
pub const VIML_FN_FINDFILE: u16 = 3467;
/// `matchfuzzy()`
pub const VIML_FN_MATCHFUZZY: u16 = 3468;
/// `matchfuzzypos()`
pub const VIML_FN_MATCHFUZZYPOS: u16 = 3469;
/// `histadd()`
pub const VIML_FN_HISTADD: u16 = 3470;
/// `histget()`
pub const VIML_FN_HISTGET: u16 = 3471;
/// `histnr()`
pub const VIML_FN_HISTNR: u16 = 3472;
/// `histdel()`
pub const VIML_FN_HISTDEL: u16 = 3473;
/// `digraph_get()`
pub const VIML_FN_DIGRAPH_GET: u16 = 3474;
/// `digraph_set()`
pub const VIML_FN_DIGRAPH_SET: u16 = 3475;
/// `digraph_getlist()`
pub const VIML_FN_DIGRAPH_GETLIST: u16 = 3476;
/// `digraph_setlist()`
pub const VIML_FN_DIGRAPH_SETLIST: u16 = 3477;
/// `setcellwidths()`
pub const VIML_FN_SETCELLWIDTHS: u16 = 3478;
/// `getcellwidths()`
pub const VIML_FN_GETCELLWIDTHS: u16 = 3479;
/// `hostname()`
pub const VIML_FN_HOSTNAME: u16 = 3480;
/// `iconv()`
pub const VIML_FN_ICONV: u16 = 3481;
/// `argc()`
pub const VIML_FN_ARGC: u16 = 3482;
/// `argidx()`
pub const VIML_FN_ARGIDX: u16 = 3483;
/// `argv()`
pub const VIML_FN_ARGV: u16 = 3484;
/// `assert_equalfile()`
pub const VIML_FN_ASSERT_EQUALFILE: u16 = 3485;
/// `arglistid()`
pub const VIML_FN_ARGLISTID: u16 = 3486;
/// `foldlevel()`
pub const VIML_FN_FOLDLEVEL: u16 = 3487;
/// `matchadd()`
pub const VIML_FN_MATCHADD: u16 = 3488;
/// `matchaddpos()`
pub const VIML_FN_MATCHADDPOS: u16 = 3489;
/// `matchdelete()`
pub const VIML_FN_MATCHDELETE: u16 = 3490;
/// `getmatches()`
pub const VIML_FN_GETMATCHES: u16 = 3491;
/// `setmatches()`
pub const VIML_FN_SETMATCHES: u16 = 3492;
/// `clearmatches()`
pub const VIML_FN_CLEARMATCHES: u16 = 3493;
/// `matcharg()`
pub const VIML_FN_MATCHARG: u16 = 3494;
/// `sign_define()`
pub const VIML_FN_SIGN_DEFINE: u16 = 3495;
/// `sign_getdefined()`
pub const VIML_FN_SIGN_GETDEFINED: u16 = 3496;
/// `sign_undefine()`
pub const VIML_FN_SIGN_UNDEFINE: u16 = 3497;
/// `foldclosed()`
pub const VIML_FN_FOLDCLOSED: u16 = 3498;
/// `foldclosedend()`
pub const VIML_FN_FOLDCLOSEDEND: u16 = 3499;
/// `hasmapto()`
pub const VIML_FN_HASMAPTO: u16 = 3503;
/// `maparg()`
pub const VIML_FN_MAPARG: u16 = 3504;
/// `mapcheck()`
pub const VIML_FN_MAPCHECK: u16 = 3505;
/// `maplist()`
pub const VIML_FN_MAPLIST: u16 = 3506;
/// `setcmdline()`
pub const VIML_FN_SETCMDLINE: u16 = 3507;
/// `getcmdline()`
pub const VIML_FN_GETCMDLINE: u16 = 3508;
/// `setcmdpos()`
pub const VIML_FN_SETCMDPOS: u16 = 3509;
/// `getcmdpos()`
pub const VIML_FN_GETCMDPOS: u16 = 3510;
/// `getcmdtype()`
pub const VIML_FN_GETCMDTYPE: u16 = 3511;
/// `sign_place()`
pub const VIML_FN_SIGN_PLACE: u16 = 3512;
/// `sign_getplaced()`
pub const VIML_FN_SIGN_GETPLACED: u16 = 3513;
/// `sign_unplace()`
pub const VIML_FN_SIGN_UNPLACE: u16 = 3514;
/// `sign_placelist()`
pub const VIML_FN_SIGN_PLACELIST: u16 = 3515;
/// `sign_unplacelist()`
pub const VIML_FN_SIGN_UNPLACELIST: u16 = 3516;
/// `sign_jump()`
pub const VIML_FN_SIGN_JUMP: u16 = 3517;
/// `indent()`
pub const VIML_FN_INDENT: u16 = 3518;
/// `foldtext()`
pub const VIML_FN_FOLDTEXT: u16 = 3519;
/// `foldtextresult()`
pub const VIML_FN_FOLDTEXTRESULT: u16 = 3520;
/// `highlight_exists()`
pub const VIML_FN_HIGHLIGHT_EXISTS: u16 = 3521;
/// `diff_filler()`
pub const VIML_FN_DIFF_FILLER: u16 = 3522;
/// `virtcol2col()`
pub const VIML_FN_VIRTCOL2COL: u16 = 3523;
/// `hlID()` (and its deprecated alias `highlightID()`)
pub const VIML_FN_HLID: u16 = 3572;
/// `diff_hlID()`
pub const VIML_FN_DIFF_HLID: u16 = 3573;
/// `wildtrigger()`
pub const VIML_FN_WILDTRIGGER: u16 = 3524;
/// `searchcount()`
pub const VIML_FN_SEARCHCOUNT: u16 = 3525;
/// `complete_info()`
pub const VIML_FN_COMPLETE_INFO: u16 = 3526;
/// `setqflist()`
pub const VIML_FN_SETQFLIST: u16 = 3527;
/// `getqflist()`
pub const VIML_FN_GETQFLIST: u16 = 3528;
/// `setloclist()`
pub const VIML_FN_SETLOCLIST: u16 = 3529;
/// `getloclist()`
pub const VIML_FN_GETLOCLIST: u16 = 3530;
/// `getcompletion()`
pub const VIML_FN_GETCOMPLETION: u16 = 3531;
/// `getchar()`
pub const VIML_FN_GETCHAR: u16 = 3532;
/// `getcharstr()`
pub const VIML_FN_GETCHARSTR: u16 = 3533;
/// `getcharmod()`
pub const VIML_FN_GETCHARMOD: u16 = 3534;
/// `getcmdprompt()`
pub const VIML_FN_GETCMDPROMPT: u16 = 3535;
/// `getcmdscreenpos()`
pub const VIML_FN_GETCMDSCREENPOS: u16 = 3536;
/// `getcmdcompltype()`
pub const VIML_FN_GETCMDCOMPLTYPE: u16 = 3537;
/// `getcmdcomplpat()`
pub const VIML_FN_GETCMDCOMPLPAT: u16 = 3538;
/// `cindent()`
pub const VIML_FN_CINDENT: u16 = 3539;
/// `lispindent()`
pub const VIML_FN_LISPINDENT: u16 = 3540;
/// `complete_add()`
pub const VIML_FN_COMPLETE_ADD: u16 = 3541;
/// `complete_check()`
pub const VIML_FN_COMPLETE_CHECK: u16 = 3542;
/// `cmdcomplete_info()`
pub const VIML_FN_CMDCOMPLETE_INFO: u16 = 3543;
/// `menu_info()`
pub const VIML_FN_MENU_INFO: u16 = 3544;
/// `test_garbagecollect_now()`
pub const VIML_FN_TEST_GARBAGECOLLECT_NOW: u16 = 3545;
/// `test_write_list_log()`
pub const VIML_FN_TEST_WRITE_LIST_LOG: u16 = 3546;
/// `pyeval()`
pub const VIML_FN_PYEVAL: u16 = 3547;
/// `pyxeval()`
pub const VIML_FN_PYXEVAL: u16 = 3548;
/// `undofile()`
pub const VIML_FN_UNDOFILE: u16 = 3549;
/// `undotree()`
pub const VIML_FN_UNDOTREE: u16 = 3550;
/// `getmousepos()`
pub const VIML_FN_GETMOUSEPOS: u16 = 3551;
/// `screenpos()`
pub const VIML_FN_SCREENPOS: u16 = 3552;
/// `getcompletiontype()`
pub const VIML_FN_GETCOMPLETIONTYPE: u16 = 3553;
/// `mapset()`
pub const VIML_FN_MAPSET: u16 = 3554;
/// `complete()`
pub const VIML_FN_COMPLETE: u16 = 3555;
/// `preinserted()`
pub const VIML_FN_PREINSERTED: u16 = 3556;
/// `getscriptinfo()`
pub const VIML_FN_GETSCRIPTINFO: u16 = 3557;
/// `getstacktrace()`
pub const VIML_FN_GETSTACKTRACE: u16 = 3558;
/// `fullcommand()`
pub const VIML_FN_FULLCOMMAND: u16 = 3559;
/// `assert_beeps()`
pub const VIML_FN_ASSERT_BEEPS: u16 = 3560;
/// `assert_nobeep()`
pub const VIML_FN_ASSERT_NOBEEP: u16 = 3561;
/// `flattennew()`
pub const VIML_FN_FLATTENNEW: u16 = 3211;
/// `sha256()`
pub const VIML_FN_SHA256: u16 = 3212;
/// `blob2list()`
pub const VIML_FN_BLOB2LIST: u16 = 3213;
/// `list2blob()`
pub const VIML_FN_LIST2BLOB: u16 = 3214;
/// `mapnew()`
pub const VIML_FN_MAPNEW: u16 = 3215;
/// `foreach()`
pub const VIML_FN_FOREACH: u16 = 3216;
/// `dictwatcheradd()`
pub const VIML_FN_DICTWATCHERADD: u16 = 3217;
/// `dictwatcherdel()`
pub const VIML_FN_DICTWATCHERDEL: u16 = 3218;
/// Debug line marker: pop a line number → notify the DAP `check_line` hook
/// (emitted before each statement only in debug-compiled chunks).
pub const VIML_SET_LINENO: u16 = 3070;
/// User-function call: pop `argc` args then the name → run the function.
pub const VIML_CALL_USER: u16 = 3071;
/// Funcref-value call: pop `argc` args then a Funcref/Partial value → call it.
pub const VIML_CALL_FUNCREF: u16 = 3574;
/// Snapshot `did_emsg` before a statement evaluates its expression, so the
/// statement (e.g. `:echo`) can suppress its output if an error was raised.
pub const VIML_ERR_MARK: u16 = 3575;
/// `:return {expr}`: pop the value → store it as the current call's result.
pub const VIML_SET_RETURN: u16 = 3072;
/// `:throw {expr}`: pop the value → raise it as the pending exception.
pub const VIML_THROW: u16 = 3073;
/// Push `Bool(an exception is pending)` — the per-statement unwind check.
pub const VIML_CHECK_EXC: u16 = 3074;
/// `:catch /{pat}/`: pop the pattern → if it matches the pending exception,
/// catch it (clear pending, keep `v:exception`) and push `Bool(true)`.
pub const VIML_CATCH_MATCH: u16 = 3075;
/// At program end: if an exception is still pending, report `E605` and clear it.
pub const VIML_REPORT_UNCAUGHT: u16 = 3076;
/// Register a deferred (block-level) `:function` when its line executes. Pops the
/// staging key emitted by the compiler and moves the staged def into the live
/// `FUNCTIONS` registry — see [`b_define_func`].
pub const VIML_DEFINE_FUNC: u16 = 3580;

/// Builtin id for comparison `(op, ignore_case)`.
pub fn cmp_id(op: CmpOp, ic: bool) -> u16 {
    let off = match op {
        CmpOp::Equal => 0,
        CmpOp::NotEqual => 1,
        CmpOp::Match => 2,
        CmpOp::NoMatch => 3,
        CmpOp::Greater => 4,
        CmpOp::GreaterEqual => 5,
        CmpOp::Less => 6,
        CmpOp::LessEqual => 7,
        CmpOp::Is => 8,
        CmpOp::IsNot => 9,
    };
    VIML_CMP_BASE + off + if ic { VIML_CMP_IC_OFFSET } else { 0 }
}

/// Resolve the comparison ignore-case flag from a `==#`/`==?` suffix. Phase 3
/// has no `'ignorecase'` option, so `Default` is match-case.
pub fn ic_flag(case: CaseFlag) -> bool {
    matches!(case, CaseFlag::IgnoreCase)
}

/// Map a lexer [`CmpOp`] to the ported [`exprtype_T`] `typval_compare` expects.
fn cmp_to_exprtype(op: CmpOp) -> exprtype_T {
    match op {
        CmpOp::Equal => EXPR_EQUAL,
        CmpOp::NotEqual => EXPR_NEQUAL,
        CmpOp::Match => EXPR_MATCH,
        CmpOp::NoMatch => EXPR_NOMATCH,
        CmpOp::Greater => EXPR_GREATER,
        CmpOp::GreaterEqual => EXPR_GEQUAL,
        CmpOp::Less => EXPR_SMALLER,
        CmpOp::LessEqual => EXPR_SEQUAL,
        CmpOp::Is => EXPR_IS,
        CmpOp::IsNot => EXPR_ISNOT,
    }
}

// ── per-run bridge state (carve-out; smuggles compounds + holds the run result
//    and echo sink — no C analog) ──

thread_local! {
    /// Compound `typval_T` handles smuggled across the fusevm `Value` boundary
    /// (see file header). Cleared between runs; `Rc` keeps live values alive.
    static REFPOOL: RefCell<Vec<typval_T>> = const { RefCell::new(Vec::new()) };
    /// Value of the last bare-expression statement (REPL `-e` result).
    static LAST_RESULT: RefCell<Option<typval_T>> = const { RefCell::new(None) };
    /// `:echo` sink: `Some(buf)` captures (tests/embedding), `None` is stdout.
    static ECHO_SINK: RefCell<Option<String>> = const { RefCell::new(None) };
    /// `did_emsg` snapshot taken by `VIML_ERR_MARK` at a statement's start, so
    /// `:echo`/`:echon` can skip output when evaluating its args raised an error.
    static ERR_MARK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// Nesting depth of `execute()` calls. While > 0, `:echo` output uses Vim's
    /// execute()-capture convention (a newline *before* each `:echo`) instead of
    /// the trailing newline used for stdout / general captures.
    static EXECUTE_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    /// Registry of user-defined functions, by name (populated from a compiled
    /// program before its `main` chunk runs).
    static FUNCTIONS: RefCell<std::collections::HashMap<String, crate::compile_viml::UserFuncDef>> =
        RefCell::new(std::collections::HashMap::new());
    /// Staged deferred (block-level) `:function` defs, by content-stable staging
    /// key (`compile_viml::deferred_key`). A program stages its `deferred_funcs`
    /// here at load; the `VIML_DEFINE_FUNC` op moves the keyed def into
    /// `FUNCTIONS` when its `:function` line executes. Global (shared by every
    /// sourced script and nested function body) and persistent, so a define-op
    /// inside a function body still resolves its def when the function is called
    /// long after the source completed.
    static PENDING_FUNCS: RefCell<std::collections::HashMap<String, crate::compile_viml::UserFuncDef>> =
        RefCell::new(std::collections::HashMap::new());
    /// Stack of pending function return values (one per active call); the
    /// `VIML_SET_RETURN` handler writes the top.
    static RETURN_STACK: RefCell<Vec<Option<typval_T>>> = const { RefCell::new(Vec::new()) };
    /// The currently-raised, not-yet-caught exception value (`:throw`). `Some`
    /// while unwinding toward a `:catch`. Models `ex_eval.c`'s `current_exception`.
    static PENDING_EXC: RefCell<Option<String>> = const { RefCell::new(None) };
    /// `v:exception` — the most recently caught exception text.
    static V_EXCEPTION: RefCell<String> = const { RefCell::new(String::new()) };
    /// `v:val` — the current element during `map()`/`filter()`/`sort()`.
    static V_VAL: RefCell<Option<typval_T>> = const { RefCell::new(None) };
    /// `v:key` — the current key/index during `map()`/`filter()`.
    static V_KEY: RefCell<Option<typval_T>> = const { RefCell::new(None) };
}

// ── Typval ↔ fusevm::Value bridge ──

fn tv_to_value(tv: typval_T) -> Value {
    match (tv.v_type, tv.vval) {
        (VAR_NUMBER, v_number(n)) => Value::Int(n),
        (VAR_FLOAT, v_float(f)) => Value::Float(f),
        (VAR_STRING, v_string(s)) => Value::str(s),
        (VAR_FUNC, v_string(s)) => Value::str(format!("\u{1}func\u{1}{s}")),
        (VAR_BOOL, v_bool(b)) => {
            Value::Bool(b == crate::ported::eval::typval_defs_h::BoolVarValue::kBoolVarTrue)
        }
        // `v:none` is rare and must stay distinct from `v:null` (it renders
        // differently), so stash it in the REFPOOL like a compound value rather
        // than collapse it to the shared `Undef` null.
        (VAR_SPECIAL, v_special(kSpecialVarNone)) => {
            let idx = REFPOOL.with(|p| {
                let mut p = p.borrow_mut();
                p.push(typval_T {
                    v_type: VAR_SPECIAL,
                    v_lock: VAR_UNLOCKED,
                    vval: v_special(kSpecialVarNone),
                });
                p.len() - 1
            });
            Value::Ref(Box::new(Value::Int(idx as i64)))
        }
        (VAR_SPECIAL, _) | (VAR_UNKNOWN, _) => Value::Undef,
        // Compound: stash the whole typval (keeps v_type) and tag with the index.
        (vt, vv) => {
            let idx = REFPOOL.with(|p| {
                let mut p = p.borrow_mut();
                p.push(typval_T {
                    v_type: vt,
                    v_lock: VAR_UNLOCKED,
                    vval: vv,
                });
                p.len() - 1
            });
            Value::Ref(Box::new(Value::Int(idx as i64)))
        }
    }
}

fn value_to_tv(v: &Value) -> typval_T {
    match v {
        Value::Int(n) => tv_num(*n),
        Value::Float(f) => tv_flt(*f),
        Value::Bool(b) => typval_T {
            v_type: VAR_BOOL,
            v_lock: VAR_UNLOCKED,
            vval: v_bool(if *b {
                crate::ported::eval::typval_defs_h::BoolVarValue::kBoolVarTrue
            } else {
                crate::ported::eval::typval_defs_h::BoolVarValue::kBoolVarFalse
            }),
        },
        Value::Undef => tv_special(),
        Value::Status(c) => tv_num(*c as varnumber_T),
        Value::Str(s) => match s.strip_prefix("\u{1}func\u{1}") {
            Some(name) => typval_T {
                v_type: VAR_FUNC,
                v_lock: VAR_UNLOCKED,
                vval: v_string(name.to_string()),
            },
            None => tv_str(s.to_string()),
        },
        Value::Ref(inner) => match inner.as_ref() {
            Value::Int(idx) => REFPOOL.with(|p| {
                p.borrow()
                    .get(*idx as usize)
                    .cloned()
                    .unwrap_or_else(tv_special)
            }),
            _ => tv_special(),
        },
        _ => tv_special(),
    }
}

fn pop_tv(vm: &mut VM) -> typval_T {
    let v = vm.pop();
    value_to_tv(&v)
}

// ── handlers ──

fn b_throw(vm: &mut VM, _: u8) -> Value {
    let v = tv_get_string(&pop_tv(vm));
    // c: throw_exception — set current_exception and v:exception.
    V_EXCEPTION.with(|e| *e.borrow_mut() = v.clone());
    set_vim_var_string(VV_EXCEPTION, &v);
    PENDING_EXC.with(|p| *p.borrow_mut() = Some(v));
    Value::Undef
}

fn b_check_exc(_vm: &mut VM, _: u8) -> Value {
    Value::Bool(PENDING_EXC.with(|p| p.borrow().is_some()))
}

fn b_catch_match(vm: &mut VM, _: u8) -> Value {
    let pat = tv_get_string(&pop_tv(vm));
    let pending = PENDING_EXC.with(|p| p.borrow().clone());
    let Some(exc) = pending else {
        return Value::Bool(false);
    };
    // Empty pattern = catch-all; otherwise the catch pattern is a Vim regex.
    let matched = pat.is_empty() || crate::viml_regex::regex_match(&pat, &exc, false);
    if matched {
        // c: caught — clear the pending exception; v:exception already set.
        PENDING_EXC.with(|p| *p.borrow_mut() = None);
        set_vim_var_string(VV_EXCEPTION, &exc);
        V_EXCEPTION.with(|e| *e.borrow_mut() = exc);
    }
    Value::Bool(matched)
}

fn b_report_uncaught(_vm: &mut VM, _: u8) -> Value {
    if let Some(exc) = PENDING_EXC.with(|p| p.borrow_mut().take()) {
        // c: E605 when an exception reaches the top level uncaught.
        message::semsg(&format!("E605: Exception not caught: {exc}"));
    }
    Value::Undef
}

fn b_getvar(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    // Dynamic v: state (not fixed v: constants).
    if name == "v:exception" {
        return Value::str(V_EXCEPTION.with(|e| e.borrow().clone()));
    }
    if name == "v:val" {
        return V_VAL
            .with(|v| v.borrow().clone())
            .map_or(Value::Int(0), tv_to_value);
    }
    if name == "v:key" {
        return V_KEY
            .with(|v| v.borrow().clone())
            .map_or(Value::Int(0), tv_to_value);
    }
    match eval_variable(&name) {
        Some(tv) => tv_to_value(tv),
        None => {
            message::semsg(&format!("E121: Undefined variable: {name}"));
            Value::Undef
        }
    }
}

fn b_setvar(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    let val = pop_tv(vm);
    set_var(&name, name.len(), val, false);
    Value::Undef
}

fn b_setenv(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    let val = tv_get_string(&pop_tv(vm));
    std::env::set_var(name, val);
    Value::Undef
}

fn b_truthy(vm: &mut VM, _: u8) -> Value {
    // VimL truthiness: tv_get_number(tv) != 0 (the `:if`/`!`/`&&`/`||` test).
    Value::Bool(tv_get_number_chk(&pop_tv(vm), None) != 0)
}

fn b_boolnum(vm: &mut VM, _: u8) -> Value {
    Value::Int((tv_get_number_chk(&pop_tv(vm), None) != 0) as varnumber_T)
}

fn b_tonumber(vm: &mut VM, _: u8) -> Value {
    // c: range() coerces each argument with tv_get_number before counting.
    Value::Int(tv_get_number_chk(&pop_tv(vm), None))
}

fn b_add(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval5 — `+` is List+List / Blob+Blob concat, else numeric.
    if let (VAR_LIST, VAR_LIST) = (a.v_type, b.v_type) {
        return tv_to_value(list_concat(&a, &b));
    }
    if let (VAR_BLOB, VAR_BLOB) = (a.v_type, b.v_type) {
        return tv_to_value(blob_concat(&a, &b));
    }
    if a.v_type == VAR_FLOAT || b.v_type == VAR_FLOAT {
        tv_to_value(tv_flt(tv_get_float(&a) + tv_get_float(&b)))
    } else {
        tv_to_value(tv_num(
            tv_get_number_chk(&a, None).wrapping_add(tv_get_number_chk(&b, None)),
        ))
    }
}

fn b_sub(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval5 — numeric subtraction (float if either is Float).
    if a.v_type == VAR_FLOAT || b.v_type == VAR_FLOAT {
        tv_to_value(tv_flt(tv_get_float(&a) - tv_get_float(&b)))
    } else {
        tv_to_value(tv_num(
            tv_get_number_chk(&a, None).wrapping_sub(tv_get_number_chk(&b, None)),
        ))
    }
}

fn b_mul(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval6 — `*`.
    if a.v_type == VAR_FLOAT || b.v_type == VAR_FLOAT {
        tv_to_value(tv_flt(tv_get_float(&a) * tv_get_float(&b)))
    } else {
        tv_to_value(tv_num(
            tv_get_number_chk(&a, None).wrapping_mul(tv_get_number_chk(&b, None)),
        ))
    }
}

fn b_div(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval6 — `/`: float division, else num_divide.
    if a.v_type == VAR_FLOAT || b.v_type == VAR_FLOAT {
        tv_to_value(tv_flt(tv_get_float(&a) / tv_get_float(&b)))
    } else {
        tv_to_value(tv_num(crate::ported::eval::num_divide(
            tv_get_number_chk(&a, None),
            tv_get_number_chk(&b, None),
        )))
    }
}

fn b_mod(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval6 — `%` is integer-only; a Float operand is an error (unlike `*`/`/`
    // which fall back to float arithmetic).
    if a.v_type == VAR_FLOAT || b.v_type == VAR_FLOAT {
        message::emsg("E804: Cannot use '%' with Float");
        return tv_to_value(tv_num(0));
    }
    tv_to_value(tv_num(crate::ported::eval::num_modulus(
        tv_get_number_chk(&a, None),
        tv_get_number_chk(&b, None),
    )))
}

fn b_concat(vm: &mut VM, _: u8) -> Value {
    let b = pop_tv(vm);
    let a = pop_tv(vm);
    // c: eval5 — `.`/`..` string concatenation.
    tv_to_value(tv_str(tv_get_string(&a) + &tv_get_string(&b)))
}

fn b_neg(vm: &mut VM, _: u8) -> Value {
    let v = pop_tv(vm);
    // c: eval7_leader — `-`: negate Float, else negate Number.
    match v.v_type {
        VAR_FLOAT => tv_to_value(tv_flt(-tv_get_float(&v))),
        _ => tv_to_value(tv_num(tv_get_number_chk(&v, None).wrapping_neg())),
    }
}

fn b_uplus(vm: &mut VM, _: u8) -> Value {
    let v = pop_tv(vm);
    // c: eval7_leader — `+`: coerce to Float/Number, no value change.
    match v.v_type {
        VAR_FLOAT => tv_to_value(tv_flt(tv_get_float(&v))),
        _ => tv_to_value(tv_num(tv_get_number_chk(&v, None))),
    }
}

fn b_not(vm: &mut VM, _: u8) -> Value {
    let v = pop_tv(vm);
    // c: eval7_leader — `!`: logical NOT of tv_get_number.
    tv_to_value(tv_num((tv_get_number_chk(&v, None) == 0) as varnumber_T))
}

/// Shared comparison body: `typval_compare(&mut a, &b, type, ic)` writes the
/// boolean result into `a`.
fn do_compare(vm: &mut VM, op: CmpOp, ic: bool) -> Value {
    let b = pop_tv(vm);
    let mut a = pop_tv(vm);
    crate::ported::eval::typval_compare(&mut a, &b, cmp_to_exprtype(op), ic);
    tv_to_value(a)
}

// One thin handler per comparison id (fusevm `register_builtin` takes plain
// `fn`s; the `(op, ic)` pair is compile-time known).
macro_rules! cmp_handlers {
    ($(($name:ident, $op:expr, $ic:literal)),+ $(,)?) => {
        $(fn $name(vm: &mut VM, _: u8) -> Value { do_compare(vm, $op, $ic) })+
        fn register_cmp_handlers(vm: &mut VM) {
            $(vm.register_builtin(cmp_id($op, $ic), $name);)+
        }
    };
}
cmp_handlers! {
    (cmp_eq,     CmpOp::Equal,        false), (cmp_eq_ic,     CmpOp::Equal,        true),
    (cmp_ne,     CmpOp::NotEqual,     false), (cmp_ne_ic,     CmpOp::NotEqual,     true),
    (cmp_match,  CmpOp::Match,        false), (cmp_match_ic,  CmpOp::Match,        true),
    (cmp_nomatch,CmpOp::NoMatch,      false), (cmp_nomatch_ic,CmpOp::NoMatch,      true),
    (cmp_gt,     CmpOp::Greater,      false), (cmp_gt_ic,     CmpOp::Greater,      true),
    (cmp_ge,     CmpOp::GreaterEqual, false), (cmp_ge_ic,     CmpOp::GreaterEqual, true),
    (cmp_lt,     CmpOp::Less,         false), (cmp_lt_ic,     CmpOp::Less,         true),
    (cmp_le,     CmpOp::LessEqual,    false), (cmp_le_ic,     CmpOp::LessEqual,    true),
    (cmp_is,     CmpOp::Is,           false), (cmp_is_ic,     CmpOp::Is,           true),
    (cmp_isnot,  CmpOp::IsNot,        false), (cmp_isnot_ic,  CmpOp::IsNot,        true),
}

fn b_make_list(vm: &mut VM, argc: u8) -> Value {
    let mut items = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        items.push(pop_tv(vm));
    }
    items.reverse();
    tv_to_value(new_list(items))
}

fn b_make_dict(vm: &mut VM, argc: u8) -> Value {
    let n = argc as usize / 2;
    let mut pairs = Vec::with_capacity(n);
    for _ in 0..n {
        let val = pop_tv(vm);
        let key = tv_get_string(&pop_tv(vm));
        pairs.push((key, val));
    }
    pairs.reverse();
    let d = crate::ported::eval::typval::tv_dict_alloc();
    {
        let mut db = d.borrow_mut();
        for (k, v) in pairs {
            crate::ported::eval::typval::tv_dict_add_tv(&mut db, &k, v);
        }
    }
    tv_to_value(typval_T {
        v_type: VAR_DICT,
        v_lock: VAR_UNLOCKED,
        vval: v_dict(Some(d)),
    })
}

fn b_index(vm: &mut VM, _: u8) -> Value {
    let index = pop_tv(vm);
    let base = pop_tv(vm);
    tv_to_value(index_value(&base, &index))
}

/// Runtime type test backing the no-space `base.key` dispatch: `true` iff the
/// popped value is a Dict (so `base.key` is a subscript; otherwise it is `.`
/// string concatenation). Faithful to eval.c, where `.` after a Dict subscripts
/// and after any other type concatenates.
fn b_is_dict(vm: &mut VM, _: u8) -> Value {
    Value::Bool(pop_tv(vm).v_type == VAR_DICT)
}

fn b_slice(vm: &mut VM, _: u8) -> Value {
    let to = pop_tv(vm);
    let from = pop_tv(vm);
    let base = pop_tv(vm);
    tv_to_value(slice_value(&base, &from, &to))
}

/// `let base[index] = value` — set a List/Dict/Blob element in place. For a Dict
/// this also fires any registered watchers (the add/change side).
fn b_setindex(vm: &mut VM, _: u8) -> Value {
    let index = pop_tv(vm);
    let base = pop_tv(vm);
    let value = pop_tv(vm);
    match (base.v_type, &base.vval) {
        (VAR_DICT, v_dict(Some(d))) => {
            let key = tv_get_string(&index);
            let old = d.borrow().dv_hashtab.get(&key).cloned();
            d.borrow_mut().dv_hashtab.insert(key.clone(), value.clone());
            crate::ported::eval::typval::tv_dict_watcher_notify(
                d,
                &key,
                Some(&value),
                old.as_ref(),
            );
        }
        (VAR_LIST, v_list(Some(l))) => {
            let len = l.borrow().lv_len as varnumber_T;
            let mut i = tv_get_number_chk(&index, None);
            if i < 0 {
                i += len;
            }
            if i >= 0 && i < len {
                l.borrow_mut().lv_items[i as usize].li_tv = value;
            } else {
                message::emsg("E684: list index out of range");
            }
        }
        (VAR_BLOB, v_blob(Some(b))) => {
            let len = crate::ported::eval::typval::tv_blob_len(&b.borrow()) as varnumber_T;
            let mut i = tv_get_number_chk(&index, None);
            if i < 0 {
                i += len;
            }
            if i >= 0 && i < len {
                crate::ported::eval::typval::tv_blob_set(
                    &mut b.borrow_mut(),
                    i as i32,
                    tv_get_number_chk(&value, None) as u8,
                );
            } else {
                message::emsg("E979: Blob index out of range");
            }
        }
        _ => message::emsg("E689: Can only index a List, Dictionary or Blob"),
    }
    Value::Undef
}

/// `let base[idx1:idx2] = list` — list range assignment via the ported
/// `tv_list_assign_range`. Stack (top→bottom): idx2, idx1, base, value. An
/// `idx2` of Undef (the compiler's `l[i:]` marker) means "to the end".
fn b_setrange(vm: &mut VM, _: u8) -> Value {
    use crate::ported::eval::typval::{
        tv_list_assign_range, tv_list_check_range_index_one, tv_list_check_range_index_two,
        tv_list_copy,
    };
    let idx2_tv = pop_tv(vm);
    let idx1_tv = pop_tv(vm);
    let base = pop_tv(vm);
    let value = pop_tv(vm);
    let dest = match (base.v_type, &base.vval) {
        (VAR_LIST, v_list(Some(l))) => l.clone(),
        _ => {
            message::emsg("E709: [:] requires a List value");
            return Value::Undef;
        }
    };
    // c: the source must be a List (E709 otherwise). NULL list → empty.
    let src = match (value.v_type, &value.vval) {
        (VAR_LIST, v_list(Some(l))) => tv_list_copy(l, false),
        (VAR_LIST, v_list(None)) => crate::ported::eval::typval::tv_list_alloc(0),
        _ => {
            message::emsg("E709: [:] requires a List value");
            return Value::Undef;
        }
    };
    // The compiler emits LoadUndef (→ VAR_SPECIAL/VAR_UNKNOWN) for an omitted
    // second index (`l[i:]`), meaning "to the end".
    let empty_idx2 = matches!(idx2_tv.v_type, VAR_SPECIAL | VAR_UNKNOWN);
    let mut n1 = tv_get_number_chk(&idx1_tv, None) as i32;
    let mut n2 = if empty_idx2 {
        0
    } else {
        tv_get_number_chk(&idx2_tv, None) as i32
    };
    let pos1 = match tv_list_check_range_index_one(&dest.borrow(), &mut n1, false) {
        Some(p) => p,
        None => return Value::Undef, // E684 already emitted
    };
    if !empty_idx2
        && tv_list_check_range_index_two(&dest.borrow(), &mut n1, pos1, &mut n2, false)
            == crate::ported::eval_h::FAIL
    {
        return Value::Undef;
    }
    tv_list_assign_range(&dest, &src.borrow(), n1, n2, empty_idx2, "=", "");
    Value::Undef
}

fn b_echo(vm: &mut VM, argc: u8) -> Value {
    echo_impl(vm, argc, true);
    Value::Undef
}
fn b_echon(vm: &mut VM, argc: u8) -> Value {
    echo_impl(vm, argc, false);
    Value::Undef
}

fn echo_impl(vm: &mut VM, argc: u8, newline: bool) {
    let mut parts = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        parts.push(pop_tv(vm));
    }
    parts.reverse();
    // Vim aborts a command whose expression raised an error: if `did_emsg` rose
    // since VIML_ERR_MARK (set just before the args were evaluated), print
    // nothing — no spurious fallback value after the error message.
    if message::did_emsg.with(|d| d.get()) > ERR_MARK.with(|m| m.get()) {
        return;
    }
    let sep = if newline { " " } else { "" };
    let rendered: Vec<String> = parts.iter().map(encode_tv2echo).collect();
    let body = rendered.join(sep);
    // To stdout, `:echo` ends with a newline (one message per line). Inside
    // execute(), Vim instead *prefixes* each `:echo` with a newline (so
    // string(execute("echo 5")) == "\n5"); `:echon` adds none.
    let exec_capture = EXECUTE_DEPTH.with(|d| d.get()) > 0;
    let line = if !newline {
        body
    } else if exec_capture {
        format!("\n{body}")
    } else {
        format!("{body}\n")
    };
    echo_write(&line);
}

fn b_set_result(vm: &mut VM, _: u8) -> Value {
    let v = pop_tv(vm);
    LAST_RESULT.with(|r| *r.borrow_mut() = Some(v));
    Value::Undef
}

fn b_getenv(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    Value::str(std::env::var(&name).unwrap_or_default())
}
fn b_exec_stmt(vm: &mut VM, argc: u8) -> Value {
    let mut parts = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        parts.push(tv_get_string(&pop_tv(vm)));
    }
    parts.reverse();
    let _ = run_source_nested(&parts.join(" "));
    Value::Undef
}

/// `:source {file}` — read the file and run it in the current (shared) scope,
/// so functions and globals it defines persist. `~`/`$VAR` in the path expand.
fn b_source(vm: &mut VM, _: u8) -> Value {
    let path = tv_get_string(&pop_tv(vm));
    // `:source` runs its filename through `expand_env` (Vim's `do_source`), so
    // `$VAR`/`${VAR}`/`~` in the path resolve — e.g. `source $ZPWR_FZF_DIR/x.vim`.
    let expanded = crate::ported::eval::fs::expand_env(&path);
    match std::fs::read_to_string(&expanded) {
        Ok(src) => {
            // `<sfile>`/`<script>` inside the sourced file resolve to ITS path,
            // not the parent's (a nested sourcing-name push, popped after).
            let sname = std::fs::canonicalize(&expanded)
                .map(|p| p.display().to_string())
                .unwrap_or_else(|_| expanded.clone());
            crate::ported::eval::fs::push_sourcing_name(sname);
            let _ = run_source_nested(&src);
            crate::ported::eval::fs::pop_sourcing_name();
        }
        Err(_) => message::semsg(&format!("E484: Can't open file {expanded}")),
    }
    Value::Undef
}

/// `:unlet {name}` — delete a variable (forceit: missing is not an error here).
fn b_unlet(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    crate::ported::eval::vars::do_unlet(&name, name.len(), true);
    Value::Undef
}

/// `:unlet base[index]` / `:unlet base.key` — remove one List item or Dict
/// entry. Mirrors the two element branches of `do_unlet_var()`
/// (vendor/eval/vars.c): list → `tv_list_item_remove`, dict → `tv_dict_item_remove`
/// (with a watcher notification), else E689.
fn b_unlet_index(vm: &mut VM, _: u8) -> Value {
    use crate::ported::eval::typval::{
        tv_dict_item_remove, tv_dict_watcher_notify, tv_list_item_remove,
    };
    let index = pop_tv(vm);
    let base = pop_tv(vm);
    match (base.v_type, &base.vval) {
        (VAR_DICT, v_dict(Some(d))) => {
            let key = tv_get_string(&index);
            let old = d.borrow().dv_hashtab.get(&key).cloned();
            match old {
                None => {
                    message::semsg(&format!("E716: Key not present in Dictionary: \"{key}\""));
                }
                Some(oldtv) => {
                    tv_dict_item_remove(&mut d.borrow_mut(), &key);
                    tv_dict_watcher_notify(d, &key, None, Some(&oldtv));
                }
            }
        }
        (VAR_LIST, v_list(Some(l))) => {
            let len = l.borrow().lv_len as varnumber_T;
            let mut i = tv_get_number_chk(&index, None);
            if i < 0 {
                i += len;
            }
            if i >= 0 && i < len {
                tv_list_item_remove(&mut l.borrow_mut(), i as usize);
            } else {
                message::emsg("E684: list index out of range");
            }
        }
        _ => message::emsg("E689: Can only index a List, Dictionary or Blob"),
    }
    Value::Undef
}

/// `VIML_ERR_MARK` — record the current `did_emsg` so a following `:echo` can
/// tell whether evaluating its arguments raised an error.
fn b_err_mark(_vm: &mut VM, _: u8) -> Value {
    ERR_MARK.with(|m| m.set(message::did_emsg.with(|d| d.get())));
    Value::Undef
}

fn b_set_lineno(vm: &mut VM, _: u8) -> Value {
    let line = tv_get_number_chk(&pop_tv(vm), None);
    crate::dap::check_line(line as u32);
    Value::Undef
}

thread_local! {
    /// Autoload files already sourced this run (by resolved path), so a missing
    /// `pkg#func` is not re-sourced on every call.
    static AUTOLOADED: RefCell<std::collections::HashSet<String>> =
        RefCell::new(std::collections::HashSet::new());
}

/// Try to autoload the package for `name` (`pkg#func`, `a#b#func` → `a/b`):
/// source `autoload/{path}.vim` (relative to the cwd) once. Returns true if a
/// file was sourced (so the call should be retried). Port of `script_autoload`.
fn try_autoload(name: &str) -> bool {
    let parts: Vec<&str> = name.split('#').collect();
    if parts.len() < 2 {
        return false;
    }
    let rel = format!("autoload/{}.vim", parts[..parts.len() - 1].join("/"));
    let already = AUTOLOADED.with(|s| s.borrow().contains(&rel));
    if already {
        return false;
    }
    AUTOLOADED.with(|s| {
        s.borrow_mut().insert(rel.clone());
    });
    match std::fs::read_to_string(&rel) {
        Ok(src) => {
            let _ = run_source_nested(&src);
            true
        }
        Err(_) => false,
    }
}

/// Direct call of a funcref VALUE: stack is `[funcref, arg0, …, arg{argc-1}]`
/// (the callee pushed first). Backs `expr(args)` for a funcref-valued `expr`.
fn b_call_funcref(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let callee = pop_tv(vm);
    if !matches!(callee.v_type, VAR_FUNC | VAR_PARTIAL) {
        message::emsg("E15: not a function");
        return Value::Undef;
    }
    match call_funcref(&callee, args) {
        Some(rettv) => tv_to_value(rettv),
        None => Value::Undef,
    }
}

fn b_call_user(vm: &mut VM, argc: u8) -> Value {
    // Stack: [name, arg0, …, arg{argc-1}] (name pushed first).
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let name = tv_get_string(&pop_tv(vm));
    if let Some(rettv) = call_user_function(&name, args.clone()) {
        return tv_to_value(rettv);
    }
    // Autoload: an undefined `pkg#func` sources `autoload/pkg.vim` (which should
    // define it), then the call is retried once.
    if name.contains('#') && try_autoload(&name) {
        if let Some(rettv) = call_user_function(&name, args.clone()) {
            return tv_to_value(rettv);
        }
    }
    // Fallback: `F(args)` where `F` is a variable holding a Funcref/Partial
    // (e.g. a lambda stored in a variable). Call through the funcref value.
    if let Some(v) = eval_variable(&name) {
        if matches!(v.v_type, VAR_FUNC | VAR_PARTIAL) {
            return match call_funcref(&v, args) {
                Some(rettv) => tv_to_value(rettv),
                None => {
                    message::semsg(&format!("E117: Unknown function: {name}"));
                    Value::Undef
                }
            };
        }
    }
    message::semsg(&format!("E117: Unknown function: {name}"));
    Value::Undef
}

fn b_set_return(vm: &mut VM, _: u8) -> Value {
    let v = pop_tv(vm);
    RETURN_STACK.with(|r| {
        if let Some(top) = r.borrow_mut().last_mut() {
            *top = Some(v);
        }
    });
    Value::Undef
}

/// Invoke a user function: bind `a:` args, push the `l:`/`a:` scope, run the
/// body chunk on a nested VM, and return the result (`0` if no `:return`).
fn call_user_function(name: &str, args: Vec<typval_T>) -> Option<typval_T> {
    let func = FUNCTIONS.with(|f| f.borrow().get(name).cloned())?;

    // Bind named parameters into the a: scope; extras into a:0 / a:000. A `...`
    // entry marks the varargs boundary: params before it are named, every arg
    // from that position on goes to a:000 (so `F(...)` collects all args).
    use crate::ported::eval::typval::tv_dict_add_tv;
    let nfixed = func
        .params
        .iter()
        .position(|p| p == "...")
        .unwrap_or(func.params.len());

    // Push the (empty) a:/l: frame first, then bind params into it one at a time.
    // Binding incrementally lets an omitted parameter's default expression read
    // the arguments bound before it, as Vim evaluates defaults left to right.
    crate::ported::eval::vars::funccal_stack.with(|s| {
        s.borrow_mut().push(crate::ported::eval::vars::FuncScope {
            fc_l_vars: crate::ported::eval::typval_defs_h::dict_T::default(),
            fc_l_avars: crate::ported::eval::typval_defs_h::dict_T::default(),
            fc_name: name.to_string(),
        })
    });
    let bind_avar = |key: &str, v: typval_T| {
        crate::ported::eval::vars::funccal_stack.with(|s| {
            if let Some(top) = s.borrow_mut().last_mut() {
                tv_dict_add_tv(&mut top.fc_l_avars, key, v);
            }
        });
    };
    for (i, p) in func.params.iter().take(nfixed).enumerate() {
        let v = if i < args.len() {
            args[i].clone()
        } else if let Some((_, chunk)) = func.defaults.iter().find(|(di, _)| *di == i) {
            // c: an omitted optional argument is its default value (evaluated now,
            // in the partially-bound a: scope); a missing non-optional one is the
            // special "v:none"-like value, as before.
            run_value_chunk(chunk.clone()).unwrap_or_else(tv_special)
        } else {
            tv_special()
        };
        bind_avar(p, v);
    }
    let extra: Vec<typval_T> = if args.len() > nfixed {
        args[nfixed..].to_vec()
    } else {
        Vec::new()
    };
    bind_avar("0", tv_num(extra.len() as varnumber_T));
    bind_avar("000", new_list(extra));

    RETURN_STACK.with(|r| r.borrow_mut().push(None));

    run_chunk_nested(func.chunk.clone());

    let ret = RETURN_STACK.with(|r| r.borrow_mut().pop().flatten());
    crate::ported::eval::vars::funccal_stack.with(|s| {
        s.borrow_mut().pop();
    });
    // c: a function with no :return yields 0.
    Some(ret.unwrap_or_else(|| tv_num(0)))
}

/// Run a chunk on a nested VM **without** resetting the refpool (a user-function
/// call happens mid-outer-run; clearing the refpool would corrupt the outer
/// VM's live compound values). The outer `last_result` is saved and restored.
fn run_chunk_nested(chunk: fusevm::Chunk) {
    let saved = LAST_RESULT.with(|r| r.borrow_mut().take());
    let mut vm = VM::new(chunk);
    install(&mut vm);
    let _ = vm.run();
    LAST_RESULT.with(|r| *r.borrow_mut() = saved);
}

/// Run a chunk compiled with `compile_expr_only` (the value is left on the VM
/// stack, so it comes back as `VMResult::Ok`) and return it as a typval. Used to
/// evaluate optional-parameter default expressions at call time. Refpool-safe.
fn run_value_chunk(chunk: fusevm::Chunk) -> Option<typval_T> {
    let saved = LAST_RESULT.with(|r| r.borrow_mut().take());
    let mut vm = VM::new(chunk);
    install(&mut vm);
    let r = vm.run();
    LAST_RESULT.with(|r2| *r2.borrow_mut() = saved);
    match r {
        fusevm::VMResult::Ok(v) => Some(value_to_tv(&v)),
        _ => None,
    }
}

/// Run a nested chunk and capture its bare-expression result (the per-element
/// expression eval used by `map`/`filter`). Refpool-safe like
/// [`run_chunk_nested`]; restores the outer `last_result`.
fn run_chunk_capture(chunk: fusevm::Chunk) -> Option<typval_T> {
    let saved = LAST_RESULT.with(|r| r.borrow_mut().take());
    let mut vm = VM::new(chunk);
    install(&mut vm);
    let _ = vm.run();
    let result = LAST_RESULT.with(|r| r.borrow_mut().take());
    LAST_RESULT.with(|r| *r.borrow_mut() = saved);
    result
}

/// Compile a single VimL expression string to a runnable chunk (for the
/// `map()`/`filter()` string-expression callback form).
fn compile_expr_chunk(src: &str) -> Result<fusevm::Chunk, VimlError> {
    let e = parse_expr(src)?;
    Ok(crate::compile_viml::compile_program(&[Stmt::Expr(e)])?.main)
}

/// Parse + compile + run VimL source on a nested VM (refpool-safe — used by
/// `execute()`, which runs commands mid-outer-run). Functions defined by the
/// source register globally.
fn run_source_nested(src: &str) -> Result<(), VimlError> {
    let prog = crate::compile_viml::compile_program(&crate::viml_parser::parse_program(src)?)?;
    register_prog_funcs(&mut prog.funcs.into_iter());
    stage_deferred_funcs(prog.deferred_funcs);
    run_chunk_nested(prog.main);
    Ok(())
}

/// Insert a program's top-level `:function` defs into the live registry — done
/// at load, unconditionally (matching Vim's top-level `:function`).
fn register_prog_funcs(funcs: &mut dyn Iterator<Item = crate::compile_viml::UserFuncDef>) {
    FUNCTIONS.with(|f| {
        let mut f = f.borrow_mut();
        for func in funcs {
            f.insert(func.name.clone(), func);
        }
    });
}

/// Stage a program's block-level `:function` defs into the pending registry.
/// They are NOT registered yet — the `VIML_DEFINE_FUNC` op registers each one
/// when its `:function` line actually executes, preserving guard idempotency.
fn stage_deferred_funcs(funcs: Vec<crate::compile_viml::UserFuncDef>) {
    if funcs.is_empty() {
        return;
    }
    PENDING_FUNCS.with(|p| {
        let mut p = p.borrow_mut();
        for func in funcs {
            p.insert(crate::compile_viml::deferred_key(&func), func);
        }
    });
}

fn b_eval(vm: &mut VM, _: u8) -> Value {
    let src = tv_get_string(&pop_tv(vm));
    match compile_expr_chunk(&src) {
        Ok(chunk) => run_chunk_capture(chunk).map_or(Value::Int(0), tv_to_value),
        Err(e) => {
            message::semsg(&format!("{e}"));
            Value::Undef
        }
    }
}

/// The `\=` substitute-expression evaluator (installed into the regex engine's
/// `SUBST_EXPR_HOOK`): compile + run the expression, return its string value.
fn subst_expr_eval(expr: &str) -> String {
    match compile_expr_chunk(expr) {
        Ok(chunk) => run_chunk_capture(chunk)
            .map(|tv| tv_get_string(&tv))
            .unwrap_or_default(),
        Err(_) => String::new(),
    }
}

/// `execute({command} [, {silent}])` — run ex command(s) (a string or a List of
/// strings) and return their captured `:echo`/message output.
fn b_execute(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let cmds: Vec<String> = match (args[0].v_type, &args[0].vval) {
        (VAR_LIST, v_list(Some(l))) => l.borrow().lv_items.iter().map(tv_string_item).collect(),
        _ => vec![tv_get_string(&args[0])],
    };
    // Redirect output into a fresh capture buffer, run, then restore the sink.
    // EXECUTE_DEPTH switches `:echo` to the leading-newline capture convention.
    let saved = ECHO_SINK.with(|s| s.borrow_mut().replace(String::new()));
    EXECUTE_DEPTH.with(|d| d.set(d.get() + 1));
    for cmd in cmds {
        let _ = run_source_nested(&cmd);
    }
    EXECUTE_DEPTH.with(|d| d.set(d.get() - 1));
    let out = ECHO_SINK.with(|s| s.borrow_mut().take().unwrap_or_default());
    ECHO_SINK.with(|s| *s.borrow_mut() = saved);
    tv_to_value(tv_str(out))
}

/// `tv_get_string` of a list item (helper for `execute`'s List form).
fn tv_string_item(it: &listitem_T) -> String {
    tv_get_string(&it.li_tv)
}

/// `assert_fails({cmd} [, {error} [, {msg}]])` — run `{cmd}` and record a
/// failure in `v:errors` if it does NOT error, or if `{error}` is not found in
/// the reported error. `{error}` is a literal substring (String) or a List of
/// up to two regex patterns matched against the first / last reported error.
///
/// Bridge-level (like `execute()`): it must run a command and observe the error
/// machinery — `did_emsg`, the captured error text, and a thrown exception
/// (reported by the nested top level). Spec: `vendor/eval.lua`; the implementation
/// follows Neovim's `testing.c`, which is not part of the vendored eval tree.
/// Appends through the ported `assert_error` (`vendor/eval/vars.c`).
fn b_assert_fails(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let cmd = tv_get_string(&args[0]);
    let opt_msg = args.get(2).filter(|m| m.v_type != VAR_UNKNOWN);
    let prefix = opt_msg
        .map(|m| format!("{}: ", encode_tv2echo(m)))
        .unwrap_or_default();

    // Run the command with errors captured (suppressed) instead of printed.
    // The command under test is *expected* to error, so its errors must not
    // count against the surrounding script — save and restore did_emsg and
    // v:exception around the run (as Vim resets called_emsg / restores
    // v:exception in assert_fails).
    let before = message::did_emsg.with(|d| d.get());
    let saved_exc = V_EXCEPTION.with(|e| e.borrow().clone());
    message::capture_errors_begin();
    let parse_err = run_source_nested(&cmd).err();
    // A throw that unwound to the nested top level is reported + cleared there;
    // clear any residue so it cannot escape into the caller's script.
    PENDING_EXC.with(|p| *p.borrow_mut() = None);
    let mut errs = message::capture_errors_take();
    if let Some(e) = &parse_err {
        errs.insert(0, e.to_string());
    }
    let failed = parse_err.is_some() || message::did_emsg.with(|d| d.get()) > before;
    message::did_emsg.with(|d| d.set(before));
    set_vim_var_string(VV_EXCEPTION, &saved_exc);
    V_EXCEPTION.with(|e| *e.borrow_mut() = saved_exc);

    if !failed {
        set_var_errors(&format!("{prefix}command did not fail: {cmd}"));
        return Value::Int(1);
    }

    // Match {error} against the reported error(s), if given.
    if let Some(want) = args.get(1).filter(|w| w.v_type != VAR_UNKNOWN) {
        let first = errs.first().cloned().unwrap_or_default();
        let last = errs.last().cloned().unwrap_or_default();
        let ok = match (want.v_type, &want.vval) {
            (VAR_LIST, v_list(Some(l))) => {
                let items = &l.borrow().lv_items;
                let pat0 = items
                    .first()
                    .map(|it| tv_get_string(&it.li_tv))
                    .unwrap_or_default();
                let m0 = pat0.is_empty() || crate::viml_regex::regex_match(&pat0, &first, false);
                let m1 = match items.get(1) {
                    Some(it) => {
                        crate::viml_regex::regex_match(&tv_get_string(&it.li_tv), &last, false)
                    }
                    None => true,
                };
                m0 && m1
            }
            _ => first.contains(&tv_get_string(want)),
        };
        if !ok {
            set_var_errors(&format!(
                "{prefix}Expected {} but got '{first}'",
                encode_tv2string(want)
            ));
            return Value::Int(1);
        }
    }
    Value::Int(0)
}

/// Append a message to `v:errors` (thin wrapper over the ported `assert_error`).
fn set_var_errors(msg: &str) {
    crate::ported::eval::vars::assert_error(msg);
}

/// Run `{cmd}` (errors captured) and report whether it "rang the bell": an Ex
/// command that errors triggers a beep in Vim, so a reported error (parse error
/// or a raised `emsg`) models the beep. Shared by `assert_beeps()`/
/// `assert_nobeep()`. Restores `did_emsg`/`v:exception` around the run.
fn assert_beeps_run(cmd: &str) -> bool {
    let before = message::did_emsg.with(|d| d.get());
    let saved_exc = V_EXCEPTION.with(|e| e.borrow().clone());
    message::capture_errors_begin();
    let parse_err = run_source_nested(cmd).err();
    PENDING_EXC.with(|p| *p.borrow_mut() = None);
    let _ = message::capture_errors_take();
    let beeped = parse_err.is_some() || message::did_emsg.with(|d| d.get()) > before;
    message::did_emsg.with(|d| d.set(before));
    set_vim_var_string(VV_EXCEPTION, &saved_exc);
    V_EXCEPTION.with(|e| *e.borrow_mut() = saved_exc);
    beeped
}

/// `assert_beeps({cmd})` — run `{cmd}` and record a failure in `v:errors` if it
/// does NOT cause a beep. Bridge-level (runs a command, like `assert_fails()`);
/// spec in `vendor/eval.lua`, implementation follows Neovim's testing.c.
fn b_assert_beeps(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let cmd = tv_get_string(&args[0]);
    if assert_beeps_run(&cmd) {
        Value::Int(0)
    } else {
        set_var_errors(&format!("command did not beep: {cmd}"));
        Value::Int(1)
    }
}

/// `assert_nobeep({cmd})` — run `{cmd}` and record a failure in `v:errors` if it
/// DOES cause a beep. The complement of `assert_beeps()`.
fn b_assert_nobeep(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let cmd = tv_get_string(&args[0]);
    if assert_beeps_run(&cmd) {
        set_var_errors(&format!("command did beep: {cmd}"));
        Value::Int(1)
    } else {
        Value::Int(0)
    }
}

/// Evaluate a `map`/`filter` callback for one element: either a string
/// expression (with `v:val`/`v:key` bound) or a funcref called as `f(key, val)`.
fn eval_callback(
    callback: &typval_T,
    chunk: &Option<fusevm::Chunk>,
    key: &typval_T,
    val: &typval_T,
) -> typval_T {
    V_VAL.with(|v| *v.borrow_mut() = Some(val.clone()));
    V_KEY.with(|v| *v.borrow_mut() = Some(key.clone()));
    match callback.v_type {
        VAR_FUNC | VAR_PARTIAL => {
            call_funcref(callback, vec![key.clone(), val.clone()]).unwrap_or_else(|| tv_num(0))
        }
        _ => chunk
            .as_ref()
            .and_then(|c| run_chunk_capture(c.clone()))
            .unwrap_or_else(|| tv_num(0)),
    }
}

// map()/filter()/mapnew()/foreach() are ported faithfully in
// `src/ported/eval/list.rs`; the per-item evaluation comes back here through the
// `FILTER_MAP_EVAL_HOOK`/`FILTER_MAP_CMD_HOOK` (installed in `install()`).

// `reduce()` is ported faithfully in `src/ported/eval/funcs.rs` (uses CALL_FUNC_HOOK).

/// The `sort()`/`uniq()` `{func}` comparator hook (installed into the value
/// layer's `SORT_FUNCREF_HOOK`): call the user function with the two items and
/// read its result as a Number. `None` signals a call/type error.
fn sort_compare_funcref(name: &str, a: &typval_T, b: &typval_T) -> Option<varnumber_T> {
    let r = call_user_function(name, vec![a.clone(), b.clone()])?;
    Some(tv_get_number_chk(&r, None))
}

/// The "evaluate an expression string" hook (installed into `EVAL_STRING_HOOK`),
/// used by the ported `eval_to_*`/`eval_expr_*` entry points: compile the
/// expression on a nested VM and capture its result.
fn eval_string_hook(expr: &str) -> Option<typval_T> {
    let chunk = compile_expr_chunk(expr).ok()?;
    run_chunk_capture(chunk)
}

/// The user-function lookup hook (installed into `FIND_FUNC_HOOK`): map a
/// registered `UserFuncDef` to the ported reduced `ufunc_T` (name + arity).
fn find_func_hook(name: &str) -> Option<crate::ported::eval::userfunc::ufunc_T> {
    let def = FUNCTIONS.with(|f| f.borrow().get(name).cloned())?;
    let nfixed = def
        .params
        .iter()
        .position(|p| p == "...")
        .unwrap_or(def.params.len());
    Some(crate::ported::eval::userfunc::ufunc_T {
        uf_name: def.name.clone(),
        uf_args: def.params[..nfixed].to_vec(),
        uf_def_args: def
            .defaults
            .iter()
            .map(|(i, _)| def.params[*i].clone())
            .collect(),
        uf_varargs: def.params.iter().any(|p| p == "..."),
        ..Default::default()
    })
}

/// The user-function removal hook (installed into `REMOVE_FUNC_HOOK`): drop a
/// function from the registry, reporting whether it was present.
fn remove_func_hook(name: &str) -> bool {
    FUNCTIONS.with(|f| f.borrow_mut().remove(name).is_some())
}

/// The generic "call user function" hook (installed into `CALL_FUNC_HOOK`), used
/// by `reduce()`.
fn call_func_hook(funcref: &typval_T, args: &[typval_T]) -> Option<typval_T> {
    call_funcref(funcref, args.to_vec())
}

/// The map()/filter()/foreach() per-item evaluator hook (installed into the
/// value layer's `FILTER_MAP_EVAL_HOOK`): set v:key/v:val and evaluate the expr
/// (string) or call the funcref → result.
fn filter_map_eval(expr: &typval_T, key: &typval_T, val: &typval_T) -> Option<typval_T> {
    let chunk = if expr.v_type == VAR_STRING {
        match compile_expr_chunk(&tv_get_string(expr)) {
            Ok(c) => Some(c),
            Err(_) => return None,
        }
    } else {
        None
    };
    Some(eval_callback(expr, &chunk, key, val))
}

/// The foreach() command hook (`do_cmdline_cmd`): set v:key/v:val and run the
/// string as a command line.
fn filter_map_cmd(cmd: &str, key: &typval_T, val: &typval_T) -> bool {
    V_VAL.with(|v| *v.borrow_mut() = Some(val.clone()));
    V_KEY.with(|v| *v.borrow_mut() = Some(key.clone()));
    run_source_nested(cmd).is_ok()
}

/// Call a Funcref/Partial typval with `extra` args. A Partial prepends its bound
/// `pt_argv` (its `self` dict is not modeled).
fn call_funcref(funcref: &typval_T, extra: Vec<typval_T>) -> Option<typval_T> {
    match (funcref.v_type, &funcref.vval) {
        (VAR_PARTIAL, v_partial(Some(p))) => {
            let mut args = p.pt_argv.clone();
            args.extend(extra);
            call_named(&p.pt_name, args)
        }
        _ => call_named(&tv_get_string(funcref), extra),
    }
}

/// `exists("*name")` — true if `name` is a defined user function or a ported
/// builtin. Installed into `FUNC_EXISTS_HOOK` for `f_exists`. A leading `g:`
/// scope prefix on the function name is ignored, as in Vim.
fn func_exists_hook(name: &str) -> bool {
    let name = name.strip_prefix("g:").unwrap_or(name);
    FUNCTIONS.with(|f| f.borrow().contains_key(name))
        || crate::compile_viml::builtin_fn_id(name).is_some()
}

/// `VIML_DEFINE_FUNC` — register a deferred (block-level) `:function` when its
/// line executes. The compiler emits this for a `:function` inside a script-level
/// `:if`/`:while`/`:for`/`:try` block: the def was staged into `PENDING_FUNCS`
/// at load, and this op moves it into the live `FUNCTIONS` registry only now,
/// when control flow actually reached the definition. That is what makes the
/// idempotent `if !exists('*F') | function F() … | endif` guard define `F` on
/// the first source and skip it thereafter. Registration overwrites an existing
/// entry, matching the top-level `:function` path (which also inserts
/// unconditionally). Returns a dummy the compiler immediately pops.
fn b_define_func(vm: &mut VM, _argc: u8) -> Value {
    let key = tv_get_string(&pop_tv(vm));
    if let Some(def) = PENDING_FUNCS.with(|p| p.borrow().get(&key).cloned()) {
        FUNCTIONS.with(|f| f.borrow_mut().insert(def.name.clone(), def));
    }
    Value::Int(0)
}

/// Resolve a function name to either a user `:function` or a ported builtin and
/// call it. Vim's `call()`/funcrefs accept builtin names (`call('printf', […])`,
/// `function('substitute')`), not just user functions — a user function takes
/// precedence when both exist.
fn call_named(name: &str, args: Vec<typval_T>) -> Option<typval_T> {
    if FUNCTIONS.with(|f| f.borrow().contains_key(name)) {
        return call_user_function(name, args);
    }
    if crate::compile_viml::builtin_fn_id(name).is_some() {
        return call_builtin_by_name(name, args);
    }
    // Neither yet — fall back to the user-function path (handles autoload-loaded
    // names registered after the initial check).
    call_user_function(name, args)
}

/// Invoke a ported builtin by name with already-evaluated argument typvals.
/// Builds a one-instruction `CallBuiltin` chunk, pushes the args onto a fresh
/// VM, and runs it — reusing every registered handler. The REFPOOL is a shared
/// thread_local, so converting compound args across the nested VM is safe.
fn call_builtin_by_name(name: &str, args: Vec<typval_T>) -> Option<typval_T> {
    let id = crate::compile_viml::builtin_fn_id(name)?;
    // Vim validates arg counts before dispatch; the direct-call path checks at
    // compile time, but `call()`/funcref invocation arrives here at runtime, so
    // re-check to keep a short arg slice from panicking inside the leaf f_*.
    if let Some(msg) = crate::compile_viml::builtin_argc_error(name, args.len()) {
        message::semsg(&msg);
        return None;
    }
    let argc = args.len() as u8;
    let mut b = fusevm::ChunkBuilder::new();
    b.emit(fusevm::Op::CallBuiltin(id, argc), 0);
    let mut vm = VM::new(b.build());
    install(&mut vm);
    for a in args {
        vm.push(tv_to_value(a));
    }
    // `run()` returns the top-of-stack as its result (it does not leave it on the
    // stack), so read the builtin's value from there.
    match vm.run() {
        fusevm::VMResult::Ok(v) => Some(value_to_tv(&v)),
        _ => None,
    }
}

fn b_call(vm: &mut VM, argc: u8) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    // The arg list is the second argument (a List).
    let call_args: Vec<typval_T> = match args.get(1).map(|a| (a.v_type, &a.vval)) {
        Some((VAR_LIST, v_list(Some(l)))) => l
            .borrow()
            .lv_items
            .iter()
            .map(|it| it.li_tv.clone())
            .collect(),
        _ => Vec::new(),
    };
    match call_funcref(&args[0], call_args) {
        Some(rettv) => tv_to_value(rettv),
        None => {
            message::semsg(&format!(
                "E117: Unknown function: {}",
                tv_get_string(&args[0])
            ));
            Value::Undef
        }
    }
}

fn b_getopt(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    // The option name may carry a `&l:`/`&g:` scope prefix; strip it.
    let name = name
        .strip_prefix("l:")
        .or_else(|| name.strip_prefix("g:"))
        .unwrap_or(&name);
    tv_to_value(crate::ported::option::get_option_value(name))
}

fn b_set(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    crate::ported::option::do_set(&args);
    Value::Undef
}

/// `:let &opt = value` — apply via `option::do_set` as `name=value`.
fn b_setopt(vm: &mut VM, _: u8) -> Value {
    let val = tv_get_string(&pop_tv(vm));
    let name = tv_get_string(&pop_tv(vm));
    crate::ported::option::do_set(&format!("{name}={val}"));
    Value::Undef
}

/// `:map`-family statement: pop the raw command line, split off its command
/// word, and apply via the ported `get_map_mode()` + `do_map()`.
fn b_map(vm: &mut VM, _: u8) -> Value {
    let line = tv_get_string(&pop_tv(vm));
    let line = line.trim();
    // The command word is the leading run of letters plus an optional `!`.
    let alpha_end = line
        .find(|c: char| !c.is_ascii_alphabetic())
        .unwrap_or(line.len());
    let cmd_end = if line[alpha_end..].starts_with('!') {
        alpha_end + 1
    } else {
        alpha_end
    };
    let cmd = &line[..cmd_end];
    let rest = &line[cmd_end..];
    if let Some((mode, unmap, clear, noremap)) = crate::ported::eval::funcs::get_map_mode(cmd) {
        // Keep vimlrs' own mapping table in sync (so `maparg()`/`hasmapto()` work)…
        crate::ported::eval::funcs::do_map(rest, mode, unmap, clear, noremap);
        // …then mirror the whole command onto the host editor's live keymap.
        MAP_HOST_HOOK.with(|h| {
            if let Some(f) = h.borrow().as_ref() {
                f(line);
            }
        });
    }
    Value::Undef
}

/// `:command` statement: pop the argument text, define a user command.
fn b_command(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    crate::ported::eval::funcs::ex_command(&args);
    Value::Undef
}

/// `:delcommand` statement: pop the name, delete the user command.
fn b_delcommand(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    crate::ported::eval::funcs::ex_delcommand(&name);
    Value::Undef
}

/// `:autocmd` statement: pop the args, register the autocommand.
fn b_autocmd(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    crate::ported::eval::funcs::do_autocmd(&args);
    Value::Undef
}

/// `:augroup` statement: pop the name, set the active autocommand group.
fn b_augroup(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    crate::ported::eval::funcs::do_augroup(&name);
    Value::Undef
}

/// `:doautocmd` statement: pop the args, run every matching autocommand.
fn b_doautocmd(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    for cmd in crate::ported::eval::funcs::do_doautocmd(&args) {
        let _ = run_source_nested(&cmd);
    }
    Value::Undef
}

/// Run one Ex command against the buffer; an unrecognized command (or a
/// `:global` sub-command that isn't an Ex command) runs as an ordinary
/// statement. Used by `b_excmd` and for each `:global`-matched line.
fn exec_ex_or_stmt(line: &str) {
    use crate::ported::eval::funcs::{do_excmd, ExCmdResult};
    match do_excmd(line) {
        ExCmdResult::Handled => {}
        ExCmdResult::NotEx => {
            // Strip a leading ':' so `:echo …` runs as the `echo` statement.
            let stmt = line.trim().strip_prefix(':').unwrap_or(line.trim());
            let _ = run_source_nested(stmt);
        }
        ExCmdResult::Global(mut lines, cmd) => {
            // Run `cmd` on each matched line, highest first so deletions above
            // don't shift the lines still to process.
            lines.sort_unstable();
            for lnum in lines.into_iter().rev() {
                crate::ported::eval::funcs::set_cursorpos(lnum, 1);
                exec_ex_or_stmt(&cmd);
            }
        }
    }
}

/// `:[range]cmd` statement: pop the raw line and run it against the buffer.
fn b_excmd(vm: &mut VM, _: u8) -> Value {
    let line = tv_get_string(&pop_tv(vm));
    exec_ex_or_stmt(&line);
    Value::Undef
}

/// `:colorscheme {name}` statement. Sets `g:colors_name`, sources the matching
/// `colors/{name}.vim` from the runtime path (which fires its `:highlight`
/// commands, populating the registry + firing the highlight host hook), then
/// fires the colorscheme host hook so an embedding editor can apply its theme.
/// A bare `:colorscheme` (no name) is a query — echo the current scheme.
fn b_colorscheme(vm: &mut VM, _: u8) -> Value {
    let name = tv_get_string(&pop_tv(vm));
    let name = name.trim();
    if name.is_empty() {
        // Query: echo the active scheme (blank if none), matching Vim.
        let cur = crate::ported::eval::vars::get_var_value("g:colors_name").unwrap_or_default();
        echo_write(&format!("{cur}\n"));
        return Value::Undef;
    }
    // Record the active scheme name (Vim sets this before sourcing).
    crate::ported::eval::vars::set_var(
        "g:colors_name",
        "g:colors_name".len(),
        tv_str(name.to_string()),
        false,
    );
    // Source colors/{name}.vim if we can find it — this runs the `:highlight`
    // commands that define the scheme.
    if let Some(path) = resolve_colorscheme(name) {
        if let Ok(src) = std::fs::read_to_string(&path) {
            let sname = std::fs::canonicalize(&path)
                .map(|p| p.display().to_string())
                .unwrap_or_else(|_| path.display().to_string());
            crate::ported::eval::fs::push_sourcing_name(sname);
            // Source the scheme statement-by-statement: real colour schemes often
            // contain a construct that errors at parse OR run time, and a single
            // aborted chunk would drop every `:highlight` after it — including the
            // core `Normal` group. Per-statement sourcing keeps the groups that do
            // work (mirrors Vim continuing after an error while sourcing).
            source_tolerant(&src);
            crate::ported::eval::fs::pop_sourcing_name();
        }
    }
    // Tell the host to (re)build + apply its theme from what was just defined.
    COLORSCHEME_HOST_HOOK.with(|h| {
        if let Some(f) = h.borrow().as_ref() {
            f(name);
        }
    });
    Value::Undef
}

/// `:highlight {args}` statement. Applies the definition to the highlight
/// registry (so `hlexists()`/`hlID()`/`synIDattr()` see it) and mirrors the raw
/// args to the highlight host hook so an embedding editor can map it onto its
/// theme. A bare `:highlight` / `:highlight {group}` listing query is a no-op.
fn b_highlight(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    if let Some(group) = crate::ported::eval::funcs::hl_define_from_args(&args) {
        let _ = group;
        HIGHLIGHT_HOST_HOOK.with(|h| {
            if let Some(f) = h.borrow().as_ref() {
                f(args.trim());
            }
        });
    }
    Value::Undef
}

/// `:syntax {args}` statement. Standalone this is a no-op (there is no live
/// highlighter); the raw args are forwarded to the syntax host hook so an
/// embedding editor may act on `syntax on`/`off`/`enable`.
fn b_syntax(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    SYNTAX_HOST_HOOK.with(|h| {
        if let Some(f) = h.borrow().as_ref() {
            f(args.trim());
        }
    });
    Value::Undef
}

/// `:filetype {args}` statement. Standalone no-op; forwarded to the filetype
/// host hook so an embedding editor may act on `filetype plugin indent on` etc.
fn b_filetype(vm: &mut VM, _: u8) -> Value {
    let args = tv_get_string(&pop_tv(vm));
    FILETYPE_HOST_HOOK.with(|h| {
        if let Some(f) = h.borrow().as_ref() {
            f(args.trim());
        }
    });
    Value::Undef
}

/// User-command invocation: pop the raw line (`Name[!] args`), expand the
/// command's replacement and run it; error E492 if there is no such command.
fn b_usercmd(vm: &mut VM, _: u8) -> Value {
    let line = tv_get_string(&pop_tv(vm));
    let line = line.trim();
    let alpha_end = line
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .unwrap_or(line.len());
    let bang = line[alpha_end..].starts_with('!');
    let name = &line[..alpha_end];
    let args_start = alpha_end + if bang { 1 } else { 0 };
    let args = line[args_start..].trim();
    match crate::ported::eval::funcs::do_ucmd(name, args, bang) {
        Some(expanded) => {
            let _ = run_source_nested(&expanded);
        }
        None => message::semsg(&format!("E492: Not an editor command: {name}")),
    }
    Value::Undef
}

/// Dispatch a Phase-3 builtin function: pop `argc` args, call the ported
/// `f_<name>` with a pre-initialized `VAR_NUMBER` rettv, push the result.
fn call_func(vm: &mut VM, argc: u8, f: fn(&[typval_T], &mut typval_T)) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    // c: call_func pre-initializes rettv to VAR_NUMBER / 0.
    let mut rettv = tv_num(0);
    f(&args, &mut rettv);
    tv_to_value(rettv)
}

/// Dispatch a single-argument float builtin (`sqrt`/`floor`/`sin`/…) through the
/// real `float_op_wrapper` with the C `func_float` (here a Rust `fn(f64)->f64`).
/// Mirrors Neovim's eval.lua `func_float` routing — there is no `f_sqrt` etc.
fn call_float_op(vm: &mut VM, argc: u8, op: fn(f64) -> f64) -> Value {
    let mut args = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        args.push(pop_tv(vm));
    }
    args.reverse();
    let mut rettv = tv_num(0);
    float_op_wrapper(&args, &mut rettv, op);
    tv_to_value(rettv)
}

fn b_fn_len(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_len)
}
fn b_fn_type(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_type)
}
fn b_fn_string(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_string)
}
fn b_fn_empty(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_empty)
}
fn b_fn_abs(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_abs)
}
fn b_fn_str2nr(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_str2nr)
}
fn b_fn_str2float(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_str2float)
}
fn b_fn_float2nr(vm: &mut VM, argc: u8) -> Value {
    call_func(vm, argc, f_float2nr)
}

// ── helpers reconstructing tree-walker logic (cite eval.c) ──

/// Build a `VAR_LIST` typval from items (the `eval_list` result shape).
fn new_list(items: Vec<typval_T>) -> typval_T {
    let l = tv_list_alloc(items.len() as isize);
    {
        let mut lb = l.borrow_mut();
        for it in items {
            tv_list_append_tv(&mut lb, it);
        }
    }
    typval_T {
        v_type: VAR_LIST,
        v_lock: VAR_UNLOCKED,
        vval: v_list(Some(l)),
    }
}

/// `eval5` List `+` List concatenation — a new list of both items' values.
fn list_concat(a: &typval_T, b: &typval_T) -> typval_T {
    let mut items = Vec::new();
    if let v_list(Some(la)) = &a.vval {
        items.extend(la.borrow().lv_items.iter().map(|it| it.li_tv.clone()));
    }
    if let v_list(Some(lb)) = &b.vval {
        items.extend(lb.borrow().lv_items.iter().map(|it| it.li_tv.clone()));
    }
    new_list(items)
}

/// `eval5` Blob `+` Blob concatenation.
fn blob_concat(a: &typval_T, b: &typval_T) -> typval_T {
    let mut data = Vec::new();
    if let v_blob(Some(ba)) = &a.vval {
        data.extend_from_slice(&ba.borrow().bv_ga);
    }
    if let v_blob(Some(bb)) = &b.vval {
        data.extend_from_slice(&bb.borrow().bv_ga);
    }
    let blob = std::rc::Rc::new(RefCell::new(blob_T {
        bv_ga: data,
        ..Default::default()
    }));
    typval_T {
        v_type: VAR_BLOB,
        v_lock: VAR_UNLOCKED,
        vval: v_blob(Some(blob)),
    }
}

/// `eval_index` subscript (`eval.c`) — Phase-3 String/List/Dict subset.
fn index_value(base: &typval_T, index: &typval_T) -> typval_T {
    match (base.v_type, &base.vval) {
        (VAR_LIST, v_list(Some(l))) => {
            // Faithful single-index via the ported value layer.
            let i = tv_get_number_chk(index, None);
            let mut rettv = base.clone();
            if tv_list_slice_or_index(l, false, i, 0, false, &mut rettv, true) == 0 {
                tv_special()
            } else {
                rettv
            }
        }
        (VAR_DICT, v_dict(Some(d))) => {
            let key = tv_get_string(index);
            match crate::ported::eval::typval::tv_dict_find(&d.borrow(), &key) {
                Some(v) => v.clone(),
                None => {
                    message::semsg(&format!("E716: Key not present in Dictionary: {key}"));
                    tv_special()
                }
            }
        }
        (VAR_STRING, v_string(s)) => {
            let chars: Vec<char> = s.chars().collect();
            let len = chars.len() as varnumber_T;
            let mut i = tv_get_number_chk(index, None);
            if i < 0 {
                i += len;
            }
            if i < 0 || i >= len {
                tv_str(String::new())
            } else {
                tv_str(chars[i as usize].to_string())
            }
        }
        (VAR_BLOB, v_blob(Some(b))) => {
            // Blob subscript → a single byte (Number), via the ported value layer.
            let i = tv_get_number_chk(index, None);
            let mut rettv = base.clone();
            let _ = crate::ported::eval::typval::tv_blob_slice_or_index(
                &b.borrow(),
                false,
                i,
                0,
                false,
                &mut rettv,
            );
            rettv
        }
        _ => {
            message::emsg("E909: Cannot index this type");
            tv_special()
        }
    }
}

/// `eval_index` slice branch (`eval.c`) — Phase-3 String/List subset.
fn slice_value(base: &typval_T, from: &typval_T, to: &typval_T) -> typval_T {
    let lower = |len: varnumber_T, t: &typval_T| -> varnumber_T {
        if t.v_type == VAR_SPECIAL {
            0
        } else {
            let mut i = tv_get_number_chk(t, None);
            if i < 0 {
                i += len;
            }
            i.max(0)
        }
    };
    let upper = |len: varnumber_T, t: &typval_T| -> varnumber_T {
        if t.v_type == VAR_SPECIAL {
            len - 1
        } else {
            let mut i = tv_get_number_chk(t, None);
            if i < 0 {
                i += len;
            }
            i.min(len - 1)
        }
    };
    match (base.v_type, &base.vval) {
        (VAR_LIST, v_list(Some(l))) => {
            // Faithful list slice via the ported value layer (inclusive bounds;
            // an omitted bound is the whole-start/whole-end default).
            let len = l.borrow().lv_len as varnumber_T;
            let n1 = if from.v_type == VAR_SPECIAL {
                0
            } else {
                tv_get_number_chk(from, None)
            };
            let n2 = if to.v_type == VAR_SPECIAL {
                len - 1
            } else {
                tv_get_number_chk(to, None)
            };
            let mut rettv = base.clone();
            let _ = tv_list_slice_or_index(l, true, n1, n2, false, &mut rettv, true);
            rettv
        }
        (VAR_STRING, v_string(s)) => {
            let chars: Vec<char> = s.chars().collect();
            let len = chars.len() as varnumber_T;
            let (lo, hi) = (lower(len, from), upper(len, to));
            if lo > hi || len == 0 {
                tv_str(String::new())
            } else {
                tv_str(
                    chars[lo as usize..=(hi as usize).min(chars.len() - 1)]
                        .iter()
                        .collect(),
                )
            }
        }
        (VAR_BLOB, v_blob(Some(b))) => {
            // Blob slice → a sub-blob, via the ported value layer (inclusive
            // bounds; an omitted bound is the whole-end default).
            let len = crate::ported::eval::typval::tv_blob_len(&b.borrow()) as varnumber_T;
            let n1 = if from.v_type == VAR_SPECIAL {
                0
            } else {
                tv_get_number_chk(from, None)
            };
            let n2 = if to.v_type == VAR_SPECIAL {
                len - 1
            } else {
                tv_get_number_chk(to, None)
            };
            let mut rettv = base.clone();
            let _ = crate::ported::eval::typval::tv_blob_slice_or_index(
                &b.borrow(),
                true,
                n1,
                n2,
                false,
                &mut rettv,
            );
            rettv
        }
        _ => {
            message::emsg("E909: Cannot slice this type");
            tv_special()
        }
    }
}

// ── echo sink + per-run lifecycle (carve-out) ──

fn echo_write(s: &str) {
    ECHO_SINK.with(|sink| {
        let mut sink = sink.borrow_mut();
        match sink.as_mut() {
            Some(buf) => buf.push_str(s),
            None => {
                use std::io::Write;
                let out = std::io::stdout();
                let _ = out.lock().write_all(s.as_bytes());
            }
        }
    });
}

/// Begin capturing `:echo` output into a buffer (tests / embedding).
pub fn capture_begin() {
    ECHO_SINK.with(|s| *s.borrow_mut() = Some(String::new()));
}

/// Take and clear the captured echo buffer, restoring stdout output.
pub fn capture_take() -> String {
    ECHO_SINK.with(|s| s.borrow_mut().take().unwrap_or_default())
}

/// Drain the captured echo buffer **without** disabling capture (the debugger
/// streams output progressively as DAP `output` events at each pause).
pub fn capture_drain() -> String {
    ECHO_SINK.with(|s| {
        let mut s = s.borrow_mut();
        match s.as_mut() {
            Some(buf) => std::mem::take(buf),
            None => String::new(),
        }
    })
}

/// Take the last bare-expression result.
pub fn take_last_result() -> Option<typval_T> {
    LAST_RESULT.with(|r| r.borrow_mut().take())
}

/// Reset per-run state (refpool, last result, `did_emsg`).
pub fn reset_run() {
    REFPOOL.with(|p| p.borrow_mut().clear());
    LAST_RESULT.with(|r| *r.borrow_mut() = None);
    PENDING_EXC.with(|p| *p.borrow_mut() = None);
    V_EXCEPTION.with(|e| e.borrow_mut().clear());
    message::did_emsg.with(|d| d.set(0));
}

/// Install a host callback invoked with the raw `:set` args (e.g. `"nu tw=80"`)
/// on every `:set`, so an embedding editor can mirror the option onto its live
/// config. EXTENSION seam — the net-new installer for the ported
/// [`crate::ported::option::SET_HOST_HOOK`] slot (net-new synthesis lives here,
/// not under `src/ported/`).
pub fn install_set_hook(f: Box<dyn Fn(&str)>) {
    crate::ported::option::SET_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

thread_local! {
    /// Host hook fired with the full raw `:map`-family command line (e.g.
    /// `"nnoremap <leader>x :Foo<CR>"`) whenever one runs, so an embedding editor
    /// can mirror the mapping onto its own live keymap. EXTENSION — no `vendor/`
    /// counterpart; a bridge seam living in the carve-out, not `src/ported/`.
    /// Installed via [`install_map_hook`]; unset by default (no-op).
    #[allow(clippy::type_complexity)]
    static MAP_HOST_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
}

/// Install a host callback invoked with the raw `:map`-family command line on
/// every `:map`/`:nmap`/`:nnoremap`/… (and `:unmap`/`:mapclear`), so an
/// embedding editor can apply the mapping to its real keymap.
pub fn install_map_hook(f: Box<dyn Fn(&str)>) {
    MAP_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

// ── COLORSCHEME / HIGHLIGHT / SYNTAX / FILETYPE HOST HOOKS ────────────────────
//
// EXTENSION — no `vendor/` counterpart. A vimrc that runs `:colorscheme molokai`
// selects a scheme; Vim then sources `colors/molokai.vim` from the runtime path,
// which issues the `:highlight` commands that paint every group. vimlrs sources
// that file itself (via [`b_colorscheme`], firing each `:highlight` through the
// registry + the highlight host hook), so an embedding editor (zemacs) can
// translate the vim highlight groups into its own theme and apply it.

thread_local! {
    /// Extra directories (highest priority first) searched for `colors/{name}.vim`
    /// in addition to the default Vim runtime dirs. A host prepends its own theme
    /// directory here so bundled schemes resolve.
    static COLORSCHEME_DIRS: RefCell<Vec<std::path::PathBuf>> = const { RefCell::new(Vec::new()) };
    /// Fired with the color-scheme name AFTER `colors/{name}.vim` has been sourced,
    /// so the host can rebuild + apply its theme from the highlights just defined.
    #[allow(clippy::type_complexity)]
    static COLORSCHEME_HOST_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
    /// Fired with each `:highlight` command's raw argument text (e.g.
    /// `"Normal ctermfg=252 guifg=#d0d0d0 guibg=#1c1c1c"`) as it runs.
    #[allow(clippy::type_complexity)]
    static HIGHLIGHT_HOST_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
    /// Fired with each `:syntax` command's raw argument text (`"on"`, `"off"`, …).
    #[allow(clippy::type_complexity)]
    static SYNTAX_HOST_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
    /// Fired with each `:filetype` command's raw argument text (`"plugin indent on"`).
    #[allow(clippy::type_complexity)]
    static FILETYPE_HOST_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
}

// Re-export the highlight-registry readers so an embedding editor can snapshot
// the groups a sourced colorscheme/vimrc defined (see `install_colorscheme_hook`).
pub use crate::ported::eval::funcs::{hl_names, hl_resolved, ResolvedHl};

/// Prepend a directory searched (before the default Vim runtime dirs) for
/// `colors/{name}.vim` when `:colorscheme {name}` runs.
pub fn add_colorscheme_dir(dir: std::path::PathBuf) {
    COLORSCHEME_DIRS.with(|d| d.borrow_mut().insert(0, dir));
}

/// Install a host callback fired with the scheme name once `:colorscheme` has
/// sourced its `colors/{name}.vim`.
pub fn install_colorscheme_hook(f: Box<dyn Fn(&str)>) {
    COLORSCHEME_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

/// Install a host callback fired with each `:highlight` command's raw args.
pub fn install_highlight_hook(f: Box<dyn Fn(&str)>) {
    HIGHLIGHT_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

/// Install a host callback fired with each `:syntax` command's raw args.
pub fn install_syntax_hook(f: Box<dyn Fn(&str)>) {
    SYNTAX_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

/// Install a host callback fired with each `:filetype` command's raw args.
pub fn install_filetype_hook(f: Box<dyn Fn(&str)>) {
    FILETYPE_HOST_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

/// Resolve `colors/{name}.vim` across the host-registered dirs, the user's Vim /
/// Neovim config trees (including plugin managers: native `pack/*`, pathogen
/// `bundle/*`, vim-plug/dein `plugged/*`), and the installed Vim runtime
/// (`$VIMRUNTIME` or a discovered system Vim, so built-in schemes like `desert`
/// resolve even when `$VIMRUNTIME` is unset). Returns the first existing file.
fn resolve_colorscheme(name: &str) -> Option<std::path::PathBuf> {
    let rel = format!("colors/{name}.vim");
    let mut roots: Vec<std::path::PathBuf> = COLORSCHEME_DIRS.with(|d| d.borrow().clone());
    if let Ok(home) = std::env::var("HOME") {
        let home = std::path::PathBuf::from(home);
        roots.push(home.join(".vim"));
        roots.push(home.join(".config/nvim"));
        roots.push(home.join(".local/share/nvim/site"));
    }
    if let Ok(rt) = std::env::var("VIMRUNTIME") {
        roots.push(std::path::PathBuf::from(rt));
    }
    roots.extend(system_vim_runtime_dirs());

    // Direct `{root}/colors/{name}.vim`.
    for root in &roots {
        let p = root.join(&rel);
        if p.is_file() {
            return Some(p);
        }
    }
    // Plugin managers: a scheme lives under `{root}/{layout}/*/colors/{name}.vim`
    // — native packages (`pack/*/start`, `pack/*/opt`), pathogen (`bundle`), and
    // vim-plug/dein (`plugged`).
    for root in &roots {
        // `pack/*/{start,opt}/*/colors/…`
        if let Ok(vendors) = std::fs::read_dir(root.join("pack")) {
            for vendor in vendors.flatten() {
                for kind in ["start", "opt"] {
                    if let Some(p) = first_child_with(&vendor.path().join(kind), &rel) {
                        return Some(p);
                    }
                }
            }
        }
        // `bundle/*/colors/…` (pathogen) and `plugged/*/colors/…` (vim-plug/dein).
        for layout in ["bundle", "plugged"] {
            if let Some(p) = first_child_with(&root.join(layout), &rel) {
                return Some(p);
            }
        }
    }
    None
}

/// Search each immediate subdirectory of `dir` for `rel`, returning the first
/// existing `{dir}/{child}/{rel}`.
fn first_child_with(dir: &std::path::Path, rel: &str) -> Option<std::path::PathBuf> {
    let entries = std::fs::read_dir(dir).ok()?;
    for child in entries.flatten() {
        let p = child.path().join(rel);
        if p.is_file() {
            return Some(p);
        }
    }
    None
}

/// Discover installed Vim runtime `colors/` roots when `$VIMRUNTIME` is unset
/// (it is normally exported only by a running Vim). Globs the standard install
/// prefixes for `vim{NN}/` and matching Neovim runtimes.
fn system_vim_runtime_dirs() -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    let prefixes = [
        "/usr/share/vim",
        "/usr/local/share/vim",
        "/opt/homebrew/share/vim",
        "/opt/local/share/vim",
        "/usr/share/nvim/runtime",
        "/usr/local/share/nvim/runtime",
        "/opt/homebrew/share/nvim/runtime",
    ];
    for prefix in prefixes {
        let path = std::path::Path::new(prefix);
        // Neovim runtime dirs already point at the runtime root.
        if path.join("colors").is_dir() {
            out.push(path.to_path_buf());
        }
        // Vim install prefixes contain a versioned `vimNN/` runtime dir.
        if let Ok(entries) = std::fs::read_dir(path) {
            for e in entries.flatten() {
                if e.path().join("colors").is_dir() {
                    out.push(e.path());
                }
            }
        }
    }
    out
}

// ── EDITOR HOST (embedding seam) ─────────────────────────────────────────────
//
// EXTENSION — no `vendor/` counterpart. When vimlrs runs standalone the editor
// builtins (getline/setline/append/getbufline, line()/col()/getpos()/setpos()/
// cursor(), bufname()/bufnr()) operate on the reduced in-crate buffer/cursor
// model in `src/ported/eval/funcs.rs` (CURBUF/CURPOS). When vimlrs is embedded
// inside a host editor (e.g. zemacs), the host installs an [`EditorHost`] so the
// SAME builtins read and mutate the host's live buffer and cursor instead. The
// buffer choke-points in funcs.rs consult these readers first and fall back to
// CURBUF/CURPOS when no host is installed.

/// Line number / column type (mirrors `varnumber_T`), 1-based line/col.
type HostNum = crate::ported::eval::typval_defs_h::varnumber_T;

/// Callbacks an embedding editor installs so Vimscript editor builtins act on the
/// host's live buffer/cursor. All line numbers and columns are 1-based, matching
/// Vim. `set_lines` mirrors `set_buffer_lines` (`append=false` replaces from
/// `lnum`; `append=true` inserts after `lnum`, `lnum==0` before line 1) and
/// returns 0 on success / 1 on an out-of-range replace.
#[allow(clippy::type_complexity)]
pub struct EditorHost {
    pub line_count: Box<dyn Fn() -> HostNum>,
    pub get_line: Box<dyn Fn(HostNum) -> Option<String>>,
    pub set_lines: Box<dyn Fn(HostNum, Vec<String>, bool) -> HostNum>,
    pub cursor: Box<dyn Fn() -> (HostNum, HostNum)>,
    pub set_cursor: Box<dyn Fn(HostNum, HostNum)>,
    pub buf_name: Box<dyn Fn() -> String>,
    pub buf_nr: Box<dyn Fn() -> HostNum>,
}

thread_local! {
    #[allow(clippy::type_complexity)]
    static EDITOR_HOST: RefCell<Option<EditorHost>> = const { RefCell::new(None) };
}

/// Install the editor host (called by an embedding editor once per thread).
/// After this, vimlrs editor builtins act on the host's live buffer/cursor.
pub fn install_editor_host(h: EditorHost) {
    EDITOR_HOST.with(|s| *s.borrow_mut() = Some(h));
}

/// Remove the editor host — builtins revert to the standalone CURBUF/CURPOS model.
pub fn clear_editor_host() {
    EDITOR_HOST.with(|s| *s.borrow_mut() = None);
}

/// True when a host editor is installed on this thread.
pub fn editor_host_active() -> bool {
    EDITOR_HOST.with(|s| s.borrow().is_some())
}

/// Host line count, or `None` when standalone.
pub fn editor_line_count() -> Option<HostNum> {
    EDITOR_HOST.with(|s| s.borrow().as_ref().map(|h| (h.line_count)()))
}

/// Host buffer lines `start..=end` (1-based, inclusive, clamped), or `None`
/// when standalone.
pub fn editor_get_lines(start: HostNum, end: HostNum) -> Option<Vec<String>> {
    EDITOR_HOST.with(|s| {
        s.borrow().as_ref().map(|h| {
            let len = (h.line_count)().max(0);
            let (a, b) = (start.max(1), end.min(len));
            if a > b {
                Vec::new()
            } else {
                (a..=b).filter_map(|i| (h.get_line)(i)).collect()
            }
        })
    })
}

/// Apply `set_buffer_lines` through the host; `None` when standalone.
pub fn editor_set_lines(lnum: HostNum, lines: Vec<String>, append: bool) -> Option<HostNum> {
    EDITOR_HOST.with(|s| {
        s.borrow()
            .as_ref()
            .map(|h| (h.set_lines)(lnum, lines, append))
    })
}

/// The host cursor `(lnum, col, curswant)`, or `fallback` (the standalone
/// CURPOS snapshot) when no host is installed.
pub fn editor_curpos(fallback: (HostNum, HostNum, HostNum)) -> (HostNum, HostNum, HostNum) {
    EDITOR_HOST.with(|s| {
        s.borrow().as_ref().map_or(fallback, |h| {
            let (l, c) = (h.cursor)();
            (l, c, c)
        })
    })
}

/// Move the host cursor; returns `true` when a host handled it (so the caller
/// skips the standalone CURPOS update), `false` when standalone.
pub fn editor_set_cursor(lnum: HostNum, col: HostNum) -> bool {
    EDITOR_HOST.with(|s| {
        s.borrow().as_ref().is_some_and(|h| {
            (h.set_cursor)(lnum, col);
            true
        })
    })
}

/// The host current-buffer name, or `None` when standalone.
pub fn editor_buf_name() -> Option<String> {
    EDITOR_HOST.with(|s| s.borrow().as_ref().map(|h| (h.buf_name)()))
}

/// The host current-buffer number, or `None` when standalone.
pub fn editor_buf_nr() -> Option<HostNum> {
    EDITOR_HOST.with(|s| s.borrow().as_ref().map(|h| (h.buf_nr)()))
}

/// Register every `VIML_*` builtin on a fresh VM before `vm.run()`.
pub fn install(vm: &mut VM) {
    // Turn on fusevm's tiered Cranelift JIT (Linear/Block/Tracing). Without
    // this the JIT never engages — `VM::new` defaults it off and the whole
    // tier dispatch is gated on it. Safe: only CallBuiltin-free chunks/loop
    // bodies are eligible; everything else runs on the interpreter exactly as
    // before, and the tracing tier deopts back to it on a slot-type guard miss.
    // `VIMLRS_NO_JIT` forces the interpreter (for benchmarking the baseline).
    if std::env::var_os("VIMLRS_NO_JIT").is_none() {
        vm.enable_tracing_jit();
    }
    // Seed the v: variable store (vimvars[]) before any script runs.
    crate::ported::eval::vars::evalvars_init();
    vm.register_builtin(VIML_GETVAR, b_getvar);
    vm.register_builtin(VIML_SETVAR, b_setvar);
    vm.register_builtin(VIML_SETENV, b_setenv);
    vm.register_builtin(VIML_TRUTHY, b_truthy);
    vm.register_builtin(VIML_BOOLNUM, b_boolnum);
    vm.register_builtin(VIML_TONUMBER, b_tonumber);
    vm.register_builtin(VIML_ADD, b_add);
    vm.register_builtin(VIML_SUB, b_sub);
    vm.register_builtin(VIML_MUL, b_mul);
    vm.register_builtin(VIML_DIV, b_div);
    vm.register_builtin(VIML_MOD, b_mod);
    vm.register_builtin(VIML_CONCAT, b_concat);
    vm.register_builtin(VIML_NEG, b_neg);
    vm.register_builtin(VIML_UPLUS, b_uplus);
    vm.register_builtin(VIML_NOT, b_not);
    register_cmp_handlers(vm);
    vm.register_builtin(VIML_MAKE_LIST, b_make_list);
    vm.register_builtin(VIML_MAKE_DICT, b_make_dict);
    vm.register_builtin(VIML_INDEX, b_index);
    vm.register_builtin(VIML_IS_DICT, b_is_dict);
    vm.register_builtin(VIML_SLICE, b_slice);
    vm.register_builtin(VIML_SETINDEX, b_setindex);
    vm.register_builtin(VIML_SETRANGE, b_setrange);
    vm.register_builtin(VIML_ECHO, b_echo);
    vm.register_builtin(VIML_ECHON, b_echon);
    vm.register_builtin(VIML_SET_RESULT, b_set_result);
    vm.register_builtin(VIML_GETENV, b_getenv);
    vm.register_builtin(VIML_GETOPT, b_getopt);
    vm.register_builtin(VIML_GETREG, |vm, n| call_func(vm, n, f_getreg));
    vm.register_builtin(VIML_SETREG, |vm, n| call_func(vm, n, f_setreg));
    vm.register_builtin(VIML_SETOPT, b_setopt);
    vm.register_builtin(VIML_FN_LEN, b_fn_len);
    vm.register_builtin(VIML_FN_TYPE, b_fn_type);
    vm.register_builtin(VIML_FN_STRING, b_fn_string);
    vm.register_builtin(VIML_FN_EMPTY, b_fn_empty);
    vm.register_builtin(VIML_FN_ABS, b_fn_abs);
    vm.register_builtin(VIML_FN_STR2NR, b_fn_str2nr);
    vm.register_builtin(VIML_FN_STR2FLOAT, b_fn_str2float);
    vm.register_builtin(VIML_FN_FLOAT2NR, b_fn_float2nr);
    // Second builtin batch — non-capturing closures coerce to the `fn` handler.
    vm.register_builtin(VIML_FN_STRLEN, |vm, n| call_func(vm, n, f_strlen));
    vm.register_builtin(VIML_FN_TOLOWER, |vm, n| call_func(vm, n, f_tolower));
    vm.register_builtin(VIML_FN_TOUPPER, |vm, n| call_func(vm, n, f_toupper));
    vm.register_builtin(VIML_FN_CHAR2NR, |vm, n| call_func(vm, n, f_char2nr));
    vm.register_builtin(VIML_FN_NR2CHAR, |vm, n| call_func(vm, n, f_nr2char));
    vm.register_builtin(VIML_FN_REPEAT, |vm, n| call_func(vm, n, f_repeat));
    vm.register_builtin(VIML_FN_SPLIT, |vm, n| call_func(vm, n, f_split));
    vm.register_builtin(VIML_FN_JOIN, |vm, n| call_func(vm, n, f_join));
    vm.register_builtin(VIML_FN_RANGE, |vm, n| call_func(vm, n, f_range));
    vm.register_builtin(VIML_FN_ADD, |vm, n| call_func(vm, n, f_add));
    vm.register_builtin(VIML_FN_REVERSE, |vm, n| call_func(vm, n, f_reverse));
    vm.register_builtin(VIML_FN_GET, |vm, n| call_func(vm, n, f_get));
    vm.register_builtin(VIML_FN_HAS_KEY, |vm, n| call_func(vm, n, f_has_key));
    vm.register_builtin(VIML_FN_KEYS, |vm, n| call_func(vm, n, f_keys));
    vm.register_builtin(VIML_FN_VALUES, |vm, n| call_func(vm, n, f_values));
    vm.register_builtin(VIML_FN_MAX, |vm, n| call_func(vm, n, f_max));
    vm.register_builtin(VIML_FN_MIN, |vm, n| call_func(vm, n, f_min));
    vm.register_builtin(VIML_FN_COUNT, |vm, n| call_func(vm, n, f_count));
    vm.register_builtin(VIML_FN_INDEX, |vm, n| call_func(vm, n, f_index));
    vm.register_builtin(VIML_FN_HAS, |vm, n| call_func(vm, n, f_has));
    vm.register_builtin(VIML_FN_EXISTS, |vm, n| call_func(vm, n, f_exists));
    vm.register_builtin(VIML_FN_PRINTF, |vm, n| call_func(vm, n, f_printf));
    // Let the value layer's map/filter/foreach evaluate per-item callbacks.
    FILTER_MAP_EVAL_HOOK.with(|h| *h.borrow_mut() = Some(filter_map_eval));
    FILTER_MAP_CMD_HOOK.with(|h| *h.borrow_mut() = Some(filter_map_cmd));
    vm.register_builtin(VIML_FN_MAP, |vm, n| call_func(vm, n, f_map));
    vm.register_builtin(VIML_FN_FILTER, |vm, n| call_func(vm, n, f_filter));
    vm.register_builtin(VIML_FN_MAPNEW, |vm, n| call_func(vm, n, f_mapnew));
    vm.register_builtin(VIML_FN_FOREACH, |vm, n| call_func(vm, n, f_foreach));
    vm.register_builtin(VIML_FN_DICTWATCHERADD, |vm, n| {
        call_func(vm, n, f_dictwatcheradd)
    });
    vm.register_builtin(VIML_FN_DICTWATCHERDEL, |vm, n| {
        call_func(vm, n, f_dictwatcherdel)
    });
    // Let the value layer's sort()/uniq() call user comparator functions.
    SORT_FUNCREF_HOOK.with(|h| *h.borrow_mut() = Some(sort_compare_funcref));
    vm.register_builtin(VIML_FN_SORT, |vm, n| call_func(vm, n, f_sort));
    vm.register_builtin(VIML_FN_CALL, b_call);
    vm.register_builtin(VIML_FN_FUNCTION, |vm, n| call_func(vm, n, f_function));
    vm.register_builtin(VIML_FN_SQRT, |vm, n| call_float_op(vm, n, f64::sqrt));
    vm.register_builtin(VIML_FN_FLOOR, |vm, n| call_float_op(vm, n, f64::floor));
    vm.register_builtin(VIML_FN_CEIL, |vm, n| call_float_op(vm, n, f64::ceil));
    vm.register_builtin(VIML_FN_ROUND, |vm, n| call_float_op(vm, n, f64::round));
    vm.register_builtin(VIML_FN_TRUNC, |vm, n| call_float_op(vm, n, f64::trunc));
    vm.register_builtin(VIML_FN_LOG, |vm, n| call_float_op(vm, n, f64::ln));
    vm.register_builtin(VIML_FN_EXP, |vm, n| call_float_op(vm, n, f64::exp));
    vm.register_builtin(VIML_FN_SIN, |vm, n| call_float_op(vm, n, f64::sin));
    vm.register_builtin(VIML_FN_COS, |vm, n| call_float_op(vm, n, f64::cos));
    vm.register_builtin(VIML_FN_POW, |vm, n| call_func(vm, n, f_pow));
    vm.register_builtin(VIML_FN_AND, |vm, n| call_func(vm, n, f_and));
    vm.register_builtin(VIML_FN_OR, |vm, n| call_func(vm, n, f_or));
    vm.register_builtin(VIML_FN_XOR, |vm, n| call_func(vm, n, f_xor));
    vm.register_builtin(VIML_FN_INVERT, |vm, n| call_func(vm, n, f_invert));
    vm.register_builtin(VIML_FN_STRCHARS, |vm, n| call_func(vm, n, f_strchars));
    vm.register_builtin(VIML_FN_STRPART, |vm, n| call_func(vm, n, f_strpart));
    vm.register_builtin(VIML_FN_STRIDX, |vm, n| call_func(vm, n, f_stridx));
    vm.register_builtin(VIML_FN_TRIM, |vm, n| call_func(vm, n, f_trim));
    vm.register_builtin(VIML_FN_INSERT, |vm, n| call_func(vm, n, f_insert));
    vm.register_builtin(VIML_FN_REMOVE, |vm, n| call_func(vm, n, f_remove));
    vm.register_builtin(VIML_FN_EXTEND, |vm, n| call_func(vm, n, f_extend));
    vm.register_builtin(VIML_FN_COPY, |vm, n| call_func(vm, n, f_copy));
    vm.register_builtin(VIML_FN_ITEMS, |vm, n| call_func(vm, n, f_items));
    vm.register_builtin(VIML_FN_UNIQ, |vm, n| call_func(vm, n, f_uniq));
    vm.register_builtin(VIML_FN_MATCHSTR, |vm, n| call_func(vm, n, f_matchstr));
    vm.register_builtin(VIML_FN_MATCH, |vm, n| call_func(vm, n, f_match));
    vm.register_builtin(VIML_FN_SUBSTITUTE, |vm, n| call_func(vm, n, f_substitute));
    vm.register_builtin(VIML_FN_MATCHLIST, |vm, n| call_func(vm, n, f_matchlist));
    vm.register_builtin(VIML_FN_MATCHEND, |vm, n| call_func(vm, n, f_matchend));
    vm.register_builtin(VIML_FN_STRRIDX, |vm, n| call_func(vm, n, f_strridx));
    vm.register_builtin(VIML_FN_ESCAPE, |vm, n| call_func(vm, n, f_escape));
    vm.register_builtin(VIML_FN_TR, |vm, n| call_func(vm, n, f_tr));
    vm.register_builtin(VIML_FN_STR2LIST, |vm, n| call_func(vm, n, f_str2list));
    vm.register_builtin(VIML_FN_LIST2STR, |vm, n| call_func(vm, n, f_list2str));
    vm.register_builtin(VIML_FN_FLATTEN, |vm, n| call_func(vm, n, f_flatten));
    CALL_FUNC_HOOK.with(|h| *h.borrow_mut() = Some(call_func_hook));
    FUNC_EXISTS_HOOK.with(|h| *h.borrow_mut() = Some(func_exists_hook));
    crate::ported::eval::typval::EVAL_STRING_HOOK
        .with(|h| *h.borrow_mut() = Some(eval_string_hook));
    crate::ported::eval::userfunc::FIND_FUNC_HOOK.with(|h| *h.borrow_mut() = Some(find_func_hook));
    crate::ported::eval::userfunc::REMOVE_FUNC_HOOK
        .with(|h| *h.borrow_mut() = Some(remove_func_hook));
    vm.register_builtin(VIML_FN_REDUCE, |vm, n| call_func(vm, n, f_reduce));
    vm.register_builtin(VIML_FN_EVAL, b_eval);
    crate::viml_regex::SUBST_EXPR_HOOK.with(|h| *h.borrow_mut() = Some(subst_expr_eval));
    vm.register_builtin(VIML_FN_EXECUTE, b_execute);
    vm.register_builtin(VIML_FN_DEEPCOPY, |vm, n| call_func(vm, n, f_deepcopy));
    vm.register_builtin(VIML_FN_FMOD, |vm, n| call_func(vm, n, f_fmod));
    vm.register_builtin(VIML_FN_ATAN2, |vm, n| call_func(vm, n, f_atan2));
    vm.register_builtin(VIML_FN_TAN, |vm, n| call_float_op(vm, n, f64::tan));
    vm.register_builtin(VIML_FN_ATAN, |vm, n| call_float_op(vm, n, f64::atan));
    vm.register_builtin(VIML_FN_ASIN, |vm, n| call_float_op(vm, n, f64::asin));
    vm.register_builtin(VIML_FN_ACOS, |vm, n| call_float_op(vm, n, f64::acos));
    vm.register_builtin(VIML_FN_SINH, |vm, n| call_float_op(vm, n, f64::sinh));
    vm.register_builtin(VIML_FN_COSH, |vm, n| call_float_op(vm, n, f64::cosh));
    vm.register_builtin(VIML_FN_TANH, |vm, n| call_float_op(vm, n, f64::tanh));
    vm.register_builtin(VIML_FN_LOG10, |vm, n| call_float_op(vm, n, f64::log10));
    vm.register_builtin(VIML_EXEC_STMT, b_exec_stmt);
    vm.register_builtin(VIML_SOURCE, b_source);
    vm.register_builtin(VIML_UNLET, b_unlet);
    vm.register_builtin(VIML_UNLET_INDEX, b_unlet_index);
    vm.register_builtin(VIML_SET, b_set);
    vm.register_builtin(VIML_MAP, b_map);
    vm.register_builtin(VIML_COMMAND, b_command);
    vm.register_builtin(VIML_DELCOMMAND, b_delcommand);
    vm.register_builtin(VIML_USERCMD, b_usercmd);
    vm.register_builtin(VIML_AUTOCMD, b_autocmd);
    vm.register_builtin(VIML_AUGROUP, b_augroup);
    vm.register_builtin(VIML_DOAUTOCMD, b_doautocmd);
    vm.register_builtin(VIML_EXCMD, b_excmd);
    vm.register_builtin(VIML_COLORSCHEME, b_colorscheme);
    vm.register_builtin(VIML_HIGHLIGHT, b_highlight);
    vm.register_builtin(VIML_SYNTAX, b_syntax);
    vm.register_builtin(VIML_FILETYPE, b_filetype);
    vm.register_builtin(VIML_FN_JSON_ENCODE, |vm, n| call_func(vm, n, f_json_encode));
    vm.register_builtin(VIML_FN_JSON_DECODE, |vm, n| call_func(vm, n, f_json_decode));
    vm.register_builtin(VIML_FN_STRGETCHAR, |vm, n| call_func(vm, n, f_strgetchar));
    vm.register_builtin(VIML_FN_STRCHARPART, |vm, n| call_func(vm, n, f_strcharpart));
    vm.register_builtin(VIML_FN_BYTEIDX, |vm, n| call_func(vm, n, f_byteidx));
    vm.register_builtin(VIML_FN_CHARIDX, |vm, n| call_func(vm, n, f_charidx));
    vm.register_builtin(VIML_FN_MATCHSTRPOS, |vm, n| call_func(vm, n, f_matchstrpos));
    vm.register_builtin(VIML_FN_EXTENDNEW, |vm, n| call_func(vm, n, f_extendnew));
    vm.register_builtin(VIML_FN_GETENV, |vm, n| call_func(vm, n, f_getenv));
    vm.register_builtin(VIML_FN_SETENV, |vm, n| call_func(vm, n, f_setenv));
    vm.register_builtin(VIML_FN_SHELLESCAPE, |vm, n| call_func(vm, n, f_shellescape));
    vm.register_builtin(VIML_FN_ISINF, |vm, n| call_func(vm, n, f_isinf));
    vm.register_builtin(VIML_FN_ISNAN, |vm, n| call_func(vm, n, f_isnan));
    vm.register_builtin(VIML_FN_GETPID, |vm, n| call_func(vm, n, f_getpid));
    vm.register_builtin(VIML_FN_LOCALTIME, |vm, n| call_func(vm, n, f_localtime));
    vm.register_builtin(VIML_FN_SOUNDFOLD, |vm, n| call_func(vm, n, f_soundfold));
    vm.register_builtin(VIML_FN_BYTEIDXCOMP, |vm, n| call_func(vm, n, f_byteidxcomp));
    vm.register_builtin(VIML_FN_RELTIME, |vm, n| call_func(vm, n, f_reltime));
    vm.register_builtin(VIML_FN_RELTIMESTR, |vm, n| call_func(vm, n, f_reltimestr));
    vm.register_builtin(VIML_FN_RELTIMEFLOAT, |vm, n| {
        call_func(vm, n, f_reltimefloat)
    });
    vm.register_builtin(VIML_FN_RAND, |vm, n| call_func(vm, n, f_rand));
    vm.register_builtin(VIML_FN_SRAND, |vm, n| call_func(vm, n, f_srand));
    vm.register_builtin(VIML_FN_STRFTIME, |vm, n| call_func(vm, n, f_strftime));
    vm.register_builtin(VIML_FN_STRPTIME, |vm, n| call_func(vm, n, f_strptime));
    vm.register_builtin(VIML_FN_PATHSHORTEN, |vm, n| call_func(vm, n, f_pathshorten));
    vm.register_builtin(VIML_FN_ISABSOLUTEPATH, |vm, n| {
        call_func(vm, n, f_isabsolutepath)
    });
    vm.register_builtin(VIML_FN_SIMPLIFY, |vm, n| call_func(vm, n, f_simplify));
    vm.register_builtin(VIML_FN_FILEREADABLE, |vm, n| {
        call_func(vm, n, f_filereadable)
    });
    vm.register_builtin(VIML_FN_FILEWRITABLE, |vm, n| {
        call_func(vm, n, f_filewritable)
    });
    vm.register_builtin(VIML_FN_ISDIRECTORY, |vm, n| call_func(vm, n, f_isdirectory));
    vm.register_builtin(VIML_FN_GETFSIZE, |vm, n| call_func(vm, n, f_getfsize));
    vm.register_builtin(VIML_FN_GETFTYPE, |vm, n| call_func(vm, n, f_getftype));
    vm.register_builtin(VIML_FN_GETFTIME, |vm, n| call_func(vm, n, f_getftime));
    vm.register_builtin(VIML_FN_GETFPERM, |vm, n| call_func(vm, n, f_getfperm));
    vm.register_builtin(VIML_FN_SETFPERM, |vm, n| call_func(vm, n, f_setfperm));
    vm.register_builtin(VIML_FN_GETCWD, |vm, n| call_func(vm, n, f_getcwd));
    vm.register_builtin(VIML_FN_CHDIR, |vm, n| call_func(vm, n, f_chdir));
    vm.register_builtin(VIML_FN_EXECUTABLE, |vm, n| call_func(vm, n, f_executable));
    vm.register_builtin(VIML_FN_EXEPATH, |vm, n| call_func(vm, n, f_exepath));
    vm.register_builtin(VIML_FN_TEMPNAME, |vm, n| call_func(vm, n, f_tempname));
    vm.register_builtin(VIML_FN_MKDIR, |vm, n| call_func(vm, n, f_mkdir));
    vm.register_builtin(VIML_FN_DELETE, |vm, n| call_func(vm, n, f_delete));
    vm.register_builtin(VIML_FN_RENAME, |vm, n| call_func(vm, n, f_rename));
    vm.register_builtin(VIML_FN_READFILE, |vm, n| call_func(vm, n, f_readfile));
    vm.register_builtin(VIML_FN_WRITEFILE, |vm, n| call_func(vm, n, f_writefile));
    vm.register_builtin(VIML_FN_FNAMEMODIFY, |vm, n| call_func(vm, n, f_fnamemodify));
    vm.register_builtin(VIML_FN_FILECOPY, |vm, n| call_func(vm, n, f_filecopy));
    vm.register_builtin(VIML_FN_HASLOCALDIR, |vm, n| call_func(vm, n, f_haslocaldir));
    vm.register_builtin(VIML_FN_RESOLVE, |vm, n| call_func(vm, n, f_resolve));
    vm.register_builtin(VIML_FN_GLOB2REGPAT, |vm, n| call_func(vm, n, f_glob2regpat));
    vm.register_builtin(VIML_FN_READDIR, |vm, n| call_func(vm, n, f_readdir));
    vm.register_builtin(VIML_FN_READBLOB, |vm, n| call_func(vm, n, f_readblob));
    vm.register_builtin(VIML_FN_GETREG, |vm, n| call_func(vm, n, f_getreg));
    vm.register_builtin(VIML_FN_GETREGTYPE, |vm, n| call_func(vm, n, f_getregtype));
    vm.register_builtin(VIML_FN_GETREGINFO, |vm, n| call_func(vm, n, f_getreginfo));
    vm.register_builtin(VIML_FN_SETREG, |vm, n| call_func(vm, n, f_setreg));
    vm.register_builtin(VIML_FN_REG_RECORDING, |vm, n| {
        call_func(vm, n, f_reg_recording)
    });
    vm.register_builtin(VIML_FN_REG_EXECUTING, |vm, n| {
        call_func(vm, n, f_reg_executing)
    });
    vm.register_builtin(VIML_FN_REG_RECORDED, |vm, n| {
        call_func(vm, n, f_reg_recorded)
    });
    vm.register_builtin(VIML_FN_GETTEXT, |vm, n| call_func(vm, n, f_gettext));
    vm.register_builtin(VIML_FN_GARBAGECOLLECT, |vm, n| {
        call_func(vm, n, f_garbagecollect)
    });
    vm.register_builtin(VIML_FN_FUNCREF, |vm, n| call_func(vm, n, f_funcref));
    vm.register_builtin(VIML_FN_ID, |vm, n| call_func(vm, n, f_id));
    vm.register_builtin(VIML_FN_INDEXOF, |vm, n| call_func(vm, n, f_indexof));
    vm.register_builtin(VIML_FN_MATCHSTRLIST, |vm, n| {
        call_func(vm, n, f_matchstrlist)
    });
    vm.register_builtin(VIML_FN_FNAMEESCAPE, |vm, n| call_func(vm, n, f_fnameescape));
    vm.register_builtin(VIML_FN_SHIFTWIDTH, |vm, n| call_func(vm, n, f_shiftwidth));
    vm.register_builtin(VIML_FN_MODE, |vm, n| call_func(vm, n, f_mode));
    vm.register_builtin(VIML_FN_STATE, |vm, n| call_func(vm, n, f_state));
    vm.register_builtin(VIML_FN_VISUALMODE, |vm, n| call_func(vm, n, f_visualmode));
    vm.register_builtin(VIML_FN_PUMVISIBLE, |vm, n| call_func(vm, n, f_pumvisible));
    vm.register_builtin(VIML_FN_WILDMENUMODE, |vm, n| {
        call_func(vm, n, f_wildmenumode)
    });
    vm.register_builtin(VIML_FN_DID_FILETYPE, |vm, n| {
        call_func(vm, n, f_did_filetype)
    });
    vm.register_builtin(VIML_FN_EVENTHANDLER, |vm, n| {
        call_func(vm, n, f_eventhandler)
    });
    vm.register_builtin(VIML_FN_HLEXISTS, |vm, n| call_func(vm, n, f_hlexists));
    vm.register_builtin(VIML_FN_WINDOWSVERSION, |vm, n| {
        call_func(vm, n, f_windowsversion)
    });
    vm.register_builtin(VIML_FN_GETFONTNAME, |vm, n| call_func(vm, n, f_getfontname));
    vm.register_builtin(VIML_FN_FOREGROUND, |vm, n| call_func(vm, n, f_foreground));
    vm.register_builtin(VIML_FN_PROMPT_GETPROMPT, |vm, n| {
        call_func(vm, n, f_prompt_getprompt)
    });
    vm.register_builtin(VIML_FN_PUM_GETPOS, |vm, n| call_func(vm, n, f_pum_getpos));
    vm.register_builtin(VIML_FN_SERVERLIST, |vm, n| call_func(vm, n, f_serverlist));
    vm.register_builtin(VIML_FN_GETPOS, |vm, n| call_func(vm, n, f_getpos));
    vm.register_builtin(VIML_FN_GETCHARPOS, |vm, n| call_func(vm, n, f_getcharpos));
    vm.register_builtin(VIML_FN_GETCURPOS, |vm, n| call_func(vm, n, f_getcurpos));
    vm.register_builtin(VIML_FN_GETCURSORCHARPOS, |vm, n| {
        call_func(vm, n, f_getcursorcharpos)
    });
    vm.register_builtin(VIML_FN_COL, |vm, n| call_func(vm, n, f_col));
    vm.register_builtin(VIML_FN_CHARCOL, |vm, n| call_func(vm, n, f_charcol));
    vm.register_builtin(VIML_FN_LINE, |vm, n| call_func(vm, n, f_line));
    vm.register_builtin(VIML_FN_VIRTCOL, |vm, n| call_func(vm, n, f_virtcol));
    vm.register_builtin(VIML_FN_SCREENROW, |vm, n| call_func(vm, n, f_screenrow));
    vm.register_builtin(VIML_FN_SCREENCOL, |vm, n| call_func(vm, n, f_screencol));
    vm.register_builtin(VIML_FN_SCREENCHAR, |vm, n| call_func(vm, n, f_screenchar));
    vm.register_builtin(VIML_FN_SCREENATTR, |vm, n| call_func(vm, n, f_screenattr));
    vm.register_builtin(VIML_FN_SCREENCHARS, |vm, n| call_func(vm, n, f_screenchars));
    vm.register_builtin(VIML_FN_SCREENSTRING, |vm, n| {
        call_func(vm, n, f_screenstring)
    });
    vm.register_builtin(VIML_FN_LINE2BYTE, |vm, n| call_func(vm, n, f_line2byte));
    vm.register_builtin(VIML_FN_BYTE2LINE, |vm, n| call_func(vm, n, f_byte2line));
    vm.register_builtin(VIML_FN_NEXTNONBLANK, |vm, n| {
        call_func(vm, n, f_nextnonblank)
    });
    vm.register_builtin(VIML_FN_PREVNONBLANK, |vm, n| {
        call_func(vm, n, f_prevnonblank)
    });
    vm.register_builtin(VIML_FN_WORDCOUNT, |vm, n| call_func(vm, n, f_wordcount));
    vm.register_builtin(VIML_FN_GETJUMPLIST, |vm, n| call_func(vm, n, f_getjumplist));
    vm.register_builtin(VIML_FN_GETCHANGELIST, |vm, n| {
        call_func(vm, n, f_getchangelist)
    });
    vm.register_builtin(VIML_FN_GETMARKLIST, |vm, n| call_func(vm, n, f_getmarklist));
    vm.register_builtin(VIML_FN_GETTAGSTACK, |vm, n| call_func(vm, n, f_gettagstack));
    vm.register_builtin(VIML_FN_TAGFILES, |vm, n| call_func(vm, n, f_tagfiles));
    vm.register_builtin(VIML_FN_TAGLIST, |vm, n| call_func(vm, n, f_taglist));
    vm.register_builtin(VIML_FN_TABPAGEBUFLIST, |vm, n| {
        call_func(vm, n, f_tabpagebuflist)
    });
    vm.register_builtin(VIML_FN_SEARCH, |vm, n| call_func(vm, n, f_search));
    vm.register_builtin(VIML_FN_SEARCHPOS, |vm, n| call_func(vm, n, f_searchpos));
    vm.register_builtin(VIML_FN_SEARCHPAIR, |vm, n| call_func(vm, n, f_searchpair));
    vm.register_builtin(VIML_FN_SEARCHPAIRPOS, |vm, n| {
        call_func(vm, n, f_searchpairpos)
    });
    vm.register_builtin(VIML_FN_SEARCHDECL, |vm, n| call_func(vm, n, f_searchdecl));
    vm.register_builtin(VIML_FN_GETCHARSEARCH, |vm, n| {
        call_func(vm, n, f_getcharsearch)
    });
    vm.register_builtin(VIML_FN_INPUT, |vm, n| call_func(vm, n, f_input));
    vm.register_builtin(VIML_FN_INPUTSECRET, |vm, n| call_func(vm, n, f_inputsecret));
    vm.register_builtin(VIML_FN_INPUTDIALOG, |vm, n| call_func(vm, n, f_inputdialog));
    vm.register_builtin(VIML_FN_INPUTLIST, |vm, n| call_func(vm, n, f_inputlist));
    vm.register_builtin(VIML_FN_INPUTSAVE, |vm, n| call_func(vm, n, f_inputsave));
    vm.register_builtin(VIML_FN_INPUTRESTORE, |vm, n| {
        call_func(vm, n, f_inputrestore)
    });
    vm.register_builtin(VIML_FN_CONFIRM, |vm, n| call_func(vm, n, f_confirm));
    vm.register_builtin(VIML_FN_SYNID, |vm, n| call_func(vm, n, f_synID));
    vm.register_builtin(VIML_FN_SYNIDTRANS, |vm, n| call_func(vm, n, f_synIDtrans));
    vm.register_builtin(VIML_FN_SYNIDATTR, |vm, n| call_func(vm, n, f_synIDattr));
    vm.register_builtin(VIML_FN_SYNSTACK, |vm, n| call_func(vm, n, f_synstack));
    vm.register_builtin(VIML_FN_SYNCONCEALED, |vm, n| {
        call_func(vm, n, f_synconcealed)
    });
    vm.register_builtin(VIML_FN_CHANGENR, |vm, n| call_func(vm, n, f_changenr));
    vm.register_builtin(VIML_FN_SWAPNAME, |vm, n| call_func(vm, n, f_swapname));
    vm.register_builtin(VIML_FN_SWAPFILELIST, |vm, n| {
        call_func(vm, n, f_swapfilelist)
    });
    vm.register_builtin(VIML_FN_SPELLBADWORD, |vm, n| {
        call_func(vm, n, f_spellbadword)
    });
    vm.register_builtin(VIML_FN_SPELLSUGGEST, |vm, n| {
        call_func(vm, n, f_spellsuggest)
    });
    vm.register_builtin(VIML_FN_GETREGION, |vm, n| call_func(vm, n, f_getregion));
    vm.register_builtin(VIML_FN_GETREGIONPOS, |vm, n| {
        call_func(vm, n, f_getregionpos)
    });
    vm.register_builtin(VIML_FN_MATCHBUFLINE, |vm, n| {
        call_func(vm, n, f_matchbufline)
    });
    vm.register_builtin(VIML_FN_MENU_GET, |vm, n| call_func(vm, n, f_menu_get));
    vm.register_builtin(VIML_FN_TIMER_INFO, |vm, n| call_func(vm, n, f_timer_info));
    vm.register_builtin(VIML_FN_TIMER_START, |vm, n| call_func(vm, n, f_timer_start));
    vm.register_builtin(VIML_FN_TIMER_STOP, |vm, n| call_func(vm, n, f_timer_stop));
    vm.register_builtin(VIML_FN_TIMER_PAUSE, |vm, n| call_func(vm, n, f_timer_pause));
    vm.register_builtin(VIML_FN_TIMER_STOPALL, |vm, n| {
        call_func(vm, n, f_timer_stopall)
    });
    vm.register_builtin(VIML_FN_SETPOS, |vm, n| call_func(vm, n, f_setpos));
    vm.register_builtin(VIML_FN_SETCHARPOS, |vm, n| call_func(vm, n, f_setcharpos));
    vm.register_builtin(VIML_FN_CURSOR, |vm, n| call_func(vm, n, f_cursor));
    vm.register_builtin(VIML_FN_SETCURSORCHARPOS, |vm, n| {
        call_func(vm, n, f_setcursorcharpos)
    });
    vm.register_builtin(VIML_FN_SETCHARSEARCH, |vm, n| {
        call_func(vm, n, f_setcharsearch)
    });
    vm.register_builtin(VIML_FN_SETTAGSTACK, |vm, n| call_func(vm, n, f_settagstack));
    vm.register_builtin(VIML_FN_ASSERT_EQUAL, |vm, n| {
        call_func(vm, n, f_assert_equal)
    });
    vm.register_builtin(VIML_FN_ASSERT_NOTEQUAL, |vm, n| {
        call_func(vm, n, f_assert_notequal)
    });
    vm.register_builtin(VIML_FN_ASSERT_TRUE, |vm, n| call_func(vm, n, f_assert_true));
    vm.register_builtin(VIML_FN_ASSERT_FALSE, |vm, n| {
        call_func(vm, n, f_assert_false)
    });
    vm.register_builtin(VIML_FN_ASSERT_MATCH, |vm, n| {
        call_func(vm, n, f_assert_match)
    });
    vm.register_builtin(VIML_FN_ASSERT_NOTMATCH, |vm, n| {
        call_func(vm, n, f_assert_notmatch)
    });
    vm.register_builtin(VIML_FN_ASSERT_REPORT, |vm, n| {
        call_func(vm, n, f_assert_report)
    });
    vm.register_builtin(VIML_FN_ASSERT_INRANGE, |vm, n| {
        call_func(vm, n, f_assert_inrange)
    });
    vm.register_builtin(VIML_FN_ASSERT_EXCEPTION, |vm, n| {
        call_func(vm, n, f_assert_exception)
    });
    vm.register_builtin(VIML_FN_ASSERT_FAILS, b_assert_fails);
    vm.register_builtin(VIML_FN_SYSTEM, |vm, n| call_func(vm, n, f_system));
    vm.register_builtin(VIML_FN_SYSTEMLIST, |vm, n| call_func(vm, n, f_systemlist));
    vm.register_builtin(VIML_FN_ENVIRON, |vm, n| call_func(vm, n, f_environ));
    vm.register_builtin(VIML_FN_SLICE, |vm, n| call_func(vm, n, f_slice));
    vm.register_builtin(VIML_FN_STRCHARLEN, |vm, n| call_func(vm, n, f_strcharlen));
    vm.register_builtin(VIML_FN_STRTRANS, |vm, n| call_func(vm, n, f_strtrans));
    vm.register_builtin(VIML_FN_STRWIDTH, |vm, n| call_func(vm, n, f_strwidth));
    vm.register_builtin(VIML_FN_STRDISPLAYWIDTH, |vm, n| {
        call_func(vm, n, f_strdisplaywidth)
    });
    vm.register_builtin(VIML_FN_CHARCLASS, |vm, n| call_func(vm, n, f_charclass));
    vm.register_builtin(VIML_FN_GLOB, |vm, n| call_func(vm, n, f_glob));
    vm.register_builtin(VIML_FN_GLOBPATH, |vm, n| call_func(vm, n, f_globpath));
    vm.register_builtin(VIML_FN_STRUTF16LEN, |vm, n| call_func(vm, n, f_strutf16len));
    vm.register_builtin(VIML_FN_UTF16IDX, |vm, n| call_func(vm, n, f_utf16idx));
    vm.register_builtin(VIML_FN_BUFNR, |vm, n| call_func(vm, n, f_bufnr));
    vm.register_builtin(VIML_FN_BUFEXISTS, |vm, n| call_func(vm, n, f_bufexists));
    vm.register_builtin(VIML_FN_BUFLISTED, |vm, n| call_func(vm, n, f_buflisted));
    vm.register_builtin(VIML_FN_BUFLOADED, |vm, n| call_func(vm, n, f_bufloaded));
    vm.register_builtin(VIML_FN_BUFNAME, |vm, n| call_func(vm, n, f_bufname));
    vm.register_builtin(VIML_FN_BUFWINNR, |vm, n| call_func(vm, n, f_bufwinnr));
    vm.register_builtin(VIML_FN_BUFWINID, |vm, n| call_func(vm, n, f_bufwinid));
    vm.register_builtin(VIML_FN_WINNR, |vm, n| call_func(vm, n, f_winnr));
    vm.register_builtin(VIML_FN_WINBUFNR, |vm, n| call_func(vm, n, f_winbufnr));
    vm.register_builtin(VIML_FN_WINWIDTH, |vm, n| call_func(vm, n, f_winwidth));
    vm.register_builtin(VIML_FN_WINHEIGHT, |vm, n| call_func(vm, n, f_winheight));
    vm.register_builtin(VIML_FN_WINLAYOUT, |vm, n| call_func(vm, n, f_winlayout));
    vm.register_builtin(VIML_FN_WINLINE, |vm, n| call_func(vm, n, f_winline));
    vm.register_builtin(VIML_FN_WINCOL, |vm, n| call_func(vm, n, f_wincol));
    vm.register_builtin(VIML_FN_WINRESTCMD, |vm, n| call_func(vm, n, f_winrestcmd));
    vm.register_builtin(VIML_FN_TABPAGENR, |vm, n| call_func(vm, n, f_tabpagenr));
    vm.register_builtin(VIML_FN_TABPAGEWINNR, |vm, n| {
        call_func(vm, n, f_tabpagewinnr)
    });
    vm.register_builtin(VIML_FN_GETLINE, |vm, n| call_func(vm, n, f_getline));
    vm.register_builtin(VIML_FN_GETBUFLINE, |vm, n| call_func(vm, n, f_getbufline));
    vm.register_builtin(VIML_FN_GETBUFONELINE, |vm, n| {
        call_func(vm, n, f_getbufoneline)
    });
    vm.register_builtin(VIML_FN_GETBUFINFO, |vm, n| call_func(vm, n, f_getbufinfo));
    vm.register_builtin(VIML_FN_SETLINE, |vm, n| call_func(vm, n, f_setline));
    vm.register_builtin(VIML_FN_SETBUFLINE, |vm, n| call_func(vm, n, f_setbufline));
    vm.register_builtin(VIML_FN_APPEND, |vm, n| call_func(vm, n, f_append));
    vm.register_builtin(VIML_FN_APPENDBUFLINE, |vm, n| {
        call_func(vm, n, f_appendbufline)
    });
    vm.register_builtin(VIML_FN_DELETEBUFLINE, |vm, n| {
        call_func(vm, n, f_deletebufline)
    });
    vm.register_builtin(VIML_FN_GETWININFO, |vm, n| call_func(vm, n, f_getwininfo));
    vm.register_builtin(VIML_FN_GETTABINFO, |vm, n| call_func(vm, n, f_gettabinfo));
    vm.register_builtin(VIML_FN_GETWINPOS, |vm, n| call_func(vm, n, f_getwinpos));
    vm.register_builtin(VIML_FN_GETWINPOSX, |vm, n| call_func(vm, n, f_getwinposx));
    vm.register_builtin(VIML_FN_GETWINPOSY, |vm, n| call_func(vm, n, f_getwinposy));
    vm.register_builtin(VIML_FN_WIN_GETID, |vm, n| call_func(vm, n, f_win_getid));
    vm.register_builtin(VIML_FN_WIN_ID2WIN, |vm, n| call_func(vm, n, f_win_id2win));
    vm.register_builtin(VIML_FN_WIN_FINDBUF, |vm, n| call_func(vm, n, f_win_findbuf));
    vm.register_builtin(VIML_FN_WIN_GOTOID, |vm, n| call_func(vm, n, f_win_gotoid));
    vm.register_builtin(VIML_FN_WIN_GETTYPE, |vm, n| call_func(vm, n, f_win_gettype));
    vm.register_builtin(VIML_FN_WIN_SCREENPOS, |vm, n| {
        call_func(vm, n, f_win_screenpos)
    });
    vm.register_builtin(VIML_FN_EXPAND, |vm, n| call_func(vm, n, f_expand));
    vm.register_builtin(VIML_FN_EXPANDCMD, |vm, n| call_func(vm, n, f_expandcmd));
    vm.register_builtin(VIML_FN_WIN_ID2TABWIN, |vm, n| {
        call_func(vm, n, f_win_id2tabwin)
    });
    vm.register_builtin(VIML_FN_WIN_SPLITMOVE, |vm, n| {
        call_func(vm, n, f_win_splitmove)
    });
    vm.register_builtin(VIML_FN_WIN_MOVE_SEPARATOR, |vm, n| {
        call_func(vm, n, f_win_move_separator)
    });
    vm.register_builtin(VIML_FN_WIN_MOVE_STATUSLINE, |vm, n| {
        call_func(vm, n, f_win_move_statusline)
    });
    vm.register_builtin(VIML_FN_GETCMDWINTYPE, |vm, n| {
        call_func(vm, n, f_getcmdwintype)
    });
    vm.register_builtin(VIML_FN_WINRESTVIEW, |vm, n| call_func(vm, n, f_winrestview));
    vm.register_builtin(VIML_FN_WINSAVEVIEW, |vm, n| call_func(vm, n, f_winsaveview));
    vm.register_builtin(VIML_FN_BUFLOAD, |vm, n| call_func(vm, n, f_bufload));
    vm.register_builtin(VIML_FN_PROMPT_GETINPUT, |vm, n| {
        call_func(vm, n, f_prompt_getinput)
    });
    vm.register_builtin(VIML_FN_PROMPT_SETPROMPT, |vm, n| {
        call_func(vm, n, f_prompt_setprompt)
    });
    vm.register_builtin(VIML_FN_PROMPT_SETCALLBACK, |vm, n| {
        call_func(vm, n, f_prompt_setcallback)
    });
    vm.register_builtin(VIML_FN_PROMPT_SETINTERRUPT, |vm, n| {
        call_func(vm, n, f_prompt_setinterrupt)
    });
    vm.register_builtin(VIML_FN_INTERRUPT, |vm, n| call_func(vm, n, f_interrupt));
    vm.register_builtin(VIML_FN_DEBUGBREAK, |vm, n| call_func(vm, n, f_debugbreak));
    vm.register_builtin(VIML_FN_API_INFO, |vm, n| call_func(vm, n, f_api_info));
    vm.register_builtin(VIML_FN_SWAPINFO, |vm, n| call_func(vm, n, f_swapinfo));
    vm.register_builtin(VIML_FN_SERVERSTART, |vm, n| call_func(vm, n, f_serverstart));
    vm.register_builtin(VIML_FN_SERVERSTOP, |vm, n| call_func(vm, n, f_serverstop));
    vm.register_builtin(VIML_FN_GETBUFVAR, |vm, n| call_func(vm, n, f_getbufvar));
    vm.register_builtin(VIML_FN_GETWINVAR, |vm, n| call_func(vm, n, f_getwinvar));
    vm.register_builtin(VIML_FN_GETTABVAR, |vm, n| call_func(vm, n, f_gettabvar));
    vm.register_builtin(VIML_FN_GETTABWINVAR, |vm, n| {
        call_func(vm, n, f_gettabwinvar)
    });
    vm.register_builtin(VIML_FN_SETBUFVAR, |vm, n| call_func(vm, n, f_setbufvar));
    vm.register_builtin(VIML_FN_SETWINVAR, |vm, n| call_func(vm, n, f_setwinvar));
    vm.register_builtin(VIML_FN_SETTABVAR, |vm, n| call_func(vm, n, f_settabvar));
    vm.register_builtin(VIML_FN_SETTABWINVAR, |vm, n| {
        call_func(vm, n, f_settabwinvar)
    });
    vm.register_builtin(VIML_FN_JOBSTART, |vm, n| call_func(vm, n, f_jobstart));
    vm.register_builtin(VIML_FN_JOBPID, |vm, n| call_func(vm, n, f_jobpid));
    vm.register_builtin(VIML_FN_JOBSTOP, |vm, n| call_func(vm, n, f_jobstop));
    vm.register_builtin(VIML_FN_JOBWAIT, |vm, n| call_func(vm, n, f_jobwait));
    vm.register_builtin(VIML_FN_JOBRESIZE, |vm, n| call_func(vm, n, f_jobresize));
    vm.register_builtin(VIML_FN_CHANCLOSE, |vm, n| call_func(vm, n, f_chanclose));
    vm.register_builtin(VIML_FN_CHANSEND, |vm, n| call_func(vm, n, f_chansend));
    vm.register_builtin(VIML_FN_FEEDKEYS, |vm, n| call_func(vm, n, f_feedkeys));
    vm.register_builtin(VIML_FN_WAIT, |vm, n| call_func(vm, n, f_wait));
    vm.register_builtin(VIML_FN_SOCKCONNECT, |vm, n| call_func(vm, n, f_sockconnect));
    vm.register_builtin(VIML_FN_WIN_EXECUTE, |vm, n| call_func(vm, n, f_win_execute));
    vm.register_builtin(VIML_FN_BUFADD, |vm, n| call_func(vm, n, f_bufadd));
    vm.register_builtin(VIML_FN_CTXGET, |vm, n| call_func(vm, n, f_ctxget));
    vm.register_builtin(VIML_FN_CTXPOP, |vm, n| call_func(vm, n, f_ctxpop));
    vm.register_builtin(VIML_FN_CTXPUSH, |vm, n| call_func(vm, n, f_ctxpush));
    vm.register_builtin(VIML_FN_CTXSET, |vm, n| call_func(vm, n, f_ctxset));
    vm.register_builtin(VIML_FN_CTXSIZE, |vm, n| call_func(vm, n, f_ctxsize));
    vm.register_builtin(VIML_FN_ISLOCKED, |vm, n| call_func(vm, n, f_islocked));
    vm.register_builtin(VIML_FN_LAST_BUFFER_NR, |vm, n| {
        call_func(vm, n, f_last_buffer_nr)
    });
    vm.register_builtin(VIML_FN_LIBCALL, |vm, n| call_func(vm, n, f_libcall));
    vm.register_builtin(VIML_FN_LIBCALLNR, |vm, n| call_func(vm, n, f_libcallnr));
    vm.register_builtin(VIML_FN_MSGPACKDUMP, |vm, n| call_func(vm, n, f_msgpackdump));
    vm.register_builtin(VIML_FN_MSGPACKPARSE, |vm, n| {
        call_func(vm, n, f_msgpackparse)
    });
    vm.register_builtin(VIML_FN_RPCNOTIFY, |vm, n| call_func(vm, n, f_rpcnotify));
    vm.register_builtin(VIML_FN_RPCREQUEST, |vm, n| call_func(vm, n, f_rpcrequest));
    vm.register_builtin(VIML_FN_RPCSTART, |vm, n| call_func(vm, n, f_rpcstart));
    vm.register_builtin(VIML_FN_RPCSTOP, |vm, n| call_func(vm, n, f_rpcstop));
    vm.register_builtin(VIML_FN_STDIOOPEN, |vm, n| call_func(vm, n, f_stdioopen));
    vm.register_builtin(VIML_FN_SUBMATCH, |vm, n| call_func(vm, n, f_submatch));
    vm.register_builtin(VIML_FN_PROMPT_APPENDBUF, |vm, n| {
        call_func(vm, n, f_prompt_appendbuf)
    });
    vm.register_builtin(VIML_FN_PY3EVAL, |vm, n| call_func(vm, n, f_py3eval));
    vm.register_builtin(VIML_FN_PERLEVAL, |vm, n| call_func(vm, n, f_perleval));
    vm.register_builtin(VIML_FN_STDPATH, |vm, n| call_func(vm, n, f_stdpath));
    vm.register_builtin(VIML_FN_KEYTRANS, |vm, n| call_func(vm, n, f_keytrans));
    vm.register_builtin(VIML_FN_LUAEVAL, |vm, n| call_func(vm, n, f_luaeval));
    vm.register_builtin(VIML_FN_RUBYEVAL, |vm, n| call_func(vm, n, f_rubyeval));
    vm.register_builtin(VIML_FN_TERMOPEN, |vm, n| call_func(vm, n, f_termopen));
    vm.register_builtin(VIML_FN_BROWSE, |vm, n| call_func(vm, n, f_browse));
    vm.register_builtin(VIML_FN_BROWSEDIR, |vm, n| call_func(vm, n, f_browsedir));
    vm.register_builtin(VIML_FN_FINDDIR, |vm, n| call_func(vm, n, f_finddir));
    vm.register_builtin(VIML_FN_FINDFILE, |vm, n| call_func(vm, n, f_findfile));
    vm.register_builtin(VIML_FN_FLATTENNEW, |vm, n| call_func(vm, n, f_flattennew));
    vm.register_builtin(VIML_FN_SHA256, |vm, n| call_func(vm, n, f_sha256));
    vm.register_builtin(VIML_FN_BLOB2LIST, |vm, n| call_func(vm, n, f_blob2list));
    vm.register_builtin(VIML_FN_LIST2BLOB, |vm, n| call_func(vm, n, f_list2blob));
    vm.register_builtin(VIML_FN_MATCHFUZZY, |vm, n| call_func(vm, n, f_matchfuzzy));
    vm.register_builtin(VIML_FN_MATCHFUZZYPOS, |vm, n| {
        call_func(vm, n, f_matchfuzzypos)
    });
    vm.register_builtin(VIML_FN_HISTADD, |vm, n| call_func(vm, n, f_histadd));
    vm.register_builtin(VIML_FN_HISTGET, |vm, n| call_func(vm, n, f_histget));
    vm.register_builtin(VIML_FN_HISTNR, |vm, n| call_func(vm, n, f_histnr));
    vm.register_builtin(VIML_FN_HISTDEL, |vm, n| call_func(vm, n, f_histdel));
    vm.register_builtin(VIML_FN_DIGRAPH_GET, |vm, n| call_func(vm, n, f_digraph_get));
    vm.register_builtin(VIML_FN_DIGRAPH_SET, |vm, n| call_func(vm, n, f_digraph_set));
    vm.register_builtin(VIML_FN_DIGRAPH_GETLIST, |vm, n| {
        call_func(vm, n, f_digraph_getlist)
    });
    vm.register_builtin(VIML_FN_DIGRAPH_SETLIST, |vm, n| {
        call_func(vm, n, f_digraph_setlist)
    });
    vm.register_builtin(VIML_FN_SETCELLWIDTHS, |vm, n| {
        call_func(vm, n, f_setcellwidths)
    });
    vm.register_builtin(VIML_FN_GETCELLWIDTHS, |vm, n| {
        call_func(vm, n, f_getcellwidths)
    });
    vm.register_builtin(VIML_FN_HOSTNAME, |vm, n| call_func(vm, n, f_hostname));
    vm.register_builtin(VIML_FN_ICONV, |vm, n| call_func(vm, n, f_iconv));
    vm.register_builtin(VIML_FN_ARGC, |vm, n| call_func(vm, n, f_argc));
    vm.register_builtin(VIML_FN_ARGIDX, |vm, n| call_func(vm, n, f_argidx));
    vm.register_builtin(VIML_FN_ARGV, |vm, n| call_func(vm, n, f_argv));
    vm.register_builtin(VIML_FN_ASSERT_EQUALFILE, |vm, n| {
        call_func(vm, n, f_assert_equalfile)
    });
    vm.register_builtin(VIML_FN_ARGLISTID, |vm, n| call_func(vm, n, f_arglistid));
    vm.register_builtin(VIML_FN_FOLDLEVEL, |vm, n| call_func(vm, n, f_foldlevel));
    vm.register_builtin(VIML_FN_MATCHADD, |vm, n| call_func(vm, n, f_matchadd));
    vm.register_builtin(VIML_FN_MATCHADDPOS, |vm, n| call_func(vm, n, f_matchaddpos));
    vm.register_builtin(VIML_FN_MATCHDELETE, |vm, n| call_func(vm, n, f_matchdelete));
    vm.register_builtin(VIML_FN_GETMATCHES, |vm, n| call_func(vm, n, f_getmatches));
    vm.register_builtin(VIML_FN_SETMATCHES, |vm, n| call_func(vm, n, f_setmatches));
    vm.register_builtin(VIML_FN_CLEARMATCHES, |vm, n| {
        call_func(vm, n, f_clearmatches)
    });
    vm.register_builtin(VIML_FN_MATCHARG, |vm, n| call_func(vm, n, f_matcharg));
    vm.register_builtin(VIML_FN_SIGN_DEFINE, |vm, n| call_func(vm, n, f_sign_define));
    vm.register_builtin(VIML_FN_SIGN_GETDEFINED, |vm, n| {
        call_func(vm, n, f_sign_getdefined)
    });
    vm.register_builtin(VIML_FN_SIGN_UNDEFINE, |vm, n| {
        call_func(vm, n, f_sign_undefine)
    });
    vm.register_builtin(VIML_FN_FOLDCLOSED, |vm, n| call_func(vm, n, f_foldclosed));
    vm.register_builtin(VIML_FN_FOLDCLOSEDEND, |vm, n| {
        call_func(vm, n, f_foldclosedend)
    });
    vm.register_builtin(VIML_FN_HASMAPTO, |vm, n| call_func(vm, n, f_hasmapto));
    vm.register_builtin(VIML_FN_MAPARG, |vm, n| call_func(vm, n, f_maparg));
    vm.register_builtin(VIML_FN_MAPCHECK, |vm, n| call_func(vm, n, f_mapcheck));
    vm.register_builtin(VIML_FN_MAPLIST, |vm, n| call_func(vm, n, f_maplist));
    vm.register_builtin(VIML_FN_SETCMDLINE, |vm, n| call_func(vm, n, f_setcmdline));
    vm.register_builtin(VIML_FN_GETCMDLINE, |vm, n| call_func(vm, n, f_getcmdline));
    vm.register_builtin(VIML_FN_SETCMDPOS, |vm, n| call_func(vm, n, f_setcmdpos));
    vm.register_builtin(VIML_FN_GETCMDPOS, |vm, n| call_func(vm, n, f_getcmdpos));
    vm.register_builtin(VIML_FN_GETCMDTYPE, |vm, n| call_func(vm, n, f_getcmdtype));
    vm.register_builtin(VIML_FN_SIGN_PLACE, |vm, n| call_func(vm, n, f_sign_place));
    vm.register_builtin(VIML_FN_SIGN_GETPLACED, |vm, n| {
        call_func(vm, n, f_sign_getplaced)
    });
    vm.register_builtin(VIML_FN_SIGN_UNPLACE, |vm, n| {
        call_func(vm, n, f_sign_unplace)
    });
    vm.register_builtin(VIML_FN_SIGN_PLACELIST, |vm, n| {
        call_func(vm, n, f_sign_placelist)
    });
    vm.register_builtin(VIML_FN_SIGN_UNPLACELIST, |vm, n| {
        call_func(vm, n, f_sign_unplacelist)
    });
    vm.register_builtin(VIML_FN_SIGN_JUMP, |vm, n| call_func(vm, n, f_sign_jump));
    vm.register_builtin(VIML_FN_INDENT, |vm, n| call_func(vm, n, f_indent));
    vm.register_builtin(VIML_FN_FOLDTEXT, |vm, n| call_func(vm, n, f_foldtext));
    vm.register_builtin(VIML_FN_FOLDTEXTRESULT, |vm, n| {
        call_func(vm, n, f_foldtextresult)
    });
    vm.register_builtin(VIML_FN_HIGHLIGHT_EXISTS, |vm, n| {
        call_func(vm, n, f_highlight_exists)
    });
    vm.register_builtin(VIML_FN_DIFF_FILLER, |vm, n| call_func(vm, n, f_diff_filler));
    vm.register_builtin(VIML_FN_HLID, |vm, n| call_func(vm, n, f_hlID));
    vm.register_builtin(VIML_FN_DIFF_HLID, |vm, n| call_func(vm, n, f_diff_hlID));
    vm.register_builtin(VIML_FN_VIRTCOL2COL, |vm, n| call_func(vm, n, f_virtcol2col));
    vm.register_builtin(VIML_FN_WILDTRIGGER, |vm, n| call_func(vm, n, f_wildtrigger));
    vm.register_builtin(VIML_FN_SEARCHCOUNT, |vm, n| call_func(vm, n, f_searchcount));
    vm.register_builtin(VIML_FN_COMPLETE_INFO, |vm, n| {
        call_func(vm, n, f_complete_info)
    });
    vm.register_builtin(VIML_FN_SETQFLIST, |vm, n| call_func(vm, n, f_setqflist));
    vm.register_builtin(VIML_FN_GETQFLIST, |vm, n| call_func(vm, n, f_getqflist));
    vm.register_builtin(VIML_FN_SETLOCLIST, |vm, n| call_func(vm, n, f_setloclist));
    vm.register_builtin(VIML_FN_GETLOCLIST, |vm, n| call_func(vm, n, f_getloclist));
    vm.register_builtin(VIML_FN_GETCOMPLETION, |vm, n| {
        call_func(vm, n, f_getcompletion)
    });
    vm.register_builtin(VIML_FN_GETCHAR, |vm, n| call_func(vm, n, f_getchar));
    vm.register_builtin(VIML_FN_GETCHARSTR, |vm, n| call_func(vm, n, f_getcharstr));
    vm.register_builtin(VIML_FN_GETCHARMOD, |vm, n| call_func(vm, n, f_getcharmod));
    vm.register_builtin(VIML_FN_GETCMDPROMPT, |vm, n| {
        call_func(vm, n, f_getcmdprompt)
    });
    vm.register_builtin(VIML_FN_GETCMDSCREENPOS, |vm, n| {
        call_func(vm, n, f_getcmdscreenpos)
    });
    vm.register_builtin(VIML_FN_GETCMDCOMPLTYPE, |vm, n| {
        call_func(vm, n, f_getcmdcompltype)
    });
    vm.register_builtin(VIML_FN_GETCMDCOMPLPAT, |vm, n| {
        call_func(vm, n, f_getcmdcomplpat)
    });
    vm.register_builtin(VIML_FN_CINDENT, |vm, n| call_func(vm, n, f_cindent));
    vm.register_builtin(VIML_FN_LISPINDENT, |vm, n| call_func(vm, n, f_lispindent));
    vm.register_builtin(VIML_FN_COMPLETE_ADD, |vm, n| {
        call_func(vm, n, f_complete_add)
    });
    vm.register_builtin(VIML_FN_COMPLETE_CHECK, |vm, n| {
        call_func(vm, n, f_complete_check)
    });
    vm.register_builtin(VIML_FN_CMDCOMPLETE_INFO, |vm, n| {
        call_func(vm, n, f_cmdcomplete_info)
    });
    vm.register_builtin(VIML_FN_MENU_INFO, |vm, n| call_func(vm, n, f_menu_info));
    vm.register_builtin(VIML_FN_TEST_GARBAGECOLLECT_NOW, |vm, n| {
        call_func(vm, n, f_test_garbagecollect_now)
    });
    vm.register_builtin(VIML_FN_TEST_WRITE_LIST_LOG, |vm, n| {
        call_func(vm, n, f_test_write_list_log)
    });
    vm.register_builtin(VIML_FN_PYEVAL, |vm, n| call_func(vm, n, f_pyeval));
    vm.register_builtin(VIML_FN_PYXEVAL, |vm, n| call_func(vm, n, f_pyxeval));
    vm.register_builtin(VIML_FN_UNDOFILE, |vm, n| call_func(vm, n, f_undofile));
    vm.register_builtin(VIML_FN_UNDOTREE, |vm, n| call_func(vm, n, f_undotree));
    vm.register_builtin(VIML_FN_GETMOUSEPOS, |vm, n| call_func(vm, n, f_getmousepos));
    vm.register_builtin(VIML_FN_SCREENPOS, |vm, n| call_func(vm, n, f_screenpos));
    vm.register_builtin(VIML_FN_GETCOMPLETIONTYPE, |vm, n| {
        call_func(vm, n, f_getcompletiontype)
    });
    vm.register_builtin(VIML_FN_MAPSET, |vm, n| call_func(vm, n, f_mapset));
    vm.register_builtin(VIML_FN_COMPLETE, |vm, n| call_func(vm, n, f_complete));
    vm.register_builtin(VIML_FN_PREINSERTED, |vm, n| call_func(vm, n, f_preinserted));
    vm.register_builtin(VIML_FN_GETSCRIPTINFO, |vm, n| {
        call_func(vm, n, f_getscriptinfo)
    });
    vm.register_builtin(VIML_FN_GETSTACKTRACE, |vm, n| {
        call_func(vm, n, f_getstacktrace)
    });
    vm.register_builtin(VIML_FN_FULLCOMMAND, |vm, n| call_func(vm, n, f_fullcommand));
    vm.register_builtin(VIML_FN_ASSERT_BEEPS, b_assert_beeps);
    vm.register_builtin(VIML_FN_ASSERT_NOBEEP, b_assert_nobeep);
    vm.register_builtin(VIML_SET_LINENO, b_set_lineno);
    vm.register_builtin(VIML_CALL_USER, b_call_user);
    vm.register_builtin(VIML_CALL_FUNCREF, b_call_funcref);
    vm.register_builtin(VIML_ERR_MARK, b_err_mark);
    vm.register_builtin(VIML_SET_RETURN, b_set_return);
    vm.register_builtin(VIML_THROW, b_throw);
    vm.register_builtin(VIML_CHECK_EXC, b_check_exc);
    vm.register_builtin(VIML_CATCH_MATCH, b_catch_match);
    vm.register_builtin(VIML_REPORT_UNCAUGHT, b_report_uncaught);
    vm.register_builtin(VIML_DEFINE_FUNC, b_define_func);
}

/// Register a compiled program's user functions, then run its `main` chunk.
pub fn run_compiled(prog: crate::compile_viml::CompiledProgram) {
    register_prog_funcs(&mut prog.funcs.into_iter());
    stage_deferred_funcs(prog.deferred_funcs);
    run_chunk(prog.main);
}

// ── debugger support (DAP) ──

/// Parse + debug-compile + run source with a `SET_LINENO` marker before each
/// statement, so the DAP `check_line` hook can pause at breakpoints.
pub fn eval_source_debug(src: &str) -> Result<(), VimlError> {
    let numbered = crate::viml_parser::parse_program_lines(src)?;
    run_chunk(crate::compile_viml::compile_program_debug(&numbered)?);
    Ok(())
}

/// Snapshot the `g:` scope for the debugger's variables view: `(name, rendered)`
/// pairs read from `globvardict` (no VM run).
pub fn dap_globals() -> Vec<(String, String)> {
    crate::ported::eval::vars::globvardict.with(|d| {
        d.borrow()
            .dv_hashtab
            .iter()
            .map(|(k, v)| (format!("g:{k}"), encode_tv2echo(v)))
            .collect()
    })
}

/// Evaluate a bare variable name for the debugger's `evaluate` request (reads
/// `eval_variable`, no nested VM run — avoids disturbing the paused executor).
pub fn dap_eval_var(name: &str) -> Option<String> {
    eval_variable(name).as_ref().map(encode_tv2echo)
}

// ── public driver: parse → compile → run on fusevm ──

/// Run an already-compiled `fusevm::Chunk` on a fresh VM with the VimL host
/// installed (the script-cache hit path — no lex/parse/compile).
pub fn run_chunk(chunk: fusevm::Chunk) {
    crate::fusevm_disasm::maybe_print_stdout("program", &chunk);
    reset_run();
    let stats = std::env::var_os("VIMLRS_JIT_STATS").is_some();
    let probe = if stats { Some(chunk.clone()) } else { None };
    let mut vm = VM::new(chunk);
    install(&mut vm);
    let _ = vm.run();
    if let Some(chunk) = probe {
        jit_stats_report(&chunk);
    }
}

/// Diagnostic (opt-in via `VIMLRS_JIT_STATS`): report how much fusevm
/// JIT-compiled to native machine code — across the main chunk AND every
/// user-function body (which run on nested VMs), counting any loop whose trace
/// compiled. Goes to stderr like `--doctor`.
fn jit_stats_report(main: &fusevm::Chunk) {
    use fusevm::Op;
    let jc = fusevm::JitCompiler::new();
    let count_traces = |chunk: &fusevm::Chunk| -> usize {
        chunk
            .ops
            .iter()
            .enumerate()
            .filter_map(|(i, o)| match o {
                Op::Jump(t) | Op::JumpIfTrue(t) | Op::JumpIfFalse(t) if *t < i => Some(*t),
                _ => None,
            })
            .filter(|&h| jc.trace_is_compiled(chunk, h))
            .count()
    };
    let mut traced = count_traces(main);
    FUNCTIONS.with(|f| {
        for func in f.borrow().values() {
            traced += count_traces(&func.chunk);
        }
    });
    eprintln!(
        "vimlrs: JIT — main block-compiled={}, loop traces compiled={}",
        jc.block_jit_is_compiled(main),
        traced
    );
}

/// Compile and run a statement list. `:echo` output and `emsg` errors happen as
/// side effects.
pub fn run_program(stmts: &[Stmt]) -> Result<(), VimlError> {
    run_compiled(compile_program(stmts)?);
    Ok(())
}

/// Parse + compile + run a block of VimL source. Block-structured (`:if`/
/// `:while`/`:for`/…) statements are parsed across lines into one chunk. Returns
/// the last bare-expression value.
pub fn eval_source(src: &str) -> Result<Option<typval_T>, VimlError> {
    run_program(&crate::viml_parser::parse_program(src)?)?;
    Ok(take_last_result())
}

/// Source a `.vim` file through the rkyv bytecode cache: a 2nd+ run with an
/// unchanged file and binary skips lex/parse/compile and runs the cached chunk.
pub fn eval_file(path: &std::path::Path) -> Result<(), VimlError> {
    // Make `<sfile>`/`<script>` (expand()) resolve to this script's path while it
    // runs. Use the absolute path when it can be resolved, else the given path.
    let sname = std::fs::canonicalize(path)
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| path.display().to_string());
    crate::ported::eval::fs::push_sourcing_name(sname);
    let r = eval_file_inner(path);
    crate::ported::eval::fs::pop_sourcing_name();
    r
}

fn eval_file_inner(path: &std::path::Path) -> Result<(), VimlError> {
    if let Some(prog) = crate::script_cache::try_load(path) {
        run_compiled(prog);
        return Ok(());
    }
    let src = std::fs::read_to_string(path)
        .map_err(|e| VimlError::msg(format!("vimlrs: {}: {e}", path.display())))?;
    // Fast path: the whole file parses + compiles as one chunk (cached).
    match crate::viml_parser::parse_program(&src) {
        Ok(stmts) => {
            let prog = compile_program(&stmts)?;
            crate::script_cache::store(path, &prog);
            run_compiled(prog);
            Ok(())
        }
        // A real-world config (e.g. `~/.vimrc`) often contains a construct vimlrs
        // does not yet parse. Rather than abort the entire file — losing every
        // option, mapping, and colour scheme after the offending line — fall back
        // to sourcing it statement-by-statement, skipping the ones that don't
        // parse or that error at run time, exactly as Vim reports an error while
        // sourcing and continues with the next command.
        Err(_) => {
            source_tolerant(&src);
            Ok(())
        }
    }
}

/// Best-effort statement-by-statement sourcing: parse the file tolerantly and run
/// each top-level statement (or block) in its own chunk so a parse *or* run-time
/// failure in one is contained and the rest of the file still takes effect.
/// Returns the number of statements that ran and the number skipped.
pub fn source_tolerant(src: &str) -> (usize, usize) {
    let (stmts, parse_errs) = crate::viml_parser::parse_program_lines_tolerant(src);
    let mut ran = 0usize;
    let mut skipped = parse_errs.len();
    for (_lineno, stmt) in stmts {
        // Each statement compiles + runs independently; a compile error or an
        // uncaught run-time error ends only that statement's chunk.
        match compile_program(std::slice::from_ref(&stmt)) {
            Ok(prog) => {
                run_compiled(prog);
                ran += 1;
            }
            Err(_) => skipped += 1,
        }
    }
    (ran, skipped)
}

/// Parse + compile + run a single expression, returning its value.
pub fn eval_expr(src: &str) -> Result<typval_T, VimlError> {
    let e = parse_expr(src)?;
    run_program(&[Stmt::Expr(e)])?;
    Ok(take_last_result().unwrap_or_else(tv_special))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run(src: &str) -> String {
        capture_begin();
        eval_source(src).unwrap();
        capture_take()
    }

    #[test]
    fn editor_host_delegation() {
        use std::cell::RefCell;
        use std::rc::Rc;
        // A fake host buffer + cursor the builtins should read/write instead of
        // the standalone CURBUF/CURPOS.
        let buf = Rc::new(RefCell::new(vec![
            "alpha".to_string(),
            "beta".to_string(),
            "gamma".to_string(),
        ]));
        let cur = Rc::new(RefCell::new((2i64, 1i64)));
        let (b1, b2, b3) = (buf.clone(), buf.clone(), buf.clone());
        let (c1, c2) = (cur.clone(), cur.clone());
        install_editor_host(EditorHost {
            line_count: Box::new(move || b1.borrow().len() as i64),
            get_line: Box::new(move |n| b2.borrow().get((n - 1) as usize).cloned()),
            set_lines: Box::new(move |lnum, lines, append| {
                let mut b = b3.borrow_mut();
                if append {
                    let pos = (lnum.max(0) as usize).min(b.len());
                    for (i, l) in lines.into_iter().enumerate() {
                        b.insert(pos + i, l);
                    }
                } else {
                    for (i, l) in lines.into_iter().enumerate() {
                        let idx = (lnum - 1) as usize + i;
                        if idx < b.len() {
                            b[idx] = l;
                        } else {
                            b.push(l);
                        }
                    }
                }
                0
            }),
            cursor: Box::new(move || *c1.borrow()),
            set_cursor: Box::new(move |l, c| *c2.borrow_mut() = (l, c)),
            buf_name: Box::new(|| "hostbuf".to_string()),
            buf_nr: Box::new(|| 7),
        });

        // reads route to the host buffer/cursor
        assert_eq!(run("echo getline(2)").trim(), "beta");
        assert_eq!(run("echo line('$')").trim(), "3");
        assert_eq!(run("echo line('.')").trim(), "2"); // host cursor line
        assert_eq!(
            run("echo bufname('') . '#' . bufnr('')").trim(),
            "hostbuf#7"
        );
        // writes route to the host buffer
        run("call setline(2, 'BETA')");
        assert_eq!(buf.borrow()[1], "BETA");
        // cursor move routes to the host cursor
        run("call cursor(3, 1)");
        assert_eq!(cur.borrow().0, 3);

        clear_editor_host();
        // after clearing, builtins fall back to the standalone model
        assert_eq!(run("call setline(1,'x') | echo getline(1)").trim(), "x");
    }

    #[test]
    fn map_host_hook_fires_with_raw_line() {
        use std::cell::RefCell;
        thread_local! { static SEEN: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }; }
        SEEN.with(|s| s.borrow_mut().clear());
        install_map_hook(Box::new(|line: &str| {
            SEEN.with(|s| s.borrow_mut().push(line.to_string()))
        }));
        eval_source("nnoremap <silent> <leader>x :Foo<CR>").unwrap();
        eval_source("inoremap jk <Esc>").unwrap();
        SEEN.with(|s| {
            assert_eq!(
                s.borrow().as_slice(),
                &[
                    "nnoremap <silent> <leader>x :Foo<CR>".to_string(),
                    "inoremap jk <Esc>".to_string(),
                ]
            )
        });
        // uninstall so later tests on this thread are unaffected
        MAP_HOST_HOOK.with(|h| *h.borrow_mut() = None);
    }

    /// `:highlight` populates the registry so `hlexists()`/`hlID()`/`synIDattr()`
    /// reflect script-defined groups, and fires the highlight host hook with the
    /// raw args.
    #[test]
    fn highlight_registry_and_host_hook() {
        use std::cell::RefCell;
        thread_local! { static SEEN: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }; }
        SEEN.with(|s| s.borrow_mut().clear());
        crate::ported::eval::funcs::HL_GROUPS.with(|r| *r.borrow_mut() = Default::default());
        install_highlight_hook(Box::new(|args: &str| {
            SEEN.with(|s| s.borrow_mut().push(args.to_string()))
        }));

        // Before any definition the group does not exist.
        assert_eq!(run("echo hlexists('Comment')").trim(), "0");

        eval_source("highlight Normal ctermfg=252 guifg=#d0d0d0 guibg=#1c1c1c gui=bold").unwrap();
        eval_source("hi link Comment Normal").unwrap();

        // hlexists / hlID see the defined + linked groups.
        assert_eq!(run("echo hlexists('Normal')").trim(), "1");
        assert_eq!(run("echo hlexists('Comment')").trim(), "1");
        assert_eq!(run("echo hlID('Normal')").trim(), "1");

        // synIDattr reads colours (gui by default) and follows links.
        assert_eq!(
            run("echo synIDattr(hlID('Normal'), 'fg')").trim(),
            "#d0d0d0"
        );
        assert_eq!(
            run("echo synIDattr(hlID('Normal'), 'fg', 'cterm')").trim(),
            "252"
        );
        assert_eq!(run("echo synIDattr(hlID('Normal'), 'bold')").trim(), "1");
        // Comment links to Normal → inherits its foreground.
        assert_eq!(
            run("echo synIDattr(hlID('Comment'), 'fg')").trim(),
            "#d0d0d0"
        );

        // The host hook saw each raw definition.
        SEEN.with(|s| {
            assert_eq!(
                s.borrow().as_slice(),
                &[
                    "Normal ctermfg=252 guifg=#d0d0d0 guibg=#1c1c1c gui=bold".to_string(),
                    "link Comment Normal".to_string(),
                ]
            )
        });
        HIGHLIGHT_HOST_HOOK.with(|h| *h.borrow_mut() = None);
    }

    /// `source_tolerant` keeps sourcing past a statement that fails to parse OR
    /// errors at run time — the good statements on either side still take effect.
    #[test]
    fn source_tolerant_continues_past_errors() {
        // Line 2 is an unterminated string (parse error); line 3 calls an
        // undefined function (run-time error). The `:let`s on 1 and 4 must run.
        let (ran, skipped) = source_tolerant(
            "let g:sta = 10\nlet bad = \"oops\ncall NoSuchFunc_xyz()\nlet g:stb = 20\n",
        );
        assert_eq!(run("echo g:sta").trim(), "10");
        assert_eq!(run("echo g:stb").trim(), "20");
        assert!(ran >= 2 && skipped >= 1, "ran={ran} skipped={skipped}");
    }

    /// `:colorscheme {name}` records `g:colors_name`, sources the matching
    /// `colors/{name}.vim` from a host-registered dir (firing its `:highlight`
    /// commands), then fires the colorscheme host hook with the name.
    #[test]
    fn colorscheme_sources_file_and_fires_hook() {
        use std::cell::RefCell;
        use std::io::Write;
        thread_local! { static APPLIED: RefCell<Option<String>> = const { RefCell::new(None) }; }
        APPLIED.with(|s| *s.borrow_mut() = None);
        crate::ported::eval::funcs::HL_GROUPS.with(|r| *r.borrow_mut() = Default::default());

        // A temp runtime dir holding colors/acme.vim.
        let dir = std::env::temp_dir().join(format!("vimlrs-colo-{}", std::process::id()));
        let colors = dir.join("colors");
        std::fs::create_dir_all(&colors).unwrap();
        let mut f = std::fs::File::create(colors.join("acme.vim")).unwrap();
        writeln!(f, "highlight Normal guifg=#abcdef guibg=#111111").unwrap();
        writeln!(f, "hi Comment guifg=#00ff00").unwrap();
        drop(f);

        add_colorscheme_dir(dir.clone());
        install_colorscheme_hook(Box::new(|name: &str| {
            APPLIED.with(|s| *s.borrow_mut() = Some(name.to_string()))
        }));

        eval_source("colorscheme acme").unwrap();

        // g:colors_name recorded, groups from the sourced file defined, hook fired
        // AFTER sourcing (so the host sees the fully-populated registry).
        assert_eq!(run("echo g:colors_name").trim(), "acme");
        assert_eq!(
            run("echo synIDattr(hlID('Normal'), 'fg')").trim(),
            "#abcdef"
        );
        assert_eq!(
            run("echo synIDattr(hlID('Comment'), 'fg')").trim(),
            "#00ff00"
        );
        APPLIED.with(|s| assert_eq!(s.borrow().as_deref(), Some("acme")));

        COLORSCHEME_HOST_HOOK.with(|h| *h.borrow_mut() = None);
        COLORSCHEME_DIRS.with(|d| d.borrow_mut().clear());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `:syntax` and `:filetype` parse (so real vimrc files load) and forward
    /// their args to the host hooks; standalone they are otherwise no-ops.
    #[test]
    fn syntax_and_filetype_forward_to_host() {
        use std::cell::RefCell;
        thread_local! {
            static SYN: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
            static FT: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
        }
        SYN.with(|s| s.borrow_mut().clear());
        FT.with(|s| s.borrow_mut().clear());
        install_syntax_hook(Box::new(|a: &str| {
            SYN.with(|s| s.borrow_mut().push(a.to_string()))
        }));
        install_filetype_hook(Box::new(|a: &str| {
            FT.with(|s| s.borrow_mut().push(a.to_string()))
        }));

        // These lines must parse and run without error (the point of the port).
        eval_source("syntax on").unwrap();
        eval_source("syntax enable").unwrap();
        eval_source("filetype plugin indent on").unwrap();

        SYN.with(|s| {
            assert_eq!(
                s.borrow().as_slice(),
                &["on".to_string(), "enable".to_string()]
            )
        });
        FT.with(|s| assert_eq!(s.borrow().as_slice(), &["plugin indent on".to_string()]));

        SYNTAX_HOST_HOOK.with(|h| *h.borrow_mut() = None);
        FILETYPE_HOST_HOOK.with(|h| *h.borrow_mut() = None);
    }

    /// Proof that a vimlrs numeric loop runs on fusevm's tracing JIT: a
    /// function with a constant-bound integer `while` loop lowers to a
    /// CallBuiltin-free native loop body (slots + compare + arith + jumps), and
    /// fusevm records and compiles a trace for it.
    #[test]
    fn numeric_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! Count()\n  let i = 0\n  while i < 1000\n    let i = i + 1\n  endwhile\n  return i\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "Count")
            .unwrap()
            .chunk
            .clone();

        // The loop lowers to native slot/compare/arith ops.
        assert!(
            chunk.ops.iter().any(|o| matches!(o, Op::GetSlot(_))),
            "slotted reads"
        );
        assert!(
            chunk.ops.iter().any(|o| matches!(o, Op::SetSlot(_))),
            "slotted writes"
        );
        assert!(
            chunk.ops.iter().any(|o| matches!(o, Op::NumLt)),
            "native compare"
        );
        assert!(chunk.ops.iter().any(|o| matches!(o, Op::Add)), "native add");

        // The loop body (loop header .. backedge) is CallBuiltin-free → trace-eligible.
        let backedge = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::Jump(t) | Op::JumpIfTrue(t) | Op::JumpIfFalse(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        let (header, back) = backedge;
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        assert!(
            matches!(chunk.ops[back], Op::JumpIfTrue(t) if t == header),
            "loop closes with a conditional backward branch to the header"
        );

        // Drive the native loop hot in a single run (1000 backedges >> the
        // threshold of 50) and confirm fusevm records and compiles a trace for
        // it — vimlrs numeric loops execute as native machine code.
        let mut vm = VM::new(chunk.clone());
        install(&mut vm); // registers VIML_SET_RETURN + enables the JIT
        while vm.frames.last().unwrap().slots.is_empty() {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the native loop at header {header}"
        );
    }

    /// Proof that the idiomatic `for i in range(N)` loop runs on the tracing
    /// JIT: it compiles to a native integer counter loop (no list is built),
    /// and fusevm records and compiles a trace for it.
    #[test]
    fn range_for_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! S()\n  let s = 0\n  for i in range(1000)\n    let s = s + i\n  endfor\n  return s\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "S")
            .unwrap()
            .chunk
            .clone();

        // No list materialization — range() never calls VIML_FN_RANGE/VIML_INDEX.
        assert!(
            !chunk.ops.iter().any(|o| matches!(o, Op::CallBuiltin(id, _)
                if *id == VIML_FN_RANGE || *id == VIML_INDEX || *id == VIML_FN_LEN)),
            "range-for must not build a list"
        );
        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "range-for loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the native range-for loop"
        );
    }

    /// Proof that a SCRIPT-LEVEL (top-level, no function) numeric loop runs on
    /// the tracing JIT — the common shape of real `.vim` scripts.
    #[test]
    fn script_level_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let s = 0\nfor i in range(1000)\n  let s = s + i\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "script-level loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 3 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the script-level loop"
        );
    }

    /// End-to-end proof: a real script run through the SAME path as
    /// `vimlrs script.vim` (`run_chunk` → `install` → `run`, no manual slot
    /// pre-sizing) JIT-compiles its hot loop. This is the actual runtime path,
    /// not a hand-built harness.
    #[test]
    fn real_run_path_jit_compiles_hot_loop() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let s = 0\nfor i in range(2000)\n  let s = s + i\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let header = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(*t),
                _ => None,
            })
            .expect("loop backedge");

        // EXACTLY what the CLI does for a script: run_chunk installs builtins,
        // enables the JIT, and runs. No ensure_slots — `let s = 0` grows them.
        run_chunk(chunk.clone());

        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "the real `vimlrs script.vim` path must JIT-compile the hot loop"
        );
    }

    /// Proof that a FLOAT accumulator loop also trace-JITs (native `fadd` over a
    /// Float slot; int counter + float accumulator in the same trace).
    #[test]
    fn float_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let x = 0.0\nfor i in range(1000)\n  let x = x + 0.5\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let header = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(*t),
                _ => None,
            })
            .expect("loop backedge");
        run_chunk(chunk.clone());
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the native float loop"
        );
    }

    /// Proof that a loop with a COMPOUND condition (`&&`/`||` of native
    /// comparisons) still trace-JITs — short-circuit lowering stays
    /// CallBuiltin-free.
    #[test]
    fn compound_condition_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let i = 0\nlet s = 0\nwhile i < 5000 && s < 1000000000\n  let s = s + i\n  let i = i + 1\nendwhile";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let header = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(*t),
                _ => None,
            })
            .expect("loop backedge");
        run_chunk(chunk.clone());
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the compound-condition loop"
        );
    }

    /// Proof that a hot loop in a function that ALSO calls another function
    /// still trace-JITs: a callee can't see this function's `l:` locals, so the
    /// call no longer bails slotting (only at script scope, where bare = `g:`).
    #[test]
    fn loop_with_sibling_call_traces_in_function() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! Helper()\n  return 99\nendfunction\nfunction! F()\n  let s = 0\n  for i in range(1000)\n    let s = s + i\n  endfor\n  let x = Helper()\n  return s + x\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "F")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        // The loop body is CallBuiltin-free even though the chunk calls Helper().
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "loop body must be CallBuiltin-free despite the sibling call, got {:?}",
            &chunk.ops[header..=back]
        );
        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the loop despite the sibling call"
        );
    }

    /// Proof that `for i in range(<dynamic>)` trace-JITs: the bound need not be a
    /// compile-time integer. `range(a:n)` hoists `a:n` once, coerced with
    /// `tv_get_number` (`VIML_TONUMBER`) in the prologue, so the loop body is
    /// native and fusevm compiles a trace. Driven through the real call path.
    #[test]
    fn dynamic_range_bound_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! F(n)\n  let s = 0\n  for i in range(a:n)\n    let s += i\n  endfor\n  return s\nendfunction\ncall F(3000)";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "F")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        // The bound coercion is in the prologue; the loop body is native.
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::NumLt)),
            "native counter compare"
        );
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "dynamic-range loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        // Drive the function hot through the actual call path (a:n = 3000).
        run_compiled(prog);
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the dynamic-range loop"
        );
    }

    /// Proof that a bit-manipulation loop trace-JITs: `and()`/`or()`/`xor()`/
    /// `invert()` of integer args lower to native `Op::BitAnd`/`BitOr`/`BitXor`/
    /// `BitNot` (fusevm lowers all of these), so the loop body is CallBuiltin-free.
    #[test]
    fn bitwise_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! H()\n  let h = 0\n  for i in range(2000)\n    let h = xor(h, i)\n    let h = and(h, 65535)\n  endfor\n  return h\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "H")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::BitXor))
                && chunk.ops[header..=back]
                    .iter()
                    .any(|o| matches!(o, Op::BitAnd)),
            "loop body should use native bitwise ops"
        );
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "bitwise loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the bitwise loop"
        );
    }

    /// Proof that a numeric ternary in a loop trace-JITs: the `?:` test lowers
    /// through `cond()` (native compare), and a ternary with numeric branches is
    /// itself treated as a Number, so the enclosing `+=` stays native.
    #[test]
    fn ternary_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! F()\n  let s = 0\n  for i in range(2000)\n    let s += i % 2 == 0 ? i : 0\n  endfor\n  return s\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "F")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "ternary loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the ternary loop"
        );
    }

    /// Proof that a value-position comparison in a loop trace-JITs: `i > 500`
    /// lowers to a native compare reified to Number 0/1 with a branch, and a
    /// comparison counts as an integer, so `let s += i > 500` stays native.
    #[test]
    fn value_compare_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! F()\n  let s = 0\n  for i in range(2000)\n    let s += i > 500\n  endfor\n  return s\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "F")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::NumGt)),
            "value-position compare should use a native compare op"
        );
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "value-compare loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the value-compare loop"
        );
    }

    /// Proof that logical-not of an integer in a loop trace-JITs: `!x` lowers to
    /// a native `x == 0` reified to Number 0/1, so `let s += !(i % 2)` stays native.
    #[test]
    fn logical_not_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! F()\n  let s = 0\n  for i in range(2000)\n    let s += !(i % 2)\n  endfor\n  return s\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "F")
            .unwrap()
            .chunk
            .clone();

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "logical-not loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the logical-not loop"
        );
    }

    /// Proof that a loop using integer `%` (e.g. `if i % 2 == 0`) trace-JITs —
    /// native `Op::Mod` (identical to VimL's `num_modulus` for ints).
    #[test]
    fn modulo_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src =
            "let s = 0\nfor i in range(5000)\n  if i % 2 == 0\n    let s = s + i\n  endif\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::Mod)),
            "loop body should use native Op::Mod"
        );
        run_chunk(chunk.clone());
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the modulo loop"
        );
    }

    /// Proof that numeric negation lowers to native `Op::Negate` and keeps a
    /// loop trace-JIT-able.
    #[test]
    fn negate_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let s = 0\nfor i in range(2000)\n  let s = s + -i\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::Negate)),
            "loop body should use native Op::Negate"
        );
        run_chunk(chunk.clone());
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the negate loop"
        );
    }

    /// Proof that explicit `l:`-scoped references in a function trace-JIT.
    /// In a legacy function `l:name` IS bare `name` (same slot), so a loop using
    /// `l:` refs lowers to the same native slot ops and fusevm compiles a trace.
    #[test]
    fn local_ref_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "function! S()\n  let l:s = 0\n  for l:i in range(2000)\n    let l:s += l:i\n  endfor\n  return l:s\nendfunction";
        let prog = compile_program(&parse_program(src).unwrap()).unwrap();
        let chunk = prog
            .funcs
            .iter()
            .find(|f| f.name == "S")
            .unwrap()
            .chunk
            .clone();

        // Both the accumulator (`l:s`) and the induction var (`l:i`) are slotted.
        assert!(
            chunk.ops.iter().any(|o| matches!(o, Op::GetSlot(_))),
            "slotted reads"
        );
        assert!(
            chunk.ops.iter().any(|o| matches!(o, Op::SetSlot(_))),
            "slotted writes"
        );

        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            !chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "l: loop body must be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );

        let mut vm = VM::new(chunk.clone());
        install(&mut vm);
        while vm.frames.last().unwrap().slots.len() < 2 {
            vm.frames
                .last_mut()
                .unwrap()
                .slots
                .push(fusevm::Value::Int(0));
        }
        let _ = vm.run();
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the l:-ref loop"
        );
    }

    /// Proof that a compound-assignment accumulator (`let s += i`) trace-JITs.
    /// `op=` desugars to `s = s + i`, the same store path as the plain form, so
    /// the hot loop body stays CallBuiltin-free and fusevm compiles a trace.
    #[test]
    fn compound_add_loop_traces_on_jit() {
        use crate::compile_viml::compile_program;
        use crate::viml_parser::parse_program;
        use fusevm::Op;

        let src = "let s = 0\nfor i in range(2000)\n  let s += i\nendfor";
        let chunk = compile_program(&parse_program(src).unwrap()).unwrap().main;
        let (header, back) = chunk
            .ops
            .iter()
            .enumerate()
            .find_map(|(i, o)| match o {
                Op::JumpIfTrue(t) if *t < i => Some(((*t), i)),
                _ => None,
            })
            .expect("loop backedge");
        assert!(
            chunk.ops[header..=back]
                .iter()
                .any(|o| matches!(o, Op::Add))
                && !chunk.ops[header..=back]
                    .iter()
                    .any(|o| matches!(o, Op::CallBuiltin(..) | Op::Extended(..))),
            "compound-add loop body must use native Op::Add and be CallBuiltin-free, got {:?}",
            &chunk.ops[header..=back]
        );
        run_chunk(chunk.clone());
        assert!(
            fusevm::JitCompiler::new().trace_is_compiled(&chunk, header),
            "fusevm must compile a trace for the `+=` loop"
        );
    }

    /// Proof that vimlrs bytecode actually runs on fusevm's Cranelift JIT:
    /// an integer expression lowers to a CallBuiltin-free native-op chunk, and
    /// fusevm block-JIT-compiles it to machine code after the warm-up threshold.
    #[test]
    fn integer_expr_runs_on_jit() {
        use crate::compile_viml::compile_expr_only;
        use crate::viml_parser::parse_expr;

        let e = parse_expr("2 + 3 * 4 - 1").unwrap();
        let chunk = compile_expr_only(&e).unwrap();

        // 1. The chunk is fully native — no builtin/extended dispatch, so it is
        //    eligible for every JIT tier.
        assert!(
            !chunk
                .ops
                .iter()
                .any(|op| matches!(op, fusevm::Op::CallBuiltin(..) | fusevm::Op::Extended(..))),
            "integer expr must lower to native ops only, got {:?}",
            chunk.ops
        );

        // 2. It computes the right value, and fusevm block-JIT compiles it after
        //    the 10-invocation warm-up (install() enables the JIT).
        let mut compiled = false;
        let mut last = Value::Undef;
        for _ in 0..15 {
            let mut vm = VM::new(chunk.clone());
            install(&mut vm);
            if let fusevm::VMResult::Ok(v) = vm.run() {
                last = v;
            }
            if fusevm::JitCompiler::new().block_jit_is_compiled(&chunk) {
                compiled = true;
            }
        }
        assert_eq!(last, Value::Int(13), "2 + 3*4 - 1 = 13");
        assert!(compiled, "fusevm must block-JIT-compile the native chunk");
    }

    #[test]
    fn echo_arithmetic() {
        assert_eq!(run("echo 1 + 2 * 3"), "7\n");
        assert_eq!(run("echo 10 / 3"), "3\n");
        assert_eq!(run("echo 10 % 3"), "1\n");
    }

    #[test]
    fn echo_float_and_concat() {
        assert_eq!(run("echo 1.5 + 1.5"), "3.0\n");
        assert_eq!(run(r#"echo "a" . "b" . 1"#), "ab1\n");
    }

    #[test]
    fn echo_collections() {
        assert_eq!(run("echo [1, 2, 3]"), "[1, 2, 3]\n");
        assert_eq!(run("echo ['a', 'b']"), "['a', 'b']\n");
        assert_eq!(run("echo {'k': 1}"), "{'k': 1}\n");
    }

    #[test]
    fn variables_and_logic() {
        assert_eq!(run("let x = 5\necho x + 1"), "6\n");
        assert_eq!(run("echo 1 == 1"), "1\n");
        assert_eq!(run(r#"echo 1 == "1""#), "1\n"); // Vim number/string coercion
        assert_eq!(run("echo 2 > 1 && 1 < 3"), "1\n");
        assert_eq!(run("echo 0 || 5"), "1\n");
    }

    #[test]
    fn scopes_and_options() {
        // s: script-local, visible inside functions.
        assert_eq!(
            run("let s:n = 100\nfunction G()\nreturn s:n\nendfunction\necho G()"),
            "100\n"
        );
        // b:/w:/t: scopes.
        assert_eq!(run("let b:x = 'B'\nlet w:y = 'W'\necho b:x . w:y"), "BW\n");
        // &opt + :set (default, set, abbreviation-off, number).
        assert_eq!(run("echo &ignorecase"), "0\n");
        assert_eq!(run("set ignorecase\necho &ic"), "1\n");
        assert_eq!(run("set ignorecase\nset noic\necho &ignorecase"), "0\n");
        assert_eq!(run("set tabstop=4\necho &tabstop"), "4\n");
        // 'ignorecase' flips =~ case sensitivity.
        assert_eq!(run("echo 'FOO' =~ 'foo'"), "0\n");
        assert_eq!(run("set ignorecase\necho 'FOO' =~ 'foo'"), "1\n");
    }

    #[test]
    fn statement_features() {
        // :execute builds and runs a command line.
        assert_eq!(run("let g:n = 5\nexecute 'echo' 'g:n * 2'"), "10\n");
        assert_eq!(run("execute 'let g:z = ' . (3 * 7)\necho g:z"), "21\n");
        // :let list-unpack (+ ;rest).
        assert_eq!(
            run("let [g:a, g:b] = [10, 20]\necho g:a . ',' . g:b"),
            "10,20\n"
        );
        assert_eq!(run("let [g:x; g:r] = [1, 2, 3]\necho g:r"), "[2, 3]\n");
        // :for destructuring over a list of pairs and over items().
        assert_eq!(
            run("for [x, y] in [[1, 2], [3, 4]]\necho x + y\nendfor"),
            "3\n7\n"
        );
    }

    #[test]
    fn compound_assignment() {
        // op= for every operator (ex_let's tv_op).
        assert_eq!(run("let a = 10\nlet a += 3\necho a"), "13\n");
        assert_eq!(run("let a = 10\nlet a -= 3\necho a"), "7\n");
        assert_eq!(run("let a = 10\nlet a *= 4\necho a"), "40\n");
        assert_eq!(run("let a = 20\nlet a /= 6\necho a"), "3\n"); // integer division
        assert_eq!(run("let a = 20\nlet a %= 6\necho a"), "2\n");
        assert_eq!(run("let s = 'foo'\nlet s .= 'bar'\necho s"), "foobar\n");
        // Float accumulation.
        assert_eq!(run("let f = 1.5\nlet f += 0.25\necho f"), "1.75\n");
        // Tight spacing (no blanks around `+=`).
        assert_eq!(run("let n=1\nlet n+=41\necho n"), "42\n");
        // Accumulation inside a loop — the common idiom that was silently a no-op.
        assert_eq!(
            run("let s = 0\nfor i in range(101)\n  let s += i\nendfor\necho s"),
            "5050\n"
        );
        // Scoped target.
        assert_eq!(run("let g:c = 5\nlet g:c += 10\necho g:c"), "15\n");
    }

    #[test]
    fn local_scope_refs() {
        // In a function, l:x is the SAME variable as bare x (both = the slot).
        assert_eq!(
            run("function! F()\nlet x = 1\nlet l:x += 2\nreturn l:x\nendfunction\necho F()"),
            "3\n"
        );
        assert_eq!(
            run("function! S()\nlet l:t = 0\nfor l:i in range(101)\nlet l:t += l:i\nendfor\nreturn l:t\nendfunction\necho S()"),
            "5050\n"
        );
        // Soundness: g: in a function is a DISTINCT store from bare (l:) — the
        // l:-slot optimization must not alias it.
        assert_eq!(
            run("let g:n = 100\nfunction! F()\nlet n = 1\nreturn g:n\nendfunction\necho F()"),
            "100\n"
        );
        // ...and writing bare n must not leak into g:n.
        assert_eq!(
            run("let g:n = 100\nfunction! F()\nlet n = 7\nendfunction\ncall F()\necho g:n"),
            "100\n"
        );
    }

    #[test]
    fn dynamic_range_bounds() {
        // `range()` bound from a parameter, a string (coerced), an expression,
        // and a two-arg inclusive range — all match Vim's tv_get_number coercion.
        assert_eq!(
            run("function! F(n)\nlet s=0\nfor i in range(a:n)\nlet s+=i\nendfor\nreturn s\nendfunction\necho F(101)"),
            "5050\n"
        );
        assert_eq!(
            run("function! F(n)\nlet s=0\nfor i in range(a:n)\nlet s+=i\nendfor\nreturn s\nendfunction\necho F('101')"),
            "5050\n"
        );
        assert_eq!(
            run("function! G(n)\nlet s=0\nfor i in range(2, a:n)\nlet s+=i\nendfor\nreturn s\nendfunction\necho G(10)"),
            "54\n"
        );
        assert_eq!(
            run("function! H(xs)\nlet s=0\nfor i in range(len(a:xs))\nlet s+=i\nendfor\nreturn s\nendfunction\necho H([5, 6, 7, 8])"),
            "6\n"
        );
    }

    #[test]
    fn strftime_builtin() {
        // TZ-independent: literal text passes through; `%%` → `%`.
        assert_eq!(run("echo strftime('hello world')"), "hello world\n");
        assert_eq!(run("echo strftime('100%%')"), "100%\n");
        // Format specifiers expand: `%Y-%m-%d` is always 10 chars (the exact date
        // is TZ-dependent, but its width is not), proving strftime() ran.
        assert_eq!(run("echo len(strftime('%Y-%m-%d', 0))"), "10\n");
    }

    #[test]
    fn strptime_builtin() {
        // Round-trip is TZ-independent: parse-local then format-local cancels the
        // zone offset, recovering the input date.
        assert_eq!(
            run("echo strftime('%Y-%m-%d', strptime('%Y-%m-%d %H:%M', '2020-06-15 12:00'))"),
            "2020-06-15\n"
        );
        // Unparseable input → 0 (strptime fails / mktime == -1).
        assert_eq!(run("echo strptime('%Y', 'not-a-year')"), "0\n");
    }

    #[test]
    fn logical_not_native() {
        // `!x` is VimL's logical not (Number 0/1), incl. double negation.
        assert_eq!(run("echo !0"), "1\n");
        assert_eq!(run("echo !5"), "0\n");
        assert_eq!(run("echo !(3 % 2)"), "0\n");
        assert_eq!(run("echo !!7"), "1\n");
        // In a loop (the native-lowered path): count even i in 0..9 → 5.
        assert_eq!(
            run("let s=0\nfor i in range(10)\nlet s += !(i % 2)\nendfor\necho s"),
            "5\n"
        );
    }

    #[test]
    fn value_position_compare() {
        // A comparison in value position yields VimL's Number 0/1 (verified vs nvim).
        assert_eq!(run("echo 5 > 3"), "1\n");
        assert_eq!(run("echo 3 > 5"), "0\n");
        assert_eq!(run("echo 2 <= 2"), "1\n");
        // Mixed Number/String still coerces via the builtin path (not native).
        assert_eq!(run("echo 1 == '1'"), "1\n");
        // Counting via a value-position compare in a loop (the native path).
        assert_eq!(
            run("let s=0\nfor i in range(10)\nlet s += i >= 5\nendfor\necho s"),
            "5\n" // i = 5,6,7,8,9
        );
    }

    #[test]
    fn ternary_native() {
        // Native-lowered ternary preserves VimL truthiness (incl. the string
        // truthiness fallback) and selects the right branch.
        assert_eq!(run("echo 5 > 3 ? 100 : 200"), "100\n");
        assert_eq!(run("echo 5 < 3 ? 100 : 200"), "200\n");
        assert_eq!(run("echo 'abc' ? 1 : 2"), "2\n"); // non-numeric string is falsy
        assert_eq!(run("echo '5' ? 1 : 2"), "1\n"); // numeric string is truthy
                                                    // Accumulating ternary in a loop (the JIT-lowered path).
        assert_eq!(
            run("let s=0\nfor i in range(10)\nlet s += i % 2 == 0 ? i : 0\nendfor\necho s"),
            "20\n" // 0+2+4+6+8
        );
    }

    #[test]
    fn flatten_and_flattennew() {
        // maxdepth-limited flatten (verified vs nvim).
        assert_eq!(run("echo flatten([1, [2, [3]]], 1)"), "[1, 2, [3]]\n");
        // flatten() mutates its argument in place...
        assert_eq!(
            run("let k=[1,[2,[3]]]\ncall flatten(k)\necho k"),
            "[1, 2, 3]\n"
        );
        // ...flattennew() returns a flattened copy, leaving the source intact.
        assert_eq!(
            run("let l=[1,[2,[3]]]\nlet m=flattennew(l)\necho l\necho m"),
            "[1, [2, [3]]]\n[1, 2, 3]\n"
        );
    }

    #[test]
    fn blob_builtins() {
        // list2blob/blob2list round-trip + native rendering (verified vs nvim).
        assert_eq!(
            run("echo blob2list(list2blob([10, 20, 30]))"),
            "[10, 20, 30]\n"
        );
        assert_eq!(run("echo list2blob([171, 205])"), "0zABCD\n");
        // Blob subscript → a byte; negative index from the end.
        assert_eq!(run("echo list2blob([10, 20, 30, 40])[2]"), "30\n");
        assert_eq!(run("echo list2blob([10, 20, 30, 40])[-1]"), "40\n");
        // Blob slice → a sub-blob (inclusive bounds).
        assert_eq!(
            run("echo blob2list(list2blob([1, 2, 3, 4, 5])[1:3])"),
            "[2, 3, 4]\n"
        );
    }

    #[test]
    fn count_builtin() {
        // String/List/Dict + case-insensitivity + start index (verified vs nvim).
        assert_eq!(run("echo count([1, 2, 2, 3], 2)"), "2\n");
        assert_eq!(run("echo count('banana', 'a')"), "3\n");
        assert_eq!(run("echo count({'a': 1, 'b': 2, 'c': 1}, 1)"), "2\n");
        assert_eq!(run("echo count([1, 2, 2, 3, 2], 2, 0, 2)"), "2\n");
        assert_eq!(run("echo count('aaa', 'aa')"), "1\n"); // non-overlapping
    }

    #[test]
    fn extend_builtins() {
        // List: append, and insert at an index (verified vs nvim).
        assert_eq!(
            run("let l=[1,2,3]\ncall extend(l,[4,5])\necho l"),
            "[1, 2, 3, 4, 5]\n"
        );
        assert_eq!(
            run("let m=[1,2,3]\ncall extend(m,[9],1)\necho m"),
            "[1, 9, 2, 3]\n"
        );
        // Dict: keep (don't overwrite) vs force (default, overwrite).
        assert_eq!(
            run("let d={'a':1,'b':2}\ncall extend(d,{'b':20,'c':3},'keep')\necho d"),
            "{'a': 1, 'b': 2, 'c': 3}\n"
        );
        assert_eq!(
            run("let e={'a':1}\ncall extend(e,{'a':99})\necho e"),
            "{'a': 99}\n"
        );
        // extendnew returns a new value, leaving the source intact.
        assert_eq!(
            run("let n=[1,2]\nlet p=extendnew(n,[3])\necho n\necho p"),
            "[1, 2]\n[1, 2, 3]\n"
        );
    }

    #[test]
    fn index_assignment() {
        // Dict key set (bracket + member), and overwrite — verified vs nvim.
        assert_eq!(
            run("let d={'a':1}\nlet d['b']=2\nlet d.c=3\nlet d['a']=99\necho d"),
            "{'a': 99, 'b': 2, 'c': 3}\n"
        );
        // List element set, including a negative index.
        assert_eq!(
            run("let l=[1,2,3]\nlet l[1]=20\nlet l[-1]=30\necho l"),
            "[1, 20, 30]\n"
        );
        // Nested subscript assignment (shared-Rc propagation through containers).
        assert_eq!(
            run("let d={'a':{'b':1},'l':[10,20]}\nlet d['a']['b']=99\nlet d['l'][0]=100\necho [d['a']['b'], d['l'][0]]"),
            "[99, 100]\n"
        );
        // Compound index-assign (desugars to d[k] = d[k] op rhs).
        assert_eq!(run("let d={'n':5}\nlet d['n']+=10\necho d['n']"), "15\n");
        // A dict-set fires a registered watcher (the add side).
        assert_eq!(
            run("let g:log=[]\nfunction! Cb(d,k,ch)\ncall add(g:log,a:k)\nendfunction\nlet w={}\ncall dictwatcheradd(w,'x',function('Cb'))\nlet w['x']=5\nlet w['y']=6\necho g:log"),
            "['x']\n"
        );
    }

    #[test]
    fn dictwatcher() {
        // A watcher fires only on a pattern-matched key change (here, remove()).
        assert_eq!(
            run("let g:log=[]\nfunction! Cb(d,k,ch)\ncall add(g:log,a:k)\nendfunction\nlet d={'a':1,'b':2}\ncall dictwatcheradd(d,'a',function('Cb'))\ncall remove(d,'a')\ncall remove(d,'b')\necho g:log"),
            "['a']\n"
        );
        // dictwatcherdel unregisters; a trailing '*' is a prefix match.
        assert_eq!(
            run("let g:log=[]\nfunction! Cb(d,k,ch)\ncall add(g:log,a:k)\nendfunction\nlet d={'foo':1}\ncall dictwatcheradd(d,'f*',function('Cb'))\ncall dictwatcherdel(d,'f*',function('Cb'))\ncall remove(d,'foo')\necho g:log"),
            "[]\n"
        );
    }

    #[test]
    fn reduce_builtin() {
        // List fold (no initial uses the first element; with initial).
        assert_eq!(
            run("function! Add(a,b)\nreturn a:a+a:b\nendfunction\necho reduce([1,2,3,4], function('Add'))"),
            "10\n"
        );
        assert_eq!(
            run("function! Add(a,b)\nreturn a:a+a:b\nendfunction\necho reduce([1,2,3,4], function('Add'), 100)"),
            "110\n"
        );
        // String fold and Blob fold.
        assert_eq!(
            run("function! Cat(a,b)\nreturn a:a . a:b\nendfunction\necho reduce('abc', function('Cat'), '>')"),
            ">abc\n"
        );
        assert_eq!(
            run("function! Add(a,b)\nreturn a:a+a:b\nendfunction\necho reduce(list2blob([1,2,3]), function('Add'), 0)"),
            "6\n"
        );
    }

    #[test]
    fn matchstrlist_fnameescape_shiftwidth() {
        // matchstrlist — content verified against nvim (key order is vimlrs's
        // deterministic IndexMap order; nvim's hashtab order differs cosmetically).
        assert_eq!(
            run("echo matchstrlist(['a1','b2','cc'], '\\d')"),
            "[{'idx': 0, 'byteidx': 1, 'text': '1'}, {'idx': 1, 'byteidx': 1, 'text': '2'}]\n"
        );
        // submatches padded to the 9 \1..\9 backrefs.
        assert_eq!(
            run("echo matchstrlist(['foobar'], '\\(o\\+\\)', {'submatches': v:true})[0]['submatches']"),
            "['oo', '', '', '', '', '', '', '', '']\n"
        );
        // fnameescape (verified vs nvim).
        assert_eq!(run("echo fnameescape('foo bar')"), "foo\\ bar\n");
        assert_eq!(run("echo fnameescape('a%b#c')"), "a\\%b\\#c\n");
        // shiftwidth: 'shiftwidth', or 'tabstop' when sw==0.
        assert_eq!(run("echo shiftwidth()"), "8\n");
        assert_eq!(run("set shiftwidth=4\necho shiftwidth()"), "4\n");
        assert_eq!(
            run("set shiftwidth=0\nset tabstop=2\necho shiftwidth()"),
            "2\n"
        );
    }

    #[test]
    fn editor_absent_builtins() {
        // A standalone interpreter has no editor UI / GUI / server (verified vs nvim).
        assert_eq!(run("echo visualmode()"), "\n");
        assert_eq!(run("echo pumvisible()"), "0\n");
        assert_eq!(run("echo wildmenumode()"), "0\n");
        assert_eq!(run("echo did_filetype()"), "0\n");
        assert_eq!(run("echo eventhandler()"), "0\n");
        assert_eq!(run("echo hlexists('Foo')"), "0\n");
        assert_eq!(run("echo windowsversion()"), "\n");
        assert_eq!(run("echo getfontname()"), "\n");
        assert_eq!(run("echo foreground()"), "0\n");
        assert_eq!(run("echo pum_getpos()"), "{}\n");
        assert_eq!(run("echo serverlist()"), "[]\n");
        assert_eq!(run("echo mode()"), "n\n");
    }

    #[test]
    fn registers() {
        // setreg/getreg/getregtype (values verified against `nvim --clean`).
        assert_eq!(run("call setreg('a','hello')\necho getreg('a')"), "hello\n");
        assert_eq!(run("call setreg('a','hello')\necho getregtype('a')"), "v\n");
        assert_eq!(
            run("call setreg('b',['x','y','z'])\necho getreg('b',1,1)"),
            "['x', 'y', 'z']\n"
        );
        assert_eq!(
            run("call setreg('b',['x','y'])\necho getregtype('b')"),
            "V\n"
        );
        // charwise append continues the last line.
        assert_eq!(
            run("call setreg('a','hello')\ncall setreg('a',' world','a')\necho getreg('a')"),
            "hello world\n"
        );
        // dict form + getreginfo (unset → {}); bracket access (the `.member`
        // concat ambiguity means tests use ['key']).
        assert_eq!(run("echo getreginfo('z')"), "{}\n");
        assert_eq!(
            run("call setreg('b',['x','y'])\necho getreginfo('b')['regcontents']"),
            "['x', 'y']\n"
        );
        assert_eq!(
            run("call setreg('e',{'regcontents':['p','q'],'regtype':'V'})\necho getreg('e',1,1)\necho getregtype('e')"),
            "['p', 'q']\nV\n"
        );
        // reg_recording/executing/recorded are empty standalone.
        assert_eq!(run("echo reg_recording()"), "\n");
    }

    #[test]
    fn misc_utilities() {
        assert_eq!(run("echo gettext('hello')"), "hello\n");
        // indexof: first item where the expr (v:val/v:key) is true, else -1.
        assert_eq!(run("echo indexof([1,2,3,4], 'v:val > 2')"), "2\n");
        assert_eq!(
            run("echo indexof(['a','bb','ccc'], 'len(v:val) == 2')"),
            "1\n"
        );
        assert_eq!(run("echo indexof([1,2,3], 'v:val > 9')"), "-1\n");
        // id() is non-empty and stable for a container, empty for a scalar.
        assert_eq!(run("let l=[1,2]\necho id(l) == id(l)"), "1\n");
        assert_eq!(run("echo id(5)"), "\n");
        assert_eq!(run("let a=[1]\nlet b=[1]\necho id(a) != id(b)"), "1\n");
        // garbagecollect() is a no-op that returns nothing.
        assert_eq!(run("call garbagecollect()\necho 'ok'"), "ok\n");
    }

    #[test]
    fn fnamemodify_and_glob() {
        // Filename modifiers (verified against `nvim --clean`).
        assert_eq!(
            run("echo fnamemodify('/home/u/file.txt.gz', ':t')"),
            "file.txt.gz\n"
        );
        assert_eq!(
            run("echo fnamemodify('/home/u/file.txt.gz', ':h')"),
            "/home/u\n"
        );
        assert_eq!(
            run("echo fnamemodify('/home/u/file.txt.gz', ':r')"),
            "/home/u/file.txt\n"
        );
        assert_eq!(run("echo fnamemodify('/home/u/file.txt.gz', ':e')"), "gz\n");
        assert_eq!(run("echo fnamemodify('a.b.c', ':e:e')"), "b.c\n");
        assert_eq!(run("echo fnamemodify('a.b.c', ':r:r')"), "a\n");
        assert_eq!(
            run("echo fnamemodify('path/to/this.file.ext', ':e:e')"),
            "file.ext\n"
        );
        assert_eq!(run("echo fnamemodify('foo/bar.txt', ':t:r')"), "bar\n");
        assert_eq!(
            run("echo fnamemodify('foo/bar.txt', ':s?bar?baz?')"),
            "foo/baz.txt\n"
        );
        // glob2regpat (pure string transform).
        assert_eq!(run("echo glob2regpat('*.txt')"), "\\.txt$\n");
        assert_eq!(run("echo glob2regpat('foo?bar')"), "^foo.bar$\n");
        assert_eq!(run("echo glob2regpat('a.b')"), "^a\\.b$\n");
        assert_eq!(run("echo haslocaldir()"), "0\n");
    }

    #[test]
    fn readdir_readblob_filecopy() {
        // Hermetic: build a dir under a tempname(), exercise readdir/readblob/
        // filecopy/readfile, then clean up. Headless-CI-safe.
        let src = "let d=tempname()\ncall mkdir(d)\n\
            call writefile(['AAA'], d.'/a.txt')\n\
            call writefile(['B'], d.'/b.log')\n\
            echo sort(readdir(d))\n\
            echo readdir(d, 'v:val =~ \"txt$\"')\n\
            echo readblob(d.'/a.txt')\n\
            call filecopy(d.'/a.txt', d.'/c.txt')\n\
            echo readfile(d.'/c.txt')\n\
            call delete(d,'rf')";
        assert_eq!(
            run(src),
            "['a.txt', 'b.log']\n['a.txt']\n0z4141410A\n['AAA']\n"
        );
    }

    #[test]
    fn fs_builtins() {
        // Pure path builtins (verified against `nvim --clean`).
        assert_eq!(run("echo isabsolutepath('/usr/bin')"), "1\n");
        assert_eq!(run("echo isabsolutepath('foo/bar')"), "0\n");
        assert_eq!(run("echo simplify('/a/b/../c')"), "/a/c\n");
        assert_eq!(run("echo simplify('a/./b//c')"), "a/b/c\n");
        // writefile → readfile round-trip + delete, through a system temp path
        // (hermetic: tempname() lives under the OS temp dir, fine in headless CI).
        assert_eq!(
            run("let f=tempname()\ncall writefile(['a','b','c'], f)\necho readfile(f)\necho getfsize(f)\ncall delete(f)\necho filereadable(f)"),
            "['a', 'b', 'c']\n6\n0\n"
        );
        // mkdir/isdirectory/delete on a temp directory.
        assert_eq!(
            run("let d=tempname()\necho mkdir(d)\necho isdirectory(d)\necho delete(d,'d')\necho isdirectory(d)"),
            "1\n1\n0\n0\n"
        );
    }

    #[test]
    fn list_range_assign() {
        // `let l[i:j] = list` — values verified against `nvim --clean`.
        assert_eq!(
            run("let l=[1,2,3,4,5]\nlet l[1:3]=[20,30,40]\necho l"),
            "[1, 20, 30, 40, 5]\n"
        );
        // `l[i:]` replaces from i to the end (grows when the source is longer).
        assert_eq!(
            run("let m=[0,0,0,0]\nlet m[1:]=[7,8,9]\necho m"),
            "[0, 7, 8, 9]\n"
        );
        assert_eq!(
            run("let g=[1,2]\nlet g[1:]=[5,6,7,8]\necho g"),
            "[1, 5, 6, 7, 8]\n"
        );
        // `l[:j]` replaces from the start; single-element range; negative index.
        assert_eq!(run("let p=[1,2,3]\nlet p[:1]=[8,9]\necho p"), "[8, 9, 3]\n");
        assert_eq!(
            run("let q=[1,2,3]\nlet q[1:1]=[99]\necho q"),
            "[1, 99, 3]\n"
        );
        assert_eq!(
            run("let l=[1,2,3,4]\nlet l[-2:]=[88,99]\necho l"),
            "[1, 2, 88, 99]\n"
        );
    }

    #[test]
    fn vim_vars() {
        // v: variable store (vimvars[]). Expected values verified against nvim.
        assert_eq!(run("echo v:version"), "801\n");
        assert_eq!(
            run(
                "echo v:t_number v:t_string v:t_func v:t_list v:t_dict v:t_float v:t_bool v:t_blob"
            ),
            "0 1 2 3 4 5 6 10\n"
        );
        assert_eq!(
            run("echo v:numbermax v:numbermin v:numbersize"),
            "9223372036854775807 -9223372036854775808 64\n"
        );
        assert_eq!(run("echo v:maxcol"), "2147483647\n");
        assert_eq!(run("echo v:true v:false v:null"), "v:true v:false v:null\n");
        assert_eq!(run("echo v:searchforward v:hlsearch v:count1"), "1 1 1\n");
        assert_eq!(run("echo type(v:msgpack_types)"), "4\n");
        assert_eq!(run("echo type(v:errors)"), "3\n");
        assert_eq!(run("echo v:register"), "\"\n");
        // Mutable v: var round-trips; read-only v: var declines assignment.
        assert_eq!(run("let v:errmsg = 'boom'\necho v:errmsg"), "boom\n");
        assert_eq!(run("echo v:errmsg"), "\n");
    }

    #[test]
    fn partials() {
        // function() with bound args → a Partial; call() prepends them. Each
        // assertion's expected value was verified against `nvim --clean`.
        let add = "function! Add(a,b)\nreturn a:a+a:b\nendfunction\n";
        let add3 = "function! Add3(x,a,b)\nreturn a:x+a:a+a:b\nendfunction\n";
        // call(partial, args): Add(10, 5).
        assert_eq!(
            run(&format!(
                "{add}let P=function('Add',[10])\necho call(P,[5])"
            )),
            "15\n"
        );
        // type() of a Partial is 2 (Funcref).
        assert_eq!(run(&format!("{add}echo type(function('Add',[10]))")), "2\n");
        // echo / string() render as function('name', [args]).
        assert_eq!(
            run(&format!("{add}echo function('Add',[10])")),
            "function('Add', [10])\n"
        );
        assert_eq!(
            run(&format!("{add}echo string(function('Add',[1,2]))")),
            "function('Add', [1, 2])\n"
        );
        // Partial honored in reduce() — Add3(100, acc, item).
        assert_eq!(
            run(&format!(
                "{add3}echo reduce([1,2,3], function('Add3',[100]), 0)"
            )),
            "306\n"
        );
        // Partial honored in map() — Add3(10, key, val).
        assert_eq!(
            run(&format!("{add3}echo map([1,2,3], function('Add3',[10]))")),
            "[11, 13, 15]\n"
        );
        // func_equal(): same name+args equal; differing args/arity not.
        assert_eq!(
            run(&format!(
                "{add}echo function('Add',[1,2])==function('Add',[1,2])"
            )),
            "1\n"
        );
        assert_eq!(
            run(&format!(
                "{add}echo function('Add',[1,2])==function('Add',[1,3])"
            )),
            "0\n"
        );
        assert_eq!(
            run(&format!("{add}echo function('Add',[1])==function('Add')")),
            "0\n"
        );
    }

    #[test]
    fn map_filter_foreach_mapnew() {
        // List map / filter.
        assert_eq!(run("echo map([1,2,3], 'v:val * 2')"), "[2, 4, 6]\n");
        assert_eq!(run("echo filter([1,2,3,4], 'v:val % 2 == 0')"), "[2, 4]\n");
        // Dict map.
        assert_eq!(
            run("echo map({'a':1,'b':2}, 'v:val + 10')"),
            "{'a': 11, 'b': 12}\n"
        );
        // String map / filter (new — char-by-char).
        assert_eq!(run("echo map('abc', 'toupper(v:val)')"), "ABC\n");
        assert_eq!(run("echo filter('hello', 'v:val != \"l\"')"), "heo\n");
        // Blob map.
        assert_eq!(
            run("echo blob2list(map(list2blob([1,2,3]), 'v:val + 1'))"),
            "[2, 3, 4]\n"
        );
        // mapnew leaves the source intact.
        assert_eq!(
            run("let l=[1,2,3]\nlet m=mapnew(l, 'v:val*10')\necho l\necho m"),
            "[1, 2, 3]\n[10, 20, 30]\n"
        );
        // foreach with a funcref (side effect).
        assert_eq!(
            run("let g:s=0\nfunction! Add(i,x)\nlet g:s+=a:x\nendfunction\ncall foreach([1,2,3,4], function('Add'))\necho g:s"),
            "10\n"
        );
        // map with a funcref.
        assert_eq!(
            run(
                "function! Dbl(k,v)\nreturn a:v*2\nendfunction\necho map([5,6,7], function('Dbl'))"
            ),
            "[10, 12, 14]\n"
        );
    }

    #[test]
    fn sort_and_uniq() {
        // Default (string) vs 'n' numeric vs 'i' ignorecase vs 'f' float.
        assert_eq!(run("echo sort([10,9,2,100])"), "[10, 100, 2, 9]\n");
        assert_eq!(run("echo sort([10,9,2,100], 'n')"), "[2, 9, 10, 100]\n");
        assert_eq!(run("echo sort(['B','a','C'], 'i')"), "['a', 'B', 'C']\n");
        assert_eq!(run("echo sort([3.5,1.2,2.8], 'f')"), "[1.2, 2.8, 3.5]\n");
        // uniq drops adjacent-equal (after sorting).
        assert_eq!(run("echo uniq(sort([3,1,2,2,1,3]))"), "[1, 2, 3]\n");
        // Funcref comparator (sort {func}) via the bridge hook.
        assert_eq!(
            run("function! Desc(a,b)\nreturn a:b - a:a\nendfunction\necho sort([1,5,3,2,4], 'Desc')"),
            "[5, 4, 3, 2, 1]\n"
        );
    }

    #[test]
    fn join_and_list_slice() {
        // join() renders items as `:echo` (nested structurally) — the prior
        // tv_get_string version dropped nested Lists. Verified vs nvim.
        assert_eq!(run("echo join([[1,2],3], '-')"), "[1, 2]-3\n");
        assert_eq!(run("echo join(['a','b','c'])"), "a b c\n");
        assert_eq!(run("echo join([1,2,3], ', ')"), "1, 2, 3\n");
        // List index/slice via the ported tv_list_slice_or_index.
        assert_eq!(run("echo [10,20,30,40][2]"), "30\n");
        assert_eq!(run("echo [10,20,30,40][1:2]"), "[20, 30]\n");
        assert_eq!(run("echo [10,20,30,40][-2:]"), "[30, 40]\n");
        assert_eq!(run("echo [10,20,30,40][1:]"), "[20, 30, 40]\n");
    }

    #[test]
    fn remove_builtin() {
        // List: single index (returns the item), and a range (returns a sub-list).
        assert_eq!(
            run("let l=[1,2,3,4]\necho remove(l, 1)\necho l"),
            "2\n[1, 3, 4]\n"
        );
        assert_eq!(
            run("let m=[10,20,30,40,50]\necho remove(m, 1, 3)\necho m"),
            "[20, 30, 40]\n[10, 50]\n"
        );
        // Dict: by key.
        assert_eq!(
            run("let d={'a':1,'b':2}\necho remove(d, 'a')\necho d"),
            "1\n{'b': 2}\n"
        );
        // Blob: single byte, and a range (returns a sub-blob).
        assert_eq!(
            run("let b=list2blob([1,2,3,4,5])\necho remove(b, 2)\necho blob2list(b)"),
            "3\n[1, 2, 4, 5]\n"
        );
        assert_eq!(
            run("echo blob2list(remove(list2blob([1,2,3,4,5]), 1, 2))"),
            "[2, 3]\n"
        );
    }

    #[test]
    fn sha256_builtin() {
        // FIPS-180-2 test vectors (also bit-exact vs Neovim).
        assert_eq!(
            run("echo sha256('abc')"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n"
        );
        assert_eq!(
            run("echo sha256('')"),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n"
        );
        // > 64 bytes exercises the multi-block loop + length padding.
        assert_eq!(
            run("echo sha256(repeat('a', 200))"),
            "c2a908d98f5df987ade41b5fce213067efbcc21ef2240212a41e54b5e7c28ae5\n"
        );
    }

    #[test]
    fn pathshorten_builtin() {
        // Verified bit-exact against Neovim: each directory shortens to `len`
        // chars (keeping a leading `~`/`.`); the final component is untouched.
        assert_eq!(
            run("echo pathshorten('~/foo/bar/baz.vim')"),
            "~/f/b/baz.vim\n"
        );
        assert_eq!(
            run("echo pathshorten('/usr/local/bin/foo')"),
            "/u/l/b/foo\n"
        );
        assert_eq!(
            run("echo pathshorten('~/.config/nvim/init.vim', 2)"),
            "~/.co/nv/init.vim\n"
        );
        assert_eq!(run("echo pathshorten('noseps')"), "noseps\n");
    }

    #[test]
    fn bitwise_builtins() {
        // and/or/xor/invert — verified bit-exact against Neovim.
        assert_eq!(run("echo and(12, 10)"), "8\n");
        assert_eq!(run("echo or(12, 10)"), "14\n");
        assert_eq!(run("echo xor(12, 10)"), "6\n");
        assert_eq!(run("echo invert(0)"), "-1\n");
        // Nested + a slotted accumulator loop (the native-lowered path).
        assert_eq!(run("echo and(255, xor(170, 85))"), "255\n");
        assert_eq!(
            run("let h=0\nfor i in range(8)\nlet h=xor(h,i)\nendfor\necho h"),
            "0\n"
        );
    }

    #[test]
    fn rand_srand_match_neovim() {
        // Bit-exact against real Neovim (verified with `nvim --headless`):
        // seeded srand/rand are deterministic (xoshiro128** + splitmix32).
        assert_eq!(
            run("echo srand(123)"),
            "[1482537201, 2737842301, 2667502145, 3175280481]\n"
        );
        // rand(seed) advances the 4-number seed list in place, yielding a fixed
        // sequence and leaving the list at the advanced state.
        assert_eq!(
            run("let s = srand(123)\necho rand(s)\necho rand(s)\necho string(s)"),
            "3146710351\n1913850085\n[3045381587, 2236591504, 3326704989, 1565652893]\n"
        );
    }

    #[test]
    fn reltime_builtins() {
        // reltime() with no args → a 2-element [high, low] list.
        assert_eq!(run("echo len(reltime())"), "2\n");
        // Difference of a timestamp with itself is exactly zero, in both forms.
        assert_eq!(
            run("let s = reltime()\necho reltimefloat(reltime(s, s))"),
            "0.0\n"
        );
        // reltimestr formats seconds as %10.6f (right-justified width 10).
        assert_eq!(
            run("let s = reltime()\necho reltimestr(reltime(s, s))"),
            "  0.000000\n"
        );
    }

    #[test]
    fn eval_execute_dictmap() {
        assert_eq!(run("echo eval('1 + 2 * 3')"), "7\n");
        assert_eq!(
            run("echo map({'a': 1, 'b': 2}, 'v:val * 10')"),
            "{'a': 10, 'b': 20}\n"
        );
        assert_eq!(
            run("echo filter({'a': 1, 'b': 2, 'c': 3}, 'v:val > 1')"),
            "{'b': 2, 'c': 3}\n"
        );
        // execute() captures with a leading newline ("\n42"); the outer echo
        // then appends its own trailing newline.
        assert_eq!(run("echo execute('echo 41 + 1')"), "\n42\n");
        assert_eq!(run("echo deepcopy([[1], [2]])"), "[[1], [2]]\n");
        assert_eq!(run("echo fmod(10.0, 3.0)"), "1.0\n");
    }

    #[test]
    fn call_resolves_builtins() {
        // call() / funcrefs accept builtin names, not just user functions.
        assert_eq!(run("echo call('printf', ['%d-%d', 3, 4])"), "3-4\n");
        assert_eq!(run("echo call('abs', [-5])"), "5\n");
        assert_eq!(run("echo call('len', [[1, 2, 3]])"), "3\n");
        assert_eq!(run("let F = function('toupper') | echo F('hi')"), "HI\n");
        // A Partial over a builtin binds leading args.
        assert_eq!(
            run("let G = function('substitute', ['axa']) | echo G('a', 'Z', 'g')"),
            "ZxZ\n"
        );
    }

    #[test]
    fn printf_sign_flags_and_byte_len() {
        assert_eq!(run("echo printf('%+d % d', 7, 7)"), "+7  7\n");
        assert_eq!(run("echo printf('%+05d', 7)"), "+0007\n");
        // len() of a String is its byte length.
        assert_eq!(run("echo len('héllo')"), "6\n");
    }

    #[test]
    fn trim_dir_and_scope_dicts() {
        assert_eq!(run("echo trim('  x  ', ' ', 1)"), "x  \n");
        assert_eq!(run("echo trim('  x  ', ' ', 2)"), "  x\n");
        // A bare scope sigil is a Dict of that scope.
        assert_eq!(run("let g:zz = 9 | echo get(g:, 'zz', -1)"), "9\n");
        assert_eq!(run("echo type(g:)"), "4\n");
        assert_eq!(run("let g:q = 1 | echo has_key(g:, 'q')"), "1\n");
    }

    #[test]
    fn printf_g_and_substitute_expr() {
        assert_eq!(
            run("echo printf('%g %g %g', 0.1, 1000000.0, 0.0001)"),
            "0.1 1000000.0 1.0e-4\n"
        );
        assert_eq!(run("echo printf('%.3g', 3.14159)"), "3.142\n");
        // \= replacement expression with submatch().
        assert_eq!(
            run("echo substitute('abcABC', '[a-z]', '\\=toupper(submatch(0))', 'g')"),
            "ABCABC\n"
        );
        assert_eq!(
            run("echo substitute('x1y2', '\\d', '\\=submatch(0)+10', 'g')"),
            "x11y12\n"
        );
    }

    #[test]
    fn batch4_builtins() {
        assert_eq!(
            run("echo matchlist('a-b', '\\(\\w\\)-\\(\\w\\)')"),
            "['a-b', 'a', 'b', '', '', '', '', '', '', '']\n"
        );
        assert_eq!(run("echo matchend('abc123', '\\d\\+')"), "6\n");
        assert_eq!(run("echo strridx('a/b/c', '/')"), "3\n");
        assert_eq!(run("echo escape('a.b', '.')"), "a\\.b\n");
        assert_eq!(run("echo tr('hello', 'el', 'ip')"), "hippo\n");
        assert_eq!(run("echo str2list('AB')"), "[65, 66]\n");
        assert_eq!(run("echo list2str([72, 105])"), "Hi\n");
        assert_eq!(run("echo flatten([1, [2, [3]]])"), "[1, 2, 3]\n");
        assert_eq!(
            run("function A(a, b)\nreturn a:a + a:b\nendfunction\necho reduce([1, 2, 3], function('A'), 0)"),
            "6\n"
        );
    }

    #[test]
    fn regex_through_eval() {
        assert_eq!(run("echo 'foobar123' =~ '\\d\\+'"), "1\n");
        assert_eq!(run("echo 'hello' =~ '^h.*o$'"), "1\n");
        assert_eq!(run("echo matchstr('ab123cd', '\\d\\+')"), "123\n");
        assert_eq!(run("echo substitute('a-b-c', '-', '/', 'g')"), "a/b/c\n");
        assert_eq!(
            run("echo substitute('John Smith', '\\(\\w\\+\\) \\(\\w\\+\\)', '\\2 \\1', '')"),
            "Smith John\n"
        );
        assert_eq!(run("echo split('a1b22c', '\\d\\+')"), "['a', 'b', 'c']\n");
        // :catch with a regex pattern.
        assert_eq!(
            run("try\nthrow 'E42: bad'\ncatch /E\\d\\+/\necho 'caught'\nendtry"),
            "caught\n"
        );
    }

    #[test]
    fn math_string_list_builtins() {
        assert_eq!(
            run("echo float2nr(sqrt(16.0)) . float2nr(pow(2.0, 5.0))"),
            "432\n"
        );
        assert_eq!(run("echo and(12, 10) . or(12, 10) . xor(12, 10)"), "8146\n");
        assert_eq!(run("echo strpart('hello world', 6)"), "world\n");
        assert_eq!(run("echo stridx('abcabc', 'c', 3)"), "5\n");
        assert_eq!(run("echo trim('  hi  ')"), "hi\n");
        assert_eq!(run("echo insert([2, 3], 1)"), "[1, 2, 3]\n");
        assert_eq!(run("echo remove([10, 20, 30], 1)"), "20\n");
        assert_eq!(run("echo extend([1, 2], [3, 4])"), "[1, 2, 3, 4]\n");
        assert_eq!(run("echo uniq([1, 1, 2, 3, 3])"), "[1, 2, 3]\n");
        assert_eq!(run("echo sort([3.0, 1.0, 2.5], 'n')"), "[1.0, 2.5, 3.0]\n");
        assert_eq!(run("echo items({'a': 1})"), "[['a', 1]]\n");
    }

    #[test]
    fn callback_builtins() {
        // map with a string expression binding v:val.
        assert_eq!(run("echo map([1, 2, 3], 'v:val * 10')"), "[10, 20, 30]\n");
        // filter.
        assert_eq!(
            run("echo filter([1, 2, 3, 4], 'v:val % 2 == 0')"),
            "[2, 4]\n"
        );
        // sort: default string order vs numeric.
        assert_eq!(run("echo sort([10, 9, 2])"), "[10, 2, 9]\n");
        assert_eq!(run("echo sort([10, 9, 2], 'n')"), "[2, 9, 10]\n");
        // map with a funcref + call().
        assert_eq!(
            run("function D(k, v)\nreturn a:v + a:v\nendfunction\necho map([1, 2], function('D'))"),
            "[2, 4]\n"
        );
        assert_eq!(
            run("function S(a, b)\nreturn a:a + a:b\nendfunction\necho call('S', [3, 4])"),
            "7\n"
        );
        // chained.
        assert_eq!(
            run("echo sort(filter(map([5, 1, 4], 'v:val * v:val'), 'v:val > 4'), 'n')"),
            "[16, 25]\n"
        );
    }

    #[test]
    fn builtins_batch() {
        assert_eq!(run("echo join(split('a b c'), '-')"), "a-b-c\n");
        assert_eq!(run("echo range(2, 8, 2)"), "[2, 4, 6, 8]\n");
        assert_eq!(run("echo toupper('hi') . repeat('!', 3)"), "HI!!!\n");
        assert_eq!(run("echo max([3, 9, 2]) . '/' . min([3, 9, 2])"), "9/2\n");
        assert_eq!(run("echo has_key({'x': 1}, 'x')"), "1\n");
        assert_eq!(run("echo get([10, 20, 30], 1)"), "20\n");
        assert_eq!(run("echo printf('%s=%05X', 'n', 255)"), "n=000FF\n");
        assert_eq!(
            run("echo count([1, 2, 2, 3], 2) . index([1, 2, 3], 3)"),
            "22\n"
        );
        assert_eq!(run("echo reverse([1, 2, 3])"), "[3, 2, 1]\n");
    }

    #[test]
    fn exceptions() {
        // throw caught by matching pattern + v:exception + finally always runs.
        assert_eq!(
            run("try\nthrow 'boom'\necho 'skipped'\ncatch /boom/\necho 'caught ' . v:exception\nfinally\necho 'fin'\nendtry"),
            "caught boom\nfin\n"
        );
        // throw from a function propagates and is caught in the caller (no
        // spurious value consumed by the aborted command).
        assert_eq!(
            run("function R(n)\nif a:n < 0\nthrow 'neg'\nendif\nreturn a:n\nendfunction\ntry\necho R(7)\necho R(-1)\ncatch /neg/\necho 'caught'\nendtry"),
            "7\ncaught\n"
        );
    }

    #[test]
    fn user_functions() {
        // a: args + return.
        assert_eq!(
            run("function Add(a, b)\nreturn a:a + a:b\nendfunction\necho Add(3, 4)"),
            "7\n"
        );
        // recursion (scope stack + nested calls).
        assert_eq!(
            run("function Fact(n)\nif a:n <= 1\nreturn 1\nendif\nreturn a:n * Fact(a:n - 1)\nendfunction\necho Fact(5)"),
            "120\n"
        );
        // l: locals + call inside an expression.
        assert_eq!(
            run("function Inc(x)\nlet l:y = a:x + 1\nreturn l:y\nendfunction\necho Inc(10) * 2"),
            "22\n"
        );
    }

    #[test]
    fn control_flow() {
        assert_eq!(
            run("let g:x = 5\nif g:x > 10\necho 'big'\nelseif g:x > 3\necho 'mid'\nelse\necho 'small'\nendif"),
            "mid\n"
        );
        // while with break/continue: i=1 echo, i=2 continue, i=3 echo, i=4 break.
        assert_eq!(
            run("let g:i = 0\nwhile g:i < 9\nlet g:i = g:i + 1\nif g:i == 2\ncontinue\nendif\nif g:i == 4\nbreak\nendif\necho g:i\nendwhile"),
            "1\n3\n"
        );
        // for over a list.
        assert_eq!(run("for n in [10, 20, 30]\necho n\nendfor"), "10\n20\n30\n");
        // while accumulator.
        assert_eq!(
            run("let g:s = 0\nlet g:k = 1\nwhile g:k <= 4\nlet g:s = g:s + g:k\nlet g:k = g:k + 1\nendwhile\necho g:s"),
            "10\n"
        );
    }

    #[test]
    fn ternary_index_builtins() {
        assert_eq!(run("echo 1 ? 'y' : 'n'"), "y\n");
        assert_eq!(run("echo 0 ?? 7"), "7\n");
        assert_eq!(run("echo [10, 20, 30][-1]"), "30\n");
        assert_eq!(run("echo 'hello'[1:3]"), "ell\n");
        assert_eq!(run("echo len([1, 2, 3])"), "3\n");
        assert_eq!(run("echo abs(-5)"), "5\n");
        assert_eq!(run("echo [1, 2, 3]->len()"), "3\n");
    }
}