beamr 0.6.3

A Rust runtime with the BEAM's execution model, targeting Gleam
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
//! Erlang Term Storage BIFs.
//!
//! These BIFs expose the core ETS table lifecycle and lookup operations through
//! the normal native-function registry under the `ets` module.

use std::{collections::BTreeMap, sync::Arc};

use crate::atom::{Atom, AtomTable};
use crate::ets::{
    AccessOp, CompiledMatchSpec, EtsError, EtsHeir, EtsRegistry, EtsTable, EtsTableId,
    EtsTableMetadata, EtsTableType, MatchArena, Protection, TermKey, copy_term_to_ets,
    copy_term_to_heap,
};
use crate::native::stdlib_stubs::maps_bifs::ContinuationStep;
use crate::native::{
    BifRegistryImpl, Capability, NativeContinuation, NativeFn, NativeRegistrationError,
    ProcessContext,
};
use crate::term::boxed::{Closure, Cons, Tuple};
use crate::term::{Term, compare};

/// Scheduler-facing ETS registry operations used by ETS BIFs.
pub trait EtsFacility: Send + Sync {
    /// Create a table and return its allocated id.
    fn create_table(&self, metadata: EtsTableMetadata) -> Result<EtsTableId, EtsError>;
    /// Look up a table by numeric id.
    fn lookup_table(&self, id: EtsTableId) -> Option<Arc<dyn EtsTable>>;
    /// Look up a named table by atom.
    fn lookup_named_table(&self, name: Atom) -> Option<Arc<dyn EtsTable>>;
    /// Look up the id currently bound to a table name.
    fn lookup_table_by_name(&self, name: Atom) -> Option<EtsTableId>;
    /// Delete a table by numeric id.
    fn delete_table(&self, id: EtsTableId) -> bool;
    /// Transfer table ownership and deliver the ETS-TRANSFER message.
    fn give_away_table(
        &self,
        table_id: EtsTableId,
        new_owner: u64,
        from_pid: u64,
        gift_data: Term,
        atom_table: &AtomTable,
    ) -> Result<(), EtsError>;
}

fn parse_heir_option(tuple: Tuple, none: Atom, options: &mut NewOptions) -> Result<(), Term> {
    match tuple.arity() {
        2 => {
            if tuple.get(1) != Some(Term::atom(none)) {
                return Err(badarg());
            }
            options.heir = None;
            Ok(())
        }
        3 => {
            let heir_pid = tuple.get(1).and_then(Term::as_pid).ok_or_else(badarg)?;
            let heir_data = tuple.get(2).ok_or_else(badarg)?;
            let data = copy_term_to_ets(heir_data).map_err(ets_error_to_badarg)?;
            options.heir = Some(EtsHeir {
                pid: heir_pid,
                data,
            });
            Ok(())
        }
        _ => Err(badarg()),
    }
}

impl EtsFacility for EtsRegistry {
    fn create_table(&self, metadata: EtsTableMetadata) -> Result<EtsTableId, EtsError> {
        self.try_create_table(metadata)
    }

    fn lookup_table(&self, id: EtsTableId) -> Option<Arc<dyn EtsTable>> {
        self.lookup_table(id)
    }

    fn lookup_named_table(&self, name: Atom) -> Option<Arc<dyn EtsTable>> {
        self.lookup_named_table(name)
    }

    fn lookup_table_by_name(&self, name: Atom) -> Option<EtsTableId> {
        self.lookup_table_by_name(name)
    }

    fn delete_table(&self, id: EtsTableId) -> bool {
        self.delete_table(id)
    }

    fn give_away_table(
        &self,
        table_id: EtsTableId,
        new_owner: u64,
        _from_pid: u64,
        _gift_data: Term,
        _atom_table: &AtomTable,
    ) -> Result<(), EtsError> {
        if self.transfer_table_owner(table_id, new_owner) {
            Ok(())
        } else {
            Err(EtsError::Badarg)
        }
    }
}

type EtsBif = (&'static str, u8, NativeFn);

const ETS_BIFS: &[EtsBif] = &[
    ("new", 2, bif_new),
    ("insert", 2, bif_insert),
    ("lookup", 2, bif_lookup),
    ("tab2list", 1, bif_tab2list),
    ("foldl", 3, bif_foldl),
    ("match", 1, bif_match_1),
    ("match", 2, bif_match_2),
    ("match", 3, bif_match_3),
    ("match_object", 2, bif_match_object),
    ("match_delete", 2, bif_match_delete),
    ("select", 1, bif_select_1),
    ("select", 2, bif_select_2),
    ("select", 3, bif_select_3),
    ("delete", 1, bif_delete_1),
    ("delete", 2, bif_delete_2),
    ("give_away", 3, bif_give_away),
    ("member", 2, bif_member),
    ("first", 1, bif_first),
    ("next", 2, bif_next),
    ("last", 1, bif_last),
    ("prev", 2, bif_prev),
    ("info", 1, bif_info_1),
    ("info", 2, bif_info_2),
];

const INFO_ITEMS: &[&str] = &[
    "name",
    "type",
    "size",
    "keypos",
    "protection",
    "owner",
    "memory",
];

struct NewOptions {
    table_type: EtsTableType,
    protection: Protection,
    named_table: bool,
    keypos: usize,
    read_concurrency: bool,
    write_concurrency: bool,
    heir: Option<EtsHeir>,
}

/// Native continuation state for ets:foldl/3.
#[derive(Clone, Debug)]
pub struct EtsFoldlState {
    fun: Term,
    entries: Vec<Term>,
    index: usize,
}

impl EtsFoldlState {
    /// Visit every held term, for GC root snapshots.
    pub(crate) fn for_each_term(&self, f: &mut dyn FnMut(Term)) {
        f(self.fun);
        self.entries.iter().copied().for_each(f);
    }

    /// Visit every held term mutably, so GC can forward moved terms.
    pub(crate) fn for_each_term_mut(&mut self, f: &mut dyn FnMut(&mut Term)) {
        f(&mut self.fun);
        self.entries.iter_mut().for_each(f);
    }
}

/// Registers all ETS BIFs under the `ets` module.
pub fn register_ets_bifs(
    registry: &BifRegistryImpl,
    atom_table: &AtomTable,
) -> Result<(), NativeRegistrationError> {
    let ets = atom_table.intern("ets");

    for &(function_name, arity, native_function) in ETS_BIFS {
        let function = atom_table.intern(function_name);
        registry.register(
            ets,
            function,
            arity,
            native_function,
            Capability::ProcessLocal,
        )?;
    }

    Ok(())
}

/// ets:new/2 — create an ETS table.
pub fn bif_new(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [name_term, options_term] = args else {
        return Err(badarg());
    };
    let name = name_term.as_atom().ok_or_else(badarg)?;
    let options = parse_new_options(*options_term, context.atom_table().ok_or_else(badarg)?)?;
    let owner = context.pid().ok_or_else(badarg)?;
    let facility = context.ets_facility().ok_or_else(badarg)?;

    let metadata = EtsTableMetadata {
        name: options.named_table.then_some(name),
        id: 0,
        table_type: options.table_type,
        protection: options.protection,
        owner: crate::ets::EtsOwner::new(owner),
        keypos: options.keypos,
        read_concurrency: options.read_concurrency,
        write_concurrency: options.write_concurrency,
        heir: options.heir,
    };
    let table_id = facility
        .create_table(metadata)
        .map_err(ets_error_to_badarg)?;

    if options.named_table {
        Ok(Term::atom(name))
    } else {
        small_int_from_u64(table_id)
    }
}

/// ets:insert/2 — insert one tuple or a proper list of tuples.
pub fn bif_insert(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, object_or_objects] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Write)
        .map_err(|_| badarg())?;

    let tuples = parse_insert_objects(*object_or_objects)?;
    for tuple in &tuples {
        crate::ets::tuple_key(*tuple, table.metadata().keypos).map_err(ets_error_to_badarg)?;
    }
    for tuple in tuples {
        table.insert(tuple).map_err(ets_error_to_badarg)?;
    }

    Ok(Term::atom(Atom::TRUE))
}

/// ets:give_away/3 — transfer a table to another process.
pub fn bif_give_away(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, pid_term, gift_data] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    if table.metadata().owner.get() != caller {
        return Err(badarg());
    }
    let recipient = pid_term.as_pid().ok_or_else(badarg)?;
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let facility = context.ets_facility().ok_or_else(badarg)?;
    facility
        .give_away_table(
            table.metadata().id,
            recipient,
            caller,
            *gift_data,
            atom_table,
        )
        .map_err(ets_error_to_badarg)?;
    Ok(Term::atom(Atom::TRUE))
}

/// ets:lookup/2 — return all tuples matching a key.
pub fn bif_lookup(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, key] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Read)
        .map_err(|_| badarg())?;

    let tuples = table.lookup(*key);
    context.ensure_heap_space(list_heap_words(tuples.len()))?;
    context.alloc_list(&tuples)
}

/// ets:tab2list/1 — return a snapshot list of all tuples in the table.
pub fn bif_tab2list(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;

    let tuples = table.tab2list();
    context.ensure_heap_space(list_heap_words(tuples.len()))?;
    context.alloc_list(&tuples)
}

/// ets:foldl/3 — fold a function over a table snapshot from left to right.
pub fn bif_foldl(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [fun, acc, tab] = args else {
        return Err(badarg());
    };
    ensure_fun_arity(*fun, 2)?;
    let table = resolve_readable_table(*tab, context)?;
    let entries = table.tab2list();
    if entries.is_empty() {
        return Ok(*acc);
    }

    context.set_continuation_trampoline(
        *fun,
        vec![entries[0], *acc],
        NativeContinuation::EtsFoldl(EtsFoldlState {
            fun: *fun,
            entries,
            index: 1,
        }),
    );
    Ok(Term::NIL)
}

/// Resume ets:foldl/3 after one closure invocation returns the next accumulator.
pub fn resume_ets_foldl(
    state: EtsFoldlState,
    closure_result: Term,
) -> Result<ContinuationStep, Term> {
    if let Some(element) = state.entries.get(state.index).copied() {
        Ok(ContinuationStep::Call {
            fun: state.fun,
            args: vec![element, closure_result],
            continuation: NativeContinuation::EtsFoldl(EtsFoldlState {
                fun: state.fun,
                entries: state.entries,
                index: state.index + 1,
            }),
        })
    } else {
        Ok(ContinuationStep::Done(closure_result))
    }
}

/// ets:match/1 — resume a paginated match continuation.
pub fn bif_match_1(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [continuation] = args else {
        return Err(badarg());
    };
    let continuation =
        MatchContinuation::parse(*continuation, MatchContinuationKind::Match, context)?;
    let table = resolve_readable_table(continuation.tab, context)?;
    collect_match_page(
        &table,
        continuation.pattern,
        continuation.position,
        continuation.limit,
        context,
    )
}

/// ets:match/2 — return bound variables for all objects matching a pattern.
pub fn bif_match_2(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, pattern] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let results = collect_match_results(&table, *pattern, MatchResultMode::Bindings, context)?;
    context.alloc_list(&results)
}

/// ets:match/3 — return a limited page of bound-variable results plus a continuation.
pub fn bif_match_3(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, pattern, limit] = args else {
        return Err(badarg());
    };
    let limit = parse_positive_limit(*limit)?;
    let table = resolve_readable_table(*tab, context)?;
    collect_match_page(&table, *pattern, 0, limit, context)
}

/// ets:match_object/2 — return all objects matching a pattern.
pub fn bif_match_object(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, pattern] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let results = collect_match_results(&table, *pattern, MatchResultMode::Object, context)?;
    context.alloc_list(&results)
}

/// ets:select/1 — resume a paginated select continuation.
pub fn bif_select_1(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [continuation] = args else {
        return Err(badarg());
    };
    let continuation =
        MatchContinuation::parse(*continuation, MatchContinuationKind::Select, context)?;
    let table = resolve_readable_table(continuation.tab, context)?;
    collect_select_page(
        &table,
        continuation.pattern,
        continuation.position,
        continuation.limit,
        context,
    )
}

/// ets:select/2 — evaluate a match specification against all table objects.
pub fn bif_select_2(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, spec] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let results = collect_select_results(&table, *spec, 0, None, context)?.results;
    context.alloc_list(&results)
}

/// ets:select/3 — evaluate a limited page of match-spec results plus a continuation.
pub fn bif_select_3(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, spec, limit] = args else {
        return Err(badarg());
    };
    let limit = parse_positive_limit(*limit)?;
    let table = resolve_readable_table(*tab, context)?;
    collect_select_page(&table, *spec, 0, limit, context)
}

/// ets:match_delete/2 — delete every object matching a pattern.
pub fn bif_match_delete(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, pattern] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Write)
        .map_err(|_| badarg())?;

    for object in table.tab2list() {
        if ets_pattern_match(*pattern, object, context)?.is_some() {
            let _deleted = table.delete_object(object);
        }
    }
    Ok(Term::atom(Atom::TRUE))
}

/// ets:first/1 — return the first key in a table snapshot or '$end_of_table'.
pub fn bif_first(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let keys = table_snapshot_keys(&table, context)?;
    Ok(keys.first().copied().unwrap_or(end_of_table_atom(context)?))
}

/// ets:next/2 — return the next key in a table snapshot or '$end_of_table'.
pub fn bif_next(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, key] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let keys = table_snapshot_keys(&table, context)?;
    cursor_neighbor(&table, keys, *key, CursorDirection::Next, context)
}

/// ets:last/1 — return the last key in a table snapshot or '$end_of_table'.
pub fn bif_last(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let keys = table_snapshot_keys(&table, context)?;
    Ok(keys.last().copied().unwrap_or(end_of_table_atom(context)?))
}

/// ets:prev/2 — return the previous key in a table snapshot or '$end_of_table'.
pub fn bif_prev(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, key] = args else {
        return Err(badarg());
    };
    let table = resolve_readable_table(*tab, context)?;
    let keys = table_snapshot_keys(&table, context)?;
    cursor_neighbor(&table, keys, *key, CursorDirection::Prev, context)
}

/// ets:delete/1 — delete an entire table. Only the owner may delete it.
pub fn bif_delete_1(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    if table.metadata().owner.get() != caller {
        return Err(badarg());
    }

    let facility = context.ets_facility().ok_or_else(badarg)?;
    if !facility.delete_table(table.metadata().id) {
        return Err(badarg());
    }
    Ok(Term::atom(Atom::TRUE))
}

/// ets:delete/2 — delete all entries matching a key.
pub fn bif_delete_2(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, key] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Write)
        .map_err(|_| badarg())?;
    let _deleted = table.delete_key(*key);
    Ok(Term::atom(Atom::TRUE))
}

/// ets:member/2 — true when a key has at least one object.
pub fn bif_member(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, key] = args else {
        return Err(badarg());
    };
    let table = resolve_existing_table(*tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Read)
        .map_err(|_| badarg())?;
    Ok(bool_term(!table.lookup(*key).is_empty()))
}

/// ets:info/1 — return a deterministic metadata proplist, or `undefined`.
pub fn bif_info_1(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab] = args else {
        return Err(badarg());
    };
    let Some(table) = resolve_table(*tab, context)? else {
        return Ok(Term::atom(Atom::UNDEFINED));
    };

    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let item_atoms = INFO_ITEMS
        .iter()
        .map(|item| atom_table.intern(item))
        .collect::<Vec<_>>();
    let values = INFO_ITEMS
        .iter()
        .map(|item| info_value(&table, item, context))
        .collect::<Result<Vec<_>, _>>()?;

    context.ensure_heap_space(info_proplist_heap_words(INFO_ITEMS.len()))?;
    let mut entries = Vec::with_capacity(INFO_ITEMS.len());
    for (item_atom, value) in item_atoms.into_iter().zip(values) {
        entries.push(context.alloc_tuple(&[Term::atom(item_atom), value])?);
    }
    context.alloc_list(&entries)
}

/// ets:info/2 — return a single metadata item, or `undefined` for missing table.
pub fn bif_info_2(args: &[Term], context: &mut ProcessContext) -> Result<Term, Term> {
    let [tab, item_term] = args else {
        return Err(badarg());
    };
    let item = item_term.as_atom().ok_or_else(badarg)?;
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let item_name = atom_table.resolve(item).ok_or_else(badarg)?;
    if !INFO_ITEMS.contains(&item_name) {
        return Err(badarg());
    }

    let Some(table) = resolve_table(*tab, context)? else {
        return Ok(Term::atom(Atom::UNDEFINED));
    };
    info_value(&table, item_name, context)
}

fn parse_new_options(options_term: Term, atom_table: &AtomTable) -> Result<NewOptions, Term> {
    let mut options = NewOptions {
        table_type: EtsTableType::Set,
        protection: Protection::Protected,
        named_table: false,
        keypos: 1,
        read_concurrency: false,
        write_concurrency: false,
        heir: None,
    };
    let set = atom_table.intern("set");
    let ordered_set = atom_table.intern("ordered_set");
    let bag = atom_table.intern("bag");
    let duplicate_bag = atom_table.intern("duplicate_bag");
    let public = atom_table.intern("public");
    let protected = atom_table.intern("protected");
    let private = atom_table.intern("private");
    let named_table = atom_table.intern("named_table");
    let keypos = atom_table.intern("keypos");
    let read_concurrency = atom_table.intern("read_concurrency");
    let write_concurrency = atom_table.intern("write_concurrency");
    let heir = atom_table.intern("heir");
    let none = atom_table.intern("none");

    let mut tail = options_term;
    while !tail.is_nil() {
        let cons = Cons::new(tail).ok_or_else(badarg)?;
        let option = cons.head();
        if let Some(atom) = option.as_atom() {
            if atom == set {
                options.table_type = EtsTableType::Set;
            } else if atom == ordered_set {
                options.table_type = EtsTableType::OrderedSet;
            } else if atom == bag {
                options.table_type = EtsTableType::Bag;
            } else if atom == duplicate_bag {
                options.table_type = EtsTableType::DuplicateBag;
            } else if atom == public {
                options.protection = Protection::Public;
            } else if atom == protected {
                options.protection = Protection::Protected;
            } else if atom == private {
                options.protection = Protection::Private;
            } else if atom == named_table {
                options.named_table = true;
            } else {
                return Err(badarg());
            }
        } else if let Some(tuple) = Tuple::new(option) {
            let option_name = tuple.get(0).ok_or_else(badarg)?;
            if option_name == Term::atom(heir) {
                parse_heir_option(tuple, none, &mut options)?;
                tail = cons.tail();
                continue;
            }
            if tuple.arity() != 2 {
                return Err(badarg());
            }
            let option_value = tuple.get(1).ok_or_else(badarg)?;
            if option_name == Term::atom(keypos) {
                let keypos_value = option_value
                    .as_small_int()
                    .and_then(|value| usize::try_from(value).ok())
                    .filter(|value| *value > 0)
                    .ok_or_else(badarg)?;
                options.keypos = keypos_value;
            } else if option_name == Term::atom(read_concurrency) {
                options.read_concurrency = parse_bool_option(option_value)?;
            } else if option_name == Term::atom(write_concurrency) {
                options.write_concurrency = parse_bool_option(option_value)?;
            } else {
                return Err(badarg());
            }
        } else {
            return Err(badarg());
        }
        tail = cons.tail();
    }

    Ok(options)
}

fn parse_bool_option(value: Term) -> Result<bool, Term> {
    if value == Term::atom(Atom::TRUE) {
        Ok(true)
    } else if value == Term::atom(Atom::FALSE) {
        Ok(false)
    } else {
        Err(badarg())
    }
}

fn parse_insert_objects(object_or_objects: Term) -> Result<Vec<Term>, Term> {
    if Tuple::new(object_or_objects).is_some() {
        return Ok(vec![object_or_objects]);
    }

    let mut tuples = Vec::new();
    let mut tail = object_or_objects;
    while !tail.is_nil() {
        let cons = Cons::new(tail).ok_or_else(badarg)?;
        let tuple = cons.head();
        if Tuple::new(tuple).is_none() {
            return Err(badarg());
        }
        tuples.push(tuple);
        tail = cons.tail();
    }
    Ok(tuples)
}

#[derive(Copy, Clone)]
enum MatchResultMode {
    Bindings,
    Object,
}

#[derive(Copy, Clone, Eq, PartialEq)]
enum MatchContinuationKind {
    Match,
    Select,
}

struct MatchContinuation {
    tab: Term,
    position: usize,
    limit: usize,
    pattern: Term,
}

struct PagedResults {
    results: Vec<Term>,
    next_position: Option<usize>,
}

impl MatchContinuation {
    fn parse(
        term: Term,
        expected_kind: MatchContinuationKind,
        context: &ProcessContext,
    ) -> Result<Self, Term> {
        let tuple = Tuple::new(term).ok_or_else(badarg)?;
        if tuple.arity() != 5 {
            return Err(badarg());
        }
        let tag = tuple.get(0).ok_or_else(badarg)?;
        let table_id = tuple.get(1).ok_or_else(badarg)?;
        let position = tuple.get(2).ok_or_else(badarg)?;
        let limit = tuple.get(3).ok_or_else(badarg)?;
        let pattern = tuple.get(4).ok_or_else(badarg)?;
        if tag != continuation_tag(expected_kind, context)? {
            return Err(badarg());
        }
        Ok(Self {
            tab: table_id,
            position: position
                .as_small_int()
                .and_then(|value| usize::try_from(value).ok())
                .ok_or_else(badarg)?,
            limit: parse_positive_limit(limit)?,
            pattern,
        })
    }
}

fn collect_match_results(
    table: &Arc<dyn EtsTable>,
    pattern: Term,
    mode: MatchResultMode,
    context: &mut ProcessContext,
) -> Result<Vec<Term>, Term> {
    // Accumulated results live on the process heap; each iteration's
    // allocation may collect, so every result is held in the rooted scope
    // and re-read at the end. Table objects themselves are ETS-owned and
    // stable across process collections.
    context.with_rooted(&[pattern], |context, roots| {
        for object in table.tab2list() {
            let pattern = context.rooted(roots, 0)?;
            let Some(bindings) = ets_pattern_match(pattern, object, context)? else {
                continue;
            };
            let result = match mode {
                MatchResultMode::Bindings => alloc_bindings_list(&bindings, context)?,
                MatchResultMode::Object => object,
            };
            context.rooted_push(roots, result)?;
        }
        (1..context.rooted_len(roots))
            .map(|index| context.rooted(roots, index))
            .collect()
    })
}

fn collect_match_page(
    table: &Arc<dyn EtsTable>,
    pattern: Term,
    start_position: usize,
    limit: usize,
    context: &mut ProcessContext,
) -> Result<Term, Term> {
    let page = collect_match_paged_results(table, pattern, start_position, limit, context)?;
    finish_paged_results(
        page,
        MatchContinuationKind::Match,
        table.metadata().id,
        pattern,
        limit,
        context,
    )
}

fn collect_match_paged_results(
    table: &Arc<dyn EtsTable>,
    pattern: Term,
    start_position: usize,
    limit: usize,
    context: &mut ProcessContext,
) -> Result<PagedResults, Term> {
    // See collect_match_results: results are rooted across per-item
    // allocations and re-read once accumulation finishes.
    context.with_rooted(&[pattern], |context, roots| {
        let snapshot = table.tab2list();
        let mut next_position = None;
        for (position, object) in snapshot.into_iter().enumerate().skip(start_position) {
            let pattern = context.rooted(roots, 0)?;
            let Some(bindings) = ets_pattern_match(pattern, object, context)? else {
                continue;
            };
            if context.rooted_len(roots) - 1 == limit {
                next_position = Some(position);
                break;
            }
            let result = alloc_bindings_list(&bindings, context)?;
            context.rooted_push(roots, result)?;
        }
        let results = (1..context.rooted_len(roots))
            .map(|index| context.rooted(roots, index))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(PagedResults {
            results,
            next_position,
        })
    })
}

fn collect_select_results(
    table: &Arc<dyn EtsTable>,
    spec: Term,
    start_position: usize,
    limit: Option<usize>,
    context: &mut ProcessContext,
) -> Result<PagedResults, Term> {
    let atom_table = context.atom_table_arc().ok_or_else(badarg)?;
    let compiled = CompiledMatchSpec::compile(spec, atom_table.as_ref()).map_err(|_| badarg())?;
    let snapshot = table.tab2list();
    let mut arena = MatchArena::new();
    // Copied results live on the process heap; root each one so later
    // per-item copies can collect safely.
    context.with_rooted(&[], |context, roots| {
        let mut next_position = None;
        for (position, object) in snapshot.into_iter().enumerate().skip(start_position) {
            if limit.is_some_and(|limit| context.rooted_len(roots) == limit) {
                next_position = Some(position);
                break;
            }
            if let Some(arena_result) = compiled
                .run(object, atom_table.as_ref(), &mut arena)
                .map_err(|_| badarg())?
            {
                let result = copy_term_to_process(arena_result, context)?;
                context.rooted_push(roots, result)?;
            }
        }
        let results = (0..context.rooted_len(roots))
            .map(|index| context.rooted(roots, index))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(PagedResults {
            results,
            next_position,
        })
    })
}

fn collect_select_page(
    table: &Arc<dyn EtsTable>,
    spec: Term,
    start_position: usize,
    limit: usize,
    context: &mut ProcessContext,
) -> Result<Term, Term> {
    let page = collect_select_results(table, spec, start_position, Some(limit), context)?;
    finish_paged_results(
        page,
        MatchContinuationKind::Select,
        table.metadata().id,
        spec,
        limit,
        context,
    )
}

fn finish_paged_results(
    page: PagedResults,
    kind: MatchContinuationKind,
    table_id: EtsTableId,
    pattern_or_spec: Term,
    limit: usize,
    context: &mut ProcessContext,
) -> Result<Term, Term> {
    if page.results.is_empty() && page.next_position.is_none() {
        return end_of_table_atom(context);
    }
    // The continuation allocation may collect after the results list is
    // built; keep both it and the pattern rooted across the sequence.
    context.with_rooted(&[pattern_or_spec], |context, roots| {
        let results = context.alloc_list(&page.results)?;
        context.rooted_push(roots, results)?;
        let pattern_or_spec = context.rooted(roots, 0)?;
        let continuation = match page.next_position {
            Some(next_position) => alloc_match_continuation(
                kind,
                table_id,
                next_position,
                limit,
                pattern_or_spec,
                context,
            )?,
            None => end_of_table_atom(context)?,
        };
        let results = context.rooted(roots, 1)?;
        context.alloc_tuple(&[results, continuation])
    })
}

fn alloc_match_continuation(
    kind: MatchContinuationKind,
    table_id: EtsTableId,
    position: usize,
    limit: usize,
    pattern_or_spec: Term,
    context: &mut ProcessContext,
) -> Result<Term, Term> {
    let tag = continuation_tag(kind, context)?;
    context.alloc_tuple(&[
        tag,
        small_int_from_u64(table_id)?,
        small_int_from_usize(position)?,
        small_int_from_usize(limit)?,
        pattern_or_spec,
    ])
}

fn continuation_tag(kind: MatchContinuationKind, context: &ProcessContext) -> Result<Term, Term> {
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let name = match kind {
        MatchContinuationKind::Match => "$ets_match_continuation",
        MatchContinuationKind::Select => "$ets_select_continuation",
    };
    Ok(Term::atom(atom_table.intern(name)))
}

fn alloc_bindings_list(
    bindings: &BTreeMap<usize, Term>,
    context: &mut ProcessContext,
) -> Result<Term, Term> {
    let values = bindings.values().copied().collect::<Vec<_>>();
    context.alloc_list(&values)
}

fn parse_positive_limit(limit: Term) -> Result<usize, Term> {
    limit
        .as_small_int()
        .and_then(|value| usize::try_from(value).ok())
        .filter(|value| *value > 0)
        .ok_or_else(badarg)
}

#[derive(Copy, Clone)]
enum MissingTable {
    Badarg,
}

fn resolve_existing_table(
    tab: Term,
    context: &ProcessContext,
    missing: MissingTable,
) -> Result<Arc<dyn EtsTable>, Term> {
    match resolve_table(tab, context)? {
        Some(table) => Ok(table),
        None => match missing {
            MissingTable::Badarg => Err(badarg()),
        },
    }
}

fn resolve_table(tab: Term, context: &ProcessContext) -> Result<Option<Arc<dyn EtsTable>>, Term> {
    let facility = context.ets_facility().ok_or_else(badarg)?;
    if let Some(table_id) = tab.as_small_int().and_then(ets_table_id_from_i64) {
        return Ok(facility.lookup_table(table_id));
    }
    if let Some(name) = tab.as_atom() {
        return Ok(facility.lookup_named_table(name));
    }
    Err(badarg())
}

fn resolve_readable_table(tab: Term, context: &ProcessContext) -> Result<Arc<dyn EtsTable>, Term> {
    let table = resolve_existing_table(tab, context, MissingTable::Badarg)?;
    let caller = context.pid().ok_or_else(badarg)?;
    table
        .check_access(caller, AccessOp::Read)
        .map_err(|_| badarg())?;
    Ok(table)
}

fn ets_pattern_match(
    pattern: Term,
    object: Term,
    context: &ProcessContext,
) -> Result<Option<BTreeMap<usize, Term>>, Term> {
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let mut bindings = BTreeMap::new();
    if match_pattern_term(pattern, object, atom_table, &mut bindings)? {
        Ok(Some(bindings))
    } else {
        Ok(None)
    }
}

fn match_pattern_term(
    pattern: Term,
    value: Term,
    atom_table: &AtomTable,
    bindings: &mut BTreeMap<usize, Term>,
) -> Result<bool, Term> {
    if ets_is_dont_care(pattern, atom_table) {
        return Ok(true);
    }
    if let Some(index) = ets_match_variable_index(pattern, atom_table) {
        return Ok(match bindings.get(&index).copied() {
            Some(bound) => compare::exact_eq(bound, value),
            None => {
                bindings.insert(index, value);
                true
            }
        });
    }
    if let Some(pattern_tuple) = Tuple::new(pattern) {
        let Some(value_tuple) = Tuple::new(value) else {
            return Ok(false);
        };
        if pattern_tuple.arity() != value_tuple.arity() {
            return Ok(false);
        }
        for index in 0..pattern_tuple.arity() {
            let pattern_element = pattern_tuple.get(index).ok_or_else(badarg)?;
            let value_element = value_tuple.get(index).ok_or_else(badarg)?;
            if !match_pattern_term(pattern_element, value_element, atom_table, bindings)? {
                return Ok(false);
            }
        }
        return Ok(true);
    }
    if pattern.is_list() || pattern.is_nil() {
        return match_list_pattern(pattern, value, atom_table, bindings);
    }
    Ok(compare::exact_eq(pattern, value))
}

fn match_list_pattern(
    pattern: Term,
    value: Term,
    atom_table: &AtomTable,
    bindings: &mut BTreeMap<usize, Term>,
) -> Result<bool, Term> {
    let mut pattern_tail = pattern;
    let mut value_tail = value;
    while !pattern_tail.is_nil() {
        let pattern_cons = Cons::new(pattern_tail).ok_or_else(badarg)?;
        let Some(value_cons) = Cons::new(value_tail) else {
            return Ok(false);
        };
        if !match_pattern_term(pattern_cons.head(), value_cons.head(), atom_table, bindings)? {
            return Ok(false);
        }
        pattern_tail = pattern_cons.tail();
        value_tail = value_cons.tail();
    }
    Ok(value_tail.is_nil())
}

fn ets_is_dont_care(term: Term, atom_table: &AtomTable) -> bool {
    term.as_atom()
        .and_then(|atom| atom_table.resolve(atom))
        .is_some_and(|name| name == "_")
}

fn ets_match_variable_index(term: Term, atom_table: &AtomTable) -> Option<usize> {
    let name = term.as_atom().and_then(|atom| atom_table.resolve(atom))?;
    let digits = name.strip_prefix('$')?;
    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    let index = digits.parse::<usize>().ok()?;
    (index > 0).then_some(index)
}

#[derive(Copy, Clone)]
enum CursorDirection {
    Next,
    Prev,
}

fn table_snapshot_keys(
    table: &Arc<dyn EtsTable>,
    context: &ProcessContext,
) -> Result<Vec<Term>, Term> {
    let mut keys = table
        .tab2list()
        .into_iter()
        .map(|tuple| {
            crate::ets::tuple_key(tuple, table.metadata().keypos).map_err(ets_error_to_badarg)
        })
        .collect::<Result<Vec<_>, _>>()?;

    if table.metadata().table_type == EtsTableType::OrderedSet {
        return Ok(keys);
    }

    let atom_table = context.atom_table_arc().ok_or_else(badarg)?;
    keys.sort_by(|left, right| {
        TermKey::with_atom_table(*left, Arc::clone(&atom_table))
            .cmp(&TermKey::with_atom_table(*right, Arc::clone(&atom_table)))
    });
    keys.dedup_by(|left, right| {
        TermKey::with_atom_table(*left, Arc::clone(&atom_table))
            == TermKey::with_atom_table(*right, Arc::clone(&atom_table))
    });
    Ok(keys)
}

fn cursor_neighbor(
    table: &Arc<dyn EtsTable>,
    keys: Vec<Term>,
    key: Term,
    direction: CursorDirection,
    context: &ProcessContext,
) -> Result<Term, Term> {
    if keys.is_empty() {
        return end_of_table_atom(context);
    }

    let atom_table = context.atom_table_arc().ok_or_else(badarg)?;
    if table.metadata().table_type == EtsTableType::OrderedSet {
        let cursor = TermKey::with_atom_table(key, Arc::clone(&atom_table));
        let position = keys.binary_search_by(|probe| {
            TermKey::with_atom_table(*probe, Arc::clone(&atom_table)).cmp(&cursor)
        });
        let neighbor = match (direction, position) {
            (CursorDirection::Next, Ok(index)) => keys.get(index + 1).copied(),
            (CursorDirection::Next, Err(index)) => keys.get(index).copied(),
            (CursorDirection::Prev, Ok(0) | Err(0)) => None,
            (CursorDirection::Prev, Ok(index) | Err(index)) => keys.get(index - 1).copied(),
        };
        return Ok(neighbor.unwrap_or(end_of_table_atom(context)?));
    }

    let position = keys.iter().position(|candidate| *candidate == key);
    let neighbor = match (direction, position) {
        (CursorDirection::Next, Some(index)) => keys.get(index + 1).copied(),
        (CursorDirection::Prev, Some(index)) if index > 0 => keys.get(index - 1).copied(),
        _ => None,
    };
    Ok(neighbor.unwrap_or(end_of_table_atom(context)?))
}

fn end_of_table_atom(context: &ProcessContext) -> Result<Term, Term> {
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    Ok(Term::atom(atom_table.intern("$end_of_table")))
}

fn ets_table_id_from_i64(value: i64) -> Option<EtsTableId> {
    u64::try_from(value).ok().filter(|id| *id > 0)
}

fn info_value(
    table: &Arc<dyn EtsTable>,
    item: &str,
    context: &ProcessContext,
) -> Result<Term, Term> {
    let atom_table = context.atom_table().ok_or_else(badarg)?;
    let metadata = table.metadata();
    match item {
        "name" => Ok(metadata
            .name
            .map(Term::atom)
            .unwrap_or_else(|| Term::atom(Atom::UNDEFINED))),
        "type" => Ok(Term::atom(table_type_atom(metadata.table_type, atom_table))),
        "size" => small_int_from_usize(table.tab2list().len()),
        "keypos" => small_int_from_usize(metadata.keypos),
        "protection" => Ok(Term::atom(protection_atom(metadata.protection, atom_table))),
        "owner" => Term::try_pid(metadata.owner.get()).ok_or_else(badarg),
        "memory" => small_int_from_usize(approximate_memory_words(table)),
        _ => Err(badarg()),
    }
}

fn table_type_atom(table_type: EtsTableType, atom_table: &AtomTable) -> Atom {
    match table_type {
        EtsTableType::Set => atom_table.intern("set"),
        EtsTableType::OrderedSet => atom_table.intern("ordered_set"),
        EtsTableType::Bag => atom_table.intern("bag"),
        EtsTableType::DuplicateBag => atom_table.intern("duplicate_bag"),
    }
}

fn protection_atom(protection: Protection, atom_table: &AtomTable) -> Atom {
    match protection {
        Protection::Public => atom_table.intern("public"),
        Protection::Protected => atom_table.intern("protected"),
        Protection::Private => atom_table.intern("private"),
    }
}

fn approximate_memory_words(table: &Arc<dyn EtsTable>) -> usize {
    const METADATA_WORDS: usize = 8;
    let entries = table.tab2list();
    METADATA_WORDS + entries.len() * 3
}

fn small_int_from_u64(value: u64) -> Result<Term, Term> {
    let value = i64::try_from(value).map_err(|_| badarg())?;
    Term::try_small_int(value).ok_or_else(badarg)
}

fn small_int_from_usize(value: usize) -> Result<Term, Term> {
    let value = i64::try_from(value).map_err(|_| badarg())?;
    Term::try_small_int(value).ok_or_else(badarg)
}

fn bool_term(value: bool) -> Term {
    Term::atom(if value { Atom::TRUE } else { Atom::FALSE })
}

const fn list_heap_words(element_count: usize) -> usize {
    element_count * 2
}

const fn info_proplist_heap_words(item_count: usize) -> usize {
    item_count * 5
}

fn copy_term_to_process(term: Term, context: &mut ProcessContext<'_>) -> Result<Term, Term> {
    let Some(process) = context.process_mut() else {
        return Err(badarg());
    };
    copy_term_to_heap(term, process.heap_mut()).map_err(ets_error_to_badarg)
}

fn ets_error_to_badarg(_error: EtsError) -> Term {
    badarg()
}

fn badarg() -> Term {
    Term::atom(Atom::BADARG)
}

fn ensure_fun_arity(fun: Term, arity: u8) -> Result<(), Term> {
    let closure = Closure::new(fun).ok_or_else(badarg)?;
    if closure.arity() == arity {
        Ok(())
    } else {
        Err(Term::atom(Atom::BADARITY))
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::{
        bif_delete_1, bif_delete_2, bif_first, bif_foldl, bif_give_away, bif_info_2, bif_insert,
        bif_last, bif_lookup, bif_match_1, bif_match_2, bif_match_3, bif_match_delete,
        bif_match_object, bif_member, bif_new, bif_next, bif_prev, bif_select_1, bif_select_2,
        bif_select_3, bif_tab2list, register_ets_bifs, resume_ets_foldl,
    };
    use crate::atom::{Atom, AtomTable};
    use crate::ets::EtsRegistry;
    use crate::native::stdlib_stubs::maps_bifs::ContinuationStep;
    use crate::native::{BifRegistryImpl, NativeContinuation, ProcessContext};
    use crate::process::Process;
    use crate::term::Term;
    use crate::term::boxed::{Cons, Tuple, write_closure};

    fn context<'a>(
        process: &'a mut Process,
        atom_table: Arc<AtomTable>,
        registry: Arc<EtsRegistry>,
    ) -> ProcessContext<'a> {
        let ets_facility: Arc<dyn crate::native::EtsFacility> = registry;
        let mut context = ProcessContext::new();
        context.set_atom_table(Some(atom_table));
        context.set_ets_facility(Some(ets_facility));
        context.attach_process(process, 0);
        context
    }

    fn atom_list(context: &mut ProcessContext, atoms: &[Atom]) -> Term {
        let terms = atoms.iter().copied().map(Term::atom).collect::<Vec<_>>();
        context.alloc_list(&terms).expect("list allocation")
    }

    fn tuple(context: &mut ProcessContext, elements: &[Term]) -> Term {
        context.alloc_tuple(elements).expect("tuple allocation")
    }

    fn tuple_option(context: &mut ProcessContext, name: Atom, value: Term) -> Term {
        tuple(context, &[Term::atom(name), value])
    }

    fn tuple3(context: &mut ProcessContext, elements: &[Term; 3]) -> Term {
        tuple(context, elements)
    }

    fn list_terms(list: Term) -> Vec<Term> {
        let mut values = Vec::new();
        let mut tail = list;
        while !tail.is_nil() {
            let cons = Cons::new(tail).expect("proper list cons");
            values.push(cons.head());
            tail = cons.tail();
        }
        values
    }

    fn tuple_values(term: Term) -> Vec<Term> {
        let tuple = Tuple::new(term).expect("tuple");
        (0..tuple.arity())
            .map(|index| tuple.get(index).expect("tuple element"))
            .collect()
    }

    fn page_tuple(term: Term) -> (Term, Term) {
        let values = tuple_values(term);
        assert_eq!(values.len(), 2);
        (values[0], values[1])
    }

    fn new_table(
        context: &mut ProcessContext,
        _atom_table: &AtomTable,
        name: Atom,
        options: &[Atom],
    ) -> Term {
        let options = atom_list(context, options);
        bif_new(&[Term::atom(name), options], context).expect("ets:new succeeds")
    }

    fn created_table(registry: &EtsRegistry, tab: Term) -> Arc<dyn crate::ets::EtsTable> {
        let table_id = tab
            .as_small_int()
            .and_then(|value| u64::try_from(value).ok())
            .expect("unnamed table returns positive numeric id");
        registry.lookup_table(table_id).expect("table exists")
    }

    #[test]
    fn ets_new_named_public_set_returns_name_and_rejects_duplicate() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let my_table = atom_table.intern("my_table");
        let set = atom_table.intern("set");
        let public = atom_table.intern("public");
        let named_table = atom_table.intern("named_table");
        let mut process = Process::new(1, 128);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);

        let result = new_table(
            &mut context,
            &atom_table,
            my_table,
            &[set, public, named_table],
        );

        assert_eq!(result, Term::atom(my_table));
        let duplicate_options = atom_list(&mut context, &[set, public, named_table]);
        assert_eq!(
            bif_new(&[Term::atom(my_table), duplicate_options], &mut context),
            Err(Term::atom(Atom::BADARG))
        );
    }

    #[test]
    fn give_away_transfers_owner_in_registry_facility_and_enforces_owner_only() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let private = atom_table.intern("private");
        let set = atom_table.intern("set");
        let mut owner_process = Process::new(1, 512);
        let mut owner_context = context(
            &mut owner_process,
            Arc::clone(&atom_table),
            Arc::clone(&registry),
        );
        let tab = new_table(
            &mut owner_context,
            &atom_table,
            atom_table.intern("give_away_tab"),
            &[set, private],
        );

        assert_eq!(
            bif_give_away(
                &[tab, Term::pid(2), Term::atom(Atom::OK)],
                &mut owner_context
            ),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(created_table(&registry, tab).metadata().owner.get(), 2);
        let row = tuple(
            &mut owner_context,
            &[Term::atom(Atom::OK), Term::small_int(1)],
        );
        assert_eq!(
            bif_insert(&[tab, row], &mut owner_context),
            Err(Term::atom(Atom::BADARG))
        );

        let mut non_owner_process = Process::new(3, 256);
        let mut non_owner_context =
            context(&mut non_owner_process, Arc::clone(&atom_table), registry);
        assert_eq!(
            bif_give_away(&[tab, Term::pid(4), Term::NIL], &mut non_owner_context),
            Err(Term::atom(Atom::BADARG))
        );
    }

    #[test]
    fn ets_new_unnamed_table_returns_numeric_id() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("unnamed_source_name");
        let mut process = Process::new(1, 128);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let options = context.alloc_list(&[]).expect("empty option list");

        let result = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");

        assert_eq!(result.as_small_int(), Some(1));
    }

    #[test]
    fn ets_new_defaults_concurrency_options_to_false() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("default_concurrency_tab");
        let mut process = Process::new(1, 128);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let options = context.alloc_list(&[]).expect("empty option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);

        assert!(!table.metadata().read_concurrency);
        assert!(!table.metadata().write_concurrency);
    }

    #[test]
    fn ets_new_parses_heir_pid_data_and_explicit_none() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("heir_tab");
        let none_table_name = atom_table.intern("heir_none_tab");
        let heir = atom_table.intern("heir");
        let none = atom_table.intern("none");
        let payload = atom_table.intern("payload");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let data = tuple(&mut context, &[Term::atom(payload), Term::small_int(42)]);
        let heir_option = tuple3(&mut context, &[Term::atom(heir), Term::pid(99), data]);
        let options = context.alloc_list(&[heir_option]).expect("option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);
        let metadata_heir = table.metadata().heir.as_ref().expect("heir stored");
        assert_eq!(metadata_heir.pid, 99);
        assert_ne!(metadata_heir.data.root().raw(), data.raw());

        let none_option = tuple_option(&mut context, heir, Term::atom(none));
        let none_options = context.alloc_list(&[none_option]).expect("option list");
        let none_tab =
            bif_new(&[Term::atom(none_table_name), none_options], &mut context).expect("new table");
        assert!(created_table(&registry, none_tab).metadata().heir.is_none());
    }

    #[test]
    fn ets_new_parses_read_concurrency_option() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("read_concurrency_tab");
        let read_concurrency = atom_table.intern("read_concurrency");
        let mut process = Process::new(1, 128);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let option = tuple_option(&mut context, read_concurrency, Term::atom(Atom::TRUE));
        let options = context.alloc_list(&[option]).expect("option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);

        assert!(table.metadata().read_concurrency);
        assert!(!table.metadata().write_concurrency);
    }

    #[test]
    fn ets_new_parses_write_concurrency_option() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("write_concurrency_tab");
        let write_concurrency = atom_table.intern("write_concurrency");
        let mut process = Process::new(1, 128);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let option = tuple_option(&mut context, write_concurrency, Term::atom(Atom::TRUE));
        let options = context.alloc_list(&[option]).expect("option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);

        assert!(!table.metadata().read_concurrency);
        assert!(table.metadata().write_concurrency);
    }

    #[test]
    fn ets_new_parses_read_and_write_concurrency_together() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("both_concurrency_tab");
        let ordered_set = atom_table.intern("ordered_set");
        let read_concurrency = atom_table.intern("read_concurrency");
        let write_concurrency = atom_table.intern("write_concurrency");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let read_option = tuple_option(&mut context, read_concurrency, Term::atom(Atom::TRUE));
        let write_option = tuple_option(&mut context, write_concurrency, Term::atom(Atom::TRUE));
        let options = context
            .alloc_list(&[Term::atom(ordered_set), read_option, write_option])
            .expect("option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);

        assert_eq!(
            table.metadata().table_type,
            crate::ets::EtsTableType::OrderedSet
        );
        assert!(table.metadata().read_concurrency);
        assert!(table.metadata().write_concurrency);
    }

    #[test]
    fn ets_new_accepts_explicit_false_concurrency_options() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let table_name = atom_table.intern("false_concurrency_tab");
        let read_concurrency = atom_table.intern("read_concurrency");
        let write_concurrency = atom_table.intern("write_concurrency");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), Arc::clone(&registry));
        let read_option = tuple_option(&mut context, read_concurrency, Term::atom(Atom::FALSE));
        let write_option = tuple_option(&mut context, write_concurrency, Term::atom(Atom::FALSE));
        let options = context
            .alloc_list(&[read_option, write_option])
            .expect("option list");

        let tab = bif_new(&[Term::atom(table_name), options], &mut context).expect("new table");
        let table = created_table(&registry, tab);

        assert!(!table.metadata().read_concurrency);
        assert!(!table.metadata().write_concurrency);
    }

    #[test]
    fn ets_new_rejects_non_boolean_concurrency_options() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let write_table_name = atom_table.intern("auto_write_concurrency_tab");
        let read_table_name = atom_table.intern("auto_read_concurrency_tab");
        let write_concurrency = atom_table.intern("write_concurrency");
        let read_concurrency = atom_table.intern("read_concurrency");
        let auto = atom_table.intern("auto");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let write_option = tuple_option(&mut context, write_concurrency, Term::atom(auto));
        let write_options = context.alloc_list(&[write_option]).expect("option list");

        assert_eq!(
            bif_new(&[Term::atom(write_table_name), write_options], &mut context),
            Err(Term::atom(Atom::BADARG))
        );

        let read_option = tuple_option(&mut context, read_concurrency, Term::small_int(1));
        let read_options = context.alloc_list(&[read_option]).expect("option list");
        assert_eq!(
            bif_new(&[Term::atom(read_table_name), read_options], &mut context),
            Err(Term::atom(Atom::BADARG))
        );
    }

    #[test]
    fn insert_and_lookup_round_trip_for_set_bag_and_ordered_set() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let bag = atom_table.intern("bag");
        let ordered_set = atom_table.intern("ordered_set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);

        for (index, table_type) in [set, bag, ordered_set].into_iter().enumerate() {
            let table_name = atom_table.intern(&format!("table_{index}"));
            let tab = new_table(&mut context, &atom_table, table_name, &[table_type, public]);
            let tuple = tuple(
                &mut context,
                &[Term::atom(Atom::OK), Term::small_int(index as i64)],
            );

            assert_eq!(
                bif_insert(&[tab, tuple], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
            let result = bif_lookup(&[tab, Term::atom(Atom::OK)], &mut context).expect("lookup");
            assert_eq!(list_terms(result), vec![tuple]);
        }
    }

    #[test]
    fn insert_accepts_proper_list_of_tuples() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let bag = atom_table.intern("bag");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("bag_tab"),
            &[bag, public],
        );
        let first = tuple(&mut context, &[Term::atom(Atom::OK), Term::small_int(1)]);
        let second = tuple(&mut context, &[Term::atom(Atom::OK), Term::small_int(2)]);
        let objects = context.alloc_list(&[first, second]).expect("tuple list");

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        let result = bif_lookup(&[tab, Term::atom(Atom::OK)], &mut context).expect("lookup");
        let mut values = list_terms(result);
        values.sort();
        let mut expected = vec![first, second];
        expected.sort();
        assert_eq!(values, expected);
    }

    #[test]
    fn tab2list_returns_all_inserted_tuples() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("tab2list_tab"),
            &[set, public],
        );
        let first = tuple(&mut context, &[Term::small_int(1), Term::small_int(10)]);
        let second = tuple(&mut context, &[Term::small_int(2), Term::small_int(20)]);
        let third = tuple(&mut context, &[Term::small_int(3), Term::small_int(30)]);
        let objects = context
            .alloc_list(&[first, second, third])
            .expect("tuple list");

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        let result = bif_tab2list(&[tab], &mut context).expect("tab2list");
        let mut values = list_terms(result);
        values.sort();
        let mut expected = vec![first, second, third];
        expected.sort();
        assert_eq!(values, expected);
    }

    #[test]
    fn tab2list_empty_table_returns_nil_and_ordered_set_is_key_sorted() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("tab2list_ordered_tab"),
            &[ordered_set, public],
        );

        assert_eq!(bif_tab2list(&[tab], &mut context), Ok(Term::NIL));

        for (key, value) in [(3, 30), (1, 10), (2, 20)] {
            let row = tuple(
                &mut context,
                &[Term::small_int(key), Term::small_int(value)],
            );
            assert_eq!(
                bif_insert(&[tab, row], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
        }

        let result = bif_tab2list(&[tab], &mut context).expect("tab2list");
        let keys = list_terms(result)
            .into_iter()
            .map(|row| {
                Tuple::new(row)
                    .and_then(|tuple| tuple.get(0))
                    .expect("tuple key")
            })
            .collect::<Vec<_>>();
        assert_eq!(
            keys,
            vec![Term::small_int(1), Term::small_int(2), Term::small_int(3)]
        );
    }

    #[test]
    fn foldl_queues_continuation_over_table_entries() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("foldl_tab"),
            &[set, public],
        );
        let first = tuple(&mut context, &[Term::small_int(1), Term::small_int(10)]);
        let second = tuple(&mut context, &[Term::small_int(2), Term::small_int(20)]);
        let objects = context.alloc_list(&[first, second]).expect("tuple list");
        let mut closure_heap = [0_u64; 7];
        let fun = write_closure(&mut closure_heap, Atom::OK, 0, 2, 1, 0, &[]).expect("closure");

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_foldl(&[fun, Term::small_int(0), tab], &mut context),
            Ok(Term::NIL)
        );
        let trampoline = context.take_trampoline().expect("foldl trampoline");
        assert_eq!(trampoline.fun, fun);
        assert_eq!(trampoline.args.len(), 2);
        assert_eq!(trampoline.args[1], Term::small_int(0));
        assert!(matches!(
            trampoline.continuation,
            Some(NativeContinuation::EtsFoldl(_))
        ));
    }

    #[test]
    fn foldl_empty_table_returns_accumulator_and_rejects_wrong_fun_arity() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("foldl_empty_tab"),
            &[set, public],
        );
        let mut unary_closure_heap = [0_u64; 7];
        let unary_fun =
            write_closure(&mut unary_closure_heap, Atom::OK, 0, 1, 1, 0, &[]).expect("closure");
        let mut binary_closure_heap = [0_u64; 7];
        let binary_fun =
            write_closure(&mut binary_closure_heap, Atom::OK, 0, 2, 1, 0, &[]).expect("closure");

        assert_eq!(
            bif_foldl(&[binary_fun, Term::small_int(42), tab], &mut context),
            Ok(Term::small_int(42))
        );
        assert!(context.take_trampoline().is_none());
        assert_eq!(
            bif_foldl(&[unary_fun, Term::small_int(0), tab], &mut context),
            Err(Term::atom(Atom::BADARITY))
        );
    }

    #[test]
    fn foldl_resume_passes_element_and_accumulator_until_done() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("foldl_resume_tab"),
            &[ordered_set, public],
        );
        let first = tuple(&mut context, &[Term::small_int(1), Term::small_int(10)]);
        let second = tuple(&mut context, &[Term::small_int(2), Term::small_int(20)]);
        let objects = context.alloc_list(&[second, first]).expect("tuple list");
        let mut closure_heap = [0_u64; 7];
        let fun = write_closure(&mut closure_heap, Atom::OK, 0, 2, 1, 0, &[]).expect("closure");

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_foldl(&[fun, Term::small_int(0), tab], &mut context),
            Ok(Term::NIL)
        );
        let trampoline = context.take_trampoline().expect("foldl trampoline");
        assert_eq!(trampoline.args, vec![first, Term::small_int(0)]);
        let Some(NativeContinuation::EtsFoldl(state)) = trampoline.continuation else {
            panic!("expected foldl continuation");
        };

        let step = resume_ets_foldl(state, Term::small_int(10)).expect("resume step");
        let ContinuationStep::Call {
            fun: step_fun,
            args,
            continuation,
        } = step
        else {
            panic!("expected second foldl call");
        };
        assert_eq!(step_fun, fun);
        assert_eq!(args, vec![second, Term::small_int(10)]);

        let NativeContinuation::EtsFoldl(state) = continuation else {
            panic!("expected foldl continuation");
        };
        let final_step = resume_ets_foldl(state, Term::small_int(30)).expect("final resume");
        let ContinuationStep::Done(result) = final_step else {
            panic!("expected foldl completion");
        };
        assert_eq!(result, Term::small_int(30));
    }

    #[test]
    fn ordered_set_cursor_traversal_visits_keys_in_order() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let end_of_table = atom_table.intern("$end_of_table");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("ordered_cursor_tab"),
            &[ordered_set, public],
        );
        for key in [Term::small_int(2), Term::small_int(1), Term::small_int(3)] {
            let row = tuple(&mut context, &[key, key]);
            assert_eq!(
                bif_insert(&[tab, row], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
        }

        assert_eq!(bif_first(&[tab], &mut context), Ok(Term::small_int(1)));
        assert_eq!(
            bif_next(&[tab, Term::small_int(1)], &mut context),
            Ok(Term::small_int(2))
        );
        assert_eq!(
            bif_next(&[tab, Term::small_int(2)], &mut context),
            Ok(Term::small_int(3))
        );
        assert_eq!(
            bif_next(&[tab, Term::small_int(3)], &mut context),
            Ok(Term::atom(end_of_table))
        );
        assert_eq!(bif_last(&[tab], &mut context), Ok(Term::small_int(3)));
        assert_eq!(
            bif_prev(&[tab, Term::small_int(3)], &mut context),
            Ok(Term::small_int(2))
        );
        assert_eq!(
            bif_next(&[tab, Term::small_int(0)], &mut context),
            Ok(Term::small_int(1))
        );
        assert_eq!(
            bif_next(&[tab, Term::small_int(4)], &mut context),
            Ok(Term::atom(end_of_table))
        );
        assert_eq!(
            bif_prev(&[tab, Term::small_int(4)], &mut context),
            Ok(Term::small_int(3))
        );
        assert_eq!(
            bif_prev(&[tab, Term::small_int(1)], &mut context),
            Ok(Term::atom(end_of_table))
        );
    }

    #[test]
    fn set_cursor_traversal_visits_all_keys_once_and_empty_tables_end() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let end_of_table = atom_table.intern("$end_of_table");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("set_cursor_tab"),
            &[set, public],
        );

        assert_eq!(
            bif_first(&[tab], &mut context),
            Ok(Term::atom(end_of_table))
        );
        assert_eq!(bif_last(&[tab], &mut context), Ok(Term::atom(end_of_table)));

        for key in [Term::small_int(2), Term::small_int(1), Term::small_int(3)] {
            let row = tuple(&mut context, &[key, key]);
            assert_eq!(
                bif_insert(&[tab, row], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
        }

        let mut visited = Vec::new();
        let mut cursor = bif_first(&[tab], &mut context).expect("first key");
        while cursor != Term::atom(end_of_table) {
            visited.push(cursor);
            cursor = bif_next(&[tab, cursor], &mut context).expect("next key");
        }
        visited.sort();
        assert_eq!(
            visited,
            vec![Term::small_int(1), Term::small_int(2), Term::small_int(3)]
        );
    }

    #[test]
    fn match_returns_bound_variable_lists_and_match_object_returns_tuples() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let wildcard = atom_table.intern("_");
        let variable = atom_table.intern("$1");
        let a = atom_table.intern("a");
        let b = atom_table.intern("b");
        let c = atom_table.intern("c");
        let mut process = Process::new(1, 1024);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("match_tab"),
            &[ordered_set, public],
        );
        let first = tuple(&mut context, &[Term::atom(a), Term::small_int(1)]);
        let second = tuple(&mut context, &[Term::atom(b), Term::small_int(2)]);
        let third = tuple(&mut context, &[Term::atom(c), Term::small_int(3)]);
        let objects = context
            .alloc_list(&[first, second, third])
            .expect("objects");
        let pattern = tuple(&mut context, &[Term::atom(wildcard), Term::atom(variable)]);

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        let result = bif_match_2(&[tab, pattern], &mut context).expect("match/2");
        let bound_lists = list_terms(result)
            .into_iter()
            .map(list_terms)
            .collect::<Vec<_>>();
        assert_eq!(
            bound_lists,
            vec![
                vec![Term::small_int(1)],
                vec![Term::small_int(2)],
                vec![Term::small_int(3)],
            ]
        );

        let matched_objects =
            bif_match_object(&[tab, pattern], &mut context).expect("match_object/2");
        assert_eq!(list_terms(matched_objects), vec![first, second, third]);
    }

    #[test]
    fn select_runs_match_spec_with_guard() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let gt = atom_table.intern(">");
        let first_var = atom_table.intern("$1");
        let second_var = atom_table.intern("$2");
        let a = atom_table.intern("a");
        let b = atom_table.intern("b");
        let c = atom_table.intern("c");
        let mut process = Process::new(1, 2048);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("select_tab"),
            &[ordered_set, public],
        );
        for (key, value) in [(1, a), (2, b), (3, c)] {
            let row = tuple(&mut context, &[Term::small_int(key), Term::atom(value)]);
            assert_eq!(
                bif_insert(&[tab, row], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
        }
        let head = tuple(
            &mut context,
            &[Term::atom(first_var), Term::atom(second_var)],
        );
        let guard = tuple(
            &mut context,
            &[Term::atom(gt), Term::atom(first_var), Term::small_int(1)],
        );
        let guards = context.alloc_list(&[guard]).expect("guards");
        let body = context.alloc_list(&[Term::atom(second_var)]).expect("body");
        let clause = tuple(&mut context, &[head, guards, body]);
        let spec = context.alloc_list(&[clause]).expect("spec");

        let result = bif_select_2(&[tab, spec], &mut context).expect("select/2");
        assert_eq!(list_terms(result), vec![Term::atom(b), Term::atom(c)]);
    }

    #[test]
    fn select_copies_constructed_results_to_process_heap() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let first_var = atom_table.intern("$1");
        let second_var = atom_table.intern("$2");
        let mut process = Process::new(1, 2048);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("select_copy_tab"),
            &[ordered_set, public],
        );
        let row = tuple(&mut context, &[Term::small_int(1), Term::small_int(10)]);
        assert_eq!(
            bif_insert(&[tab, row], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );

        let head = tuple(
            &mut context,
            &[Term::atom(first_var), Term::atom(second_var)],
        );
        let guards = context.alloc_list(&[]).expect("empty guards");
        let body_tuple = tuple(
            &mut context,
            &[Term::atom(second_var), Term::atom(first_var)],
        );
        let body_constructor = tuple(&mut context, &[body_tuple]);
        let body = context.alloc_list(&[body_constructor]).expect("body");
        let clause = tuple(&mut context, &[head, guards, body]);
        let spec = context.alloc_list(&[clause]).expect("spec");

        let result_list = bif_select_2(&[tab, spec], &mut context).expect("select/2");
        let results = list_terms(result_list);
        assert_eq!(results.len(), 1);
        let result_tuple = Tuple::new(results[0]).expect("select result is tuple");
        assert_eq!(result_tuple.get(0), Some(Term::small_int(10)));
        assert_eq!(result_tuple.get(1), Some(Term::small_int(1)));
        let result_ptr = results[0].heap_ptr().expect("tuple has heap pointer");
        assert!(
            context
                .process_mut()
                .expect("process attached")
                .heap()
                .contains(result_ptr),
            "constructed select result must be copied into the process heap"
        );
    }

    #[test]
    fn match_and_select_pagination_consumes_all_rows() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let ordered_set = atom_table.intern("ordered_set");
        let wildcard = atom_table.intern("_");
        let first_var = atom_table.intern("$1");
        let second_var = atom_table.intern("$2");
        let end_of_table = atom_table.intern("$end_of_table");
        let mut process = Process::new(1, 20000);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("page_tab"),
            &[ordered_set, public],
        );
        for key in 1..=100 {
            let row = tuple(
                &mut context,
                &[Term::small_int(key), Term::small_int(key * 10)],
            );
            assert_eq!(
                bif_insert(&[tab, row], &mut context),
                Ok(Term::atom(Atom::TRUE))
            );
        }

        let match_pattern = tuple(
            &mut context,
            &[Term::atom(wildcard), Term::atom(second_var)],
        );
        let mut match_count = 0;
        let mut match_page =
            bif_match_3(&[tab, match_pattern, Term::small_int(10)], &mut context).expect("match/3");
        loop {
            let (results, continuation) = page_tuple(match_page);
            match_count += list_terms(results).len();
            if continuation == Term::atom(end_of_table) {
                break;
            }
            match_page = bif_match_1(&[continuation], &mut context).expect("match/1");
        }
        assert_eq!(match_count, 100);

        let head = tuple(
            &mut context,
            &[Term::atom(first_var), Term::atom(second_var)],
        );
        let guards = context.alloc_list(&[]).expect("empty guards");
        let body = context.alloc_list(&[Term::atom(second_var)]).expect("body");
        let clause = tuple(&mut context, &[head, guards, body]);
        let spec = context.alloc_list(&[clause]).expect("spec");
        let mut select_count = 0;
        let mut select_page =
            bif_select_3(&[tab, spec, Term::small_int(10)], &mut context).expect("select/3");
        loop {
            let (results, continuation) = page_tuple(select_page);
            select_count += list_terms(results).len();
            if continuation == Term::atom(end_of_table) {
                break;
            }
            select_page = bif_select_1(&[continuation], &mut context).expect("select/1");
        }
        assert_eq!(select_count, 100);
    }

    #[test]
    fn match_delete_removes_only_matching_bag_objects() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let duplicate_bag = atom_table.intern("duplicate_bag");
        let wildcard = atom_table.intern("_");
        let ok = atom_table.intern("ok");
        let mut process = Process::new(1, 1024);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("match_delete_tab"),
            &[duplicate_bag, public],
        );
        let first = tuple(&mut context, &[Term::atom(ok), Term::small_int(1)]);
        let second = tuple(&mut context, &[Term::atom(ok), Term::small_int(2)]);
        let duplicate = tuple(&mut context, &[Term::atom(ok), Term::small_int(1)]);
        let objects = context
            .alloc_list(&[first, second, duplicate])
            .expect("objects");
        let pattern = tuple(&mut context, &[Term::atom(wildcard), Term::small_int(1)]);

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_match_delete(&[tab, pattern], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        let remaining = bif_lookup(&[tab, Term::atom(ok)], &mut context).expect("lookup");
        assert_eq!(list_terms(remaining), vec![second]);
    }

    #[test]
    fn delete_key_and_member_round_trip() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let set = atom_table.intern("set");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("member_tab"),
            &[set, public],
        );
        let tuple = tuple(&mut context, &[Term::atom(Atom::OK), Term::small_int(1)]);

        assert_eq!(
            bif_insert(&[tab, tuple], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_member(&[tab, Term::atom(Atom::OK)], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_delete_2(&[tab, Term::atom(Atom::OK)], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_member(&[tab, Term::atom(Atom::OK)], &mut context),
            Ok(Term::atom(Atom::FALSE))
        );
    }

    #[test]
    fn delete_one_removes_named_table() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let named_table = atom_table.intern("named_table");
        let table_name = atom_table.intern("delete_named_tab");
        let mut process = Process::new(1, 256);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            table_name,
            &[public, named_table],
        );

        assert_eq!(
            bif_delete_1(&[tab], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_info_2(&[tab, Term::atom(atom_table.intern("size"))], &mut context),
            Ok(Term::atom(Atom::UNDEFINED))
        );
    }

    #[test]
    fn info_size_matches_inserted_entries() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let bag = atom_table.intern("bag");
        let size = atom_table.intern("size");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            atom_table.intern("info_tab"),
            &[bag, public],
        );
        let first = tuple(&mut context, &[Term::atom(Atom::OK), Term::small_int(1)]);
        let second = tuple(&mut context, &[Term::atom(Atom::ERROR), Term::small_int(2)]);
        let objects = context.alloc_list(&[first, second]).expect("tuple list");

        assert_eq!(
            bif_insert(&[tab, objects], &mut context),
            Ok(Term::atom(Atom::TRUE))
        );
        assert_eq!(
            bif_info_2(&[tab, Term::atom(size)], &mut context),
            Ok(Term::small_int(2))
        );
    }

    #[test]
    fn info_one_returns_metadata_proplist() {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let registry = Arc::new(EtsRegistry::new());
        let public = atom_table.intern("public");
        let named_table = atom_table.intern("named_table");
        let table_name = atom_table.intern("info_named_tab");
        let mut process = Process::new(1, 512);
        let mut context = context(&mut process, Arc::clone(&atom_table), registry);
        let tab = new_table(
            &mut context,
            &atom_table,
            table_name,
            &[public, named_table],
        );

        let proplist = super::bif_info_1(&[tab], &mut context).expect("info/1");
        let entries = list_terms(proplist);
        assert_eq!(entries.len(), 7);
        let first_entry = Tuple::new(entries[0]).expect("info tuple");
        assert_eq!(first_entry.arity(), 2);
    }

    #[test]
    fn ets_bifs_are_registered_under_ets_module() {
        let atom_table = AtomTable::with_common_atoms();
        let registry = BifRegistryImpl::new();
        register_ets_bifs(&registry, &atom_table).expect("register ets bifs");
        let ets = atom_table.intern("ets");

        for (name, arity) in [
            ("new", 2),
            ("insert", 2),
            ("lookup", 2),
            ("tab2list", 1),
            ("foldl", 3),
            ("match", 1),
            ("match", 2),
            ("match", 3),
            ("match_object", 2),
            ("match_delete", 2),
            ("select", 1),
            ("select", 2),
            ("select", 3),
            ("delete", 1),
            ("delete", 2),
            ("give_away", 3),
            ("member", 2),
            ("first", 1),
            ("next", 2),
            ("last", 1),
            ("prev", 2),
            ("info", 1),
            ("info", 2),
        ] {
            assert!(
                registry
                    .lookup(ets, atom_table.intern(name), arity)
                    .is_some(),
                "missing ets:{name}/{arity}"
            );
        }
    }
}