use super::{
Evidence, ExecutionProfile, Inference, Limit, Premises, ReasoningError, ReasoningStore,
RunLimits, RunReport, TripleCursor, TripleSource,
plan::{Bindings, Body, Clause},
};
pub struct Reasoner {
profile: ExecutionProfile,
limits: RunLimits,
}
impl Reasoner {
pub const fn new(profile: ExecutionProfile, limits: RunLimits) -> Self {
Self { profile, limits }
}
pub const fn profile(&self) -> ExecutionProfile {
self.profile
}
pub const fn implementation_version(&self) -> &'static str {
env!("CARGO_PKG_VERSION")
}
pub const fn rule_catalogue(&self) -> &'static str {
env!("INFERENCE_ENGINE_RULE_CATALOGUE")
}
pub async fn run<S: ReasoningStore>(
&self,
store: &mut S,
) -> Result<RunReport, ReasoningError<S::Error>> {
Self::check_cancelled(store)?;
let mut clauses = Vec::with_capacity(self.profile.rules().len());
for &rule in self.profile.rules() {
clauses.push(Clause::compile(rule, store).await?);
}
let mut report = RunReport::default();
loop {
Self::check_cancelled(store)?;
if report.rounds == self.limits.rounds.get() {
return Err(ReasoningError::LimitExceeded(Limit::Rounds));
}
report.rounds += 1;
let snapshot = store.snapshot().await.map_err(ReasoningError::Storage)?;
let before = report.inferred;
for clause in &clauses {
self.evaluate(clause, &snapshot, store, &mut report).await?;
}
Self::check_cancelled(store)?;
if report.inferred == before {
return Ok(report);
}
}
}
async fn evaluate<S: ReasoningStore>(
&self,
clause: &Clause<S::Term>,
source: &S::Snapshot,
store: &mut S,
report: &mut RunReport,
) -> Result<(), ReasoningError<S::Error>> {
let empty = std::array::from_fn(|_| None);
let mut outer = source
.scan(clause.body.first().probe(&empty))
.await
.map_err(ReasoningError::Storage)?;
while let Some(first) = self.next(&mut outer, store, report).await? {
let Some(bindings) = clause.body.first().bind(&first, empty.clone()) else {
continue;
};
let Body::Two([_, second_pattern]) = &clause.body else {
self.emit(clause, &bindings, Premises::One(first), store, report)
.await?;
continue;
};
let mut inner = source
.scan(second_pattern.probe(&bindings))
.await
.map_err(ReasoningError::Storage)?;
while let Some(second) = self.next(&mut inner, store, report).await? {
let Some(bindings) = second_pattern.bind(&second, bindings.clone()) else {
continue;
};
self.emit(
clause,
&bindings,
Premises::Two([first.clone(), second]),
store,
report,
)
.await?;
}
}
Ok(())
}
async fn emit<S: ReasoningStore>(
&self,
clause: &Clause<S::Term>,
bindings: &Bindings<S::Term>,
premises: Premises<S::Term>,
store: &mut S,
report: &mut RunReport,
) -> Result<(), ReasoningError<S::Error>> {
let triple = clause
.head
.ground(bindings)
.ok_or(ReasoningError::UnsupportedRule(clause.id))?;
if store
.contains(&triple)
.await
.map_err(ReasoningError::Storage)?
{
return Ok(());
}
Self::check_cancelled(store)?;
if report.inferred == self.limits.inferred.get() {
return Err(ReasoningError::LimitExceeded(Limit::Inferred));
}
let inference = Inference {
triple,
evidence: Evidence::Rule {
rule: clause.id,
premises,
},
};
if store
.insert_inferred(inference)
.await
.map_err(ReasoningError::Storage)?
{
report.inferred += 1;
}
Ok(())
}
async fn next<S: ReasoningStore, C: TripleCursor<Term = S::Term, Error = S::Error>>(
&self,
cursor: &mut C,
store: &mut S,
report: &mut RunReport,
) -> Result<Option<[S::Term; 3]>, ReasoningError<S::Error>> {
Self::check_cancelled(store)?;
let tuple = cursor.next().await.map_err(ReasoningError::Storage)?;
if tuple.is_some() {
if report.matches == self.limits.matches.get() {
return Err(ReasoningError::LimitExceeded(Limit::Matches));
}
report.matches += 1;
crate::cooperative::checkpoint(report.matches).await;
Self::check_cancelled(store)?;
}
Ok(tuple)
}
fn check_cancelled<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
if store.is_cancelled() {
Err(ReasoningError::Cancelled)
} else {
Ok(())
}
}
}