Skip to main content

datalog_structural_model/ir/
term.rs

1//! Datalog [`Term`] enum.
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/// [`ValidationLimits::triple_term_nesting`](crate::ValidationLimits::triple_term_nesting);
24/// programs exceeding it are rejected by
25/// [`Program::validate`](super::program::Program::validate).
26///
27/// The `Skolem` variant (extension) is a deterministic fresh-IRI
28/// minting operator: given a label and a tuple of argument terms,
29/// the evaluator produces a stable
30/// `urn:example:skolem:<label>:<hash>` IRI that's content-addressed
31/// from the argument bindings. SKOLEM is only meaningful in head
32/// positions — body atoms that carry a `Skolem` term are rejected
33/// at validation time as
34/// [`super::error::ProgramValidationError::SkolemInBodyAtom`]
35/// because a SKOLEM term has no pattern semantics (it's a
36/// function, not a wildcard).
37#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
38#[serde(try_from = "super::serde_input::TermInput")]
39pub enum Term {
40    /// Variable term.
41    Variable(VariableSymbol),
42    /// Constant term.
43    Constant(ConstantSymbol),
44    /// Quoted-triple term: an inner [`Atom`] used as a value in
45    /// the enclosing atom. Conceptually represents `<< s p o >>`
46    /// per RDF 1.2 N-Triples-star syntax.
47    TripleTerm(Box<Atom>),
48    /// `SKOLEM(name, arg_1, …, arg_n)` — a deterministic fresh-IRI
49    /// minting function (extension). Permitted in rule heads only;
50    /// arguments must be [`Self::Variable`] or [`Self::Constant`]
51    /// (no nested SKOLEM, no quoted-triple terms).
52    Skolem {
53        /// Label that namespaces the skolemized IRI — typically a
54        /// short ASCII tag like `"example-key"` so collisions across
55        /// independent rule sets stay scoped per author.
56        name: ConstantSymbol,
57        /// Argument terms whose ground values feed the
58        /// content-addressed hash. Must be variables or constants.
59        args: Vec<Term>,
60    },
61}
62
63impl Term {
64    /// Distinct variables in stable symbol order, recursively including triple
65    /// terms and Skolem arguments. Constants and relation names are excluded.
66    /// This inspects syntax; it does not resolve bindings or evaluate Skolem calls.
67    #[must_use]
68    pub fn variables(&self) -> std::collections::BTreeSet<VariableSymbol> {
69        // bounded: variable symbols in this finite authored term, never facts.
70        let mut variables = std::collections::BTreeSet::new();
71        self.collect_variables(&mut variables);
72        variables
73    }
74
75    /// Visit borrowed variable occurrences in operand order, including nested
76    /// triple terms and Skolem arguments. Repeated occurrences are retained.
77    /// This traverses authored syntax without cloning symbols or resolving values.
78    pub fn visit_variables<'a>(&'a self, visitor: &mut impl FnMut(&'a VariableSymbol)) {
79        match self {
80            Self::Variable(variable) => visitor(variable),
81            Self::Constant(_) => {}
82            Self::TripleTerm(atom) => atom.visit_variables(visitor),
83            Self::Skolem { args, .. } => {
84                for term in args {
85                    term.visit_variables(visitor);
86                }
87            }
88        }
89    }
90
91    pub(super) fn collect_variables(&self, out: &mut std::collections::BTreeSet<VariableSymbol>) {
92        self.visit_variables(&mut |variable| {
93            out.insert(variable.clone());
94        });
95    }
96
97    /// Depth of the term's triple-term nesting. `0` for plain
98    /// variables, constants, and SKOLEM terms (a SKOLEM produces a
99    /// flat IRI so it doesn't extend the triple-term tree);
100    /// `1 + max_child_depth` for a `TripleTerm` whose inner atom
101    /// contains other terms.
102    #[must_use]
103    pub(super) fn nesting_depth(&self) -> usize {
104        match self {
105            Self::Variable(_) | Self::Constant(_) | Self::Skolem { .. } => 0,
106            Self::TripleTerm(atom) => 1 + atom.nesting_depth(),
107        }
108    }
109
110    /// Returns `true` when the term is a `SKOLEM(...)` function
111    /// call. Used by body-atom validation to reject SKOLEM terms
112    /// outside head positions.
113    #[must_use]
114    pub fn is_skolem(&self) -> bool {
115        matches!(self, Self::Skolem { .. })
116    }
117}
118
119/// Display a [`Term`]: variables as `?<name>`, constants as their
120/// raw symbol, and triple terms as `<< s p o >>` per
121/// N-Triples-star syntax.
122impl fmt::Display for Term {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        match self {
125            Self::Variable(var) => write!(f, "?{}", var.as_str()),
126            Self::Constant(c) => write!(f, "{}", c.as_str()),
127            Self::TripleTerm(atom) => {
128                // RDF-star convention: `<< s p o >>` for the
129                // 2-arity case (subject + object as the inner
130                // atom's `terms`, predicate as the inner atom's
131                // `predicate`). For other arities — which are
132                // valid as a Datalog encoding even though they
133                // are not standard RDF triples — fall back to
134                // `<< pred(t1, t2, …) >>` so the print still
135                // round-trips through a developer's eye.
136                if atom.terms.len() == 2 {
137                    write!(
138                        f,
139                        "<< {} {} {} >>",
140                        atom.terms[0],
141                        atom.predicate.as_str(),
142                        atom.terms[1],
143                    )
144                } else {
145                    write!(f, "<< {atom} >>")
146                }
147            }
148            Self::Skolem { name, args } => {
149                write!(f, "SKOLEM({}", name.as_str())?;
150                for arg in args {
151                    write!(f, ", {arg}")?;
152                }
153                write!(f, ")")
154            }
155        }
156    }
157}