Skip to main content

inference_engine/reasoning/literal_typing/
cursor.rs

1use super::{
2    LiteralOccurrence, LiteralOccurrenceCursor, LiteralOccurrenceRead, LiteralReader, LiteralRole,
3};
4use crate::{
5    entailment::EntailmentTerms,
6    reasoning::{
7        OccurrenceError, OccurrenceLimits, Rdf12OccurrenceCursor, TermOccurrence, TripleCursor,
8    },
9};
10use std::{error::Error, fmt, future::Future};
11
12/// Asynchronous access to one exact literal's metadata and streamed payload.
13///
14/// Reuse the immutable identity/structural accessor used by occurrence traversal.
15/// Reader payloads may borrow it or use independent backend handles; never clone
16/// a whole lexical form or hydrate all literals. Preserve exact language/direction
17/// identity and reject unsupported term extensions at the admission boundary.
18pub trait LiteralTermAccess: EntailmentTerms {
19    /// Reader may borrow metadata/payload handles for the immutable accessor lifetime.
20    type Reader<'a>: LiteralReader<Error = Self::Error>
21    where
22        Self: 'a;
23    /// Return a reader for a literal and `None` only for a supported nonliteral.
24    /// Cache misses must load authoritative classification/metadata or fail;
25    /// they must never become `None`. Opening must not buffer the lexical value.
26    fn open_literal<'a>(
27        &'a self,
28        term: &Self::Term,
29    ) -> impl Future<Output = Result<Option<Self::Reader<'a>>, Self::Error>> + Send;
30}
31
32/// Failure to enumerate or open a selected literal; never successful EOF.
33#[derive(Debug)]
34pub enum LiteralCursorError<T, E> {
35    /// Custom cursor/backend selection failed.
36    Storage(E),
37    /// Native recursive occurrence traversal failed.
38    Traversal(OccurrenceError<E>),
39    /// Opening a known occurrence failed, retaining its exact structural context.
40    Open {
41        /// Actual term/root/parent/path/role whose literal access failed.
42        occurrence: TermOccurrence<T>,
43        /// Backend opening failure, before any lexical read.
44        error: E,
45    },
46}
47impl<T, E> From<E> for LiteralCursorError<T, E> {
48    fn from(error: E) -> Self {
49        Self::Storage(error)
50    }
51}
52impl<T, E: fmt::Display> fmt::Display for LiteralCursorError<T, E> {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            Self::Storage(error) => write!(f, "literal occurrence access failed: {error}"),
56            Self::Traversal(error) => error.fmt(f),
57            Self::Open { error, .. } => write!(f, "literal opening failed: {error}"),
58        }
59    }
60}
61impl<T: fmt::Debug, E: Error + 'static> Error for LiteralCursorError<T, E> {
62    fn source(&self) -> Option<&(dyn Error + 'static)> {
63        match self {
64            Self::Storage(error) | Self::Open { error, .. } => Some(error),
65            Self::Traversal(error) => Some(error),
66        }
67    }
68}
69
70/// Native bounded recursive literal selection, with readers borrowed from storage.
71///
72/// Walks actual selected term structure using `Rdf12OccurrenceCursor`, then opens
73/// supported literal readers one at a time. Repeated keys keep distinct paths;
74/// metadata datatype IRIs are never traversed as actual RDF terms. No input graph,
75/// dictionary or whole literal value is collected. Scratch writes must not change
76/// the selected immutable root/dictionary/payload view during this phase.
77pub struct Rdf12LiteralOccurrences<'a, A: LiteralTermAccess, C: TripleCursor> {
78    cursor: Rdf12OccurrenceCursor<'a, A, C>,
79    access: &'a A,
80}
81impl<'a, A, C> Rdf12LiteralOccurrences<'a, A, C>
82where
83    A: LiteralTermAccess,
84    C: TripleCursor<Term = A::Term, Error = A::Error>,
85{
86    /// Select one immutable source/target scope and explicit traversal budgets.
87    /// Retain snapshot/source-graph provenance alongside emitted root/path records.
88    pub fn new(roots: C, access: &'a A, role: LiteralRole, limits: OccurrenceLimits) -> Self {
89        Self {
90            cursor: Rdf12OccurrenceCursor::new(roots, access, role, limits),
91            access,
92        }
93    }
94}
95impl<'a, A, C> LiteralOccurrenceCursor for Rdf12LiteralOccurrences<'a, A, C>
96where
97    A: LiteralTermAccess,
98    C: TripleCursor<Term = A::Term, Error = A::Error>,
99{
100    type Term = A::Term;
101    type Error = A::Error;
102    type Reader = A::Reader<'a>;
103    async fn next(&mut self) -> LiteralOccurrenceRead<Self::Term, Self::Reader, Self::Error> {
104        loop {
105            let Some(appearance) = self
106                .cursor
107                .next()
108                .await
109                .map_err(LiteralCursorError::Traversal)?
110            else {
111                return Ok(None);
112            };
113            let reader = self
114                .access
115                .open_literal(&appearance.term)
116                .await
117                .map_err(|error| LiteralCursorError::Open {
118                    occurrence: appearance.clone(),
119                    error,
120                })?;
121            let Some(reader) = reader else {
122                continue;
123            };
124            return Ok(Some((
125                LiteralOccurrence {
126                    literal: appearance.term,
127                    root: appearance.root,
128                    role: appearance.role,
129                    path: appearance.path,
130                },
131                reader,
132            )));
133        }
134    }
135}