Skip to main content

pddl_core/parsers/actions/
action_def.rs

1//! Provides parsers for action definitions (`<action-def>`).
2
3use crate::parsers::error::R;
4use crate::parsers::sexpr::Node;
5use crate::parsers::{
6    empty_or, keyword_arg, opt_keyword_arg, parse_action_symbol, parse_da_effect, parse_effect,
7    parse_pre_gd, prefix, typed_variables,
8};
9use crate::types::{ActionDefinition, DurativeActionEffect, ProcessDefinition};
10
11/// Parses an action definition (`<action-def>`), i.e. `(:action <action-symbol> :parameters (<typed list (variable)>)
12/// [:precondition <pre-GD>] [:effect <effect>])`. `()` stands for no precondition or effect.
13pub(crate) fn parse_action_def(node: &Node) -> R<ActionDefinition> {
14    parse_action_like(node, ":action")
15}
16
17/// Parses a PDDL+ event definition, i.e. `(:event <name> :parameters (<typed list (variable)>)
18/// [:precondition <pre-GD>] [:effect <effect>])`, which has the form of an action.
19pub(crate) fn parse_event_def(node: &Node) -> R<ActionDefinition> {
20    parse_action_like(node, ":event")
21}
22
23/// Parses a PDDL+ process definition, i.e. `(:process <name> :parameters (<typed list (variable)>)
24/// [:precondition <pre-GD>] [:effect <da-effect>])`. The effect is read like a durative
25/// action's, so its continuous effects keep `#t`, but it may contain only continuous effects
26/// such as `(increase (height) (* #t (velocity)))`: a timed `(at <time-specifier> ...)`
27/// effect is an error, and so is `when`, whose condition a `<da-effect>` reads as timed.
28pub(crate) fn parse_process_def(node: &Node) -> R<ProcessDefinition> {
29    prefix(node, ":process", |args| {
30        let symbol = parse_action_symbol(args.next()?)?;
31        let parameters = keyword_arg(args, ":parameters", typed_variables)?;
32        let precondition = opt_keyword_arg(args, ":precondition", |n| empty_or(n, parse_pre_gd))?;
33        let effect = opt_keyword_arg(args, ":effect", |n| empty_or(n, parse_process_effect))?;
34        args.reject_misspelled(&[":precondition", ":effect"])?;
35        Ok(ProcessDefinition::new(
36            symbol,
37            parameters,
38            precondition.flatten().into(),
39            effect.flatten(),
40        ))
41    })
42}
43
44/// Parses a process's effect: a `<da-effect>` made of continuous effects only.
45fn parse_process_effect(node: &Node) -> R<DurativeActionEffect> {
46    let effect = parse_da_effect(node)?;
47    reject_timed_effects(node)?;
48    Ok(effect)
49}
50
51/// Fails at the first `(at <time-specifier> ...)` or `(when ...)` effect in the parsed
52/// `<da-effect>` `node`, looking through `and` and `forall`; what remains are continuous
53/// effects. A `when` fails as a whole: in a `<da-effect>` its condition is a timed
54/// `<da-GD>`, and a process has no start or end for it to refer to.
55fn reject_timed_effects(node: &Node) -> R<()> {
56    let children = node.children().unwrap_or_default();
57    let effects = match node.head().map(str::to_ascii_lowercase).as_deref() {
58        Some("and") => children.get(1..),
59        Some("forall") => children.get(2..),
60        Some("at" | "when") => {
61            let reason = "a process allows only continuous effects";
62            return Err(node.error().reason(reason).fatal());
63        }
64        _ => None,
65    };
66
67    effects
68        .unwrap_or_default()
69        .iter()
70        .try_for_each(reject_timed_effects)
71}
72
73/// Parses `(<keyword> <name> :parameters ... [:precondition ...] [:effect ...])`, the
74/// form actions and events share.
75fn parse_action_like(node: &Node, keyword: &'static str) -> R<ActionDefinition> {
76    prefix(node, keyword, |args| {
77        let symbol = parse_action_symbol(args.next()?)?;
78        let parameters = keyword_arg(args, ":parameters", typed_variables)?;
79        let precondition = opt_keyword_arg(args, ":precondition", |n| empty_or(n, parse_pre_gd))?;
80        let effect = opt_keyword_arg(args, ":effect", |n| empty_or(n, parse_effect))?;
81        args.reject_misspelled(&[":precondition", ":effect"])?;
82        Ok(ActionDefinition::new(
83            symbol,
84            parameters,
85            precondition.flatten().into(),
86            effect.flatten(),
87        ))
88    })
89}
90
91crate::parsers::impl_parser!(ActionDefinition => parse_action_def);
92crate::parsers::impl_parser!(ProcessDefinition => parse_process_def);
93
94#[cfg(test)]
95mod tests {
96    use crate::parsers::UnwrapValue;
97    use assert2::check;
98
99    use crate::*;
100
101    #[test]
102    fn test_parse() {
103        let input = r"(:action take-out
104                            :parameters (?x - physob)
105                            :precondition (not (= ?x B))
106                            :effect (not (in ?x))
107                        )";
108
109        let action = ActionDefinition::from_str(input).unwrap();
110
111        check!(
112            action
113                == ActionDefinition::new(
114                    ActionSymbol::string("take-out"),
115                    TypedList::from_iter([Variable::new_string("x").to_typed("physob")]),
116                    PreconditionGoalDescriptions::from_str("(not (= ?x B))").unwrap(),
117                    Some(Effects::from_str("(not (in ?x))").unwrap())
118                )
119        );
120    }
121
122    #[test]
123    fn doc_example_0() {
124        let input = r"(:action take-out
125                            :parameters (?x - physob)
126                            :precondition (not (= ?x B))
127                            :effect (not (in ?x))
128                        )";
129
130        let action = ActionDefinition::from_str(input);
131
132        check!(action.is_value(ActionDefinition::new(
133            ActionSymbol::string("take-out"),
134            TypedList::from_iter([Variable::new_string("x").to_typed("physob")]),
135            PreconditionGoalDescriptions::from(PreconditionGoalDescription::Preference(
136                PreferenceGoalDescription::from_gd(GoalDescription::new_not(
137                    GoalDescription::AtomicFormula(AtomicFormula::new_equality(
138                        Term::Variable(Variable::new_string("x")),
139                        Term::Name(Name::new("B"))
140                    ))
141                ))
142            )),
143            Some(Effects::new(ConditionalEffect::new_primitive_effect(
144                PrimitiveEffect::NotAtomicFormula(AtomicFormula::new_predicate(
145                    Predicate::new_string("in"),
146                    vec![Term::Variable(Variable::new_string("x"))]
147                ))
148            )))
149        )));
150    }
151
152    #[test]
153    fn doc_example_1() {
154        let input = r"(:action take-out
155                            :parameters (?x - physob)
156                            :precondition (not (= ?x B))
157                            :effect (not (in ?x))
158                        )";
159
160        let action = ActionDefinition::from_str(input).unwrap();
161
162        check!(
163            action
164                == ActionDefinition::new(
165                    ActionSymbol::string("take-out"),
166                    TypedList::from_iter([Variable::new_string("x").to_typed("physob")]),
167                    PreconditionGoalDescriptions::from_str("(not (= ?x B))").unwrap(),
168                    Some(Effects::from_str("(not (in ?x))").unwrap())
169                )
170        );
171    }
172
173    #[test]
174    fn parses_pddl_plus_processes_and_events() {
175        let process = ProcessDefinition::from_str(
176            "(:process fall :parameters (?b - ball)
177               :precondition (falling ?b)
178               :effect (and (increase (height ?b) (* #t (velocity ?b)))
179                            (increase (velocity ?b) (* #t 9.8))))",
180        )
181        .unwrap();
182        check!(process.symbol() == &ActionSymbol::string("fall"));
183        check!(process.parameters().len() == 1);
184        check!(process.precondition().len() == 1);
185        assert2::assert!(let Some(DurativeActionEffect::All(effects)) = process.effect());
186        check!(effects.len() == 2);
187        check!(let DurativeActionEffect::Timed(TimedEffect::ContinuousEffect(..)) = &effects[0]);
188
189        let event = StructureDef::from_str(
190            "(:event bounce :parameters (?b - ball)
191               :precondition (and (falling ?b) (<= (height ?b) 0))
192               :effect (assign (velocity ?b) (* 0.8 (velocity ?b))))",
193        );
194        check!(let Ok(StructureDef::Event(_)) = event);
195
196        let without_effect = StructureDef::from_str("(:process idle :parameters ())").unwrap();
197        assert2::assert!(let StructureDef::Process(idle) = without_effect.clone());
198        let idle = *idle;
199        check!(idle.effect().is_none());
200        check!(idle.precondition().is_empty());
201        let symbol: &ActionSymbol = idle.as_ref();
202        check!(symbol == &ActionSymbol::string("idle"));
203        check!(StructureDef::from(idle) == without_effect);
204
205        check!(ProcessDefinition::from_str("(:action a :parameters ())").is_err());
206    }
207    /// The parse error of a discrete effect in a process.
208    const ONLY_CONTINUOUS: &str = "a process allows only continuous effects";
209
210    /// A process has only continuous effects, so a timed `at` effect anywhere in it,
211    /// also inside `and`, `forall` or `when`, is a parse error at that effect.
212    #[test]
213    fn process_rejects_timed_effects() {
214        let cases = [
215            "(:process fall :parameters (?b) :effect (at end (p)))",
216            "(:process fall :parameters (?b) :effect (and (increase (h) (* #t 1)) (at start (p))))",
217            "(:process fall :parameters (?b) :effect (forall (?x) (at end (increase (h) 1))))",
218        ];
219        for input in cases {
220            let error = ProcessDefinition::from_str(input).unwrap_err();
221            check!(error.reason() == Some(ONLY_CONTINUOUS), "{input}");
222            check!(input[error.offset()..].starts_with("(at "), "{input}");
223        }
224
225        // A `when` condition would be timed, so `when` fails as a whole, also around a
226        // continuous effect.
227        let conditional = [
228            "(:process fall :parameters (?b) :effect (when (at start (q)) (at end (p))))",
229            "(:process fall :parameters (?b)
230                :effect (forall (?x) (when (at start (q)) (decrease (h ?x) (* #t 2)))))",
231            "(:process fall :parameters (?b)
232                :effect (and (increase (h) (* #t 1)) (when (over all (q)) (increase (h) (* #t 2)))))",
233        ];
234        for input in conditional {
235            let error = ProcessDefinition::from_str(input).unwrap_err();
236            check!(error.reason() == Some(ONLY_CONTINUOUS), "{input}");
237            check!(input[error.offset()..].starts_with("(when "), "{input}");
238        }
239
240        let continuous = "(:process fall :parameters (?b)
241            :effect (forall (?x) (and (decrease (h ?x) (* #t 2)) (increase (t) #t))))";
242        check!(ProcessDefinition::from_str(continuous).is_ok());
243    }
244}