datalog_structural_model/ir/
rule.rs1use 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
12pub(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
24fn 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#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
34#[serde(try_from = "super::serde_input::RuleInput")]
35pub struct Rule {
36 pub head: Atom,
38 pub body: Vec<Literal>,
40}
41
42impl Rule {
43 pub fn try_new(head: Atom, body: Vec<Literal>) -> Result<Self, super::ProgramValidationError> {
47 let rule = Self { head, body };
48 super::Program {
50 rules: vec![rule.clone()],
51 }
52 .validate()?;
53 Ok(rule)
54 }
55
56 #[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 #[must_use]
70 pub fn new(head: Atom, body: Vec<Literal>) -> Self {
71 Self { head, body }
72 }
73
74 #[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 #[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 #[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 #[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 #[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 already_bound.extend(agg.exported_variables());
200 errors.into_iter().collect()
201 })
202 }
203
204 #[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 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 #[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 #[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
276fn unsafe_inner_body_variables(
278 agg: &AggregateBody,
279 inner_bound: &BTreeSet<VariableSymbol>,
280) -> BTreeSet<VariableSymbol> {
281 let mut errors: BTreeSet<VariableSymbol> = BTreeSet::new();
282 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}