Skip to main content

datalog_structural_model/ir/
program.rs

1//! Datalog [`Program`] — an ordered set of [`Rule`]s plus
2//! validation and stratification entry points.
3
4use super::equality_mode::EqualityMode;
5use super::error::ProgramValidationError;
6use super::head::{ExistentialFault, HeadFault};
7use super::literal::Literal;
8use super::rule::{LiteralFault, Rule};
9use crate::limits::ValidationLimits;
10use crate::position::{LiteralIndex, LiteralPath, RuleIndex};
11use crate::stratify::{Stratification, stratify};
12
13/// Datalog program as an ordered set of rules.
14#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
15#[serde(try_from = "super::serde_input::ProgramInput")]
16pub struct Program {
17    /// Program rules.
18    pub rules: Vec<Rule>,
19}
20
21impl Program {
22    /// Construct a program only when all safety and stratification checks pass.
23    /// # Errors
24    /// Returns the same structural failures as [`Self::validate`].
25    pub fn try_new(rules: Vec<Rule>) -> Result<Self, ProgramValidationError> {
26        let program = Self { rules };
27        program.validate()?;
28        Ok(program)
29    }
30
31    /// Validate all rules in the program for safety and
32    /// stratifiability.
33    ///
34    /// Runs two checks:
35    ///
36    /// 1. **Safety** — every rule must be range-restricted; head variables and
37    ///    variables inside negated body literals must also appear in some
38    ///    positive body literal.
39    /// 2. **Stratifiability** — the compatible-rule dependency graph must have no
40    ///    cycle that includes a negation edge (see [`Program::stratify`]).
41    ///
42    /// # Errors
43    ///
44    /// Returns [`ProgramValidationError::UnsafeRule`] on a safety
45    /// failure, [`ProgramValidationError::UnsafeNegation`] when a
46    /// negated body literal references a variable that no positive
47    /// literal binds, or
48    /// [`ProgramValidationError::UnstratifiableCycle`] when the
49    /// program contains a recursive cycle through negation.
50    pub fn validate(&self) -> Result<(), ProgramValidationError> {
51        self.validate_within(EqualityMode::Default, &ValidationLimits::standard())
52    }
53
54    /// Validate the program under a specified equality-reasoning
55    /// mode (extension).
56    ///
57    /// Runs the same safety / stratification / triple-term-nesting
58    /// checks as [`Self::validate`] and additionally rejects
59    /// negation and aggregation when
60    /// `equality_mode == EqualityMode::SameAs`. The two features
61    /// interact non-monotonically with `owl:sameAs` rewriting; see
62    /// [`EqualityMode`] for the semantic rationale.
63    ///
64    /// # Errors
65    ///
66    /// Returns the same errors as [`Self::validate`] plus
67    /// [`ProgramValidationError::NegationUnderEqualityMode`] or
68    /// [`ProgramValidationError::AggregationUnderEqualityMode`]
69    /// when the corresponding feature is used under
70    /// [`EqualityMode::SameAs`].
71    pub fn validate_with_equality_mode(
72        &self,
73        equality_mode: EqualityMode,
74    ) -> Result<(), ProgramValidationError> {
75        self.validate_within(equality_mode, &ValidationLimits::standard())
76    }
77
78    /// Validate under an equality mode and explicit structural `limits`.
79    ///
80    /// Checks the rule count, each rule's body length and triple-term
81    /// nesting against `limits` before the safety and stratification checks
82    /// of [`Self::validate_with_equality_mode`]. The Skolem depth limit
83    /// needs the termination analysis and is enforced by
84    /// [`Self::validate_for`].
85    ///
86    /// # Errors
87    ///
88    /// Returns [`ProgramValidationError::RuleCountExceeded`],
89    /// [`ProgramValidationError::BodyLengthExceeded`] or
90    /// [`ProgramValidationError::TripleTermNestingExceeded`] with the limit
91    /// and the value reached, or any error of
92    /// [`Self::validate_with_equality_mode`].
93    pub fn validate_within(
94        &self,
95        equality_mode: EqualityMode,
96        limits: &ValidationLimits,
97    ) -> Result<(), ProgramValidationError> {
98        if self.rules.len() > limits.rules() {
99            return Err(ProgramValidationError::RuleCountExceeded {
100                count: self.rules.len(),
101                limit: limits.rules(),
102            });
103        }
104        if equality_mode == EqualityMode::SameAs {
105            check_equality_mode_compatibility(&self.rules)?;
106        }
107        for (index, rule) in self.rules.iter().enumerate() {
108            rule.validate(RuleIndex::new(index), limits)?;
109        }
110        // Stratification check — reject programs with recursion
111        // through negation.
112        self.stratify()?;
113        Ok(())
114    }
115
116    /// Compute the program's stratification.
117    ///
118    /// Connects producers to consumers whose complete tuple patterns can
119    /// unify, collapses strongly connected components, and assigns each rule
120    /// to a stratum. Negative and aggregate dependencies require a strictly
121    /// earlier producer stratum. Pure EDB inputs are available before stratum
122    /// zero. Rule indices refer to this program's rule order.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`ProgramValidationError::UnstratifiableCycle`]
127    /// when a cycle in the dependency graph contains a negation
128    /// edge.
129    pub fn stratify(&self) -> Result<Stratification, ProgramValidationError> {
130        stratify(self).map_err(ProgramValidationError::from)
131    }
132}
133
134/// Reject negation and aggregation under [`EqualityMode::SameAs`], naming
135/// the first offending top-level body literal.
136fn check_equality_mode_compatibility(rules: &[Rule]) -> Result<(), ProgramValidationError> {
137    for (index, rule) in rules.iter().enumerate() {
138        let rule_index = RuleIndex::new(index);
139        for (position, lit) in rule.body.iter().enumerate() {
140            let literal = LiteralPath::top(LiteralIndex::new(position));
141            match lit {
142                Literal::Negative(_) => {
143                    return Err(ProgramValidationError::NegationUnderEqualityMode {
144                        rule: rule_index,
145                        literal,
146                    });
147                }
148                Literal::Aggregate(_) => {
149                    return Err(ProgramValidationError::AggregationUnderEqualityMode {
150                        rule: rule_index,
151                        literal,
152                    });
153                }
154                Literal::Positive(_) | Literal::Filter(_) | Literal::Bind { .. } => {}
155            }
156        }
157    }
158    Ok(())
159}
160
161impl Rule {
162    /// Per-rule shape and safety checks, in reporting order.
163    fn validate(
164        &self,
165        rule: RuleIndex,
166        limits: &ValidationLimits,
167    ) -> Result<(), ProgramValidationError> {
168        let length = self.literal_count();
169        if length > limits.body_literals() {
170            return Err(ProgramValidationError::BodyLengthExceeded {
171                rule,
172                length,
173                limit: limits.body_literals(),
174            });
175        }
176        self.validate_term_shapes(rule, limits)?;
177        match self.existential_fault() {
178            Some(ExistentialFault::Unused(variable)) => {
179                return Err(ProgramValidationError::UnusedExistentialVariable { rule, variable });
180            }
181            Some(ExistentialFault::BoundInBody(variable)) => {
182                return Err(ProgramValidationError::ExistentialVariableBoundInBody {
183                    rule,
184                    variable,
185                });
186            }
187            None => {}
188        }
189        if let Some(HeadFault { atom, variables }) = self.unsafe_head_variables() {
190            return Err(ProgramValidationError::UnsafeRule {
191                rule,
192                atom,
193                variables,
194            });
195        }
196        if let Some(LiteralFault { literal, variables }) = self.unsafe_negative_variables() {
197            return Err(ProgramValidationError::UnsafeNegation {
198                rule,
199                literal,
200                variables,
201            });
202        }
203        if let Some(LiteralFault { literal, variables }) = self.unsafe_filter_variables() {
204            return Err(ProgramValidationError::UnsafeFilter {
205                rule,
206                literal,
207                variables,
208            });
209        }
210        if let Some(LiteralFault { literal, variables }) = self.unsafe_bind_variables() {
211            return Err(ProgramValidationError::UnsafeBind {
212                rule,
213                literal,
214                variables,
215            });
216        }
217        if let Some(literal) = self.nested_aggregate_in_inner_body() {
218            return Err(ProgramValidationError::NestedAggregateInInnerBody { rule, literal });
219        }
220        if let Some(LiteralFault { literal, variables }) = self.unsafe_aggregate_variables() {
221            return Err(ProgramValidationError::UnsafeAggregate {
222                rule,
223                literal,
224                variables,
225            });
226        }
227        Ok(())
228    }
229}