deduxit 0.5.0

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

//! The two-sided view of a derivation of classical linear logic: the
//! one-sided derivation read through the record of how its sequent was
//! written. Every sequent is split by side, every rule is named by the
//! side of its principal formula, and a negation step, which the one-sided
//! calculus does not have, stands wherever a negation was written.

use super::view::{Derivation, InfId, Inference};
use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::occurrences::written::{self, Written};
use crate::linear::occurrences::{Forest, Member, OccId, Side};
use crate::linear::proofs::size::Weights;
use crate::linear::proofs::style::{Drawn, Labels};
use crate::linear::proofs::{Rule, Size, TextOptions};
use std::fmt::{Display, Formatter, Result as FmtResult, Write};

/// A rule of the two-sided sequent calculus of classical linear logic, as
/// the two-sided view ([`TwoSided`]) names it.
///
/// It is a one-sided rule applied to a formula on one side of `⊢`, or a
/// negation step, which moves a formula written with a negation to the
/// other side of `⊢` without it.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ClassicalRule {
    /// `ax`: `A ⊢ A`.
    Axiom,
    /// `⊗L`
    TensorLeft,
    /// `⊗R`
    TensorRight,
    /// `⅋L`
    ParLeft,
    /// `⅋R`
    ParRight,
    /// `⊸L`
    LollipopLeft,
    /// `⊸R`
    LollipopRight,
    /// `1L`
    OneLeft,
    /// `1R`
    OneRight,
    /// `⊥L`
    BotLeft,
    /// `⊥R`
    BotRight,
    /// `&L₁`
    WithLeft1,
    /// `&L₂`
    WithLeft2,
    /// `&R`
    WithRight,
    /// `⊕L`
    PlusLeft,
    /// `⊕R₁`
    PlusRight1,
    /// `⊕R₂`
    PlusRight2,
    /// `⊤R`
    TopRight,
    /// `0L`
    ZeroLeft,
    /// `!L`, dereliction.
    BangLeft,
    /// `!R`, promotion.
    BangRight,
    /// `!c`, contraction of a `!` formula on the left.
    BangContraction,
    /// `!w`, weakening by a `!` formula on the left.
    BangWeakening,
    /// `?L`, promotion on the left.
    QuestLeft,
    /// `?R`, dereliction on the right.
    QuestRight,
    /// `?c`, contraction of a `?` formula on the right.
    QuestContraction,
    /// `?w`, weakening by a `?` formula on the right.
    QuestWeakening,
    /// `∀L`: from `Γ, A[t/x] ⊢ Δ` to `Γ, ∀x. A ⊢ Δ`.
    ForallLeft,
    /// `∀R`: from `Γ ⊢ A[a/x], Δ` to `Γ ⊢ ∀x. A, Δ`, the eigenvariable `a`
    /// in neither `Γ` nor `Δ`.
    ForallRight,
    /// `∃L`: from `Γ, A[a/x] ⊢ Δ` to `Γ, ∃x. A ⊢ Δ`, the eigenvariable `a`
    /// in neither `Γ` nor `Δ`.
    ExistsLeft,
    /// `∃R`: from `Γ ⊢ A[t/x], Δ` to `Γ ⊢ ∃x. A, Δ`.
    ExistsRight,
    /// `mix`
    Mix,
    /// `wk`, weakening by a formula that is no exponential, in affine
    /// mode.
    Weakening,
    /// `cut`: from `Γ ⊢ A, Δ` and `Γ', A ⊢ Δ'` to `Γ, Γ' ⊢ Δ, Δ'`.
    Cut,
    /// `~L`: from `Γ ⊢ A, Δ` to `Γ, A⊥ ⊢ Δ`.
    NegationLeft,
    /// `~R`: from `Γ, A ⊢ Δ` to `Γ ⊢ A⊥, Δ`.
    NegationRight,
    /// An open goal of a proof in progress.
    Open,
}

impl ClassicalRule {
    /// Every rule, in the order of declaration, by which the label tables
    /// are indexed.
    pub(crate) const ALL: [Self; 37] = {
        use ClassicalRule::*;
        [
            Axiom,
            TensorLeft,
            TensorRight,
            ParLeft,
            ParRight,
            LollipopLeft,
            LollipopRight,
            OneLeft,
            OneRight,
            BotLeft,
            BotRight,
            WithLeft1,
            WithLeft2,
            WithRight,
            PlusLeft,
            PlusRight1,
            PlusRight2,
            TopRight,
            ZeroLeft,
            BangLeft,
            BangRight,
            BangContraction,
            BangWeakening,
            QuestLeft,
            QuestRight,
            QuestContraction,
            QuestWeakening,
            ForallLeft,
            ForallRight,
            ExistsLeft,
            ExistsRight,
            Mix,
            Weakening,
            Cut,
            NegationLeft,
            NegationRight,
            Open,
        ]
    };

    /// The upright labels, in the order of [`ALL`](Self::ALL).
    const UPRIGHT: [&'static str; 37] = [
        "ax", "⊗L", "⊗R", "⅋L", "⅋R", "⊸L", "⊸R", "1L", "1R", "⊥L", "⊥R", "&L_1", "&L_2", "&R",
        "⊕L", "⊕R_1", "⊕R_2", "⊤R", "0L", "!L", "!R", "!c", "!w", "?L", "?R", "?c", "?w", "∀L",
        "∀R", "∃L", "∃R", "mix", "wk", "cut", "~L", "~R", "",
    ];

    /// The labels with the side as a subscript, in the order of
    /// [`ALL`](Self::ALL).
    const SUBSCRIPT: [&'static str; 37] = [
        "ax", "⊗_L", "⊗_R", "⅋_L", "⅋_R", "⊸_L", "⊸_R", "1_L", "1_R", "⊥_L", "⊥_R", "&_{L1}",
        "&_{L2}", "&_R", "⊕_L", "⊕_{R1}", "⊕_{R2}", "⊤_R", "0_L", "!_L", "!_R", "!_c", "!_w",
        "?_L", "?_R", "?_c", "?_w", "∀_L", "∀_R", "∃_L", "∃_R", "mix", "wk", "cut", "~_L", "~_R",
        "",
    ];

    /// Returns the rule's name: `⊗L`, `⅋R`, `⊸L`, `&L₁`, `~R`, and so on.
    pub const fn name(self) -> &'static str {
        use ClassicalRule::*;
        match self {
            Axiom => "ax",
            TensorLeft => "⊗L",
            TensorRight => "⊗R",
            ParLeft => "⅋L",
            ParRight => "⅋R",
            LollipopLeft => "⊸L",
            LollipopRight => "⊸R",
            OneLeft => "1L",
            OneRight => "1R",
            BotLeft => "⊥L",
            BotRight => "⊥R",
            WithLeft1 => "&L₁",
            WithLeft2 => "&L₂",
            WithRight => "&R",
            PlusLeft => "⊕L",
            PlusRight1 => "⊕R₁",
            PlusRight2 => "⊕R₂",
            TopRight => "⊤R",
            ZeroLeft => "0L",
            BangLeft => "!L",
            BangRight => "!R",
            BangContraction => "!c",
            BangWeakening => "!w",
            QuestLeft => "?L",
            QuestRight => "?R",
            QuestContraction => "?c",
            QuestWeakening => "?w",
            ForallLeft => "∀L",
            ForallRight => "∀R",
            ExistsLeft => "∃L",
            ExistsRight => "∃R",
            Mix => "mix",
            Weakening => "wk",
            Cut => "cut",
            NegationLeft => "~L",
            NegationRight => "~R",
            Open => "open",
        }
    }

    /// Returns the one-sided rule behind the rule, or `None` for a
    /// negation step. The one-sided calculus has no negation step: read
    /// one-sided, its premise and its conclusion are the same sequent.
    pub const fn rule(self) -> Option<Rule> {
        use ClassicalRule::*;
        Some(match self {
            Axiom => Rule::Ax,
            TensorRight | ParLeft | LollipopLeft => Rule::Tensor,
            TensorLeft | ParRight | LollipopRight => Rule::Par,
            OneRight | BotLeft => Rule::One,
            OneLeft | BotRight => Rule::Bot,
            WithRight | PlusLeft => Rule::With,
            PlusRight1 | WithLeft1 => Rule::PlusLeft,
            PlusRight2 | WithLeft2 => Rule::PlusRight,
            TopRight | ZeroLeft => Rule::Top,
            BangRight | QuestLeft => Rule::Promotion,
            BangLeft | QuestRight => Rule::Dereliction,
            BangContraction | QuestContraction => Rule::Contraction,
            BangWeakening | QuestWeakening => Rule::Weakening,
            ForallRight | ExistsLeft => Rule::Forall,
            ExistsRight | ForallLeft => Rule::Exists,
            Mix => Rule::Mix,
            Weakening => Rule::AffineWeakening,
            Cut => Rule::Cut,
            Open => Rule::Open,
            NegationLeft | NegationRight => return None,
        })
    }

    /// Returns the side of `⊢` the principal formula stands on in the
    /// rule's conclusion, or `None` for the axiom, Mix, weakening, the cut
    /// and an open goal, whose names have no side.
    pub const fn side(self) -> Option<Side> {
        use ClassicalRule::*;
        match self {
            TensorLeft | ParLeft | LollipopLeft | OneLeft | BotLeft | WithLeft1 | WithLeft2
            | PlusLeft | ZeroLeft | BangLeft | BangContraction | BangWeakening | QuestLeft
            | ForallLeft | ExistsLeft | NegationLeft => Some(Side::Input),
            TensorRight | ParRight | LollipopRight | OneRight | BotRight | WithRight
            | PlusRight1 | PlusRight2 | TopRight | BangRight | QuestRight | QuestContraction
            | QuestWeakening | ForallRight | ExistsRight | NegationRight => Some(Side::Output),
            Axiom | Mix | Weakening | Cut | Open => None,
        }
    }

    /// Returns the two-sided name of the one-sided rule `rule` applied to a
    /// formula written as `written`. For example, a `⊗` on the input side
    /// is `⅋L` (or `⊸L` where an implication was written), and a `∀` on the
    /// input side is `∃L`.
    fn applied(rule: Rule, written: Written) -> Self {
        use ClassicalRule::*;
        let left = written.side() == Side::Input;
        let pick = |input, output| if left { input } else { output };
        match rule {
            Rule::Forall => pick(ExistsLeft, ForallRight),
            Rule::Exists => pick(ForallLeft, ExistsRight),
            Rule::Ax => Axiom,
            Rule::Tensor if written.is_implication() => LollipopLeft,
            Rule::Tensor => pick(ParLeft, TensorRight),
            Rule::Par if written.is_implication() => LollipopRight,
            Rule::Par => pick(TensorLeft, ParRight),
            Rule::One => pick(BotLeft, OneRight),
            Rule::Bot => pick(OneLeft, BotRight),
            Rule::With => pick(PlusLeft, WithRight),
            Rule::PlusLeft => pick(WithLeft1, PlusRight1),
            Rule::PlusRight => pick(WithLeft2, PlusRight2),
            Rule::Top => pick(ZeroLeft, TopRight),
            Rule::Promotion => pick(QuestLeft, BangRight),
            Rule::Dereliction => pick(BangLeft, QuestRight),
            Rule::Contraction => pick(BangContraction, QuestContraction),
            Rule::Weakening => pick(BangWeakening, QuestWeakening),
            Rule::Mix => Mix,
            Rule::AffineWeakening => Weakening,
            Rule::Cut => Cut,
            Rule::Open => Open,
        }
    }

    /// Returns the negation step whose principal formula stands on `side`
    /// in its conclusion.
    const fn negation(side: Side) -> Self {
        match side {
            Side::Input => Self::NegationLeft,
            Side::Output => Self::NegationRight,
        }
    }

    /// Returns the rule's label in the markup of the labels, upright or
    /// with the side as a subscript; empty for an open goal.
    pub(crate) const fn markup(self, subscript: bool) -> &'static str {
        if subscript {
            Self::SUBSCRIPT[self as usize]
        } else {
            Self::UPRIGHT[self as usize]
        }
    }
}

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

/// One inference of the two-sided view: the one-sided sequent it shows,
/// which of its formulas stand before their negation step, its rule and
/// its premises.
#[derive(Clone, Debug)]
struct Shown {
    /// The one-sided inference whose sequent this one shows.
    base: InfId,
    /// The positions in that sequent of the formulas whose negation step
    /// stands above: they are shown as written inside their parent,
    /// negation and all, on the side their parent puts them.
    pending: Vec<usize>,
    /// The positions in that sequent of formulas it leaves out, where a
    /// run of the one-sided derivation is split by side: the copies the
    /// upper half of a run of contractions has not made yet, or what the
    /// lower half of a run of weakenings weakens.
    hidden: Vec<usize>,
    /// The rule.
    rule: ClassicalRule,
    /// The premises, in the rule's order.
    premises: Vec<InfId>,
    /// How many applications of the rule it stands for.
    times: u32,
}

/// The two-sided view of a derivation of classical linear logic, drawn as
/// its sequent was written.
///
/// Each formula stands on the side of `⊢` it was written on, each rule
/// has its two-sided name (`⊗L`, `⅋R`, `⊸L`, …, [`ClassicalRule`]), and
/// a negation step (`~L`, `~R`) stands wherever a negation was written.
/// A negation step moves a formula across `⊢`: from `Γ, A ⊢ Δ` to
/// `Γ ⊢ A⊥, Δ`. The one-sided calculus has no such step.
///
/// A one-sided proof has many two-sided derivations. The record of the
/// written sequent
/// ([`ClassicalSequent::writing`](crate::linear::ClassicalSequent::writing))
/// picks the one written:
/// - A formula is shown on the side its connective was written on.
/// - A formula written with a negation is shown with it, on the side its
///   parent puts it, only in the premise of the rule that exposes it (or
///   in the conclusion, for a formula of the sequent). A negation step
///   right above moves it. So every rule acts on formulas as they were
///   written.
/// - A compact run of weakenings or contractions that acts on both sides
///   of `⊢` is shown as two inferences, `!w*` below `?w*`, so that each
///   inference is one rule.
/// - The derivation of a goal (a proof of a goal rather than of the
///   sequent) ends in the goal as the rules above it read it, with no
///   negation step below: that is how the goal stands in a larger
///   derivation.
/// - At first order the quantifier rules are `∀L`, `∀R`, `∃L` and `∃R`,
///   and an instance is written with the eigenvariables and witnesses of
///   its frame, as the derivation writes it.
///
/// Read one-sided (every formula on the left negated and moved right),
/// every inference is the one-sided inference it shows, and a negation
/// step's conclusion is its premise's sequent again.
///
/// [`Display`] draws the tree as [`Derivation`]'s does.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::{Limits, linear::{ClassicalSequent, Mode, Options, TwoSided, prove}};
///
/// let written: ClassicalSequent = "|- A^ par A".parse()?;
/// let outcome = prove(written.sequent(), Mode::CLASSICAL, &Options::default())?;
/// let proof = outcome.verdict.proof().unwrap();
/// let derivation = proof.derivation()?;
/// let view = TwoSided::new(&derivation, written.writing(), &Limits::default())?;
/// assert_eq!(
///     view.to_string(),
///     " ───── ax\n A ⊢ A\n─────── ~R\n⊢ ~A, A\n──────── ⅋R\n⊢ ~A ⅋ A"
/// );
/// # Ok::<(), deduxit::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct TwoSided<'a> {
    /// The one-sided derivation shown.
    derivation: &'a Derivation<'a>,
    /// How every occurrence of its forest was written.
    writing: &'a [Written],
    /// The inferences, premises before conclusions, the root last.
    inferences: Vec<Shown>,
}

impl<'a> TwoSided<'a> {
    /// Returns the two-sided view of a one-sided derivation whose sequent
    /// was written as `writing` records, unless the view is estimated past
    /// `limits.derivation_bytes`. A negation step repeats a sequent, so
    /// the view has at most three times the derivation's inferences, plus
    /// one per formula of the sequent.
    ///
    /// # Errors
    ///
    /// [`Refusal::Output`] past the bound and [`Refusal::Index`] for more
    /// inferences than an [`InfId`] counts, which only a call without a
    /// bound can reach, each with nothing built.
    ///
    /// # Panics
    ///
    /// For a record of another sequent than the derivation's: one entry
    /// per occurrence of its forest, as
    /// [`ClassicalSequent::writing`](crate::linear::ClassicalSequent::writing) or
    /// a session's [`writing`](crate::linear::Interactive::writing) gives it.
    pub fn new(
        derivation: &'a Derivation<'a>,
        writing: &'a [Written],
        limits: &Limits,
    ) -> Result<Self, Error> {
        let forest = derivation.forest();
        if let Some(fault) = written::fault(forest, writing) {
            panic!("the record is not one of the derivation's sequent: {fault}");
        }
        let view = Self {
            derivation,
            writing,
            inferences: Vec::new(),
        };
        // The same walk runs twice, first counting and then making, so
        // that nothing past the bound is made.
        let mut counted = Counted::new(derivation);
        view.walk(&mut counted);
        if counted.inferences > Derivation::MOST {
            return Err(Error::Refused(Refusal::Index {
                what: Space::Inference,
                count: counted.inferences,
                most: Derivation::MOST,
            }));
        }
        if let Some(bound) = limits.derivation_bytes
            && counted.bytes > bound
        {
            return Err(Error::Refused(Refusal::Output {
                what: "derivation",
                estimate_bytes: counted.bytes,
                limit_bytes: bound,
                least_bytes: None,
            }));
        }
        // At most `Derivation::MOST`. A `usize` holds that on any target
        // with the memory for that many inferences.
        let mut made = Vec::with_capacity(usize::try_from(counted.inferences).unwrap_or(0));
        view.walk(&mut made);
        Ok(Self {
            inferences: made,
            ..view
        })
    }

    /// Walks the view's inferences in their order, premises before
    /// conclusions, handing each to `sink`, which returns its id.
    fn walk(&self, sink: &mut impl Sink) {
        let derivation = self.derivation;
        let forest = derivation.forest();
        let mut ids = Vec::with_capacity(derivation.inferences().len());
        for (index, inference) in derivation.inferences().iter().enumerate() {
            let rule = inference.rule().rule;
            let principal = inference
                .principal()
                .map(|position| inference.sequent()[position]);
            let body = matches!(rule, Rule::Forall | Rule::Exists);
            let mut premises = Vec::with_capacity(inference.premises().len());
            for (j, &premise) in inference.premises().iter().enumerate() {
                let top: InfId = ids[premise.index()];
                // A cut puts its cut formula into its first premise and the
                // dual into its second, each written as a root is; each is
                // exposed under the cut's member.
                let exposed = match (inference.cut(), principal) {
                    (Some(a), _) => {
                        let o = derivation.occurrence(a);
                        let c = if j == 0 { o } else { forest.dual(o).unwrap() };
                        Some((a, [Some(c), None]))
                    }
                    (None, Some(p)) => {
                        Some((p, exposed(forest, rule, derivation.occurrence(p), j)))
                    }
                    (None, None) => None,
                };
                let negated = exposed
                    .into_iter()
                    .flat_map(|(of, children)| children.into_iter().flatten().map(move |c| (of, c)))
                    .filter(|&(_, c)| written::negated(forest, self.writing, c))
                    .map(|(of, c)| (self.exposed_at(inference, premise, of, c, body), c));
                premises.push(self.negations(sink, premise, negated, top));
            }
            let written = principal.map_or(Written::new(Side::Output, false), |p| {
                self.writing[derivation.occurrence(p).index()]
            });
            let shown = Shown {
                base: InfId::new(index as u32),
                pending: Vec::new(),
                hidden: Vec::new(),
                rule: ClassicalRule::applied(rule, written),
                premises,
                times: inference.times(),
            };
            ids.push(self.by_side(sink, shown, rule, inference.premises()));
        }
        let root = derivation.root();
        if !derivation.is_of_goal() {
            // The formulas of the sequent written with a negation, as they
            // were written below the last rule.
            let sequent = derivation.inference(root).sequent();
            // A root's member is numbered as its occurrence.
            let roots = sequent
                .iter()
                .map(|&m| derivation.occurrence(m))
                .filter(|&o| {
                    forest.parent(o).is_none() && written::negated(forest, self.writing, o)
                })
                .map(|o| (sequent.partition_point(|&m| m < Member::from(o)), o));
            self.negations(sink, root, roots, ids[root.index()]);
        }
    }

    /// Hands `sink` the inference `shown` of the one-sided rule `rule`,
    /// whose own premises are `below`, and returns its id.
    ///
    /// The one-sided derivation may draw a run of weakenings or
    /// contractions of `?` formulas on both sides of `⊢` as one inference.
    /// Such a run is handed as two, so that each inference is one
    /// two-sided rule: the input side's (`!w`, `!c`) below the output
    /// side's (`?w`, `?c`).
    fn by_side(
        &self,
        sink: &mut impl Sink,
        mut shown: Shown,
        rule: Rule,
        below: &[InfId],
    ) -> InfId {
        let derivation = self.derivation;
        let (Rule::Weakening | Rule::Contraction, &[premise]) = (rule, below) else {
            return sink.take(shown);
        };
        let conclusion = derivation.inference(shown.base).sequent();
        let above = derivation.inference(premise).sequent();
        // What the run takes away or adds, by position in the larger
        // sequent: the weakened formulas, or the copies contracted.
        let (larger, extra) = if rule == Rule::Weakening {
            (shown.base, difference(conclusion, above))
        } else {
            (premise, difference(above, conclusion))
        };
        let larger_sequent = derivation.inference(larger).sequent();
        let side =
            |&p: &usize| self.writing[derivation.occurrence(larger_sequent[p]).index()].side();
        let (input, output): (Vec<usize>, Vec<usize>) =
            extra.iter().partition(|p| side(p) == Side::Input);
        if input.is_empty() || output.is_empty() {
            return sink.take(shown);
        }
        let named = |side| ClassicalRule::applied(rule, Written::new(side, false));
        let count = |positions: &[usize]| u32::try_from(positions.len()).unwrap_or(u32::MAX);
        // The output side's half above, the input side's below; the upper
        // half shows the larger sequent less what the lower half adds.
        let upper = sink.take(Shown {
            base: larger,
            pending: Vec::new(),
            hidden: if rule == Rule::Weakening {
                input.clone()
            } else {
                output.clone()
            },
            rule: named(Side::Output),
            premises: shown.premises.clone(),
            times: count(&output),
        });
        shown.rule = named(Side::Input);
        shown.premises = vec![upper];
        shown.times = count(&input);
        sink.take(shown)
    }

    /// Hands `sink` one negation step below the inference `top` for each
    /// of `negated` in turn, and returns the id of the last (`top` for
    /// none).
    ///
    /// `top` shows the one-sided inference `base`, and each of `negated`
    /// is a position in its sequent with the occurrence there. Each step's
    /// conclusion shows one more formula as written, negation and all.
    fn negations(
        &self,
        sink: &mut impl Sink,
        base: InfId,
        negated: impl Iterator<Item = (usize, OccId)>,
        mut top: InfId,
    ) -> InfId {
        let forest = self.derivation.forest();
        let mut pending = Vec::new();
        for (position, c) in negated {
            debug_assert_eq!(
                self.derivation
                    .occurrence(self.derivation.inference(base).sequent()[position]),
                c
            );
            pending.push(position);
            let side = written::context(forest, self.writing, c);
            top = sink.take(Shown {
                base,
                pending: pending.clone(),
                hidden: Vec::new(),
                rule: ClassicalRule::negation(side),
                premises: vec![top],
                times: 1,
            });
        }
        top
    }

    /// Returns the position, in the sequent of the one-sided inference
    /// `premise`, of the member of `c` that the rule of `below` exposes
    /// there.
    ///
    /// That member is a subformula of the member `of` (the principal or
    /// the cut formula) under the same frame or, with `body`, a binder's
    /// body under a frame that pushes one term onto `of`'s. Where the
    /// sequent holds the formula twice, either copy may be returned.
    fn exposed_at(
        &self,
        below: &Inference,
        premise: InfId,
        of: Member,
        c: OccId,
        body: bool,
    ) -> usize {
        let sequent = self.derivation.inference(premise).sequent();
        let Some(framing) = self.derivation.framing() else {
            // Every member is the occurrence it stands for.
            let position = sequent.partition_point(|&m| m < Member::from(c));
            debug_assert_eq!(sequent[position].occ(), c);
            return position;
        };
        let table = framing.table;
        let frame = |m: Member| table.instance(m).map(|(_, f)| f);
        let wanted = frame(of);
        let fits = |m: Member| {
            framing.occurrence(m) == c
                && if body {
                    frame(m).is_some_and(|f| table.frame_parts(f).0 == wanted)
                } else {
                    frame(m) == wanted
                }
        };
        let count = |s: &[Member], m: Member| {
            s.partition_point(|&x| x <= m) - s.partition_point(|&x| x < m)
        };
        // Of a binder's bodies under several terms, the one the rule adds:
        // the premise holds more of it than the conclusion.
        let mut first = None;
        for (position, &m) in sequent.iter().enumerate().filter(|&(_, &m)| fits(m)) {
            if count(sequent, m) > count(below.sequent(), m) {
                return position;
            }
            first.get_or_insert(position);
        }
        first.expect("a premise holds what its rule exposes")
    }

    /// Returns the one-sided derivation the view shows.
    pub fn derivation(&self) -> &'a Derivation<'a> {
        self.derivation
    }

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

    /// Returns whether the view has no inference. A view built from a
    /// derivation always has one.
    pub fn is_empty(&self) -> bool {
        self.inferences.is_empty()
    }

    /// Returns the root: the inference that concludes the sequent.
    pub fn root(&self) -> InfId {
        // At least one inference, and no more than `new` counted against
        // `Derivation::MOST`.
        InfId::new(self.inferences.len() as u32 - 1)
    }

    /// Returns the rule of the inference at `id`.
    ///
    /// # Panics
    ///
    /// For an id past the view's end.
    pub fn rule(&self, id: InfId) -> ClassicalRule {
        self.inferences[id.index()].rule
    }

    /// Returns the premises of the inference at `id`, in the rule's order.
    ///
    /// # Panics
    ///
    /// For an id past the view's end.
    pub fn premises(&self, id: InfId) -> &[InfId] {
        &self.inferences[id.index()].premises
    }

    /// Returns the inference of the one-sided derivation whose sequent the
    /// inference at `id` shows: its own, or for a negation step its
    /// premise's.
    ///
    /// # Panics
    ///
    /// For an id past the view's end.
    pub fn shows(&self, id: InfId) -> InfId {
        self.inferences[id.index()].base
    }

    /// Returns the formulas of the sequent of the inference at `id` as it
    /// shows them, in the order of the one-sided sequent: each member, the
    /// side of `⊢` it stands on, and whether it is shown with the negation
    /// it was written with.
    ///
    /// # Panics
    ///
    /// For an id past the view's end.
    pub fn sides(&self, id: InfId) -> impl Iterator<Item = (Member, Side, bool)> + '_ {
        let shown = &self.inferences[id.index()];
        let derivation = self.derivation;
        let forest = derivation.forest();
        let sequent = derivation.inference(shown.base).sequent();
        let shown_at = move |&(position, _): &(usize, &Member)| !shown.hidden.contains(&position);
        sequent
            .iter()
            .enumerate()
            .filter(shown_at)
            .map(move |(position, &m)| {
                let o = derivation.occurrence(m);
                if shown.pending.contains(&position) {
                    (m, written::context(forest, self.writing, o), true)
                } else {
                    (m, self.writing[o.index()].side(), false)
                }
            })
    }

    /// Returns the sequent of the inference at `id`, `Γ ⊢ Δ`, as the text
    /// tree writes it.
    ///
    /// # Panics
    ///
    /// For an id past the view's end.
    pub fn sequent(&self, id: InfId) -> impl Display + '_ {
        Sequent { view: self, id }
    }

    /// Writes the sequent of the inference at `id` in a notation.
    fn write(
        &self,
        out: &mut impl Write,
        notation: &crate::linear::sequents::notation::Notation,
        id: InfId,
        aligned: bool,
        marks: bool,
    ) -> FmtResult {
        let shown = |side: Side| {
            self.sides(id)
                .filter(move |&(_, s, _)| s == side)
                .map(|(m, _, negated)| (m, negated))
        };
        notation.classical(
            out,
            self.derivation.forest(),
            self.writing,
            self.derivation.framing(),
            shown(Side::Input),
            shown(Side::Output),
            aligned,
            marks,
        )
    }

    /// Returns the width and the height of the text tree the options
    /// draw, as [`Derivation::text_size`] does.
    pub fn text_size(&self, options: &TextOptions) -> (usize, usize) {
        crate::linear::proofs::fmt::text_size(self, options)
    }

    /// Writes the text tree into `out` under `options`, as
    /// [`Derivation::write_text`] does, asking `stop` after each row.
    ///
    /// # 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),
        )
    }
}

impl Drawn for TwoSided<'_> {
    fn rules(&self) -> usize {
        ClassicalRule::ALL.len()
    }

    fn open(&self) -> Option<usize> {
        Some(ClassicalRule::Open as usize)
    }

    fn markup<'a>(&'a self, rule: usize, labels: &'a Labels) -> Option<&'a str> {
        let rule = ClassicalRule::ALL[rule];
        // A table names the rules of the one-sided calculus and of
        // intuitionistic linear logic, so these keep their upright labels.
        let label = match labels {
            Labels::Upright | Labels::Table(_) => rule.markup(false),
            Labels::Subscript => rule.markup(true),
            Labels::Off => return None,
        };
        (!label.is_empty()).then_some(label)
    }

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

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

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

    fn rule(&self, id: InfId) -> usize {
        self.inferences[id.index()].rule as usize
    }

    fn name(&self, id: InfId) -> &'static str {
        self.inferences[id.index()].rule.name()
    }

    fn times(&self, id: InfId) -> u32 {
        self.inferences[id.index()].times
    }

    fn write_sequent(&self, out: &mut impl Write, id: InfId) -> FmtResult {
        self.write(
            out,
            &crate::linear::sequents::notation::TEXT,
            id,
            false,
            false,
        )
    }

    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    fn sequent(
        &self,
        out: &mut String,
        notation: &crate::linear::sequents::notation::Notation,
        id: InfId,
        aligned: bool,
        marks: bool,
    ) {
        // Writing into a `String` does not fail.
        self.write(out, notation, id, aligned, marks).unwrap();
    }

    #[cfg(feature = "svg")]
    fn positions(&self, id: InfId) -> Vec<usize> {
        let sides: Vec<Side> = self.sides(id).map(|(_, side, _)| side).collect();
        let (left, right): (Vec<usize>, Vec<usize>) =
            (0..sides.len()).partition(|&p| sides[p] == Side::Input);
        left.into_iter().chain(right).collect()
    }
}

/// The sequent of an inference of a view, as a value that writes it.
struct Sequent<'v, 'a> {
    /// The view.
    view: &'v TwoSided<'a>,
    /// The inference.
    id: InfId,
}

impl Display for Sequent<'_, '_> {
    /// Writes the sequent in Unicode.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let notation = &crate::linear::sequents::notation::TEXT;
        self.view.write(f, notation, self.id, false, false)
    }
}

impl Display for TwoSided<'_> {
    /// Draws the view 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)
    }
}

/// Returns the positions in `larger` of the members `smaller` lacks, both
/// in ascending order and `smaller` a sub-multiset of `larger`.
fn difference(larger: &[Member], smaller: &[Member]) -> Vec<usize> {
    let mut extra = Vec::new();
    let mut k = 0;
    for (position, m) in larger.iter().enumerate() {
        if smaller.get(k) == Some(m) {
            k += 1;
        } else {
            extra.push(position);
        }
    }
    extra
}

/// Returns the subformulas of `p` that the one-sided rule `rule` on it
/// puts into its premise `j`: the left and the right one of a `⅋`, one
/// factor of a `⊗` or `&` each, the operand of a `⊕` rule, `!` and `?d`,
/// the body of `∀` and `∃`, and none for every other rule.
fn exposed(forest: &Forest, rule: Rule, p: OccId, j: usize) -> [Option<OccId>; 2] {
    match (rule, j) {
        (Rule::Par, _) => [forest.left(p), forest.right(p)],
        (Rule::Tensor | Rule::With, 1) | (Rule::PlusRight, _) => [forest.right(p), None],
        (
            Rule::Tensor
            | Rule::With
            | Rule::PlusLeft
            | Rule::Promotion
            | Rule::Dereliction
            | Rule::Forall
            | Rule::Exists,
            _,
        ) => [forest.left(p), None],
        (
            Rule::Ax
            | Rule::One
            | Rule::Bot
            | Rule::Top
            | Rule::Contraction
            | Rule::Weakening
            | Rule::Mix
            | Rule::AffineWeakening
            | Rule::Cut
            | Rule::Open,
            _,
        ) => [None, None],
    }
}

/// What the walk over a view's inferences hands them to.
trait Sink {
    /// Takes the next inference and returns its id.
    fn take(&mut self, shown: Shown) -> InfId;
}

impl Sink for Vec<Shown> {
    fn take(&mut self, shown: Shown) -> InfId {
        self.push(shown);
        // As many as the counting pass allowed, fewer than `u32::MAX`.
        InfId::new(self.len() as u32 - 1)
    }
}

/// The counting pass: the inferences and the bytes of the view by the
/// derivation size's estimate ([`Size::bytes`]), every sum saturating.
struct Counted<'d> {
    /// The derivation the view shows.
    derivation: &'d Derivation<'d>,
    /// The characters of every member's formula and its separator, an
    /// instance's at most.
    weights: Weights,
    /// The characters of each one-sided inference's sequent, by its id,
    /// kept once computed: a chain of negation steps shows one sequent
    /// many times.
    characters: Vec<Option<u64>>,
    /// The inferences so far.
    inferences: u64,
    /// The estimate so far.
    bytes: u64,
}

impl<'d> Counted<'d> {
    /// Returns a count of nothing yet, of a view of `derivation`.
    fn new(derivation: &'d Derivation<'d>) -> Self {
        Self {
            derivation,
            weights: Weights::of_members(
                derivation.forest(),
                derivation.framing().map(|framing| framing.table),
            ),
            characters: vec![None; derivation.inferences().len()],
            inferences: 0,
            bytes: 0,
        }
    }
}

impl Sink for Counted<'_> {
    fn take(&mut self, shown: Shown) -> InfId {
        let characters = *self.characters[shown.base.index()].get_or_insert_with(|| {
            let sequent = self.derivation.inference(shown.base).sequent();
            sequent.iter().fold(0u64, |sum, m| {
                sum.saturating_add(self.weights.get(*m).into())
            })
        });
        self.inferences = self.inferences.saturating_add(1);
        self.bytes = self.bytes.saturating_add(
            characters
                .saturating_mul(Size::BYTES_PER_CHARACTER)
                .saturating_add(Size::BYTES_PER_INFERENCE),
        );
        // The id is a placeholder the count never reads back.
        InfId::new(u32::try_from(self.inferences).unwrap_or(u32::MAX))
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::linear::occurrences::ClassicalSequent;
    use crate::linear::proofs::{Compact, ViewOptions};
    use crate::linear::search::generate::{self, Rng, Rules};
    use crate::linear::{Mode, Options, Proof};

    /// Returns a proof of a written sequent in `mode`.
    fn proved(written: &ClassicalSequent, mode: Mode) -> Proof {
        let outcome = crate::linear::prove(written.sequent(), mode, &Options::default()).unwrap();
        outcome.verdict.proof().expect("provable").clone()
    }

    /// Returns a proof with a cut of a written sequent in `mode` and the
    /// record of its session, or `None` where the search leaves a goal
    /// open.
    ///
    /// The session cuts on one of the sequent's formulas, typed as it was
    /// written. The first premise takes the other formulas or, where the
    /// cut formula stands left of `⊢`, that formula alone. The search
    /// closes both goals.
    #[cfg(feature = "interactive")]
    fn cut_written(
        written: &ClassicalSequent,
        mode: Mode,
        rng: &mut Rng,
    ) -> Option<(Proof, Vec<Written>)> {
        use crate::linear::{CutFormula, InputOptions, Interactive};
        let limits = Limits::default();
        let mut session = Interactive::of_classical(written, mode, &limits).unwrap();
        let root = session.goals().next().unwrap();
        let roots = written.forest().roots();
        let p = rng.below(roots.len());
        let text = written.formula(roots[p]).to_string();
        let antecedents = written.sequent().antecedents().unwrap_or(0) as usize;
        let left: Vec<usize> = if p < antecedents {
            vec![p]
        } else {
            (0..roots.len()).filter(|&q| q != p).collect()
        };
        let formula =
            CutFormula::parse_within(&text, mode, &InputOptions::default(), &limits).unwrap();
        session.cut(root, &formula, &left, &limits).unwrap();
        let options = Options::default();
        let view = ViewOptions::default();
        for (_, closed) in session.close_all(&options, &view, &limits, |_| false) {
            closed.ok()?.grafted.ok()?;
        }
        let proof = session.proof(&limits, |_| false).ok()?;
        Some((proof, session.writing().unwrap().to_vec()))
    }

    /// Returns no proof with a cut: the sessions that make one need the
    /// feature `interactive`.
    #[cfg(not(feature = "interactive"))]
    fn cut_written(_: &ClassicalSequent, _: Mode, _: &mut Rng) -> Option<(Proof, Vec<Written>)> {
        None
    }

    /// Returns the two-sided tree of a sequent's proof in classical mode,
    /// every run of a structural rule drawn as one inference.
    fn drawn(text: &str) -> String {
        let written: ClassicalSequent = text.parse().unwrap();
        let proof = proved(&written, Mode::CLASSICAL);
        let options = ViewOptions::default().with_compact(Compact::Always);
        let limits = Limits::default();
        let derivation = proof
            .derivation_within(&options, &limits, |_| false)
            .unwrap();
        TwoSided::new(&derivation, written.writing(), &limits)
            .unwrap()
            .to_string()
    }

    /// Rules are named by the side and the writing of their principal
    /// formula, and a written negation is a step of its own, right above
    /// the rule that exposes the formula or below the last rule for one
    /// of the sequent.
    #[test]
    fn rules_by_side_and_negation_steps() {
        let cases = [
            (
                "A -o B, A |- B",
                "───── ax   ───── ax\n\
                 A ⊢ A      B ⊢ B\n\
                 ──────────────── ⊸L\n  \
                 A ⊸ B, A ⊢ B",
            ),
            (
                "|- ~(A * B), A * B",
                "───── ax   ───── ax\n\
                 A ⊢ A      B ⊢ B\n\
                 ──────────────── ⊗R\n  \
                 A, B ⊢ A ⊗ B\n  \
                 ───────────── ⊗L\n  \
                 A ⊗ B ⊢ A ⊗ B\n\
                 ───────────────── ~R\n\
                 ⊢ ~(A ⊗ B), A ⊗ B",
            ),
            (
                "A par B |- ~(~A * ~B)",
                "───── ax   ───── ax\n\
                 A ⊢ A      B ⊢ B\n\
                 ──────────────── ⅋L\n  \
                 A ⅋ B ⊢ A, B\n  \
                 ───────────── ~L\n  \
                 A ⅋ B, ~A ⊢ B\n \
                 ─────────────── ~L\n \
                 A ⅋ B, ~A, ~B ⊢\n \
                 ──────────────── ⊗L\n \
                 A ⅋ B, ~A ⊗ ~B ⊢\n\
                 ────────────────── ~R\n\
                 A ⅋ B ⊢ ~(~A ⊗ ~B)",
            ),
            (
                // A run of weakenings on both sides, drawn compact, is
                // split by side.
                "!b, a |- a, ?c",
                "    ───── ax\n    \
                 a ⊢ a\n  \
                 ───────── ?w\n  \
                 a ⊢ a, ?c\n\
                 ───────────── !w\n\
                 !b, a ⊢ a, ?c",
            ),
            (
                "!A |- ?(A + B) * 1",
                "   ───── ax\n   \
                 A ⊢ A\n \
                 ───────── ⊕R₁\n \
                 A ⊢ A ⊕ B\n\
                 ──────────── ?R\n\
                 A ⊢ ?(A ⊕ B)\n\
                 ───────────── !L   ─── 1R\n\
                 !A ⊢ ?(A ⊕ B)      ⊢ 1\n\
                 ────────────────────── ⊗R\n  \
                 !A ⊢ ?(A ⊕ B) ⊗ 1",
            ),
            (
                // The quantifier rules, every instance written with the
                // eigenvariable or the witness of its frame.
                "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)",
                "          ───────────────── ax\n          \
                 r(b, a) ⊢ r(b, a)\n        \
                 ───────────────────── ∃R\n        \
                 r(b, a) ⊢ ∃y. r(b, y)\n      \
                 ───────────────────────── ∀L\n      \
                 ∀x. r(x, a) ⊢ ∃y. r(b, y)\n   \
                 ─────────────────────────────── ∀R\n   \
                 ∀x. r(x, a) ⊢ ∀x. (∃y. r(x, y))\n\
                 ───────────────────────────────────── ∃L\n\
                 ∃y. (∀x. r(x, y)) ⊢ ∀x. (∃y. r(x, y))",
            ),
        ];
        for (text, tree) in cases {
            assert_eq!(drawn(text), tree, "{text}");
        }
    }

    /// A view estimated past the bound on derivations is refused, with
    /// nothing built; the derivation it would show is within it.
    #[test]
    fn a_view_past_the_bound_is_refused() {
        let written: ClassicalSequent = "A par B |- ~(~A * ~B)".parse().unwrap();
        let proof = proved(&written, Mode::CLASSICAL);
        let derivation = proof.derivation().unwrap();
        let shown = derivation.inferences().len() as u64 * Size::BYTES_PER_INFERENCE;
        let limits = Limits::default().with_derivation_bytes(Some(shown));
        let refused = TwoSided::new(&derivation, written.writing(), &limits).unwrap_err();
        assert!(matches!(
            refused,
            Error::Refused(Refusal::Output { estimate_bytes, limit_bytes, .. })
                if estimate_bytes > limit_bytes && limit_bytes == shown
        ));
    }

    /// Returns the formulas of an inference of a view as it shows them,
    /// those left of `⊢` first, each in the order of the one-sided
    /// sequent.
    fn shown(view: &TwoSided<'_>, id: InfId) -> Vec<(Member, Side, bool)> {
        let all: Vec<_> = view.sides(id).collect();
        let on = |side| all.iter().copied().filter(move |&(_, s, _)| s == side);
        on(Side::Input).chain(on(Side::Output)).collect()
    }

    /// What [`reads_as_its_term`] saw over the views it checked.
    #[derive(Default)]
    struct Tally {
        /// The inferences.
        inferences: usize,
        /// The negation steps.
        negations: usize,
        /// The inferences that leave formulas out: halves of a run split
        /// by side.
        split: usize,
        /// The cuts.
        cuts: usize,
        /// Every rule seen.
        rules: std::collections::BTreeSet<ClassicalRule>,
    }

    /// Checks the two-sided views of `proof`, drawn with and without
    /// compaction, of a sequent written as `writing` records:
    /// - every inference prints as a sequent that parses back to the same
    ///   formulas on the same sides, each written as its occurrence was,
    ///   an instance with its frame's terms, and a negation where the view
    ///   shows one;
    /// - read one-sided, each inference is the one it shows: a rule of the
    ///   term, its principal formula as written on the side its name says,
    ///   or a negation step that moves one formula across, with its
    ///   negation in the conclusion and without it in the premise;
    /// - the root is the sequent as written.
    fn reads_as_its_term(proof: &Proof, writing: &[Written], text: &str, tally: &mut Tally) {
        let limits = Limits::default();
        let written: ClassicalSequent = text.parse().unwrap();
        for compact in [Compact::Never, Compact::Always] {
            let options = ViewOptions::default().with_compact(compact);
            let derivation = proof
                .derivation_within(&options, &limits, |_| false)
                .unwrap();
            let view = TwoSided::new(&derivation, writing, &limits).unwrap();
            let forest = derivation.forest();
            let occurrence = |m: Member| derivation.occurrence(m);
            let root = view.root();
            assert_eq!(
                view.sequent(root).to_string(),
                written.to_string(),
                "{text}"
            );
            for k in 0..view.len() {
                let id = InfId::new(k as u32);
                let printed = view.sequent(id).to_string();
                let parsed: ClassicalSequent = printed.parse().unwrap();
                let members = shown(&view, id);
                let left = members.iter().filter(|m| m.1 == Side::Input).count();
                let (pf, pw) = (parsed.forest(), parsed.writing());
                assert_eq!(
                    parsed.sequent().antecedents(),
                    Some(left as u32),
                    "{printed}"
                );
                assert_eq!(pf.roots().len(), members.len(), "{printed}");
                for (&r, &(m, _, negated)) in pf.roots().iter().zip(&members) {
                    let o = occurrence(m);
                    assert_eq!(pf.size(r), forest.size(o), "{printed}");
                    assert_eq!(
                        pf.formula(r).to_string(),
                        derivation.formula(m).to_string(),
                        "{printed}"
                    );
                    for d in 0..forest.size(o) {
                        let (p, q) = (OccId::new(r.get() + d), OccId::new(o.get() + d));
                        assert_eq!(pf.kind(p), forest.kind(q), "{printed}");
                        assert_eq!(pw[p.index()], writing[q.index()], "{printed}");
                        if m.occurrence(forest).is_some() {
                            let name = |f: &Forest, x| {
                                f.atom(x).map(|a| f.sequent().atom_name(a).to_owned())
                            };
                            assert_eq!(name(pf, p), name(forest, q), "{printed}");
                        }
                    }
                    assert_eq!(parsed.is_negated(r), negated, "{printed}");
                }
                let base = derivation.inference(view.shows(id));
                let rule = view.rule(id);
                match rule.rule() {
                    None => {
                        let &[premise] = view.premises(id) else {
                            panic!("a negation step has one premise");
                        };
                        assert_eq!(view.shows(premise), view.shows(id));
                        let above: Vec<_> = view.sides(premise).collect();
                        let below: Vec<_> = view.sides(id).collect();
                        let moved: Vec<_> =
                            (0..below.len()).filter(|&p| above[p] != below[p]).collect();
                        let &[p] = &moved[..] else {
                            panic!("a negation step moves one formula: {printed}");
                        };
                        let (m, side, negated) = below[p];
                        assert!(negated && !above[p].2, "{printed}");
                        assert_eq!(above[p].1, writing[occurrence(m).index()].side());
                        assert_eq!(Some(side), rule.side(), "{printed}");
                        assert_ne!(side, above[p].1, "{printed}");
                        tally.negations += 1;
                    }
                    Some(one_sided) if one_sided.is_structural() => {
                        // A run: what it adds or takes away stands on its
                        // name's side, as many as it counts.
                        assert_eq!(one_sided, base.rule().rule, "{printed}");
                        let &[premise] = view.premises(id) else {
                            panic!("a structural rule has one premise");
                        };
                        let key = |s: &(Member, Side, bool)| (s.0, s.1 == Side::Input, s.2);
                        let mut below: Vec<_> = view.sides(id).map(|s| key(&s)).collect();
                        let mut above: Vec<_> = view.sides(premise).map(|s| key(&s)).collect();
                        below.sort_unstable();
                        above.sort_unstable();
                        let (larger, smaller) = if one_sided == Rule::Contraction {
                            (&above, &below)
                        } else {
                            (&below, &above)
                        };
                        let mut moved = larger.clone();
                        for s in smaller {
                            let at = moved.iter().position(|m| m == s).expect("a sub-multiset");
                            moved.remove(at);
                        }
                        assert_eq!(moved.len() as u32, view.inferences[k].times, "{printed}");
                        if let Some(named) = rule.side() {
                            let input = named == Side::Input;
                            assert!(moved.iter().all(|m| m.1 == input), "{printed} by {rule}");
                        }
                    }
                    Some(one_sided) => {
                        assert_eq!(one_sided, base.rule().rule, "{printed}");
                        assert_eq!(view.premises(id).len(), base.premises().len());
                        if let Some(position) = base.principal() {
                            let (m, side, negated) = view.sides(id).nth(position).unwrap();
                            assert!(!negated, "a rule acts on a formula as written");
                            if let Some(named) = rule.side() {
                                assert_eq!(side, named, "{printed} by {rule}");
                            }
                            let implication = writing[occurrence(m).index()].is_implication();
                            let lollipop = matches!(
                                rule,
                                ClassicalRule::LollipopLeft | ClassicalRule::LollipopRight
                            );
                            assert_eq!(implication, lollipop, "{printed} by {rule}");
                        }
                    }
                }
                tally.split += usize::from(!view.inferences[k].hidden.is_empty());
                tally.cuts += usize::from(rule == ClassicalRule::Cut);
                tally.rules.insert(rule);
                tally.inferences += 1;
            }
        }
    }

    /// Over the proofs of generated sequents written at random, every
    /// inference of the two-sided view reads as its term
    /// ([`reads_as_its_term`]). So does every inference of a proof with a
    /// cut on a formula typed as written, whose two occurrences the
    /// session records on their sides.
    #[test]
    fn every_inference_parses_back_and_reads_as_its_term() {
        let mut tally = Tally::default();
        let mut cut_rng = Rng::new(41);
        for (i, rules) in Rules::ALL.into_iter().enumerate() {
            let mode = if rules.mix {
                Mode::CLASSICAL.with_mix()
            } else {
                Mode::CLASSICAL
            };
            let mut rng = Rng::new(400 + i as u64);
            for _ in 0..10 {
                let budget = 2 + rng.below(10);
                let provable = generate::provable(&mut rng, rules, 3, budget);
                let (text, _) = generate::written(&mut rng, &provable.formulas);
                let written: ClassicalSequent = text.parse().unwrap();
                let plain = (proved(&written, mode), written.writing().to_vec());
                let cut = cut_written(&written, mode, &mut cut_rng);
                for (proof, writing) in [Some(plain), cut].into_iter().flatten() {
                    reads_as_its_term(&proof, &writing, &text, &mut tally);
                }
            }
        }
        let Tally {
            inferences,
            negations,
            split,
            ..
        } = tally;
        assert!(
            inferences > 1000 && negations > 100 && split > 0,
            "{inferences} {negations} {split}"
        );
        #[cfg(feature = "interactive")]
        assert!(tally.cuts > 50, "{} cuts", tally.cuts);
    }

    /// A first-order proof's view reads as its term too. Its quantifier
    /// rules are named by side, its instances are written with the
    /// eigenvariables and witnesses of their frames, and a negation written
    /// over a binder or its body is a step of its own.
    #[test]
    fn a_first_order_view_reads_as_its_term() {
        let mut tally = Tally::default();
        for text in [
            "forall x. p(x) |- p(a)",
            "exists y. forall x. r(x, y) |- forall x. exists y. r(x, y)",
            "p(a) & p(b), q(b) |- exists x. (p(x) * q(x))",
            "|- ~(forall x. p(x)), p(a)",
            "exists x. ~p(x) |- ~(forall x. p(x))",
            "|- forall x. ~(p(x) * q(x)), exists x. (p(x) * q(x))",
            "!forall x. p(x), !q(c) |- p(a) * p(b), ?q(c)",
            "!forall x. ~p(x), p(a) par p(b) |-",
        ] {
            let written: ClassicalSequent = text.parse().unwrap();
            let proof = proved(&written, Mode::CLASSICAL);
            assert!(proof.instances().is_some(), "{text}");
            reads_as_its_term(&proof, written.writing(), text, &mut tally);
        }
        let quantifiers = [
            ClassicalRule::ForallLeft,
            ClassicalRule::ForallRight,
            ClassicalRule::ExistsLeft,
            ClassicalRule::ExistsRight,
        ];
        assert!(
            quantifiers.iter().all(|r| tally.rules.contains(r)),
            "{:?}",
            tally.rules
        );
        assert!(tally.negations >= 3, "{} negations", tally.negations);
    }

    /// The rules are in [`ClassicalRule::ALL`] in their order of
    /// declaration, by which the label tables are indexed; the quantifier
    /// rules are named and labelled by the side of their principal
    /// formula.
    #[test]
    fn rules_are_labelled_in_declaration_order() {
        use ClassicalRule::*;
        for (i, rule) in ClassicalRule::ALL.into_iter().enumerate() {
            assert_eq!(rule as usize, i, "{rule}");
        }
        for (rule, name, upright, subscript, side, one_sided) in [
            (ForallLeft, "∀L", "∀L", "∀_L", Side::Input, Rule::Exists),
            (ForallRight, "∀R", "∀R", "∀_R", Side::Output, Rule::Forall),
            (ExistsLeft, "∃L", "∃L", "∃_L", Side::Input, Rule::Forall),
            (ExistsRight, "∃R", "∃R", "∃_R", Side::Output, Rule::Exists),
        ] {
            assert_eq!(rule.name(), name);
            assert_eq!(rule.markup(false), upright);
            assert_eq!(rule.markup(true), subscript);
            assert_eq!(rule.side(), Some(side));
            assert_eq!(rule.rule(), Some(one_sided));
            assert_eq!(
                ClassicalRule::applied(one_sided, Written::new(side, false)),
                rule
            );
        }
    }
}