inference-engine 0.1.0-alpha.8

Native Rust inference foundation with checked RDF rule-profile compilation
Documentation
use super::{SchemaFreeEntailment, SchemaFreeError, SchemaFreeRestriction};
use crate::{
    entailment::IriTermAccess,
    reasoning::{LiteralRole, Rdf12OccurrenceCursor, TermOccurrence, TermPosition, TripleSource},
};

pub(super) enum Admission<T> {
    Accepted {
        count: u64,
        standard_constraint: Option<TermOccurrence<T>>,
    },
    Unsupported {
        restriction: SchemaFreeRestriction,
        occurrence: TermOccurrence<T>,
    },
}
impl SchemaFreeEntailment {
    pub(super) async fn admit<S, A>(
        &self,
        graph: &S,
        access: &A,
        role: LiteralRole,
    ) -> Result<Admission<S::Term>, SchemaFreeError<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| SchemaFreeError::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;
        while let Some(occurrence) = cursor.next().await.map_err(SchemaFreeError::Traversal)? {
            count = count
                .checked_add(1)
                .ok_or(SchemaFreeError::CounterOverflow)?;
            let restriction = self
                .restriction(access, &occurrence, cursor.current_is_triple_term())
                .await?;
            Self::cancelled(access)?;
            if let Some(restriction) = restriction {
                if restriction == SchemaFreeRestriction::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,
        })
    }
    async fn restriction<A: IriTermAccess>(
        &self,
        access: &A,
        occurrence: &TermOccurrence<A::Term>,
        is_triple_term: bool,
    ) -> Result<Option<SchemaFreeRestriction>, SchemaFreeError<A::Term, A::Error>> {
        if is_triple_term {
            return Ok(
                (occurrence.path.positions().last() != Some(&TermPosition::Object))
                    .then_some(SchemaFreeRestriction::GeneralizedPosition),
            );
        }
        let iri = access
            .iri(&occurrence.term, self.limits.iri_bytes)
            .await
            .map_err(|error| SchemaFreeError::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(SchemaFreeError::IriLimit {
                    occurrence: occurrence.clone(),
                });
            }
            return Ok(if !is_reserved_iri(iri) {
                None
            } else if occurrence.role == LiteralRole::Source {
                Some(SchemaFreeRestriction::ReservedSourceVocabulary)
            } else if occurrence.path.positions().eq([&TermPosition::Predicate]) {
                Some(SchemaFreeRestriction::UnresolvedStandardConstraint)
            } else {
                None
            });
        }
        let blank =
            access
                .is_blank(&occurrence.term)
                .await
                .map_err(|error| SchemaFreeError::Metadata {
                    occurrence: occurrence.clone(),
                    error,
                })?;
        Self::cancelled(access)?;
        Ok(if !blank {
            Some(SchemaFreeRestriction::Literal)
        } else if occurrence.is_predicate() {
            Some(SchemaFreeRestriction::GeneralizedPosition)
        } else {
            None
        })
    }
}

pub(super) fn is_reserved_iri(iri: &str) -> bool {
    // bounded: exactly the three reserved namespace prefixes in the admission proof.
    [
        "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
        "http://www.w3.org/2000/01/rdf-schema#",
        "http://www.w3.org/2001/XMLSchema#",
    ]
    .iter()
    .any(|prefix| iri.starts_with(prefix))
}