pddl_parser/plan/
durative_action.rs

1use std::fmt::Display;
2
3use nom::sequence::{delimited, pair, terminated, tuple};
4use nom::IResult;
5use serde::{Deserialize, Serialize};
6
7use crate::domain::parameter::Parameter;
8use crate::error::ParserError;
9use crate::lexer::{Token, TokenStream};
10use crate::tokens;
11use crate::tokens::id;
12
13/// A durative action is an action that has a duration.
14#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, PartialOrd)]
15pub struct DurativeAction {
16    /// The name of the action.
17    pub name: String,
18    /// The parameters of the action.
19    #[serde(default)]
20    pub parameters: Vec<Parameter>,
21    /// The duration of the action.
22    pub duration: f64,
23    /// The condition of the action.
24    pub timestamp: f64,
25}
26
27impl DurativeAction {
28    /// Create a new durative action. This is the same as the simple action, but with a duration and a timestamp.
29    ///
30    /// # Arguments
31    ///
32    /// * `name` - The name of the action.
33    /// * `parameters` - The parameters of the action.
34    /// * `duration` - The duration of the action. This is the time it takes for the action to complete.
35    /// * `timestamp` - The timestamp of the action. This is the time at which the action starts.
36    pub const fn new(name: String, parameters: Vec<Parameter>, duration: f64, timestamp: f64) -> Self {
37        Self {
38            name,
39            parameters,
40            duration,
41            timestamp,
42        }
43    }
44
45    /// Parse a durative action from a token stream.
46    pub fn parse(input: TokenStream) -> IResult<TokenStream, Self, ParserError> {
47        let (output, (timestamp, (name, parameters), duration)) = tuple((
48            terminated(tokens::float, Token::Colon),
49            delimited(
50                Token::OpenParen,
51                pair(id, Parameter::parse_parameters),
52                Token::CloseParen,
53            ),
54            delimited(Token::OpenBracket, tokens::float, Token::CloseBracket),
55        ))(input)?;
56        Ok((output, Self::new(name, parameters, duration, timestamp)))
57    }
58}
59
60impl Display for DurativeAction {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(
63            f,
64            "({} {})",
65            self.name,
66            self.parameters
67                .iter()
68                .map(ToString::to_string)
69                .collect::<Vec<_>>()
70                .join(" ")
71        )
72    }
73}