deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The one printer of formulas and sequents: a table of spellings per
//! target, [`TEXT`](crate::linear::sequents::notation::TEXT) for `Display` and one per export, and the walks that
//! write a formula, a sequent one-sided or two-sided under a reading, and
//! a sequent of ordinary logic through it. A new connective is an arm here
//! and a spelling in each table, never a printer of its own.

use crate::hash::HashMap;
use crate::linear::occurrences::instances::Framing;
use crate::linear::occurrences::written::{self, Written};
use crate::linear::occurrences::{Forest, IllConnective, Member, OccId, Reading, Side};
use crate::linear::sequents::{Atom, Kind, Sequent, Stop, Stops, Term, TermId};
use crate::ordinary::{Formulas, NodeId, Symbols};
use std::borrow::Cow;
use std::fmt::{Result as FmtResult, Write};

/// How a target writes formulas and sequents: the spelling of every
/// connective, unit and of the turnstile, and how an atom's name is
/// escaped. Binary connectives are written between spaces, `!` and `?`
/// directly before their operand.
pub(crate) struct Notation {
    /// `⊗`
    pub(crate) tensor: &'static str,
    /// `⅋`
    pub(crate) par: &'static str,
    /// `&`
    pub(crate) with: &'static str,
    /// `⊕`
    pub(crate) plus: &'static str,
    /// `⊸`, which only a two-sided sequent shows.
    pub(crate) lollipop: &'static str,
    /// `\`, the left division, which only a two-sided sequent of the
    /// Lambek calculus shows.
    pub(crate) under: &'static str,
    /// `/`, the right division, as `under`.
    pub(crate) over: &'static str,
    /// `!`
    pub(crate) bang: &'static str,
    /// `?`
    pub(crate) quest: &'static str,
    /// `1`
    pub(crate) one: &'static str,
    /// `⊥`
    pub(crate) bot: &'static str,
    /// `⊤`
    pub(crate) top: &'static str,
    /// `0`
    pub(crate) zero: &'static str,
    /// The mark before a negated atom's name.
    pub(crate) dual_prefix: &'static str,
    /// The mark after a negated atom's name.
    pub(crate) dual: &'static str,
    /// `⊢`
    pub(crate) turnstile: &'static str,
    /// What goes before the turnstile of a two-sided sequent in a proof
    /// tree so that the turnstiles of a unary inference line up; empty
    /// where the target cannot align them.
    pub(crate) align: &'static str,
    /// How an atom's name is written.
    pub(crate) atom: Atoms,
    /// `∀`, with what stands between it and the variable's name.
    pub(crate) forall: &'static str,
    /// `∃`, as `forall`.
    pub(crate) exists: &'static str,
    /// What stands between a binder's variable and its body: the dot and
    /// a space.
    pub(crate) dot: &'static str,
    /// The connectives and constants of ordinary formulas.
    pub(crate) ordinary: Symbols,
}

/// The spellings `Display` writes: the Unicode symbols, a negated atom as
/// `~a`, a name as it is.
pub(crate) const TEXT: Notation = Notation {
    tensor: "⊗",
    par: "⅋",
    with: "&",
    plus: "⊕",
    lollipop: "⊸",
    under: "\\",
    over: "/",
    bang: "!",
    quest: "?",
    one: "1",
    bot: "⊥",
    top: "⊤",
    zero: "0",
    dual_prefix: "~",
    dual: "",
    turnstile: "⊢",
    align: "",
    atom: Atoms::Plain,
    forall: "∀",
    exists: "∃",
    dot: ". ",
    ordinary: Symbols::UNICODE,
};

/// How a target writes an atom's name: a closed set rather than a function
/// pointer, so that every writer is compiled for the output it writes
/// into (through `dyn Write` one call per character made the Typst
/// export a fifth slower).
#[derive(Clone, Copy, Debug)]
pub(crate) enum Atoms {
    /// As it is.
    Plain,
    /// In LaTeX's math mode.
    #[cfg(feature = "latex")]
    Latex,
    /// In Typst's math mode.
    #[cfg(feature = "typst")]
    Typst,
    /// With its Latin letters as mathematical italic characters.
    #[cfg(feature = "svg")]
    Italic,
}

impl Atoms {
    /// Writes an atom's name into `out`.
    pub(crate) fn write<W: Write + ?Sized>(self, out: &mut W, name: &str) -> FmtResult {
        match self {
            Self::Plain => out.write_str(name),
            #[cfg(feature = "latex")]
            Self::Latex => crate::export::latex::atom(out, name),
            #[cfg(feature = "typst")]
            Self::Typst => crate::export::typst::atom(out, name),
            #[cfg(feature = "svg")]
            Self::Italic => crate::export::svg::italic(out, name),
        }
    }
}

/// The binders a printer's walk is inside of: their variables' names as
/// written, innermost last, and how many binders of each name are open,
/// so that a bound variable is written as its binder's name and a new
/// binder's name is checked in constant time. Empty, and allocating
/// nothing, while the walk meets no binder.
#[derive(Default)]
pub(crate) struct Scope<'a> {
    /// The names, innermost last.
    names: Vec<Cow<'a, str>>,
    /// How many open binders have each name.
    open: HashMap<Cow<'a, str>, u32>,
    /// The sequent's symbol names, filled at the first binder.
    symbols: Option<std::collections::HashSet<&'a str>>,
    /// The terms of an instance's frame as written, its innermost
    /// binder's first: what the bound variables the names do not reach
    /// stand for. Empty but for an instance.
    frame: Vec<String>,
}

/// What a sequent of a proof with instances is written under: the
/// reading of a two-sided one, the proof's instances, and the marks
/// around every formula.
struct Sides<'r, 'f> {
    /// The reading, of a two-sided sequent.
    reading: Option<&'r Reading<'r>>,
    /// The instances.
    framing: &'f Framing<'f>,
    /// What stands before and after every formula.
    marks: (&'static str, &'static str),
}

/// A string that takes `left` more characters and then refuses: a term
/// written in it stops at the cap.
struct Capped {
    /// What was written.
    text: String,
    /// How many characters it takes still.
    left: usize,
}

impl Write for Capped {
    fn write_str(&mut self, s: &str) -> FmtResult {
        let n = s.chars().count();
        if n <= self.left {
            self.left -= n;
            self.text.push_str(s);
            return Ok(());
        }
        self.text.extend(s.chars().take(self.left));
        self.left = 0;
        Err(std::fmt::Error)
    }
}

/// A writer that passes everything on to the one it holds: a type of its
/// own for the walks an instance makes.
struct Apart<'w, W: ?Sized>(&'w mut W);

impl<W: Write + ?Sized> Write for Apart<'_, W> {
    fn write_str(&mut self, s: &str) -> FmtResult {
        self.0.write_str(s)
    }

    fn write_char(&mut self, c: char) -> FmtResult {
        self.0.write_char(c)
    }
}

/// What a bound variable is written as.
enum Bound<'s> {
    /// The name of a binder of the formula.
    Name(&'s str),
    /// A term of an instance's frame, written in the target's markup.
    Term(&'s str),
}

impl<'a> Scope<'a> {
    /// Returns the name a binder's variable of `name` is written with:
    /// `name` itself, or with `_` and a number after it where a symbol of
    /// `sequent` or an enclosing binder has the name, so that the text
    /// reads back as the formula it writes (`∀x. p(x, x)` with a constant
    /// `x` would not); then opens the binder.
    #[cold]
    #[inline(never)]
    fn enter(&mut self, sequent: &'a Sequent, name: &'a str) -> &str {
        let symbols = self
            .symbols
            .get_or_insert_with(|| sequent.fo.symbols.iter().map(|(s, _)| s.as_str()).collect());
        let clashes = |open: &HashMap<Cow<'a, str>, u32>, candidate: &str| {
            symbols.contains(candidate) || open.contains_key(candidate)
        };
        let mut written = Cow::Borrowed(name);
        let mut n = 0u32;
        while clashes(&self.open, &written) {
            n += 1;
            written = Cow::Owned(format!("{name}_{n}"));
        }
        *self.open.entry(written.clone()).or_insert(0) += 1;
        self.names.push(written);
        self.names.last().expect("just pushed")
    }

    /// Closes the innermost binder.
    #[cold]
    #[inline(never)]
    fn exit(&mut self) {
        if let Some(name) = self.names.pop()
            && let Some(count) = self.open.get_mut(&name)
        {
            *count -= 1;
            if *count == 0 {
                self.open.remove(&name);
            }
        }
    }

    /// Returns what the bound variable `index` binders up is written as,
    /// if the scope or the frame reaches it.
    fn name(&self, index: u32) -> Option<Bound<'_>> {
        match self.names.len().checked_sub(index as usize + 1) {
            Some(at) => Some(Bound::Name(self.names[at].as_ref())),
            None => self
                .frame
                .get(index as usize - self.names.len())
                .map(|t| Bound::Term(t)),
        }
    }

    /// Returns the scope of an instance whose frame's terms are written
    /// as `frame`, the innermost binder's first, where `taken` (the
    /// eigenvariables' names) are open, so that no binder of the formula
    /// is written with one of them.
    pub(crate) fn framed(frame: Vec<String>, taken: impl Iterator<Item = &'a str>) -> Self {
        let mut open = HashMap::default();
        for name in taken {
            open.insert(Cow::Borrowed(name), 1);
        }
        Self {
            names: Vec::new(),
            open,
            symbols: None,
            frame,
        }
    }
}

/// Returns whether a formula of `kind` is written in brackets where it
/// stands inside another: a binary one, and a binder, whose scope would
/// otherwise run on.
fn bracketed(kind: Kind) -> bool {
    kind.arity() == 2 || kind.is_binder()
}

/// The place a walk keeps its scope: made at the first binder, and
/// dropped by [`close`] at the walk's end, so that a walk without a
/// binder, which is every propositional one, pays no drop.
type Slot<'a> = std::mem::ManuallyDrop<Option<Box<Scope<'a>>>>;

/// Drops the scope of `slot`, if one was made.
#[inline(always)]
fn close(slot: Slot<'_>) {
    if let Some(scope) = std::mem::ManuallyDrop::into_inner(slot) {
        drop(scope);
    }
}

impl Notation {
    /// Writes the atom `atom` of `sequent`: its name, or a predicate with
    /// its arguments, a bound variable by the name of its binder in
    /// `scope`, and by its index after `#` where the scope does not reach
    /// it (an occurrence written below its binder).
    #[inline(always)]
    pub(crate) fn write_atom<W: Write + ?Sized>(
        &self,
        out: &mut W,
        sequent: &Sequent,
        atom: Atom,
        predicates: bool,
        scope: Option<&Scope<'_>>,
    ) -> FmtResult {
        if predicates {
            self.write_predicate(out, sequent, atom, scope)
        } else {
            self.atom.write(out, sequent.atom_name(atom))
        }
    }

    /// Writes the atom `atom` of a first-order `sequent` as
    /// [`write_atom`](Self::write_atom) does.
    #[cold]
    #[inline(never)]
    fn write_predicate<W: Write + ?Sized>(
        &self,
        out: &mut W,
        sequent: &Sequent,
        atom: Atom,
        scope: Option<&Scope<'_>>,
    ) -> FmtResult {
        let (symbol, args) = sequent.fo.atoms[atom.index()];
        let fo = &sequent.fo;
        self.atom.write(out, &fo.symbols[symbol.index()].0)?;
        let list = fo.list(args);
        if list.is_empty() {
            return Ok(());
        }
        out.write_char('(')?;
        for (i, &t) in list.iter().enumerate() {
            if i > 0 {
                out.write_str(", ")?;
            }
            fo.write(
                out,
                t,
                &mut |out, name| self.atom.write(out, name),
                &mut |out, index| match scope.and_then(|scope| scope.name(index)) {
                    Some(Bound::Name(name)) => self.atom.write(out, name),
                    Some(Bound::Term(term)) => out.write_str(term),
                    None => write!(out, "#{index}"),
                },
            )?;
        }
        out.write_char(')')
    }

    /// Opens the binder `term` of `sequent` in `scope` and writes it, `∀x.
    /// ` up to where its body starts, with the name its variable is
    /// written by (`x` where none is recorded).
    #[cold]
    #[inline(never)]
    fn binder<'a, W: Write + ?Sized>(
        &self,
        out: &mut W,
        sequent: &'a Sequent,
        term: TermId,
        kind: Kind,
        scope: &mut Option<Box<Scope<'a>>>,
    ) -> FmtResult {
        out.write_str(if kind == Kind::Forall {
            self.forall
        } else {
            self.exists
        })?;
        let scope = scope.get_or_insert_with(Box::default);
        let name = scope.enter(sequent, sequent.binder_name(term).unwrap_or("x"));
        self.atom.write(out, name)?;
        out.write_str(self.dot)
    }

    /// Writes the formula rooted at `id` of `sequent` one-sided, in
    /// brackets if it is binary or a binder and `brackets` is set.
    pub(crate) fn term<W: Write>(
        &self,
        out: &mut W,
        sequent: &Sequent,
        id: TermId,
        brackets: bool,
    ) -> FmtResult {
        let mut slot: Slot<'_> = std::mem::ManuallyDrop::new(None);
        let written = self.term_in(out, sequent, id, brackets, &mut slot);
        close(slot);
        written
    }

    /// Writes the formula of the instance `member` of a proof's `framing`
    /// as [`term`](Self::term) writes an occurrence's, or under a reading
    /// as [`ill`](Self::ill) does: its bound variables that no binder of
    /// it binds written as the terms of its frame, each cut after `cap`
    /// characters with `…` where one is given (a term of shared subterms
    /// can be exponentially longer than the proof that names it).
    #[cold]
    #[inline(never)]
    pub(crate) fn instance<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        reading: Option<&Reading>,
        framing: &Framing<'_>,
        member: Member,
        cap: Option<usize>,
    ) -> FmtResult {
        let (o, mut slot) = self.framed_scope(framing, member, cap)?;
        // A writer of its own type, so that the walks a propositional
        // print makes stay instantiated once, with the iterator inside.
        let mut out = Apart(out);
        let written = match reading {
            Some(reading) => self.ill_in(&mut out, reading, o, false, &mut slot),
            None => self.term_in(&mut out, forest.sequent(), forest.term(o), false, &mut slot),
        };
        close(slot);
        written
    }

    /// Writes the formula of the instance `member` of a proof's `framing`
    /// as [`written`](Self::written) writes an occurrence, as its author
    /// wrote it, with its bound variables that no binder of it binds
    /// written as the terms of its frame.
    #[cold]
    #[inline(never)]
    fn written_instance<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        writing: &[Written],
        framing: &Framing<'_>,
        member: Member,
        negated: bool,
    ) -> FmtResult {
        let (o, mut slot) = self.framed_scope(framing, member, None)?;
        let written = self.written_in(&mut Apart(out), forest, writing, o, negated, &mut slot);
        close(slot);
        written
    }

    /// Returns the occurrence the instance `member` of `framing` stands
    /// for and the scope it is written in: its frame's terms, each cut
    /// after `cap` characters with `…` where one is given, and the
    /// eigenvariables' names open.
    fn framed_scope<'f>(
        &self,
        framing: &'f Framing<'_>,
        member: Member,
        cap: Option<usize>,
    ) -> Result<(OccId, Slot<'f>), std::fmt::Error> {
        let (o, frame) = framing
            .table
            .instance(member)
            .expect("a member of the proof's table");
        let frame = framing
            .table
            .frame_terms(frame)
            .into_iter()
            .map(|t| {
                let mut text = Capped {
                    text: String::new(),
                    left: cap.unwrap_or(usize::MAX),
                };
                match framing.write_term(&mut text, t, &mut |out, name| self.atom.write(out, name))
                {
                    Ok(()) => Ok(text.text),
                    // Past the cap: what was written, and `…`.
                    Err(_) if text.left == 0 => Ok(text.text + "…"),
                    Err(e) => Err(e),
                }
            })
            .collect::<Result<Vec<String>, _>>()?;
        let scope = Scope::framed(frame, framing.names());
        Ok((o, std::mem::ManuallyDrop::new(Some(Box::new(scope)))))
    }

    /// Writes the formula as [`term`](Self::term) does, its scope in
    /// `scope`.
    #[inline(always)]
    fn term_in<'a, W: Write>(
        &self,
        out: &mut W,
        sequent: &'a Sequent,
        id: TermId,
        brackets: bool,
        scope: &mut Option<Box<Scope<'a>>>,
    ) -> FmtResult {
        use Term::*;
        debug_assert!(id.index() < sequent.terms.len());
        let predicates = !sequent.fo.atoms.is_empty();
        for visit in Stops::new(id, brackets, |k| sequent.term(k).operands()) {
            match visit {
                Stop::Enter(k, nested) => {
                    let term = sequent.term(k);
                    debug_assert!(term.subterms().all(|sub| sub < k));
                    match term {
                        Atom(a) => {
                            self.write_atom(out, sequent, a, predicates, scope.as_deref())?
                        }
                        DualAtom(a) => {
                            if !self.dual_prefix.is_empty() {
                                out.write_str(self.dual_prefix)?;
                            }
                            self.write_atom(out, sequent, a, predicates, scope.as_deref())?;
                            out.write_str(self.dual)?;
                        }
                        One => out.write_str(self.one)?,
                        Bot => out.write_str(self.bot)?,
                        Top => out.write_str(self.top)?,
                        Zero => out.write_str(self.zero)?,
                        Tensor(..) | Par(..) | With(..) | Plus(..) if nested => {
                            out.write_char('(')?;
                        }
                        Tensor(..) | Par(..) | With(..) | Plus(..) => {}
                        Bang(_) => out.write_str(self.bang)?,
                        Quest(_) => out.write_str(self.quest)?,
                        Forall(_) | Exists(_) => {
                            if nested {
                                out.write_char('(')?;
                            }
                            self.binder(out, sequent, k, term.kind(), scope)?;
                        }
                    }
                }
                Stop::Between(k) => {
                    out.write_char(' ')?;
                    out.write_str(match sequent.term(k) {
                        Tensor(..) => self.tensor,
                        Par(..) => self.par,
                        With(..) => self.with,
                        Atom(_) | DualAtom(_) | One | Bot | Top | Zero | Plus(..) | Bang(_)
                        | Quest(_) | Forall(_) | Exists(_) => self.plus,
                    })?;
                    out.write_char(' ')?;
                }
                Stop::Exit(k, nested) => {
                    let kind = sequent.term(k).kind();
                    if kind.is_binder()
                        && let Some(scope) = scope
                    {
                        scope.exit();
                    }
                    if nested && bracketed(kind) {
                        out.write_char(')')?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Writes the intuitionistic formula at `o` as the reading reads it
    /// (`⊸`, `1` for `⊥`, `⊤` for an input `0`, and so on), in brackets if
    /// it is binary and `brackets` is set.
    pub(crate) fn ill<W: Write>(
        &self,
        out: &mut W,
        reading: &Reading,
        o: OccId,
        brackets: bool,
    ) -> FmtResult {
        let mut slot: Slot<'_> = std::mem::ManuallyDrop::new(None);
        let written = self.ill_in(out, reading, o, brackets, &mut slot);
        close(slot);
        written
    }

    /// Writes the intuitionistic formula as [`ill`](Self::ill) does, its
    /// scope in `scope`.
    #[inline(always)]
    fn ill_in<'a, W: Write>(
        &self,
        out: &mut W,
        reading: &'a Reading,
        o: OccId,
        brackets: bool,
        scope: &mut Option<Box<Scope<'a>>>,
    ) -> FmtResult {
        use IllConnective as C;
        let forest = reading.forest();
        let sequent = forest.sequent();
        let predicates = !sequent.fo.atoms.is_empty();
        for visit in Stops::new(o, brackets, |o| reading.operands(o)) {
            match visit {
                Stop::Enter(o, nested) => match reading.connective(o) {
                    C::Atom => {
                        let atom = forest.atom(o).expect("a literal has an atom");
                        self.write_atom(out, sequent, atom, predicates, scope.as_deref())?;
                    }
                    C::One => out.write_str(self.one)?,
                    C::Top => out.write_str(self.top)?,
                    C::Zero => out.write_str(self.zero)?,
                    C::Tensor | C::With | C::Plus | C::Lollipop | C::Under | C::Over if nested => {
                        out.write_char('(')?;
                    }
                    C::Tensor | C::With | C::Plus | C::Lollipop | C::Under | C::Over => {}
                    C::Bang => out.write_str(self.bang)?,
                    connective @ (C::Forall | C::Exists) => {
                        if nested {
                            out.write_char('(')?;
                        }
                        let kind = if connective == C::Forall {
                            Kind::Forall
                        } else {
                            Kind::Exists
                        };
                        self.binder(out, sequent, forest.term(o), kind, scope)?;
                    }
                },
                Stop::Between(o) => {
                    out.write_char(' ')?;
                    out.write_str(match reading.connective(o) {
                        C::Tensor => self.tensor,
                        C::Lollipop => self.lollipop,
                        C::Under => self.under,
                        C::Over => self.over,
                        C::With => self.with,
                        C::Atom
                        | C::One
                        | C::Top
                        | C::Zero
                        | C::Bang
                        | C::Plus
                        | C::Forall
                        | C::Exists => self.plus,
                    })?;
                    out.write_char(' ')?;
                }
                Stop::Exit(o, nested) => {
                    let kind = forest.kind(o);
                    if kind.is_binder()
                        && let Some(scope) = scope
                    {
                        scope.exit();
                    }
                    if nested && bracketed(kind) {
                        out.write_char(')')?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Writes the formula at `o` as its author wrote it (`writing`): each
    /// connective on the side it stands on, `⊸` where an implication was
    /// written, a negation before every subformula written with one, and
    /// before `o` itself where `negated` says. A negated binary formula,
    /// and where the negation follows its operand a negated `!` or `?`, is
    /// in brackets, as is a binary one inside another.
    pub(crate) fn written<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        writing: &[Written],
        o: OccId,
        negated: bool,
    ) -> FmtResult {
        let mut slot: Slot<'_> = std::mem::ManuallyDrop::new(None);
        let written = self.written_in(out, forest, writing, o, negated, &mut slot);
        close(slot);
        written
    }

    /// Writes the formula as [`written`](Self::written) does, its scope
    /// in `scope`.
    #[inline(always)]
    fn written_in<'a, W: Write>(
        &self,
        out: &mut W,
        forest: &'a Forest,
        writing: &[Written],
        o: OccId,
        negated: bool,
        scope: &mut Option<Box<Scope<'a>>>,
    ) -> FmtResult {
        let top = o;
        let negation = |k: OccId| {
            if k == top {
                negated
            } else {
                written::negated(forest, writing, k)
            }
        };
        // The connective as written: on the input side the dual of the
        // one-sided one.
        let core = |k: OccId| match writing[k.index()].side() {
            Side::Output => forest.kind(k),
            Side::Input => forest.kind(k).dual(),
        };
        // Where the negation follows its operand, a prefix operator under
        // it needs brackets to stay under it.
        let postfix = !self.dual.is_empty();
        let operands = |k: OccId| (forest.left(k), forest.right(k));
        let sequent = forest.sequent();
        let predicates = !sequent.fo.atoms.is_empty();
        for visit in Stops::new(o, false, operands) {
            match visit {
                Stop::Enter(k, nested) => {
                    let negated = negation(k);
                    if negated {
                        out.write_str(self.dual_prefix)?;
                    }
                    match core(k) {
                        Kind::Atom => {
                            let atom = forest.atom(k).expect("a literal has an atom");
                            self.write_atom(out, sequent, atom, predicates, scope.as_deref())?;
                        }
                        Kind::DualAtom => {
                            let atom = forest.atom(k).expect("a literal has an atom");
                            out.write_str(self.dual_prefix)?;
                            self.write_atom(out, sequent, atom, predicates, scope.as_deref())?;
                            out.write_str(self.dual)?;
                        }
                        Kind::One => out.write_str(self.one)?,
                        Kind::Bot => out.write_str(self.bot)?,
                        Kind::Top => out.write_str(self.top)?,
                        Kind::Zero => out.write_str(self.zero)?,
                        Kind::Tensor | Kind::Par | Kind::With | Kind::Plus => {
                            if nested || negated {
                                out.write_char('(')?;
                            }
                        }
                        kind @ (Kind::Bang | Kind::Quest) => {
                            if negated && postfix {
                                out.write_char('(')?;
                            }
                            out.write_str(if kind == Kind::Bang {
                                self.bang
                            } else {
                                self.quest
                            })?;
                        }
                        kind @ (Kind::Forall | Kind::Exists) => {
                            if nested || negated {
                                out.write_char('(')?;
                            }
                            self.binder(out, sequent, forest.term(k), kind, scope)?;
                        }
                    }
                    if negated && forest.kind(k).arity() == 0 {
                        out.write_str(self.dual)?;
                    }
                }
                Stop::Between(k) => {
                    out.write_char(' ')?;
                    out.write_str(if writing[k.index()].is_implication() {
                        self.lollipop
                    } else {
                        match core(k) {
                            Kind::Tensor => self.tensor,
                            Kind::Par => self.par,
                            Kind::With => self.with,
                            Kind::Plus
                            | Kind::Atom
                            | Kind::DualAtom
                            | Kind::One
                            | Kind::Bot
                            | Kind::Top
                            | Kind::Zero
                            | Kind::Bang
                            | Kind::Quest
                            | Kind::Forall
                            | Kind::Exists => self.plus,
                        }
                    })?;
                    out.write_char(' ')?;
                }
                Stop::Exit(k, nested) => {
                    let negated = negation(k);
                    let kind = forest.kind(k);
                    if kind.is_binder()
                        && let Some(scope) = scope
                    {
                        scope.exit();
                    }
                    let arity = kind.arity();
                    if (bracketed(kind) && (nested || negated))
                        || (arity == 1 && !kind.is_binder() && negated && postfix)
                    {
                        out.write_char(')')?;
                    }
                    if negated {
                        out.write_str(self.dual)?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Writes a classical sequent two-sided, `left ⊢ right`, each formula
    /// a member as its author wrote it with a negation before it or
    /// without ([`written`](Self::written)), a member past the forest an
    /// instance of the proof's `framing`, the turnstile lined up as
    /// [`sequent`](Self::sequent) does when `aligned` is set, and with
    /// `marks` every formula between `'\u{2}'` and `'\u{3}'`.
    #[expect(
        clippy::too_many_arguments,
        reason = "the sides, the instances and the two switches are what every target passes"
    )]
    pub(crate) fn classical<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        writing: &[Written],
        framing: Option<&Framing<'_>>,
        left: impl Iterator<Item = (Member, bool)>,
        right: impl Iterator<Item = (Member, bool)>,
        aligned: bool,
        marks: bool,
    ) -> FmtResult {
        let (open, close) = if marks { ("\u{2}", "\u{3}") } else { ("", "") };
        let formula = |out: &mut W, m: Member, negated: bool| {
            out.write_str(open)?;
            match framing {
                Some(framing) if m.index() >= forest.len() => {
                    self.written_instance(out, forest, writing, framing, m, negated)?;
                }
                _ => self.written(out, forest, writing, m.occ(), negated)?,
            }
            out.write_str(close)
        };
        let mut any = false;
        for (m, negated) in left {
            if any {
                out.write_str(", ")?;
            }
            formula(out, m, negated)?;
            any = true;
        }
        if any {
            out.write_char(' ')?;
        }
        if aligned {
            out.write_str(self.align)?;
        }
        out.write_str(self.turnstile)?;
        for (i, (m, negated)) in right.enumerate() {
            out.write_str(if i == 0 { " " } else { ", " })?;
            formula(out, m, negated)?;
        }
        Ok(())
    }

    /// Writes a sequent one-sided: the turnstile, then its root formulas,
    /// comma-separated.
    pub(crate) fn one_sided<W: Write>(&self, out: &mut W, sequent: &Sequent) -> FmtResult {
        out.write_str(self.turnstile)?;
        for (i, &id) in sequent.roots().iter().enumerate() {
            out.write_str(if i == 0 { " " } else { ", " })?;
            self.term(out, sequent, id, false)?;
        }
        Ok(())
    }

    /// Writes a sequent of a derivation, occurrences in ascending order:
    /// one-sided, or two-sided under a reading with the hypotheses in the
    /// order it writes them before the turnstile and the goal after it, which `aligned`
    /// lines up with the turnstiles above and below. With `marks`, every
    /// formula stands between the two characters `'\u{2}'` and `'\u{3}'`.
    /// A member past the forest is an instance of the proof's `framing`.
    #[expect(
        clippy::too_many_arguments,
        reason = "the sides, the instances and the two switches are what every target passes"
    )]
    pub(crate) fn sequent<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        reading: Option<&Reading>,
        framing: Option<&Framing<'_>>,
        sequent: &[Member],
        aligned: bool,
        marks: bool,
    ) -> FmtResult {
        let (open, close) = if marks { ("\u{2}", "\u{3}") } else { ("", "") };
        if let Some(framing) = framing {
            let sides = Sides {
                reading,
                framing,
                marks: (open, close),
            };
            return self.framed(out, forest, &sides, sequent, aligned);
        }
        let Some(reading) = reading else {
            out.write_str(self.turnstile)?;
            for (i, o) in sequent.iter().map(|m| m.occ()).enumerate() {
                out.write_str(if i == 0 { " " } else { ", " })?;
                out.write_str(open)?;
                self.term(out, forest.sequent(), forest.term(o), false)?;
                out.write_str(close)?;
            }
            return Ok(());
        };
        let output = |o: OccId| reading.position(o) == Side::Output;
        let goal = sequent.iter().map(|m| m.occ()).rfind(|&o| output(o));
        let hypotheses = reading
            .written(sequent)
            .map(|p| sequent[p].occ())
            .filter(|&o| !output(o));
        self.two_sided(out, reading, hypotheses, goal, aligned, (open, close))
    }

    /// Writes a sequent of a derivation as [`sequent`](Self::sequent) does,
    /// whose members past the forest are instances of `sides.framing`: out
    /// of line, so that a sequent of occurrences is written as it always
    /// was.
    #[cold]
    #[inline(never)]
    fn framed<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        sides: &Sides<'_, '_>,
        sequent: &[Member],
        aligned: bool,
    ) -> FmtResult {
        let (open, close) = sides.marks;
        let framing = sides.framing;
        let Some(reading) = sides.reading else {
            out.write_str(self.turnstile)?;
            for (i, &m) in sequent.iter().enumerate() {
                out.write_str(if i == 0 { " " } else { ", " })?;
                out.write_str(open)?;
                self.member(out, forest, None, framing, m)?;
                out.write_str(close)?;
            }
            return Ok(());
        };
        let occ = |m: Member| framing.occurrence(m);
        let output = |m: Member| reading.position(occ(m)) == Side::Output;
        let goal = sequent.iter().copied().rfind(|&m| output(m));
        let mut any = false;
        for m in reading
            .written_by(sequent, occ)
            .map(|p| sequent[p])
            .filter(|&m| !output(m))
        {
            if any {
                out.write_str(", ")?;
            }
            out.write_str(open)?;
            self.member(out, forest, Some(reading), framing, m)?;
            out.write_str(close)?;
            any = true;
        }
        if any {
            out.write_char(' ')?;
        }
        if aligned {
            out.write_str(self.align)?;
        }
        out.write_str(self.turnstile)?;
        if let Some(goal) = goal {
            out.write_char(' ')?;
            out.write_str(open)?;
            self.member(out, forest, Some(reading), framing, goal)?;
            out.write_str(close)?;
        }
        Ok(())
    }

    /// Writes the member `m` of a proof with instances: an occurrence as
    /// [`term`](Self::term) or [`ill`](Self::ill) writes it, an instance as
    /// [`instance`](Self::instance) does.
    fn member<W: Write>(
        &self,
        out: &mut W,
        forest: &Forest,
        reading: Option<&Reading>,
        framing: &Framing<'_>,
        m: Member,
    ) -> FmtResult {
        if m.index() >= forest.len() {
            return self.instance(out, forest, reading, framing, m, None);
        }
        match reading {
            Some(reading) => self.ill(out, reading, m.occ(), false),
            None => self.term(out, forest.sequent(), forest.term(m.occ()), false),
        }
    }

    /// Writes the sequent a reading reads two-sided: its hypotheses in the
    /// order written, `⊢` and its goal.
    pub(crate) fn reading<W: Write>(&self, out: &mut W, reading: &Reading) -> FmtResult {
        let goal = Some(reading.goal());
        self.two_sided(out, reading, reading.hypotheses(), goal, false, ("", ""))
    }

    /// Writes `hypotheses ⊢ goal` under a reading, the turnstile lined up
    /// where `aligned`, every formula between the `marks`.
    fn two_sided<W: Write>(
        &self,
        out: &mut W,
        reading: &Reading,
        hypotheses: impl Iterator<Item = OccId>,
        goal: Option<OccId>,
        aligned: bool,
        marks: (&str, &str),
    ) -> FmtResult {
        let (open, close) = marks;
        let mut any = false;
        for o in hypotheses {
            if any {
                out.write_str(", ")?;
            }
            out.write_str(open)?;
            self.ill(out, reading, o, false)?;
            out.write_str(close)?;
            any = true;
        }
        if any {
            out.write_char(' ')?;
        }
        if aligned {
            out.write_str(self.align)?;
        }
        out.write_str(self.turnstile)?;
        if let Some(goal) = goal {
            out.write_char(' ')?;
            out.write_str(open)?;
            self.ill(out, reading, goal, false)?;
            out.write_str(close)?;
        }
        Ok(())
    }

    /// Writes a sequent of ordinary formulas two-sided, `left ⊢ right`
    /// in the order given, with the turnstile lined up as
    /// [`sequent`](Self::sequent) does when `aligned` is set, and with
    /// `marks` every formula between `'\u{2}'` and `'\u{3}'`.
    pub(crate) fn ordinary<W: Write>(
        &self,
        out: &mut W,
        formulas: &Formulas,
        sides: (&[NodeId], &[NodeId]),
        aligned: bool,
        marks: bool,
    ) -> FmtResult {
        let (open, close) = if marks { ("\u{2}", "\u{3}") } else { ("", "") };
        let formula = |out: &mut W, id: NodeId| {
            out.write_str(open)?;
            formulas.write(out, id, false, &self.ordinary, |o, a| {
                self.atom.write(o, formulas.atom_name(a))
            })?;
            out.write_str(close)
        };
        let (left, right) = sides;
        for (i, &id) in left.iter().enumerate() {
            if i > 0 {
                out.write_str(", ")?;
            }
            formula(out, id)?;
        }
        if !left.is_empty() {
            out.write_char(' ')?;
        }
        if aligned {
            out.write_str(self.align)?;
        }
        out.write_str(self.turnstile)?;
        for (i, &id) in right.iter().enumerate() {
            out.write_str(if i == 0 { " " } else { ", " })?;
            formula(out, id)?;
        }
        Ok(())
    }
}