deduxit 0.4.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The layout of a proof structure without boxes: its formula trees under
//! their axiom links.
//!
//! - The literals stand side by side along the top in occurrence order,
//!   which is left to right in every tree. Edges and links meet a literal
//!   at the middle of its atom, not of a negated literal's whole `A⊥`.
//! - Each connective is one layer below the lower of its premises. The
//!   conclusions are on the bottom layer.
//! - An axiom link is a half-ellipse over the two literals it joins. Its
//!   height is its width times a fixed ratio up to [`Style::link_cap`],
//!   and grows more slowly beyond, so that the arcs of nested pairs of
//!   literals never cross. Links over interleaved pairs do cross.
//!
//! Drawn with its formulas, every occurrence is its formula's text. A
//! connective's text has its own connective under the joint, the point
//! where the edges from its premises meet. Each premise's subtree stands
//! as far to its side of the joint as the premise stands in the text. So
//! every subformula of a one-sided net is where it is in its conclusion,
//! and since the subtrees of a connective's two premises stand on either
//! side of its joint, no edge crosses a formula.
//!
//! Compact, the literals are packed `literal_gap` apart, and every
//! connective is a circle halfway between its premises. The conclusions
//! are written under the edges that hang from the bottom layer, as far
//! apart as their texts need.
//!
//! A structure that is not a proof net has its switching cycle, or every
//! part but the first that it falls into, in the highlight colour. Drawn
//! as an essential net, the same layout shows the reading's direction on
//! every edge, as an arrowhead halfway along it, and its polarity in the
//! colours.

use super::font::{AXIS, DEPTH, HEIGHT};
use super::{
    Marks, NOTATION, NetDrawing, PLAIN, Premises, RAISED_BOT, Style, document, escaped, lay,
    net_conclusion, net_link, net_verdict, run, text,
};
use crate::linear::nets::{NetError, ProofStructure};
use crate::linear::occurrences::{OccId, Reading, Side};
use crate::linear::sequents::Kind;
use std::fmt::Write;

/// The height of the middle of `⅋` above the baseline. `⅋` stands on the
/// baseline, where `⊗` is centred on the math axis.
pub(super) const PAR_MIDDLE: i64 = 344;

/// Writes an arrowhead with its tip at `tip`, pointing along `towards`,
/// its wings `size` back from the tip.
pub(super) fn arrowhead(out: &mut String, tip: (i64, i64), towards: (f64, f64), size: i64) {
    let length = towards.0.hypot(towards.1);
    let (dx, dy) = (towards.0 / length, towards.1 / length);
    let back = (
        tip.0 as f64 - dx * size as f64,
        tip.1 as f64 - dy * size as f64,
    );
    let side = 0.6 * size as f64;
    let wing = |sign: f64| {
        (
            (back.0 - sign * dy * side).round() as i64,
            (back.1 + sign * dx * side).round() as i64,
        )
    };
    let (a, b) = (wing(1.0), wing(-1.0));
    writeln!(
        out,
        r#"<path d="M{} {}L{} {}L{} {}"/>"#,
        a.0, a.1, tip.0, tip.1, b.0, b.1
    )
    .unwrap();
}

/// Writes an arrowhead halfway along the segment from `from` to `to`,
/// pointing at `to`.
pub(super) fn arrow_along(out: &mut String, from: (i64, i64), to: (i64, i64), size: i64) {
    let towards = ((to.0 - from.0) as f64, (to.1 - from.1) as f64);
    let middle = ((from.0 + to.0) / 2, (from.1 + to.1) / 2);
    let tip = towards_by(middle, towards, size / 2);
    arrowhead(out, tip, towards, size);
}

/// Returns the point `by` from `from` in the direction `towards`.
pub(super) fn towards_by(from: (i64, i64), towards: (f64, f64), by: i64) -> (i64, i64) {
    let scale = by as f64 / towards.0.hypot(towards.1);
    (
        from.0 + (towards.0 * scale).round() as i64,
        from.1 + (towards.1 * scale).round() as i64,
    )
}

/// Returns the point `by` along the segment from `from` towards `to`.
pub(super) fn towards(from: (i64, i64), to: (i64, i64), by: i64) -> (i64, i64) {
    let (dx, dy) = ((to.0 - from.0) as f64, (to.1 - from.1) as f64);
    let scale = by as f64 / dx.hypot(dy);
    (
        from.0 + (dx * scale).round() as i64,
        from.1 + (dy * scale).round() as i64,
    )
}

/// Returns the height of a link's arc, `rx` being half its width.
///
/// Up to the style's cap `W`, the height is `rx` times the style's ratio.
/// Beyond it, the height is the ratio times `sqrt(W·rx)`, which equals
/// the first at `rx = W`.
///
/// Nested arcs never cross. The squared height at `x` of an arc over
/// `(a, b)` is `φ(rx)·(x−a)(b−x)`, with `φ` the square of the height over
/// `rx`:
/// - for a constant `φ` (arcs of one shape) it shrinks with the interval;
/// - for `φ ∝ 1/rx` (past the cap) it is a multiple of the harmonic mean
///   of `x−a` and `b−x`, which shrinks with the interval too;
/// - an arc with `rx ≤ W` lies below that harmonic arc of its own
///   interval, so it stays below a wider arc past the cap as well.
pub(super) fn height(rx: i64, style: &Style) -> i64 {
    let ratio = i64::from(style.link_height);
    match style.link_cap.map(i64::from) {
        Some(cap) if rx > cap => ratio * cap.saturating_mul(rx).isqrt() / 1000,
        _ => rx * ratio / 1000,
    }
}

/// Returns the links of a structure as pairs of the occurrences they join.
fn joined(net: &ProofStructure) -> impl Iterator<Item = (OccId, OccId)> {
    net.links().iter().map(|&(x, y)| (x.occ(), y.occ()))
}

/// Returns every occurrence's component in the switching that keeps the
/// left premise of every `⅋`, each component named by the index of one of
/// its occurrences.
fn components(net: &ProofStructure) -> Vec<usize> {
    let forest = net.forest();
    let mut parent: Vec<usize> = (0..forest.len()).collect();
    let find = |parent: &mut Vec<usize>, mut o: usize| {
        while parent[o] != o {
            parent[o] = parent[parent[o]];
            o = parent[o];
        }
        o
    };
    let kept = forest
        .ids()
        .filter(|&o| net.vertex(o).is_some())
        .flat_map(|o| {
            let cut = (forest.kind(o) == Kind::Par)
                .then(|| forest.right(o))
                .flatten();
            forest
                .children(o)
                .filter(move |&c| Some(c) != cut)
                .map(move |c| (o, c))
        });
    let across = net.cuts().iter().map(|&(x, y)| (x.occ(), y.occ()));
    for (a, b) in kept.chain(across).chain(joined(net)) {
        let (a, b) = (find(&mut parent, a.index()), find(&mut parent, b.index()));
        parent[a] = b;
    }
    (0..forest.len()).map(|o| find(&mut parent, o)).collect()
}

/// The bytes of a drawing's start, its groups and its end, beyond what
/// [`estimate`] counts per part.
pub(super) const DOCUMENT: u64 = 1000;

/// The bytes of one `<text>` element besides its characters: its
/// coordinates and width of up to twelve digits, its size, an id and a
/// fill attribute's name.
pub(super) const PIECE: u64 = 140;

/// The bytes of the group a formula's text is when it has several pieces,
/// besides its colour.
pub(super) const GROUP: u64 = 40;

/// The bytes a connective adds to its formula's text: its symbol, the
/// spaces around it and the brackets around the formula.
pub(super) const BINARY: u64 = 7;

/// The bytes of a connective: its circle, its symbol and its two premise
/// edges.
pub(super) const CONNECTIVE: u64 = 400;

/// The bytes of the edge below a conclusion.
pub(super) const ROOT: u64 = 60;

/// The bytes of a link's arc and the two lines down to its literals.
pub(super) const LINK: u64 = 160;

/// The bytes of an arrowhead, a path of three points with coordinates of
/// up to twelve digits. An essential net's drawing adds one per edge,
/// conclusion and link.
pub(super) const ARROW: u64 = 100;

/// A writer that counts the bytes of what it is given escaped for XML,
/// and fails when they pass `most`.
pub(super) struct Count {
    /// The bytes counted.
    bytes: u64,
    /// The most it counts before it fails.
    most: u64,
}

impl Count {
    /// Returns a counter that fails past `most` bytes.
    pub(super) const fn new(most: u64) -> Self {
        Self { bytes: 0, most }
    }

    /// Returns the bytes counted.
    pub(super) const fn bytes(&self) -> u64 {
        self.bytes
    }
}

impl Write for Count {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        for c in s.chars() {
            let escaped = match c {
                '&' => "&amp;".len(),
                '<' | '>' => "&lt;".len(),
                '"' => "&quot;".len(),
                c => c.len_utf8(),
            };
            self.bytes = self.bytes.saturating_add(escaped as u64);
        }
        if self.bytes > self.most {
            return Err(std::fmt::Error);
        }
        Ok(())
    }
}

/// Returns an estimate of the bytes of a structure's drawing, made from
/// the structure without drawing it.
///
/// The estimate is at least what the drawing has without its
/// description, which [`described_bytes`] counts. `read` says the
/// structure is drawn as its essential net. The sums saturate, so no
/// structure is estimated small.
pub(super) fn estimate(net: &ProofStructure, style: &Style, read: bool) -> u64 {
    let forest = net.forest();
    let sequent = forest.sequent();
    let formulas = style.net == NetDrawing::Formulas;
    let colour = match read {
        true => escaped(&style.input).len() as u64 + 8,
        false => 0,
    };
    let mut bytes = DOCUMENT;
    // Per occurrence, the bytes of its formula's text, at four bytes a
    // letter, and how many negated literals it has. A negated literal is a
    // raised `⊥` that splits the text into two more pieces, unless the
    // reading writes it as its atom. Every subformula drawn writes its own
    // text, so the drawing grows with the formulas' depth.
    let (mut chars, mut duals) = (vec![0u64; forest.len()], vec![0u64; forest.len()]);
    for o in forest.ids().rev() {
        let i = o.index();
        (chars[i], duals[i]) = match (forest.left(o), forest.right(o), forest.atom(o)) {
            (Some(l), Some(r), _) => (
                chars[l.index()]
                    .saturating_add(chars[r.index()])
                    .saturating_add(BINARY),
                duals[l.index()].saturating_add(duals[r.index()]),
            ),
            (_, _, atom) => {
                let name = atom.map_or(0, |a| sequent.atom_name(a).len() as u64);
                let dual = !read && forest.kind(o) == Kind::DualAtom;
                (name.saturating_mul(4).saturating_add(3), u64::from(dual))
            }
        };
        if formulas || forest.is_literal(o) || forest.parent(o).is_none() {
            let pieces = duals[i].saturating_mul(2).saturating_add(1);
            bytes = bytes
                .saturating_add(chars[i])
                .saturating_add(pieces.saturating_mul(PIECE + colour))
                .saturating_add(GROUP + colour);
        }
        bytes = bytes.saturating_add(match forest.atom(o) {
            // In the title, the name as it is, with a `⊥`.
            Some(atom) => (sequent.atom_name(atom).len() as u64).saturating_add(3),
            // Its circle or joint, its symbol and its edges, and in the
            // title the symbol with a space on either side and brackets.
            None => CONNECTIVE + 9,
        });
    }
    let roots = forest.roots().len() as u64;
    let links = net.links().len() as u64 + net.cuts().len() as u64;
    bytes = bytes
        .saturating_add(roots.saturating_mul(ROOT + 2))
        .saturating_add(links.saturating_mul(LINK));
    if read {
        // An arrowhead per edge (two per connective), conclusion and link,
        // and the drawing's two more groups. The colours are counted per
        // piece of text above.
        let edges = (forest.len() as u64)
            .saturating_mul(2)
            .saturating_add(roots)
            .saturating_add(links);
        bytes = bytes
            .saturating_add(edges.saturating_mul(ARROW))
            .saturating_add(DOCUMENT);
    }
    bytes
}

/// Returns the bytes of a structure's description as [`describe`]
/// writes it, escaped, or some number past `most`. The drawing's
/// estimate leaves it out: it needs the verdict, which the criterion
/// gives only after the estimate has refused what is too large.
pub(super) fn described_bytes(
    net: &ProofStructure,
    verdict: &Result<(), NetError>,
    reading: Option<&Reading<'_>>,
    most: u64,
) -> u64 {
    let mut count = Count::new(most);
    let _ = describe(net, verdict, reading, &mut count);
    count.bytes()
}

/// Writes a structure's description, which a screen reader reads in
/// place of the drawing, as short sentences: the sequent it concludes,
/// each cut link, each axiom link (by the smaller of its ends), and
/// `verdict`. A formula is named by its vertex, which is the occurrence
/// the drawing's id `o<n>` names, and written in the title's notation.
pub(super) fn describe(
    net: &ProofStructure,
    verdict: &Result<(), NetError>,
    reading: Option<&Reading<'_>>,
    out: &mut impl Write,
) -> std::fmt::Result {
    let forest = net.forest();
    let end = |v: crate::linear::nets::VertexId| (v.get(), v.occ());
    net_conclusion(out, forest, reading)?;
    for &(x, y) in net.cuts() {
        net_link(out, true, [end(x), end(y)], forest, reading)?;
    }
    let mut links: Vec<_> = net
        .links()
        .iter()
        .map(|&(x, y)| (x.min(y), x.max(y)))
        .collect();
    links.sort_unstable();
    for (x, y) in links {
        net_link(out, false, [end(x), end(y)], forest, reading)?;
    }
    let mode = match reading {
        Some(reading) if reading.is_ordered() => Some(crate::linear::Mode::LAMBEK),
        Some(_) => Some(crate::linear::Mode::INTUITIONISTIC),
        None => None,
    };
    match verdict {
        Ok(()) => net_verdict(out, net.criterion(), None),
        Err(error) => {
            let described = error.describe(forest);
            let described = match mode {
                Some(mode) => described.in_mode(mode),
                None => described,
            };
            net_verdict(out, net.criterion(), Some(&described))
        }
    }
}

/// Returns a proof structure as an SVG document, titled with its sequent
/// in plain text.
///
/// `verdict` is the structure's [`ProofStructure::is_correct`]. With the
/// `reading` of its sequent, the structure is drawn as its essential net,
/// and `verdict` is its [`ProofStructure::is_essential`]. `described` is
/// the verdict the description states, always `is_correct`'s: the
/// essential criterion does not test planarity. `step` marks what a step
/// of cut elimination acted on, in the highlight colour.
pub(super) fn draw(
    net: &ProofStructure,
    style: &Style,
    verdict: &Result<(), NetError>,
    described: &Result<(), NetError>,
    reading: Option<&Reading<'_>>,
    step: &Marks,
) -> String {
    let forest = net.forest();
    // The vertices are the live occurrences: all but those of a cut
    // formula's tree that lie above no end of a cut link. The formulas at
    // the bottom (`tops`) are the conclusions, then each cut link's two
    // ends side by side.
    let live = |o: OccId| net.vertex(o).is_some();
    let mut tops: Vec<OccId> = forest.roots().to_vec();
    tops.extend(net.cuts().iter().flat_map(|&(x, y)| [x.occ(), y.occ()]));
    let n = forest.len();
    let formulas = style.net == NetDrawing::Formulas;
    let line_height = i64::from(style.line_height);
    let (gap, radius) = (i64::from(style.literal_gap), i64::from(style.node_radius));
    let (margin, stroke) = (i64::from(style.margin), i64::from(style.stroke_width));
    let label_size = i64::from(style.label_size);
    let input = |o: OccId| reading.is_some_and(|r| r.position(o) == Side::Input);
    let arrow = radius / 2;
    let advance = |c: char| i64::from(style.font.advances.advance(c));
    let width = |text: &str| lay(text, 1000, &style.font, |_| {});
    let root = |o: OccId| forest.parent(o).is_none_or(|p| !live(p));
    // Whether an occurrence's formula is written: a compact net writes
    // only its literals and its conclusions.
    let written = |o: OccId| formulas || forest.is_literal(o) || root(o);
    // An occurrence's formula as the drawing writes it: one-sided, or as
    // the reading reads it, which writes a literal as its atom.
    let write = |out: &mut String, o: OccId, brackets: bool| {
        match reading {
            Some(r) => NOTATION.ill(out, r, o, brackets),
            None => NOTATION.term(out, forest.sequent(), forest.term(o), brackets),
        }
        .unwrap();
    };
    // The symbol at a connective's joint or in its compact circle, and the
    // height of its middle above its baseline. An essential net shows the
    // reading's connectives: `A⊥ ⅋ B` in output position and `A ⊗ B⊥` in
    // input position are `⊸`. A division of the Lambek calculus is `⊸`
    // too, and the conclusion's text tells its side: a `\` or `/` at the
    // joint would read as a piece of an edge.
    let symbol = |o: OccId| -> (&'static str, i64) {
        match reading {
            Some(_) if (forest.kind(o) == Kind::Par) != input(o) => (NOTATION.lollipop, AXIS),
            Some(_) => (NOTATION.tensor, AXIS),
            None if forest.kind(o) == Kind::Par => (NOTATION.par, PAR_MIDDLE),
            None => (NOTATION.tensor, AXIS),
        }
    };

    // Bottom-up: the extent of every subtree around its anchor, each
    // anchor's offset from its parent's, and each connective's layer, one
    // below the lower of its premises. The anchor is a literal's atom's
    // middle (not a negated literal's whole `A⊥`), a connective's joint,
    // or a compact node's centre.
    let mut formula = String::new();
    let mut from_left = vec![0; n];
    let mut extent = vec![(0, 0); n];
    let mut offset = vec![0; n];
    let mut layer = vec![0; n];
    for o in forest.ids().rev() {
        let i = o.index();
        formula.clear();
        let text_width = if written(o) {
            write(&mut formula, o, false);
            width(&formula)
        } else {
            0
        };
        let (Some(l), Some(r)) = (forest.left(o), forest.right(o)) else {
            let atom = match (forest.kind(o), reading) {
                (Kind::DualAtom, None) => width(formula.trim_end_matches(RAISED_BOT)),
                _ => text_width,
            };
            from_left[i] = atom / 2;
            extent[i] = (-(atom / 2), text_width - atom / 2);
            continue;
        };
        layer[i] = 1 + layer[l.index()].max(layer[r.index()]);
        let (left, right) = (extent[l.index()], extent[r.index()]);
        let own = if formulas {
            // The text's connective stands under the joint. Each premise's
            // subtree is as far from the joint as the premise is in the
            // text: half the connective, a space, and a bracket unless the
            // premise is a literal. So every subformula of a one-sided net
            // is drawn where it is in its conclusion, and the two premises'
            // subtrees stand on either side of the joint, which keeps every
            // edge off every formula.
            let first = reading.and_then(|r| r.operands(o).0).unwrap_or(l);
            formula.clear();
            write(&mut formula, first, true);
            formula.push(' ');
            let half = symbol(o).0.chars().map(advance).sum::<i64>() / 2;
            from_left[i] = width(&formula) + half;
            let bracket = |child: OccId, c: char| match forest.is_literal(child) {
                true => 0,
                false => advance(c),
            };
            let space = advance(' ');
            offset[l.index()] = -(half + space + bracket(l, ')') + left.1);
            offset[r.index()] = half + space + bracket(r, '(') - right.0;
            (-from_left[i], text_width - from_left[i])
        } else {
            // The subtrees stand `literal_gap` apart, the node halfway
            // between their anchors, a conclusion's text centred under its
            // circle.
            let span = left.1 + gap - right.0;
            offset[l.index()] = -(span / 2);
            offset[r.index()] = span - span / 2;
            from_left[i] = text_width / 2;
            (
                (-radius).min(-from_left[i]),
                radius.max(text_width - from_left[i]),
            )
        };
        extent[i] = (
            own.0.min(offset[l.index()] + left.0),
            own.1.max(offset[r.index()] + right.1),
        );
    }
    // The conclusions side by side on the bottom layer, `literal_gap`
    // apart, and top-down every anchor from its parent's.
    let bottom = tops.iter().map(|r| layer[r.index()]).max();
    let bottom = bottom.unwrap_or(0);
    let mut x = vec![0; n];
    let mut right = margin - gap;
    for &r in &tops {
        layer[r.index()] = bottom;
        x[r.index()] = right + gap - extent[r.index()].0;
        right = x[r.index()] + extent[r.index()].1;
    }
    for o in forest.ids() {
        if let Some(p) = forest.parent(o)
            && !root(o)
        {
            x[o.index()] = x[p.index()] + offset[o.index()];
        }
    }

    // The highest arc decides where the literals' baseline is.
    let arc = |(p, q): (OccId, OccId)| {
        let (a, b) = (
            x[p.index()].min(x[q.index()]),
            x[p.index()].max(x[q.index()]),
        );
        let rx = (b - a) / 2;
        (a, b, rx, height(rx, style))
    };
    let highest = joined(net).map(|l| arc(l).3).max();
    let baseline = margin + stroke + highest.unwrap_or(0) + HEIGHT;
    let top = baseline - HEIGHT;
    // With formulas, every layer is a line of text, and the next is
    // `line_height` plus a joint's room further down (`pitch`). Compact,
    // the nodes' layers are `line_height` apart, the conclusions' edges
    // end half a layer below the lowest, and the conclusions are written
    // under them.
    let pitch = line_height + radius + HEIGHT + DEPTH;
    let end = baseline - AXIS + bottom * line_height + line_height / 2;
    let under = end + HEIGHT;
    let text_y = |o: OccId| match (formulas, root(o)) {
        (true, _) => baseline + layer[o.index()] * pitch,
        (false, true) => under,
        (false, false) => baseline,
    };
    // A connective's joint, 1.5 radii above the top of its text, or a
    // compact node's centre.
    let node = |o: OccId| match formulas {
        true => (x[o.index()], text_y(o) - HEIGHT - radius - radius / 2),
        false => (
            x[o.index()],
            baseline - AXIS + layer[o.index()] * line_height,
        ),
    };
    // Where a premise edge ends under a written formula, clear of its
    // descenders, in either drawing.
    let depth = style.font.advances.depth();
    let foot = |o: OccId| (x[o.index()], text_y(o) + depth);

    // What the verdict highlights: a cycle as its edges, sorted; or for a
    // disconnected structure, every occurrence's component in the
    // switching that keeps each left premise, and the first part's
    // component, which stays unmarked.
    let (mut cycle, mut parts) = (Vec::new(), None);
    match verdict {
        Err(
            NetError::SwitchingCycle { cycle: vertices }
            | NetError::DirectedCycle { cycle: vertices },
        ) => {
            let next = vertices.iter().cycle().skip(1);
            cycle = vertices
                .iter()
                .zip(next)
                .map(|(&a, &b)| (a.min(b).occ(), a.max(b).occ()))
                .collect();
            cycle.sort_unstable();
        }
        Err(NetError::Disconnected { parts: tops }) => {
            let component = components(net);
            let first = component[tops[0][0].index()];
            parts = Some((component, first));
        }
        // The path, and the missing edge from the implication to its
        // antecedent that it goes around.
        Err(NetError::NoDominator { implication, path }) => {
            cycle = path
                .windows(2)
                .map(|w| (w[0].min(w[1]).occ(), w[0].max(w[1]).occ()))
                .collect();
            if let Some(antecedent) = forest.left(implication.occ()) {
                cycle.push((implication.occ(), antecedent));
            }
            cycle.sort_unstable();
        }
        _ => {}
    }
    let apart = |o: OccId| {
        parts
            .as_ref()
            .is_some_and(|(c, first)| c[o.index()] != *first)
    };
    let marks = |a: OccId, b: OccId| {
        let joined = parts
            .as_ref()
            .is_some_and(|(c, _)| c[a.index()] == c[b.index()]);
        cycle.binary_search(&(a.min(b), a.max(b))).is_ok()
            || (joined && apart(a))
            || step.has(a.get(), b.get())
    };

    let (mut lines, mut pars, mut links) = (String::new(), String::new(), String::new());
    let (mut marked, mut texts) = (String::new(), String::new());
    let (mut inputs, mut dominators) = (String::new(), String::new());
    let dash = format!("{} {}", 3 * stroke, 3 * stroke);
    let fill = |o: OccId| match input(o) {
        true => format!(r#" fill="{}""#, escaped(&style.input)),
        false => String::new(),
    };
    for o in forest.ids().filter(|&o| live(o)) {
        if written(o) {
            // A compact net's circle is its connective's element.
            let mut attributes = match formulas || forest.is_literal(o) {
                true => format!(r#" id="o{}""#, o.get()),
                false => String::new(),
            };
            attributes.push_str(&fill(o));
            formula.clear();
            write(&mut formula, o, false);
            let line = run(&formula, 1000, &style.font);
            text(
                &mut texts,
                x[o.index()] - from_left[o.index()],
                text_y(o),
                &line,
                &attributes,
                None,
            );
        }
        if forest.is_literal(o) {
            continue;
        }
        let centre = node(o);
        let (sign, middle) = symbol(o);
        let label = run(sign, label_size, &style.font);
        let mut size = format!(r#" font-size="{label_size}""#);
        if formulas {
            size.push_str(&fill(o));
        } else {
            writeln!(
                if input(o) { &mut inputs } else { &mut lines },
                r#"<circle id="o{}" cx="{}" cy="{}" r="{radius}"/>"#,
                o.get(),
                centre.0,
                centre.1
            )
            .unwrap();
        }
        text(
            &mut texts,
            centre.0 - label.width / 2,
            centre.1 + middle * label_size / 1000,
            &label,
            &size,
            None,
        );
        for child in forest.children(o) {
            let to = match formulas || forest.is_literal(child) {
                true => foot(child),
                false => towards(node(child), centre, radius),
            };
            let from = towards(centre, to, radius);
            if reading.is_some() {
                // Output premises lead down into their connective, input
                // connectives up into their input premises, and nothing
                // into the antecedent of an output implication.
                let (upward, antecedent) = (input(child), input(child) && !input(o));
                let out = match (marks(o, child), antecedent, upward) {
                    (true, _, _) => &mut marked,
                    (false, true, _) => &mut dominators,
                    (false, false, true) => &mut inputs,
                    (false, false, false) => &mut lines,
                };
                write!(out, r#"<path d="M{} {}L{} {}""#, from.0, from.1, to.0, to.1).unwrap();
                if antecedent {
                    write!(out, r#" stroke-dasharray="{stroke} {}""#, 2 * stroke).unwrap();
                    out.push_str("/>\n");
                } else {
                    out.push_str("/>\n");
                    let (start, end) = if upward { (from, to) } else { (to, from) };
                    arrow_along(out, start, end, arrow);
                }
                continue;
            }
            // Under `Premises::Plain`, a `⅋` edge is drawn as a `⊗` edge.
            let par = forest.kind(o) == Kind::Par && style.net_look.premises == Premises::Dashed;
            let out = match (marks(o, child), par) {
                (true, _) => &mut marked,
                (false, true) => &mut pars,
                (false, false) => &mut lines,
            };
            write!(out, r#"<path d="M{} {}L{} {}""#, from.0, from.1, to.0, to.1).unwrap();
            if par && marks(o, child) {
                write!(out, r#" stroke-dasharray="{dash}""#).unwrap();
            }
            out.push_str("/>\n");
        }
        // A compact conclusion's edge hangs from its circle to its text.
        // Under the reading, a hypothesis's arrow points up, the goal's
        // down.
        if root(o) && !formulas {
            let (column, start) = (x[o.index()], centre.1 + radius);
            let out = match (apart(o), input(o)) {
                (true, _) => &mut marked,
                (false, true) => &mut inputs,
                (false, false) => &mut lines,
            };
            writeln!(out, r#"<path d="M{column} {start}V{end}"/>"#).unwrap();
            if reading.is_some() {
                let (from, to) = ((column, start), (column, end));
                let (from, to) = if input(o) { (to, from) } else { (from, to) };
                arrow_along(out, from, to, arrow);
            }
        }
    }
    for (p, q) in joined(net) {
        let (a, b, rx, ry) = arc((p, q));
        let out = if marks(p, q) { &mut marked } else { &mut links };
        // A literal that is a conclusion stands at the bottom, and its
        // link's arc reaches down to it.
        let (left, right) = if x[p.index()] < x[q.index()] {
            (p, q)
        } else {
            (q, p)
        };
        let (down_left, down_right) = (text_y(left) - HEIGHT, text_y(right) - HEIGHT);
        write!(
            out,
            r#"<path id="l{}-{}" d="M{a} {down_left}"#,
            p.min(q).get(),
            p.max(q).get()
        )
        .unwrap();
        if down_left != top {
            write!(out, "V{top}").unwrap();
        }
        write!(out, "A{rx} {ry} 0 0 1 {b} {top}").unwrap();
        if down_right != top {
            write!(out, "V{down_right}").unwrap();
        }
        out.push_str("\"/>\n");
        // From the input literal to the output one, at the arc's top.
        if reading.is_some() {
            let leftwards = left == if input(p) { q } else { p };
            let towards = (if leftwards { -1.0 } else { 1.0 }, 0.0);
            let tip = towards_by((a + rx, top - ry), towards, arrow / 2);
            arrowhead(out, tip, towards, arrow);
        }
    }

    // Each cut link as the literature draws one: a bar under its two
    // formulas, joined to them from below.
    let cut_depth = 2 * radius;
    for &(a, d) in net.cuts() {
        let (a, d) = (a.occ(), d.occ());
        let below = |o: OccId| match formulas {
            true => text_y(o) + depth,
            false => under + depth,
        };
        let low = below(a).max(below(d)) + cut_depth;
        let out = match step.cut == Some((a.get(), d.get())) {
            true => &mut marked,
            false => &mut lines,
        };
        writeln!(
            out,
            r#"<path id="c{}-{}" d="M{} {}V{low}H{}V{}"/>"#,
            a.get(),
            d.get(),
            x[a.index()],
            below(a),
            x[d.index()],
            below(d)
        )
        .unwrap();
    }
    let group = |out: &mut String, colour: &str, extra: &str, content: &str| {
        writeln!(
            out,
            "<g fill=\"none\" stroke=\"{}\" stroke-width=\"{stroke}\"{extra}>",
            escaped(colour)
        )
        .unwrap();
        out.push_str(content);
        out.push_str("</g>\n");
    };
    let body = |out: &mut String| {
        group(out, &style.line, "", &lines);
        if reading.is_some() {
            group(out, &style.input, "", &inputs);
            group(out, &style.dominator, "", &dominators);
        } else if style.net_look.premises == Premises::Dashed {
            group(
                out,
                &style.par,
                &format!(r#" stroke-dasharray="{dash}""#),
                &pars,
            );
        }
        group(out, &style.link, "", &links);
        if !marked.is_empty() {
            group(out, &style.highlight, "", &marked);
        }
        out.push_str(&texts);
    };
    // An essential net is of the intuitionistic sequent its reading reads.
    let mut title = String::new();
    match reading {
        Some(reading) => PLAIN.reading(&mut title, reading).unwrap(),
        None => PLAIN.one_sided(&mut title, forest.sequent()).unwrap(),
    }
    let width = if tops.is_empty() {
        2 * margin
    } else {
        right + margin
    };
    let cuts = if net.is_cut_free() {
        0
    } else {
        depth.max(DEPTH) + cut_depth + stroke
    };
    let height = match formulas {
        true => baseline + bottom * pitch + DEPTH.max(cuts) + margin,
        false => under + DEPTH.max(cuts) + margin,
    };
    let description = style.description.then(|| {
        let mut text = String::new();
        describe(net, described, reading, &mut text).unwrap();
        text
    });
    document(style, &title, description.as_deref(), (width, height), body)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The arc of a wide link stays under the arc of a wider link it is
    /// nested in, past the cap. A height that stopped growing at the cap
    /// would make them cross.
    #[test]
    fn nested_arcs_do_not_cross() {
        let style = Style::default();
        // The height of the arc over `(a, b)` at `x`.
        let at = |(a, b): (i64, i64), x: i64| {
            let (rx, middle) = ((b - a) as f64 / 2.0, (a + b) as f64 / 2.0);
            let ry = height((b - a) / 2, &style) as f64;
            ry * (1.0 - ((x as f64 - middle) / rx).powi(2)).max(0.0).sqrt()
        };
        let (outer, inner) = ((0, 200_000), (2_000, 30_000));
        assert!(height(15_000, &style) < 15_000 * 600 / 1000);
        for x in [inner.0, inner.0 + 500, (inner.0 + inner.1) / 2, inner.1] {
            assert!(at(inner, x) < at(outer, x), "{x}");
        }
    }
}