deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! What every output that draws a derivation shares: the labels of the
//! rules and the shape of an open goal.
//!
//! Each label convention is written once, in a small markup that each
//! output typesets its own way:
//!
//! - the connective and unit characters `⊗ ⅋ & ⊕ ⊸ \ / ! ? ⊤ ⊥ 0 1`, the
//!   quantifiers `∀ ∃`, and the connectives of ordinary logic
//!   `∧ ∨ → ¬ ↔` (for the labels of LK and LJ, such as `→L`) are symbols;
//! - `*` is a symbol too, set as a superscript where the output can: it
//!   marks a run of one rule (`?w*`);
//! - `_x` or `_{xy}` is a subscript;
//! - every other character is upright text.
//!
//! So `⊸L` is `⊸` followed by an upright `L`, and `&L_1` has the
//! subscript `1`.
//!
//! Every output draws a derivation through the crate-private trait
//! `Drawn`, which the linear derivations and those of LK and LJ
//! implement.

use super::derivation::{Derivation, InfId};
use super::{Named, Rule};
#[cfg(any(feature = "latex", feature = "typst"))]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Write;

/// How the rules of a derivation are labelled.
///
/// In JSON (feature `serialize`) it is `"upright"`, `"subscript"`,
/// `"off"`, or `{"table": {"⊗": "\\otimes", …}}` keyed by the rules'
/// names.
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Labels {
    /// The connective with an upright `L` or `R` and the subscripts `1`
    /// and `2`: `⊸L`, `&L₁`, `?d`, as [`Named::name`] spells them.
    #[default]
    Upright,
    /// The side, and the letter of an exponential rule, as a subscript:
    /// `⊸_L`, `&_{L1}`, `?_d`.
    Subscript,
    /// No labels.
    Off,
    /// Your own labels by rule, in the [label markup](crate::linear::proofs::style).
    /// A rule the table leaves out keeps its upright label.
    Table(BTreeMap<Named, String>),
}

/// How many rules the label tables hold: [`Named::ALL`], then the
/// divisions of the Lambek calculus.
const LABELLED: usize = Named::ALL.len() + Named::DIVISIONS.len();

/// The labels of the upright convention, by rule in the order of
/// [`Named::ALL`], then `\L`, `\R`, `/L` and `/R`.
const UPRIGHT: [&str; LABELLED] = [
    "ax", "⊗", "⅋", "1", "⊥", "&", "⊕_1", "⊕_2", "⊤", "!", "?d", "?c", "?w", "mix", "wk", "cut",
    "∀", "∃", "⊸L", "⊸R", "⊗L", "⊗R", "&L_1", "&L_2", "&R", "⊕L", "⊕R_1", "⊕R_2", "1L", "1R", "0L",
    "⊤R", "!L", "!R", "!c", "!w", "∀R", "∃L", "∃R", "∀L", "", "\\L", "\\R", "/L", "/R",
];

/// The labels of the subscript convention, in the order of [`UPRIGHT`].
const SUBSCRIPT: [&str; LABELLED] = [
    "ax", "⊗", "⅋", "1", "⊥", "&", "⊕_1", "⊕_2", "⊤", "!", "?_d", "?_c", "?_w", "mix", "wk", "cut",
    "∀", "∃", "⊸_L", "⊸_R", "⊗_L", "⊗_R", "&_{L1}", "&_{L2}", "&_R", "⊕_L", "⊕_{R1}", "⊕_{R2}",
    "1_L", "1_R", "0_L", "⊤_R", "!_L", "!_R", "!_c", "!_w", "∀_R", "∃_L", "∃_R", "∀_L", "", "\\_L",
    "\\_R", "/_L", "/_R",
];

impl Labels {
    /// Returns the label of a rule in the [label
    /// markup](crate::linear::proofs::style), or `None` where the rule has
    /// none: an open goal, or every rule when labels are off.
    pub fn markup(&self, rule: Named) -> Option<&str> {
        let index = rule.index();
        let label = match self {
            Self::Upright => UPRIGHT[index],
            Self::Subscript => SUBSCRIPT[index],
            Self::Off => return None,
            Self::Table(table) => table.get(&rule).map_or(UPRIGHT[index], String::as_str),
        };
        (rule.rule != Rule::Open && !label.is_empty()).then_some(label)
    }
}

/// The mark at the end of the label of an inference that stands for a run
/// of a structural rule, as in `?w*`.
pub(crate) const RUN: &str = "*";

/// One part of a label's markup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Part<'a> {
    /// A symbol: a connective, unit or quantifier character, or `*`.
    Symbol(char),
    /// Text set upright.
    Text(&'a str),
    /// A subscript, its text set upright.
    Sub(&'a str),
    /// A superscript, its text set upright: the marks of the hypotheses a
    /// rule of natural deduction discharges.
    Sup(&'a str),
}

/// The mark before a character of a label that is text, whatever the
/// markup makes of it otherwise: a rule file's rule named `and_intro`
/// writes its `_` so. No label typed by hand holds it, being a control
/// character.
pub(crate) const LITERAL: char = '\u{7}';

/// The mark before a `{…}` group of a label set as a superscript: the
/// marks of the hypotheses a rule discharges, `→I¹`. A control character,
/// so no label typed by hand holds it.
pub(crate) const RAISED: char = '\u{8}';

/// Returns whether a character of a label is a symbol.
fn symbol(c: char) -> bool {
    matches!(
        c,
        '⊗' | '⅋'
            | '&'
            | '⊕'
            | '⊸'
            | '\\'
            | '/'
            | '!'
            | '?'
            | '⊤'
            | '⊥'
            | '0'
            | '1'
            | '*'
            | '∧'
            | '∨'
            | '→'
            | '¬'
            | '↔'
            | '∀'
            | '∃'
    )
}

/// Returns the parts of a label's markup in order. A `_` at the end
/// gives an empty subscript, and a `{` that is never closed makes the
/// rest of the label its subscript.
pub(crate) fn parts(markup: &str) -> Vec<Part<'_>> {
    let mut parts = Vec::new();
    let mut rest = markup;
    while let Some(c) = rest.chars().next() {
        if c == RAISED {
            let after = &rest[c.len_utf8()..];
            let (group, next) = match after.strip_prefix('{') {
                Some(group) => group.split_once('}').unwrap_or((group, "")),
                None => ("", after),
            };
            parts.push(Part::Sup(group));
            rest = next;
        } else if c == LITERAL {
            let after = &rest[c.len_utf8()..];
            let next = after.chars().next().map_or(0, char::len_utf8);
            if next > 0 {
                parts.push(Part::Text(&after[..next]));
            }
            rest = &after[next..];
        } else if c == '_' {
            let after = &rest[1..];
            let (sub, next) = match after.strip_prefix('{') {
                Some(group) => group.split_once('}').unwrap_or((group, "")),
                None => after.split_at(after.chars().next().map_or(0, char::len_utf8)),
            };
            parts.push(Part::Sub(sub));
            rest = next;
        } else if symbol(c) {
            parts.push(Part::Symbol(c));
            rest = &rest[c.len_utf8()..];
        } else {
            let end = rest
                .find(|c: char| c == '_' || c == LITERAL || c == RAISED || symbol(c))
                .unwrap_or(rest.len());
            parts.push(Part::Text(&rest[..end]));
            rest = &rest[end..];
        }
    }
    parts
}

/// Returns a character raised as Unicode writes it: a digit as its
/// superscript character, anything else as it is.
pub(crate) fn superscript(c: char) -> char {
    match c {
        '1' => '¹',
        '2' => '²',
        '3' => '³',
        '0' | '4'..='9' => c
            .to_digit(10)
            .and_then(|d| char::from_u32(0x2070 + d))
            .unwrap_or(c),
        c => c,
    }
}

/// Returns a label's markup as plain Unicode text: subscript digits
/// become subscript characters, and everything else stays as it is.
pub(crate) fn plain(markup: &str) -> String {
    let mut out = String::new();
    for part in parts(markup) {
        match part {
            Part::Symbol(c) => out.push(c),
            Part::Text(text) => out.push_str(text),
            Part::Sub(text) => out.extend(text.chars().map(|c| match c.to_digit(10) {
                Some(d) => char::from_u32(0x2080 + d).unwrap(),
                None => c,
            })),
            Part::Sup(text) => out.extend(text.chars().map(superscript)),
        }
    }
    out
}

/// What an output needs from a derivation to draw it: the tree, each
/// inference's rule and label, and each inference's sequent, as text or
/// in a target's notation. The linear derivations and those of LK and LJ
/// implement it, so every output draws both.
pub(crate) trait Drawn {
    /// Returns how many rules the calculus has: a rule is a number below
    /// it.
    fn rules(&self) -> usize;

    /// Returns the rule of an open goal, if the calculus has one.
    fn open(&self) -> Option<usize>;

    /// Returns the label of a rule under `labels`, in the label markup, or
    /// `None` where it has none: an open goal, or every rule when labels
    /// are off.
    fn markup<'a>(&'a self, rule: usize, labels: &'a Labels) -> Option<&'a str>;

    /// Returns the number of inferences.
    fn len(&self) -> usize;

    /// Returns the root, the last inference.
    fn root(&self) -> InfId;

    /// Returns the premises of an inference, in the rule's order; each
    /// precedes it.
    fn premises(&self, id: InfId) -> &[InfId];

    /// Returns the rule of an inference, a number below [`rules`](Self::rules).
    fn rule(&self, id: InfId) -> usize;

    /// Returns the name of an inference's rule, as the numbered list of
    /// steps writes it.
    fn name(&self, id: InfId) -> &str;

    /// Returns how many applications of its rule an inference stands for.
    fn times(&self, id: InfId) -> u32;

    /// Writes the sequent an inference concludes in Unicode, as the text
    /// tree shows it.
    fn write_sequent(&self, out: &mut impl Write, id: InfId) -> std::fmt::Result;

    /// Writes the sequent an inference concludes in a target's notation,
    /// as [`Notation::sequent`](crate::linear::sequents::notation::Notation::sequent)
    /// does with `aligned` and `marks`.
    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    fn sequent(
        &self,
        out: &mut String,
        notation: &crate::linear::sequents::notation::Notation,
        id: InfId,
        aligned: bool,
        marks: bool,
    );

    /// Returns the positions of the formulas of an inference's sequent in
    /// the order [`sequent`](Self::sequent) writes them, hypotheses first.
    #[cfg(feature = "svg")]
    fn positions(&self, id: InfId) -> Vec<usize>;

    /// Returns whether an inference is an open goal.
    fn is_open(&self, id: InfId) -> bool {
        self.open() == Some(self.rule(id))
    }

    /// Returns the rule whose inferences are drawn as their sequent alone,
    /// with no line and no label, if the calculus has one: a hypothesis of
    /// natural deduction, which stands at a leaf as a formula, as
    /// textbooks draw it.
    fn bare(&self) -> Option<usize> {
        None
    }

    /// Returns whether an inference is drawn as its sequent alone
    /// ([`bare`](Self::bare)).
    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    fn is_bare(&self, id: InfId) -> bool {
        self.bare() == Some(self.rule(id))
    }

    /// Returns the label of an inference as [`markup`](Self::markup) does,
    /// followed by [`RUN`] when the inference stands for a run of its rule.
    #[cfg(any(feature = "latex", feature = "typst"))]
    fn label<'l>(&'l self, id: InfId, labels: &'l Labels) -> Option<Cow<'l, str>> {
        let markup = self.markup(self.rule(id), labels)?;
        Some(match self.times(id) {
            1 => Cow::Borrowed(markup),
            _ => Cow::Owned(format!("{markup}{RUN}")),
        })
    }
}

impl Drawn for Derivation<'_> {
    fn rules(&self) -> usize {
        LABELLED
    }

    fn open(&self) -> Option<usize> {
        Some(Named::new(Rule::Open, None).index())
    }

    fn markup<'a>(&'a self, rule: usize, labels: &'a Labels) -> Option<&'a str> {
        labels.markup(Named::at(rule))
    }

    fn len(&self) -> usize {
        self.inferences().len()
    }

    fn root(&self) -> InfId {
        Derivation::root(self)
    }

    fn premises(&self, id: InfId) -> &[InfId] {
        &self.inference(id).premises
    }

    fn rule(&self, id: InfId) -> usize {
        self.inference(id).rule.index()
    }

    fn name(&self, id: InfId) -> &'static str {
        self.inference(id).rule.name()
    }

    fn times(&self, id: InfId) -> u32 {
        self.inference(id).times
    }

    fn write_sequent(&self, out: &mut impl Write, id: InfId) -> std::fmt::Result {
        super::fmt::write_sequent(
            out,
            self.forest(),
            self.reading(),
            self.framing(),
            &self.inference(id).sequent,
        )
    }

    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    fn sequent(
        &self,
        out: &mut String,
        notation: &crate::linear::sequents::notation::Notation,
        id: InfId,
        aligned: bool,
        marks: bool,
    ) {
        let sequent = &self.inference(id).sequent;
        notation
            .sequent(
                out,
                self.forest(),
                self.reading(),
                self.framing(),
                sequent,
                aligned,
                marks,
            )
            .unwrap();
    }

    #[cfg(feature = "svg")]
    fn positions(&self, id: InfId) -> Vec<usize> {
        let sequent = &self.inference(id).sequent;
        match (self.reading(), self.framing()) {
            // An instance's side is its occurrence's.
            (Some(reading), Some(framing)) => reading
                .written_by(sequent, |m| framing.occurrence(m))
                .collect(),
            (Some(reading), None) => reading.written(sequent).collect(),
            (None, _) => (0..sequent.len()).collect(),
        }
    }
}

/// How an open goal of a proof in progress is drawn.
///
/// In JSON (feature `serialize`) it is `"dots"`, `"bare"`, `"dashed"`, or
/// `{"mark": "?"}`.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum OpenGoal {
    /// Its sequent under vertical dots.
    Dots,
    /// Its sequent alone.
    Bare,
    /// Its sequent under an inference line labelled with this text, in the
    /// [label markup](crate::linear::proofs::style): `?`, or a name.
    Mark(String),
    /// Its sequent under a dashed line where the output can draw one, else
    /// under vertical dots.
    Dashed,
}

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

    /// Every rule's name parses back to the rule, and each upright label,
    /// written as plain text, is the rule's name.
    #[test]
    fn names_round_trip() {
        for rule in Named::ALL.into_iter().chain(Named::DIVISIONS) {
            assert_eq!(rule.name().parse::<Named>().unwrap(), rule, "{rule:?}");
            if rule.rule != Rule::Open {
                let label = Labels::Upright.markup(rule).unwrap();
                assert_eq!(plain(label), rule.name(), "{rule:?}");
            }
        }
    }

    /// Markup splits into symbols, upright text and subscripts.
    #[test]
    fn markup_parts() {
        use Part::*;
        assert_eq!(
            parts("&L_1"),
            [Symbol('&'), Text("L"), Sub("1")],
            "a subscript of one character"
        );
        assert_eq!(parts("⊕_{R2}x"), [Symbol('⊕'), Sub("R2"), Text("x")]);
        assert_eq!(parts("ax"), [Text("ax")]);
        assert_eq!(parts("a_"), [Text("a"), Sub("")]);
    }
}