Skip to main content

pddl_core/parsers/structure/
length_spec.rs

1//! Provides parsers for length specifications (`<length-spec>`).
2
3use crate::parsers::error::R;
4use crate::parsers::sexpr::Node;
5use crate::parsers::{prefix, Args};
6use crate::types::LengthSpec;
7
8/// Parses a length specification (`<length-spec>`), i.e. `(:length [(:serial <integer>)] [(:parallel <integer>)])`.
9///
10/// Deprecated since PDDL 2.1.
11pub(crate) fn parse_problem_length_spec(node: &Node) -> R<LengthSpec> {
12    prefix(node, ":length", |args| {
13        let serial = opt_limit(args, ":serial")?;
14        let parallel = opt_limit(args, ":parallel")?;
15        Ok(LengthSpec::new(serial, parallel))
16    })
17}
18
19/// Parses `(<keyword> <integer>)` if the next child starts with `keyword`.
20fn opt_limit(args: &mut Args, keyword: &'static str) -> R<Option<u64>> {
21    match args.peek() {
22        Some(node) if node.head().is_some_and(|h| h.eq_ignore_ascii_case(keyword)) => {
23            let node = args.next()?;
24            prefix(node, keyword, |args| {
25                let value = args.next()?;
26                value
27                    .atom()
28                    .filter(|a| a.bytes().all(|b| b.is_ascii_digit()))
29                    .and_then(|a| a.parse().ok())
30                    .ok_or_else(|| value.error())
31            })
32            .map(Some)
33        }
34        _ => Ok(None),
35    }
36}
37
38crate::parsers::impl_parser!(LengthSpec => parse_problem_length_spec);
39
40#[cfg(test)]
41mod tests {
42    use crate::parsers::UnwrapValue;
43    use assert2::check;
44
45    use crate::*;
46
47    #[test]
48    fn test_parse() {
49        check!(LengthSpec::from_str("(:length)").is_value(LengthSpec::default()));
50        check!(
51            LengthSpec::from_str("(:length (:serial 123))").is_value(LengthSpec::new_serial(123))
52        );
53        check!(
54            LengthSpec::from_str("(:length (:parallel 42))").is_value(LengthSpec::new_parallel(42))
55        );
56        check!(
57            LengthSpec::from_str("(:length (:serial 123) (:parallel 42))")
58                .is_value(LengthSpec::new(Some(123), Some(42)))
59        );
60    }
61
62    #[test]
63    fn doc_example_0() {
64        check!(LengthSpec::from_str("(:length)").is_value(LengthSpec::default()));
65        check!(
66            LengthSpec::from_str("(:length (:serial 123))").is_value(LengthSpec::new_serial(123))
67        );
68        check!(
69            LengthSpec::from_str("(:length (:parallel 42))").is_value(LengthSpec::new_parallel(42))
70        );
71        check!(
72            LengthSpec::from_str("(:length (:serial 123) (:parallel 42))")
73                .is_value(LengthSpec::new(Some(123), Some(42)))
74        );
75    }
76}