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