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
//! Lower the R AST to `fusevm::Chunk`.
//!
//! Control flow (`if`, `for`, `while`, `repeat`, `&&`, `||`) lowers to native
//! fusevm jumps with native `Int` loop counters, so the tracing JIT can compile
//! loops. Everything else — every value, every operator, every call — lowers to
//! a `CallBuiltin` that lands in `builtins.rs`, because in R even `1 + 1` is a
//! vectorized operation over attribute-carrying objects and not something the
//! VM's native `Add` could do.
//!
//! Assignment is compiled the way R defines it: `f(x) <- v` is
//! `x <- \`f<-\`(x, v)`, and `x\[i\] <- v` rebuilds `x` and re-binds it, so nested
//! targets like `x$a\[\[2\]\] <- v` unwind outward-in through the same two rules.

use crate::ast::*;
use crate::deparse::{deparse_expr, deparse_lines};
use crate::host::{ops, ClosureDef};
use fusevm::{Chunk, ChunkBuilder, Op, Value};

/// A compiled program: the top-level chunk plus every closure body it defines.
pub struct Program {
    pub main: Chunk,
    pub closures: Vec<ClosureDef>,
}

/// Jump fixups for one enclosing loop.
struct LoopCtx {
    /// Where `next` jumps to (the increment/condition edge).
    continues: Vec<usize>,
    /// Where `break` jumps to (past the loop).
    breaks: Vec<usize>,
}

#[derive(Default)]
struct Compiler {
    closures: Vec<ClosureDef>,
    loops: Vec<LoopCtx>,
    /// Counter for unique loop temporaries in the VM's own variable space.
    tmp: usize,
    /// Names bound to native frame slots (fusevm `GetVar`/`SetVar`, JIT-visible)
    /// instead of the string-keyed environment. Empty unless the whole top level
    /// is slot-safe (see [`slot_locals`]).
    locals: std::collections::HashSet<String>,
    /// Slots proven to hold an unboxed native numeric scalar (see
    /// [`native_num_slots`]) — usable as a native `for (i in 1:n)` bound.
    native_nums: std::collections::HashSet<String>,
    /// The deparsed text of the complex assignment being lowered — the call
    /// R names when a replacement function in it fails (`dim(y) <- c(4, 2)`),
    /// since a primitive `f<-` makes no context of its own.
    assign_text: String,
    /// Set while lowering an expression whose value is the value of a whole
    /// statement. Only there does visibility matter, and only a bare numeric
    /// literal needs help with it — see [`Compiler::expr`].
    tail: bool,
    /// Set while lowering a lazy body (see [`lazy_thunk`]) written inside a loop:
    /// a `break`/`next` there has no loop of its own chunk to jump in, and
    /// raises a signal for the loop that encloses the lazy call instead.
    lazy_loop: bool,
    /// `(op index, deparsed call)` for each binary operator lowered into the
    /// chunk being built, attached to it as one constant when it is built (see
    /// [`Compiler::finish_chunk`]) so a warning the operator raises can name it.
    op_sites: Vec<(usize, String)>,
}

/// Builtins that reach into an environment by name; their presence makes it
/// unsafe to keep any local in a native slot instead of the string environment.
const DYNAMIC_ENV_FNS: &[&str] = &[
    "get",
    "get0",
    "mget",
    "match.fun",
    "getS3method",
    "subset",
    "assign",
    "exists",
    "environment",
    "environmentName",
    "eval",
    "evalq",
    "local",
    "with",
    "within",
    "do.call",
    "Recall",
    "sys.call",
    "sys.function",
    "sys.frame",
    "match.call",
    "match.arg",
    "parent.frame",
    "parent.env",
    "ls",
    "rm",
    "remove",
    "attach",
    "detach",
    "substitute",
    "quote",
    "bquote",
    "missing",
    "on.exit",
    "delayedAssign",
    "makeActiveBinding",
    "new.env",
    "globalenv",
    "as.environment",
    "list2env",
    "eapply",
    "Reduce",
    "Filter",
    "Map",
    "do.call",
    "apply",
    "sapply",
    "lapply",
    "vapply",
    "mapply",
    "tapply",
    "outer",
];

/// The functions R implements as primitives (`is.primitive`), in R 4.6.1.
///
/// The distinction matters to conditions, not to dispatch: a closure call makes
/// an R *context* before its argument promises are forced, so a warning raised
/// while evaluating an argument reports the enclosing call
/// (`In print(as.integer("x")) : NAs introduced by coercion`), while a
/// primitive makes none and the same warning at the same depth reports no call
/// at all (`x <- sum(as.integer("x"))`). rlang implements nearly all of these
/// as Rust builtins either way, so the list is what tells the two apart.
const R_PRIMITIVES: &[&str] = &[
    "-",
    ":",
    "::",
    ":::",
    "!",
    "!=",
    "...elt",
    "...length",
    "...names",
    ".C",
    ".cache_class",
    ".Call",
    ".Call.graphics",
    ".class2",
    ".External",
    ".External.graphics",
    ".External2",
    ".Fortran",
    ".Internal",
    ".isMethodsDispatchOn",
    ".Primitive",
    ".primTrace",
    ".primUntrace",
    ".subset",
    ".subset2",
    "(",
    "[",
    "[[",
    "[[<-",
    "[<-",
    "{",
    "@",
    "@<-",
    "*",
    "/",
    "&",
    "&&",
    "%*%",
    "%/%",
    "%%",
    "^",
    "+",
    "<",
    "<-",
    "<<-",
    "<=",
    "=",
    "==",
    ">",
    ">=",
    "|",
    "||",
    "~",
    "$",
    "$<-",
    "abs",
    "acos",
    "acosh",
    "all",
    "any",
    "anyNA",
    "Arg",
    "as.call",
    "as.character",
    "as.complex",
    "as.double",
    "as.environment",
    "as.integer",
    "as.logical",
    "as.numeric",
    "as.raw",
    "asin",
    "asinh",
    "atan",
    "atanh",
    "attr",
    "attr<-",
    "attributes",
    "attributes<-",
    "baseenv",
    "break",
    "browser",
    "c",
    "call",
    "ceiling",
    "class",
    "class<-",
    "Conj",
    "cos",
    "cosh",
    "cospi",
    "crossprod",
    "cummax",
    "cummin",
    "cumprod",
    "cumsum",
    "declare",
    "digamma",
    "dim",
    "dim<-",
    "dimnames",
    "dimnames<-",
    "emptyenv",
    "enc2native",
    "enc2utf8",
    "environment<-",
    "Exec",
    "exp",
    "expm1",
    "expression",
    "floor",
    "for",
    "forceAndCall",
    "function",
    "gamma",
    "gc.time",
    "globalenv",
    "if",
    "Im",
    "interactive",
    "invisible",
    "is.array",
    "is.atomic",
    "is.call",
    "is.character",
    "is.complex",
    "is.double",
    "is.environment",
    "is.expression",
    "is.finite",
    "is.function",
    "is.infinite",
    "is.integer",
    "is.language",
    "is.list",
    "is.logical",
    "is.matrix",
    "is.na",
    "is.name",
    "is.nan",
    "is.null",
    "is.numeric",
    "is.object",
    "is.pairlist",
    "is.raw",
    "is.recursive",
    "is.single",
    "is.symbol",
    "isS4",
    "lazyLoadDBfetch",
    "length",
    "length<-",
    "levels<-",
    "lgamma",
    "list",
    "log",
    "log10",
    "log1p",
    "log2",
    "max",
    "min",
    "missing",
    "Mod",
    "names",
    "names<-",
    "nargs",
    "next",
    "nzchar",
    "oldClass",
    "oldClass<-",
    "on.exit",
    "pos.to.env",
    "proc.time",
    "prod",
    "quote",
    "range",
    "Re",
    "rep",
    "repeat",
    "retracemem",
    "return",
    "round",
    "seq_along",
    "seq_len",
    "seq.int",
    "sign",
    "signif",
    "sin",
    "sinh",
    "sinpi",
    "sqrt",
    "standardGeneric",
    "storage.mode<-",
    "substitute",
    "sum",
    "switch",
    "Tailcall",
    "tan",
    "tanh",
    "tanpi",
    "tcrossprod",
    "tracemem",
    "trigamma",
    "trunc",
    "unCfillPOSIXlt",
    "unclass",
    "untracemem",
    "UseMethod",
    "while",
    "xtfrm",
];

/// Whether R implements `name` as a primitive (`is.primitive`).
pub(crate) fn is_r_primitive(name: &str) -> bool {
    R_PRIMITIVES.contains(&name)
}

/// Whether calling `name` makes an R context — true for everything R implements
/// as a closure, which is what [`ops::OPEN_CALL`] is emitted for.
fn makes_context(name: &str) -> bool {
    // A `.rlang_*` shim is the compiler talking to its own runtime, not a call
    // the script wrote, so it makes no R context: one on the stack would sit
    // between a closure and its caller and make `substitute`/`sys.call` read
    // the wrong frame's source.
    !is_r_primitive(name) && !name.starts_with(".rlang_")
}

/// The names in a whole-program top level that are safe to bind to native frame
/// slots: the unit must contain no nested `function` (a closure captures the
/// enclosing frame by name), no `<<-`, no formula, and no call to an
/// environment-reaching builtin. A name assigned through a complex target
/// (`x[i] <-`, `x$f <-`) is excluded — `rebuild` reads/writes it by name — so
/// its every access stays on the environment path. If the unit is not slot-safe
/// the set is empty and nothing changes from the string-keyed default.
fn slot_locals(exprs: &[Expr]) -> std::collections::HashSet<String> {
    let mut targets = std::collections::HashSet::new();
    let mut blocked = std::collections::HashSet::new();
    let mut safe = true;
    for e in exprs {
        scan_slots(e, &mut safe, &mut targets, &mut blocked);
    }
    if !safe {
        return std::collections::HashSet::new();
    }
    targets.retain(|n| !blocked.contains(n));
    targets
}

/// The root variable name of a (possibly complex) assignment target, e.g. `x`
/// for `x[[1]]$y[2]`.
fn root_ident(e: &Expr) -> Option<&str> {
    match e {
        Expr::Ident(n) | Expr::Str(n) => Some(n),
        Expr::Paren(x) => root_ident(x),
        Expr::Index { obj, .. } => root_ident(obj),
        Expr::Call { args, .. } => args
            .first()
            .and_then(|a| a.value.as_ref())
            .and_then(root_ident),
        _ => None,
    }
}

fn scan_slots(
    e: &Expr,
    safe: &mut bool,
    targets: &mut std::collections::HashSet<String>,
    blocked: &mut std::collections::HashSet<String>,
) {
    if !*safe {
        return;
    }
    let mut go = |x: &Expr, s: &mut bool| scan_slots(x, s, targets, blocked);
    match e {
        Expr::Function { .. } | Expr::Formula { .. } => *safe = false,
        Expr::Assign {
            target,
            value,
            super_assign,
        } => {
            if *super_assign {
                *safe = false;
                return;
            }
            match target.as_ref() {
                Expr::Ident(n) | Expr::Str(n) => {
                    targets.insert(n.clone());
                }
                other => {
                    if let Some(r) = root_ident(other) {
                        blocked.insert(r.to_string());
                    }
                    scan_slots(other, safe, targets, blocked);
                }
            }
            scan_slots(value, safe, targets, blocked);
        }
        Expr::For { var, seq, body } => {
            targets.insert(var.clone());
            scan_slots(seq, safe, targets, blocked);
            scan_slots(body, safe, targets, blocked);
        }
        Expr::Call { fun, args } => {
            if let Expr::Ident(name) = fun.as_ref() {
                // A lazy special form (`try`, `suppressWarnings`, …) has its
                // body lowered into a `function()` thunk, and a thunk reads
                // its free names through the environment — so it is as unsafe
                // as a `function` written in the source. Without this,
                // `m <- …; r <- try(nrow(m))` read `m` as NULL.
                if DYNAMIC_ENV_FNS.contains(&name.as_str()) || thunk_lazy_args(name, args).is_some()
                {
                    *safe = false;
                    return;
                }
                // A name in function position is resolved by `GETFUN` through
                // the environment chain, so one the program binds (`g <- sum;
                // g(1, 2)`) has to live there, not in a slot.
                blocked.insert(name.clone());
            }
            scan_slots(fun, safe, targets, blocked);
            for a in args {
                if let Some(v) = &a.value {
                    scan_slots(v, safe, targets, blocked);
                }
            }
        }
        Expr::If { cond, then, els } => {
            go(cond, safe);
            go(then, safe);
            if let Some(x) = els {
                go(x, safe);
            }
        }
        Expr::While { cond, body } => {
            go(cond, safe);
            go(body, safe);
        }
        Expr::Repeat(b) => go(b, safe),
        Expr::Paren(x) => scan_slots(x, safe, targets, blocked),
        Expr::Block(xs) => {
            for x in xs {
                scan_slots(x, safe, targets, blocked);
            }
        }
        Expr::Binary { lhs, rhs, .. } | Expr::Special { lhs, rhs, .. } => {
            go(lhs, safe);
            go(rhs, safe);
        }
        Expr::Unary { operand, .. } => go(operand, safe),
        Expr::Index { obj, args, .. } => {
            go(obj, safe);
            for a in args {
                if let Some(v) = &a.value {
                    scan_slots(v, safe, targets, blocked);
                }
            }
        }
        _ => {}
    }
}

/// Compile a whole program — top-level locals may be bound to native frame
/// slots (JIT-visible) when the unit is slot-safe.
pub fn compile(exprs: &[Expr]) -> Result<Program, String> {
    compile_inner(exprs, true)
}

/// Compile without slot binding. The REPL keeps one host across prompts and
/// persists variables through the shared environment, so its top-level names
/// must live there, not in a per-chunk slot vector.
pub fn compile_no_slots(exprs: &[Expr]) -> Result<Program, String> {
    compile_inner(exprs, false)
}

fn compile_inner(exprs: &[Expr], use_slots: bool) -> Result<Program, String> {
    let mut c = Compiler::default();
    if use_slots {
        c.locals = slot_locals(exprs);
        c.native_nums = native_num_slots(exprs);
    }
    let mut b = ChunkBuilder::new();
    if exprs.is_empty() {
        b.emit(Op::CallBuiltin(ops::CONST_NULL, 0), 0);
    }
    for (i, e) in exprs.iter().enumerate() {
        // A slot assignment's native `SetVar` does not clear the visibility flag
        // the way the `SETVAR` builtin does, so it can't reach `AUTOPRINT` — but
        // an assignment is invisible and never echoed anyway, so `stmt` stores it
        // directly (no Dup/Pop). All other top-level values are echoed like
        // `Rscript`.
        let slot_assign = matches!(e, Expr::Assign { target, super_assign: false, .. }
            if matches!(target.as_ref(), Expr::Ident(n) | Expr::Str(n) if c.locals.contains(n)));
        if slot_assign {
            c.stmt(&mut b, e)?;
        } else {
            c.tail = true;
            c.expr(&mut b, e)?;
            b.emit(Op::CallBuiltin(ops::AUTOPRINT, 1), 0);
        }
        // The statement is over, so R's deferred warnings print here — after
        // its own output, before the next statement's. The builtin pushes the
        // NULL every builtin pushes; the value being echoed is under it.
        b.emit(Op::CallBuiltin(ops::WARN_FLUSH, 0), 0);
        b.emit(Op::Pop, 0);
        if !slot_assign && i + 1 < exprs.len() {
            b.emit(Op::Pop, 0);
        }
    }
    c.finish_chunk(&mut b, Vec::new());
    Ok(Program {
        main: b.build(),
        closures: c.closures,
    })
}

/// Renumber a program's closure ids by `base`.
///
/// The REPL keeps one host across prompts, so each new program's closure bodies
/// are appended to the ones already loaded; the `LoadInt(id)` that feeds every
/// `MKCLOSURE` has to move with them.
pub fn shift_closure_ids(prog: Program, base: usize) -> Program {
    if base == 0 {
        return prog;
    }
    let shift = |chunk: &mut Chunk| {
        for i in 0..chunk.ops.len() {
            let is_mkclosure = matches!(
                chunk.ops.get(i + 1),
                Some(Op::CallBuiltin(id, 1)) if *id == ops::MKCLOSURE
            );
            if !is_mkclosure {
                continue;
            }
            if let Some(Op::LoadInt(n)) = chunk.ops.get_mut(i) {
                *n += base as i64;
            }
        }
        rehash(chunk);
    };
    let mut main = prog.main;
    shift(&mut main);
    let closures = prog
        .closures
        .into_iter()
        .map(|mut c| {
            shift(&mut c.chunk);
            c
        })
        .collect();
    Program { main, closures }
}

/// Recompute a chunk's cached op hash after rewriting its ops, so the JIT's
/// code cache keys off what the chunk now contains.
fn rehash(chunk: &mut Chunk) {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut h = DefaultHasher::new();
    chunk.ops.hash(&mut h);
    chunk.constants.hash(&mut h);
    chunk.op_hash = h.finish();
}

impl Compiler {
    fn kstr(&mut self, b: &mut ChunkBuilder, s: &str) {
        let idx = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(idx), 0);
    }

    /// Close the chunk `b` is building: attach the operator sites lowered into
    /// it, and hand the compiler back the sites of the chunk that encloses it.
    /// A full constant pool just drops the table — its operators then warn
    /// without naming a call, which is all a missing table ever costs.
    fn finish_chunk(&mut self, b: &mut ChunkBuilder, outer: Vec<(usize, String)>) {
        let sites = std::mem::replace(&mut self.op_sites, outer);
        if !sites.is_empty() {
            let _ = b.try_add_constant(crate::host::op_sites_constant(sites));
        }
    }

    fn tmp_name(&mut self, b: &mut ChunkBuilder, tag: &str) -> u16 {
        self.tmp += 1;
        b.add_name(&format!("__{tag}{}", self.tmp))
    }

    /// Compile a body sequence: every value but the last is discarded.
    fn seq(&mut self, b: &mut ChunkBuilder, body: &[Expr]) -> Result<(), String> {
        let tail = std::mem::take(&mut self.tail);
        if body.is_empty() {
            b.emit(Op::CallBuiltin(ops::CONST_NULL, 0), 0);
            return Ok(());
        }
        for (i, e) in body.iter().enumerate() {
            if i + 1 < body.len() {
                self.stmt(b, e)?;
            } else {
                // The last element is the block's value, so it keeps whatever
                // statement position the block itself had.
                self.tail = tail;
                self.expr(b, e)?;
            }
        }
        Ok(())
    }

    /// Emit the flag-setting builtin after a value that cannot set it itself.
    fn mark_visible(&mut self, b: &mut ChunkBuilder, tail: bool) {
        if tail {
            b.emit(Op::CallBuiltin(ops::SET_VISIBLE, 1), 0);
        }
    }

    /// Compile an expression in statement position — its value is discarded. A
    /// slot assignment stores directly (native `SetVar` consumes the value) with
    /// no `Dup`/`Pop`, saving two ops per statement: this is the hot path of a
    /// `for`/`while` body like `s <- s + i`.
    fn stmt(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        if let Expr::Assign {
            target,
            value,
            super_assign: false,
        } = e
        {
            if let Expr::Ident(n) | Expr::Str(n) = target.as_ref() {
                if self.locals.contains(n) {
                    self.expr(b, value)?;
                    let slot = b.add_name(n);
                    b.emit(Op::SetVar(slot), 0);
                    return Ok(());
                }
            }
        }
        self.expr(b, e)?;
        b.emit(Op::Pop, 0);
        Ok(())
    }

    fn expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        // Compiling recurses once per level of nesting (a long `1 + 1 + …`
        // chain once per operator), so a nest too deep for the native stack
        // is refused here rather than overflowing it.
        if let Some(msg) = crate::host::stack_exhausted() {
            return Err(msg);
        }
        // Statement position is consumed here: it applies to this expression
        // only, and is handed on explicitly by the few constructs whose value is
        // the value of a sub-expression (`{ }`, `if`).
        let tail = std::mem::take(&mut self.tail);
        match e {
            // A numeric literal rides unboxed (native `Value::Float`/`Int`) — no
            // `CONST_DBL`/`CONST_INT` builtin. Every host accessor already reads
            // the unboxed variants, and keeping literals off the builtin path is
            // what lets `--aot` native-lower a whole loop that starts with, e.g.,
            // `s <- 0` (a deopt-point builtin call there would end native codegen
            // before the loop even begins).
            // A literal lowers to a native op that never enters an rlang
            // builtin, so unlike every other expression it cannot set the
            // visibility flag on the way past. R sets `R_Visible = TRUE` for
            // one, so a block ending in a bare literal echoes even when the
            // statement before it was invisible (`{ x <- 1; 3 }` prints 3).
            // Only statement position needs it: a literal used as an operand or
            // an argument has its visibility decided by the enclosing call, and
            // paying for a builtin there would cost the hot arithmetic path.
            Expr::Num(n) => {
                b.emit(Op::LoadFloat(*n), 0);
                self.mark_visible(b, tail);
            }
            Expr::Int(n) => {
                b.emit(Op::LoadInt(*n), 0);
                self.mark_visible(b, tail);
            }
            Expr::Str(s) => {
                self.kstr(b, s);
                b.emit(Op::CallBuiltin(ops::CONST_STR, 1), 0);
            }
            Expr::Bool(v) => {
                b.emit(if *v { Op::LoadTrue } else { Op::LoadFalse }, 0);
                b.emit(Op::CallBuiltin(ops::CONST_LGL, 1), 0);
            }
            Expr::Null => {
                b.emit(Op::CallBuiltin(ops::CONST_NULL, 0), 0);
            }
            Expr::Na(kind) => {
                let tag = match kind {
                    NaKind::Logical => 0,
                    NaKind::Integer => 1,
                    NaKind::Real => 2,
                    NaKind::Character => 3,
                };
                b.emit(Op::LoadInt(tag), 0);
                b.emit(Op::CallBuiltin(ops::CONST_NA, 1), 0);
            }
            Expr::Inf => {
                b.emit(Op::LoadFloat(f64::INFINITY), 0);
                b.emit(Op::CallBuiltin(ops::CONST_DBL, 1), 0);
            }
            Expr::NaN => {
                b.emit(Op::LoadFloat(f64::NAN), 0);
                b.emit(Op::CallBuiltin(ops::CONST_DBL, 1), 0);
            }
            Expr::Ident(name) => {
                if self.locals.contains(name) {
                    // A slot-bound local: native read, JIT-visible, no env hash.
                    let slot = b.add_name(name);
                    b.emit(Op::GetVar(slot), 0);
                } else {
                    self.kstr(b, name);
                    b.emit(Op::CallBuiltin(ops::GETVAR, 1), 0);
                }
            }
            Expr::Dots => {
                b.emit(Op::CallBuiltin(ops::DOTS, 0), 0);
            }
            Expr::Function { params, body } => {
                let id = self.closure(params, body)?;
                b.emit(Op::LoadInt(id as i64), 0);
                b.emit(Op::CallBuiltin(ops::MKCLOSURE, 1), 0);
            }
            Expr::Block(body) => {
                self.tail = tail;
                self.seq(b, body)?
            }
            // `(x)` yields `x` but *visibly*: R's `(` is a function, and a call
            // sets the visibility flag, so `(x <- 5)` echoes at top level while
            // the bare assignment does not.
            Expr::Paren(inner) => {
                self.expr(b, inner)?;
                b.emit(Op::CallBuiltin(ops::SET_VISIBLE, 1), 0);
            }
            Expr::Call { fun, args } => self.call_expr(b, e, fun, args)?,
            Expr::Formula { lhs, rhs } => {
                // A formula is unevaluated language: deparse it back to R source
                // and build the formula object in the embedded R.
                let src = match lhs {
                    Some(l) => format!("{} ~ {}", deparse_expr(l), deparse_expr(rhs)),
                    None => format!("~ {}", deparse_expr(rhs)),
                };
                let call = Expr::Call {
                    fun: Box::new(Expr::Ident(".rlang_formula".into())),
                    args: vec![Arg {
                        name: None,
                        value: Some(Expr::Str(src)),
                    }],
                };
                self.expr(b, &call)?;
            }
            Expr::Binary { op, lhs, rhs } => match op {
                BinOp::And2 | BinOp::Or2 => self.short_circuit(b, op, lhs, rhs)?,
                _ => {
                    self.expr(b, lhs)?;
                    self.expr(b, rhs)?;
                    // `+ - * /` lower to native fusevm ops: two unboxed scalars
                    // compute directly in the dispatch loop (and are JIT-visible),
                    // while a boxed vector/NA operand delegates to R's `arith`
                    // through the VM's numeric hook (installed in builtins). Ops
                    // whose native semantics differ from R (`%%` sign, `^` NA
                    // rules, comparison NaN→NA) keep the builtin path.
                    let ip = match native_binop(op) {
                        Some(nop) => b.emit(nop, 0),
                        None => {
                            self.kstr(b, binop_name(op));
                            b.emit(Op::CallBuiltin(ops::BINOP, 3), 0)
                        }
                    };
                    // R names the operator call in the warnings it raises
                    // (`In 1:3 + 1:2 : longer object length …`); read only when
                    // one fires — see `host::op_site_call`.
                    self.op_sites.push((ip, deparse_lines(e)));
                }
            },
            Expr::Special { name, lhs, rhs } => {
                self.expr(b, lhs)?;
                self.expr(b, rhs)?;
                self.kstr(b, name);
                // A `%op%` function is called with the infix expression as its
                // call, so its context and its errors name `x %op% y`.
                self.kstr(b, &deparse_lines(e));
                b.emit(Op::CallBuiltin(ops::SPECIAL, 4), 0);
            }
            Expr::Unary { op, operand } => {
                self.expr(b, operand)?;
                self.kstr(
                    b,
                    match op {
                        UnOp::Neg => "-",
                        UnOp::Plus => "+",
                        UnOp::Not => "!",
                    },
                );
                b.emit(Op::CallBuiltin(ops::UNOP, 2), 0);
            }
            Expr::Index { kind, obj, args } => {
                self.expr(b, obj)?;
                let ip = match kind {
                    IndexKind::Dollar | IndexKind::At => {
                        // The name is a literal, not an evaluated expression.
                        match args.first().and_then(|a| a.value.clone()) {
                            Some(Expr::Str(n)) => self.kstr(b, &n),
                            _ => return Err("malformed $ access".into()),
                        }
                        b.emit(Op::CallBuiltin(ops::DOLLAR, 2), 0)
                    }
                    IndexKind::Single => {
                        self.args(b, args)?;
                        b.emit(Op::CallBuiltin(ops::INDEX, 2), 0)
                    }
                    IndexKind::Double => {
                        self.args(b, args)?;
                        b.emit(Op::CallBuiltin(ops::INDEX2, 2), 0)
                    }
                };
                // A subscript error names the subscript call
                // (`Error in x[[5]] : subscript out of bounds`).
                self.op_sites.push((ip, deparse_lines(e)));
            }
            Expr::If { cond, then, els } => {
                self.expr(b, cond)?;
                // A condition R cannot read reports the `if` itself as its call.
                self.kstr(b, &deparse_lines(e));
                b.emit(Op::CallBuiltin(ops::TRUTHY, 2), 0);
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                // Whichever branch runs *is* the statement's value, so each
                // inherits the statement position the `if` itself was in.
                self.tail = tail;
                self.expr(b, then)?;
                let jend = b.emit(Op::Jump(0), 0);
                let else_at = b.current_pos();
                b.patch_jump(jf, else_at);
                self.tail = tail;
                match els {
                    Some(e) => self.expr(b, e)?,
                    // `if` without `else` yields invisible NULL.
                    None => {
                        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
                    }
                }
                let end = b.current_pos();
                b.patch_jump(jend, end);
            }
            Expr::While { cond, body } => {
                self.loops.push(LoopCtx {
                    continues: Vec::new(),
                    breaks: Vec::new(),
                });
                let start = b.current_pos();
                self.expr(b, cond)?;
                self.kstr(b, &deparse_lines(e));
                b.emit(Op::CallBuiltin(ops::TRUTHY, 2), 0);
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                self.stmt(b, body)?;
                b.emit(Op::Jump(start), 0);
                let end = b.current_pos();
                b.patch_jump(jf, end);
                self.close_loop(b, start, end);
                // A loop evaluates to invisible NULL.
                b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
            }
            Expr::Repeat(body) => {
                self.loops.push(LoopCtx {
                    continues: Vec::new(),
                    breaks: Vec::new(),
                });
                let start = b.current_pos();
                self.stmt(b, body)?;
                b.emit(Op::Jump(start), 0);
                let end = b.current_pos();
                self.close_loop(b, start, end);
                // A loop evaluates to invisible NULL.
                b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
            }
            Expr::For { var, seq, body } => self.for_loop(b, var, seq, body)?,
            Expr::Break => {
                if self.loops.is_empty() && !self.lazy_loop {
                    // R reports this when the `break` is *evaluated*, as an
                    // ordinary error a `tryCatch` can see — not when the
                    // program is read.
                    return self.no_loop_error(b);
                }
                self.leave_loop(b, true);
                // Keep the stack shape uniform: the jump is taken, so this is
                // only reached by the verifier, never at runtime.
                b.emit(Op::CallBuiltin(ops::CONST_NULL, 0), 0);
            }
            Expr::Next => {
                if self.loops.is_empty() && !self.lazy_loop {
                    return self.no_loop_error(b);
                }
                self.leave_loop(b, false);
                b.emit(Op::CallBuiltin(ops::CONST_NULL, 0), 0);
            }
            Expr::Assign {
                target,
                value,
                super_assign,
            } => self.assign(b, target, value, *super_assign)?,
        }
        Ok(())
    }

    /// A call: the special forms the compiler lowers itself, then an ordinary
    /// call. Kept out of [`Compiler::expr`] so that `expr`'s frame, which every
    /// level of a nested expression holds on the native stack (a long `1 + 1 +
    /// …` chain recurses once per operator), does not carry this arm's locals.
    #[inline(never)]
    fn call_expr(
        &mut self,
        b: &mut ChunkBuilder,
        e: &Expr,
        fun: &Expr,
        args: &[Arg],
    ) -> Result<(), String> {
        // `switch` is a lazy special form (only the selected branch may
        // run), so it compiles to a jump table rather than an eager call.
        if let Expr::Ident(name) = fun {
            if name == "switch" && !args.is_empty() {
                return self.switch_expr(b, args);
            }
            // `local(expr)` evaluates `expr` in a fresh environment
            // whose parent is the caller's — which is exactly what
            // calling a zero-argument closure does, and is how R's own
            // `local` is defined.
            if name == "local" && args.len() == 1 {
                if let Some(body) = args[0].value.clone() {
                    return self.expr(b, &call_thunk(body));
                }
            }
            // `local(expr, envir)` is R's
            // `eval.parent(substitute(eval(quote(expr), envir)))`: the
            // expression, unevaluated, run in the given environment.
            if name == "local" && args.len() == 2 {
                let named = |n: &str| args.iter().position(|a| a.name.as_deref() == Some(n));
                let expr_at = named("expr").unwrap_or(usize::from(named("envir") == Some(0)));
                if let (Some(inner), Some(scope)) =
                    (args[expr_at].value.clone(), args[1 - expr_at].value.clone())
                {
                    let call = vec![
                        Arg {
                            name: None,
                            value: Some(quote_call(&inner, false)),
                        },
                        Arg {
                            name: None,
                            value: Some(scope),
                        },
                    ];
                    return self.expr(
                        b,
                        &Expr::Call {
                            fun: Box::new(Expr::Ident("eval".into())),
                            args: call,
                        },
                    );
                }
            }
            // `with(data, expr)` and `evalq(expr, envir)` are `eval`
            // of the *unevaluated* expression, which R reaches through
            // `substitute`. Lowering to `eval(quote(expr), …)` keeps
            // the expression from running before the scope exists.
            if matches!(name.as_str(), "with" | "evalq") && args.len() >= 2 {
                let (expr_at, scope_at) = if name == "with" { (1, 0) } else { (0, 1) };
                if let Some(inner) = args[expr_at].value.clone() {
                    let mut call = vec![
                        Arg {
                            name: None,
                            value: Some(quote_call(&inner, false)),
                        },
                        Arg {
                            name: None,
                            value: args[scope_at].value.clone(),
                        },
                    ];
                    call.extend(args[2..].iter().cloned());
                    return self.expr(
                        b,
                        &Expr::Call {
                            fun: Box::new(Expr::Ident("eval".into())),
                            args: call,
                        },
                    );
                }
            }
            // `delayedAssign(x, value)` binds `x` to an unevaluated
            // promise for `value`, forced at first use. It lowers to
            // `assign(x, <promise of value>)`, which is what a closure
            // argument already is. `assign.env` becomes `envir`.
            if name == "delayedAssign" && args.len() >= 2 {
                let tag = |a: &Arg, n: &str| a.name.as_deref() == Some(n);
                let mut rest: Vec<Arg> = args.to_vec();
                let pick = |rest: &mut Vec<Arg>, n: &str, pos: usize| -> Option<Arg> {
                    if let Some(i) = rest.iter().position(|a| tag(a, n)) {
                        return Some(rest.remove(i));
                    }
                    let unnamed: Vec<usize> = rest
                        .iter()
                        .enumerate()
                        .filter(|(_, a)| a.name.is_none())
                        .map(|(i, _)| i)
                        .collect();
                    unnamed.get(pos).map(|&i| rest.remove(i))
                };
                let x = pick(&mut rest, "x", 0);
                let value = pick(&mut rest, "value", 0);
                let _eval_env = pick(&mut rest, "eval.env", 0);
                let assign_env = pick(&mut rest, "assign.env", 0);
                if let (Some(x), Some(value)) = (x, value) {
                    if let Some(v) = value.value {
                        let mut call = vec![
                            Arg {
                                name: None,
                                value: x.value,
                            },
                            Arg {
                                name: None,
                                value: Some(Expr::Call {
                                    fun: Box::new(Expr::Ident(".rlang_promise".into())),
                                    args: vec![Arg {
                                        name: None,
                                        value: Some(thunk(v)),
                                    }],
                                }),
                            },
                        ];
                        if let Some(env) = assign_env {
                            call.push(Arg {
                                name: Some("envir".into()),
                                value: env.value,
                            });
                        }
                        self.expr(
                            b,
                            &Expr::Call {
                                fun: Box::new(Expr::Ident("assign".into())),
                                args: call,
                            },
                        )?;
                        b.emit(Op::Pop, 0);
                        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
                        return Ok(());
                    }
                }
            }
            // `quote(x)` yields the expression, not its value, so the
            // argument must not be compiled at all. Its deparse is
            // carried across as a string the way a formula's is, and
            // `.rlang_quote` parses it back into a language object.
            if matches!(name.as_str(), "quote" | "bquote") && args.len() == 1 {
                if let Some(inner) = args[0].value.clone() {
                    return self.expr(b, &quote_call(&inner, name == "bquote"));
                }
            }
            // `missing(x)` asks about the *name*, so its argument must
            // not be evaluated — an omitted formal with no default is
            // unbound, and compiling `x` would raise "object not found"
            // rather than answer. R accepts the quoted spelling too, so
            // lowering the symbol to it keeps one implementation.
            if name == "missing" && args.len() == 1 {
                if let Some(Expr::Ident(sym)) = args[0].value.clone() {
                    let mut call = args.to_vec();
                    call[0] = Arg {
                        name: None,
                        value: Some(Expr::Str(sym)),
                    };
                    return self.expr(
                        b,
                        &Expr::Call {
                            fun: Box::new(Expr::Ident("missing".into())),
                            args: call,
                        },
                    );
                }
            }
            // `substitute(x)` reads the *expression* a caller passed,
            // so like `quote` its argument is carried across as source
            // rather than compiled. A second argument is the lookup
            // table and is evaluated normally.
            if name == "substitute" && !args.is_empty() {
                if let Some(inner) = args[0].value.clone() {
                    let mut call = args.to_vec();
                    call[0] = Arg {
                        name: None,
                        value: Some(Expr::Str(deparse_lines(&inner))),
                    };
                    return self.expr(
                        b,
                        &Expr::Call {
                            fun: Box::new(Expr::Ident(".rlang_substitute".into())),
                            args: call,
                        },
                    );
                }
            }
        }
        // `tryCatch` / `try` / `on.exit` take their body *unevaluated*:
        // rlang evaluates arguments eagerly, so the body is wrapped in a
        // zero-argument closure here and the builtin decides when — and
        // whether — to call it. A closure body runs on its own nested
        // VM, so an error inside it unwinds only that far, which is what
        // makes it catchable. The rewritten list shadows `args` rather
        // than being re-compiled as a fresh call, which would re-enter
        // this rewrite and thunk the thunk forever.
        let thunked = match fun {
            Expr::Ident(name) => thunk_lazy_args(name, args),
            _ => None,
        };
        let args: &[Arg] = thunked.as_deref().unwrap_or(args);
        // Arguments taken as names, not values (NSE): the package of
        // `library(pkg)` / `require(pkg)`, and every bare symbol of
        // `rm(x, y)`. Each is compiled as its string name, here, before
        // the promise rewrite below would wrap the symbol in a thunk.
        let nse_names = match fun {
            Expr::Ident(n) => match n.as_str() {
                "library" | "require" | "requireNamespace" | "loadNamespace" => Some(1),
                "rm" | "remove" => Some(usize::MAX),
                _ => None,
            },
            _ => None,
        };
        let named_args: Option<Vec<Arg>> = nse_names.map(|first_n| {
            args.iter()
                .enumerate()
                .map(|(i, a)| match &a.value {
                    Some(Expr::Ident(sym)) if i < first_n && (first_n == 1 || a.name.is_none()) => {
                        Arg {
                            name: a.name.clone(),
                            value: Some(Expr::Str(sym.clone())),
                        }
                    }
                    _ => a.clone(),
                })
                .collect()
        });
        let args: &[Arg] = named_args.as_deref().unwrap_or(args);
        // `table`'s dimension names are its arguments as written, so they
        // are read here, before the promise rewrite below wraps them.
        let table_dnn: Option<Vec<String>> = match fun {
            Expr::Ident(n)
                if n == "table" && !args.iter().any(|a| matches!(a.value, Some(Expr::Dots))) =>
            {
                Some(
                    args.iter()
                        .filter(|a| a.name.is_none())
                        .map(|a| match &a.value {
                            Some(Expr::Ident(sym)) => sym.clone(),
                            _ => String::new(),
                        })
                        .collect(),
                )
            }
            _ => None,
        };
        // `rbind`/`cbind` label the binding seam with the deparsed
        // argument (`rbind(x, x)` gives rownames "x", "x"). A builtin
        // receives values, not expressions, so the deparsed text is
        // read here — before the promise rewrite below wraps every
        // symbol in `.rlang_promise(function() x)` — and rides along
        // as two vectors, one element per argument: `.deparse.sym`
        // carries a bare symbol's name (R's default `deparse.level =
        // 1`) and `.deparse.txt` the full deparse (`deparse.level =
        // 2`). Skipped when `...` is present — its runtime expansion
        // would slide the arguments out of alignment with the vectors.
        let bind_labels: Option<Vec<BindLabel>> = match fun {
            Expr::Ident(n)
                if (n == "rbind" || n == "cbind")
                    && !args.is_empty()
                    && !args
                        .iter()
                        .any(|a| matches!(a.value, Some(Expr::Dots)) || a.value.is_none()) =>
            {
                Some(
                    args.iter()
                        .map(|a| {
                            let e = a.value.as_ref().expect("checked above");
                            let sym = match e {
                                Expr::Ident(s) => Some(s.clone()),
                                _ => None,
                            };
                            (sym, deparse_expr(e))
                        })
                        .collect(),
                )
            }
            _ => None,
        };
        // R binds a CLOSURE's arguments as promises: the expression is
        // evaluated on first read, in the caller's environment, and not
        // at all if the formal is never read. `f <- function(x) 42;
        // f(stop("boom"))` is 42 in R, and was an error here.
        //
        // The same predicate as the context above decides it, because
        // it asks the same question — is this call a closure's? A name
        // that turns out to be a primitive after all gets its arguments
        // forced at `call_primitive`'s door, so the promise never
        // reaches a builtin's hands.
        let promised = match fun {
            // Slot mode is only ever on for a unit with no `function`
            // in it (see `slot_locals`), so there is no closure for a
            // promise to be bound in and nothing can observe the
            // difference — while a thunk compiled here WOULD read a
            // slot that only the enclosing frame has.
            _ if !self.locals.is_empty() => None,
            Expr::Ident(name) if !makes_context(name) => None,
            // The rewrite's own call, and the rest of the compiler's
            // internal shims, take what they are handed: promising a
            // `.rlang_promise` argument would re-enter this rewrite on
            // the thunk it just built, forever.
            Expr::Ident(name) if name.starts_with(".rlang_") => None,
            _ => promise_args(args),
        };
        let args: &[Arg] = promised.as_deref().unwrap_or(args);
        // R's contexts carry the call that created them, and every
        // condition raised inside one reports it (`In f(1) : …`), while
        // `sys.call()` hands it back as data. The deparse is fixed at
        // compile time and rides under the callee, so it nests with the
        // call itself and needs no save/restore: `CALL` takes it as its
        // third operand and pushes it on the host's context stack for
        // as long as the call runs. The *whole* deparse is carried, not
        // just the line a diagnostic shows, because a language object
        // built from it has to parse back to the same call.
        self.kstr(b, &deparse_lines(e));
        // R makes a closure's context *before* forcing its argument
        // promises, and none at all for a primitive, so a condition
        // raised while evaluating an argument reports the enclosing
        // call only in the first case. Opening the context here, ahead
        // of the arguments, is that difference. A callee that is not a
        // plain name cannot be a primitive.
        let opens = match fun {
            Expr::Ident(name) => makes_context(name),
            _ => true,
        };
        if opens {
            b.emit(Op::CallBuiltin(ops::OPEN_CALL, 1), 0);
        }
        // A named callee resolves in function position, skipping
        // non-function bindings (`c <- 1; c(1, 2)` still concatenates).
        match fun {
            Expr::Ident(name) => {
                self.kstr(b, name);
                b.emit(Op::CallBuiltin(ops::GETFUN, 1), 0);
            }
            other => self.expr(b, other)?,
        }
        let call_op = match opens {
            true => ops::CALL_OPENED,
            false => ops::CALL,
        };
        // `table(z)` labels its dimension with the deparsed argument
        // (R's `deparse.level = 1`: a bare symbol names it, anything
        // else leaves it ""). The names were read before the promise
        // rewrite wrapped the symbols, and ride along as `.dnn`, one
        // per unnamed argument; a lone non-symbol argument passes none.
        if let Some(names) = table_dnn {
            let mut rewritten = args.to_vec();
            let dnn = match names.len() {
                1 if names[0].is_empty() => None,
                1 => Some(Expr::Str(names[0].clone())),
                _ => Some(Expr::Call {
                    fun: Box::new(Expr::Ident("c".into())),
                    args: names
                        .into_iter()
                        .map(|n| Arg {
                            name: None,
                            value: Some(Expr::Str(n)),
                        })
                        .collect(),
                }),
            };
            if let Some(dnn) = dnn {
                rewritten.push(Arg {
                    name: Some(".dnn".into()),
                    value: Some(dnn),
                });
            }
            self.args(b, &rewritten)?;
            b.emit(Op::CallBuiltin(call_op, 3), 0);
            return Ok(());
        }
        // The seam labels `rbind`/`cbind` read off the argument
        // expressions (taken above, before the promise rewrite) ride
        // along as `.deparse.sym` and `.deparse.txt`.
        if let Some(labels) = bind_labels {
            let label = |f: &dyn Fn(&BindLabel) -> Option<String>| Arg {
                name: None,
                value: Some(Expr::Call {
                    fun: Box::new(Expr::Ident("c".into())),
                    args: labels
                        .iter()
                        .map(|l| Arg {
                            name: None,
                            value: Some(match f(l) {
                                Some(s) => Expr::Str(s),
                                None => Expr::Na(NaKind::Character),
                            }),
                        })
                        .collect(),
                }),
            };
            let mut rewritten = args.to_vec();
            rewritten.push(Arg {
                name: Some(".deparse.sym".into()),
                ..label(&|(sym, _)| sym.clone())
            });
            rewritten.push(Arg {
                name: Some(".deparse.txt".into()),
                ..label(&|(_, txt)| Some(txt.clone()))
            });
            self.args(b, &rewritten)?;
            b.emit(Op::CallBuiltin(call_op, 3), 0);
            return Ok(());
        }
        self.args(b, args)?;
        b.emit(Op::CallBuiltin(call_op, 3), 0);
        // The body of a lazy call is a promise: a `break`/`next` in it
        // leaves through this call to the loop that encloses it.
        let defers = thunked.is_some() && !matches!(fun, Expr::Ident(n) if n == "on.exit");
        if defers && (!self.loops.is_empty() || self.lazy_loop) {
            self.dispatch_loop_signal(b);
        }
        Ok(())
    }

    /// Leave the innermost loop: a native jump when the loop is in this chunk,
    /// else (a lazy body written inside a loop) a signal for the loop that
    /// encloses the call that forces this chunk.
    fn leave_loop(&mut self, b: &mut ChunkBuilder, is_break: bool) {
        match self.loops.last_mut() {
            Some(ctx) => {
                let j = b.emit(Op::Jump(0), 0);
                if is_break {
                    ctx.breaks.push(j);
                } else {
                    ctx.continues.push(j);
                }
            }
            None => {
                b.emit(Op::LoadInt(if is_break { 1 } else { 2 }), 0);
                b.emit(Op::CallBuiltin(ops::LOOP_SIGNAL, 1), 0);
            }
        }
    }

    /// After a lazy call inside a loop, act on a `break`/`next` its body raised:
    /// `[result]` stays as the call's value unless a jump is taken.
    fn dispatch_loop_signal(&mut self, b: &mut ChunkBuilder) {
        b.emit(Op::CallBuiltin(ops::TAKE_LOOP_SIGNAL, 0), 0);
        let mut exits = Vec::new();
        for code in [1, 2] {
            b.emit(Op::Dup, 0);
            b.emit(Op::LoadInt(code), 0);
            b.emit(Op::NumEq, 0);
            exits.push(b.emit(Op::JumpIfTrue(0), 0));
        }
        b.emit(Op::Pop, 0);
        let done = b.emit(Op::Jump(0), 0);
        for (j, is_break) in exits.into_iter().zip([true, false]) {
            let here = b.current_pos();
            b.patch_jump(j, here);
            b.emit(Op::Pop, 0);
            b.emit(Op::Pop, 0);
            self.leave_loop(b, is_break);
        }
        let end = b.current_pos();
        b.patch_jump(done, end);
    }

    /// Lower a construct R only rejects when it is *evaluated* to the error R
    /// raises for it, so a `tryCatch` sees it and a branch never taken is
    /// harmless.
    fn runtime_error(&mut self, b: &mut ChunkBuilder, msg: &str) -> Result<(), String> {
        self.expr(
            b,
            &Expr::Call {
                fun: Box::new(Expr::Ident("stop".into())),
                args: vec![Arg {
                    name: None,
                    value: Some(Expr::Str(msg.into())),
                }],
            },
        )
    }

    /// A `break`/`next` written outside any loop.
    fn no_loop_error(&mut self, b: &mut ChunkBuilder) -> Result<(), String> {
        self.runtime_error(b, "no loop for break/next, jumping to top level")
    }

    /// Patch every `break`/`next` recorded for the innermost loop.
    fn close_loop(&mut self, b: &mut ChunkBuilder, cont: usize, end: usize) {
        let ctx = self.loops.pop().expect("close_loop without a loop");
        for j in ctx.breaks {
            b.patch_jump(j, end);
        }
        for j in ctx.continues {
            b.patch_jump(j, cont);
        }
    }

    /// `for (v in seq) body` — a native counter loop over the sequence's
    /// elements, so fusevm's JIT sees an ordinary integer loop.
    fn for_loop(
        &mut self,
        b: &mut ChunkBuilder,
        var: &str,
        seq: &Expr,
        body: &Expr,
    ) -> Result<(), String> {
        // `for (i in a:b)` with a slot loop variable iterates a native integer
        // counter and computes `i = from + c*step` with native ops — no
        // per-element builtin call, so `--aot` can lower the whole loop.
        if self.locals.contains(var) {
            if let Expr::Binary {
                op: BinOp::Colon,
                lhs,
                rhs,
            } = seq
            {
                return self.for_range(b, var, lhs, rhs, body);
            }
        }
        let v_seq = self.tmp_name(b, "seq");
        let v_len = self.tmp_name(b, "len");
        let v_i = self.tmp_name(b, "i");

        self.expr(b, seq)?;
        b.emit(Op::SetVar(v_seq), 0);
        b.emit(Op::GetVar(v_seq), 0);
        b.emit(Op::CallBuiltin(ops::SEQ_LEN, 1), 0);
        b.emit(Op::SetVar(v_len), 0);
        b.emit(Op::LoadInt(0), 0);
        b.emit(Op::SetVar(v_i), 0);

        self.loops.push(LoopCtx {
            continues: Vec::new(),
            breaks: Vec::new(),
        });
        let start = b.current_pos();
        b.emit(Op::GetVar(v_i), 0);
        b.emit(Op::GetVar(v_len), 0);
        b.emit(Op::NumLt, 0);
        let jf = b.emit(Op::JumpIfFalse(0), 0);

        // var <- seq[[i]]
        if self.locals.contains(var) {
            // Native store into the loop variable's slot; `SetVar` consumes the
            // fetched element, leaving nothing (no trailing `Pop`).
            b.emit(Op::GetVar(v_seq), 0);
            b.emit(Op::GetVar(v_i), 0);
            b.emit(Op::CallBuiltin(ops::SEQ_ELEM, 2), 0);
            let slot = b.add_name(var);
            b.emit(Op::SetVar(slot), 0);
        } else {
            self.kstr(b, var);
            b.emit(Op::GetVar(v_seq), 0);
            b.emit(Op::GetVar(v_i), 0);
            b.emit(Op::CallBuiltin(ops::SEQ_ELEM, 2), 0);
            b.emit(Op::CallBuiltin(ops::SETVAR, 2), 0);
            b.emit(Op::Pop, 0);
        }

        self.stmt(b, body)?;

        let cont = b.current_pos();
        b.emit(Op::GetVar(v_i), 0);
        b.emit(Op::LoadInt(1), 0);
        b.emit(Op::Add, 0);
        b.emit(Op::SetVar(v_i), 0);
        b.emit(Op::Jump(start), 0);
        let end = b.current_pos();
        b.patch_jump(jf, end);
        self.close_loop(b, cont, end);
        // `for` itself evaluates to invisible NULL.
        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
        Ok(())
    }

    /// `for (i in from:to)` as a native counter loop: `RANGE_FROM/STEP/LEN` (one
    /// call each, at setup) reproduce `:`'s typed start, ±1 step, and count; the
    /// body computes `i = from + c*step` with native `Mul`/`Add`, `NumLt` for the
    /// bound — no `SEQ_ELEM`, no `1:N` materialization, and `--aot`-lowerable.
    fn for_range(
        &mut self,
        b: &mut ChunkBuilder,
        var: &str,
        lhs: &Expr,
        rhs: &Expr,
        body: &Expr,
    ) -> Result<(), String> {
        let v_a = self.tmp_name(b, "ra");
        let v_b = self.tmp_name(b, "rb");
        let v_from = self.tmp_name(b, "rfrom");
        let v_step = self.tmp_name(b, "rstep");
        let v_len = self.tmp_name(b, "rlen");
        let v_c = self.tmp_name(b, "rc");
        let islot = b.add_name(var);

        // Constant-fold `LIT:LIT` (e.g. `1:1000000`): compute the typed start,
        // ±1 step, and count at compile time and load them as native constants,
        // so the loop setup makes no builtin call. That keeps the whole loop off
        // the builtin path, which is what lets `--aot` native-lower it (a builtin
        // call is a deopt point that ends native codegen).
        let folded = match (const_num(lhs), const_num(rhs)) {
            (Some(a), Some(bv)) => {
                let whole = a == a.trunc() && bv == bv.trunc();
                // NaN-preserving (see `b_range_step`): `!(a > bv)` holds for NaN.
                let step_up = !matches!(a.partial_cmp(&bv), Some(std::cmp::Ordering::Greater));
                let count = ((bv - a).abs() + 1e-10).floor() as i64 + 1;
                if whole {
                    b.emit(Op::LoadInt(a as i64), 0);
                    b.emit(Op::SetVar(v_from), 0);
                    b.emit(Op::LoadInt(if step_up { 1 } else { -1 }), 0);
                    b.emit(Op::SetVar(v_step), 0);
                } else {
                    b.emit(Op::LoadFloat(a), 0);
                    b.emit(Op::SetVar(v_from), 0);
                    b.emit(Op::LoadFloat(if step_up { 1.0 } else { -1.0 }), 0);
                    b.emit(Op::SetVar(v_step), 0);
                }
                b.emit(Op::LoadInt(count), 0);
                b.emit(Op::SetVar(v_len), 0);
                true
            }
            _ => false,
        };
        // `for (i in <int-literal> : <native-scalar>)` — e.g. `1:n`: the elements
        // are integers (start is integer-valued), so compute step/count with
        // native ops on the bound (its `to_float` reads a real scalar only
        // because `native_nums` proved it unboxed). No builtin call, so `--aot`
        // lowers the whole loop.
        let native_bound = !folded
            && int_literal(lhs).is_some()
            && matches!(rhs, Expr::Ident(n) if self.native_nums.contains(n));
        if native_bound {
            let a = int_literal(lhs).unwrap();
            self.expr(b, rhs)?; // the bound → native scalar
            b.emit(Op::SetVar(v_b), 0);
            b.emit(Op::LoadInt(a), 0);
            b.emit(Op::SetVar(v_from), 0);
            // step = if from <= to { 1 } else { -1 }
            b.emit(Op::GetVar(v_from), 0);
            b.emit(Op::GetVar(v_b), 0);
            b.emit(Op::NumLe, 0);
            let to_desc = b.emit(Op::JumpIfFalse(0), 0);
            b.emit(Op::LoadInt(1), 0);
            b.emit(Op::SetVar(v_step), 0);
            let to_after = b.emit(Op::Jump(0), 0);
            let desc = b.current_pos();
            b.patch_jump(to_desc, desc);
            b.emit(Op::LoadInt(-1), 0);
            b.emit(Op::SetVar(v_step), 0);
            let after = b.current_pos();
            b.patch_jump(to_after, after);
            // count = floor(|to - from| + 1e-10) + 1  (native)
            b.emit(Op::GetVar(v_b), 0);
            b.emit(Op::GetVar(v_from), 0);
            b.emit(Op::Sub, 0);
            b.emit(Op::AbsFloat, 0);
            b.emit(Op::LoadFloat(1e-10), 0);
            b.emit(Op::Add, 0);
            b.emit(Op::FloorFloat, 0);
            b.emit(Op::TruncInt, 0);
            b.emit(Op::LoadInt(1), 0);
            b.emit(Op::Add, 0);
            b.emit(Op::SetVar(v_len), 0);
        } else if !folded {
            self.expr(b, lhs)?;
            b.emit(Op::SetVar(v_a), 0);
            self.expr(b, rhs)?;
            b.emit(Op::SetVar(v_b), 0);
            for (op, dst) in [
                (ops::RANGE_FROM, v_from),
                (ops::RANGE_STEP, v_step),
                (ops::RANGE_LEN, v_len),
            ] {
                b.emit(Op::GetVar(v_a), 0);
                b.emit(Op::GetVar(v_b), 0);
                b.emit(Op::CallBuiltin(op, 2), 0);
                b.emit(Op::SetVar(dst), 0);
            }
        }
        b.emit(Op::LoadInt(0), 0);
        b.emit(Op::SetVar(v_c), 0);

        self.loops.push(LoopCtx {
            continues: Vec::new(),
            breaks: Vec::new(),
        });
        let start = b.current_pos();
        b.emit(Op::GetVar(v_c), 0);
        b.emit(Op::GetVar(v_len), 0);
        b.emit(Op::NumLt, 0);
        let jf = b.emit(Op::JumpIfFalse(0), 0);

        b.emit(Op::GetVar(v_from), 0);
        b.emit(Op::GetVar(v_c), 0);
        b.emit(Op::GetVar(v_step), 0);
        b.emit(Op::Mul, 0);
        b.emit(Op::Add, 0);
        b.emit(Op::SetVar(islot), 0);

        self.stmt(b, body)?;

        let cont = b.current_pos();
        b.emit(Op::GetVar(v_c), 0);
        b.emit(Op::LoadInt(1), 0);
        b.emit(Op::Add, 0);
        b.emit(Op::SetVar(v_c), 0);
        b.emit(Op::Jump(start), 0);
        let end = b.current_pos();
        b.patch_jump(jf, end);
        self.close_loop(b, cont, end);
        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
        Ok(())
    }

    /// `&&` / `||`: evaluate the right side only when the left cannot already
    /// decide the answer. A definite FALSE short-circuits `&&`, a definite TRUE
    /// short-circuits `||`; an `NA` left operand falls through to the
    /// vectorized rule, which is how R gets `NA && FALSE` to be FALSE.
    fn short_circuit(
        &mut self,
        b: &mut ChunkBuilder,
        op: &BinOp,
        lhs: &Expr,
        rhs: &Expr,
    ) -> Result<(), String> {
        // Each operand is read down to one logical first (`LOGIC2_ARG`), so a
        // longer vector or a string is R's error rather than a vectorized `&`.
        let sym = if matches!(op, BinOp::And2) {
            "&&"
        } else {
            "||"
        };
        self.expr(b, lhs)?;
        self.kstr(b, &format!("x{sym}"));
        b.emit(Op::CallBuiltin(ops::LOGIC2_ARG, 2), 0);
        b.emit(Op::Dup, 0);
        let probe = if matches!(op, BinOp::And2) {
            ops::IS_FALSE
        } else {
            ops::IS_TRUE
        };
        b.emit(Op::CallBuiltin(probe, 1), 0);
        let done = b.emit(Op::JumpIfTrue(0), 0);
        self.expr(b, rhs)?;
        self.kstr(b, &format!("y{sym}"));
        b.emit(Op::CallBuiltin(ops::LOGIC2_ARG, 2), 0);
        self.kstr(b, binop_name(op));
        b.emit(Op::CallBuiltin(ops::BINOP, 3), 0);
        let end = b.current_pos();
        b.patch_jump(done, end);
        Ok(())
    }

    /// Build the argument list for a call or an index.
    fn args(&mut self, b: &mut ChunkBuilder, args: &[Arg]) -> Result<(), String> {
        for a in args {
            match &a.name {
                Some(n) => self.kstr(b, n),
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
            match &a.value {
                Some(v) => self.expr(b, v)?,
                // An empty argument (`x[, 1]`) is R's "missing" marker.
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
        }
        let argc = u8::try_from(args.len() * 2)
            .map_err(|_| "too many arguments in one call (limit 127)".to_string())?;
        b.emit(Op::CallBuiltin(ops::MKARGS, argc), 0);
        Ok(())
    }

    /// Compile `switch(EXPR, name = value, …, default)` as a lazy jump table:
    /// evaluate `EXPR` once, ask `SWITCH_INDEX` which branch to run, then jump
    /// straight to that branch's code — no other branch is evaluated. An empty
    /// branch (`a =`) falls through to the next branch's value.
    fn switch_expr(&mut self, b: &mut ChunkBuilder, args: &[Arg]) -> Result<(), String> {
        let expr = args[0]
            .value
            .as_ref()
            .ok_or("switch: missing EXPR argument")?;
        let branches = &args[1..];
        let m = branches.len();
        self.expr(b, expr)?;
        for br in branches {
            self.kstr(b, br.name.as_deref().unwrap_or(""));
        }
        let argc = u8::try_from(1 + m).map_err(|_| "switch: too many branches".to_string())?;
        b.emit(Op::CallBuiltin(ops::SWITCH_INDEX, argc), 0);

        // Dispatch: the index `i` stays on the stack; for each branch `k`,
        // `Dup; LoadInt k; Eq; JumpIfTrue body_k`.
        let mut jt = Vec::with_capacity(m);
        for k in 0..m {
            b.emit(Op::Dup, 0);
            b.emit(Op::LoadInt(k as i64), 0);
            b.emit(Op::NumEq, 0);
            jt.push(b.emit(Op::JumpIfTrue(0), 0));
        }
        // No branch matched: drop `i`, yield invisible NULL.
        b.emit(Op::Pop, 0);
        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
        let mut end_jumps = vec![b.emit(Op::Jump(0), 0)];

        // Bodies. `value_start[k]` is the point after `k`'s `Pop`, where a
        // fall-through from an earlier empty branch lands.
        let mut value_start = vec![0usize; m];
        let mut fallthrough: Vec<(usize, usize)> = Vec::new();
        for k in 0..m {
            let body_start = b.current_pos();
            b.patch_jump(jt[k], body_start);
            b.emit(Op::Pop, 0); // drop `i`
            value_start[k] = b.current_pos();
            match branches[k].value.as_ref() {
                Some(v) => {
                    self.expr(b, v)?;
                    end_jumps.push(b.emit(Op::Jump(0), 0));
                }
                None => {
                    if k + 1 < m {
                        // Empty branch: run the next branch's value instead.
                        fallthrough.push((k, b.emit(Op::Jump(0), 0)));
                    } else {
                        b.emit(Op::CallBuiltin(ops::NULL_INVISIBLE, 0), 0);
                        end_jumps.push(b.emit(Op::Jump(0), 0));
                    }
                }
            }
        }
        for (k, j) in fallthrough {
            b.patch_jump(j, value_start[k + 1]);
        }
        let end = b.current_pos();
        for j in end_jumps {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    /// Compile a `function(...)` body into its own chunk, with a prologue that
    /// fills in each defaulted formal the caller omitted.
    fn closure(&mut self, params: &[Param], body: &Expr) -> Result<usize, String> {
        let lazy = params.first().is_some_and(|p| p.name == LAZY_MARK);
        let params = &params[usize::from(lazy)..];
        let saved = std::mem::take(&mut self.loops);
        let in_loop = lazy && (!saved.is_empty() || self.lazy_loop);
        let saved_lazy = std::mem::replace(&mut self.lazy_loop, in_loop);
        let mut fb = ChunkBuilder::new();
        let outer_sites = std::mem::take(&mut self.op_sites);
        for p in params {
            let Some(default) = &p.default else { continue };
            // if (missing(p)) p <- <default>, the default bound as a promise:
            // R evaluates it at first use, in the callee's frame, so
            // `function(a, b = a * 2) { a <- 10; b }` sees the rebound `a`.
            // A literal cannot tell the difference and is bound as itself.
            self.kstr(&mut fb, &p.name);
            fb.emit(Op::CallBuiltin(ops::MISSING, 1), 0);
            let skip = fb.emit(Op::JumpIfFalse(0), 0);
            self.kstr(&mut fb, &p.name);
            let promised = promise_args(&[Arg {
                name: None,
                value: Some(default.clone()),
            }])
            .and_then(|mut wrapped| wrapped.remove(0).value);
            self.expr(&mut fb, promised.as_ref().unwrap_or(default))?;
            fb.emit(Op::CallBuiltin(ops::SETVAR, 2), 0);
            fb.emit(Op::Pop, 0);
            let here = fb.current_pos();
            fb.patch_jump(skip, here);
        }
        // A closure's body is its value, so it is in statement position: the
        // caller's `AUTOPRINT` asks whether *that* value is visible.
        self.tail = true;
        self.expr(&mut fb, body)?;
        self.loops = saved;
        self.lazy_loop = saved_lazy;
        self.finish_chunk(&mut fb, outer_sites);
        self.closures.push(ClosureDef {
            params: params.iter().map(|p| p.name.clone()).collect(),
            chunk: fb.build(),
            // Deparse from the AST here: it is the last point at which the body
            // and the default-argument expressions still exist.
            src: crate::deparse::deparse_closure(params, body),
        });
        Ok(self.closures.len() - 1)
    }

    // ── assignment ─────────────────────────────────────────────────────

    fn assign(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        value: &Expr,
        sup: bool,
    ) -> Result<(), String> {
        match target {
            Expr::Ident(name) | Expr::Str(name) if !sup && self.locals.contains(name) => {
                // A slot-bound local: native store, JIT-visible. `SetVar` pops
                // the value, so `Dup` keeps the copy an assignment expression
                // yields (statements pop it, `y <- x <- 1` and `f(x <- 1)` use it).
                self.expr(b, value)?;
                b.emit(Op::Dup, 0);
                let slot = b.add_name(name);
                b.emit(Op::SetVar(slot), 0);
            }
            Expr::Ident(name) | Expr::Str(name) => {
                self.kstr(b, name);
                self.expr(b, value)?;
                let op = if sup { ops::SETSUPER } else { ops::SETVAR };
                b.emit(Op::CallBuiltin(op, 2), 0);
            }
            _ => {
                let whole = Expr::Assign {
                    target: Box::new(target.clone()),
                    value: Box::new(value.clone()),
                    super_assign: sup,
                };
                let outer = std::mem::replace(
                    &mut self.assign_text,
                    crate::deparse::deparse_first_line(&whole),
                );
                let out = self.complex_assign(b, target, value, sup);
                self.assign_text = outer;
                out?;
            }
        }
        Ok(())
    }

    /// Compile `target <- value` for an index or replacement-call target the way
    /// R's `applydefine` runs it: the right-hand side is evaluated FIRST, before
    /// the target's object or subscripts, and it — not the rebuilt container —
    /// is the value of the whole assignment, so `y <- (names(x) <- "a")` binds
    /// `"a"` and a function whose last statement is `x[2] <- 10` returns `10`.
    /// The modified container is then assigned back to the inner target,
    /// recursing outward-in through [`Self::assign_stack`].
    fn complex_assign(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        value: &Expr,
        sup: bool,
    ) -> Result<(), String> {
        // A target that is no name, index or call is R's runtime error, raised
        // by `do_set` before the right-hand side is touched.
        if !matches!(target, Expr::Index { .. } | Expr::Call { .. }) {
            return self.runtime_error(b, "invalid (do_set) left-hand side to assignment");
        }
        self.expr(b, value)?;
        b.emit(Op::Dup, 0);
        self.assign_stack(b, target, sup)?;
        // Drop what the outermost store returned; the right-hand side remains.
        b.emit(Op::Pop, 0);
        Ok(())
    }

    /// The object of an assignment target has just been pushed. When it is a
    /// bare variable, its reference count describes exactly how many bindings
    /// can see it, so `x[i] <- v` may write into it. When it is anything else
    /// (`x$a[i] <- v`, `f(x)[i] <- v`) the pushed value is an element of some
    /// container, and the count on the element says nothing about how many
    /// bindings reach the container — so it is pinned shared and the write
    /// rebuilds, as it did before reference counting existed. R reaches the
    /// same place from the other direction: `EnsureLocal` duplicates a shared
    /// container, and the duplicate increments every element it shares.
    fn mark_shared_intermediate(&mut self, b: &mut ChunkBuilder, obj: &Expr) {
        if !matches!(obj, Expr::Ident(_) | Expr::Str(_)) {
            b.emit(Op::CallBuiltin(ops::MARK_SHARED, 1), 0);
        }
    }

    /// Assign the value already on top of the stack to `target`.
    fn assign_stack(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        sup: bool,
    ) -> Result<(), String> {
        match target {
            Expr::Ident(name) | Expr::Str(name) => {
                // SETVAR wants [name, value]; the value is already on top.
                self.kstr(b, name);
                b.emit(Op::Swap, 0);
                let op = if sup { ops::SETSUPER } else { ops::SETVAR };
                b.emit(Op::CallBuiltin(op, 2), 0);
                Ok(())
            }
            Expr::Index { kind, obj, args } => {
                // Stack: [value]. Build [obj, args, value] with a rotate.
                self.expr(b, obj)?;
                self.mark_shared_intermediate(b, obj);
                let ip = match kind {
                    IndexKind::Dollar | IndexKind::At => {
                        match args.first().and_then(|a| a.value.clone()) {
                            Some(Expr::Str(n)) => self.kstr(b, &n),
                            _ => return Err("malformed $ assignment target".into()),
                        }
                        b.emit(Op::Rot, 0);
                        b.emit(Op::CallBuiltin(ops::DOLLAR_SET, 3), 0)
                    }
                    IndexKind::Single => {
                        self.args(b, args)?;
                        b.emit(Op::Rot, 0);
                        b.emit(Op::CallBuiltin(ops::INDEX_SET, 3), 0)
                    }
                    IndexKind::Double => {
                        self.args(b, args)?;
                        b.emit(Op::Rot, 0);
                        b.emit(Op::CallBuiltin(ops::INDEX2_SET, 3), 0)
                    }
                };
                // A subassignment's warnings and errors name the whole
                // assignment (`In x[5:6] <- 1:3 :`), as R's `applydefine`
                // evaluates `[<-` under the assignment call.
                self.op_sites.push((ip, self.assign_text.clone()));
                self.assign_stack(b, obj, sup)
            }
            // `f(x, …)[i] <- v` — the replacement function reached through
            // another target, so its own new value is already on the stack. R
            // unrolls it the same way it unrolls the outermost case:
            // `names(x)[1] <- z` is `x <- \`names<-\`(x, \`[<-\`(names(x), 1, z))`,
            // and the inner `[<-` is what the `Index` arm above just emitted.
            //
            // `REPLACE` wants `[name, obj, args, value]` and the value is at the
            // BOTTOM here rather than pushed last, so each operand is swapped
            // under it as it goes on. `Rot` cannot do it: it reaches three deep
            // and this is four.
            Expr::Call { fun, args } => {
                let Expr::Ident(fname) = fun.as_ref() else {
                    return Err("invalid function in complex assignment".into());
                };
                let Some(inner) = args.first().and_then(|a| a.value.clone()) else {
                    return Err(format!("invalid target for {fname}<-"));
                };
                self.kstr(b, fname);
                b.emit(Op::Swap, 0);
                self.expr(b, &inner)?;
                b.emit(Op::Swap, 0);
                self.args(b, &args[1..])?;
                b.emit(Op::Swap, 0);
                let text = self.assign_text.clone();
                self.kstr(b, &text);
                b.emit(Op::CallBuiltin(ops::REPLACE, 5), 0);
                self.assign_stack(b, &inner, sup)
            }
            _ => self.runtime_error(b, "target of assignment expands to non-language object"),
        }
    }
}

/// The native fusevm op for a binary operator whose scalar semantics match R
/// exactly. `+ - *` do. `/` does NOT: fusevm's `Op::Div` yields `Undef` on a
/// zero divisor (awk/shell semantics), whereas R's `/` is IEEE (`1/0` is `Inf`,
/// `0/0` is `NaN`) — so it stays on the builtin path, as fusevm's own `Op::Div`
/// comment prescribes for a frontend with different division semantics. `%%`/
/// `%/%` arrive as `Expr::Special`; `^`, comparisons, and `& |` also stay
/// builtins (native forms diverge from R on NA/NaN or sign).
/// A numeric literal's value, for compile-time folding of a `LIT:LIT` range.
fn const_num(e: &Expr) -> Option<f64> {
    match e {
        Expr::Num(n) => Some(*n),
        Expr::Int(n) => Some(*n as f64),
        _ => None,
    }
}

/// An integer-valued numeric literal — the start of a range whose elements are
/// integers (`1:n`), so the loop variable is statically `Int`.
fn int_literal(e: &Expr) -> Option<i64> {
    match e {
        Expr::Int(n) => Some(*n),
        Expr::Num(n) if *n == n.trunc() => Some(*n as i64),
        _ => None,
    }
}

/// Slots that provably hold an **unboxed native numeric scalar** — a value
/// `Value::Int/Float`, never a heap `Obj`. A slot qualifies when every
/// assignment to it is a numeric literal or scalar arithmetic over such slots
/// (and `for`-range counters, which are native ints). Anything that could box —
/// a builtin call, `c(...)`, an index — disqualifies it. Fixed-point over the
/// self/other-slot references (`s <- s + i`). Used so `for (i in 1:n)` can lower
/// its bound `n` with native ops (whose `to_float` reads only native scalars).
fn native_num_slots(exprs: &[Expr]) -> std::collections::HashSet<String> {
    let mut cand = std::collections::HashSet::new();
    let mut assigns: Vec<(String, &Expr)> = Vec::new();
    for e in exprs {
        collect_num_assigns(e, &mut cand, &mut assigns);
    }
    loop {
        let mut changed = false;
        for (name, rhs) in &assigns {
            if cand.contains(name) && !is_native_num(rhs, &cand) {
                cand.remove(name);
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    cand
}

/// Gather every simple `name <- rhs` (and `for` counter) under `e`; a name is a
/// candidate native-num slot, `assigns` records each rhs to re-check at fixpoint.
fn collect_num_assigns<'a>(
    e: &'a Expr,
    cand: &mut std::collections::HashSet<String>,
    assigns: &mut Vec<(String, &'a Expr)>,
) {
    match e {
        Expr::Assign {
            target,
            value,
            super_assign: false,
        } => {
            if let Expr::Ident(n) | Expr::Str(n) = target.as_ref() {
                cand.insert(n.clone());
                assigns.push((n.clone(), value));
            }
            collect_num_assigns(value, cand, assigns);
        }
        Expr::For { var, seq, body } => {
            // A for-range counter is a native int; a general `for` var is not.
            if int_literal(seq_start(seq)).is_some() {
                cand.insert(var.clone());
            }
            collect_num_assigns(body, cand, assigns);
        }
        Expr::If { cond, then, els } => {
            collect_num_assigns(cond, cand, assigns);
            collect_num_assigns(then, cand, assigns);
            if let Some(x) = els {
                collect_num_assigns(x, cand, assigns);
            }
        }
        Expr::While { cond, body } => {
            collect_num_assigns(cond, cand, assigns);
            collect_num_assigns(body, cand, assigns);
        }
        Expr::Repeat(b) => collect_num_assigns(b, cand, assigns),
        Expr::Paren(x) => collect_num_assigns(x, cand, assigns),
        Expr::Block(xs) => {
            for x in xs {
                collect_num_assigns(x, cand, assigns);
            }
        }
        _ => {}
    }
}

/// The `lhs` of a `seq` that is a `:` range (else the expr itself).
fn seq_start(seq: &Expr) -> &Expr {
    match seq {
        Expr::Binary {
            op: BinOp::Colon,
            lhs,
            ..
        } => lhs,
        other => other,
    }
}

/// Whether `e` provably evaluates to a native numeric scalar given the current
/// candidate slot set.
fn is_native_num(e: &Expr, cand: &std::collections::HashSet<String>) -> bool {
    match e {
        Expr::Num(_) | Expr::Int(_) => true,
        Expr::Ident(n) => cand.contains(n),
        Expr::Binary { op, lhs, rhs } => {
            matches!(
                op,
                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Pow
            ) && is_native_num(lhs, cand)
                && is_native_num(rhs, cand)
        }
        Expr::Special { name, lhs, rhs } if name == "%%" || name == "%/%" => {
            is_native_num(lhs, cand) && is_native_num(rhs, cand)
        }
        Expr::Unary { operand, .. } => is_native_num(operand, cand),
        _ => false,
    }
}

/// Marks the zero-formal closure [`lazy_thunk`] builds; `closure` strips it.
const LAZY_MARK: &str = ".rlang_lazy";

/// [`thunk`] for the body of a lazy base function (`tryCatch`, `try`, …), which
/// R forces as a promise: `return`, `break` and `next` in it act on the code
/// that wrote it, not on the thunk.
fn lazy_thunk(body: Expr) -> Expr {
    Expr::Function {
        params: vec![Param {
            name: LAZY_MARK.into(),
            default: None,
        }],
        body: Box::new(body),
    }
}

/// `function() <body>` — a zero-argument closure that defers `body`.
fn thunk(body: Expr) -> Expr {
    Expr::Function {
        params: Vec::new(),
        body: Box::new(body),
    }
}

/// `(function() <body>)()` — defer `body`, then immediately call it, so it runs
/// in a fresh environment enclosing the caller's.
fn call_thunk(body: Expr) -> Expr {
    Expr::Call {
        fun: Box::new(thunk(body)),
        args: Vec::new(),
    }
}

/// Wrap the arguments a lazy special form must not have evaluated for it in
/// `function() …` thunks, or `None` when `name` is not one of them.
///
/// `tryCatch(expr, error = h, finally = f)`: `expr` and `finally` are
/// expressions to run under the handlers, while the handlers are already
/// functions and are left alone. `try(expr)` and `on.exit(expr)` defer their one
/// body argument the same way.
/// `.rlang_quote("<source>")` — the eager call that stands in for a quoted
/// expression. The deparse is the whole tree, newline-separated, so the
/// primitive parses back the call that was written. `bquote` adds a second
/// argument, `TRUE`, asking the primitive to splice each `.(x)` with the value
/// of `x` in the caller's frame.
fn quote_call(inner: &Expr, splice: bool) -> Expr {
    let mut args = vec![Arg {
        name: None,
        value: Some(Expr::Str(deparse_lines(inner))),
    }];
    if splice {
        args.push(Arg {
            name: None,
            value: Some(Expr::Bool(true)),
        });
    }
    Expr::Call {
        fun: Box::new(Expr::Ident(".rlang_quote".into())),
        args,
    }
}

/// One `rbind`/`cbind` argument's seam label as written: the bare symbol's
/// name, when it is one (R's `deparse.level = 1`), and its full deparse
/// (`deparse.level = 2`).
type BindLabel = (Option<String>, String);

/// Wrap each argument of a closure call in `.rlang_promise(function() <arg>)`,
/// or `None` when the call has nothing to defer.
///
/// A `...` or an empty argument is left alone: the first expands at run time
/// into arguments that were already promised at THEIR call, and the second is
/// the missing marker, which is not an expression to defer. A literal is left
/// alone too — evaluating it cannot fail, cannot have an effect, and wrapping
/// it would cost a closure and a heap object per call for nothing.
fn promise_args(args: &[Arg]) -> Option<Vec<Arg>> {
    // Already a closure value: promising it would only hide the loop around a
    // lazy body from the thunk, whose `break`/`next` must reach that loop.
    fn is_lazy_thunk(e: &Expr) -> bool {
        matches!(e, Expr::Function { params, .. } if params.first().is_some_and(|p| p.name == LAZY_MARK))
    }
    fn is_literal(e: &Expr) -> bool {
        matches!(
            e,
            Expr::Num(_) | Expr::Int(_) | Expr::Str(_) | Expr::Bool(_) | Expr::Null
        )
    }
    let mut out = Vec::with_capacity(args.len());
    let mut changed = false;
    for a in args {
        match &a.value {
            Some(v) if !matches!(v, Expr::Dots) && !is_literal(v) && !is_lazy_thunk(v) => {
                changed = true;
                out.push(Arg {
                    name: a.name.clone(),
                    value: Some(Expr::Call {
                        fun: Box::new(Expr::Ident(".rlang_promise".into())),
                        args: vec![Arg {
                            name: None,
                            value: Some(thunk(v.clone())),
                        }],
                    }),
                });
            }
            _ => out.push(a.clone()),
        }
    }
    changed.then_some(out)
}

fn thunk_lazy_args(name: &str, args: &[Arg]) -> Option<Vec<Arg>> {
    // The argument names whose values are bodies rather than handlers, per
    // special form. An empty name means "the first positional argument".
    let deferred: &[&str] = match name {
        "tryCatch" | "withCallingHandlers" => &["", "expr", "finally"],
        "try" => &["", "expr"],
        "on.exit" => &["", "expr"],
        // `withRestarts` runs its body with restarts established, and the
        // `suppress*` family runs its body under a muffling handler — both need
        // the frame in place *before* the body evaluates, which eager arguments
        // cannot give them.
        "withRestarts" => &["", "expr"],
        "suppressWarnings" | "suppressMessages" | "suppressPackageStartupMessages" => &["", "expr"],
        _ => return None,
    };
    let mut out = Vec::with_capacity(args.len());
    let mut seen_positional = false;
    let mut changed = false;
    for a in args {
        // A `...` or empty argument cannot be thunked — its expression only
        // exists at run time — so such a call is left to the eager path.
        let value = a.value.clone()?;
        let is_body = match &a.name {
            Some(n) => deferred.contains(&n.as_str()),
            None => {
                let first = !seen_positional;
                seen_positional = true;
                first && deferred.contains(&"")
            }
        };
        if is_body && !matches!(value, Expr::Dots) {
            changed = true;
            out.push(Arg {
                name: a.name.clone(),
                value: Some(lazy_thunk(value)),
            });
        } else {
            out.push(a.clone());
        }
    }
    changed.then_some(out)
}

fn native_binop(op: &BinOp) -> Option<Op> {
    match op {
        BinOp::Add => Some(Op::Add),
        BinOp::Sub => Some(Op::Sub),
        BinOp::Mul => Some(Op::Mul),
        _ => None,
    }
}

fn binop_name(op: &BinOp) -> &'static str {
    match op {
        BinOp::Add => "+",
        BinOp::Sub => "-",
        BinOp::Mul => "*",
        BinOp::Div => "/",
        BinOp::Pow => "^",
        BinOp::Lt => "<",
        BinOp::Gt => ">",
        BinOp::Le => "<=",
        BinOp::Ge => ">=",
        BinOp::Eq => "==",
        BinOp::Ne => "!=",
        BinOp::And | BinOp::And2 => "&",
        BinOp::Or | BinOp::Or2 => "|",
        BinOp::Colon => ":",
    }
}

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

    fn ops_of(src: &str) -> Vec<Op> {
        compile(&parse(src).unwrap()).unwrap().main.ops
    }

    #[test]
    fn loops_lower_to_native_jumps_not_builtins() {
        let ops = ops_of("for (i in 1:3) i");
        assert!(ops.iter().any(|o| matches!(o, Op::NumLt)));
        assert!(ops.iter().any(|o| matches!(o, Op::JumpIfFalse(_))));
        assert!(ops.iter().any(|o| matches!(o, Op::Add)));
    }

    #[test]
    fn short_circuit_and_emits_a_guard_jump() {
        let ops = ops_of("a && b");
        assert!(ops
            .iter()
            .any(|o| matches!(o, Op::CallBuiltin(id, 1) if *id == ops::IS_FALSE)));
        assert!(ops.iter().any(|o| matches!(o, Op::JumpIfTrue(_))));
    }

    #[test]
    fn nested_index_assignment_rebuilds_outward_in() {
        // x$a[1] <- 9  ->  INDEX_SET on the inner vector, then DOLLAR_SET on x,
        // then SETVAR of x.
        let ops = ops_of("x$a[1] <- 9");
        let ids: Vec<u16> = ops
            .iter()
            .filter_map(|o| match o {
                Op::CallBuiltin(id, _) => Some(*id),
                _ => None,
            })
            .collect();
        let pos = |id: u16| ids.iter().position(|x| *x == id);
        assert!(pos(ops::INDEX_SET) < pos(ops::DOLLAR_SET));
        assert!(pos(ops::DOLLAR_SET) < pos(ops::SETVAR));
    }

    #[test]
    fn replacement_functions_lower_to_replace() {
        let ops = ops_of("names(x) <- c(\"a\")");
        assert!(ops
            .iter()
            .any(|o| matches!(o, Op::CallBuiltin(id, 5) if *id == ops::REPLACE)));
    }

    #[test]
    fn break_outside_a_loop_is_a_runtime_error() {
        // R reports it when the `break` is evaluated, as a condition a
        // `tryCatch` can handle, so the program still compiles and the
        // `break` lowers to a call of `stop`.
        let ops = ops_of("break");
        assert!(!ops.is_empty());
        assert!(!ops.iter().any(|o| matches!(o, Op::Jump(_))));
    }
}