datalog_structural_model/ir/
rule.rs1use 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
13pub(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
25fn 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#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
35#[serde(try_from = "super::serde_input::RuleInput")]
36pub struct Rule {
37 pub head: RuleHead,
39 pub body: Vec<Literal>,
41}
42
43impl Rule {
44 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 super::Program {
54 rules: vec![rule.clone()],
55 }
56 .validate()?;
57 Ok(rule)
58 }
59
60 #[must_use]
62 pub fn literal_count(&self) -> usize {
63 Literal::count(&self.body)
64 }
65
66 #[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 #[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 #[must_use]
89 pub fn head_form(&self) -> HeadForm {
90 self.head.form()
91 }
92
93 #[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 #[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 #[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 #[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 #[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 already_bound.extend(agg.exported_variables());
215 errors.into_iter().collect()
216 })
217 }
218
219 #[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 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 #[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 #[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
291fn unsafe_inner_body_variables(
293 agg: &AggregateBody,
294 inner_bound: &BTreeSet<VariableSymbol>,
295) -> BTreeSet<VariableSymbol> {
296 let mut errors: BTreeSet<VariableSymbol> = BTreeSet::new();
297 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}