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