use crate::Limits;
use crate::errors::ParseError;
use crate::{Error, linear::Sequent};
pub const HYPHEN: char = '‿';
pub const DOT: char = '·';
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Problem {
pub sequent: Sequent,
pub status: Option<Status>,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Theorem,
NonTheorem,
}
pub fn read(text: &str, limits: &Limits) -> Result<Problem, Error> {
let clauses = clauses(text, |message| Error::Lltp { message })?;
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) => {
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,
})
}
pub(crate) struct Clauses {
code: String,
hypotheses: Vec<std::ops::Range<usize>>,
conjecture: std::ops::Range<usize>,
pub(crate) status: Option<Status>,
}
impl Clauses {
pub(crate) fn hypotheses(&self) -> impl Iterator<Item = &str> {
self.hypotheses.iter().map(|r| &self.code[r.clone()])
}
pub(crate) fn code(&self) -> &str {
&self.code
}
pub(crate) fn conjecture(&self) -> &str {
&self.code[self.conjecture.clone()]
}
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)
}
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();
}
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)
}
}
pub(crate) fn clauses(text: &str, error: fn(String) -> Error) -> Result<Clauses, Error> {
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 == '_')
};
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")))?;
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),
})
}
#[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"
)
}
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::*;
#[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:?}"
);
}
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}");
}
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}");
}
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:?}"),
}
}
}
#[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)
);
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)
);
}
#[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"
));
}
}