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
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
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Proof nets for unit-free MLL, with or without Mix: build a proof
//! structure, test whether it is a proof net, turn it into a proof, read
//! it off a proof, and eliminate its cuts.
//!
//! A [`ProofStructure`] is a sequent's formula trees plus axiom links. The
//! formula trees are the sequent's occurrence [`Forest`], whose
//! occurrences are the vertices. A `⊗` vertex (a *tensor link*) or a `⅋`
//! vertex (a *par link*) has an edge to each of its two premises, its
//! immediate subformulas. An *axiom link* joins two dual literals, `a`
//! and `~a` of one atom; it is the net's form of the axiom rule
//! `⊢ a, ~a`. The structure is *complete* when every literal is linked.
//!
//! A *switching* keeps one of the two premise edges of every par link and
//! drops the other. A complete structure is a *proof net* when it passes
//! the Danos–Regnier criterion: no switching leaves a cycle, and, unless
//! Mix is allowed, every switching leaves the graph connected.
//! [`is_correct`](ProofStructure::is_correct) decides it, independently
//! of any search and of the proof checker, and names a witness when it
//! fails ([`NetError`]).
//!
//! What a caller does with one:
//!
//! - build it over the sequent's forest with
//!   [`from_links`](ProofStructure::from_links), or with
//!   [`new`](ProofStructure::new) and then [`link`](ProofStructure::link)
//!   for each link; the [`Criterion`] says whether Mix is allowed and
//!   which order of formulas the calculus keeps;
//! - test it with [`is_correct`](ProofStructure::is_correct);
//! - turn a proof net into a proof that the checker accepts with
//!   [`sequentialize`](ProofStructure::sequentialize);
//! - read the net off a proof of MLL with
//!   [`from_proof`](ProofStructure::from_proof): two derivations that
//!   differ only in the order of their rules give the same net;
//! - eliminate the cut links of a net step by step with [`cut`].
//!
//! The net engine ([`Engine::Net`](crate::linear::Engine::Net)) returns
//! the net it found in the `net` field of its
//! [`Outcome`](crate::linear::Outcome).
//!
//! The structure of an intuitionistic sequent is also an essential net or
//! not. [`is_essential`](ProofStructure::is_essential) decides that by a
//! directed criterion with the same verdict. In the cyclic order a proof
//! net is also planar ([`is_planar`](ProofStructure::is_planar)).
//! Proof nets of MELL, with `!`-boxes, are [`MellStructure`]s.

// A new variant of the calculus's enums must be decided at every match,
// never fall into an existing arm.
#![deny(clippy::wildcard_enum_match_arm)]

pub mod cut;
/// Essential nets: the directed criterion of intuitionistic structures.
pub(crate) mod essential;
/// The coloured structure graph and the criterion's tests on it.
mod graph;
/// Proof nets of unit-free MELL with `!`-boxes.
mod mell;
/// From a proof net to a proof term.
mod sequentialize;
/// The `â…‹`-free skeleton as a union-find with undo.
mod skeleton;

pub use graph::Scratch;
pub use mell::{MellStructure, Parts, Placed, Placement};

use crate::Error;
use crate::errors::describe::{Budget, Limit, Names, cut as clipped};
use crate::errors::{Described, Owner, Subject};
use crate::limits::{Limits, Phase, Progress, Refusal, Space};
use crate::linear::fragment::{Fragment, Mode, Order};
use crate::linear::occurrences::{Forest, OccId, OccSet, ShapeError};
use crate::linear::proofs::{Node, NodeId, Proof};
use crate::linear::sequents::{Kind, Sequent, Term};
use graph::Graph;
use skeleton::Skeleton;
use std::fmt::{Display, Formatter, Result as FmtResult, Write};

/// The raw index that stands for "no vertex".
const NONE: u32 = u32::MAX;

/// The most vertices a structure may have.
///
/// A vertex has at most three slots in the graph, one per edge: to its
/// parent, to its premises, or across its axiom link. The slots' offsets
/// are `u32`, and the last offset is the total number of slots, so three
/// slots per vertex must fit.
const MOST: u64 = (u32::MAX / 3 - 1) as u64;

/// Refuses a forest with more occurrences than a structure can hold as
/// vertices ([`MOST`]).
///
/// The engines that build a structure call it before they search, so no
/// structure is made past the bound.
///
/// # Errors
///
/// [`Refusal::Index`] past [`MOST`].
pub(crate) const fn fits(occurrences: usize) -> Result<(), Error> {
    if occurrences as u64 > MOST {
        Err(Error::Refused(Refusal::Index {
            what: Space::Vertex,
            count: occurrences as u64,
            most: MOST,
        }))
    } else {
        Ok(())
    }
}

/// Checks that proof nets exist for a sequent of `fragment` in `mode`:
/// unit-free MLL, in a mode that is not affine, with or without Mix.
///
/// A front end asks it before it offers a net. It fails with the error
/// that [`ProofStructure::new`] and [`Criterion::of`] give. The net engine
/// refuses the same sequents, with an error of its own.
///
/// # Errors
///
/// [`NetError::Fragment`] for a larger fragment, and [`NetError::Mode`] in
/// affine mode and in an ordered mode with Mix.
///
/// # Examples
///
/// ```
/// use deduxit::linear::{Fragment, Mode, nets};
///
/// assert!(nets::exist(Fragment::MLL, Mode::CLASSICAL.with_mix()).is_ok());
/// assert!(nets::exist(Fragment::MLL, Mode::CLASSICAL.with_affine()).is_err());
/// assert!(nets::exist(Fragment::MALL, Mode::CLASSICAL).is_err());
/// ```
pub fn exist(fragment: Fragment, mode: Mode) -> Result<(), NetError> {
    has_nets(fragment)?;
    Criterion::of(mode).map(|_| ())
}

/// Fails unless proof structures exist for a sequent of `fragment`.
fn has_nets(fragment: Fragment) -> Result<(), NetError> {
    if fragment.has_nets() {
        Ok(())
    } else {
        Err(NetError::Fragment { fragment })
    }
}

/// The bytes a structure holds per vertex, the copy of its forest
/// included: the forest's per-occurrence arrays (25), `partner` (4), the
/// graph's offset (4) and up to three slots (12), the skeleton's parent
/// and rank (5), and a link per two literals (4).
const STRUCTURE_BYTES: u64 = 25 + 4 + 4 + 12 + 5 + 4;

/// The bytes the criterion's working memory takes per vertex: a flag per
/// slot (3), the search's four arrays (16), its bridge flags (1) and its
/// stack (8), and the two sets of deleted vertices (1).
const SCRATCH_BYTES: u64 = 3 + 16 + 1 + 8 + 1;

/// The bytes a sequentialization holds per vertex beside its structure:
/// the proof's copy of the forest (25), at most one node (16), the
/// working memory of the criterion and the conclusions waiting to be
/// proved (8).
const SEQUENTIALIZE_BYTES: u64 = 25 + 16 + SCRATCH_BYTES + 8;

/// A vertex of a proof structure, by its number.
///
/// In a [`ProofStructure`] vertex `i` is occurrence `i` of its forest. A
/// [`MellStructure`] numbers its vertices itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VertexId(u32);

impl VertexId {
    /// Wraps a raw vertex index.
    pub const fn new(index: u32) -> Self {
        Self(index)
    }

    /// Returns the raw vertex index.
    pub const fn get(self) -> u32 {
        self.0
    }

    /// Returns the index as a `usize`, for indexing per-vertex arrays.
    pub const fn index(self) -> usize {
        self.0 as usize
    }

    /// Returns the vertex of an occurrence of an MLL structure.
    pub(crate) const fn of(o: OccId) -> Self {
        Self(o.get())
    }

    /// Returns the occurrence of a vertex of an MLL structure.
    pub(crate) const fn occ(self) -> OccId {
        OccId::new(self.0)
    }
}

/// The rules a proof structure is checked under: whether Mix is allowed,
/// and the order of formulas the calculus keeps.
///
/// With Mix a proof net need not be connected. In the cyclic order no two
/// links of a proof net cross ([`ProofStructure::is_planar`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Criterion {
    /// Whether the Mix rule is allowed.
    pub mix: bool,
    /// The order of the sequent's formulas the calculus keeps.
    pub order: Order,
}

impl Criterion {
    /// Multiplicative linear logic without Mix.
    pub const MLL: Self = Self {
        mix: false,
        order: Order::Commutative,
    };

    /// Cyclic multiplicative linear logic, without Mix: a proof net is
    /// planar.
    pub const CYCLIC: Self = Self {
        mix: false,
        order: Order::Cyclic,
    };

    /// Returns the criterion with Mix allowed.
    #[must_use]
    pub const fn with_mix(self) -> Self {
        Self { mix: true, ..self }
    }

    /// Returns the criterion of a mode, with Mix and the order as the mode
    /// has them.
    ///
    /// In intuitionistic mode the net is the one of the one-sided sequent.
    /// In the Lambek calculus it is a planar one. A proof net of the
    /// calculus without empty antecedents must meet one more condition,
    /// which the essential engine's search tests.
    ///
    /// # Errors
    ///
    /// [`NetError::Mode`] in affine mode, which has no proof nets, and in
    /// an ordered mode with Mix, which [`Mode::check`] refuses.
    pub fn of(mode: Mode) -> Result<Self, NetError> {
        if mode.is_affine() || (mode.is_ordered() && mode.check().is_err()) {
            return Err(NetError::Mode { mode });
        }
        Ok(Self {
            mix: mode.has_mix(),
            order: mode.order(),
        })
    }

    /// The mode a sequentialized proof holds in: classical, with Mix if
    /// the criterion allows it, or the cyclic mode.
    const fn mode(self) -> Mode {
        match (self.order, self.mix) {
            (Order::Cyclic, _) => Mode::CYCLIC,
            (Order::Commutative, true) => Mode::CLASSICAL.with_mix(),
            (Order::Commutative, false) => Mode::CLASSICAL,
        }
    }
}

/// Why a proof structure is not a proof net, why a list of links is not a
/// proof structure, or why there is no structure.
///
/// `Display` prints each vertex as its id;
/// [`describe`](Self::describe) prints it as its formula.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NetError {
    /// A link names a vertex outside the structure.
    #[non_exhaustive]
    NoVertex {
        /// The vertex named.
        vertex: u32,
        /// How many vertices the structure has.
        vertices: u32,
    },
    /// A link names a vertex that is not a literal.
    #[non_exhaustive]
    NotLiteral {
        /// The vertex.
        vertex: VertexId,
    },
    /// A link joins two literals that are not `a` and `~a` for one atom.
    #[non_exhaustive]
    NotDual {
        /// The first literal of the link.
        x: VertexId,
        /// The second literal of the link.
        y: VertexId,
    },
    /// A literal appears in two links.
    #[non_exhaustive]
    LinkedTwice {
        /// The literal.
        vertex: VertexId,
    },
    /// A literal has no link, so the structure is incomplete.
    #[non_exhaustive]
    Unlinked {
        /// The literal.
        vertex: VertexId,
    },
    /// The structure has no vertex at all: no rule concludes the empty
    /// sequent.
    Empty,
    /// A cycle survives some switching.
    #[non_exhaustive]
    SwitchingCycle {
        /// The vertices the cycle runs through, in order along it.
        cycle: Vec<VertexId>,
    },
    /// Every switching falls into several parts.
    #[non_exhaustive]
    Disconnected {
        /// The parts of the switching that keeps the left premise of
        /// every `â…‹`, each given by the vertices in it that have no parent
        /// edge there: the roots and the right premises of `â…‹` nodes.
        parts: Vec<Vec<VertexId>>,
    },
    /// A directed cycle of the essential net.
    #[non_exhaustive]
    DirectedCycle {
        /// The vertices the cycle runs through, each followed by the one
        /// its edge leads to, the last by the first.
        cycle: Vec<VertexId>,
    },
    /// An implication in output position does not dominate its
    /// antecedent in the essential net: a path from the antecedent
    /// reaches the goal around it.
    #[non_exhaustive]
    NoDominator {
        /// The implication, `A ⊸ B` stored as `A⊥ ⅋ B`.
        implication: VertexId,
        /// The path, from the antecedent `A⊥` to the goal.
        path: Vec<VertexId>,
    },
    /// Two links cross in the cyclic order of the literals, so the
    /// structure is no proof net of the cyclic order: going round, the
    /// four literals alternate between the two links.
    #[non_exhaustive]
    Crossing {
        /// The two links, each from its smaller vertex to its larger one,
        /// the first one's smaller vertex the smallest of the four.
        links: [(VertexId, VertexId); 2],
    },
    /// The structure's sequent has no intuitionistic reading, so it has
    /// no essential net.
    #[non_exhaustive]
    NotIntuitionistic {
        /// Why the sequent has no reading.
        shape: ShapeError,
    },
    /// Proof nets exist for unit-free MLL only, and the sequent lies in a
    /// larger fragment.
    #[non_exhaustive]
    Fragment {
        /// The sequent's fragment.
        fragment: Fragment,
    },
    /// Proof nets exist in linear mode only, and the mode is affine.
    #[non_exhaustive]
    Mode {
        /// The mode asked for.
        mode: Mode,
    },
    /// A node of the proof applies a rule that a proof net of unit-free
    /// MLL has no place for.
    #[non_exhaustive]
    Rule {
        /// The node.
        node: NodeId,
        /// The rule's name, as [`Node::name`] gives it.
        rule: &'static str,
    },
    /// A vertex of a structure with boxes is out of place in the formula
    /// trees, the boxes, the links or the weakenings.
    #[non_exhaustive]
    Placement {
        /// The vertex.
        vertex: VertexId,
        /// What is wrong with it.
        fault: Placement,
    },
    /// A weakening of a structure with boxes, a `?` vertex without copies,
    /// hangs on no axiom link.
    #[non_exhaustive]
    Unattached {
        /// The `?` vertex.
        vertex: VertexId,
    },
    /// The criterion fails inside a box, with the boxes in it contracted to
    /// their `!` vertex and the `?` vertices outside it standing for their
    /// doors.
    #[non_exhaustive]
    InBox {
        /// The box's `!` vertex.
        door: VertexId,
        /// How the criterion fails there.
        error: Box<NetError>,
    },
    /// Proof nets with boxes exist for unit-free MELL in classical mode,
    /// with or without Mix, and in intuitionistic mode, and the sequent or
    /// the mode lies outside.
    #[non_exhaustive]
    NotMell {
        /// The sequent's fragment.
        fragment: Fragment,
        /// The mode asked for.
        mode: Mode,
    },
    /// A step of cut elimination was asked of a vertex that is no end of a
    /// cut link, or of a net without one.
    #[non_exhaustive]
    NoCut {
        /// The vertex named, or `None` where the strategy found no cut
        /// link.
        vertex: Option<VertexId>,
    },
    /// The criterion refused the net a step of cut elimination made: a
    /// defect of this crate, which never returns such a net.
    #[non_exhaustive]
    Reduction {
        /// How the criterion refused it.
        error: Box<NetError>,
    },
    /// A bound or the caller's stop ended the call without a verdict on
    /// the structure.
    #[non_exhaustive]
    Refused {
        /// The bound that refused it, or the stop.
        refusal: Refusal,
    },
}

impl NetError {
    /// Returns what sort of failure this is.
    ///
    /// A list of links that is no structure is malformed, and a structure
    /// that is no net is invalid. A sequent, a mode or a rule without nets
    /// is unsupported, and so is a step of cut elimination asked of no cut
    /// link. A refusal is no verdict and has its refusal's kind. A net that
    /// a step made and the criterion refuses is a defect.
    pub fn kind(&self) -> crate::ErrorKind {
        use crate::ErrorKind::*;
        match self {
            Self::NoVertex { .. }
            | Self::NotLiteral { .. }
            | Self::NotDual { .. }
            | Self::LinkedTwice { .. }
            | Self::Placement { .. } => Malformed,
            Self::InBox { error, .. } => error.kind(),
            Self::Unlinked { .. }
            | Self::Unattached { .. }
            | Self::Empty
            | Self::SwitchingCycle { .. }
            | Self::Disconnected { .. }
            | Self::DirectedCycle { .. }
            | Self::NoDominator { .. }
            | Self::Crossing { .. } => Invalid,
            Self::Fragment { .. }
            | Self::Mode { .. }
            | Self::Rule { .. }
            | Self::NotMell { .. }
            | Self::NotIntuitionistic { .. }
            | Self::NoCut { .. } => Unsupported,
            Self::Reduction { .. } => crate::ErrorKind::Defect,
            Self::Refused { refusal } => crate::errors::refusal_kind(refusal),
        }
    }

    /// Returns the stable code of the error.
    ///
    /// The code is `no_nets` where no structure exists,
    /// `not_intuitionistic` where no essential net does, `no_cut` for a
    /// step asked of no cut link, and `reduction_rejected` for a step's
    /// net the criterion refuses. A refusal has its refusal's code. Every
    /// other error is `invalid_net`.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Fragment { .. }
            | Self::Mode { .. }
            | Self::Rule { .. }
            | Self::NotMell { .. } => "no_nets",
            Self::InBox { error, .. } => error.code(),
            Self::NotIntuitionistic { .. } => "not_intuitionistic",
            Self::NoCut { .. } => "no_cut",
            Self::Reduction { .. } => "reduction_rejected",
            Self::Refused { refusal } => refusal.code(),
            Self::NoVertex { .. }
            | Self::NotLiteral { .. }
            | Self::NotDual { .. }
            | Self::LinkedTwice { .. }
            | Self::Placement { .. }
            | Self::Unlinked { .. }
            | Self::Unattached { .. }
            | Self::Empty
            | Self::SwitchingCycle { .. }
            | Self::Disconnected { .. }
            | Self::DirectedCycle { .. }
            | Self::NoDominator { .. }
            | Self::Crossing { .. } => "invalid_net",
        }
    }

    /// Returns the error for display with every vertex as its formula
    /// followed by its id in brackets, as in `~A[0]`, read from `owner`,
    /// the structure that failed or its forest.
    pub fn describe<'a>(&'a self, owner: &'a impl Owner) -> Described<'a> {
        Described::new(Subject::Net(self), owner)
    }

    /// Writes the error as [`Display`] does, with `formula[id]` in place of
    /// every vertex id when a forest is given.
    pub(crate) fn write(
        &self,
        f: &mut Formatter<'_>,
        names: Option<Names<'_>>,
        limit: Limit,
    ) -> FmtResult {
        self.write_over(f, names, None, limit)
    }

    /// Writes the error as [`write`](Self::write) does, reading each
    /// vertex's occurrence from `vertices` when a structure with boxes is
    /// given, where vertices are no occurrences.
    pub(crate) fn write_over(
        &self,
        f: &mut Formatter<'_>,
        names: Option<Names<'_>>,
        vertices: Option<&[OccId]>,
        limit: Limit,
    ) -> FmtResult {
        // Each formula, and each list of them, cut after `limit` characters.
        let vertex = |v: &VertexId| {
            let o = match vertices {
                Some(table) => table.get(v.index()).copied(),
                None => names.and_then(|n| (v.index() < n.forest.len()).then(|| v.occ())),
            };
            match (names, o) {
                (Some(names), Some(o)) => {
                    let mut formula = String::new();
                    clipped(&mut formula, Some(names), o.into(), limit).unwrap();
                    format!("{formula}[{}]", v.get())
                }
                _ => v.get().to_string(),
            }
        };
        let list = |vs: &[VertexId]| {
            let mut text = String::new();
            let mut budget = Budget::new(&mut text, limit);
            let cut_short = vs.iter().enumerate().any(|(i, v)| {
                let separator = if i == 0 { "" } else { ", " };
                budget
                    .write_str(separator)
                    .and_then(|()| budget.write_str(&vertex(v)))
                    .is_err()
            });
            if cut_short {
                write!(text, "… ({} vertices)", vs.len()).unwrap();
            }
            text
        };
        use NetError::*;
        match self {
            // A vertex outside the structure has no formula.
            NoVertex { vertex, vertices } => write!(
                f,
                "a link names vertex {vertex}, but the structure has {}",
                crate::errors::counted(*vertices, "vertex", "vertices")
            ),
            NotLiteral { vertex: v } => write!(f, "vertex {} is not a literal", vertex(v)),
            NotDual { x, y } => {
                write!(
                    f,
                    "the literals {} and {} are not dual",
                    vertex(x),
                    vertex(y)
                )
            }
            LinkedTwice { vertex: v } => write!(f, "literal {} is linked twice", vertex(v)),
            Unlinked { vertex: v } => write!(f, "literal {} has no axiom link", vertex(v)),
            Empty => f.write_str("the structure is empty, and no rule concludes the empty sequent"),
            SwitchingCycle { cycle } => write!(f, "a switching cycle runs through {}", list(cycle)),
            Disconnected { parts } => {
                let parts: Vec<String> = parts.iter().map(|p| format!("{{{}}}", list(p))).collect();
                write!(
                    f,
                    "every switching falls into {} parts; keeping every left premise, they are {}",
                    parts.len(),
                    parts.join(" and ")
                )
            }
            DirectedCycle { cycle } => write!(
                f,
                "a directed cycle of the essential net runs through {}",
                list(cycle)
            ),
            NoDominator { implication, path } => write!(
                f,
                "the implication {} does not dominate its antecedent: the path {} reaches the \
                 goal around it",
                vertex(implication),
                list(path)
            ),
            Crossing {
                links: [(x, y), (u, v)],
            } => write!(
                f,
                "the links {} — {} and {} — {} cross in the cyclic order",
                vertex(x),
                vertex(y),
                vertex(u),
                vertex(v)
            ),
            NotIntuitionistic { shape } => {
                f.write_str("essential nets exist for intuitionistic sequents only: ")?;
                shape.write(f, names, limit)
            }
            Fragment { fragment } => write!(
                f,
                "proof nets exist for MLL without units only, not for {fragment}"
            ),
            Mode { mode } => write!(
                f,
                "proof nets exist in linear mode only, with or without Mix, not in {mode} mode"
            ),
            Rule { node, rule } => write!(
                f,
                "node {} applies {rule}, which a proof net of MLL without units has no place for",
                node.get()
            ),
            NetError::Placement { vertex: v, fault } => {
                write!(f, "vertex {} {}", vertex(v), fault.clause())
            }
            Unattached { vertex: v } => {
                write!(f, "the weakening {} hangs on no axiom link", vertex(v))
            }
            InBox { door, error } => {
                write!(f, "inside the box of {}, ", vertex(door))?;
                error.write_over(f, names, vertices, limit)
            }
            NotMell { fragment, mode } => {
                // `Fragment` alone names the variant here.
                use crate::linear::fragment::Fragment as F;
                let unit_free = F::MLL.union(F::EXPONENTIALS);
                if !unit_free.contains(*fragment)
                    && unit_free.union(F::MULTIPLICATIVE_UNITS).contains(*fragment)
                    && !mode.is_affine()
                    && !mode.is_ordered()
                {
                    // The units alone are the reason.
                    f.write_str(
                        "proof nets with boxes exist only for MELL without units, and the \
                         sequent has a unit",
                    )
                } else {
                    write!(
                        f,
                        "proof nets with boxes exist for MELL without units in classical mode, \
                         with or without Mix, and in intuitionistic mode, only, not for \
                         {fragment} in {mode} mode"
                    )
                }
            }
            NoCut { vertex: Some(v) } => write!(f, "vertex {} is no end of a cut link", vertex(v)),
            NoCut { vertex: None } => f.write_str("the net has no cut link"),
            Reduction { error } => {
                f.write_str("a step of cut elimination made a net the criterion refuses: ")?;
                error.write_over(f, names, vertices, limit)
            }
            Refused { refusal } => write!(f, "{refusal}"),
        }
    }
}

impl Display for NetError {
    /// Writes the error with vertex ids.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.write(f, None, None)
    }
}

impl std::error::Error for NetError {}

/// Fails with [`Refusal::Memory`] when `bytes` are more than `limits`
/// allow.
fn afford(bytes: u64, limits: &Limits) -> Result<(), NetError> {
    match limits.memory_bytes {
        Some(limit) if bytes > limit => Err(NetError::Refused {
            refusal: Refusal::Memory {
                phase: Phase::Net,
                limit_bytes: limit,
                needed_bytes: Some(bytes),
            },
        }),
        _ => Ok(()),
    }
}

/// Cut links validated, each from its end in a cut formula's tree, and
/// the set of a structure's vertices where its forest has cut formulas.
type CutsPlaced = (Vec<(VertexId, VertexId)>, Option<OccSet>);

/// The error of a vertex out of place.
fn misplaced(vertex: VertexId, fault: Placement) -> Error {
    NetError::Placement { vertex, fault }.into()
}

/// The refusal of a call that `stop` ended.
const STOPPED: NetError = NetError::Refused {
    refusal: Refusal::Stopped { phase: Phase::Net },
};

/// A proof structure of unit-free MLL: the formula trees of a sequent
/// plus axiom links between dual literals, checked under a [`Criterion`].
///
/// The formula trees are the sequent's occurrence forest, and vertex `i`
/// is occurrence `i` of it ([`vertex`](Self::vertex),
/// [`occurrence`](Self::occurrence)). An axiom link joins two literals
/// `a` and `~a` of one atom. A *switching* keeps one of the two premise
/// edges of every `â…‹` vertex and drops the other. The structure is a proof
/// net when every literal is linked and the switchings pass the
/// criterion, which [`is_correct`](Self::is_correct) decides.
///
/// Over a sequent with cut formulas, a structure may have *cut links*
/// ([`with_cuts`](Self::with_cuts)). A cut link joins an occurrence of a
/// cut formula's tree to its dual; it is the cut rule of a proof. The
/// vertices are then the conclusions' trees and the trees above the cut
/// links' ends: the ends and their subformulas. The occurrences of the
/// cut formulas' trees above no cut link's end are no vertices. For the
/// criterion a cut link is an edge every switching keeps. [`cut`]
/// eliminates the cut links.
///
/// [`link`](Self::link) adds a link and refuses what is not one.
/// [`unlink`](Self::unlink) takes back the last link made. So a search
/// can try linkings by backtracking. The structure keeps its `â…‹`-free
/// skeleton (the premise edges of `⊗` vertices, the cut links and the
/// axiom links) as a union-find. So
/// [`same_component`](Self::same_component) answers in logarithmic time
/// whether a candidate link would close a cycle that no switching breaks.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::{Criterion, Forest, ProofStructure, Sequent, VertexId};
///
/// // ⊢ ~A, A ⊗ ~B, B, with the vertices 0: ~A, 1: A ⊗ ~B, 2: A,
/// // 3: ~B, 4: B.
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let v = VertexId::new;
/// let links = [(v(0), v(2)), (v(3), v(4))];
/// let net = ProofStructure::from_links(Forest::new(&sequent)?, Criterion::MLL, &links)?;
/// assert!(net.is_complete());
/// assert_eq!(net.partner(v(2)), Some(v(0)));
/// assert_eq!(net.is_correct(|_| false), Ok(()));
/// # Ok::<(), deduxit::Error>(())
/// ```
///
/// # JSON
///
/// With the feature `serialize` a structure is `{"version": 1, "sequent":
/// …, "mix": …, "links": [[x, y], …]}` ([`wire`](crate::wire)).
/// `sequent` is in [`Sequent`]'s form. The criterion's fields follow:
/// whether Mix is allowed, and `"order": "cyclic"` at level 2 for the
/// cyclic order. The cut links are `"cuts": [[x, y], …]`, at level 6,
/// where the structure has some. `links` holds the axiom links as pairs
/// of vertex ids, in the order they were made.
///
/// Reading validates the cut links and links as
/// [`with_cuts`](Self::with_cuts) does. It takes a partial or incorrect
/// structure, since whether it is a net is
/// [`is_correct`](Self::is_correct)'s question.
#[derive(Clone, Debug)]
pub struct ProofStructure {
    /// The forest of the sequent.
    forest: Forest,
    /// The rules the structure is checked under.
    criterion: Criterion,
    /// Per vertex, the literal it is linked to, or `NONE`.
    partner: Box<[u32]>,
    /// The links in the order they were made, each as the pair given to
    /// [`link`](Self::link).
    links: Vec<(VertexId, VertexId)>,
    /// The cut links, each from its end in a cut formula's tree to the
    /// dual end, in the order given.
    cuts: Vec<(VertexId, VertexId)>,
    /// Over a forest with cut formulas, the vertices of the structure:
    /// the conclusions' trees and the trees above the ends of every cut
    /// link. `None` over a forest without, where every occurrence is one.
    live: Option<OccSet>,
    /// The literals among the vertices.
    literals: usize,
    /// The coloured structure graph.
    graph: Graph,
    /// The `â…‹`-free skeleton.
    skeleton: Skeleton,
}

impl ProofStructure {
    /// Returns the structure over the forest, with no link yet.
    ///
    /// Over a forest with cut formulas the structure has no cut link, so
    /// the cut formulas' trees hold none of its vertices.
    /// [`with_cuts`](Self::with_cuts) makes one with cut links.
    ///
    /// # Errors
    ///
    /// [`NetError::Fragment`] for a sequent outside unit-free MLL, which
    /// has no proof nets; [`NetError::Mode`] for a criterion of the cyclic
    /// order with Mix, which no calculus has; [`Refusal::Index`] for a
    /// forest of more than 1 431 655 764 occurrences, more vertices than a
    /// structure holds.
    pub fn new(forest: Forest, criterion: Criterion) -> Result<Self, Error> {
        Self::build(forest, criterion, &[])
    }

    /// Returns the structure with the given axiom links, made in the order
    /// given.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new) does, and the [`NetError`] of
    /// [`link`](Self::link) for a pair that is no link: a vertex outside
    /// the structure, two literals that are not dual, or a literal linked
    /// twice.
    pub fn from_links(
        forest: Forest,
        criterion: Criterion,
        links: &[(VertexId, VertexId)],
    ) -> Result<Self, Error> {
        Self::with_cuts(forest, criterion, &[], links)
    }

    /// Returns the structure with the given cut links and axiom links.
    ///
    /// A cut link joins an occurrence of a cut formula's tree to its dual
    /// ([`Forest::dual`]), given in either order. The vertices of the
    /// structure are then the conclusions' trees and the trees above the
    /// ends of every cut link. No cut link may lie in the tree above
    /// another.
    ///
    /// # Errors
    ///
    /// As [`from_links`](Self::from_links) does;
    /// [`NetError::Placement`] with [`Placement::Cut`] for a cut link that
    /// does not join an occurrence of a cut formula's tree to its dual or
    /// that lies in the tree above another, with [`Placement::Uncut`] for
    /// a link to a vertex of a cut formula above no cut link;
    /// [`NetError::Mode`] for cut links under a criterion of the cyclic
    /// order, whose calculus has no cut.
    pub fn with_cuts(
        forest: Forest,
        criterion: Criterion,
        cuts: &[(VertexId, VertexId)],
        links: &[(VertexId, VertexId)],
    ) -> Result<Self, Error> {
        let mut net = Self::build(forest, criterion, cuts)?;
        for &(x, y) in links {
            net.link(x, y)?;
        }
        Ok(net)
    }

    /// Returns the structure over the forest with the given cut links and
    /// no link yet.
    fn build(
        forest: Forest,
        criterion: Criterion,
        cuts: &[(VertexId, VertexId)],
    ) -> Result<Self, Error> {
        has_nets(forest.sequent().fragment())?;
        // No calculus of the cyclic order has Mix or a cut.
        if criterion.order != Order::Commutative && (criterion.mix || !cuts.is_empty()) {
            let mode = if criterion.mix {
                Mode::CYCLIC.with_mix()
            } else {
                Mode::CYCLIC
            };
            return Err(NetError::Mode { mode }.into());
        }
        let n = forest.len();
        fits(n)?;
        let (cuts, live) = Self::place_cuts(&forest, cuts)?;
        let alive = |o: OccId| live.as_ref().is_none_or(|live| live.contains(o));
        let mut skeleton = Skeleton::new(n);
        for o in forest.ids().filter(|&o| alive(o)) {
            if let Some(p) = forest.parent(o)
                && forest.kind(p) == Kind::Tensor
                && alive(p)
            {
                skeleton.union(p.get(), o.get());
            }
        }
        for &(x, y) in &cuts {
            skeleton.union(x.get(), y.get());
        }
        let literals = match &live {
            None => forest.all_literals().len(),
            Some(live) => forest
                .all_literals()
                .iter()
                .filter(|&&l| live.contains(l))
                .count(),
        };
        skeleton.commit(literals / 2);
        Ok(Self {
            graph: Graph::new(&forest, live.as_ref(), &cuts),
            forest,
            criterion,
            partner: vec![NONE; n].into_boxed_slice(),
            links: Vec::with_capacity(literals / 2),
            cuts,
            live,
            literals,
            skeleton,
        })
    }

    /// Validates cut links over the forest and returns them each from its
    /// end in a cut formula's tree, with the set of the structure's
    /// vertices where the forest has cut formulas.
    fn place_cuts(forest: &Forest, cuts: &[(VertexId, VertexId)]) -> Result<CutsPlaced, Error> {
        if !forest.has_cuts() {
            if let Some(&(x, _)) = cuts.first() {
                return Err(misplaced(x, Placement::Cut));
            }
            return Ok((Vec::new(), None));
        }
        let n = forest.len();
        let conclusions = forest.ids().take_while(|&o| forest.is_conclusion(o));
        let mut live = OccSet::of(n, conclusions);
        let mut placed = Vec::with_capacity(cuts.len());
        for &(x, y) in cuts {
            for v in [x, y] {
                if v.index() >= n {
                    return Err(NetError::NoVertex {
                        vertex: v.get(),
                        vertices: n as u32,
                    }
                    .into());
                }
            }
            let (a, d) = match (forest.dual(x.occ()), forest.dual(y.occ())) {
                (Some(dx), _) if dx == y.occ() && x < y => (x, y),
                (_, Some(dy)) if dy == x.occ() && y < x => (y, x),
                _ => return Err(misplaced(x, Placement::Cut)),
            };
            for end in [a, d] {
                for o in forest.subtree(end.occ()) {
                    if !live.insert(o) {
                        return Err(misplaced(end, Placement::Cut));
                    }
                }
            }
            placed.push((a, d));
        }
        Ok((placed, Some(live)))
    }
    /// Returns the proof net of a proof of MLL, the net's axiom links read
    /// off the proof's `Ax` nodes and its cut links off its `Cut` nodes.
    /// This is desequentialization, the converse of
    /// [`sequentialize`](Self::sequentialize).
    ///
    /// The structure is built over a copy of the proof's forest. Every
    /// proof the checker accepts gives a proof net, and two proofs that
    /// differ only in the order of their rules give the same one. The
    /// checker is not run: the net of a proof the checker would reject can
    /// still be a proof net, and is returned as one.
    ///
    /// The call holds within `limits.memory_bytes`: it estimates the
    /// structure and the criterion's working memory before it makes
    /// anything. It asks `stop` once per node and once per round of the
    /// criterion, and gives up when `stop` returns true.
    ///
    /// # Errors
    ///
    /// - [`Error::GoalProof`] for a proof of a goal other than the sequent.
    /// - [`NetError::Rule`] for a node a net has no place for: any but
    ///   `ax`, `⊗`, `⅋`, Mix and the cut.
    /// - The errors of [`from_links`](Self::from_links), and the
    ///   criterion's error if the links are not a proof net. That happens
    ///   only for a proof the checker rejects, or one that uses Mix where
    ///   the criterion forbids it.
    /// - [`NetError::Placement`] with [`Placement::Cut`] for a proof that
    ///   cuts one occurrence in two branches, or an occurrence in one
    ///   branch and a subformula of it in another. Its net needs two
    ///   vertices of one occurrence. The checker accepts such a proof, and
    ///   [`MellStructure::from_proof`] makes its net.
    /// - [`NetError::Refused`] when the bound or the stop ended the call.
    ///
    /// # Examples
    ///
    #[cfg_attr(feature = "parse", doc = "```")]
    #[cfg_attr(not(feature = "parse"), doc = "```ignore")]
    /// use deduxit::Limits;
    /// use deduxit::linear::{Criterion, Mode, Options, ProofStructure, Sequent, prove};
    ///
    /// let sequent: Sequent = "A, A -o B |- B".parse()?;
    /// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
    /// let proof = outcome.verdict.proof().expect("provable");
    /// let net = ProofStructure::from_proof(proof, Criterion::MLL, &Limits::default(), |_| false)?;
    /// assert!(net.is_complete());
    /// assert_eq!(net.links().len(), 2);
    /// # Ok::<(), deduxit::Error>(())
    /// ```
    pub fn from_proof(
        proof: &Proof,
        criterion: Criterion,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Self, Error> {
        if proof.goal().is_some() {
            return Err(Error::GoalProof);
        }
        let forest = proof.forest();
        let bytes = Self::bytes(forest);
        afford(bytes, limits)?;
        let mut links = Vec::with_capacity(forest.all_literals().len() / 2);
        let mut cuts = Vec::new();
        for (i, &node) in proof.nodes().iter().enumerate() {
            let done = i as u64 + 1;
            let progress = Progress {
                held_bytes: bytes,
                ..Progress::new(Phase::Net, 1, done)
            };
            if stop(progress) {
                return Err(STOPPED.into());
            }
            match node {
                Node::Ax(x, y) => links.push((VertexId::of(x.occ()), VertexId::of(y.occ()))),
                Node::Tensor(..) | Node::Par(..) | Node::Mix(..) => {}
                // A member that is no cut formula's is refused as a cut
                // link from itself.
                Node::Cut(a, ..) => {
                    let d = forest.dual(a.occ()).unwrap_or(a.occ());
                    cuts.push((VertexId::of(a.occ()), VertexId::of(d)));
                }
                Node::One(_)
                | Node::Bot(..)
                | Node::With(..)
                | Node::Plus(..)
                | Node::Top(_)
                | Node::Bang(..)
                | Node::Quest(..)
                | Node::Copy(..)
                | Node::Weaken(..)
                | Node::Forall(..)
                | Node::Exists(..) => {
                    return Err(NetError::Rule {
                        node: NodeId::new(i as u32),
                        rule: node.name(),
                    }
                    .into());
                }
            }
        }
        let net = Self::with_cuts(forest.clone(), criterion, &cuts, &links)?;
        net.is_correct(|progress| {
            stop(Progress {
                held_bytes: bytes,
                ..progress
            })
        })?;
        Ok(net)
    }

    /// Returns the bytes a structure over the forest holds with the
    /// criterion's working memory, the copy of its forest included.
    fn bytes(forest: &Forest) -> u64 {
        let arena = forest.sequent().terms().len() as u64 * size_of::<Term>() as u64;
        (forest.len() as u64 * (STRUCTURE_BYTES + SCRATCH_BYTES)).saturating_add(arena)
    }

    /// Fails if `x` and `y` are not two unlinked dual literals of the
    /// structure; the ids may be any, also none of the structure's.
    fn check_link(&self, x: VertexId, y: VertexId) -> Result<(), NetError> {
        let f = &self.forest;
        for v in [x, y] {
            if v.index() >= f.len() {
                return Err(NetError::NoVertex {
                    vertex: v.get(),
                    vertices: f.len() as u32,
                });
            }
            if !f.is_literal(v.occ()) {
                return Err(NetError::NotLiteral { vertex: v });
            }
            if !self.is_vertex(v.occ()) {
                return Err(NetError::Placement {
                    vertex: v,
                    fault: Placement::Uncut,
                });
            }
        }
        if !self.dual(x, y) {
            return Err(NetError::NotDual { x, y });
        }
        for v in [x, y] {
            if self.partner(v).is_some() {
                return Err(NetError::LinkedTwice { vertex: v });
            }
        }
        Ok(())
    }

    /// Returns whether two literal vertices are `a` and `~a` for one atom.
    fn dual(&self, x: VertexId, y: VertexId) -> bool {
        self.forest.dual_literals(x.occ(), y.occ())
    }

    /// Returns the forest of the sequent.
    pub fn forest(&self) -> &Forest {
        &self.forest
    }

    /// Returns the sequent.
    pub fn sequent(&self) -> &Sequent {
        self.forest.sequent()
    }

    /// Returns the rules the structure is checked under.
    pub fn criterion(&self) -> Criterion {
        self.criterion
    }

    /// Returns whether an occurrence of the forest is a vertex: every one
    /// over a forest without cut formulas, else one of the conclusions'
    /// trees or of a tree above an end of a cut link.
    fn is_vertex(&self, o: OccId) -> bool {
        self.live.as_ref().is_none_or(|live| live.contains(o))
    }

    /// Returns the vertex of an occurrence of the forest. `None` for an
    /// id outside it, and for an occurrence of a cut formula's tree above
    /// no cut link's end.
    pub fn vertex(&self, o: OccId) -> Option<VertexId> {
        (o.index() < self.forest.len() && self.is_vertex(o)).then_some(VertexId::of(o))
    }

    /// Returns the occurrence a vertex stands for, `None` for a vertex
    /// outside the structure.
    pub fn occurrence(&self, v: VertexId) -> Option<OccId> {
        self.vertex(v.occ()).map(VertexId::occ)
    }

    /// Returns the vertices, in order: every occurrence of the forest but
    /// those of cut formulas' trees above no cut link's end.
    pub fn vertices(&self) -> impl Iterator<Item = VertexId> + '_ {
        self.forest
            .ids()
            .filter(|&o| self.is_vertex(o))
            .map(VertexId::of)
    }

    /// Returns the cut links, each from its end in a cut formula's tree to
    /// its dual end, in the order they were given.
    pub fn cuts(&self) -> &[(VertexId, VertexId)] {
        &self.cuts
    }

    /// Returns the other end of the cut link at a vertex, `None` for a
    /// vertex at no cut link.
    pub fn cut_partner(&self, v: VertexId) -> Option<VertexId> {
        self.cuts.iter().find_map(|&(x, y)| match v {
            v if v == x => Some(y),
            v if v == y => Some(x),
            _ => None,
        })
    }

    /// Returns whether the structure has no cut link.
    pub fn is_cut_free(&self) -> bool {
        self.cuts.is_empty()
    }

    /// Returns the literal a vertex is linked to, or `None` for an
    /// unlinked literal, a connective or a vertex outside the structure.
    pub fn partner(&self, v: VertexId) -> Option<VertexId> {
        match self.partner.get(v.index()) {
            None | Some(&NONE) => None,
            Some(&p) => Some(VertexId(p)),
        }
    }

    /// Returns [`partner`](Self::partner) of a vertex the caller knows to
    /// be the structure's, as a search knows its candidates.
    ///
    /// It makes one comparison. A search asks it for every candidate link.
    pub(crate) fn mate(&self, v: VertexId) -> Option<VertexId> {
        match self.partner[v.index()] {
            NONE => None,
            p => Some(VertexId(p)),
        }
    }

    /// Returns the links in the order they were made.
    pub fn links(&self) -> &[(VertexId, VertexId)] {
        &self.links
    }

    /// Returns whether every literal is linked.
    pub fn is_complete(&self) -> bool {
        2 * self.links.len() == self.literals
    }

    /// Returns the literals without a link, grouped by atom and sign as
    /// [`Forest::all_literals`] lists them.
    pub fn unlinked(&self) -> impl Iterator<Item = VertexId> {
        self.forest
            .all_literals()
            .iter()
            .filter(|&&l| self.partner[l.index()] == NONE && self.is_vertex(l))
            .map(|&l| VertexId::of(l))
    }

    /// Links two unlinked dual literals, in time logarithmic in the
    /// structure.
    ///
    /// # Errors
    ///
    /// Fails, and leaves the structure as it is, if one of the two is no
    /// vertex of the structure ([`NetError::NoVertex`]), no literal
    /// ([`NetError::NotLiteral`]) or a literal of a cut formula's tree
    /// above no cut link's end ([`NetError::Placement`] with
    /// [`Placement::Uncut`]), if they are not dual
    /// ([`NetError::NotDual`]), or if one has a link already
    /// ([`NetError::LinkedTwice`]).
    pub fn link(&mut self, x: VertexId, y: VertexId) -> Result<(), NetError> {
        self.check_link(x, y)?;
        self.link_unchecked(x, y);
        Ok(())
    }

    /// Links two literals that the caller knows to be unlinked dual
    /// literals of the structure, as a search knows the candidates it
    /// enumerates.
    ///
    /// Only a debug build checks them. Any other pair corrupts the
    /// structure.
    pub(crate) fn link_unchecked(&mut self, x: VertexId, y: VertexId) {
        debug_assert!(
            self.check_link(x, y).is_ok(),
            "{x:?} and {y:?} cannot be linked"
        );
        self.partner[x.index()] = y.get();
        self.partner[y.index()] = x.get();
        self.links.push((x, y));
        self.skeleton.union(x.get(), y.get());
        self.graph.link(x.get(), y.get());
    }

    /// Takes back the last link made, in constant time, and returns it.
    /// `None` if there is no link.
    ///
    /// Links are undone in the reverse order of their making, as a
    /// backtracking search undoes them.
    pub fn unlink(&mut self) -> Option<(VertexId, VertexId)> {
        let (x, y) = self.links.pop()?;
        self.partner[x.index()] = NONE;
        self.partner[y.index()] = NONE;
        self.skeleton.undo();
        self.graph.unlink(x.get(), y.get());
        Some((x, y))
    }

    /// Returns whether two vertices are joined by a path that uses no
    /// premise edge of a `⅋`: only `⊗` premise edges, cut links and axiom
    /// links.
    ///
    /// Linking two such literals closes a cycle that every switching
    /// keeps. A vertex outside the structure is joined to nothing. It takes
    /// time logarithmic in the structure.
    pub fn same_component(&self, x: VertexId, y: VertexId) -> bool {
        let n = self.forest.len();
        x.index() < n && y.index() < n && self.joined(x, y)
    }

    /// Returns [`same_component`](Self::same_component) of two vertices
    /// the caller knows to be the structure's, as a search knows its
    /// candidates.
    ///
    /// It skips the comparison of the ids with the structure's length,
    /// since a search asks it for every candidate link.
    pub(crate) fn joined(&self, x: VertexId, y: VertexId) -> bool {
        self.skeleton.same(x.get(), y.get())
    }

    /// Returns the component of a vertex of the structure in the
    /// `â…‹`-free skeleton, as the vertex that names it until the next link
    /// or unlink.
    pub(crate) fn component(&self, v: VertexId) -> u32 {
        self.skeleton.find(v.get())
    }

    /// Returns working memory for the tests of the criterion, sized for
    /// this structure. One serves any number of calls.
    pub fn scratch(&self) -> Scratch {
        self.graph.scratch()
    }

    /// Returns whether no cycle survives any switching.
    ///
    /// The answer means the same on a partial structure, since an unlinked
    /// literal lies on no cycle. With a scratch from
    /// [`scratch`](Self::scratch) the call allocates nothing. A scratch
    /// sized for another structure is replaced by one for this one.
    ///
    /// It runs the deletion procedure of Yeo's theorem on the graph whose
    /// edges are the premise edges, the cut links and the axiom links. The
    /// two premise edges of a `â…‹` share a colour, and every other edge has
    /// a colour of its own. A vertex that every part of the graph without
    /// it meets in edges of one colour only lies on no switching cycle, and
    /// is deleted. When no vertex is left to delete, either nothing
    /// remains or what remains carries a switching cycle.
    pub fn is_acyclic(&self, scratch: &mut Scratch) -> bool {
        if !self.cuts.is_empty() && self.looped().is_some() {
            return false;
        }
        if !scratch.fits(&self.graph) {
            *scratch = self.scratch();
        }
        scratch.restore();
        self.graph
            .acyclic(&self.forest, scratch, &mut |_| false)
            .unwrap_or(false)
    }

    /// Decides whether the structure is a proof net by the Danos–Regnier
    /// criterion, independently of any search and of the proof checker.
    ///
    /// A proof net has every literal linked, and no cycle survives any
    /// switching. Unless the criterion allows Mix, every switching is also
    /// connected. Once no switching has a cycle, connectedness is a count:
    /// the edges a switching keeps are one fewer than the vertices. A cut link
    /// is an edge every switching keeps, as a `⊗` without a conclusion
    /// would be (Girard, *Linear logic*, 1987). Under a criterion of the
    /// cyclic order the links must also be planar
    /// ([`is_planar`](Self::is_planar)).
    ///
    /// The call holds working memory linear in the structure. It asks
    /// `stop` once per round of the deletion procedure
    /// ([`is_acyclic`](Self::is_acyclic)). The witness of a cycle runs
    /// that procedure once per edge.
    ///
    /// # Errors
    ///
    /// [`NetError::Empty`], [`NetError::Unlinked`],
    /// [`NetError::SwitchingCycle`] or [`NetError::Disconnected`] with a
    /// witness; [`NetError::Crossing`] under a criterion of the cyclic
    /// order; [`NetError::Refused`] when `stop` ended it.
    ///
    /// # Examples
    ///
    #[cfg_attr(feature = "parse", doc = "```")]
    #[cfg_attr(not(feature = "parse"), doc = "```ignore")]
    /// use deduxit::linear::{Criterion, Forest, NetError, ProofStructure, Sequent, VertexId};
    ///
    /// // ⊢ A ⅋ B, ~A, ~B, with the vertices 0: A ⅋ B, 1: A, 2: B, 3: ~A,
    /// // 4: ~B.
    /// let sequent: Sequent = "|- A par B, ~A, ~B".parse()?;
    /// let forest = Forest::new(&sequent)?;
    /// let v = VertexId::new;
    /// let links = [(v(1), v(3)), (v(2), v(4))];
    ///
    /// // Every switching falls into two parts: the one that keeps A
    /// // leaves B and ~B apart.
    /// let net = ProofStructure::from_links(forest.clone(), Criterion::MLL, &links)?;
    /// assert!(matches!(
    ///     net.is_correct(|_| false),
    ///     Err(NetError::Disconnected { .. })
    /// ));
    ///
    /// // With Mix a proof net need not be connected.
    /// let mix = Criterion::MLL.with_mix();
    /// let net = ProofStructure::from_links(forest, mix, &links)?;
    /// assert_eq!(net.is_correct(|_| false), Ok(()));
    /// # Ok::<(), deduxit::Error>(())
    /// ```
    pub fn is_correct(&self, mut stop: impl FnMut(Progress) -> bool) -> Result<(), NetError> {
        if self.forest.is_empty() {
            return Err(NetError::Empty);
        }
        if let Some(l) = self.unlinked().next() {
            return Err(NetError::Unlinked { vertex: l });
        }
        // A cut link and an axiom link between the same two literals are
        // a cycle that the graph, which holds one edge between two
        // vertices, cannot show.
        if let Some((x, y)) = self.looped() {
            return Err(NetError::SwitchingCycle { cycle: vec![x, y] });
        }
        let mut scratch = self.scratch();
        let held_bytes = self.forest.len() as u64 * SCRATCH_BYTES;
        let mut rounds = 0;
        let mut stop = |round: u64| {
            rounds += round;
            stop(Progress {
                held_bytes,
                ..Progress::new(Phase::Net, round, rounds)
            })
        };
        match self.graph.acyclic(&self.forest, &mut scratch, &mut stop) {
            None => return Err(STOPPED),
            Some(false) => {
                return match self.graph.cycle(&self.forest, &mut scratch, &mut stop) {
                    Some(cycle) => Err(NetError::SwitchingCycle { cycle }),
                    None => Err(STOPPED),
                };
            }
            Some(true) => {}
        }
        if !self.criterion.mix
            && self.graph.switched_edges(self.links.len()) + 1 != self.graph.vertices()
        {
            return Err(NetError::Disconnected {
                parts: self.graph.parts(&self.forest, &mut scratch),
            });
        }
        if self.criterion.order != Order::Commutative {
            self.is_planar()?;
        }
        Ok(())
    }

    /// Returns a cut link whose two literals are linked to each other.
    fn looped(&self) -> Option<(VertexId, VertexId)> {
        self.cuts
            .iter()
            .copied()
            .find(|&(x, y)| self.partner(x) == Some(y))
    }

    /// Decides whether the links are planar: no two of them cross in the
    /// cyclic order of the literals. The answer is independent of any
    /// search and of the criterion's other conditions.
    ///
    /// The cyclic order is the order of the occurrence ids: the order the
    /// formulas are written in, a formula's left operand before its right
    /// one. Two links cross when their four literals alternate between
    /// them going round. That is the same in the cyclic order as in the
    /// linear one, whatever the rotation. A partial structure is planar
    /// when the links it has are. The test is one pass over the vertices,
    /// with a stack of the links whose first literal has been passed and
    /// whose second has not. In a planar structure the second literal
    /// reached always closes the link on top.
    ///
    /// A structure of unit-free MLL is a proof net of cyclic MLL exactly
    /// when it is a proof net and planar. Every derivation of the cyclic
    /// calculus joins its premises' planar nets side by side at a `⊗`. And
    /// every sequentialization of a planar net splits each `⊗` into the
    /// two arcs on either side of it, since the parts that removing it
    /// leaves are connected and drawn without crossing.
    ///
    /// # Errors
    ///
    /// [`NetError::Crossing`] with two links that cross.
    #[expect(
        clippy::missing_panics_doc,
        reason = "the expect and the unreachable state that a link's two literals name each other, which linking keeps"
    )]
    pub fn is_planar(&self) -> Result<(), NetError> {
        let mut open: Vec<VertexId> = Vec::new();
        for o in self.forest.ids() {
            let v = VertexId::of(o);
            let Some(partner) = self.partner(v) else {
                continue;
            };
            if partner > v {
                open.push(v);
                continue;
            }
            // The link closes here: its first literal must be on top.
            match open.pop() {
                Some(top) if top == partner => {}
                Some(top) => {
                    let inner = self.partner(top).expect("an open literal is linked");
                    return Err(NetError::Crossing {
                        links: [(partner, v), (top, inner)],
                    });
                }
                None => unreachable!("the partner of a later literal was passed and is open"),
            }
        }
        Ok(())
    }
}

impl Display for ProofStructure {
    /// Writes the sequent, then one line per cut link, in their order, as
    /// `cut A ⊗ B[5] — ~A ⅋ ~B[8]`. Then one line per axiom link as
    /// `~A[0] — A[2]`, each literal with its vertex id, the smaller id
    /// first and the links ordered by it. Last comes the verdict of the
    /// criterion: `proof net (the correctness criterion holds)`, the same
    /// with Mix, a `planar proof net` in the cyclic order, or `not a proof
    /// net: ` and the reason with formulas. No trailing newline.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.write(f, None)
    }
}

impl ProofStructure {
    /// Returns the structure for display as `mode` reads it.
    ///
    /// That is what [`Display`] writes, except in an intuitionistic mode
    /// where the sequent has a reading. There the sequent is two-sided,
    /// and every formula is written as the reading writes it
    /// (`A ⊸ B, A ⊢ B`, `A[0] — A[2]`).
    pub fn written_in(&self, mode: crate::linear::Mode) -> impl Display + '_ {
        In {
            structure: self,
            mode,
        }
    }

    /// Writes the structure as [`Display`] does, or as `mode` reads it:
    /// in an intuitionistic mode every formula as the reading writes it,
    /// where the sequent has one.
    fn write(&self, f: &mut Formatter<'_>, mode: Option<crate::linear::Mode>) -> FmtResult {
        let reading = mode
            .filter(|mode| mode.is_intuitionistic())
            .and_then(|_| self.reading().ok());
        let reading = reading.as_ref();
        match reading {
            Some(reading) => writeln!(f, "{reading}")?,
            None => writeln!(f, "{}", self.sequent())?,
        }
        let mut links: Vec<(VertexId, VertexId)> = self
            .links
            .iter()
            .map(|&(x, y)| (x.min(y), x.max(y)))
            .collect();
        links.sort_unstable();
        let formula = |v: VertexId| match reading {
            Some(reading) => reading.formula(v.occ()).to_string(),
            None => self.forest.formula(v.occ()).to_string(),
        };
        for &(x, y) in &self.cuts {
            writeln!(
                f,
                "cut {}[{}] — {}[{}]",
                formula(x),
                x.get(),
                formula(y),
                y.get()
            )?;
        }
        for (x, y) in links {
            writeln!(
                f,
                "{}[{}] — {}[{}]",
                formula(x),
                x.get(),
                formula(y),
                y.get()
            )?;
        }
        match self.is_correct(|_| false) {
            Ok(()) if self.criterion.mix => {
                f.write_str("proof net with Mix (the correctness criterion with Mix holds)")
            }
            Ok(()) if self.criterion.order != Order::Commutative => f.write_str(
                "planar proof net (the correctness criterion holds, and no two links cross)",
            ),
            Ok(()) => f.write_str("proof net (the correctness criterion holds)"),
            Err(e) => match mode {
                Some(mode) => write!(
                    f,
                    "not a proof net: {}",
                    e.describe(&self.forest).in_mode(mode)
                ),
                None => write!(f, "not a proof net: {}", e.describe(&self.forest)),
            },
        }
    }
}

/// A proof structure, or one with boxes, for display as a mode reads it.
pub(crate) struct In<'a, S> {
    /// The structure.
    pub(crate) structure: &'a S,
    /// The mode.
    pub(crate) mode: crate::linear::Mode,
}

impl Display for In<'_, ProofStructure> {
    /// Writes the structure under its reading in an intuitionistic mode,
    /// else as its own [`Display`] does.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.structure.write(f, Some(self.mode))
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    #[cfg(feature = "parse")]
    use crate::linear::fragment::Mode;
    #[cfg(feature = "parse")]
    use crate::linear::occurrences::Member;
    #[cfg(feature = "parse")]
    use crate::linear::proofs::NodeId;

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

    /// Wraps a raw vertex id.
    const fn v(id: u32) -> VertexId {
        VertexId::new(id)
    }

    /// A forest of one occurrence more than a structure has vertices is
    /// refused. The net engines refuse it so before they search, and never
    /// panic where a search makes its structure. The test builds no forest
    /// that large, at some 25 bytes an occurrence.
    #[test]
    fn a_forest_past_the_vertices_is_refused() {
        let most = usize::try_from(MOST).unwrap();
        assert!(fits(most).is_ok());
        assert!(matches!(
            fits(most + 1),
            Err(Error::Refused(Refusal::Index {
                what: Space::Vertex,
                count,
                most: MOST,
            })) if count == MOST + 1
        ));
    }

    /// The criterion with Mix allowed or not.
    const fn criterion(mix: bool) -> Criterion {
        Criterion {
            mix,
            ..Criterion::MLL
        }
    }

    /// Builds the forest of `input`, or panics with the parse error.
    #[cfg(feature = "parse")]
    fn forest(input: &str) -> Forest {
        let s: Sequent = input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"));
        Forest::new(&s).unwrap()
    }

    /// Links are made and taken back in stack order, the partners and the
    /// skeleton follow, and completeness is every literal linked.
    #[cfg(feature = "parse")]
    #[test]
    fn link_and_unlink() {
        // ⊢ ~A, A ⊗ ~B, B: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B.
        let mut net = ProofStructure::new(forest("A, A -o B |- B"), criterion(false)).unwrap();
        assert!(!net.is_complete());
        assert_eq!(net.unlinked().collect::<Vec<_>>(), [v(2), v(0), v(4), v(3)]);
        assert!(net.same_component(v(2), v(3)), "the ⊗ joins its premises");
        assert!(!net.same_component(v(0), v(2)));

        net.link(v(0), v(2)).unwrap();
        assert_eq!(net.partner(v(2)), Some(v(0)));
        assert_eq!(net.partner(v(1)), None);
        assert!(net.same_component(v(0), v(3)), "through the link and the ⊗");
        net.link(v(4), v(3)).unwrap();
        assert!(net.is_complete());
        assert_eq!(net.links(), [(v(0), v(2)), (v(4), v(3))]);

        assert_eq!(net.unlink(), Some((v(4), v(3))));
        assert_eq!(net.partner(v(4)), None);
        assert!(!net.same_component(v(4), v(0)));
        assert_eq!(net.unlink(), Some((v(0), v(2))));
        assert!(!net.same_component(v(0), v(3)));
        assert_eq!(net.unlink(), None);
        assert_eq!(net.unlinked().count(), 4);
    }

    /// Two derivations that differ only in the order of their rules give
    /// the same net, and a proof that is not one of MLL is refused.
    #[cfg(feature = "parse")]
    #[test]
    fn desequentialize() {
        use Node::*;
        let (n, mode) = (NodeId::new, Mode::CLASSICAL);
        // ⊢ A ⊗ B, ~A, ~B ⊗ C, ~C: 0 ⊗, 1 A, 2 B, 3 ~A, 4 ⊗, 5 ~B, 6 C, 7 ~C.
        let f = forest("|- A * B, ~A, ~B * C, ~C");
        let first_tensor_first = Proof::new(
            f.clone(),
            vec![
                Ax(o(1).into(), o(3).into()),
                Ax(o(2).into(), o(5).into()),
                Ax(o(6).into(), o(7).into()),
                Tensor(Member::from(o(4)), n(1), n(2)),
                Tensor(Member::from(o(0)), n(0), n(3)),
            ],
            n(4),
        )
        .unwrap();
        let second_tensor_first = Proof::new(
            f.clone(),
            vec![
                Ax(o(1).into(), o(3).into()),
                Ax(o(2).into(), o(5).into()),
                Tensor(Member::from(o(0)), n(0), n(1)),
                Ax(o(6).into(), o(7).into()),
                Tensor(Member::from(o(4)), n(2), n(3)),
            ],
            n(4),
        )
        .unwrap();
        assert_eq!(first_tensor_first.check(mode), Ok(()));
        assert_eq!(second_tensor_first.check(mode), Ok(()));
        let a = ProofStructure::from_proof(
            &first_tensor_first,
            criterion(false),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        let b = ProofStructure::from_proof(
            &second_tensor_first,
            criterion(false),
            &Limits::default(),
            |_| false,
        )
        .unwrap();
        assert_eq!(links(&a), links(&b));
        assert_eq!(links(&a), [(v(1), v(3)), (v(2), v(5)), (v(6), v(7))]);

        // A proof with Mix desequentializes only when Mix is allowed.
        let f = forest("|- A par B, ~A, ~B");
        let with_mix = Proof::new(
            f,
            vec![
                Ax(o(1).into(), o(3).into()),
                Ax(o(2).into(), o(4).into()),
                Mix(n(0), n(1)),
                Par(Member::from(o(0)), n(2)),
            ],
            n(3),
        )
        .unwrap();
        assert!(
            ProofStructure::from_proof(&with_mix, criterion(true), &Limits::default(), |_| false)
                .is_ok()
        );
        assert!(matches!(
            ProofStructure::from_proof(&with_mix, criterion(false), &Limits::default(), |_| false),
            Err(Error::Net(e)) if matches!(*e, NetError::Disconnected { .. })
        ));
        // Outside MLL there is no net, and a node a net has no place for
        // is refused, never skipped.
        let f = forest("|- A & A, ~A");
        let additive = Proof::new(
            f,
            vec![
                Ax(o(1).into(), o(3).into()),
                Ax(o(2).into(), o(3).into()),
                With(Member::from(o(0)), n(0), n(1)),
            ],
            n(2),
        )
        .unwrap();
        assert!(matches!(
            ProofStructure::from_proof(&additive, criterion(false), &Limits::default(), |_| false),
            Err(Error::Net(e)) if matches!(*e, NetError::Rule { node, rule: "&" } if node == n(2))
        ));
        // Affine weakening on a sequent of MLL.
        let f = forest("|- A, ~A, B");
        let weakened = Proof::new(
            f,
            vec![Ax(o(0).into(), o(1).into()), Weaken(o(2).into(), n(0))],
            n(1),
        )
        .unwrap();
        assert!(matches!(
            ProofStructure::from_proof(&weakened, criterion(false), &Limits::default(), |_| false),
            Err(Error::Net(e)) if matches!(*e, NetError::Rule { rule: "wk", .. })
        ));
    }

    /// Random derivations of MLL, with and without Mix, round-trip through
    /// their net: the net is correct, the sequentialized proof passes the
    /// checker, and it has the same net as the derivation it came from.
    #[cfg(feature = "parse")]
    #[test]
    fn round_trip_random_derivations() {
        use crate::linear::search::generate::{self, Rng, Rules};
        use crate::linear::search::{Options, prove};
        for (seed, mix) in [(3, false), (4, true)] {
            let rules = Rules {
                units: false,
                additives: false,
                mix,
                exponentials: false,
            };
            let mode = if mix {
                Mode::CLASSICAL.with_mix()
            } else {
                Mode::CLASSICAL
            };
            let mut rng = Rng::new(seed);
            for _ in 0..60 {
                let budget = 2 + rng.below(14);
                let formulas = generate::provable(&mut rng, rules, 3, budget).formulas;
                let text = generate::sequent(&formulas);
                let s: Sequent = text.parse().unwrap();
                let outcome = prove(&s, mode, &Options::default()).unwrap();
                let proof = outcome.verdict.proof().expect("the sequent is provable");
                assert_eq!(proof.check(mode), Ok(()), "{text:?}");
                let net =
                    ProofStructure::from_proof(proof, criterion(mix), &Limits::default(), |_| {
                        false
                    })
                    .unwrap_or_else(|e| panic!("{text:?}: {e}"));
                let back = net
                    .sequentialize(&Limits::default(), |_| false)
                    .unwrap_or_else(|e| panic!("{text:?}: {e}"));
                assert_eq!(back.check(mode), Ok(()), "{text:?}");
                let again =
                    ProofStructure::from_proof(&back, criterion(mix), &Limits::default(), |_| {
                        false
                    })
                    .unwrap();
                assert_eq!(links(&again), links(&net), "{text:?}");
            }
        }
    }

    /// Planarity agrees with a comparison of every two links on every
    /// complete linking of small sequents, its witness crosses, a
    /// structure is a proof net of the cyclic order exactly when it is a
    /// planar proof net, and every such net sequentializes into a proof
    /// the checker accepts in the cyclic mode, whose net it is.
    #[test]
    fn planarity() {
        use crate::linear::occurrences::Sign;
        use crate::linear::search::generate::{self, Rng, Rules};
        use crate::linear::sequents::Atom;
        /// Whether the links `(x, y)` and `(u, v)` cross: their ends
        /// alternate, in the linear order as in the cyclic one.
        fn cross((x, y): (VertexId, VertexId), (u, v): (VertexId, VertexId)) -> bool {
            let (x, y) = (x.min(y), x.max(y));
            let (u, v) = (u.min(v), u.max(v));
            (x < u && u < y && y < v) || (u < x && x < v && v < y)
        }
        /// Tries every linking of the literals of `positives` to unlinked
        /// partners, and compares the criteria on each complete one;
        /// returns the planar nets seen.
        fn every(net: &mut ProofStructure, positives: &[OccId], mll: &mut ProofStructure) -> u32 {
            let Some((&x, rest)) = positives.split_first() else {
                let pairwise = net
                    .links()
                    .iter()
                    .all(|&l| net.links().iter().all(|&m| !cross(l, m)));
                match net.is_planar() {
                    Ok(()) => assert!(pairwise, "{net}"),
                    Err(NetError::Crossing { links: [l, m] }) => {
                        assert!(!pairwise && cross(l, m), "{net}");
                        assert!(l.0 < l.1 && m.0 < m.1 && l.0 < m.0, "{l:?} {m:?}");
                    }
                    Err(e) => panic!("{e}"),
                }
                let cyclic = net.is_correct(|_| false).is_ok();
                assert_eq!(
                    cyclic,
                    pairwise && mll.is_correct(|_| false).is_ok(),
                    "{net}"
                );
                if cyclic {
                    let proof = net.sequentialize(&Limits::default(), |_| false).unwrap();
                    assert_eq!(proof.check(Mode::CYCLIC), Ok(()), "{net}");
                    let back = ProofStructure::from_proof(
                        &proof,
                        Criterion::CYCLIC,
                        &Limits::default(),
                        |_| false,
                    )
                    .unwrap();
                    assert_eq!(links(&back), links(net), "{net}");
                }
                return u32::from(cyclic);
            };
            let forest = net.forest().clone();
            let mut nets = 0;
            for &y in forest.literals(forest.atom(x).unwrap(), Sign::Dual) {
                if net.partner(VertexId::of(y)).is_none() {
                    net.link(VertexId::of(x), VertexId::of(y)).unwrap();
                    mll.link(VertexId::of(x), VertexId::of(y)).unwrap();
                    nets += every(net, rest, mll);
                    net.unlink();
                    mll.unlink();
                }
            }
            nets
        }
        let rules = Rules {
            units: false,
            additives: false,
            mix: false,
            exponentials: false,
        };
        let mut rng = Rng::new(36);
        let (mut sequents, mut nets) = (0, 0);
        for round in 0..300 {
            let formulas = if round % 2 == 0 {
                let budget = 2 + rng.below(8);
                generate::provable(&mut rng, rules, 2, budget).formulas
            } else {
                let (atoms, pairs) = (1 + rng.below(2) as u8, 1 + rng.below(5));
                generate::balanced(&mut rng, atoms, pairs, false)
            };
            let s: Sequent = generate::sequent(&formulas).parse().unwrap();
            let forest = Forest::new(&s).unwrap();
            // At most 5! pairings of one atom's literals.
            let positives: Vec<OccId> = (0..s.atom_names().len() as u32)
                .flat_map(|a| forest.literals(Atom::new(a), Sign::Atom).to_vec())
                .collect();
            let balanced = (0..s.atom_names().len() as u32).all(|a| {
                let a = Atom::new(a);
                let n = forest.literals(a, Sign::Atom).len();
                n == forest.literals(a, Sign::Dual).len() && n <= 5
            });
            if !balanced {
                continue;
            }
            let mut net = ProofStructure::new(forest.clone(), Criterion::CYCLIC).unwrap();
            let mut mll = ProofStructure::new(forest, Criterion::MLL).unwrap();
            sequents += 1;
            nets += every(&mut net, &positives, &mut mll);
        }
        assert!(
            sequents > 150 && nets > 100,
            "{sequents} sequents, {nets} planar nets"
        );
    }

    /// The text form lists the sequent, the links with their positions and
    /// the verdict, with formulas in the reason when there is one.
    #[cfg(feature = "parse")]
    #[test]
    fn text_form() {
        let net = ProofStructure::from_links(
            forest("A, A -o B |- B"),
            criterion(false),
            &[(v(2), v(0)), (v(3), v(4))],
        )
        .unwrap();
        assert_eq!(
            net.to_string(),
            "⊢ ~A, A ⊗ ~B, B\n~A[0] — A[2]\n~B[3] — B[4]\nproof net (the correctness criterion holds)"
        );
        let mut net = ProofStructure::new(forest("|- A par B, ~A, ~B"), criterion(true)).unwrap();
        net.link(v(1), v(3)).unwrap();
        assert_eq!(
            net.to_string(),
            "⊢ A ⅋ B, ~A, ~B\nA[1] — ~A[3]\nnot a proof net: literal B[2] has no axiom link"
        );
        net.link(v(2), v(4)).unwrap();
        assert!(
            net.to_string()
                .ends_with("\nproof net with Mix (the correctness criterion with Mix holds)")
        );
        let net =
            ProofStructure::from_links(forest("|- A * ~A"), criterion(false), &[(v(1), v(2))])
                .unwrap();
        assert!(
            net.to_string().ends_with(
                "not a proof net: a switching cycle runs through A ⊗ ~A[0], A[1], ~A[2]"
            )
        );
        let net = ProofStructure::from_links(
            forest("|- A par B, ~A, ~B"),
            criterion(false),
            &[(v(1), v(3)), (v(2), v(4))],
        )
        .unwrap();
        assert!(net.to_string().ends_with(
            "not a proof net: every switching falls into 2 parts; keeping every left premise, \
             they are {A â…‹ B[0], ~A[3]} and {B[2], ~B[4]}"
        ));
    }

    /// The links of a structure as sorted pairs, for comparing nets.
    fn links(net: &ProofStructure) -> Vec<(VertexId, VertexId)> {
        let mut links: Vec<(VertexId, VertexId)> = net
            .links()
            .iter()
            .map(|&(x, y)| (x.min(y), x.max(y)))
            .collect();
        links.sort();
        links
    }

    /// A list of links is validated: literals only, dual, each at most
    /// once, inside the forest; and only unit-free MLL has structures. A
    /// single link is validated alike, and one refused changes nothing.
    #[cfg(feature = "parse")]
    #[test]
    fn validation() {
        // ⊢ ~A, A ⊗ ~B, B, A: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B, 5 A.
        let f = || forest("A, A -o B |- B, A");
        let net = ProofStructure::from_links(f(), criterion(false), &[(v(0), v(5))]).unwrap();
        assert!(!net.is_complete());
        for (links, error) in [
            (
                vec![(v(0), v(9))],
                NetError::NoVertex {
                    vertex: 9,
                    vertices: 6,
                },
            ),
            (vec![(v(1), v(0))], NetError::NotLiteral { vertex: v(1) }),
            (vec![(v(0), v(3))], NetError::NotDual { x: v(0), y: v(3) }),
            (vec![(v(5), v(2))], NetError::NotDual { x: v(5), y: v(2) }),
            (
                vec![(v(0), v(5)), (v(0), v(2))],
                NetError::LinkedTwice { vertex: v(0) },
            ),
        ] {
            match ProofStructure::from_links(f(), criterion(false), &links) {
                Err(Error::Net(e)) => assert_eq!(*e, error, "{links:?}"),
                other => panic!("{links:?}: {other:?}"),
            }
            let mut net = ProofStructure::new(f(), criterion(false)).unwrap();
            let (&(x, y), made) = links.split_last().unwrap();
            for &(x, y) in made {
                net.link(x, y).unwrap();
            }
            assert_eq!(net.link(x, y), Err(error), "{links:?}");
            assert_eq!(net.links(), made, "{links:?}");
            assert_eq!(net.partner(v(2)), None, "{links:?}");
        }
        let outside = NetError::NoVertex {
            vertex: u32::MAX,
            vertices: 6,
        };
        assert_eq!(
            outside.describe(net.forest()).to_string(),
            "a link names vertex 4294967295, but the structure has 6 vertices"
        );
        for input in ["|- 1", "|- A & B", "|- !A"] {
            assert!(
                matches!(
                    ProofStructure::new(forest(input), criterion(true)),
                    Err(Error::Net(e)) if matches!(*e, NetError::Fragment { .. })
                ),
                "{input}"
            );
        }
        assert!(ProofStructure::new(forest("|-"), criterion(true)).is_ok());
    }

    /// An id the structure does not hold is answered, never a panic: no
    /// partner, joined to nothing, no occurrence; and a scratch sized for
    /// another structure is replaced, so the test answers as with its own.
    #[cfg(feature = "parse")]
    #[test]
    fn foreign_ids_and_scratches() {
        let small = ProofStructure::from_links(forest("a |- a"), criterion(false), &[(v(0), v(1))])
            .unwrap();
        assert_eq!(small.partner(v(99)), None);
        assert!(!small.same_component(v(0), v(99)));
        assert_eq!(small.occurrence(v(2)), None);
        assert_eq!(small.vertex(o(1)), Some(v(1)));
        // ⊢ A ⊗ ~A, B, ~B with both links has a switching cycle.
        let cyclic = ProofStructure::from_links(
            forest("|- A * ~A, B, ~B"),
            criterion(true),
            &[(v(1), v(2)), (v(3), v(4))],
        )
        .unwrap();
        let mut scratch = small.scratch();
        assert!(!cyclic.is_acyclic(&mut scratch));
        assert!(small.is_acyclic(&mut scratch));
    }

    /// `exist` refuses as the constructors do, with their variant and
    /// code, where the net engine answers its own refusal.
    #[test]
    fn exist_refuses_as_the_constructors() {
        let additive = forest("|- a & b, ~a");
        let fragment = additive.sequent().fragment();
        let refused = exist(fragment, Mode::CLASSICAL).unwrap_err();
        let built = ProofStructure::new(additive, Criterion::MLL).unwrap_err();
        assert_eq!(Error::Net(Box::new(refused)), built);
        assert_eq!(built.code(), "no_nets");
        let affine = Mode::CLASSICAL.with_affine();
        assert_eq!(
            exist(Fragment::MLL, affine),
            Criterion::of(affine).map(|_| ())
        );
    }

    /// The bound and the stop refuse building a net from a proof, judging
    /// it and sequentializing it, with no verdict.
    #[cfg(feature = "parse")]
    #[test]
    #[expect(
        clippy::wildcard_enum_match_arm,
        reason = "a test's other arm is its failure"
    )]
    fn refusals() {
        use crate::linear::search::{Options, prove};
        let s: Sequent = "A * B |- B * A".parse().unwrap();
        let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
        let proof = outcome.verdict.proof().unwrap();
        let tiny = Limits::default().with_memory_bytes(Some(100));
        let refused = |error: Error| match error {
            Error::Net(e) => match *e {
                NetError::Refused { refusal } => refusal,
                other => panic!("{other:?}"),
            },
            other => panic!("{other:?}"),
        };
        let memory = refused(
            ProofStructure::from_proof(proof, Criterion::MLL, &tiny, |_| false).unwrap_err(),
        );
        assert!(matches!(
            memory,
            Refusal::Memory {
                phase: Phase::Net,
                ..
            }
        ));
        let stopped = Refusal::Stopped { phase: Phase::Net };
        let error = ProofStructure::from_proof(proof, Criterion::MLL, &Limits::default(), |_| true);
        assert_eq!(refused(error.unwrap_err()), stopped);
        let mut held = Vec::new();
        let net = ProofStructure::from_proof(proof, Criterion::MLL, &Limits::default(), |p| {
            held.push(p.held_bytes);
            false
        })
        .unwrap();
        // Each poll says what the call holds by its estimate. When the
        // criterion runs alone, that is its working memory.

        assert!(!held.is_empty() && held.iter().all(|&bytes| bytes > 0));
        let mut scratch = Vec::new();
        net.is_correct(|p| {
            scratch.push(p.held_bytes);
            false
        })
        .unwrap();
        assert!(!scratch.is_empty() && scratch.iter().all(|&bytes| bytes > 0));
        assert_eq!(
            net.is_correct(|_| true),
            Err(NetError::Refused {
                refusal: stopped.clone()
            })
        );
        assert_eq!(
            refused(net.sequentialize(&Limits::default(), |_| true).unwrap_err()),
            stopped
        );
        let memory = refused(net.sequentialize(&tiny, |_| false).unwrap_err());
        assert!(matches!(
            memory,
            Refusal::Memory {
                phase: Phase::Net,
                ..
            }
        ));
        let back = net.sequentialize(&Limits::default(), |_| false).unwrap();
        assert_eq!(back.mode(), Some(Mode::CLASSICAL));
    }
}

impl Display for In<'_, crate::linear::MellStructure> {
    /// Writes the structure under its reading in an intuitionistic mode,
    /// else as its own [`Display`] does.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.structure.write(f, Some(self.mode))
    }
}