mod linear;
mod ordinary;
mod rules;
mod shared;
#[cfg(test)]
pub(crate) use ordinary::write_statement as ordinary_statement;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::{Error, Limits, Progress, Settings, wire};
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
Statement,
Definition,
Work,
Evidence,
Rendering,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Class {
Derived,
Work,
Copy,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Cost {
Instant,
Search,
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct Kind {
pub name: &'static str,
pub role: Role,
pub form: &'static str,
pub level: Option<u32>,
pub stored: bool,
pub label: &'static str,
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct Parameter {
pub name: &'static str,
pub values: &'static [&'static str],
pub default: Option<&'static str>,
pub description: &'static str,
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct Promise {
pub name: &'static str,
pub check: Option<Cost>,
pub description: &'static str,
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct Operation {
pub name: &'static str,
pub from: &'static [&'static [&'static str]],
pub to: &'static str,
pub class: Class,
pub cost: Cost,
pub parameters: &'static [Parameter],
pub reads: &'static [&'static str],
pub promise: &'static Promise,
pub label: &'static str,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub struct Call<'a> {
pub operation: &'static Operation,
pub inputs: &'a [&'a str],
pub parameters: &'a str,
pub settings: &'a Settings,
}
impl<'a> Call<'a> {
pub const fn new(
operation: &'static Operation,
inputs: &'a [&'a str],
parameters: &'a str,
settings: &'a Settings,
) -> Self {
Self {
operation,
inputs,
parameters,
settings,
}
}
fn input(&self, index: usize) -> &'a str {
self.inputs.get(index).copied().unwrap_or_default()
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct Limit {
pub reason: &'static str,
pub setting: Option<&'static str>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Produced {
pub value: String,
pub limit: Option<Limit>,
}
impl Produced {
const fn done(value: String) -> Self {
Self { value, limit: None }
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Held,
Failed,
Open,
Recorded,
Outside,
None,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
Valid,
NotValid,
Unknown,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct Part {
pub name: String,
pub status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub verdict: Option<Verdict>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct Check {
pub promise: String,
pub status: Status,
pub parts: Vec<Part>,
}
impl Check {
fn whole(promise: &'static Promise, status: Status) -> Self {
Self {
promise: promise.name.to_owned(),
status,
parts: Vec::new(),
}
}
fn of(promise: &'static Promise, parts: Vec<Part>) -> Self {
let status = if parts.iter().any(|p| p.status == Status::Failed) {
Status::Failed
} else if parts.iter().any(|p| p.status == Status::Open) {
Status::Open
} else {
Status::Held
};
Self {
promise: promise.name.to_owned(),
status,
parts,
}
}
}
pub type Ask<'a> = dyn FnMut(&str, &[&str], &str) -> Result<String, Error> + 'a;
pub trait Suite: Sync {
fn name(&self) -> &'static str;
fn label(&self) -> &'static str;
fn kinds(&self) -> &'static [Kind];
fn operations(&self) -> &'static [Operation];
fn read(&self, kind: &Kind, value: &str, limits: &Limits) -> Result<(), Error>;
fn summary(&self, kind: &Kind, value: &str, limits: &Limits) -> Result<String, Error>;
fn run(
&self,
call: &Call<'_>,
stop: &mut dyn FnMut(Progress) -> bool,
) -> Result<Produced, Error>;
fn check(
&self,
call: &Call<'_>,
output: &str,
ask: &mut Ask<'_>,
stop: &mut dyn FnMut(Progress) -> bool,
) -> Result<Check, Error>;
}
pub fn suites() -> &'static [&'static dyn Suite] {
&SUITES
}
static SUITES: [&dyn Suite; 3] = [&linear::LINEAR, &ordinary::ORDINARY, &rules::RULES];
pub const fn shared() -> &'static [Kind] {
&shared::KINDS
}
const OPERATIONS: &[&str] = &[
"linear.prove",
"linear.start",
"linear.goal",
"linear.proof",
"linear.net",
"linear.eliminate",
"linear.term",
#[cfg(feature = "svg")]
"linear.draw",
"linear.export",
#[cfg(feature = "rocq")]
"linear.certificate",
"linear.duplicate",
"ordinary.decide",
"ordinary.start",
"ordinary.goal",
"ordinary.derivation",
"ordinary.translate",
"ordinary.interpolate",
"ordinary.half",
"ordinary.embed",
"ordinary.term",
#[cfg(feature = "svg")]
"ordinary.draw",
"ordinary.export",
#[cfg(feature = "rocq")]
"ordinary.certificate",
"ordinary.duplicate",
"rules.start",
"rules.derivation",
"rules.from_ordinary",
#[cfg(feature = "svg")]
"rules.draw",
#[cfg(any(feature = "latex", feature = "typst"))]
"rules.export",
"rules.duplicate",
];
const KINDS: &[&str] = &[
"linear.sequent",
"linear.session",
"linear.outcome",
"linear.proof",
"linear.net",
"ordinary.sequent",
"ordinary.session",
"ordinary.outcome",
"ordinary.derivation",
"ordinary.interpolant",
"rules.calculus",
"rules.sequent",
"rules.session",
"rules.derivation",
"drawing",
"text",
"certificate",
"term",
];
pub fn operation(name: &str) -> Result<(&'static dyn Suite, &'static Operation), Error> {
suites()
.iter()
.find_map(|suite| {
suite
.operations()
.iter()
.find(|operation| operation.name == name)
.map(|operation| (*suite, operation))
})
.ok_or_else(|| Error::UnknownName {
what: "operation",
name: name.into(),
known: OPERATIONS,
})
}
pub fn kind(name: &str) -> Result<(Option<&'static dyn Suite>, &'static Kind), Error> {
if let Some(kind) = shared::KINDS.iter().find(|kind| kind.name == name) {
return Ok((None, kind));
}
suites()
.iter()
.find_map(|suite| {
suite
.kinds()
.iter()
.find(|kind| kind.name == name)
.map(|kind| (Some(*suite), kind))
})
.ok_or_else(|| Error::UnknownName {
what: "kind",
name: name.into(),
known: KINDS,
})
}
pub fn read(kind: &str, value: &str, limits: &Limits) -> Result<(), Error> {
match self::kind(kind)? {
(Some(suite), kind) => suite.read(kind, value, limits),
(None, kind) => shared::read(kind, value),
}
}
pub fn summary(kind: &str, value: &str, limits: &Limits) -> Result<String, Error> {
match self::kind(kind)? {
(Some(suite), kind) => suite.summary(kind, value, limits),
(None, kind) => shared::summary(kind, value),
}
}
pub fn run(
operation: &str,
inputs: &[&str],
parameters: &str,
settings: &Settings,
mut stop: impl FnMut(Progress) -> bool,
) -> Result<Produced, Error> {
let (suite, operation) = self::operation(operation)?;
let call = Call::new(operation, inputs, parameters, settings);
arity(&call)?;
suite.run(&call, &mut stop)
}
pub fn check(
operation: &str,
inputs: &[&str],
parameters: &str,
output: &str,
settings: &Settings,
mut stop: impl FnMut(Progress) -> bool,
) -> Result<Check, Error> {
let (suite, operation) = self::operation(operation)?;
let call = Call::new(operation, inputs, parameters, settings);
arity(&call)?;
let stop = std::cell::RefCell::new(&mut stop);
let mut ask = |name: &str, inputs: &[&str], parameters: &str| {
run(name, inputs, parameters, settings, |progress| {
(stop.borrow_mut())(progress)
})
.map(|produced| produced.value)
};
suite.check(&call, output, &mut ask, &mut |progress| {
(stop.borrow_mut())(progress)
})
}
fn kinds(call: &Call<'_>) -> Error {
Error::Json {
form: "input",
message: format!(
"{} takes {}",
call.operation.name,
call.operation
.from
.first()
.map_or(String::new(), |kinds| kinds.join(" or "))
),
}
}
fn takes(call: &Call<'_>, kind: &str) -> Result<(), Error> {
if call
.operation
.from
.first()
.is_some_and(|kinds| kinds.contains(&kind))
{
Ok(())
} else {
Err(kinds(call))
}
}
pub fn statement(
suite: &str,
text: &str,
parameter: &str,
limits: &Limits,
) -> Result<String, Error> {
match suite {
"ordinary" => {
let logic: crate::ordinary::Logic = parameter.parse()?;
let sequent = crate::ordinary::Sequent::parse_within(text, limits)?;
ordinary::typed_statement(&sequent, logic, Some(text))
}
"linear" => {
let mode: crate::linear::Mode = parameter.parse()?;
let sequent = if mode.is_intuitionistic() && !mode.is_ordered() {
crate::linear::IllSequent::parse_within(text, limits)?.into_sequent()
} else if mode.is_ordered() {
crate::linear::Sequent::parse_ordered(text, mode.order(), limits)?
} else {
crate::linear::Sequent::parse_within(text, limits)?
};
linear::typed_statement(&sequent, mode, Some(text))
}
_ => Err(Error::UnknownName {
what: "suite",
name: suite.into(),
known: &["linear", "ordinary"],
}),
}
}
fn arity(call: &Call<'_>) -> Result<(), Error> {
let takes = call.operation.from.len();
if call.inputs.len() == takes {
Ok(())
} else {
Err(Error::InvalidOption {
key: "inputs",
message: format!(
"{} takes {takes} input{}, not {}",
call.operation.name,
if takes == 1 { "" } else { "s" },
call.inputs.len()
),
})
}
}
#[derive(Debug, Serialize)]
pub struct Catalogue {
deduxit: &'static str,
level: u32,
suites: Vec<Described>,
shared: &'static [Kind],
}
#[derive(Debug, Serialize)]
struct Described {
suite: &'static str,
label: &'static str,
kinds: &'static [Kind],
operations: &'static [Operation],
}
pub fn catalogue() -> Catalogue {
Catalogue {
deduxit: env!("CARGO_PKG_VERSION"),
level: wire::LEVEL,
suites: suites()
.iter()
.map(|suite| Described {
suite: suite.name(),
label: suite.label(),
kinds: suite.kinds(),
operations: suite.operations(),
})
.collect(),
shared: &shared::KINDS,
}
}
fn document<T: wire::Readable>(text: &str, limits: &Limits) -> Result<T, Error> {
let mut json = serde_json::Deserializer::from_str(text);
let value = wire::upgrade(&mut json, limits)?;
json.end().map_err(|error| Error::Json {
form: T::FORM,
message: error.to_string(),
})?;
Ok(value)
}
fn object<T: DeserializeOwned>(text: &str, form: &'static str) -> Result<T, Error> {
serde_json::from_str(text).map_err(|error| Error::Json {
form,
message: error.to_string(),
})
}
fn parameters<T: DeserializeOwned + Default>(call: &Call<'_>) -> Result<T, Error> {
if call.parameters.trim().is_empty() {
return Ok(T::default());
}
serde_json::from_str(call.parameters).map_err(|error| Error::InvalidOption {
key: "parameters",
message: format!("{}: {error}", call.operation.name),
})
}
fn written(value: &impl Serialize) -> Result<String, Error> {
serde_json::to_string(value).map_err(|error| Error::Json {
form: "value",
message: error.to_string(),
})
}
#[derive(serde::Deserialize)]
struct Verdicted {
verdict: String,
}
fn verdict_of(outcome: &str) -> Result<Verdict, Error> {
let read: Verdicted = object(outcome, "outcome")?;
Ok(match read.verdict.as_str() {
"valid" | "proved" => Verdict::Valid,
"not_valid" | "unprovable" => Verdict::NotValid,
_ => Verdict::Unknown,
})
}
fn part(name: &'static str, verdict: Verdict, expected: Verdict) -> Part {
let status = match verdict {
Verdict::Unknown => Status::Open,
found if found == expected => Status::Held,
_ => Status::Failed,
};
Part {
name: name.to_owned(),
status,
verdict: Some(verdict),
}
}
fn same_verdict(
promise: &'static Promise,
names: [&'static str; 2],
verdicts: [Verdict; 2],
) -> Check {
let open = verdicts.contains(&Verdict::Unknown);
let agree = verdicts[0] == verdicts[1];
let status = |verdict| match verdict {
Verdict::Unknown => Status::Open,
_ if agree || open => Status::Held,
_ => Status::Failed,
};
Check::of(
promise,
vec![
Part {
name: names[0].to_owned(),
status: status(verdicts[0]),
verdict: Some(verdicts[0]),
},
Part {
name: names[1].to_owned(),
status: status(verdicts[1]),
verdict: Some(verdicts[1]),
},
],
)
}
mod promises {
use super::{Cost, Promise};
pub(super) static EXACT: Promise = Promise {
name: "exact",
check: None,
description: "The output is read off the input: a goal, a half, a start or a copy.",
};
pub(super) static DECIDES: Promise = Promise {
name: "decides",
check: Some(Cost::Instant),
description: "A verdict has its evidence, which deduxit's checker accepts: a proof or derivation, a refutation or a countermodel.",
};
pub(super) static PROVES: Promise = Promise {
name: "proves",
check: Some(Cost::Instant),
description: "The proof, derivation or net proves its sequent, which deduxit's checker accepts.",
};
pub(super) static SAME_VERDICT: Promise = Promise {
name: "same_verdict",
check: Some(Cost::Search),
description: "The input and the output are valid together or not: both are decided and the verdicts compared.",
};
pub(super) static INTERPOLATES: Promise = Promise {
name: "interpolates",
check: Some(Cost::Search),
description: "The interpolant's atoms occur in both parts, and both halves are valid.",
};
pub(super) static RENDERS: Promise = Promise {
name: "renders",
check: None,
description: "The drawing or text shows its input.",
};
#[cfg(feature = "rocq")]
pub(super) static CERTIFIES: Promise = Promise {
name: "certifies",
check: None,
description: "Rocq accepts the certificate; deduxit checked what it writes, and Rocq checks the file.",
};
}
const SIZES: [&str; 2] = ["limits.occurrences", "limits.terms"];
const START: [&str; 4] = [
"limits.memory_bytes",
"limits.occurrences",
"limits.terms",
"limits.derivation_bytes",
];
const SEARCH: [&str; 8] = [
"limits.memory_bytes",
"limits.occurrences",
"limits.terms",
"limits.derivation_bytes",
"limits.work",
"limits.recursion_depth",
"limits.table_atoms",
"search",
];
#[cfg(test)]
mod tests;