use crate::errors::describe::{Budget, Limit, Names, cut, occurrence};
use crate::errors::{Described, Owner, Subject};
use crate::limits::Refusal;
use crate::linear::occurrences::{Member, ShapeError, Side};
use crate::linear::proofs::{Node, NodeId};
use crate::linear::sequents::Eigen;
use std::fmt::{Display, Formatter, Result as FmtResult};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dyadic {
pub theta: Vec<Member>,
pub gamma: Vec<Member>,
pub any: bool,
}
impl Display for Dyadic {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
self.write(f, None, None)
}
}
impl Dyadic {
fn write(&self, f: &mut Formatter<'_>, names: Option<Names<'_>>, limit: Limit) -> FmtResult {
let list = |f: &mut Formatter<'_>, ids: &mut dyn Iterator<Item = &Member>, len: usize| {
let mut budget = Budget::new(f, limit);
for (i, &o) in ids.enumerate() {
let written =
std::fmt::Write::write_str(&mut budget, if i == 0 { " " } else { ", " })
.and_then(|()| occurrence(&mut budget, names, o));
if written.is_err() && budget.cut {
return write!(budget.f, "… ({len} formulas)");
}
written?;
}
Ok(())
};
let any =
|f: &mut Formatter<'_>, empty: bool| f.write_str(if empty { " …" } else { ", …" });
if let Some(Names {
reading: Some(reading),
framing,
..
}) = names
{
let occ = move |m: Member| framing.map_or(m.occ(), |f| f.occurrence(m));
let side = |side: Side| move |o: &&Member| reading.position(occ(**o)) == side;
let inputs = self.gamma.iter().filter(side(Side::Input)).count();
if !self.theta.is_empty() {
list(f, &mut self.theta.iter(), self.theta.len())?;
f.write_str(" ;")?;
}
list(f, &mut self.gamma.iter().filter(side(Side::Input)), inputs)?;
if self.any {
any(f, inputs == 0)?;
}
f.write_str(if self.theta.is_empty() && inputs == 0 && !self.any {
"⊢"
} else {
" ⊢"
})?;
let outputs = self.gamma.len() - inputs;
return list(
f,
&mut self.gamma.iter().filter(side(Side::Output)),
outputs,
);
}
f.write_str("⊢")?;
if !self.theta.is_empty() {
list(f, &mut self.theta.iter(), self.theta.len())?;
f.write_str(" ;")?;
}
list(f, &mut self.gamma.iter(), self.gamma.len())?;
if self.any {
any(f, self.gamma.is_empty())?;
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CheckError {
Invalid(Box<Invalid>),
Refused(Refused),
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Invalid {
pub node: NodeId,
pub rule: Node,
pub premises: Vec<Dyadic>,
pub fault: Fault,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Refused {
pub node: NodeId,
pub refusal: Refusal,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fault {
Forbidden,
Shape(ShapeError),
#[non_exhaustive]
Succedents {
count: usize,
},
#[non_exhaustive]
Kind {
member: Member,
},
NotDual,
#[non_exhaustive]
Missing {
premise: usize,
member: Member,
},
NotEmpty,
Differ,
Order,
EmptyAntecedent,
#[non_exhaustive]
NotUnderQuest {
member: Member,
},
#[non_exhaustive]
NotACut {
member: Member,
},
Surplus,
#[non_exhaustive]
Instance {
member: Member,
},
#[non_exhaustive]
Eigenvariable {
eigen: Eigen,
},
#[non_exhaustive]
Reintroduced {
eigen: Eigen,
},
#[non_exhaustive]
Conclusion {
derived: Dyadic,
},
}
impl Invalid {
pub(crate) fn new(node: NodeId, rule: Node, premises: Vec<Dyadic>, fault: Fault) -> Self {
Self {
node,
rule,
premises,
fault,
}
}
}
impl CheckError {
pub fn node(&self) -> NodeId {
match self {
Self::Invalid(invalid) => invalid.node,
Self::Refused(refused) => refused.node,
}
}
pub fn fault(&self) -> Option<&Fault> {
match self {
Self::Invalid(invalid) => Some(&invalid.fault),
Self::Refused(_) => None,
}
}
pub(crate) fn invalid(node: NodeId, rule: Node, premises: Vec<Dyadic>, fault: Fault) -> Self {
Self::Invalid(Box::new(Invalid::new(node, rule, premises, fault)))
}
}
impl Display for CheckError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
self.write(f, None, None)
}
}
impl CheckError {
pub fn describe<'a>(&'a self, owner: &'a impl Owner) -> Described<'a> {
Described::new(Subject::Check(self), owner)
}
pub(crate) fn write(
&self,
f: &mut Formatter<'_>,
names: Option<Names<'_>>,
limit: Limit,
) -> FmtResult {
let invalid = match self {
Self::Invalid(invalid) => invalid,
Self::Refused(refused) => {
return write!(
f,
"the check was given up at node {}, without a verdict on the proof: {}",
refused.node.get(),
refused.refusal
);
}
};
invalid.write(f, names, limit)
}
}
impl Invalid {
fn write(&self, f: &mut Formatter<'_>, names: Option<Names<'_>>, limit: Limit) -> FmtResult {
let reading = names.and_then(|n| n.reading);
let occ = |m: Member| {
names
.and_then(|n| n.framing)
.map_or(m.occ(), |framing| framing.occurrence(m))
};
write!(
f,
"node {} ({}",
self.node.get(),
name(self.rule, reading, occ)
)?;
for (i, o) in self.rule.members().enumerate() {
f.write_str(if i == 0 { " on " } else { ", " })?;
cut(f, names, o, limit)?;
}
for (i, p) in self.rule.premises().enumerate() {
write!(f, "{}{}", if i == 0 { " from " } else { ", " }, p.get())?;
}
f.write_str(")")?;
for (i, p) in self.premises.iter().enumerate() {
f.write_str(if i == 0 { " with premises " } else { " and " })?;
p.write(f, names, limit)?;
}
f.write_str(": ")?;
use Fault::*;
match &self.fault {
Forbidden => f.write_str("the mode forbids the rule"),
Shape(e) => {
f.write_str("not an intuitionistic sequent: ")?;
e.write(f, names, limit)
}
Succedents { count } => write!(
f,
"a sequent of the rule has {count} formulas on the right of ⊢ instead of one"
),
Kind { member: o } => {
if names.is_none() {
f.write_str("occurrence ")?;
}
cut(f, names, *o, limit)?;
f.write_str(" is not what the rule acts on")
}
NotDual => f.write_str(if reading.is_some() {
"the axiom's formulas are not one atom on either side of ⊢"
} else {
"the literals are not an atom and its negation"
}),
Missing { premise, member: o } => {
write!(f, "premise {premise} lacks ")?;
if names.is_none() {
f.write_str("occurrence ")?;
}
cut(f, names, *o, limit)
}
NotEmpty => f.write_str("the linear zone is not empty"),
Differ => f.write_str("the premises differ"),
Order => f.write_str("the premises' contexts are not the arcs on either side of the ⊗"),
EmptyAntecedent => f.write_str(
"the sequent has no formula left of ⊢, which the Lambek calculus without empty antecedents forbids",
),
NotACut { member: o } => {
if names.is_none() {
f.write_str("occurrence ")?;
}
cut(f, names, *o, limit)?;
f.write_str(" is not in a cut formula")
}
NotUnderQuest { member: o } => {
if names.is_none() {
f.write_str("occurrence ")?;
}
cut(f, names, *o, limit)?;
f.write_str(if reading.is_some() {
" is not under a hypothesis's !"
} else {
" is not under a ?"
})
}
Surplus => f.write_str(
"the linear zone holds more formulas than the rest of the proof can consume",
),
Instance { member: o } => {
if names.is_none() {
f.write_str("occurrence ")?;
}
cut(f, names, *o, limit)?;
f.write_str(" stands under a binder and is named without its instance")
}
Eigenvariable { eigen } => {
f.write_str("eigenvariable ")?;
eigenvariable(f, names, *eigen)?;
f.write_str(" occurs outside the ∀ step that introduces it")
}
Reintroduced { eigen } => {
f.write_str("eigenvariable ")?;
eigenvariable(f, names, *eigen)?;
f.write_str(" is introduced by a second ∀ step")
}
Conclusion { derived: d } => {
f.write_str("the proof concludes ")?;
d.write(f, names, limit)?;
f.write_str(", not the sequent")
}
}
}
}
impl std::error::Error for CheckError {}
fn name(
node: Node,
reading: Option<&crate::linear::Reading<'_>>,
occ: impl Fn(Member) -> crate::linear::OccId,
) -> &'static str {
use crate::linear::proofs::{Branch, Named, Rule};
let (Some(reading), Some(o)) = (reading, node.principal()) else {
return node.name();
};
let rule = match node {
Node::Tensor(..) => Rule::Tensor,
Node::Par(..) => Rule::Par,
Node::One(_) => Rule::One,
Node::Bot(..) => Rule::Bot,
Node::With(..) => Rule::With,
Node::Plus(_, Branch::Left, _) => Rule::PlusLeft,
Node::Plus(_, Branch::Right, _) => Rule::PlusRight,
Node::Top(_) => Rule::Top,
Node::Bang(..) => Rule::Promotion,
Node::Quest(..) => Rule::Dereliction,
Node::Forall(..) => Rule::Forall,
Node::Exists(..) => Rule::Exists,
Node::Ax(..) | Node::Copy(..) | Node::Weaken(..) | Node::Mix(..) | Node::Cut(..) => {
return node.name();
}
};
Named::applied(rule, Some(reading), occ(o)).name()
}
fn eigenvariable(f: &mut Formatter<'_>, names: Option<Names<'_>>, eigen: Eigen) -> FmtResult {
match names.and_then(|n| n.framing) {
Some(framing) => f.write_str(framing.name(eigen)),
None => write!(f, "{}", eigen.get()),
}
}