Skip to main content

pddl_validate/
error.rs

1//! Errors in the domain or problem, found before any plan runs.
2
3use alloc::string::String;
4use core::fmt;
5
6/// The domain or problem is malformed, so no plan can be validated against it.
7///
8/// [`Validator::new`](crate::Validator::new) checks every name and arity up front, so a
9/// plan's verdict never depends on a typo in the domain.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct ModelError {
13    /// Where the problem is, such as ``action `drive` `` or `goal`.
14    pub location: String,
15    /// What is wrong.
16    pub kind: ModelErrorKind,
17}
18
19impl ModelError {
20    /// Builds an error at `location`.
21    pub(crate) fn new(location: impl Into<String>, kind: ModelErrorKind) -> Self {
22        Self {
23            location: location.into(),
24            kind,
25        }
26    }
27}
28
29/// The kinds of [`ModelError`]. All names are in ASCII lowercase.
30#[derive(Debug, Clone, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum ModelErrorKind {
33    /// The problem names another domain in `(:domain ...)`.
34    DomainMismatch {
35        /// The name of the domain given to the validator.
36        domain: String,
37        /// The domain the problem names.
38        problem_domain: String,
39    },
40    /// A type is used but not declared.
41    UnknownType(String),
42    /// A predicate is used but not declared.
43    UnknownPredicate(String),
44    /// A function is used but not declared.
45    UnknownFunction(String),
46    /// An object or constant is used but not declared.
47    UnknownObject(String),
48    /// A variable is used outside the parameters and quantifiers that bind it.
49    UnboundVariable(String),
50    /// A predicate or function is applied to the wrong number of arguments.
51    Arity {
52        /// The predicate or function.
53        symbol: String,
54        /// The number of parameters it is declared with.
55        expected: usize,
56        /// The number of arguments it is applied to.
57        found: usize,
58    },
59    /// Two actions share a name.
60    DuplicateAction(String),
61    /// One parameter or quantifier list declares a variable twice, such as `(?x ?x)`.
62    DuplicateVariable(String),
63    /// An action effect or the initial state sets a derived predicate, which only its
64    /// rule may define.
65    DerivedPredicateSet(String),
66    /// An effect or the initial state sets an equality `(= a b)`.
67    EqualitySet,
68    /// Two timed initial literals at the same time make one atom both true and false,
69    /// such as `(at 1 (q))` and `(at 1 (not (q)))`.
70    ContradictoryTimedLiterals {
71        /// The ground atom, such as `(at r1 base)`.
72        atom: String,
73        /// The time of the first of the two literals, formatted as a decimal number.
74        time: String,
75    },
76}
77
78impl fmt::Display for ModelError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        write!(f, "{}: {}", self.location, self.kind)
81    }
82}
83
84impl fmt::Display for ModelErrorKind {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::DomainMismatch {
88                domain,
89                problem_domain,
90            } => write!(
91                f,
92                "the problem is for domain `{problem_domain}`, not `{domain}`"
93            ),
94            Self::UnknownType(name) => write!(f, "unknown type `{name}`"),
95            Self::UnknownPredicate(name) => write!(f, "unknown predicate `{name}`"),
96            Self::UnknownFunction(name) => write!(f, "unknown function `{name}`"),
97            Self::UnknownObject(name) => write!(f, "unknown object `{name}`"),
98            Self::UnboundVariable(name) => write!(f, "unbound variable `?{name}`"),
99            Self::Arity {
100                symbol,
101                expected,
102                found,
103            } => write!(
104                f,
105                "`{symbol}` takes {expected} arguments but is given {found}"
106            ),
107            Self::DuplicateAction(name) => write!(f, "action `{name}` is defined twice"),
108            Self::DuplicateVariable(name) => write!(f, "variable `?{name}` is declared twice"),
109            Self::DerivedPredicateSet(name) => {
110                write!(f, "derived predicate `{name}` cannot be set directly")
111            }
112            Self::EqualitySet => f.write_str("`=` cannot be set"),
113            Self::ContradictoryTimedLiterals { atom, time } => {
114                write!(
115                    f,
116                    "timed literals make `{atom}` both true and false at {time}"
117                )
118            }
119        }
120    }
121}
122
123impl core::error::Error for ModelError {}
124
125#[cfg(test)]
126mod tests {
127    //! Pins the exact text of every model error, as users read it.
128
129    use alloc::string::ToString;
130
131    use super::*;
132
133    #[test]
134    fn model_errors_display_location_and_kind() {
135        let name = || "drive".to_string();
136        let cases = [
137            (
138                ModelErrorKind::DomainMismatch {
139                    domain: "trucks".to_string(),
140                    problem_domain: "boats".to_string(),
141                },
142                "the problem is for domain `boats`, not `trucks`",
143            ),
144            (ModelErrorKind::UnknownType(name()), "unknown type `drive`"),
145            (
146                ModelErrorKind::UnknownPredicate(name()),
147                "unknown predicate `drive`",
148            ),
149            (
150                ModelErrorKind::UnknownFunction(name()),
151                "unknown function `drive`",
152            ),
153            (
154                ModelErrorKind::UnknownObject(name()),
155                "unknown object `drive`",
156            ),
157            (
158                ModelErrorKind::UnboundVariable(name()),
159                "unbound variable `?drive`",
160            ),
161            (
162                ModelErrorKind::Arity {
163                    symbol: name(),
164                    expected: 2,
165                    found: 3,
166                },
167                "`drive` takes 2 arguments but is given 3",
168            ),
169            (
170                ModelErrorKind::DuplicateAction(name()),
171                "action `drive` is defined twice",
172            ),
173            (
174                ModelErrorKind::DuplicateVariable(name()),
175                "variable `?drive` is declared twice",
176            ),
177            (
178                ModelErrorKind::DerivedPredicateSet(name()),
179                "derived predicate `drive` cannot be set directly",
180            ),
181            (ModelErrorKind::EqualitySet, "`=` cannot be set"),
182            (
183                ModelErrorKind::ContradictoryTimedLiterals {
184                    atom: "(open shop)".to_string(),
185                    time: "1.5".to_string(),
186                },
187                "timed literals make `(open shop)` both true and false at 1.5",
188            ),
189        ];
190
191        for (kind, text) in cases {
192            let error = ModelError::new("action `drive`", kind);
193            assert_eq!(error.to_string(), alloc::format!("action `drive`: {text}"));
194        }
195    }
196}