use super::{
LiteralOccurrence, LiteralOccurrenceCursor, LiteralOccurrenceRead, LiteralReader, LiteralRole,
};
use crate::{
entailment::EntailmentTerms,
reasoning::{
OccurrenceError, OccurrenceLimits, Rdf12OccurrenceCursor, TermOccurrence, TripleCursor,
},
};
use std::{error::Error, fmt, future::Future};
pub trait LiteralTermAccess: EntailmentTerms {
type Reader<'a>: LiteralReader<Error = Self::Error>
where
Self: 'a;
fn open_literal<'a>(
&'a self,
term: &Self::Term,
) -> impl Future<Output = Result<Option<Self::Reader<'a>>, Self::Error>> + Send;
}
#[derive(Debug)]
pub enum LiteralCursorError<T, E> {
Storage(E),
Traversal(OccurrenceError<E>),
Open {
occurrence: TermOccurrence<T>,
error: E,
},
}
impl<T, E> From<E> for LiteralCursorError<T, E> {
fn from(error: E) -> Self {
Self::Storage(error)
}
}
impl<T, E: fmt::Display> fmt::Display for LiteralCursorError<T, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Storage(error) => write!(f, "literal occurrence access failed: {error}"),
Self::Traversal(error) => error.fmt(f),
Self::Open { error, .. } => write!(f, "literal opening failed: {error}"),
}
}
}
impl<T: fmt::Debug, E: Error + 'static> Error for LiteralCursorError<T, E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Storage(error) | Self::Open { error, .. } => Some(error),
Self::Traversal(error) => Some(error),
}
}
}
pub struct Rdf12LiteralOccurrences<'a, A: LiteralTermAccess, C: TripleCursor> {
cursor: Rdf12OccurrenceCursor<'a, A, C>,
access: &'a A,
}
impl<'a, A, C> Rdf12LiteralOccurrences<'a, A, C>
where
A: LiteralTermAccess,
C: TripleCursor<Term = A::Term, Error = A::Error>,
{
pub fn new(roots: C, access: &'a A, role: LiteralRole, limits: OccurrenceLimits) -> Self {
Self {
cursor: Rdf12OccurrenceCursor::new(roots, access, role, limits),
access,
}
}
}
impl<'a, A, C> LiteralOccurrenceCursor for Rdf12LiteralOccurrences<'a, A, C>
where
A: LiteralTermAccess,
C: TripleCursor<Term = A::Term, Error = A::Error>,
{
type Term = A::Term;
type Error = A::Error;
type Reader = A::Reader<'a>;
async fn next(&mut self) -> LiteralOccurrenceRead<Self::Term, Self::Reader, Self::Error> {
loop {
let Some(appearance) = self
.cursor
.next()
.await
.map_err(LiteralCursorError::Traversal)?
else {
return Ok(None);
};
let reader = self
.access
.open_literal(&appearance.term)
.await
.map_err(|error| LiteralCursorError::Open {
occurrence: appearance.clone(),
error,
})?;
let Some(reader) = reader else {
continue;
};
return Ok(Some((
LiteralOccurrence {
literal: appearance.term,
root: appearance.root,
role: appearance.role,
path: appearance.path,
},
reader,
)));
}
}
}