Skip to main content

datalog_structural_model/ir/
rule.rs

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