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

//! Sequents of intuitionistic linear logic as their author wrote them.
//!
//! An [`IllSequent`] has its hypotheses in the order written and exactly
//! one goal, built from the connectives of intuitionistic linear logic
//! alone. It is lowered once to the one-sided forest the engines, the
//! checker and the views work on, and the side of every occurrence is
//! recorded at the lowering.

use super::reading::{Reading, Side};
use super::{Forest, OccId};
use crate::linear::sequents::Sequent;
use crate::{Error, Limits};
use std::fmt::{Display, Formatter, Result as FmtResult};

/// A sequent of intuitionistic linear logic, `Γ ⊢ A`: its hypotheses in
/// the order written and exactly one goal, every formula built from `⊗`,
/// `⊸`, `&`, `⊕`, `!`, `1`, `⊤`, `0` and atoms.
///
/// To read intuitionistic input, parse it as an `IllSequent` and prove its
/// [`sequent`](Self::sequent) in
/// [`Mode::INTUITIONISTIC`](crate::linear::Mode::INTUITIONISTIC). A
/// classical symbol in the text is then refused with a hint of what to
/// write instead. The same text parsed as a [`Sequent`] is read
/// intuitionistically only when it is proved. If its one-sided form has an
/// intuitionistic reading, it is proved as that reading: `~(A * ~B), A |-
/// B` is `A ⊸ B, A ⊢ B`. If it has none, the proof is refused with a
/// [`ShapeError`](crate::linear::ShapeError), which may name a subformula
/// only by its number.
///
/// There are three ways to make one:
/// - from text, with [`parse_within`](Self::parse_within) (or
///   [`str::parse`]), which reads intuitionistic syntax alone;
/// - from its JSON form, with the feature `serialize`;
/// - from a one-sided sequent, with
///   [`read_one_sided`](Self::read_one_sided), which takes the sides from
///   the one-sided formulas where they decide them and refuses the
///   sequent where they do not.
///
/// Each lowers the sequent once to the [`Forest`] the engines take and
/// records the side of every occurrence. [`reading`](Self::reading) lends
/// the [`Reading`] over those sides. It prints the sequent two-sided as
/// written, and it is the reading [`Reading::new`] gives of the same
/// forest.
///
/// # JSON
///
/// With the feature `serialize`, the document `{"version": 5, "terms":
/// […], "atoms": […], "hypotheses": […], "goal": n}`:
/// - `terms`, an arena of intuitionistic formulas, each a term
///   `{"V": atom}`, `"1"`, `"0"`, `"⊤"`, `{"!": t}`, or `{"⊗": [t, u]}`
///   with `⊗`, `⊸`, `&` or `⊕`, every operand an index below its own;
/// - `atoms`, the atom names;
/// - `hypotheses` and `goal`, the roots by index.
///
/// A tag of classical linear logic (`D`, `⅋`, `?`, `⊥`) is refused as an
/// unknown variant.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::{Error, linear::{IllSequent, Mode, Options, Side, prove}};
///
/// let sequent: IllSequent = "A -o B, A |- B".parse()?;
/// assert_eq!(sequent.to_string(), "A ⊸ B, A ⊢ B");
/// assert_eq!(sequent.sequent().to_string(), "⊢ A ⊗ ~B, ~A, B");
/// let reading = sequent.reading();
/// assert_eq!(reading.position(sequent.goal()), Side::Output);
///
/// let outcome = prove(sequent.sequent(), Mode::INTUITIONISTIC, &Options::default())?;
/// assert!(outcome.verdict.proof().is_some());
///
/// // A symbol of classical linear logic is refused with a hint.
/// let Err(Error::Parse(error)) = "|- A par B".parse::<IllSequent>() else {
///     panic!("par is no intuitionistic syntax");
/// };
/// assert_eq!(error.span, 5..8);
/// assert!(error.to_string().contains("write ~A par B as A -o B"));
/// # Ok::<(), Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct IllSequent {
    /// The one-sided lowering, laid out as the forest the engines take.
    forest: Forest,
    /// Per occurrence, the side it stands on as written.
    position: Box<[Side]>,
    /// The goal: the one root on the output side.
    goal: OccId,
}

impl IllSequent {
    /// Lowers a sequent written two-sided in intuitionistic syntax, and
    /// records the side of every occurrence.
    ///
    /// The roots after the first `antecedents` are the goal, and there
    /// must be exactly one. Every other occurrence takes its parent's
    /// side, except the antecedent of an implication, which takes the
    /// other side. An implication is a `⅋` on the goal's side or a `⊗` on
    /// the hypotheses' side, and its left factor is the antecedent. This
    /// is exact because a written `A ⊸ B` is lowered to `A⊥ ⅋ B` and
    /// intuitionistic syntax writes no other `⅋`.
    #[cfg(any(feature = "parse", feature = "serialize"))]
    pub(crate) fn lowered(sequent: Sequent, limits: &Limits) -> Result<Self, Error> {
        use super::reading::ShapeError;
        use crate::linear::sequents::Kind;
        let antecedents = sequent.antecedents().unwrap_or(0) as usize;
        let succedents = sequent.roots().len().saturating_sub(antecedents);
        if succedents != 1 {
            return Err(Error::NotIntuitionistic(ShapeError::Succedents {
                count: succedents,
            }));
        }
        let forest = Forest::from_owned(sequent, limits)?;
        let goal = forest.roots()[antecedents];
        let mut position = vec![Side::Input; forest.len()].into_boxed_slice();
        position[goal.index()] = Side::Output;
        // Preorder: a parent's side is known before its children's.
        for o in forest.ids() {
            let side = position[o.index()];
            let implication = matches!(
                (forest.kind(o), side),
                (Kind::Par, Side::Output) | (Kind::Tensor, Side::Input)
            );
            if let Some(left) = forest.left(o) {
                position[left.index()] = if implication { !side } else { side };
            }
            if let Some(right) = forest.right(o) {
                position[right.index()] = side;
            }
        }
        let lowered = Self {
            forest,
            position,
            goal,
        };
        debug_assert!(
            Reading::new(&lowered.forest).is_ok_and(|reading| reading.goal() == goal
                && lowered
                    .forest
                    .ids()
                    .all(|o| reading.position(o) == lowered.position[o.index()])),
            "the recorded sides are the reading's"
        );
        Ok(lowered)
    }

    /// Reads a one-sided sequent as intuitionistic, as [`Reading::new`]
    /// reads its forest.
    ///
    /// The goal is the formula right of `⊢` where the sequent records its
    /// sides, else the one root that can be the goal. Every formula is
    /// read in the position its one-sided form decides: `⊢ A ⊗ ~B, ~A, B`
    /// (the text `~(A * ~B), A |- B`) is read as `A ⊸ B, A ⊢ B`.
    ///
    /// # Errors
    ///
    /// [`Error::NotIntuitionistic`] with the [`ShapeError`](crate::linear::ShapeError) of a sequent
    /// that has no intuitionistic reading or more than one, and the
    /// errors of [`Forest::from_owned`] past the limits.
    pub fn read_one_sided(sequent: Sequent, limits: &Limits) -> Result<Self, Error> {
        let forest = Forest::from_owned(sequent, limits)?;
        let (position, goal) = Reading::new(&forest)
            .map_err(Error::NotIntuitionistic)?
            .into_parts();
        Ok(Self {
            forest,
            position,
            goal,
        })
    }

    /// Returns the one-sided sequent the engines take, with `A ⊸ B` as
    /// `A⊥ ⅋ B`. Of a parsed sequent it is the hypotheses negated, then
    /// the goal.
    pub fn sequent(&self) -> &Sequent {
        self.forest.sequent()
    }

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

    /// Returns the one-sided sequent, for a caller that hands it on.
    pub fn into_sequent(self) -> Sequent {
        self.forest.sequent().clone()
    }

    /// Returns the goal's occurrence.
    pub fn goal(&self) -> OccId {
        self.goal
    }

    /// Returns the reading over the recorded sides, in constant time. It
    /// gives the position of every occurrence and prints the formulas and
    /// the sequent as written.
    pub fn reading(&self) -> Reading<'_> {
        Reading::of_parts(&self.forest, &self.position, self.goal, false)
    }
}

impl PartialEq for IllSequent {
    /// Two sequents are equal when they are written alike: the same
    /// formulas on the same sides, however their arenas share subterms.
    fn eq(&self, other: &Self) -> bool {
        let (a, b) = (&self.forest, &other.forest);
        fn name(forest: &Forest, o: OccId) -> Option<&str> {
            forest.atom(o).map(|x| forest.sequent().atom_name(x))
        }
        a.len() == b.len()
            && a.roots() == b.roots()
            && self.goal == other.goal
            && self.position == other.position
            && a.ids()
                .all(|o| a.kind(o) == b.kind(o) && name(a, o) == name(b, o))
    }
}

impl Eq for IllSequent {}

impl Display for IllSequent {
    /// Writes the sequent two-sided, as it was written up to spacing and
    /// brackets: `A ⊸ B, A ⊢ B`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        self.reading().fmt(f)
    }
}

#[cfg(feature = "parse")]
impl IllSequent {
    /// Parses a sequent of intuitionistic linear logic, such as
    /// `A -o B, A |- B`.
    ///
    /// The syntax is the one [`Sequent`] reads, without the symbols of
    /// classical linear logic. A `~`, `^`, `⅋` (`par`, `|`), `?` or `⊥`
    /// (`bot`) is a parse error whose [`hint`](crate::ParseError::hint)
    /// says what to write instead. Exactly one formula stands right of
    /// `|-`, and the hypotheses keep the order written. The text is
    /// refused at the first term past `limits.occurrences`, as
    /// [`Sequent::parse_within`] refuses it.
    ///
    /// Needs the cargo feature `parse` (on by default).
    ///
    /// # Errors
    ///
    /// [`Error::Parse`] for text that is no intuitionistic sequent, at the
    /// first place that cannot go on one; [`Error::NotIntuitionistic`]
    /// with [`ShapeError::Succedents`](crate::linear::ShapeError::Succedents) for another number of formulas
    /// right of `|-` than one; and the refusals of
    /// [`Sequent::parse_within`].
    pub fn parse_within(text: &str, limits: &Limits) -> Result<Self, Error> {
        let sequent = match Sequent::parse_within(text, limits) {
            Ok(sequent) => sequent,
            // A classical symbol before the place the parser stopped at
            // is the first thing wrong.
            Err(Error::Parse(error)) => {
                return Err(crate::linear::parse::classical(text, error.span.start)
                    .map_or(Error::Parse(error), Error::from));
            }
            Err(error) => return Err(error),
        };
        if let Some(error) = crate::linear::parse::classical(text, text.len()) {
            return Err(error.into());
        }
        Self::lowered(sequent, limits)
    }
}

#[cfg(feature = "parse")]
impl std::str::FromStr for IllSequent {
    type Err = Error;

    /// Parses a sequent as [`IllSequent::parse_within`] does, within the
    /// default [`Limits`].
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_within(s, &Limits::default())
    }
}

/// How a front end reads the text of a sequent in an intuitionistic mode.
///
/// # JSON
///
/// With the feature `serialize`, its name: `"strict"` or `"one-sided"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
pub enum IllSyntax {
    /// Intuitionistic syntax alone ([`IllSequent::parse_within`]): a
    /// symbol of classical linear logic is refused with a hint.
    #[default]
    Strict,
    /// The syntax of classical linear logic. The text is lowered to a
    /// one-sided sequent, which is then read as intuitionistic
    /// ([`IllSequent::read_one_sided`]): `~(A * ~B), A |- B` is
    /// `A ⊸ B, A ⊢ B`.
    OneSided,
}

/// How a front end reads its input.
///
/// # JSON
///
/// With the feature `serialize`, an object with a key per field, a
/// missing one taking its default and a misspelt one refused.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct InputOptions {
    /// How the text of an intuitionistic sequent is read.
    pub intuitionistic: IllSyntax,
}

impl InputOptions {
    /// The default reading of an intuitionistic sequent's text: its own
    /// syntax alone.
    pub const DEFAULT_INTUITIONISTIC: IllSyntax = IllSyntax::Strict;

    /// Returns the options with another
    /// [`intuitionistic`](Self::intuitionistic).
    #[must_use]
    pub const fn with_intuitionistic(self, intuitionistic: IllSyntax) -> Self {
        Self { intuitionistic }
    }
}

impl Default for InputOptions {
    /// Returns the defaults the constants name.
    fn default() -> Self {
        Self {
            intuitionistic: Self::DEFAULT_INTUITIONISTIC,
        }
    }
}

#[cfg(all(test, feature = "parse"))]
mod tests {
    use super::*;
    use crate::errors::ParseError;
    use crate::linear::occurrences::ShapeError;
    use crate::linear::search::generate::{self, IllRules, Rng};
    use crate::linear::sequents::notation::TEXT;
    use crate::linear::{Mode, search};

    /// The text of generated provable intuitionistic sequents, of every
    /// rule set, `per` of each.
    fn generated(seed: u64, per: usize) -> Vec<String> {
        let mut texts = Vec::new();
        for (i, rules) in IllRules::ALL.into_iter().enumerate() {
            let mut rng = Rng::new(seed + i as u64);
            for _ in 0..per {
                let budget = 2 + rng.below(10);
                let ill = generate::ill(&mut rng, rules, 3, budget);
                texts.push(generate::two_sided(&ill.hypotheses, &ill.goal));
            }
        }
        texts
    }

    /// Returns the parse error of `text`, which the strict parser refuses.
    fn refused(text: &str) -> ParseError {
        match text.parse::<IllSequent>() {
            Err(Error::Parse(error)) => *error,
            other => panic!("{text:?}: {other:?}"),
        }
    }

    /// Every symbol of classical linear logic is refused where it stands,
    /// with a hint of what to write instead; a syntax error before it is
    /// reported first; names that only contain a keyword are atoms; and
    /// another number of goals than one is refused.
    #[test]
    fn the_strict_parser_refuses_classical_symbols() {
        for (text, at, hint) in [
            ("~(A * ~B), A |- B", 0..1, "no negation"),
            ("A^ |- B", 1..2, "no negation"),
            ("|- A par B", 5..8, "no par"),
            ("|- A ⅋ B", 5..8, "no par"),
            ("|- A | B", 5..6, "no par"),
            ("?A |- B", 0..1, "no ?"),
            ("|- bot", 3..6, "no bot"),
            ("⊥ |- A", 0..3, "no bot"),
        ] {
            let error = refused(text);
            assert_eq!(error.span, at, "{text:?}");
            assert!(
                error.hint.is_some_and(|h| h.contains(hint)),
                "{text:?}: {error}"
            );
            assert!(error.to_string().contains(hint), "{error}");
        }
        // The `bot` after an implication written without a space, as the
        // parser cuts its tokens; the turnstile before an atom is no par.
        assert_eq!(refused("A -obot |- B").span, 4..7);
        assert_eq!(refused("(A -obot) -obot |- A").span, 5..8);
        let sequent: IllSequent = "A |-obot".parse().unwrap();
        assert_eq!(sequent.to_string(), "A ⊢ obot");
        // A turnstile where none can stand is the parser's error, at its `-`.
        for text in ["A |- B |- C", "(A |- B)"] {
            let error = refused(text);
            assert_eq!(error.hint, None, "{text:?}");
            assert!(text[error.span.start..].starts_with('-'), "{text:?}");
        }
        // The parser's own error comes first where it is earlier.
        let error = refused("A * , ~B |- C");
        assert_eq!((error.span, error.hint), (4..5, None));
        // The `~` before the parser's error is the first thing wrong.
        assert_eq!(refused("~A * , B |- C").span, 0..1);
        let sequent: IllSequent = "bottom, parity |- bottom ⊗ parity".parse().unwrap();
        assert_eq!(sequent.to_string(), "bottom, parity ⊢ bottom ⊗ parity");
        for (text, count) in [("A |- B, C", 2), ("A |-", 0)] {
            assert!(
                matches!(
                    text.parse::<IllSequent>(),
                    Err(Error::NotIntuitionistic(ShapeError::Succedents { count: c })) if c == count
                ),
                "{text:?}"
            );
        }
    }

    /// The explicit reading of a one-sided sequent reads what the
    /// one-sided formulas decide and refuses the rest.
    #[test]
    fn a_one_sided_sequent_is_read_explicitly() {
        let limits = Limits::default();
        let read = |text: &str| {
            let sequent: Sequent = text.parse().unwrap();
            IllSequent::read_one_sided(sequent, &limits)
        };
        assert_eq!(
            read("~(A * ~B), A |- B").unwrap().to_string(),
            "A ⊸ B, A ⊢ B"
        );
        assert!(matches!(
            read("|- A par B"),
            Err(Error::NotIntuitionistic(ShapeError::Formula { .. }))
        ));
        let mut unsided: Sequent = "|- 0, top".parse().unwrap();
        unsided.antecedents = None;
        assert!(matches!(
            IllSequent::read_one_sided(unsided, &limits),
            Err(Error::NotIntuitionistic(ShapeError::Undetermined { .. }))
        ));
    }

    /// The sides recorded at lowering are the reading's, on every
    /// sequent lowered: the generated ones and those whose units stand on
    /// either side, where the one-sided form alone does not say.
    #[test]
    fn the_recorded_sides_are_the_readings() {
        let units = [
            "top |- 0",
            "0 |- top",
            "top, 0 |- top & 0",
            "(top -o 0) -o top |- 0 + top",
            "!(0 -o top), 1 |- (1 -o top) * 0",
        ];
        let texts = generated(4000, 20);
        for text in units
            .iter()
            .copied()
            .chain(texts.iter().map(String::as_str))
        {
            let sequent: IllSequent = text.parse().unwrap_or_else(|e| panic!("{text:?}: {e}"));
            let reading = Reading::new(sequent.forest()).unwrap();
            assert_eq!(reading.goal(), sequent.goal(), "{text:?}");
            let recorded = sequent.reading();
            for o in sequent.forest().ids() {
                assert_eq!(
                    reading.position(o),
                    recorded.position(o),
                    "{text:?} at {o:?}"
                );
            }
            // A cut on the goal as written, and on formulas of units,
            // records its two occurrences as the reading of the sequent
            // with its cut formulas reads them.
            #[cfg(feature = "interactive")]
            {
                use crate::{
                    Limits,
                    linear::{CutFormula, InputOptions, Interactive},
                };
                let limits = Limits::default();
                let goal = recorded.formula(recorded.goal()).to_string();
                let mut session =
                    Interactive::new(sequent.sequent(), Mode::INTUITIONISTIC).unwrap();
                let mut open = session.goals().next().unwrap();
                for cut in [goal.as_str(), "top -o 0", "0 * top"] {
                    let len = session.goal(open).unwrap().len();
                    let formula = CutFormula::parse_within(
                        cut,
                        Mode::INTUITIONISTIC,
                        &InputOptions::default(),
                        &limits,
                    )
                    .unwrap();
                    // Every formula goes to the second premise, the goal
                    // with them.
                    open = session.cut(open, &formula, &[], &limits).unwrap()[1];
                    assert_eq!(session.goal(open).unwrap().len(), len + 1);
                }
                let forest = session.forest();
                let reading = Reading::new(forest).unwrap();
                let recorded = session.reading().unwrap();
                assert_eq!(forest.cut_pairs().len(), 3);
                for o in forest.ids() {
                    assert_eq!(
                        reading.position(o),
                        recorded.position(o),
                        "{text:?} at {o:?}"
                    );
                }
            }
        }
    }

    /// A parsed sequent prints back to itself: the print parses to the
    /// same sequent, sides included.
    #[test]
    fn a_parsed_sequent_prints_back_to_itself() {
        for text in generated(4100, 20) {
            let sequent: IllSequent = text.parse().unwrap_or_else(|e| panic!("{text:?}: {e}"));
            let printed = sequent.to_string();
            let back: IllSequent = printed
                .parse()
                .unwrap_or_else(|e| panic!("{text:?} printed as {printed:?}: {e}"));
            assert_eq!(back, sequent, "{text:?} printed as {printed:?}");
        }
    }

    /// Every inference of every proof found prints as an intuitionistic
    /// sequent, which parses back to the same formulas on the same sides.
    #[test]
    fn every_inference_prints_as_an_intuitionistic_sequent() {
        let options = search::Options::default();
        let mut inferences = 0;
        #[cfg(feature = "interactive")]
        let mut cuts = 0;
        let mut proofs = vec![];
        for text in generated(4200, 6) {
            let sequent: IllSequent = text.parse().unwrap();
            let outcome = search::prove(sequent.sequent(), Mode::INTUITIONISTIC, &options).unwrap();
            if let Some(proof) = outcome.verdict.proof() {
                proofs.push((text, proof.clone()));
            }
        }
        // And proofs with cuts of the same sequents.
        #[cfg(feature = "interactive")]
        {
            let found: Vec<_> = proofs
                .iter()
                .map(|(_, p)| (p.clone(), Mode::INTUITIONISTIC))
                .collect();
            for (proof, _) in
                crate::linear::proofs::interactive::with_cuts(&found, &mut Rng::new(41))
            {
                proofs.push((proof.sequent().to_string(), proof));
            }
        }
        for (text, proof) in &proofs {
            let derivation = proof.derivation().unwrap();
            let reading = derivation
                .reading()
                .expect("an intuitionistic proof is two-sided");
            for inference in derivation.inferences() {
                let mut printed = String::new();
                TEXT.sequent(
                    &mut printed,
                    proof.forest(),
                    Some(reading),
                    None,
                    inference.sequent(),
                    false,
                    false,
                )
                .unwrap();
                let back: IllSequent = printed
                    .parse()
                    .unwrap_or_else(|e| panic!("{text:?}: {printed:?}: {e}"));
                let formulas = |reading: &Reading, members: &mut dyn Iterator<Item = OccId>| {
                    members
                        .map(|o| reading.formula(o).to_string())
                        .collect::<Vec<_>>()
                };
                let written: Vec<OccId> = reading
                    .written(inference.sequent())
                    .map(|p| inference.sequent()[p].occ())
                    .collect();
                let (goals, hypotheses): (Vec<OccId>, Vec<OccId>) = written
                    .into_iter()
                    .partition(|&o| reading.position(o) == Side::Output);
                assert_eq!(goals.len(), 1, "{text:?}: {printed:?}");
                let read = back.reading();
                assert_eq!(
                    formulas(&read, &mut read.hypotheses()),
                    formulas(reading, &mut hypotheses.into_iter()),
                    "{text:?}: {printed:?}"
                );
                assert_eq!(
                    read.formula(read.goal()).to_string(),
                    reading.formula(goals[0]).to_string(),
                    "{text:?}: {printed:?}"
                );
                #[cfg(feature = "interactive")]
                {
                    cuts += usize::from(inference.cut().is_some());
                }
                inferences += 1;
            }
        }
        assert!(inferences > 200, "{inferences} inferences");
        #[cfg(feature = "interactive")]
        assert!(cuts > 50, "{cuts} cuts");
    }

    /// The symbols of classical linear logic in every notation's spelling
    /// (text, LaTeX, Typst, SVG), none of which an intuitionistic output
    /// may contain.
    #[cfg(all(
        feature = "latex",
        feature = "typst",
        feature = "svg",
        feature = "rocq",
        feature = "interactive"
    ))]
    const CLASSICAL: [&str; 8] = ["~", "⅋", "⊥", "?", r"\parr", r"\bot", r"\wn", "perp"];

    /// Asserts that `out`, what `what` wrote of `sequent`, has no symbol of
    /// classical linear logic: of a Rocq certificate the comments, whose
    /// code is Rocq's (`~` its negation), and no classical constructor.
    #[cfg(all(
        feature = "latex",
        feature = "typst",
        feature = "svg",
        feature = "rocq",
        feature = "interactive"
    ))]
    fn intuitionistic(sequent: &str, what: &str, out: &str) {
        // An SVG document's declaration is no formula.
        let out = out.replace("<?xml", "").replace("?>", "");
        let rocq = out.contains("Lemma certificate");
        let comments: String = out
            .lines()
            .filter(|line| !rocq || line.starts_with("(*"))
            .collect::<Vec<_>>()
            .join("\n");
        for symbol in CLASSICAL {
            assert!(
                !comments.contains(symbol),
                "{sequent:?}: {what} writes {symbol:?}:\n{out}"
            );
        }
        if rocq {
            for word in ["parr", "wn ", "dual", " ll "] {
                assert!(
                    !out.contains(word),
                    "{sequent:?}: {what} writes {word:?}:\n{out}"
                );
            }
        }
    }

    /// No output of an intuitionistic sequent writes a symbol of classical
    /// linear logic: over generated provable sequents and their mutants,
    /// the sequent printed, a session's goal formulas, the text tree, the
    /// LaTeX, Typst, SVG and Rocq exports of a proof, its formulas, its
    /// net's text and drawing, the report of a proof the checker refuses,
    /// and a refutation's phrase and certificate.
    #[cfg(all(
        feature = "latex",
        feature = "typst",
        feature = "svg",
        feature = "rocq",
        feature = "interactive"
    ))]
    #[test]
    fn no_intuitionistic_output_writes_a_classical_symbol() {
        use crate::export::{Styles, latex, rocq, svg, typst};
        use crate::linear::nets::{Criterion, MellStructure, ProofStructure};
        use crate::linear::proofs::Node;
        use crate::linear::search::Verdict;
        use crate::linear::{Interactive, Proof};
        let styles = Styles::default();
        let limits = Limits::default();
        let options = search::Options::default();
        let essential = styles.svg.clone().with_essential(true);
        let criterion = Criterion::of(Mode::INTUITIONISTIC).unwrap();
        let mode = Mode::INTUITIONISTIC;
        // Proofs, refutations, nets and refused proofs seen.
        let mut seen = [0; 4];
        let mut rng = Rng::new(4400);
        for rules in IllRules::ALL {
            for _ in 0..6 {
                let budget = 2 + rng.below(8);
                let mut ill = generate::ill(&mut rng, rules, 3, budget);
                let provable = generate::two_sided(&ill.hypotheses, &ill.goal);
                let mutated =
                    generate::mutate_two_sided(&mut rng, &mut ill.hypotheses, &mut ill.goal, 3)
                        .then(|| generate::two_sided(&ill.hypotheses, &ill.goal));
                for text in std::iter::once(provable).chain(mutated) {
                    let check = |what: &str, out: &str| intuitionistic(&text, what, out);
                    let sequent: IllSequent = text.parse().unwrap();
                    check("the sequent", &sequent.to_string());
                    let session = Interactive::new(sequent.sequent(), mode).unwrap();
                    for goal in session.goals() {
                        for &m in session.goal(goal).unwrap() {
                            check("a goal's formula", &session.formula(m).to_string());
                        }
                    }
                    let outcome = search::prove(sequent.sequent(), mode, &options).unwrap();
                    match &outcome.verdict {
                        Verdict::Proved(proof) => {
                            seen[0] += 1;
                            let derivation = proof.derivation().unwrap();
                            check("the text tree", &derivation.to_string());
                            let mut out = String::new();
                            latex::write(&derivation, &styles.latex, &mut out, |_| false).unwrap();
                            check("LaTeX", &out);
                            out.clear();
                            typst::write(&derivation, &styles.typst, &mut out, |_| false).unwrap();
                            check("Typst", &out);
                            out.clear();
                            svg::write(&derivation, &styles.svg, &mut out, |_| false).unwrap();
                            check("SVG", &out);
                            out.clear();
                            rocq::write(&derivation, &styles.rocq, &mut out, |_| false).unwrap();
                            check("Rocq", &out);
                            for m in proof.forest().root_members() {
                                check("a formula of the proof", &proof.formula(m).to_string());
                            }
                            let fragment = proof.sequent().fragment();
                            if crate::linear::nets::exist(fragment, mode).is_ok() {
                                let net =
                                    ProofStructure::from_proof(proof, criterion, &limits, |_| {
                                        false
                                    })
                                    .unwrap();
                                check("the net", &net.written_in(mode).to_string());
                                let drawn = svg::net(&net, &essential, &limits, |_| false).unwrap();
                                check("the net drawn", &drawn);
                                seen[2] += 1;
                            } else if MellStructure::exist(fragment, mode).is_ok() {
                                let net =
                                    MellStructure::from_proof(proof, criterion, &limits, |_| false)
                                        .unwrap();
                                check("the net", &net.written_in(mode).to_string());
                                let drawn =
                                    svg::mell_net(&net, &essential, &limits, |_| false).unwrap();
                                check("the net drawn", &drawn);
                                seen[2] += 1;
                            }
                            // An axiom of a literal with itself, which the
                            // checker refuses.
                            let mut nodes = proof.nodes().to_vec();
                            if let Some(n) = nodes.iter().position(|n| matches!(n, Node::Ax(..))) {
                                let Node::Ax(a, _) = nodes[n] else {
                                    unreachable!()
                                };
                                nodes[n] = Node::Ax(a, a);
                                let broken =
                                    Proof::new(proof.forest().clone(), nodes, proof.root())
                                        .unwrap()
                                        .with_mode(mode);
                                let error = broken.check(mode).unwrap_err();
                                check("a refused proof", &error.describe(&broken).to_string());
                                seen[3] += 1;
                            }
                        }
                        Verdict::Unprovable(disproof) => {
                            seen[1] += 1;
                            check("the refutation", &disproof.to_string());
                            let mut out = String::new();
                            if rocq::write_disproof(disproof, &styles.rocq, &mut out).is_ok() {
                                check("the refutation's certificate", &out);
                            }
                        }
                        Verdict::Unknown(_) => {}
                    }
                }
            }
        }
        assert!(seen.iter().all(|&n| n > 5), "{seen:?}");
    }

    /// The JSON form writes the sequent as its reading reads it and reads
    /// back the same sequent; a classical tag, an index out of bounds or
    /// out of order, and a level above the build's are refused.
    #[cfg(feature = "serialize")]
    #[test]
    fn the_json_form() {
        let sequent: IllSequent = "A -o B, top |- 0 & B".parse().unwrap();
        let json = serde_json::to_string(&sequent).unwrap();
        assert_eq!(
            json,
            r#"{"version":5,"terms":[{"V":0},{"V":1},{"⊸":[0,1]},"⊤","0",{"&":[4,1]}],"atoms":["A","B"],"hypotheses":[2,3],"goal":5}"#
        );
        let back: IllSequent = serde_json::from_str(&json).unwrap();
        assert_eq!(back, sequent);
        for text in generated(4300, 10) {
            let sequent: IllSequent = text.parse().unwrap();
            let json = serde_json::to_string(&sequent).unwrap();
            let back: IllSequent = serde_json::from_str(&json).unwrap();
            assert_eq!(back.to_string(), sequent.to_string(), "{json}");
            let reading = Reading::new(back.forest()).unwrap();
            assert!(
                back.forest()
                    .ids()
                    .all(|o| reading.position(o) == back.reading().position(o))
            );
        }
        let read = |json: &str| {
            let mut document = serde_json::Deserializer::from_str(json);
            crate::wire::upgrade::<IllSequent, _>(&mut document, &Limits::default())
        };
        for tag in [r#"{"D":0}"#, r#"{"⅋":[0,0]}"#, r#"{"?":0}"#, r#""⊥""#] {
            let json =
                format!(r#"{{"terms":[{{"V":0}},{tag}],"atoms":["A"],"hypotheses":[],"goal":1}}"#);
            assert!(
                matches!(read(&json), Err(Error::Json { message, .. }) if message.contains("unknown variant")),
                "{json}"
            );
        }
        assert!(matches!(
            read(r#"{"terms":[{"⊸":[1,1]},{"V":0}],"atoms":["A"],"hypotheses":[],"goal":0}"#),
            Err(Error::NotTopological { .. })
        ));
        assert!(matches!(
            read(r#"{"terms":[{"V":0}],"atoms":["A"],"hypotheses":[3],"goal":0}"#),
            Err(Error::IndexOutOfBounds { index: 3, .. })
        ));
        // A level above this build's is refused by name.
        let above = crate::wire::LEVEL + 1;
        let json = format!(
            r#"{{"version":{above},"terms":[{{"V":0}}],"atoms":["A"],"hypotheses":[],"goal":0}}"#
        );
        assert!(matches!(
            read(&json),
            Err(Error::Version { found, .. }) if found == u64::from(above)
        ));
    }
}