use std::fmt;
use super::atom::Atom;
use super::symbols::{ConstantSymbol, VariableSymbol};
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "super::serde_input::TermInput")]
pub enum Term {
Variable(VariableSymbol),
Constant(ConstantSymbol),
TripleTerm(Box<Atom>),
Skolem {
name: ConstantSymbol,
args: Vec<Term>,
},
}
impl Term {
#[must_use]
pub fn variables(&self) -> std::collections::BTreeSet<VariableSymbol> {
let mut variables = std::collections::BTreeSet::new();
self.collect_variables(&mut variables);
variables
}
pub fn visit_variables<'a>(&'a self, visitor: &mut impl FnMut(&'a VariableSymbol)) {
match self {
Self::Variable(variable) => visitor(variable),
Self::Constant(_) => {}
Self::TripleTerm(atom) => atom.visit_variables(visitor),
Self::Skolem { args, .. } => {
for term in args {
term.visit_variables(visitor);
}
}
}
}
pub(super) fn collect_variables(&self, out: &mut std::collections::BTreeSet<VariableSymbol>) {
self.visit_variables(&mut |variable| {
out.insert(variable.clone());
});
}
#[must_use]
pub(super) fn nesting_depth(&self) -> usize {
match self {
Self::Variable(_) | Self::Constant(_) | Self::Skolem { .. } => 0,
Self::TripleTerm(atom) => 1 + atom.nesting_depth(),
}
}
#[must_use]
pub fn is_skolem(&self) -> bool {
matches!(self, Self::Skolem { .. })
}
}
impl fmt::Display for Term {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Variable(var) => write!(f, "?{}", var.as_str()),
Self::Constant(c) => write!(f, "{}", c.as_str()),
Self::TripleTerm(atom) => {
if atom.terms.len() == 2 {
write!(
f,
"<< {} {} {} >>",
atom.terms[0],
atom.predicate.as_str(),
atom.terms[1],
)
} else {
write!(f, "<< {atom} >>")
}
}
Self::Skolem { name, args } => {
write!(f, "SKOLEM({}", name.as_str())?;
for arg in args {
write!(f, ", {arg}")?;
}
write!(f, ")")
}
}
}
}