rlang 0.1.11

R as a fusevm frontend: a lexer, parser, and compiler to fusevm bytecode on an RHost vector heap, with no bespoke VM or JIT
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
//! The R value heap and runtime, reached from fusevm through registered
//! builtins (`register_builtin`).
//!
//! rlang owns no VM and no JIT: the compiler lowers R to `fusevm::Chunk`, and
//! every R-specific operation lands in a builtin that calls in here.
//!
//! Value representation: **every** R value is a heap object behind a
//! `Value::Obj(u32)` handle, because R has no scalars — `1` is a
//! double vector of length one, and any value can carry attributes (`names`,
//! `dim`, `class`). Native `Value::Int` appears only in compiler-internal loop
//! counters, never as an R value.
//!
//! Environments are `Rc<RefCell<..>>` chained child-to-parent, so a closure
//! captures its defining environment by reference — R's lexical scoping, and
//! what makes `<<-` reach the enclosing frame.

use fusevm::{Chunk, VMResult, Value, VM};
/// Every map keyed by an R *name* — an environment's bindings, an object's
/// attributes — hashes with `FxHasher` rather than the standard library's
/// SipHash. R resolves a variable by name on every read, so this is the
/// interpreter's hottest hash; the keys are program identifiers, never
/// untrusted input, so SipHash's collision resistance was pure overhead.
/// Insertion order — which `ls()` and `attributes()` expose — is IndexMap's,
/// independent of the hasher.
pub type NameMap = IndexMap<String, Value, rustc_hash::FxBuildHasher>;

use indexmap::IndexMap;
use std::cell::RefCell;
use std::rc::Rc;

/// Builtin ids emitted by the compiler and registered on every VM.
pub mod ops {
    /// `[name]` → value bound to a name (any binding).
    pub const GETVAR: u16 = 1;
    /// `[name]` → the nearest *function* binding (R searches past non-functions).
    pub const GETFUN: u16 = 2;
    /// `[name, value]` → value (assignment is invisible).
    pub const SETVAR: u16 = 3;
    /// `[name, value]` → value, assigning in an enclosing frame (`<<-`).
    pub const SETSUPER: u16 = 4;
    /// `[(name|NULL), value, ...]` argc=2n → argument list.
    pub const MKARGS: u16 = 5;
    /// `[fn, args]` → call result.
    pub const CALL: u16 = 6;
    /// `[closure_id]` → closure capturing the current environment.
    pub const MKCLOSURE: u16 = 7;
    /// `[f64]` → double vector of length 1.
    pub const CONST_DBL: u16 = 8;
    /// `[i64]` → integer vector of length 1.
    pub const CONST_INT: u16 = 9;
    /// `[Str]` → character vector of length 1.
    pub const CONST_STR: u16 = 10;
    /// `[bool]` → logical vector of length 1.
    pub const CONST_LGL: u16 = 11;
    /// `[]` → NULL.
    pub const CONST_NULL: u16 = 12;
    /// `[i64 kind]` → typed NA.
    pub const CONST_NA: u16 = 13;
    /// `[]` → the `...` list of the current frame.
    pub const DOTS: u16 = 14;

    /// `[op_name, lhs, rhs]` → vectorized binary operation.
    pub const BINOP: u16 = 20;
    /// `[op_name, operand]` → vectorized unary operation.
    pub const UNOP: u16 = 21;
    /// `[name, lhs, rhs]` → `%op%` dispatch (`%%`, `%in%`, user-defined).
    pub const SPECIAL: u16 = 22;

    /// `[x, args]` → `x[...]`.
    pub const INDEX: u16 = 30;
    /// `[x, args]` → `x[[...]]`.
    pub const INDEX2: u16 = 31;
    /// `[x, name]` → `x$name`.
    pub const DOLLAR: u16 = 32;
    /// `[x, args, value]` → the modified `x` (`x[...] <- value`).
    pub const INDEX_SET: u16 = 33;
    /// `[x, args, value]` → the modified `x` (`x[[...]] <- value`).
    pub const INDEX2_SET: u16 = 34;
    /// `[x, name, value]` → the modified `x` (`x$name <- value`).
    pub const DOLLAR_SET: u16 = 35;
    /// `[fname, x, args, value]` → the modified `x` via the replacement
    /// function `fname<-` (`names(x) <- v`, `dim(x) <- v`, …).
    pub const REPLACE: u16 = 36;

    /// `[v]` → native `Bool` for a native `JumpIfFalse`.
    pub const TRUTHY: u16 = 40;
    /// `[]` → halt the loop body chunk with a `break` signal.
    pub const SIG_BREAK: u16 = 41;
    /// `[]` → halt the loop body chunk with a `next` signal.
    pub const SIG_NEXT: u16 = 42;
    /// `[v]` → halt the closure body with a `return` signal.
    pub const SIG_RETURN: u16 = 43;
    /// `[v]` → native `Int` length, for the native `for` loop counter.
    pub const SEQ_LEN: u16 = 44;
    /// `[v, Int]` → the i-th element as an R value (`for` iteration).
    pub const SEQ_ELEM: u16 = 45;
    /// `[v]` → v, printing it first if the value is visible (top-level echo).
    pub const AUTOPRINT: u16 = 46;
    /// `[v]` → native `Bool`: is this a definite FALSE? (`&&` short-circuit).
    pub const IS_FALSE: u16 = 47;
    /// `[v]` → native `Bool`: is this a definite TRUE? (`||` short-circuit).
    pub const IS_TRUE: u16 = 48;
    /// `[name]` → native `Bool`: was this formal left unsupplied? (default
    /// prologue, and the `missing()` primitive).
    pub const MISSING: u16 = 49;
    /// `[]` → NULL, marked invisible. The value of a loop and of an `if` with no
    /// `else`, neither of which R echoes at top level.
    pub const NULL_INVISIBLE: u16 = 50;

    /// `switch` branch selection: pops the `EXPR` value plus the branch names and
    /// pushes the raw integer index of the branch to run (or -1 for none), which
    /// the compiled jump table then dispatches on. Keeps `switch` lazy — only the
    /// selected branch's code is ever executed.
    pub const SWITCH_INDEX: u16 = 51;
    pub const RANGE_FROM: u16 = 52;
    pub const RANGE_STEP: u16 = 53;
    pub const RANGE_LEN: u16 = 54;
    /// `[v]` → v, marked visible. What `(` does in R: it is a function whose
    /// value is its argument, and evaluating a call sets the visibility flag —
    /// so `(x <- 5)` echoes while `x <- 5` does not.
    pub const SET_VISIBLE: u16 = 55;
    /// `[]` → NULL. Emitted after every top-level statement: R's default
    /// `options(warn = 0)` holds warnings until the statement that raised them
    /// finishes, then prints the whole batch, so this is where a top-level
    /// expression ends as far as the warning machinery is concerned.
    pub const WARN_FLUSH: u16 = 56;
    /// `[v]` → v, marked permanently shared. Emitted for the intermediate of a
    /// nested assignment target (`x$a[i] <- v`), whose object is an element of
    /// a container rather than the value of a binding, so the reference count
    /// on it does not describe how many bindings can see it.
    pub const MARK_SHARED: u16 = 57;
    /// `[text]` → text, with `text` opened as a call context *before* the
    /// arguments are evaluated. Emitted for a callee R implements as a closure:
    /// R makes the closure's context first and forces the argument promises
    /// inside it, so a condition raised while evaluating an argument reports
    /// the enclosing call. A callee R implements as a primitive makes no
    /// context at all, and gets no `OPEN_CALL`.
    pub const OPEN_CALL: u16 = 58;
    /// `[text, fun, args]` → result, for a call whose context [`OPEN_CALL`]
    /// already opened. Identical to [`CALL`] but for adopting that entry
    /// instead of pushing a second one.
    pub const CALL_OPENED: u16 = 59;
    /// `[v, which]` → `v` as one logical, for an operand of `&&` / `||`:
    /// `which` is `"x&&"`, `"y||"`, … — the operand and the operator, which
    /// name it in the error a non-number or a longer vector raises.
    pub const LOGIC2_ARG: u16 = 60;
    /// `[kind]` → stops the chunk with a pending `break` (1) or `next` (2).
    /// What those mean inside a lazy body (`tryCatch(expr)` and friends), which
    /// R evaluates as a promise: the loop that encloses the call is the target.
    pub const LOOP_SIGNAL: u16 = 61;
    /// `[]` → the pending loop signal as an integer (0 none, 1 break, 2 next),
    /// cleared. Emitted after a lazy call inside a loop so its jump table can
    /// act on a `break`/`next` the body raised.
    pub const TAKE_LOOP_SIGNAL: u16 = 62;
}

/// A variable environment: a frame's bindings plus a link to its enclosure.
pub struct EnvData {
    pub vars: NameMap,
    pub parent: Option<Env>,
}
/// A reference-counted environment, shared between a frame and every closure
/// that captured it.
pub type Env = Rc<RefCell<EnvData>>;

fn new_env(parent: Option<Env>) -> Env {
    Rc::new(RefCell::new(EnvData {
        vars: NameMap::default(),
        parent,
    }))
}

/// A compiled `function(...)`: its formals, its body chunk, and its deparsed
/// source. Defaults are not stored as expressions here — the compiler emits
/// them as a body prologue (`if (missing(p)) p <- <default>`), which is what
/// makes an R default able to refer to another argument.
///
/// `src` is the closure rendered by [`crate::deparse::deparse_closure`] at
/// compile time — the lines `print(f)`, `deparse(f)` and `format(f)` return.
/// It is computed from the AST before the body is lowered, because the AST does
/// not survive compilation and the default-argument expressions survive only as
/// prologue bytecode.
#[derive(Clone)]
pub struct ClosureDef {
    pub params: Vec<String>,
    pub chunk: Chunk,
    pub src: Vec<String>,
}

/// The non-local control transfers a builtin can raise.
#[derive(Debug, Clone)]
pub enum Signal {
    Break,
    Next,
    Return(Value),
}

/// One R value: its data, its attributes (`names`, `dim`, `class`, …), and the
/// count of durable references to it.
///
/// `refcnt` is R's `REFCNT` (true reference counting since R 4.0, where `NAMED`
/// used to be a saturating 0/1/2 approximation). It counts the places that
/// *keep* the object — an environment binding, an attribute slot, a list
/// element, a call frame's argument list — and deliberately not the operand
/// stack, exactly as R does not count C-stack references. A value with a count
/// of one is mutated in place by `x[i] <- v`; anything above one is copied
/// first. See [`RHost::may_mutate`].
#[derive(Clone)]
pub struct RObj {
    pub data: RData,
    pub attrs: NameMap,
    pub refcnt: u32,
}

/// The count at which reference counting stops. R's `REFCNTMAX` works the same
/// way: once a value has been referenced this many times the count saturates
/// and never decrements again, so the value stays permanently shared rather
/// than risking an undercount.
const REFCNT_MAX: u32 = u32::MAX;

/// Take a durable reference to `v` — R's `INCREMENT_REFCNT`.
///
/// A call-site argument list (`RData::Args`) is the one container that does not
/// count its elements when it is built: it exists for the duration of one call
/// and counting there would leave every argument of every call permanently
/// shared, which is the pessimisation this whole mechanism exists to avoid.
/// Binding one to a name — which is how `...` becomes durable — counts them
/// here instead, and [`release`] gives them back.
fn retain(heap: &mut [RObj], v: &Value) {
    let Value::Obj(i) = v else { return };
    let nested = {
        let Some(o) = heap.get_mut(*i as usize) else {
            return;
        };
        if o.refcnt == REFCNT_MAX {
            return;
        }
        o.refcnt += 1;
        match &o.data {
            RData::Args(items) => items.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
            _ => Vec::new(),
        }
    };
    for v in &nested {
        retain(heap, v);
    }
}

/// Give up a durable reference to `v` — R's `DECREMENT_REFCNT`.
fn release(heap: &mut [RObj], v: &Value) {
    let Value::Obj(i) = v else { return };
    let nested = {
        let Some(o) = heap.get_mut(*i as usize) else {
            return;
        };
        if o.refcnt == REFCNT_MAX || o.refcnt == 0 {
            return;
        }
        o.refcnt -= 1;
        match &o.data {
            RData::Args(items) => items.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
            _ => Vec::new(),
        }
    };
    for v in &nested {
        release(heap, v);
    }
}

/// Bind `name` to `val` in `env`, keeping the counts R's `SETCAR` keeps: the
/// new value gains a reference, the one it displaces loses one, and rebinding a
/// name to the object it already holds changes neither. That last rule is what
/// lets `x[i] <- v` re-bind `x` to the vector it just mutated in place without
/// marking it shared — R's `SETCAR` has the same early return.
fn bind_in(heap: &mut [RObj], env: &Env, name: &str, val: Value) {
    let old = env.borrow_mut().vars.insert(name.to_string(), val.clone());
    if old.as_ref() == Some(&val) {
        return;
    }
    if let Some(o) = old {
        release(heap, &o);
    }
    retain(heap, &val);
}

/// The R data types rlang represents. Atomic vectors hold `Option<T>`, where
/// `None` is `NA` — R's missing value is part of every atomic type, not a
/// separate one.
/// Which runtime function-combinator an [`RData::Combinator`] applies.
#[derive(Clone, Copy)]
pub enum CombinatorKind {
    /// `Negate(f)` — logical negation of `f`'s result.
    Negate,
    /// `Vectorize(f)` — apply `f` elementwise over recycled arguments.
    Vectorize,
}

#[derive(Clone)]
pub enum RData {
    Null,
    Lgl(Vec<Option<bool>>),
    Int(Vec<Option<i64>>),
    Dbl(Vec<Option<f64>>),
    Str(Vec<Option<String>>),
    /// A generic vector (`list(...)`); elements are handles to other objects.
    List(Vec<Value>),
    Closure {
        id: usize,
        env: Env,
    },
    /// A primitive implemented in Rust, named for dispatch and printing.
    Builtin(String),
    /// An unevaluated argument: R's promise. The `thunk` is a zero-argument
    /// closure over the CALLER's environment holding the argument expression,
    /// and `value` is what forcing it produced — filled in once, because R
    /// evaluates a promise at most once however many times the formal is read.
    ///
    /// A promise is created only by [`crate::builtins::call_primitive`]'s
    /// `.rlang_promise` (which the compiler emits around every argument of a
    /// call that may reach a closure) and is forced wherever a binding is
    /// READ — `force_value` is that door.
    Promise {
        thunk: Value,
        value: Option<Value>,
        /// How deep the call-context stack was where the argument was WRITTEN.
        /// Forcing happens later and further in — inside the callee — but the
        /// expression still belongs to the frame that wrote it, so the walkers
        /// (`substitute`, `sys.call`, warning's `In <call> :`) are shown the
        /// stack as it stood here. R gets this from the promise's own env.
        ctx_depth: usize,
    },
    /// An opaque handle to an R object living in the embedded GNU R (a raw
    /// vector, S4 object, data frame, environment — anything rlang has no type
    /// for). The `usize` is the preserved `SEXP` pointer; it flows back into R
    /// verbatim, so a value rlang cannot inspect can still pass through it.
    RForeign(usize),
    /// A function built at runtime by wrapping another — `Negate(f)` /
    /// `Vectorize(f)`. The closure model uses compile-time chunk ids, so a
    /// runtime-constructed function is represented as data: the combinator kind
    /// plus a handle to the wrapped function.
    Combinator {
        kind: CombinatorKind,
        inner: Value,
    },
    Environment(Env),
    /// A call-site argument list: `(tag, value)` pairs, produced by `MKARGS`.
    /// `Value::Undef` is an empty argument (`x[, 1]`).
    Args(Vec<(Option<String>, Value)>),
    /// An unevaluated R expression — R's `LANGSXP`. What `quote(f(x))` builds,
    /// what `sys.call()` hands back, and what a condition's `call` slot holds.
    /// The payload is the parse tree itself, so it deparses back to source and
    /// takes apart the way R's does.
    Lang(crate::ast::Expr),
    /// An R name — `SYMSXP`. `quote(x)`, and the head of every call.
    Sym(String),
}

/// Which [`RData`] variant a value holds, without its payload.
///
/// [`RHost::data_of`] *clones* the data — R's copy-on-assign semantics mean a
/// caller that keeps it must own it — so asking `matches!(data(x), RData::Str(_))`
/// copied the whole vector to read its tag. `RHost::kind_of` answers the same
/// question in O(1), which is what the vector paths (arithmetic, comparison,
/// subscript assignment) ask on every operation.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RKind {
    Null,
    /// An unforced promise. No R type answers to this — a promise that reaches
    /// a value position is a bug in the forcing, not a value a script can see.
    Promise,
    Lgl,
    Int,
    Dbl,
    Str,
    List,
    Closure,
    Builtin,
    RForeign,
    Combinator,
    Environment,
    Args,
    Lang,
    Sym,
}

impl RKind {
    /// The kind of an already-materialised `RData`.
    pub fn of(d: &RData) -> RKind {
        match d {
            RData::Null => RKind::Null,
            RData::Promise { .. } => RKind::Promise,
            RData::Lgl(_) => RKind::Lgl,
            RData::Int(_) => RKind::Int,
            RData::Dbl(_) => RKind::Dbl,
            RData::Str(_) => RKind::Str,
            RData::List(_) => RKind::List,
            RData::Closure { .. } => RKind::Closure,
            RData::Builtin(_) => RKind::Builtin,
            RData::RForeign(_) => RKind::RForeign,
            RData::Combinator { .. } => RKind::Combinator,
            RData::Environment(_) => RKind::Environment,
            RData::Args(_) => RKind::Args,
            RData::Lang(_) => RKind::Lang,
            RData::Sym(_) => RKind::Sym,
        }
    }

    /// This kind's place on the promotion ladder — see [`type_rank`].
    pub fn rank(self) -> u8 {
        match self {
            RKind::Null => 0,
            RKind::Lgl => 1,
            RKind::Int => 2,
            RKind::Dbl => 3,
            RKind::Str => 4,
            _ => 5,
        }
    }
}

/// The scalar type ladder used for promotion in `c()` and arithmetic:
/// logical < integer < double < character.
pub fn type_rank(d: &RData) -> u8 {
    match d {
        RData::Null => 0,
        RData::Lgl(_) => 1,
        RData::Int(_) => 2,
        RData::Dbl(_) => 3,
        RData::Str(_) => 4,
        _ => 5,
    }
}

/// One entry on the R call stack.
pub struct Frame {
    pub env: Env,
    /// True for the frame a forced promise runs in. R evaluates a promise in
    /// the caller's environment and makes NO call frame for it, so everything
    /// that walks frames — `substitute`, `parent.frame`, `sys.call` — has to
    /// look straight through this one.
    pub promise: bool,
    /// The call's arguments, kept for `UseMethod` and `sys.call`-style needs.
    pub args: Vec<(Option<String>, Value)>,
    /// The name the function was called by, when known.
    pub fun_name: Option<String>,
    /// The closure being executed, as the `(id, environment)` pair it was built
    /// from, so `Recall` can re-invoke it — anonymous functions included. Kept
    /// as the pair rather than an allocated closure value because only `Recall`
    /// ever reads it, and building the value allocated a heap cell on every
    /// call. `None` for the top-level frame, which is in no closure.
    pub fun: Option<(usize, Env)>,
    /// Set by `UseMethod` so `NextMethod` can continue down the class vector.
    pub dispatch: Option<(String, Vec<String>)>,
    /// Thunks registered by `on.exit`, run when this frame is left — whether it
    /// returns normally or unwinds with an error.
    pub on_exit: Vec<Value>,
    /// Formals the caller omitted and the default-argument prologue filled in.
    /// R's `missing()` asks whether the *caller* supplied an argument, which a
    /// default answers no to even though it leaves the name bound — so the
    /// binding alone cannot tell the two apart and the prologue records it.
    /// Written only by [`ops::MISSING`], which the prologue runs exactly once
    /// per defaulted formal, so tracking this costs nothing at any other call.
    pub defaulted: Vec<String>,
}

/// One `tryCatch` or `withCallingHandlers` frame, innermost last.
///
/// The two differ only in what happens when a handler matches: an *exiting*
/// handler (`tryCatch`) unwinds the stack first and runs the handler in the
/// `tryCatch`'s own frame, while a *calling* handler (`withCallingHandlers`)
/// runs at the point the condition was signalled and — unless it transfers
/// control to a restart — lets evaluation resume there.
pub struct HandlerFrame {
    /// `true` for `withCallingHandlers`.
    pub calling: bool,
    /// `(condition class, handler)` in the order written, which is the order R
    /// tries them: `tryCatch` runs the first match, `withCallingHandlers` runs
    /// every match.
    pub handlers: Vec<(String, Value)>,
    /// Set while one of this frame's handlers runs, so a condition signalled
    /// from inside a handler is only offered to frames established *outside*
    /// it. Without this, a `warning()` in a warning handler re-enters it.
    pub disabled: bool,
    /// A frame established by `suppressWarnings`/`suppressMessages`, which have
    /// no R-level handler: a matching condition is muffled outright. Holds the
    /// condition class to muffle (`"warning"` / `"message"`).
    pub muffle: Option<String>,
}

/// One restart, as established by `withRestarts` or by the `warning()` /
/// `message()` builtins around their own signalling.
pub struct RestartFrame {
    /// Identity for `invokeRestart`, which names a *particular* established
    /// restart — two nested `withRestarts` may use the same name.
    pub id: u64,
    pub name: String,
    pub description: String,
    /// The function to run after control transfers here. `None` for the
    /// built-in muffle restarts, which are consumed by the signalling builtin
    /// itself rather than by an R-level handler.
    pub handler: Option<Value>,
}

/// A restart transfer in flight: the target restart's id, and the arguments
/// `invokeRestart` was given to pass on to its handler.
pub type RestartInvoke = (u64, Vec<(Option<String>, Value)>);

/// The `Err` payload that carries a restart transfer out to its establishing
/// frame. It is not a message anyone sees: every site that catches errors
/// (`tryCatch`, `try`, the top-level reporter) re-propagates while
/// [`RHost::restart_invoke`] is set, and the establishing frame clears it.
pub const RESTART_UNWIND: &str = "\u{1}restart";

/// The R runtime: heap, environments, call stack, and pending control state.
/// A queued warning: its message and the call it was raised from, which R
/// prints as the `In <call> :` prefix. `None` for one raised at top level,
/// where R's `findCall` finds no enclosing call either.
/// A context's call text, read back out of the constant holding it.
fn ctx_text(v: &Value) -> String {
    // A diagnostic shows one line: R's `deparse1s(call)` keeps only the first,
    // so `withCallingHandlers({ … })` reports as `withCallingHandlers({`. The
    // rest of the deparse is there for `sys.call()`, which needs source that
    // parses back.
    ctx_source(v).lines().next().unwrap_or_default().to_string()
}

/// A context's call as whole R source — every line of the deparse.
pub fn ctx_source(v: &Value) -> String {
    match v {
        Value::Str(s) => s.to_string(),
        _ => String::new(),
    }
}

/// One entry on the call context stack.
pub struct CallCtx {
    /// The call's deparsed source, as `In <call> :` renders it — held as the
    /// compiler's own string constant, so opening a context is an `Arc` bump
    /// rather than a copy. Every call pays for this; only a warning reads it.
    pub text: Value,
    /// Whether the call has actually been entered, or is only open around the
    /// evaluation of its own arguments. rlang evaluates arguments eagerly but
    /// opens a closure's context before them, so both states exist here where
    /// R has a promise instead. The diagnostics want the open call — a warning
    /// raised while evaluating an argument to `print` reports `print(…)`, as it
    /// does in R — while `sys.call()` wants the entered one, because a promise
    /// belongs to the frame whose body wrote it: `h <- function() g(sys.call())`
    /// answers `h()`, not `g(…)`.
    pub entered: bool,
    /// Whether *R* would make a function context for this call — R's
    /// `CTXT_FUNCTION`, which every closure sets and no primitive does. It is
    /// decided by the compiler from R's primitive list rather than by what
    /// rlang implements the callee as, because rlang implements most of R's
    /// base *closures* as Rust builtins and the condition machinery has to see
    /// R's shape, not rlang's.
    pub closure: bool,
}

pub struct Warning {
    pub msg: String,
    pub call: Option<String>,
}

pub struct RHost {
    heap: Vec<RObj>,
    pub global: Env,
    pub frames: Vec<Frame>,
    pub closures: Vec<ClosureDef>,
    pub error: Option<String>,
    /// The S3 class vector of the condition currently being signalled — R's
    /// `c("simpleError", "error", "condition")` and friends. It rides alongside
    /// `error` so a `tryCatch` handler can be selected by class.
    pub error_classes: Vec<String>,
    /// The condition object itself, when the pending unwind was signalled with
    /// one — `stop(cond)`, `warning(cond)`, `signalCondition(cond)`. R hands an
    /// exiting handler that very object, extra fields and all; only a condition
    /// rlang raised from a message is rebuilt from `error_classes`.
    pub error_condition: Option<Value>,
    /// What `geterrmessage()` answers — R's `errbuf`. An error raised from a
    /// message writes the message there before any handler sees it, and
    /// `try` overwrites it with the whole `Error in <call> : …` line it
    /// reports; a condition object signalled by `stop(cond)` leaves it alone.
    pub errmessage: String,
    /// The call the pending error was raised in — R's `errorcall`. Held as
    /// whole R source: the `Error in <call> :` line shows its first line, and
    /// the condition object the error carries needs the rest. It has to be taken where the error is
    /// recorded: by the time the unwind reaches the top the context stack has
    /// been cut back past it. Written through [`RHost::set_error_call`].
    pub error_call: Option<String>,
    /// The deparsed call of every *function* context the pending error was
    /// raised under, innermost last — what R's `Calls:` line is built from.
    /// Snapshotted with [`RHost::set_error_call`], for the same reason.
    pub error_trace: Vec<String>,
    /// Whether the pending error's call has been decided. `error_call` alone
    /// cannot say: a top-level `stop()` decides on *no* call, which is an
    /// answer rather than an absence, and every frame the unwind passes through
    /// would otherwise overwrite it with its own.
    pub error_call_known: bool,
    /// The enclosing `tryCatch` / `withCallingHandlers` frames, innermost last.
    /// Every signalling site walks it outward: a calling handler runs in place,
    /// an exiting handler unwinds, and reaching the bottom with nothing matched
    /// is what lets `warning()` and `message()` keep R's default action.
    pub handlers: Vec<HandlerFrame>,
    /// The established restarts, innermost group last. One group per
    /// `withRestarts` call (or per signalling builtin), because the restarts in
    /// a single call are searched in the order written while the groups
    /// themselves are searched innermost-first.
    pub restarts: Vec<Vec<RestartFrame>>,
    /// Source of [`RestartFrame::id`].
    pub next_restart_id: u64,
    /// Set by `invokeRestart` and cleared by the frame that established the
    /// target: the restart's id and the arguments to pass its handler. While it
    /// is set the current unwind is a control transfer, not an error, so no
    /// handler may absorb it.
    pub restart_invoke: Option<RestartInvoke>,
    /// Set by S3 dispatch immediately before invoking a method, and consumed by
    /// the frame that method pushes, so `NextMethod` inside it knows which
    /// classes are still to try.
    pub pending_dispatch: Option<(String, Vec<String>)>,
    /// Set for exactly one `call_primitive` by `NextMethod`'s fall-through, so
    /// the primitive behind a generic runs its own implementation instead of
    /// dispatching S3 on the same object again.
    pub suppress_s3: bool,
    pub signal: Option<Signal>,
    /// R's "visibility" flag: assignment and `invisible()` clear it, so the
    /// top-level echo knows not to print.
    pub visible: bool,
    /// Whether the top-level echo prints at all. On for `Rscript` and the REPL,
    /// off for embedding and for tests that want the value, not the transcript.
    pub echo: bool,
    /// One entry per call now being evaluated, innermost last — R's context
    /// stack, narrowed to what the condition machinery reads off it. R's
    /// `findCall` walks it for the innermost *function* context, which is the
    /// call `warning()` reports; a warning raised inside a primitive reports
    /// that primitive's own call instead.
    pub calls: Vec<CallCtx>,
    /// Warnings raised by the top-level statement now running, held until it
    /// finishes — R's default `options(warn = 0)`. Capped at [`MAX_WARNINGS`]
    /// entries the way R caps `nwarnings`.
    pub warnings: Vec<Warning>,
    /// How many warnings that statement raised, which keeps counting past the
    /// cap so the "50 or more" banner can say so.
    pub warn_count: usize,
    /// The uniform random number stream behind `set.seed`, `runif`, `rnorm`
    /// and `sample` (see `crate::rng`).
    pub rng: crate::rng::Rng,
    /// Interned singletons so `NULL` and the common constants do not allocate a
    /// fresh heap cell on every evaluation.
    null: Option<Value>,
}

thread_local! {
    static HOST: RefCell<RHost> = RefCell::new(RHost::new());
    /// When `Some`, R's stdout output (`print`/`cat`/autoprint) is appended here
    /// instead of written to the process stdout. `wasm32` has no real stdout, so
    /// the wasm entry point (`crate::eval_capture`) drains this buffer; native
    /// callers leave it `None` and print straight through.
    static CAPTURE: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Write R program output. Appended to the capture buffer when one is active
/// (see [`start_capture`]), otherwise written to the process stdout. Every
/// R-visible stdout write (`print`, `cat`, top-level autoprint) goes through
/// here so a single switch redirects them all.
pub fn emit(s: &str) {
    CAPTURE.with(|c| {
        if let Some(buf) = c.borrow_mut().as_mut() {
            buf.push_str(s);
        } else {
            use std::io::Write as _;
            let mut out = std::io::stdout();
            let _ = out.write_all(s.as_bytes());
        }
    });
}

/// Begin capturing R stdout into an in-memory buffer, replacing any prior one.
pub fn start_capture() {
    CAPTURE.with(|c| *c.borrow_mut() = Some(String::new()));
}

/// Run `f` with stdout captured, returning its result and what it wrote. Unlike
/// [`start_capture`] it nests: an enclosing capture is restored afterwards.
pub fn with_capture<T>(f: impl FnOnce() -> T) -> (T, String) {
    let outer = CAPTURE.with(|c| c.borrow_mut().replace(String::new()));
    let out = f();
    let text = CAPTURE.with(|c| std::mem::replace(&mut *c.borrow_mut(), outer));
    (out, text.unwrap_or_default())
}

/// Stop capturing and return everything written since [`start_capture`].
pub fn take_capture() -> String {
    CAPTURE.with(|c| c.borrow_mut().take().unwrap_or_default())
}

thread_local! {
    /// What R's `stdin` connection (`readLines("stdin")`) reads. `None` reads
    /// the process stdin; an embedder installs in-memory text with
    /// [`set_stdin`]. Separate from the host so `reset_host` leaves it alone.
    static STDIN: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Make `text` the stdin this thread's R programs read, in place of the
/// process stdin. Lines are consumed as they are read.
pub fn set_stdin(text: &str) {
    STDIN.with(|s| *s.borrow_mut() = Some(text.to_string()));
}

/// Read and consume up to `limit` lines (every remaining line when `None`)
/// from R's stdin, without their `\n`. A final line with no newline is still
/// a line.
pub fn read_stdin_lines(limit: Option<usize>) -> Vec<String> {
    STDIN.with(|s| {
        let mut installed = s.borrow_mut();
        let mut next_line = || {
            let mut line = match installed.as_mut() {
                Some(buf) if buf.is_empty() => return None,
                Some(buf) => {
                    let end = buf.find('\n').map_or(buf.len(), |i| i + 1);
                    buf.drain(..end).collect::<String>()
                }
                None => {
                    let mut line = String::new();
                    match std::io::stdin().read_line(&mut line) {
                        Ok(0) | Err(_) => return None,
                        Ok(_) => line,
                    }
                }
            };
            if line.ends_with('\n') {
                line.pop();
            }
            Some(line)
        };
        let mut lines = Vec::new();
        while limit.is_none_or(|n| lines.len() < n) {
            match next_line() {
                Some(line) => lines.push(line),
                None => break,
            }
        }
        lines
    })
}

thread_local! {
    /// Where R's diagnostics go. `None` writes them straight to the process
    /// stderr; `Rscript` installs a hook instead, because it buffers stdout for
    /// the CRAN fallback and has to replay the two streams in the order they
    /// were written rather than one after the other. See `main.rs`.
    #[allow(clippy::type_complexity)]
    static STDERR_HOOK: RefCell<Option<Box<dyn Fn(&str)>>> = const { RefCell::new(None) };
}

/// Route R's diagnostics (the warning batches) through `f` instead of stderr.
pub fn set_stderr_hook(f: Box<dyn Fn(&str)>) {
    STDERR_HOOK.with(|h| *h.borrow_mut() = Some(f));
}

/// Stop diverting diagnostics, so later ones go straight to stderr. Without
/// this the batch a *failed* statement queued was written into a sink that had
/// already been replayed, and vanished: R prints it after the error line, under
/// `In addition:`, which is after the replay.
pub fn clear_stderr_hook() {
    STDERR_HOOK.with(|h| *h.borrow_mut() = None);
}

/// Write one diagnostic — through the installed hook, or to stderr.
pub fn emit_stderr(s: &str) {
    let handled = STDERR_HOOK.with(|h| h.borrow().as_ref().map(|f| f(s)).is_some());
    if !handled {
        eprint!("{s}");
    }
}

/// Run `f` with mutable access to the thread-local host.
pub fn with_host<R>(f: impl FnOnce(&mut RHost) -> R) -> R {
    HOST.with(|h| f(&mut h.borrow_mut()))
}

/// Reset the host to a clean slate (fresh global environment and heap).
pub fn reset_host() {
    CLOSURE_VMS.with(|c| c.borrow_mut().clear());
    with_host(|h| *h = RHost::new());
}

/// The base primitives R implements as `special` (arguments passed
/// unevaluated). A subset of `compiler::R_PRIMITIVES`. Sorted for `binary_search`.
const R_SPECIAL_PRIMITIVES: &[&str] = &[
    "$",
    "$<-",
    "&&",
    ".Internal",
    "::",
    ":::",
    "<-",
    "<<-",
    "=",
    "@",
    "@<-",
    "Exec",
    "Tailcall",
    "UseMethod",
    "[",
    "[<-",
    "[[",
    "[[<-",
    "break",
    "call",
    "declare",
    "expression",
    "for",
    "forceAndCall",
    "function",
    "if",
    "log",
    "missing",
    "next",
    "on.exit",
    "quote",
    "rep",
    "repeat",
    "return",
    "round",
    "signif",
    "substitute",
    "switch",
    "while",
    "{",
    "||",
    "~",
];

/// `typeof` of a Rust-implemented function named `name`: R's own type for it.
/// Only R's primitives are `builtin`/`special`; every other base function is a
/// closure in R, so it reports `closure` here too.
pub fn builtin_type(name: &str) -> &'static str {
    if !crate::compiler::is_r_primitive(name) {
        "closure"
    } else if R_SPECIAL_PRIMITIVES.binary_search(&name).is_ok() {
        "special"
    } else {
        "builtin"
    }
}

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

impl RHost {
    /// A fresh runtime with an empty heap and an empty global environment.
    pub fn new() -> Self {
        let global = new_env(None);
        RHost {
            heap: Vec::new(),
            global: global.clone(),
            frames: vec![Frame {
                promise: false,
                env: global,
                args: Vec::new(),
                fun_name: None,
                fun: None,
                dispatch: None,
                on_exit: Vec::new(),
                defaulted: Vec::new(),
            }],
            closures: Vec::new(),
            error: None,
            error_classes: Vec::new(),
            error_condition: None,
            errmessage: String::new(),
            error_call: None,
            error_trace: Vec::new(),
            error_call_known: false,
            handlers: Vec::new(),
            restarts: Vec::new(),
            next_restart_id: 0,
            restart_invoke: None,
            pending_dispatch: None,
            suppress_s3: false,
            signal: None,
            visible: true,
            echo: true,
            calls: Vec::new(),
            warnings: Vec::new(),
            warn_count: 0,
            rng: crate::rng::Rng::default(),
            null: None,
        }
    }

    /// Install the compiled closure bodies for a program.
    pub fn load_closures(&mut self, closures: Vec<ClosureDef>) {
        // The parked VMs are keyed by closure id and still hold the *old*
        // program's chunk for that id, so a new closure table invalidates every
        // one of them.
        CLOSURE_VMS.with(|c| c.borrow_mut().clear());
        self.closures = closures;
    }

    // ── heap ───────────────────────────────────────────────────────────

    /// Allocate `data` with no attributes and return its handle.
    pub fn alloc(&mut self, data: RData) -> Value {
        self.alloc_with(data, NameMap::default())
    }

    /// Allocate `data` carrying `attrs`.
    pub fn alloc_with(&mut self, data: RData, attrs: NameMap) -> Value {
        // A container holds a durable reference to each element, the way R's
        // `SET_VECTOR_ELT` and `setAttrib` increment what they store. rlang
        // builds a container by allocating a fresh one, so this is the single
        // site where a list's or a combinator's elements are counted.
        match &data {
            RData::List(xs) => {
                for v in xs {
                    retain(&mut self.heap, v);
                }
            }
            RData::Combinator { inner, .. } => retain(&mut self.heap, inner),
            // A promise holds its thunk for as long as it is unforced, which is
            // the same durable reference a list holds over its elements.
            RData::Promise { thunk, .. } => retain(&mut self.heap, thunk),
            _ => {}
        }
        for v in attrs.values() {
            retain(&mut self.heap, v);
        }
        self.heap.push(RObj {
            data,
            attrs,
            refcnt: 0,
        });
        Value::Obj((self.heap.len() - 1) as u32)
    }

    /// R's `REFCNT`: how many durable references the value has. An unboxed
    /// scalar has no heap cell at all, so it answers `REFCNT_MAX` — never
    /// eligible for in-place mutation.
    pub fn refcnt(&self, v: &Value) -> u32 {
        match v {
            Value::Obj(i) => self.heap.get(*i as usize).map_or(REFCNT_MAX, |o| o.refcnt),
            _ => REFCNT_MAX,
        }
    }

    /// R's `!MAYBE_SHARED`: whether nothing but the binding being assigned
    /// through holds this object, so `x[i] <- v` may write into it rather than
    /// rebuilding it.
    pub fn may_mutate(&self, v: &Value) -> bool {
        self.refcnt(v) <= 1
    }

    /// Run `f` on a heap object's data in place. The caller must have
    /// established [`RHost::may_mutate`] first — this is the write half of R's
    /// reference-count rule and there is no other way to reach it.
    pub fn with_data_mut<R>(&mut self, v: &Value, f: impl FnOnce(&mut RData) -> R) -> Option<R> {
        self.get_mut(v).map(|o| f(&mut o.data))
    }

    /// Write `val` into a list's slots in place, keeping the element counts:
    /// each slot written takes a reference to `val` and gives back the one it
    /// held. A position past the end extends the list, filling the slots the
    /// assignment skipped with `NULL` the way R's `EnlargeVector` does. `None`
    /// when the value is not a list, which leaves the caller on the rebuild
    /// path.
    pub fn set_list_elements(&mut self, x: &Value, positions: &[usize], val: &Value) -> Option<()> {
        let null = self.null();
        let displaced = self.with_data_mut(x, |d| match d {
            RData::List(items) => Some(
                positions
                    .iter()
                    .map(|p| {
                        while items.len() <= *p {
                            items.push(null.clone());
                        }
                        std::mem::replace(&mut items[*p], val.clone())
                    })
                    .collect::<Vec<_>>(),
            ),
            _ => None,
        })??;
        for old in &displaced {
            release(&mut self.heap, old);
        }
        for _ in 0..positions.len() {
            retain(&mut self.heap, val);
        }
        Some(())
    }

    /// Mark a value permanently shared, so no later `x[i] <- v` writes into it.
    /// The compiler emits this for the intermediate of a *nested* assignment
    /// target (`x$a[i] <- v`), whose object is an element of a container rather
    /// than the value of a binding: R reaches the same conclusion by having
    /// `EnsureLocal`'s shallow duplicate increment every element it shares.
    pub fn mark_shared(&mut self, v: &Value) {
        if let Value::Obj(i) = v {
            if let Some(o) = self.heap.get_mut(*i as usize) {
                o.refcnt = REFCNT_MAX;
            }
        }
    }

    /// The object behind a handle, if the value is one.
    pub fn get(&self, v: &Value) -> Option<&RObj> {
        match v {
            Value::Obj(i) => self.heap.get(*i as usize),
            _ => None,
        }
    }

    fn get_mut(&mut self, v: &Value) -> Option<&mut RObj> {
        match v {
            Value::Obj(i) => self.heap.get_mut(*i as usize),
            _ => None,
        }
    }

    /// The data behind a handle, cloned. R has copy-on-assign value semantics,
    /// so every mutation path here rebuilds the object rather than aliasing it.
    pub fn data_of(&self, v: &Value) -> RData {
        match unboxed(v) {
            Some(Ub::I(n)) => return RData::Int(vec![Some(n)]),
            Some(Ub::F(f)) => return RData::Dbl(vec![Some(f)]),
            Some(Ub::B(b)) => return RData::Lgl(vec![Some(b)]),
            None => {}
        }
        self.get(v).map(|o| o.data.clone()).unwrap_or(RData::Null)
    }

    /// Which variant this value's data is, without copying the data.
    pub fn kind_of(&self, v: &Value) -> RKind {
        match unboxed(v) {
            Some(Ub::I(_)) => return RKind::Int,
            Some(Ub::F(_)) => return RKind::Dbl,
            Some(Ub::B(_)) => return RKind::Lgl,
            None => {}
        }
        self.get(v)
            .map(|o| RKind::of(&o.data))
            .unwrap_or(RKind::Null)
    }

    /// A length-1, unattributed, non-NA numeric/logical value as
    /// `(value, is_integer_typed)` — the scalar fast path for arithmetic and
    /// comparison. Returns `None` (forcing the full vector path) for anything
    /// with attributes, length != 1, an NA element, or a non-numeric type. Reads
    /// by borrow: no `data_of` clone of the backing vector.
    pub fn scalar_real(&self, v: &Value) -> Option<(f64, bool)> {
        match unboxed(v) {
            Some(Ub::I(n)) => return Some((n as f64, true)),
            Some(Ub::F(f)) => return Some((f, false)),
            Some(Ub::B(b)) => return Some((b as i64 as f64, true)),
            None => {}
        }
        let o = self.get(v)?;
        if !o.attrs.is_empty() {
            return None;
        }
        match &o.data {
            RData::Int(x) if x.len() == 1 => x[0].map(|n| (n as f64, true)),
            RData::Lgl(x) if x.len() == 1 => x[0].map(|b| (b as i64 as f64, true)),
            RData::Dbl(x) if x.len() == 1 => x[0].map(|n| (n, false)),
            _ => None,
        }
    }

    /// The attributes of a value.
    pub fn attrs_of(&self, v: &Value) -> NameMap {
        if unboxed(v).is_some() {
            return NameMap::default();
        }
        self.get(v).map(|o| o.attrs.clone()).unwrap_or_default()
    }

    /// Read one attribute.
    pub fn attr(&self, v: &Value, name: &str) -> Option<Value> {
        if unboxed(v).is_some() {
            return None;
        }
        self.get(v).and_then(|o| o.attrs.get(name).cloned())
    }

    /// Set (or, with `NULL`, remove) one attribute in place.
    pub fn set_attr(&mut self, v: &Value, name: &str, val: Value) {
        let is_null = matches!(self.data_of(&val), RData::Null);
        let Some(o) = self.get_mut(v) else { return };
        let old = if is_null {
            o.attrs.shift_remove(name)
        } else {
            o.attrs.insert(name.to_string(), val.clone())
        };
        // An attribute slot is a durable reference, like a binding: the value it
        // held loses one and the value replacing it gains one.
        if old.as_ref() == Some(&val) {
            return;
        }
        if let Some(o) = old {
            release(&mut self.heap, &o);
        }
        if !is_null {
            retain(&mut self.heap, &val);
        }
    }

    /// The shared `NULL` singleton.
    pub fn null(&mut self) -> Value {
        if let Some(v) = &self.null {
            return v.clone();
        }
        let v = self.alloc(RData::Null);
        self.null = Some(v.clone());
        v
    }

    // ── constructors ───────────────────────────────────────────────────

    /// A double vector.
    pub fn dbl(&mut self, xs: Vec<Option<f64>>) -> Value {
        self.alloc(RData::Dbl(xs))
    }
    /// An integer vector.
    pub fn int(&mut self, xs: Vec<Option<i64>>) -> Value {
        self.alloc(RData::Int(xs))
    }
    /// A logical vector.
    pub fn lgl(&mut self, xs: Vec<Option<bool>>) -> Value {
        self.alloc(RData::Lgl(xs))
    }
    /// A character vector.
    pub fn str_vec(&mut self, xs: Vec<Option<String>>) -> Value {
        self.alloc(RData::Str(xs))
    }
    /// A generic vector (list).
    pub fn list(&mut self, xs: Vec<Value>) -> Value {
        self.alloc(RData::List(xs))
    }
    /// A length-1 double.
    pub fn scalar_dbl(&mut self, x: f64) -> Value {
        self.dbl(vec![Some(x)])
    }
    /// A length-1 integer.
    pub fn scalar_int(&mut self, x: i64) -> Value {
        self.int(vec![Some(x)])
    }
    /// A length-1 logical.
    pub fn scalar_lgl(&mut self, x: bool) -> Value {
        self.lgl(vec![Some(x)])
    }
    /// A length-1 character vector.
    pub fn scalar_str(&mut self, x: impl Into<String>) -> Value {
        self.str_vec(vec![Some(x.into())])
    }

    // ── lengths, coercion, accessors ───────────────────────────────────

    /// `length(x)`.
    pub fn length(&self, v: &Value) -> usize {
        if unboxed(v).is_some() {
            return 1;
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Null) | None => 0,
            Some(RData::Lgl(x)) => x.len(),
            Some(RData::Int(x)) => x.len(),
            Some(RData::Dbl(x)) => x.len(),
            Some(RData::Str(x)) => x.len(),
            Some(RData::List(x)) => x.len(),
            Some(RData::Args(x)) => x.len(),
            Some(RData::Environment(e)) => e.borrow().vars.len(),
            // A call's length is its parts: the function and its arguments.
            // A name is one thing.
            Some(RData::Lang(e)) => crate::builtins::lang_len(e),
            _ => 1,
        }
    }

    /// Coerce to logicals (`as.logical`); non-convertible strings become NA.
    pub fn as_lgl(&self, v: &Value) -> Vec<Option<bool>> {
        match unboxed(v) {
            Some(Ub::I(n)) => return vec![Some(n != 0)],
            Some(Ub::F(f)) => return vec![Some(f != 0.0)],
            Some(Ub::B(b)) => return vec![Some(b)],
            None => {}
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Lgl(x)) => x.clone(),
            Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n != 0)).collect(),
            Some(RData::Dbl(x)) => x.iter().map(|e| e.map(|n| n != 0.0)).collect(),
            Some(RData::Str(x)) => x
                .iter()
                // R accepts exactly four spellings per truth value — the initial,
                // the all-caps word, the all-lower word, and the capitalised word
                // (`StringTrue` in R's coerceVector). Anything else, including
                // "Tr" or "yes", is NA.
                .map(|e| match e.as_deref() {
                    Some("T") | Some("TRUE") | Some("true") | Some("True") => Some(true),
                    Some("F") | Some("FALSE") | Some("false") | Some("False") => Some(false),
                    _ => None,
                })
                .collect(),
            Some(RData::List(x)) => x.iter().flat_map(|e| self.as_lgl(e)).collect(),
            _ => Vec::new(),
        }
    }

    /// Coerce to integers (`as.integer`); doubles truncate toward zero.
    pub fn as_int(&self, v: &Value) -> Vec<Option<i64>> {
        match unboxed(v) {
            Some(Ub::I(n)) => return vec![Some(n)],
            Some(Ub::F(f)) => return vec![f.is_finite().then_some(f.trunc() as i64)],
            Some(Ub::B(b)) => return vec![Some(b as i64)],
            None => {}
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Lgl(x)) => x.iter().map(|e| e.map(|b| b as i64)).collect(),
            Some(RData::Int(x)) => x.clone(),
            Some(RData::Dbl(x)) => x
                .iter()
                .map(|e| e.and_then(|n| n.is_finite().then_some(n.trunc() as i64)))
                .collect(),
            Some(RData::Str(x)) => x
                .iter()
                .map(|e| e.as_ref().and_then(|s| parse_num(s.trim())))
                .map(|o| o.and_then(|n| n.is_finite().then_some(n.trunc() as i64)))
                .collect(),
            Some(RData::List(x)) => x.iter().flat_map(|e| self.as_int(e)).collect(),
            _ => Vec::new(),
        }
    }

    /// Coerce to doubles (`as.numeric`).
    pub fn as_dbl(&self, v: &Value) -> Vec<Option<f64>> {
        match unboxed(v) {
            Some(Ub::I(n)) => return vec![Some(n as f64)],
            Some(Ub::F(f)) => return vec![Some(f)],
            Some(Ub::B(b)) => return vec![Some(b as i64 as f64)],
            None => {}
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Lgl(x)) => x.iter().map(|e| e.map(|b| b as i64 as f64)).collect(),
            Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n as f64)).collect(),
            Some(RData::Dbl(x)) => x.clone(),
            Some(RData::Str(x)) => x
                .iter()
                .map(|e| e.as_ref().and_then(|s| parse_num(s.trim())))
                .collect(),
            Some(RData::List(x)) => x.iter().flat_map(|e| self.as_dbl(e)).collect(),
            _ => Vec::new(),
        }
    }

    /// Coerce to strings (`as.character`).
    pub fn as_str(&self, v: &Value) -> Vec<Option<String>> {
        match unboxed(v) {
            Some(Ub::I(n)) => return vec![Some(n.to_string())],
            Some(Ub::F(f)) => return vec![Some(format_dbl(f))],
            Some(Ub::B(b)) => return vec![Some(if b { "TRUE" } else { "FALSE" }.to_string())],
            None => {}
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Lgl(x)) => x
                .iter()
                .map(|e| e.map(|b| if b { "TRUE" } else { "FALSE" }.to_string()))
                .collect(),
            Some(RData::Int(x)) => x.iter().map(|e| e.map(|n| n.to_string())).collect(),
            Some(RData::Dbl(x)) => x.iter().map(|e| e.map(format_dbl)).collect(),
            Some(RData::Str(x)) => x.clone(),
            Some(RData::List(x)) => x.iter().flat_map(|e| self.as_str(e)).collect(),
            _ => Vec::new(),
        }
    }

    /// The single string of a length-1 character vector (argument helper).
    pub fn str1(&self, v: &Value) -> Option<String> {
        self.as_str(v).into_iter().next().flatten()
    }
    /// The single number of a length-1 numeric vector (argument helper).
    pub fn num1(&self, v: &Value) -> Option<f64> {
        self.as_dbl(v).into_iter().next().flatten()
    }
    /// The single logical of a length-1 vector (argument helper).
    pub fn lgl1(&self, v: &Value) -> Option<bool> {
        self.as_lgl(v).into_iter().next().flatten()
    }

    /// The list elements of a value: a list yields its elements; an atomic
    /// vector yields one length-1 value per element (what `lapply` iterates).
    pub fn elements(&mut self, v: &Value) -> Vec<Value> {
        match self.data_of(v) {
            RData::List(xs) => xs,
            RData::Null => Vec::new(),
            _ => (0..self.length(v)).map(|i| self.element_at(v, i)).collect(),
        }
    }

    /// The i-th element of a vector or list as a standalone R value.
    pub fn element_at(&mut self, v: &Value, i: usize) -> Value {
        // An unboxed scalar is length-1: element 0 is itself.
        if unboxed(v).is_some() {
            return if i == 0 { v.clone() } else { self.null() };
        }
        // Read ONE element by borrowing the backing store — never clone the
        // whole vector. `data_of` clones all of `o.data`, so the old
        // `match self.data_of(v)` here was O(n) per call, making
        // `for (x in seq)` O(n^2) over the sequence length.
        enum Elem {
            Lgl(Option<bool>),
            Int(Option<i64>),
            Dbl(Option<f64>),
            Str(Option<String>),
            Val(Value),
            Null,
        }
        let e = match self.get(v).map(|o| &o.data) {
            Some(RData::Lgl(x)) => Elem::Lgl(x.get(i).cloned().flatten()),
            Some(RData::Int(x)) => Elem::Int(x.get(i).cloned().flatten()),
            Some(RData::Dbl(x)) => Elem::Dbl(x.get(i).cloned().flatten()),
            Some(RData::Str(x)) => Elem::Str(x.get(i).cloned().flatten()),
            Some(RData::List(x)) => x.get(i).cloned().map(Elem::Val).unwrap_or(Elem::Null),
            _ => Elem::Null,
        };
        // A non-NA numeric/logical element rides unboxed (allocation-free) — this
        // is what makes `for (i in seq)` allocate nothing per iteration. NA has
        // no unboxed form, and strings are not yet unboxed, so those still box.
        match e {
            Elem::Lgl(Some(b)) => Value::Bool(b),
            Elem::Int(Some(n)) => Value::Int(n),
            Elem::Dbl(Some(f)) => Value::Float(f),
            Elem::Lgl(o) => self.lgl(vec![o]),
            Elem::Int(o) => self.int(vec![o]),
            Elem::Dbl(o) => self.dbl(vec![o]),
            Elem::Str(o) => self.str_vec(vec![o]),
            Elem::Val(v) => v,
            Elem::Null => self.null(),
        }
    }

    /// `names(x)`, as a plain vector of `Option<String>` (`None` where unnamed).
    pub fn names(&self, v: &Value) -> Vec<Option<String>> {
        if let Some(n) = self.attr(v, "names") {
            return self.as_str(&n);
        }
        // A 1-D array carries no `names` attribute: R's `names.default` reads
        // `dimnames[[1]]` instead, which is where a `table`'s labels live.
        let one_d = self.attr(v, "dim").is_some_and(|d| self.length(&d) == 1);
        if one_d {
            if let Some(dn) = self.attr(v, "dimnames") {
                if let Some(RObj {
                    data: RData::List(xs),
                    ..
                }) = self.get(&dn)
                {
                    if let Some(first) = xs.first() {
                        return self.as_str(first);
                    }
                }
            }
        }
        Vec::new()
    }

    /// Whether the value is `NULL`.
    pub fn is_null(&self, v: &Value) -> bool {
        if unboxed(v).is_some() {
            return false;
        }
        matches!(self.get(v).map(|o| &o.data), Some(RData::Null) | None)
    }

    /// Whether the value is callable.
    pub fn is_function(&self, v: &Value) -> bool {
        matches!(
            self.get(v).map(|o| &o.data),
            Some(RData::Closure { .. }) | Some(RData::Builtin(_)) | Some(RData::Combinator { .. })
        )
    }

    /// The implicit or explicit class vector, as `class(x)` reports it.
    pub fn class_of(&self, v: &Value) -> Vec<String> {
        if let Some(c) = self.attr(v, "class") {
            let cs: Vec<String> = self.as_str(&c).into_iter().flatten().collect();
            if !cs.is_empty() {
                return cs;
            }
        }
        // R's implicit class for a dimensioned object: rank 2 is a matrix (and
        // an array), any other rank is an array.
        match self.attr(v, "dim").map(|d| self.length(&d)) {
            Some(2) => return vec!["matrix".into(), "array".into()],
            Some(n) if n > 0 => return vec!["array".into()],
            _ => {}
        }
        match unboxed(v) {
            Some(Ub::I(_)) => return vec!["integer".into()],
            Some(Ub::F(_)) => return vec!["numeric".into()],
            Some(Ub::B(_)) => return vec!["logical".into()],
            None => {}
        }
        vec![match self.get(v).map(|o| &o.data) {
            Some(RData::Null) | None => "NULL",
            Some(RData::Lgl(_)) => "logical",
            Some(RData::Int(_)) => "integer",
            Some(RData::Dbl(_)) => "numeric",
            Some(RData::Str(_)) => "character",
            Some(RData::List(_)) => "list",
            Some(RData::Closure { .. })
            | Some(RData::Builtin(_))
            | Some(RData::Combinator { .. }) => "function",
            Some(RData::Environment(_)) => "environment",
            Some(RData::Args(_)) => "list",
            // An unevaluated expression's implicit class is what it *is*: a
            // call, or the name of one thing.
            // R's `lang2str` names the syntactic forms after their function:
            // `class(quote({}))` is "{", `class(quote(if (a) b))` is "if".
            Some(RData::Lang(e)) => match e {
                crate::ast::Expr::Block(_) => "{",
                crate::ast::Expr::Paren(_) => "(",
                crate::ast::Expr::If { .. } => "if",
                crate::ast::Expr::For { .. } => "for",
                crate::ast::Expr::While { .. } => "while",
                crate::ast::Expr::Assign {
                    super_assign: false,
                    ..
                } => "<-",
                _ => "call",
            },
            Some(RData::Sym(_)) => "name",
            // A foreign R object's real class is only known to R.
            Some(RData::RForeign(_)) => "R_object",
            // R answers "promise" for the type of an unforced one, which only
            // `pryr`-style introspection ever sees; every ordinary read forces
            // first (`force_value`).
            Some(RData::Promise { .. }) => "promise",
        }
        .to_string()]
    }

    /// `typeof(x)`.
    pub fn type_of(&self, v: &Value) -> &'static str {
        match unboxed(v) {
            Some(Ub::I(_)) => return "integer",
            Some(Ub::F(_)) => return "double",
            Some(Ub::B(_)) => return "logical",
            None => {}
        }
        match self.get(v).map(|o| &o.data) {
            Some(RData::Null) | None => "NULL",
            Some(RData::Lgl(_)) => "logical",
            Some(RData::Int(_)) => "integer",
            Some(RData::Dbl(_)) => "double",
            Some(RData::Str(_)) => "character",
            Some(RData::List(_)) | Some(RData::Args(_)) => "list",
            Some(RData::RForeign(_)) => "externalptr",
            Some(RData::Closure { .. }) | Some(RData::Combinator { .. }) => "closure",
            Some(RData::Builtin(name)) => builtin_type(name),
            Some(RData::Environment(_)) => "environment",
            Some(RData::Lang(_)) => "language",
            Some(RData::Sym(_)) => "symbol",
            Some(RData::Promise { .. }) => "promise",
        }
    }

    // ── environments ───────────────────────────────────────────────────

    /// The environment of the innermost frame.
    pub fn env(&self) -> Env {
        self.frames
            .last()
            .map(|f| f.env.clone())
            .unwrap_or_else(|| self.global.clone())
    }

    /// Look a name up through the environment chain.
    pub fn lookup(&self, name: &str) -> Option<Value> {
        self.lookup_from(self.env(), name)
    }

    /// Look a name up starting from `env` rather than from the current frame —
    /// what `get`, `exists` and `mget` do when handed an `envir`. The search
    /// still walks the enclosure chain, which is R's `inherits = TRUE` default.
    pub fn lookup_from(&self, env: Env, name: &str) -> Option<Value> {
        let mut e = Some(env);
        while let Some(cur) = e {
            if let Some(v) = cur.borrow().vars.get(name) {
                return Some(v.clone());
            }
            e = cur.borrow().parent.clone();
        }
        None
    }

    /// Whether `name` is a formal of the closure running in the current frame
    /// that the call left unbound — omitted, with no default to fill it. A
    /// defaulted formal is bound by the prologue before any read, and `...`
    /// is never read as a name.
    pub fn unsupplied_formal(&self, name: &str) -> bool {
        let Some(frame) = self.frames.last() else {
            return false;
        };
        let Some((id, _)) = &frame.fun else {
            return false;
        };
        if frame.promise || frame.env.borrow().vars.contains_key(name) {
            return false;
        }
        self.closures
            .get(*id)
            .is_some_and(|c| c.params.iter().any(|p| p == name))
    }

    /// Look up a name, skipping non-function bindings — R's function-position
    /// rule, which lets `c <- 1; c(1, 2)` still call the concatenate function.
    pub fn lookup_function(&self, name: &str) -> Option<Value> {
        let mut e = Some(self.env());
        while let Some(cur) = e {
            let hit = cur.borrow().vars.get(name).cloned();
            if let Some(v) = hit {
                if self.is_function(&v) {
                    return Some(v);
                }
            }
            e = cur.borrow().parent.clone();
        }
        None
    }

    /// The call now being evaluated, whatever kind it is. A warning raised
    /// inside a primitive reports this — `as.integer("x")` warns as
    /// `In as.integer("x") : NAs introduced by coercion`.
    pub fn current_call(&self) -> Option<String> {
        self.calls.last().map(|c| ctx_text(&c.text))
    }

    /// The same call, as whole R source. A *diagnostic* shows one line of it; a
    /// condition object carries the call itself, so it needs all of it.
    pub fn current_call_source(&self) -> Option<String> {
        self.calls.last().map(|c| ctx_source(&c.text))
    }

    /// The deparsed source of each argument in the call now being entered —
    /// what a diagnostic that quotes an argument back at the caller reads.
    /// Empty when the context is not a call, which leaves the caller to say
    /// nothing rather than something wrong.
    pub fn current_call_arg_sources(&self) -> Vec<String> {
        let Some(src) = self.current_call_source() else {
            return Vec::new();
        };
        let Ok(mut exprs) = crate::parser::parse(&src) else {
            return Vec::new();
        };
        if exprs.len() != 1 {
            return Vec::new();
        }
        let crate::ast::Expr::Call { args, .. } = exprs.remove(0) else {
            return Vec::new();
        };
        args.iter()
            .map(|a| {
                a.value
                    .as_ref()
                    .map(crate::deparse::deparse_first_line)
                    .unwrap_or_default()
            })
            .collect()
    }

    /// The call [`RHost::enclosing_call`] names, as whole R source.
    pub fn enclosing_call_source(&self) -> Option<String> {
        self.calls
            .iter()
            .rev()
            .skip(1)
            .find(|c| c.closure)
            .map(|c| ctx_source(&c.text))
    }

    /// The innermost *function* context — what R's C `warning()` reports when
    /// it is called from inside a primitive that has no call of its own, as
    /// `CoercionWarning` is. A primitive makes no context, so the warning lands
    /// on the closure containing it: `print(as.integer("x"))`, and nothing at
    /// all when that closure is the top level.
    pub fn context_call(&self) -> Option<String> {
        self.innermost_context(0)
    }

    /// [`Self::context_call`] as whole R source, for an error raised the way
    /// R's C `error()` raises one from inside a builtin.
    pub fn context_call_source(&self) -> Option<String> {
        self.enclosing_ctx(0).map(|c| ctx_source(&c.text))
    }

    /// R's `findCall`, which starts at `R_GlobalContext->nextcontext`: the
    /// innermost function context *outside* the call now running. `warning()`
    /// is itself a closure in R, so its own context is the one being skipped,
    /// and what is left is the function that called it.
    pub fn enclosing_call(&self) -> Option<String> {
        self.innermost_context(1)
    }

    fn innermost_context(&self, skip: usize) -> Option<String> {
        self.enclosing_ctx(skip).map(|c| ctx_text(&c.text))
    }

    /// The innermost enclosing closure call as whole R source — what
    /// `sys.call()` parses back into a language object. The same search
    /// `enclosing_call` runs for the diagnostics, and it skips one frame for
    /// the same reason: `sys.call()` is itself a call.
    /// How deep the context stack is counting only calls that have been
    /// ENTERED — the open-but-not-entered ones on top are calls whose own
    /// arguments are being evaluated right now.
    pub fn entered_ctx_depth(&self) -> usize {
        self.calls
            .iter()
            .rposition(|c| c.entered)
            .map_or(0, |i| i + 1)
    }

    /// R's `sys.nframe()`: how many function contexts lie at and below the
    /// one `sys.nframe()` was written in — `framedepth` of the context whose
    /// frame is the caller's, found by the same search `sys.call()` makes. A
    /// context below it counts whether or not it has been entered: a promise
    /// forced inside `print(f())` runs `f` with `print`'s context beneath it.
    pub fn nframe(&self) -> usize {
        self.sys_contexts().len()
    }

    /// The function contexts from the outermost call up to the one
    /// `sys.nframe()` was written in, outermost first — R's frame numbers
    /// `1..=sys.nframe()` index this list.
    fn sys_contexts(&self) -> Vec<&CallCtx> {
        let found = self
            .calls
            .iter()
            .enumerate()
            .rev()
            .filter(|(i, _)| !ctx_hidden(*i))
            .skip(1)
            .find(|(_, c)| c.closure && c.entered);
        match found {
            Some((k, _)) => self.calls[..=k].iter().filter(|c| c.closure).collect(),
            None => Vec::new(),
        }
    }

    /// Resolve R's `which` argument (`0` current, `n > 0` absolute, `n < 0`
    /// relative to the current frame) to a frame number, or the error R's
    /// `R_sysframe` raises when it names a frame that does not exist.
    pub fn sys_frame_number(&self, which: i64) -> Result<usize, String> {
        let cur = self.nframe() as i64;
        let target = if which > 0 { which } else { cur + which };
        if target < 0 || target > cur {
            return Err("not that many frames on the stack".into());
        }
        Ok(target as usize)
    }

    /// `sys.call(which)` as source; `None` for frame 0 (the top level).
    pub fn sys_call_source(&self, which: i64) -> Result<Option<String>, String> {
        let n = self.sys_frame_number(which)?;
        Ok(n.checked_sub(1)
            .and_then(|i| self.sys_contexts().get(i).map(|c| ctx_source(&c.text))))
    }

    /// Every active call, outermost first, as source — `sys.calls()`.
    pub fn sys_calls_source(&self) -> Vec<String> {
        self.sys_contexts()
            .iter()
            .map(|c| ctx_source(&c.text))
            .collect()
    }

    /// The closure running as frame `n` (1-based), as the `(id, env)` pair.
    pub fn sys_function_at(&self, n: usize) -> Option<(usize, Env)> {
        self.frames
            .iter()
            .filter(|f| !f.promise)
            .nth(n)
            .and_then(|f| f.fun.clone())
    }

    pub fn enclosing_source(&self) -> Option<String> {
        self.enclosing_source_from(1)
    }

    /// The same search, skipping `skip` contexts first.
    ///
    /// `sys.call()` and friends skip one because they are themselves calls with
    /// a context of their own. `substitute()` compiles to a `.rlang_*` shim,
    /// which makes no context at all, so it skips none — the innermost entered
    /// closure IS the frame whose formals it is asking about.
    pub fn enclosing_source_from(&self, skip: usize) -> Option<String> {
        self.calls
            .iter()
            .enumerate()
            .rev()
            .filter(|(i, _)| !ctx_hidden(*i))
            .skip(skip)
            .find(|(_, c)| c.closure && c.entered)
            .map(|(_, c)| ctx_source(&c.text))
    }

    fn enclosing_ctx(&self, skip: usize) -> Option<&CallCtx> {
        self.calls.iter().rev().skip(skip).find(|c| c.closure)
    }

    /// The formals of the closure now executing, for the builtins that have to
    /// know what a call's arguments were matched *against*.
    pub fn current_formals(&self) -> Option<Vec<String>> {
        let (id, _) = self.innermost_call()?.fun.as_ref()?;
        Some(self.closures.get(*id)?.params.clone())
    }

    /// The call frame code is running in now: the innermost non-promise frame
    /// that owns the current environment. A promise frame is evaluation of its
    /// writer's own expression, which R makes no frame for, and it may be
    /// forced several calls deeper than where it was written — `f(nargs())`
    /// inside `g` asks about `g`'s call however far down `f` reads it.
    pub fn innermost_call(&self) -> Option<&Frame> {
        let env = self.env();
        self.frames
            .iter()
            .rev()
            .find(|f| !f.promise && Rc::ptr_eq(&f.env, &env))
            .or_else(|| self.frames.iter().rev().find(|f| !f.promise))
    }

    /// The expression an unforced promise holds, with the environment it was
    /// written in — R's `PREXPR`/`PRENV`. The thunk `function() <expr>` the
    /// compiler wraps an argument in keeps its source, so the body is read
    /// back from there.
    pub fn promise_expr(&self, v: &Value) -> Option<(crate::ast::Expr, Env)> {
        let RData::Promise {
            thunk, value: None, ..
        } = &self.get(v)?.data
        else {
            return None;
        };
        let RData::Closure { id, env } = &self.get(thunk)?.data else {
            return None;
        };
        let src = self.closures.get(*id)?.src.join("\n");
        let mut exprs = crate::parser::parse(&src).ok()?;
        match exprs.pop() {
            Some(crate::ast::Expr::Function { params, body })
                if exprs.is_empty() && params.is_empty() =>
            {
                Some((*body, env.clone()))
            }
            _ => None,
        }
    }

    /// [`Self::promise_expr`] when the expression is a bare symbol.
    pub fn promise_symbol(&self, v: &Value) -> Option<(String, Env)> {
        match self.promise_expr(v)? {
            (crate::ast::Expr::Ident(s), env) => Some((s, env)),
            _ => None,
        }
    }

    /// R's `R_isMissing(symbol, rho)`: whether `name`, as bound in `env`, is an
    /// argument its caller never supplied — followed through a promise whose
    /// expression is itself a bare symbol, so `g <- function(y) f(y)` makes
    /// `missing(x)` in `f` answer for `g`'s `y`. rlang leaves an omitted formal
    /// with no default unbound, which is R's `R_MissingArg`; a formal the
    /// default filled in is R's `MISSING == 2` and does NOT count here (only
    /// `missing()` on the formal itself sees it), so a forwarded default reads
    /// as supplied, as it does in R.
    pub fn is_missing_in(&self, env: &Env, name: &str) -> bool {
        let bound = env.borrow().vars.get(name).cloned();
        match bound {
            None => self.frames.iter().rev().any(|f| {
                !f.promise
                    && Rc::ptr_eq(&f.env, env)
                    && f.fun
                        .as_ref()
                        .and_then(|(id, _)| self.closures.get(*id))
                        .is_some_and(|c| c.params.iter().any(|p| p == name))
            }),
            Some(v) => match self.promise_symbol(&v) {
                // `function(a = a)`: R's PRSEEN guard answers missing.
                Some((s, e)) if s == name && Rc::ptr_eq(&e, env) => true,
                Some((s, e)) => self.is_missing_in(&e, &s),
                None => false,
            },
        }
    }

    /// R's `parent.frame(n)`: the environment `n` calling generations above
    /// the one `parent.frame` was written in.
    ///
    /// A call's parent is the frame its call expression was *evaluated* in,
    /// not the frame below it on the stack: a closure called while a promise
    /// is forced was written in the promise's frame — whose environment is its
    /// writer's (see [`call_closure`]) — so the walk finds the innermost call
    /// frame owning that environment, as `do_parentframe` matches `cloenv`.
    /// Past the outermost call there is only the global environment.
    pub fn parent_frame_env(&self, n: usize) -> Env {
        let frame_of = |env: &Env, below: usize| {
            self.frames[..below]
                .iter()
                .rposition(|f| !f.promise && Rc::ptr_eq(&f.env, env))
        };
        let mut cur = frame_of(&self.env(), self.frames.len());
        for _ in 0..n {
            cur = match cur {
                Some(i) if i > 0 => frame_of(&self.frames[i - 1].env, i),
                _ => None,
            };
        }
        match cur {
            Some(i) => self.frames[i].env.clone(),
            None => self.global.clone(),
        }
    }

    /// Bind `name` in the current environment.
    pub fn set_var(&mut self, name: &str, val: Value) {
        let env = self.env();
        bind_in(&mut self.heap, &env, name, val);
    }

    /// Bind `name` in `env`, maintaining reference counts. Used by the call
    /// machinery, which binds into a frame environment that is not yet current.
    pub fn bind(&mut self, env: &Env, name: &str, val: Value) {
        bind_in(&mut self.heap, env, name, val);
    }

    /// Bind `name` in a binding environment (`<<-`): the first enclosing frame
    /// that already has it, else the global environment.
    pub fn set_super(&mut self, name: &str, val: Value) {
        let mut e = self.env().borrow().parent.clone();
        while let Some(cur) = e {
            let has = cur.borrow().vars.contains_key(name);
            if has {
                bind_in(&mut self.heap, &cur, name, val);
                return;
            }
            e = cur.borrow().parent.clone();
        }
        let g = self.global.clone();
        bind_in(&mut self.heap, &g, name, val);
    }

    /// Whether a name is bound anywhere in the chain.
    pub fn exists(&self, name: &str) -> bool {
        self.lookup(name).is_some()
    }

    /// The `...` bindings of the current frame, if any.
    pub fn dots(&self) -> Vec<(Option<String>, Value)> {
        match self.lookup("...").map(|v| self.data_of(&v)) {
            Some(RData::Args(a)) => a,
            _ => Vec::new(),
        }
    }

    /// Record an R error; the VM run unwinds and the message surfaces as the
    /// program's error.
    pub fn fail<T>(&mut self, msg: impl Into<String>) -> Option<T> {
        if self.error.is_none() {
            let call = self.current_call_source();
            self.set_error_call(call);
            self.error = Some(msg.into());
        }
        None
    }

    /// Decide which call the pending error reports. The first site to decide
    /// wins — `stop()` names its caller, a primitive that failed by returning
    /// `Err` names itself, and neither may be overwritten by a frame the unwind
    /// merely passes through.
    pub fn set_error_call(&mut self, call: Option<String>) {
        if self.error_call_known {
            return;
        }
        self.error_trace = self
            .calls
            .iter()
            .filter(|c| c.closure)
            .map(|c| ctx_source(&c.text))
            .collect();
        self.error_call = call;
        self.error_call_known = true;
    }

    /// Give the decision back: a handler took the error, so the next one starts
    /// over.
    pub fn clear_error_call(&mut self) {
        self.error_call = None;
        self.error_condition = None;
        self.error_trace.clear();
        self.error_call_known = false;
    }

    /// Take and clear a pending error.
    pub fn take_error(&mut self) -> Option<String> {
        self.error.take()
    }
}

/// Parse a numeric literal the way `as.numeric` does, including `Inf`/`NaN`.
/// An unboxed length-1 atomic carried directly on the fusevm stack (no RHost
/// heap object), used for scalar-heavy code like `for`/`while` loop bodies.
/// `Value::Int/Float/Bool` are R's length-1 integer/double/logical with no
/// attributes; every host accessor maps them to that vector view so any builtin
/// consumes them transparently.
enum Ub {
    I(i64),
    F(f64),
    B(bool),
}

fn unboxed(v: &Value) -> Option<Ub> {
    match v {
        Value::Int(n) => Some(Ub::I(*n)),
        Value::Float(f) => Some(Ub::F(*f)),
        Value::Bool(b) => Some(Ub::B(*b)),
        _ => None,
    }
}

fn parse_num(s: &str) -> Option<f64> {
    match s {
        "Inf" => Some(f64::INFINITY),
        "-Inf" => Some(f64::NEG_INFINITY),
        "NaN" => Some(f64::NAN),
        _ => {
            // R accepts C-style hexadecimal (`0x1F`, `-0xff`) in numeric coercion.
            if let Some(hex) = s
                .strip_prefix("0x")
                .or_else(|| s.strip_prefix("0X"))
                .or_else(|| s.strip_prefix("-0x").or_else(|| s.strip_prefix("-0X")))
            {
                let neg = s.starts_with('-');
                return i64::from_str_radix(hex, 16)
                    .ok()
                    .map(|n| if neg { -n } else { n } as f64);
            }
            s.parse().ok()
        }
    }
}

thread_local! {
    /// Significant digits for numeric printing — R's `getOption("digits")`,
    /// default 7. `print(x, digits = n)` overrides it for one call.
    static PRINT_DIGITS: std::cell::Cell<usize> = const { std::cell::Cell::new(7) };
    /// R's `getOption("scipen")`, default 0: the penalty added to the width of
    /// a scientific rendering before it is compared with the fixed one, so a
    /// positive value biases towards fixed and a negative one towards
    /// scientific. R clamps it below at -9.
    static PRINT_SCIPEN: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
    /// R's `getOption("OutDec")`, default `"."`: the decimal mark `print`,
    /// `format` and `as.character` write in place of the point.
    static OUT_DEC: std::cell::RefCell<String> = std::cell::RefCell::new(".".into());
}

/// Put `getOption("OutDec")` in place of the decimal point of one rendered
/// number, as R's `encodeReal0` does for the fixed form and the scientific
/// mantissa alike. `deparse` keeps the point, so only the user-facing
/// formatters call this, never [`render_fixed`]/[`render_sci`] themselves.
pub fn out_dec(s: String) -> String {
    OUT_DEC.with(|d| {
        let d = d.borrow();
        if d.as_str() == "." {
            s
        } else {
            s.replacen('.', &d, 1)
        }
    })
}

/// Run `f` with the decimal mark forced back to `"."` — for renderings that
/// must read back as R source (`deparse`, `dput`), which R never localises.
pub fn with_point<T>(f: impl FnOnce() -> T) -> T {
    let prev = OUT_DEC.with(|d| std::mem::replace(&mut *d.borrow_mut(), ".".into()));
    let out = f();
    OUT_DEC.with(|d| *d.borrow_mut() = prev);
    out
}

/// Significant digits `as.character`, `paste` and `toString` render doubles at.
/// Unlike `print`/`format`, these do NOT follow `getOption("digits")`: R fixes
/// them at 15, which is why `as.character(pi)` is "3.14159265358979" whatever
/// `digits` is set to. They do still follow `scipen`.
pub const AS_CHARACTER_DIGITS: usize = 15;

/// R's lower clamp on `scipen`; `options(scipen = -10)` warns and uses -9.
pub const SCIPEN_MIN: i32 = -9;

/// The current significant-digit setting for numeric printing.
pub fn print_digits() -> usize {
    PRINT_DIGITS.with(|c| c.get())
}

/// Set the significant-digit setting; returns the previous value so a caller can
/// restore it after a one-off `print(x, digits = n)`.
pub fn set_print_digits(d: usize) -> usize {
    PRINT_DIGITS.with(|c| c.replace(d.max(1)))
}

/// The current fixed-versus-scientific bias.
pub fn print_scipen() -> i32 {
    PRINT_SCIPEN.with(|c| c.get())
}

/// Set the fixed-versus-scientific bias, clamped the way R clamps it; returns
/// the previous value so a caller can restore it.
pub fn set_print_scipen(s: i32) -> i32 {
    PRINT_SCIPEN.with(|c| c.replace(s.max(SCIPEN_MIN)))
}

/// Run `f` with `digits` temporarily set, restoring the previous value after.
/// Every one-off digit override (`print(x, digits =)`, `format(x, digits =)`,
/// the fixed-15 `as.character` family) goes through here so none of them can
/// leak into `getOption("digits")`.
pub fn with_print_digits<T>(digits: usize, f: impl FnOnce() -> T) -> T {
    let prev = set_print_digits(digits);
    let out = f();
    set_print_digits(prev);
    out
}

/// A value held in R's global options list. `options` accepts any name, so the
/// store has to hold whatever an unrecognised one was set to as well as the
/// settings rlang acts on.
#[derive(Clone, Debug, PartialEq)]
pub enum OptionValue {
    Int(i64),
    Dbl(f64),
    Str(String),
    Lgl(bool),
}

thread_local! {
    /// Options other than `digits` and `scipen`. Those two are NOT kept here:
    /// they live in `PRINT_DIGITS` / `PRINT_SCIPEN`, which the formatting code
    /// reads once per value, and `option_get`/`option_set` route their names to
    /// those cells. Keeping one store per setting is what stops the two from
    /// drifting apart.
    static OTHER_OPTIONS: std::cell::RefCell<std::collections::HashMap<String, OptionValue>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

/// R's legal range for `options(digits = )`; outside it R raises
/// "invalid 'digits' parameter, allowed 1...22".
pub const DIGITS_MIN: i64 = 1;
pub const DIGITS_MAX: i64 = 22;

/// The current value of option `name`, or `None` if it has never been set.
pub fn option_get(name: &str) -> Option<OptionValue> {
    match name {
        "digits" => Some(OptionValue::Int(print_digits() as i64)),
        "scipen" => Some(OptionValue::Int(print_scipen() as i64)),
        "OutDec" => Some(OptionValue::Str(OUT_DEC.with(|d| d.borrow().clone()))),
        // `warn` reads as 0 until something sets it, the way R's does.
        "warn" => Some(
            OTHER_OPTIONS
                .with(|o| o.borrow().get(name).cloned())
                .unwrap_or(OptionValue::Int(0)),
        ),
        _ => OTHER_OPTIONS.with(|o| o.borrow().get(name).cloned()),
    }
}

/// Set option `name`, returning its previous value and any warning text the
/// caller should emit. `digits` and `scipen` are validated the way R validates
/// them: `digits` outside 1..22 is an error, `scipen` below -9 warns and clamps.
/// The warning is handed back rather than printed here so that emitting it stays
/// with the builtin layer that owns R's warning format.
pub fn option_set(
    name: &str,
    value: OptionValue,
) -> Result<(Option<OptionValue>, Option<String>), String> {
    let prev = option_get(name);
    let mut warning = None;
    match name {
        "digits" => {
            let d = match value {
                OptionValue::Int(n) => n,
                OptionValue::Dbl(x) if x.is_finite() => x.trunc() as i64,
                _ => return Err("invalid 'digits' parameter, allowed 1...22".into()),
            };
            if !(DIGITS_MIN..=DIGITS_MAX).contains(&d) {
                return Err("invalid 'digits' parameter, allowed 1...22".into());
            }
            set_print_digits(d as usize);
        }
        "scipen" => {
            let s = match value {
                OptionValue::Int(n) => n,
                OptionValue::Dbl(x) if x.is_finite() => x.trunc() as i64,
                _ => return Err("invalid 'scipen' parameter".into()),
            };
            let s = s.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
            if s < SCIPEN_MIN {
                warning = Some(format!("invalid 'scipen' {s}, used {SCIPEN_MIN}"));
            }
            set_print_scipen(s);
        }
        // R's `do_options`: a non-string is an error; a string that is not
        // one character warns and is used anyway.
        "OutDec" => {
            let OptionValue::Str(dec) = value else {
                return Err("invalid value for 'OutDec'".into());
            };
            if dec.chars().count() != 1 {
                warning = Some("'OutDec' must be a string of one character".into());
            }
            OUT_DEC.with(|d| *d.borrow_mut() = dec);
        }
        _ => {
            OTHER_OPTIONS.with(|o| o.borrow_mut().insert(name.to_string(), value));
        }
    }
    Ok((prev, warning))
}

/// R's fixed-versus-scientific choice, given the two candidate widths.
///
/// R picks fixed exactly when `width(fixed) <= width(scientific) + scipen`, so
/// ties go to fixed and `scipen` shifts the threshold. Verified against R 4.6.1
/// over 57354 comparisons — every `digits` in 1..22 crossed with `scipen` in
/// {-9,-5,-2,-1,0,1,2,3,5,10,50} over 237 values spanning 1e-300 .. 1e300 and
/// both signs — with zero mismatches, taking R's own `format(x, scientific =
/// FALSE)` and `format(x, scientific = TRUE)` as the two widths so the test
/// assumed nothing about how either rendering is built.
///
/// This is the single place the choice is made; callers must not compare the
/// two widths themselves, or `scipen` silently stops applying at that site.
pub fn prefers_fixed(fixed_width: usize, sci_width: usize) -> bool {
    (fixed_width as i64) <= sci_width as i64 + print_scipen() as i64
}

/// Decimal places a fixed-notation rendering of `x` needs at the current
/// significant-digit setting, with trailing zeros dropped.
pub fn fixed_decimals(x: f64) -> usize {
    if !x.is_finite() || (x == x.trunc() && x.abs() < 1e15) {
        return 0;
    }
    let mag = x.abs().log10().floor() as i32;
    // Enough places to keep `print_digits()` significant digits even for tiny
    // magnitudes: a 15-place cap rounded values like `1e-17` down to `0`, so
    // `format_dbl` then judged fixed "0" narrower than scientific and printed
    // the wrong, lossy form. The double exponent range bounds the real need.
    let sig = print_digits() as i32;
    let d = ((sig - 1) - mag).clamp(0, 340) as usize;
    let s = format!("{x:.d$}");
    let trimmed = s.trim_end_matches('0');
    match trimmed.split_once('.') {
        Some((_, frac)) => frac.len(),
        None => 0,
    }
}

/// `x` in R's scientific spelling at `decimals` mantissa places: mantissa, `e`,
/// an explicit sign, and at least two exponent digits (`1e+05`, `1.5e-05`).
///
/// The mantissa comes from Rust's `{:.*e}`, which rounds correctly from the
/// exact binary value. The previous approach — dividing by `10f64.powi(mag)`
/// and formatting the quotient — was lossy, and the loss surfaced as soon as
/// `digits` could be set above the default: at `digits = 16`, `6.022e23`
/// divided down to `6.022000000000001`, so no trailing zeros trimmed and R's
/// `6.022e+23` printed as `6.022000000000001e+23`. Correct rounding also agrees
/// with the platform's `snprintf` (checked directly against a C `%.20e`), which
/// is the renderer R's own `formatReal` reaches for.
fn r_sci(x: f64, decimals: usize) -> String {
    let s = format!("{x:.decimals$e}");
    // Rust writes the exponent bare (`1.5e-5`); R pads it to two digits and
    // always signs it. `{:e}` already normalises the mantissa into [1, 10) and
    // carries `9.9999999` up to `1e1`, so nothing else needs adjusting.
    let (mant, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
    let e: i32 = exp.parse().unwrap_or(0);
    format!("{mant}e{}{:02}", if e < 0 { '-' } else { '+' }, e.abs())
}

/// Mantissa decimal places a scientific rendering of `x` needs at the current
/// significant-digit setting, with trailing zeros dropped (`1e+05` needs none,
/// `1.5e-05` needs one).
pub fn sci_decimals(x: f64) -> usize {
    if !x.is_finite() || x == 0.0 {
        return 0;
    }
    let prec = print_digits().saturating_sub(1);
    let s = r_sci(x, prec);
    let mant = s.split_once('e').map_or(s.as_str(), |(m, _)| m);
    match mant.trim_end_matches('0').split_once('.') {
        Some((_, frac)) => frac.len(),
        None => 0,
    }
}

/// Fixed-notation rendering with a given number of decimals; the non-finite
/// values keep R's spellings.
pub fn render_fixed(x: f64, decimals: usize) -> String {
    if x.is_nan() {
        return "NaN".into();
    }
    if x.is_infinite() {
        return if x > 0.0 { "Inf" } else { "-Inf" }.into();
    }
    // R never prints a negative zero: `0 * -2` is `0`, not `-0`. `-0.0 == 0.0`,
    // so this collapses the sign without touching any nonzero value.
    let x = if x == 0.0 { 0.0 } else { x };
    format!("{x:.decimals$}")
}

/// Scientific rendering with a given mantissa width, in R's shape: at least two
/// exponent digits and an explicit sign (`1e+05`, `1.5e-05`).
pub fn render_sci(x: f64, decimals: usize) -> String {
    if !x.is_finite() {
        return render_fixed(x, 0);
    }
    // `%e` already normalises the mantissa into [1, 10), carries `9.9999999`
    // up to `1e+01` rather than leaving `10e+00`, and pads the exponent to two
    // digits — so there is nothing left to adjust here.
    r_sci(if x == 0.0 { 0.0 } else { x }, decimals)
}

/// Format one double the way R prints it: at `getOption("digits")` significant
/// digits, taking fixed or scientific notation by [`prefers_fixed`] — which is
/// why `1e5` prints as `1e+05` but `123456789` stays fixed at the default
/// `scipen = 0`, and why raising `scipen` turns the first into `100000`.
pub fn format_dbl(x: f64) -> String {
    let fixed = render_fixed(x, fixed_decimals(x));
    if !x.is_finite() {
        return fixed;
    }
    let sci = render_sci(x, sci_decimals(x));
    out_dec(
        if prefers_fixed(fixed.chars().count(), sci.chars().count()) {
            fixed
        } else {
            sci
        },
    )
}

// ===========================================================================
// Running chunks: the program, closure bodies, loop bodies.
// ===========================================================================

/// Register every rlang builtin on a fresh VM and run `chunk` on it.
pub fn run_chunk(chunk: Chunk) -> Result<Value, String> {
    let mut vm = fresh_vm(chunk);
    let r = drive(&mut vm);
    // A top-level or one-shot chunk has no owner to be cached against, so the
    // VM is dropped; its cost was the allocation, which the closure cache is
    // what avoids.
    r
}

thread_local! {
    /// One parked VM per closure id, each still holding that closure's chunk.
    ///
    /// Every R call runs its body on a nested VM, and building one is not cheap:
    /// `VM::new` allocates the stack, frame and globals vectors and a JIT
    /// compiler, [`crate::builtins::install`] registers the whole builtin table
    /// on top, and the body chunk has to be *cloned* in because the VM owns it.
    /// A closure called in a loop paid all of that per iteration. Parking the VM
    /// under its closure id means the next call to the same closure reuses the
    /// allocations, the builtin table and the chunk already in place —
    /// `VM::reset` keeps the table and the hooks, and the chunk is moved out and
    /// straight back rather than cloned.
    ///
    /// A recursive (or otherwise re-entrant) call finds the slot empty, because
    /// the outer call took the VM out for the duration, and builds a fresh one —
    /// which is what keeps each activation's chunk state its own.
    /// Indexed by closure id — the ids are dense and small, so a vector beats a
    /// map, and the `Box` means parking and taking a VM moves a pointer rather
    /// than the whole `VM` struct.
    static CLOSURE_VMS: RefCell<Vec<Option<Box<VM>>>> = const { RefCell::new(Vec::new()) };
}

/// A VM ready to run `chunk`: allocations, builtin table and hooks all in place.
fn fresh_vm(chunk: Chunk) -> VM {
    let mut vm = VM::new(chunk);
    crate::builtins::install(&mut vm);
    vm
}

/// Run closure `id`'s body on its parked VM, parking it again afterwards.
fn run_closure_chunk(id: usize) -> Result<Value, String> {
    let parked = CLOSURE_VMS.with(|c| c.borrow_mut().get_mut(id).and_then(Option::take));
    let mut vm = match parked {
        Some(mut vm) => {
            // The chunk is already this closure's: move it out and hand it back
            // to `reset`, which clears the stack, frames, globals and ip while
            // keeping the builtin table and the numeric hook.
            let chunk = std::mem::take(&mut vm.chunk);
            vm.reset(chunk);
            vm
        }
        // First call, or a re-entrant one whose VM is checked out: this is the
        // only path that copies the body.
        None => {
            let chunk = with_host(|h| h.closures.get(id).map(|d| d.chunk.clone()))
                .ok_or_else(|| format!("internal: unknown closure #{id}"))?;
            Box::new(fresh_vm(chunk))
        }
    };
    let r = drive(&mut vm);
    CLOSURE_VMS.with(|c| {
        let mut slots = c.borrow_mut();
        if slots.len() <= id {
            slots.resize_with(id + 1, || None);
        }
        slots[id] = Some(vm);
    });
    r
}

// ===========================================================================
// Operator call sites, for the warnings an operator raises.
// ===========================================================================

/// The tag that opens a chunk's operator-site table: one constant, an array of
/// this tag followed by `(op index, deparsed operator call)` pairs. The
/// compiler attaches it when it builds the chunk ([`op_sites_constant`]);
/// nothing loads it, so it costs the running program nothing, and it travels
/// with the chunk through the bytecode cache. It is read only when an operator
/// actually warns.
const OP_SITES_TAG: &str = "\u{1}rlang.op_sites";

/// The constant holding a chunk's operator sites.
pub fn op_sites_constant(sites: Vec<(usize, String)>) -> Value {
    let mut table = Vec::with_capacity(1 + 2 * sites.len());
    table.push(Value::str(OP_SITES_TAG));
    for (ip, text) in sites {
        table.push(Value::Int(ip as i64));
        table.push(Value::str(text));
    }
    Value::Array(std::sync::Arc::new(table))
}

/// Which operator the innermost running VM is evaluating.
#[derive(Clone)]
pub enum OpSite {
    /// A native `+ - *` or a `BINOP` builtin: its op index in the running chunk.
    Op(usize),
    /// `%%` / `%/%`, whose `SPECIAL` op carries the call text itself.
    Text(Value),
}

/// The chunk the innermost VM is running and the operator it is in.
struct OpContext {
    chunk: *const Chunk,
    site: Option<OpSite>,
}

thread_local! {
    static OP_CONTEXT: RefCell<OpContext> = const {
        RefCell::new(OpContext {
            chunk: std::ptr::null(),
            site: None,
        })
    };
}

/// Run `f` as the evaluation of the operator at `site` in the running chunk, so
/// a warning raised inside can name it.
pub fn in_op_site<T>(site: OpSite, f: impl FnOnce() -> T) -> T {
    let prev = OP_CONTEXT.with(|c| c.borrow_mut().site.replace(site));
    let out = f();
    OP_CONTEXT.with(|c| c.borrow_mut().site = prev);
    out
}

/// The operator call R's `warningcall` names for a warning the current operator
/// raises — `1:3 + 1:2` for its recycling warning — as one line: the first
/// line of [`ctx_source`], which is how a diagnostic shows a call; `None`
/// outside an operator, or where the chunk
/// recorded no site for it.
pub fn op_site_call() -> Option<String> {
    op_site_value().map(|v| ctx_text(&v))
}

/// [`op_site_call`] as whole R source, for the call of an error the operator
/// raises (`Error in 1 + "a" : …`), which the error report folds itself.
pub fn op_site_source() -> Option<String> {
    op_site_value().map(|v| ctx_source(&v))
}

/// The current operator's deparsed call, as the constant that holds it.
fn op_site_value() -> Option<Value> {
    let (chunk, site) = OP_CONTEXT.with(|c| {
        let c = c.borrow();
        (c.chunk, c.site.clone())
    });
    match site? {
        OpSite::Text(v) => Some(v),
        OpSite::Op(_) if chunk.is_null() => None,
        OpSite::Op(ip) => {
            // SAFETY: `chunk` belongs to the VM that `drive` is running further
            // down this thread's stack. `drive` puts the previous pointer back
            // before that VM can be moved or dropped, and a running VM never
            // mutates its own chunk.
            let chunk = unsafe { &*chunk };
            let table = chunk.constants.iter().rev().find_map(|c| match c {
                Value::Array(t) if matches!(t.first(), Some(Value::Str(s)) if s.as_str() == OP_SITES_TAG) => {
                    Some(t)
                }
                _ => None,
            })?;
            table[1..].chunks_exact(2).find_map(|pair| match pair {
                [Value::Int(at), text] if *at == ip as i64 => Some(text.clone()),
                _ => None,
            })
        }
    }
}

/// Run a prepared VM to completion and read its outcome.
fn drive(vm: &mut VM) -> Result<Value, String> {
    // A nested VM starts a fresh operator context: none of the caller's sites
    // are its own, and its op indices address its own chunk.
    let outer = OP_CONTEXT.with(|c| {
        std::mem::replace(
            &mut *c.borrow_mut(),
            OpContext {
                chunk: &vm.chunk as *const Chunk,
                site: None,
            },
        )
    });
    let out = drive_unwound(vm);
    OP_CONTEXT.with(|c| *c.borrow_mut() = outer);
    out
}

/// [`drive`]'s body: run the VM, then cut the call stack back.
fn drive_unwound(vm: &mut VM) -> Result<Value, String> {
    // An `OPEN_CALL` in this chunk whose `CALL_OPENED` never ran — an argument
    // errored, or a `return`/`break` jumped past it — would leave its context
    // behind. Unwinding lands here, so the stack is cut back to the depth this
    // chunk started at however it ends.
    let depth = with_host(|h| h.calls.len());
    let out = drive_inner(vm);
    with_host(|h| h.calls.truncate(depth));
    out
}

fn drive_inner(vm: &mut VM) -> Result<Value, String> {
    // The tracing JIT is deliberately NOT enabled. It cannot compile R: fusevm's
    // tracer rejects any trace containing `Op::CallBuiltin` (builtin bodies are
    // arbitrary Rust it can't lower to Cranelift IR), and R lowers nearly every
    // operation — element fetch, comparisons, `%%`, indexing — to a builtin. So
    // for R the tracer never produces native code, yet its per-backward-branch
    // trace-cache lookup (a hashed probe) runs every loop iteration. Profiling a
    // scalar loop showed ~12% of time in that bookkeeping; turning the tracer off
    // is a measured ~12% speedup with zero loss of compilation (there was none).
    // AOT (`--aot`) is a separate Cranelift path and is unaffected.
    let outcome = vm.run();
    if let Some(e) = with_host(|h| h.take_error()) {
        return Err(e);
    }
    match outcome {
        VMResult::Ok(v) => Ok(v),
        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
        VMResult::Error(e) => Err(e),
    }
}

/// Run the top-level program chunk.
pub fn run_main(chunk: Chunk) -> Result<Value, String> {
    let r = run_chunk(chunk);
    with_host(|h| h.signal = None);
    // A program that ended normally has already flushed after its last
    // statement; one that unwound has not, and R prints that leftover batch
    // *after* the error line — so leave it to the caller (see `main.rs`).
    if r.is_ok() {
        flush_warnings(false);
    }
    r
}

/// R's `nwarnings`: the most warnings one top-level statement keeps.
pub const MAX_WARNINGS: usize = 50;

/// Queue `msg` for the end of the current top-level statement.
///
/// `options(warn = 0)` (the default) defers; a positive `warn` prints at once;
/// a negative one drops the warning entirely.
pub fn queue_warning(msg: &str, call: Option<String>) {
    match warn_level() {
        w if w < 0 => {}
        0 => with_host(|h| {
            h.warn_count += 1;
            if h.warnings.len() < MAX_WARNINGS {
                h.warnings.push(Warning {
                    msg: msg.to_string(),
                    call,
                });
            }
        }),
        // `warn = 1` prints where the warning happens, under its own banner.
        // R's `vwarningcall_dflt` allows 18 columns for the `Warning in ` and
        // ` : ` around the call before deciding whether the message still fits.
        _ => {
            let text = match &call {
                None => format!("Warning: {msg}\n"),
                Some(c) => format!("Warning in {c} :{}", fold(c, msg, 18)),
            };
            emit_stderr(&text);
        }
    }
}

/// R's `LONGWARN`: the column past which a warning's first line is folded onto
/// the next, indented.
const LONGWARN: usize = 75;

/// The tail of a warning line, from just after `<call> :` — either ` msg` on
/// the same line, or a fold onto the next line indented two spaces. R keeps the
/// message on the line when `overhead + width(call) + width(msg's first line)`
/// fits in [`LONGWARN`]; `overhead` is R's allowance for the decoration around
/// the call, which differs per banner.
fn fold(call: &str, msg: &str, overhead: usize) -> String {
    let first = msg.split('\n').next().unwrap_or(msg);
    let width = |s: &str| crate::strwidth::display_width(s);
    if overhead + width(call) + width(first) > LONGWARN {
        format!("\n  {msg}\n")
    } else {
        format!(" {msg}\n")
    }
}

/// Print and clear the warnings the finished statement queued, in R's three
/// shapes: one warning under a singular banner, up to ten numbered under a
/// plural one, and more than that as a count. `after_error` adds the
/// `In addition: ` R prefixes the batch with when the statement also failed.
pub fn flush_warnings(after_error: bool) {
    let (msgs, count) = with_host(|h| {
        (
            std::mem::take(&mut h.warnings),
            std::mem::replace(&mut h.warn_count, 0),
        )
    });
    if count == 0 {
        return;
    }
    let lead = if after_error { "In addition: " } else { "" };
    // R's `PrintWarnings` allows 6 columns of decoration around the call for a
    // lone warning and 10 for a numbered one — the extra 4 being the `N: `
    // prefix — before deciding whether the message still fits on the line.
    let text = if count == 1 {
        format!("{lead}Warning message:\n{}", warning_line(&msgs[0], 6))
    } else if count <= 10 {
        let body: String = msgs
            .iter()
            .enumerate()
            .map(|(i, w)| format!("{}: {}", i + 1, warning_line(w, 10)))
            .collect();
        format!("{lead}Warning messages:\n{body}")
    } else if count < MAX_WARNINGS {
        format!("{lead}There were {count} warnings (use warnings() to see them)\n")
    } else {
        format!(
            "{lead}There were {MAX_WARNINGS} or more warnings (use warnings() to see the first {MAX_WARNINGS})\n"
        )
    };
    emit_stderr(&text);
}

/// An uncaught error as R's `verrorcall_dflt` writes it: `Error in <call> : `
/// then the message, folded onto the next line and indented two spaces when the
/// line would run past `LONGWARN`. R allows 14 columns for the decoration
/// around the call. Without a call it is a bare `Error: `, which is what a
/// `stop()` at top level produces.
pub fn error_report(msg: &str, call: Option<&str>) -> String {
    // One line, like every other diagnostic: the call is held as whole source
    // for the condition object's sake.
    match call.and_then(|c| c.lines().next()) {
        None => format!("Error: {msg}\n"),
        // The trailing space after the colon is R's, and survives the fold.
        Some(c) => format!("Error in {c} : {}", fold_error(c, msg)),
    }
}

/// R's `R_NShowCalls`: how much of the traceback is shown before its middle is
/// elided.
const N_SHOW_CALLS: usize = 50;

/// R's `R_ConciseTraceback` — the `Calls:` line under an uncaught error.
///
/// `frames` is the deparsed call of every function context the error was raised
/// under, innermost last; `call` is the one the error itself reports. The chain
/// reads outermost first and names functions, not calls: a callee that is not a
/// plain symbol shows as `<Anonymous>`.
///
/// `stop`, `warning` and the suppress wrappers clear everything collected
/// *inside* them, which is what keeps `stop()`'s own frame and the machinery
/// under it out of the chain. A chain naming nothing but the call the error
/// already reported is dropped — R does not repeat itself — and a long one is
/// elided in the middle, keeping the outermost frame and the innermost few.
pub fn traceback(frames: &[String], call: Option<&str>) -> Option<String> {
    // Collected innermost-first and reversed at the end, so a reset drops
    // exactly what was seen inside the frame that triggered it.
    let mut names: Vec<String> = Vec::new();
    let mut ncalls = 0usize;
    let mut top: Option<String> = None;
    let mut elided = false;
    for text in frames.iter().rev() {
        let this = call_name(text);
        if matches!(
            this.as_str(),
            "stop" | "warning" | "suppressWarnings" | ".signalSimpleWarning"
        ) {
            names.clear();
            ncalls = 0;
            top = None;
            elided = false;
            continue;
        }
        ncalls += 1;
        if elided || names.join(" -> ").len() > N_SHOW_CALLS {
            elided = true;
            top = Some(this);
        } else {
            names.push(this);
        }
    }
    let mut out = names
        .iter()
        .rev()
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(" -> ");
    if elided {
        out = match top.filter(|t| t.len() < 50) {
            Some(t) => format!("{t} ... {out}"),
            None => format!("... {out}"),
        };
    }
    if ncalls == 1 && call.map(call_name).as_deref() == Some(out.as_str()) {
        return None;
    }
    (!out.is_empty()).then_some(out)
}

/// The function name a traceback shows for a call: the callee when it is a
/// plain symbol, `<Anonymous>` for anything else — a call in function position,
/// a function literal. Read off the deparsed text, where the callee is
/// everything before the argument list.
fn call_name(text: &str) -> String {
    let head = text.lines().next().unwrap_or_default();
    let head = head.split('(').next().unwrap_or_default();
    let head = head
        .strip_prefix('`')
        .and_then(|h| h.strip_suffix('`'))
        .unwrap_or(head);
    match crate::deparse::is_syntactic_name(head) {
        true => head.to_string(),
        false => "<Anonymous>".into(),
    }
}

/// The message half of an `Error in <call> : ` line — R's `tail` is `"\n  "`,
/// appended before the message when the first line would not fit.
fn fold_error(call: &str, msg: &str) -> String {
    let first = msg.split('\n').next().unwrap_or(msg);
    let width = |s: &str| crate::strwidth::display_width(s);
    if 14 + width(call) + width(first) > LONGWARN {
        format!("\n  {msg}\n")
    } else {
        format!("{msg}\n")
    }
}

/// One queued warning as `PrintWarnings` writes it: the message followed by a
/// space when it carries no call, and `In <call> : <message>` when it does.
fn warning_line(w: &Warning, overhead: usize) -> String {
    match &w.call {
        None => format!("{} \n", w.msg),
        Some(c) => format!("In {c} :{}", fold(c, &w.msg, overhead)),
    }
}

/// The current `options(warn = )`, which defaults to 0 as it does in R.
pub fn warn_level() -> i64 {
    match option_get("warn") {
        Some(OptionValue::Int(n)) => n,
        Some(OptionValue::Dbl(x)) if x.is_finite() => x.trunc() as i64,
        _ => 0,
    }
}

/// Force every promise in an argument list — what a callee that binds no
/// formals (a primitive, a combinator, a foreign handle) needs before it can
/// look at what it was passed.
pub fn force_all(
    args: Vec<(Option<String>, Value)>,
) -> Result<Vec<(Option<String>, Value)>, String> {
    if !args.iter().any(|(_, v)| {
        with_host(|h| matches!(h.get(v).map(|o| &o.data), Some(RData::Promise { .. })))
    }) {
        return Ok(args);
    }
    let mut out = Vec::with_capacity(args.len());
    for (n, v) in args {
        out.push((n, force_value(&v)?));
    }
    Ok(out)
}

thread_local! {
    /// Set for the duration of one `call_closure` entry, so the frame it makes
    /// can mark itself a promise frame. A flag rather than a parameter because
    /// the call goes through `call_value`, which every other caller shares.
    static FORCING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// `(from, to)` for each promise being forced: the stretch of the call
    /// stack that stands between where its expression was written and where it
    /// is being evaluated. Only the "whose expression is this?" walkers skip
    /// it — see [`RHost::enclosing_source_from`].
    static HIDDEN: std::cell::RefCell<Vec<(usize, usize)>> = const {
        std::cell::RefCell::new(Vec::new())
    };
}

/// Whether context index `i` is inside a promise's hidden stretch.
fn ctx_hidden(i: usize) -> bool {
    HIDDEN.with(|s| s.borrow().iter().any(|(lo, hi)| i >= *lo && i < *hi))
}

/// Force a promise: run the argument expression it holds, in the environment
/// the caller wrote it in, and remember the answer.
///
/// R evaluates an argument at most once and only if it is read, which is what
/// makes `f(stop("boom"))` legal for an `f` that never touches its formal.
/// Every place that READS a binding goes through here; anything that is not a
/// promise is handed straight back, so the call is free for the common case.
pub fn force_value(v: &Value) -> Result<Value, String> {
    // Two steps, deliberately: the memo is read (and the borrow dropped) before
    // the thunk runs, because forcing re-enters the interpreter and a live host
    // borrow across that is a panic.
    let Some((thunk, memo, depth)) = with_host(|h| match h.get(v).map(|o| &o.data) {
        Some(RData::Promise {
            thunk,
            value,
            ctx_depth,
        }) => Some((thunk.clone(), value.clone(), *ctx_depth)),
        _ => None,
    }) else {
        return Ok(v.clone());
    };
    if let Some(done) = memo {
        return Ok(done);
    }
    // The stack between where the argument was written and here is the
    // machinery of getting the promise forced — the callee's own context, and
    // whatever it called on the way. It is HIDDEN rather than removed: R keeps
    // it, so a warning raised while forcing still reports the callee (`In
    // print(as.integer("x")) : NAs introduced by coercion`), and only the
    // walkers that ask "whose expression is this?" — `substitute`, `sys.call`
    // — look past it to the frame that wrote the argument.
    let out = eval_promise_thunk(&thunk, depth)?;
    with_host(|h| {
        retain(&mut h.heap, &out);
        if let Some(o) = h.get_mut(v) {
            if let RData::Promise { value, .. } = &mut o.data {
                *value = Some(out.clone());
            }
        }
    });
    Ok(out)
}

/// Run a promise's `thunk` — a zero-argument closure over the environment that
/// wrote the expression — the way R evaluates a promise: in that environment
/// itself, with no frame of its own, and with the contexts from `depth` (how
/// deep the stack stood where the expression was written) to here hidden from
/// the walkers that ask whose expression it is.
pub fn eval_promise_thunk(thunk: &Value, depth: usize) -> Result<Value, String> {
    HIDDEN.with(|s| s.borrow_mut().push((depth, with_host(|h| h.calls.len()))));
    FORCING.with(|f| f.set(true));
    let out = call_value(thunk, Vec::new(), None);
    FORCING.with(|f| f.set(false));
    HIDDEN.with(|s| {
        s.borrow_mut().pop();
    });
    out
}

/// R's `findFun`: the first binding of `name`, from the current frame outward,
/// that is a function — forcing a promise on the way to see what it holds, so
/// a function factory's unforced argument (`function(f) function(x) f(x)`) is
/// callable. A binding that is not a function, forced or not, is passed over.
pub fn lookup_function_forcing(name: &str) -> Result<Option<Value>, String> {
    let mut e = Some(with_host(|h| h.env()));
    while let Some(cur) = e {
        let hit = cur.borrow().vars.get(name).cloned();
        if let Some(v) = hit {
            let v = force_value(&v)?;
            if with_host(|h| h.is_function(&v)) {
                return Ok(Some(v));
            }
        }
        e = cur.borrow().parent.clone();
    }
    Ok(None)
}

/// Call any callable value with an already-evaluated argument list.
pub fn call_value(
    f: &Value,
    args: Vec<(Option<String>, Value)>,
    fun_name: Option<String>,
) -> Result<Value, String> {
    match with_host(|h| h.data_of(f)) {
        RData::Builtin(name) => crate::builtins::call_primitive(&name, args),
        RData::Closure { id, env } => call_closure(id, env, args, fun_name),
        // A combinator and a foreign handle are primitive-shaped: neither binds
        // formals, so both take their arguments forced, as `call_primitive`
        // does.
        RData::Combinator { kind, inner } => {
            crate::builtins::call_combinator(kind, &inner, force_all(args)?)
        }
        // A foreign R function handle (R6 method, package closure) is invoked in
        // embedded R with marshalled arguments.
        #[cfg(not(target_arch = "wasm32"))]
        RData::RForeign(ptr) => crate::rembed::call_handle(ptr, &force_all(args)?),
        // A function named by a string — what `match.fun` accepts, so
        // `sapply(x, "sum")`, `Reduce("+", xs)` and `Map("paste", …)` call it.
        RData::Str(names) if names.len() == 1 => {
            let name = names[0].clone().unwrap_or_default();
            let f = crate::builtins::function_named(&name)
                .ok_or_else(|| format!("could not find function \"{name}\""))?;
            call_value(&f, args, Some(name))
        }
        _ => Err("attempt to apply non-function".into()),
    }
}

/// The call-depth ceiling. R stops at `options(expressions = 5000)` with
/// "evaluation nested too deeply"; rlang stops at the same place so runaway
/// recursion reports an R error instead of exhausting the native stack (each R
/// call runs its body on a nested VM, so depth costs real stack).
pub const MAX_DEPTH: usize = 5000;

thread_local! {
    /// This thread's native stack as `(highest address, size)`, read once.
    /// `None` where the platform does not say (wasm), which turns the check off
    /// the way R's `R_CStackLimit = -1` does.
    static STACK_BOUNDS: std::cell::OnceCell<Option<(usize, usize)>> =
        const { std::cell::OnceCell::new() };
}

/// The calling thread's stack: its highest address and its size.
#[cfg(target_vendor = "apple")]
fn thread_stack_bounds() -> Option<(usize, usize)> {
    // SAFETY: both calls only read the running thread's own attributes.
    unsafe {
        let me = libc::pthread_self();
        let top = libc::pthread_get_stackaddr_np(me) as usize;
        Some((top, libc::pthread_get_stacksize_np(me)))
    }
}

/// The calling thread's stack: its highest address and its size.
#[cfg(any(target_os = "linux", target_os = "android"))]
fn thread_stack_bounds() -> Option<(usize, usize)> {
    // SAFETY: `attr` is initialised by `pthread_getattr_np` before it is read
    // and destroyed once; the calls only read the running thread's attributes.
    unsafe {
        let mut attr = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();
        if libc::pthread_getattr_np(libc::pthread_self(), attr.as_mut_ptr()) != 0 {
            return None;
        }
        let mut low: *mut libc::c_void = std::ptr::null_mut();
        let mut size: libc::size_t = 0;
        let ok = libc::pthread_attr_getstack(attr.as_ptr(), &mut low, &mut size) == 0;
        libc::pthread_attr_destroy(attr.as_mut_ptr());
        ok.then(|| (low as usize + size, size))
    }
}

/// The calling thread's stack: unknown on this platform.
#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))]
fn thread_stack_bounds() -> Option<(usize, usize)> {
    None
}

/// Native stack a single step between two checks may still need: one R call
/// level, which in an unoptimised build holds the primitive library's frame
/// and three nested VMs. R's `R_CheckStack2(extra)` takes the same allowance. On a small stack
/// (a test harness's 2 MB thread) it is capped at a quarter of the stack, so
/// that ordinary shallow programs still run there.
const STACK_STEP: usize = 2 * 1024 * 1024;

/// The native stack in use, when it has come within R's 5% margin (plus
/// `STACK_STEP`) of the thread's limit — R's `R_CheckStack` test. Every
/// recursion that a program's shape drives (the evaluator, the parser and the
/// compiler) asks this before going a level deeper. A frame count such as
/// [`MAX_DEPTH`] cannot stand in for it: how much stack one level costs is a
/// property of the build, and it grows as the frames that run a level grow.
pub fn stack_exhausted() -> Option<String> {
    let (top, size) = STACK_BOUNDS.with(|b| *b.get_or_init(thread_stack_bounds))?;
    let here = 0u8;
    let usage = top.saturating_sub(std::ptr::addr_of!(here) as usize);
    let limit = (size as f64 * 0.95) as usize;
    (usage + STACK_STEP.min(size / 4) > limit)
        .then(|| format!("C stack usage  {usage} is too close to the limit"))
}

/// [`stack_exhausted`] for the evaluator: R's `stackOverflowError`, a condition
/// `tryCatch(error =)` takes, rather than letting the next frame overflow and
/// abort the process.
pub fn check_stack() -> Result<(), String> {
    let Some(msg) = stack_exhausted() else {
        return Ok(());
    };
    with_host(|h| {
        if h.error.is_none() {
            // R signals it with no call ("to avoid using stack in deparsing")
            // and skips calling handlers; an exiting handler still takes it.
            h.set_error_call(None);
            h.error_classes = [
                "CStackOverflowError",
                "stackOverflowError",
                "error",
                "condition",
            ]
            .iter()
            .map(|s| s.to_string())
            .collect();
        }
    });
    Err(msg)
}

/// Call a closure: match the arguments to the formals, push a frame whose
/// environment encloses the closure's captured environment, and run the body.
pub fn call_closure(
    id: usize,
    env: Env,
    args: Vec<(Option<String>, Value)>,
    fun_name: Option<String>,
) -> Result<Value, String> {
    // Only the formals are needed to enter the call; the body chunk stays in the
    // closure table (cloning the whole `ClosureDef` copied the bytecode on every
    // call, which for a closure called in a loop was the largest single cost of
    // calling it).
    let params = with_host(|h| h.closures.get(id).map(|d| d.params.clone()))
        .ok_or_else(|| format!("internal: unknown closure #{id}"))?;
    if with_host(|h| h.frames.len()) >= MAX_DEPTH {
        return Err("evaluation nested too deeply: infinite recursion?".into());
    }
    check_stack()?;
    // A forced promise is its caller's own expression, evaluated where it
    // was written: R makes no environment for it, so `environment()` or an
    // assignment inside one sees the writer's frame, not a child of it.
    let promise = FORCING.with(|f| f.replace(false));
    let frame_env = if promise {
        env.clone()
    } else {
        new_env(Some(env.clone()))
    };
    let bindings = match_args(&params, &args)?;
    with_host(|h| {
        for (k, v) in bindings {
            h.bind(&frame_env, &k, v);
        }
    });
    with_host(|h| {
        // The frame keeps the evaluated arguments for `UseMethod`/`NextMethod`
        // to re-dispatch on, so they are durable references for as long as the
        // call runs — R's promise holds the same reference.
        for (_, v) in &args {
            retain(&mut h.heap, v);
        }
        // The dispatch that selected this method, if it was one — set just
        // before the call so `NextMethod` in the body can continue it.
        let dispatch = h.pending_dispatch.take();
        // A method sees the generic it was reached through as `.Generic` — for
        // an `Ops` method, the operator (`"+"`), which is how one body serves
        // the whole group.
        if let Some((generic, _)) = &dispatch {
            let g = h.alloc(RData::Str(vec![Some(generic.clone())]));
            h.bind(&frame_env, ".Generic", g);
        }
        h.frames.push(Frame {
            env: frame_env,
            promise,
            args,
            fun_name,
            fun: Some((id, env)),
            dispatch,
            on_exit: Vec::new(),
            defaulted: Vec::new(),
        })
    });
    let out = run_closure_chunk(id);
    // `on.exit` runs on the way out however the frame is left — normal return,
    // `return()`, or an error unwinding through it — so it is taken off the
    // frame before the result is propagated.
    let exits = with_host(|h| {
        let e = h.frames.last_mut().map(|f| std::mem::take(&mut f.on_exit));
        // Leaving the frame gives back every reference it held: its arguments
        // always, and its bindings when the environment dies with it — which it
        // does unless a closure defined inside captured it, or `environment()`
        // handed it out, in which case another `Rc` is still alive.
        if let Some(f) = h.frames.pop() {
            for (_, v) in &f.args {
                release(&mut h.heap, v);
            }
            if Rc::strong_count(&f.env) == 1 {
                let held: Vec<Value> = f.env.borrow().vars.values().cloned().collect();
                for v in &held {
                    release(&mut h.heap, v);
                }
            }
        }
        e.unwrap_or_default()
    });
    // `run_chunk` has already moved any error out of the host and into `out`,
    // so the cleanups run on a clean slate. An error raised by a cleanup
    // propagates only when the body itself succeeded — otherwise the body's
    // error is the one that reaches the caller, as in R.
    let mut out = out;
    for thunk in exits {
        // A `return()` signal from the body must not halt the cleanup chunk, and
        // whether the *call* prints is decided by its own value — a `cat` in the
        // cleanup must not make the result invisible.
        let (sig, vis) = with_host(|h| (h.signal.take(), h.visible));
        let cleanup = call_value(&thunk, Vec::new(), None);
        with_host(|h| {
            h.signal = sig;
            h.visible = vis;
        });
        if out.is_ok() {
            if let Err(e) = cleanup {
                out = Err(e);
            }
        }
    }
    let out = out?;
    // A promise has no function of its own: a `return()` in it leaves the
    // function that wrote the expression, so the signal stays pending for the
    // chunk that forced it to halt on.
    if promise {
        if let Some(Signal::Return(v)) = with_host(|h| h.signal.clone()) {
            return Ok(v);
        }
    }
    // A `return()` inside the body halted the chunk; its value is the result.
    let sig = with_host(|h| h.signal.take());
    match sig {
        Some(Signal::Return(v)) => Ok(v),
        Some(other) => {
            with_host(|h| h.signal = Some(other));
            Ok(out)
        }
        None => Ok(out),
    }
}

/// Which formal each supplied argument binds to — R's argument matching, in
/// R's own order: an exact tag first, then a partial tag against the formals
/// before `...`, then position. `None` for an argument that matched no formal
/// and so belongs to `...`.
///
/// The rule lives here once because two callers need the same answer about
/// different things: [`match_args`] binds *values* to formals, and
/// `match.call()` re-tags the *expressions* the caller wrote.
pub fn match_positions(
    params: &[String],
    tags: &[Option<String>],
) -> Result<Vec<Option<usize>>, String> {
    let mut to = vec![None; tags.len()];
    let mut taken = vec![false; params.len()];
    let dots_at = params.iter().position(|p| p == "...");

    // 1. exact tag matches
    for (ai, tag) in tags.iter().enumerate() {
        let Some(tag) = tag else { continue };
        if let Some(pi) = params.iter().position(|p| p == tag) {
            if taken[pi] {
                return Err(format!(
                    "formal argument \"{tag}\" matched by multiple actual arguments"
                ));
            }
            taken[pi] = true;
            to[ai] = Some(pi);
        }
    }
    // 2. partial tag matches, only against formals before `...`
    let partial_limit = dots_at.unwrap_or(params.len());
    for (ai, tag) in tags.iter().enumerate() {
        if to[ai].is_some() {
            continue;
        }
        let Some(tag) = tag else { continue };
        let hits: Vec<usize> = (0..partial_limit)
            .filter(|&pi| !taken[pi] && params[pi].starts_with(tag.as_str()))
            .collect();
        match hits.len() {
            0 => {}
            1 => {
                taken[hits[0]] = true;
                to[ai] = Some(hits[0]);
            }
            _ => return Err(format!("argument {tag} matches multiple formal arguments")),
        }
    }
    // 3. positional fill, stopping at `...` — everything past it is variadic
    let mut pi = 0usize;
    for (ai, tag) in tags.iter().enumerate() {
        if to[ai].is_some() || tag.is_some() {
            continue;
        }
        while pi < params.len() && taken[pi] && params[pi] != "..." {
            pi += 1;
        }
        if pi >= params.len() || params[pi] == "..." {
            break;
        }
        taken[pi] = true;
        to[ai] = Some(pi);
        pi += 1;
    }
    Ok(to)
}

/// Bind a call's arguments to a closure's formals, R's way. Unmatched
/// arguments go to `...` when the closure has one and are an error when it does
/// not.
pub fn match_args(
    params: &[String],
    args: &[(Option<String>, Value)],
) -> Result<Vec<(String, Value)>, String> {
    let tags: Vec<Option<String>> = args.iter().map(|(t, _)| t.clone()).collect();
    let to = match_positions(params, &tags)?;
    let mut bound: Vec<Option<Value>> = vec![None; params.len()];
    for (ai, slot) in to.iter().enumerate() {
        if let Some(pi) = slot {
            bound[*pi] = Some(args[ai].1.clone());
        }
    }
    let mut out = Vec::new();
    for (i, p) in params.iter().enumerate() {
        if p == "..." {
            continue;
        }
        // An empty argument (`f(1, )`, `x[i, ]` reaching a `[` method) is R's
        // `R_MissingArg`: the formal stays unbound, so `missing()` answers TRUE
        // and the default, if any, fills it.
        if let Some(v) = &bound[i] {
            if !matches!(v, Value::Undef) {
                out.push((p.clone(), v.clone()));
            }
        }
    }
    // leftovers → `...`, or an error
    let rest: Vec<(Option<String>, Value)> = args
        .iter()
        .zip(&to)
        .filter(|(_, slot)| slot.is_none())
        .map(|(a, _)| a.clone())
        .collect();
    if params.iter().any(|p| p == "...") {
        let dots = with_host(|h| h.alloc(RData::Args(rest)));
        out.push(("...".to_string(), dots));
    } else if !rest.is_empty() {
        // R names the unused arguments as they were *written* — `f(1, x + y)`
        // reports `unused argument (x + y)` — so the text comes from the call on
        // the context stack, and the tag is put back in front of it.
        let written = with_host(|h| h.current_call_arg_sources());
        let named: Vec<String> = to
            .iter()
            .enumerate()
            .filter(|(_, slot)| slot.is_none())
            .map(|(ai, _)| {
                let src = written.get(ai).cloned().unwrap_or_default();
                match &args[ai].0 {
                    Some(t) => format!("{t} = {src}"),
                    None => src,
                }
            })
            .collect();
        let plural = if named.len() > 1 { "s" } else { "" };
        return Err(format!("unused argument{plural} ({})", named.join(", ")));
    }
    Ok(out)
}

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

    #[test]
    fn format_dbl_matches_r_seven_significant_digits() {
        assert_eq!(format_dbl(1.0), "1");
        assert_eq!(format_dbl(1.5), "1.5");
        assert_eq!(format_dbl(1.0 / 3.0), "0.3333333");
        assert_eq!(format_dbl(123.456), "123.456");
        assert_eq!(format_dbl(f64::INFINITY), "Inf");
        assert_eq!(format_dbl(f64::NAN), "NaN");
    }

    #[test]
    fn exact_tags_beat_position() {
        reset_host();
        let (a, b) = with_host(|h| (h.scalar_dbl(1.0), h.scalar_dbl(2.0)));
        let bound = match_args(
            &["x".into(), "y".into()],
            &[(Some("y".into()), a.clone()), (None, b.clone())],
        )
        .unwrap();
        assert_eq!(bound[0].0, "x");
        assert_eq!(bound[0].1, b);
        assert_eq!(bound[1].0, "y");
        assert_eq!(bound[1].1, a);
    }

    #[test]
    fn partial_tags_match_unique_prefixes_only() {
        reset_host();
        let v = with_host(|h| h.scalar_dbl(1.0));
        let ok = match_args(&["verbose".into()], &[(Some("verb".into()), v.clone())]).unwrap();
        assert_eq!(ok[0].0, "verbose");
        let ambiguous = match_args(
            &["value".into(), "verbose".into()],
            &[(Some("v".into()), v.clone())],
        );
        assert!(ambiguous.is_err());
    }

    #[test]
    fn extra_arguments_need_dots() {
        reset_host();
        let v = with_host(|h| h.scalar_dbl(1.0));
        assert!(match_args(&["x".into()], &[(None, v.clone()), (None, v.clone())]).is_err());
        let with_dots =
            match_args(&["x".into(), "...".into()], &[(None, v.clone()), (None, v)]).unwrap();
        assert_eq!(with_dots.len(), 2);
        assert_eq!(with_dots[1].0, "...");
    }
}