Skip to main content

pddl_core/parsers/expressions/
f_exp.rs

1//! Provides parsers for fluent expressions (`<f-exp>`).
2
3use crate::parsers::error::R;
4use crate::parsers::sexpr::Node;
5use crate::parsers::{alt, parens, parse_binary_op, parse_f_head, parse_number};
6use crate::types::{BinaryOp, FluentExpression, MultiOp};
7
8/// Parses a fluent expression (`<f-exp>`), i.e. `<number> | (<binary-op> <f-exp> <f-exp>)
9/// | (<multi-op> <f-exp> <f-exp>⁺) | (- <f-exp>) | <f-head>`.
10pub(crate) fn parse_f_exp(node: &Node) -> R<FluentExpression> {
11    alt(
12        node,
13        &[
14            &|n| parse_number(n).map(FluentExpression::new_number),
15            &|n| {
16                op_expr(
17                    n,
18                    parse_f_exp,
19                    FluentExpression::new_negative,
20                    FluentExpression::new_binary_op,
21                    FluentExpression::new_multi_op,
22                )
23            },
24            &|n| parse_f_head(n).map(FluentExpression::new_function),
25        ],
26    )
27}
28
29/// Parses an arithmetic expression `(<op> <arg>⁺)`: `-` with one argument is a
30/// negation, any operator with two is a binary operation, and `*` or `+` with
31/// more is a multi-operand operation.
32pub(crate) fn op_expr<'n, 'a, E>(
33    node: &'n Node<'a>,
34    arg: impl Fn(&'n Node<'a>) -> R<E>,
35    negative: fn(E) -> E,
36    binary: fn(BinaryOp, E, E) -> E,
37    multi: fn(MultiOp, E, Vec<E>) -> E,
38) -> R<E> {
39    parens(node, |args| {
40        let op_node = args.next()?;
41        let op = parse_binary_op(op_node)?;
42        let mut operands = args.list1(&arg)?;
43        match operands.len() {
44            1 if op == BinaryOp::Subtraction => Ok(negative(operands.remove(0))),
45            2 => {
46                let rhs = operands.remove(1);
47                let lhs = operands.remove(0);
48                Ok(binary(op, lhs, rhs))
49            }
50            3.. => {
51                let op = MultiOp::try_from(op).map_err(|_| op_node.error())?;
52                let rest = operands.split_off(1);
53                Ok(multi(op, operands.remove(0), rest))
54            }
55            _ => Err(op_node.error()),
56        }
57    })
58}
59
60crate::parsers::impl_parser!(FluentExpression => parse_f_exp);
61
62#[cfg(test)]
63mod tests {
64    use crate::parsers::UnwrapValue;
65    use assert2::check;
66
67    use crate::*;
68
69    #[test]
70    fn test_parse() {
71        check!(FluentExpression::from_str("1.23").is_value(FluentExpression::new_number(1.23)));
72
73        check!(FluentExpression::from_str("(+ 1.23 2.34)").is_value(
74            FluentExpression::new_binary_op(
75                BinaryOp::Addition,
76                FluentExpression::new_number(1.23),
77                FluentExpression::new_number(2.34)
78            )
79        ));
80
81        check!(FluentExpression::from_str("(+ 1.23 2.34 3.45)").is_value(
82            FluentExpression::new_multi_op(
83                MultiOp::Addition,
84                FluentExpression::new_number(1.23),
85                [
86                    FluentExpression::new_number(2.34),
87                    FluentExpression::new_number(3.45)
88                ]
89            )
90        ));
91
92        check!(
93            FluentExpression::from_str("(- 1.23)").is_value(FluentExpression::new_negative(
94                FluentExpression::new_number(1.23)
95            ))
96        );
97
98        check!(FluentExpression::from_str("(- 1.23 2.34)").is_value(
99            FluentExpression::new_binary_op(
100                BinaryOp::Subtraction,
101                FluentExpression::new_number(1.23),
102                FluentExpression::new_number(2.34)
103            )
104        ));
105
106        // Only `-` takes one argument, and only `+` and `*` take more than two.
107        check!(FluentExpression::from_str("(+ 1)").is_err());
108        check!(FluentExpression::from_str("(- 1 2 3)").is_err());
109        check!(FluentExpression::from_str("(/ 1 2 3)").is_err());
110
111        check!(
112            FluentExpression::from_str("fun-sym").is_value(FluentExpression::new_function(
113                FunctionHead::new(FunctionSymbol::new_string("fun-sym"))
114            ))
115        );
116    }
117
118    #[test]
119    fn nested_negation_parses_in_linear_time() {
120        // Trying each operator form in turn parsed the argument again for every
121        // form, about 3x work per level: depth 30 took hours.
122        let input = format!("{}x{}", "(- ".repeat(30), ")".repeat(30));
123        let start = std::time::Instant::now();
124        check!(FluentExpression::from_str(&input).is_ok());
125        check!(start.elapsed() < std::time::Duration::from_secs(1));
126    }
127
128    #[test]
129    fn doc_example_0() {
130        check!(FluentExpression::from_str("1.23").is_value(FluentExpression::new_number(1.23)));
131
132        check!(FluentExpression::from_str("(+ 1.23 2.34)").is_value(
133            FluentExpression::new_binary_op(
134                BinaryOp::Addition,
135                FluentExpression::new_number(1.23),
136                FluentExpression::new_number(2.34)
137            )
138        ));
139
140        check!(FluentExpression::from_str("(+ 1.23 2.34 3.45)").is_value(
141            FluentExpression::new_multi_op(
142                MultiOp::Addition,
143                FluentExpression::new_number(1.23),
144                [
145                    FluentExpression::new_number(2.34),
146                    FluentExpression::new_number(3.45)
147                ]
148            )
149        ));
150
151        check!(
152            FluentExpression::from_str("(- 1.23)").is_value(FluentExpression::new_negative(
153                FluentExpression::new_number(1.23)
154            ))
155        );
156
157        check!(
158            FluentExpression::from_str("fun-sym").is_value(FluentExpression::new_function(
159                FunctionHead::new(FunctionSymbol::new_string("fun-sym"))
160            ))
161        );
162    }
163
164    /// A space after an arithmetic operator is optional.
165    #[test]
166    fn operators_need_no_space_after_them() {
167        let x = || FluentExpression::new_function(FunctionHead::new(FunctionSymbol::from("x")));
168        check!(
169            FluentExpression::from_str("(+x 1)")
170                == Ok(FluentExpression::new_binary_op(
171                    BinaryOp::Addition,
172                    x(),
173                    FluentExpression::new_number(1)
174                ))
175        );
176        check!(FluentExpression::from_str("(-x)") == Ok(FluentExpression::new_negative(x())));
177    }
178}