pddl_parser/domain/
action.rs

1use nom::branch::alt;
2use nom::combinator::map;
3use nom::IResult;
4use serde::{Deserialize, Serialize};
5
6use super::durative_action::DurativeAction;
7use super::expression::Expression;
8use super::simple_action::SimpleAction;
9use crate::domain::typed_parameter::TypedParameter;
10use crate::error::ParserError;
11use crate::lexer::TokenStream;
12
13/// Enum to represent either an `Action` or a `DurativeAction`.
14#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub enum Action {
16    /// An Action wrapper around a simple action. See [`SimpleAction`](../simple_action/struct.SimpleAction.html).
17    Simple(SimpleAction),
18    /// An Action wrapper around a durative action. See [`DurativeAction`](../durative_action/struct.DurativeAction.html).
19    Durative(DurativeAction),
20}
21
22impl From<SimpleAction> for Action {
23    fn from(action: SimpleAction) -> Self {
24        Self::Simple(action)
25    }
26}
27
28impl From<DurativeAction> for Action {
29    fn from(action: DurativeAction) -> Self {
30        Self::Durative(action)
31    }
32}
33
34impl Action {
35    /// Get the name of the action. This is the same as the name of the simple or durative action.
36    pub fn name(&self) -> &str {
37        match self {
38            Self::Simple(action) => &action.name,
39            Self::Durative(action) => &action.name,
40        }
41    }
42
43    /// Get the parameters of the action. This is the same as the parameters of the simple or durative action.
44    pub fn parameters(&self) -> &[TypedParameter] {
45        match self {
46            Self::Simple(action) => &action.parameters,
47            Self::Durative(action) => &action.parameters,
48        }
49    }
50
51    /// Get the precondition of the action. This is the same as the precondition of the simple or durative action.
52    pub fn precondition(&self) -> Option<Expression> {
53        match self {
54            Self::Simple(action) => action.precondition.clone(),
55            Self::Durative(action) => action.condition.clone(),
56        }
57    }
58
59    /// Get the effect of the action. This is the same as the effect of the simple or durative action.
60    pub fn effect(&self) -> Expression {
61        match self {
62            Self::Simple(action) => action.effect.clone(),
63            Self::Durative(action) => action.effect.clone(),
64        }
65    }
66
67    /// Parse an action from a token stream.
68    pub fn parse(input: TokenStream) -> IResult<TokenStream, Action, ParserError> {
69        alt((
70            map(SimpleAction::parse, Self::Simple),
71            map(DurativeAction::parse, Self::Durative),
72        ))(input)
73    }
74
75    /// Convert the action to PDDL.
76    pub fn to_pddl(&self) -> String {
77        match self {
78            Self::Simple(action) => action.to_pddl(),
79            Self::Durative(action) => action.to_pddl(),
80        }
81    }
82}