inference_engine/reasoning/
occurrence.rs1use super::{LiteralRole, TripleCursor};
2use crate::entailment::EntailmentTerms;
3use serde::{Deserialize, Serialize};
4use std::{
5 error::Error,
6 fmt,
7 num::{NonZeroU32, NonZeroU64},
8};
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
12pub enum TermPosition {
13 Subject,
15 Predicate,
17 Object,
19}
20impl TermPosition {
21 fn at(index: u8) -> Self {
22 match index {
23 0 => Self::Subject,
24 1 => Self::Predicate,
25 2 => Self::Object,
26 _ => unreachable!("triple position"),
27 }
28 }
29}
30
31#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct OccurrencePath {
35 root: TermPosition,
36 nested: Vec<TermPosition>,
37}
38impl OccurrencePath {
39 pub const fn root(position: TermPosition) -> Self {
41 Self {
42 root: position,
43 nested: Vec::new(),
44 }
45 }
46 pub fn positions(&self) -> impl DoubleEndedIterator<Item = &TermPosition> {
48 std::iter::once(&self.root).chain(self.nested.iter())
49 }
50 fn is_predicate(&self) -> bool {
51 self.nested.last().unwrap_or(&self.root) == &TermPosition::Predicate
52 }
53}
54
55#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct TermOccurrence<T> {
59 pub term: T,
61 pub root: [T; 3],
63 pub parent: [T; 3],
65 pub role: LiteralRole,
67 pub path: OccurrencePath,
69}
70impl<T> TermOccurrence<T> {
71 pub fn is_predicate(&self) -> bool {
73 self.path.is_predicate()
74 }
75}
76
77#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct OccurrenceLimits {
81 depth: NonZeroU32,
82 occurrences: NonZeroU64,
83 steps: NonZeroU64,
84}
85impl OccurrenceLimits {
86 pub const fn new(depth: NonZeroU32, occurrences: NonZeroU64, steps: NonZeroU64) -> Self {
89 Self {
90 depth,
91 occurrences,
92 steps,
93 }
94 }
95}
96
97#[derive(Debug)]
99pub enum OccurrenceError<E> {
100 Storage(E),
102 Cancelled,
104 DepthLimit,
106 OccurrenceLimit,
108 StepLimit,
110}
111impl<E: fmt::Display> fmt::Display for OccurrenceError<E> {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 match self {
114 Self::Storage(error) => write!(f, "occurrence access failed: {error}"),
115 Self::Cancelled => f.write_str("occurrence traversal cancelled"),
116 Self::DepthLimit => f.write_str("occurrence path depth limit exceeded"),
117 Self::OccurrenceLimit => f.write_str("occurrence count limit exceeded"),
118 Self::StepLimit => f.write_str("occurrence work limit exceeded"),
119 }
120 }
121}
122impl<E: Error + 'static> Error for OccurrenceError<E> {
123 fn source(&self) -> Option<&(dyn Error + 'static)> {
124 match self {
125 Self::Storage(error) => Some(error),
126 _ => None,
127 }
128 }
129}
130
131struct Frame<T> {
132 triple: [T; 3],
133 next: u8,
134}
135
136pub struct Rdf12OccurrenceCursor<'a, A: EntailmentTerms, C: TripleCursor> {
149 roots: C,
150 terms: &'a A,
151 role: LiteralRole,
152 limits: OccurrenceLimits,
153 root: Option<[A::Term; 3]>,
154 frames: Vec<Frame<A::Term>>,
156 occurrences: u64,
157 steps: u64,
158 finished: bool,
159 current_triple_term: bool,
160}
161impl<'a, A, C> Rdf12OccurrenceCursor<'a, A, C>
162where
163 A: EntailmentTerms,
164 C: TripleCursor<Term = A::Term, Error = A::Error>,
165{
166 pub fn new(roots: C, terms: &'a A, role: LiteralRole, limits: OccurrenceLimits) -> Self {
169 Self {
170 roots,
171 terms,
172 role,
173 limits,
174 root: None,
175 frames: Vec::new(),
176 occurrences: 0,
177 steps: 0,
178 finished: false,
179 current_triple_term: false,
180 }
181 }
182 pub const fn role(&self) -> LiteralRole {
184 self.role
185 }
186
187 pub(super) const fn current_is_triple_term(&self) -> bool {
190 self.current_triple_term
191 }
192
193 pub async fn next(
199 &mut self,
200 ) -> Result<Option<TermOccurrence<A::Term>>, OccurrenceError<A::Error>> {
201 self.cancel()?;
202 if self.finished {
203 return Ok(None);
204 }
205 loop {
206 if self.frames.is_empty() {
207 self.step().await?;
208 let Some(root) = self.roots.next().await.map_err(OccurrenceError::Storage)? else {
209 self.cancel()?;
210 self.finished = true;
211 return Ok(None);
212 };
213 self.root = Some(root.clone());
214 self.frames.push(Frame {
215 triple: root,
216 next: 0,
217 });
218 }
219 let frame = self.frames.last_mut().expect("root frame exists");
220 if frame.next == 3 {
221 self.frames.pop();
222 continue;
223 }
224 let parent = frame.triple.clone();
225 let term = frame.triple[usize::from(frame.next)].clone();
226 frame.next += 1;
227 if self.occurrences == self.limits.occurrences.get() {
228 return Err(OccurrenceError::OccurrenceLimit);
229 }
230 self.step().await?;
231 let nested = self
232 .terms
233 .triple_term(&term)
234 .await
235 .map_err(OccurrenceError::Storage)?;
236 self.cancel()?;
237 let path = OccurrencePath {
239 root: TermPosition::at(self.frames[0].next - 1),
240 nested: self
241 .frames
242 .iter()
243 .skip(1)
244 .map(|frame| TermPosition::at(frame.next - 1))
245 .collect(),
246 };
247 self.current_triple_term = nested.is_some();
248 if let Some(triple) = nested {
249 if self.frames.len() == self.limits.depth.get() as usize {
250 return Err(OccurrenceError::DepthLimit);
251 }
252 self.frames.push(Frame { triple, next: 0 });
253 }
254 self.occurrences += 1;
255 return Ok(Some(TermOccurrence {
256 term,
257 parent,
258 root: self.root.clone().expect("selected root exists"),
259 role: self.role,
260 path,
261 }));
262 }
263 }
264 async fn step(&mut self) -> Result<(), OccurrenceError<A::Error>> {
265 self.cancel()?;
266 if self.steps == self.limits.steps.get() {
267 return Err(OccurrenceError::StepLimit);
268 }
269 self.steps += 1;
270 crate::cooperative::checkpoint(self.steps).await;
271 self.cancel()
272 }
273 fn cancel(&self) -> Result<(), OccurrenceError<A::Error>> {
274 if self.terms.is_cancelled() {
275 Err(OccurrenceError::Cancelled)
276 } else {
277 Ok(())
278 }
279 }
280}