Skip to main content

datalog_structural_model/ir/
literal.rs

1//! Body literal — positive/negated atom, filter, `BIND`, or
2//! aggregation.
3
4use super::aggregate::AggregateBody;
5use super::atom::Atom;
6use super::bind::BindExpr;
7use super::filter::BuiltinFilter;
8use super::symbols::VariableSymbol;
9
10/// Datalog body literal — a positive or negated atom, a built-in
11/// filter expression, or a built-in `BIND(expr AS ?var)` form.
12///
13/// Rule bodies in Datalog¬ are conjunctions of literals. Positive
14/// literals must match facts in the database; negative literals
15/// must **not** match. Negation semantics follow the stratified
16/// negation-as-failure convention: every rule whose head can match a
17/// negated atom runs in a strictly lower stratum. The matching fact
18/// extension is therefore closed by the time the consuming rule fires.
19///
20/// `Filter` literals carry a [`BuiltinFilter`] expression that
21/// guards the current candidate binding — the evaluator drops a
22/// binding whenever the filter does not evaluate to `true`.
23///
24/// `Bind` literals carry a [`BindExpr`] expression and a fresh
25/// variable name; the evaluator extends the current candidate
26/// binding with `var → eval(expr, binding)` and the new variable
27/// is then visible to all subsequent body literals (including
28/// further `Bind`s, `Filter`s, the rule head, and SPARQL-style
29/// constraints over computed values). Filter and bind literals
30/// participate in safety analysis but contribute no edges to the
31/// rule dependency graph used by stratification.
32#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
33#[serde(deny_unknown_fields)]
34pub enum Literal {
35    /// Positive literal — the body atom must match a fact.
36    Positive(Atom),
37    /// Negative literal — the body atom must **not** match any
38    /// fact.
39    Negative(Atom),
40    /// Built-in filter expression evaluated against the current
41    /// candidate binding.
42    Filter(BuiltinFilter),
43    /// `BIND(expr AS ?var)` — extend the current candidate
44    /// binding with a computed value. `var` must be fresh
45    /// relative to all positive body atoms, earlier `Bind` outputs,
46    /// and earlier aggregate exports. Every variable in `expr` must
47    /// come from a positive body atom anywhere in the body, an earlier
48    /// `Bind`, or an earlier aggregate export.
49    Bind {
50        /// The fresh variable produced by this bind.
51        var: VariableSymbol,
52        /// The expression to compute. Evaluated against the
53        /// current candidate binding.
54        expr: BindExpr,
55    },
56    /// Aggregation sub-query — fold the inner body into a
57    /// per-group aggregate result that the outer body sees as a
58    /// freshly-bound variable. See [`AggregateBody`] for the
59    /// scoping and inner-body restrictions. Execution support is
60    /// declared by each consumer.
61    Aggregate(AggregateBody),
62}
63
64impl Literal {
65    /// Access the underlying atom, when this literal carries one.
66    ///
67    /// Returns `None` for [`Literal::Filter`], [`Literal::Bind`],
68    /// and [`Literal::Aggregate`] — none of which carries a
69    /// single fact-matching atom in its top-level position.
70    /// (An aggregate's inner literals live inside
71    /// [`AggregateBody::inner_body`].)
72    #[must_use]
73    pub fn atom(&self) -> Option<&Atom> {
74        match self {
75            Self::Positive(atom) | Self::Negative(atom) => Some(atom),
76            Self::Filter(_) | Self::Bind { .. } | Self::Aggregate(_) => None,
77        }
78    }
79
80    /// True when the literal is positive.
81    #[must_use]
82    pub fn is_positive(&self) -> bool {
83        matches!(self, Self::Positive(_))
84    }
85
86    /// True when the literal is negated.
87    #[must_use]
88    pub fn is_negative(&self) -> bool {
89        matches!(self, Self::Negative(_))
90    }
91
92    /// True when the literal is a [`BuiltinFilter`] guard.
93    #[must_use]
94    pub fn is_filter(&self) -> bool {
95        matches!(self, Self::Filter(_))
96    }
97
98    /// True when the literal is a `BIND(expr AS ?var)` form.
99    #[must_use]
100    pub fn is_bind(&self) -> bool {
101        matches!(self, Self::Bind { .. })
102    }
103
104    /// True when the literal is an aggregation sub-query.
105    #[must_use]
106    pub fn is_aggregate(&self) -> bool {
107        matches!(self, Self::Aggregate(_))
108    }
109}
110
111impl Literal {
112    /// Number of literals in `body`, recursing into aggregate inner bodies.
113    pub(super) fn count(body: &[Self]) -> usize {
114        body.iter()
115            .map(|literal| match literal {
116                Self::Aggregate(aggregate) => 1 + Self::count(&aggregate.inner_body),
117                _ => 1,
118            })
119            .sum()
120    }
121}