use std::cmp::Ordering;
use crate::ATermIntRef;
use crate::ATermRef;
use crate::Symb;
use crate::Term;
use crate::is_int_term;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct StructuralOrd<T>(pub T);
impl<'a, 'b, T: Term<'a, 'b> + Eq> PartialOrd for StructuralOrd<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a, 'b, T: Term<'a, 'b> + Eq> Ord for StructuralOrd<T> {
fn cmp(&self, other: &Self) -> Ordering {
structural_cmp(&self.0.borrow(), &other.0.borrow())
}
}
pub fn structural_cmp(lhs: &ATermRef<'_>, rhs: &ATermRef<'_>) -> Ordering {
let mut lhs = lhs.copy();
let mut rhs = rhs.copy();
while lhs != rhs {
match (is_int_term(&lhs), is_int_term(&rhs)) {
(true, true) => return ATermIntRef::from(lhs).value().cmp(&ATermIntRef::from(rhs).value()),
(true, false) => return Ordering::Less,
(false, true) => return Ordering::Greater,
(false, false) => {}
}
let lhs_symbol = lhs.get_head_symbol();
let rhs_symbol = rhs.get_head_symbol();
if lhs_symbol != rhs_symbol {
return lhs_symbol
.name()
.cmp(rhs_symbol.name())
.then_with(|| lhs_symbol.arity().cmp(&rhs_symbol.arity()));
}
let arity = lhs_symbol.arity();
debug_assert!(arity > 0, "distinct terms with the same symbol differ in an argument");
for index in 0..arity - 1 {
let ordering = structural_cmp(&lhs.arg(index), &rhs.arg(index));
if ordering != Ordering::Equal {
return ordering;
}
}
let last = arity - 1;
(lhs, rhs) = (lhs.arg(last), rhs.arg(last));
}
Ordering::Equal
}
#[cfg(test)]
mod tests {
use merc_utilities::test_logger;
use crate::ATerm;
use crate::ATermInt;
use crate::StructuralOrd;
fn term(text: &str) -> ATerm {
ATerm::from_string(text).unwrap()
}
#[test]
fn test_structural_ord() {
test_logger();
let ordered = [
"a",
"b",
"f(a)",
"f(b)",
"f(a, b)",
"f(a, g(a))",
"f(a, g(b))",
"f(b, a)",
"g(a)",
];
for (i, lhs) in ordered.iter().enumerate() {
for (j, rhs) in ordered.iter().enumerate() {
assert_eq!(
StructuralOrd(term(lhs)).cmp(&StructuralOrd(term(rhs))),
i.cmp(&j),
"comparing {lhs} and {rhs}"
);
}
}
}
#[test]
fn test_structural_ord_int() {
test_logger();
assert!(StructuralOrd(ATermInt::new(2)) < StructuralOrd(ATermInt::new(10)));
assert!(StructuralOrd(ATerm::from(ATermInt::new(10))) < StructuralOrd(term("a")));
}
}