deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The zone of a first-order search: its members are occurrences under
//! binders with the terms their binders were opened with, a fresh
//! eigenvariable for a `∀` and a metavariable for the witness of an `∃`,
//! and its identities join literals whose terms unify.
//!
//! **Members.** An occurrence outside every binder is its own member. An
//! instance of a binder's body is a *span* of member ids, one per
//! occurrence of the body's subtree, with the body's frame: the binder's
//! own frame and the new term. So a subformula's member is the member's
//! id moved by as much as the occurrence is, and no table is looked up
//! on the engine's paths but where an occurrence is read, which finds
//! the span by its first id. A binder below another is never reached
//! through its parent's span: the rules open it with a span of its own.
//!
//! **Terms** are shared, never built: a term is a term of the sequent's
//! arena read under a frame, whose bound variables are the frame's terms,
//! or a variable of the search, a metavariable that a binding may point
//! at another term, or an eigenvariable. Unification binds metavariables
//! to such terms with the occurs check, iteratively, each pair of terms
//! once.
//!
//! **Levels** keep the eigenvariable condition. Eigenvariables are
//! numbered in the order they are made, and an eigenvariable's level is
//! its number plus one; a metavariable's level is the number of
//! eigenvariables made before it. A metavariable is bound only to a term
//! whose eigenvariables are below its level, and the metavariables of
//! that term are lowered to its level, trailed. An eigenvariable made
//! after a metavariable lies in the subtree of a `∀` above the `∃` that
//! made the metavariable, or on another branch, where none of its
//! terms ever meets the metavariable but through metavariables of lower
//! levels; so a binding the levels allow puts no eigenvariable into the
//! conclusion of its own `∀`, and the checker's condition holds.
//!
//! **Undo.** Every binding and every lowering is on the trail, and the
//! spans, frames and variables only grow; a mark is where each stands,
//! and undoing to it pops the trail and truncates the rest. The engine
//! undoes exactly where it releases pending nodes, and where a binder
//! rule or an identity it tried failed.
//!
//! **Answers.** A rule of two premises whose second premise shares an
//! unbound metavariable with the first may need another answer of the
//! first: one that binds it otherwise. The first premise's answer is the
//! tuple of the shared metavariables' terms; when the second fails under
//! it, it fails under every instance of it (with metavariables no more
//! free and no eigenvariable of a higher level), so the answer is
//! recorded as a pattern and the first premise searched again with every
//! binding that makes the tuple an instance of a recorded pattern
//! refused. Bindings only make the tuple more specific, so the refusal at
//! the binding prunes exactly the proofs whose answer is such an
//! instance, and the search of the first premise finds every other
//! answer. It ends when the bindings before the first premise are an
//! instance themselves, or when the first premise has no proof left.

use super::choices::Choices;
use super::classes::Classes;
use super::context::Context;
use super::scratch::{Pooled, Pools};
use super::zone::{Cursors, Linear, Unrestricted, Zone};
use crate::hash::{HashMap, HashSet};
use crate::linear::Instances;
use crate::linear::occurrences::{Forest, FrameId, Member, OccId, OccSet};
use crate::linear::proofs::Node;
use crate::linear::search::memory::{Charged, bytes_of};
use crate::linear::search::{Options, Reason};
use crate::linear::sequents::fo::FirstOrder;
use crate::linear::sequents::{Eigen, FoTerm, FoTermId, Symbol};
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// The frame of no binder: an occurrence outside every binder, or a
/// closed term, which reads no frame.
const NONE: u32 = u32::MAX;

#[cfg(test)]
thread_local! {
    /// The first member id a test's search may not give, below the
    /// default's: the bound on members is reached only by a search far
    /// larger than a test runs.
    pub(super) static MEMBER_LIMIT: std::cell::Cell<u32> = const { std::cell::Cell::new(u32::MAX) };
}

/// The first member id a search may not give: `u32::MAX`, which stands
/// for no frame among the frames' parents, or in a test what its thread
/// set.
fn member_limit() -> u32 {
    #[cfg(test)]
    {
        MEMBER_LIMIT.with(std::cell::Cell::get)
    }
    #[cfg(not(test))]
    {
        u32::MAX
    }
}

/// A member of a first-order search: an occurrence of the forest below
/// its length, an occurrence of a span past it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) struct FMember(u32);

impl From<FMember> for Member {
    fn from(m: FMember) -> Self {
        Self::new(m.0)
    }
}

/// A term of a search: a term of the sequent's arena under a frame (an
/// id below the arena's length), or a variable of the search (the id past
/// it by the variable's index), whose frame is [`NONE`], as a closed
/// term's is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct TRef {
    /// The term or the variable.
    id: u32,
    /// The frame its bound variables are read in.
    frame: u32,
}

/// A variable of the search.
#[derive(Clone, Copy, Debug)]
enum Var {
    /// The witness of an `∃` step: unbound, or bound to a term, and its
    /// level, below which every eigenvariable of a term it is bound to
    /// lies.
    Meta {
        /// What it is bound to.
        binding: Option<TRef>,
        /// Its level.
        level: u32,
    },
    /// The eigenvariable of a `∀` step, by its number, one less than its
    /// level.
    Eigen(u32),
}

/// What undoing a step of the trail takes back.
#[derive(Clone, Copy, Debug)]
enum Undone {
    /// The binding of the metavariable of this index.
    Bound(u32),
    /// The lowering of the metavariable of this index from that level.
    Lowered(u32, u32),
    /// What the metavariable of this index was found to stand for.
    Named(u32),
}

/// What a bound metavariable was found to stand for, kept until an undo
/// takes back a binding it rests on.
#[derive(Clone, Copy, Debug)]
enum Named {
    /// Not looked at since it was bound.
    Unknown,
    /// The ground term of this id.
    Ground(u32),
    /// A term that holds the variable of this index, unbound or an
    /// eigenvariable: so while that variable stays unbound.
    Open(u32),
}

/// The head of an application in the table of ground terms: a symbol
/// before its first argument, else the application to the arguments
/// before.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Head {
    /// The symbol.
    Symbol(u32),
    /// The application of this id.
    Applied(u32),
}

/// The table of ground terms: a zone's own, or the one every engine of a
/// search on a pool shares, so that a ground term has one id in all their
/// keys and their memo is one.
#[derive(Clone, Debug)]
enum Grounds {
    /// The zone's own.
    Own(HashMap<(Head, u32), u32>),
    /// The pool's.
    #[cfg(feature = "parallel")]
    Shared(Arc<SharedGrounds>),
}

/// The table of ground terms a pool's engines share, and its slots,
/// which every engine's account reads at each poll: an atomic, so that
/// the poll takes no lock.
#[cfg(feature = "parallel")]
#[derive(Debug)]
struct SharedGrounds {
    /// The table.
    table: std::sync::Mutex<HashMap<(Head, u32), u32>>,
    /// Its capacity after the last insertion.
    slots: std::sync::atomic::AtomicUsize,
}

impl Grounds {
    /// The name of the application of `symbol` to terms of the names
    /// `args`, as [`Framed::apply`] gives it.
    fn apply(&mut self, symbol: Symbol, args: &[Name]) -> Name {
        match self {
            Self::Own(table) => Framed::apply(table, symbol, args),
            #[cfg(feature = "parallel")]
            Self::Shared(shared) => {
                let mut table = crate::linear::search::lock(&shared.table);
                let name = Framed::apply(&mut table, symbol, args);
                shared.slots.store(table.capacity(), Ordering::Relaxed);
                name
            }
        }
    }

    /// The slots of the table. A shared one is counted by every engine
    /// that reads it, more than it holds, which the memory bound errs on.
    fn capacity(&self) -> usize {
        match self {
            Self::Own(table) => table.capacity(),
            #[cfg(feature = "parallel")]
            Self::Shared(shared) => shared.slots.load(Ordering::Relaxed),
        }
    }
}

/// A step of the walk that names a metavariable's term.
#[derive(Clone, Copy, Debug)]
enum Naming {
    /// Name a term.
    Term(TRef),
    /// Name a variable, by index.
    Var(u32),
    /// Apply the symbol to the last names found, as many as its arity.
    Apply(Symbol, u32),
    /// Keep the last name found as the metavariable's of this index.
    Keep(u32),
}

/// A name a walk found for a term.
#[derive(Clone, Copy, Debug)]
enum Name {
    /// The ground term of this id.
    Ground(u32),
    /// A term holding the variable of this index.
    Open(u32),
    /// A ground term whose id would pass a key word's value.
    Past,
}

/// The members of one instance of a binder's body: the ids from `base`
/// to `end`, one per occurrence from `first` on, under `frame`.
#[derive(Clone, Copy, Debug)]
struct Span {
    /// The first id.
    base: u32,
    /// The first id past the span.
    end: u32,
    /// The occurrence of the first id: the body's.
    first: u32,
    /// The frame of every member of the span.
    frame: u32,
}

/// Where the trail and the tables of a first-order search stand.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Mark {
    /// The spans.
    spans: usize,
    /// The frames.
    frames: usize,
    /// The variables.
    vars: usize,
    /// The eigenvariables made.
    eigens: u32,
    /// The trail.
    trail: usize,
    /// The eigenvariables whose `∀` node is not built.
    introduced: usize,
}

/// What a unification found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Unified {
    /// The terms unify, with the bindings made.
    Yes,
    /// They do not, or the bindings make an excluded answer.
    No,
    /// A binding would pass the witness depth: the branch is cut.
    Cut,
}

/// A node of a recorded answer's pattern.
#[derive(Clone, Copy, Debug)]
enum Pat {
    /// A metavariable of the answer, numbered within it.
    Var(u32),
    /// An eigenvariable, by number.
    Eigen(u32),
    /// A closed term of the sequent's arena.
    Closed(u32),
    /// A symbol applied to the patterns `kids[start..start + len]`.
    App(Symbol, u32, u32),
}

/// A recorded answer: per shared metavariable the pattern of its term,
/// and per metavariable of the patterns its level.
#[derive(Clone, Debug, Default)]
struct Pattern {
    /// The nodes.
    nodes: Vec<Pat>,
    /// The children of the applications.
    kids: Vec<u32>,
    /// Per shared metavariable, its term's node.
    roots: Vec<u32>,
    /// Per metavariable of the patterns, its level when recorded.
    levels: Vec<u32>,
}

/// The answers of one rule's first premise.
#[derive(Clone, Debug)]
struct Answers {
    /// The metavariables the second premise shares, by index.
    metas: Vec<u32>,
    /// The answers under which the second premise failed.
    patterns: Vec<Pattern>,
    /// Whether the first premise is being searched, when the patterns
    /// are excluded.
    first: bool,
}

/// The zone whose members are instances of occurrences under binders:
/// the spans, frames and variables, the trail, the answers excluded, the
/// first-order bounds, and the tables read off the sequent's terms.
pub(super) struct Framed {
    /// The forest's length: the first id of a span.
    occurrences: u32,
    /// The sequent's terms: the first id of a variable.
    base: u32,
    /// The spans, one per instance held: the forest's occurrences are
    /// members below them.
    spans: Vec<Span>,
    /// Per frame, its parent ([`NONE`] for none) and its term.
    frames: Vec<(u32, TRef)>,
    /// The variables.
    vars: Vec<Var>,
    /// How many eigenvariables were made: the next one's number.
    eigens: u32,
    /// The bindings and lowerings, to be undone.
    trail: Vec<Undone>,
    /// The eigenvariables of the `∀` steps whose nodes are not built.
    introduced: Vec<Eigen>,
    /// The answers of the rules open on the branch, the innermost last.
    answers: Vec<Answers>,
    /// The choices made while a rule may ask for another answer, and the
    /// replay that resumes its first premise.
    choices: Choices,
    /// The deepest term a metavariable may be bound to.
    witness_depth: u32,
    /// The most instances of binders the search may hold at once.
    instances: u32,
    /// The bound that cut a branch of the level, if one did.
    cut: Option<Reason>,
    /// Per term of the sequent's arena, whether no bound variable lies
    /// below it. This table and the two below never change once the zone
    /// is made: the forks of a pool share them.
    closed: Arc<[bool]>,
    /// Per term of the sequent's arena, its depth: a constant's is 0.
    depth: Arc<[u32]>,
    /// Per predicate and sign, the stamp of the marking that last found
    /// a literal of it among the members.
    marks: Vec<u64>,
    /// The stamp of the last marking.
    stamp: u64,
    /// The terms the walks visited since the engine last took them: the
    /// work a unification, a pattern or a match does, which grows with the
    /// terms' size and not with the search's steps. Atomic, so that the
    /// walks that read the zone count too; one thread uses it.
    steps: AtomicU64,
    /// The unifications of two literals tried.
    unifications: u64,
    /// The metavariables bound.
    bindings: u64,
    /// The bytes of the tables and the walks' buffers the engine was last
    /// told the zone holds.
    charged: usize,
    /// Scratch: pairs of terms to unify or compare.
    pairs: Vec<(TRef, TRef)>,
    /// Scratch: the pairs met in one walk.
    met: HashSet<(TRef, TRef)>,
    /// Scratch: terms to walk, and whether their children were.
    walk: Vec<(TRef, bool)>,
    /// Scratch: the depth of every term a binding's walk met.
    depths: HashMap<TRef, u32>,
    /// Scratch: the buffers the keys of stable sequents are written with.
    key: KeyScratch,
    /// The ground terms the keys name, by their heads and last arguments:
    /// each term met gets one id for the whole search, so equal ids are
    /// equal terms however they were reached.
    ground: Grounds,
    /// Per term of the sequent's arena, its id in `ground` if it is
    /// closed and its id below a key word's value, else [`NONE`].
    arena: Arc<[u32]>,
    /// Per variable, what it was found to stand for, on the trail.
    named: Vec<Named>,
    /// Scratch: the steps of a naming walk.
    naming: Vec<Naming>,
    /// Scratch: the names it found.
    names: Vec<Name>,
}

impl Framed {
    /// Counts a term visited by a walk.
    fn step(&self) {
        self.steps.fetch_add(1, Ordering::Relaxed);
    }

    /// The occurrence and frame of a member.
    fn instance(&self, m: FMember) -> (OccId, u32) {
        if m.0 < self.occurrences {
            return (OccId::new(m.0), NONE);
        }
        let span = self.spans[self.spans.partition_point(|s| s.base <= m.0) - 1];
        (OccId::new(span.first + (m.0 - span.base)), span.frame)
    }

    /// The term the bound variable `i` of `frame` stands for.
    fn frame_term(&self, mut frame: u32, i: u32) -> TRef {
        for _ in 0..i {
            frame = self.frames[frame as usize].0;
        }
        self.frames[frame as usize].1
    }

    /// The term `t` stands for: its bound variables read in its frame,
    /// its metavariables' bindings followed; a closed term without its
    /// frame.
    fn deref(&self, fo: &FirstOrder, mut t: TRef) -> TRef {
        loop {
            if t.id < self.base {
                if let FoTerm::Bound(i) = fo.terms[t.id as usize] {
                    t = self.frame_term(t.frame, i);
                    continue;
                }
                if self.closed[t.id as usize] {
                    t.frame = NONE;
                }
                return t;
            }
            match self.vars[(t.id - self.base) as usize] {
                Var::Meta {
                    binding: Some(b), ..
                } => t = b,
                _ => return t,
            }
        }
    }

    /// The variable a term is, by index, if it is one.
    fn var(&self, t: TRef) -> Option<u32> {
        t.id.checked_sub(self.base)
    }

    /// The level of a variable.
    fn level(&self, v: u32) -> u32 {
        match self.vars[v as usize] {
            Var::Meta { level, .. } => level,
            Var::Eigen(number) => number + 1,
        }
    }

    /// The symbol and the arguments of a term of the arena that is an
    /// application.
    fn app(fo: &FirstOrder, t: TRef) -> (Symbol, &[FoTermId]) {
        match fo.terms[t.id as usize] {
            FoTerm::App(symbol, args) => (symbol, fo.list(args)),
            term => unreachable!("{term:?} is no application after a deref"),
        }
    }

    /// Adds a variable and returns its term.
    fn push_var(&mut self, var: Var) -> Result<TRef, Reason> {
        let id = u32::try_from(self.vars.len())
            .ok()
            .and_then(|v| self.base.checked_add(v))
            .filter(|&id| id < u32::MAX)
            .ok_or(Reason::IndexLimit)?;
        self.vars.push(var);
        self.named.push(Named::Unknown);
        Ok(TRef { id, frame: NONE })
    }

    /// Opens the body of the binder `binder` with `term`: a span of the
    /// body's occurrences under the binder's frame extended by `term`.
    fn open(&mut self, forest: &Forest, binder: FMember, term: TRef) -> Result<FMember, Reason> {
        let (o, frame) = self.instance(binder);
        let frames = u32::try_from(self.frames.len())
            .ok()
            .filter(|&f| f < NONE)
            .ok_or(Reason::IndexLimit)?;
        let base = self.spans.last().map_or(self.occurrences, |s| s.end);
        // A binder's body is one occurrence at the least.
        let end = base
            .checked_add(forest.size(o) - 1)
            .filter(|&end| end <= member_limit())
            .ok_or(Reason::IndexLimit)?;
        self.frames.push((frame, term));
        self.spans.push(Span {
            base,
            end,
            first: o.get() + 1,
            frame: frames,
        });
        Ok(FMember(base))
    }

    /// Whether the search holds as many instances as it may: the next
    /// binder step cuts its branch.
    fn full(&mut self) -> bool {
        if self.spans.len() >= self.instances as usize {
            self.cut = Some(Reason::Instances {
                instances: self.instances,
            });
            return true;
        }
        false
    }

    /// Binds the metavariable `x` to `t`: refused where `x` occurs in
    /// `t` or `t` holds an eigenvariable at or past `x`'s level, cut where
    /// `t` is deeper than the witness depth; the metavariables of `t`
    /// above `x`'s level are lowered to it.
    fn bind(&mut self, fo: &FirstOrder, x: u32, t: TRef) -> Unified {
        let level = self.level(x);
        self.depths.clear();
        self.walk.clear();
        self.walk.push((t, false));
        while let Some((u, expanded)) = self.walk.pop() {
            self.step();
            let u = self.deref(fo, u);
            if !expanded && self.depths.contains_key(&u) {
                continue;
            }
            let depth = if let Some(v) = self.var(u) {
                match self.vars[v as usize] {
                    Var::Meta { level: l, .. } => {
                        if v == x {
                            return Unified::No;
                        }
                        if l > level {
                            self.trail.push(Undone::Lowered(v, l));
                            self.vars[v as usize] = Var::Meta {
                                binding: None,
                                level,
                            };
                        }
                    }
                    Var::Eigen(number) => {
                        if number + 1 > level {
                            return Unified::No;
                        }
                    }
                }
                0
            } else if self.closed[u.id as usize] {
                self.depth[u.id as usize]
            } else {
                let (_, args) = Self::app(fo, u);
                if !expanded {
                    self.walk.push((u, true));
                    self.walk.extend(args.iter().map(|&a| {
                        (
                            TRef {
                                id: a.get(),
                                frame: u.frame,
                            },
                            false,
                        )
                    }));
                    continue;
                }
                let deepest = args
                    .iter()
                    .map(|&a| {
                        let child = self.deref(
                            fo,
                            TRef {
                                id: a.get(),
                                frame: u.frame,
                            },
                        );
                        self.depths[&child]
                    })
                    .max();
                deepest.map_or(0, |d| d + 1)
            };
            if depth > self.witness_depth {
                self.cut = Some(Reason::WitnessDepth {
                    depth: self.witness_depth,
                });
                return Unified::Cut;
            }
            self.depths.insert(u, depth);
        }
        self.trail.push(Undone::Bound(x));
        self.bindings += 1;
        self.vars[x as usize] = Var::Meta {
            binding: Some(t),
            level,
        };
        Unified::Yes
    }

    /// Unifies the pairs of terms on `pairs`.
    fn unify_pairs(&mut self, fo: &FirstOrder) -> Unified {
        self.met.clear();
        while let Some((a, b)) = self.pairs.pop() {
            self.step();
            let (a, b) = (self.deref(fo, a), self.deref(fo, b));
            if a == b || !self.met.insert((a, b)) {
                continue;
            }
            let found = match (self.var(a), self.var(b)) {
                (Some(x), Some(y)) => match (self.vars[x as usize], self.vars[y as usize]) {
                    // The younger of two metavariables is bound to the
                    // older, which lowers nothing.
                    (Var::Meta { level: l, .. }, Var::Meta { level: m, .. }) => {
                        if l >= m {
                            self.bind(fo, x, b)
                        } else {
                            self.bind(fo, y, a)
                        }
                    }
                    (Var::Meta { .. }, Var::Eigen(_)) => self.bind(fo, x, b),
                    (Var::Eigen(_), Var::Meta { .. }) => self.bind(fo, y, a),
                    (Var::Eigen(_), Var::Eigen(_)) => Unified::No,
                },
                (Some(x), None) => match self.vars[x as usize] {
                    Var::Meta { .. } => self.bind(fo, x, b),
                    Var::Eigen(_) => Unified::No,
                },
                (None, Some(y)) => match self.vars[y as usize] {
                    Var::Meta { .. } => self.bind(fo, y, a),
                    Var::Eigen(_) => Unified::No,
                },
                (None, None) => {
                    let ((s, xs), (r, ys)) = (Self::app(fo, a), Self::app(fo, b));
                    if s != r {
                        Unified::No
                    } else {
                        self.pairs.extend(xs.iter().zip(ys).map(|(&x, &y)| {
                            (
                                TRef {
                                    id: x.get(),
                                    frame: a.frame,
                                },
                                TRef {
                                    id: y.get(),
                                    frame: b.frame,
                                },
                            )
                        }));
                        Unified::Yes
                    }
                }
            };
            if found != Unified::Yes {
                self.pairs.clear();
                return found;
            }
        }
        Unified::Yes
    }

    /// Whether two terms are equal, as they stand.
    fn equal(&self, fo: &FirstOrder, a: TRef, b: TRef) -> bool {
        let mut pairs = vec![(a, b)];
        let mut met = HashSet::default();
        while let Some((a, b)) = pairs.pop() {
            self.step();
            let (a, b) = (self.deref(fo, a), self.deref(fo, b));
            if a == b || !met.insert((a, b)) {
                continue;
            }
            if self.var(a).is_some() || self.var(b).is_some() {
                return false;
            }
            let ((s, xs), (r, ys)) = (Self::app(fo, a), Self::app(fo, b));
            if s != r {
                return false;
            }
            pairs.extend(xs.iter().zip(ys).map(|(&x, &y)| {
                (
                    TRef {
                        id: x.get(),
                        frame: a.frame,
                    },
                    TRef {
                        id: y.get(),
                        frame: b.frame,
                    },
                )
            }));
        }
        true
    }

    /// Whether every variable of `t` is below `level`, or at it for a
    /// metavariable: what a metavariable of that level could be bound
    /// to, and be read as.
    fn fits(&self, fo: &FirstOrder, t: TRef, level: u32) -> bool {
        let mut walk = vec![t];
        let mut met = HashSet::default();
        while let Some(u) = walk.pop() {
            self.step();
            let u = self.deref(fo, u);
            if !met.insert(u) {
                continue;
            }
            if let Some(v) = self.var(u) {
                let fits = match self.vars[v as usize] {
                    Var::Meta { level: l, .. } => l <= level,
                    Var::Eigen(number) => number < level,
                };
                if !fits {
                    return false;
                }
            } else if !self.closed[u.id as usize] {
                walk.extend(Self::app(fo, u).1.iter().map(|&a| TRef {
                    id: a.get(),
                    frame: u.frame,
                }));
            }
        }
        true
    }

    /// Whether the terms of the metavariables `metas` are an instance of
    /// `pattern`: its metavariables replaced by terms that fit their
    /// levels, consistently.
    fn instance_of(&self, fo: &FirstOrder, metas: &[u32], pattern: &Pattern) -> bool {
        let mut theta: Vec<Option<TRef>> = vec![None; pattern.levels.len()];
        let mut walk: Vec<(u32, TRef)> = metas
            .iter()
            .zip(&pattern.roots)
            .map(|(&m, &root)| {
                (
                    root,
                    TRef {
                        id: self.base + m,
                        frame: NONE,
                    },
                )
            })
            .collect();
        let mut met = HashSet::default();
        while let Some((node, t)) = walk.pop() {
            self.step();
            let t = self.deref(fo, t);
            if !met.insert((node, t)) {
                continue;
            }
            let fits = match pattern.nodes[node as usize] {
                Pat::Var(k) => match theta[k as usize] {
                    None => {
                        theta[k as usize] = Some(t);
                        self.fits(fo, t, pattern.levels[k as usize])
                    }
                    Some(u) => self.equal(fo, u, t),
                },
                Pat::Eigen(number) => self
                    .var(t)
                    .is_some_and(|v| matches!(self.vars[v as usize], Var::Eigen(n) if n == number)),
                Pat::Closed(id) => self.equal(fo, TRef { id, frame: NONE }, t),
                Pat::App(symbol, start, len) => {
                    if self.var(t).is_some() {
                        false
                    } else {
                        let (s, args) = Self::app(fo, t);
                        let kids = &pattern.kids[start as usize..(start + len) as usize];
                        walk.extend(kids.iter().zip(args).map(|(&kid, &a)| {
                            (
                                kid,
                                TRef {
                                    id: a.get(),
                                    frame: t.frame,
                                },
                            )
                        }));
                        s == symbol
                    }
                }
            };
            if !fits {
                return false;
            }
        }
        true
    }

    /// Whether the bindings as they stand make no answer excluded while
    /// its first premise is searched.
    fn passes(&self, fo: &FirstOrder) -> bool {
        self.answers
            .iter()
            .filter(|answers| answers.first)
            .all(|answers| {
                answers
                    .patterns
                    .iter()
                    .all(|p| !self.instance_of(fo, &answers.metas, p))
            })
    }

    /// The pattern of the terms of `metas` as they stand.
    fn pattern(&self, fo: &FirstOrder, metas: &[u32]) -> Pattern {
        let mut pattern = Pattern::default();
        let mut nodes: HashMap<TRef, u32> = HashMap::default();
        let mut numbered: HashMap<u32, u32> = HashMap::default();
        for &m in metas {
            let root = TRef {
                id: self.base + m,
                frame: NONE,
            };
            let mut walk = vec![(root, false)];
            while let Some((u, expanded)) = walk.pop() {
                self.step();
                let u = self.deref(fo, u);
                if !expanded && nodes.contains_key(&u) {
                    continue;
                }
                let node = if let Some(v) = self.var(u) {
                    match self.vars[v as usize] {
                        Var::Meta { level, .. } => {
                            let k = *numbered.entry(v).or_insert_with(|| {
                                pattern.levels.push(level);
                                (pattern.levels.len() - 1) as u32
                            });
                            Pat::Var(k)
                        }
                        Var::Eigen(number) => Pat::Eigen(number),
                    }
                } else if self.closed[u.id as usize] {
                    Pat::Closed(u.id)
                } else {
                    let (symbol, args) = Self::app(fo, u);
                    let child = |a: &FoTermId| TRef {
                        id: a.get(),
                        frame: u.frame,
                    };
                    if !expanded {
                        walk.push((u, true));
                        walk.extend(args.iter().map(|a| (child(a), false)));
                        continue;
                    }
                    let start = pattern.kids.len() as u32;
                    for a in args {
                        let kid = nodes[&self.deref(fo, child(a))];
                        pattern.kids.push(kid);
                    }
                    Pat::App(symbol, start, args.len() as u32)
                };
                pattern.nodes.push(node);
                nodes.insert(u, (pattern.nodes.len() - 1) as u32);
            }
            pattern.roots.push(nodes[&self.deref(fo, root)]);
        }
        pattern
    }

    /// The marks' index of a literal's predicate, or of its atom where
    /// the sequent's atoms have no predicates, and sign.
    fn key(forest: &Forest, o: OccId, dual: bool) -> Option<usize> {
        let (atom, sign) = (forest.atom(o)?, forest.sign(o)?);
        let fo = &forest.sequent().fo;
        let index = match fo.atoms.get(atom.index()) {
            Some(&(symbol, _)) => symbol.index(),
            None => atom.index(),
        };
        Some(2 * index + (sign as usize ^ usize::from(dual)))
    }
}

// The keys of a first-order search's stable sequents, which its memo and
// loop check read.
//
// A member is written as its occurrence followed by the terms of its
// frame, innermost first, each in prefix order as the bindings resolve
// it: a ground term by its id in the search's table of ground terms
// (the arena's closed terms and every ground term a binding built, each
// once, so equal ids are equal terms however they were reached, and a
// witness built over many bindings is one word, not its length), an
// application holding a variable by its symbol followed by its
// arguments, a metavariable or an eigenvariable by a number. The
// occurrence fixes how many binders lie above it, and a symbol its
// arity, so the words of a member end where its last term does.
//
// **The instance's own key** names every variable as the search does,
// and every metavariable's level beside it: two stable sequents share it
// exactly when they are the same instance, the same members over the
// same unbound metavariables and eigenvariables. The loop check compares
// it: a sequent equal to an ancestor whose metavariables are still
// unbound is that ancestor, and a smallest proof of the ancestor never
// passes through it. A failure cut by a bound is recorded under it, as
// the propositional engine records one under the sequent's own key.
//
// **The canonical key** is the same sequent up to a renaming of its
// variables: the members sorted with every metavariable alike, the
// metavariables then numbered as they first appear, the eigenvariables
// ranked by number, and every metavariable's level written as how many
// of the sequent's eigenvariables lie below it, which is all of its
// level a search of the sequent reads: a binding there only ever meets
// the sequent's own eigenvariables and younger ones, which no
// metavariable of the sequent may take. Two sequents with one canonical
// key are one sequent up to a renaming that keeps the levels' order, so
// a complete failure of either is one of the other.

/// The bits of a term's word that say what it is.
const TAG: u32 = 3 << 30;
/// A ground term, by its id in the table of ground terms.
const GROUND: u32 = 0;
/// An application, by its symbol; its arguments follow.
const APP: u32 = 1 << 30;
/// An eigenvariable, by its number or rank.
const EIGEN: u32 = 2 << 30;
/// A metavariable, by its index or number.
const META: u32 = 3 << 30;
/// The bits of a term's word that hold its value. A value past them is
/// refused: such a sequent is decided without a key.
const VALUE: u32 = !TAG;

/// The most words the members of a key may take: a sequent whose terms,
/// written out, pass it (a witness shared many times over is written as
/// often as it is reached) is decided without the memo and the loop
/// check, which would spend more on its key than on most searches.
const KEY_WORDS: usize = 1 << 16;

/// The buffers the keys are written with, kept between stable sequents.
#[derive(Debug, Default)]
struct KeyScratch {
    /// The members' words, one member after another.
    words: Vec<u32>,
    /// Per member, where its words start, `Γ`'s first.
    starts: Vec<usize>,
    /// Per member, how many copies of it the zone holds.
    copies: Vec<u32>,
    /// The members' order in a key.
    order: Vec<usize>,
    /// The eigenvariables' numbers, sorted, each once.
    eigens: Vec<u32>,
    /// The metavariables by index, in the order a key names them.
    metas: Vec<u32>,
    /// The number of each metavariable in the canonical key.
    numbers: HashMap<u32, u32>,
    /// The terms to write.
    walk: Vec<TRef>,
}

impl KeyScratch {
    /// The bytes its buffers hold; a hash table's entries as its slots
    /// and a control byte each.
    fn bytes(&self) -> usize {
        bytes_of(&self.words)
            + bytes_of(&self.starts)
            + bytes_of(&self.copies)
            + bytes_of(&self.order)
            + bytes_of(&self.eigens)
            + bytes_of(&self.metas)
            + bytes_of(&self.walk)
            + self.numbers.capacity() * (size_of::<(u32, u32)>() + 1)
    }

    /// Where the words of member `i` lie.
    fn range(&self, i: usize) -> std::ops::Range<usize> {
        let end = self.starts.get(i + 1).copied().unwrap_or(self.words.len());
        self.starts[i]..end
    }

    /// The words of member `i`.
    fn member(&self, i: usize) -> &[u32] {
        &self.words[self.range(i)]
    }

    /// Orders members `x` and `y` as the canonical key does: by their
    /// words, a metavariable as any other and an eigenvariable by its
    /// rank.
    fn abstract_order(&self, x: usize, y: usize) -> std::cmp::Ordering {
        let (x, y) = (self.member(x), self.member(y));
        x[0].cmp(&y[0]).then_with(|| {
            x[1..]
                .iter()
                .map(|&w| self.abstracted(w))
                .cmp(y[1..].iter().map(|&w| self.abstracted(w)))
        })
    }

    /// The word as the canonical key's order reads it: a metavariable as
    /// any other, an eigenvariable by its rank.
    fn abstracted(&self, word: u32) -> u32 {
        match word & TAG {
            META => META,
            EIGEN => EIGEN | self.rank(word & VALUE),
            _ => word,
        }
    }

    /// The rank of an eigenvariable among the sequent's.
    fn rank(&self, number: u32) -> u32 {
        // Fewer eigenvariables than words.
        self.eigens.partition_point(|&n| n < number) as u32
    }
}

impl Framed {
    /// Writes the keys of the stable sequent `⊢ Θ ; Γ`: its own and its
    /// canonical one, as said above [`KeyScratch`]. False where a variable, a term
    /// or a symbol passes a word's value or the words pass
    /// [`KEY_WORDS`]: the sequent is then decided without a key.
    fn write_keys(
        &mut self,
        forest: &Forest,
        theta: &Set,
        gamma: &Members,
        own: &mut Vec<OccId>,
        canonical: &mut Vec<OccId>,
    ) -> bool {
        let fo = &forest.sequent().fo;
        let mut s = std::mem::take(&mut self.key);
        s.words.clear();
        s.starts.clear();
        s.copies.clear();
        s.eigens.clear();
        // A member present more than once is written once, with its number
        // of copies: a clause copied a hundred times leaves a hundred
        // copies of one instance, which written out made every key as long.
        let written = gamma
            .0
            .chunk_by(|x, y| x == y)
            .chain(theta.0.chunks(1))
            .all(|copies| {
                u32::try_from(copies.len()).is_ok_and(|n| {
                    s.copies.push(n);
                    self.write_member(fo, copies[0], &mut s)
                })
            });
        if written {
            // Writing the keys reads every word once per key and sorts the
            // members: counted as the terms a walk visits.
            let sorting = usize::BITS - s.starts.len().leading_zeros();
            self.steps.fetch_add(
                (s.words.len() as u64).saturating_mul(2 * u64::from(1 + sorting)),
                Ordering::Relaxed,
            );
            s.eigens.sort_unstable();
            s.eigens.dedup();
            let n = gamma.0.chunk_by(|x, y| x == y).count();
            self.own_key(&mut s, n, own);
            self.canonical_key(&mut s, n, canonical);
        }
        self.key = s;
        written
    }

    /// Writes a member's words, collecting its eigenvariables.
    fn write_member(&mut self, fo: &FirstOrder, m: FMember, s: &mut KeyScratch) -> bool {
        let (o, mut frame) = self.instance(m);
        s.starts.push(s.words.len());
        s.words.push(o.get());
        while frame != NONE {
            let (parent, term) = self.frames[frame as usize];
            s.walk.clear();
            s.walk.push(term);
            while let Some(t) = s.walk.pop() {
                self.step();
                if s.words.len() >= KEY_WORDS {
                    return false;
                }
                let (tag, value) = match self.name(fo, t) {
                    Name::Ground(id) => (GROUND, id),
                    Name::Past => return false,
                    Name::Open(_) => {
                        let t = self.deref(fo, t);
                        if let Some(v) = self.var(t) {
                            match self.vars[v as usize] {
                                Var::Meta { .. } => (META, v),
                                Var::Eigen(number) => {
                                    s.eigens.push(number);
                                    (EIGEN, number)
                                }
                            }
                        } else {
                            let (symbol, args) = Self::app(fo, t);
                            s.walk.extend(args.iter().rev().map(|a| TRef {
                                id: a.get(),
                                frame: t.frame,
                            }));
                            (APP, symbol.get())
                        }
                    }
                };
                if value > VALUE {
                    return false;
                }
                s.words.push(tag | value);
            }
            frame = parent;
        }
        true
    }

    /// The name of the term `t` stands for: its id where it is ground, a
    /// variable it holds where it is not, or past a word's value. Every
    /// bound metavariable the walk passes keeps its name, on the trail,
    /// so a key names a witness built over many bindings in one step:
    /// a name rests only on bindings made before it, which an undo takes
    /// back after it, and an open name is asked again once its variable
    /// is bound.
    fn name(&mut self, fo: &FirstOrder, t: TRef) -> Name {
        // A frame's term is a variable: an unbound one, an eigenvariable
        // or a kept name needs no walk.
        if let Some(v) = self.var(t) {
            match self.vars[v as usize] {
                Var::Meta {
                    binding: Some(_), ..
                } => {
                    if let Some(name) = self.kept(v) {
                        return name;
                    }
                }
                _ => return Name::Open(v),
            }
        }
        let mut steps = std::mem::take(&mut self.naming);
        let mut names = std::mem::take(&mut self.names);
        steps.clear();
        names.clear();
        steps.push(Naming::Term(t));
        while let Some(step) = steps.pop() {
            self.step();
            match step {
                Naming::Term(mut t) => {
                    while t.id < self.base
                        && let FoTerm::Bound(i) = fo.terms[t.id as usize]
                    {
                        t = self.frame_term(t.frame, i);
                    }
                    if let Some(v) = self.var(t) {
                        steps.push(Naming::Var(v));
                    } else if self.closed[t.id as usize] {
                        names.push(match self.arena[t.id as usize] {
                            NONE => Name::Past,
                            id => Name::Ground(id),
                        });
                    } else {
                        let (symbol, args) = Self::app(fo, t);
                        // An arity is below a sequent's length.
                        steps.push(Naming::Apply(symbol, args.len() as u32));
                        steps.extend(args.iter().rev().map(|a| {
                            Naming::Term(TRef {
                                id: a.get(),
                                frame: t.frame,
                            })
                        }));
                    }
                }
                Naming::Var(v) => match self.vars[v as usize] {
                    Var::Meta {
                        binding: Some(b), ..
                    } => match self.kept(v) {
                        Some(name) => names.push(name),
                        None => {
                            steps.push(Naming::Keep(v));
                            steps.push(Naming::Term(b));
                        }
                    },
                    _ => names.push(Name::Open(v)),
                },
                Naming::Apply(symbol, arity) => {
                    let at = names.len() - arity as usize;
                    let name = self.ground.apply(symbol, &names[at..]);
                    names.truncate(at);
                    names.push(name);
                }
                Naming::Keep(v) => {
                    let kept = match names.last() {
                        Some(&Name::Ground(id)) => Named::Ground(id),
                        Some(&Name::Open(w)) => Named::Open(w),
                        _ => continue,
                    };
                    self.named[v as usize] = kept;
                    self.trail.push(Undone::Named(v));
                }
            }
        }
        let name = names.pop().expect("a walk names its term");
        self.naming = steps;
        self.names = names;
        name
    }

    /// The name the bound metavariable `v` keeps, where it still holds.
    fn kept(&self, v: u32) -> Option<Name> {
        match self.named[v as usize] {
            Named::Unknown => None,
            Named::Ground(id) => Some(Name::Ground(id)),
            Named::Open(w) => match self.vars[w as usize] {
                Var::Meta {
                    binding: Some(_), ..
                } => None,
                _ => Some(Name::Open(w)),
            },
        }
    }

    /// The name of the application of `symbol` to terms of the names
    /// `args`: where all are ground, the id of the term in `ground`, a
    /// new one for a new term, the arguments taken one at a time (a
    /// constant applied to none, [`NONE`]); else the first open one, or
    /// past.
    fn apply(ground: &mut HashMap<(Head, u32), u32>, symbol: Symbol, args: &[Name]) -> Name {
        let mut past = false;
        for &arg in args {
            match arg {
                Name::Open(v) => return Name::Open(v),
                Name::Past => past = true,
                Name::Ground(_) => {}
            }
        }
        if past {
            return Name::Past;
        }
        let ids = args.iter().map(|&arg| match arg {
            Name::Ground(id) => id,
            Name::Open(_) | Name::Past => unreachable!("every argument is ground"),
        });
        let mut head = Head::Symbol(symbol.get());
        let mut id = NONE;
        for arg in ids.chain(args.is_empty().then_some(NONE)) {
            let next = u32::try_from(ground.len())
                .ok()
                .filter(|&next| next <= VALUE);
            id = match (ground.entry((head, arg)), next) {
                (Entry::Occupied(entry), _) => *entry.get(),
                (Entry::Vacant(entry), Some(next)) => *entry.insert(next),
                (Entry::Vacant(_), None) => return Name::Past,
            };
            head = Head::Applied(id);
        }
        Name::Ground(id)
    }

    /// The level of a metavariable, by index.
    fn meta_level(&self, v: u32) -> u32 {
        match self.vars[v as usize] {
            Var::Meta { level, .. } => level,
            Var::Eigen(_) => unreachable!("a metavariable's word names a metavariable"),
        }
    }

    /// The instance's own key: the members of `Γ` (the first `n`, each
    /// once) and of `Θ`, each zone's sorted by their words, each member
    /// after its number of copies and each zone after its number of
    /// members, then the level of every metavariable in the order they
    /// appear.
    fn own_key(&self, s: &mut KeyScratch, n: usize, key: &mut Vec<OccId>) {
        let total = s.starts.len();
        s.order.clear();
        s.order.extend(0..total);
        let mut order = std::mem::take(&mut s.order);
        order[..n].sort_by(|&x, &y| s.member(x).cmp(s.member(y)));
        order[n..].sort_by(|&x, &y| s.member(x).cmp(s.member(y)));
        s.metas.clear();
        s.numbers.clear();
        key.clear();
        for members in [&order[..n], &order[n..]] {
            // A zone's distinct members are fewer than a word counts: each
            // is a member id, a `u32`.
            key.push(OccId::new(members.len() as u32));
            for &i in members {
                let range = s.range(i);
                key.push(OccId::new(s.copies[i]));
                key.push(OccId::new(s.words[range.start]));
                for &w in &s.words[range.start + 1..range.end] {
                    if w & TAG == META && s.numbers.insert(w & VALUE, 0).is_none() {
                        s.metas.push(w & VALUE);
                    }
                    key.push(OccId::new(w));
                }
            }
        }
        key.extend(s.metas.iter().map(|&v| OccId::new(self.meta_level(v))));
        s.order = order;
    }

    /// The canonical key: the members of `Γ` (the first `n`, each once,
    /// after its number of copies) and of `Θ`, each zone's sorted with every metavariable alike and every
    /// eigenvariable by its rank, the metavariables numbered as they
    /// first appear in that order, then per metavariable how many of the
    /// sequent's eigenvariables lie below its level.
    fn canonical_key(&self, s: &mut KeyScratch, n: usize, key: &mut Vec<OccId>) {
        let mut order = std::mem::take(&mut s.order);
        order[..n].sort_by(|&x, &y| s.abstract_order(x, y));
        order[n..].sort_by(|&x, &y| s.abstract_order(x, y));
        s.metas.clear();
        s.numbers.clear();
        key.clear();
        for members in [&order[..n], &order[n..]] {
            key.push(OccId::new(members.len() as u32));
            for &i in members {
                let range = s.range(i);
                key.push(OccId::new(s.copies[i]));
                key.push(OccId::new(s.words[range.start]));
                for j in range.start + 1..range.end {
                    let w = s.words[j];
                    let word = match w & TAG {
                        META => {
                            let v = w & VALUE;
                            // Fewer metavariables than words.
                            let next = s.metas.len() as u32;
                            let number = *s.numbers.entry(v).or_insert(next);
                            if number == next {
                                s.metas.push(v);
                            }
                            META | number
                        }
                        EIGEN => EIGEN | s.rank(w & VALUE),
                        _ => w,
                    };
                    key.push(OccId::new(word));
                }
            }
        }
        key.extend(
            s.metas
                .iter()
                .map(|&v| OccId::new(s.rank(self.meta_level(v)))),
        );
        s.order = order;
    }
}

impl Zone for Framed {
    const FIRST_ORDER: bool = true;

    type Member = FMember;
    type Linear = Members;
    type Unrestricted = Set;
    type Duals = usize;

    fn new(forest: &Forest, options: &Options) -> Self {
        let fo = &forest.sequent().fo;
        let mut closed = vec![true; fo.terms.len()];
        let mut depth = vec![0; fo.terms.len()];
        // Every term names only terms before it.
        for (i, term) in fo.terms.iter().enumerate() {
            (closed[i], depth[i]) = match *term {
                FoTerm::Bound(_) => (false, 0),
                FoTerm::App(_, args) => {
                    let args = fo.list(args);
                    (
                        args.iter().all(|a| closed[a.index()]),
                        args.iter().map(|a| depth[a.index()] + 1).max().unwrap_or(0),
                    )
                }
                FoTerm::Eigen(_) | FoTerm::Meta(_) => {
                    unreachable!("a sequent's arena holds no eigenvariable or metavariable")
                }
            };
        }
        // A forest has fewer than 2³² occurrences and a sequent fewer
        // terms than its text or document.
        let occurrences = forest.len() as u32;
        let mut ground = Grounds::Own(HashMap::default());
        let mut arena = vec![NONE; fo.terms.len()];
        // Every term names only terms before it.
        let mut names = Vec::new();
        for (i, term) in fo.terms.iter().enumerate() {
            if let FoTerm::App(symbol, args) = *term
                && closed[i]
            {
                names.clear();
                names.extend(fo.list(args).iter().map(|a| match arena[a.index()] {
                    NONE => Name::Past,
                    id => Name::Ground(id),
                }));
                if let Name::Ground(id) = ground.apply(symbol, &names) {
                    arena[i] = id;
                }
            }
        }
        Self {
            occurrences,
            base: fo.terms.len() as u32,
            spans: Vec::new(),
            frames: Vec::new(),
            vars: Vec::new(),
            eigens: 0,
            trail: Vec::new(),
            introduced: Vec::new(),
            answers: Vec::new(),
            choices: Choices::default(),
            witness_depth: options.witness_depth,
            instances: options.instances,
            cut: None,
            closed: closed.into(),
            depth: depth.into(),
            marks: Vec::new(),
            stamp: 0,
            steps: AtomicU64::new(0),
            unifications: 0,
            bindings: 0,
            charged: 0,
            pairs: Vec::new(),
            met: HashSet::default(),
            walk: Vec::new(),
            depths: HashMap::default(),
            key: KeyScratch::default(),
            ground,
            arena: arena.into(),
            named: Vec::new(),
            naming: Vec::new(),
            names: Vec::new(),
        }
    }

    /// A copy of the spans, frames, variables, bindings and trail, with
    /// the sequent's tables and the table of ground terms the pool shares
    /// ([`Zone::share`]), so
    /// that the worker's keys name what every engine's do; the counters
    /// at zero and the scratch empty. No rule
    /// is open that asks for another answer ([`Zone::divides`]), so there
    /// is no answer and no choice to log.
    #[cfg(feature = "parallel")]
    fn fork(&self) -> Self {
        Self {
            occurrences: self.occurrences,
            base: self.base,
            spans: self.spans.clone(),
            frames: self.frames.clone(),
            vars: self.vars.clone(),
            eigens: self.eigens,
            trail: self.trail.clone(),
            introduced: self.introduced.clone(),
            answers: Vec::new(),
            choices: Choices::default(),
            witness_depth: self.witness_depth,
            instances: self.instances,
            cut: None,
            closed: Arc::clone(&self.closed),
            depth: Arc::clone(&self.depth),
            marks: Vec::new(),
            stamp: 0,
            steps: AtomicU64::new(0),
            unifications: 0,
            bindings: 0,
            charged: 0,
            pairs: Vec::new(),
            met: HashSet::default(),
            walk: Vec::new(),
            depths: HashMap::default(),
            key: KeyScratch::default(),
            ground: self.ground.clone(),
            arena: Arc::clone(&self.arena),
            named: self.named.clone(),
            naming: Vec::new(),
            names: Vec::new(),
        }
    }

    #[cfg(feature = "parallel")]
    fn share(&mut self) {
        if let Grounds::Own(table) = &mut self.ground {
            let table = std::mem::take(table);
            self.ground = Grounds::Shared(Arc::new(SharedGrounds {
                slots: std::sync::atomic::AtomicUsize::new(table.capacity()),
                table: std::sync::Mutex::new(table),
            }));
        }
    }

    /// While a rule may ask a premise for another answer, its choices are
    /// logged and replayed in order, and a failure may rest on an answer
    /// excluded: only a choice outside every such rule is divided.
    #[cfg(feature = "parallel")]
    fn divides(&self) -> bool {
        self.answers.is_empty()
    }

    #[cfg(feature = "parallel")]
    fn adopt(&mut self, worker: Self) {
        let (unifications, bindings, cut, charged) =
            (self.unifications, self.bindings, self.cut, self.charged);
        let steps = *self.steps.get_mut();
        *self = Self {
            unifications,
            bindings,
            cut,
            charged,
            steps: AtomicU64::new(steps),
            ..worker
        };
    }

    #[cfg(feature = "parallel")]
    fn cut_by(&mut self, reason: Reason) {
        self.cut.get_or_insert(reason);
    }

    fn root(&self, o: OccId) -> FMember {
        FMember(o.get())
    }

    fn occurrence(&self, m: FMember) -> OccId {
        self.instance(m).0
    }

    fn child(&self, m: FMember, child: OccId) -> FMember {
        FMember(m.0 + (child.get() - self.occurrence(m).get()))
    }

    /// A literal of a predicate whose atoms are all closed, so that its
    /// dual is its atom's.
    fn dual_in(&self, forest: &Forest, literal: FMember, within: &Set) -> Option<FMember> {
        let o = self.occurrence(literal);
        let (atom, sign) = (forest.atom(o)?, forest.sign(o)?);
        within.iter().find(|&d| {
            let d = self.occurrence(d);
            forest.atom(d) == Some(atom) && forest.sign(d) == Some(!sign)
        })
    }

    /// As [`Self::dual_in`], over the members of `rest` in their order.
    fn dual_from(
        &self,
        forest: &Forest,
        literal: FMember,
        rest: &Members,
        _cursors: &mut Cursors,
    ) -> Option<FMember> {
        let o = self.occurrence(literal);
        let (atom, sign) = (forest.atom(o)?, forest.sign(o)?);
        rest.iter().find(|&d| {
            let d = self.occurrence(d);
            forest.atom(d) == Some(atom) && forest.sign(d) == Some(!sign)
        })
    }

    /// The predicates and signs of the members' literals.
    fn mark_literals(&mut self, forest: &Forest, members: &[FMember], scratch: &mut Charged) {
        if self.marks.is_empty() {
            let fo = &forest.sequent().fo;
            let keys = 2 * fo.symbols.len().max(forest.sequent().atom_names().len());
            scratch.charge(keys * size_of::<u64>());
            self.marks = vec![0; keys];
        }
        self.stamp += 1;
        for &m in members {
            if let Some(key) = Self::key(forest, self.occurrence(m), false) {
                self.marks[key] = self.stamp;
            }
        }
    }

    fn duals(&self, _: &Forest, _: FMember) -> Option<usize> {
        None
    }

    fn marked(&self, _: usize) -> Option<FMember> {
        None
    }

    fn first_lookup(&mut self, _: usize) -> bool {
        false
    }

    /// Whether a literal below the formula has a predicate whose dual
    /// literal the last marking found.
    fn meets(&self, forest: &Forest, formula: FMember) -> bool {
        forest
            .subtree(self.occurrence(formula))
            .filter_map(|l| Self::key(forest, l, true))
            .any(|key| self.marks[key] == self.stamp)
    }

    /// An occurrence's class; an instance is its own.
    fn class(&self, classes: &Classes, m: FMember) -> FMember {
        if m.0 < self.occurrences {
            FMember(classes.of(OccId::new(m.0)).get())
        } else {
            m
        }
    }

    fn same(&self, classes: &Classes, x: FMember, y: FMember) -> bool {
        if x.0 < self.occurrences && y.0 < self.occurrences {
            classes.same(OccId::new(x.0), OccId::new(y.0))
        } else {
            x == y
        }
    }

    /// A first-order search keys its sequents by instance
    /// ([`Zone::keys`]), not by occurrence.
    fn memoizes(&self, _: &Set, _: &Members) -> bool {
        false
    }

    /// A pool of its own: the members are no words.
    fn word_lists(pools: &mut Pools<Self>) -> &mut Vec<Pooled<OccId>> {
        &mut pools.words
    }

    fn listed(_: &[OccId]) -> Option<&[FMember]> {
        None
    }

    fn mark(&self) -> Mark {
        Mark {
            spans: self.spans.len(),
            frames: self.frames.len(),
            vars: self.vars.len(),
            eigens: self.eigens,
            trail: self.trail.len(),
            introduced: self.introduced.len(),
        }
    }

    fn undo(&mut self, mark: Mark) {
        while self.trail.len() > mark.trail {
            match self.trail.pop().expect("longer than the mark") {
                Undone::Bound(v) => {
                    if let Var::Meta { binding, .. } = &mut self.vars[v as usize] {
                        *binding = None;
                    }
                }
                Undone::Lowered(v, old) => {
                    if let Var::Meta { level, .. } = &mut self.vars[v as usize] {
                        *level = old;
                    }
                }
                Undone::Named(v) => self.named[v as usize] = Named::Unknown,
            }
        }
        self.spans.truncate(mark.spans);
        self.frames.truncate(mark.frames);
        self.vars.truncate(mark.vars);
        self.named.truncate(mark.vars);
        self.eigens = mark.eigens;
        // The nodes built since took theirs already.
        self.introduced.truncate(mark.introduced);
    }

    fn begin_level(&mut self) {
        self.cut = None;
    }

    fn cut(&self) -> Option<Reason> {
        self.cut
    }

    fn forall(&mut self, forest: &Forest, binder: FMember) -> Result<Option<FMember>, Reason> {
        if self.full() {
            return Ok(None);
        }
        let number = self.eigens;
        let term = self.push_var(Var::Eigen(number))?;
        self.eigens += 1;
        self.introduced.push(Eigen::new(number));
        self.open(forest, binder, term).map(Some)
    }

    fn introduced(&mut self) -> Eigen {
        self.introduced
            .pop()
            .expect("an eigenvariable per `∀` step")
    }

    fn exists(
        &mut self,
        forest: &Forest,
        binder: FMember,
    ) -> Result<Option<(FMember, FoTermId)>, Reason> {
        if self.full() {
            return Ok(None);
        }
        let term = self.push_var(Var::Meta {
            binding: None,
            level: self.eigens,
        })?;
        let body = self.open(forest, binder, term)?;
        Ok(Some((body, FoTermId::new(term.id))))
    }

    fn opposite(&self, forest: &Forest, p: FMember, q: FMember) -> bool {
        let (p, q) = (self.occurrence(p), self.occurrence(q));
        let (Some(a), Some(s), Some(b), Some(t)) = (
            forest.atom(p),
            forest.sign(p),
            forest.atom(q),
            forest.sign(q),
        ) else {
            return false;
        };
        if s == t {
            return false;
        }
        let fo = &forest.sequent().fo;
        match (fo.atoms.get(a.index()), fo.atoms.get(b.index())) {
            (Some(&(x, _)), Some(&(y, _))) => x == y,
            _ => a == b,
        }
    }

    fn unify(&mut self, forest: &Forest, p: FMember, q: FMember) -> Unified {
        self.unifications += 1;
        let fo = &forest.sequent().fo;
        let ((o, f), (r, g)) = (self.instance(p), self.instance(q));
        let (Some(a), Some(b)) = (forest.atom(o), forest.atom(r)) else {
            return Unified::No;
        };
        if let (Some(&(_, xs)), Some(&(_, ys))) = (fo.atoms.get(a.index()), fo.atoms.get(b.index()))
        {
            self.pairs.clear();
            self.pairs
                .extend(fo.list(xs).iter().zip(fo.list(ys)).map(|(&x, &y)| {
                    (
                        TRef {
                            id: x.get(),
                            frame: f,
                        },
                        TRef {
                            id: y.get(),
                            frame: g,
                        },
                    )
                }));
            let found = self.unify_pairs(fo);
            if found != Unified::Yes {
                return found;
            }
        } else if a != b {
            return Unified::No;
        }
        // A replay takes the alternatives the first search took, which
        // passed the answers excluded then.
        if self.choices.replaying() || self.passes(fo) {
            Unified::Yes
        } else {
            Unified::No
        }
    }

    fn open_answers(
        &mut self,
        forest: &Forest,
        members: &mut dyn Iterator<Item = FMember>,
    ) -> bool {
        let fo = &forest.sequent().fo;
        let mut metas = Vec::new();
        let mut frames = HashSet::default();
        let mut met = HashSet::default();
        let mut walk = Vec::new();
        for m in members {
            let mut frame = self.instance(m).1;
            while frame != NONE && frames.insert(frame) {
                let (parent, term) = self.frames[frame as usize];
                walk.push(term);
                frame = parent;
            }
        }
        while let Some(t) = walk.pop() {
            self.step();
            let t = self.deref(fo, t);
            if !met.insert(t) {
                continue;
            }
            match self.var(t) {
                Some(v) => {
                    if matches!(self.vars[v as usize], Var::Meta { .. }) {
                        metas.push(v);
                    }
                }
                None if !self.closed[t.id as usize] => {
                    walk.extend(Self::app(fo, t).1.iter().map(|&a| TRef {
                        id: a.get(),
                        frame: t.frame,
                    }));
                }
                None => {}
            }
        }
        if metas.is_empty() {
            return false;
        }
        metas.sort_unstable();
        self.answers.push(Answers {
            metas,
            patterns: Vec::new(),
            first: true,
        });
        true
    }

    fn searching_first(&mut self, first: bool) {
        self.answers.last_mut().expect("answers open").first = first;
    }

    fn record(&mut self, forest: &Forest) -> usize {
        let fo = &forest.sequent().fo;
        let answers = self.answers.last().expect("answers open");
        let pattern = self.pattern(fo, &answers.metas);
        let bytes = size_of::<Pattern>()
            + pattern.nodes.len() * size_of::<Pat>()
            + (pattern.kids.len() + pattern.roots.len() + pattern.levels.len()) * size_of::<u32>();
        self.answers
            .last_mut()
            .expect("answers open")
            .patterns
            .push(pattern);
        bytes
    }

    fn exhausted(&mut self, forest: &Forest) -> bool {
        let fo = &forest.sequent().fo;
        let answers = self.answers.last().expect("answers open");
        answers
            .patterns
            .iter()
            .any(|p| self.instance_of(fo, &answers.metas, p))
    }

    fn close_answers(&mut self) {
        self.answers.pop();
    }

    fn keys(
        &mut self,
        forest: &Forest,
        theta: &Set,
        gamma: &Members,
        own: &mut Vec<OccId>,
        canonical: &mut Vec<OccId>,
    ) -> bool {
        self.write_keys(forest, theta, gamma, own, canonical)
    }

    /// Whether an answer is excluded while its first premise is searched.
    fn excluding(&self) -> bool {
        self.answers
            .iter()
            .any(|answers| answers.first && !answers.patterns.is_empty())
    }

    fn take_steps(&mut self) -> u64 {
        std::mem::take(self.steps.get_mut())
    }

    fn counts(&self) -> (u64, u64) {
        (self.unifications, self.bindings)
    }

    /// The tables and the walks' buffers by their capacities; a hash
    /// table's entries as its slots and a control byte each.
    fn held(&mut self) -> (usize, usize) {
        let entries = |slots: usize, size: usize| slots * (size + 1);
        let held = bytes_of(&self.spans)
            + bytes_of(&self.frames)
            + bytes_of(&self.vars)
            + bytes_of(&self.trail)
            + bytes_of(&self.introduced)
            + bytes_of(&self.pairs)
            + bytes_of(&self.walk)
            + self.key.bytes()
            + entries(self.met.capacity(), size_of::<(TRef, TRef)>())
            + entries(self.depths.capacity(), size_of::<(TRef, u32)>())
            + entries(self.ground.capacity(), size_of::<((Head, u32), u32)>())
            + bytes_of(&self.named)
            + bytes_of(&self.naming)
            + bytes_of(&self.names)
            + self.choices.bytes();
        (std::mem::replace(&mut self.charged, held), held)
    }

    fn close(&self, forest: &Forest, nodes: &mut [Node]) -> Result<Instances, Reason> {
        let closing = RefCell::new(Closing {
            framed: self,
            fo: &forest.sequent().fo,
            table: Instances::new(forest),
            terms: HashMap::default(),
            frames: HashMap::default(),
            members: HashMap::default(),
            fresh: HashMap::default(),
        });
        for node in nodes.iter_mut() {
            let renamed = node.renamed(|m| -> Result<Member, Reason> {
                Ok(closing.borrow_mut().member(FMember(m.get())))
            })?;
            *node = match renamed {
                Node::Exists(m, w, p) => Node::Exists(
                    m,
                    closing.borrow_mut().term(TRef {
                        id: w.get(),
                        frame: NONE,
                    }),
                    p,
                ),
                node => node,
            };
        }
        Ok(closing.into_inner().table)
    }

    fn choices(&mut self) -> &mut Choices {
        &mut self.choices
    }
}

/// The closing of a proof: its instance table as it is built, and what
/// it gave each term, frame, member and unbound metavariable.
struct Closing<'a> {
    /// The search.
    framed: &'a Framed,
    /// The sequent's tables.
    fo: &'a FirstOrder,
    /// The table.
    table: Instances,
    /// What each term became.
    terms: HashMap<TRef, FoTermId>,
    /// What each frame became.
    frames: HashMap<u32, FrameId>,
    /// What each member past the forest became.
    members: HashMap<u32, Member>,
    /// The fresh constant of each unbound metavariable.
    fresh: HashMap<u32, Eigen>,
}

impl Closing<'_> {
    /// The table's term for a term as the search's bindings left it.
    fn term(&mut self, t: TRef) -> FoTermId {
        let framed = self.framed;
        let mut walk = vec![(t, false)];
        while let Some((u, expanded)) = walk.pop() {
            let u = framed.deref(self.fo, u);
            if !expanded && self.terms.contains_key(&u) {
                continue;
            }
            let id = if let Some(v) = framed.var(u) {
                let eigen = match framed.vars[v as usize] {
                    Var::Eigen(number) => Eigen::new(number),
                    Var::Meta { .. } => {
                        // A constant outside the signature that no `∀`
                        // step introduces: the eigenvariables past every
                        // one the search made.
                        let next = framed.eigens.saturating_add(self.fresh.len() as u32);
                        *self.fresh.entry(v).or_insert(Eigen::new(next))
                    }
                };
                self.table.eigen(eigen)
            } else if framed.closed[u.id as usize] {
                FoTermId::new(u.id)
            } else {
                let (symbol, args) = Framed::app(self.fo, u);
                let child = |a: &FoTermId| TRef {
                    id: a.get(),
                    frame: u.frame,
                };
                if !expanded {
                    walk.push((u, true));
                    walk.extend(args.iter().map(|a| (child(a), false)));
                    continue;
                }
                let ids: Vec<FoTermId> = args
                    .iter()
                    .map(|a| self.terms[&framed.deref(self.fo, child(a))])
                    .collect();
                self.table.apply(symbol, &ids)
            };
            self.terms.insert(u, id);
        }
        self.terms[&framed.deref(self.fo, t)]
    }

    /// The table's frame for a frame of the search.
    fn frame(&mut self, frame: u32) -> FrameId {
        let mut chain = Vec::new();
        let mut f = frame;
        while f != NONE && !self.frames.contains_key(&f) {
            chain.push(f);
            f = self.framed.frames[f as usize].0;
        }
        for &f in chain.iter().rev() {
            let (parent, term) = self.framed.frames[f as usize];
            let parent = (parent != NONE).then(|| self.frames[&parent]);
            let term = self.term(term);
            let id = self.table.frame(parent, term);
            self.frames.insert(f, id);
        }
        self.frames[&frame]
    }

    /// The table's member for a member of the search.
    fn member(&mut self, m: FMember) -> Member {
        if m.0 < self.framed.occurrences {
            return Member::new(m.0);
        }
        if let Some(&member) = self.members.get(&m.0) {
            return member;
        }
        let (o, frame) = self.framed.instance(m);
        let frame = self.frame(frame);
        let member = self.table.member(o, frame);
        self.members.insert(m.0, member);
        member
    }
}

/// A linear zone of a first-order search: its members in ascending
/// order, with repeats.
#[derive(Clone, Debug, Default)]
pub(super) struct Members(Vec<FMember>);

impl Linear<FMember> for Members {
    fn empty(_: &Forest) -> Self {
        Self(Vec::new())
    }

    fn insert(&mut self, m: FMember) {
        let at = self.0.partition_point(|&x| x <= m);
        self.0.insert(at, m);
    }

    fn remove(&mut self, m: FMember) {
        let at = self.0.binary_search(&m).expect("a member");
        self.0.remove(at);
    }

    fn contains(&self, m: FMember) -> bool {
        self.0.binary_search(&m).is_ok()
    }

    fn clear(&mut self) {
        self.0.clear();
    }

    fn copy_from(&mut self, other: &Self) {
        self.0.clone_from(&other.0);
    }

    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn iter(&self) -> impl Iterator<Item = FMember> + '_ {
        self.0.iter().copied()
    }

    fn list_into(&self, list: &mut Vec<FMember>) {
        list.extend_from_slice(&self.0);
    }

    fn ground(&self) -> &Context {
        unreachable!("a first-order search keys no sequent by occurrence")
    }
}

/// An unrestricted zone of a first-order search: its members in
/// ascending order, each once, and the empty set of occurrences its
/// interning reads.
#[derive(Clone, Debug)]
pub(super) struct Set(Vec<FMember>, OccSet);

impl Unrestricted<FMember> for Set {
    fn empty(_: &Forest) -> Self {
        Self(Vec::new(), OccSet::empty(0))
    }

    fn insert(&mut self, m: FMember) {
        if let Err(at) = self.0.binary_search(&m) {
            self.0.insert(at, m);
        }
    }

    fn contains(&self, m: FMember) -> bool {
        self.0.binary_search(&m).is_ok()
    }

    fn clear(&mut self) {
        self.0.clear();
    }

    fn copy_from(&mut self, other: &Self) {
        self.0.clone_from(&other.0);
    }

    fn iter(&self) -> impl Iterator<Item = FMember> + '_ {
        self.0.iter().copied()
    }

    /// The empty set: a first-order search keys its sequents by instance,
    /// and its table of zones keeps none, so it gives every zone a new id
    /// without reading it.
    fn ground(&self) -> &OccSet {
        &self.1
    }
}