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

//! Ordinary propositional logic: classical, intuitionistic and minimal.
//!
//! [`decide()`] says whether a [`Sequent`] is valid in a [`Logic`]. A
//! valid sequent comes with checked [`Evidence`]: a derivation of LK
//! (classical logic) or LJ (intuitionistic and minimal logic), Gentzen's
//! sequent calculi, which [`Derivation::check`] accepted; or, from the SAT
//! solver in classical logic, a clausal proof that the crate's checker
//! accepted. A sequent that is not valid comes with a checked Kripke model
//! that refutes it ([`Countermodel`]) where the method finds one.
//! [`decide_within`] does the same under the caller's bounds, search
//! options and stop.
//!
//! [`Method`] chooses how a sequent is decided:
//! - a SAT solver, the default for every logic; it needs the cargo feature
//!   `sat`, on by default;
//! - Dyckhoff's calculus LJT, for intuitionistic and minimal logic, their
//!   default without `sat`;
//! - the embedding, classical logic's default without `sat`. It translates
//!   the sequent into linear logic by a [`Translation`] ([`translate()`]
//!   returns an [`Image`]: a linear sequent and the mode to prove it in),
//!   and reads the linear proof back ([`Image::read_back`]). Classical
//!   logic goes into affine MALL, intuitionistic and minimal logic into
//!   intuitionistic linear logic.
//!
//! [`Method::default_for`] says which evidence the default keeps from the
//! other methods.
//!
//! The excluded middle is not valid in intuitionistic logic, the default:
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::ordinary::{Options, Sequent, Verdict, decide};
//!
//! let sequent: Sequent = "a \\/ ~a".parse()?;
//! let outcome = decide(&sequent, &Options::default())?;
//! match &outcome.verdict {
//!     Verdict::Valid(evidence) => println!("valid\n{}", evidence.derivation()?),
//!     Verdict::NotValid => println!("not valid"),
//!     _ => println!("unknown"),
//! }
//! if let Some(countermodel) = &outcome.countermodel {
//!     println!("{}", countermodel.model);
//! }
//! assert!(matches!(outcome.verdict, Verdict::NotValid));
//! # Ok::<(), deduxit::Error>(())
//! ```

// A new variant must be decided at every arm, never fall into an
// existing one.
#![deny(clippy::wildcard_enum_match_arm)]

/// Deciding an ordinary sequent in one call.
mod decide;
/// The derivations of LK and LJ, the read-back and its check.
mod derivation;
/// Step-by-step proving in LK and LJ.
#[cfg(feature = "interactive")]
mod interactive;
pub mod ljt;
/// The check of a Kripke model.
mod model;
#[cfg(feature = "parse")]
mod parse;
/// The certificates over `Prop`.
#[cfg(feature = "rocq")]
pub(crate) mod rocq;
#[cfg(feature = "sat")]
pub mod sat;
/// The translations into linear logic.
mod table;
#[cfg(feature = "interactive")]
mod tableau;
mod translate;

pub use decide::{
    EVIDENCE_WORK, Evidence, Outcome, Search, Verdict, decide, decide_within, gives_way,
};
pub use derivation::{Derivation, Inference, Rule, Side};
#[cfg(all(feature = "interactive", feature = "serialize"))]
pub(crate) use interactive::Parts;
#[cfg(feature = "interactive")]
pub use interactive::{Applicable, Closed, Context, Hint, Interactive, Needs, Step, StepError};
pub use model::{Countermodel, Forcing, MODEL_CELLS};
#[cfg(feature = "parse")]
pub use parse::{Problem, read_tptp};
pub use table::{TruthTable, truth_table};
#[cfg(feature = "interactive")]
pub use tableau::{End, Sign, Signed, Tableau, TableauNode};
pub use translate::{FALSE, Image, translate};

use crate::Error;
use crate::hash::HashMap;
use crate::limits::{Refusal, Space};
use crate::linear::fragment::{Fragment, Mode};
use crate::linear::sequents::notation::TEXT;
use crate::linear::sequents::{Stop, Stops};
use std::fmt::{Display, Formatter, Result as FmtResult, Write};

/// An ordinary propositional logic.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Logic {
    /// Classical logic, whose derivations are LK's.
    Classical,
    /// Intuitionistic logic, whose derivations are LJ's.
    #[default]
    Intuitionistic,
    /// Minimal logic: intuitionistic logic without ex falso. False is a
    /// proposition like any other and does not prove every formula.
    Minimal,
}

impl Logic {
    /// Every logic, in the order of [`NAMES`](Self::NAMES).
    pub const ALL: &'static [Self] = &[Self::Classical, Self::Intuitionistic, Self::Minimal];

    /// The logics' names, which [`name`](Self::name) writes and `FromStr`
    /// reads.
    pub const NAMES: &'static [&'static str] = &["classical", "intuitionistic", "minimal"];

    /// Returns the logic's name in lower case.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Classical => "classical",
            Self::Intuitionistic => "intuitionistic",
            Self::Minimal => "minimal",
        }
    }

    /// Returns the name of its sequent calculus: LK, or LJ for the other
    /// two.
    pub const fn calculus(self) -> &'static str {
        match self {
            Self::Classical => "LK",
            Self::Intuitionistic | Self::Minimal => "LJ",
        }
    }
}

impl Display for Logic {
    /// Writes the logic's [`name`](Self::name).
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())
    }
}

impl std::str::FromStr for Logic {
    type Err = Error;

    /// Reads a logic's [`name`](Self::name), one of
    /// [`NAMES`](Self::NAMES).
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::ALL
            .iter()
            .copied()
            .find(|logic| logic.name() == name)
            .ok_or_else(|| Error::UnknownName {
                what: "logic",
                name: name.into(),
                known: Self::NAMES,
            })
    }
}

/// A translation of ordinary logic into linear logic, by its name.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum Translation {
    /// Classical logic into affine MALL: the one-sided sequent in negation
    /// normal form, `∧` as `&`, `∨` as `⅋`, true as `⊤`, false as `⊥`, an
    /// implication `A → B` as `¬A ∨ B` and `A ↔ B` as `(A → B) ∧ (B → A)`.
    #[cfg_attr(feature = "serialize", serde(rename = "affine"))]
    Affine,
    /// Girard's call-by-name translation into ILL: `A → B` as `!A ⊸ B`,
    /// `∧` as `&`, `A ∨ B` as `!A ⊕ !B`, `¬A` as `!A ⊸ 0`, true as `⊤`,
    /// false as `0`, every hypothesis under `!`.
    #[cfg_attr(feature = "serialize", serde(rename = "cbn"))]
    CallByName,
    /// Girard's call-by-value translation into ILL: an atom `a` as `!a`,
    /// `A → B` as `!(A ⊸ B)`, `∧` as `⊗`, `∨` as `⊕`, `¬A` as `!(A ⊸ 0)`,
    /// true as `1`, false as `0`.
    #[cfg_attr(feature = "serialize", serde(rename = "cbv"))]
    CallByValue,
    /// Liang and Miller's 0/1 translation into ILL, as the LLTP library
    /// states it: hypotheses by the negative translation `t₀` under `!`,
    /// the goal by the positive one `t₁`, with `t₀(A ∧ B) = !t₀A & !t₀B`,
    /// `t₀(A → B) = !t₁A ⊸ !t₀B`, `t₁(A ∧ B) = !(t₁A & t₁B)`,
    /// `t₁(A → B) = !(!t₀A ⊸ t₁B)`, `A ∨ B` as `!A ⊕ !B` in both, true as
    /// `⊤` and `1`, false as `0`, and `¬A` as `A → false`.
    #[cfg_attr(feature = "serialize", serde(rename = "01"))]
    ZeroOne,
}

impl Translation {
    /// Every translation, in the order of [`NAMES`](Self::NAMES).
    pub const ALL: &'static [Self] = &[
        Self::Affine,
        Self::CallByName,
        Self::CallByValue,
        Self::ZeroOne,
    ];

    /// The translation that decides intuitionistic and minimal logic by
    /// default, chosen by a run of the ILTP library's propositional
    /// problems.
    pub const DEFAULT_INTUITIONISTIC: Self = Self::CallByName;

    /// The translations' names, which [`name`](Self::name) writes and
    /// `FromStr` reads.
    pub const NAMES: &'static [&'static str] = &["affine", "cbn", "cbv", "01"];

    /// Returns the translation's short name: `affine`, `cbn`, `cbv` or
    /// `01`, as the command and the JSON spell it.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Affine => "affine",
            Self::CallByName => "cbn",
            Self::CallByValue => "cbv",
            Self::ZeroOne => "01",
        }
    }

    /// Returns the translation the logic is decided with by default:
    /// [`Affine`](Self::Affine) for classical logic,
    /// [`DEFAULT_INTUITIONISTIC`](Self::DEFAULT_INTUITIONISTIC) for the
    /// others.
    pub const fn default_for(logic: Logic) -> Self {
        match logic {
            Logic::Classical => Self::Affine,
            Logic::Intuitionistic | Logic::Minimal => Self::DEFAULT_INTUITIONISTIC,
        }
    }

    /// Returns whether the translation decides the logic: the affine one
    /// classical logic, the others intuitionistic and minimal logic.
    pub const fn decides(self, logic: Logic) -> bool {
        matches!(
            (self, logic),
            (Self::Affine, Logic::Classical)
                | (
                    Self::CallByName | Self::CallByValue | Self::ZeroOne,
                    Logic::Intuitionistic | Logic::Minimal
                )
        )
    }

    /// Returns the fragment and mode of the translation's images: MALL in
    /// classical affine mode, or LL in intuitionistic mode.
    pub const fn target(self) -> Target {
        match self {
            Self::Affine => Target {
                fragment: Fragment::MALL,
                mode: Mode::CLASSICAL.with_affine(),
            },
            Self::CallByName | Self::CallByValue | Self::ZeroOne => Target {
                fragment: Fragment::LL,
                mode: Mode::INTUITIONISTIC,
            },
        }
    }
}

/// Where a translation's images lie: the largest fragment and the mode
/// they are decided in.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Target {
    /// The fragment.
    pub fragment: Fragment,
    /// The mode.
    pub mode: Mode,
}

impl Display for Target {
    /// Writes the fragment's name in the mode, after `affine` in classical
    /// affine mode: `affine MALL`, `ILL`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        if self.mode.is_affine() && !self.mode.is_intuitionistic() {
            f.write_str("affine ")?;
        }
        f.write_str(self.fragment.name_in(self.mode))
    }
}

impl Display for Translation {
    /// Writes the translation's [`name`](Self::name).
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())
    }
}

impl std::str::FromStr for Translation {
    type Err = Error;

    /// Reads a translation's [`name`](Self::name), one of
    /// [`NAMES`](Self::NAMES).
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::ALL
            .iter()
            .copied()
            .find(|translation| translation.name() == name)
            .ok_or_else(|| Error::UnknownName {
                what: "translation",
                name: name.into(),
                known: Self::NAMES,
            })
    }
}

/// How an ordinary sequent is decided: through its embedding into linear
/// logic, or by a calculus of its own logic.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Method {
    /// The sequent's image under a [`Translation`] is searched in linear
    /// logic, and the proof read back as a derivation of LK or LJ
    /// ([`decide()`]). It decides every logic; intuitionistic and minimal
    /// logic go through exponentials, so the search may answer "unknown".
    Embedding,
    /// Dyckhoff's calculus LJT ([`ljt::decide`]), whose search always
    /// ends: intuitionistic and minimal logic only.
    Ljt,
    /// A SAT solver ([`sat::decide`]), whose search always ends. A sequent
    /// that is not valid gets a Kripke model. In intuitionistic and
    /// minimal logic the solver works on clauses for the implications; in
    /// classical logic on the clauses of the sequent's negation, and a
    /// valid sequent gets a checked clausal proof. Needs the cargo feature
    /// `sat`.
    #[cfg(feature = "sat")]
    Sat,
    /// The truth table ([`truth_table`]): every assignment of the atoms,
    /// classical logic only, within [`Limits::table_atoms`](crate::Limits::table_atoms). A sequent
    /// that is not valid gets its first falsifying row as a countermodel.
    Table,
    /// A signed analytic tableau ([`Tableau`]), classical logic only. A
    /// closed tableau is a derivation of LK, which is checked; an open
    /// branch gives a countermodel, which is checked too. Needs the cargo
    /// feature `interactive`.
    #[cfg(feature = "interactive")]
    Tableau,
}

impl Method {
    /// Every method, in the order of [`NAMES`](Self::NAMES).
    pub const ALL: &'static [Self] = &[
        Self::Embedding,
        Self::Ljt,
        #[cfg(feature = "sat")]
        Self::Sat,
        Self::Table,
        #[cfg(feature = "interactive")]
        Self::Tableau,
    ];

    /// The methods' names, which [`name`](Self::name) writes and `FromStr`
    /// reads.
    pub const NAMES: &'static [&'static str] = &[
        "embedding",
        "ljt",
        #[cfg(feature = "sat")]
        "sat",
        "table",
        #[cfg(feature = "interactive")]
        "tableau",
    ];

    /// Returns the method's name: `embedding`, `ljt`, `sat`, `table` or
    /// `tableau`, as the command and the JSON spell it.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Embedding => "embedding",
            Self::Ljt => "ljt",
            #[cfg(feature = "sat")]
            Self::Sat => "sat",
            Self::Table => "table",
            #[cfg(feature = "interactive")]
            Self::Tableau => "tableau",
        }
    }

    /// Returns the method's name in a sentence: `LJT`, `a truth table`.
    pub(crate) const fn title(self) -> &'static str {
        match self {
            Self::Embedding => "the embedding",
            Self::Ljt => "LJT",
            #[cfg(feature = "sat")]
            Self::Sat => "the SAT solver",
            Self::Table => "a truth table",
            #[cfg(feature = "interactive")]
            Self::Tableau => "a tableau",
        }
    }

    /// Returns the logics the method decides, in words.
    pub(crate) const fn logics(self) -> &'static str {
        match self {
            Self::Embedding => "every logic",
            #[cfg(feature = "sat")]
            Self::Sat => "every logic",
            Self::Ljt => "intuitionistic and minimal logic",
            Self::Table => "classical logic",
            #[cfg(feature = "interactive")]
            Self::Tableau => "classical logic",
        }
    }

    /// Returns the method the logic is decided with by default: the SAT
    /// solver, chosen by a run of the ILTP library's propositional
    /// problems. Without the cargo feature `sat` it is the embedding for
    /// classical logic and LJT for the others.
    ///
    /// The default keeps the evidence of the other methods. In classical
    /// logic it asks the embedding for a derivation of LK or a refutation,
    /// within [`EVIDENCE_WORK`]; in intuitionistic and minimal logic it
    /// prefers LJT's derivation. Where a bound stops the SAT solver, the
    /// default gives way to the embedding ([`gives_way`]).
    pub const fn default_for(logic: Logic) -> Self {
        match logic {
            #[cfg(feature = "sat")]
            Logic::Classical | Logic::Intuitionistic | Logic::Minimal => Self::Sat,
            #[cfg(not(feature = "sat"))]
            Logic::Classical => Self::Embedding,
            #[cfg(not(feature = "sat"))]
            Logic::Intuitionistic | Logic::Minimal => Self::Ljt,
        }
    }

    /// Returns whether the method decides the logic: the embedding and the
    /// SAT solver every logic, LJT intuitionistic and minimal logic, the
    /// truth table and the tableau classical logic.
    pub const fn decides(self, logic: Logic) -> bool {
        match self {
            Self::Embedding => true,
            Self::Ljt => !matches!(logic, Logic::Classical),
            #[cfg(feature = "sat")]
            Self::Sat => true,
            Self::Table => matches!(logic, Logic::Classical),
            #[cfg(feature = "interactive")]
            Self::Tableau => matches!(logic, Logic::Classical),
        }
    }
}

impl Display for Method {
    /// Writes the method's [`name`](Self::name).
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())
    }
}

impl std::str::FromStr for Method {
    type Err = Error;

    /// Reads a method's [`name`](Self::name), one of
    /// [`NAMES`](Self::NAMES).
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::ALL
            .iter()
            .copied()
            .find(|method| method.name() == name)
            .ok_or_else(|| Error::UnknownName {
                what: "method",
                name: name.into(),
                known: Self::NAMES,
            })
    }
}

/// How an ordinary sequent is decided: the logic, the method, and the
/// translation of the embedding.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
    /// The logic.
    pub logic: Logic,
    /// The translation, or `None` for the logic's default. A translation
    /// given without a method chooses the embedding.
    pub translation: Option<Translation>,
    /// The method, or `None` for the embedding when a translation is
    /// given and otherwise the logic's default ([`Method::default_for`]).
    pub method: Option<Method>,
}

impl Options {
    /// Returns the options with the logic given.
    #[must_use]
    pub const fn with_logic(self, logic: Logic) -> Self {
        Self { logic, ..self }
    }

    /// Returns the options with the translation given, `None` for the
    /// logic's default.
    #[must_use]
    pub const fn with_translation(self, translation: Option<Translation>) -> Self {
        Self {
            translation,
            ..self
        }
    }

    /// Returns the translation these options choose.
    pub const fn translation(&self) -> Translation {
        match self.translation {
            Some(translation) => translation,
            None => Translation::default_for(self.logic),
        }
    }

    /// Returns the options with the method given, `None` for the
    /// default.
    #[must_use]
    pub const fn with_method(self, method: Option<Method>) -> Self {
        Self { method, ..self }
    }

    /// Returns the method these options choose: the one given, else the
    /// embedding when a translation is given, else the logic's default.
    pub const fn method(&self) -> Method {
        match (self.method, self.translation) {
            (Some(method), _) => method,
            (None, Some(_)) => Method::Embedding,
            (None, None) => Method::default_for(self.logic),
        }
    }
}

/// The index of a formula in a [`Formulas`] arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(u32);

impl NodeId {
    /// Returns the index as a `usize`, for indexing the arena.
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// A node of an ordinary formula, which refers to its subformulas by
/// arena index.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Node {
    /// An atom, by its index among the arena's atom names.
    Atom(u32),
    /// `⊤`, true.
    True,
    /// `⊥`, false.
    False,
    /// `¬A`
    Not(NodeId),
    /// `A ∧ B`
    And(NodeId, NodeId),
    /// `A ∨ B`
    Or(NodeId, NodeId),
    /// `A → B`
    Implies(NodeId, NodeId),
    /// `A ↔ B`
    Iff(NodeId, NodeId),
}

/// A node stays a tag and at most two arena indices, since the arena and
/// the translation's tables grow with its size.
const _: () = assert!(size_of::<Node>() == 12);

impl Node {
    /// Returns the subformulas, in the order they are written.
    pub const fn operands(self) -> (Option<NodeId>, Option<NodeId>) {
        match self {
            Self::Atom(_) | Self::True | Self::False => (None, None),
            Self::Not(a) => (Some(a), None),
            Self::And(a, b) | Self::Or(a, b) | Self::Implies(a, b) | Self::Iff(a, b) => {
                (Some(a), Some(b))
            }
        }
    }
}

/// The formulas of ordinary sequents, as an arena in which every
/// subformula precedes the formulas built from it and equal formulas are
/// one node, so that two formulas are equal exactly when their ids are.
#[derive(Clone, Debug, Default)]
pub struct Formulas {
    /// The nodes, each after its subformulas.
    nodes: Vec<Node>,
    /// The atom names, by the index `Node::Atom` holds.
    atoms: Vec<String>,
    /// The index of every atom name.
    names: HashMap<String, u32>,
    /// The id of every node, for sharing.
    ids: HashMap<Node, NodeId>,
}

impl Formulas {
    /// Returns the id of a node the arena holds, if it holds it.
    pub(crate) fn find(&self, node: Node) -> Option<NodeId> {
        self.ids.get(&node).copied()
    }

    /// The most nodes an arena holds: the ids are `u32`.
    pub const MOST: usize = u32::MAX as usize;

    /// Returns the node with the id given, which must belong to this arena.
    ///
    /// # Panics
    ///
    /// If the id is past the arena's end, as an id of another arena may
    /// be.
    pub fn node(&self, id: NodeId) -> Node {
        self.nodes[id.index()]
    }

    /// Returns the nodes, each after its subformulas.
    #[cfg(any(feature = "serialize", feature = "svg"))]
    pub(crate) fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    /// Returns the number of nodes.
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Returns whether the arena has no node.
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Returns the name of the atom with the index given.
    pub fn atom_name(&self, atom: u32) -> &str {
        &self.atoms[atom as usize]
    }

    /// Returns the atom names, in the order of their indices.
    pub fn atom_names(&self) -> &[String] {
        &self.atoms
    }

    /// Returns the id of `node`, adding it unless the arena has it.
    ///
    /// # Errors
    ///
    /// [`Error::IndexOutOfBounds`] for a subformula that is no node of
    /// this arena (an id of another one) or an atom that is not one of its
    /// names, and [`Refusal::Index`] when the arena
    /// is full.
    #[cfg_attr(
        target_pointer_width = "32",
        expect(
            clippy::absurd_extreme_comparisons,
            reason = "`MOST` is `usize::MAX` on 32 bits, where the test still holds"
        )
    )]
    pub fn add(&mut self, node: Node) -> Result<NodeId, Error> {
        if let Some(&id) = self.ids.get(&node) {
            return Ok(id);
        }
        let (a, b) = node.operands();
        for id in [a, b].into_iter().flatten() {
            self.holds(id)?;
        }
        if let Node::Atom(atom) = node
            && atom as usize >= self.atoms.len()
        {
            return Err(Error::IndexOutOfBounds {
                space: Space::Atom,
                index: atom as usize,
                len: self.atoms.len(),
            });
        }
        if self.nodes.len() >= Self::MOST {
            return Err(Error::Refused(Refusal::Index {
                what: Space::Formula,
                count: Self::MOST as u64 + 1,
                most: Self::MOST as u64,
            }));
        }
        let id = NodeId(self.nodes.len() as u32);
        self.nodes.push(node);
        self.ids.insert(node, id);
        Ok(id)
    }

    /// Fails unless `id` is a node of this arena.
    fn holds(&self, id: NodeId) -> Result<(), Error> {
        if id.index() < self.nodes.len() {
            Ok(())
        } else {
            Err(Error::IndexOutOfBounds {
                space: Space::Formula,
                index: id.index(),
                len: self.nodes.len(),
            })
        }
    }

    /// Returns the atom named `name`, adding it unless the arena has it.
    /// The name is kept in Unicode normal form NFC, so one name is one atom
    /// however its accents are encoded. It must be an identifier of the
    /// text syntax and no keyword, so that a formula written as text reads
    /// back as itself: not `true` or `false`, and no keyword of the linear
    /// syntax either, since the translations keep the atom's name.
    ///
    /// # Errors
    ///
    /// [`Error::AtomName`] for a name that is no identifier, a keyword or a
    /// word reserved for a later version of the syntax (`forall`,
    /// `exists`), and [`Refusal::Index`] when the arena is full.
    pub fn atom(&mut self, name: &str) -> Result<NodeId, Error> {
        let name = &*crate::linear::sequents::name::normalized(name);
        let index = match self.names.get(name) {
            Some(&index) => index,
            None => {
                crate::linear::sequents::name::check_ordinary(name)?;
                let index = self.atoms.len() as u32;
                self.atoms.push(name.to_owned());
                self.names.insert(name.to_owned(), index);
                index
            }
        };
        self.add(Node::Atom(index))
    }

    /// Returns the formula at `id` as a value that prints it.
    pub fn formula(&self, id: NodeId) -> Formula<'_> {
        Formula { formulas: self, id }
    }

    /// Writes the formula at `id` with the spellings given, every binary
    /// subformula in brackets, and the whole in brackets too if it is
    /// binary and `brackets` is set.
    pub(crate) fn write<W: Write>(
        &self,
        out: &mut W,
        id: NodeId,
        brackets: bool,
        symbols: &Symbols,
        atom: impl Fn(&mut W, u32) -> FmtResult,
    ) -> FmtResult {
        for visit in Stops::new(id, brackets, |k| self.node(k).operands()) {
            match visit {
                Stop::Enter(k, nested) => match self.node(k) {
                    Node::Atom(a) => atom(out, a)?,
                    Node::True => out.write_str(symbols.truth)?,
                    Node::False => out.write_str(symbols.falsity)?,
                    Node::Not(_) => out.write_str(symbols.not)?,
                    _ if nested => out.write_char('(')?,
                    Node::And(..) | Node::Or(..) | Node::Implies(..) | Node::Iff(..) => {}
                },
                Stop::Between(k) => {
                    out.write_char(' ')?;
                    out.write_str(match self.node(k) {
                        Node::And(..) => symbols.and,
                        Node::Or(..) => symbols.or,
                        Node::Implies(..) => symbols.implies,
                        Node::Atom(_) | Node::True | Node::False | Node::Not(_) | Node::Iff(..) => {
                            symbols.iff
                        }
                    })?;
                    out.write_char(' ')?;
                }
                Stop::Exit(k, nested) => {
                    if nested && self.node(k).operands().1.is_some() {
                        out.write_char(')')?;
                    }
                }
            }
        }
        Ok(())
    }
}

/// How a target spells the connectives and constants of ordinary
/// formulas.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Symbols {
    /// `¬`, written directly before its operand.
    pub(crate) not: &'static str,
    /// `∧`
    pub(crate) and: &'static str,
    /// `∨`
    pub(crate) or: &'static str,
    /// `→`
    pub(crate) implies: &'static str,
    /// `↔`
    pub(crate) iff: &'static str,
    /// `⊤`
    pub(crate) truth: &'static str,
    /// `⊥`
    pub(crate) falsity: &'static str,
}

impl Symbols {
    /// The Unicode symbols, which `Display` writes.
    pub(crate) const UNICODE: Self = Self {
        not: "¬",
        and: "∧",
        or: "∨",
        implies: "→",
        iff: "↔",
        truth: "⊤",
        falsity: "⊥",
    };
}

/// A formula of an arena, as a value that prints it with the Unicode
/// symbols, every binary subformula in brackets.
#[derive(Clone, Copy, Debug)]
pub struct Formula<'a> {
    /// The arena.
    formulas: &'a Formulas,
    /// The formula.
    id: NodeId,
}

impl Display for Formula<'_> {
    /// Writes the formula: `(a ∧ b) → ¬c`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.formulas
            .write(f, self.id, false, &Symbols::UNICODE, |o, a| {
                o.write_str(self.formulas.atom_name(a))
            })
    }
}

/// A sequent of ordinary propositional logic, `Γ ⊢ Δ`: the hypotheses `Γ`
/// left of the turnstile, and the formulas `Δ` right of it. Classically
/// `Δ` reads as the disjunction of its formulas. In intuitionistic and
/// minimal logic `Δ` holds one goal at most, and an empty `Δ` means
/// false.
///
/// # Syntax
///
/// With the cargo feature `parse`, `"…".parse::<ordinary::Sequent>()`
/// reads a sequent written `formulas |- formulas` (or `⊢`), each side a
/// list separated by commas and possibly empty; a text without a turnstile
/// is one formula to prove. From the loosest binding to the tightest, a
/// formula is built with `<->`/`↔` (to the right), `->`/`→` (to the
/// right), `\/`/`∨`, `/\`/`∧` (these to the left) and the prefix `~`/`¬`,
/// over the constants `true`/`⊤` and `false`/`⊥`, atoms and parentheses.
/// An atom is a Unicode identifier other than a keyword: `true`, `false`,
/// the linear syntax's `par`, `top` and `bot`, and the reserved `forall`
/// and `exists`. The symbols of linear logic (`&`, `|`, `*`, `-o`, …) are
/// not read here, so that a linear connective is never taken for an
/// ordinary one.
///
/// `Display` writes the Unicode symbols with every nested binary formula
/// in brackets, which this syntax reads back.
///
/// # JSON
///
/// With the cargo feature `serialize` a sequent is `{"version": 8,
/// "formulas": [{"V": 0}, {"V": 1}, {"→": [0, 1]}], "atoms": ["a", "b"],
/// "left": [0], "right": [1]}` for `a ⊢ b` with the arena `a, b, a → b`
/// ([`wire`](crate::wire)): the formulas in the arena's order, every
/// operand before the formula built from it, as `{"V": atom}`, `"⊤"`,
/// `"⊥"`, `{"¬": a}`, `{"∧": [a, b]}`, `{"∨": [a, b]}`, `{"→": [a, b]}`
/// and `{"↔": [a, b]}`, and the two sides as indices into them.
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// let sequent: deduxit::ordinary::Sequent = "a /\\ b -> c |- ~c -> ~a \\/ ~b".parse()?;
/// assert_eq!(sequent.to_string(), "(a ∧ b) → c ⊢ ¬c → (¬a ∨ ¬b)");
/// # Ok::<(), deduxit::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct Sequent {
    /// The formulas.
    formulas: Formulas,
    /// The hypotheses, in the order written.
    left: Vec<NodeId>,
    /// The formulas right of the turnstile, in the order written.
    right: Vec<NodeId>,
}

impl Sequent {
    /// Returns the sequent `left ⊢ right` over the formulas given.
    ///
    /// # Errors
    ///
    /// [`Error::IndexOutOfBounds`] for an id of the two lists that is no
    /// node of `formulas`.
    pub fn new(formulas: Formulas, left: Vec<NodeId>, right: Vec<NodeId>) -> Result<Self, Error> {
        for &id in left.iter().chain(&right) {
            formulas.holds(id)?;
        }
        Ok(Self {
            formulas,
            left,
            right,
        })
    }

    /// Returns the arena of the formulas.
    pub fn formulas(&self) -> &Formulas {
        &self.formulas
    }

    /// Returns the formulas left of the turnstile, in the order written.
    pub fn left(&self) -> &[NodeId] {
        &self.left
    }

    /// Returns the formulas right of the turnstile, in the order written.
    pub fn right(&self) -> &[NodeId] {
        &self.right
    }
}

impl Display for Sequent {
    /// Writes `Γ ⊢ Δ` with the Unicode symbols.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let sides = (&self.left[..], &self.right[..]);
        TEXT.ordinary(f, &self.formulas, sides, false, false)
    }
}

/// Returns the number of subformula occurrences the formulas unfold to,
/// saturating.
#[cfg(any(feature = "interactive", feature = "serialize"))]
fn occurrences<'a>(formulas: &Formulas, roots: impl Iterator<Item = &'a NodeId>) -> u64 {
    // Every subformula precedes the formulas built from it.
    let mut size: Vec<u64> = Vec::with_capacity(formulas.len());
    for node in &formulas.nodes {
        let (a, b) = node.operands();
        let of = |k: Option<NodeId>| k.map_or(0, |k| size[k.index()]);
        size.push(1u64.saturating_add(of(a)).saturating_add(of(b)));
    }
    roots.fold(0, |sum, id| sum.saturating_add(size[id.index()]))
}

/// Checks that a sequent over the formulas unfolds to at most
/// `limits.occurrences` subformula occurrences.
#[cfg(any(feature = "interactive", feature = "serialize"))]
pub(crate) fn bound(
    formulas: &Formulas,
    left: &[NodeId],
    right: &[NodeId],
    limits: &crate::Limits,
) -> Result<(), Error> {
    let occurrences = occurrences(formulas, left.iter().chain(right));
    match limits.occurrences {
        Some(limit) if occurrences > limit => {
            Err(Error::Refused(Refusal::Occurrences { occurrences, limit }))
        }
        _ => Ok(()),
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::linear::search::generate::Rng;
    use crate::linear::{Options as Search, Verdict, prove};

    /// Decides `text` in `logic` by `translation` with a copy bound of
    /// eight, and returns whether it was proved, with the derivation read
    /// back checked.
    fn decide(text: &str, logic: Logic, translation: Translation) -> Option<bool> {
        let sequent: Sequent = text.parse().unwrap();
        let image = translate(&sequent, logic, translation, &crate::Limits::default()).unwrap();
        let search = Search::default().with_copies(Some(8));
        let outcome = prove(image.sequent(), image.mode(), &search).unwrap();
        match &outcome.verdict {
            Verdict::Proved(proof) => {
                let unbounded = crate::Limits::default();
                let derivation = image.read_back(proof, &unbounded, |_| false).unwrap();
                derivation
                    .check(&unbounded, |_| false)
                    .unwrap_or_else(|e| panic!("{text} ({translation}): {e}"));
                Some(true)
            }
            Verdict::Unprovable(_) => Some(false),
            Verdict::Unknown(_) => None,
        }
    }

    /// Every logic and translation reads back from its name, an unknown
    /// name is refused naming the known ones, and the readers and the
    /// translation keep to the occurrence bound.
    #[test]
    fn names_read_back_and_bounds_hold() {
        let logics: Vec<_> = Logic::ALL.iter().map(|l| l.name()).collect();
        let translations: Vec<_> = Translation::ALL.iter().map(|t| t.name()).collect();
        assert_eq!(logics, Logic::NAMES);
        assert_eq!(translations, Translation::NAMES);
        for &logic in Logic::ALL {
            assert_eq!(logic.name().parse::<Logic>().unwrap(), logic);
        }
        for &translation in Translation::ALL {
            assert_eq!(
                translation.name().parse::<Translation>().unwrap(),
                translation
            );
        }
        assert!(matches!(
            "cbz".parse::<Translation>(),
            Err(Error::UnknownName { known, .. }) if known == Translation::NAMES
        ));
        let bound = |n| crate::Limits::default().with_occurrences(Some(n));
        let refused = |result: Result<(), Error>| {
            matches!(result, Err(Error::Refused(Refusal::Occurrences { .. })))
        };
        // Five formulas: a, b, c, a ∧ b and the implication.
        assert!(Sequent::parse_within("a /\\ b -> c", &bound(5)).is_ok());
        assert!(refused(
            Sequent::parse_within("a /\\ b -> c", &bound(4)).map(|_| ())
        ));
        let tptp = "fof(c, conjecture, (a & b) => c).";
        assert!(read_tptp(tptp, &bound(5)).is_ok());
        assert!(refused(read_tptp(tptp, &bound(4)).map(|_| ())));
        // One atom repeated: one formula of the arena, but each repeat is
        // an occurrence of the image.
        let repeated = ["a"; 6].join(", ");
        assert!(Sequent::parse_within(&repeated, &bound(6)).is_ok());
        assert!(refused(
            Sequent::parse_within(&repeated, &bound(5)).map(|_| ())
        ));
        // A parenthesis waits but makes no formula: `~(~(a))` is three
        // formulas and read at a bound of three.
        assert!(Sequent::parse_within("~(~(a))", &bound(3)).is_ok());
        // What waits for its operand counts too: a run of `~` or of `->`
        // is refused before the parse error after it.
        for run in ["~".repeat(100), "a -> ".repeat(100), "(".repeat(100)] {
            assert!(refused(
                Sequent::parse_within(&format!("{run}a b"), &bound(10)).map(|_| ())
            ));
        }
        let hypotheses = "fof(h, axiom, a).\n".repeat(5) + "fof(c, conjecture, a).";
        assert!(read_tptp(&hypotheses, &bound(6)).is_ok());
        assert!(refused(read_tptp(&hypotheses, &bound(5)).map(|_| ())));
        let sequent: Sequent = "a /\\ b -> c".parse().unwrap();
        let image = translate(
            &sequent,
            Logic::Classical,
            Translation::Affine,
            &bound(1_000),
        )
        .unwrap();
        let size = image.sequent().occurrences();
        let classical = |n| translate(&sequent, Logic::Classical, Translation::Affine, &bound(n));
        assert!(classical(size).is_ok());
        assert!(refused(classical(size - 1).map(|_| ())));
    }

    /// A name is one atom however its accents are encoded, and a keyword
    /// of either syntax names none.
    #[test]
    fn atom_names_are_composed_identifiers() {
        let mut formulas = Formulas::default();
        let composed = formulas.atom("\u{e9}").unwrap();
        assert_eq!(formulas.atom("e\u{301}").unwrap(), composed);
        assert_eq!(formulas.atom_names(), ["\u{e9}"]);
        for name in ["top", "true", "forall", "a b"] {
            assert!(
                matches!(formulas.atom(name), Err(Error::AtomName { .. })),
                "{name}"
            );
        }
    }

    /// An arena refuses a subformula of another arena and an atom
    /// outside its names, and a sequent an id outside its arena.
    #[test]
    fn foreign_ids_are_refused() {
        let mut other = Formulas::default();
        let (a, b) = (other.atom("a").unwrap(), other.atom("b").unwrap());
        let and = other.add(Node::And(a, b)).unwrap();
        let mut formulas = Formulas::default();
        let x = formulas.atom("x").unwrap();
        let refused = |result: Result<_, Error>, space| matches!(result, Err(Error::IndexOutOfBounds { space: s, .. }) if s == space);
        assert!(refused(formulas.add(Node::Not(and)), Space::Formula));
        assert!(refused(formulas.add(Node::Atom(5)), Space::Atom));
        let sequent = Sequent::new(formulas.clone(), vec![x], vec![and]);
        assert!(refused(sequent.map(|_| x), Space::Formula));
        assert!(Sequent::new(formulas, vec![], vec![x]).is_ok());
    }

    /// A TPTP problem cannot name an atom `false`, which the ordinary
    /// syntax reads as the constant and minimal logic's false is the atom
    /// of.
    #[test]
    fn false_is_no_atom_of_the_sequent() {
        let read = read_tptp(
            "fof(a, axiom, p). fof(b, axiom, ~p). fof(c, conjecture, false).",
            &crate::Limits::default(),
        );
        assert!(matches!(read, Err(Error::AtomName { name }) if name == FALSE));
    }

    /// Every translation decides the sequents of its logic as the logic
    /// does, and every proof reads back as a derivation its checker
    /// accepts: the connectives on both sides, nested negations, the
    /// constants, contraction, and the sequents that separate the logics.
    #[test]
    fn decides_and_reads_back() {
        // (sequent, classical, intuitionistic, minimal)
        let cases = [
            ("a -> a", true, true, true),
            ("a \\/ ~a", true, false, false),
            ("~~a -> a", true, false, false),
            ("a -> ~~a", true, true, true),
            ("((a -> b) -> a) -> a", true, false, false),
            ("false -> a", true, true, false),
            ("~a -> a -> b", true, true, false),
            ("~a -> a -> ~b", true, true, true),
            ("a /\\ b <-> b /\\ a", true, true, true),
            ("a \\/ b, ~a |- b", true, true, false),
            ("(a -> b) /\\ (a -> c) |- a -> b /\\ c", true, true, true),
            ("a -> b, b -> c |- a -> c", true, true, true),
            ("~(a \\/ b) <-> ~a /\\ ~b", true, true, true),
            ("~(a /\\ b) -> ~a \\/ ~b", true, false, false),
            ("true, a |- a /\\ true", true, true, true),
            ("a -> (a -> b) -> b", true, true, true),
            ("(a <-> b) -> (b <-> a)", true, true, true),
            ("a |- b", false, false, false),
            ("a \\/ b |- a /\\ b", false, false, false),
            ("~~(a \\/ ~a)", true, true, true),
            // Minimal logic's false is an atom, copied like any other.
            ("false |- ~true", true, true, true),
            ("false |- a -> a", true, true, true),
            ("q |- r -> ((false \\/ q) -> r)", true, true, true),
        ];
        for (text, classical, intuitionistic, minimal) in cases {
            assert_eq!(
                decide(text, Logic::Classical, Translation::Affine),
                Some(classical),
                "{text} classically"
            );
            for translation in [
                Translation::CallByName,
                Translation::CallByValue,
                Translation::ZeroOne,
            ] {
                for (logic, valid) in [
                    (Logic::Intuitionistic, intuitionistic),
                    (Logic::Minimal, minimal),
                ] {
                    let verdict = decide(text, logic, translation);
                    assert!(
                        verdict.is_none() || verdict == Some(valid),
                        "{text} in {logic} logic by {translation}: {verdict:?}"
                    );
                    if valid {
                        assert_eq!(
                            verdict,
                            Some(true),
                            "{text} in {logic} logic by {translation}"
                        );
                    }
                }
            }
        }
    }

    /// Returns a formula of depth `depth` at most over `atoms`, true and
    /// false, built with `¬`, `∧`, `∨` and `→`.
    fn generated(rng: &mut Rng, formulas: &mut Formulas, atoms: &[NodeId], depth: usize) -> NodeId {
        if depth == 0 || rng.one_in(4) {
            // Each atom twice as likely as each constant.
            let leaf = rng.below(2 * atoms.len() + 2);
            let node = match leaf.checked_sub(2 * atoms.len()) {
                None => return atoms[leaf % atoms.len()],
                Some(0) => Node::True,
                Some(_) => Node::False,
            };
            return formulas.add(node).unwrap();
        }
        let a = generated(rng, formulas, atoms, depth - 1);
        let node = match rng.below(4) {
            0 => Node::Not(a),
            choice => {
                let b = generated(rng, formulas, atoms, depth - 1);
                match choice {
                    1 => Node::And(a, b),
                    2 => Node::Or(a, b),
                    _ => Node::Implies(a, b),
                }
            }
        };
        formulas.add(node).unwrap()
    }

    /// Returns a sequent in the atoms `a`, `b` and `c` of up to two
    /// hypotheses and at most one formula right of `⊢`, each of depth
    /// three at most.
    pub(super) fn generated_sequent(rng: &mut Rng) -> Sequent {
        let mut formulas = Formulas::default();
        let atoms: Vec<_> = ["a", "b", "c"]
            .into_iter()
            .map(|name| formulas.atom(name).unwrap())
            .collect();
        let left = (0..rng.below(3))
            .map(|_| generated(rng, &mut formulas, &atoms, 3))
            .collect();
        let right = (0..usize::from(!rng.one_in(6)))
            .map(|_| generated(rng, &mut formulas, &atoms, 3))
            .collect();
        Sequent::new(formulas, left, right).unwrap()
    }

    /// Returns whether every assignment of the sequent's atoms that makes
    /// all its hypotheses true makes some formula right of `⊢` true.
    pub(super) fn valid_by_truth_table(sequent: &Sequent) -> bool {
        let formulas = sequent.formulas();
        (0..1_u32 << formulas.atom_names().len()).all(|assignment| {
            // Every node after its operands, so one pass evaluates all.
            let mut value: Vec<bool> = Vec::with_capacity(formulas.len());
            for n in 0..formulas.len() {
                let of = |id: NodeId| value[id.index()];
                let holds = match formulas.node(NodeId(n as u32)) {
                    Node::Atom(atom) => assignment >> atom & 1 == 1,
                    Node::True => true,
                    Node::False => false,
                    Node::Not(a) => !of(a),
                    Node::And(a, b) => of(a) && of(b),
                    Node::Or(a, b) => of(a) || of(b),
                    Node::Implies(a, b) => !of(a) || of(b),
                    Node::Iff(a, b) => of(a) == of(b),
                };
                value.push(holds);
            }
            !sequent.left().iter().all(|id| value[id.index()])
                || sequent.right().iter().any(|id| value[id.index()])
        })
    }

    /// On a few hundred generated sequents, each logic's translations
    /// agree: wherever two of them decide a sequent they give it the same
    /// verdict, and each decides at least half of the sequents. Classical
    /// logic's verdicts are the truth table's, and a sequent valid in
    /// intuitionistic or minimal logic is valid by the truth table.
    #[test]
    fn translations_agree_with_each_other_and_the_truth_table() {
        const SEQUENTS: usize = 300;
        // Bounds that keep the run to a second or two unoptimized.
        let search = Search::default().with_copies(Some(6));
        let limits = crate::Limits::default().with_work(Some(50_000));
        let mut rng = Rng::new(2_026);
        let mut decided: HashMap<(Logic, Translation), usize> = HashMap::default();
        for _ in 0..SEQUENTS {
            let sequent = generated_sequent(&mut rng);
            let classical = valid_by_truth_table(&sequent);
            for &logic in Logic::ALL {
                let verdicts: Vec<_> = Translation::ALL
                    .iter()
                    .filter(|translation| translation.decides(logic))
                    .map(|&translation| {
                        let options = Options::default()
                            .with_logic(logic)
                            .with_translation(Some(translation));
                        let outcome =
                            super::decide_within(&sequent, &options, &search, &limits, |_| false)
                                .unwrap_or_else(|e| {
                                    panic!("{sequent} in {logic} logic by {translation}: {e}")
                                });
                        let valid = match outcome.verdict {
                            super::Verdict::Valid(_) => Some(true),
                            super::Verdict::NotValid => Some(false),
                            super::Verdict::Unknown(_) => None,
                        };
                        if valid.is_some() {
                            *decided.entry((logic, translation)).or_default() += 1;
                        }
                        (translation, valid)
                    })
                    .collect();
                let answers: Vec<bool> = verdicts.iter().filter_map(|&(_, valid)| valid).collect();
                assert!(
                    answers.windows(2).all(|pair| pair[0] == pair[1]),
                    "{sequent} in {logic} logic: {verdicts:?}"
                );
                if logic == Logic::Classical {
                    assert!(
                        answers.iter().all(|&valid| valid == classical),
                        "{sequent} classically: {verdicts:?}, the truth table says {classical}"
                    );
                } else {
                    assert!(
                        classical || !answers.contains(&true),
                        "{sequent} in {logic} logic: {verdicts:?}, the truth table refutes it"
                    );
                }
            }
        }
        for &logic in Logic::ALL {
            for &translation in Translation::ALL.iter().filter(|t| t.decides(logic)) {
                let count = decided.get(&(logic, translation)).copied().unwrap_or(0);
                assert!(
                    2 * count >= SEQUENTS,
                    "{translation} decided {count} of {SEQUENTS} sequents in {logic} logic"
                );
            }
        }
    }
}