deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Cut elimination on proof terms.
//!
//! [`step`] reduces one cut, the caller's or the strategy's, and says
//! which cut and by which case. [`eliminate`] takes steps by the strategy
//! until no cut is left or a bound is reached.
//!
//! Every proof a step makes lives over the forest of the proof it was
//! made from, and every cut it makes is on an occurrence of the cut
//! formula's tree: a key case cuts the subformulas of the formula cut,
//! and the other cases cut the occurrence they were given. A step copies
//! nothing in the forest. A contraction or a commutation over `&` makes a
//! second cut of a subproof that both cuts share, and a copy of a box
//! shares the box's subproof, as the arena shares any subproof.
//!
//! The exponentials are those of the dyadic calculus: a `?` step moves
//! its formula into the unrestricted zone, and a copy uses it from there.
//! So a box `!A` cut against a `?A⊥` that a `?` step took into the zone
//! moves up the other premise with that step. On its way:
//! - at a copy of `A⊥` it is a *dereliction*: the box's content is cut
//!   against the copy's premise;
//! - it is a *contraction* where that premise still uses `A⊥`: the
//!   content is cut, and the box is kept for the uses above;
//! - a box it meets, it enters;
//! - a subproof that does not use `A⊥` *weakens* the box away.
//!
//! At first order a member is an instance: an occurrence under binders,
//! with the terms they were opened with. The cases read members through
//! the proof's instance table and are the propositional ones, with one
//! more key case: `∀x.A` against `∃x.A⊥` with the witness `t` cuts `A`
//! with `t` for `x`, and substitutes the witness for the eigenvariable
//! throughout the `∀` premise. A subproof shared under the cut is
//! substituted in a copy. A `∀` step that a step remakes while the proof
//! still reads the original elsewhere gets an eigenvariable of its own, so
//! every eigenvariable stays introduced by one step.
//!
//! A step is checked, not trusted. [`step`] returns a proof the checker
//! accepts for the same conclusion in the mode it was given, and
//! [`eliminate`] checks every proof it reaches before its next step, and
//! the last one before it returns.

use crate::Error;
use crate::hash::{HashMap, HashSet};
use crate::limits::{Limits, Phase, Progress, Refusal};
use crate::linear::fragment::Mode;
use crate::linear::occurrences::{Forest, Member, OccId, Reading, Side};
use crate::linear::proofs::check::{self, Allowance, CheckError, Facts, Observer, State};
use crate::linear::proofs::multiset::Multiset;
use crate::linear::proofs::{Branch, Node, NodeId, Proof};
use crate::linear::sequents::{Eigen, FoTermId};

/// How an elimination proceeds and when it stops.
///
/// # JSON
///
/// With the feature `serialize` an object of the fields, the bounds a
/// number or `null`; a missing field takes its default and a misspelt one
/// is refused.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct Options {
    /// Which cut a step reduces when the caller names none.
    pub strategy: Strategy,
    /// The most steps [`eliminate`] takes.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub steps: Option<u64>,
    /// The most nodes a proof made by a step may have. On a proof net
    /// ([`nets::cut`](crate::linear::nets::cut)), the most vertices a net
    /// made by a step may have.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub nodes: Option<u64>,
    /// For a front end that draws every step of an elimination, on a proof
    /// or on a net, the most bytes those drawings take together. Past it,
    /// the steps are taken undrawn. The library draws none itself.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub drawn_bytes: Option<u64>,
}

impl Options {
    /// The default bound on steps: ten thousand.
    pub const DEFAULT_STEPS: u64 = 10_000;
    /// The default bound on a proof's nodes: a hundred thousand, which is
    /// 1.6 MB of arena.
    pub const DEFAULT_NODES: u64 = 100_000;
    /// The default bound on the bytes the drawings of an elimination's
    /// steps take together: 256 MiB, four drawings at the default bound on
    /// one drawing.
    pub const DEFAULT_DRAWN_BYTES: u64 = 256 << 20;

    /// Returns the options with another [`strategy`](Self::strategy).
    #[must_use]
    pub const fn with_strategy(self, strategy: Strategy) -> Self {
        Self { strategy, ..self }
    }

    /// Returns the options with another bound on [`steps`](Self::steps).
    #[must_use]
    pub const fn with_steps(self, steps: Option<u64>) -> Self {
        Self { steps, ..self }
    }

    /// Returns the options with another bound on [`nodes`](Self::nodes).
    #[must_use]
    pub const fn with_nodes(self, nodes: Option<u64>) -> Self {
        Self { nodes, ..self }
    }

    /// Returns the options with another bound on
    /// [`drawn_bytes`](Self::drawn_bytes).
    #[must_use]
    pub const fn with_drawn_bytes(self, drawn_bytes: Option<u64>) -> Self {
        Self {
            drawn_bytes,
            ..self
        }
    }
}

impl Default for Options {
    /// The strategy [`Strategy::Topmost`] within
    /// [`DEFAULT_STEPS`](Self::DEFAULT_STEPS),
    /// [`DEFAULT_NODES`](Self::DEFAULT_NODES) and
    /// [`DEFAULT_DRAWN_BYTES`](Self::DEFAULT_DRAWN_BYTES).
    fn default() -> Self {
        Self {
            strategy: Strategy::default(),
            steps: Some(Self::DEFAULT_STEPS),
            nodes: Some(Self::DEFAULT_NODES),
            drawn_bytes: Some(Self::DEFAULT_DRAWN_BYTES),
        }
    }
}

/// Which cut a step reduces when the caller names none.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum Strategy {
    /// The cut that comes first in the proof's arena, so that no cut
    /// stands above it. Its steps, and those of the cuts they make, each
    /// work on a smaller formula or between smaller premises. That is the
    /// classical argument that elimination ends.
    #[default]
    Topmost,
}

impl Strategy {
    /// Returns the cut of `proof` the strategy reduces next, or `None`
    /// for a cut-free proof.
    pub fn pick(self, proof: &Proof) -> Option<NodeId> {
        match self {
            Self::Topmost => proof
                .ids()
                .find(|&id| matches!(proof.node(id), Node::Cut(..))),
        }
    }
}

/// What a step did to the cut it reduced, by the usual name of the case.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "snake_case")
)]
pub enum Case {
    /// A premise is an axiom on the cut formula: the other premise takes
    /// the axiom's other literal in its place.
    Axiom,
    /// `A ⊗ B` against `A⊥ ⅋ B⊥`: two cuts, on `A` and on `B`.
    TensorPar,
    /// `1` against `⊥`: the `⊥` premise's own premise.
    OneBot,
    /// `A & B` against `A⊥ ⊕ B⊥`: one cut, on the subformula the `⊕`
    /// chose.
    WithPlus,
    /// A weakened formula. A box cut against a `?A⊥` that the rest of the
    /// subproof does not use, or that a `?w` brought in, is erased. In
    /// affine mode a weakened cut formula erases the other premise, whose
    /// formulas are weakened in.
    Weakening,
    /// A box cut against the last copy of `A⊥`: the box's content cut
    /// against the copy's premise.
    Dereliction,
    /// A box cut against a copy of `A⊥` whose premise uses `A⊥` again: the
    /// box's content is cut against the copy's premise, and the box kept
    /// for the other uses. Or a box cut against a rule both of whose
    /// premises use `A⊥`: the box is cut against each premise.
    Contraction,
    /// A box cut against a box whose content uses `A⊥`: the cut enters
    /// that box.
    BoxIntoBox,
    /// `∀x.A` against `∃x.A⊥` with the witness `t`: one cut, on `A` with
    /// `t` for `x`, and the witness substituted for the `∀` step's
    /// eigenvariable throughout its premise.
    ForallExists,
    /// The cut moves above a rule of one premise that does not act on the
    /// cut formula: into the premise of that rule that holds the formula,
    /// or into both premises of a `&`. At a `⊤`, which absorbs the cut
    /// formula, the cut and the other premise are gone.
    Commutative,
}

impl Case {
    /// Every case, in the order of declaration.
    pub const ALL: &'static [Self] = &[
        Self::Axiom,
        Self::TensorPar,
        Self::OneBot,
        Self::WithPlus,
        Self::Weakening,
        Self::Dereliction,
        Self::Contraction,
        Self::BoxIntoBox,
        Self::ForallExists,
        Self::Commutative,
    ];

    /// Returns the case's name as a phrase: `the axiom case`, `the key
    /// case of ⊗ and ⅋`, `weakening`, `a box entering a box`, `the key
    /// case of ∀ and ∃`, …
    pub const fn name(self) -> &'static str {
        match self {
            Self::Axiom => "the axiom case",
            Self::TensorPar => "the key case of ⊗ and ⅋",
            Self::OneBot => "the key case of 1 and ⊥",
            Self::WithPlus => "the key case of & and ⊕",
            Self::Weakening => "weakening",
            Self::Dereliction => "dereliction",
            Self::Contraction => "contraction",
            Self::BoxIntoBox => "a box entering a box",
            Self::ForallExists => "the key case of ∀ and ∃",
            Self::Commutative => "a commutative case",
        }
    }
}

/// One step of an elimination: which cut it reduced and how.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Step {
    /// The cut reduced, a node of the proof the step was taken on.
    pub cut: NodeId,
    /// The occurrence of the cut formula it cut.
    pub formula: Member,
    /// The case.
    pub case: Case,
    /// The node of the proof the step was taken on where the step acted
    /// besides the cut, if any: the rule a commutative case moved the cut
    /// above, the copy a dereliction or a contraction opened, or the box
    /// that a box entered.
    pub above: Option<NodeId>,
}

/// A step and the proof it made.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Reduction {
    /// The proof after the step, over the same forest and of the same
    /// conclusion, which the checker accepted in the step's mode.
    pub proof: Proof,
    /// What the step did.
    pub step: Step,
}

/// Why an elimination ended.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum End {
    /// No cut is left.
    CutFree,
    /// A bound or the stop ended it, with the proof reached so far.
    Refused(Refusal),
}

/// The outcome of an elimination: the last proof it reached, the steps
/// that led there and why it ended.
///
/// # JSON
///
/// With the feature `serialize`, written only: `{"version": 6, "proof":
/// {…}, "steps": [{"cut": 7, "formula": 9, "case": "tensor_par"}, …],
/// "end": "cut_free"}`.
/// - `proof` is in [`Proof`]'s form without `version`.
/// - Each step's `cut` is a node of the proof it was taken on, `formula`
///   the occurrence it cut, `case` the [`Case`] in snake case, and
///   `above` the node [`Step::above`] names, where there is one.
/// - `end` is `cut_free`, or `refused` with `reason`, the refusal in an
///   error's form.
///
/// The wire level in `version` is the proof's: 6 for a sequent with cut
/// formulas ([`wire`](crate::wire)).
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Elimination {
    /// The last proof reached, which the checker accepted: cut-free when
    /// the elimination ended at [`End::CutFree`].
    pub proof: Proof,
    /// The steps taken, in order, each on the proof the step before made.
    pub steps: Vec<Step>,
    /// Why the elimination ended.
    pub end: End,
}

/// Reduces one cut of `proof`: the one at `at`, or the one the strategy
/// of `options` picks.
///
/// It checks the proof in `mode`, takes the step and checks the proof the
/// step made, each check within `limits` and asking `stop`.
/// [`eliminate`] takes such steps until no cut is left.
///
/// # Errors
///
/// - The checker's error for a proof that is not one in `mode`.
/// - [`Error::NoCut`] for an `at` that is no cut, or a proof without one.
/// - [`Refusal::Elimination`] for a proof made past `options.nodes`, and
///   the refusals of the checks.
/// - [`Error::Reduction`] where the checker refuses the proof made: a
///   defect of this crate.
pub fn step(
    proof: &Proof,
    mode: Mode,
    at: Option<NodeId>,
    options: &Options,
    limits: &Limits,
    mut stop: impl FnMut(Progress) -> bool,
) -> Result<Reduction, Error> {
    let record = Record::of(proof, mode, limits, &mut stop).map_err(Error::Check)?;
    let cut = match at {
        Some(at) if matches!(proof.nodes().get(at.index()), Some(Node::Cut(..))) => at,
        Some(at) => {
            return Err(Error::NoCut {
                node: Some(at.get()),
            });
        }
        None => options
            .strategy
            .pick(proof)
            .ok_or(Error::NoCut { node: None })?,
    };
    let (made, step) =
        reduce(proof, &record, mode, cut, options, limits, &mut stop).map_err(Error::Refused)?;
    let reading = check::reading(&made, mode).map_err(Error::Check)?;
    let allowance = Allowance::new(limits, Phase::Eliminate, &mut stop);
    match check::examine(
        &made,
        &made.conclusion(),
        mode,
        reading.as_ref(),
        allowance,
        &mut (),
    ) {
        Ok(()) => Ok(Reduction { proof: made, step }),
        Err(refused @ CheckError::Refused(_)) => Err(Error::Check(refused)),
        Err(invalid) => Err(Error::Reduction(Box::new(invalid))),
    }
}

/// Eliminates the cuts of `proof` step by step, until none is left or a
/// bound or `stop` ends the elimination.
///
/// The first step reduces the cut at `at` where one is given; every other
/// step reduces the cut the strategy of `options` picks. When a bound of
/// `options` or `limits`, or `stop`, ends the elimination, the proof
/// reached is returned with its cuts and the refusal that ended it.
///
/// Every proof reached is checked in `mode` before the next step is taken
/// on it, and the last one before it is returned. `each` gets every step,
/// with the proof it was taken on, once the proof the step made has
/// passed its check: a caller draws every step there. `limits` bound each
/// check. `stop` is asked between steps and by the checks.
///
/// # Examples
///
/// A proof of `a ⊢ a` with a cut on `a`, made in a session, loses its cut
/// in one step:
///
#[cfg_attr(all(feature = "parse", feature = "interactive"), doc = "```")]
#[cfg_attr(
    not(all(feature = "parse", feature = "interactive")),
    doc = "```ignore"
)]
/// use deduxit::Limits;
/// use deduxit::linear::proofs::cut::{self, Case, End};
/// use deduxit::linear::{CutFormula, InputOptions, Interactive, Mode, Options, Sequent, ViewOptions};
///
/// let (mode, limits) = (Mode::CLASSICAL, Limits::default());
/// let sequent: Sequent = "a |- a".parse()?;
/// let mut session = Interactive::new(&sequent, mode)?;
/// let goal = session.goals().next().unwrap();
/// let formula = CutFormula::parse_within("a", mode, &InputOptions::default(), &limits)?;
/// session.cut(goal, &formula, &[0], &limits)?;
/// // The closures `|_| false` never stop.
/// session.close_all(&Options::default(), &ViewOptions::default(), &limits, |_| false);
/// let proof = session.proof(&limits, |_| false)?;
/// assert!(!proof.is_cut_free());
///
/// let options = cut::Options::default();
/// let done = cut::eliminate(&proof, mode, None, &options, &limits, |_| false, |_, _| {})?;
/// assert_eq!(done.end, End::CutFree);
/// assert!(done.proof.is_cut_free());
/// let cases: Vec<Case> = done.steps.iter().map(|step| step.case).collect();
/// assert_eq!(cases, [Case::Axiom]);
/// # Ok::<(), deduxit::Error>(())
/// ```
///
/// # Errors
///
/// - The checker's error for a proof that is not one in `mode`, or its
///   refusal of the first check.
/// - [`Error::NoCut`] for an `at` that is no cut.
/// - [`Error::Reduction`] where the checker refuses a proof a step made:
///   a defect of this crate.
pub fn eliminate(
    proof: &Proof,
    mode: Mode,
    at: Option<NodeId>,
    options: &Options,
    limits: &Limits,
    mut stop: impl FnMut(Progress) -> bool,
    mut each: impl FnMut(&Proof, &Step),
) -> Result<Elimination, Error> {
    let mut steps: Vec<Step> = Vec::new();
    // The proof reached last, and the one before it: while the latest
    // waits for its check, that one is the last proof checked.
    let mut current = proof.clone();
    let mut checked: Option<Proof> = None;
    loop {
        let ended = |proof: Proof, steps: Vec<Step>, refusal: Refusal| Elimination {
            proof,
            steps,
            end: End::Refused(refusal),
        };
        let record = match Record::of(&current, mode, limits, &mut stop) {
            Ok(record) => record,
            Err(CheckError::Refused(refused)) => {
                let Some(checked) = checked else {
                    return Err(Error::Check(CheckError::Refused(refused)));
                };
                // The latest proof is unchecked, so the one before it is
                // the proof reached, and the step that made the latest is
                // dropped.
                steps.pop();
                return Ok(ended(checked, steps, refused.refusal));
            }
            Err(invalid) if checked.is_none() => return Err(Error::Check(invalid)),
            Err(invalid) => return Err(Error::Reduction(Box::new(invalid))),
        };
        if let (Some(before), Some(last)) = (&checked, steps.last()) {
            each(before, last);
        }
        let cut = match at.filter(|_| steps.is_empty()) {
            Some(at) if matches!(current.nodes().get(at.index()), Some(Node::Cut(..))) => Some(at),
            Some(at) => {
                return Err(Error::NoCut {
                    node: Some(at.get()),
                });
            }
            None => options.strategy.pick(&current),
        };
        let Some(cut) = cut else {
            return Ok(Elimination {
                proof: current,
                steps,
                end: End::CutFree,
            });
        };
        if let Some(limit) = options.steps
            && steps.len() as u64 >= limit
        {
            let refusal = Refusal::Elimination {
                what: crate::limits::Bound::Steps,
                limit,
            };
            return Ok(ended(current, steps, refusal));
        }
        if stop(Progress::new(Phase::Eliminate, 1, steps.len() as u64)) {
            let refusal = Refusal::Stopped {
                phase: Phase::Eliminate,
            };
            return Ok(ended(current, steps, refusal));
        }
        match reduce(&current, &record, mode, cut, options, limits, &mut stop) {
            Ok((made, step)) => {
                steps.push(step);
                checked = Some(std::mem::replace(&mut current, made));
            }
            Err(refusal) => return Ok(ended(current, steps, refusal)),
        }
    }
}

/// What a step reads of the checker's pass over a proof: whether each
/// node's subproof absorbs any context through a `⊤`, and the linear zone
/// of every premise of a `⊗`, a Mix or a cut.
struct Record {
    /// Whether a `⊤` in a node's subproof absorbs any context.
    absorbs: Vec<bool>,
    /// Whether a node is a premise of a `⊗`, a Mix or a cut.
    kept: Vec<bool>,
    /// The linear zones of the kept nodes.
    zones: HashMap<NodeId, Multiset<Member>>,
    /// The bytes of the zones kept so far; it saturates.
    held: u64,
}

impl Record {
    /// What a kept zone takes besides its members.
    const ENTRY: u64 = 96;

    /// Checks `proof` in `mode` within `limits` and returns what the check
    /// derived, or the checker's error.
    fn of(
        proof: &Proof,
        mode: Mode,
        limits: &Limits,
        stop: &mut dyn FnMut(Progress) -> bool,
    ) -> Result<Self, CheckError> {
        let len = proof.nodes().len();
        let mut kept = vec![false; len];
        for id in proof.ids() {
            if let node @ (Node::Tensor(..) | Node::Mix(..) | Node::Cut(..)) = proof.node(id) {
                for p in node.premises() {
                    kept[p.index()] = true;
                }
            }
        }
        let mut record = Self {
            absorbs: vec![false; len],
            kept,
            zones: HashMap::default(),
            held: 0,
        };
        let reading = check::reading(proof, mode)?;
        check::examine(
            proof,
            &proof.conclusion(),
            mode,
            reading.as_ref(),
            Allowance::new(limits, Phase::Eliminate, stop),
            &mut record,
        )?;
        Ok(record)
    }

    /// Returns the linear zone the checker derived for a premise of a
    /// `⊗`, a Mix or a cut.
    fn zone(&self, id: NodeId) -> &Multiset<Member> {
        &self.zones[&id]
    }
}

impl Observer for Record {
    fn bytes(&self) -> u64 {
        // Two flags for each of fewer than 2³² nodes, and the zones.
        self.held.saturating_add(self.kept.len() as u64 * 2)
    }

    fn derived(&mut self, id: NodeId, state: &State, _: &Facts<'_>) {
        self.absorbs[id.index()] = state.absorbs();
        if self.kept[id.index()] {
            let zone = Multiset::of(
                state
                    .linear()
                    .flat_map(|(m, n)| std::iter::repeat_n(m, n as usize)),
            );
            let bytes = (zone.as_slice().len() as u64).saturating_mul(4);
            self.held = self.held.saturating_add(Self::ENTRY).saturating_add(bytes);
            self.zones.insert(id, zone);
        }
    }
}

/// Reduces the cut at `cut` of a checked proof whose record is `record`,
/// and returns the proof made, not yet checked, and the step.
///
/// Fails with the refusal of a proof past the bounds, or of `stop`, which
/// the specialized erasure and, at first order, the renaming of twin
/// eigenvariables ask.
fn reduce(
    proof: &Proof,
    record: &Record,
    mode: Mode,
    cut: NodeId,
    options: &Options,
    limits: &Limits,
    stop: &mut dyn FnMut(Progress) -> bool,
) -> Result<(Proof, Step), Refusal> {
    // The proof was checked in `mode`, so it has a reading there.
    let reading = check::reading(proof, mode).unwrap_or_default();
    let most = options
        .nodes
        .map_or(usize::MAX, |n| usize::try_from(n).unwrap_or(usize::MAX));
    let mut rewrite = Rewrite {
        proof,
        forest: proof.forest(),
        record,
        reading,
        nodes: proof.nodes().to_vec(),
        overflowed: false,
        table: framed::Table::of(proof),
        most,
        memory: limits.memory_bytes,
    };
    // Every propositional rewrite but the specialized erasure adds fewer
    // nodes than the proof has for each of its passes. So only that one is
    // bounded on the way, by the nodes, the memory and the stop. At first
    // order a copy of a subproof is charged before it is made
    // (`Rewrite::afford`). The proof made is measured after.
    let (made, step) = rewrite.reduce(cut, mode)?;
    let mut root = match made {
        Made::Subproof(replacement) => rewrite.replace(cut, replacement, proof.root()),
        Made::Erasure { kept, proved } => {
            rewrite.specialize(cut, kept, &proved, most, limits.memory_bytes, stop)?
        }
    };
    rewrite.within_ids()?;
    let mut instances = None;
    if rewrite.table.is_some() {
        root = rewrite.apart(root, stop)?;
        instances = Some(rewrite.compact(root));
    }
    let nodes = rewrite.nodes;
    let forest = proof.forest.clone();
    let made = match instances {
        None => Proof::new(forest, nodes, root),
        Some(instances) => Proof::with_instances(forest, instances, nodes, root),
    }
    .map_err(|error| match error {
        Error::Refused(refusal) => refusal,
        error => unreachable!("a rewrite keeps the arena's order and the table: {error}"),
    })?;
    let count = made.nodes().len() as u64;
    if let Some(limit) = options.nodes
        && count > limit
    {
        return Err(Refusal::Elimination {
            what: crate::limits::Bound::Nodes,
            limit,
        });
    }
    let bytes = count.saturating_mul(size_of::<Node>() as u64);
    if let Some(limit) = limits.memory_bytes
        && bytes > limit
    {
        return Err(Refusal::Memory {
            phase: Phase::Eliminate,
            limit_bytes: limit,
            needed_bytes: Some(bytes),
        });
    }
    let made = Proof {
        goal: proof.goal.clone(),
        mode: Some(mode),
        ..made
    };
    Ok((made, step))
}

/// What a reduction makes of its cut.
enum Made {
    /// A subproof of the cut's conclusion, which takes the cut's place
    /// wherever the proof reads it.
    Subproof(NodeId),
    /// Over `kept`, which proves `proved` of the cut's context, the
    /// weakenings of the rest of that context, as each place that reads the
    /// cut gives it.
    Erasure {
        /// The subproof kept.
        kept: NodeId,
        /// What it proves.
        proved: Multiset<Member>,
    },
}

/// A proof's arena as a step rewrites it: the proof's nodes, and after
/// them the nodes the step adds. A node is never changed in place, since
/// others may share it; a changed node is a new one.
struct Rewrite<'a> {
    /// The proof the step is taken on.
    proof: &'a Proof,
    /// Its forest.
    forest: &'a Forest,
    /// What the checker derived of it.
    record: &'a Record,
    /// The intuitionistic reading, in an intuitionistic mode.
    reading: Option<Reading<'a>>,
    /// The arena.
    nodes: Vec<Node>,
    /// Whether the arena passed what a node id names, so that the step is
    /// refused rather than made of ids that alias.
    overflowed: bool,
    /// The proof's instance table and what the step adds to it, for a
    /// proof with one.
    table: Option<framed::Table>,
    /// The most nodes the step may add to the proof's arena by copies of
    /// subproofs: the bound on a proof's nodes.
    most: usize,
    /// The most bytes the arena may take.
    memory: Option<u64>,
}

impl Rewrite<'_> {
    /// Adds a node and returns its id. The arena grows by a few times the
    /// proof's nodes at most, which [`reduce`] measures after. Past what a
    /// node id names, the id returned is a placeholder and the step is
    /// refused.
    fn push(&mut self, node: Node) -> NodeId {
        let id = match u32::try_from(self.nodes.len()) {
            Ok(id) if id < u32::MAX => id,
            _ => {
                self.overflowed = true;
                u32::MAX
            }
        };
        self.nodes.push(node);
        NodeId::new(id)
    }

    /// Returns the refusal of an arena past what a node id names.
    fn within_ids(&self) -> Result<(), Refusal> {
        if self.overflowed {
            return Err(Refusal::Index {
                what: crate::limits::Space::Node,
                count: self.nodes.len() as u64,
                most: u64::from(u32::MAX),
            });
        }
        Ok(())
    }

    /// Returns the node at `id`.
    fn node(&self, id: NodeId) -> Node {
        self.nodes[id.index()]
    }

    /// Adds the cut of `a` from `first` and `second`.
    fn cut(&mut self, a: Member, first: NodeId, second: NodeId) -> NodeId {
        self.push(Node::Cut(a, first, second))
    }

    /// Returns the occurrence a member stands for.
    fn occ(&self, m: Member) -> OccId {
        match &self.table {
            Some(table) => table.resolve(m).0,
            None => m.occ(),
        }
    }

    /// Returns the member that is the occurrence `o` under the frame of
    /// `like`, a member of an occurrence under as many binders.
    fn beside(&mut self, o: OccId, like: Member) -> Member {
        match &mut self.table {
            Some(table) => table.beside(o, like),
            None => Member::from(o),
        }
    }

    /// Returns the member of the left subformula of a connective's member.
    fn left(&mut self, m: Member) -> Member {
        let o = self.forest.left(self.occ(m)).expect("a connective");
        self.beside(o, m)
    }

    /// Returns the member of the right subformula of a binary
    /// connective's member.
    fn right(&mut self, m: Member) -> Member {
        let o = self.forest.right(self.occ(m)).expect("a binary connective");
        self.beside(o, m)
    }

    /// Returns the member of a binary connective's subformula on `side`.
    fn child(&mut self, m: Member, side: Branch) -> Member {
        match side {
            Branch::Left => self.left(m),
            Branch::Right => self.right(m),
        }
    }

    /// Returns the member of the dual of a member of a cut formula's tree.
    fn dual(&mut self, m: Member) -> Member {
        let o = self.forest.dual(self.occ(m)).expect("a cut formula's tree");
        self.beside(o, m)
    }

    /// Returns the member of the body of a binder's member, with `term`
    /// for its variable.
    fn body(&mut self, m: Member, term: FoTermId) -> Member {
        self.table
            .as_mut()
            .expect("a binder's proof has instances")
            .body(m, term)
    }

    /// Returns whether the derived zone of `id`, a premise of a `⊗`, a Mix
    /// or a cut, holds `x` beyond the occurrence `consumed` its rule takes
    /// from it.
    fn holds(&self, id: NodeId, x: Member, consumed: Option<Member>) -> bool {
        let zone = self.record.zone(id).as_slice();
        let count = zone.partition_point(|&o| o <= x) - zone.partition_point(|&o| o < x);
        count > usize::from(consumed == Some(x))
    }

    /// Returns the premise of a two-premise rule, `first` or `second`, that
    /// an occurrence `x` of its conclusion comes from: the one whose zone
    /// holds it beyond what the rule takes from it, else one whose `⊤`
    /// absorbs it ([`absorber`](Self::absorber)).
    fn holder(
        &self,
        x: Member,
        first: (NodeId, Option<Member>),
        second: (NodeId, Option<Member>),
    ) -> Branch {
        if self.holds(first.0, x, first.1) {
            Branch::Left
        } else if self.holds(second.0, x, second.1) {
            Branch::Right
        } else {
            self.absorber(self.is_output(x), first, second)
        }
    }

    /// Returns the premise of a two-premise rule whose `⊤` takes formulas
    /// its zone lacks: the first that absorbs any. With `output`, the
    /// formulas include one right of `⊢`, which a premise that already has
    /// a formula there cannot take.
    fn absorber(
        &self,
        output: bool,
        first: (NodeId, Option<Member>),
        second: (NodeId, Option<Member>),
    ) -> Branch {
        let takes = |(id, taken): (NodeId, Option<Member>)| {
            self.record.absorbs[id.index()] && !(output && self.has_output(id, taken))
        };
        if takes(first) || !takes(second) {
            Branch::Left
        } else {
            Branch::Right
        }
    }

    /// Returns whether an occurrence stands right of `⊢` under the reading.
    fn is_output(&self, x: Member) -> bool {
        self.reading
            .as_ref()
            .is_some_and(|reading| reading.position(self.occ(x)) == Side::Output)
    }

    /// Returns whether the sequent of `id` already has its formula right of
    /// `⊢`, in its derived zone or as the formula `taken` where a `⊤`
    /// absorbed it. `id` is a premise of a `⊗`, a Mix or a cut whose rule
    /// takes `taken` from it.
    fn has_output(&self, id: NodeId, taken: Option<Member>) -> bool {
        self.reading.is_some()
            && (self
                .record
                .zone(id)
                .as_slice()
                .iter()
                .any(|&o| self.is_output(o))
                || taken.is_some_and(|t| self.is_output(t)))
    }

    /// Returns the two premises of a two-premise node and what its rule
    /// takes from each: `None` for any other node.
    fn split(&mut self, node: Node) -> Option<[(NodeId, Option<Member>); 2]> {
        match node {
            Node::Tensor(o, p, q) => {
                let (l, r) = (self.left(o), self.right(o));
                Some([(p, Some(l)), (q, Some(r))])
            }
            Node::Cut(b, p, q) => {
                let d = self.dual(b);
                Some([(p, Some(b)), (q, Some(d))])
            }
            Node::Mix(p, q) => Some([(p, None), (q, None)]),
            _ => None,
        }
    }

    /// Reduces the cut at `cut` and returns what it makes and the step,
    /// or the refusal of a copy past the bounds.
    fn reduce(&mut self, cut: NodeId, mode: Mode) -> Result<(Made, Step), Refusal> {
        let Node::Cut(a, l, r) = self.node(cut) else {
            unreachable!("the node reduced is a cut")
        };
        let da = self.dual(a);
        let (nl, nr) = (self.node(l), self.node(r));
        let step = |case, above| Step {
            cut,
            formula: a,
            case,
            above,
        };
        if let Node::Ax(x, y) = nl {
            let other = if x == a { y } else { x };
            let made = self.rename(r, da, other);
            return Ok((Made::Subproof(made), step(Case::Axiom, None)));
        }
        if let Node::Ax(x, y) = nr {
            let other = if x == da { y } else { x };
            let made = self.rename(l, a, other);
            return Ok((Made::Subproof(made), step(Case::Axiom, None)));
        }
        if mode.affine {
            if let Node::Weaken(w, k) = nl
                && w == a
            {
                return Ok((self.erase(k, l, a, r, da), step(Case::Weakening, None)));
            }
            if let Node::Weaken(w, k) = nr
                && w == da
            {
                return Ok((self.erase(k, r, da, l, a), step(Case::Weakening, None)));
            }
        }
        if !principal(nl, a) {
            let made = self.commute(cut, Branch::Left);
            return Ok((Made::Subproof(made), step(Case::Commutative, Some(l))));
        }
        if !principal(nr, da) {
            let made = self.commute(cut, Branch::Right);
            return Ok((Made::Subproof(made), step(Case::Commutative, Some(r))));
        }
        let key = |made, case| (Made::Subproof(made), step(case, None));
        Ok(match (nl, nr) {
            (Node::Tensor(_, l1, l2), Node::Par(_, r1)) => {
                let (left, right) = (self.left(a), self.right(a));
                let inner = self.cut(right, l2, r1);
                key(self.cut(left, l1, inner), Case::TensorPar)
            }
            (Node::Par(_, l1), Node::Tensor(_, r1, r2)) => {
                let (left, right) = (self.left(a), self.right(a));
                let inner = self.cut(right, l1, r2);
                key(self.cut(left, inner, r1), Case::TensorPar)
            }
            (Node::One(_), Node::Bot(_, r1)) => key(r1, Case::OneBot),
            (Node::Bot(_, l1), Node::One(_)) => key(l1, Case::OneBot),
            (Node::With(_, l1, l2), Node::Plus(_, side, r1)) => {
                let premise = if side == Branch::Left { l1 } else { l2 };
                let child = self.child(a, side);
                key(self.cut(child, premise, r1), Case::WithPlus)
            }
            (Node::Plus(_, side, l1), Node::With(_, r1, r2)) => {
                let premise = if side == Branch::Left { r1 } else { r2 };
                let child = self.child(a, side);
                key(self.cut(child, l1, premise), Case::WithPlus)
            }
            (Node::Bang(..), Node::Weaken(_, r1)) => key(r1, Case::Weakening),
            (Node::Weaken(_, l1), Node::Bang(..)) => key(l1, Case::Weakening),
            (Node::Bang(_, l1), Node::Quest(_, r1)) => {
                let (made, case, above) = self.exponential(cut, Branch::Left, l1, r1);
                (Made::Subproof(made), step(case, above))
            }
            (Node::Quest(_, l1), Node::Bang(_, r1)) => {
                let (made, case, above) = self.exponential(cut, Branch::Right, r1, l1);
                (Made::Subproof(made), step(case, above))
            }
            (Node::Forall(_, e, l1), Node::Exists(_, w, r1)) => {
                let body = self.body(a, w);
                let l1 = self.substitute(l1, &witness(e, w))?;
                key(self.cut(body, l1, r1), Case::ForallExists)
            }
            (Node::Exists(_, w, l1), Node::Forall(_, e, r1)) => {
                let body = self.body(a, w);
                let r1 = self.substitute(r1, &witness(e, w))?;
                key(self.cut(body, l1, r1), Case::ForallExists)
            }
            (nl, nr) => unreachable!("no rule of a checked proof gives {nl} against {nr}"),
        })
    }

    /// Moves the cut at `cut` above the last rule of its premise `side`,
    /// which does not act on the cut formula, and returns the subproof
    /// made.
    fn commute(&mut self, cut: NodeId, side: Branch) -> NodeId {
        let Node::Cut(a, l, r) = self.node(cut) else {
            unreachable!("the node reduced is a cut")
        };
        let (premise, x) = match side {
            Branch::Left => (l, a),
            Branch::Right => (r, self.dual(a)),
        };
        let cut_with = |this: &mut Self, p: NodeId| match side {
            Branch::Left => this.cut(a, p, r),
            Branch::Right => this.cut(a, l, p),
        };
        let node = self.node(premise);
        if let Node::Top(_) = node {
            // The `⊤` absorbs the cut formula, and with it the other
            // premise's context.
            return premise;
        }
        if let Node::With(o, p, q) = node {
            let (p, q) = (cut_with(self, p), cut_with(self, q));
            return self.push(Node::With(o, p, q));
        }
        if let Some([(p, tp), (q, tq)]) = self.split(node) {
            let made = match self.holder(x, (p, tp), (q, tq)) {
                Branch::Left => {
                    let p = cut_with(self, p);
                    node.with_premises(p, q)
                }
                Branch::Right => {
                    let q = cut_with(self, q);
                    node.with_premises(p, q)
                }
            };
            return self.push(made);
        }
        let [p] = node.premises().collect::<Vec<_>>()[..] else {
            unreachable!("{node} acts on the cut formula or has one premise")
        };
        let p = cut_with(self, p);
        self.push(node.map_premises(|_| p))
    }

    /// Reduces the exponential cases: a box at `cut`'s premise `boxed`
    /// (`Left` for `!A` in the first premise), whose content is `content`,
    /// against the `?` step of the other premise, whose premise is
    /// `quest`. Returns the subproof made, the case and the node acted at.
    fn exponential(
        &mut self,
        cut: NodeId,
        boxed: Branch,
        content: NodeId,
        quest: NodeId,
    ) -> (NodeId, Case, Option<NodeId>) {
        let Node::Cut(a, l, r) = self.node(cut) else {
            unreachable!("the node reduced is a cut")
        };
        // The box's content proves `inside`; the other premise uses its
        // dual `x` from the unrestricted zone.
        let inside = self.left(a);
        let x = match boxed {
            Branch::Left => self.dual(inside),
            Branch::Right => inside,
        };
        let uses = self.uses(quest, x);
        // The cut of the box against the `?` step over `p`, which keeps the
        // box for the uses of `x` in `p`.
        let wrap = |this: &mut Self, p: NodeId| {
            if !uses[p.index()] {
                return p;
            }
            match boxed {
                Branch::Left => {
                    let Node::Quest(q, _) = this.node(r) else {
                        unreachable!("the other premise is a ? step")
                    };
                    let p = this.push(Node::Quest(q, p));
                    this.cut(a, l, p)
                }
                Branch::Right => {
                    let Node::Quest(q, _) = this.node(l) else {
                        unreachable!("the other premise is a ? step")
                    };
                    let p = this.push(Node::Quest(q, p));
                    this.cut(a, p, r)
                }
            }
        };
        // The cut of the box's content against a premise `p` that holds `x`.
        let open = |this: &mut Self, p: NodeId| match boxed {
            Branch::Left => this.cut(inside, content, p),
            Branch::Right => this.cut(inside, p, content),
        };
        if !uses[quest.index()] {
            return (quest, Case::Weakening, None);
        }
        let node = self.node(quest);
        match node {
            Node::Copy(o, p) if o == x => {
                if uses[p.index()] {
                    let kept = wrap(self, p);
                    (open(self, kept), Case::Contraction, Some(quest))
                } else {
                    (open(self, p), Case::Dereliction, Some(quest))
                }
            }
            Node::Bang(o, p) => {
                let p = wrap(self, p);
                (self.push(Node::Bang(o, p)), Case::BoxIntoBox, Some(quest))
            }
            Node::With(o, p, q) => {
                let (p, q) = (wrap(self, p), wrap(self, q));
                (
                    self.push(Node::With(o, p, q)),
                    Case::Commutative,
                    Some(quest),
                )
            }
            Node::Tensor(_, p, q) | Node::Mix(p, q) | Node::Cut(_, p, q) => {
                let case = if uses[p.index()] && uses[q.index()] {
                    Case::Contraction
                } else {
                    Case::Commutative
                };
                let (p, q) = (wrap(self, p), wrap(self, q));
                (self.push(node.with_premises(p, q)), case, Some(quest))
            }
            node => {
                let [p] = node.premises().collect::<Vec<_>>()[..] else {
                    unreachable!("a node that uses the zone has premises")
                };
                let p = wrap(self, p);
                (
                    self.push(node.map_premises(|_| p)),
                    Case::Commutative,
                    Some(quest),
                )
            }
        }
    }

    /// Returns, for every node up to `top`, whether its subproof uses the
    /// unrestricted occurrence `x`: whether it has a copy of `x` that no
    /// `?` step of its formula below discharges. That is when the
    /// checker's least unrestricted zone holds `x`.
    fn uses(&mut self, top: NodeId, x: Member) -> Vec<bool> {
        let quest = self.forest.parent(self.occ(x)).map(|q| self.beside(q, x));
        let mut uses = vec![false; top.index() + 1];
        for i in 0..=top.index() {
            uses[i] = match self.nodes[i] {
                Node::Copy(o, p) => o == x || uses[p.index()],
                Node::Quest(o, p) => Some(o) != quest && uses[p.index()],
                node => node.premises().any(|p| uses[p.index()]),
            };
        }
        uses
    }

    /// Returns a subproof that is the one at `top` with the occurrence of
    /// `from` in its conclusion renamed to `to`, a literal of the same
    /// atom and sign. The occurrence is followed up to the axiom (or the
    /// affine weakening) that introduces it, or the `⊤` that absorbs it,
    /// and every node on the way is made anew.
    fn rename(&mut self, top: NodeId, from: Member, to: Member) -> NodeId {
        let mut seen: HashSet<NodeId> = HashSet::default();
        // The nodes on the way, and for a `⊗`, a Mix or a cut the premise
        // the occurrence comes from: only that one is made anew, even
        // where both premises are one shared subproof.
        let mut on: Vec<(NodeId, Option<Branch>)> = Vec::new();
        let mut stack = vec![top];
        while let Some(id) = stack.pop() {
            if !seen.insert(id) {
                continue;
            }
            let node = self.node(id);
            let mut entered = None;
            match node {
                Node::Ax(..) | Node::One(_) | Node::Top(_) => {}
                Node::Weaken(o, _) if o == from => {}
                Node::With(_, p, q) => stack.extend([p, q]),
                node => match self.split(node) {
                    Some([first, second]) => {
                        let side = self.holder(from, first, second);
                        entered = Some(side);
                        stack.push(match side {
                            Branch::Left => first.0,
                            Branch::Right => second.0,
                        });
                    }
                    None => stack.extend(node.premises()),
                },
            }
            on.push((id, entered));
        }
        on.sort_unstable_by_key(|&(id, _)| id);
        let mut made: HashMap<NodeId, NodeId> = HashMap::default();
        for (id, entered) in on {
            let old = self.node(id);
            let split = entered.and_then(|_| self.split(old));
            let new = |p: NodeId| made.get(&p).copied().unwrap_or(p);
            let node = match (old, entered) {
                (Node::Ax(x, y), _) if x == from => Node::Ax(to, y),
                (Node::Ax(x, y), _) if y == from => Node::Ax(x, to),
                (Node::Weaken(o, p), _) if o == from => Node::Weaken(to, p),
                (node, Some(side)) => {
                    let [first, second] = split.expect("a rule of two premises");
                    match side {
                        Branch::Left => node.with_premises(new(first.0), second.0),
                        Branch::Right => node.with_premises(first.0, new(second.0)),
                    }
                }
                (node, None) => node.map_premises(new),
            };
            if node != old {
                let new = self.push(node);
                made.insert(id, new);
            }
        }
        made.get(&top).copied().unwrap_or(top)
    }

    /// Erases the premise `erased` of the cut, whose cut formula there is
    /// `theirs`, by the affine weakening at `weakened` of `ours` over
    /// `kept`: the erased premise's formulas are weakened over `kept`.
    ///
    /// Where the erased premise absorbs context through a `⊤` and the kept
    /// one does not, those formulas are what each place that reads the cut
    /// gives it, not only what the checker derived. That case returns
    /// [`Made::Erasure`] for [`specialize`](Self::specialize).
    fn erase(
        &mut self,
        kept: NodeId,
        weakened: NodeId,
        ours: Member,
        erased: NodeId,
        theirs: Member,
    ) -> Made {
        let mut proved = self.record.zone(weakened).clone();
        proved.remove(ours);
        if self.record.absorbs[erased.index()] && !self.record.absorbs[kept.index()] {
            return Made::Erasure { kept, proved };
        }
        let mut context = self.record.zone(erased).clone();
        context.remove(theirs);
        Made::Subproof(self.weaken(kept, &context))
    }

    /// Returns the subproof that weakens every member of `context` over
    /// the one at `kept`.
    fn weaken(&mut self, kept: NodeId, context: &Multiset<Member>) -> NodeId {
        context
            .as_slice()
            .iter()
            .fold(kept, |p, &o| self.push(Node::Weaken(o, p)))
    }

    /// Puts `replacement` in the place of the node at `at` wherever the
    /// proof at `root` reads it, making anew every node below it, and
    /// returns the root.
    fn replace(&mut self, at: NodeId, replacement: NodeId, root: NodeId) -> NodeId {
        let mut made: Vec<Option<NodeId>> = vec![None; root.index() + 1];
        made[at.index()] = Some(replacement);
        for i in at.index() + 1..=root.index() {
            let node = self.nodes[i];
            if node.premises().any(|p| made[p.index()].is_some()) {
                let node = node.map_premises(|p| made[p.index()].unwrap_or(p));
                made[i] = Some(self.push(node));
            }
        }
        made[root.index()].unwrap_or(root)
    }

    /// Erases a cut whose context only the places that read it can tell,
    /// and returns the root.
    ///
    /// Every node from the root to the cut is made anew for each exact
    /// conclusion it has on the way there. Each place that reads the cut
    /// gets, over `kept`, the weakenings of its own conclusion's formulas
    /// beyond `proved`.
    ///
    /// Refuses more than `most` nodes made, more than `memory` bytes held
    /// by the conclusions it keeps and the nodes it makes, and a `stop`,
    /// which it asks every 4 096 pairs.
    fn specialize(
        &mut self,
        cut: NodeId,
        kept: NodeId,
        proved: &Multiset<Member>,
        most: usize,
        memory: Option<u64>,
        stop: &mut dyn FnMut(Progress) -> bool,
    ) -> Result<NodeId, Refusal> {
        /// How many pairs pass between two polls of the stop.
        const POLL: usize = 4096;
        /// A node with an exact conclusion, and the pairs of its premises
        /// that lead to the cut.
        struct Pair {
            /// The node.
            id: NodeId,
            /// Its exact conclusion.
            zone: Multiset<Member>,
            /// The pairs of its premises, in the rule's order, where they
            /// lead to the cut.
            premises: [Option<usize>; 2],
        }
        let root = self.proof.root();
        let mut reaches = vec![false; root.index() + 1];
        reaches[cut.index()] = true;
        for i in cut.index() + 1..=root.index() {
            reaches[i] = self.nodes[i].premises().any(|p| reaches[p.index()]);
        }
        let mut pairs = vec![Pair {
            id: root,
            zone: Multiset::of(self.proof.conclusion().into_iter().map(Member::from)),
            premises: [None; 2],
        }];
        let mut index: HashMap<(NodeId, Multiset<Member>), usize> = HashMap::default();
        let mut stack = vec![0];
        let refused = || Refusal::Elimination {
            what: crate::limits::Bound::Nodes,
            limit: most as u64,
        };
        // The bytes held, saturating: eight a member, since each
        // conclusion is held twice (the pair's and the index's key) at
        // four bytes a member, and 64 a node made, for its sixteen bytes
        // and a table entry.
        let mut held: u64 = 0;
        let mut hold = |members: usize, nodes: usize| -> Result<(), Refusal> {
            held = held
                .saturating_add((members as u64).saturating_mul(8))
                .saturating_add((nodes as u64).saturating_mul(64));
            match memory {
                Some(limit) if held > limit => Err(Refusal::Memory {
                    phase: Phase::Eliminate,
                    limit_bytes: limit,
                    needed_bytes: None,
                }),
                _ => Ok(()),
            }
        };
        let mut popped: usize = 0;
        while let Some(k) = stack.pop() {
            // Each pair is popped once, and there are at most `most` of them.
            popped += 1;
            if popped.is_multiple_of(POLL)
                && stop(Progress::new(Phase::Eliminate, POLL as u64, popped as u64))
            {
                return Err(Refusal::Stopped {
                    phase: Phase::Eliminate,
                });
            }
            let id = pairs[k].id;
            if id == cut {
                continue;
            }
            let node = self.nodes[id.index()];
            let zone = pairs[k].zone.clone();
            let above = self.above(node, &zone);
            for (j, (p, zone)) in node.premises().zip(above).enumerate() {
                if !reaches[p.index()] {
                    continue;
                }
                let at = match index.get(&(p, zone.clone())) {
                    Some(&at) => at,
                    None => {
                        if pairs.len() >= most {
                            return Err(refused());
                        }
                        hold(zone.as_slice().len(), 1)?;
                        pairs.push(Pair {
                            id: p,
                            zone: zone.clone(),
                            premises: [None; 2],
                        });
                        index.insert((p, zone), pairs.len() - 1);
                        stack.push(pairs.len() - 1);
                        pairs.len() - 1
                    }
                };
                pairs[k].premises[j] = Some(at);
            }
        }
        // Each pair makes a node, and each place that reads the cut makes
        // the weakenings of its context. Count them before making any.
        let weakenings = pairs
            .iter()
            .filter(|pair| pair.id == cut)
            .fold(0usize, |sum, pair| {
                sum.saturating_add(pair.zone.difference(proved).as_slice().len())
            });
        if pairs.len().saturating_add(weakenings) > most {
            return Err(refused());
        }
        hold(0, weakenings)?;
        let mut order: Vec<usize> = (0..pairs.len()).collect();
        order.sort_unstable_by_key(|&k| pairs[k].id);
        let mut made = vec![NodeId::new(0); pairs.len()];
        for k in order {
            let pair = &pairs[k];
            made[k] = if pair.id == cut {
                let context = pair.zone.difference(proved);
                self.weaken(kept, &context)
            } else {
                let node = self.nodes[pair.id.index()];
                let mut j = 0;
                let premises = pair.premises;
                let node = node.map_premises(|p| {
                    let at = premises[j];
                    j += 1;
                    at.map_or(p, |at| made[at])
                });
                self.push(node)
            };
        }
        Ok(made[0])
    }

    /// Returns the exact conclusions of the premises of `node`, in the
    /// rule's order, when its own is `zone`.
    ///
    /// For a rule of one premise, that is `zone` with what the rule takes
    /// away and adds. For a rule of two premises, each premise gets its
    /// derived zone, and the formula the rule takes from it where a `⊤`
    /// absorbed it; the rest of `zone` goes to a premise that absorbs it.
    fn above(&mut self, node: Node, zone: &Multiset<Member>) -> Vec<Multiset<Member>> {
        let change = |removed: Option<Member>, added: &[Member]| {
            let mut up = zone.clone();
            if let Some(o) = removed {
                up.remove(o);
            }
            for &o in added {
                up.insert(o);
            }
            up
        };
        if let Some([(p, tp), (q, tq)]) = self.split(node) {
            let removed = match node {
                Node::Tensor(o, ..) => Some(o),
                _ => None,
            };
            let mut rest = change(removed, &[]);
            let derived = |id: NodeId, taken: Option<Member>| {
                let mut up = self.record.zone(id).clone();
                if let Some(t) = taken
                    && !up.contains(t)
                {
                    up.insert(t);
                }
                up
            };
            let (mut up_p, mut up_q) = (derived(p, tp), derived(q, tq));
            for (up, taken) in [(&up_p, tp), (&up_q, tq)] {
                let mut own = up.clone();
                if let Some(t) = taken {
                    own.remove(t);
                }
                rest = rest.difference(&own);
            }
            let output = rest.as_slice().iter().any(|&o| self.is_output(o));
            match self.absorber(output, (p, tp), (q, tq)) {
                Branch::Left => up_p = up_p.sum(&rest),
                Branch::Right => up_q = up_q.sum(&rest),
            }
            return vec![up_p, up_q];
        }
        match node {
            Node::Par(o, _) => {
                let (l, r) = (self.left(o), self.right(o));
                vec![change(Some(o), &[l, r])]
            }
            Node::Bang(o, _) => {
                let content = self.left(o);
                vec![change(Some(o), &[content])]
            }
            Node::Bot(o, _) | Node::Quest(o, _) | Node::Weaken(o, _) => vec![change(Some(o), &[])],
            Node::Plus(o, side, _) => {
                let child = self.child(o, side);
                vec![change(Some(o), &[child])]
            }
            Node::With(o, ..) => {
                let (l, r) = (self.left(o), self.right(o));
                vec![change(Some(o), &[l]), change(Some(o), &[r])]
            }
            Node::Copy(o, _) => vec![change(None, &[o])],
            Node::Forall(o, a, _) => {
                let term = self
                    .table
                    .as_mut()
                    .expect("a binder's proof has instances")
                    .eigen(a);
                let body = self.body(o, term);
                vec![change(Some(o), &[body])]
            }
            Node::Exists(o, w, _) => {
                let body = self.body(o, w);
                vec![change(Some(o), &[body])]
            }
            _ => vec![],
        }
    }
}

/// Returns whether the last rule of a premise acts on its occurrence `x`
/// of the cut formula: introduces it, or for `⊤` is it. A copy never
/// does: it adds to the linear zone, and introduces nothing there.
fn principal(node: Node, x: Member) -> bool {
    match node {
        Node::Ax(p, q) => p == x || q == x,
        Node::Copy(..) | Node::Mix(..) | Node::Cut(..) => false,
        node => node.principal() == Some(x),
    }
}

/// Returns the substitution of the witness `w` for the eigenvariable `a`.
fn witness(a: Eigen, w: FoTermId) -> HashMap<Eigen, FoTermId> {
    let mut sigma = HashMap::default();
    sigma.insert(a, w);
    sigma
}

impl Node {
    /// Returns the node of two premises with `first` and `second` for its
    /// premises.
    fn with_premises(self, first: NodeId, second: NodeId) -> Self {
        match self {
            Self::Tensor(o, ..) => Self::Tensor(o, first, second),
            Self::With(o, ..) => Self::With(o, first, second),
            Self::Mix(..) => Self::Mix(first, second),
            Self::Cut(o, ..) => Self::Cut(o, first, second),
            node => unreachable!("{node} has two premises"),
        }
    }
}

mod framed;

#[cfg(all(test, feature = "parse", feature = "interactive"))]
mod tests;