deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

use super::translate::{Core, Image, pattern};
use super::{Formulas, Logic, Node, NodeId, Translation};
use crate::limits::{Limits, Phase, Progress, Refusal};
use crate::linear::occurrences::OccId;
use crate::linear::proofs::style::Drawn;
use crate::linear::proofs::{
    Compact, InfId, Labels, Rule as Linear, Sides, Structural, TextOptions, ViewOptions,
};
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
use crate::linear::sequents::notation::Notation;
use crate::linear::sequents::notation::TEXT;
use crate::{Error, linear::Proof};
use std::borrow::Cow;
use std::fmt::{Display, Formatter, Result as FmtResult, Write};

/// A side of the turnstile.
///
/// # JSON
///
/// With the feature `serialize`, `"left"` or `"right"`.
#[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 Side {
    /// Left of `⊢`: a hypothesis.
    Left,
    /// Right of `⊢`.
    Right,
}

impl Side {
    /// Returns the other side.
    pub(crate) const fn flip(self) -> Self {
        match self {
            Self::Left => Self::Right,
            Self::Right => Self::Left,
        }
    }
}

/// A rule of LK or LJ, as a derivation read back names it.
///
/// The derivations are those of Gentzen's calculi with explicit weakening
/// and contraction: a rule with two premises takes its context either
/// whole into both (as `∧R` of LJ does) or split between them (as `→L`
/// of LJ does); an axiom `A ⊢ A` has no context, while `⊤R` and `⊥L` take
/// any. `¬A` is a connective of its own; in LJ its left rule has the form
/// of `→L` for `A → ⊥`, and in LK the one premise `Γ ⊢ A, Δ`. Every LJ
/// sequent has at most one formula right of `⊢`; minimal logic has no
/// `⊥L` and exactly one formula right of `⊢` in every sequent (G1m), since
/// an empty right side would be read as `⊥` by one rule and as anything
/// by another.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Rule {
    /// `ax`: `A ⊢ A`.
    Axiom,
    /// `WL`, weakening of a hypothesis.
    WeakenLeft,
    /// `WR`, weakening right of `⊢`.
    WeakenRight,
    /// `CL`, contraction of a hypothesis.
    ContractLeft,
    /// `CR`, contraction right of `⊢`.
    ContractRight,
    /// `∧L`, both conjuncts.
    AndLeft,
    /// `∧L₁`, the first conjunct.
    AndLeft1,
    /// `∧L₂`, the second conjunct.
    AndLeft2,
    /// `∧R`
    AndRight,
    /// `∨L`
    OrLeft,
    /// `∨R`, both disjuncts (LK).
    OrRight,
    /// `∨R₁`
    OrRight1,
    /// `∨R₂`
    OrRight2,
    /// `→L`
    ImpliesLeft,
    /// `→R`
    ImpliesRight,
    /// `¬L`
    NotLeft,
    /// `¬R`
    NotRight,
    /// `↔L`, both implications.
    IffLeft,
    /// `↔L₁`, the implication from left to right.
    IffLeft1,
    /// `↔L₂`, the implication from right to left.
    IffLeft2,
    /// `↔R`
    IffRight,
    /// `⊥L`, ex falso.
    FalseLeft,
    /// `⊥R`, false dropped from the right.
    FalseRight,
    /// `⊤L`, true dropped from the hypotheses.
    TrueLeft,
    /// `⊤R`
    TrueRight,
    /// An open goal of a proof in progress, which no derivation the
    /// checker accepts has.
    Open,
}

/// The labels of every rule in the order of [`Rule::ALL`], upright and
/// with the side and the letter of a structural rule as a subscript: the
/// upright one is the rule's name in markup, which a test compares.
const LABELS: [(&str, &str); Rule::ALL.len()] = [
    ("ax", "ax"),
    ("WL", "W_L"),
    ("WR", "W_R"),
    ("CL", "C_L"),
    ("CR", "C_R"),
    ("∧L", "∧_L"),
    ("∧L_1", "∧_{L1}"),
    ("∧L_2", "∧_{L2}"),
    ("∧R", "∧_R"),
    ("∨L", "∨_L"),
    ("∨R", "∨_R"),
    ("∨R_1", "∨_{R1}"),
    ("∨R_2", "∨_{R2}"),
    ("→L", "→_L"),
    ("→R", "→_R"),
    ("¬L", "¬_L"),
    ("¬R", "¬_R"),
    ("↔L", "↔_L"),
    ("↔L_1", "↔_{L1}"),
    ("↔L_2", "↔_{L2}"),
    ("↔R", "↔_R"),
    ("⊥L", "⊥_L"),
    ("⊥R", "⊥_R"),
    ("⊤L", "⊤_L"),
    ("⊤R", "⊤_R"),
    ("open", "open"),
];

impl Rule {
    /// Every rule, in the order of declaration, which is the order of
    /// `rule as usize`.
    pub(crate) const ALL: [Self; 26] = {
        use Rule::*;
        [
            Axiom,
            WeakenLeft,
            WeakenRight,
            ContractLeft,
            ContractRight,
            AndLeft,
            AndLeft1,
            AndLeft2,
            AndRight,
            OrLeft,
            OrRight,
            OrRight1,
            OrRight2,
            ImpliesLeft,
            ImpliesRight,
            NotLeft,
            NotRight,
            IffLeft,
            IffLeft1,
            IffLeft2,
            IffRight,
            FalseLeft,
            FalseRight,
            TrueLeft,
            TrueRight,
            Open,
        ]
    };

    /// Returns the rule's usual spelling.
    pub const fn name(self) -> &'static str {
        use Rule::*;
        match self {
            Axiom => "ax",
            WeakenLeft => "WL",
            WeakenRight => "WR",
            ContractLeft => "CL",
            ContractRight => "CR",
            AndLeft => "∧L",
            AndLeft1 => "∧L₁",
            AndLeft2 => "∧L₂",
            AndRight => "∧R",
            OrLeft => "∨L",
            OrRight => "∨R",
            OrRight1 => "∨R₁",
            OrRight2 => "∨R₂",
            ImpliesLeft => "→L",
            ImpliesRight => "→R",
            NotLeft => "¬L",
            NotRight => "¬R",
            IffLeft => "↔L",
            IffLeft1 => "↔L₁",
            IffLeft2 => "↔L₂",
            IffRight => "↔R",
            FalseLeft => "⊥L",
            FalseRight => "⊥R",
            TrueLeft => "⊤L",
            TrueRight => "⊤R",
            Open => "open",
        }
    }

    /// Returns whether the rule is structural: a weakening or a
    /// contraction.
    pub const fn is_structural(self) -> bool {
        matches!(
            self,
            Self::WeakenLeft | Self::WeakenRight | Self::ContractLeft | Self::ContractRight
        )
    }

    /// Returns the label in the markup the exports set (a subscript as
    /// `_1`), upright or with the side and the letter of a structural
    /// rule as a subscript.
    pub(crate) const fn markup(self, subscript: bool) -> &'static str {
        let (upright, lowered) = LABELS[self as usize];
        if subscript { lowered } else { upright }
    }
}

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

/// The ASCII spellings of the rules, each beside its rule: the
/// connectives as the parser of ordinary formulas reads them (`/\`, `\/`,
/// `->`, `~`, `<->`) or as words (`and`, `or`, `imp`, `not`, `iff`,
/// `false`, `true`), a subscript as a digit.
const ASCII: [(&str, Rule); 36] = [
    ("/\\L", Rule::AndLeft),
    ("/\\L1", Rule::AndLeft1),
    ("/\\L2", Rule::AndLeft2),
    ("/\\R", Rule::AndRight),
    ("\\/L", Rule::OrLeft),
    ("\\/R", Rule::OrRight),
    ("\\/R1", Rule::OrRight1),
    ("\\/R2", Rule::OrRight2),
    ("->L", Rule::ImpliesLeft),
    ("->R", Rule::ImpliesRight),
    ("~L", Rule::NotLeft),
    ("~R", Rule::NotRight),
    ("<->L", Rule::IffLeft),
    ("<->L1", Rule::IffLeft1),
    ("<->L2", Rule::IffLeft2),
    ("<->R", Rule::IffRight),
    ("andL", Rule::AndLeft),
    ("andL1", Rule::AndLeft1),
    ("andL2", Rule::AndLeft2),
    ("andR", Rule::AndRight),
    ("orL", Rule::OrLeft),
    ("orR", Rule::OrRight),
    ("orR1", Rule::OrRight1),
    ("orR2", Rule::OrRight2),
    ("impL", Rule::ImpliesLeft),
    ("impR", Rule::ImpliesRight),
    ("notL", Rule::NotLeft),
    ("notR", Rule::NotRight),
    ("iffL", Rule::IffLeft),
    ("iffL1", Rule::IffLeft1),
    ("iffL2", Rule::IffLeft2),
    ("iffR", Rule::IffRight),
    ("falseL", Rule::FalseLeft),
    ("falseR", Rule::FalseRight),
    ("trueL", Rule::TrueLeft),
    ("trueR", Rule::TrueRight),
];

/// The names of every rule a step takes, all but [`Rule::Open`], as an
/// unknown name's error lists them.
const NAMES: [&str; Rule::ALL.len() - 1] = {
    let mut names = [""; Rule::ALL.len() - 1];
    let mut i = 0;
    while i < names.len() {
        names[i] = Rule::ALL[i].name();
        i += 1;
    }
    names
};

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

    /// Reads a rule from its [`name`](Self::name) or an ASCII spelling of
    /// it: `/\R` or `andR` for `∧R`, `\/R1` or `orR1` for `∨R₁`, `->L` or
    /// `impL` for `→L`, `~R` or `notR` for `¬R`, `<->L2` or `iffL2` for
    /// `↔L₂`, `falseL` for `⊥L`, `trueR` for `⊤R`, and a subscript as a
    /// digit after the Unicode connective too (`∧L1`). An open goal is no
    /// rule a step takes, so `open` is refused.
    fn from_str(text: &str) -> Result<Self, Error> {
        let digits = text.replace('1', "₁").replace('2', "₂");
        NAMES
            .iter()
            .position(|&name| name == text || name == digits)
            .map(|i| Self::ALL[i])
            .or_else(|| {
                ASCII
                    .iter()
                    .find(|(name, _)| *name == text)
                    .map(|&(_, rule)| rule)
            })
            .ok_or_else(|| Error::UnknownName {
                what: "rule of LK or LJ",
                name: text.into(),
                known: &NAMES,
            })
    }
}

/// One inference of a derivation of LK or LJ: the sequent it concludes,
/// the rule, the formula the rule introduces, and its premises.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Inference {
    /// The hypotheses of the sequent concluded, a formula repeated as often
    /// as the sequent holds it.
    pub(crate) left: Vec<NodeId>,
    /// The formulas right of `⊢`.
    pub(crate) right: Vec<NodeId>,
    /// The rule.
    pub(crate) rule: Rule,
    /// The side and the position there of the formula the rule
    /// introduces, removes or copies; `None` for an axiom.
    pub(crate) principal: Option<(Side, usize)>,
    /// The premises, in the rule's order.
    pub(crate) premises: Vec<InfId>,
}

impl Inference {
    /// Returns the hypotheses of the sequent concluded, a formula repeated
    /// as often as the sequent holds it.
    pub fn left(&self) -> &[NodeId] {
        &self.left
    }

    /// Returns the formulas right of `⊢`.
    pub fn right(&self) -> &[NodeId] {
        &self.right
    }

    /// Returns the rule.
    pub const fn rule(&self) -> Rule {
        self.rule
    }

    /// Returns the side and the position there of the formula the rule
    /// introduces, removes or copies; `None` for an axiom.
    pub const fn principal(&self) -> Option<(Side, usize)> {
        self.principal
    }

    /// Returns the premises, in the rule's order.
    pub fn premises(&self) -> &[InfId] {
        &self.premises
    }

    /// Returns the formulas of one side.
    pub(crate) fn side(&self, side: Side) -> &[NodeId] {
        match side {
            Side::Left => &self.left,
            Side::Right => &self.right,
        }
    }
}

/// A derivation of LK or LJ (see [`Rule`]), read back from a linear proof
/// of an image by [`Image::read_back`] or made step by step (feature
/// `interactive`): premises precede their conclusion, the root is the
/// last inference.
///
/// # JSON
///
/// With the feature `serialize` a derivation is `{"version": 8, "logic":
/// "classical", "sequent": {…}, "inferences": […]}`, the sequent in the
/// ordinary sequent's form with every formula the inferences name, each
/// inference `{"left": [ids], "right": [ids], "rule": name, "principal":
/// ["right", position], "premises": [indices]}` ([`wire`](crate::wire)).
/// Reading one checks its shape, not its rules: that is
/// [`check`](Self::check)'s.
#[derive(Clone, Debug)]
pub struct Derivation {
    /// The logic.
    logic: Logic,
    /// The formulas, those an equivalence or a negation needs included.
    formulas: Formulas,
    /// The sequent derived.
    left: Vec<NodeId>,
    /// The sequent derived, right of `⊢`.
    right: Vec<NodeId>,
    /// The inferences, premises before conclusions.
    inferences: Vec<Inference>,
}

impl Derivation {
    /// Returns the logic.
    pub fn logic(&self) -> Logic {
        self.logic
    }

    /// Returns the formulas the inferences refer to.
    pub fn formulas(&self) -> &Formulas {
        &self.formulas
    }

    /// Returns every inference, premises before conclusions, the root last.
    pub fn inferences(&self) -> &[Inference] {
        &self.inferences
    }

    /// Reads the derivation back as a term of the simply typed lambda
    /// calculus ([`lambda`](crate::lambda)), asking `stop` once per
    /// inference: a derivation of LJ, in either view of its structural
    /// rules.
    ///
    /// # Errors
    ///
    /// [`Error::NoTerm`] for a derivation of LK or one with open goals;
    /// [`Refusal::Stopped`] when `stop` fired.
    pub fn term(
        &self,
        limits: &crate::Limits,
        stop: impl FnMut(crate::Progress) -> bool,
    ) -> Result<crate::lambda::Term, Error> {
        crate::lambda::simple::read(self, limits, stop)
    }

    /// Returns the inference at `id`, which must belong to this derivation.
    ///
    /// # Panics
    ///
    /// For an id of another one, past its end.
    pub fn inference(&self, id: InfId) -> &Inference {
        &self.inferences[id.index()]
    }

    /// Returns the root.
    pub fn root(&self) -> InfId {
        // A derivation read back, made by a proof in progress or read from
        // its JSON has an inference for every leaf.
        InfId::new(self.inferences.len() as u32 - 1)
    }

    /// Returns the derivation of `logic` over `formulas` that concludes
    /// `left ⊢ right` with `inferences`, which have its shape: premises
    /// before conclusions, the root last, at least one. Nothing is
    /// checked: [`check`](Self::check) judges it.
    #[cfg(any(feature = "interactive", feature = "serialize"))]
    pub(crate) fn from_parts(
        logic: Logic,
        formulas: Formulas,
        (left, right): (Vec<NodeId>, Vec<NodeId>),
        inferences: Vec<Inference>,
    ) -> Self {
        Self {
            logic,
            formulas,
            left,
            right,
            inferences,
        }
    }

    /// Returns the sequent the derivation concludes, its two sides.
    pub fn sequent(&self) -> (&[NodeId], &[NodeId]) {
        (&self.left, &self.right)
    }

    /// Returns the derivation as `structural` shows it: itself when
    /// explicit, and when admissible without every weakening and
    /// contraction whose branch the rules above it close, each such run's
    /// lowest conclusion shown as the conclusion of the first rule above
    /// it that is no structural one, its principal formula found there by
    /// its formula. A run above which a goal is still open stays, so that
    /// an open goal shows its own sequent. What is shown when admissible
    /// is no derivation [`check`](Self::check) accepts: its axioms have a
    /// context.
    pub fn shown(&self, structural: Structural) -> Cow<'_, Self> {
        match structural {
            Structural::Explicit => Cow::Borrowed(self),
            Structural::Admissible => Cow::Owned(self.admissible().0),
        }
    }

    /// Returns the derivation shown with its structural rules admissible,
    /// as [`shown`](Self::shown) does, and for each inference of it the
    /// inference of this derivation it shows.
    pub(crate) fn admissible(&self) -> (Self, Vec<InfId>) {
        let mut out: Vec<Inference> = Vec::with_capacity(self.inferences.len());
        // Per inference of this derivation, the one of `out` that shows it
        // and whether the rules above it close their branch.
        let mut shown: Vec<(InfId, bool)> = Vec::with_capacity(self.inferences.len());
        let mut origin = Vec::with_capacity(self.inferences.len());
        for (n, inference) in self.inferences.iter().enumerate() {
            if inference.rule.is_structural()
                && let [premise] = inference.premises[..]
                && let (above, true) = shown[premise.index()]
                // The rule above takes this conclusion where its principal
                // formula is in it, as in a derivation the checker accepts,
                // whose runs only add a formula or remove one of two
                // copies; elsewhere this inference is shown.
                && let Some(principal) = out[above.index()].principal.map_or(Some(None), |(side, at)| {
                    let id = out[above.index()].side(side)[at];
                    let found = inference.side(side).iter().position(|&x| x == id);
                    found.map(|at| Some((side, at)))
                })
            {
                let target = &mut out[above.index()];
                target.left.clone_from(&inference.left);
                target.right.clone_from(&inference.right);
                target.principal = principal;
                shown.push((above, true));
                continue;
            }
            let premises = inference
                .premises
                .iter()
                .map(|p| shown[p.index()].0)
                .collect();
            // Fewer inferences shown than this derivation has.
            let id = InfId::new(out.len() as u32);
            out.push(Inference {
                premises,
                ..inference.clone()
            });
            origin.push(InfId::new(n as u32));
            let closes = inference.rule != Rule::Open
                && inference.premises.iter().all(|p| shown[p.index()].1);
            shown.push((id, closes));
        }
        let derivation = Self {
            logic: self.logic,
            formulas: self.formulas.clone(),
            left: self.left.clone(),
            right: self.right.clone(),
            inferences: out,
        };
        (derivation, origin)
    }

    /// Checks the derivation by the rules of its logic, as [`Rule`]
    /// describes them, and that its root concludes the sequent it was read
    /// back for: each inference on its own, from the formulas as they
    /// stand, sharing nothing with the linear proof or the read-back.
    /// Checks `limits.work` inferences at most and asks `stop` before
    /// each.
    ///
    /// # Errors
    ///
    /// [`Error::ReadBack`] naming the first inference that breaks a rule;
    /// [`Refusal::Work`] past the bound and [`Refusal::Stopped`] when
    /// `stop` fired, neither a verdict on the derivation.
    pub fn check(
        &self,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<(), Error> {
        if let Some(limit) = limits.work
            && self.inferences.len() as u64 > limit
        {
            return Err(Error::Refused(Refusal::Work { limit }));
        }
        let calculus = self.logic.calculus();
        let fail = |n: usize, why: String| Error::ReadBack {
            calculus,
            reason: format!("inference {n} ({}): {why}", self.inferences[n].rule),
        };
        let root = self
            .inferences
            .len()
            .checked_sub(1)
            .ok_or(Error::ReadBack {
                calculus,
                reason: "no inference".to_owned(),
            })?;
        let root_inference = &self.inferences[root];
        if !same(&root_inference.left, &self.left) || !same(&root_inference.right, &self.right) {
            return Err(fail(
                root,
                "the root does not conclude the sequent".to_owned(),
            ));
        }
        for (n, inference) in self.inferences.iter().enumerate() {
            if stop(Progress::new(Phase::Check, 1, n as u64 + 1)) {
                return Err(Error::Refused(Refusal::Stopped {
                    phase: Phase::Check,
                }));
            }
            if inference.premises.iter().any(|p| p.index() >= n) {
                return Err(fail(n, "a premise does not precede it".to_owned()));
            }
            let premises: Vec<&Inference> = inference
                .premises
                .iter()
                .map(|&p| &self.inferences[p.index()])
                .collect();
            check_inference(&self.formulas, self.logic, inference, &premises)
                .map_err(|why| fail(n, why))?;
        }
        Ok(())
    }
}

/// Checks one inference of a derivation of `logic` over `formulas`
/// against its rule, given its premises: the number of formulas right of
/// `⊢` its logic allows, then the rule. [`Derivation::check`] asks it of
/// every inference, and a proof in progress of every step it takes.
pub(super) fn check_inference(
    formulas: &Formulas,
    logic: Logic,
    inference: &Inference,
    premises: &[&Inference],
) -> Result<(), String> {
    use Rule::*;
    use Side::{Left, Right};
    if inference.rule == Open {
        return Err("an open goal".to_owned());
    }
    if logic != Logic::Classical && inference.right.len() > 1 {
        return Err("more than one formula right of ⊢".to_owned());
    }
    // An empty right side is ⊥ for one rule and anything for another
    // (`WR`, a split `∨L`), which is ex falso.
    if logic == Logic::Minimal && inference.right.is_empty() {
        return Err("no formula right of ⊢ in minimal logic".to_owned());
    }
    let f = formulas;
    let count = |n: usize| {
        if premises.len() == n {
            Ok(())
        } else {
            Err(format!("{} premises instead of {n}", premises.len()))
        }
    };
    if inference.rule == Axiom {
        count(0)?;
        return match (&inference.left[..], &inference.right[..]) {
            ([a], [b]) if a == b && inference.principal.is_none() => Ok(()),
            _ => Err("not a sequent A ⊢ A".to_owned()),
        };
    }
    let Some((side, at)) = inference.principal else {
        return Err("no principal formula".to_owned());
    };
    let principal = *inference
        .side(side)
        .get(at)
        .ok_or("the principal position lies outside the sequent")?;
    let node = f.node(principal);
    // The sequent without the principal formula.
    let mut context = (inference.left.clone(), inference.right.clone());
    match side {
        Left => context.0.remove(at),
        Right => context.1.remove(at),
    };
    let with = |added: &[(Side, NodeId)]| {
        let mut sequent = context.clone();
        for &(side, id) in added {
            match side {
                Left => sequent.0.push(id),
                Right => sequent.1.push(id),
            }
        }
        sequent
    };
    // One premise that is the context with the formulas given added.
    let unary = |added: &[(Side, NodeId)]| {
        count(1)?;
        if is(premises[0], &with(added)) {
            Ok(())
        } else {
            Err("the premise is not what the rule makes of the conclusion".to_owned())
        }
    };
    // Two premises, each the context, whole or a part of a split, with
    // the formulas given added.
    let binary = |first: &[(Side, NodeId)], second: &[(Side, NodeId)]| {
        count(2)?;
        if is(premises[0], &with(first)) && is(premises[1], &with(second)) {
            return Ok(());
        }
        // Split: what each premise holds beyond its formulas is a part
        // of the context, the two parts together all of it.
        let rest = |p: &Inference, added: &[(Side, NodeId)]| {
            let mut left = p.left.clone();
            let mut right = p.right.clone();
            for &(side, id) in added {
                let list = if side == Left { &mut left } else { &mut right };
                let i = list.iter().position(|&x| x == id)?;
                list.remove(i);
            }
            Some((left, right))
        };
        if let (Some(mut a), Some(b)) = (rest(premises[0], first), rest(premises[1], second)) {
            a.0.extend(b.0);
            a.1.extend(b.1);
            if same(&a.0, &context.0) && same(&a.1, &context.1) {
                return Ok(());
            }
        }
        Err("the premises do not share or split the context".to_owned())
    };
    let leaf = || count(0);
    match (inference.rule, side, node) {
        (WeakenLeft, Left, _) | (WeakenRight, Right, _) => unary(&[]),
        (ContractLeft, Left, _) => unary(&[(Left, principal), (Left, principal)]),
        (ContractRight, Right, _) => unary(&[(Right, principal), (Right, principal)]),
        (AndLeft, Left, Node::And(a, b)) => unary(&[(Left, a), (Left, b)]),
        (AndLeft1, Left, Node::And(a, _)) => unary(&[(Left, a)]),
        (AndLeft2, Left, Node::And(_, b)) => unary(&[(Left, b)]),
        (AndRight, Right, Node::And(a, b)) => binary(&[(Right, a)], &[(Right, b)]),
        (OrLeft, Left, Node::Or(a, b)) => binary(&[(Left, a)], &[(Left, b)]),
        (OrRight, Right, Node::Or(a, b)) => unary(&[(Right, a), (Right, b)]),
        (OrRight1, Right, Node::Or(a, _)) => unary(&[(Right, a)]),
        (OrRight2, Right, Node::Or(_, b)) => unary(&[(Right, b)]),
        (ImpliesLeft, Left, Node::Implies(a, b)) => binary(&[(Right, a)], &[(Left, b)]),
        (ImpliesRight, Right, Node::Implies(a, b)) => unary(&[(Left, a), (Right, b)]),
        // `¬A` as itself, or as `A → ⊥` in LJ; LK's rules have their own
        // forms only, which its certificate reads.
        (NotRight, Right, Node::Not(a)) if logic == Logic::Classical => unary(&[(Left, a)]),
        (NotLeft, Left, Node::Not(_)) if logic == Logic::Classical && premises.len() != 1 => {
            Err("LK's ¬L has one premise".to_owned())
        }
        (NotRight, Right, Node::Not(a)) => unary(&[(Left, a)]).or_else(|_| {
            let falsity = formulas.ids.get(&Node::False).copied();
            unary(&[
                (Left, a),
                (Right, falsity.ok_or("no ⊥ for the form of →R")?),
            ])
        }),
        (NotLeft, Left, Node::Not(a)) if premises.len() == 1 => unary(&[(Right, a)]),
        (NotLeft, Left, Node::Not(a)) => {
            let falsity = formulas.ids.get(&Node::False).copied();
            let falsity = falsity.ok_or("no ⊥ for the form of →L")?;
            binary(&[(Right, a)], &[(Left, falsity)])
        }
        (IffLeft | IffLeft1 | IffLeft2 | IffRight, _, Node::Iff(a, b)) => {
            let forward = formulas.ids.get(&Node::Implies(a, b)).copied();
            let backward = formulas.ids.get(&Node::Implies(b, a)).copied();
            let (Some(forward), Some(backward)) = (forward, backward) else {
                return Err("the implications of the equivalence are missing".to_owned());
            };
            match (inference.rule, side) {
                (IffLeft, Left) => unary(&[(Left, forward), (Left, backward)]),
                (IffLeft1, Left) => unary(&[(Left, forward)]),
                (IffLeft2, Left) => unary(&[(Left, backward)]),
                (IffRight, Right) => binary(&[(Right, forward)], &[(Right, backward)]),
                _ => Err("the rule does not apply on this side".to_owned()),
            }
        }
        (FalseLeft, Left, Node::False) if logic != Logic::Minimal => leaf(),
        (FalseLeft, ..) if logic == Logic::Minimal => {
            Err("minimal logic has no ex falso".to_owned())
        }
        (FalseRight, Right, Node::False) | (TrueLeft, Left, Node::True) => unary(&[]),
        (TrueRight, Right, Node::True) => leaf(),
        _ => Err("the rule does not apply to the principal formula".to_owned()),
    }
}

impl Derivation {
    /// Returns the width in characters and the number of lines of the tree
    /// that [`write_text`](Self::write_text) draws under the options,
    /// without drawing it.
    pub fn text_size(&self, options: &TextOptions) -> (usize, usize) {
        crate::linear::proofs::fmt::text_size(self, options)
    }

    /// Writes the derivation as a tree of sequents `Γ ⊢ Δ`, one line per
    /// row, without a trailing newline, as
    /// [`crate::linear::Derivation::write_text`] draws a linear one, and asks
    /// `stop` before every piece of a row. The labels are those of
    /// [`Rule`] (a label table of [`Labels::Table`] is keyed by the
    /// linear rules, so it leaves them upright).
    ///
    /// # Errors
    ///
    /// [`Refusal::Stopped`] when `stop` fired, and
    /// [`Error::WriteFailed`] when `out` refused the text.
    pub fn write_text(
        &self,
        options: &TextOptions,
        out: &mut impl Write,
        stop: impl FnMut(crate::limits::Progress) -> bool,
    ) -> Result<(), Error> {
        crate::linear::proofs::fmt::write_text(
            self,
            options,
            out,
            crate::limits::counting(stop, crate::limits::Phase::Write),
        )
    }

    /// Writes the derivation as a numbered list of its inferences, one per
    /// line, premises before their conclusion and the conclusion last, as
    /// [`crate::linear::Derivation::write_steps`] reads a linear one out: the
    /// reading of a derivation for a screen reader. Asks `stop` before
    /// every line.
    ///
    /// # Errors
    ///
    /// [`Refusal::Stopped`] when `stop` fired, and
    /// [`Error::WriteFailed`] when `out` refused the text.
    pub fn write_steps(
        &self,
        out: &mut impl Write,
        stop: impl FnMut(crate::limits::Progress) -> bool,
    ) -> Result<(), Error> {
        crate::linear::proofs::fmt::write_steps(
            self,
            out,
            crate::limits::counting(stop, crate::limits::Phase::Write),
        )
    }
}

impl Display for Derivation {
    /// Draws the derivation as a tree of sequents under the default
    /// [`TextOptions`], one line per row, without a trailing newline.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.write_text(&TextOptions::default(), f, |_| false)
            .map_err(|_| std::fmt::Error)
    }
}

impl Drawn for Derivation {
    const RULES: usize = Rule::ALL.len();
    const OPEN: Option<usize> = Some(Rule::Open as usize);

    fn markup(rule: usize, labels: &Labels) -> Option<&str> {
        let rule = Rule::ALL[rule];
        match labels {
            _ if rule == Rule::Open => None,
            Labels::Upright | Labels::Table(_) => Some(rule.markup(false)),
            Labels::Subscript => Some(rule.markup(true)),
            Labels::Off => None,
        }
    }

    fn len(&self) -> usize {
        self.inferences.len()
    }

    fn root(&self) -> InfId {
        Derivation::root(self)
    }

    fn premises(&self, id: InfId) -> &[InfId] {
        &self.inference(id).premises
    }

    fn rule(&self, id: InfId) -> usize {
        self.inference(id).rule as usize
    }

    fn name(&self, id: InfId) -> &'static str {
        self.inference(id).rule.name()
    }

    fn times(&self, _: InfId) -> u32 {
        1
    }

    fn write_sequent(&self, out: &mut impl Write, id: InfId) -> FmtResult {
        let inference = self.inference(id);
        let sides = (&inference.left[..], &inference.right[..]);
        TEXT.ordinary(out, &self.formulas, sides, false, false)
    }

    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    fn sequent(
        &self,
        out: &mut String,
        notation: &Notation,
        id: InfId,
        aligned: bool,
        marks: bool,
    ) {
        let inference = self.inference(id);
        let sides = (&inference.left[..], &inference.right[..]);
        notation
            .ordinary(out, &self.formulas, sides, aligned, marks)
            .unwrap();
    }

    #[cfg(feature = "svg")]
    fn positions(&self, id: InfId) -> Vec<usize> {
        let inference = self.inference(id);
        (0..inference.left.len() + inference.right.len()).collect()
    }
}

/// Returns whether two lists are the same multiset: at once where their
/// lengths differ or they are equal as they stand, by counting where they
/// are short, and by sorting copies only where they are long, so that the
/// checker's question of every inference costs no allocation.
pub(super) fn same(a: &[NodeId], b: &[NodeId]) -> bool {
    /// The longest lists compared by counting, a square of comparisons.
    const SHORT: usize = 16;
    if a.len() != b.len() {
        return false;
    }
    if a == b {
        return true;
    }
    if a.len() <= SHORT {
        let count = |list: &[NodeId], x: NodeId| list.iter().filter(|&&y| y == x).count();
        return a.iter().all(|&x| count(a, x) == count(b, x));
    }
    let (mut a, mut b) = (a.to_vec(), b.to_vec());
    a.sort_unstable();
    b.sort_unstable();
    a == b
}

/// Returns whether an inference concludes the sequent given, as multisets.
fn is(inference: &Inference, sequent: &(Vec<NodeId>, Vec<NodeId>)) -> bool {
    same(&inference.left, &sequent.0) && same(&inference.right, &sequent.1)
}

/// A formula followed through its classical negations.
struct Unwound {
    /// The negations passed, outermost first, each with its side.
    chain: Vec<(NodeId, Side)>,
    /// The formula under them, its translation function and its side.
    core: (NodeId, u8, Side),
}

/// What a linear occurrence is the image of.
#[derive(Clone, Copy, Debug)]
struct Tag {
    /// The ordinary formula, as the sequents show it.
    node: NodeId,
    /// Its translation function.
    function: u8,
    /// The `!`s above the pattern's connective still to pass.
    bangs: u8,
    /// Its side.
    side: Side,
}

impl Image {
    /// Unfolds a proof of the image into the derivation the read-back
    /// reads: two-sided for an image in ILL, one-sided otherwise, never
    /// compact, within `limits` and until `stop` fires, as
    /// [`Proof::derivation_within`] does.
    pub(crate) fn linear_derivation<'p>(
        &self,
        proof: &'p Proof,
        limits: &Limits,
        stop: impl FnMut(Progress) -> bool,
    ) -> Result<crate::linear::Derivation<'p>, Error> {
        let sides = if self.mode.intuitionistic {
            Sides::Two
        } else {
            Sides::One
        };
        let view = ViewOptions::default()
            .with_compact(Compact::Never)
            .with_sides(sides);
        proof.derivation_within(&view, limits, stop)
    }

    /// Reads a proof of the image back as a derivation of LK (classical
    /// logic) or LJ (intuitionistic and minimal logic) of the ordinary
    /// sequent: a linear rule on an image is the rule of its connective, a
    /// dereliction or a promotion is no inference, a contraction or a
    /// weakening is one of the ordinary formula, and a classical negation,
    /// which has no image of its own, is a `¬` rule where its operand is
    /// taken apart. The proof is unfolded first, never compact (two-sided
    /// for an image in ILL), within `limits.derivation_bytes` and
    /// `limits.memory_bytes`, and `stop` is asked as that unfolding asks
    /// it and once per inference read; [`Derivation::check`] checks the
    /// result.
    ///
    /// # Errors
    ///
    /// [`Error::GoalProof`] for a proof of a goal other than the image's
    /// roots, whose read-back would conclude another sequent; as
    /// [`Proof::derivation_within`] for the unfolding; [`Error::ReadBack`]
    /// for a proof that is not of this image, or a rule with no reading;
    /// [`Refusal::Stopped`] when `stop` fired.
    #[expect(
        clippy::missing_panics_doc,
        reason = "the expects state that the forest's preorder tags a parent before its children, which the walk establishes"
    )]
    pub fn read_back(
        &self,
        proof: &Proof,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Derivation, Error> {
        if proof.goal().is_some() {
            return Err(Error::GoalProof);
        }
        let linear = &self.linear_derivation(proof, limits, &mut stop)?;
        let calculus = self.logic.calculus();
        let fail = |reason: String| Error::ReadBack { calculus, reason };
        let forest = linear.forest();
        if forest.sequent() != &self.sequent {
            return Err(fail("the proof is not of the image".to_owned()));
        }
        let formulas = &self.ordinary.formulas;
        // Every occurrence's tag, parents before children.
        let mut tags: Vec<Option<Tag>> = vec![None; forest.len()];
        for (&root, info) in forest.roots().iter().zip(&self.roots) {
            tags[root.index()] = Some(Tag {
                node: info.node,
                function: info.function,
                bangs: info.bangs,
                side: info.side,
            });
        }
        for o in forest.ids() {
            let tag = tags[o.index()].expect("a parent is tagged before its children");
            if tag.bangs > 0 {
                if let Some(child) = forest.left(o) {
                    tags[child.index()] = Some(Tag {
                        bangs: tag.bangs - 1,
                        ..tag
                    });
                }
                continue;
            }
            let (node, function, side) = self.unwind(tag.node, tag.function, tag.side).core;
            let p = pattern(
                formulas,
                &self.extra,
                self.translation,
                self.logic,
                node,
                function,
            );
            for (k, child) in forest.children(o).enumerate() {
                let Some((x, fx, extra)) = p.operands[k] else {
                    return Err(fail(format!("occurrence {} has no operand {k}", o.index())));
                };
                let px = pattern(formulas, &self.extra, self.translation, self.logic, x, fx);
                let flips = match p.core {
                    Core::Lollipop => k == 0,
                    Core::Atom
                    | Core::Unit(_)
                    | Core::Tensor
                    | Core::Par
                    | Core::With
                    | Core::Plus
                    | Core::Pass => false,
                };
                // The classical implication's antecedent is on the other
                // side through its function.
                let side = if self.translation == Translation::Affine {
                    if fx == 0 { Side::Right } else { Side::Left }
                } else if flips {
                    side.flip()
                } else {
                    side
                };
                tags[child.index()] = Some(Tag {
                    node: x,
                    function: fx,
                    bangs: px.bangs + extra,
                    side,
                });
            }
        }
        let tag = |o: OccId| tags[o.index()].expect("every occurrence is tagged");

        let mut out = Vec::new();
        // Per linear inference, the ordinary inference that stands for it.
        let mut mapped: Vec<InfId> = Vec::with_capacity(linear.inferences().len());
        for (i, inference) in linear.inferences().iter().enumerate() {
            if stop(Progress::new(Phase::ReadBack, 1, i as u64 + 1)) {
                return Err(Error::Refused(Refusal::Stopped {
                    phase: Phase::ReadBack,
                }));
            }
            let members: Vec<(NodeId, Side)> = inference
                .sequent
                .iter()
                .map(|&o| (tag(o.occ()).node, tag(o.occ()).side))
                .collect();
            let premises: Vec<InfId> = inference
                .premises
                .iter()
                .map(|p| mapped[p.index()])
                .collect();
            let rule = inference.rule.rule;
            let next = match rule {
                Linear::Promotion | Linear::Dereliction => premises[0],
                Linear::Contraction | Linear::Weakening | Linear::AffineWeakening => {
                    let at = inference
                        .principal
                        .expect("a structural rule has a principal formula");
                    let (_, side) = members[at];
                    let rule = match (rule, side) {
                        (Linear::Contraction, Side::Left) => Rule::ContractLeft,
                        (Linear::Contraction, Side::Right) => Rule::ContractRight,
                        (_, Side::Left) => Rule::WeakenLeft,
                        (_, Side::Right) => Rule::WeakenRight,
                    };
                    push(&mut out, &members, at, rule, premises)
                }
                // An image of ordinary propositional logic has no binder.
                Linear::Forall | Linear::Exists => {
                    return Err(fail(
                        "a quantifier, which the read-back has no rule for".to_owned(),
                    ));
                }
                // An ordinary derivation of the image read back is
                // cut-free, as every proof the search finds is.
                Linear::Cut => {
                    return Err(fail(
                        "a cut, which the read-back has no rule for".to_owned(),
                    ));
                }
                Linear::Ax => {
                    let mut members = members;
                    let chains: Vec<_> = (0..2)
                        .map(|at| {
                            let (node, side) = members[at];
                            let Unwound { chain, core } = self.unwind(node, 0, side);
                            members[at] = (core.0, core.2);
                            (at, chain)
                        })
                        .collect();
                    let mut id = push(&mut out, &members, usize::MAX, Rule::Axiom, premises);
                    for (at, chain) in chains {
                        id = negations(&mut out, &mut members, at, chain, id);
                    }
                    id
                }
                rule @ Linear::Tensor
                | rule @ Linear::Par
                | rule @ Linear::One
                | rule @ Linear::Bot
                | rule @ Linear::With
                | rule @ Linear::PlusLeft
                | rule @ Linear::PlusRight
                | rule @ Linear::Top
                | rule @ Linear::Mix
                | rule @ Linear::Open => {
                    let at = inference
                        .principal
                        .ok_or_else(|| fail("no principal formula".to_owned()))?;
                    let mut members = members;
                    let (node, side) = members[at];
                    let Unwound { chain, core } = self.unwind(node, 0, side);
                    members[at] = (core.0, core.2);
                    let ordinary = self
                        .rule_of(formulas.node(core.0), core.2, rule)
                        .ok_or_else(|| {
                            fail(format!(
                                "the linear rule {rule} on {} has no reading",
                                formulas.formula(core.0)
                            ))
                        })?;
                    let id = push(&mut out, &members, at, ordinary, premises);
                    negations(&mut out, &mut members, at, chain, id)
                }
            };
            mapped.push(next);
        }
        Ok(Derivation {
            logic: self.logic,
            formulas: self.ordinary.formulas.clone(),
            left: self.ordinary.left.clone(),
            right: self.ordinary.right.clone(),
            inferences: out,
        })
    }

    /// Follows a formula through the classical negations, which have no
    /// image of their own, to the formula whose connective its image has:
    /// returns the negations passed and that formula. Other translations
    /// pass none.
    fn unwind(&self, mut node: NodeId, mut function: u8, mut side: Side) -> Unwound {
        let mut chain = Vec::new();
        if self.translation == Translation::Affine {
            while let Node::Not(a) = self.ordinary.formulas.node(node) {
                chain.push((node, side));
                node = a;
                side = side.flip();
                function = 1 - function;
            }
        }
        Unwound {
            chain,
            core: (node, function, side),
        }
    }

    /// Returns the ordinary rule a classical linear rule is on the image of
    /// `node` standing on `side`.
    fn rule_of(&self, node: Node, side: Side, rule: Linear) -> Option<Rule> {
        use Linear as L;
        use Side::{Left, Right};
        Some(match (node, side, rule) {
            (Node::And(..), Right, L::With | L::Tensor) => Rule::AndRight,
            (Node::And(..), Left, L::Par) => Rule::AndLeft,
            (Node::And(..), Left, L::PlusLeft) => Rule::AndLeft1,
            (Node::And(..), Left, L::PlusRight) => Rule::AndLeft2,
            (Node::Or(..), Right, L::Par) => Rule::OrRight,
            (Node::Or(..), Right, L::PlusLeft) => Rule::OrRight1,
            (Node::Or(..), Right, L::PlusRight) => Rule::OrRight2,
            (Node::Or(..), Left, L::With) => Rule::OrLeft,
            (Node::Implies(..), Right, L::Par) => Rule::ImpliesRight,
            (Node::Implies(..), Left, L::Tensor | L::With) => Rule::ImpliesLeft,
            (Node::Not(_), Right, L::Par) => Rule::NotRight,
            (Node::Not(_), Left, L::Tensor) => Rule::NotLeft,
            (Node::Iff(..), Right, L::With | L::Tensor) => Rule::IffRight,
            (Node::Iff(..), Left, L::Par) => Rule::IffLeft,
            (Node::Iff(..), Left, L::PlusLeft) => Rule::IffLeft1,
            (Node::Iff(..), Left, L::PlusRight) => Rule::IffLeft2,
            (Node::True, Right, L::Top | L::One) => Rule::TrueRight,
            (Node::True, Left, L::Bot) => Rule::TrueLeft,
            (Node::False, Left, L::Top) => Rule::FalseLeft,
            (Node::False, Right, L::Bot) => Rule::FalseRight,
            _ => return None,
        })
    }
}

/// Adds the inference concluding `members` by `rule`, with the formula at
/// `at` principal (none for an axiom), and returns its id.
fn push(
    out: &mut Vec<Inference>,
    members: &[(NodeId, Side)],
    at: usize,
    rule: Rule,
    premises: Vec<InfId>,
) -> InfId {
    let lefts = members
        .iter()
        .filter(|&&(_, side)| side == Side::Left)
        .count();
    let (mut left, mut right) = (
        Vec::with_capacity(lefts),
        Vec::with_capacity(members.len() - lefts),
    );
    let mut principal = None;
    for (i, &(node, side)) in members.iter().enumerate() {
        let list = if side == Side::Left {
            &mut left
        } else {
            &mut right
        };
        if i == at {
            principal = Some((side, list.len()));
        }
        list.push(node);
    }
    out.push(Inference {
        left,
        right,
        rule,
        principal,
        premises,
    });
    // A read-back has an inference for every linear inference and every
    // negation passed, as many as the linear derivation's `InfId` counts
    // times the depth of a formula, far below `u32::MAX` for any proof a
    // search returns within its memory bound.
    InfId::new(out.len() as u32 - 1)
}

/// Adds below `id` the `¬` inferences that take the formula at `at` from
/// its core back to the negations of `chain`, the innermost first, and
/// returns the last one.
fn negations(
    out: &mut Vec<Inference>,
    members: &mut [(NodeId, Side)],
    at: usize,
    chain: Vec<(NodeId, Side)>,
    mut id: InfId,
) -> InfId {
    for (node, side) in chain.into_iter().rev() {
        members[at] = (node, side);
        let rule = match side {
            Side::Left => Rule::NotLeft,
            Side::Right => Rule::NotRight,
        };
        id = push(out, members, at, rule, vec![id]);
    }
    id
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::super::{Sequent, translate};
    use super::*;
    use crate::linear::{Options, Verdict, prove};

    /// The text tree draws `Γ ⊢ Δ` with the rules of LJ, and its size is
    /// that of the text.
    #[test]
    fn text_tree() {
        let sequent: Sequent = "a -> b, b -> c |- a -> c".parse().unwrap();
        let image = translate(
            &sequent,
            Logic::Intuitionistic,
            Translation::CallByName,
            &crate::Limits::default(),
        )
        .unwrap();
        let outcome = prove(image.sequent(), image.mode(), &Options::default()).unwrap();
        let Verdict::Proved(proof) = &outcome.verdict else {
            panic!("provable");
        };
        let derivation = image
            .read_back(proof, &crate::Limits::default(), |_| false)
            .unwrap();
        let tree = derivation.to_string();
        assert_eq!(
            tree,
            "───── ax   ───── ax\n\
             a ⊢ a      b ⊢ b\n\
             ──────────────── →L   ───── ax\n\
            \x20 a → b, a ⊢ b        c ⊢ c\n\
            \x20 ───────────────────────── →L\n\
            \x20    a → b, b → c, a ⊢ c\n\
            \x20    ──────────────────── →R\n\
            \x20    a → b, b → c ⊢ a → c"
        );
        let width = tree.lines().map(|l| l.chars().count()).max();
        let size = derivation.text_size(&crate::linear::proofs::TextOptions::default());
        assert_eq!(Some(size), width.map(|w| (w, tree.lines().count())));
        let root = derivation.inferences().last().unwrap();
        assert_eq!(root.rule(), Rule::ImpliesRight);
        assert_eq!((root.left().len(), root.right().len()), (2, 1));
        assert_eq!(root.principal(), Some((Side::Right, 0)));
        assert_eq!(root.premises(), [InfId::new(4)]);
        let mut steps = String::new();
        derivation.write_steps(&mut steps, |_| false).unwrap();
        assert_eq!(steps.lines().count(), 6);
        assert_eq!(
            steps.lines().last(),
            Some("6. a → b, b → c ⊢ a → c, by →R from 5.")
        );
    }

    /// Ex falso through an empty right side, `a, ¬a ⊢` weakened to
    /// `a, ¬a ⊢ b`, is refused in minimal logic and accepted in
    /// intuitionistic logic.
    #[test]
    fn minimal_logic_refuses_an_empty_right_side() {
        let sequent: Sequent = "a, ~a |- b".parse().unwrap();
        let f = sequent.formulas();
        let (a, not_a, b) = (sequent.left()[0], sequent.left()[1], sequent.right()[0]);
        let inference = |left: Vec<NodeId>, right, rule, principal, premises: &[u32]| Inference {
            left,
            right,
            rule,
            principal,
            premises: premises.iter().map(|&p| InfId::new(p)).collect(),
        };
        let forged = |logic| Derivation {
            logic,
            formulas: f.clone(),
            left: vec![a, not_a],
            right: vec![b],
            inferences: vec![
                inference(vec![a], vec![a], Rule::Axiom, None, &[]),
                inference(
                    vec![a, not_a],
                    vec![],
                    Rule::NotLeft,
                    Some((Side::Left, 1)),
                    &[0],
                ),
                inference(
                    vec![a, not_a],
                    vec![b],
                    Rule::WeakenRight,
                    Some((Side::Right, 0)),
                    &[1],
                ),
            ],
        };
        let unbounded = crate::Limits::default();
        assert!(
            forged(Logic::Intuitionistic)
                .check(&unbounded, |_| false)
                .is_ok()
        );
        assert!(matches!(
            forged(Logic::Minimal).check(&unbounded, |_| false),
            Err(Error::ReadBack { .. })
        ));
    }

    /// Both labels of every rule read as its name in plain text, the
    /// subscript one with its side lowered, as the linear rules' upright
    /// ones do (`names_round_trip` in `proofs::style`), and the table is
    /// in the order of `Rule::ALL`.
    #[test]
    fn labels_are_the_names() {
        use crate::linear::proofs::style::plain;
        for (i, rule) in Rule::ALL.into_iter().enumerate() {
            assert_eq!(rule as usize, i, "{rule}");
            assert_eq!(plain(rule.markup(false)), rule.name(), "{rule}");
            assert_eq!(plain(rule.markup(true)), rule.name(), "{rule}");
        }
    }

    /// Every rule a step takes reads back from its name and from its
    /// ASCII spelling, and an open goal or an unknown name is refused.
    #[test]
    fn rules_read_from_their_names() {
        for rule in &Rule::ALL[..Rule::ALL.len() - 1] {
            assert_eq!(rule.name().parse::<Rule>().unwrap(), *rule);
        }
        for (name, rule) in super::ASCII {
            assert_eq!(name.parse::<Rule>().unwrap(), rule, "{name}");
        }
        assert_eq!("∨R2".parse::<Rule>().unwrap(), Rule::OrRight2);
        for refused in ["open", "⊗", "and", "-oL"] {
            assert!(matches!(
                refused.parse::<Rule>(),
                Err(Error::UnknownName { .. })
            ));
        }
    }

    /// A proof of a goal off the image's roots is refused before it is
    /// read back: its derivation would conclude another sequent.
    #[test]
    fn a_goal_proof_reads_back_as_nothing() {
        let sequent: Sequent = "a, b |- a".parse().unwrap();
        let image = translate(
            &sequent,
            Logic::Intuitionistic,
            Translation::CallByName,
            &crate::Limits::default(),
        )
        .unwrap();
        let forest = crate::linear::Forest::new(image.sequent()).unwrap();
        let roots = forest.roots();
        let goal = [
            crate::linear::Member::from(roots[0]),
            crate::linear::Member::from(roots[2]),
        ];
        let limits = crate::Limits::default();
        let outcome = crate::linear::search::prove_goal(
            crate::linear::search::Goal::new(&forest, &goal).unwrap(),
            image.mode(),
            &Options::default(),
            &limits,
            |_| false,
        )
        .unwrap();
        let Verdict::Proved(proof) = &outcome.verdict else {
            panic!("a ⊢ a is provable");
        };
        assert_eq!(
            image.read_back(proof, &limits, |_| false).unwrap_err(),
            Error::GoalProof
        );
    }

    /// Two lists are one multiset whatever their order, short or long,
    /// and two with a member counted differently are not.
    #[test]
    fn same_compares_multisets() {
        let ids = |list: &[u32]| list.iter().map(|&i| NodeId(i)).collect::<Vec<_>>();
        let long: Vec<u32> = (0..40).map(|i| i % 7).collect();
        let reversed: Vec<u32> = long.iter().rev().copied().collect();
        let mut other = long.clone();
        other[0] = 6;
        for (a, b, equal) in [
            (&[1, 2, 2][..], &[2, 1, 2][..], true),
            (&[1, 2, 2], &[1, 1, 2], false),
            (&[1, 2], &[1, 2, 2], false),
            (&long, &reversed, true),
            (&long, &other, false),
        ] {
            assert_eq!(same(&ids(a), &ids(b)), equal, "{a:?} {b:?}");
        }
    }

    /// Every guard of the checker refuses what it guards against: a
    /// derivation read back checks, and each of these breaks of one of its
    /// inferences fails, with the bound and the stop refusing besides.
    #[test]
    fn the_checker_refuses_each_break() {
        let sequent: Sequent = "a -> b, b -> c |- a -> c".parse().unwrap();
        let image = translate(
            &sequent,
            Logic::Intuitionistic,
            Translation::CallByName,
            &crate::Limits::default(),
        )
        .unwrap();
        let outcome = prove(image.sequent(), image.mode(), &Options::default()).unwrap();
        let Verdict::Proved(proof) = &outcome.verdict else {
            panic!("provable");
        };
        let unbounded = crate::Limits::default();
        let derivation = image.read_back(proof, &unbounded, |_| false).unwrap();
        assert_eq!(derivation.check(&unbounded, |_| false), Ok(()));
        let rules: Vec<Rule> = derivation.inferences.iter().map(|i| i.rule).collect();
        let at = |rule| rules.iter().position(|&r| r == rule).unwrap();
        let (axiom, left, right) = (
            at(Rule::Axiom),
            at(Rule::ImpliesLeft),
            at(Rule::ImpliesRight),
        );
        let root = rules.len() - 1;
        // Each break with the reason its guard gives: with the guard
        // gone, another would fail it for another reason, or none would.
        type Break = (&'static str, Box<dyn Fn(&mut Derivation)>);
        let broken: [Break; 12] = [
            (
                "an open goal",
                Box::new(move |d| d.inferences[axiom].rule = Rule::Open),
            ),
            ("the root does not conclude", Box::new(|d| d.right.clear())),
            (
                "not a sequent A ⊢ A",
                Box::new(move |d| d.inferences[axiom].principal = Some((Side::Left, 0))),
            ),
            (
                "a premise does not precede",
                Box::new(move |d| {
                    d.inferences[left].premises[0] = InfId::new(root as u32);
                }),
            ),
            (
                "more than one formula right",
                Box::new(move |d| {
                    let extra = d.inferences[axiom].left[0];
                    d.inferences[axiom].right.push(extra);
                }),
            ),
            (
                "not a sequent A ⊢ A",
                Box::new(move |d| {
                    let other = d.inferences[right].right[0];
                    d.inferences[axiom].right[0] = other;
                }),
            ),
            (
                "no principal formula",
                Box::new(move |d| d.inferences[left].principal = None),
            ),
            (
                "lies outside the sequent",
                Box::new(move |d| {
                    d.inferences[left].principal = Some((Side::Left, 9));
                }),
            ),
            (
                "premises instead of 2",
                Box::new(move |d| {
                    d.inferences[left].premises.pop();
                }),
            ),
            (
                "do not share or split",
                Box::new(move |d| d.inferences[left].premises.reverse()),
            ),
            (
                "does not apply to the principal",
                Box::new(move |d| {
                    d.inferences[right].rule = Rule::AndRight;
                }),
            ),
            (
                "not what the rule makes",
                Box::new(move |d| {
                    d.inferences[right].premises[0] = InfId::new(axiom as u32);
                }),
            ),
        ];
        for (why, mutate) in &broken {
            let mut d = derivation.clone();
            mutate(&mut d);
            match d.check(&unbounded, |_| false) {
                Err(Error::ReadBack { reason, .. }) => {
                    assert!(reason.contains(why), "{why}: {reason}")
                }
                other => panic!("{why}: {other:?}"),
            }
        }
        // A rule whose premises share the context, the second one wrong
        // (`∧R` of LJ under cbn), a `⊥L` in minimal logic, and a `⊥R`
        // read back from a linear `⊥`.
        let read = |input: &str, logic, translation| {
            let sequent: Sequent = input.parse().unwrap();
            let image = translate(&sequent, logic, translation, &crate::Limits::default()).unwrap();
            let outcome = prove(image.sequent(), image.mode(), &Options::default()).unwrap();
            let Verdict::Proved(proof) = &outcome.verdict else {
                panic!("{input} is provable");
            };
            let derivation = image.read_back(proof, &unbounded, |_| false).unwrap();
            assert_eq!(derivation.check(&unbounded, |_| false), Ok(()), "{input}");
            derivation
        };
        let reason = |d: &Derivation| match d.check(&unbounded, |_| false) {
            Err(Error::ReadBack { reason, .. }) => reason,
            other => panic!("{other:?}"),
        };
        let cbn = Translation::CallByName;
        let mut shared = read("a, b |- a /\\ b", Logic::Intuitionistic, cbn);
        let and = shared
            .inferences
            .iter()
            .position(|i| i.rule == Rule::AndRight)
            .unwrap();
        let first = shared.inferences[and].premises[0];
        shared.inferences[and].premises[1] = first;
        assert!(reason(&shared).contains("do not share or split"));
        let mut minimal = read("a -> b, b -> c |- a -> c", Logic::Minimal, cbn);
        let leaf = minimal
            .inferences
            .iter()
            .position(|i| i.rule == Rule::Axiom)
            .unwrap();
        minimal.inferences[leaf].rule = Rule::FalseLeft;
        minimal.inferences[leaf].principal = Some((Side::Left, 0));
        assert!(reason(&minimal).contains("minimal logic has no ex falso"));
        let falsity = read("a |- a, false", Logic::Classical, Translation::Affine);
        assert!(
            falsity
                .inferences
                .iter()
                .any(|i| i.rule == Rule::FalseRight)
        );
        // A split (LJ's →L) whose conclusion holds a hypothesis neither
        // premise has, the right sides agreeing.
        let mut split = derivation.clone();
        let extra = split.inferences[axiom].left[0];
        split.inferences[left].left.push(extra);
        let at_split = format!("inference {left} (→L): the premises do not share or split");
        assert!(reason(&split).starts_with(&at_split), "{}", reason(&split));
        // A contraction whose premise holds its formula not at all, or
        // once (through a weakening), on either side: `a, b ⊢ a` and
        // `a ⊢ a, b` from `a ⊢ a`.
        let base = read("a -> b, a |- b", Logic::Classical, Translation::Affine);
        let atom = |i| base.formulas.ids[&Node::Atom(i)];
        let (a, b) = (atom(0), atom(1));
        let sides = [
            (Rule::ContractLeft, Rule::WeakenLeft, Side::Left),
            (Rule::ContractRight, Rule::WeakenRight, Side::Right),
        ];
        for (contract, weaken, side) in sides {
            let with_b = match side {
                Side::Left => (vec![a, b], vec![a]),
                Side::Right => (vec![a], vec![a, b]),
            };
            let make = |rule, premises: Vec<InfId>| Inference {
                left: with_b.0.clone(),
                right: with_b.1.clone(),
                rule,
                principal: Some((side, 1)),
                premises,
            };
            let axiom = Inference {
                left: vec![a],
                right: vec![a],
                rule: Rule::Axiom,
                principal: None,
                premises: Vec::new(),
            };
            let once = make(weaken, vec![InfId::new(0)]);
            for inferences in [
                vec![axiom.clone(), make(contract, vec![InfId::new(0)])],
                vec![axiom, once, make(contract, vec![InfId::new(1)])],
            ] {
                let mut contracted = base.clone();
                let root = inferences.len() - 1;
                contracted.inferences = inferences;
                (contracted.left, contracted.right) = with_b.clone();
                let expected = format!("inference {root} ({contract}): the premise is not what");
                assert!(reason(&contracted).starts_with(&expected), "{contract}");
            }
        }
        let one = unbounded.with_work(Some(1));
        assert_eq!(
            derivation.check(&one, |_| false),
            Err(Error::Refused(Refusal::Work { limit: 1 }))
        );
        let enough = unbounded.with_work(Some(derivation.inferences.len() as u64));
        assert_eq!(derivation.check(&enough, |_| false), Ok(()));
        assert_eq!(
            derivation.check(&unbounded, |_| true),
            Err(Error::Refused(Refusal::Stopped {
                phase: Phase::Check
            }))
        );
        assert_eq!(
            image
                .read_back(proof, &unbounded, |p| p.phase == Phase::ReadBack)
                .unwrap_err(),
            Error::Refused(Refusal::Stopped {
                phase: Phase::ReadBack
            })
        );
    }
}