Skip to main content

datalog_structural_model/ir/
structural_term.rs

1//! Context-free term invariants shared by constructors and checked decoding.
2use super::{Atom, ConstantSymbol, GroundAtom, GroundTerm, Term};
3use crate::error_code::ErrorCode;
4use crate::limits::ValidationLimits;
5use std::{error::Error, fmt};
6
7/// Invalid term structure, independent of variable binding or rule position.
8#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
9#[serde(deny_unknown_fields)]
10pub enum TermShapeError {
11    /// A structured term exceeds the supported nesting depth.
12    TripleTermNestingExceeded {
13        /// Observed nesting depth.
14        depth: usize,
15        /// Supported maximum depth.
16        limit: usize,
17    },
18    /// A Skolem argument is neither a variable nor a constant.
19    InvalidSkolemArguments,
20}
21impl fmt::Display for TermShapeError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::TripleTermNestingExceeded { depth, limit } => {
25                write!(f, "triple term depth {depth} exceeds limit {limit}")
26            }
27            Self::InvalidSkolemArguments => {
28                f.write_str("Skolem arguments must be variables or constants")
29            }
30        }
31    }
32}
33impl Error for TermShapeError {}
34impl TermShapeError {
35    /// Code of [`Self::TripleTermNestingExceeded`].
36    pub const CODE_TRIPLE_TERM_NESTING_EXCEEDED: ErrorCode =
37        ErrorCode::new("triple-term-nesting-exceeded");
38    /// Code of [`Self::InvalidSkolemArguments`].
39    pub const CODE_INVALID_SKOLEM_ARGUMENTS: ErrorCode = ErrorCode::new("invalid-skolem-arguments");
40    /// Stable kebab-case code of this variant.
41    #[must_use]
42    pub fn code(&self) -> ErrorCode {
43        match self {
44            Self::TripleTermNestingExceeded { .. } => Self::CODE_TRIPLE_TERM_NESTING_EXCEEDED,
45            Self::InvalidSkolemArguments => Self::CODE_INVALID_SKOLEM_ARGUMENTS,
46        }
47    }
48}
49impl Term {
50    /// Construct a structured term with checked nesting and Skolem arguments.
51    /// # Errors
52    /// Rejects excessive nesting or invalid nested Skolem arguments.
53    pub fn try_triple_term(atom: Atom) -> Result<Self, TermShapeError> {
54        let term = Self::TripleTerm(Box::new(atom));
55        term.validate_structure()?;
56        Ok(term)
57    }
58    /// Construct a deterministic head term with flat arguments.
59    /// # Errors
60    /// Rejects arguments other than variables and constants.
61    pub fn try_skolem(name: ConstantSymbol, args: Vec<Self>) -> Result<Self, TermShapeError> {
62        let term = Self::Skolem { name, args };
63        term.validate_structure()?;
64        Ok(term)
65    }
66    /// Check context-free structure under the standard
67    /// [`ValidationLimits`]. Rule-position and binding checks require
68    /// [`super::Program::validate`].
69    /// # Errors
70    /// Rejects excessive triple depth or non-flat Skolem arguments.
71    pub fn validate_structure(&self) -> Result<(), TermShapeError> {
72        self.validate_structure_within(&ValidationLimits::standard())
73    }
74    /// Check context-free structure under explicit `limits`.
75    /// # Errors
76    /// Rejects triple depth beyond `limits` or non-flat Skolem arguments.
77    pub fn validate_structure_within(
78        &self,
79        limits: &ValidationLimits,
80    ) -> Result<(), TermShapeError> {
81        let depth = self.nesting_depth();
82        let limit = limits.triple_term_nesting();
83        if depth > limit {
84            return Err(TermShapeError::TripleTermNestingExceeded { depth, limit });
85        }
86        match self {
87            Self::Variable(_) | Self::Constant(_) => {}
88            Self::TripleTerm(atom) => {
89                for term in &atom.terms {
90                    term.validate_structure_within(limits)?;
91                }
92            }
93            Self::Skolem { args, .. } => {
94                if args
95                    .iter()
96                    .any(|term| !matches!(term, Self::Variable(_) | Self::Constant(_)))
97                {
98                    return Err(TermShapeError::InvalidSkolemArguments);
99                }
100            }
101        }
102        Ok(())
103    }
104}
105impl GroundTerm {
106    fn nesting_depth(&self) -> usize {
107        match self {
108            Self::Constant(_) => 0,
109            Self::TripleTerm(atom) => {
110                1 + atom.args.iter().map(Self::nesting_depth).max().unwrap_or(0)
111            }
112        }
113    }
114    /// Construct a grounded structured term with checked nesting.
115    /// # Errors
116    /// Rejects excessive triple-term nesting.
117    pub fn try_triple_term(atom: GroundAtom) -> Result<Self, TermShapeError> {
118        let term = Self::TripleTerm(Box::new(atom));
119        term.validate_structure()?;
120        Ok(term)
121    }
122    /// Check the standard nesting invariant used before grounding a program.
123    /// # Errors
124    /// Rejects excessive triple-term nesting.
125    pub fn validate_structure(&self) -> Result<(), TermShapeError> {
126        self.validate_structure_within(&ValidationLimits::standard())
127    }
128    /// Check triple-term nesting under explicit `limits`.
129    /// # Errors
130    /// Rejects triple-term nesting beyond `limits`.
131    pub fn validate_structure_within(
132        &self,
133        limits: &ValidationLimits,
134    ) -> Result<(), TermShapeError> {
135        let depth = self.nesting_depth();
136        let limit = limits.triple_term_nesting();
137        if depth > limit {
138            return Err(TermShapeError::TripleTermNestingExceeded { depth, limit });
139        }
140        Ok(())
141    }
142}