Skip to main content

pddl_validate/
plan.rs

1//! Plans and the plan file format.
2//!
3//! A plan file lists one ground action per step, as Fast Downward and most classical
4//! planners write it:
5//!
6//! ```text
7//! ; a comment
8//! (pick ball1 rooma left)
9//! (move rooma roomb)
10//! ; cost = 4 (general cost)
11//! ```
12//!
13//! Comments run from `;` to the end of the line, so cost lines are comments too and the
14//! validator computes the cost itself. Steps may share a line or span several. Names are
15//! case-insensitive and stored in ASCII lowercase.
16//!
17//! Temporal planners prefix each step with its start time and follow a durative action
18//! with its duration, as VAL reads them:
19//!
20//! ```text
21//! 0.000: (load p1 t1 depot) [2.000]
22//! 2.010: (drive t1 depot shop) [5.000]
23//! 7.020: (refuel t1)
24//! ```
25//!
26//! Times and durations are non-negative decimal numbers. Steps need not be sorted by
27//! time. A plan either times every step or none.
28
29use alloc::string::String;
30use alloc::vec::Vec;
31use core::fmt;
32use core::str::FromStr;
33
34use crate::atom::lower;
35
36/// A plan: ground actions, executed one after the other or, with timestamps, at the
37/// times given.
38#[derive(Debug, Clone, PartialEq, Default)]
39pub struct Plan {
40    /// The steps in execution order.
41    steps: Vec<PlanStep>,
42}
43
44impl Plan {
45    /// Builds a plan from steps.
46    #[must_use]
47    pub const fn new(steps: Vec<PlanStep>) -> Self {
48        Self { steps }
49    }
50
51    /// Returns the steps in execution order.
52    #[must_use]
53    pub fn steps(&self) -> &[PlanStep] {
54        &self.steps
55    }
56
57    /// Returns the number of steps.
58    #[must_use]
59    pub fn len(&self) -> usize {
60        self.steps.len()
61    }
62
63    /// Returns `true` for the empty plan, which is valid exactly when the initial state
64    /// satisfies the goal.
65    #[must_use]
66    pub fn is_empty(&self) -> bool {
67        self.steps.is_empty()
68    }
69}
70
71impl FromIterator<PlanStep> for Plan {
72    fn from_iter<T: IntoIterator<Item = PlanStep>>(iter: T) -> Self {
73        Self::new(iter.into_iter().collect())
74    }
75}
76
77impl FromStr for Plan {
78    type Err = PlanError;
79
80    /// Parses a plan file.
81    ///
82    /// # Errors
83    ///
84    /// Returns a [`PlanError`] with the line and column of the first problem; see
85    /// [`PlanErrorKind`] for the kinds.
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// use pddl_validate::Plan;
91    ///
92    /// let plan: Plan = "(move a b) ; first\n(MOVE b c)\n; cost = 2 (unit cost)".parse().unwrap();
93    /// assert_eq!(plan.len(), 2);
94    /// assert_eq!(plan.steps()[1].to_string(), "(move b c)");
95    /// assert_eq!(plan.steps()[1].line(), 2);
96    /// ```
97    fn from_str(text: &str) -> Result<Self, Self::Err> {
98        Scanner::new(text).plan()
99    }
100}
101
102/// One ground action of a plan, such as `(drive t1 home shop)`, with its start time
103/// and duration in a temporal plan.
104#[derive(Debug, Clone, PartialEq)]
105pub struct PlanStep {
106    /// The action name, in ASCII lowercase.
107    action: String,
108    /// The objects the action is applied to, in ASCII lowercase.
109    arguments: Vec<String>,
110    /// The 1-based line of the plan file the step starts on; 0 for a step built in code.
111    line: usize,
112    /// The start time, finite and non-negative; `None` in a sequential plan.
113    time: Option<f64>,
114    /// The duration of a durative action, finite and non-negative; `None` otherwise.
115    duration: Option<f64>,
116}
117
118impl PlanStep {
119    /// Builds a step, lowercasing the action and its arguments. Its [`line`](Self::line) is 0.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use pddl_validate::PlanStep;
125    ///
126    /// let step = PlanStep::new("Drive", ["t1", "home", "shop"]);
127    /// assert_eq!(step.to_string(), "(drive t1 home shop)");
128    /// ```
129    #[must_use]
130    pub fn new<S, I, A>(action: S, arguments: I) -> Self
131    where
132        S: AsRef<str>,
133        I: IntoIterator<Item = A>,
134        A: AsRef<str>,
135    {
136        Self {
137            action: lower(action.as_ref()),
138            arguments: arguments.into_iter().map(|a| lower(a.as_ref())).collect(),
139            line: 0,
140            time: None,
141            duration: None,
142        }
143    }
144
145    /// Returns the step starting at `time`, for a temporal plan.
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use pddl_validate::PlanStep;
151    ///
152    /// let step = PlanStep::new("drive", ["t1"]).at(1.5).lasting(2.0);
153    /// assert_eq!((step.time(), step.duration()), (Some(1.5), Some(2.0)));
154    /// ```
155    #[must_use]
156    pub const fn at(mut self, time: f64) -> Self {
157        self.time = Some(time);
158        self
159    }
160
161    /// Returns the step with a duration, for a durative action.
162    #[must_use]
163    pub const fn lasting(mut self, duration: f64) -> Self {
164        self.duration = Some(duration);
165        self
166    }
167
168    /// Returns the start time, or `None` in a sequential plan.
169    #[must_use]
170    pub const fn time(&self) -> Option<f64> {
171        self.time
172    }
173
174    /// Returns the duration, or `None` if the plan gives none.
175    #[must_use]
176    pub const fn duration(&self) -> Option<f64> {
177        self.duration
178    }
179
180    /// Returns the action name, in ASCII lowercase.
181    #[must_use]
182    pub fn action(&self) -> &str {
183        &self.action
184    }
185
186    /// Returns the arguments, in ASCII lowercase.
187    #[must_use]
188    pub fn arguments(&self) -> &[String] {
189        &self.arguments
190    }
191
192    /// Returns the 1-based line the step starts on in its plan file, or 0 if it was built
193    /// in code.
194    #[must_use]
195    pub const fn line(&self) -> usize {
196        self.line
197    }
198}
199
200impl fmt::Display for PlanStep {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        write!(f, "({}", self.action)?;
203        for argument in &self.arguments {
204            write!(f, " {argument}")?;
205        }
206
207        f.write_str(")")
208    }
209}
210
211/// Why a plan file could not be read, and where.
212#[derive(Debug, Clone, PartialEq, Eq)]
213#[non_exhaustive]
214pub struct PlanError {
215    /// The 1-based line of the problem.
216    pub line: usize,
217    /// The 1-based column of the problem, counted in characters.
218    pub column: usize,
219    /// What is wrong.
220    pub kind: PlanErrorKind,
221}
222
223/// The kinds of [`PlanError`].
224#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub enum PlanErrorKind {
227    /// A `(` without its `)` before the end of the file.
228    Unclosed,
229    /// A `)` without a matching `(`.
230    Unopened,
231    /// A `(` inside a step. Steps are flat lists of names.
232    Nested,
233    /// A step `()` without an action name.
234    EmptyStep,
235    /// Text outside parentheses that is neither whitespace, a comment, a timestamp nor a
236    /// duration.
237    UnexpectedText(String),
238    /// A timestamp (`0.5:`) without a step after it.
239    DanglingTimestamp,
240    /// A `[` without its `]`, or a duration that is not one number.
241    MalformedDuration,
242    /// A time or duration that is not a finite, non-negative number.
243    InvalidNumber(String),
244}
245
246impl fmt::Display for PlanError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        write!(f, "line {}, column {}: ", self.line, self.column)?;
249        match &self.kind {
250            PlanErrorKind::Unclosed => f.write_str("`(` is never closed"),
251            PlanErrorKind::Unopened => f.write_str("`)` has no matching `(`"),
252            PlanErrorKind::Nested => f.write_str("a step cannot contain `(`"),
253            PlanErrorKind::EmptyStep => f.write_str("a step needs an action name"),
254            PlanErrorKind::UnexpectedText(text) => {
255                write!(f, "unexpected `{text}` outside a step")
256            }
257            PlanErrorKind::DanglingTimestamp => f.write_str("a timestamp needs a step after it"),
258            PlanErrorKind::MalformedDuration => {
259                f.write_str("a duration is one number in `[` and `]`")
260            }
261            PlanErrorKind::InvalidNumber(text) => {
262                write!(f, "`{text}` is not a finite, non-negative number")
263            }
264        }
265    }
266}
267
268impl core::error::Error for PlanError {}
269
270/// A position in the plan text.
271#[derive(Debug, Clone, Copy)]
272struct Position {
273    /// The 1-based line.
274    line: usize,
275    /// The 1-based column, in characters.
276    column: usize,
277}
278
279/// A single-pass, non-recursive reader of plan files.
280///
281/// It never indexes into the text, so no input can make it panic, and it keeps no stack,
282/// so no nesting depth can overflow one.
283struct Scanner<'t> {
284    /// The remaining characters.
285    chars: core::iter::Peekable<core::str::Chars<'t>>,
286    /// The position of the next character.
287    at: Position,
288}
289
290impl<'t> Scanner<'t> {
291    /// Starts reading `text`, skipping a leading byte order mark.
292    fn new(text: &'t str) -> Self {
293        let text = text.strip_prefix('\u{feff}').unwrap_or(text);
294        Self {
295            chars: text.chars().peekable(),
296            at: Position { line: 1, column: 1 },
297        }
298    }
299
300    /// Reads the whole plan.
301    fn plan(mut self) -> Result<Plan, PlanError> {
302        let mut steps = Vec::new();
303        while let Some(c) = self.skip_blank() {
304            let start = self.at;
305            match c {
306                '(' => {
307                    self.bump();
308                    let step = self.step(start)?;
309                    steps.push(self.duration(step)?);
310                }
311                ')' => return Err(error(start, PlanErrorKind::Unopened)),
312                _ => {
313                    let time = self.timestamp(start)?;
314                    let at = self.at;
315                    if self.skip_blank() != Some('(') {
316                        return Err(error(at, PlanErrorKind::DanglingTimestamp));
317                    }
318
319                    let step_start = self.at;
320                    self.bump();
321                    let step = self.step(step_start)?.at(time);
322                    steps.push(self.duration(step)?);
323                }
324            }
325        }
326
327        Ok(Plan::new(steps))
328    }
329
330    /// Reads a timestamp such as `0.500:`.
331    fn timestamp(&mut self, start: Position) -> Result<f64, PlanError> {
332        let mut word = self.word();
333        if word.is_empty() {
334            // A lone `[` or `]`, which `word` does not consume.
335            word.extend(self.chars.next());
336        }
337
338        let Some(number) = word.strip_suffix(':') else {
339            return Err(error(start, PlanErrorKind::UnexpectedText(word)));
340        };
341
342        number_at(start, number)
343    }
344
345    /// Reads an optional `[duration]` after a step and attaches it.
346    fn duration(&mut self, step: PlanStep) -> Result<PlanStep, PlanError> {
347        if self.skip_blank() != Some('[') {
348            return Ok(step);
349        }
350
351        let start = self.at;
352        self.bump();
353        if self.skip_blank().is_none() {
354            return Err(error(start, PlanErrorKind::MalformedDuration));
355        }
356
357        let number_start = self.at;
358        let word = self.word();
359        let duration = number_at(number_start, &word)?;
360        if self.skip_blank() != Some(']') {
361            return Err(error(start, PlanErrorKind::MalformedDuration));
362        }
363
364        self.bump();
365        Ok(step.lasting(duration))
366    }
367
368    /// Reads the names of a step after its `(`, through its `)`.
369    fn step(&mut self, start: Position) -> Result<PlanStep, PlanError> {
370        let mut names = Vec::new();
371        loop {
372            match self.skip_blank() {
373                None => return Err(error(start, PlanErrorKind::Unclosed)),
374                Some(')') => {
375                    self.bump();
376                    break;
377                }
378                Some('(') => return Err(error(self.at, PlanErrorKind::Nested)),
379                Some(c @ ('[' | ']')) => {
380                    let kind = PlanErrorKind::UnexpectedText(String::from(c));
381                    return Err(error(self.at, kind));
382                }
383                Some(_) => names.push(lower(&self.word())),
384            }
385        }
386
387        let mut names = names.into_iter();
388        let action = names
389            .next()
390            .ok_or_else(|| error(start, PlanErrorKind::EmptyStep))?;
391
392        Ok(PlanStep {
393            action,
394            arguments: names.collect(),
395            line: start.line,
396            time: None,
397            duration: None,
398        })
399    }
400
401    /// Skips whitespace and comments and returns the next character without consuming it.
402    fn skip_blank(&mut self) -> Option<char> {
403        loop {
404            let c = *self.chars.peek()?;
405            if c == ';' {
406                while self.chars.peek().is_some_and(|&c| c != '\n' && c != '\r') {
407                    self.bump();
408                }
409            } else if c.is_whitespace() {
410                self.bump();
411            } else {
412                return Some(c);
413            }
414        }
415    }
416
417    /// Reads a run of characters up to whitespace, a parenthesis or a comment.
418    fn word(&mut self) -> String {
419        let mut word = String::new();
420        while let Some(&c) = self.chars.peek() {
421            if c.is_whitespace() || matches!(c, '(' | ')' | ';' | '[' | ']') {
422                break;
423            }
424
425            word.push(c);
426            self.bump();
427        }
428
429        word
430    }
431
432    /// Consumes one character and advances the position. A `\r\n` pair, a lone `\r` and a
433    /// lone `\n` each end one line.
434    fn bump(&mut self) {
435        match self.chars.next() {
436            Some('\r') if self.chars.peek() == Some(&'\n') => {}
437            Some('\n' | '\r') => {
438                self.at.line += 1;
439                self.at.column = 1;
440            }
441            Some(_) => self.at.column += 1,
442            None => {}
443        }
444    }
445}
446
447/// Builds a [`PlanError`] at `at`.
448const fn error(at: Position, kind: PlanErrorKind) -> PlanError {
449    PlanError {
450        line: at.line,
451        column: at.column,
452        kind,
453    }
454}
455
456/// Parses a time or duration written at `at`.
457fn number_at(at: Position, text: &str) -> Result<f64, PlanError> {
458    match text.parse::<f64>() {
459        Ok(value) if value.is_finite() && value >= 0.0 => Ok(value),
460        _ => Err(error(at, PlanErrorKind::InvalidNumber(String::from(text)))),
461    }
462}