Skip to main content

datalog_structural_model/
profile.rs

1//! Checked generic language profiles; RDF/OWL semantics belong in rule packages.
2use crate::error_code::ErrorCode;
3use crate::{
4    DatalogCapabilities, DatalogFeature, EqualityMode, HeadForm, Program, ProgramValidationError,
5    RuleIndex, TerminationViolation, ValidationLimits,
6};
7use std::{error::Error, fmt};
8
9/// Explicit language features, equality regime and structural limits
10/// selected for a program.
11/// This is neither an RDF entailment profile nor an execution strategy.
12#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct DatalogProfile {
15    capabilities: DatalogCapabilities,
16    equality_mode: EqualityMode,
17    limits: ValidationLimits,
18}
19impl DatalogProfile {
20    /// Construct an explicit language contract with the standard
21    /// [`ValidationLimits`]. Program-specific combinations are checked by
22    /// [`Program::validate_for`].
23    #[must_use]
24    pub fn new(capabilities: DatalogCapabilities, equality_mode: EqualityMode) -> Self {
25        Self {
26            capabilities,
27            equality_mode,
28            limits: ValidationLimits::standard(),
29        }
30    }
31    /// Replace this profile's structural limits.
32    #[must_use]
33    pub fn with_limits(mut self, limits: ValidationLimits) -> Self {
34        self.limits = limits;
35        self
36    }
37    /// Positive flat Datalog without built-in expression extensions.
38    #[must_use]
39    pub fn positive() -> Self {
40        Self::new(DatalogCapabilities::positive(), EqualityMode::Default)
41    }
42    /// Flat Datalog with stratified negation, without built-in extensions.
43    #[must_use]
44    pub fn stratified() -> Self {
45        Self::new(
46            DatalogCapabilities::positive().with(DatalogFeature::StratifiedNegation),
47            EqualityMode::Default,
48        )
49    }
50    /// The explicitly selected language features.
51    #[must_use]
52    pub fn capabilities(&self) -> &DatalogCapabilities {
53        &self.capabilities
54    }
55    /// The selected equality validation regime.
56    #[must_use]
57    pub fn equality_mode(&self) -> EqualityMode {
58        self.equality_mode
59    }
60    /// The structural limits [`Program::validate_for`] enforces.
61    #[must_use]
62    pub fn limits(&self) -> &ValidationLimits {
63        &self.limits
64    }
65}
66
67/// Features required by the program and absent from the selected profile.
68#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct UnsupportedCapabilities {
71    missing: DatalogCapabilities,
72}
73impl UnsupportedCapabilities {
74    /// Inspect every missing feature, including nested operators.
75    #[must_use]
76    pub fn missing(&self) -> &DatalogCapabilities {
77        &self.missing
78    }
79}
80impl fmt::Display for UnsupportedCapabilities {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "unsupported Datalog features: {:?}", self.missing)
83    }
84}
85impl Error for UnsupportedCapabilities {}
86
87/// An invalid program or an explicitly unsupported language feature.
88#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
89#[serde(deny_unknown_fields)]
90pub enum ProfileCheckError {
91    /// Structural safety, stratification or equality compatibility failed.
92    InvalidProgram(ProgramValidationError),
93    /// A rule's head form needs a capability the profile lacks. Reported
94    /// before, and never folded into, [`Self::Unsupported`].
95    UnsupportedHeadForm {
96        /// The first rule whose head form is not accepted.
97        rule: RuleIndex,
98        /// Its head form.
99        form: HeadForm,
100    },
101    /// One or more required features are absent from the profile.
102    Unsupported(UnsupportedCapabilities),
103    /// The program is not weakly acyclic, so evaluation may not terminate.
104    TerminationUncertified(TerminationViolation),
105}
106impl fmt::Display for ProfileCheckError {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::InvalidProgram(error) => error.fmt(f),
110            Self::UnsupportedHeadForm { rule, form } => write!(
111                f,
112                "[{}] {rule} has a {form} head, which the profile does not accept",
113                self.code()
114            ),
115            Self::Unsupported(error) => error.fmt(f),
116            Self::TerminationUncertified(error) => error.fmt(f),
117        }
118    }
119}
120impl ProfileCheckError {
121    /// Code of [`Self::InvalidProgram`]; the wrapped error carries its own code.
122    pub const CODE_INVALID_PROGRAM: ErrorCode = ErrorCode::new("invalid-program");
123    /// Code of [`Self::UnsupportedHeadForm`].
124    pub const CODE_UNSUPPORTED_HEAD_FORM: ErrorCode = ErrorCode::new("unsupported-head-form");
125    /// Code of [`Self::Unsupported`].
126    pub const CODE_UNSUPPORTED_CAPABILITIES: ErrorCode = ErrorCode::new("unsupported-capabilities");
127    /// Code of [`Self::TerminationUncertified`]; the wrapped violation
128    /// carries its own code.
129    pub const CODE_TERMINATION_UNCERTIFIED: ErrorCode = ErrorCode::new("termination-uncertified");
130    /// Stable kebab-case code of this variant.
131    #[must_use]
132    pub fn code(&self) -> ErrorCode {
133        match self {
134            Self::InvalidProgram(_) => Self::CODE_INVALID_PROGRAM,
135            Self::UnsupportedHeadForm { .. } => Self::CODE_UNSUPPORTED_HEAD_FORM,
136            Self::Unsupported(_) => Self::CODE_UNSUPPORTED_CAPABILITIES,
137            Self::TerminationUncertified(_) => Self::CODE_TERMINATION_UNCERTIFIED,
138        }
139    }
140}
141impl Error for ProfileCheckError {
142    fn source(&self) -> Option<&(dyn Error + 'static)> {
143        match self {
144            Self::InvalidProgram(error) => Some(error),
145            Self::UnsupportedHeadForm { .. } => None,
146            Self::Unsupported(error) => Some(error),
147            Self::TerminationUncertified(error) => Some(error),
148        }
149    }
150}
151impl Program {
152    /// Validate safety within the profile's limits, reject every feature
153    /// missing from the selected contract, and require
154    /// [`TerminationCriterion::WeaklyAcyclic`](crate::TerminationCriterion::WeaklyAcyclic)
155    /// with invented values no deeper than the profile's Skolem depth limit.
156    /// # Errors
157    /// Returns typed structural failures (limit errors report the limit and
158    /// the value reached), the first rule whose head form the profile does
159    /// not accept, the exact unsupported feature set, or the cyclic
160    /// value-inventing edge.
161    pub fn validate_for(&self, profile: &DatalogProfile) -> Result<(), ProfileCheckError> {
162        self.validate_within(profile.equality_mode, &profile.limits)
163            .map_err(ProfileCheckError::InvalidProgram)?;
164        self.check_head_forms(&profile.capabilities)?;
165        let missing = self
166            .required_capabilities()
167            .missing_from(&profile.capabilities);
168        if !missing.is_empty() {
169            return Err(ProfileCheckError::Unsupported(UnsupportedCapabilities {
170                missing,
171            }));
172        }
173        let certificate = self
174            .check_weak_acyclicity()
175            .map_err(ProfileCheckError::TerminationUncertified)?;
176        let limit = profile.limits.skolem_depth();
177        match certificate.deepest() {
178            Some(position) if certificate.skolem_depth() > limit => Err(
179                ProfileCheckError::InvalidProgram(ProgramValidationError::SkolemDepthExceeded {
180                    position: position.clone(),
181                    depth: certificate.skolem_depth(),
182                    limit,
183                }),
184            ),
185            _ => Ok(()),
186        }
187    }
188
189    /// Reject the first rule whose head form needs an undeclared capability.
190    fn check_head_forms(&self, supported: &DatalogCapabilities) -> Result<(), ProfileCheckError> {
191        self.rules
192            .iter()
193            .enumerate()
194            .find_map(|(index, rule)| {
195                let form = rule.head_form();
196                let feature = form.required_feature()?;
197                (!supported.contains(&feature)).then_some(ProfileCheckError::UnsupportedHeadForm {
198                    rule: RuleIndex::new(index),
199                    form,
200                })
201            })
202            .map_or(Ok(()), Err)
203    }
204}