Skip to main content

datalog_structural_model/ir/
rule.rs

1//! Datalog [`Rule`] — a [`RuleHead`] plus a conjunction of body
2//! literals.
3
4use std::collections::BTreeSet;
5
6use super::aggregate::AggregateBody;
7use super::atom::Atom;
8use super::head::{HeadForm, RuleHead};
9use super::literal::Literal;
10use super::symbols::VariableSymbol;
11use crate::position::{LiteralIndex, LiteralPath};
12
13/// A body literal and the variables that make it unsafe.
14pub(super) struct LiteralFault {
15    pub(super) literal: LiteralPath,
16    pub(super) variables: Vec<VariableSymbol>,
17}
18
19impl LiteralFault {
20    fn new(literal: LiteralPath, variables: Vec<VariableSymbol>) -> Self {
21        Self { literal, variables }
22    }
23}
24
25/// Sorted variables of `vars` missing from `bound`.
26fn unbound(
27    vars: BTreeSet<VariableSymbol>,
28    bound: &BTreeSet<VariableSymbol>,
29) -> Vec<VariableSymbol> {
30    vars.into_iter().filter(|v| !bound.contains(v)).collect()
31}
32
33/// Datalog rule: `head :- body_1, ..., body_n`.
34#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
35#[serde(try_from = "super::serde_input::RuleInput")]
36pub struct Rule {
37    /// What the rule concludes.
38    pub head: RuleHead,
39    /// Body literals. An empty body represents a fact.
40    pub body: Vec<Literal>,
41}
42
43impl Rule {
44    /// Construct a standalone rule only when it is safe and stratifiable.
45    /// # Errors
46    /// Rejects invalid terms, unsafe variables and recursion through negation.
47    pub fn try_new(
48        head: impl Into<RuleHead>,
49        body: Vec<Literal>,
50    ) -> Result<Self, super::ProgramValidationError> {
51        let rule = Self::new(head, body);
52        // bounded: one authored rule, not a fact relation or graph.
53        super::Program {
54            rules: vec![rule.clone()],
55        }
56        .validate()?;
57        Ok(rule)
58    }
59
60    /// Number of body literals, counting each aggregate's inner body.
61    #[must_use]
62    pub fn literal_count(&self) -> usize {
63        Literal::count(&self.body)
64    }
65
66    /// Construct a rule whose body contains only positive literals.
67    ///
68    /// Convenience for the common case — callers that do not need
69    /// negation never have to name [`Literal`].
70    #[must_use]
71    pub fn positive(head: impl Into<RuleHead>, body: Vec<Atom>) -> Self {
72        Self {
73            head: head.into(),
74            body: body.into_iter().map(Literal::Positive).collect(),
75        }
76    }
77
78    /// Construct a rule with an explicit literal body.
79    #[must_use]
80    pub fn new(head: impl Into<RuleHead>, body: Vec<Literal>) -> Self {
81        Self {
82            head: head.into(),
83            body,
84        }
85    }
86
87    /// The logical form of the head; see [`HeadForm`].
88    #[must_use]
89    pub fn head_form(&self) -> HeadForm {
90        self.head.form()
91    }
92
93    /// Returns true when the rule satisfies Datalog¬ safety.
94    ///
95    /// A rule is safe when:
96    ///
97    /// 1. Every variable appearing in a head atom is bound by some positive
98    ///    body atom, `Bind`, or aggregate export, unless the head quantifies it
99    ///    existentially. Existential variables are unused nowhere and bound
100    ///    nowhere in the body.
101    /// 2. Every variable appearing in a **negative** body literal is bound by
102    ///    some positive body atom, `Bind`, or aggregate export (range restriction —
103    ///    negation-as-failure requires the negated atom to be ground by the
104    ///    time it is evaluated).
105    /// 3. Every variable appearing inside a [`Literal::Filter`] is bound by
106    ///    some positive body atom, `Bind`, or aggregate export — filters guard bindings,
107    ///    they do not produce them.
108    /// 4. Every variable inside a [`Literal::Bind`] expression is bound by an
109    ///    positive body atom, an earlier `Bind`, or an earlier aggregate export,
110    ///    and the `Bind`'s output variable is fresh in that bound set.
111    #[must_use]
112    pub fn is_safe(&self) -> bool {
113        self.unsafe_head_variables().is_none()
114            && self.existential_fault().is_none()
115            && self.unsafe_negative_variables().is_none()
116            && self.unsafe_filter_variables().is_none()
117            && self.unsafe_bind_variables().is_none()
118            && self.unsafe_aggregate_variables().is_none()
119    }
120
121    /// First negative body literal with variables no positive literal binds.
122    #[must_use]
123    pub(super) fn unsafe_negative_variables(&self) -> Option<LiteralFault> {
124        let bound = self.bound_body_variables();
125        self.first_literal_fault(|lit| match lit {
126            Literal::Negative(atom) => unbound(atom.variables(), &bound),
127            Literal::Positive(_)
128            | Literal::Filter(_)
129            | Literal::Bind { .. }
130            | Literal::Aggregate(_) => Vec::new(),
131        })
132    }
133
134    /// First filter literal with variables no positive literal binds.
135    #[must_use]
136    pub(super) fn unsafe_filter_variables(&self) -> Option<LiteralFault> {
137        let bound = self.bound_body_variables();
138        self.first_literal_fault(|lit| match lit {
139            Literal::Filter(filter) => unbound(filter.variables(), &bound),
140            Literal::Positive(_)
141            | Literal::Negative(_)
142            | Literal::Bind { .. }
143            | Literal::Aggregate(_) => Vec::new(),
144        })
145    }
146
147    /// Position-aware safety check for `BIND(expr AS ?var)`.
148    ///
149    /// Walks the body in order, building up the set of variables bound by
150    /// every positive atom, prior `Bind`, and prior aggregate export. Every
151    /// variable inside `expr` must already be bound and the output variable
152    /// must be fresh. Reports the first offending `Bind`.
153    #[must_use]
154    pub(super) fn unsafe_bind_variables(&self) -> Option<LiteralFault> {
155        let mut bound = self.positive_atom_variables();
156        self.first_literal_fault(|lit| match lit {
157            Literal::Aggregate(aggregate) => {
158                bound.extend(aggregate.exported_variables());
159                Vec::new()
160            }
161            Literal::Bind { var, expr } => {
162                let mut errors: BTreeSet<VariableSymbol> = expr
163                    .variables()
164                    .into_iter()
165                    .filter(|v| !bound.contains(v))
166                    .collect();
167                if !bound.insert(var.clone()) {
168                    errors.insert(var.clone());
169                }
170                errors.into_iter().collect()
171            }
172            Literal::Positive(_) | Literal::Negative(_) | Literal::Filter(_) => Vec::new(),
173        })
174    }
175
176    /// Safety check for [`Literal::Aggregate`]; reports the first offending
177    /// aggregate.
178    ///
179    /// 1. `input_var` and every `group_by` key are bound by the inner body.
180    /// 2. `result_var` is fresh relative to positive body atoms, `BIND`
181    ///    outputs, and previous aggregate exports.
182    /// 3. Inner-body literals satisfy the outer per-kind safety rules.
183    ///
184    /// Nested aggregates are reported separately by
185    /// [`Self::nested_aggregate_in_inner_body`].
186    #[must_use]
187    pub(super) fn unsafe_aggregate_variables(&self) -> Option<LiteralFault> {
188        let mut already_bound = self.positive_atom_variables();
189        for lit in &self.body {
190            if let Literal::Bind { var, .. } = lit {
191                already_bound.insert(var.clone());
192            }
193        }
194        self.first_literal_fault(|lit| {
195            let Literal::Aggregate(agg) = lit else {
196                return Vec::new();
197            };
198            let inner_bound = agg.inner_bound_variables();
199            let mut errors: BTreeSet<VariableSymbol> = BTreeSet::new();
200            if !inner_bound.contains(&agg.input_var) {
201                errors.insert(agg.input_var.clone());
202            }
203            for key in &agg.group_by {
204                if !inner_bound.contains(key) {
205                    errors.insert(key.clone());
206                }
207            }
208            if already_bound.contains(&agg.result_var) {
209                errors.insert(agg.result_var.clone());
210            }
211            errors.extend(unsafe_inner_body_variables(agg, &inner_bound));
212            // Both the result and grouping keys are visible to subsequent
213            // body literals; inner-only variables remain scoped inside.
214            already_bound.extend(agg.exported_variables());
215            errors.into_iter().collect()
216        })
217    }
218
219    /// Path to the first aggregate nested inside an aggregate's inner body.
220    #[must_use]
221    pub(super) fn nested_aggregate_in_inner_body(&self) -> Option<LiteralPath> {
222        self.body.iter().enumerate().find_map(|(outer, lit)| {
223            let Literal::Aggregate(agg) = lit else {
224                return None;
225            };
226            agg.inner_body
227                .iter()
228                .position(Literal::is_aggregate)
229                .map(|inner| {
230                    LiteralPath::top(LiteralIndex::new(outer)).inner(LiteralIndex::new(inner))
231                })
232        })
233    }
234
235    /// First top-level body literal for which `check` reports variables.
236    /// `check` sees every literal in order, so it may carry scope state.
237    fn first_literal_fault(
238        &self,
239        mut check: impl FnMut(&Literal) -> Vec<VariableSymbol>,
240    ) -> Option<LiteralFault> {
241        self.body.iter().enumerate().find_map(|(index, lit)| {
242            let variables = check(lit);
243            (!variables.is_empty())
244                .then(|| LiteralFault::new(LiteralPath::top(LiteralIndex::new(index)), variables))
245        })
246    }
247
248    /// Variables bound by the time the rule head fires: positive
249    /// body atoms, every `Bind` output variable, and every
250    /// `Aggregate` body literal's exported variables
251    /// (`result_var` and `group_by` — the inner-only variables
252    /// stay scoped inside the aggregate). Used by head,
253    /// negation, and filter safety checks.
254    #[must_use]
255    pub(super) fn bound_body_variables(&self) -> BTreeSet<VariableSymbol> {
256        let mut out = self.positive_atom_variables();
257        for lit in &self.body {
258            match lit {
259                Literal::Bind { var, .. } => {
260                    out.insert(var.clone());
261                }
262                Literal::Aggregate(agg) => {
263                    out.extend(agg.exported_variables());
264                }
265                Literal::Positive(_) | Literal::Negative(_) | Literal::Filter(_) => {}
266            }
267        }
268        out
269    }
270
271    /// Variables produced by positive body atoms only (no
272    /// `Bind` output variables, no aggregate exports). Used by
273    /// `Bind` safety as the initial bound-set before walking
274    /// the body.
275    #[must_use]
276    fn positive_atom_variables(&self) -> BTreeSet<VariableSymbol> {
277        self.body
278            .iter()
279            .filter_map(|lit| match lit {
280                Literal::Positive(atom) => Some(atom.variables()),
281                Literal::Negative(_)
282                | Literal::Filter(_)
283                | Literal::Bind { .. }
284                | Literal::Aggregate(_) => None,
285            })
286            .flatten()
287            .collect()
288    }
289}
290
291/// Validate variable safety inside an aggregate's inner body.
292fn unsafe_inner_body_variables(
293    agg: &AggregateBody,
294    inner_bound: &BTreeSet<VariableSymbol>,
295) -> BTreeSet<VariableSymbol> {
296    let mut errors: BTreeSet<VariableSymbol> = BTreeSet::new();
297    // Inner-Bind position-aware safety. Start the bound set
298    // from inner-positive variables; walk inner `BIND`s in
299    // order, checking expression references and freshness, and
300    // extending the bound set with each output.
301    let mut inner_bind_bound: BTreeSet<VariableSymbol> = agg
302        .inner_body
303        .iter()
304        .filter_map(|lit| match lit {
305            Literal::Positive(atom) => Some(atom.variables()),
306            _ => None,
307        })
308        .flatten()
309        .collect();
310    for lit in &agg.inner_body {
311        match lit {
312            Literal::Negative(atom) => {
313                for v in atom.variables() {
314                    if !inner_bound.contains(&v) {
315                        errors.insert(v);
316                    }
317                }
318            }
319            Literal::Filter(filter) => {
320                for v in filter.variables() {
321                    if !inner_bound.contains(&v) {
322                        errors.insert(v);
323                    }
324                }
325            }
326            Literal::Bind { var, expr } => {
327                for v in expr.variables() {
328                    if !inner_bind_bound.contains(&v) {
329                        errors.insert(v);
330                    }
331                }
332                if inner_bind_bound.contains(var) {
333                    errors.insert(var.clone());
334                }
335                inner_bind_bound.insert(var.clone());
336            }
337            Literal::Positive(_) | Literal::Aggregate(_) => {}
338        }
339    }
340    errors
341}