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

//! Typst: formulas in math mode, and derivations as proof trees, of the
//! `curryst` package, whose `rule(name: …, premises…, conclusion)` nests
//! the premises inside their conclusion, or of deduxit's own layout.
//!
//! The connectives are written as their Unicode characters (`⊗ ⅋ ⊕ ⊸ ⊢
//! ⊥ ⊤`), which Typst's math reads with their Unicode math class and which
//! no renaming of Typst's symbol names can break; `&` is escaped and set
//! as a binary operator, `?` set as an ordinary symbol so that no
//! punctuation space follows it, and `1` bold. A fragment is a sequent in
//! `$…$` or a `#prooftree(…)` call, for a document that imports `rule`
//! and `prooftree` from curryst [`CURRYST`]; a standalone document imports
//! them itself and sizes the page to its content. Neither chooses a font:
//! the output is set in the fonts of the document it goes into. curryst cannot align
//! turnstiles, so every sequent is centred. An open goal of a proof in
//! progress is its sequent under vertical dots, with no inference line.
//! curryst nests its layout at every level of the tree, so Typst refuses a
//! tree with two premises on a branch more than [`CURRYST_HEIGHT`]
//! inferences high ("maximum show rule depth exceeded"). A higher tree is
//! therefore written by default in deduxit's own layout ([`Layout`]): a
//! `#context` block that lists the inferences and measures, lays out and
//! places them in one box, the SVG drawing's layout with Typst's
//! measurements, so that no height reaches a limit and no package is
//! needed.
//!
//! An atom named by one letter is written as it is, in math italic; any
//! other name is a string in `italic(…)`, with `"` and `\` escaped, since
//! Typst would read a longer name as a variable of its own. Typst is
//! Unicode throughout, so names beyond ASCII need nothing else.
//!
//! Needs the cargo feature `typst` (on by default).
//!
//! # Examples
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::export::typst;
//! use deduxit::{Limits, linear::{Mode, Options, Sequent, Verdict, prove}};
//!
//! let sequent: Sequent = "A, A -o B |- B".parse()?;
//! let options = typst::Options::default();
//! let printed = typst::sequent(&sequent, Mode::CLASSICAL, &options, &Limits::default())?;
//! assert_eq!(printed, "$⊢ A^⊥, A ⊗ B^⊥, B$");
//!
//! let outcome = prove(&sequent, Mode::INTUITIONISTIC, &Options::default())?;
//! let Verdict::Proved(proof) = &outcome.verdict else {
//!     panic!("provable");
//! };
//! let mut written = String::new();
//! typst::write(&proof.derivation()?, &options, &mut written, |_| false)?;
//! assert_eq!(
//!     written,
//!     r#"#prooftree(
//!   rule(
//!     name: $⊸ upright(L)$,
//!     rule(name: $"ax"$, $A ⊢ A$),
//!     rule(name: $"ax"$, $B ⊢ B$),
//!     $A, A ⊸ B ⊢ B$,
//!   ),
//! )"#
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use super::notation::{Step, flush, walk};
use super::{Drawable, Form};
use crate::Error;
use crate::linear::proofs::style::{Drawn, Part, parts};
use crate::linear::proofs::{Labels, OpenGoal};
use crate::linear::sequents::Sequent;
use crate::linear::sequents::notation::{Atoms, Notation};
use crate::ordinary::Symbols;
use std::fmt::Write;

/// The version of curryst a standalone document imports, the one the
/// output is written for. The flake's `export` check compiles the output
/// with this version from nixpkgs, so the two change together.
pub const CURRYST: &str = "0.6.0";

/// The Typst spelling of formulas and sequents.
const NOTATION: Notation = Notation {
    tensor: "⊗",
    par: "⅋",
    with: r#"class("binary", \&)"#,
    plus: "⊕",
    lollipop: "⊸",
    under: r#"class("binary", backslash)"#,
    over: r#"class("binary", slash)"#,
    bang: "!",
    quest: r#"class("normal", ?)"#,
    one: "bold(1)",
    bot: "⊥",
    top: "⊤",
    zero: "0",
    dual_prefix: "",
    dual: "^⊥",
    turnstile: "⊢",
    align: "",
    atom: Atoms::Typst,
    forall: "forall ",
    exists: "exists ",
    dot: ". ",
    ordinary: Symbols::UNICODE,
};

/// Writes an atom's name in math mode.
pub(crate) fn atom<W: Write + ?Sized>(out: &mut W, name: &str) -> std::fmt::Result {
    let mut chars = name.chars();
    if let (Some(c), None) = (chars.next(), chars.next())
        && c.is_alphabetic()
    {
        return out.write_char(c);
    }
    out.write_str("italic(\"")?;
    for c in name.chars() {
        if c == '"' || c == '\\' {
            out.write_char('\\')?;
        }
        out.write_char(c)?;
    }
    out.write_str("\")")
}

/// The page setup of a standalone document by default: as large as its
/// content.
pub const PAGE: &str = "#set page(width: auto, height: auto, margin: 5pt)";

/// The highest tree, in inferences on its longest branch, that curryst
/// [`CURRYST`] sets: Typst refuses a higher one with two premises
/// anywhere on the branch ("maximum show rule depth exceeded").
pub const CURRYST_HEIGHT: usize = 9;

/// Which code sets a Typst proof tree.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Layout {
    /// curryst for a tree of at most [`CURRYST_HEIGHT`] inferences on
    /// its longest branch, deduxit's own layout for a higher one.
    #[default]
    Auto,
    /// curryst's `prooftree` and `rule`, which a document imports.
    Curryst,
    /// Typst code of deduxit's own in the output, which measures every
    /// sequent and places it, with no package and no limit on the height.
    /// Read from `"linlog"` too, its name up to 0.2.0.
    #[cfg_attr(feature = "serialize", serde(alias = "linlog"))]
    Deduxit,
}

/// A Typst length the output writes as code: a number of digits, with a
/// fraction after a `.` or not, and one of the units `pt`, `mm`, `cm`,
/// `in` and `em`, as in `1.5em`, so that an option's value can never be
/// other code. In JSON (feature `serialize`) its text.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Length(Box<str>);

impl Length {
    /// The units a length may have.
    pub const UNITS: [&'static str; 5] = ["pt", "mm", "cm", "in", "em"];

    /// Returns the length `text` is.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidOption`] for text that is no such length.
    pub fn new(text: &str) -> Result<Self, Error> {
        let number = text.trim_end_matches(|c: char| c.is_ascii_alphabetic());
        let (whole, fraction) = number.split_once('.').unwrap_or((number, "0"));
        let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
        if digits(whole) && digits(fraction) && Self::UNITS.contains(&&text[number.len()..]) {
            Ok(Self(text.into()))
        } else {
            Err(Error::InvalidOption {
                key: "typst",
                message: format!(
                    "`{text}` is no Typst length: digits, a fraction or not, and one of {}",
                    Self::UNITS.join(", ")
                ),
            })
        }
    }

    /// Returns the length's text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::str::FromStr for Length {
    type Err = Error;

    /// Reads a length as [`new`](Self::new) does.
    fn from_str(text: &str) -> Result<Self, Error> {
        Self::new(text)
    }
}

impl std::fmt::Display for Length {
    /// Writes the length as Typst reads it.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(feature = "serialize")]
impl serde::Serialize for Length {
    /// Serializes the length as its text.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

#[cfg(feature = "serialize")]
impl<'a> serde::Deserialize<'a> for Length {
    /// Deserializes a length from its text, refusing what
    /// [`new`](Self::new) refuses.
    fn deserialize<D: serde::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let text = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        Self::new(&text).map_err(serde::de::Error::custom)
    }
}

/// What a user may vary in the Typst output.
/// Made from its `default()` with the fields set that differ, since a
/// later field breaks no caller that way.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
    /// A fragment to paste, or a document that compiles on its own.
    pub form: Form,
    /// The labels of the rules.
    pub labels: Labels,
    /// How an open goal is drawn: under `dots.v`, bare, as a leaf rule
    /// named by a mark, or under a dashed line.
    pub open: OpenGoal,
    /// The line of a standalone document that imports `prooftree` and
    /// `rule` from curryst.
    pub import: String,
    /// The page setup of a standalone document.
    pub page: String,
    /// Which code sets the tree.
    pub layout: Layout,
    /// The least space between two premises side by side in deduxit's own
    /// layout.
    pub premise_gap: Length,
    /// The space between an inference line and its rule's label in
    /// deduxit's own layout.
    pub label_gap: Length,
    /// The least height of the space an inference line stands in, between
    /// its premises and its conclusion, in deduxit's own layout; a taller
    /// label makes it taller.
    pub band: Length,
    /// The thickness of an inference line in deduxit's own layout.
    pub stroke: Length,
    /// Whether the derivation's lambda-term is written under its
    /// conclusion, as its typing judgement ([`lambda`](crate::lambda)),
    /// with these options, their notation being the target's own; `None`
    /// by default. A derivation without a term is refused
    /// ([`Error::NoTerm`]), and a term whose text would pass the default
    /// output bound ([`Limits::DEFAULT_DERIVATION_BYTES`](crate::Limits::DEFAULT_DERIVATION_BYTES))
    /// is refused before anything is written.
    pub lambda: Option<crate::lambda::Options>,
}

impl Default for Options {
    /// Returns a fragment with upright labels, an open goal under
    /// vertical dots, the import of curryst [`CURRYST`], the page
    /// [`PAGE`], curryst up to its height and deduxit's own layout above
    /// it, with curryst's spacing and line.
    fn default() -> Self {
        Self {
            form: Form::Fragment,
            labels: Labels::Upright,
            open: OpenGoal::Dots,
            import: format!("#import \"@preview/curryst:{CURRYST}\": prooftree, rule"),
            page: PAGE.to_owned(),
            layout: Layout::Auto,
            premise_gap: Length("1.5em".into()),
            label_gap: Length("0.2em".into()),
            band: Length("0.8em".into()),
            stroke: Length("0.05em".into()),
            lambda: None,
        }
    }
}

impl Options {
    /// Returns the options with another [`form`](Self::form).
    #[must_use]
    pub fn with_form(self, form: Form) -> Self {
        Self { form, ..self }
    }

    /// Returns the options with another [`labels`](Self::labels).
    #[must_use]
    pub fn with_labels(self, labels: Labels) -> Self {
        Self { labels, ..self }
    }

    /// Returns the options with another [`open`](Self::open).
    #[must_use]
    pub fn with_open(self, open: OpenGoal) -> Self {
        Self { open, ..self }
    }

    /// Returns the options with another [`import`](Self::import).
    #[must_use]
    pub fn with_import(self, import: String) -> Self {
        Self { import, ..self }
    }

    /// Returns the options with another [`page`](Self::page).
    #[must_use]
    pub fn with_page(self, page: String) -> Self {
        Self { page, ..self }
    }

    /// Returns the options with another [`layout`](Self::layout).
    #[must_use]
    pub fn with_layout(self, layout: Layout) -> Self {
        Self { layout, ..self }
    }

    /// Returns the options with another [`premise_gap`](Self::premise_gap).
    #[must_use]
    pub fn with_premise_gap(self, premise_gap: Length) -> Self {
        Self {
            premise_gap,
            ..self
        }
    }

    /// Returns the options with another [`label_gap`](Self::label_gap).
    #[must_use]
    pub fn with_label_gap(self, label_gap: Length) -> Self {
        Self { label_gap, ..self }
    }

    /// Returns the options with another [`band`](Self::band).
    #[must_use]
    pub fn with_band(self, band: Length) -> Self {
        Self { band, ..self }
    }

    /// Returns the options with another [`stroke`](Self::stroke).
    #[must_use]
    pub fn with_stroke(self, stroke: Length) -> Self {
        Self { stroke, ..self }
    }
}

/// Writes a label's markup in math mode: symbols as their characters,
/// one letter as `upright(L)`, longer text as a string, subscripts after
/// `_`, and a space before text that follows something.
fn label(out: &mut String, markup: &str) {
    let text = |out: &mut String, text: &str| {
        let mut chars = text.chars();
        if let (Some(c), None) = (chars.next(), chars.next())
            && c.is_alphabetic()
        {
            out.push_str("upright(");
            out.push(c);
            out.push(')');
            return;
        }
        out.push('"');
        for c in text.chars() {
            if c == '"' || c == '\\' {
                out.push('\\');
            }
            out.push(c);
        }
        out.push('"');
    };
    let start = out.len();
    for part in parts(markup) {
        match part {
            Part::Symbol(c) => out.push_str(match c {
                '&' => r"\&",
                '?' => NOTATION.quest,
                '1' => NOTATION.one,
                '⊗' => "⊗",
                '⅋' => "⅋",
                '⊕' => "⊕",
                '⊸' => "⊸",
                '\\' => "backslash",
                '/' => "slash",
                '!' => "!",
                '⊤' => "⊤",
                '⊥' => "⊥",
                '*' => "^*",
                '∧' => "∧",
                '∨' => "∨",
                '→' => "→",
                '¬' => "¬",
                '↔' => "↔",
                '∀' => "forall",
                '∃' => "exists",
                _ => "0",
            }),
            Part::Text(t) => {
                if out.len() > start {
                    out.push(' ');
                }
                text(out, t);
            }
            Part::Sub(t) if t.len() == 1 && t.chars().all(|c| c.is_ascii_digit()) => {
                out.push('_');
                out.push_str(t);
            }
            Part::Sub(t) => {
                out.push_str("_(");
                text(out, t);
                out.push(')');
            }
        }
    }
}

/// Returns `math` in the options' form: as it is, or after the page
/// setup.
fn formed(math: String, options: &Options) -> String {
    match options.form {
        Form::Fragment => math,
        Form::Standalone => format!("{}\n\n{math}", options.page.trim_end()),
    }
}

/// The bytes a sequent's text is estimated at per occurrence, besides
/// its longest atom name: at least what any connective, its brackets and
/// its separator take.
const PER_OCCURRENCE: u64 = 32;

/// Returns a sequent in the options' form: one-sided, or in
/// intuitionistic mode two-sided by its reading.
///
/// # Errors
///
/// [`Refusal::Output`](crate::Refusal::Output) for a sequent whose text is
/// estimated past `limits.derivation_bytes` (`32` bytes an occurrence
/// and its longest atom name), before anything is laid out;
/// [`Error::NotIntuitionistic`] in intuitionistic mode for one without an
/// intuitionistic reading, and the refusal of
/// [`Forest::within`](crate::linear::Forest::within).
pub fn sequent(
    sequent: &Sequent,
    mode: crate::linear::Mode,
    options: &Options,
    limits: &crate::Limits,
) -> Result<String, Error> {
    super::math(sequent, mode, PER_OCCURRENCE, limits, &NOTATION).map(|out| formed(out, options))
}

/// Writes a derivation as a proof tree into `out`, in the options' form,
/// one inference at a time, and asks `stop` after each: a curryst
/// `#prooftree(…)` call, in which a rule with premises spans several
/// lines, indented by its depth, and a leaf is one line; or a `#context`
/// block of deduxit's own layout ([`Options::layout`]), the inferences
/// listed first, from the root in preorder, one line each, then the code
/// that sets them. A linear derivation is two-sided if it is; one of LK
/// or LJ is two-sided, its connectives and constants their Unicode
/// characters `¬ ∧ ∨ → ↔ ⊤ ⊥` and its labels those of [`ordinary::Rule`](crate::ordinary::Rule)
/// (a label table of [`Labels::Table`] is keyed by the linear rules, so it
/// leaves them upright). A `String` takes the whole.
///
/// # Errors
///
/// [`Refusal::Stopped`](crate::Refusal::Stopped) when `stop` fired, and
/// [`Error::WriteFailed`] when `out` refused the text.
pub fn write<'a>(
    derivation: impl Into<Drawable<'a>>,
    options: &Options,
    out: &mut impl Write,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<(), Error> {
    let mut stop = stop;
    let drawable = derivation.into();
    let judgement = super::judgement(
        drawable,
        options.lambda.as_ref(),
        &crate::lambda::print::TYPST,
        &mut stop,
    )?;
    let judgement = judgement.as_deref();
    let stop = crate::limits::counting(stop, crate::limits::Phase::Write);
    match drawable {
        Drawable::Linear(derivation) => tree(derivation, options, judgement, out, stop),
        Drawable::Ordinary(derivation) => tree(derivation, options, judgement, out, stop),
        Drawable::Classical(view) => tree(view, options, judgement, out, stop),
    }
}

/// Writes any derivation as [`write()`] does, in the layout the options
/// choose, and under its conclusion the judgement given.
fn tree<T: Drawn>(
    derivation: &T,
    options: &Options,
    judgement: Option<&str>,
    out: &mut impl Write,
    stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    let own = match options.layout {
        Layout::Curryst => false,
        Layout::Deduxit => true,
        Layout::Auto => height(derivation) > CURRYST_HEIGHT,
    };
    if own {
        laid_out(derivation, options, judgement, out, stop)
    } else {
        curryst(derivation, options, judgement, out, stop)
    }
}

/// Returns the inferences on the longest branch of a derivation.
fn height<T: Drawn>(derivation: &T) -> usize {
    // Premises come before their conclusions, the root last.
    let mut heights = vec![0; derivation.len()];
    for i in 0..heights.len() {
        let premises = derivation.premises(crate::linear::InfId::new(i as u32));
        let above = premises.iter().map(|p| heights[p.index()]);
        heights[i] = 1 + above.max().unwrap_or(0);
    }
    heights.last().copied().unwrap_or(0)
}

/// The Typst code of deduxit's own layout, which follows the inferences
/// (`nodes`: premises, label and conclusion, from the root in preorder;
/// `none` premises for an open goal drawn as `open` says) and the spacing
/// in a `#context` block. It measures every sequent and label, lays the
/// tree out as the SVG drawing does (premises side by side `gap` apart,
/// their conclusions centred over the conclusion, the line spanning both
/// with the label after it) and places every piece in one box: nothing is
/// nested per level, so no height reaches a limit of Typst's. A sequent's
/// ascent is its height less its depth, which a strut of `tall` above it
/// reveals, so that the sequents of a row share a baseline.
const LAYOUT: &str = r#"  let n = nodes.len()
  let tall = (3em).to-absolute()
  let metrics(c) = {
    let size = measure(box(c))
    let low = measure(box[#box(height: tall, width: 0pt)#c]).height - tall
    (size.width, size.height - low, low)
  }
  let (dots-width, dots-up, dots-down) = metrics(dots)
  let (width, up, down, wide, left, offset) = ((0pt,) * n,) * 6
  let bar = (none,) * n
  let names = (none,) * n
  let stack = ()
  for i in range(n - 1, -1, step: -1) {
    let (k, name, c) = nodes.at(i)
    let (w, a, d) = metrics(c)
    width.at(i) = w
    up.at(i) = a
    down.at(i) = d
    if k == none {
      let reach = if open == "dots" { dots-width } else { 0pt }
      wide.at(i) = calc.max(w, reach)
      left.at(i) = calc.max(reach - w, 0pt) / 2
      if open == "dashed" { bar.at(i) = (left.at(i), left.at(i) + w) }
      stack.push(i)
      continue
    }
    let kids = ()
    for _ in range(k) { kids.push(stack.pop()) }
    let x = 0pt
    let span = none
    for p in kids {
      offset.at(p) = x
      let s = x + left.at(p)
      span = (if span == none { s } else { span.at(0 ) }, s + width.at(p))
      x += wide.at(p) + gap
    }
    let (l, b) = if span == none { (0pt, (0pt, w)) } else {
      let l = (span.at(0) + span.at(1) - w) / 2
      (l, (calc.min(span.at(0), l), calc.max(span.at(1), l + w)))
    }
    let shift = calc.max(-l, 0pt)
    for p in kids { offset.at(p) += shift }
    let named = 0pt
    if name != none {
      let size = measure(box(name))
      names.at(i) = (size.width, size.height)
      named = name-gap + size.width
    }
    let row = if k == 0 { 0pt } else { x - gap }
    wide.at(i) = calc.max(row, b.at(1) + named) + shift
    left.at(i) = l + shift
    bar.at(i) = (b.at(0) + shift, b.at(1) + shift)
    stack.push(i)
  }
  let (x, depth) = ((0pt,) * n, (0,) * n)
  let parents = ()
  for i in range(n) {
    if parents.len() > 0 {
      let (p, r) = parents.last()
      x.at(i) = x.at(p) + offset.at(i)
      depth.at(i) = depth.at(p) + 1
      if r == 1 { let _ = parents.pop() } else { parents.at(-1) = (p, r - 1) }
    }
    let k = nodes.at(i).at(0)
    if k != none and k > 0 { parents.push((i, k)) }
  }
  let rows = calc.max(..depth) + 2
  let (row-up, row-down, between) = ((0pt,) * rows,) * 3
  for i in range(n) {
    let j = depth.at(i)
    row-up.at(j) = calc.max(row-up.at(j), up.at(i))
    row-down.at(j) = calc.max(row-down.at(j), down.at(i))
    if bar.at(i) != none {
      let tall = if names.at(i) == none { 0pt } else { names.at(i).at(1) }
      between.at(j) = calc.max(between.at(j), band, tall)
    }
    if nodes.at(i).at(0) == none and open == "dots" {
      between.at(j) = calc.max(between.at(j), band / 2)
      row-up.at(j + 1) = calc.max(row-up.at(j + 1), dots-up)
      row-down.at(j + 1) = calc.max(row-down.at(j + 1), dots-down)
    }
  }
  let base = (0pt,) * rows
  base.at(rows - 1) = row-up.at(rows - 1)
  for j in range(rows - 2, -1, step: -1) {
    base.at(j) = base.at(j + 1) + row-down.at(j + 1) + between.at(j) + row-up.at(j)
  }
  box(width: wide.at(0), height: base.at(0) + row-down.at(0), baseline: row-down.at(0), {
    for i in range(n) {
      let (k, name, c) = nodes.at(i)
      let (j, at) = (depth.at(i), x.at(i))
      place(dx: at + left.at(i), dy: base.at(j) - up.at(i), box(c))
      if k == none and open == "dots" {
        let dx = at + (wide.at(i) - dots-width) / 2
        place(dx: dx, dy: base.at(j + 1) - dots-up, box(dots))
      }
      if bar.at(i) != none {
        let (start, end) = bar.at(i)
        let y = base.at(j) - row-up.at(j) - between.at(j) / 2
        let dash = if k == none { "dashed" } else { none }
        place(dx: at + start, dy: y, line(length: end - start, stroke: (thickness: stroke, dash: dash)))
        if names.at(i) != none {
          let (w, h) = names.at(i)
          place(dx: at + end + name-gap, dy: y - h / 2, box(name))
        }
      }
    }
  })
}
"#;

/// Writes a derivation in deduxit's own layout into `out`, one inference
/// at a time, and asks `stop` after each; with a judgement, the tree and
/// the judgement under it in a stack.
fn laid_out<T: Drawn>(
    derivation: &T,
    options: &Options,
    judgement: Option<&str>,
    out: &mut impl Write,
    mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    if options.form == Form::Standalone {
        write!(out, "{}\n\n", options.page.trim_end())?;
    }
    if judgement.is_some() {
        out.write_str(STACK)?;
    } else {
        out.write_char('#')?;
    }
    let open = match options.open {
        OpenGoal::Dots => "dots",
        OpenGoal::Dashed => "dashed",
        OpenGoal::Bare | OpenGoal::Mark(_) => "bare",
    };
    write!(
        out,
        "context {{\n  let open = \"{open}\"\n  let gap = ({}).to-absolute()\n  \
         let name-gap = ({}).to-absolute()\n  let band = ({}).to-absolute()\n  \
         let stroke = {}\n  let dots = $dots.v$\n  let nodes = (\n",
        options.premise_gap, options.label_gap, options.band, options.stroke
    )?;
    let mut buffer = String::new();
    walk(derivation, |step| {
        let Step::Enter(id, _) = step else {
            return Ok(());
        };
        let markup = derivation.label(id, &options.labels);
        let (premises, name) = match (derivation.is_open(id), &options.open) {
            (true, OpenGoal::Mark(mark)) => ("0".to_owned(), Some(mark.as_str())),
            (true, _) => ("none".to_owned(), None),
            _ => (derivation.premises(id).len().to_string(), markup.as_deref()),
        };
        write!(buffer, "    ({premises}, ")?;
        match name {
            Some(name) => {
                buffer.push('$');
                label(&mut buffer, name);
                buffer.push('$');
            }
            None => buffer.push_str("none"),
        }
        buffer.push_str(", $");
        derivation.sequent(&mut buffer, &NOTATION, id, false, false);
        buffer.push_str("$),\n");
        flush(out, &mut buffer, &mut stop)
    })?;
    out.write_str("  )\n")?;
    out.write_str(LAYOUT.trim_end())?;
    under(out, judgement)
}

/// What opens the stack of a tree and the judgement under it.
const STACK: &str = "#stack(spacing: 0.8em, align(center, ";

/// Closes the stack [`STACK`] opened with the judgement given under the
/// tree, if there is one.
fn under(out: &mut impl Write, judgement: Option<&str>) -> Result<(), Error> {
    if let Some(judgement) = judgement {
        write!(out, "), align(center, ${judgement}$))")?;
    }
    Ok(())
}

/// Writes a derivation as a curryst tree into `out`, one inference at a
/// time, and asks `stop` after each; with a judgement, the tree and the
/// judgement under it in a stack.
fn curryst<T: Drawn>(
    derivation: &T,
    options: &Options,
    judgement: Option<&str>,
    out: &mut impl Write,
    mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    if options.form == Form::Standalone {
        write!(
            out,
            "{}\n{}\n\n",
            options.import.trim_end(),
            options.page.trim_end()
        )?;
    }
    out.write_str(if judgement.is_some() { STACK } else { "#" })?;
    out.write_str("prooftree(\n")?;
    let indent = |out: &mut String, depth: usize| {
        for _ in 0..depth {
            out.push_str("  ");
        }
    };
    let conclusion = |out: &mut String, id| {
        out.push('$');
        derivation.sequent(out, &NOTATION, id, false, false);
        out.push('$');
    };
    let mut buffer = String::new();
    walk(derivation, |step| {
        match step {
            Step::Enter(id, depth) => {
                let premises = derivation.premises(id);
                indent(&mut buffer, depth + 1);
                // A grid of one column is as wide as the sequent, and so
                // is a line across it.
                let open = |out: &mut String, grid: &str| {
                    out.push_str(grid);
                    conclusion(out, id);
                    out.push_str("),\n");
                };
                match (derivation.is_open(id), &options.open) {
                    (true, OpenGoal::Dots) => open(
                        &mut buffer,
                        "grid(align: center, row-gutter: 0.4em, $dots.v$, ",
                    ),
                    (true, OpenGoal::Dashed) => open(
                        &mut buffer,
                        "grid(align: center, inset: (top: 0.3em), \
                         grid.hline(stroke: (dash: \"dashed\")), ",
                    ),
                    (true, OpenGoal::Bare) => {
                        conclusion(&mut buffer, id);
                        buffer.push_str(",\n");
                    }
                    (true, OpenGoal::Mark(mark)) => {
                        buffer.push_str("rule(name: $");
                        label(&mut buffer, mark);
                        buffer.push_str("$, ");
                        conclusion(&mut buffer, id);
                        buffer.push_str("),\n");
                    }
                    _ => {
                        let markup = derivation.label(id, &options.labels);
                        let markup = markup.as_deref();
                        let name = |out: &mut String| {
                            if let Some(markup) = markup {
                                out.push_str("name: $");
                                label(out, markup);
                                out.push('$');
                            }
                        };
                        buffer.push_str("rule(");
                        if premises.is_empty() {
                            name(&mut buffer);
                            if markup.is_some() {
                                buffer.push_str(", ");
                            }
                            conclusion(&mut buffer, id);
                            buffer.push_str("),\n");
                        } else if markup.is_some() {
                            buffer.push('\n');
                            indent(&mut buffer, depth + 2);
                            name(&mut buffer);
                            buffer.push_str(",\n");
                        } else {
                            buffer.push('\n');
                        }
                    }
                }
            }
            Step::Exit(id, depth) => {
                if !derivation.premises(id).is_empty() {
                    indent(&mut buffer, depth + 2);
                    conclusion(&mut buffer, id);
                    buffer.push_str(",\n");
                    indent(&mut buffer, depth + 1);
                    buffer.push_str("),\n");
                }
            }
        }
        flush(out, &mut buffer, &mut stop)
    })?;
    out.write_char(')')?;
    under(out, judgement)
}

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

    /// Returns an atom's name as the Typst export writes it.
    fn escaped(name: &str) -> String {
        let mut out = String::new();
        atom(&mut out, name).unwrap();
        out
    }

    /// A length is a number and a unit, and nothing else reaches the
    /// output as code.
    #[test]
    fn lengths_are_numbers_and_units() {
        for text in ["1.5em", "0pt", "12mm", "2.25in", "3cm"] {
            assert_eq!(Length::new(text).unwrap().as_str(), text);
        }
        for text in [
            "", "em", "1", "1.em", ".5em", "1.5 em", "-1em", "1em)", "1fr", "1em+2pt",
        ] {
            assert!(
                matches!(
                    Length::new(text),
                    Err(Error::InvalidOption { key: "typst", .. })
                ),
                "{text:?}"
            );
        }
    }

    /// One letter stays as it is; every other name is an italic string
    /// with quotes and backslashes escaped.
    #[test]
    fn names_are_escaped() {
        for (name, expected) in [
            ("A", "A"),
            ("α", "α"),
            ("foo", r#"italic("foo")"#),
            ("x_1", r#"italic("x_1")"#),
            (r#"a"b\c"#, r#"italic("a\"b\\c")"#),
        ] {
            assert_eq!(escaped(name), expected, "{name:?}");
        }
    }
}