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

//! LaTeX: formulas in math mode with the connectives of the `cmll` and
//! `amssymb` packages (`\otimes`, `\parr`, `\with`, `\oplus`, `\multimap`,
//! `\oc`, `\wn`, `\mathbf{1}`, `\bot`, `\top`, `0`, `A^\bot`, `\vdash`),
//! and derivations as proof trees of the `ebproof` package, one statement
//! per inference in its postfix order.
//!
//! A fragment is a sequent in `$…$` or a `prooftree` environment, for a
//! document that loads `amssymb`, `cmll` and `ebproof`; a standalone
//! document is of the `standalone` class, which crops the page to the
//! content, and compiles with pdfLaTeX. Neither chooses a font: the output
//! is set in the fonts of the document it goes into. The turnstiles of two-sided
//! sequents are aligned in the tree with ebproof's `&` unless
//! [`Options::align`] is off; one-sided sequents are centred.
//!
//! An atom named by one ASCII letter is written as it is, in math italic,
//! and one named by a Greek letter as its command (`\alpha`, `\Gamma`, or
//! the Latin letter of a capital that looks like one); any other name goes
//! into `\mathit{…}`, with `\ { } $ # % & _` escaped by a backslash, `^`,
//! `~` and `\` written as text, a space kept, a Greek letter as its
//! command in braces, and the `‿` and `·` of the names `lltp::read` makes
//! as `\smallsmile` and `\cdotp`. So names of ASCII and Greek letters and
//! those of the LLTP library compile with pdfLaTeX; any other character
//! is written as it is and needs a Unicode engine such as LuaLaTeX with
//! `unicode-math`, or a declaration of the character for pdfLaTeX.
//!
//! Needs the cargo feature `latex` (on by default).
//!
//! # Examples
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::export::latex;
//! use deduxit::{Limits, linear::{Mode, Options, Sequent, Verdict, prove}};
//!
//! let sequent: Sequent = "A, A -o B |- B".parse()?;
//! let options = latex::Options::default();
//! let printed = latex::sequent(&sequent, Mode::CLASSICAL, &options, &Limits::default())?;
//! assert_eq!(printed, r"$\vdash A^\bot, A \otimes B^\bot, B$");
//!
//! let outcome = prove(&sequent, Mode::INTUITIONISTIC, &Options::default())?;
//! let Verdict::Proved(proof) = &outcome.verdict else {
//!     panic!("provable");
//! };
//! let mut written = String::new();
//! latex::write(&proof.derivation()?, &options, &mut written, |_| false)?;
//! assert_eq!(
//!     written,
//!     r"\begin{prooftree}
//! \infer0[$\mathrm{ax}$]{A &\vdash A}
//! \infer0[$\mathrm{ax}$]{B &\vdash B}
//! \infer2[$\multimap\mathrm{L}$]{A, A \multimap B &\vdash B}
//! \end{prooftree}"
//! );
//! # 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 LaTeX spelling of formulas and sequents.
const NOTATION: Notation = Notation {
    tensor: r"\otimes",
    par: r"\parr",
    with: r"\with",
    plus: r"\oplus",
    lollipop: r"\multimap",
    under: r"\mathbin{\backslash}",
    over: r"\mathbin{/}",
    bang: r"\oc ",
    quest: r"\wn ",
    one: r"\mathbf{1}",
    bot: r"\bot",
    top: r"\top",
    zero: "0",
    dual_prefix: "",
    dual: r"^\bot",
    turnstile: r"\vdash",
    align: "&",
    atom: Atoms::Latex,
    forall: r"\forall ",
    exists: r"\exists ",
    dot: r".\,",
    ordinary: Symbols {
        not: r"\lnot ",
        and: r"\land",
        or: r"\lor",
        implies: r"\to",
        iff: r"\leftrightarrow",
        truth: r"\top",
        falsity: r"\bot",
    },
};

/// The preamble of a standalone document: `amssymb` for `\multimap`,
/// `cmll` for `\parr`, `\with`, `\oc` and `\wn`.
const PREAMBLE: &str = r"\documentclass[border=5pt]{standalone}
\usepackage{amssymb}
\usepackage{cmll}
";

/// Returns the math-mode spelling of a Greek letter: its command, or
/// the Latin letter of a capital that looks like one.
fn greek(c: char) -> Option<&'static str> {
    Some(match c {
        'α' => r"\alpha",
        'β' => r"\beta",
        'γ' => r"\gamma",
        'δ' => r"\delta",
        'ε' => r"\varepsilon",
        'ϵ' => r"\epsilon",
        'ζ' => r"\zeta",
        'η' => r"\eta",
        'θ' => r"\theta",
        'ϑ' => r"\vartheta",
        'ι' => r"\iota",
        'κ' => r"\kappa",
        'λ' => r"\lambda",
        'μ' => r"\mu",
        'ν' => r"\nu",
        'ξ' => r"\xi",
        'ο' => "o",
        'π' => r"\pi",
        'ϖ' => r"\varpi",
        'ρ' => r"\rho",
        'ϱ' => r"\varrho",
        'σ' => r"\sigma",
        'ς' => r"\varsigma",
        'τ' => r"\tau",
        'υ' => r"\upsilon",
        'φ' => r"\varphi",
        'ϕ' => r"\phi",
        'χ' => r"\chi",
        'ψ' => r"\psi",
        'ω' => r"\omega",
        'Γ' => r"\Gamma",
        'Δ' => r"\Delta",
        'Θ' => r"\Theta",
        'Λ' => r"\Lambda",
        'Ξ' => r"\Xi",
        'Π' => r"\Pi",
        'Σ' => r"\Sigma",
        'Υ' => r"\Upsilon",
        'Φ' => r"\Phi",
        'Ψ' => r"\Psi",
        'Ω' => r"\Omega",
        'Α' => "A",
        'Β' => "B",
        'Ε' => "E",
        'Ζ' => "Z",
        'Η' => "H",
        'Ι' => "I",
        'Κ' => "K",
        'Μ' => "M",
        'Ν' => "N",
        'Ο' => "O",
        'Ρ' => "P",
        'Τ' => "T",
        'Χ' => "X",
        _ => return None,
    })
}

/// 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()) {
        if c.is_ascii_alphabetic() {
            return out.write_char(c);
        }
        if let Some(letter) = greek(c) {
            return out.write_str(letter);
        }
    }
    out.write_str(r"\mathit{")?;
    for c in name.chars() {
        escape(out, c)?;
    }
    out.write_char('}')
}

/// Writes a character of text in math mode, escaped.
fn escape(out: &mut (impl Write + ?Sized), c: char) -> std::fmt::Result {
    match c {
        '\\' => out.write_str(r"\mbox{\textbackslash}"),
        '{' | '}' | '$' | '#' | '%' | '&' | '_' => {
            out.write_char('\\')?;
            out.write_char(c)
        }
        '^' => out.write_str(r"\mbox{\textasciicircum}"),
        '~' => out.write_str(r"\mbox{\textasciitilde}"),
        ' ' => out.write_str(r"\ "),
        // `lltp::HYPHEN` and `lltp::DOT`, spelt out since `lltp` needs the
        // `parse` feature.
        '‿' => out.write_str(r"{\smallsmile}"),
        '·' => out.write_str(r"{\cdotp}"),
        // Braces keep a letter that follows from joining the command.
        c => match greek(c) {
            Some(letter) if letter.starts_with('\\') => write!(out, "{{{letter}}}"),
            Some(letter) => out.write_str(letter),
            None => out.write_char(c),
        },
    }
}

/// What a user may vary in the LaTeX 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 `\vdots`, bare (`\hypo`), under a
    /// line with a mark, or under ebproof's dashed line.
    pub open: OpenGoal,
    /// Whether the turnstiles of a two-sided tree line up (ebproof's `&`).
    pub align: bool,
    /// The options of every `prooftree` environment, as ebproof reads
    /// them between brackets, or empty for none.
    pub ebproof: String,
    /// What a standalone document starts with, before
    /// `\begin{document}`, or `None` for a `standalone` class cropped to
    /// the content with `amssymb`, `cmll` and, for a tree, `ebproof`. A
    /// preamble of the user's must load those packages itself.
    pub preamble: Option<String>,
    /// 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, aligned turnstiles, no ebproof options and the
    /// `standalone` preamble.
    fn default() -> Self {
        Self {
            form: Form::Fragment,
            labels: Labels::Upright,
            open: OpenGoal::Dots,
            align: true,
            ebproof: String::new(),
            preamble: None,
            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 [`align`](Self::align).
    #[must_use]
    pub fn with_align(self, align: bool) -> Self {
        Self { align, ..self }
    }

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

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

/// Writes a label's markup in math mode: symbols as the connectives,
/// text in `\mathrm`, subscripts after `_`.
fn label(out: &mut String, markup: &str) {
    let text = |out: &mut String, text: &str| {
        out.push_str(r"\mathrm{");
        for c in text.chars() {
            escape(out, c).unwrap();
        }
        out.push('}');
    };
    for part in parts(markup) {
        match part {
            Part::Symbol(c) => out.push_str(match c {
                '⊗' => NOTATION.tensor,
                '⅋' => NOTATION.par,
                '&' => NOTATION.with,
                '⊕' => NOTATION.plus,
                '⊸' => NOTATION.lollipop,
                '\\' => r"\backslash",
                '/' => "/",
                '!' => r"\oc",
                '?' => r"\wn",
                '⊤' => NOTATION.top,
                '⊥' => NOTATION.bot,
                '1' => NOTATION.one,
                '*' => "^{*}",
                '∧' => NOTATION.ordinary.and,
                '∨' => NOTATION.ordinary.or,
                '→' => NOTATION.ordinary.implies,
                '¬' => r"\lnot",
                '↔' => NOTATION.ordinary.iff,
                '∀' => r"\forall",
                '∃' => r"\exists",
                _ => NOTATION.zero,
            }),
            Part::Text(t) => 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('}');
            }
        }
    }
}

/// Writes the start of a standalone document, with `ebproof` loaded if
/// `tree` is set.
fn begin(out: &mut impl Write, options: &Options, tree: bool) -> std::fmt::Result {
    match &options.preamble {
        Some(preamble) => writeln!(out, "{}", preamble.trim_end())?,
        None => {
            out.write_str(PREAMBLE)?;
            if tree {
                out.write_str("\\usepackage{ebproof}\n")?;
            }
        }
    }
    out.write_str("\\begin{document}\n")
}

/// Returns `math` in the options' form: as it is, or in a standalone
/// document.
fn formed(math: String, options: &Options) -> String {
    match options.form {
        Form::Fragment => math,
        Form::Standalone => {
            let mut out = String::new();
            begin(&mut out, options, false).expect("a string takes any text");
            out.push_str(&math);
            out.push_str("\n\\end{document}");
            out
        }
    }
}

/// 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 an ebproof `prooftree` environment into `out`,
/// in the options' form, one inference at a time, and asks `stop` after
/// each: a linear one two-sided if it is, one of LK or LJ two-sided with
/// the turnstiles lined up unless [`Options::align`] is off, its
/// connectives `\lnot`, `\land`, `\lor`, `\to` and `\leftrightarrow`, its
/// constants `\top` and `\bot` 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::LATEX,
        &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, and under its conclusion the
/// judgement given.
fn tree<T: Drawn>(
    derivation: &T,
    options: &Options,
    judgement: Option<&str>,
    out: &mut impl Write,
    mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    let standalone = options.form == Form::Standalone;
    if standalone {
        begin(out, options, true)?;
    }
    out.write_str("\\begin{prooftree}")?;
    if !options.ebproof.is_empty() {
        write!(out, "[{}]", options.ebproof)?;
    }
    out.write_char('\n')?;
    let mut buffer = String::new();
    walk(derivation, |step| {
        let Step::Exit(id, _) = step else {
            return Ok(());
        };
        let markup = derivation.label(id, &options.labels);
        let markup = markup.as_deref();
        match (derivation.is_open(id), &options.open) {
            (true, OpenGoal::Dots) => buffer.push_str("\\hypo{\\vdots}\n\\infer[no rule]1"),
            (true, OpenGoal::Bare) => buffer.push_str("\\hypo"),
            (true, OpenGoal::Dashed) => buffer.push_str("\\infer[dashed]0"),
            (true, OpenGoal::Mark(mark)) => {
                buffer.push_str("\\infer0[$");
                label(&mut buffer, mark);
                buffer.push_str("$]");
            }
            _ => {
                buffer.push_str("\\infer");
                buffer.push_str(&derivation.premises(id).len().to_string());
                if let Some(markup) = markup {
                    buffer.push_str("[$");
                    label(&mut buffer, markup);
                    buffer.push_str("$]");
                }
            }
        }
        buffer.push('{');
        derivation.sequent(&mut buffer, &NOTATION, id, options.align, false);
        buffer.push_str("}\n");
        flush(out, &mut buffer, &mut stop)
    })?;
    if let Some(judgement) = judgement {
        writeln!(out, "\\infer[no rule]1{{{judgement}}}")?;
    }
    out.write_str("\\end{prooftree}")?;
    if standalone {
        out.write_str("\n\\end{document}")?;
    }
    Ok(())
}

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

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

    /// One ASCII letter stays as it is and one Greek letter is its
    /// command; every other name is set in `\mathit` with the special
    /// characters escaped and Greek letters and `lltp`'s marks as commands
    /// in braces.
    #[test]
    fn names_are_escaped() {
        for (name, expected) in [
            ("A", "A"),
            ("p", "p"),
            ("foo", r"\mathit{foo}"),
            ("x_1", r"\mathit{x\_1}"),
            ("α", r"\alpha"),
            ("Γ", r"\Gamma"),
            ("Α", "A"),
            ("αβ", r"\mathit{{\alpha}{\beta}}"),
            ("Οx", r"\mathit{Ox}"),
            ("P‿a·b", r"\mathit{P{\smallsmile}a{\cdotp}b}"),
            ("é", r"\mathit{é}"),
            (
                r"a{b}$#%&^~\ c",
                r"\mathit{a\{b\}\$\#\%\&\mbox{\textasciicircum}\mbox{\textasciitilde}\mbox{\textbackslash}\ c}",
            ),
        ] {
            assert_eq!(escaped(name), expected, "{name:?}");
        }
    }
}