use super::{
Evidence, Inference, Limit, LiteralRole, OccurrenceError, Rdf12OccurrenceCursor,
ReasoningError, ReasoningStore, TripleCursor, plan::OccurrenceClause,
};
use crate::entailment::EntailmentTerms;
use rdf_reasoning::Rdf12OccurrenceRuleId;
use serde::{Deserialize, Serialize};
use std::{error::Error, fmt, num::NonZeroU64};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OccurrenceTypingReport {
pub occurrences: u64,
pub inferred: u64,
pub deferred_triple_terms: u64,
}
#[derive(Debug)]
pub enum OccurrenceTypingError<E> {
RoleMismatch {
expected: LiteralRole,
actual: LiteralRole,
},
Traversal(OccurrenceError<E>),
Reasoning(ReasoningError<E>),
}
impl<E> From<ReasoningError<E>> for OccurrenceTypingError<E> {
fn from(error: ReasoningError<E>) -> Self {
Self::Reasoning(error)
}
}
impl<E: fmt::Display> fmt::Display for OccurrenceTypingError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RoleMismatch { expected, actual } => write!(
f,
"occurrence role mismatch: expected {expected:?}, got {actual:?}"
),
Self::Traversal(error) => error.fmt(f),
Self::Reasoning(error) => error.fmt(f),
}
}
}
impl<E: Error + 'static> Error for OccurrenceTypingError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Traversal(error) => Some(error),
Self::Reasoning(error) => Some(error),
_ => None,
}
}
}
pub struct Rdf12OccurrenceTyper {
inferred: NonZeroU64,
role: LiteralRole,
}
impl Rdf12OccurrenceTyper {
pub const fn new(inferred: NonZeroU64, role: LiteralRole) -> Self {
Self { inferred, role }
}
pub async fn run<S, A, C>(
&self,
store: &mut S,
cursor: &mut Rdf12OccurrenceCursor<'_, A, C>,
) -> Result<OccurrenceTypingReport, OccurrenceTypingError<S::Error>>
where
S: ReasoningStore,
A: EntailmentTerms<Term = S::Term, Error = S::Error>,
C: TripleCursor<Term = S::Term, Error = S::Error>,
{
if cursor.role() != self.role {
return Err(OccurrenceTypingError::RoleMismatch {
expected: self.role,
actual: cursor.role(),
});
}
Self::cancel(store)?;
let mut clauses = Vec::with_capacity(2);
for &id in Rdf12OccurrenceRuleId::ALL {
if self.role == LiteralRole::TargetContext && id == Rdf12OccurrenceRuleId::RdfD2 {
continue;
}
clauses.push(OccurrenceClause::compile(id, store).await?);
}
let mut report = OccurrenceTypingReport::default();
loop {
Self::cancel(store)?;
let next = cursor
.next()
.await
.map_err(OccurrenceTypingError::Traversal)?;
Self::cancel(store)?;
let Some(occurrence) = next else {
return Ok(report);
};
report.occurrences += 1;
for clause in &clauses {
let Some(bindings) = clause.bind(&occurrence) else {
continue;
};
let triple = clause
.head
.ground(&bindings)
.ok_or(ReasoningError::UnsupportedOccurrenceRule(clause.id))?;
if store
.contains(&triple)
.await
.map_err(ReasoningError::Storage)?
{
continue;
}
if self.role == LiteralRole::TargetContext && cursor.current_is_triple_term() {
report.deferred_triple_terms += 1;
continue;
}
Self::cancel(store)?;
if report.inferred == self.inferred.get() {
return Err(ReasoningError::LimitExceeded(Limit::Inferred).into());
}
if store
.insert_inferred(Inference {
triple,
evidence: Evidence::Occurrence {
rule: clause.id,
occurrence: occurrence.clone(),
},
})
.await
.map_err(ReasoningError::Storage)?
{
report.inferred += 1;
}
}
}
}
fn cancel<S: ReasoningStore>(store: &S) -> Result<(), ReasoningError<S::Error>> {
if store.is_cancelled() {
Err(ReasoningError::Cancelled)
} else {
Ok(())
}
}
}