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

//! The coloured structure graph of a proof structure and the tests the
//! correctness criterion runs on it.
//!
//! The vertices are the occurrences. The edges are the premise edges of
//! every `⊗` and `⅋`, the cut links and the axiom links. A cut link takes
//! the place of the parent edge at both its ends, whose parents are no
//! vertices. An occurrence that is no vertex of the structure (one of a
//! cut formula's tree above no cut link's end) has no slot at all.
//!
//! The colouring: the two premise edges of a `⅋` share a colour of their
//! own, and every other edge has a colour of its own. So a cycle is
//! *properly coloured* (no two consecutive edges alike) exactly when it
//! never enters and leaves a `⅋` through its two premises, that is, when
//! some switching keeps it. A switching cycle is a properly coloured
//! cycle. Unlinked literals are leaves and lie on no cycle, so the test
//! means the same on a partial structure.
//!
//! By Yeo's theorem, a graph without a properly coloured cycle has a
//! vertex that every component of the graph without it meets in edges of
//! one colour only. Such a vertex lies on no properly coloured cycle, and
//! deleting it keeps the property. Repeating the deletion until it stops
//! decides the question exactly: everything goes, or a properly coloured
//! cycle is left.
//!
//! With this colouring the deletion condition needs no colours. A vertex
//! that is not a `⅋` has an edge of its own colour to every neighbour, so
//! it is deletable when every incident edge is a bridge, an edge whose
//! removal disconnects its two ends. A `⅋` is deletable when its parent
//! edge is a bridge or absent, since its premise edges share a colour.
//! One depth-first search per round finds the bridges.

use super::{NONE, VertexId};
use crate::linear::occurrences::{Forest, OccId, OccSet};
use crate::linear::sequents::Kind;

/// The coloured structure graph in compressed sparse row layout: per
/// vertex, its edge to its parent or across its cut link first, then to
/// its children, and for a literal its axiom link last, with `NONE` while
/// it is unlinked.
#[derive(Clone, Debug)]
pub(super) struct Graph {
    /// Per vertex, where its slots start in `to`; one more entry holds the
    /// total. A vertex has three slots at most and a structure fewer than
    /// `u32::MAX / 3` vertices (`super::MOST`), so the total fits.
    start: Box<[u32]>,
    /// Per slot, the other end of the edge.
    to: Box<[u32]>,
    /// The edges every switching keeps: two per `⊗`, one per `⅋` and one
    /// per cut link.
    switched_tree_edges: usize,
    /// The vertices with slots: every occurrence but those of a cut
    /// formula's tree above no cut link's end.
    vertices: usize,
}

/// Working memory for the correctness tests, sized for one structure, so
/// that a test allocates nothing.
///
/// [`ProofStructure::scratch`] makes one, and
/// [`ProofStructure::is_acyclic`] takes it.
///
/// [`ProofStructure::scratch`]: super::ProofStructure::scratch
/// [`ProofStructure::is_acyclic`]: super::ProofStructure::is_acyclic
#[derive(Clone, Debug)]
pub struct Scratch {
    /// The vertices the deletion procedure has removed.
    deleted: OccSet,
    /// The vertices deleted when the procedure got stuck, kept while a
    /// cycle is being isolated among the others.
    stuck: OccSet,
    /// Per slot, whether the edge is taken out of the graph, which the
    /// witness searches use.
    removed: Box<[bool]>,
    /// Per vertex, its discovery time in the last search, or `NONE`.
    disc: Box<[u32]>,
    /// Per vertex, the least discovery time it reaches through its
    /// search-tree descendants and one back edge.
    low: Box<[u32]>,
    /// Per vertex, its parent in the search tree, or `NONE` for a root.
    dfs_parent: Box<[u32]>,
    /// Per vertex, whether the edge to its search-tree parent is a bridge.
    bridge: Box<[bool]>,
    /// Per vertex, the root of the search tree that reached it.
    component: Box<[u32]>,
    /// The search stack: a vertex and its next slot to look at.
    stack: Vec<(u32, u32)>,
}

impl Scratch {
    /// Returns working memory for a graph.
    fn new(graph: &Graph) -> Self {
        let n = graph.start.len() - 1;
        Self {
            deleted: OccSet::empty(n),
            stuck: OccSet::empty(n),
            removed: vec![false; graph.to.len()].into_boxed_slice(),
            disc: vec![NONE; n].into_boxed_slice(),
            low: vec![NONE; n].into_boxed_slice(),
            dfs_parent: vec![NONE; n].into_boxed_slice(),
            bridge: vec![false; n].into_boxed_slice(),
            component: vec![NONE; n].into_boxed_slice(),
            stack: Vec::with_capacity(n),
        }
    }

    /// Returns whether the scratch is sized for `graph`.
    pub(super) fn fits(&self, graph: &Graph) -> bool {
        self.removed.len() == graph.to.len() && self.disc.len() == graph.len()
    }

    /// Returns whether a vertex is deleted.
    fn is_deleted(&self, v: u32) -> bool {
        self.deleted.contains(OccId::new(v))
    }

    /// Makes every vertex present again.
    pub(super) fn restore(&mut self) {
        self.deleted.clear();
    }

    /// Takes a vertex out of the graph.
    pub(super) fn delete(&mut self, v: OccId) {
        self.deleted.insert(v);
    }

    /// Returns whether the last search reached the vertex.
    pub(super) fn reached(&self, v: OccId) -> bool {
        self.disc[v.index()] != NONE
    }

    /// Returns the root of the search tree that reached the vertex in the
    /// last search.
    pub(super) fn component(&self, v: OccId) -> OccId {
        OccId::new(self.component[v.index()])
    }

    /// Returns whether the edge between two adjacent vertices is a bridge
    /// according to the last search, which must have reached them.
    pub(super) fn is_bridge(&self, v: u32, w: u32) -> bool {
        debug_assert!(
            self.reached(OccId::new(v)) && self.reached(OccId::new(w)),
            "the last search did not reach both ends"
        );
        (self.dfs_parent[w as usize] == v && self.bridge[w as usize])
            || (self.dfs_parent[v as usize] == w && self.bridge[v as usize])
    }
}

impl Graph {
    /// Builds the graph of a forest, with every literal unlinked: over the
    /// occurrences `live` holds, or every one, and the cut links `cuts`
    /// between them.
    pub(super) fn new(
        forest: &Forest,
        live: Option<&OccSet>,
        cuts: &[(VertexId, VertexId)],
    ) -> Self {
        let n = forest.len();
        let mut start = Vec::with_capacity(n + 1);
        let mut to = Vec::with_capacity(3 * n);
        let mut switched_tree_edges = cuts.len();
        let mut across = Vec::new();
        if !cuts.is_empty() {
            across = vec![NONE; n];
            for &(x, y) in cuts {
                across[x.index()] = y.get();
                across[y.index()] = x.get();
            }
        }
        let mut vertices = 0;
        for o in forest.ids() {
            start.push(to.len() as u32);
            if live.is_some_and(|live| !live.contains(o)) {
                continue;
            }
            vertices += 1;
            match across.get(o.index()) {
                Some(&end) if end != NONE => to.push(end),
                _ => {
                    if let Some(p) = forest.parent(o) {
                        to.push(p.get());
                    }
                }
            }
            to.extend(forest.children(o).map(OccId::get));
            match forest.kind(o) {
                Kind::Tensor => switched_tree_edges += 2,
                Kind::Par => switched_tree_edges += 1,
                Kind::Atom
                | Kind::DualAtom
                | Kind::One
                | Kind::Bot
                | Kind::Top
                | Kind::Zero
                | Kind::With
                | Kind::Plus
                | Kind::Bang
                | Kind::Quest
                | Kind::Forall
                | Kind::Exists => to.push(NONE),
            }
        }
        start.push(to.len() as u32);
        Self {
            start: start.into_boxed_slice(),
            to: to.into_boxed_slice(),
            switched_tree_edges,
            vertices,
        }
    }

    /// Returns the number of vertices with slots.
    pub(super) fn vertices(&self) -> usize {
        self.vertices
    }

    /// Returns working memory for this graph.
    pub(super) fn scratch(&self) -> Scratch {
        Scratch::new(self)
    }

    /// Returns the number of vertices.
    fn len(&self) -> usize {
        self.start.len() - 1
    }

    /// Returns the slots of a vertex.
    fn slots(&self, v: u32) -> std::ops::Range<usize> {
        self.start[v as usize] as usize..self.start[v as usize + 1] as usize
    }

    /// Returns the slot of a literal's axiom link.
    fn axiom_slot(&self, l: u32) -> usize {
        self.start[l as usize + 1] as usize - 1
    }

    /// Returns the slot at `w` of the edge to `v`.
    fn twin(&self, v: u32, w: u32) -> usize {
        self.slots(w)
            .find(|&s| self.to[s] == v)
            .expect("the edge exists at both ends")
    }

    /// Adds the axiom link between two literals.
    pub(super) fn link(&mut self, x: u32, y: u32) {
        self.to[self.axiom_slot(x)] = y;
        self.to[self.axiom_slot(y)] = x;
    }

    /// Removes the axiom link between two literals.
    pub(super) fn unlink(&mut self, x: u32, y: u32) {
        self.to[self.axiom_slot(x)] = NONE;
        self.to[self.axiom_slot(y)] = NONE;
    }

    /// Takes the cut link at its end `x` out of the graph for the searches
    /// with `scratch` from now on.
    pub(super) fn remove_cut(&self, scratch: &mut Scratch, x: u32) {
        let slot = self.slots(x).start;
        let y = self.to[slot];
        let twin = self.twin(x, y);
        scratch.removed[slot] = true;
        scratch.removed[twin] = true;
    }

    /// Returns the number of edges every switching keeps when the
    /// structure has `links` axiom links.
    pub(super) fn switched_edges(&self, links: usize) -> usize {
        self.switched_tree_edges + links
    }

    /// Searches depth-first from each of `roots` in turn, over the vertices
    /// not deleted and the edges not removed. Returns the number of roots
    /// that reached something new, which is the number of connected
    /// components among the vertices reached.
    ///
    /// For every vertex reached, the search records its discovery time,
    /// its search-tree parent, the root that reached it, and whether its
    /// edge to that parent is a bridge.
    pub(super) fn search(
        &self,
        scratch: &mut Scratch,
        roots: impl IntoIterator<Item = u32>,
    ) -> u32 {
        debug_assert_eq!(
            scratch.removed.len(),
            self.to.len(),
            "a scratch of another graph"
        );
        scratch.disc.fill(NONE);
        let mut time = 0;
        let mut trees = 0;
        for r in roots {
            if scratch.is_deleted(r) || scratch.disc[r as usize] != NONE {
                continue;
            }
            trees += 1;
            self.discover(scratch, r, NONE, r, &mut time);
            while let Some(&(v, next)) = scratch.stack.last() {
                if next < self.start[v as usize + 1] {
                    scratch.stack.last_mut().unwrap().1 = next + 1;
                    let w = self.to[next as usize];
                    if w == NONE
                        || scratch.removed[next as usize]
                        || scratch.is_deleted(w)
                        || w == scratch.dfs_parent[v as usize]
                    {
                        continue;
                    }
                    if scratch.disc[w as usize] == NONE {
                        self.discover(scratch, w, v, r, &mut time);
                    } else {
                        let (lv, dw) = (scratch.low[v as usize], scratch.disc[w as usize]);
                        scratch.low[v as usize] = lv.min(dw);
                    }
                } else {
                    scratch.stack.pop();
                    let p = scratch.dfs_parent[v as usize];
                    if p != NONE {
                        let (lp, lv) = (scratch.low[p as usize], scratch.low[v as usize]);
                        scratch.low[p as usize] = lp.min(lv);
                        scratch.bridge[v as usize] = lv > scratch.disc[p as usize];
                    }
                }
            }
        }
        trees
    }

    /// Enters a vertex in the search: from `parent`, in the tree of `root`.
    fn discover(&self, scratch: &mut Scratch, v: u32, parent: u32, root: u32, time: &mut u32) {
        scratch.disc[v as usize] = *time;
        scratch.low[v as usize] = *time;
        *time += 1;
        scratch.dfs_parent[v as usize] = parent;
        scratch.component[v as usize] = root;
        scratch.bridge[v as usize] = false;
        scratch.stack.push((v, self.start[v as usize]));
    }

    /// Returns whether a vertex may be deleted according to the last
    /// search: it is a `⅋` whose parent edge is absent or a bridge, or any
    /// other vertex all of whose edges are bridges.
    fn deletable(&self, forest: &Forest, scratch: &Scratch, v: u32) -> bool {
        let present = |s: usize| {
            let w = self.to[s];
            w != NONE && !scratch.removed[s] && !scratch.is_deleted(w)
        };
        if forest.kind(OccId::new(v)) == Kind::Par {
            // A `⅋` has two premises and no axiom slot, so a third slot is
            // its parent edge, to its parent or across its cut link.
            let slots = self.slots(v);
            slots.len() < 3 || !present(slots.start) || scratch.is_bridge(v, self.to[slots.start])
        } else {
            self.slots(v)
                .all(|s| !present(s) || scratch.is_bridge(v, self.to[s]))
        }
    }

    /// Runs the deletion procedure on the vertices not yet deleted: in
    /// rounds, deletes every deletable vertex until none is. Returns
    /// whether every vertex went, which means the graph has no switching
    /// cycle. Otherwise the vertices left in place are those the procedure
    /// got stuck on, and a switching cycle runs among them. `None` when
    /// `stop` fired.
    ///
    /// It asks `stop` before each round. `stop` is a `dyn`, asked once a
    /// round. A generic function would be made in its caller's codegen
    /// unit, where `search` and `deletable`, which run per vertex, cannot
    /// be inlined into it.
    pub(super) fn acyclic(
        &self,
        forest: &Forest,
        scratch: &mut Scratch,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Option<bool> {
        let n = self.len();
        let mut remaining = n - scratch.deleted.len();
        while remaining > 0 {
            if stop(1) {
                return None;
            }
            self.search(scratch, 0..n as u32);
            let before = remaining;
            for v in 0..n as u32 {
                if !scratch.is_deleted(v) && self.deletable(forest, scratch, v) {
                    scratch.delete(OccId::new(v));
                    remaining -= 1;
                }
            }
            if remaining == before {
                return Some(false);
            }
        }
        Some(true)
    }

    /// Isolates one switching cycle among the vertices that
    /// [`acyclic`](Self::acyclic) got stuck on, in the call just before,
    /// and returns its vertices in order along the cycle. `None` when
    /// `stop`, which every deletion procedure asks, fired.
    ///
    /// Every edge among those vertices is taken out in turn, and kept out
    /// when a switching cycle survives without it. An edge found necessary
    /// stays necessary as edges go, so one pass leaves exactly one cycle.
    pub(super) fn cycle(
        &self,
        forest: &Forest,
        scratch: &mut Scratch,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Option<Vec<VertexId>> {
        let n = self.len();
        scratch.stuck.clone_from(&scratch.deleted);
        for v in 0..n as u32 {
            for s in self.slots(v) {
                let w = self.to[s];
                if w == NONE
                    || w < v
                    || scratch.removed[s]
                    || scratch.stuck.contains(OccId::new(v))
                    || scratch.stuck.contains(OccId::new(w))
                {
                    continue;
                }
                let t = self.twin(v, w);
                scratch.removed[s] = true;
                scratch.removed[t] = true;
                scratch.deleted.clone_from(&scratch.stuck);
                let Some(acyclic) = self.acyclic(forest, scratch, stop) else {
                    scratch.removed.fill(false);
                    return None;
                };
                if acyclic {
                    scratch.removed[s] = false;
                    scratch.removed[t] = false;
                } else {
                    scratch.stuck.clone_from(&scratch.deleted);
                }
            }
        }
        // What is left is one cycle: walk it from its first vertex.
        let first = (0..n as u32)
            .find(|&v| !scratch.stuck.contains(OccId::new(v)))
            .expect("a switching cycle is left");
        let mut cycle = Vec::new();
        let (mut previous, mut current) = (NONE, first);
        loop {
            cycle.push(VertexId(current));
            let next = self
                .slots(current)
                .map(|s| (s, self.to[s]))
                .find(|&(s, w)| {
                    w != NONE
                        && w != previous
                        && !scratch.removed[s]
                        && !scratch.stuck.contains(OccId::new(w))
                })
                .map(|(_, w)| w)
                .expect("every vertex of the cycle has two edges on it");
            if next == first {
                break;
            }
            (previous, current) = (current, next);
        }
        scratch.removed.fill(false);
        Some(cycle)
    }

    /// Returns the connected components of the switching that keeps the
    /// left premise of every `⅋`, in the order of their smallest vertex.
    ///
    /// Each component is given as the vertices in it that have no parent
    /// edge there: the roots, the right premises of `⅋` nodes, and of each
    /// cut link its end in a cut formula's tree.
    pub(super) fn parts(&self, forest: &Forest, scratch: &mut Scratch) -> Vec<Vec<VertexId>> {
        let n = self.len();
        scratch.restore();
        let vertex = |o: OccId| !self.slots(o.get()).is_empty();
        for p in forest
            .ids()
            .filter(|&p| forest.kind(p) == Kind::Par && vertex(p))
        {
            let r = forest.right(p).unwrap();
            scratch.removed[self.twin(r.get(), p.get())] = true;
            scratch.removed[self.slots(r.get()).start] = true;
        }
        self.search(scratch, 0..n as u32);
        scratch.removed.fill(false);
        let mut parts: Vec<(u32, Vec<VertexId>)> = Vec::new();
        for v in forest.ids().filter(|&v| vertex(v)) {
            // A cut link is named by its end in a cut formula's tree.
            let cut = match forest.parent(v) {
                None => forest.dual(v).is_none_or(|d| v < d),
                Some(p) if !vertex(p) => forest.dual(v).is_some_and(|d| v < d),
                Some(p) => forest.kind(p) == Kind::Par && forest.right(p) == Some(v),
            };
            if !cut {
                continue;
            }
            let label = scratch.component[v.index()];
            match parts.iter_mut().find(|(l, _)| *l == label) {
                Some((_, part)) => part.push(VertexId::of(v)),
                None => parts.push((label, vec![VertexId::of(v)])),
            }
        }
        parts.sort_by_key(|(label, _)| *label);
        parts.into_iter().map(|(_, part)| part).collect()
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::super::{Criterion, NetError, ProofStructure, VertexId};
    use crate::linear::occurrences::{Forest, OccId};
    use crate::linear::search::generate::{self, Rng, Rules};
    use crate::linear::sequents::{Kind, Sequent};

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

    /// Builds the structure of `input` with the links, or panics.
    fn net(input: &str, mix: bool, links: &[(u32, u32)]) -> ProofStructure {
        let s: Sequent = input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"));
        let links: Vec<(VertexId, VertexId)> = links.iter().map(|&(x, y)| (v(x), v(y))).collect();
        ProofStructure::from_links(
            Forest::new(&s).unwrap(),
            Criterion {
                mix,
                ..Criterion::MLL
            },
            &links,
        )
        .unwrap()
    }

    /// The Danos–Regnier criterion by brute force: every switching is
    /// built and tested for a cycle and for connectedness with a
    /// union-find. Returns whether every switching is acyclic and whether
    /// every switching is connected.
    #[expect(
        clippy::wildcard_enum_match_arm,
        reason = "a structure of MLL has no other parent"
    )]
    fn enumerate(net: &ProofStructure) -> (bool, bool) {
        let f = net.forest();
        let pars: Vec<OccId> = f.ids().filter(|&p| f.kind(p) == Kind::Par).collect();
        assert!(pars.len() <= 16, "too many switchings to enumerate");
        let (mut acyclic, mut connected) = (true, true);
        for switching in 0..1u32 << pars.len() {
            let keeps_left = |p: OccId| {
                let i = pars.iter().position(|&q| q == p).unwrap();
                switching & (1 << i) == 0
            };
            let mut parent: Vec<usize> = (0..f.len()).collect();
            fn find(parent: &mut [usize], mut x: usize) -> usize {
                while parent[x] != x {
                    x = parent[x];
                }
                x
            }
            let mut components = f.len();
            let mut cyclic = false;
            let mut join = |x: OccId, y: OccId| {
                let (a, b) = (find(&mut parent, x.index()), find(&mut parent, y.index()));
                if a == b {
                    cyclic = true;
                } else {
                    parent[a] = b;
                    components -= 1;
                }
            };
            for v in f.ids() {
                if let Some(p) = f.parent(v) {
                    let kept = match f.kind(p) {
                        Kind::Tensor => true,
                        Kind::Par => keeps_left(p) == (f.left(p) == Some(v)),
                        _ => unreachable!(),
                    };
                    if kept {
                        join(p, v);
                    }
                }
            }
            for &(x, y) in net.links() {
                join(x.occ(), y.occ());
            }
            acyclic &= !cyclic;
            connected &= components == 1;
        }
        (acyclic, connected)
    }

    /// Checks that a reported cycle is a switching cycle: a simple cycle of
    /// the graph that uses at most one premise edge of every `⅋`.
    fn check_cycle(net: &ProofStructure, cycle: &[VertexId]) {
        let f = net.forest();
        let cycle: Vec<OccId> = cycle.iter().map(|v| v.occ()).collect();
        assert!(cycle.len() >= 3, "{cycle:?}");
        let mut sorted = cycle.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(sorted.len(), cycle.len(), "simple: {cycle:?}");
        for i in 0..cycle.len() {
            let (a, b, c) = (
                cycle[(i + cycle.len() - 1) % cycle.len()],
                cycle[i],
                cycle[(i + 1) % cycle.len()],
            );
            let adjacent = f.parent(b) == Some(c)
                || f.parent(c) == Some(b)
                || net.partner(VertexId::of(b)) == Some(VertexId::of(c));
            assert!(adjacent, "{b:?} and {c:?} are not adjacent in {cycle:?}");
            if f.kind(b) == Kind::Par {
                assert!(
                    f.parent(a) != Some(b) || f.parent(c) != Some(b),
                    "{cycle:?} passes {b:?} through both premises"
                );
            }
        }
    }

    /// The classic nets: the axiom-tensor example is a net, a link below a
    /// `⊗` is a cycle, below a `⅋` it is a net, two separate axioms under a
    /// `⅋` are a net with Mix only, and a partial or empty structure is
    /// neither.
    #[test]
    fn classic_structures() {
        // ⊢ ~A, A ⊗ ~B, B: 0 ~A, 1 ⊗, 2 A, 3 ~B, 4 B.
        assert_eq!(
            net("A, A -o B |- B", false, &[(0, 2), (3, 4)]).is_correct(|_| false),
            Ok(())
        );
        let partial = net("A, A -o B |- B", false, &[(0, 2)]);
        assert_eq!(
            partial.is_correct(|_| false),
            Err(NetError::Unlinked { vertex: v(4) })
        );
        assert!(partial.is_acyclic(&mut partial.scratch()));
        // ⊢ A ⊗ ~A: 0 ⊗, 1 A, 2 ~A.
        let cyclic = net("|- A * ~A", true, &[(1, 2)]);
        let Err(NetError::SwitchingCycle { cycle }) = cyclic.is_correct(|_| false) else {
            panic!("a link below a ⊗ is a switching cycle");
        };
        check_cycle(&cyclic, &cycle);
        assert_eq!(cycle, [v(0), v(1), v(2)]);
        assert!(!cyclic.is_acyclic(&mut cyclic.scratch()));
        // ⊢ A ⅋ ~A: the cycle through both premises does not count.
        assert_eq!(
            net("|- A par ~A", false, &[(1, 2)]).is_correct(|_| false),
            Ok(())
        );
        // ⊢ A ⅋ B, ~A, ~B: 0 ⅋, 1 A, 2 B, 3 ~A, 4 ~B.
        assert_eq!(
            net("|- A par B, ~A, ~B", false, &[(1, 3), (2, 4)]).is_correct(|_| false),
            Err(NetError::Disconnected {
                parts: vec![vec![v(0), v(3)], vec![v(2), v(4)]]
            })
        );
        assert_eq!(
            net("|- A par B, ~A, ~B", true, &[(1, 3), (2, 4)]).is_correct(|_| false),
            Ok(())
        );
        // ⊢ (A ⅋ ~A) ⅋ (B ⅋ ~B): 0 ⅋, 1 ⅋, 2 A, 3 ~A, 4 ⅋, 5 B, 6 ~B. The
        // switching that keeps every left premise drops the edge from 0 to
        // 4, which leaves 4, 5 and 6 apart.

        assert_eq!(
            net("|- (A par ~A) par (B par ~B)", false, &[(2, 3), (5, 6)]).is_correct(|_| false),
            Err(NetError::Disconnected {
                parts: vec![vec![v(0), v(3)], vec![v(4), v(6)]]
            })
        );
        // ⊢ A ⊗ B, ~A ⊗ ~B: 0 ⊗, 1 A, 2 B, 3 ⊗, 4 ~A, 5 ~B: a cycle through
        // both tensors.
        let cyclic = net("|- A * B, ~A * ~B", true, &[(1, 4), (2, 5)]);
        let Err(NetError::SwitchingCycle { cycle }) = cyclic.is_correct(|_| false) else {
            panic!("two tensors joined twice are a switching cycle");
        };
        check_cycle(&cyclic, &cycle);
        assert_eq!(cycle.len(), 6);
        assert_eq!(
            net("|-", true, &[]).is_correct(|_| false),
            Err(NetError::Empty)
        );
    }

    /// The criterion agrees with the brute-force enumeration of switchings
    /// on random linkings of random sequents, with and without Mix,
    /// partial and complete, and every witness it names is one.
    #[test]
    fn agrees_with_enumeration() {
        let mut cases = (0, 0, 0);
        for (seed, mix) in [(1, false), (2, true)] {
            let mut rng = Rng::new(seed);
            for i in 0..200 {
                // Sequents that need Mix give disconnected structures when
                // Mix is not allowed; mutants give partial and cyclic ones.
                let rules = Rules {
                    units: false,
                    additives: false,
                    mix: i % 3 == 2,
                    exponentials: false,
                };
                let budget = 2 + rng.below(9);
                let mut formulas = generate::provable(&mut rng, rules, 3, budget).formulas;
                if i % 2 == 1 {
                    generate::mutate(&mut rng, &mut formulas, 3);
                }
                let text = generate::sequent(&formulas);
                let s: Sequent = text.parse().unwrap();
                let forest = Forest::new(&s).unwrap();
                // A random pairing per atom, as far as the counts allow.
                let mut pairs = Vec::new();
                for a in 0..s.atom_names().len() {
                    let atom = crate::linear::sequents::Atom::new(a as u32);
                    let vars = forest.literals(atom, crate::linear::occurrences::Sign::Atom);
                    let mut duals = forest
                        .literals(atom, crate::linear::occurrences::Sign::Dual)
                        .to_vec();
                    for k in (1..duals.len()).rev() {
                        duals.swap(k, rng.below(k + 1));
                    }
                    pairs.extend(vars.iter().copied().zip(duals));
                }
                for k in (1..pairs.len()).rev() {
                    pairs.swap(k, rng.below(k + 1));
                }
                let mut net = ProofStructure::new(
                    forest,
                    Criterion {
                        mix,
                        ..Criterion::MLL
                    },
                )
                .unwrap();
                let mut scratch = net.scratch();
                for &(x, y) in &pairs {
                    net.link(VertexId::of(x), VertexId::of(y)).unwrap();
                    let (acyclic, _) = enumerate(&net);
                    assert_eq!(
                        net.is_acyclic(&mut scratch),
                        acyclic,
                        "{text:?} with {:?}",
                        net.links()
                    );
                }
                let (acyclic, connected) = enumerate(&net);
                let verdict = net.is_correct(|_| false);
                let expected =
                    !net.forest().is_empty() && net.is_complete() && acyclic && (mix || connected);
                assert_eq!(
                    verdict.is_ok(),
                    expected,
                    "{text:?} with {:?}: {verdict:?}",
                    net.links()
                );
                match &verdict {
                    Ok(()) => cases.0 += 1,
                    Err(NetError::SwitchingCycle { cycle }) => {
                        check_cycle(&net, cycle);
                        cases.1 += 1;
                    }
                    Err(NetError::Disconnected { parts }) => {
                        let f = net.forest();
                        let switched = f.ids().filter(|&v| f.kind(v) == Kind::Tensor).count() * 2
                            + f.ids().filter(|&v| f.kind(v) == Kind::Par).count()
                            + net.links().len();
                        assert_eq!(parts.len(), f.len() - switched, "{text:?}");
                        for &r in f.roots() {
                            assert_eq!(
                                parts
                                    .iter()
                                    .filter(|p| p.contains(&VertexId::of(r)))
                                    .count(),
                                1,
                                "{text:?}"
                            );
                        }
                        cases.2 += 1;
                    }
                    Err(NetError::Unlinked { .. }) => {}
                    Err(e) => panic!("{text:?}: {e}"),
                }
            }
        }
        assert!(cases.0 > 20 && cases.1 > 20 && cases.2 > 5, "{cases:?}");
    }
}