Skip to main content

pddl_core/parsers/structure/
problem.rs

1//! Provides parsers for problem definitions (`<problem>`).
2
3use crate::parsers::error::{Error, R};
4use crate::parsers::sexpr::Node;
5use crate::parsers::{
6    parse_name, parse_problem_constraints_def, parse_problem_goal_def, parse_problem_init_def,
7    parse_problem_length_spec, parse_problem_metric_spec, parse_problem_objects_declaration,
8    parse_require_def, prefix, set_once,
9};
10use crate::types::{InitElements, Problem};
11
12/// The section keywords of a problem, for suggestions.
13const SECTIONS: &[&str] = &[
14    ":domain",
15    ":requirements",
16    ":objects",
17    ":init",
18    ":goal",
19    ":constraints",
20    ":metric",
21    ":length",
22];
23
24/// Parses a problem definition (`<problem>`), i.e. `(define (problem <name>) <section>*)`.
25///
26/// The sections may appear in any order, each at most once; `:domain` and `:goal`
27/// are required. The grammar requires `:init` too, but a problem without one parses
28/// with an empty initial state.
29pub(crate) fn parse_problem(node: &Node) -> R<Problem> {
30    // Without `errors`, a failing section returns its error, so the problem is never `None`.
31    parse_problem_recovering(node, None).map(|problem| problem.expect("no recovery"))
32}
33
34/// Like [`parse_problem`], but with `errors`, a failing section is recorded there
35/// and skipped, so that the sections after it are still checked. Then `None`
36/// means that a section failed and a required section is missing, which is not
37/// reported again: it may be the one that failed.
38pub(crate) fn parse_problem_recovering(
39    node: &Node,
40    mut errors: Option<&mut Vec<Error>>,
41) -> R<Option<Problem>> {
42    let mut failed = false;
43    prefix(node, "define", |args| {
44        let name = prefix(args.next()?, "problem", |args| parse_name(args.next()?))?;
45        let mut domain = None;
46        let mut requirements = None;
47        let mut objects = None;
48        let mut init = None;
49        let mut goal = None;
50        let mut constraints = None;
51        let mut metric = None;
52        let mut length = None;
53        for section in args.rest() {
54            let mut read = || -> R<()> {
55                if section.atom().is_some() {
56                    return Err(section.error());
57                }
58                let head = section.head().unwrap_or_default().to_ascii_lowercase();
59                match head.as_str() {
60                    ":domain" => {
61                        let value = prefix(section, ":domain", |args| parse_name(args.next()?))?;
62                        set_once(&mut domain, value, section)
63                    }
64                    ":requirements" => {
65                        set_once(&mut requirements, parse_require_def(section)?, section)
66                    }
67                    ":objects" => {
68                        let value = parse_problem_objects_declaration(section)?;
69                        set_once(&mut objects, value, section)
70                    }
71                    ":init" => set_once(&mut init, parse_problem_init_def(section)?, section),
72                    ":goal" => set_once(&mut goal, parse_problem_goal_def(section)?, section),
73                    ":constraints" => {
74                        let value = parse_problem_constraints_def(section)?;
75                        set_once(&mut constraints, value, section)
76                    }
77                    // :numeric-fluents
78                    ":metric" => {
79                        set_once(&mut metric, parse_problem_metric_spec(section)?, section)
80                    }
81                    // Deprecated since PDDL 2.1
82                    ":length" => {
83                        set_once(&mut length, parse_problem_length_spec(section)?, section)
84                    }
85                    _ => {
86                        let error = section.error().reason("unknown section").fatal();
87                        Err(match section.head() {
88                            Some(head) => error.suggest(head, SECTIONS),
89                            None => error,
90                        })
91                    }
92                }
93            };
94            match (read(), errors.as_deref_mut()) {
95                (Ok(()), _) => {}
96                (Err(error), Some(errors)) => {
97                    errors.push(error);
98                    failed = true;
99                }
100                (Err(error), None) => return Err(error),
101            }
102        }
103        // Exhaustive per section, so a new required section can't be reported as another one.
104        let missing = |reason| {
105            if failed {
106                Ok(None)
107            } else {
108                Err(args.error_at_close().reason(reason).fatal())
109            }
110        };
111        let (domain, goal) = match (domain, goal) {
112            (Some(domain), Some(goal)) => (domain, goal),
113            (None, _) => return missing("missing `:domain`"),
114            (_, None) => return missing("missing `:goal`"),
115        };
116        let init = init.unwrap_or_else(|| InitElements::new(Vec::new()));
117        Ok(Some(Problem::new(
118            name,
119            domain,
120            requirements.unwrap_or_default(),
121            objects.unwrap_or_default(),
122            init,
123            goal,
124            constraints.unwrap_or_default(),
125            metric,
126            length,
127        )))
128    })
129}
130
131crate::parsers::impl_parser!(Problem => parse_problem);
132
133#[cfg(test)]
134mod tests {
135    use assert2::check;
136
137    use crate::*;
138
139    #[test]
140    fn sections_in_any_order() {
141        let ordered = Problem::from_str(
142            "(define (problem p) (:domain d) (:requirements :strips) (:objects a) \
143             (:init (at a)) (:goal (at a)) (:metric minimize (total-time)))",
144        )
145        .unwrap();
146        let shuffled = Problem::from_str(
147            "(define (problem p) (:metric minimize (total-time)) (:goal (at a)) (:objects a) \
148             (:init (at a)) (:requirements :strips) (:domain d))",
149        )
150        .unwrap();
151        check!(ordered == shuffled);
152    }
153
154    #[test]
155    fn missing_required_section_is_reported_where_the_sections_end() {
156        let input = "(define (problem p) (:domain d) (:init (at a))\n)";
157        let error = Problem::from_str(input).unwrap_err();
158        check!((error.line(), error.column()) == (2, 1));
159        check!(error.found() == Some(")"));
160    }
161
162    #[test]
163    fn duplicate_section_is_reported_at_the_second_occurrence() {
164        let input = "(define (problem p) (:domain d) (:init) (:goal (and)) (:init))";
165        let error = Problem::from_str(input).unwrap_err();
166        check!(Some(error.offset()) == input.rfind("(:init)"));
167    }
168
169    #[test]
170    fn test_parse() {
171        let input = r"(define (problem get-paid)
172                 (:domain briefcase-world)
173                 (:init (place home) (place office)
174                        (object p) (object d) (object b)
175                        (at B home) (at P home) (at D home) (in P))
176                 (:goal (and (at B office) (at D office) (at P home)))
177             )";
178
179        let problem = Problem::from_str(input).unwrap();
180        check!(problem.name() == &Name::new("get-paid"));
181        check!(problem.domain() == &Name::new("briefcase-world"));
182        check!(problem.requirements().is_empty());
183        check!(problem.init().len() == 9);
184        check!(problem.goals().len() == 3);
185    }
186
187    #[test]
188    fn doc_example_0() {
189        let input = r"(define (problem get-paid)
190                (:domain briefcase-world)
191                (:init (place home) (place office)
192                       (object p) (object d) (object b)
193                       (at B home) (at P home) (at D home) (in P))
194                (:goal (and (at B office) (at D office) (at P home)))
195            )";
196
197        let problem = Problem::from_str(input).unwrap();
198        check!(problem.name() == &Name::new("get-paid"));
199        check!(problem.domain() == &Name::new("briefcase-world"));
200        check!(problem.requirements().is_empty());
201        check!(problem.init().len() == 9);
202        check!(problem.goals().len() == 3);
203    }
204
205    #[test]
206    fn doc_example_1() {
207        let input = r"(define (problem get-paid)
208                (:domain briefcase-world)
209                (:init (place home) (place office)
210                       (object p) (object d) (object b)
211                       (at B home) (at P home) (at D home) (in P))
212                (:goal (and (at B office) (at D office) (at P home)))
213            )";
214
215        let problem = Problem::from_str(input).unwrap();
216
217        check!(problem.name() == &Name::new("get-paid"));
218        check!(problem.domain() == &Name::new("briefcase-world"));
219        check!(problem.requirements().is_empty());
220        check!(problem.init().len() == 9);
221        check!(problem.goals().len() == 3);
222    }
223
224    #[test]
225    fn init_may_be_left_out() {
226        let problem = Problem::from_str("(define (problem p) (:domain d) (:goal (and)))").unwrap();
227        check!(problem.init().is_empty());
228    }
229}