chase-rs/src/chase/instance.rs

175 lines
4.5 KiB
Rust
Raw Normal View History

2026-03-09 09:59:10 +01:00
//! A database instance is a set of ground atoms (facts).
2026-03-13 10:20:52 +01:00
use std::collections::{HashMap, HashSet};
use std::error::Error;
2026-03-09 09:59:10 +01:00
use std::fmt;
use super::atom::Atom;
2026-03-13 10:20:52 +01:00
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstanceError {
NonGroundFact(Atom),
}
impl fmt::Display for InstanceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstanceError::NonGroundFact(atom) => {
write!(f, "facts must be ground atoms: {}", atom)
}
}
}
}
impl Error for InstanceError {}
2026-03-09 09:59:10 +01:00
/// A database instance containing ground atoms.
#[derive(Debug, Clone, Default)]
pub struct Instance {
2026-03-13 10:20:52 +01:00
facts_by_predicate: HashMap<String, HashSet<Atom>>,
len: usize,
2026-03-09 09:59:10 +01:00
}
impl Instance {
/// Create an empty instance.
pub fn new() -> Self {
Instance {
2026-03-13 10:20:52 +01:00
facts_by_predicate: HashMap::new(),
len: 0,
}
}
/// Try to add a fact to the instance. Returns true if the fact was new.
pub fn try_add(&mut self, fact: Atom) -> Result<bool, InstanceError> {
if !fact.is_ground() {
return Err(InstanceError::NonGroundFact(fact));
}
let bucket = self
.facts_by_predicate
.entry(fact.predicate.clone())
.or_default();
let inserted = bucket.insert(fact);
if inserted {
self.len += 1;
2026-03-09 09:59:10 +01:00
}
2026-03-13 10:20:52 +01:00
Ok(inserted)
2026-03-09 09:59:10 +01:00
}
/// Add a fact to the instance. Returns true if the fact was new.
2026-03-13 10:20:52 +01:00
///
/// Panics if the atom is not ground.
2026-03-09 09:59:10 +01:00
pub fn add(&mut self, fact: Atom) -> bool {
2026-03-13 10:20:52 +01:00
self.try_add(fact).expect("facts must be ground atoms")
2026-03-09 09:59:10 +01:00
}
/// Check if the instance contains a fact.
pub fn contains(&self, fact: &Atom) -> bool {
2026-03-13 10:20:52 +01:00
self.facts_by_predicate
.get(&fact.predicate)
.is_some_and(|facts| facts.contains(fact))
2026-03-09 09:59:10 +01:00
}
/// Get the number of facts.
pub fn len(&self) -> usize {
2026-03-13 10:20:52 +01:00
self.len
2026-03-09 09:59:10 +01:00
}
/// Check if the instance is empty.
pub fn is_empty(&self) -> bool {
2026-03-13 10:20:52 +01:00
self.len == 0
2026-03-09 09:59:10 +01:00
}
/// Iterate over all facts.
2026-03-09 11:22:38 +01:00
pub fn iter(&self) -> impl Iterator<Item = &Atom> {
2026-03-13 10:20:52 +01:00
self.facts_by_predicate
.values()
.flat_map(|facts| facts.iter())
2026-03-09 09:59:10 +01:00
}
/// Get all facts with a given predicate.
pub fn facts_for_predicate(&self, predicate: &str) -> Vec<&Atom> {
2026-03-13 10:20:52 +01:00
self.facts_by_predicate
.get(predicate)
.into_iter()
.flat_map(|facts| facts.iter())
2026-03-09 09:59:10 +01:00
.collect()
}
}
impl fmt::Display for Instance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Instance {{")?;
2026-03-13 10:20:52 +01:00
for fact in self.iter() {
2026-03-09 09:59:10 +01:00
writeln!(f, " {}", fact)?;
}
write!(f, "}}")
}
}
impl FromIterator<Atom> for Instance {
2026-03-09 11:22:38 +01:00
fn from_iter<T: IntoIterator<Item = Atom>>(iter: T) -> Self {
2026-03-09 09:59:10 +01:00
let mut instance = Instance::new();
for atom in iter {
instance.add(atom);
}
instance
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chase::term::Term;
#[test]
fn test_instance_operations() {
let mut instance = Instance::new();
let fact1 = Atom::new(
"Parent",
vec![Term::constant("alice"), Term::constant("bob")],
);
let fact2 = Atom::new(
"Parent",
vec![Term::constant("bob"), Term::constant("carol")],
);
assert!(instance.add(fact1.clone()));
assert!(instance.add(fact2.clone()));
assert!(!instance.add(fact1.clone())); // Duplicate
assert_eq!(instance.len(), 2);
assert!(instance.contains(&fact1));
}
#[test]
fn test_facts_for_predicate() {
let instance: Instance = vec![
Atom::new(
"Parent",
vec![Term::constant("alice"), Term::constant("bob")],
),
2026-03-09 11:22:38 +01:00
Atom::new("Person", vec![Term::constant("alice")]),
2026-03-09 09:59:10 +01:00
]
2026-03-09 11:22:38 +01:00
.into_iter()
.collect();
2026-03-09 09:59:10 +01:00
assert_eq!(instance.facts_for_predicate("Parent").len(), 1);
assert_eq!(instance.facts_for_predicate("Person").len(), 1);
assert_eq!(instance.facts_for_predicate("Other").len(), 0);
}
2026-03-13 10:20:52 +01:00
#[test]
fn test_try_add_rejects_non_ground_facts() {
let mut instance = Instance::new();
let fact = Atom::new("Parent", vec![Term::var("X"), Term::constant("bob")]);
let error = instance.try_add(fact).unwrap_err();
assert!(matches!(error, InstanceError::NonGroundFact(_)));
assert!(instance.is_empty());
}
2026-03-09 09:59:10 +01:00
}