Skip to main content

datalog_structural_model/stratify/
types.rs

1//! Public rule scheduling result types and errors.
2
3use std::collections::BTreeSet;
4use std::{error::Error, fmt};
5
6use super::cycle::UnstratifiableCycle;
7use crate::error_code::ErrorCode;
8use crate::position::RuleIndex;
9
10/// Rule-level stratification of a finite Datalog program.
11///
12/// Dependencies connect a producer to a consumer only when the producer's
13/// complete head pattern can unify with a body atom. EDB facts are available
14/// before stratum zero. Rule indices refer to the analyzed program's rule order.
15#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct Stratification {
18    /// Strata in evaluation order; close each to a fixed point before advancing.
19    pub strata: Vec<Stratum>,
20    /// One stratum index for each rule, in program order.
21    pub rule_stratum: Vec<usize>,
22}
23
24impl Stratification {
25    /// Return the stratum of a rule, or `None` for an out-of-range rule index.
26    #[must_use]
27    pub fn stratum_of_rule(&self, rule: RuleIndex) -> Option<usize> {
28        self.rule_stratum.get(rule.get()).copied()
29    }
30}
31
32/// A set of rules evaluated together to a fixed point.
33#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct Stratum {
36    /// Indices into the analyzed program's rule list.
37    pub rules: BTreeSet<RuleIndex>,
38}
39
40/// Stratification failure.
41#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
42#[serde(deny_unknown_fields)]
43pub enum StratificationError {
44    /// A cycle of compatible rule dependencies contains negation or aggregation.
45    UnstratifiableCycle(UnstratifiableCycle),
46}
47
48impl StratificationError {
49    /// Code of [`Self::UnstratifiableCycle`].
50    pub const CODE_UNSTRATIFIABLE_CYCLE: ErrorCode = ErrorCode::new("unstratifiable-cycle");
51
52    /// Stable kebab-case code of this variant.
53    #[must_use]
54    pub fn code(&self) -> ErrorCode {
55        match self {
56            Self::UnstratifiableCycle(_) => Self::CODE_UNSTRATIFIABLE_CYCLE,
57        }
58    }
59}
60
61impl fmt::Display for StratificationError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::UnstratifiableCycle(cycle) => cycle.fmt(f),
65        }
66    }
67}
68
69impl Error for StratificationError {}