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::literal::Literal;
7use super::rule::{LiteralFault, Rule};
8use crate::position::{LiteralIndex, LiteralPath, RuleIndex};
9use crate::stratify::{Stratification, stratify};
10
11/// Datalog program as an ordered set of rules.
12#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
13#[serde(try_from = "super::serde_input::ProgramInput")]
14pub struct Program {
15    /// Program rules.
16    pub rules: Vec<Rule>,
17}
18
19impl Program {
20    /// Construct a program only when all safety and stratification checks pass.
21    /// # Errors
22    /// Returns the same structural failures as [`Self::validate`].
23    pub fn try_new(rules: Vec<Rule>) -> Result<Self, ProgramValidationError> {
24        let program = Self { rules };
25        program.validate()?;
26        Ok(program)
27    }
28
29    /// Validate all rules in the program for safety and
30    /// stratifiability.
31    ///
32    /// Runs two checks:
33    ///
34    /// 1. **Safety** — every rule must be range-restricted; head variables and
35    ///    variables inside negated body literals must also appear in some
36    ///    positive body literal.
37    /// 2. **Stratifiability** — the compatible-rule dependency graph must have no
38    ///    cycle that includes a negation edge (see [`Program::stratify`]).
39    ///
40    /// # Errors
41    ///
42    /// Returns [`ProgramValidationError::UnsafeRule`] on a safety
43    /// failure, [`ProgramValidationError::UnsafeNegation`] when a
44    /// negated body literal references a variable that no positive
45    /// literal binds, or
46    /// [`ProgramValidationError::UnstratifiableCycle`] when the
47    /// program contains a recursive cycle through negation.
48    pub fn validate(&self) -> Result<(), ProgramValidationError> {
49        self.validate_with_equality_mode(EqualityMode::Default)
50    }
51
52    /// Validate the program under a specified equality-reasoning
53    /// mode (extension).
54    ///
55    /// Runs the same safety / stratification / triple-term-nesting
56    /// checks as [`Self::validate`] and additionally rejects
57    /// negation and aggregation when
58    /// `equality_mode == EqualityMode::SameAs`. The two features
59    /// interact non-monotonically with `owl:sameAs` rewriting; see
60    /// [`EqualityMode`] for the semantic rationale.
61    ///
62    /// # Errors
63    ///
64    /// Returns the same errors as [`Self::validate`] plus
65    /// [`ProgramValidationError::NegationUnderEqualityMode`] or
66    /// [`ProgramValidationError::AggregationUnderEqualityMode`]
67    /// when the corresponding feature is used under
68    /// [`EqualityMode::SameAs`].
69    pub fn validate_with_equality_mode(
70        &self,
71        equality_mode: EqualityMode,
72    ) -> Result<(), ProgramValidationError> {
73        if equality_mode == EqualityMode::SameAs {
74            check_equality_mode_compatibility(&self.rules)?;
75        }
76        for (index, rule) in self.rules.iter().enumerate() {
77            rule.validate(RuleIndex::new(index))?;
78        }
79        // Stratification check — reject programs with recursion
80        // through negation.
81        self.stratify()?;
82        Ok(())
83    }
84
85    /// Compute the program's stratification.
86    ///
87    /// Connects producers to consumers whose complete tuple patterns can
88    /// unify, collapses strongly connected components, and assigns each rule
89    /// to a stratum. Negative and aggregate dependencies require a strictly
90    /// earlier producer stratum. Pure EDB inputs are available before stratum
91    /// zero. Rule indices refer to this program's rule order.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`ProgramValidationError::UnstratifiableCycle`]
96    /// when a cycle in the dependency graph contains a negation
97    /// edge.
98    pub fn stratify(&self) -> Result<Stratification, ProgramValidationError> {
99        stratify(self).map_err(ProgramValidationError::from)
100    }
101}
102
103/// Reject negation and aggregation under [`EqualityMode::SameAs`], naming
104/// the first offending top-level body literal.
105fn check_equality_mode_compatibility(rules: &[Rule]) -> Result<(), ProgramValidationError> {
106    for (index, rule) in rules.iter().enumerate() {
107        let rule_index = RuleIndex::new(index);
108        for (position, lit) in rule.body.iter().enumerate() {
109            let literal = LiteralPath::top(LiteralIndex::new(position));
110            match lit {
111                Literal::Negative(_) => {
112                    return Err(ProgramValidationError::NegationUnderEqualityMode {
113                        rule: rule_index,
114                        literal,
115                    });
116                }
117                Literal::Aggregate(_) => {
118                    return Err(ProgramValidationError::AggregationUnderEqualityMode {
119                        rule: rule_index,
120                        literal,
121                    });
122                }
123                Literal::Positive(_) | Literal::Filter(_) | Literal::Bind { .. } => {}
124            }
125        }
126    }
127    Ok(())
128}
129
130impl Rule {
131    /// Per-rule shape and safety checks, in reporting order.
132    fn validate(&self, rule: RuleIndex) -> Result<(), ProgramValidationError> {
133        self.validate_term_shapes(rule)?;
134        let variables = self.unsafe_head_variables();
135        if !variables.is_empty() {
136            return Err(ProgramValidationError::UnsafeRule { rule, variables });
137        }
138        if let Some(LiteralFault { literal, variables }) = self.unsafe_negative_variables() {
139            return Err(ProgramValidationError::UnsafeNegation {
140                rule,
141                literal,
142                variables,
143            });
144        }
145        if let Some(LiteralFault { literal, variables }) = self.unsafe_filter_variables() {
146            return Err(ProgramValidationError::UnsafeFilter {
147                rule,
148                literal,
149                variables,
150            });
151        }
152        if let Some(LiteralFault { literal, variables }) = self.unsafe_bind_variables() {
153            return Err(ProgramValidationError::UnsafeBind {
154                rule,
155                literal,
156                variables,
157            });
158        }
159        if let Some(literal) = self.nested_aggregate_in_inner_body() {
160            return Err(ProgramValidationError::NestedAggregateInInnerBody { rule, literal });
161        }
162        if let Some(LiteralFault { literal, variables }) = self.unsafe_aggregate_variables() {
163            return Err(ProgramValidationError::UnsafeAggregate {
164                rule,
165                literal,
166                variables,
167            });
168        }
169        Ok(())
170    }
171}