Skip to main content

pddl_core/parsers/structure/
domain.rs

1//! Provides parsers for domain definitions (`<domain>`).
2
3use crate::parsers::error::{Error, R};
4use crate::parsers::sexpr::Node;
5use crate::parsers::{
6    parse_constants_def, parse_domain_constraints_def, parse_functions_def, parse_name,
7    parse_predicates_def, parse_require_def, parse_structure_def, parse_timeless_def,
8    parse_types_def, prefix, set_once,
9};
10use crate::types::{Domain, StructureDefs};
11
12/// The section keywords of a domain, for suggestions.
13const SECTIONS: &[&str] = &[
14    ":extends",
15    ":requirements",
16    ":types",
17    ":constants",
18    ":predicates",
19    ":functions",
20    ":constraints",
21    ":timeless",
22    ":action",
23    ":durative-action",
24    ":derived",
25    ":process",
26    ":event",
27];
28
29/// Parses a domain definition (`<domain>`), i.e. `(define (domain <name>) <section>*)`.
30///
31/// The sections may appear in any order; each one except actions at most once.
32pub(crate) fn parse_domain(node: &Node) -> R<Domain> {
33    parse_domain_recovering(node, None)
34}
35
36/// Like [`parse_domain`], but with `errors`, a failing section is recorded there
37/// and skipped, so that the sections after it are still checked.
38pub(crate) fn parse_domain_recovering(
39    node: &Node,
40    mut errors: Option<&mut Vec<Error>>,
41) -> R<Domain> {
42    prefix(node, "define", |args| {
43        let name = prefix(args.next()?, "domain", |args| parse_name(args.next()?))?;
44        let mut extends = None;
45        let mut requirements = None;
46        let mut types = None;
47        let mut constants = None;
48        let mut predicates = None;
49        let mut functions = None;
50        let mut constraints = None;
51        let mut timeless = None;
52        let mut structure = Vec::new();
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                    ":extends" => {
61                        let names = prefix(section, ":extends", |args| args.list1(parse_name))?;
62                        set_once(&mut extends, names, section)
63                    }
64                    ":requirements" => {
65                        set_once(&mut requirements, parse_require_def(section)?, section)
66                    }
67                    ":types" => set_once(&mut types, parse_types_def(section)?, section),
68                    ":constants" => {
69                        set_once(&mut constants, parse_constants_def(section)?, section)
70                    }
71                    ":predicates" => {
72                        set_once(&mut predicates, parse_predicates_def(section)?, section)
73                    }
74                    ":functions" => {
75                        set_once(&mut functions, parse_functions_def(section)?, section)
76                    }
77                    ":constraints" => {
78                        let value = parse_domain_constraints_def(section)?;
79                        set_once(&mut constraints, value, section)
80                    }
81                    ":timeless" => set_once(&mut timeless, parse_timeless_def(section)?, section),
82                    ":action" | ":durative-action" | ":derived" | ":process" | ":event" => {
83                        structure.push(parse_structure_def(section)?);
84                        Ok(())
85                    }
86                    _ => {
87                        let error = section.error().reason("unknown section").fatal();
88                        Err(match section.head() {
89                            Some(head) => error.suggest(head, SECTIONS),
90                            None => error,
91                        })
92                    }
93                }
94            };
95            match (read(), errors.as_deref_mut()) {
96                (Ok(()), _) => {}
97                (Err(error), Some(errors)) => errors.push(error),
98                (Err(error), None) => return Err(error),
99            }
100        }
101        Ok(Domain::builder(name, StructureDefs::new(structure))
102            .with_extends(extends.unwrap_or_default())
103            .with_requirements(requirements.unwrap_or_default())
104            .with_types(types.unwrap_or_default())
105            .with_constants(constants.unwrap_or_default())
106            .with_predicates(predicates.unwrap_or_default())
107            .with_functions(functions.unwrap_or_default())
108            .with_constraints(constraints.unwrap_or_default())
109            .with_timeless(timeless.unwrap_or_default()))
110    })
111}
112
113crate::parsers::impl_parser!(Domain => parse_domain);
114
115#[cfg(test)]
116mod tests {
117    use assert2::check;
118
119    use crate::*;
120
121    #[test]
122    fn sections_in_any_order() {
123        let ordered = Domain::from_str(
124            "(define (domain d) (:requirements :strips) (:types t) (:predicates (p)) (:functions (c)) \
125             (:action a :parameters () :effect (p)) (:action b :parameters () :effect (p)))",
126        )
127        .unwrap();
128        let shuffled = Domain::from_str(
129            "(define (domain d) (:functions (c)) (:action a :parameters () :effect (p)) \
130             (:predicates (p)) (:types t) (:action b :parameters () :effect (p)) (:requirements :strips))",
131        )
132        .unwrap();
133        check!(ordered == shuffled);
134    }
135
136    #[test]
137    fn duplicate_section_is_reported_at_the_second_occurrence() {
138        let input = "(define (domain d)\n  (:predicates (p))\n  (:predicates (q)))";
139        let error = Domain::from_str(input).unwrap_err();
140        check!((error.line(), error.column()) == (3, 3));
141        check!(error.found() == Some("(:predicates (q)))"));
142    }
143
144    #[test]
145    fn test_parse() {
146        let input = r"
147         ; A toy domain.
148         (define (domain briefcase-world)
149              ; If no requirements are provided, :strips is implied.
150              (:requirements :strips :equality :typing :conditional-effects)
151              (:types location physob) ; type definitions could also be represented as predicates
152              (:constants B P D - physob)
153              (:predicates (at ?x - physob ?y - location)
154                           (in ?x ?y - physob))
155              (:constraints (and))
156
157              ; Move briefcase from one location to another.
158              (:action mov-B
159                   :parameters (?m ?l - location)
160                   :precondition (and (at B ?m) (not (= ?m ?l)))
161                   :effect (and (at B ?l) (not (at B ?m))
162                                (forall (?z)
163                                    (when (and (in ?z) (not (= ?z B)))
164                                          (and (at ?z ?l) (not (at ?z ?m)))))) )
165
166              ; Put the item in the briefcase if it is not already in there.
167              (:action put-in
168                   :parameters (?x - physob ?l - location)
169                   :precondition (not (= ?x B))
170                   :effect (when (and (at ?x ?l) (at B ?l))
171                         (in ?x)) )
172
173              ; Take the item out of the briefcase if it is in there.
174              (:action take-out
175                   :parameters (?x - physob)
176                   :precondition (not (= ?x B))
177                   :effect (not (in ?x)) )
178            )";
179
180        let domain = Domain::from_str(input).unwrap();
181
182        check!(domain.name() == &Name::new("briefcase-world"));
183        check!(domain.requirements().len() == 4);
184        check!(domain.types().len() == 2);
185        check!(domain.constants().len() == 3);
186        check!(domain.predicates().len() == 2);
187        check!(domain.constraints().is_empty());
188        check!(domain.structure().len() == 3);
189    }
190
191    #[test]
192    fn doc_example_0() {
193        let input = r"(define (domain briefcase-world)
194              (:requirements :strips :equality :typing :conditional-effects)
195              (:types location physob)
196              (:constants B P D - physob)
197              (:predicates (at ?x - physob ?y - location)
198                           (in ?x ?y - physob))
199              (:constraints (and))
200        
201              (:action mov-B
202                   :parameters (?m ?l - location)
203                   :precondition (and (at B ?m) (not (= ?m ?l)))
204                   :effect (and (at B ?l) (not (at B ?m))
205                                (forall (?z)
206                                    (when (and (in ?z) (not (= ?z B)))
207                                          (and (at ?z ?l) (not (at ?z ?m)))))) )
208        
209              (:action put-in
210                   :parameters (?x - physob ?l - location)
211                   :precondition (not (= ?x B))
212                   :effect (when (and (at ?x ?l) (at B ?l))
213                         (in ?x)) )
214        
215              (:action take-out
216                   :parameters (?x - physob)
217                   :precondition (not (= ?x B))
218                   :effect (not (in ?x)) )
219            )";
220
221        let domain = Domain::from_str(input).unwrap();
222        check!(domain.name() == &Name::new("briefcase-world"));
223        check!(domain.requirements().len() == 4);
224        check!(domain.types().len() == 2);
225        check!(domain.constants().len() == 3);
226        check!(domain.predicates().len() == 2);
227        check!(domain.constraints().is_empty());
228        check!(domain.structure().len() == 3);
229    }
230
231    #[test]
232    fn doc_example_1() {
233        let input = r"
234         ; A toy domain.
235         (define (domain briefcase-world)
236              ; If no requirements are provided, :strips is implied.
237              (:requirements :strips :equality :typing :conditional-effects)
238              (:types location physob) ; type definitions could also be represented as predicates
239              (:constants B P D - physob)
240              (:predicates (at ?x - physob ?y - location)
241                           (in ?x ?y - physob))
242              (:constraints (and))
243        
244              ; Move briefcase from one location to another.
245              (:action mov-B
246                   :parameters (?m ?l - location)
247                   :precondition (and (at B ?m) (not (= ?m ?l)))
248                   :effect (and (at B ?l) (not (at B ?m))
249                                (forall (?z)
250                                    (when (and (in ?z) (not (= ?z B)))
251                                          (and (at ?z ?l) (not (at ?z ?m)))))) )
252        
253              ; Put the item in the briefcase if it is not already in there.
254              (:action put-in
255                   :parameters (?x - physob ?l - location)
256                   :precondition (not (= ?x B))
257                   :effect (when (and (at ?x ?l) (at B ?l))
258                         (in ?x)) )
259        
260              ; Take the item out of the briefcase if it is in there.
261              (:action take-out
262                   :parameters (?x - physob)
263                   :precondition (not (= ?x B))
264                   :effect (not (in ?x)) )
265            )";
266
267        let domain = Domain::from_str(input).unwrap();
268
269        check!(domain.name() == &Name::new("briefcase-world"));
270        check!(domain.requirements().len() == 4);
271        check!(domain.types().len() == 2);
272        check!(domain.constants().len() == 3);
273        check!(domain.predicates().len() == 2);
274        check!(domain.constraints().is_empty());
275        check!(domain.structure().len() == 3);
276    }
277}