Skip to main content

pddl_core/parsers/structure/
pddl_file.rs

1//! Provides parsers for files with several domain and problem definitions.
2
3use crate::parsers::error::{Lines, R};
4use crate::parsers::sexpr::{self, Node};
5use crate::parsers::structure::domain::parse_domain_recovering;
6use crate::parsers::structure::problem::parse_problem_recovering;
7use crate::parsers::{alt, parse_domain, parse_nodes, parse_problem, ParseError, Parser};
8use crate::types::{Definition, PddlFile};
9
10/// Parses a single `(define ...)` block, determining whether it's a domain or problem.
11pub(crate) fn parse_definition(node: &Node) -> R<Definition> {
12    alt(
13        node,
14        &[&|n| parse_domain(n).map(Definition::Domain), &|n| {
15            parse_problem(n).map(Definition::Problem)
16        }],
17    )
18}
19
20/// Parses every leading `(define ...)` node of `nodes` and returns how many it read.
21pub(crate) fn parse_pddl_file(nodes: &[Node]) -> R<(PddlFile, usize)> {
22    let mut domains = Vec::new();
23    let mut problems = Vec::new();
24    let mut read = 0;
25    for node in nodes {
26        if !node
27            .head()
28            .is_some_and(|h| h.eq_ignore_ascii_case("define"))
29        {
30            break;
31        }
32        match parse_definition(node)? {
33            Definition::Domain(d) => domains.push(d),
34            Definition::Problem(p) => problems.push(p),
35        }
36        read += 1;
37    }
38    let file = PddlFile::with_domains_and_problems(domains, problems);
39    Ok((file, read))
40}
41
42crate::parsers::impl_parser!(Definition => parse_definition);
43
44/// The most errors [`check`] reports; it stops checking once it found this many.
45const MAX_ERRORS: usize = 1000;
46
47/// Parses `input` like [`PddlFile::from_str`](crate::Parser::from_str), but
48/// returns every error it finds instead of stopping at the first one.
49///
50/// After an error, checking resumes at the next section of the same domain or
51/// problem, or at the next top-level form. So it reports at most one error per
52/// section, action or top-level form, in input order, and at most the first
53/// 1000. The result is empty exactly when
54/// [`PddlFile::from_str`](crate::Parser::from_str) succeeds.
55///
56/// ## Example
57/// ```
58/// let input = "(define (domain d)\n  (:predicats (p))\n  (:action a :parameters (?x -)))";
59/// let errors = pddl::parsers::check(input);
60/// assert_eq!(errors.len(), 2);
61/// assert_eq!(errors[0].help(), Some("did you mean `:predicates`?"));
62/// assert_eq!(errors[1].line(), 3);
63/// ```
64#[must_use]
65pub fn check(input: &str) -> Vec<ParseError> {
66    let forest = match sexpr::read(input) {
67        Ok(forest) => forest,
68        Err(error) => return vec![ParseError::new(input, &error)],
69    };
70    let mut errors = Vec::new();
71    for node in &forest.nodes {
72        if errors.len() >= MAX_ERRORS {
73            break;
74        }
75
76        if !node
77            .head()
78            .is_some_and(|h| h.eq_ignore_ascii_case("define"))
79        {
80            errors.push(node.error());
81            continue;
82        }
83        let kind = node.children().and_then(|c| c.get(1)).and_then(Node::head);
84        let result = match kind.map(str::to_ascii_lowercase).as_deref() {
85            Some("domain") => parse_domain_recovering(node, Some(&mut errors)).map(drop),
86            Some("problem") => parse_problem_recovering(node, Some(&mut errors)).map(drop),
87            _ => parse_definition(node).map(drop),
88        };
89        errors.extend(result.err());
90    }
91    errors.extend(forest.unbalanced);
92    errors.truncate(MAX_ERRORS);
93
94    let lines = Lines::new(input);
95    errors
96        .iter()
97        .map(|e| ParseError::with_lines(&lines, e))
98        .collect()
99}
100
101impl Parser for PddlFile {
102    type Item = PddlFile;
103
104    /// Parses zero or more `(define ...)` blocks, in any order.
105    fn from_str(input: &str) -> Result<Self::Item, ParseError> {
106        parse_nodes(input, |nodes, _| parse_pddl_file(nodes))
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::MAX_ERRORS;
113    use assert2::check;
114
115    use crate::*;
116
117    const DOMAIN: &str = "(define (domain d) (:predicates (p)))";
118    const PROBLEM: &str = "(define (problem q) (:domain d) (:init) (:goal (p)))";
119
120    #[test]
121    fn define_is_matched_case_insensitively() {
122        let file = PddlFile::from_str(&format!("{}\n{}", DOMAIN.to_uppercase(), PROBLEM)).unwrap();
123        check!((file.domain_count(), file.problem_count()) == (1, 1));
124    }
125
126    #[test]
127    fn definition_kind_comes_from_the_header_not_comments() {
128        for comment in ["", "; Uses (domain d)\n", "; Example (problem q)\n"] {
129            let domain = Definition::from_str(&format!("{comment}{DOMAIN} ; end\n"));
130            check!(let Ok(Definition::Domain(_)) = domain, "{domain:?}");
131            let problem = Definition::from_str(&format!("{comment}{PROBLEM}"));
132            check!(let Ok(Definition::Problem(_)) = problem, "{problem:?}");
133        }
134    }
135
136    #[test]
137    fn definition_rejects_empty_multiple_or_trailing_input() {
138        for input in [
139            String::new(),
140            "; comment only\n".into(),
141            format!("{DOMAIN}\n{PROBLEM}"),
142            format!("{PROBLEM}\n{PROBLEM}"),
143            format!("{DOMAIN}\ngarbage"),
144            format!("text {DOMAIN}"),
145            "(define (foo x))".into(),
146            "(define (domain".into(),
147        ] {
148            check!(Definition::from_str(&input).is_err(), "accepted {input:?}");
149        }
150    }
151
152    /// Structural errors inside a definition must be reported where they are,
153    /// not as the fallback `problem` alternative failing at `(domain`.
154    #[test]
155    fn section_errors_are_reported_at_the_offending_section() {
156        let cases = [
157            (
158                "misspelled section",
159                "(define (domain d)\n  (:requirement :strips)\n  (:predicates (p)))",
160                "(:requirement",
161            ),
162            (
163                "duplicate section",
164                "(define (domain d)\n  (:predicates (p))\n  (:predicates (q)))",
165                "(:predicates (q)",
166            ),
167            (
168                "missing :goal",
169                "(define (problem p) (:domain d) (:init)\n)",
170                ")",
171            ),
172        ];
173        for (label, input, at) in cases {
174            let error = PddlFile::from_str(input).unwrap_err();
175            check!(Some(error.offset()) == input.rfind(at), "{label}: {error}");
176        }
177    }
178
179    #[test]
180    fn check_reports_one_error_per_section_and_form() {
181        let input = "(define (domain d)\n  (:predicats (p))\n  (:types t)\n  (:types u)\n  \
182                     (:action a :parameters (?x -) :effect (p))\n  \
183                     (:action b :parameters () :effect (p)))\n\
184                     stray\n\
185                     (define (problem q) (:domain d) (:init (p) 1) (:goal (p)))\n\
186                     (define (problem r) (:domain d) (:init (p)))\n\
187                     (define (problem s) (:domain d) (:goal (p) (q)))\n\
188                     (";
189        let errors = parsers::check(input);
190        let found: Vec<_> = errors
191            .iter()
192            .map(|e| (e.line(), e.reason().unwrap_or_default()))
193            .collect();
194        check!(
195            found
196                == [
197                    (2, "unknown section"),
198                    (4, "duplicate section"),
199                    (5, ""),
200                    (7, ""),
201                    (8, ""),
202                    (9, "missing `:goal`"),
203                    (10, "expected `)`"),
204                    (11, ""),
205                    (11, "expected `)`"),
206                ]
207        );
208        // A failed `:init` is not reported again as missing.
209        check!(errors.iter().all(|e| e.reason() != Some("missing `:init`")));
210    }
211
212    #[test]
213    fn check_reports_sections_that_are_not_keyword_lists() {
214        let input = "(define (domain d) word (()) (:predicates (p)))\n\
215                     (define (problem q) (:domain d) (()) (:init) (:goal (p)))";
216        let errors = parsers::check(input);
217        let found: Vec<_> = errors
218            .iter()
219            .map(|e| {
220                let excerpt = e.found().unwrap_or_default();
221                (
222                    &excerpt[..excerpt.find(' ').unwrap()],
223                    e.reason().unwrap_or_default(),
224                )
225            })
226            .collect();
227        check!(
228            found
229                == [
230                    ("word", ""),
231                    ("(())", "unknown section"),
232                    ("(())", "unknown section")
233                ]
234        );
235        check!(errors.iter().all(|e| e.help().is_none()));
236    }
237
238    #[test]
239    fn check_stops_at_the_error_limit_with_correct_positions() {
240        // Counting lines again for each error took 21 s for this input.
241        let errors = parsers::check(&"x\n".repeat(100_000));
242        check!(errors.len() == MAX_ERRORS);
243        for (i, error) in errors.iter().enumerate() {
244            check!((error.line(), error.column(), error.offset()) == (i + 1, 1, 2 * i));
245        }
246    }
247
248    #[test]
249    fn check_agrees_with_from_str() {
250        let inputs = [
251            String::new(),
252            format!("{DOMAIN}\n{PROBLEM}"),
253            format!("{DOMAIN})"),
254            "(define (foo x))".into(),
255            "(define (domain".into(),
256            ") (define (domain d))".into(),
257            "(define (domain d) (:requirement :strips))".into(),
258            "(define (problem p) (:domain d) (:init (p) 1) (:goal (p)))".into(),
259            "(define (problem p) (:domain d) (:init))".into(),
260            "(".repeat(100),
261        ];
262        for input in inputs {
263            let first = PddlFile::from_str(&input).err();
264            let all = parsers::check(&input);
265            check!(all.first() == first.as_ref(), "{input:?}");
266        }
267    }
268
269    #[test]
270    fn parse_single_domain_and_problem() {
271        let input = r"
272            (define (domain briefcase-world)
273                (:requirements :strips)
274                (:predicates (at ?x))
275            )
276            (define (problem get-paid)
277                (:domain briefcase-world)
278                (:init (at home))
279                (:goal (at office))
280            )
281        ";
282
283        let pddl_file = PddlFile::from_str(input).unwrap();
284        check!(pddl_file.domain_count() == 1);
285        check!(pddl_file.problem_count() == 1);
286        check!(pddl_file.domains[0].name() == &Name::new("briefcase-world"));
287        check!(pddl_file.problems[0].name() == &Name::new("get-paid"));
288    }
289
290    #[test]
291    fn parse_two_domains_and_one_problem() {
292        let input = r"
293            (define (domain d1)
294                (:requirements :strips)
295                (:predicates (p))
296            )
297            (define (domain d2)
298                (:requirements :strips)
299                (:predicates (q))
300            )
301            (define (problem p1)
302                (:domain d1)
303                (:init)
304                (:goal (and))
305            )
306        ";
307
308        let pddl_file = PddlFile::from_str(input).unwrap();
309        check!(pddl_file.domain_count() == 2);
310        check!(pddl_file.problem_count() == 1);
311        check!(pddl_file.domains[0].name() == &Name::new("d1"));
312        check!(pddl_file.domains[1].name() == &Name::new("d2"));
313    }
314
315    #[test]
316    fn parse_one_domain_and_two_problems() {
317        let input = r"
318            (define (domain d1)
319                (:requirements :strips)
320                (:predicates (p))
321            )
322            (define (problem p1)
323                (:domain d1)
324                (:init)
325                (:goal (and))
326            )
327            (define (problem p2)
328                (:domain d1)
329                (:init)
330                (:goal (and))
331            )
332        ";
333
334        let pddl_file = PddlFile::from_str(input).unwrap();
335        check!(pddl_file.domain_count() == 1);
336        check!(pddl_file.problem_count() == 2);
337    }
338
339    #[test]
340    fn parse_mixed_order_problem_before_domain() {
341        let input = r"
342            (define (problem p1)
343                (:domain d1)
344                (:init)
345                (:goal (and))
346            )
347            (define (domain d1)
348                (:requirements :strips)
349                (:predicates (p))
350            )
351        ";
352
353        let pddl_file = PddlFile::from_str(input).unwrap();
354        check!(pddl_file.domain_count() == 1);
355        check!(pddl_file.problem_count() == 1);
356        // Problem comes first in the file
357        check!(pddl_file.problems[0].name() == &Name::new("p1"));
358        check!(pddl_file.domains[0].name() == &Name::new("d1"));
359    }
360
361    #[test]
362    fn parse_file_with_leading_comments() {
363        let input = r"
364            ; This is a comment
365            ; Another comment
366            (define (domain test)
367                (:requirements :strips)
368                (:predicates (p))
369            )
370        ";
371
372        let pddl_file = PddlFile::from_str(input).unwrap();
373        check!(pddl_file.domain_count() == 1);
374        check!(pddl_file.domains[0].name() == &Name::new("test"));
375    }
376
377    #[test]
378    fn parse_empty_file() {
379        let input = "";
380
381        let pddl_file = PddlFile::from_str(input).unwrap();
382        check!(pddl_file.is_empty());
383        check!(pddl_file.domain_count() == 0);
384        check!(pddl_file.problem_count() == 0);
385    }
386
387    #[test]
388    fn parse_file_with_only_whitespace_and_comments() {
389        let input = r"; Just a comment
390
391; Another comment
392";
393
394        let pddl_file = PddlFile::from_str(input).unwrap();
395        check!(pddl_file.is_empty());
396    }
397
398    #[test]
399    fn parse_using_parser_trait() {
400        let input = r"
401            (define (domain d1)
402                (:requirements :strips)
403                (:predicates (p))
404            )
405            (define (problem p1)
406                (:domain d1)
407                (:init)
408                (:goal (and))
409            )
410        ";
411
412        let pddl_file = PddlFile::from_str(input).unwrap();
413        check!(pddl_file.domain_count() == 1);
414        check!(pddl_file.problem_count() == 1);
415    }
416
417    #[test]
418    fn parse_domains_only() {
419        let input = r"
420            (define (domain d1)
421                (:requirements :strips)
422                (:predicates (p))
423            )
424            (define (domain d2)
425                (:requirements :strips)
426                (:predicates (q))
427            )
428        ";
429
430        let domains = PddlFile::from_str(input).unwrap().domains;
431        check!(domains.len() == 2);
432        check!(domains[0].name() == &Name::new("d1"));
433        check!(domains[1].name() == &Name::new("d2"));
434    }
435
436    #[test]
437    fn parse_problems_only() {
438        let input = r"
439            (define (problem p1)
440                (:domain d1)
441                (:init)
442                (:goal (and))
443            )
444            (define (problem p2)
445                (:domain d1)
446                (:init)
447                (:goal (and))
448            )
449        ";
450
451        let problems = PddlFile::from_str(input).unwrap().problems;
452        check!(problems.len() == 2);
453    }
454
455    #[test]
456    fn parse_rejects_malformed_define_block_after_valid_ones() {
457        let input = r"
458            (define (domain d1)
459                (:requirements :strips)
460                (:predicates (p))
461            )
462            (define (domain d2)
463                (:requirements
464            )
465        ";
466
467        let result = PddlFile::from_str(input);
468        check!(
469            result.is_err(),
470            "Should reject file with malformed define block after valid ones"
471        );
472    }
473
474    #[test]
475    fn doc_example_0() {
476        let input = r"
477            (define (domain briefcase-world)
478                (:requirements :strips)
479                (:predicates (at ?x))
480            )
481            (define (problem get-paid)
482                (:domain briefcase-world)
483                (:init (at home))
484                (:goal (at office))
485            )
486        ";
487
488        let pddl_file = PddlFile::from_str(input).unwrap();
489        check!(pddl_file.domain_count() == 1);
490        check!(pddl_file.problem_count() == 1);
491    }
492
493    #[test]
494    fn doc_example_1() {
495        let input = r"
496            (define (domain d1) (:requirements :strips) (:predicates (p)))
497            (define (domain d2) (:requirements :strips) (:predicates (q)))
498        ";
499
500        let domains = PddlFile::from_str(input).unwrap().domains;
501        check!(domains.len() == 2);
502    }
503
504    #[test]
505    fn doc_example_2() {
506        let input = r"
507            (define (problem p1) (:domain d) (:init) (:goal (and)))
508            (define (problem p2) (:domain d) (:init) (:goal (and)))
509        ";
510
511        let problems = PddlFile::from_str(input).unwrap().problems;
512        check!(problems.len() == 2);
513    }
514
515    #[test]
516    fn doc_example_3() {
517        let input = "; Uses (domain d)\n(define (problem q) (:domain d) (:init) (:goal (p)))";
518        check!(let Ok(Definition::Problem(_)) = Definition::from_str(input));
519
520        // A second definition is trailing input, not part of this one.
521        let two = "(define (domain d) (:predicates (p)))\n(define (domain e) (:predicates (q)))";
522        check!(Definition::from_str(two).is_err());
523    }
524
525    #[test]
526    fn doc_example_4() {
527        let input = r"
528            (define (domain briefcase-world)
529                (:requirements :strips)
530                (:predicates (at ?x))
531            )
532            (define (problem get-paid)
533                (:domain briefcase-world)
534                (:init (at home))
535                (:goal (at office))
536            )
537        ";
538
539        let pddl_file = PddlFile::from_str(input).unwrap();
540        check!(pddl_file.domain_count() == 1);
541        check!(pddl_file.problem_count() == 1);
542    }
543}