Skip to main content

datalog_structural_model/position/
term_path.rs

1//! [`TermPath`] — a term inside an atom or expression, through nested
2//! triple terms and Skolem argument lists.
3
4use std::fmt;
5
6use super::index::{AtomSlot, ExpressionTermIndex};
7
8/// Where the outermost term of a [`TermPath`] sits.
9#[derive(
10    Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
11)]
12#[serde(deny_unknown_fields)]
13pub enum TermRoot {
14    /// A slot of the head or body atom.
15    Slot(AtomSlot),
16    /// A top-level term of a filter or BIND expression.
17    ExpressionTerm(ExpressionTermIndex),
18}
19
20/// Path to a term: its root, then one argument slot per nested triple term
21/// or Skolem call descended into.
22#[derive(
23    Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
24)]
25#[serde(deny_unknown_fields)]
26pub struct TermPath {
27    root: TermRoot,
28    // bounded: depth of authored term nesting, which validation caps.
29    nested: Vec<AtomSlot>,
30}
31
32impl TermPath {
33    /// Path to a root term.
34    #[must_use]
35    pub fn new(root: TermRoot) -> Self {
36        Self {
37            root,
38            nested: Vec::new(),
39        }
40    }
41
42    /// Path to argument `slot` of the term this path points to.
43    #[must_use]
44    pub fn child(&self, slot: AtomSlot) -> Self {
45        let mut nested = self.nested.clone();
46        nested.push(slot);
47        Self {
48            root: self.root,
49            nested,
50        }
51    }
52
53    /// The outermost term's position.
54    #[must_use]
55    pub fn root(&self) -> TermRoot {
56        self.root
57    }
58
59    /// Argument slots descended into below the root.
60    #[must_use]
61    pub fn nested(&self) -> &[AtomSlot] {
62        &self.nested
63    }
64}
65
66impl fmt::Display for TermPath {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self.root {
69            TermRoot::Slot(slot) => write!(f, "slot {}", slot.get())?,
70            TermRoot::ExpressionTerm(index) => write!(f, "expression term {}", index.get())?,
71        }
72        for slot in &self.nested {
73            write!(f, " > argument {}", slot.get())?;
74        }
75        Ok(())
76    }
77}