use super::search::Why;
use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::proofs::InfId;
use crate::ordinary::{
Derivation, Evidence, Formulas, Inference, Logic, Node, NodeId, Outcome, Rule, Search, Sequent,
Side, Translation, Verdict, bound, ljt,
};
#[cfg(feature = "interactive")]
use crate::ordinary::{Interactive, Parts};
use crate::wire::{self, Readable};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
impl Serialize for Rule {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.name())
}
}
impl<'a> Deserialize<'a> for Rule {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
Rule::ALL
.into_iter()
.find(|rule| rule.name() == name)
.ok_or_else(|| serde::de::Error::custom(format!("no rule of LK or LJ is named {name}")))
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
enum FormulaForm {
#[serde(rename = "V")]
Atom(u32),
#[serde(rename = "⊤")]
True,
#[serde(rename = "⊥")]
False,
#[serde(rename = "¬")]
Not(u32),
#[serde(rename = "∧")]
And(u32, u32),
#[serde(rename = "∨")]
Or(u32, u32),
#[serde(rename = "→")]
Implies(u32, u32),
#[serde(rename = "↔")]
Iff(u32, u32),
}
impl From<Node> for FormulaForm {
fn from(node: Node) -> Self {
let i = |k: NodeId| k.index() as u32;
match node {
Node::Atom(a) => Self::Atom(a),
Node::True => Self::True,
Node::False => Self::False,
Node::Not(a) => Self::Not(i(a)),
Node::And(a, b) => Self::And(i(a), i(b)),
Node::Or(a, b) => Self::Or(i(a), i(b)),
Node::Implies(a, b) => Self::Implies(i(a), i(b)),
Node::Iff(a, b) => Self::Iff(i(a), i(b)),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SequentForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
formulas: Vec<FormulaForm>,
atoms: Vec<String>,
left: Vec<u32>,
right: Vec<u32>,
}
impl SequentForm {
fn of(formulas: &Formulas, left: &[NodeId], right: &[NodeId]) -> Self {
let ids = |list: &[NodeId]| list.iter().map(|k| k.index() as u32).collect();
Self {
version: None,
formulas: formulas
.nodes()
.iter()
.map(|&n| FormulaForm::from(n))
.collect(),
atoms: formulas.atom_names().to_vec(),
left: ids(left),
right: ids(right),
}
}
fn within(self, limits: &Limits) -> Result<(Read, Vec<NodeId>, Vec<NodeId>), Error> {
if let Some(limit) = limits.occurrences
&& self.formulas.len() as u64 > limit
{
return Err(Error::Refused(Refusal::Occurrences {
occurrences: self.formulas.len() as u64,
limit,
}));
}
let mut formulas = Formulas::default();
let mut ids: Vec<NodeId> = Vec::with_capacity(self.formulas.len());
for (n, form) in self.formulas.iter().enumerate() {
let at = |k: u32| {
ids.get(k as usize).copied().ok_or(Error::IndexOutOfBounds {
space: Space::Formula,
index: k as usize,
len: n,
})
};
let id = match *form {
FormulaForm::Atom(a) => {
let name = self.atoms.get(a as usize).ok_or(Error::IndexOutOfBounds {
space: Space::Atom,
index: a as usize,
len: self.atoms.len(),
})?;
formulas.atom(name)?
}
FormulaForm::True => formulas.add(Node::True)?,
FormulaForm::False => formulas.add(Node::False)?,
FormulaForm::Not(a) => formulas.add(Node::Not(at(a)?))?,
FormulaForm::And(a, b) => formulas.add(Node::And(at(a)?, at(b)?))?,
FormulaForm::Or(a, b) => formulas.add(Node::Or(at(a)?, at(b)?))?,
FormulaForm::Implies(a, b) => formulas.add(Node::Implies(at(a)?, at(b)?))?,
FormulaForm::Iff(a, b) => formulas.add(Node::Iff(at(a)?, at(b)?))?,
};
ids.push(id);
}
let read = Read { formulas, ids };
let left = read.ids(&self.left)?;
let right = read.ids(&self.right)?;
bound(&read.formulas, &left, &right, limits)?;
Ok((read, left, right))
}
}
struct Read {
formulas: Formulas,
ids: Vec<NodeId>,
}
impl Read {
fn ids(&self, indices: &[u32]) -> Result<Vec<NodeId>, Error> {
indices
.iter()
.map(|&k| {
self.ids
.get(k as usize)
.copied()
.ok_or(Error::IndexOutOfBounds {
space: Space::Formula,
index: k as usize,
len: self.ids.len(),
})
})
.collect()
}
}
impl Serialize for Sequent {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut form = SequentForm::of(self.formulas(), self.left(), self.right());
form.version = Some(wire::ORDINARY);
form.serialize(serializer)
}
}
impl<'a> Deserialize<'a> for Sequent {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
impl crate::sealed::Readable for Sequent {}
impl Readable for Sequent {
const FORM: &'static str = "ordinary sequent";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
let form = SequentForm::deserialize(deserializer)?;
sequent(form, limits).map_err(wire::fail)
}
}
fn sequent(form: SequentForm, limits: &Limits) -> Result<Sequent, Error> {
let (read, left, right) = form.within(limits)?;
Sequent::new(read.formulas, left, right)
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct InferenceForm {
left: Vec<u32>,
right: Vec<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
rule: Option<Rule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
principal: Option<(Side, usize)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
premises: Vec<u32>,
}
impl InferenceForm {
fn of(inference: &Inference, open: bool) -> Self {
let ids = |list: &[NodeId]| list.iter().map(|k| k.index() as u32).collect();
Self {
left: ids(&inference.left),
right: ids(&inference.right),
rule: (!(open && inference.rule == Rule::Open)).then_some(inference.rule),
principal: inference.principal,
premises: inference.premises.iter().map(|p| p.get()).collect(),
}
}
fn read(self, read: &Read, len: usize) -> Result<Inference, Error> {
let premises = self
.premises
.iter()
.map(|&p| match p as usize {
p if p < len => Ok(InfId::new(p as u32)),
index => Err(Error::IndexOutOfBounds {
space: Space::Inference,
index,
len,
}),
})
.collect::<Result<_, _>>()?;
let inference = Inference {
left: read.ids(&self.left)?,
right: read.ids(&self.right)?,
rule: self.rule.unwrap_or(Rule::Open),
principal: self.principal,
premises,
};
if let Some((side, at)) = inference.principal
&& at >= inference.side(side).len()
{
return Err(Error::IndexOutOfBounds {
space: Space::Formula,
index: at,
len: inference.side(side).len(),
});
}
Ok(inference)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DerivationForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
logic: Logic,
sequent: SequentForm,
inferences: Vec<InferenceForm>,
}
impl From<&Derivation> for DerivationForm {
fn from(derivation: &Derivation) -> Self {
let (left, right) = derivation.sequent();
Self {
version: None,
logic: derivation.logic(),
sequent: SequentForm::of(derivation.formulas(), left, right),
inferences: derivation
.inferences()
.iter()
.map(|i| InferenceForm::of(i, false))
.collect(),
}
}
}
impl DerivationForm {
fn within(self, limits: &Limits) -> Result<Derivation, Error> {
let (read, left, right) = self.sequent.within(limits)?;
let len = self.inferences.len();
let mut parents = vec![0u8; len];
let mut inferences = Vec::with_capacity(len);
for (n, form) in self.inferences.into_iter().enumerate() {
let inference = form.read(&read, n)?;
if inference.rule == Rule::Open
&& (inference.principal.is_some() || !inference.premises.is_empty())
{
return Err(Error::Json {
form: "ordinary derivation",
message: format!("inference {n} is an open goal with a principal or premises"),
});
}
for p in &inference.premises {
parents[p.index()] = parents[p.index()].saturating_add(1);
}
inferences.push(inference);
}
let shaped = parents
.split_last()
.is_some_and(|(&root, rest)| root == 0 && rest.iter().all(|&n| n == 1));
if !shaped {
return Err(Error::Json {
form: "ordinary derivation",
message: "the inferences are no tree with its root last".to_owned(),
});
}
Ok(
Derivation::from_parts(self.logic, read.formulas, (left, right), inferences)
.untrusted(),
)
}
}
impl Serialize for Derivation {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut form = DerivationForm::from(self);
form.version = Some(level(self.inferences()));
form.serialize(serializer)
}
}
impl<'a> Deserialize<'a> for Derivation {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
impl crate::sealed::Readable for Derivation {}
impl Readable for Derivation {
const FORM: &'static str = "ordinary derivation";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
let form = DerivationForm::deserialize(deserializer)?;
form.within(limits).map_err(wire::fail)
}
}
#[derive(Serialize)]
struct OutcomeForm<'a> {
version: u32,
deduxit: &'static str,
verdict: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
reason: Option<Why>,
logic: Logic,
search: SearchForm<'a>,
#[serde(skip_serializing_if = "Option::is_none")]
derivation: Option<DerivationForm>,
#[cfg(feature = "sat")]
#[serde(skip_serializing_if = "Option::is_none")]
clausal_proof: Option<&'a crate::ordinary::sat::ClausalProof>,
#[serde(skip_serializing_if = "Option::is_none")]
countermodel: Option<CountermodelForm>,
}
#[derive(Serialize, Deserialize)]
struct CountermodelForm {
sequent: SequentForm,
model: super::kripke::ModelForm,
}
#[derive(Serialize)]
#[serde(tag = "method", rename_all = "snake_case")]
enum SearchForm<'a> {
Embedding {
translation: Translation,
image: super::search::Nested<'a>,
},
Ljt {
statistics: &'a ljt::Statistics,
},
#[cfg(feature = "sat")]
Sat {
statistics: &'a crate::ordinary::sat::Statistics,
},
Table {
table: TableForm,
},
#[cfg(feature = "interactive")]
Tableau {
tableau: TableauForm,
},
}
impl Serialize for Outcome {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let (verdict, reason, derivation) = match &self.verdict {
Verdict::Valid(Evidence::Derivation(d)) => {
("valid", None, Some(DerivationForm::from(&**d)))
}
#[cfg(feature = "sat")]
Verdict::Valid(Evidence::Clausal(_)) => ("valid", None, None),
Verdict::Valid(Evidence::Image | Evidence::Table) => ("valid", None, None),
Verdict::NotValid => ("not_valid", None, None),
Verdict::Unknown(r) => ("unknown", Some(Why::from(*r)), None),
};
let search = match &self.search {
Search::Embedding {
translation,
linear,
} => SearchForm::Embedding {
translation: *translation,
image: super::search::Nested(linear),
},
Search::Ljt(statistics) => SearchForm::Ljt { statistics },
#[cfg(feature = "sat")]
Search::Sat(statistics) => SearchForm::Sat { statistics },
Search::Table(table) => SearchForm::Table {
table: TableForm::from(&**table),
},
#[cfg(feature = "interactive")]
Search::Tableau(tableau) => SearchForm::Tableau {
tableau: TableauForm::from(&**tableau),
},
};
let version = match &self.search {
Search::Table(_) => wire::TABLES,
#[cfg(feature = "interactive")]
Search::Tableau(_) => wire::TABLES,
Search::Embedding { .. } | Search::Ljt(_) => wire::SEARCH,
#[cfg(feature = "sat")]
Search::Sat(_) => wire::SEARCH,
};
let countermodel = self.countermodel.as_ref().map(|c| CountermodelForm {
sequent: SequentForm::of(c.sequent.formulas(), c.sequent.left(), c.sequent.right()),
model: super::kripke::ModelForm::from(&c.model),
});
OutcomeForm {
version,
deduxit: env!("CARGO_PKG_VERSION"),
verdict,
reason,
logic: self.logic,
search,
derivation,
#[cfg(feature = "sat")]
clausal_proof: match &self.verdict {
Verdict::Valid(Evidence::Clausal(proof)) => Some(proof),
Verdict::Valid(Evidence::Derivation(_) | Evidence::Image | Evidence::Table)
| Verdict::NotValid
| Verdict::Unknown(_) => None,
},
countermodel,
}
.serialize(serializer)
}
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum VerdictWord {
Valid,
NotValid,
Unknown,
}
#[derive(Deserialize)]
#[serde(tag = "method", rename_all = "snake_case")]
enum SearchRead {
Embedding {
translation: Translation,
image: Box<super::search::OutcomeForm>,
},
Ljt {
statistics: ljt::Statistics,
},
#[cfg(feature = "sat")]
Sat {
statistics: crate::ordinary::sat::Statistics,
},
Table {
table: TableForm,
},
#[cfg(feature = "interactive")]
Tableau {
tableau: TableauForm,
},
}
#[derive(Deserialize)]
struct OutcomeRead {
#[serde(default, deserialize_with = "wire::version")]
version: Option<u32>,
verdict: VerdictWord,
#[serde(default)]
reason: Option<Why>,
logic: Logic,
#[serde(default)]
search: Option<SearchRead>,
#[serde(default)]
derivation: Option<DerivationForm>,
#[serde(default)]
clausal_proof: Option<serde::de::IgnoredAny>,
#[serde(default)]
countermodel: Option<CountermodelForm>,
}
impl OutcomeRead {
fn within(self, limits: &Limits) -> Result<Outcome, Error> {
let refuse = |message: &str| Error::Json {
form: "ordinary outcome",
message: message.to_owned(),
};
let search = match self.search {
Some(search) => search,
None if self.version.unwrap_or(wire::BASE) < wire::SEARCH => {
return Err(refuse(
"an ordinary outcome below level 12 has no `search` and is not read back",
));
}
None => return Err(refuse("missing field `search`")),
};
let search = match search {
SearchRead::Embedding { translation, image } => Search::Embedding {
translation,
linear: Box::new(image.within(limits)?),
},
SearchRead::Ljt { statistics } => Search::Ljt(statistics),
#[cfg(feature = "sat")]
SearchRead::Sat { statistics } => Search::Sat(statistics),
SearchRead::Table { table } => Search::Table(Box::new(table.within(limits)?)),
#[cfg(feature = "interactive")]
SearchRead::Tableau { tableau } => Search::Tableau(Box::new(tableau.within(limits)?)),
};
let image = match &search {
Search::Embedding { linear, .. } => Some(&linear.verdict),
#[cfg(feature = "sat")]
Search::Sat(_) => None,
Search::Ljt(_) | Search::Table(_) => None,
#[cfg(feature = "interactive")]
Search::Tableau(_) => None,
};
use crate::linear::search::Verdict as Linear;
let borne = match (&self.verdict, image) {
(_, None)
| (VerdictWord::Valid, Some(Linear::Proved(_)))
| (VerdictWord::NotValid, Some(Linear::Unprovable(_)))
| (VerdictWord::Unknown, Some(Linear::Unknown(_))) => true,
(_, Some(_)) => false,
};
if !borne {
return Err(refuse("the verdict is not the image's outcome's"));
}
let shown = match (&self.verdict, &search) {
(VerdictWord::Valid, Search::Table(table)) => table.falsifying().is_empty(),
(VerdictWord::NotValid, Search::Table(table)) => !table.falsifying().is_empty(),
#[cfg(feature = "interactive")]
(VerdictWord::Valid, Search::Tableau(tableau)) => tableau.is_closed(),
#[cfg(feature = "interactive")]
(VerdictWord::NotValid, Search::Tableau(tableau)) => !tableau.is_closed(),
_ => true,
};
if !shown {
return Err(refuse("the verdict is not its table's or its tableau's"));
}
let verdict = match self.verdict {
VerdictWord::Valid if self.clausal_proof.is_some() => {
return Err(refuse(
"a clausal proof is written as its counts, which hold no proof to read back",
));
}
VerdictWord::Valid => match self.derivation {
Some(form) => Verdict::Valid(Evidence::Derivation(Box::new(form.within(limits)?))),
None if image.is_some() => Verdict::Valid(Evidence::Image),
None if matches!(search, Search::Table(_)) => Verdict::Valid(Evidence::Table),
None => return Err(refuse("missing field `derivation`")),
},
VerdictWord::NotValid => Verdict::NotValid,
VerdictWord::Unknown => match self.reason {
Some(reason) => Verdict::Unknown(reason.into()),
None => return Err(refuse("missing field `reason`")),
},
};
let countermodel = match (self.countermodel, &verdict) {
(None, _) => None,
(Some(form), Verdict::NotValid) => Some(crate::ordinary::Countermodel::new(
sequent(form.sequent, limits)?,
form.model.within(limits)?,
)),
(Some(_), _) => {
return Err(refuse(
"a countermodel beside a verdict other than not_valid",
));
}
};
Ok(Outcome {
verdict,
logic: self.logic,
search,
countermodel,
})
}
}
impl<'a> Deserialize<'a> for Outcome {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
impl crate::sealed::Readable for Outcome {}
impl Readable for Outcome {
const FORM: &'static str = "ordinary outcome";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
OutcomeRead::deserialize(deserializer)?
.within(limits)
.map_err(wire::fail)
}
}
#[cfg(feature = "interactive")]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
logic: Logic,
sequent: SequentForm,
inferences: Vec<InferenceForm>,
history: Vec<u32>,
}
#[cfg(feature = "interactive")]
impl Serialize for Interactive {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let (logic, formulas, inferences, history) = self.parts();
let (left, right) = self.sequent();
SessionForm {
version: Some(level(inferences)),
logic,
sequent: SequentForm::of(formulas, left, right),
inferences: inferences
.iter()
.map(|i| InferenceForm::of(i, true))
.collect(),
history: history.iter().map(|h| h.get()).collect(),
}
.serialize(serializer)
}
}
#[cfg(feature = "interactive")]
impl<'a> Deserialize<'a> for Interactive {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
#[cfg(feature = "interactive")]
impl crate::sealed::Readable for Interactive {}
#[cfg(feature = "interactive")]
impl Readable for Interactive {
const FORM: &'static str = "ordinary session";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
let form = SessionForm::deserialize(deserializer)?;
session(form, limits).map_err(wire::fail)
}
}
#[cfg(feature = "interactive")]
fn session(form: SessionForm, limits: &Limits) -> Result<Interactive, Error> {
let (read, left, right) = form.sequent.within(limits)?;
let len = form.inferences.len();
let inferences = form
.inferences
.into_iter()
.map(|i| i.read(&read, len))
.collect::<Result<Vec<_>, _>>()?;
if inferences
.first()
.is_some_and(|root| root.left != left || root.right != right)
{
return Err(Error::InconsistentSession {
reason: "the root does not conclude the sequent",
});
}
let history = form
.history
.iter()
.map(|&h| match h as usize {
h if h < len => Ok(InfId::new(h as u32)),
index => Err(Error::IndexOutOfBounds {
space: Space::Inference,
index,
len,
}),
})
.collect::<Result<_, _>>()?;
Interactive::from_parts(
Parts {
logic: form.logic,
formulas: read.formulas,
inferences,
history,
},
limits,
)
}
fn level(inferences: &[Inference]) -> u32 {
if inferences.iter().any(|i| i.rule() == Rule::Cut) {
wire::ORDINARY_CUT
} else {
wire::ORDINARY
}
}
#[derive(Serialize, Deserialize)]
struct TableForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
sequent: SequentForm,
rows: Vec<String>,
falsifying: Vec<u64>,
}
impl From<&crate::ordinary::TruthTable> for TableForm {
fn from(table: &crate::ordinary::TruthTable) -> Self {
let sequent = table.sequent();
Self {
version: None,
sequent: SequentForm::of(sequent.formulas(), sequent.left(), sequent.right()),
rows: (0..table.rows())
.map(|row| {
table
.row(row)
.map(|value| if value { 'T' } else { 'F' })
.collect()
})
.collect(),
falsifying: table.falsifying().to_vec(),
}
}
}
impl TableForm {
fn within(self, limits: &Limits) -> Result<crate::ordinary::TruthTable, Error> {
let (read, left, right) = self.sequent.within(limits)?;
let ids = read.ids.clone();
let sequent = Sequent::new(read.formulas, left, right)?;
let table = crate::ordinary::truth_table(&sequent, limits, |_| false)?;
let matches = self.rows.len() as u64 == table.rows()
&& self.rows.iter().enumerate().all(|(row, text)| {
text.chars().count() == ids.len()
&& text.chars().zip(&ids).all(|(c, &id)| {
(c == 'T') == table.value(row as u64, id) && "TF".contains(c)
})
})
&& self.falsifying == table.falsifying();
if !matches {
return Err(Error::Json {
form: "truth table",
message: "the rows are not the sequent's truth table".to_owned(),
});
}
Ok(table)
}
}
impl Serialize for crate::ordinary::TruthTable {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut form = TableForm::from(self);
form.version = Some(wire::TABLES);
form.serialize(serializer)
}
}
impl<'a> Deserialize<'a> for crate::ordinary::TruthTable {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
impl crate::sealed::Readable for crate::ordinary::TruthTable {}
impl Readable for crate::ordinary::TruthTable {
const FORM: &'static str = "truth table";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
TableForm::deserialize(deserializer)?
.within(limits)
.map_err(wire::fail)
}
}
#[cfg(feature = "interactive")]
#[derive(Clone, Copy, Serialize, Deserialize)]
enum SignForm {
T,
F,
}
#[cfg(feature = "interactive")]
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum EndForm {
Closed {
true_line: u32,
false_line: u32,
},
Falsity {
line: u32,
},
Truth {
line: u32,
},
Open,
Unexpanded,
}
#[cfg(feature = "interactive")]
#[derive(Serialize, Deserialize)]
struct TableauNodeForm {
lines: Vec<(SignForm, u32)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
expands: Option<(u32, Rule)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
children: Vec<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
end: Option<EndForm>,
}
#[cfg(feature = "interactive")]
#[derive(Serialize, Deserialize)]
struct TableauForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
sequent: SequentForm,
nodes: Vec<TableauNodeForm>,
}
#[cfg(feature = "interactive")]
impl From<&crate::ordinary::Tableau> for TableauForm {
fn from(tableau: &crate::ordinary::Tableau) -> Self {
use crate::ordinary::{End, Sign};
let (left, right) = tableau.sequent();
Self {
version: None,
sequent: SequentForm::of(tableau.formulas(), left, right),
nodes: tableau
.nodes()
.iter()
.map(|node| TableauNodeForm {
lines: node
.lines()
.iter()
.map(|line| {
let sign = match line.sign {
Sign::True => SignForm::T,
Sign::False => SignForm::F,
};
(sign, line.formula.index() as u32)
})
.collect(),
expands: node.expands(),
children: node.children().to_vec(),
end: node.end().map(|end| match end {
End::Closed {
true_line,
false_line,
} => EndForm::Closed {
true_line,
false_line,
},
End::Falsity { line } => EndForm::Falsity { line },
End::Truth { line } => EndForm::Truth { line },
End::Open => EndForm::Open,
End::Unexpanded => EndForm::Unexpanded,
}),
})
.collect(),
}
}
}
#[cfg(feature = "interactive")]
impl TableauForm {
fn within(self, limits: &Limits) -> Result<crate::ordinary::Tableau, Error> {
use crate::ordinary::{End, Sign, Signed, Tableau, TableauNode};
let refuse = |message: String| Error::Json {
form: "tableau",
message,
};
let (read, left, right) = self.sequent.within(limits)?;
let total: u64 = self.nodes.iter().map(|n| n.lines.len() as u64).sum();
let total =
u32::try_from(total).map_err(|_| refuse("more lines than a u32 numbers".to_owned()))?;
let line = |n: u32| {
if n < total {
Ok(n)
} else {
Err(refuse(format!(
"line {n} is past the tableau's {total} lines"
)))
}
};
let len = self.nodes.len();
let mut parents = vec![0u8; len];
let mut nodes = Vec::with_capacity(len);
let mut first = 0u32;
for (n, form) in self.nodes.into_iter().enumerate() {
let lines = form
.lines
.iter()
.map(|&(sign, k)| {
let sign = match sign {
SignForm::T => Sign::True,
SignForm::F => Sign::False,
};
Ok(Signed::new(sign, read.ids(&[k])?[0]))
})
.collect::<Result<Vec<_>, Error>>()?;
for &child in &form.children {
if (child as usize) <= n || child as usize >= len {
return Err(refuse(format!("node {n} names child {child}")));
}
parents[child as usize] = parents[child as usize].saturating_add(1);
}
let expands = form
.expands
.map(|(l, rule)| line(l).map(|l| (l, rule)))
.transpose()?;
let end = form
.end
.map(|end| {
Ok::<_, Error>(match end {
EndForm::Closed {
true_line,
false_line,
} => End::Closed {
true_line: line(true_line)?,
false_line: line(false_line)?,
},
EndForm::Falsity { line: l } => End::Falsity { line: line(l)? },
EndForm::Truth { line: l } => End::Truth { line: line(l)? },
EndForm::Open => End::Open,
EndForm::Unexpanded => End::Unexpanded,
})
})
.transpose()?;
let leaf = form.children.is_empty();
if leaf != end.is_some() || leaf == expands.is_some() {
return Err(refuse(format!(
"node {n} must have children and expand a line, or end its branch"
)));
}
let count = lines.len() as u32;
nodes.push(TableauNode::from_parts(
first,
lines,
(expands, form.children, end),
));
first += count;
}
let shaped = parents
.split_first()
.is_some_and(|(&root, rest)| root == 0 && rest.iter().all(|&p| p == 1));
if !shaped {
return Err(refuse(
"the nodes are no tree with its root first".to_owned(),
));
}
Ok(Tableau::from_parts(read.formulas, (left, right), nodes))
}
}
#[cfg(feature = "interactive")]
impl Serialize for crate::ordinary::Tableau {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut form = TableauForm::from(self);
form.version = Some(wire::TABLES);
form.serialize(serializer)
}
}
#[cfg(feature = "interactive")]
impl<'a> Deserialize<'a> for crate::ordinary::Tableau {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
#[cfg(feature = "interactive")]
impl crate::sealed::Readable for crate::ordinary::Tableau {}
#[cfg(feature = "interactive")]
impl Readable for crate::ordinary::Tableau {
const FORM: &'static str = "tableau";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
TableauForm::deserialize(deserializer)?
.within(limits)
.map_err(wire::fail)
}
}