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

//! Problems of the LLTP library (`github.com/meta-logic/lltp`), the
//! benchmark collection of linear logic provers: TPTP-style files of
//! `fof(name, role, formula).` clauses whose axioms are the hypotheses and
//! whose conjecture is the goal. The formulas are written as this crate's
//! parser reads them (`*`, `|`, `&`, `+`, `-o`, `!`, `?`, postfix `^`,
//! `1`, `0`, `bot`, `top`), with the same precedences, so a problem is
//! read by assembling `axioms |- conjecture` and parsing that.
//!
//! The file says nothing about the mode: the library keeps its
//! intuitionistic problems under `ILL/` and its classical ones under
//! `CLL/`, and the caller picks the mode by that.
//!
//! # Examples
//!
//! ```
//! use deduxit::Limits;
//! use deduxit::linear::lltp::{Status, read};
//!
//! let text = "% Status (intuit.) : Theorem\n\
//!             fof(ax1, axiom, !(a -o b)).\n\
//!             fof(ax2, axiom, a).\n\
//!             fof(con, conjecture, b * 1).\n";
//! let problem = read(text, &Limits::default())?;
//! assert_eq!(problem.status, Some(Status::Theorem));
//! assert_eq!(problem.sequent, "!(a -o b), a |- b * 1".parse()?);
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! Needs the cargo feature `parse` (on by default).

use crate::Limits;
use crate::errors::ParseError;
use crate::{Error, linear::Sequent};

/// What stands for a `-` inside an atom name, as the library's Petri nets
/// write them (`P-start_1_1`): this crate's names cannot hold a `-`, which
/// starts the operator `-o`, and `‿` is a character that joins words in a
/// Unicode identifier.
pub const HYPHEN: char = '‿';

/// What stands for a `.` inside an atom name, as some of the library's
/// Petri nets write them (`merge.s00001061.input`): a `.` ends a clause in
/// the file and is no name character here, and `·` is one in a Unicode
/// identifier.
pub const DOT: char = '·';

/// A problem read from an LLTP file.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Problem {
    /// The sequent of the problem: the axioms, in the order of the file,
    /// left of `⊢`, the conjecture right of it.
    pub sequent: Sequent,
    /// The provability the file's header claims, if it has a `Status`
    /// line this reader understands.
    pub status: Option<Status>,
}

/// The provability an LLTP header claims.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    /// `Theorem`: the sequent is provable.
    Theorem,
    /// `Non-Theorem` or `CounterSatisfiable`: the sequent is not provable.
    NonTheorem,
}

/// Reads an LLTP problem. Every `fof` clause with the role `axiom` or
/// `hypothesis` is a hypothesis and the one with the role `conjecture`
/// the formula on the right of `⊢`; lines from `%` on are comments. The
/// status is the first `Status (intuit.)` or `Status (linear)` comment's,
/// else the first plain `Status` comment's: the library's translations of
/// intuitionistic problems keep the classical source's status first. A
/// `-` inside an atom name becomes [`HYPHEN`], a `.` [`DOT`], unless the
/// `-` starts `-o` with a space or the end of the name after it: `a-o b`
/// is `a ⊸ b`, and `a-ob`, which is both, is refused.
///
/// # Errors
///
/// [`Error::Lltp`] for text that is not a sequence of `fof(name, role,
/// formula).` clauses (an annotation after the formula or an empty
/// formula included), a clause with another role or `-o` between two
/// characters of a name,
/// [`Error::SeveralConjectures`] for a file with more than one conjecture,
/// whose meaning in linear logic no convention fixes, and
/// [`Error::Parse`] for a formula this crate's parser rejects, its place
/// that in the file, and the parser's refusal of a sequent past
/// `limits.occurrences`.
pub fn read(text: &str, limits: &Limits) -> Result<Problem, Error> {
    let clauses = clauses(text, |message| Error::Lltp { message })?;
    // The sequent as text, and where each formula of the file starts in it.
    let mut sequent = String::new();
    let mut pieces = Vec::new();
    let ranges = clauses.hypotheses.iter().chain([&clauses.conjecture]);
    for (i, range) in ranges.enumerate() {
        sequent.push_str(match i {
            0 => "",
            _ if i == clauses.hypotheses.len() => " |- ",
            _ => ", ",
        });
        pieces.push((sequent.len(), range.clone()));
        sequent.push_str(&clauses.code[range.clone()]);
    }
    if clauses.hypotheses.is_empty() {
        sequent.insert_str(0, "|- ");
        pieces[0].0 += 3;
    }
    let sequent = Sequent::parse_within(&sequent, limits).map_err(|error| match error {
        Error::Parse(error) => {
            // The formula a byte of the sequent belongs to, and where in
            // the file's text: past a formula's end is that end.
            let at = |byte: usize| {
                let (start, range) = pieces
                    .iter()
                    .rev()
                    .find(|(start, _)| *start <= byte)
                    .unwrap_or(&pieces[0]);
                let offset = byte.saturating_sub(*start);
                (range.start + offset.min(range.len()), offset >= range.len())
            };
            Error::Parse(Box::new(clauses.located(text, &error, at)))
        }
        other => other,
    })?;
    Ok(Problem {
        sequent,
        status: clauses.status,
    })
}

/// The clauses of a TPTP-style file: its text with names made readable,
/// the ranges of its formulas in that text by role, and its status.
pub(crate) struct Clauses {
    /// The file's text without comments, a `-` inside a name as
    /// [`HYPHEN`] and a `.` as [`DOT`].
    code: String,
    /// The formulas of the clauses with the role `axiom` or `hypothesis`.
    hypotheses: Vec<std::ops::Range<usize>>,
    /// The formula of the one clause with the role `conjecture`.
    conjecture: std::ops::Range<usize>,
    /// The provability the header claims.
    pub(crate) status: Option<Status>,
}

impl Clauses {
    /// Returns the hypotheses' formulas, in the order of the file.
    pub(crate) fn hypotheses(&self) -> impl Iterator<Item = &str> {
        self.hypotheses.iter().map(|r| &self.code[r.clone()])
    }

    /// Returns the text of the clauses: the file's without comments,
    /// with the names made readable.
    pub(crate) fn code(&self) -> &str {
        &self.code
    }

    /// Returns the conjecture's formula.
    pub(crate) fn conjecture(&self) -> &str {
        &self.code[self.conjecture.clone()]
    }

    /// Returns the byte of `file`, the text these clauses were read from,
    /// where byte `at` of their text stands. The text keeps the file's
    /// lines and puts one character for each, up to a comment, so the
    /// line and the character in it are the file's.
    fn in_file(&self, file: &str, at: usize) -> usize {
        let before = &self.code[..at];
        let line = before.matches('\n').count();
        let column = before[before.rfind('\n').map_or(0, |n| n + 1)..]
            .chars()
            .count();
        let start: usize = file.split_inclusive('\n').take(line).map(str::len).sum();
        let rest = &file[start..];
        start
            + rest
                .char_indices()
                .nth(column)
                .map_or(rest.len(), |(i, _)| i)
    }

    /// Returns a parse error of the clauses' formulas with its place in
    /// `file`, the text they were read from, `at` mapping a byte of the
    /// parsed text to a byte of theirs and whether it lies at a formula's
    /// end or past it: such an error is at the next character of the file
    /// that is no white space, where the formula should have gone on.
    pub(crate) fn located(
        &self,
        file: &str,
        error: &ParseError,
        at: impl Fn(usize) -> (usize, bool),
    ) -> ParseError {
        let (byte, ended) = at(error.span.start);
        let mut start = self.in_file(file, byte);
        if ended {
            let rest = &file[start..];
            start += rest.len() - rest.trim_start().len();
        }
        // An error that spans a word, or carries a hint, keeps both.
        if error.hint.is_some() || error.span.len() > 1 {
            let end = self.in_file(file, at(error.span.end).0);
            let mut placed = ParseError::spanning(file, start..end.max(start), error.expected);
            if let Some(hint) = error.hint {
                placed = placed.with_hint(hint);
            }
            return placed;
        }
        ParseError::new(file, start, error.expected)
    }
}

/// Splits a file of `fof(name, role, formula).` clauses as [`read`]
/// describes, with every error of the file's form made by `error`: every
/// formula is not empty, and there is exactly one conjecture.
pub(crate) fn clauses(text: &str, error: fn(String) -> Error) -> Result<Clauses, Error> {
    // The status of a line for the logic of the problem, and of a plain one.
    let (mut status, mut plain) = (None, None);
    let mut code = String::with_capacity(text.len());
    for line in text.lines() {
        let (before, comment) = line.split_once('%').unwrap_or((line, ""));
        if let Some((key, word)) = comment
            .split_once("Status")
            .and_then(|(_, r)| r.rsplit_once(':'))
        {
            let word = word.trim();
            let value = if word.starts_with("Theorem") {
                Some(Status::Theorem)
            } else if word.starts_with("Non-Theorem") || word.starts_with("CounterSatisfiable") {
                Some(Status::NonTheorem)
            } else {
                None
            };
            let slot = if key.contains("(intuit") || key.contains("(linear") {
                &mut status
            } else {
                &mut plain
            };
            if slot.is_none() {
                *slot = value;
            }
        }
        let chars: Vec<char> = before.chars().collect();
        for (i, &c) in chars.iter().enumerate() {
            let name = |j: usize| {
                chars
                    .get(j)
                    .is_some_and(|&c| c.is_ascii_alphanumeric() || c == '_')
            };
            // A `-` or `.` between two characters of a name belongs to the
            // name, unless the `-` starts the operator `-o`; between two
            // names `-o` is both, and refused.
            let inner = i > 0 && name(i - 1) && name(i + 1);
            code.push(match c {
                '-' if inner && !(chars[i + 1] == 'o' && !name(i + 2)) => {
                    if chars[i + 1] == 'o' {
                        return Err(error(glued(&chars, i)));
                    }
                    HYPHEN
                }
                '.' if inner => DOT,
                c => c,
            });
        }
        code.push('\n');
    }

    let mut hypotheses = Vec::new();
    let mut conjecture = None;
    let mut rest = code.trim_start();
    while !rest.is_empty() {
        let body = rest
            .strip_prefix("fof")
            .map(str::trim_start)
            .and_then(|r| r.strip_prefix('('))
            .ok_or_else(|| error(format!("expected `fof(` at `{}`", excerpt(rest))))?;
        let (name, body) = body
            .split_once(',')
            .ok_or_else(|| error(format!("a clause without a role at `{}`", excerpt(rest))))?;
        let name = name.trim();
        let (role, body) = body
            .split_once(',')
            .ok_or_else(|| error(format!("clause `{name}` has no formula")))?;
        // The formula runs to the parenthesis that closes `fof(`; a comma
        // outside its parentheses starts an annotation.
        let mut depth = 1usize;
        let end = body
            .char_indices()
            .find(|&(_, c)| {
                match c {
                    '(' => depth += 1,
                    ')' => depth -= 1,
                    _ => {}
                }
                depth == 0 || (depth == 1 && c == ',')
            })
            .ok_or_else(|| error(format!("clause `{name}` is not closed")))?;
        if end.1 == ',' {
            return Err(error(format!(
                "clause `{name}` has an annotation, which this reader does not take"
            )));
        }
        let end = end.0;
        let formula = body[..end].trim();
        if formula.is_empty() {
            return Err(error(format!("clause `{name}` has an empty formula")));
        }
        let start = formula.as_ptr() as usize - code.as_ptr() as usize;
        let range = start..start + formula.len();
        match role.trim() {
            "axiom" | "hypothesis" => hypotheses.push(range),
            "conjecture" if conjecture.is_some() => {
                return Err(Error::SeveralConjectures {
                    second: name.to_owned(),
                });
            }
            "conjecture" => conjecture = Some(range),
            other => {
                return Err(error(format!(
                    "clause `{name}` has the role `{other}`, not axiom, hypothesis or conjecture"
                )));
            }
        }
        rest = body[end + 1..]
            .trim_start()
            .strip_prefix('.')
            .ok_or_else(|| error(format!("clause `{name}` does not end with `).`")))?
            .trim_start();
    }
    let Some(conjecture) = conjecture else {
        return Err(error("no conjecture".to_owned()));
    };
    Ok(Clauses {
        code,
        hypotheses,
        conjecture,
        status: status.or(plain),
    })
}

/// Returns the message for `-o` at `at` of a line's `chars` between two
/// characters of a name, which reads both as one name and as the
/// connective between two.
#[cold]
fn glued(chars: &[char], at: usize) -> String {
    let name = |c: &char| c.is_ascii_alphanumeric() || *c == '_';
    let start = chars[..at]
        .iter()
        .rposition(|c| !name(c))
        .map_or(0, |n| n + 1);
    let end = chars[at + 2..]
        .iter()
        .position(|c| !name(c))
        .map_or(chars.len(), |n| at + 2 + n);
    let word: String = chars[start..end].iter().collect();
    format!(
        "`{word}` reads as one name and as two joined by `-o`: write a space before `-o` for \
         the connective"
    )
}

/// Returns the start of `text`'s first line, for an error message.
fn excerpt(text: &str) -> &str {
    let line = text.lines().next().unwrap_or_default();
    let end = line.char_indices().nth(24).map_or(line.len(), |(i, _)| i);
    &line[..end]
}

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

    /// Clauses over several lines, comments between and after them, a
    /// `hypothesis` role, uppercase atoms, names with `-` and `.`, postfix
    /// negation and every unit read into the sequent the parser gives for
    /// the same formulas; the intuitionistic status wins over the plain
    /// one before it, and malformed files are refused.
    #[test]
    fn reads_problems() {
        let text = "%---\n% Status   : Theorem\n% Status (intuit.) : Non-Theorem\n%---\n\
                    fof(ax1, axiom, !( (P-a_1) -o\n  (Q.b * Q.b) ) ).   % a transition\n\
                    fof(h, hypothesis, bot | top^).\n\
                    fof(con, conjecture, (Q.b * Q.b) + 0 & 1).\n";
        let problem = read(text, &Limits::default()).unwrap();
        assert_eq!(problem.status, Some(Status::NonTheorem));
        let expected: Sequent = "!(P‿a_1 -o Q·b * Q·b), bot | top^ |- (Q·b * Q·b) + 0 & 1"
            .parse()
            .unwrap();
        assert_eq!(problem.sequent, expected);

        for bad in [
            "fof(a, axiom, a).",
            "fof(a, axiom, a). fof(c, conjecture, a",
            "fof(c, conjecture, a) fof(d, axiom, b).",
            "fof(c, definition, a).",
            "fof(c, conjecture, a, unknown).",
            "cnf(c, conjecture, a).",
            "fof(h, axiom, bot). fof(c, conjecture, ).",
            "fof(h, axiom, ). fof(c, conjecture, a).",
        ] {
            assert!(
                matches!(read(bad, &Limits::default()), Err(Error::Lltp { .. })),
                "{bad:?}"
            );
        }
        // `a-ob` is a name of the library's kind and `a -o b` in this
        // crate's syntax; `a-o b` and `a -ob` are the connective.
        assert!(matches!(
            read("fof(c, conjecture, x * a-ob).", &Limits::default()),
            Err(Error::Lltp { message }) if message.starts_with("`a-ob` reads as one name")
        ));
        for text in ["fof(c, conjecture, a-o b).", "fof(c, conjecture, a -ob)."] {
            let problem = read(text, &Limits::default()).unwrap();
            assert_eq!(problem.sequent, "|- a -o b".parse().unwrap(), "{text}");
        }
        // A hyphen or a dot between name characters is part of the name,
        // a `-o` after a name's last character the connective.
        for (formula, sequent) in [
            ("p.q", "|- p·q"),
            ("a-b-o c", "|- a‿b -o c"),
            ("(a)-o(b)", "|- a -o b"),
            ("a-1 * b.c.d", "|- a‿1 * b·c·d"),
        ] {
            let text = format!("fof(c, conjecture, {formula}).");
            let problem = read(&text, &Limits::default()).unwrap();
            assert_eq!(problem.sequent, sequent.parse().unwrap(), "{formula}");
        }
        // The messages say what is wrong, and where.
        for (text, message) in [
            ("fof(a, axiom, a).", "no conjecture"),
            (
                "cnf(c, conjecture, a).",
                "expected `fof(` at `cnf(c, conjecture, a).`",
            ),
            (
                "fof(c, lemma, a).",
                "clause `c` has the role `lemma`, not axiom, hypothesis or conjecture",
            ),
        ] {
            match read(text, &Limits::default()) {
                Err(Error::Lltp { message: m }) => assert_eq!(m, message, "{text}"),
                other => panic!("{text}: {other:?}"),
            }
        }
    }

    /// A formula that does not parse is reported at its place in the
    /// file, not in the sequent assembled from the clauses: a formula cut
    /// short where its clause closes, and a binder cut short after a
    /// comment and a name with a hyphen.
    #[test]
    fn parse_errors_are_placed_in_the_file() {
        let place = |text: &str| match read(text, &Limits::default()) {
            Err(Error::Parse(e)) => (e.line, e.column, e.found.clone(), e.reserved),
            other => panic!("{other:?}"),
        };
        let text = "fof(a1, axiom, a).\nfof(a2, axiom, b * ).\nfof(c, conjecture, a).";
        assert_eq!(place(text), (2, 20, Some(")".to_owned()), false));
        let text =
            "% a comment\nfof(a1, axiom, P-a % and one more\n * forall).\nfof(c, conjecture, a).";
        assert_eq!(place(text), (3, 10, Some(")".to_owned()), false));
        assert_eq!(
            place("fof(c, conjecture, a * )."),
            (1, 24, Some(")".to_owned()), false)
        );
        // Without hypotheses, inside the conjecture, and after the white
        // space that ends it.
        assert_eq!(
            place("fof(c, conjecture, a * * b)."),
            (1, 24, Some("*".to_owned()), false)
        );
        assert_eq!(
            place("fof(c, conjecture, a *   )."),
            (1, 26, Some(")".to_owned()), false)
        );
    }

    /// A second conjecture is refused by name: joined right of `⊢`, the
    /// two would be read as their par, and `⊢ a, ~a` is provable where
    /// neither `⊢ a` nor `⊢ ~a` is.
    #[test]
    fn refuses_several_conjectures() {
        let text = "fof(c1, conjecture, a). fof(c2, conjecture, a^).";
        assert!(matches!(
            read(text, &Limits::default()),
            Err(Error::SeveralConjectures { second }) if second == "c2"
        ));
    }
}