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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The proof checker: it derives, node by node, the sequent a proof term
//! proves under the rules of the dyadic sequent calculus and accepts the
//! term only if the root derives the proof's sequent. It is the reference
//! for what a proof is, so it shares no code with any search engine and must
//! never: an engine's proofs are validated by something that cannot repeat
//! the engine's mistakes.
//!
//! The pass is bottom-up, one node at a time in arena order, and never
//! recurses. What a subproof proves is a `State`, a sequent kept as two
//! tables of its members; the one rule whose conclusion the premises do not
//! determine, `⊤`, is handled by a flag that says the subproof proves its
//! sequent under any further context. A node's sequent is built from its
//! premises' own: the last node to read a premise takes its sequent and
//! changes it in place, an earlier reader a copy, so what the pass holds at
//! any moment is the sequents some later node still reads. Those are
//! counted in bytes as they come and go, and a pass that would hold more
//! than its bound ends with a refusal, which is no verdict on the proof.
//!
//! No arithmetic here may wrap, in any build: a term from a file is
//! hostile input, and a counter that wrapped once made a term a proof
//! that was none. So every integer says at its declaration why it stays
//! in range, or saturates into a refusal.
//!
//! In intuitionistic mode the same pass also checks the one-succedent
//! condition against the sequent's intuitionistic reading: every derived
//! linear zone holds at most one formula in output position, exactly one
//! unless a `⊤` above absorbs the rest, a `⊤` never absorbs a second
//! output, weakening never discards the goal, and Mix has no premise with
//! a goal at all. Every intuitionistic rule is a classical rule on the
//! one-sided sequent, so nothing else is intuitionistic about a proof.

mod error;
/// What the pass knows of a proof's members, and the frame pass.
mod frames;
mod pass;
mod zones;

pub use error::{CheckError, Dyadic, Fault, Invalid, Refused};
pub(crate) use frames::{Framed, Ground, Instancing};
pub(crate) use pass::{Allowance, Facts, Observer, afford, check, check_within, examine, reading};
pub(crate) use zones::State;

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::pass::tables;
    use super::zones::{Bag, Zone, table_bytes};
    use super::*;
    use crate::limits::{Phase, Refusal};
    use crate::linear::fragment::Mode;
    use crate::linear::occurrences::{Forest, Member, OccId};
    use crate::linear::proofs::oracle;
    use crate::linear::proofs::{Branch, Node, NodeId, Proof};
    use crate::linear::search::generate::Rng;
    use crate::{Error, linear::Sequent};

    /// Wraps a raw member id.
    const fn o(id: u32) -> Member {
        Member::new(id)
    }

    /// Wraps a raw node id.
    const fn n(id: u32) -> NodeId {
        NodeId::new(id)
    }

    /// Builds a proof of the sequent `input` parses to, with the last node
    /// as the root. Occurrence ids are the preorder numbering, which each
    /// test lists in a comment.
    fn proof(input: &str, nodes: Vec<Node>) -> Proof {
        let s: Sequent = input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"));
        let root = n(nodes.len() as u32 - 1);
        Proof::new(Forest::new(&s).unwrap(), nodes, root).unwrap()
    }

    /// A proof with one node changed at random, or none when the change
    /// does not leave a proof term: another occurrence, another premise,
    /// another rule on the same operands, the premises swapped, or a
    /// weakening in the node's place.
    fn mutant(rng: &mut Rng, proof: &Proof) -> Option<Proof> {
        use Node::*;
        let mut nodes = proof.nodes().to_vec();
        let i = rng.below(nodes.len());
        let occurrences = proof.forest().len();
        let occ = |rng: &mut Rng| o(rng.below(occurrences) as u32);
        let earlier = |rng: &mut Rng| n(rng.below(i.max(1)) as u32);
        let unary = |k: usize, o: OccId, p: NodeId| match k % 8 {
            0 => Bot(Member::from(o), p),
            1 => Par(Member::from(o), p),
            2 => Bang(Member::from(o), p),
            3 => Quest(Member::from(o), p),
            4 => Copy(Member::from(o), p),
            5 => Weaken(Member::from(o), p),
            6 => Plus(Member::from(o), Branch::Left, p),
            _ => Plus(Member::from(o), Branch::Right, p),
        };
        let choice = rng.below(5);
        nodes[i] = match (nodes[i], choice) {
            (Ax(a, _), 0) => Ax(a, occ(rng)),
            (Ax(a, b), 1) => Ax(b, a),
            (Ax(a, _), 2) => One(a),
            (Ax(_, b), 3) => Top(b),
            (One(a) | Top(a), 0 | 1) => Ax(a, occ(rng)),
            (One(a), _) => Top(a),
            (Top(a), _) => One(a),
            (Tensor(_, l, r) | With(_, l, r), 0) => Tensor(occ(rng), l, r),
            (Tensor(a, _, r), 1) => Tensor(a, earlier(rng), r),
            (With(a, l, _), 1) => With(a, l, earlier(rng)),
            (Tensor(a, l, r), 2) => With(a, l, r),
            (With(a, l, r), 2) => Tensor(a, l, r),
            (Tensor(a, l, r), 3) => Tensor(a, r, l),
            (With(a, l, r), 3) => With(a, r, l),
            (Tensor(_, l, r) | With(_, l, r), 4) if proof.forest().has_cuts() => {
                Cut(occ(rng), l, r)
            }
            (Tensor(_, l, r) | With(_, l, r), _) => Mix(l, r),
            (Cut(_, l, r), 0) => Cut(occ(rng), l, r),
            (Cut(a, l, r), 1) => Cut(a, r, l),
            (Cut(a, l, _), 2) => Cut(a, l, earlier(rng)),
            (Cut(_, l, r), 3) => Tensor(occ(rng), l, r),
            (Cut(_, l, r), _) => Mix(l, r),
            (Mix(l, r), 0 | 1) => Tensor(occ(rng), l, r),
            (Mix(l, r), 2) => With(occ(rng), l, r),
            (Mix(l, r), 3) => Mix(r, l),
            (Mix(l, _), _) => Mix(l, earlier(rng)),
            (node, 0) => unary(rng.below(8), occ(rng).occ(), node.premises().next()?),
            (node, 1) => unary(rng.below(8), (node.members().next()?).occ(), earlier(rng)),
            (node, 2) => unary(
                rng.below(8),
                (node.members().next()?).occ(),
                node.premises().next()?,
            ),
            (node, 3) => Weaken(occ(rng), node.premises().next()?),
            (Ax(a, _), _) => Ax(a, a),
            (node, _) => {
                let p = node.premises().next()?;
                Mix(p, earlier(rng))
            }
        };
        Proof::new(proof.forest().clone(), nodes, proof.root()).ok()
    }

    /// The checker agrees with its first implementation, which keeps every
    /// node's sequent, on the verdict and on the error: on the proofs the
    /// engines find of generated sequents, classical and intuitionistic,
    /// and of the smallest instance of every family, in the mode they were
    /// found in and in the others, and on mutants of them.
    #[test]
    fn agrees_with_the_first_implementation() {
        let classical = Mode::CLASSICAL;
        let proofs = oracle::proofs();
        assert!(proofs.len() > 1000, "{} proofs", proofs.len());
        #[cfg(feature = "interactive")]
        {
            let two_cuts = |(p, _): &&(Proof, Mode)| {
                p.nodes()
                    .iter()
                    .filter(|n| matches!(n, Node::Cut(..)))
                    .count()
                    == 2
            };
            let (classical, ill) = proofs
                .iter()
                .filter(two_cuts)
                .fold((0, 0), |(c, i), (_, m)| {
                    if m.intuitionistic {
                        (c, i + 1)
                    } else {
                        (c + 1, i)
                    }
                });
            assert!(
                classical > 50 && ill > 50,
                "{classical} and {ill} proofs with two cuts"
            );
        }

        let modes = [
            classical,
            classical.with_affine().with_mix(),
            Mode::INTUITIONISTIC,
            Mode::INTUITIONISTIC.with_affine(),
            Mode::CYCLIC,
            Mode::LAMBEK,
            Mode::LAMBEK.with_empty_antecedents(),
        ];
        let mut rng = Rng::new(7);
        let (mut mutants, mut rejected) = (0, 0);
        for (proof, mode) in &proofs {
            assert_eq!(check(proof, *mode), Ok(()), "{}", proof.sequent());
            for mode in modes {
                assert_eq!(
                    check(proof, mode),
                    oracle::check(proof, mode),
                    "{} in {mode} mode",
                    proof.sequent()
                );
            }
            for _ in 0..8 {
                let Some(mutant) = mutant(&mut rng, proof) else {
                    continue;
                };
                mutants += 1;
                for mode in [
                    *mode,
                    classical.with_affine().with_mix(),
                    Mode::CYCLIC,
                    Mode::LAMBEK,
                ] {
                    let result = check(&mutant, mode);
                    rejected += u32::from(result.is_err());
                    assert_eq!(
                        result,
                        oracle::check(&mutant, mode),
                        "{:?} of {} in {mode} mode",
                        mutant.nodes(),
                        mutant.sequent()
                    );
                }
            }
        }
        assert!(mutants > 5000, "{mutants} mutants");
        assert!(
            rejected > mutants,
            "{rejected} of {mutants} mutants rejected"
        );
    }

    /// Every rule applied correctly is accepted: the multiplicatives and
    /// their units, the additives with `⊤` absorbing its context, the
    /// exponentials in dyadic form, weakening in affine mode and Mix.
    #[test]
    fn accepts_every_rule() {
        use Node::*;
        let classical = Mode::CLASSICAL;
        for (input, nodes, mode) in [
            // ⊢ ~A, A ⊗ ~B, B: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B
            (
                "A, A -o B |- B",
                vec![Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(0), n(1))],
                classical,
            ),
            // ⊢ A ⅋ ~A: 0 ⅋, 1 A, 2 ~A
            (
                "|- A par ~A",
                vec![Ax(o(2), o(1)), Par(o(0), n(0))],
                classical,
            ),
            // ⊢ 1, ⊥
            ("|- 1, bot", vec![One(o(0)), Bot(o(1), n(0))], classical),
            // ⊢ A & B, ~A ⊕ ~B: 0 &, 1 A, 2 B, 3 ⊕, 4 ~A, 5 ~B
            (
                "|- A & B, ~A + ~B",
                vec![
                    Ax(o(1), o(4)),
                    Plus(o(3), Branch::Left, n(0)),
                    Ax(o(2), o(5)),
                    Plus(o(3), Branch::Right, n(2)),
                    With(o(0), n(1), n(3)),
                ],
                classical,
            ),
            // ⊢ ⊤, A: ⊤ absorbs A.
            ("|- top, A", vec![Top(o(0))], classical),
            // ⊢ A & ⊤, ~A: 0 &, 1 A, 2 ⊤, 3 ~A: the ⊤ side adapts to the
            // other.
            (
                "|- A & top, ~A",
                vec![Ax(o(1), o(3)), Top(o(2)), With(o(0), n(0), n(1))],
                classical,
            ),
            // ⊢ ⊤ ⊗ A, ~A, B: 0 ⊗, 1 ⊤, 2 A, 3 ~A, 4 B: the ⊤ side of the
            // split takes B.
            (
                "|- top * A, ~A, B",
                vec![Top(o(1)), Ax(o(2), o(3)), Tensor(o(0), n(0), n(1))],
                classical,
            ),
            // ⊢ ?~A, A: 0 ?, 1 ~A, 2 A: a copy, then the ? step.
            (
                "!A |- A",
                vec![Ax(o(1), o(2)), Copy(o(1), n(0)), Quest(o(0), n(1))],
                classical,
            ),
            // ⊢ ?~A, A ⊗ A: 0 ?, 1 ~A, 2 ⊗, 3 A, 4 A: two copies of one
            // occurrence.
            (
                "!A |- A * A",
                vec![
                    Ax(o(1), o(3)),
                    Copy(o(1), n(0)),
                    Ax(o(1), o(4)),
                    Copy(o(1), n(2)),
                    Tensor(o(2), n(1), n(3)),
                    Quest(o(0), n(4)),
                ],
                classical,
            ),
            // ⊢ ?~A, 1: 0 ?, 1 ~A, 2 1: an unused ? formula.
            ("!A |- 1", vec![One(o(2)), Quest(o(0), n(0))], classical),
            // ⊢ ?~A, ?(A ⊗ ~B), !B: 0 ?, 1 ~A, 2 ?, 3 ⊗, 4 A, 5 ~B, 6 !, 7 B:
            // promotion under two ? formulas.
            (
                "!A, !(A -o B) |- !B",
                vec![
                    Ax(o(1), o(4)),
                    Copy(o(1), n(0)),
                    Ax(o(5), o(7)),
                    Tensor(o(3), n(1), n(2)),
                    Copy(o(3), n(3)),
                    Bang(o(6), n(4)),
                    Quest(o(2), n(5)),
                    Quest(o(0), n(6)),
                ],
                classical,
            ),
            // ⊢ !(A ⅋ ~A): 0 !, 1 ⅋, 2 A, 3 ~A: promotion of a closed
            // formula.
            (
                "|- !(A par ~A)",
                vec![Ax(o(2), o(3)), Par(o(1), n(0)), Bang(o(0), n(1))],
                classical,
            ),
            // ⊢ ~A, ~B, A: weakening of ~B.
            (
                "A, B |- A",
                vec![Ax(o(0), o(2)), Weaken(o(1), n(0))],
                classical.with_affine(),
            ),
            // ⊢ 1, ?A: weakening of a ? formula needs no affine mode.
            ("|- 1, ?A", vec![One(o(0)), Weaken(o(1), n(0))], classical),
            // ⊢ ?⊤, !0: 0 ?, 1 ⊤, 2 !, 3 0: the ⊤ stands in for the 0 the
            // promotion consumes, and the zone is empty after it.
            (
                "|- ?top, !0",
                vec![
                    Top(o(1)),
                    Copy(o(1), n(0)),
                    Bang(o(2), n(1)),
                    Quest(o(0), n(2)),
                ],
                classical,
            ),
            // ⊢ ⊤ & ⊤, A: both sides absorb.
            (
                "|- top & top, A",
                vec![Top(o(1)), Top(o(2)), With(o(0), n(0), n(1))],
                classical,
            ),
            // ⊢ ⊤, ?A: 0 ⊤, 1 ?, 2 A: a copy the ⊤ stands in for.
            (
                "|- top, ?A",
                vec![Top(o(0)), Copy(o(2), n(0)), Quest(o(1), n(1))],
                classical,
            ),
            // ⊢ ?(?~A), A ⊗ A: 0 ?, 1 ?, 2 ~A, 3 ⊗, 4 A, 5 A: the inner ?
            // is copied twice and its ? step taken twice on one path.
            (
                "|- ?(?~A), A * A",
                vec![
                    Ax(o(2), o(4)),
                    Copy(o(2), n(0)),
                    Ax(o(2), o(5)),
                    Copy(o(2), n(2)),
                    Tensor(o(3), n(1), n(3)),
                    Quest(o(1), n(4)),
                    Copy(o(1), n(5)),
                    Quest(o(1), n(6)),
                    Copy(o(1), n(7)),
                    Quest(o(0), n(8)),
                ],
                classical,
            ),
            // ⊢ ?A, ?~A: 0 ?, 1 A, 2 ?, 3 ~A: one subproof shared by both
            // sides of a Mix.
            (
                "|- ?A, ?~A",
                vec![
                    Ax(o(1), o(3)),
                    Copy(o(1), n(0)),
                    Copy(o(3), n(1)),
                    Mix(n(2), n(2)),
                    Quest(o(2), n(3)),
                    Quest(o(0), n(4)),
                ],
                classical.with_mix(),
            ),
            // ⊢ ~A ⅋ ~B, A ⅋ B: 0 ⅋, 1 ~A, 2 ~B, 3 ⅋, 4 A, 5 B: needs Mix.
            (
                "A * B |- A par B",
                vec![
                    Ax(o(1), o(4)),
                    Ax(o(2), o(5)),
                    Mix(n(0), n(1)),
                    Par(o(0), n(2)),
                    Par(o(3), n(3)),
                ],
                classical.with_mix(),
            ),
        ] {
            let p = proof(input, nodes);
            assert_eq!(p.check(mode), Ok(()), "{input:?}");
        }
    }

    /// Every rule misapplied is rejected at the node that misapplies it,
    /// with the problem named; a rule the mode forbids is rejected too, and
    /// so is a root that concludes something else.
    #[test]
    fn rejects_every_misuse() {
        use Fault::*;
        use Node::*;
        let classical = Mode::CLASSICAL;
        for (input, nodes, mode, node, problem) in [
            // Axiom on two copies of one literal.
            ("|- A, A", vec![Ax(o(0), o(1))], classical, 0, NotDual),
            // Axiom on a connective: 0 ⊗, 1 A, 2 B, 3 ~A.
            (
                "|- A * B, ~A",
                vec![Ax(o(0), o(3))],
                classical,
                0,
                Kind { member: o(0) },
            ),
            // ⊗ with its premises swapped: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B.
            (
                "A, A -o B |- B",
                vec![Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(1), n(0))],
                classical,
                2,
                Missing {
                    premise: 0,
                    member: o(2),
                },
            ),
            // ⅋ on a ⊗ occurrence.
            (
                "A, A -o B |- B",
                vec![Ax(o(0), o(2)), Par(o(1), n(0))],
                classical,
                1,
                Kind { member: o(1) },
            ),
            // ⅋ whose premise lacks a subformula: 0 A, 1 ⅋, 2 ~A, 3 B.
            (
                "|- A, ~A par B",
                vec![Ax(o(0), o(2)), Par(o(1), n(0))],
                classical,
                1,
                Missing {
                    premise: 0,
                    member: o(3),
                },
            ),
            // 1 on ⊥.
            (
                "|- bot",
                vec![One(o(0))],
                classical,
                0,
                Kind { member: o(0) },
            ),
            // ⊥ on 1.
            (
                "|- 1, bot",
                vec![One(o(0)), Bot(o(0), n(0))],
                classical,
                1,
                Kind { member: o(0) },
            ),
            // & whose premises consume different contexts: 0 &, 1 A, 2 B,
            // 3 ~A, 4 ~B.
            (
                "|- A & B, ~A, ~B",
                vec![Ax(o(1), o(3)), Ax(o(2), o(4)), With(o(0), n(0), n(1))],
                classical,
                2,
                Differ,
            ),
            // & whose ⊤ side needs more than the other side has: the root
            // then concludes ⊢ A & ⊤, ~A without ~B.
            (
                "|- A & top, ~A, ~B",
                vec![Ax(o(1), o(3)), Top(o(2)), With(o(0), n(0), n(1))],
                classical,
                2,
                Conclusion {
                    derived: Dyadic {
                        theta: vec![],
                        gamma: vec![o(0), o(3)],
                        any: false,
                    },
                },
            ),
            // ⊕ on the side the premise does not prove: 0 ⊕, 1 A, 2 B, 3 ~A.
            (
                "|- A + B, ~A",
                vec![Ax(o(1), o(3)), Plus(o(0), Branch::Right, n(0))],
                classical,
                1,
                Missing {
                    premise: 0,
                    member: o(2),
                },
            ),
            // ⊤ on 0.
            ("|- 0", vec![Top(o(0))], classical, 0, Kind { member: o(0) }),
            // Promotion with a linear formula in the context: 0 ~A, 1 !, 2 A.
            (
                "A |- !A",
                vec![Ax(o(0), o(2)), Bang(o(1), n(0))],
                classical,
                1,
                NotEmpty,
            ),
            // A copy of a formula under !: 0 !, 1 ~A, 2 A.
            (
                "?A |- A",
                vec![Ax(o(1), o(2)), Copy(o(1), n(0))],
                classical,
                1,
                NotUnderQuest { member: o(1) },
            ),
            // A copy of a formula the premise does not hold: 0 ?, 1 ~A, 2 1.
            (
                "!A |- 1",
                vec![One(o(2)), Copy(o(1), n(0))],
                classical,
                1,
                Missing {
                    premise: 0,
                    member: o(1),
                },
            ),
            // A copy without the ? step below it: the root still needs ~A
            // in the unrestricted zone.
            (
                "!A |- A",
                vec![Ax(o(1), o(2)), Copy(o(1), n(0))],
                classical,
                1,
                Conclusion {
                    derived: Dyadic {
                        theta: vec![o(1)],
                        gamma: vec![o(2)],
                        any: false,
                    },
                },
            ),
            // ? on a ! occurrence.
            (
                "|- !(A par ~A)",
                vec![Ax(o(2), o(3)), Par(o(1), n(0)), Quest(o(0), n(1))],
                classical,
                2,
                Kind { member: o(0) },
            ),
            // Weakening outside affine mode.
            (
                "A, B |- A",
                vec![Ax(o(0), o(2)), Weaken(o(1), n(0))],
                classical,
                1,
                Forbidden,
            ),
            // Mix without Mix.
            (
                "|- A, ~A, B, ~B",
                vec![Ax(o(0), o(1)), Ax(o(2), o(3)), Mix(n(0), n(1))],
                classical,
                2,
                Forbidden,
            ),
            // A proof of a smaller sequent.
            (
                "|- A, ~A, 1",
                vec![Ax(o(0), o(1))],
                classical,
                0,
                Conclusion {
                    derived: Dyadic {
                        theta: vec![],
                        gamma: vec![o(0), o(1)],
                        any: false,
                    },
                },
            ),
            // Intuitionistic mode needs an intuitionistic sequent, whatever
            // the proof.
            (
                "|- A par B",
                vec![Ax(o(1), o(2))],
                Mode::INTUITIONISTIC,
                0,
                Shape(crate::linear::occurrences::ShapeError::Formula {
                    occurrence: o(0).occ(),
                }),
            ),
        ] {
            let p = proof(input, nodes);
            let e = p.check(mode).unwrap_err();
            let message = e.to_string();
            assert_eq!(
                (e.node(), e.fault()),
                (n(node), Some(&problem)),
                "{input:?}: {message}"
            );
        }
    }

    /// A term that doubles a zone at every node is refused where the zone
    /// outgrows what the rest of the proof can consume, long before a
    /// counter is full: this one mixes 2⁶⁴ copies of `⊢ 1`, promotes `⊥`
    /// over them and mixes one more in, and `⊢ !⊥, 1` has no proof.
    #[test]
    fn refuses_a_zone_too_large_to_conclude() {
        use Node::*;
        // ⊢ !⊥, 1: 0 !, 1 ⊥, 2 1
        let mut nodes = vec![One(o(2))];
        for i in 0..63 {
            nodes.push(Mix(n(i), n(i)));
        }
        let mut all = n(0);
        for i in 1..64 {
            nodes.push(Mix(all, n(i)));
            all = n(nodes.len() as u32 - 1);
        }
        nodes.push(Mix(all, n(0)));
        nodes.push(Bot(o(1), n(nodes.len() as u32 - 1)));
        nodes.push(Bang(o(0), n(nodes.len() as u32 - 1)));
        nodes.push(Mix(n(nodes.len() as u32 - 1), n(0)));
        let p = proof("|- !bot, 1", nodes);
        let mode = Mode::CLASSICAL.with_mix();
        let e = p.check(mode).unwrap_err();
        // Node 8 holds 256 copies with 122 nodes to come.
        assert_eq!((e.node(), e.fault()), (n(8), Some(&Fault::Surplus)));
        assert_eq!(Err(e.clone()), oracle::check(&p, mode));
        // The pass that adds up weights for the size refuses it there too.
        assert_eq!(p.size_of(false), Err(e));
    }

    /// A proof of `⊢ 1, ⊥, …, ⊥, T` with `width` formulas `⊥` and `T` a
    /// balanced tree of `&` over `2^depth` leaves `⊥`: the `⊥` formulas are
    /// introduced once, into one sequent that every leaf of the tree then
    /// reads, and all the leaves come before the first `&` that joins two
    /// of them. So a pass holds a copy of that sequent for every leaf.
    fn shared(width: u32, depth: u32) -> Proof {
        use crate::linear::sequents::{Term, TermId};
        use Node::*;
        // Terms: 0 is 1, 1 is ⊥, and 2 + j the tree of depth j + 1 over
        // two of depth j, so the arena has the tree once per depth.
        let mut terms = vec![Term::One, Term::Bot];
        for j in 0..depth {
            terms.push(Term::With(TermId::new(1 + j), TermId::new(1 + j)));
        }
        let mut roots = vec![TermId::new(0)];
        roots.extend((0..width).map(|_| TermId::new(1)));
        roots.push(TermId::new(1 + depth));
        let sequent = Sequent {
            terms,
            roots,
            atoms: vec![],
            antecedents: None,
            cuts: vec![],
            fo: Default::default(),
        };
        // Occurrences: 0 is 1, 1 to `width` the ⊥ formulas, then the tree
        // in preorder.
        let mut nodes = vec![One(o(0))];
        for i in 1..=width {
            nodes.push(Bot(o(i), n(i - 1)));
        }
        let context = n(width);
        // The tree's occurrences with their depths, in preorder: a tree of
        // depth j has 2^(j + 1) − 1 of them.
        let mut tree = vec![];
        let mut stack = vec![(width + 1, depth)];
        while let Some((at, d)) = stack.pop() {
            tree.push((at, d));
            if d > 0 {
                stack.push((at + (1 << d), d - 1));
                stack.push((at + 1, d - 1));
            }
        }
        let mut proved = crate::hash::HashMap::default();
        for &(at, d) in &tree {
            if d == 0 {
                proved.insert(at, n(nodes.len() as u32));
                nodes.push(Bot(o(at), context));
            }
        }
        // A subtree's occurrences follow its root, so the reverse of the
        // preorder has both subformulas before their `&`.
        for &(at, d) in tree.iter().rev() {
            if d > 0 {
                let (l, r) = (proved[&(at + 1)], proved[&(at + (1 << d))]);
                proved.insert(at, n(nodes.len() as u32));
                nodes.push(With(o(at), l, r));
            }
        }
        let root = n(nodes.len() as u32 - 1);
        Proof::new(Forest::new(&sequent).unwrap(), nodes, root).unwrap()
    }

    /// A zone's count of its bytes stays what its table takes when a
    /// member that is there already is added again: the table is full at
    /// fourteen members in sixteen slots, and would double to make room
    /// before it looked the member up.
    #[test]
    fn a_member_twice_grows_no_table() {
        let mut zone = Zone::default();
        for id in 0..14 {
            assert!(zone.insert(o(id)));
        }
        let (bytes, room) = (zone.bytes(), zone.members.capacity());
        assert_eq!((bytes, room), (16 * 5 + 16, 14));
        for id in 0..14 {
            assert!(!zone.insert(o(id)));
        }
        assert_eq!((zone.bytes(), zone.members.capacity()), (bytes, room));
    }

    /// The pass's own tables are asked for before it judges anything: a
    /// term whose first node is no rule is refused, not judged, under a
    /// bound of a byte less than its tables, and judged at the tables'
    /// size exactly.
    #[test]
    fn refuses_its_tables_before_it_judges() {
        let (o, mode) = (|i| Member::new(i), Mode::CLASSICAL);
        let crossed = proof("|- a, a", vec![Node::Ax(o(0), o(1))]);
        // A count of four bytes and a pointer for the one node.
        let bytes = tables(&crossed);
        assert_eq!(bytes, 4 + size_of::<usize>() as u64);
        let within = |bytes| {
            let limits = crate::Limits::default().with_memory_bytes(Some(bytes));
            crossed.check_within(mode, &limits, |_| false)
        };
        match within(bytes) {
            Err(CheckError::Invalid(invalid)) => assert_eq!(invalid.fault, Fault::NotDual),
            other => panic!("{other:?}"),
        }
        match within(bytes - 1) {
            Err(CheckError::Refused(refused)) => assert!(
                matches!(
                    refused.refusal,
                    Refusal::Memory { limit_bytes, .. } if limit_bytes == bytes - 1
                ),
                "{refused:?}"
            ),
            other => panic!("{other:?}"),
        }
    }

    /// A proof of `⊢ ⊤, ⊥, …, ⊥, ⊥ & ⊥, …, ⊥ & ⊥` with `width` formulas
    /// `⊥` and `length` of `⊥ & ⊥`: the `⊥` formulas introduced one by one
    /// over the `⊤`, then a chain of `&` nodes each of whose right premises
    /// is that one node, which absorbs both of its subformulas. The chain
    /// is a proof file linear in its length whose pass handles the
    /// node's sequent at every link.
    fn chained(width: u32, length: u32) -> Proof {
        use crate::linear::sequents::{Term, TermId};
        use Node::*;
        let mut roots = vec![TermId::new(0)];
        roots.extend((0..width).map(|_| TermId::new(1)));
        roots.extend((0..length).map(|_| TermId::new(2)));
        let sequent = Sequent {
            terms: vec![
                Term::Top,
                Term::Bot,
                Term::With(TermId::new(1), TermId::new(1)),
            ],
            roots,
            atoms: vec![],
            antecedents: None,
            cuts: vec![],
            fo: Default::default(),
        };
        // Occurrences: 0 is ⊤, 1 to `width` the ⊥ formulas, then each
        // `⊥ & ⊥` and its two subformulas.
        let mut nodes = vec![Top(o(0))];
        for i in 1..=width {
            nodes.push(Bot(o(i), n(i - 1)));
        }
        let context = n(width);
        let mut previous = context;
        for j in 0..length {
            nodes.push(With(o(width + 1 + 3 * j), previous, context));
            previous = n(nodes.len() as u32 - 1);
        }
        Proof::new(Forest::new(&sequent).unwrap(), nodes, previous).unwrap()
    }

    /// A node that many others read costs each of them its sequent: the
    /// pass counts that work, asks the stop by it and refuses past a bound
    /// on it. Counted by nodes, an 8.6 MB file of this shape took 83 s,
    /// between two polls a few seconds apart.
    #[test]
    fn counts_the_work_of_shared_premises() {
        let (proof, mode) = (chained(2000, 2000), Mode::CLASSICAL);
        let mut polls = 0;
        let checked = proof.check_within(mode, &crate::Limits::default(), |_| {
            polls += 1;
            false
        });
        assert_eq!(checked, Ok(()));
        // 4 001 nodes, one poll by their count; each link handles two
        // sequents of thousands of formulas: 176 polls, one per 65 536
        // units, not one per node.
        assert!((100..300).contains(&polls), "{polls} polls");
        let enough = crate::Limits::default().with_work(Some(1 << 40));
        assert_eq!(proof.check_within(mode, &enough, |_| false), Ok(()));
        let limits = crate::Limits::default().with_work(Some(40_010));
        let e = proof.check_within(mode, &limits, |_| false).unwrap_err();
        assert!(
            matches!(&e, CheckError::Refused(r) if r.refusal == Refusal::Work { limit: 40_010 }),
            "{e}"
        );
    }

    /// The bound is exact: the check of `⊢ 1` holds its tables and the
    /// root's sequent, the value and a table of one member, passes at
    /// exactly their bytes and is refused one byte below; and a zone's
    /// bound leaves its counters room.
    #[test]
    fn the_bound_is_exact() {
        let p = proof("|- 1", vec![Node::One(o(0))]);
        let root = size_of::<State>() as u64 + 16 + table_bytes(1, size_of::<(OccId, u32)>());
        let exact = tables(&p) + root;
        let within = |bytes| {
            let limits = crate::Limits::default().with_memory_bytes(Some(bytes));
            p.check_within(Mode::CLASSICAL, &limits, |_| false)
        };
        assert_eq!(within(exact), Ok(()));
        assert!(matches!(within(exact - 1), Err(CheckError::Refused(_))));
        assert!(Bag::MOST < u32::MAX as usize);
    }

    /// A check holds no more than it is allowed: a proof file of a megabyte
    /// whose pass would hold 16 384 copies of a sequent of 14 001 formulas,
    /// over two gigabytes, is refused after a few hundred of them, and the
    /// refusal is no verdict. So are its size and its derivation. The same
    /// proof at a size that fits is valid.
    #[test]
    fn holds_no_more_than_its_bound() {
        let mode = Mode::CLASSICAL;
        let small = shared(200, 6);
        assert_eq!(
            small.check_within(
                mode,
                &crate::Limits::default().with_memory_bytes(None),
                |_| false
            ),
            Ok(())
        );
        assert_eq!(small.check(mode), oracle::check(&small, mode));
        // 201 formulas take 256 slots of nine bytes: under 3 KB a copy, 64
        // copies and as many nodes within 256 KB, and not within 64 KB.
        assert_eq!(
            small.check_within(
                mode,
                &crate::Limits::default().with_memory_bytes(Some(256 << 10)),
                |_| false
            ),
            Ok(())
        );
        let e = small
            .check_within(
                mode,
                &crate::Limits::default().with_memory_bytes(Some(64 << 10)),
                |_| false,
            )
            .unwrap_err();
        assert!(matches!(e, CheckError::Refused(_)), "{e}");
        // The pass's own tables, a count and a pointer for each of 328
        // nodes, are refused before the first node a byte short of them.
        let short = tables(&small) - 1;
        let e = small
            .check_within(
                mode,
                &crate::Limits::default().with_memory_bytes(Some(short)),
                |_| false,
            )
            .unwrap_err();
        assert!(
            matches!(e, CheckError::Refused(_)) && e.node() == n(0),
            "{e}"
        );

        let (width, depth) = (14_000, 14);
        let large = shared(width, depth);
        #[cfg(feature = "serialize")]
        {
            let file = serde_json::to_string(&large).unwrap().len();
            assert!((900_000..1_200_000).contains(&file), "{file} bytes");
        }
        let limit = 64 << 20;
        let e = large
            .check_within(
                mode,
                &crate::Limits::default().with_memory_bytes(Some(limit)),
                |_| false,
            )
            .unwrap_err();
        let CheckError::Refused(refused) = &e else {
            panic!("{e}")
        };
        assert_eq!(
            refused.refusal,
            Refusal::Memory {
                phase: Phase::Check,
                limit_bytes: limit,
                needed_bytes: None
            }
        );
        // A copy takes 16 384 slots of nine bytes, 144 KiB: the bound is
        // reached within 512 leaves of the tree.
        let leaf = e.node().get() - width - 1;
        assert!((256..512).contains(&leaf), "leaf {leaf}");
        assert_eq!(
            e.to_string(),
            format!(
                "the check was given up at node {}, without a verdict on the proof: the check \
                 takes more than the memory limit of {limit} bytes",
                e.node().get(),
            )
        );
        // The size and the derivation are under the same bound, and their
        // refusal is no invalid proof either.
        assert!(matches!(
            large.derivation_size(
                &crate::linear::proofs::ViewOptions::default(),
                &crate::Limits::default().with_memory_bytes(Some(limit)),
                |_| false
            ),
            Err(CheckError::Refused(_))
        ));
        let view = crate::linear::proofs::ViewOptions::default();
        let limits = crate::Limits::UNBOUNDED.with_memory_bytes(Some(limit));
        let refused = large
            .derivation_within(&view, &limits, |_| false)
            .unwrap_err();
        assert!(matches!(
            refused,
            crate::Error::Check(CheckError::Refused(_))
        ));
        assert!(refused.is_refusal());
    }

    /// Intuitionistic mode accepts the classical terms of intuitionistic
    /// proofs and rejects a sequent with two goals or none: a `⊸L` split
    /// that keeps the goal on the antecedent's side, a weakened goal, Mix.
    #[test]
    fn intuitionistic() {
        use Fault::*;
        use Node::*;
        let m = Mode::INTUITIONISTIC;
        for (input, nodes) in [
            // A, A ⊸ B ⊢ B: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B
            (
                "A, A -o B |- B",
                vec![Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(0), n(1))],
            ),
            // A & B ⊢ A & B: 0 ⊕, 1 ~A, 2 ~B, 3 &, 4 A, 5 B
            (
                "A & B |- A & B",
                vec![
                    Ax(o(1), o(4)),
                    Plus(o(0), Branch::Left, n(0)),
                    Ax(o(2), o(5)),
                    Plus(o(0), Branch::Right, n(2)),
                    With(o(3), n(1), n(3)),
                ],
            ),
            // A ⊸ 0, A ⊢ B: 0 ⊗, 1 A, 2 ⊤, 3 ~A, 4 B: the `0` on the left
            // absorbs the goal.
            (
                "A -o 0, A |- B",
                vec![Ax(o(1), o(3)), Top(o(2)), Tensor(o(0), n(0), n(1))],
            ),
            // 0 ⊢ ⊤ ⊗ ⊤: 0 ⊤, 1 ⊗, 2 ⊤, 3 ⊤; the hypothesis `0` is absorbed
            // by one `⊤R`.
            (
                "0 |- top * top",
                vec![Top(o(2)), Top(o(3)), Tensor(o(1), n(0), n(1))],
            ),
            // !A, !(A ⊸ B) ⊢ !B: 0 ?, 1 ~A, 2 ?, 3 ⊗, 4 A, 5 ~B, 6 !, 7 B
            (
                "!A, !(A -o B) |- !B",
                vec![
                    Ax(o(1), o(4)),
                    Copy(o(1), n(0)),
                    Ax(o(5), o(7)),
                    Tensor(o(3), n(1), n(2)),
                    Copy(o(3), n(3)),
                    Bang(o(6), n(4)),
                    Quest(o(2), n(5)),
                    Quest(o(0), n(6)),
                ],
            ),
        ] {
            let p = proof(input, nodes);
            p.check(m)
                .unwrap_or_else(|e| panic!("{input:?}: {}", e.describe(p.forest())));
        }
        // A, B ⊢ A in affine mode: weakening the hypothesis is fine, the
        // goal never.
        let p = proof("A, B |- A", vec![Ax(o(0), o(2)), Weaken(o(1), n(0))]);
        assert_eq!(p.check(m.with_affine()), Ok(()));
        // A, 0 ⊢ B: 0 ~A, 1 ⊤, 2 B
        let p = proof("A, 0 |- B", vec![Top(o(1)), Weaken(o(2), n(0))]);
        assert_eq!(
            p.check(m.with_affine()).unwrap_err().fault(),
            Some(&Succedents { count: 0 })
        );
        // ((A ⊗ ⊤) & (B ⊗ ⊤)) ⊸ 0 ⊢ (A ⊸ C) ⊕ (B ⊸ C), which classical
        // linear logic proves and intuitionistic linear logic does not:
        // 0 ⊗, 1 &, 2 ⊗, 3 A, 4 ⊤, 5 ⊗, 6 B, 7 ⊤, 8 ⊤, 9 ⊕, 10 ⅋, 11 ~A,
        // 12 C, 13 ⅋, 14 ~B, 15 C. The classical proof splits the `⊸L`
        // with the goal on the antecedent's side, where a `⊤` absorbs it.
        let p = proof(
            "((A * top) & (B * top)) -o 0 |- (A -o C) + (B -o C)",
            vec![
                Ax(o(3), o(11)),
                Top(o(4)),
                Tensor(o(2), n(0), n(1)),
                Par(o(10), n(2)),
                Plus(o(9), Branch::Left, n(3)),
                Ax(o(6), o(14)),
                Top(o(7)),
                Tensor(o(5), n(5), n(6)),
                Par(o(13), n(7)),
                Plus(o(9), Branch::Right, n(8)),
                With(o(1), n(4), n(9)),
                Top(o(8)),
                Tensor(o(0), n(10), n(11)),
            ],
        );
        assert_eq!(p.check(Mode::CLASSICAL), Ok(()));
        let e = p.check(m).unwrap_err();
        assert_eq!(
            (e.node(), e.fault()),
            (n(3), Some(&Succedents { count: 2 }))
        );
        assert_eq!(
            e.describe(p.forest()).to_string(),
            "node 3 (⅋ on ~A ⅋ C from 2) with premises ⊢ A ⊗ ⊤, ~A, …: \
             a sequent of the rule has 2 formulas on the right of ⊢ instead of one"
        );
        // A ⊕ B, (1 ⊗ ⊤) ⊸ X, 0 ⊢ 1 ⊗ ⊤: 0 &, 1 ~A, 2 ~B, 3 ⊗, 4 ⊗, 5 1,
        // 6 ⊤, 7 ~X, 8 ⊤, 9 ⊗, 10 1, 11 ⊤. Both premises of the `&L` absorb
        // with a `⊤`, the left holding the antecedent `1 ⊗ ⊤` and the
        // right the goal, so the `&` joins two succedents, which only the
        // rule on every node's sequent sees: the `⊸L` below takes the
        // antecedent away again, and the root's sequent is the goal's.
        let p = proof(
            "A + B, (1 * top) -o X, 0 |- 1 * top",
            vec![
                One(o(5)),
                Top(o(6)),
                Tensor(o(4), n(0), n(1)),
                One(o(10)),
                Top(o(11)),
                Tensor(o(9), n(3), n(4)),
                With(o(0), n(2), n(5)),
                Top(o(8)),
                Tensor(o(3), n(6), n(7)),
            ],
        );
        assert_eq!(p.check(Mode::CLASSICAL), Ok(()));
        let e = p.check(m).unwrap_err();
        assert_eq!(
            (e.node(), e.fault()),
            (n(6), Some(&Succedents { count: 2 }))
        );
        // Mix is never intuitionistic. 0 ⊗, 1 A, 2 ~B, 3 ~A, 4 B: A ⊸ B, A
        // ⊢ B with a Mix of the axioms.
        let p = proof(
            "A -o B, A |- B",
            vec![Ax(o(1), o(3)), Ax(o(2), o(4)), Mix(n(0), n(1))],
        );
        assert_eq!(p.check(m.with_mix()).unwrap_err().fault(), Some(&Forbidden));
    }

    /// Returns a proof of the sequent `input` parses to, with the cut
    /// formulas `cuts` added in order, the last node its root.
    fn with_cuts(input: &str, cuts: &[&str], nodes: Vec<Node>) -> Proof {
        let mut s: Sequent = input.parse().unwrap();
        for cut in cuts {
            s.add_cut(format!("|- {cut}").parse().unwrap()).unwrap();
        }
        let root = n(nodes.len() as u32 - 1);
        Proof::new(Forest::new(&s).unwrap(), nodes, root).unwrap()
    }

    /// A cut takes its formula from its first premise and the dual from
    /// its second, in every commutative mode, and is refused on any other
    /// member, with premises that lack them, where a premise would have
    /// two goals, and in the ordered modes; the oracle agrees.
    #[test]
    fn cut() {
        use Fault::*;
        use Node::*;
        let modes = [
            Mode::CLASSICAL,
            Mode::CLASSICAL.with_affine().with_mix(),
            Mode::INTUITIONISTIC,
            Mode::INTUITIONISTIC.with_affine(),
        ];
        let agree = |p: &Proof, mode: Mode| {
            let result = p.check(mode);
            assert_eq!(result, oracle::check(p, mode), "{mode}");
            result
        };
        // A ⊢ A by a cut on A: 0 ~A, 1 A, then the cut formula 2 A and
        // its dual 3 ~A.
        let ax = |x, y, r| with_cuts("A |- A", &["A"], vec![Ax(o(0), o(x)), Ax(o(1), o(y)), r]);
        let good = ax(2, 3, Cut(o(2), n(0), n(1)));
        assert_eq!(
            good.forest().cut_pairs().collect::<Vec<_>>(),
            [(OccId::new(2), OccId::new(3))]
        );
        for mode in modes {
            assert_eq!(agree(&good, mode), Ok(()), "{mode}");
        }
        for mode in [
            Mode::CYCLIC,
            Mode::LAMBEK,
            Mode::LAMBEK.with_empty_antecedents(),
        ] {
            assert_eq!(agree(&good, mode).unwrap_err().fault(), Some(&Forbidden));
        }
        // On the dual, or on a formula of the conclusion: no cut formula.
        for a in [3, 1] {
            let wrong = ax(2, 3, Cut(o(a), n(0), n(1)));
            let error = agree(&wrong, Mode::CLASSICAL).unwrap_err();
            assert_eq!(error.fault(), Some(&NotACut { member: o(a) }));
        }
        // The premises the other way round: the first lacks the formula.
        let swapped = ax(2, 3, Cut(o(2), n(1), n(0)));
        let error = agree(&swapped, Mode::CLASSICAL).unwrap_err();
        assert_eq!(
            error.fault(),
            Some(&Missing {
                premise: 0,
                member: o(2)
            })
        );
        // A cut formula B the premises do not have.
        let mismatched = with_cuts(
            "A |- A",
            &["B"],
            vec![Ax(o(0), o(1)), Ax(o(0), o(1)), Cut(o(2), n(0), n(1))],
        );
        let error = agree(&mismatched, Mode::CLASSICAL).unwrap_err();
        assert_eq!(
            error.fault(),
            Some(&Missing {
                premise: 0,
                member: o(2)
            })
        );
        // A, 0 ⊢ ⊤ by a cut on A: 0 ~A, 1 ⊤ (the hypothesis 0), 2 ⊤, then
        // 3 A and 4 ~A. Classically either ⊤ absorbs either side; in
        // intuitionistic mode the goal's ⊤ cannot also absorb the cut
        // formula, which would make its premise ⊢ ⊤, A, two goals.
        let tops = |l, r| {
            with_cuts(
                "A, 0 |- top",
                &["A"],
                vec![Top(o(l)), Top(o(r)), Cut(o(3), n(0), n(1))],
            )
        };
        let (right, two_goals) = (tops(1, 2), tops(2, 1));
        for mode in modes {
            assert_eq!(agree(&right, mode), Ok(()), "{mode}");
        }
        assert_eq!(agree(&two_goals, Mode::CLASSICAL), Ok(()));
        let error = agree(&two_goals, Mode::INTUITIONISTIC).unwrap_err();
        assert_eq!(
            (error.node(), error.fault()),
            (n(2), Some(&Succedents { count: 2 }))
        );
        // A cut formula that is no intuitionistic formula: ~A cannot be a
        // goal.
        let classical = with_cuts(
            "A |- A",
            &["~A"],
            vec![Ax(o(1), o(2)), Ax(o(0), o(3)), Cut(o(2), n(0), n(1))],
        );
        assert_eq!(agree(&classical, Mode::CLASSICAL), Ok(()));
        let error = agree(&classical, Mode::INTUITIONISTIC).unwrap_err();
        assert!(matches!(
            error.fault(),
            Some(Shape(crate::linear::ShapeError::CutFormula { .. }))
        ));
    }

    /// In the cyclic mode a `⊗` joins the two arcs on either side of it,
    /// and only the rules of unit-free MLL apply.
    #[test]
    fn cyclic() {
        use Node::*;
        let cyclic = Mode::CYCLIC;
        // 0 ⊗, 1 a, 2 b, 3 ~b, 4 ~a: the links nest.
        let planar = proof(
            "|- a * b, ~b, ~a",
            vec![Ax(o(1), o(4)), Ax(o(2), o(3)), Tensor(o(0), n(0), n(1))],
        );
        assert_eq!(planar.check(cyclic), Ok(()));
        // 0 ⊗, 1 a, 2 b, 3 ~a, 4 ~b: the links cross, so the contexts
        // are not the arcs.
        let crossing = proof(
            "|- a * b, ~a, ~b",
            vec![Ax(o(1), o(3)), Ax(o(2), o(4)), Tensor(o(0), n(0), n(1))],
        );
        assert_eq!(crossing.check(Mode::CLASSICAL), Ok(()));
        let error = crossing.check(cyclic).unwrap_err();
        assert_eq!((error.node(), error.fault()), (n(2), Some(&Fault::Order)));
        // Turning the sequent changes nothing: 0 ~a, 1 ⊗, 2 a, 3 b, 4 ~b.
        let turned = proof(
            "|- ~a, a * b, ~b",
            vec![Ax(o(2), o(0)), Ax(o(3), o(4)), Tensor(o(1), n(0), n(1))],
        );
        assert_eq!(turned.check(cyclic), Ok(()));
        let one = proof("|- 1", vec![One(o(0))]);
        assert_eq!(
            one.check(cyclic).unwrap_err().fault(),
            Some(&Fault::Forbidden)
        );
    }

    /// In the Lambek calculus every sequent of a proof keeps a hypothesis
    /// unless empty antecedents are allowed, and the ordered reading
    /// takes either factor as a division's antecedent; the oracle agrees.
    #[test]
    fn lambek() {
        use Node::*;
        let ordered = |input: &str, nodes: Vec<Node>| {
            let s = Sequent::parse_ordered(
                input,
                crate::linear::Order::Cyclic,
                &crate::Limits::default(),
            )
            .unwrap();
            let root = n(nodes.len() as u32 - 1);
            Proof::new(Forest::new(&s).unwrap(), nodes, root).unwrap()
        };
        let (lambek, star) = (Mode::LAMBEK, Mode::LAMBEK.with_empty_antecedents());
        // a ⊢ (b \ b) ⊗ a, that is ⊢ ~a, (~b ⅋ b) ⊗ a: 0 ~a, 1 ⊗, 2 ⅋,
        // 3 ~b, 4 b, 5 a. The `⊗R`'s left premise ⊢ b \ b has no
        // hypothesis.
        let empty = ordered(
            "a |- (b \\ b) * a",
            vec![
                Ax(o(3), o(4)),
                Par(o(2), n(0)),
                Ax(o(0), o(5)),
                Tensor(o(1), n(1), n(2)),
            ],
        );
        assert_eq!(empty.check(star), Ok(()));
        assert_eq!(oracle::check(&empty, star), Ok(()));
        let error = empty.check(lambek).unwrap_err();
        assert_eq!(
            (error.node(), error.fault()),
            (n(1), Some(&Fault::EmptyAntecedent))
        );
        assert_eq!(oracle::check(&empty, lambek), Err(error));
        // b / a, a ⊢ b, that is ⊢ ~a, a ⊗ ~b, b: 0 ~a, 1 ⊗, 2 a, 3 ~b,
        // 4 b, the antecedent the right factor of `b ⅋ ~a`.
        let over = ordered(
            "b / a, a |- b",
            vec![Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(0), n(1))],
        );
        for mode in [lambek, star] {
            assert_eq!(over.check(mode), Ok(()));
            assert_eq!(oracle::check(&over, mode), Ok(()));
        }
        // ⊢ a \ a has no hypothesis at all.
        let bare = ordered("|- a \\ a", vec![Ax(o(1), o(2)), Par(o(0), n(0))]);
        assert_eq!(bare.check(star), Ok(()));
        assert_eq!(
            bare.check(lambek).unwrap_err().fault(),
            Some(&Fault::Shape(
                crate::linear::occurrences::ShapeError::EmptyAntecedent
            ))
        );
    }

    /// The error names the node, its premises and the problem.
    #[test]
    fn error_message() {
        use Node::*;
        // ⊢ ~A, A ⊗ ~B, B with the ⊗ premises swapped.
        let p = proof(
            "A, A -o B |- B",
            vec![Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(1), n(0))],
        );
        assert_eq!(
            p.check(Mode::CLASSICAL).unwrap_err().to_string(),
            "node 2 (⊗ on 1 from 1, 0) with premises ⊢ 3, 4 and ⊢ 0, 2: \
             premise 0 lacks occurrence 2"
        );
        assert_eq!(
            p.check(Mode::CLASSICAL)
                .unwrap_err()
                .describe(p.forest())
                .to_string(),
            "node 2 (⊗ on A ⊗ ~B from 1, 0) with premises ⊢ ~B, B and ⊢ ~A, A: \
             premise 0 lacks A"
        );
        // Cut to three characters a formula, as a long report is.
        assert_eq!(
            p.check(Mode::CLASSICAL)
                .unwrap_err()
                .describe(p.forest())
                .abbreviated(Some(3))
                .to_string(),
            "node 2 (⊗ on A ⊗… from 1, 0) with premises ⊢ ~B… (2 formulas) and ⊢ ~A… \
             (2 formulas): premise 0 lacks A"
        );
        // The fault's formula is cut too: an axiom on a formula a proof
        // file can make as long as it likes.
        let p = proof("|- a * (b * c), ~a", vec![Ax(o(0), o(5))]);
        let report = |limit| {
            p.check(Mode::CLASSICAL)
                .unwrap_err()
                .describe(p.forest())
                .abbreviated(limit)
                .to_string()
        };
        assert_eq!(
            report(Some(3)),
            "node 0 (ax on a ⊗…, ~a): a ⊗… is not what the rule acts on"
        );
        assert_eq!(
            report(None),
            "node 0 (ax on a ⊗ (b ⊗ c), ~a): a ⊗ (b ⊗ c) is not what the rule acts on"
        );
        // ⊢ ?~A, A with the ? step missing: a dyadic sequent with Θ.
        let p = proof("!A |- A", vec![Ax(o(1), o(2)), Copy(o(1), n(0))]);
        assert_eq!(
            p.check(Mode::CLASSICAL).unwrap_err().to_string(),
            "node 1 (copy on 1 from 0) with premises ⊢ 1, 2: \
             the proof concludes ⊢ 1 ; 2, not the sequent"
        );
        assert_eq!(
            Dyadic {
                theta: vec![],
                gamma: vec![o(0)],
                any: true
            }
            .to_string(),
            "⊢ 0, …"
        );
    }

    /// A proof keeps only the nodes its root reaches, renumbered in order,
    /// and refuses a node that points outside the arena or the forest, or
    /// at a later node.
    #[test]
    fn construction() {
        use Node::*;
        let s: Sequent = "A, A -o B |- B".parse().unwrap();
        let f = Forest::new(&s).unwrap();
        // Node 1 is unused.
        let p = Proof::new(
            f.clone(),
            vec![
                Ax(o(0), o(2)),
                One(o(4)),
                Ax(o(3), o(4)),
                Tensor(o(1), n(0), n(2)),
            ],
            n(3),
        )
        .unwrap();
        assert_eq!(
            p.nodes(),
            [Ax(o(0), o(2)), Ax(o(3), o(4)), Tensor(o(1), n(0), n(1))]
        );
        assert_eq!(p.root(), n(2));
        assert_eq!(p.check(Mode::CLASSICAL), Ok(()));
        // The root is beyond the arena.
        assert!(matches!(
            Proof::new(f.clone(), vec![Ax(o(0), o(2))], n(1)),
            Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Node,
                index: 1,
                len: 1
            })
        ));
        // A premise does not precede its conclusion.
        assert!(matches!(
            Proof::new(f.clone(), vec![Par(o(1), n(0))], n(0)),
            Err(Error::NotTopological {
                space: crate::limits::Space::Node,
                index: 0,
                parent: 0
            })
        ));
        // An occurrence beyond the forest.
        assert!(matches!(
            Proof::new(f, vec![Ax(o(0), o(5))], n(0)),
            Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Occurrence,
                index: 5,
                len: 5
            })
        ));
    }
}