pub(crate) mod describe;
#[cfg(feature = "parse")]
mod parse;
pub(crate) use describe::Subject;
pub use describe::{Described, Owner};
#[cfg(feature = "parse")]
pub use parse::ParseError;
use crate::limits::{Refusal, Space};
use crate::linear::fragment::{Fragment, Mode};
use crate::linear::nets::NetError;
use crate::linear::occurrences::ShapeError;
use crate::linear::proofs::CheckError;
use crate::linear::search::{Engine, NotTaken};
use crate::linear::sequents::fo::SymbolFault;
use thiserror::Error;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Error)]
pub enum Error {
#[cfg(feature = "parse")]
#[error("cannot parse the sequent: {0}")]
Parse(Box<ParseError>),
#[cfg(feature = "parse")]
#[error("not an LLTP problem: {message}")]
#[non_exhaustive]
Lltp {
message: String,
},
#[cfg(feature = "parse")]
#[error("not a .spec problem: {message}")]
#[non_exhaustive]
Spec {
message: String,
},
#[cfg(feature = "parse")]
#[error("not a TPTP problem: {message}")]
#[non_exhaustive]
Tptp {
message: String,
},
#[cfg(feature = "parse")]
#[error("the file has a second conjecture, `{second}`; a file holds one conjecture only")]
#[non_exhaustive]
SeveralConjectures {
second: String,
},
#[error("unknown {what} `{name}`: {}", or_list(.known))]
#[non_exhaustive]
UnknownName {
what: &'static str,
name: Box<str>,
known: &'static [&'static str],
},
#[cfg(feature = "parse")]
#[error(
"the family {family} has no instance of size {size}: its sizes are {}at least {least}",
if *.powers_of_two { "the powers of two " } else { "" }
)]
#[non_exhaustive]
FamilySize {
family: &'static str,
size: u32,
least: u32,
powers_of_two: bool,
},
#[cfg(feature = "parse")]
#[error(
"the family {family} has no instance {index}: it has {instances} per size, numbered from 0"
)]
#[non_exhaustive]
FamilyIndex {
family: &'static str,
index: u32,
instances: u32,
},
#[error("{key}: {message}")]
#[non_exhaustive]
InvalidOption {
key: &'static str,
message: String,
},
#[error("not {} {form} of deduxit's wire form: {message}", article(form))]
#[non_exhaustive]
Json {
form: &'static str,
message: String,
},
#[error("the {form} is of wire level {found}; this build reads levels up to {supported}")]
#[non_exhaustive]
Version {
form: &'static str,
found: u64,
supported: u32,
},
#[error("{}", out_of_bounds(*.space, *.index, *.len))]
#[non_exhaustive]
IndexOutOfBounds {
space: Space,
index: usize,
len: usize,
},
#[error("{}", not_topological(*.space, *.index, *.parent))]
#[non_exhaustive]
NotTopological {
space: Space,
index: usize,
parent: usize,
},
#[error(
"the sequent has {} left of ⊢ but {} in all",
counted(*.antecedents, "formula", "formulas"),
counted(*.roots, "formula", "formulas")
)]
#[non_exhaustive]
Antecedents {
antecedents: usize,
roots: usize,
},
#[error(
"a cut formula is one formula, not {}",
counted(*.formulas, "formula", "formulas")
)]
#[non_exhaustive]
CutFormula {
formulas: usize,
},
#[error(
"the atom name {name:?} {}",
crate::linear::sequents::name::fault(name)
)]
#[non_exhaustive]
AtomName {
name: String,
},
#[error("the symbol {name:?} {fault}")]
#[non_exhaustive]
Symbol {
name: String,
fault: SymbolFault,
},
#[error("term {term} has a bound variable that no binder of it binds")]
#[non_exhaustive]
LooseVariable {
term: usize,
},
#[error("{predicates} predicates for {atoms} atoms: every atom has its predicate, or none has")]
#[non_exhaustive]
Predicates {
predicates: usize,
atoms: usize,
},
#[cfg(feature = "interactive")]
#[error("not a proof in progress: {reason}")]
#[non_exhaustive]
InconsistentSession {
reason: &'static str,
},
#[error("{}", check_message(.0))]
Check(CheckError),
#[error("{0}")]
Refutation(crate::linear::search::RefutationFault),
#[error("not a proof net: {0}")]
Net(Box<NetError>),
#[cfg(feature = "interactive")]
#[error(transparent)]
Step(#[from] crate::linear::proofs::StepError),
#[cfg(feature = "interactive")]
#[error(transparent)]
OrdinaryStep(#[from] crate::ordinary::StepError),
#[cfg(feature = "interactive")]
#[error(
"the proof is not finished: {}",
if *.count == 1 { "1 goal is open".to_owned() } else { format!("{} goals are open", .count) }
)]
#[non_exhaustive]
OpenGoals {
count: usize,
},
#[cfg(feature = "interactive")]
#[error("the proof is of another sequent than the session's")]
ForeignProof,
#[cfg(feature = "interactive")]
#[error("the proof concludes another goal than the one it is to close")]
GoalMismatch,
#[error("the proof concludes a goal, not the sequent")]
GoalProof,
#[error(
"the proof's conclusions are not the goal's formulas: {} only in the proof, {} only in the goal",
listed(proof),
listed(goal)
)]
#[non_exhaustive]
SequentMismatch {
proof: Vec<String>,
goal: Vec<String>,
},
#[error("not an intuitionistic sequent: {0}")]
NotIntuitionistic(ShapeError),
#[error("Mix has no intuitionistic form: one premise of a Mix would have nothing right of ⊢")]
IntuitionisticMix,
#[error("{mode} mode has no calculus: an ordered mode takes neither weakening nor Mix")]
#[non_exhaustive]
OrderedMode {
mode: Mode,
},
#[error("{mode} mode decides unit-free MLL, and the sequent lies in {fragment}")]
#[non_exhaustive]
OrderedFragment {
fragment: Fragment,
mode: Mode,
},
#[error("an intuitionistic goal has exactly one formula right of ⊢, not {count}")]
#[non_exhaustive]
GoalOutputs {
count: usize,
},
#[error("an intuitionistic sequent has at most one formula right of ⊢, not {count}")]
#[non_exhaustive]
Succedents {
count: usize,
},
#[error("the sequent lies in {detected}, outside {asserted}, the fragment asked for")]
#[non_exhaustive]
FragmentMismatch {
asserted: Fragment,
detected: Fragment,
},
#[error("the {translation} translation does not decide {logic} logic")]
#[non_exhaustive]
Translation {
translation: crate::ordinary::Translation,
logic: crate::ordinary::Logic,
},
#[error("{} decides {}, not {logic} logic", .method.title(), .method.logics())]
#[non_exhaustive]
Logic {
logic: crate::ordinary::Logic,
method: crate::ordinary::Method,
},
#[error("{} does not carry classical logic into {logic} logic", .translation.title())]
#[non_exhaustive]
NegativeTarget {
translation: crate::ordinary::negative::Translation,
logic: crate::ordinary::Logic,
},
#[error("not a partition of the sequent: {reason}")]
#[non_exhaustive]
Partition {
reason: String,
},
#[error(
"the derivation has a cut, and an interpolant is read off a derivation without one; \
decide the sequent through the embedding, or in classical logic by a tableau"
)]
NotCutFree,
#[error("{operation} does not apply: {reason}")]
#[non_exhaustive]
NotApplicable {
operation: Box<str>,
reason: String,
},
#[error(
"node {node} is made by its recipe and takes no value of its own; change what it is made \
from, or detach it first"
)]
#[non_exhaustive]
NotGiven {
node: u32,
},
#[error("{claim} does not hold here: {reason}")]
#[non_exhaustive]
ClaimFails {
claim: String,
reason: String,
},
#[error("no engine decides {fragment} in {mode} mode")]
#[non_exhaustive]
NoEngine {
fragment: Fragment,
mode: Mode,
},
#[error("{}", .because.explained(*.engine))]
#[non_exhaustive]
EngineRefused {
engine: Engine,
because: NotTaken,
},
#[cfg(feature = "rocq")]
#[error(transparent)]
Unsupported(#[from] crate::export::rocq::Unsupported),
#[error("{0}")]
Refused(Refusal),
#[cfg(feature = "parallel")]
#[error("cannot start {threads} search threads: {message}")]
#[non_exhaustive]
ThreadPool {
threads: usize,
message: String,
},
#[error("the writer failed")]
WriteFailed,
#[cfg(any(feature = "png", feature = "pdf"))]
#[error("not an SVG document the renderer reads: {message}")]
#[non_exhaustive]
NotSvg {
message: String,
},
#[cfg(any(feature = "png", feature = "pdf"))]
#[error("the renderer failed: {message}")]
#[non_exhaustive]
RenderFailed {
message: String,
},
#[cfg(feature = "pdf")]
#[error("a PDF/A document needs the date it was made: give pdf::Options::date")]
NoDate,
#[error("{}", match .node {
Some(node) => format!("node {node} is no cut"),
None => "the proof has no cut".to_owned(),
})]
#[non_exhaustive]
NoCut {
node: Option<u32>,
},
#[error("a step of cut elimination made a proof the checker refuses: {0}")]
Reduction(Box<CheckError>),
#[error("{}{}", describe::REJECTED, .0)]
Rejected(Box<CheckError>),
#[error("the proof has no lambda-term: {reason}")]
#[non_exhaustive]
NoTerm {
reason: crate::lambda::NoTerm,
},
#[error(
"the sequent is valid by {evidence}, which is no derivation; the method embedding gives \
the derivation of LK"
)]
#[non_exhaustive]
NoDerivation {
evidence: &'static str,
},
#[error(
"the sequent is valid by the checked proof of its image, whose derivation was not built; \
raise the derivation limit or the time limit to build it"
)]
NotBuilt,
#[error("the proof read back is not a derivation of {calculus}: {reason}")]
#[non_exhaustive]
ReadBack {
calculus: &'static str,
reason: String,
},
#[error("the Kripke model does not refute the sequent: {reason}")]
#[non_exhaustive]
Countermodel {
reason: String,
},
#[error("the Kripke model is wrong: {reason}")]
#[non_exhaustive]
Model {
reason: String,
},
#[error("the rule file is no calculus: {reason}")]
#[non_exhaustive]
InvalidCalculus {
reason: String,
},
#[error("not a derivation in the calculus {calculus}: {reason}")]
#[non_exhaustive]
InvalidDerivation {
calculus: Box<str>,
reason: String,
},
#[error("the step is refused: {reason}")]
#[non_exhaustive]
StepRefused {
reason: String,
},
#[error("the step needs {} given: what the goal leaves open", .needs.join(", "))]
#[non_exhaustive]
StepNeeds {
needs: Vec<String>,
},
#[error("no Fitch proof: {reason}")]
#[non_exhaustive]
NotFitch {
reason: String,
},
#[error("the sequent has {found} zones; the derivation's sequents have {zones}")]
#[non_exhaustive]
Zones {
found: usize,
zones: usize,
},
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize),
serde(rename_all = "snake_case")
)]
pub enum ErrorKind {
Malformed,
Invalid,
Unsupported,
Limit,
Stopped,
Failed,
Defect,
}
impl ErrorKind {
pub const fn is_refusal(self) -> bool {
matches!(self, Self::Unsupported | Self::Limit | Self::Stopped)
}
pub const fn name(self) -> &'static str {
match self {
Self::Malformed => "malformed",
Self::Invalid => "invalid",
Self::Unsupported => "unsupported",
Self::Limit => "limit",
Self::Stopped => "stopped",
Self::Failed => "failed",
Self::Defect => "defect",
}
}
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
fn listed(formulas: &[String]) -> String {
if formulas.is_empty() {
"nothing".to_owned()
} else {
formulas.join(", ")
}
}
impl Error {
pub const CODES: &'static [&'static str] = &[
"parse",
"lltp",
"spec",
"tptp",
"several_conjectures",
"unknown_name",
"family_size",
"family_index",
"invalid_option",
"json",
"unsupported_version",
"index_out_of_bounds",
"not_topological",
"antecedents",
"cut_formula",
"atom_name",
"inconsistent_session",
"invalid_proof",
"invalid_refutation",
"uncertified",
"invalid_net",
"no_nets",
"step",
"open_goals",
"foreign_proof",
"goal_mismatch",
"goal_proof",
"sequent_mismatch",
"not_intuitionistic",
"intuitionistic_mix",
"ordered_mode",
"symbol",
"loose_variable",
"predicates",
"ordered_fragment",
"goal_outputs",
"succedents",
"fragment_mismatch",
"translation",
"logic",
"negative_target",
"partition",
"not_cut_free",
"not_applicable",
"not_given",
"claim_fails",
"no_engine",
"engine_refused",
"no_certificate",
"stopped",
"memory_limit",
"too_many_occurrences",
"too_many_terms",
"output_too_large",
"work_limit",
"too_many_pixels",
"too_many_atoms",
"workspace_limit",
"elimination_limit",
"index_limit",
"thread_pool",
"write_failed",
"not_svg",
"render_failed",
"no_date",
"rejected",
"read_back",
"countermodel",
"invalid_model",
"invalid_calculus",
"invalid_derivation",
"zones",
"step_refused",
"step_needs",
"not_fitch",
"no_term",
"no_derivation",
"not_built",
"no_cut",
"reduction_rejected",
];
pub fn kind(&self) -> ErrorKind {
use ErrorKind::*;
match self {
#[cfg(feature = "parse")]
Self::Parse(_)
| Self::Lltp { .. }
| Self::Spec { .. }
| Self::Tptp { .. }
| Self::SeveralConjectures { .. } => Malformed,
Self::UnknownName { .. } | Self::InvalidOption { .. } | Self::Json { .. } => Malformed,
#[cfg(feature = "parse")]
Self::FamilySize { .. } | Self::FamilyIndex { .. } => Malformed,
Self::Version { .. } => Unsupported,
Self::IndexOutOfBounds { .. }
| Self::NotTopological { .. }
| Self::Antecedents { .. }
| Self::CutFormula { .. }
| Self::AtomName { .. }
| Self::Symbol { .. }
| Self::LooseVariable { .. }
| Self::Predicates { .. } => Malformed,
#[cfg(feature = "interactive")]
Self::InconsistentSession { .. } => Malformed,
Self::Check(CheckError::Invalid(_)) => Invalid,
Self::Check(CheckError::Refused(refused)) => refusal_kind(&refused.refusal),
Self::Refutation(crate::linear::search::RefutationFault::Uncertified { .. }) => {
Unsupported
}
Self::Refutation(_) => Invalid,
Self::Net(error) => error.kind(),
#[cfg(feature = "interactive")]
Self::Step(_)
| Self::OrdinaryStep(_)
| Self::OpenGoals { .. }
| Self::ForeignProof
| Self::GoalMismatch => Invalid,
Self::GoalProof => Unsupported,
Self::SequentMismatch { .. } | Self::Model { .. } | Self::InvalidDerivation { .. } => {
Invalid
}
Self::InvalidCalculus { .. } | Self::Zones { .. } | Self::StepNeeds { .. } => Malformed,
Self::StepRefused { .. } => Invalid,
Self::NotFitch { .. } => Unsupported,
Self::NotIntuitionistic(_)
| Self::IntuitionisticMix
| Self::OrderedMode { .. }
| Self::OrderedFragment { .. }
| Self::GoalOutputs { .. }
| Self::Succedents { .. }
| Self::FragmentMismatch { .. }
| Self::Translation { .. }
| Self::Logic { .. }
| Self::NegativeTarget { .. }
| Self::NotCutFree
| Self::NoEngine { .. }
| Self::EngineRefused { .. } => Unsupported,
Self::NotApplicable { .. } | Self::NotGiven { .. } => Malformed,
Self::Partition { .. } => Malformed,
Self::ClaimFails { .. } => Defect,
#[cfg(feature = "rocq")]
Self::Unsupported(_) => Unsupported,
Self::Refused(refusal) => refusal_kind(refusal),
#[cfg(feature = "parallel")]
Self::ThreadPool { .. } => Failed,
Self::WriteFailed => Failed,
#[cfg(any(feature = "png", feature = "pdf"))]
Self::NotSvg { .. } => Malformed,
#[cfg(any(feature = "png", feature = "pdf"))]
Self::RenderFailed { .. } => Failed,
#[cfg(feature = "pdf")]
Self::NoDate => Malformed,
Self::Rejected(_)
| Self::ReadBack { .. }
| Self::Countermodel { .. }
| Self::Reduction(_) => Defect,
Self::NoCut { .. } => Unsupported,
Self::NoTerm { .. } | Self::NoDerivation { .. } => Unsupported,
Self::NotBuilt => Limit,
}
}
pub fn code(&self) -> &'static str {
match self {
#[cfg(feature = "parse")]
Self::Parse(_) => "parse",
#[cfg(feature = "parse")]
Self::Lltp { .. } => "lltp",
#[cfg(feature = "parse")]
Self::Spec { .. } => "spec",
#[cfg(feature = "parse")]
Self::Tptp { .. } => "tptp",
#[cfg(feature = "parse")]
Self::SeveralConjectures { .. } => "several_conjectures",
Self::UnknownName { .. } => "unknown_name",
#[cfg(feature = "parse")]
Self::FamilySize { .. } => "family_size",
#[cfg(feature = "parse")]
Self::FamilyIndex { .. } => "family_index",
Self::InvalidOption { .. } => "invalid_option",
Self::Json { .. } => "json",
Self::Version { .. } => "unsupported_version",
Self::IndexOutOfBounds { .. } => "index_out_of_bounds",
Self::NotTopological { .. } => "not_topological",
Self::Antecedents { .. } => "antecedents",
Self::CutFormula { .. } => "cut_formula",
Self::AtomName { .. } => "atom_name",
Self::Symbol { .. } => "symbol",
Self::LooseVariable { .. } => "loose_variable",
Self::Predicates { .. } => "predicates",
#[cfg(feature = "interactive")]
Self::InconsistentSession { .. } => "inconsistent_session",
Self::Check(CheckError::Invalid(_)) => "invalid_proof",
Self::Check(CheckError::Refused(refused)) => refused.refusal.code(),
Self::Refutation(crate::linear::search::RefutationFault::Uncertified { .. }) => {
"uncertified"
}
Self::Refutation(_) => "invalid_refutation",
Self::Net(error) => error.code(),
#[cfg(feature = "interactive")]
Self::Step(_) | Self::OrdinaryStep(_) => "step",
#[cfg(feature = "interactive")]
Self::OpenGoals { .. } => "open_goals",
#[cfg(feature = "interactive")]
Self::ForeignProof => "foreign_proof",
#[cfg(feature = "interactive")]
Self::GoalMismatch => "goal_mismatch",
Self::GoalProof => "goal_proof",
Self::SequentMismatch { .. } => "sequent_mismatch",
Self::NotIntuitionistic(_) => "not_intuitionistic",
Self::IntuitionisticMix => "intuitionistic_mix",
Self::OrderedMode { .. } => "ordered_mode",
Self::OrderedFragment { .. } => "ordered_fragment",
Self::GoalOutputs { .. } => "goal_outputs",
Self::Succedents { .. } => "succedents",
Self::FragmentMismatch { .. } => "fragment_mismatch",
Self::Translation { .. } => "translation",
Self::Logic { .. } => "logic",
Self::NegativeTarget { .. } => "negative_target",
Self::Partition { .. } => "partition",
Self::NotCutFree => "not_cut_free",
Self::NotApplicable { .. } => "not_applicable",
Self::NotGiven { .. } => "not_given",
Self::ClaimFails { .. } => "claim_fails",
Self::NoEngine { .. } => "no_engine",
Self::EngineRefused { .. } => "engine_refused",
#[cfg(feature = "rocq")]
Self::Unsupported(_) => "no_certificate",
Self::Refused(refusal) => refusal.code(),
#[cfg(feature = "parallel")]
Self::ThreadPool { .. } => "thread_pool",
Self::WriteFailed => "write_failed",
#[cfg(any(feature = "png", feature = "pdf"))]
Self::NotSvg { .. } => "not_svg",
#[cfg(any(feature = "png", feature = "pdf"))]
Self::RenderFailed { .. } => "render_failed",
#[cfg(feature = "pdf")]
Self::NoDate => "no_date",
Self::Rejected(_) => "rejected",
Self::ReadBack { .. } => "read_back",
Self::Countermodel { .. } => "countermodel",
Self::Model { .. } => "invalid_model",
Self::InvalidCalculus { .. } => "invalid_calculus",
Self::InvalidDerivation { .. } => "invalid_derivation",
Self::Zones { .. } => "zones",
Self::StepRefused { .. } => "step_refused",
Self::StepNeeds { .. } => "step_needs",
Self::NotFitch { .. } => "not_fitch",
Self::NoCut { .. } => "no_cut",
Self::NoTerm { .. } => "no_term",
Self::NoDerivation { .. } => "no_derivation",
Self::NotBuilt => "not_built",
Self::Reduction(_) => "reduction_rejected",
}
}
pub fn setting(&self) -> Option<&'static str> {
match self {
Self::Refused(refusal) => refusal.setting(),
Self::Check(CheckError::Refused(refused)) => refused.refusal.setting(),
Self::Net(error) => match error.as_ref() {
NetError::Refused { refusal } => refusal.setting(),
_ => None,
},
_ => None,
}
}
pub fn is_refusal(&self) -> bool {
self.kind().is_refusal()
}
}
pub(crate) const fn refusal_kind(refusal: &Refusal) -> ErrorKind {
match refusal {
Refusal::Stopped { .. } => ErrorKind::Stopped,
_ => ErrorKind::Limit,
}
}
fn article(form: &str) -> &'static str {
match form.chars().next() {
Some('a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U') => "an",
_ => "a",
}
}
fn or_list(names: &[&str]) -> String {
match names.split_last() {
None => String::new(),
Some((last, [])) => (*last).to_owned(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
}
}
fn out_of_bounds(space: Space, index: usize, len: usize) -> String {
match space {
Space::Atom => format!(
"a term refers to atom {index}, but the atom list has {}",
counted(len, "name", "names")
),
Space::Term => format!(
"a root formula is term {index}, but the arena has {}",
counted(len, "term", "terms")
),
Space::Node => format!(
"a proof refers to node {index}, but it has {}",
counted(len, "node", "nodes")
),
Space::Occurrence => format!(
"a proof node refers to occurrence {index}, but the sequent has {}",
counted(len, "occurrence", "occurrences")
),
_ => format!(
"an index names {index}, but there {} {}",
if len == 1 { "is" } else { "are" },
counted(len, space.singular(), space.plural())
),
}
}
pub(crate) fn counted<N>(count: N, one: &str, many: &str) -> String
where
N: Copy + std::fmt::Display + TryInto<u64>,
{
let noun = if count.try_into().ok() == Some(1) {
one
} else {
many
};
format!("{count} {noun}")
}
fn not_topological(space: Space, index: usize, parent: usize) -> String {
match space {
Space::Node => format!(
"proof node {parent} has premise {index}, but a premise must come before the nodes \
that use it"
),
_ => format!(
"term {parent} refers to term {index}, but a subterm must come before the terms that \
use it"
),
}
}
fn check_message(error: &CheckError) -> String {
match error {
CheckError::Invalid(_) => format!("{INVALID_PROOF}{error}"),
CheckError::Refused(_) => error.to_string(),
}
}
impl From<CheckError> for Error {
fn from(error: CheckError) -> Self {
Self::Check(error)
}
}
impl From<NetError> for Error {
fn from(error: NetError) -> Self {
Self::Net(Box::new(error))
}
}
impl From<ShapeError> for Error {
fn from(error: ShapeError) -> Self {
Self::NotIntuitionistic(error)
}
}
impl From<Refusal> for Error {
fn from(refusal: Refusal) -> Self {
Self::Refused(refusal)
}
}
impl From<std::fmt::Error> for Error {
fn from(_: std::fmt::Error) -> Self {
Self::WriteFailed
}
}
#[cfg(feature = "parse")]
impl From<ParseError> for Error {
fn from(error: ParseError) -> Self {
Self::Parse(Box::new(error))
}
}
const INVALID_PROOF: &str = "invalid proof: ";
const _: () = assert!(size_of::<Error>() <= 64);
const _: fn() = || {
const fn shared<T: Send + Sync + 'static>() {}
shared::<Error>();
};
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn samples() -> Vec<Error> {
use crate::limits::Phase;
use crate::linear::occurrences::{Member, OccId};
use crate::linear::proofs::{Fault, Invalid, Node, NodeId, Refused};
let refusals = [
Refusal::Stopped {
phase: Phase::Search,
},
Refusal::Memory {
phase: Phase::Search,
limit_bytes: 1,
needed_bytes: None,
},
Refusal::Occurrences {
occurrences: 2,
limit: 1,
},
Refusal::Terms { terms: 2, limit: 1 },
Refusal::Output {
what: "derivation",
estimate_bytes: 2,
limit_bytes: 1,
least_bytes: None,
},
Refusal::Work { limit: 1 },
Refusal::Pixels {
pixels: 2,
limit: 1,
},
Refusal::Elimination {
what: crate::limits::Bound::Steps,
limit: 1,
},
Refusal::Atoms { atoms: 2, limit: 1 },
Refusal::Workspace {
what: crate::limits::Held::Nodes,
count: 2,
limit: 1,
},
Refusal::Index {
what: Space::Node,
count: 2,
most: 1,
},
];
let invalid = CheckError::Invalid(Box::new(Invalid {
node: NodeId::new(0),
rule: Node::One(Member::from(OccId::new(0))),
premises: Vec::new(),
fault: Fault::NotDual,
}));
let message = String::new;
let mut samples = vec![
Error::UnknownName {
what: "mode",
name: "x".into(),
known: &[],
},
Error::InvalidOption {
key: "typst",
message: message(),
},
Error::Json {
form: "sequent",
message: message(),
},
Error::Version {
form: "sequent",
found: 2,
supported: 1,
},
Error::IndexOutOfBounds {
space: Space::Term,
index: 1,
len: 1,
},
Error::NotTopological {
space: Space::Term,
index: 1,
parent: 0,
},
Error::Antecedents {
antecedents: 2,
roots: 1,
},
Error::CutFormula { formulas: 2 },
Error::AtomName { name: "par".into() },
Error::Symbol {
name: "p".into(),
fault: SymbolFault::Role,
},
Error::Predicates {
predicates: 1,
atoms: 2,
},
Error::LooseVariable { term: 3 },
Error::Check(invalid.clone()),
Error::Check(CheckError::Refused(Refused {
node: NodeId::new(0),
refusal: refusals[0].clone(),
})),
Error::Refutation(crate::linear::search::RefutationFault::Satisfied),
Error::Refutation(crate::linear::search::RefutationFault::Uncertified {
kind: "exhausted",
}),
Error::GoalProof,
Error::SequentMismatch {
proof: vec!["A ⊗ B".into()],
goal: Vec::new(),
},
Error::NotIntuitionistic(ShapeError::NoGoal),
Error::IntuitionisticMix,
Error::OrderedMode {
mode: Mode::CYCLIC.with_mix(),
},
Error::OrderedFragment {
fragment: Fragment::MALL,
mode: Mode::CYCLIC,
},
Error::GoalOutputs { count: 2 },
Error::Succedents { count: 2 },
Error::FragmentMismatch {
asserted: Fragment::MLL,
detected: Fragment::LL,
},
Error::Translation {
translation: crate::ordinary::Translation::Affine,
logic: crate::ordinary::Logic::Intuitionistic,
},
Error::Logic {
logic: crate::ordinary::Logic::Classical,
method: crate::ordinary::Method::Ljt,
},
Error::NegativeTarget {
translation: crate::ordinary::negative::Translation::Kuroda,
logic: crate::ordinary::Logic::Minimal,
},
Error::Partition { reason: message() },
Error::NotCutFree,
Error::NotApplicable {
operation: "detach".into(),
reason: message(),
},
Error::NotGiven { node: 1 },
Error::ClaimFails {
claim: "Kolmogorov's translation".into(),
reason: message(),
},
Error::NoEngine {
fragment: Fragment::LL,
mode: Mode::CLASSICAL,
},
Error::EngineRefused {
engine: Engine::Net,
because: NotTaken::Goal,
},
Error::WriteFailed,
Error::Rejected(Box::new(invalid.clone())),
Error::Reduction(Box::new(invalid)),
Error::NoCut { node: Some(3) },
Error::NoTerm {
reason: crate::lambda::NoTerm::Classical,
},
Error::NoDerivation { evidence: "x" },
Error::NotBuilt,
Error::ReadBack {
calculus: "LK",
reason: message(),
},
Error::Countermodel { reason: message() },
Error::Model { reason: message() },
Error::InvalidCalculus { reason: message() },
Error::InvalidDerivation {
calculus: "LK".into(),
reason: message(),
},
Error::Zones { found: 1, zones: 2 },
Error::StepRefused { reason: message() },
Error::StepNeeds {
needs: vec!["C".to_owned()],
},
Error::NotFitch { reason: message() },
];
let vertex = crate::linear::nets::VertexId::new(0);
let nets = [
NetError::NoVertex {
vertex: 1,
vertices: 1,
},
NetError::NotLiteral { vertex },
NetError::NotDual {
x: vertex,
y: vertex,
},
NetError::LinkedTwice { vertex },
NetError::Unlinked { vertex },
NetError::Empty,
NetError::SwitchingCycle {
cycle: vec![vertex],
},
NetError::Disconnected {
parts: vec![vec![vertex]],
},
NetError::DirectedCycle {
cycle: vec![vertex],
},
NetError::NoDominator {
implication: vertex,
path: vec![vertex],
},
NetError::Crossing {
links: [(vertex, vertex), (vertex, vertex)],
},
NetError::NotIntuitionistic {
shape: ShapeError::NoGoal,
},
NetError::Fragment {
fragment: Fragment::LL,
},
NetError::Mode {
mode: Mode::CLASSICAL.with_affine(),
},
NetError::Rule {
node: NodeId::new(0),
rule: "wk",
},
NetError::Placement {
vertex,
fault: crate::linear::nets::Placement::Premise,
},
NetError::Unattached { vertex },
NetError::InBox {
door: vertex,
error: Box::new(NetError::Empty),
},
NetError::NotMell {
fragment: Fragment::LL,
mode: Mode::INTUITIONISTIC,
},
NetError::NoCut {
vertex: Some(vertex),
},
NetError::Reduction {
error: Box::new(NetError::Empty),
},
NetError::Refused {
refusal: refusals[1].clone(),
},
];
samples.extend(nets.into_iter().map(|error| Error::Net(Box::new(error))));
samples.extend(refusals.into_iter().map(Error::Refused));
#[cfg(feature = "parse")]
samples.extend([
Error::Parse(Box::new(ParseError::spanning("(", 1..1, &["a formula"]))),
Error::Lltp { message: message() },
Error::Spec { message: message() },
Error::Tptp { message: message() },
Error::SeveralConjectures { second: message() },
Error::FamilySize {
family: "chain",
size: 0,
least: 1,
powers_of_two: false,
},
Error::FamilyIndex {
family: "contraction",
index: 2,
instances: 2,
},
]);
#[cfg(feature = "interactive")]
samples.extend([
Error::InconsistentSession { reason: "" },
Error::Step(crate::linear::proofs::StepError::NoGoal {
goal: crate::linear::proofs::interactive::GoalId::new(0),
}),
Error::OpenGoals { count: 1 },
Error::ForeignProof,
Error::GoalMismatch,
]);
#[cfg(feature = "rocq")]
samples.push(Error::Unsupported(crate::export::rocq::Unsupported::Mix));
#[cfg(feature = "parallel")]
samples.push(Error::ThreadPool {
threads: 2,
message: message(),
});
#[cfg(any(feature = "png", feature = "pdf"))]
samples.extend([
Error::NotSvg { message: message() },
Error::RenderFailed { message: message() },
]);
#[cfg(feature = "pdf")]
samples.push(Error::NoDate);
samples
}
fn variant(error: &Error) {
match error {
Error::Net(net) => match net.as_ref() {
NetError::Refused { refusal } => refused(refusal),
NetError::NoVertex { .. }
| NetError::NotLiteral { .. }
| NetError::NotDual { .. }
| NetError::LinkedTwice { .. }
| NetError::Unlinked { .. }
| NetError::Empty
| NetError::SwitchingCycle { .. }
| NetError::Disconnected { .. }
| NetError::DirectedCycle { .. }
| NetError::NoDominator { .. }
| NetError::Crossing { .. }
| NetError::NotIntuitionistic { .. }
| NetError::Fragment { .. }
| NetError::Mode { .. }
| NetError::Rule { .. }
| NetError::Placement { .. }
| NetError::Unattached { .. }
| NetError::InBox { .. }
| NetError::NotMell { .. }
| NetError::NoCut { .. }
| NetError::Reduction { .. } => {}
},
Error::Refused(refusal) => refused(refusal),
#[cfg(feature = "parse")]
Error::Parse(_)
| Error::Lltp { .. }
| Error::Spec { .. }
| Error::Tptp { .. }
| Error::SeveralConjectures { .. }
| Error::FamilySize { .. }
| Error::FamilyIndex { .. } => {}
#[cfg(feature = "interactive")]
Error::InconsistentSession { .. }
| Error::Step(_)
| Error::OrdinaryStep(_)
| Error::OpenGoals { .. }
| Error::ForeignProof
| Error::GoalMismatch => {}
#[cfg(feature = "rocq")]
Error::Unsupported(_) => {}
#[cfg(feature = "parallel")]
Error::ThreadPool { .. } => {}
#[cfg(any(feature = "png", feature = "pdf"))]
Error::NotSvg { .. } | Error::RenderFailed { .. } => {}
#[cfg(feature = "pdf")]
Error::NoDate => {}
Error::UnknownName { .. }
| Error::InvalidOption { .. }
| Error::Json { .. }
| Error::Version { .. }
| Error::IndexOutOfBounds { .. }
| Error::NotTopological { .. }
| Error::Antecedents { .. }
| Error::CutFormula { .. }
| Error::AtomName { .. }
| Error::Symbol { .. }
| Error::LooseVariable { .. }
| Error::Predicates { .. }
| Error::Check(_)
| Error::Refutation(_)
| Error::GoalProof
| Error::SequentMismatch { .. }
| Error::NotIntuitionistic(_)
| Error::IntuitionisticMix
| Error::OrderedMode { .. }
| Error::OrderedFragment { .. }
| Error::GoalOutputs { .. }
| Error::Succedents { .. }
| Error::FragmentMismatch { .. }
| Error::Translation { .. }
| Error::Logic { .. }
| Error::NegativeTarget { .. }
| Error::Partition { .. }
| Error::NotCutFree
| Error::NotApplicable { .. }
| Error::NotGiven { .. }
| Error::ClaimFails { .. }
| Error::NoEngine { .. }
| Error::EngineRefused { .. }
| Error::WriteFailed
| Error::Rejected(_)
| Error::ReadBack { .. }
| Error::Countermodel { .. }
| Error::Model { .. }
| Error::InvalidCalculus { .. }
| Error::InvalidDerivation { .. }
| Error::Zones { .. }
| Error::StepRefused { .. }
| Error::StepNeeds { .. }
| Error::NotFitch { .. }
| Error::NoCut { .. }
| Error::NoTerm { .. }
| Error::NoDerivation { .. }
| Error::NotBuilt
| Error::Reduction(_) => {}
}
}
fn refused(refusal: &Refusal) {
match refusal {
Refusal::Stopped { .. }
| Refusal::Memory { .. }
| Refusal::Occurrences { .. }
| Refusal::Terms { .. }
| Refusal::Output { .. }
| Refusal::Work { .. }
| Refusal::Pixels { .. }
| Refusal::Elimination { .. }
| Refusal::Atoms { .. }
| Refusal::Workspace { .. }
| Refusal::Index { .. } => {}
}
}
#[test]
fn a_wire_error_takes_its_article() {
let error = |form| Error::Json {
form,
message: "missing field `verdict`".to_owned(),
};
assert_eq!(
error("ordinary outcome").to_string(),
"not an ordinary outcome of deduxit's wire form: missing field `verdict`"
);
assert_eq!(
error("proof").to_string(),
"not a proof of deduxit's wire form: missing field `verdict`"
);
}
#[test]
fn the_codes_are_listed() {
let listed: BTreeSet<&str> = Error::CODES.iter().copied().collect();
assert_eq!(listed.len(), Error::CODES.len(), "a code listed twice");
let mut given = BTreeSet::new();
for error in samples() {
variant(&error);
assert!(
listed.contains(error.code()),
"{} is not listed",
error.code()
);
given.insert(error.code());
}
let parse = ["parse", "lltp", "spec", "tptp", "several_conjectures"];
let interactive = [
"inconsistent_session",
"step",
"open_goals",
"foreign_proof",
"goal_mismatch",
];
let gated = |code: &str| {
let render = cfg!(any(feature = "png", feature = "pdf"));
(parse.contains(&code) || code == "family_size" || code == "family_index")
&& !cfg!(feature = "parse")
|| interactive.contains(&code) && !cfg!(feature = "interactive")
|| code == "no_certificate" && !cfg!(feature = "rocq")
|| code == "thread_pool" && !cfg!(feature = "parallel")
|| (code == "not_svg" || code == "render_failed") && !render
|| code == "no_date" && !cfg!(feature = "pdf")
};
for code in listed.difference(&given) {
assert!(gated(code), "no error gives {code}");
}
}
}