use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::rules::{Associativity, Calculus, Derivation, Discipline, Fixity, Step, TermId};
use crate::rules::{Node, Term, Terms};
use crate::wire::{self, Readable};
use serde::de::{DeserializeSeed, MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, SerializeSeq};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
use std::fmt::{Formatter, Result as FmtResult};
pub(crate) const DEPTH: u32 = 64;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct CalculusForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
pub(crate) version: Option<u32>,
pub(crate) name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub(crate) description: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) sorts: Vec<String>,
pub(crate) connectives: Vec<ConnectiveForm>,
pub(crate) sequent: Vec<ZoneForm>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(crate) variables: BTreeMap<String, Vec<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) contexts: Vec<String>,
pub(crate) rules: Vec<RuleForm>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ConnectiveForm {
pub(crate) name: String,
pub(crate) arity: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) sorts: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) symbol: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) fixity: Option<Fixity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) precedence: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) associativity: Option<Associativity>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ZoneForm {
pub(crate) name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) sort: Option<String>,
pub(crate) discipline: Discipline,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) mark: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) least: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) most: Option<u32>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RuleForm {
pub(crate) name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) premises: Vec<PremiseForm>,
#[serde(deserialize_with = "once")]
pub(crate) conclusion: SequentForm,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) fresh: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) atomic: Vec<String>,
}
pub(crate) type SequentForm = BTreeMap<String, Vec<PatternForm>>;
#[derive(Clone, Debug, Default)]
pub(crate) struct PremiseForm {
pub(crate) sequent: SequentForm,
pub(crate) discharges: Vec<SequentForm>,
}
pub(crate) const DISCHARGES: &str = "discharges";
impl Serialize for PremiseForm {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
for (zone, entries) in &self.sequent {
map.serialize_entry(zone, entries)?;
}
if !self.discharges.is_empty() {
map.serialize_entry(DISCHARGES, &self.discharges)?;
}
map.end()
}
}
impl<'de> Deserialize<'de> for PremiseForm {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Keys;
impl<'de> Visitor<'de> for Keys {
type Value = PremiseForm;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("a premise: its zones, and what it discharges")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<PremiseForm, A::Error> {
let mut premise = PremiseForm::default();
let mut discharges = false;
while let Some(key) = map.next_key::<String>()? {
let twice = if key == DISCHARGES {
let hypotheses: Vec<Once> = map.next_value()?;
premise.discharges = hypotheses.into_iter().map(|h| h.0).collect();
std::mem::replace(&mut discharges, true)
} else {
let entries = map.next_value()?;
premise.sequent.insert(key.clone(), entries).is_some()
};
if twice {
return Err(serde::de::Error::custom(format!(
"the key {key:?} is written twice"
)));
}
}
Ok(premise)
}
}
deserializer.deserialize_map(Keys)
}
}
struct Once(SequentForm);
impl<'de> Deserialize<'de> for Once {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Keys;
impl<'de> Visitor<'de> for Keys {
type Value = Once;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("a sequent: the entries of each zone, by the zone's name")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Once, A::Error> {
let mut sequent = SequentForm::new();
while let Some(key) = map.next_key::<String>()? {
let entries = map.next_value()?;
if sequent.insert(key.clone(), entries).is_some() {
return Err(serde::de::Error::custom(format!(
"the key {key:?} is written twice"
)));
}
}
Ok(Once(sequent))
}
}
deserializer.deserialize_map(Keys)
}
}
fn once<'de, D: Deserializer<'de>>(deserializer: D) -> Result<SequentForm, D::Error> {
Once::deserialize(deserializer).map(|once| once.0)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PatternForm {
Name(String),
Apply(String, Vec<PatternForm>),
}
impl Serialize for PatternForm {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Name(name) => serializer.serialize_str(name),
Self::Apply(connective, arguments) => {
let mut seq = serializer.serialize_seq(Some(arguments.len() + 1))?;
seq.serialize_element(connective)?;
for argument in arguments {
seq.serialize_element(argument)?;
}
seq.end()
}
}
}
}
struct Nested(u32);
impl<'de> DeserializeSeed<'de> for Nested {
type Value = PatternForm;
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<PatternForm, D::Error> {
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for Nested {
type Value = PatternForm;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("a name, or an array of a connective's name and its arguments")
}
fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<PatternForm, E> {
Ok(PatternForm::Name(name.to_owned()))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<PatternForm, A::Error> {
if self.0 >= DEPTH {
return Err(serde::de::Error::custom(format!(
"a pattern is nested deeper than {DEPTH}"
)));
}
let connective: String = seq
.next_element()?
.ok_or_else(|| serde::de::Error::custom("an empty array names no connective"))?;
let mut arguments = Vec::new();
while let Some(argument) = seq.next_element_seed(Nested(self.0 + 1))? {
arguments.push(argument);
}
Ok(PatternForm::Apply(connective, arguments))
}
}
impl<'de> Deserialize<'de> for PatternForm {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Nested(0).deserialize(deserializer)
}
}
impl Serialize for Calculus {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut form = self.form().clone();
form.version = Some(wire::RULES);
form.serialize(serializer)
}
}
impl<'a> Deserialize<'a> for Calculus {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
impl crate::sealed::Readable for Calculus {}
impl Readable for Calculus {
const FORM: &'static str = "calculus";
fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
let mut form = CalculusForm::deserialize(deserializer)?;
form.version = None;
Self::from_form(form, limits).map_err(wire::fail)
}
}
#[derive(Clone, Debug)]
enum TermForm {
Atom(String, String),
Apply(String, Vec<u32>),
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AtomForm {
atom: String,
#[serde(default = "formula")]
sort: String,
}
fn formula() -> String {
crate::rules::FORMULA.to_owned()
}
impl Serialize for TermForm {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::Atom(name, sort) if sort == crate::rules::FORMULA => {
serializer.serialize_str(name)
}
Self::Atom(name, sort) => AtomForm {
atom: name.clone(),
sort: sort.clone(),
}
.serialize(serializer),
Self::Apply(connective, arguments) => {
let mut seq = serializer.serialize_seq(Some(arguments.len() + 1))?;
seq.serialize_element(connective)?;
for argument in arguments {
seq.serialize_element(argument)?;
}
seq.end()
}
}
}
}
impl<'de> Deserialize<'de> for TermForm {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Forms;
impl<'de> Visitor<'de> for Forms {
type Value = TermForm;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("an atom's name, an atom with its sort, or a connective and indices")
}
fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<TermForm, E> {
Ok(TermForm::Atom(name.to_owned(), formula()))
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<TermForm, A::Error> {
let atom =
AtomForm::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
Ok(TermForm::Atom(atom.atom, atom.sort))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<TermForm, A::Error> {
let connective: String = seq.next_element()?.ok_or_else(|| {
serde::de::Error::custom("an empty array names no connective")
})?;
let mut arguments = Vec::new();
while let Some(argument) = seq.next_element()? {
arguments.push(argument);
}
Ok(TermForm::Apply(connective, arguments))
}
}
deserializer.deserialize_any(Forms)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NodeForm {
sequent: Vec<Vec<u32>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
rule: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
hypothesis: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
at: Vec<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
premises: Vec<u32>,
#[serde(default, skip_serializing_if = "is_zero")]
scope: u32,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
const fn is_zero(scope: &u32) -> bool {
*scope == 0
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DerivationForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
calculus: String,
terms: Vec<TermForm>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
scopes: Vec<u32>,
nodes: Vec<NodeForm>,
}
impl From<&Derivation> for DerivationForm {
fn from(derivation: &Derivation) -> Self {
let index = |id: &TermId| id.index() as u32;
Self {
version: None,
calculus: derivation.calculus().to_owned(),
terms: terms_form(derivation.terms()),
scopes: derivation.scope_parents().iter().skip(1).copied().collect(),
nodes: derivation
.nodes()
.map(|node| NodeForm {
sequent: (0..derivation.zones())
.map(|zone| node.zone(zone).iter().map(index).collect())
.collect(),
rule: match node.step() {
Step::Rule(name) => Some(name.to_owned()),
Step::Hypothesis | Step::Open => None,
},
hypothesis: node.step() == Step::Hypothesis,
at: node.positions().to_vec(),
premises: node.premises().iter().map(|p| p.index() as u32).collect(),
scope: node.scope().index() as u32,
})
.collect(),
}
}
}
fn terms_form(terms: &Terms) -> Vec<TermForm> {
(0..terms.len())
.map(|n| match terms.term(TermId::new(n as u32)) {
Term::Atom { name, sort } => TermForm::Atom(name.to_owned(), sort.to_owned()),
Term::Apply {
connective,
arguments,
} => TermForm::Apply(
connective.to_owned(),
arguments.iter().map(|id| id.index() as u32).collect(),
),
})
.collect()
}
fn read_terms(
forms: &[TermForm],
terms: &mut Terms,
limits: &Limits,
) -> Result<Vec<TermId>, Error> {
if let Some(limit) = limits.occurrences
&& forms.len() as u64 > limit
{
return Err(Error::Refused(Refusal::Occurrences {
occurrences: forms.len() as u64,
limit,
}));
}
let mut ids: Vec<TermId> = Vec::with_capacity(forms.len());
for form in forms {
let id = match form {
TermForm::Atom(name, sort) => terms.atom(name, sort)?,
TermForm::Apply(connective, arguments) => {
let arguments = arguments
.iter()
.map(|&index| term_at(&ids, index))
.collect::<Result<Vec<_>, _>>()?;
terms.apply(connective, &arguments)?
}
};
ids.push(id);
}
Ok(ids)
}
fn term_at(ids: &[TermId], index: u32) -> Result<TermId, Error> {
ids.get(index as usize)
.copied()
.ok_or(Error::IndexOutOfBounds {
space: Space::Term,
index: index as usize,
len: ids.len(),
})
}
impl DerivationForm {
fn within(self, limits: &Limits) -> Result<Derivation, Error> {
let zones = self.nodes.first().map_or(0, |node| node.sequent.len());
let mut derivation = Derivation::new(&self.calculus, zones);
let ids = read_terms(&self.terms, derivation.terms_mut(), limits)?;
let at = term_at;
for parent in self.scopes {
derivation.scope(parent)?;
}
for form in self.nodes {
let sequent = form
.sequent
.iter()
.map(|zone| zone.iter().map(|&index| at(&ids, index)).collect())
.collect::<Result<Vec<Vec<TermId>>, _>>()?;
let step = match (&form.rule, form.hypothesis) {
(Some(rule), false) => Step::Rule(rule),
(None, true) => Step::Hypothesis,
(None, false) => Step::Open,
(Some(_), true) => {
return Err(Error::Json {
form: Derivation::FORM,
message: "a node is both a rule's and a hypothesis".to_owned(),
});
}
};
derivation.push(Node {
sequent: &sequent,
step,
premises: &form.premises,
positions: &form.at,
scope: form.scope,
})?;
}
if derivation.is_empty() {
return Err(Error::Json {
form: Derivation::FORM,
message: "a derivation has at least one node".to_owned(),
});
}
Ok(derivation)
}
}
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(wire::RULES);
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 = "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)
}
}
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ScopeForm {
#[serde(default, skip_serializing_if = "is_zero")]
parent: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
owner: Option<(u32, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
hypotheses: Vec<Vec<Vec<u32>>>,
}
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionNodeForm {
sequent: Vec<Vec<u32>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
rule: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
hypothesis: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
at: Vec<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
premises: Vec<u32>,
#[serde(default, skip_serializing_if = "is_zero")]
scope: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
opened: Option<u32>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
line: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
cites: Option<u32>,
}
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionForm {
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "wire::version"
)]
version: Option<u32>,
calculus: CalculusForm,
terms: Vec<TermForm>,
scopes: Vec<ScopeForm>,
nodes: Vec<SessionNodeForm>,
#[serde(default)]
history: Vec<u32>,
}
#[cfg(all(feature = "interactive", feature = "parse"))]
impl Serialize for crate::rules::Interactive {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use crate::rules::interactive::Done;
let ids = |sequent: &[Vec<TermId>]| -> Vec<Vec<u32>> {
sequent
.iter()
.map(|zone| zone.iter().map(|id| id.index() as u32).collect())
.collect()
};
let mut calculus = self.calculus().form().clone();
calculus.version = None;
let forward = self.nodes.iter().any(|node| node.line);
let form = SessionForm {
version: Some(if forward {
wire::FORWARD
} else {
wire::SESSION
}),
calculus,
terms: terms_form(self.terms()),
scopes: self
.scopes
.iter()
.map(|scope| ScopeForm {
parent: scope.parent,
owner: scope.owner,
hypotheses: scope.hypotheses.iter().map(|h| ids(h)).collect(),
})
.collect(),
nodes: self
.nodes
.iter()
.map(|node| SessionNodeForm {
sequent: ids(&node.sequent),
rule: match &node.done {
Done::Rule(name, _) => Some(name.clone()),
Done::Open | Done::Hypothesis | Done::Line(_) => None,
},
hypothesis: node.done == Done::Hypothesis,
at: match &node.done {
Done::Rule(_, at) => at.clone(),
Done::Open | Done::Hypothesis | Done::Line(_) => Vec::new(),
},
premises: node.premises.clone(),
scope: node.scope,
opened: (node.opened != node.scope).then_some(node.opened),
line: node.line,
cites: match node.done {
Done::Line(line) => Some(line),
Done::Open | Done::Hypothesis | Done::Rule(..) => None,
},
})
.collect(),
history: self.history.clone(),
};
form.serialize(serializer)
}
}
#[cfg(all(feature = "interactive", feature = "parse"))]
impl<'a> Deserialize<'a> for crate::rules::Interactive {
fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
Self::read(deserializer, &Limits::default())
}
}
#[cfg(all(feature = "interactive", feature = "parse"))]
impl crate::sealed::Readable for crate::rules::Interactive {}
#[cfg(all(feature = "interactive", feature = "parse"))]
impl Readable for crate::rules::Interactive {
const FORM: &'static str = "session in a calculus";
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(all(feature = "interactive", feature = "parse"))]
fn session(form: SessionForm, limits: &Limits) -> Result<crate::rules::Interactive, Error> {
use crate::rules::interactive::{Done, Goal, Scope};
let calculus = Calculus::from_form(form.calculus, limits)?;
let mut terms = Terms::default();
let ids = read_terms(&form.terms, &mut terms, limits)?;
let sequent = |zones: &[Vec<u32>]| -> Result<Vec<Vec<TermId>>, Error> {
zones
.iter()
.map(|zone| zone.iter().map(|&i| term_at(&ids, i)).collect())
.collect()
};
let scopes = form
.scopes
.iter()
.map(|scope| {
Ok(Scope {
parent: scope.parent,
owner: scope.owner,
hypotheses: scope
.hypotheses
.iter()
.map(|h| sequent(h))
.collect::<Result<_, Error>>()?,
})
})
.collect::<Result<Vec<_>, Error>>()?;
let nodes = form
.nodes
.iter()
.map(|node| {
let done = match (&node.rule, node.hypothesis, node.cites) {
(Some(rule), false, None) => Done::Rule(rule.clone(), node.at.clone()),
(None, true, None) => Done::Hypothesis,
(None, false, Some(line)) => Done::Line(line),
(None, false, None) => Done::Open,
_ => {
return Err(Error::InconsistentSession {
reason: "a node is more than one of a rule's, a hypothesis and a line's",
});
}
};
Ok(Goal {
sequent: sequent(&node.sequent)?,
done,
premises: node.premises.clone(),
scope: node.scope,
opened: node.opened.unwrap_or(node.scope),
line: node.line,
})
})
.collect::<Result<Vec<_>, Error>>()?;
crate::rules::Interactive::from_parts(calculus, terms, scopes, nodes, form.history, limits)
}