use super::{LiteralRole, TripleCursor};
use crate::entailment::EntailmentTerms;
use serde::{Deserialize, Serialize};
use std::{
error::Error,
fmt,
num::{NonZeroU32, NonZeroU64},
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum TermPosition {
Subject,
Predicate,
Object,
}
impl TermPosition {
fn at(index: u8) -> Self {
match index {
0 => Self::Subject,
1 => Self::Predicate,
2 => Self::Object,
_ => unreachable!("triple position"),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OccurrencePath {
root: TermPosition,
nested: Vec<TermPosition>,
}
impl OccurrencePath {
pub const fn root(position: TermPosition) -> Self {
Self {
root: position,
nested: Vec::new(),
}
}
pub fn positions(&self) -> impl DoubleEndedIterator<Item = &TermPosition> {
std::iter::once(&self.root).chain(self.nested.iter())
}
fn is_predicate(&self) -> bool {
self.nested.last().unwrap_or(&self.root) == &TermPosition::Predicate
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TermOccurrence<T> {
pub term: T,
pub root: [T; 3],
pub parent: [T; 3],
pub role: LiteralRole,
pub path: OccurrencePath,
}
impl<T> TermOccurrence<T> {
pub fn is_predicate(&self) -> bool {
self.path.is_predicate()
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OccurrenceLimits {
depth: NonZeroU32,
occurrences: NonZeroU64,
steps: NonZeroU64,
}
impl OccurrenceLimits {
pub const fn new(depth: NonZeroU32, occurrences: NonZeroU64, steps: NonZeroU64) -> Self {
Self {
depth,
occurrences,
steps,
}
}
}
#[derive(Debug)]
pub enum OccurrenceError<E> {
Storage(E),
Cancelled,
DepthLimit,
OccurrenceLimit,
StepLimit,
}
impl<E: fmt::Display> fmt::Display for OccurrenceError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Storage(error) => write!(f, "occurrence access failed: {error}"),
Self::Cancelled => f.write_str("occurrence traversal cancelled"),
Self::DepthLimit => f.write_str("occurrence path depth limit exceeded"),
Self::OccurrenceLimit => f.write_str("occurrence count limit exceeded"),
Self::StepLimit => f.write_str("occurrence work limit exceeded"),
}
}
}
impl<E: Error + 'static> Error for OccurrenceError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Storage(error) => Some(error),
_ => None,
}
}
}
struct Frame<T> {
triple: [T; 3],
next: u8,
}
pub struct Rdf12OccurrenceCursor<'a, A: EntailmentTerms, C: TripleCursor> {
roots: C,
terms: &'a A,
role: LiteralRole,
limits: OccurrenceLimits,
root: Option<[A::Term; 3]>,
frames: Vec<Frame<A::Term>>,
occurrences: u64,
steps: u64,
finished: bool,
current_triple_term: bool,
}
impl<'a, A, C> Rdf12OccurrenceCursor<'a, A, C>
where
A: EntailmentTerms,
C: TripleCursor<Term = A::Term, Error = A::Error>,
{
pub fn new(roots: C, terms: &'a A, role: LiteralRole, limits: OccurrenceLimits) -> Self {
Self {
roots,
terms,
role,
limits,
root: None,
frames: Vec::new(),
occurrences: 0,
steps: 0,
finished: false,
current_triple_term: false,
}
}
pub const fn role(&self) -> LiteralRole {
self.role
}
pub(crate) const fn current_is_triple_term(&self) -> bool {
self.current_triple_term
}
pub async fn next(
&mut self,
) -> Result<Option<TermOccurrence<A::Term>>, OccurrenceError<A::Error>> {
self.cancel()?;
if self.finished {
return Ok(None);
}
loop {
if self.frames.is_empty() {
self.step().await?;
let Some(root) = self.roots.next().await.map_err(OccurrenceError::Storage)? else {
self.cancel()?;
self.finished = true;
return Ok(None);
};
self.root = Some(root.clone());
self.frames.push(Frame {
triple: root,
next: 0,
});
}
let frame = self.frames.last_mut().expect("root frame exists");
if frame.next == 3 {
self.frames.pop();
continue;
}
let parent = frame.triple.clone();
let term = frame.triple[usize::from(frame.next)].clone();
frame.next += 1;
if self.occurrences == self.limits.occurrences.get() {
return Err(OccurrenceError::OccurrenceLimit);
}
self.step().await?;
let nested = self
.terms
.triple_term(&term)
.await
.map_err(OccurrenceError::Storage)?;
self.cancel()?;
let path = OccurrencePath {
root: TermPosition::at(self.frames[0].next - 1),
nested: self
.frames
.iter()
.skip(1)
.map(|frame| TermPosition::at(frame.next - 1))
.collect(),
};
self.current_triple_term = nested.is_some();
if let Some(triple) = nested {
if self.frames.len() == self.limits.depth.get() as usize {
return Err(OccurrenceError::DepthLimit);
}
self.frames.push(Frame { triple, next: 0 });
}
self.occurrences += 1;
return Ok(Some(TermOccurrence {
term,
parent,
root: self.root.clone().expect("selected root exists"),
role: self.role,
path,
}));
}
}
async fn step(&mut self) -> Result<(), OccurrenceError<A::Error>> {
self.cancel()?;
if self.steps == self.limits.steps.get() {
return Err(OccurrenceError::StepLimit);
}
self.steps += 1;
crate::cooperative::checkpoint(self.steps).await;
self.cancel()
}
fn cancel(&self) -> Result<(), OccurrenceError<A::Error>> {
if self.terms.is_cancelled() {
Err(OccurrenceError::Cancelled)
} else {
Ok(())
}
}
}