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

//! The check of a refutation by saturation ([`Saturated`]).
//!
//! The certificate is a set of stable sequents, closed under the derived
//! rules of the focused calculus. None of them stands for a certain stable
//! sequent of the goal's asynchronous phase, one that a proof needs. The
//! check shares no code with the search that saturates: it reads the
//! rules off the forest again, and applies every rule to every choice of
//! premises from the set.
//!
//! # Why it refutes
//!
//! Fix the polarity of the atoms the certificate names. Focusing is
//! complete under every polarity and in every commutative mode, so a
//! provable goal has a focused proof. Its asynchronous phases end in
//! stable sequents: positive formulas and negative literals in the linear
//! zone, and the subformulas of `?` in the unrestricted one. Take each of
//! them with two changes. A negative literal under a `?` in its linear
//! zone moves back to the unrestricted zone: only a copy put it there,
//! and the copy left it there too. And the globals (below) are left out.
//!
//! By induction over the proof, every such sequent is one that a member
//! of the set stands for. The phase above it is an instance of a rule
//! below: its focus or copy, the sides of its `⊕`, the partners of its
//! axioms, and the releases ending in its premises. Each premise is one
//! that a member stands for. Applied to those members, the rule derives a
//! sequent that stands for it, since every step is monotone in what a
//! sequent stands for:
//!
//! - a member absent from a premise that absorbs or weakens it is
//!   absorbed or weakened at the step that takes it;
//! - the `&` join of two premises that stand for equal zones stands for
//!   that zone;
//! - the steps keep one output under the reading.
//!
//! That sequent, its globals left out, is coherent, since the proof's is.
//! So the closure gives a member that stands for it, and so for the
//! proof's sequent. Each stable sequent that the goal's phase ends in, a
//! hole of the phase, then has a member that stands for it: that is what
//! filling the hole means. One hole that no member fills refutes the goal.
//!
//! # The terms
//!
//! - *What a sequent stands for*: `linear ; unrestricted` stands for the
//!   stable sequents with exactly that linear zone and an unrestricted
//!   zone that holds `unrestricted`. Where it `absorbs` (a `⊤` above), or
//!   in affine mode, it also stands for those with a larger linear zone.
//!   A member in output position is then absorbed only where the zone has
//!   none, and never weakened in.
//! - *The normal form* of the partners: a negative literal under a `?`
//!   reaches the linear zone only by a copy. So an axiom takes it from the
//!   unrestricted zone, and from the linear zone only where the goal holds
//!   it, and no copy rule is read for it. A partner outside the goal's
//!   subtrees stands in no proof of the goal; a goal other than the roots
//!   has such occurrences beside it.
//! - *Coherence*: outside the subformulas of `?`, no sequent of a proof
//!   holds an occurrence twice, or two that a connective other than `⅋`
//!   joins, given a goal whose own members are coherent. Two occurrences
//!   are joined that way when one lies below the other, or when a `⊗`, `&`
//!   or `⊕` lies above both, which sends them to different premises or
//!   keeps one side. The check tests only the neighbours in a sorted list:
//!   the forest numbers its occurrences in preorder, and the common
//!   ancestors of a sorted list are those of its neighbours.
//! - *The globals* are the subformulas of the `?` the goal reaches through
//!   `⅋` alone. They are in the unrestricted zone of every sequent of a
//!   proof, since the goal's phase decomposes the `?` before any `&`. So a
//!   set's sequents may leave them out, and a sequent derived is compared
//!   with them left out.

use super::refutation::{RefutationFault, Saturated, Stable};
use crate::hash::HashMap;
use crate::linear::fragment::Mode;
use crate::linear::occurrences::{Forest, OccId, Reading, Side, Sign};
use crate::linear::sequents::Kind;

/// Why a check did not accept a certificate: it does not hold, or the
/// stop fired before the check ended.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Failed {
    /// The certificate does not hold.
    Fault(RefutationFault),
    /// The stop fired.
    Stopped,
}

impl From<RefutationFault> for Failed {
    /// The fault as a failure.
    fn from(fault: RefutationFault) -> Self {
        Failed::Fault(fault)
    }
}

/// How many units of work the check does between two polls of its stop.
const UNITS_PER_POLL: u64 = 1 << 16;

/// A sequent as the check derives it: its linear zone sorted with repeats,
/// its unrestricted zone sorted without, and whether a `⊤` above absorbs
/// any further linear member.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Zone {
    /// The linear zone.
    linear: Vec<OccId>,
    /// The unrestricted zone.
    unrestricted: Vec<OccId>,
    /// Whether it absorbs.
    absorbs: bool,
}

/// A step of a rule's term, written in postorder: the operands of a step
/// are the values of the steps before it, on a stack.
#[derive(Clone, Copy, Debug)]
enum Step {
    /// The axiom of a positive literal with the partner of a slot.
    Axiom(OccId, usize),
    /// `1`.
    One(OccId),
    /// `⊤`, absorbing.
    Top(OccId),
    /// The premise of a hole.
    Hole(usize),
    /// `⊗`.
    Tensor(OccId),
    /// `⊕` on the side given.
    Plus(OccId, OccId),
    /// `!`.
    Bang(OccId),
    /// `⅋`.
    Par(OccId),
    /// `⊥`.
    Bot(OccId),
    /// `?`.
    Quest(OccId),
    /// `&`.
    With(OccId),
    /// A copy of a `?` formula's subformula into the unrestricted zone.
    Copy(OccId),
}

/// The partner of a positive literal: a negative literal of its atom,
/// from the linear zone or, under a copy, from the unrestricted one.
#[derive(Clone, Copy, Debug)]
struct Partner {
    /// The negative literal.
    literal: OccId,
    /// Whether it comes from the unrestricted zone.
    unrestricted: bool,
}

/// A stable sequent that a rule's asynchronous phase ends in: the members
/// the phase takes from its premise, the subformulas of `?` it met, and
/// the release it belongs to. The `&` of a release joins its premises;
/// premises of different releases stand side by side.
#[derive(Clone, Debug)]
struct Hole {
    /// The members taken, sorted.
    leaves: Vec<OccId>,
    /// The subformulas of `?` met, sorted.
    met: Vec<OccId>,
    /// The release.
    release: usize,
}

/// A rule: its term in postorder, its holes and the partners of its slots.
#[derive(Debug, Default)]
struct Rule {
    /// The steps.
    steps: Vec<Step>,
    /// The holes, by the index their steps name.
    holes: Vec<Hole>,
    /// The partners each slot may take, by the index the steps name.
    slots: Vec<Vec<Partner>>,
}

/// Where a rule's term starts.
#[derive(Clone, Copy)]
enum Start<'g> {
    /// A focus on a positive formula.
    Focus(OccId),
    /// A copy of a `?` formula's subformula, focused on or released.
    Copy(OccId),
    /// The goal's asynchronous phase.
    Goal(&'g [OccId]),
}

/// What is left to write of a rule's term.
enum Pending {
    /// A focus on a positive formula.
    Focus(OccId),
    /// An asynchronous phase.
    Phase(Phase),
}

/// An asynchronous phase being written: the formulas left to decompose,
/// and the stable members and `?` subformulas met.
#[derive(Clone, Default)]
struct Phase {
    /// A `⊤` met.
    top: Option<OccId>,
    /// The `⅋`, `⊥` and `?` left.
    unary: Vec<OccId>,
    /// The `&` left, decomposed after the unary ones.
    withs: Vec<OccId>,
    /// The stable members met.
    leaves: Vec<OccId>,
    /// The subformulas of `?` met.
    met: Vec<OccId>,
    /// The release.
    release: usize,
}

/// The calculus the certificate is read in: the forest under its polarity
/// in the mode, and the goal.
struct Calculus<'a> {
    /// The forest.
    forest: &'a Forest,
    /// The positive literal of each atom.
    positive: &'a [Sign],
    /// The reading, in intuitionistic mode.
    reading: Option<Reading<'a>>,
    /// Whether weakening is allowed.
    affine: bool,
    /// Whether each occurrence lies below a `?`.
    copied: Vec<bool>,
    /// Whether each occurrence lies in a goal member's subtree, which a
    /// proof of the goal holds nothing outside of.
    inside: Vec<bool>,
    /// The goal's members, sorted.
    goal: Vec<OccId>,
    /// The subformulas of the `?` the goal reaches through `⅋` alone,
    /// sorted.
    globals: Vec<OccId>,
}

impl<'a> Calculus<'a> {
    /// Whether an occurrence is positive: `⊗`, `1`, `⊕`, `0`, `!`, `∃`,
    /// and the literals the polarity names.
    fn positive(&self, o: OccId) -> bool {
        match self.forest.kind(o) {
            Kind::Tensor | Kind::One | Kind::Plus | Kind::Zero | Kind::Bang | Kind::Exists => true,
            Kind::Atom | Kind::DualAtom => {
                self.forest.atom(o).map(|a| self.positive[a.index()]) == self.forest.sign(o)
            }
            Kind::Par | Kind::Bot | Kind::With | Kind::Top | Kind::Quest | Kind::Forall => false,
        }
    }

    /// Whether an occurrence stays in a stable sequent: positive, or a
    /// literal.
    fn stable(&self, o: OccId) -> bool {
        self.positive(o) || self.forest.is_literal(o)
    }

    /// Whether an occurrence is in output position.
    fn output(&self, o: OccId) -> bool {
        self.reading
            .as_ref()
            .is_some_and(|r| r.position(o) == Side::Output)
    }

    /// How many members of a list are in output position.
    fn outputs(&self, list: &[OccId]) -> usize {
        list.iter().filter(|&&o| self.output(o)).count()
    }

    /// Whether a sequent stands for larger linear zones too.
    fn weak(&self, z: &Zone) -> bool {
        z.absorbs || self.affine
    }

    /// Whether a sequent is one of the mode: under the reading one member
    /// in output position, or none where it absorbs.
    fn shaped(&self, z: &Zone) -> bool {
        self.reading.is_none() || {
            let outputs = self.outputs(&z.linear);
            outputs == 1 || (outputs == 0 && z.absorbs)
        }
    }

    /// Whether two occurrences can stand in one sequent of a proof.
    fn coherent(&self, x: OccId, y: OccId) -> bool {
        let Some(w) = self.forest.lca(x, y) else {
            return true;
        };
        self.forest.kind(w) == Kind::Quest
            || self.copied[w.index()]
            || (w != x && w != y && self.forest.kind(w) == Kind::Par)
    }

    /// Whether every two members of a sorted list can stand in one sequent
    /// of a proof.
    fn coherent_list(&self, sorted: &[OccId]) -> bool {
        sorted.windows(2).all(|w| self.coherent(w[0], w[1]))
    }

    /// Places an occurrence an asynchronous phase meets.
    fn place(&self, phase: &mut Phase, o: OccId) {
        if self.stable(o) {
            phase.leaves.push(o);
            return;
        }
        match self.forest.kind(o) {
            Kind::Top => {
                phase.top.get_or_insert(o);
            }
            Kind::With => phase.withs.push(o),
            _ => phase.unary.push(o),
        }
    }

    /// The partners of a positive literal: the negative literals of its
    /// atom within the goal's subtrees, in the other position under the
    /// reading. One directly under a `?` comes from the unrestricted zone.
    /// One that is not, or that the goal holds, comes from the linear
    /// zone. A literal outside the goal's subtrees stands in no sequent of
    /// a proof of the goal.
    fn partners(&self, p: OccId) -> Vec<Partner> {
        let forest = self.forest;
        let (Some(atom), Some(sign)) = (forest.atom(p), forest.sign(p)) else {
            return Vec::new();
        };
        let mut found = Vec::new();
        for &x in forest.literals(atom, !sign) {
            if !self.inside[x.index()] {
                continue;
            }
            if self.reading.is_some() && self.output(x) == self.output(p) {
                continue;
            }
            let quest = forest
                .parent(x)
                .is_some_and(|q| forest.kind(q) == Kind::Quest);
            if quest {
                found.push(Partner {
                    literal: x,
                    unrestricted: true,
                });
            }
            if !quest || self.goal.binary_search(&x).is_ok() {
                found.push(Partner {
                    literal: x,
                    unrestricted: false,
                });
            }
        }
        found
    }

    /// Writes the term of a rule from `start`: its steps in postorder, its
    /// holes and its slots. `sides` gives the side taken at each `⊕`, as
    /// the `⊕` and its operand. The steps are found root first, the right
    /// operand before the left, which reversed is postorder.
    fn write(&self, start: Start<'_>, sides: &[(OccId, OccId)]) -> Rule {
        let forest = self.forest;
        let mut rule = Rule::default();
        let mut found: Vec<Step> = Vec::new();
        let mut releases = 0;
        let mut release = |phase: &mut Phase| {
            phase.release = releases;
            releases += 1;
        };
        let under_focus = |o: OccId, release: &mut dyn FnMut(&mut Phase)| {
            if self.positive(o) {
                Pending::Focus(o)
            } else {
                let mut phase = Phase::default();
                release(&mut phase);
                self.place(&mut phase, o);
                Pending::Phase(phase)
            }
        };
        let root = match start {
            Start::Focus(o) => Pending::Focus(o),
            Start::Copy(o) => {
                found.push(Step::Copy(o));
                under_focus(o, &mut release)
            }
            Start::Goal(members) => {
                let mut phase = Phase::default();
                release(&mut phase);
                for &o in members {
                    self.place(&mut phase, o);
                }
                Pending::Phase(phase)
            }
        };
        let mut stack = vec![root];
        while let Some(pending) = stack.pop() {
            match pending {
                Pending::Focus(o) => match forest.kind(o) {
                    Kind::Tensor => {
                        found.push(Step::Tensor(o));
                        let (l, r) = (forest.left(o), forest.right(o));
                        for c in [l, r].into_iter().flatten() {
                            stack.push(under_focus(c, &mut release));
                        }
                    }
                    Kind::Plus => {
                        let Some(&(_, child)) = sides.iter().find(|&&(p, _)| p == o) else {
                            unreachable!("every ⊕ under the focus has a side");
                        };
                        found.push(Step::Plus(o, child));
                        stack.push(under_focus(child, &mut release));
                    }
                    Kind::One => found.push(Step::One(o)),
                    Kind::Bang => {
                        found.push(Step::Bang(o));
                        let mut phase = Phase::default();
                        release(&mut phase);
                        if let Some(c) = forest.left(o) {
                            self.place(&mut phase, c);
                        }
                        stack.push(Pending::Phase(phase));
                    }
                    Kind::Atom | Kind::DualAtom => {
                        found.push(Step::Axiom(o, rule.slots.len()));
                        rule.slots.push(self.partners(o));
                    }
                    Kind::Zero
                    | Kind::Par
                    | Kind::Bot
                    | Kind::With
                    | Kind::Top
                    | Kind::Quest
                    | Kind::Forall
                    | Kind::Exists => {
                        unreachable!("no focus on a 0, a negative formula or a binder")
                    }
                },
                Pending::Phase(mut phase) => loop {
                    if let Some(t) = phase.top {
                        found.push(Step::Top(t));
                        break;
                    }
                    if let Some(o) = phase.unary.pop() {
                        match forest.kind(o) {
                            Kind::Par => {
                                found.push(Step::Par(o));
                                for c in forest.children(o) {
                                    self.place(&mut phase, c);
                                }
                            }
                            Kind::Bot => found.push(Step::Bot(o)),
                            Kind::Quest => {
                                found.push(Step::Quest(o));
                                phase.met.extend(forest.left(o));
                            }
                            _ => unreachable!("only ⅋, ⊥ and ? are unary"),
                        }
                        continue;
                    }
                    if let Some(o) = phase.withs.pop() {
                        found.push(Step::With(o));
                        let mut left = phase.clone();
                        left.place_child(self, forest.left(o));
                        phase.place_child(self, forest.right(o));
                        stack.push(Pending::Phase(left));
                        continue;
                    }
                    phase.leaves.sort_unstable();
                    phase.met.sort_unstable();
                    found.push(Step::Hole(rule.holes.len()));
                    rule.holes.push(Hole {
                        leaves: phase.leaves,
                        met: phase.met,
                        release: phase.release,
                    });
                    break;
                },
            }
        }
        found.reverse();
        rule.steps = found;
        rule
    }
}

impl Phase {
    /// Places an operand, where there is one.
    fn place_child(&mut self, calculus: &Calculus<'_>, o: Option<OccId>) {
        if let Some(o) = o {
            calculus.place(self, o);
        }
    }
}

/// Inserts into a sorted list, keeping repeats.
fn insert(list: &mut Vec<OccId>, o: OccId) {
    let at = list.partition_point(|&x| x <= o);
    list.insert(at, o);
}

/// Returns the sum of two sorted multisets.
fn sum(a: &[OccId], b: &[OccId]) -> Vec<OccId> {
    let mut out = Vec::with_capacity(a.len() + b.len());
    let (mut i, mut j) = (0, 0);
    while i < a.len() || j < b.len() {
        if j == b.len() || (i < a.len() && a[i] <= b[j]) {
            out.push(a[i]);
            i += 1;
        } else {
            out.push(b[j]);
            j += 1;
        }
    }
    out
}

/// Returns the union of two sorted sets.
fn union(a: &[OccId], b: &[OccId]) -> Vec<OccId> {
    let mut out = sum(a, b);
    out.dedup();
    out
}

/// Returns the members of the sorted multiset `of` beyond those of the
/// sorted `within`, with repeats.
fn excess(of: &[OccId], within: &[OccId]) -> Vec<OccId> {
    let mut out = Vec::new();
    let mut j = 0;
    for &o in of {
        while j < within.len() && within[j] < o {
            j += 1;
        }
        if j < within.len() && within[j] == o {
            j += 1;
        } else {
            out.push(o);
        }
    }
    out
}

/// Whether the sorted multiset `small` lies within the sorted `large`.
fn within(small: &[OccId], large: &[OccId]) -> bool {
    let mut j = 0;
    for &o in small {
        while j < large.len() && large[j] < o {
            j += 1;
        }
        if j == large.len() || large[j] != o {
            return false;
        }
        j += 1;
    }
    true
}

/// Whether a list is sorted, without repeats where `set`.
fn sorted(list: &[OccId], set: bool) -> bool {
    list.windows(2)
        .all(|w| w[0] < w[1] || (!set && w[0] == w[1]))
}

impl Calculus<'_> {
    /// Takes a principal's subformula out of a premise's linear zone, and
    /// returns whether it could. The subformula is there; or the premise
    /// absorbs it, one in output position only where the zone has none; or
    /// in affine mode it is weakened in, never one in output position.
    fn take(&self, z: &mut Zone, o: OccId) -> bool {
        if let Ok(at) = z.linear.binary_search(&o) {
            z.linear.remove(at);
            return true;
        }
        if z.absorbs {
            return !(self.output(o) && self.outputs(&z.linear) > 0);
        }
        self.affine && !self.output(o)
    }

    /// Joins the premises of a `&`, their subformulas taken, or returns
    /// `None` where they do not join. They join when their linear zones are
    /// equal, when one that absorbs lies within one that does not, or when
    /// both absorb, to the larger count of each member. In affine mode
    /// either side may be weakened up to that, never with a member in
    /// output position.
    fn join(&self, l: Zone, r: Zone) -> Option<Zone> {
        let most = sum(&l.linear, &excess(&r.linear, &l.linear));
        let joined = match (l.absorbs, r.absorbs) {
            (true, true) => true,
            (false, false) => l.linear == r.linear,
            (true, false) => within(&l.linear, &r.linear),
            (false, true) => within(&r.linear, &l.linear),
        };
        if !joined {
            let weakened = |side: &Zone| {
                side.absorbs || excess(&most, &side.linear).iter().all(|&o| !self.output(o))
            };
            if !(self.affine && weakened(&l) && weakened(&r)) {
                return None;
            }
        }
        Some(Zone {
            linear: most,
            unrestricted: union(&l.unrestricted, &r.unrestricted),
            absorbs: l.absorbs && r.absorbs,
        })
    }

    /// Evaluates a rule's term over the premises of its holes and the
    /// partners of its slots, given by index into `set` and into each
    /// slot's list. Returns the sequent derived, or `None` where a step's
    /// condition fails. Adds to `units` a unit for each step and for each
    /// member of the zone it yields.
    fn derive(
        &self,
        rule: &Rule,
        set: &[Zone],
        premises: &[usize],
        partners: &[usize],
        units: &mut u64,
    ) -> Option<Zone> {
        let forest = self.forest;
        let mut stack: Vec<Zone> = Vec::new();
        for &step in &rule.steps {
            let z = match step {
                Step::Axiom(p, slot) => {
                    let partner = rule.slots[slot][partners[slot]];
                    let mut z = Zone {
                        linear: vec![p],
                        ..Zone::default()
                    };
                    if partner.unrestricted {
                        z.unrestricted.push(partner.literal);
                    } else {
                        insert(&mut z.linear, partner.literal);
                    }
                    z
                }
                Step::One(o) => Zone {
                    linear: vec![o],
                    ..Zone::default()
                },
                Step::Top(o) => Zone {
                    linear: vec![o],
                    unrestricted: Vec::new(),
                    absorbs: true,
                },
                Step::Hole(h) => set[premises[h]].clone(),
                Step::Tensor(o) => {
                    let mut r = stack.pop()?;
                    let mut l = stack.pop()?;
                    if !self.take(&mut l, forest.left(o)?) || !self.take(&mut r, forest.right(o)?) {
                        return None;
                    }
                    let mut z = Zone {
                        linear: sum(&l.linear, &r.linear),
                        unrestricted: union(&l.unrestricted, &r.unrestricted),
                        absorbs: l.absorbs || r.absorbs,
                    };
                    insert(&mut z.linear, o);
                    z
                }
                Step::Plus(o, child) => {
                    let mut z = stack.pop()?;
                    if !self.take(&mut z, child) {
                        return None;
                    }
                    insert(&mut z.linear, o);
                    z
                }
                Step::Bang(o) => {
                    let mut z = stack.pop()?;
                    if !self.take(&mut z, forest.left(o)?) || !z.linear.is_empty() {
                        return None;
                    }
                    z.absorbs = false;
                    insert(&mut z.linear, o);
                    z
                }
                Step::Par(o) => {
                    let mut z = stack.pop()?;
                    if !self.take(&mut z, forest.left(o)?) || !self.take(&mut z, forest.right(o)?) {
                        return None;
                    }
                    insert(&mut z.linear, o);
                    z
                }
                Step::Bot(o) => {
                    let mut z = stack.pop()?;
                    insert(&mut z.linear, o);
                    z
                }
                Step::Quest(o) => {
                    let mut z = stack.pop()?;
                    let a = forest.left(o)?;
                    z.unrestricted.retain(|&x| x != a);
                    insert(&mut z.linear, o);
                    z
                }
                Step::With(o) => {
                    let mut r = stack.pop()?;
                    let mut l = stack.pop()?;
                    if !self.take(&mut l, forest.left(o)?) || !self.take(&mut r, forest.right(o)?) {
                        return None;
                    }
                    let mut z = self.join(l, r)?;
                    insert(&mut z.linear, o);
                    z
                }
                Step::Copy(o) => {
                    let mut z = stack.pop()?;
                    if !self.take(&mut z, o) {
                        return None;
                    }
                    z.unrestricted = union(&z.unrestricted, &[o]);
                    z
                }
            };
            *units += 1 + (z.linear.len() + z.unrestricted.len()) as u64;
            if !self.shaped(&z) {
                return None;
            }
            stack.push(z);
        }
        let z = stack.pop()?;
        stack.is_empty().then_some(z)
    }

    /// Calls `each` with every rule, and counts each choice looked at as
    /// work. The rules are a focus on every positive formula a stable
    /// sequent can hold (one whose parent is `⅋`, `&` or `!`, or a member
    /// of the goal), and a copy of every subformula of a `?` but a negative
    /// literal. Each is taken under every choice of the sides of its `⊕`,
    /// leaving out a choice that reaches a `0`.
    fn rules(
        &self,
        work: &mut Work<'_>,
        each: &mut dyn FnMut(&Rule, &mut Work<'_>) -> Result<(), Failed>,
    ) -> Result<(), Failed> {
        let forest = self.forest;
        let mut previous = None;
        for &g in &self.goal {
            if previous.replace(g) == Some(g) {
                continue;
            }
            for o in forest.subtree(g) {
                let parent = forest.parent(o).filter(|_| o != g).map(|p| forest.kind(p));
                let mut starts = Vec::new();
                if self.positive(o)
                    && matches!(parent, None | Some(Kind::Par | Kind::With | Kind::Bang))
                {
                    starts.push(Start::Focus(o));
                }
                if parent == Some(Kind::Quest) && !(forest.is_literal(o) && !self.positive(o)) {
                    starts.push(Start::Copy(o));
                }
                for start in starts {
                    let mut open: Vec<Vec<(OccId, OccId)>> = vec![Vec::new()];
                    'plans: while let Some(sides) = open.pop() {
                        work.add(1)?;
                        let mut walk = vec![o];
                        while let Some(x) = walk.pop() {
                            match forest.kind(x) {
                                Kind::Tensor => {
                                    walk.extend(forest.children(x).filter(|&c| self.positive(c)))
                                }
                                Kind::Plus => match sides.iter().find(|&&(p, _)| p == x) {
                                    Some(&(_, child)) => {
                                        if self.positive(child) {
                                            walk.push(child);
                                        }
                                    }
                                    None => {
                                        for child in forest.children(x) {
                                            let mut more = sides.clone();
                                            more.push((x, child));
                                            open.push(more);
                                        }
                                        continue 'plans;
                                    }
                                },
                                Kind::Zero => continue 'plans,
                                _ => {}
                            }
                        }
                        let rule = self.write(start, &sides);
                        work.add(rule.steps.len() as u64)?;
                        each(&rule, work)?;
                    }
                }
            }
        }
        Ok(())
    }
}

/// The work of a check, polled against its stop.
struct Work<'s> {
    /// The units since the last poll.
    unpolled: u64,
    /// The stop, told the units at each poll.
    stop: &'s mut dyn FnMut(u64) -> bool,
}

impl Work<'_> {
    /// Counts units of work, polling the stop once enough are done.
    fn add(&mut self, units: u64) -> Result<(), Failed> {
        self.unpolled = self.unpolled.saturating_add(units);
        if self.unpolled >= UNITS_PER_POLL && (self.stop)(std::mem::take(&mut self.unpolled)) {
            return Err(Failed::Stopped);
        }
        Ok(())
    }
}

/// The certificate's sequents, indexed by what the check asks of them.
struct Set {
    /// The sequents.
    zones: Vec<Zone>,
    /// The sequents that stand for their linear zone alone, by it.
    exact: HashMap<Vec<OccId>, Vec<usize>>,
    /// Those, by every member of their linear zone.
    holding: HashMap<OccId, Vec<usize>>,
    /// Those with an empty linear zone.
    exact_empty: Vec<usize>,
    /// The sequents that stand for larger linear zones too.
    weak: Vec<usize>,
    /// Those, by the first member of their linear zone.
    weak_first: HashMap<OccId, Vec<usize>>,
    /// Those with an empty linear zone.
    weak_empty: Vec<usize>,
}

impl Set {
    /// Indexes the sequents.
    fn new(calculus: &Calculus<'_>, zones: Vec<Zone>) -> Self {
        let mut set = Set {
            zones: Vec::new(),
            exact: HashMap::default(),
            holding: HashMap::default(),
            exact_empty: Vec::new(),
            weak: Vec::new(),
            weak_first: HashMap::default(),
            weak_empty: Vec::new(),
        };
        for (i, z) in zones.iter().enumerate() {
            if calculus.weak(z) {
                set.weak.push(i);
                match z.linear.first() {
                    Some(&o) => set.weak_first.entry(o).or_default().push(i),
                    None => set.weak_empty.push(i),
                }
            } else {
                set.exact.entry(z.linear.clone()).or_default().push(i);
                let mut members = z.linear.clone();
                members.dedup();
                for o in members {
                    set.holding.entry(o).or_default().push(i);
                }
                if z.linear.is_empty() {
                    set.exact_empty.push(i);
                }
            }
        }
        set.zones = zones;
        set
    }

    /// Returns the sequents that can go into a hole: those that stand for
    /// their zone alone and hold the hole's members, and every one that
    /// stands for larger zones. Any other fails at the step that takes the
    /// member it lacks. Counts a unit for each sequent looked at and for
    /// each member compared.
    fn candidates(&self, hole: &Hole, work: &mut Work<'_>) -> Result<Vec<usize>, Failed> {
        let mut out: Vec<usize> = match hole.leaves.first() {
            None => self.exact.values().flatten().copied().collect(),
            Some(o) => {
                let holding = self.holding.get(o).map_or(&[][..], Vec::as_slice);
                let compared: usize = holding.iter().map(|&i| self.zones[i].linear.len()).sum();
                work.add((holding.len() + compared) as u64)?;
                holding
                    .iter()
                    .copied()
                    .filter(|&i| within(&hole.leaves, &self.zones[i].linear))
                    .collect()
            }
        };
        out.extend(&self.weak);
        work.add(out.len() as u64)?;
        Ok(out)
    }

    /// Returns whether a sequent of the set stands for every sequent that
    /// `c` stands for.
    ///
    /// A sequent that stands for its linear zone alone does, where it has
    /// `c`'s linear zone and an unrestricted zone within `c`'s, and `c`
    /// does not stand for more. A sequent that stands for larger zones
    /// does, where both its zones lie within `c`'s. Its members in output
    /// position are then those of `c`, or absorbed: the set's sequents are
    /// shaped, and `c`'s linear zone holds at most one such member.
    fn subsumes(
        &self,
        calculus: &Calculus<'_>,
        c: &Zone,
        work: &mut Work<'_>,
    ) -> Result<bool, Failed> {
        if !calculus.weak(c)
            && let Some(list) = self.exact.get(&c.linear)
        {
            for &i in list {
                work.add(1 + self.zones[i].unrestricted.len() as u64)?;
                if within(&self.zones[i].unrestricted, &c.unrestricted) {
                    return Ok(true);
                }
            }
        }
        let mut firsts = c.linear.clone();
        firsts.dedup();
        let lists = firsts
            .iter()
            .filter_map(|o| self.weak_first.get(o))
            .chain([&self.weak_empty]);
        for list in lists {
            for &i in list {
                let s = &self.zones[i];
                work.add(1 + (s.linear.len() + s.unrestricted.len()) as u64)?;
                if within(&s.linear, &c.linear) && within(&s.unrestricted, &c.unrestricted) {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }
}

/// Checks a refutation by saturation of the goal `goal` of the forest in
/// `mode`, polling `stop` with its units of work. The module's
/// documentation says why such a set refutes.
///
/// The check passes when:
///
/// - the certificate names a positive literal for each atom, and
///   occurrences of the forest in sorted zones;
/// - its sequents are sequents of the mode;
/// - every rule, applied to every choice of its premises among them and
///   of its axioms' partners, derives a sequent that cannot stand in a
///   proof or that one of them stands for, and so does Mix where the mode
///   has it;
/// - some stable sequent of the goal's phase is one that none of them
///   stands for.
pub(crate) fn check(
    forest: &Forest,
    goal: &[OccId],
    mode: Mode,
    saturated: &Saturated,
    stop: &mut dyn FnMut(u64) -> bool,
) -> Result<(), Failed> {
    const INVARIANT: &str = "saturation";
    let not_applicable = |why| {
        Failed::Fault(RefutationFault::NotApplicable {
            invariant: INVARIANT,
            why,
        })
    };
    if mode.is_ordered() {
        return Err(not_applicable(
            "its rules are those of the commutative modes",
        ));
    }
    if mode.intuitionistic && mode.has_mix() {
        return Err(not_applicable("intuitionistic mode has no Mix"));
    }
    if saturated.positive.len() != forest.sequent().atom_names().len() {
        return Err(RefutationFault::Mismatch.into());
    }
    let len = forest.len();
    let ours =
        |list: &[OccId], set: bool| sorted(list, set) && list.iter().all(|o| o.index() < len);
    if !saturated
        .sequents
        .iter()
        .all(|s| ours(&s.linear, false) && ours(&s.unrestricted, true))
    {
        return Err(RefutationFault::Mismatch.into());
    }
    let reading = if mode.intuitionistic {
        Some(
            Reading::of_mode(forest, mode)
                .map_err(|_| not_applicable("the sequent has no intuitionistic reading"))?,
        )
    } else {
        None
    };
    let mut copied = vec![false; len];
    for i in 0..len {
        let o = OccId::new(i as u32);
        if let Some(p) = forest.parent(o) {
            copied[i] = copied[p.index()] || forest.kind(p) == Kind::Quest;
        }
    }
    let mut members = goal.to_vec();
    members.sort_unstable();
    let mut inside = vec![false; len];
    for &g in goal {
        for o in forest.subtree(g) {
            inside[o.index()] = true;
        }
    }
    let mut globals = Vec::new();
    let mut walk = members.clone();
    while let Some(o) = walk.pop() {
        match forest.kind(o) {
            Kind::Par => walk.extend(forest.children(o)),
            Kind::Quest => globals.extend(forest.left(o)),
            _ => {}
        }
    }
    globals.sort_unstable();
    globals.dedup();
    let calculus = Calculus {
        forest,
        positive: &saturated.positive,
        reading,
        affine: mode.is_affine(),
        copied,
        inside,
        goal: members,
        globals,
    };
    if !calculus.coherent_list(&calculus.goal) {
        return Err(not_applicable(
            "two members of the goal can stand in no sequent of a proof together",
        ));
    }
    let zones: Vec<Zone> = saturated
        .sequents
        .iter()
        .map(|s: &Stable| Zone {
            linear: s.linear.clone(),
            unrestricted: s.unrestricted.clone(),
            absorbs: s.absorbs,
        })
        .collect();
    if !zones.iter().all(|z| calculus.shaped(z)) {
        return Err(RefutationFault::Unshaped.into());
    }
    let set = Set::new(&calculus, zones);
    let mut work = Work { unpolled: 0, stop };
    // Checks a sequent derived, its globals left out: it cannot stand in a
    // proof, or a sequent of the set stands for it.
    let closed = |mut c: Zone, work: &mut Work<'_>| -> Result<(), Failed> {
        c.unrestricted
            .retain(|o| calculus.globals.binary_search(o).is_err());
        work.add((c.linear.len() + c.unrestricted.len()) as u64)?;
        let all = sum(&c.linear, &c.unrestricted);
        if !calculus.coherent_list(&all) || set.subsumes(&calculus, &c, work)? {
            return Ok(());
        }
        Err(RefutationFault::NotClosed.into())
    };
    calculus.rules(&mut work, &mut |rule, work| {
        let lists = rule
            .holes
            .iter()
            .map(|h| set.candidates(h, work))
            .collect::<Result<Vec<Vec<usize>>, Failed>>()?;
        if lists.iter().any(Vec::is_empty) || rule.slots.iter().any(Vec::is_empty) {
            return Ok(());
        }
        // What each candidate brings beside the hole's members. The `&`
        // steps of a release join its premises, so two of them that stand
        // for their zone alone must bring the same.
        let contexts: Vec<Vec<Vec<OccId>>> = rule
            .holes
            .iter()
            .zip(&lists)
            .map(|(h, list)| {
                list.iter()
                    .map(|&i| excess(&set.zones[i].linear, &h.leaves))
                    .collect()
            })
            .collect();
        let compared: usize = lists
            .iter()
            .flatten()
            .map(|&i| set.zones[i].linear.len())
            .sum();
        work.add(compared as u64)?;
        let fits = |at: &[usize], j: usize| {
            let p = lists[j][at[j]];
            calculus.weak(&set.zones[p])
                || (0..j).all(|i| {
                    let q = lists[i][at[i]];
                    rule.holes[i].release != rule.holes[j].release
                        || calculus.weak(&set.zones[q])
                        || contexts[i][at[i]] == contexts[j][at[j]]
                })
        };
        let holes = rule.holes.len();
        let mut at = vec![0usize; holes];
        let mut premises = vec![0usize; holes];
        let mut j = 0;
        loop {
            if j == holes {
                for (p, (&a, list)) in premises.iter_mut().zip(at.iter().zip(&lists)) {
                    *p = list[a];
                }
                let mut partners = vec![0usize; rule.slots.len()];
                loop {
                    let mut units = 0;
                    let derived =
                        calculus.derive(rule, &set.zones, &premises, &partners, &mut units);
                    work.add(units)?;
                    if let Some(c) = derived {
                        closed(c, work)?;
                    }
                    let mut more = false;
                    for (k, p) in partners.iter_mut().enumerate() {
                        *p += 1;
                        if *p < rule.slots[k].len() {
                            more = true;
                            break;
                        }
                        *p = 0;
                    }
                    if !more {
                        break;
                    }
                }
                if holes == 0 {
                    return Ok(());
                }
                j = holes - 1;
                at[j] += 1;
            }
            while at[j] < lists[j].len() && !fits(&at, j) {
                work.add(1 + j as u64)?;
                at[j] += 1;
            }
            if at[j] < lists[j].len() {
                j += 1;
            } else if j == 0 {
                return Ok(());
            } else {
                at[j] = 0;
                j -= 1;
                at[j] += 1;
            }
        }
    })?;
    if mode.has_mix() && !calculus.affine {
        for i in 0..set.zones.len() {
            for k in i..set.zones.len() {
                let (l, r) = (&set.zones[i], &set.zones[k]);
                closed(
                    Zone {
                        linear: sum(&l.linear, &r.linear),
                        unrestricted: union(&l.unrestricted, &r.unrestricted),
                        absorbs: l.absorbs || r.absorbs,
                    },
                    &mut work,
                )?;
            }
        }
    }
    // The goal's phase: a proof would need each of its stable sequents,
    // and some is one that no sequent of the set stands for.
    let phase = calculus.write(Start::Goal(&calculus.goal), &[]);
    let fills = |s: &Zone, hole: &Hole| {
        within(&s.unrestricted, &hole.met)
            && within(&s.linear, &hole.leaves)
            && (calculus.weak(s) || s.linear.len() == hole.leaves.len())
            && (s.absorbs
                || excess(&hole.leaves, &s.linear)
                    .iter()
                    .all(|&o| !calculus.output(o)))
    };
    let mut open = false;
    for hole in &phase.holes {
        let mut filled = false;
        for s in &set.zones {
            work.add(1 + (s.linear.len() + s.unrestricted.len()) as u64)?;
            if fills(s, hole) {
                filled = true;
                break;
            }
        }
        if !filled {
            open = true;
            break;
        }
    }
    if !open {
        return Err(RefutationFault::Filled.into());
    }
    Ok(())
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::{Failed, check};
    use crate::linear::occurrences::{Forest, OccId, Sign};
    use crate::linear::search::{
        Engine, Options, Refutation, RefutationFault, Saturated, Stable, Verdict, prove,
    };
    use crate::linear::{Mode, Sequent};

    /// Returns the forest of a sequent and the saturated set the inverse
    /// method refutes it with in `mode`.
    fn saturated(text: &str, mode: Mode) -> (Forest, Saturated) {
        let sequent: Sequent = text.parse().unwrap();
        let options = Options::default().with_engine(Some(Engine::Inverse));
        let outcome = prove(&sequent, mode, &options).unwrap();
        let Verdict::Unprovable(disproof) = outcome.verdict else {
            panic!("{text} in {mode}: {:?}", outcome.verdict);
        };
        let Refutation::Saturated(set) = disproof.refutation().clone() else {
            panic!("{text} in {mode}: {disproof}");
        };
        (Forest::new(&sequent).unwrap(), set)
    }

    /// Checks a set as the refutation of a sequent's roots in `mode`.
    fn checked(forest: &Forest, mode: Mode, set: &Saturated) -> Result<(), Failed> {
        check(forest, forest.roots(), mode, set, &mut |_| false)
    }

    /// A goal other than the roots: a literal of the atom outside the
    /// goal's subtrees is no partner, and the engine's set passes. A check
    /// that took every literal of the forest as a partner would refuse the
    /// set as not closed.
    #[test]
    fn a_goal_off_the_roots_is_refuted() {
        let sequent: Sequent = "|- ((?a par ?~a) par (b * ~b)) * (a * ~a)".parse().unwrap();
        let forest = Forest::new(&sequent).unwrap();
        let members = [crate::linear::Member::new(1)];
        let goal = crate::linear::search::Goal::new(&forest, &members).unwrap();
        let options = Options::default().with_engine(Some(Engine::Inverse));
        let outcome = crate::linear::search::prove_goal(
            goal,
            Mode::CLASSICAL,
            &options,
            &crate::Limits::default(),
            |_| false,
        )
        .unwrap();
        let Verdict::Unprovable(disproof) = outcome.verdict else {
            panic!("{:?}", outcome.verdict);
        };
        assert!(matches!(disproof.refutation(), Refutation::Saturated(_)));
        assert_eq!(disproof.check(), Ok(()));
    }

    /// The sets the inverse method refutes with pass in every commutative
    /// mode.
    #[test]
    fn the_engines_sets_pass() {
        for (text, mode) in [
            ("|- ?~a * ?~a, !a", Mode::CLASSICAL),
            ("|- ?~a * ?~a, !a", Mode::CLASSICAL.with_mix()),
            ("|- ?~a * ?~a, !a", Mode::CLASSICAL.with_affine()),
            ("|- ?(~a * ~a), !a", Mode::CLASSICAL),
            ("|- a, ~a, !b, ?~b", Mode::CLASSICAL),
            ("!(a -o b), a |- b * b", Mode::INTUITIONISTIC),
            ("!(a -o b), !(b -o c), a |- c * c", Mode::INTUITIONISTIC),
            ("!(a -o b), a |- b * b", Mode::INTUITIONISTIC.with_affine()),
        ] {
            let (forest, set) = saturated(text, mode);
            assert_eq!(checked(&forest, mode, &set), Ok(()), "{text} in {mode}");
        }
    }

    /// A set is refused for each condition of the check it breaks: a
    /// polarity for another number of atoms, a member past the forest or a
    /// zone out of order, a sequent of another shape than the mode's, a
    /// rule (one without premises among them) or Mix whose sequent derived
    /// none of the set stands for, a set that gives every stable sequent
    /// of the goal's phase, and an ordered mode.
    #[test]
    fn a_wrong_set_is_refused() {
        let fault = |f| Err(Failed::Fault(f));
        let intuitionistic = Mode::INTUITIONISTIC;
        let (forest, set) = saturated("!(a -o b), a |- b * b", intuitionistic);
        let refused = |set: Saturated| checked(&forest, intuitionistic, &set);
        let with = |change: &dyn Fn(&mut Saturated)| {
            let mut set = set.clone();
            change(&mut set);
            set
        };
        let past = OccId::new(forest.len() as u32);
        assert_eq!(
            refused(with(&|s| s.positive.push(Sign::Atom))),
            fault(RefutationFault::Mismatch)
        );
        assert_eq!(
            refused(with(&|s| s.sequents[0].linear.push(past))),
            fault(RefutationFault::Mismatch)
        );
        assert_eq!(
            refused(with(&|s| {
                let z = &mut s.sequents[0].unrestricted;
                z.extend([OccId::new(1), OccId::new(0)]);
            })),
            fault(RefutationFault::Mismatch)
        );
        // Two members in output position: the goal's `b ⊗ b` twice.
        let goal = forest.roots()[forest.roots().len() - 1];
        assert_eq!(
            refused(with(&|s| s.sequents.push(Stable::new(
                vec![goal, goal],
                Vec::new(),
                false
            )))),
            fault(RefutationFault::Unshaped)
        );
        // No sequent at all: the axioms, which have no premises, derive
        // ones none stands for.
        assert_eq!(
            refused(with(&|s| s.sequents.clear())),
            fault(RefutationFault::NotClosed)
        );
        // Each sequent the search kept left out: one at least is needed.
        assert!((0..set.sequents.len()).any(|i| refused(with(&|s| {
            s.sequents.remove(i);
        })) == fault(RefutationFault::NotClosed)));
        // One sequent that absorbs everything: closed, and it gives the
        // goal every stable sequent it needs.
        assert_eq!(
            refused(with(
                &|s| s.sequents = vec![Stable::new(Vec::new(), Vec::new(), true)]
            )),
            fault(RefutationFault::Filled)
        );
        assert_eq!(
            checked(&forest, Mode::CYCLIC, &set),
            fault(RefutationFault::NotApplicable {
                invariant: "saturation",
                why: "its rules are those of the commutative modes",
            })
        );
        // The set of `⊢ a, ~a` and `⊢ !b ; ~b` is closed under the rules,
        // but not under Mix, which joins them into a sequent of the goal's.
        let (forest, set) = saturated("|- a, ~a, !b, ?~b", Mode::CLASSICAL);
        assert_eq!(
            checked(&forest, Mode::CLASSICAL.with_mix(), &set),
            fault(RefutationFault::NotClosed)
        );
    }
}