inference-engine 0.1.0-alpha.14

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::evidence::{Inspection, IriKind, TargetEvidence, is_reserved_iri};
use super::{Rdfs12FragmentEntailment, Rdfs12FragmentError, Rdfs12FragmentRestriction};
use crate::{
    entailment::IriTermAccess,
    reasoning::{LiteralRole, Rdf12OccurrenceCursor, TermOccurrence, TermPosition, TripleSource},
};

pub(super) enum Admission<T> {
    Accepted {
        count: u64,
        standard_constraint: Option<TermOccurrence<T>>,
        evidence: TargetEvidence<T>,
    },
    Unsupported {
        restriction: Rdfs12FragmentRestriction,
        occurrence: TermOccurrence<T>,
    },
}
impl Rdfs12FragmentEntailment {
    pub(super) async fn admit<S, A>(
        &self,
        graph: &S,
        access: &A,
        role: LiteralRole,
    ) -> Result<Admission<S::Term>, Rdfs12FragmentError<S::Term, S::Error>>
    where
        S: TripleSource,
        A: IriTermAccess<Term = S::Term, Error = S::Error>,
    {
        Self::cancelled(access)?;
        let roots = graph
            .scan([None, None, None])
            .await
            .map_err(|error| Rdfs12FragmentError::Graph { role, error })?;
        Self::cancelled(access)?;
        let mut cursor = Rdf12OccurrenceCursor::new(roots, access, role, self.limits.traversal);
        let mut count = 0_u64;
        // bounded: retain only the first unresolved standard predicate appearance.
        let mut standard_constraint = None;
        let mut evidence = TargetEvidence::new();
        // bounded: three root IRI classifications and the first reserved appearance.
        let mut source_root = [None; 3];
        let mut reserved = None;
        while let Some(occurrence) = cursor
            .next()
            .await
            .map_err(Rdfs12FragmentError::Traversal)?
        {
            count = count
                .checked_add(1)
                .ok_or(Rdfs12FragmentError::CounterOverflow)?;
            let inspected = self
                .inspect_term(access, &occurrence, cursor.current_is_triple_term())
                .await?;
            Self::cancelled(access)?;
            evidence.observe(&occurrence, inspected.iri);
            let root_position = {
                let mut path = occurrence.path.positions();
                let first = *path.next().expect("nonempty occurrence path");
                path.next().is_none().then_some(first)
            };
            if role == LiteralRole::Source
                && let Some(position) = root_position
            {
                let index = match position {
                    TermPosition::Subject => 0,
                    TermPosition::Predicate => 1,
                    TermPosition::Object => 2,
                };
                if index == 0 {
                    source_root = [None; 3];
                    reserved = None;
                }
                source_root[index] = inspected.iri;
                if inspected.restriction == Some(Rdfs12FragmentRestriction::UnsupportedSourceSchema)
                    && reserved.is_none()
                {
                    reserved = Some(occurrence.clone());
                }
                if index == 2 {
                    let allowed = matches!(
                        source_root,
                        [
                            Some(IriKind::Ordinary),
                            Some(IriKind::Type),
                            Some(IriKind::Property)
                        ] | [
                            Some(IriKind::Resource),
                            Some(IriKind::SubClass),
                            Some(IriKind::Class)
                        ] | [
                            Some(IriKind::Proposition),
                            Some(IriKind::SubClass),
                            Some(IriKind::Property)
                        ]
                    );
                    if !allowed && let Some(occurrence) = reserved.take() {
                        return Ok(Admission::Unsupported {
                            restriction: Rdfs12FragmentRestriction::UnsupportedSourceSchema,
                            occurrence,
                        });
                    }
                }
                if inspected.restriction == Some(Rdfs12FragmentRestriction::UnsupportedSourceSchema)
                {
                    continue;
                }
            }
            if let Some(restriction) = inspected.restriction {
                if restriction == Rdfs12FragmentRestriction::UnresolvedStandardConstraint {
                    if standard_constraint.is_none() {
                        standard_constraint = Some(occurrence);
                    }
                    continue;
                }
                return Ok(Admission::Unsupported {
                    restriction,
                    occurrence,
                });
            }
        }
        Self::cancelled(access)?;
        Ok(Admission::Accepted {
            count,
            standard_constraint,
            evidence,
        })
    }
    async fn inspect_term<A: IriTermAccess>(
        &self,
        access: &A,
        occurrence: &TermOccurrence<A::Term>,
        is_triple_term: bool,
    ) -> Result<Inspection, Rdfs12FragmentError<A::Term, A::Error>> {
        if is_triple_term {
            return Ok(Inspection::non_iri(
                (occurrence.path.positions().last() != Some(&TermPosition::Object))
                    .then_some(Rdfs12FragmentRestriction::GeneralizedPosition),
            ));
        }
        let iri = access
            .iri(&occurrence.term, self.limits.iri_bytes)
            .await
            .map_err(|error| Rdfs12FragmentError::Metadata {
                occurrence: occurrence.clone(),
                error,
            })?;
        Self::cancelled(access)?;
        if let Some(iri) = iri {
            let iri = iri.as_ref();
            if iri.len() > self.limits.iri_bytes.get() as usize {
                return Err(Rdfs12FragmentError::IriLimit {
                    occurrence: occurrence.clone(),
                });
            }
            let restriction = if !is_reserved_iri(iri) {
                None
            } else if occurrence.role == LiteralRole::Source
                && occurrence.path.positions().eq([&TermPosition::Predicate])
            {
                Some(Rdfs12FragmentRestriction::UnsupportedSourceSchema)
            } else if occurrence.path.positions().eq([&TermPosition::Predicate]) {
                Some(Rdfs12FragmentRestriction::UnresolvedStandardConstraint)
            } else {
                None
            };
            return Ok(Inspection {
                restriction,
                iri: Some(IriKind::inspect(iri)),
            });
        }
        let blank = access.is_blank(&occurrence.term).await.map_err(|error| {
            Rdfs12FragmentError::Metadata {
                occurrence: occurrence.clone(),
                error,
            }
        })?;
        Self::cancelled(access)?;
        Ok(Inspection::non_iri(if !blank {
            Some(Rdfs12FragmentRestriction::Literal)
        } else if occurrence.is_predicate() {
            Some(Rdfs12FragmentRestriction::GeneralizedPosition)
        } else {
            None
        }))
    }
}