Skip to main content

datalog_structural_model/ir/
term.rs

1//! Datalog [`Term`] enum and the triple-term nesting bound.
2
3use std::fmt;
4
5use super::atom::Atom;
6use super::symbols::{ConstantSymbol, VariableSymbol};
7
8/// Datalog term (`variable`, `constant`, `quoted-triple term`,
9/// or `SKOLEM(name, args...)` function call).
10///
11/// The `TripleTerm` variant wraps a structured [`Atom`]. An adapter owns
12/// the interpretation of that atom's relation symbol and ordered operands.
13/// A two-operand encoding can put a fixed RDF predicate IRI in `predicate`
14/// and `[subject, object]` in `terms`. For a variable RDF predicate, an
15/// adapter can instead use a fixed triple relation with three operands
16/// `[subject, predicate, object]`. The RDF reasoning catalogue uses
17/// `urn:rdf-reasoning:triple` for this three-slot convention, recursively.
18/// Its relation symbol is distinct from the RDF predicate operand.
19///
20/// These encodings are structurally distinct; this model neither converts
21/// between them nor validates RDF term domains or blank-node scope. Display
22/// text is not a canonical identity or serialization. Nesting is bounded by
23/// [`MAX_TRIPLE_TERM_NESTING`]; programs exceeding it are rejected by
24/// [`Program::validate`](super::program::Program::validate).
25///
26/// The `Skolem` variant (extension) is a deterministic fresh-IRI
27/// minting operator: given a label and a tuple of argument terms,
28/// the evaluator produces a stable
29/// `urn:example:skolem:<label>:<hash>` IRI that's content-addressed
30/// from the argument bindings. SKOLEM is only meaningful in head
31/// positions — body atoms that carry a `Skolem` term are rejected
32/// at validation time as
33/// [`super::error::ProgramValidationError::SkolemInBodyAtom`]
34/// because a SKOLEM term has no pattern semantics (it's a
35/// function, not a wildcard).
36#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
37#[serde(try_from = "super::serde_input::TermInput")]
38pub enum Term {
39    /// Variable term.
40    Variable(VariableSymbol),
41    /// Constant term.
42    Constant(ConstantSymbol),
43    /// Quoted-triple term: an inner [`Atom`] used as a value in
44    /// the enclosing atom. Conceptually represents `<< s p o >>`
45    /// per RDF 1.2 N-Triples-star syntax.
46    TripleTerm(Box<Atom>),
47    /// `SKOLEM(name, arg_1, …, arg_n)` — a deterministic fresh-IRI
48    /// minting function (extension). Permitted in rule heads only;
49    /// arguments must be [`Self::Variable`] or [`Self::Constant`]
50    /// (no nested SKOLEM, no quoted-triple terms).
51    Skolem {
52        /// Label that namespaces the skolemized IRI — typically a
53        /// short ASCII tag like `"example-key"` so collisions across
54        /// independent rule sets stay scoped per author.
55        name: ConstantSymbol,
56        /// Argument terms whose ground values feed the
57        /// content-addressed hash. Must be variables or constants.
58        args: Vec<Term>,
59    },
60}
61
62impl Term {
63    pub(super) fn collect_variables(&self, out: &mut std::collections::BTreeSet<VariableSymbol>) {
64        match self {
65            Self::Variable(var) => {
66                out.insert(var.clone());
67            }
68            Self::Constant(_) => {}
69            Self::TripleTerm(atom) => {
70                for term in &atom.terms {
71                    term.collect_variables(out);
72                }
73            }
74            Self::Skolem { args, .. } => {
75                for term in args {
76                    term.collect_variables(out);
77                }
78            }
79        }
80    }
81
82    /// Depth of the term's triple-term nesting. `0` for plain
83    /// variables, constants, and SKOLEM terms (a SKOLEM produces a
84    /// flat IRI so it doesn't extend the triple-term tree);
85    /// `1 + max_child_depth` for a `TripleTerm` whose inner atom
86    /// contains other terms.
87    #[must_use]
88    pub(super) fn nesting_depth(&self) -> usize {
89        match self {
90            Self::Variable(_) | Self::Constant(_) | Self::Skolem { .. } => 0,
91            Self::TripleTerm(atom) => 1 + atom.nesting_depth(),
92        }
93    }
94
95    /// Returns `true` when the term is a `SKOLEM(...)` function
96    /// call. Used by body-atom validation to reject SKOLEM terms
97    /// outside head positions.
98    #[must_use]
99    pub fn is_skolem(&self) -> bool {
100        matches!(self, Self::Skolem { .. })
101    }
102}
103
104/// Maximum allowed nesting depth for [`Term::TripleTerm`]
105/// variants. Programs whose triple-term nesting exceeds this
106/// limit are rejected at
107/// [`Program::validate`](super::program::Program::validate) time.
108///
109/// The bound exists because unification cost grows with nesting
110/// and because the W3C RDF-star CG has not specified a
111/// normative bound — see
112/// [rdf12-triple-term-reasoning.mdx](the RDF-star specification)
113/// for the rationale.
114pub const MAX_TRIPLE_TERM_NESTING: usize = 4;
115
116/// Display a [`Term`]: variables as `?<name>`, constants as their
117/// raw symbol, and triple terms as `<< s p o >>` per
118/// N-Triples-star syntax.
119impl fmt::Display for Term {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Variable(var) => write!(f, "?{}", var.as_str()),
123            Self::Constant(c) => write!(f, "{}", c.as_str()),
124            Self::TripleTerm(atom) => {
125                // RDF-star convention: `<< s p o >>` for the
126                // 2-arity case (subject + object as the inner
127                // atom's `terms`, predicate as the inner atom's
128                // `predicate`). For other arities — which are
129                // valid as a Datalog encoding even though they
130                // are not standard RDF triples — fall back to
131                // `<< pred(t1, t2, …) >>` so the print still
132                // round-trips through a developer's eye.
133                if atom.terms.len() == 2 {
134                    write!(
135                        f,
136                        "<< {} {} {} >>",
137                        atom.terms[0],
138                        atom.predicate.as_str(),
139                        atom.terms[1],
140                    )
141                } else {
142                    write!(f, "<< {atom} >>")
143                }
144            }
145            Self::Skolem { name, args } => {
146                write!(f, "SKOLEM({}", name.as_str())?;
147                for arg in args {
148                    write!(f, ", {arg}")?;
149                }
150                write!(f, ")")
151            }
152        }
153    }
154}