Skip to main content

pddl_validate/
report.rs

1//! The result of validating a plan: verdict, diagnostic and execution trace.
2
3use alloc::format;
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6use core::fmt;
7
8use crate::atom::Atom;
9use crate::ValidationStatus;
10
11/// What [`Validator::validate`](crate::Validator::validate) found.
12#[derive(Debug, Clone, PartialEq)]
13pub struct Report {
14    /// The verdict, with its diagnostic.
15    outcome: Outcome,
16    /// What each executed step changed, in order.
17    trace: Vec<StepTrace>,
18    /// The value of the problem's metric in the final state of a valid plan; `None` if the
19    /// problem has none or its value is undefined.
20    metric: Option<Metric>,
21}
22
23impl Report {
24    /// Builds a report without a metric value.
25    pub(crate) const fn new(outcome: Outcome, trace: Vec<StepTrace>) -> Self {
26        Self {
27            outcome,
28            trace,
29            metric: None,
30        }
31    }
32
33    /// Adds the metric value.
34    pub(crate) const fn with_metric(mut self, metric: Metric) -> Self {
35        self.metric = Some(metric);
36        self
37    }
38
39    /// Returns the value of the problem's `:metric` in the final state, for a valid plan
40    /// of a problem that has one.
41    ///
42    /// `None` if the plan is not valid, if the problem has no metric, or if its value is
43    /// undefined in the final state (it reads a fluent without a value, divides by zero
44    /// or leaves the finite range); an undefined metric does not make the plan invalid.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use pddl::{Domain, Optimization, Parser, Problem};
50    /// use pddl_validate::Validator;
51    ///
52    /// let domain = Domain::from_str("(define (domain d) (:requirements :action-costs)
53    ///     (:predicates (done)) (:functions (total-cost) - number)
54    ///     (:action work :parameters () :effect (and (done) (increase (total-cost) 2.5))))").unwrap();
55    /// let problem = Problem::from_str("(define (problem p) (:domain d)
56    ///     (:init (= (total-cost) 0)) (:goal (done)) (:metric minimize (total-cost)))").unwrap();
57    /// let report = Validator::new(&domain, &problem).unwrap().validate_text("(work) (work)");
58    /// let metric = report.metric().unwrap();
59    /// assert_eq!((metric.optimization, metric.value), (Optimization::Minimize, 5.0));
60    /// ```
61    #[must_use]
62    pub const fn metric(&self) -> Option<&Metric> {
63        self.metric.as_ref()
64    }
65
66    /// Returns the verdict.
67    #[must_use]
68    pub const fn status(&self) -> ValidationStatus {
69        match self.outcome {
70            Outcome::Valid => ValidationStatus::Valid,
71            Outcome::Invalid(_) => ValidationStatus::Invalid,
72            Outcome::Unsupported(_) => ValidationStatus::Unsupported,
73        }
74    }
75
76    /// Returns the verdict with its diagnostic.
77    #[must_use]
78    pub const fn outcome(&self) -> &Outcome {
79        &self.outcome
80    }
81
82    /// Returns why the plan is invalid, or `None` if it is not.
83    #[must_use]
84    pub const fn violation(&self) -> Option<&Violation> {
85        match &self.outcome {
86            Outcome::Invalid(violation) => Some(violation),
87            _ => None,
88        }
89    }
90
91    /// Returns the construct the validator cannot interpret, or `None` if there is none.
92    #[must_use]
93    pub const fn unsupported(&self) -> Option<&Unsupported> {
94        match &self.outcome {
95            Outcome::Unsupported(unsupported) => Some(unsupported),
96            _ => None,
97        }
98    }
99
100    /// Returns what each step changed, for the steps that were applied.
101    ///
102    /// A valid sequential plan has one entry per step, a valid temporal plan one per
103    /// happening. An invalid plan has entries up to the failing step or happening. An
104    /// unsupported one has none.
105    #[must_use]
106    pub fn trace(&self) -> &[StepTrace] {
107        &self.trace
108    }
109}
110
111/// The verdict of a [`Report`], with its diagnostic.
112#[derive(Debug, Clone, PartialEq)]
113#[non_exhaustive]
114pub enum Outcome {
115    /// Every step is applicable and the final state satisfies the goal.
116    Valid,
117    /// The first violation found. Validation stops there, as VAL's does.
118    Invalid(Violation),
119    /// A construct the validator does not interpret. The plan is neither accepted nor
120    /// rejected.
121    Unsupported(Unsupported),
122}
123
124/// Why a plan is invalid.
125#[derive(Debug, Clone, PartialEq)]
126#[non_exhaustive]
127pub struct Violation {
128    /// The step that fails, or `None` if the plan text or the goal does.
129    pub step: Option<StepRef>,
130    /// What fails.
131    pub kind: ViolationKind,
132}
133
134impl Violation {
135    /// Returns a repair hint in the style of VAL's "Plan Repair Advice".
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use pddl::{Domain, Parser, Problem};
141    /// use pddl_validate::Validator;
142    ///
143    /// let domain = Domain::from_str("(define (domain d) (:predicates (p) (q))
144    ///     (:action a :parameters () :precondition (p) :effect (q)))").unwrap();
145    /// let problem = Problem::from_str("(define (problem x) (:domain d) (:init) (:goal (q)))").unwrap();
146    /// let report = Validator::new(&domain, &problem).unwrap().validate_text("(a)");
147    /// let advice = report.violation().unwrap().advice();
148    /// assert_eq!(advice, "(a) has an unsatisfied precondition at step 1: (Set (p) to true)");
149    /// ```
150    #[must_use]
151    pub fn advice(&self) -> String {
152        let at = |step: &StepRef| format!("{} at step {}", step.action, step.number);
153        match (&self.kind, &self.step) {
154            (ViolationKind::PreconditionUnsatisfied(unmet), Some(step)) => format!(
155                "{} has an unsatisfied precondition at step {}: {}",
156                step.action,
157                step.number,
158                unmet.advice()
159            ),
160            (ViolationKind::StartConditionUnsatisfied(unmet), Some(step)) => format!(
161                "{} has an unsatisfied condition at start at step {}: {}",
162                step.action,
163                step.number,
164                unmet.advice()
165            ),
166            (ViolationKind::EndConditionUnsatisfied(unmet), Some(step)) => format!(
167                "{} has an unsatisfied condition at end at step {}: {}",
168                step.action,
169                step.number,
170                unmet.advice()
171            ),
172            (ViolationKind::InvariantViolated { time, unmet }, Some(step)) => format!(
173                "{} has an unsatisfied invariant at time {time} (step {}): {}",
174                step.action,
175                step.number,
176                unmet.advice()
177            ),
178            (ViolationKind::DurationConstraint(unmet), Some(step)) => {
179                format!("Choose a duration for {} that satisfies {unmet}", at(step))
180            }
181            (ViolationKind::SelfOverlap { other }, Some(step)) => {
182                format!("Start {} after step {other} ends", at(step))
183            }
184            (ViolationKind::Interference { other, .. }, Some(step)) => format!(
185                "Move {} at least epsilon away from {other}, or reorder them",
186                at(step)
187            ),
188            (ViolationKind::GoalUnsatisfied(unmet), _) => {
189                format!("The goal is not satisfied: {}", unmet.advice())
190            }
191            (ViolationKind::UnknownAction(_), Some(step)) => {
192                format!("Replace {}: the domain has no such action", at(step))
193            }
194            (ViolationKind::Arity { expected, .. }, Some(step)) => {
195                format!("Give {} exactly {expected} arguments", at(step))
196            }
197            (ViolationKind::UnknownObject { object, .. }, Some(step)) => {
198                format!("Declare `{object}` or replace it in {}", at(step))
199            }
200            (
201                ViolationKind::TypeMismatch {
202                    parameter,
203                    expected,
204                    ..
205                },
206                Some(step),
207            ) => format!(
208                "Pass an object of type `{expected}` for ?{parameter} in {}",
209                at(step)
210            ),
211            (ViolationKind::PlanSyntax(_), _) => "Fix the plan file".to_string(),
212            (ViolationKind::Undefined(fluent), _) => {
213                format!("(Give {fluent} a value in :init or an earlier step)")
214            }
215            (kind, Some(step)) => format!("{kind} in {}", at(step)),
216            (kind, None) => kind.to_string(),
217        }
218    }
219}
220
221impl fmt::Display for Violation {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        if let Some(step) = &self.step {
224            write!(f, "step {} {}: ", step.number, step.action)?;
225        }
226
227        write!(f, "{}", self.kind)
228    }
229}
230
231/// A step of the plan, as diagnostics name it.
232#[derive(Debug, Clone, PartialEq)]
233#[non_exhaustive]
234pub struct StepRef {
235    /// The 1-based position of the step in the plan, as VAL counts.
236    pub number: usize,
237    /// The 1-based line of the plan file the step starts on; 0 for a plan built in code.
238    pub line: usize,
239    /// The step as written, in lowercase, such as `(drive t1 home shop)`.
240    pub action: String,
241    /// The start time of the step in a temporal plan; `None` in a sequential one.
242    pub time: Option<f64>,
243}
244
245/// The kinds of [`Violation`]. All names are in ASCII lowercase.
246#[derive(Debug, Clone, PartialEq)]
247#[non_exhaustive]
248pub enum ViolationKind {
249    /// The plan text cannot be read.
250    PlanSyntax(crate::PlanError),
251    /// The step names an action the domain does not define.
252    UnknownAction(String),
253    /// The step passes the wrong number of arguments.
254    Arity {
255        /// The number of parameters of the action.
256        expected: usize,
257        /// The number of arguments of the step.
258        found: usize,
259    },
260    /// The step passes an object that neither the domain nor the problem declares.
261    UnknownObject {
262        /// The parameter it is passed for, without `?`.
263        parameter: String,
264        /// The undeclared object.
265        object: String,
266    },
267    /// The step passes an object of the wrong type.
268    TypeMismatch {
269        /// The parameter it is passed for, without `?`.
270        parameter: String,
271        /// The object passed.
272        object: String,
273        /// The declared type of the parameter, such as `truck` or `(either car truck)`.
274        expected: String,
275    },
276    /// The precondition does not hold in the state before the step.
277    PreconditionUnsatisfied(Unmet),
278    /// The final state does not satisfy the goal.
279    GoalUnsatisfied(Unmet),
280    /// An effect, or a condition whose truth value depends on it, reads a numeric fluent
281    /// that has no value.
282    Undefined(Atom),
283    /// The rendered expression divides by zero.
284    DivisionByZero(String),
285    /// The rendered expression has no finite value.
286    NonFinite(String),
287    /// The step updates the fluent with `assign`, `scale-up` or `scale-down` together
288    /// with another update, so the result would depend on their order.
289    ConflictingUpdates(Atom),
290    /// A timestamped plan has a step without a timestamp.
291    MissingTimestamp,
292    /// A durative action has no `[duration]`.
293    MissingDuration,
294    /// An instantaneous action has a `[duration]`.
295    UnexpectedDuration,
296    /// The duration is not positive (at most 1e-9), not finite, or rounds away when added
297    /// to a huge start time.
298    NonPositiveDuration(f64),
299    /// A start or end time that is negative or not finite.
300    InvalidTime(f64),
301    /// The duration violates the action's `:duration` constraint; `left` is the duration.
302    DurationConstraint(Unmet),
303    /// The step runs while an earlier step of the same action with the same arguments
304    /// still runs. Following the formal semantics of PDDL 2.1 the validator is built on
305    /// (Abdulaziz and Koller, 2022), a ground durative action must not overlap itself:
306    /// its end could belong to either start.
307    SelfOverlap {
308        /// The 1-based number of the other step, as [`StepRef::number`].
309        other: usize,
310    },
311    /// An `at start` condition does not hold when the action starts.
312    StartConditionUnsatisfied(Unmet),
313    /// An `at end` condition does not hold when the action ends.
314    EndConditionUnsatisfied(Unmet),
315    /// An `over all` condition fails at `time`, strictly between the action's start and
316    /// end.
317    InvariantViolated {
318        /// A time at which the condition fails.
319        time: f64,
320        /// What fails then.
321        unmet: Unmet,
322    },
323    /// The event interferes with another one at the same time or less than the
324    /// separation `epsilon` apart (PDDL 2.1 mutex): one changes what the other reads or
325    /// changes.
326    Interference {
327        /// What this step does then: `start`, `end` or `apply`.
328        event: String,
329        /// The other event, such as `end of (drive t1 a b) (step 2)` or
330        /// `timed literal (open shop)`.
331        other: String,
332        /// The time of this event.
333        time: f64,
334        /// The time between the two events, smaller than `epsilon`.
335        separation: f64,
336    },
337    /// PDDL+ events kept triggering each other at `time`: after `limit` rounds of firing,
338    /// one was still enabled, typically an event whose effect leaves its own precondition
339    /// true.
340    EventCascade {
341        /// When the cascade happened.
342        time: f64,
343        /// The number of rounds fired.
344        limit: usize,
345    },
346}
347
348impl fmt::Display for ViolationKind {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self {
351            Self::PlanSyntax(error) => write!(f, "cannot read the plan: {error}"),
352            Self::UnknownAction(name) => write!(f, "unknown action `{name}`"),
353            Self::Arity { expected, found } => {
354                write!(f, "expected {expected} arguments, found {found}")
355            }
356            Self::UnknownObject { parameter, object } => {
357                write!(f, "unknown object `{object}` for ?{parameter}")
358            }
359            Self::TypeMismatch {
360                parameter,
361                object,
362                expected,
363            } => write!(
364                f,
365                "`{object}` is not of type `{expected}`, as ?{parameter} requires"
366            ),
367            Self::PreconditionUnsatisfied(unmet) => {
368                write!(f, "unsatisfied precondition: {unmet}")
369            }
370            Self::GoalUnsatisfied(unmet) => write!(f, "goal not satisfied: {unmet}"),
371            Self::Undefined(fluent) => write!(f, "{fluent} is undefined"),
372            Self::DivisionByZero(exp) => write!(f, "{exp} divides by zero"),
373            Self::NonFinite(exp) => write!(f, "{exp} has no finite value"),
374            Self::ConflictingUpdates(fluent) => {
375                write!(f, "{fluent} is updated twice in incompatible ways")
376            }
377            Self::MissingTimestamp => f.write_str("the plan is timed but this step has no time"),
378            Self::MissingDuration => f.write_str("a durative action needs a [duration]"),
379            Self::UnexpectedDuration => {
380                f.write_str("an instantaneous action cannot have a [duration]")
381            }
382            Self::NonPositiveDuration(d) => {
383                write!(f, "the duration {d} is not a positive, finite number")
384            }
385            Self::InvalidTime(t) => write!(f, "the time {t} is not a non-negative, finite number"),
386            Self::DurationConstraint(unmet) => {
387                write!(f, "the duration violates {unmet}")
388            }
389            Self::SelfOverlap { other } => {
390                write!(
391                    f,
392                    "overlaps step {other}, the same action with the same arguments"
393                )
394            }
395            Self::StartConditionUnsatisfied(unmet) => {
396                write!(f, "unsatisfied condition at start: {unmet}")
397            }
398            Self::EndConditionUnsatisfied(unmet) => {
399                write!(f, "unsatisfied condition at end: {unmet}")
400            }
401            Self::InvariantViolated { time, unmet } => {
402                write!(f, "invariant violated at time {time}: {unmet}")
403            }
404            Self::EventCascade { time, limit } => {
405                write!(
406                    f,
407                    "events still trigger at time {time} after {limit} rounds"
408                )
409            }
410            Self::Interference {
411                event,
412                other,
413                time,
414                separation,
415            } => write!(
416                f,
417                "{event} at time {time} interferes with {other} {separation} apart"
418            ),
419        }
420    }
421}
422
423/// The part of a condition that does not hold, as specific as the condition allows.
424///
425/// A conjunction reports its first failing conjunct, a universal quantifier its first
426/// failing instance. A disjunction or existential quantifier has no single culprit and
427/// reports [`Unmet::NoneOf`] with each alternative.
428#[derive(Debug, Clone, PartialEq)]
429#[non_exhaustive]
430pub enum Unmet {
431    /// A ground atom has the wrong truth value.
432    Atom {
433        /// The atom.
434        atom: Atom,
435        /// The truth value the condition needs.
436        expected: bool,
437        /// `true` if the atom is a derived predicate, so its rule decides its value.
438        derived: bool,
439    },
440    /// An equality `(= a b)` has the wrong truth value.
441    Equality {
442        /// The left object.
443        left: String,
444        /// The right object.
445        right: String,
446        /// `true` if the condition needs the objects to be the same.
447        expected: bool,
448    },
449    /// A numeric comparison has the wrong truth value.
450    Comparison {
451        /// The comparison, ground, such as `(>= (fuel t1) 5)`.
452        condition: String,
453        /// The value of the left side.
454        left: f64,
455        /// The value of the right side.
456        right: f64,
457        /// The truth value the condition needs.
458        expected: bool,
459    },
460    /// No alternative of a disjunction, existential quantifier or implication holds.
461    NoneOf {
462        /// The condition, ground as far as the enclosing bindings go.
463        condition: String,
464        /// Why each alternative fails, at most [`MAX_ALTERNATIVES`] of them.
465        alternatives: Vec<Unmet>,
466        /// The number of failing alternatives left out of `alternatives`.
467        omitted: usize,
468    },
469}
470
471/// The most alternatives an [`Unmet::NoneOf`] lists. An existential quantifier over many
472/// objects would otherwise list every one of them.
473pub const MAX_ALTERNATIVES: usize = 8;
474
475impl Unmet {
476    /// Returns a repair hint, such as `(Set (at t1 shop) to true)`.
477    #[must_use]
478    pub fn advice(&self) -> String {
479        match self {
480            Self::Atom {
481                atom,
482                expected,
483                derived: false,
484            } => format!("(Set {atom} to {expected})"),
485            Self::Atom {
486                atom,
487                expected,
488                derived: true,
489            } => format!("(Make the rule of derived {atom} yield {expected})"),
490            Self::Equality {
491                left,
492                right,
493                expected: true,
494            } => format!("(Use the same object for {left} and {right})"),
495            Self::Equality {
496                left,
497                expected: false,
498                ..
499            } => format!("(Use different objects instead of {left} twice)"),
500            Self::Comparison {
501                condition,
502                left,
503                right,
504                expected,
505            } => format!("(Make {condition} {expected}: the sides are {left} and {right})"),
506            Self::NoneOf { alternatives, .. } if alternatives.is_empty() => {
507                String::from("(No binding exists; declare a matching object)")
508            }
509            Self::NoneOf { alternatives, .. } => {
510                let hints: Vec<String> = alternatives.iter().map(Self::advice).collect();
511                format!("one of: {}", hints.join(" or "))
512            }
513        }
514    }
515}
516
517impl fmt::Display for Unmet {
518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519        match self {
520            Self::Atom {
521                atom,
522                expected: true,
523                ..
524            } => write!(f, "{atom}"),
525            Self::Atom { atom, .. } => write!(f, "(not {atom})"),
526            Self::Equality {
527                left,
528                right,
529                expected: true,
530            } => write!(f, "(= {left} {right})"),
531            Self::Equality { left, right, .. } => write!(f, "(not (= {left} {right}))"),
532            Self::Comparison {
533                condition,
534                expected: true,
535                ..
536            }
537            | Self::NoneOf { condition, .. } => write!(f, "{condition}"),
538            Self::Comparison { condition, .. } => write!(f, "(not {condition})"),
539        }
540    }
541}
542
543/// The ground changes one step made to the state.
544#[derive(Debug, Clone, PartialEq, Default)]
545#[non_exhaustive]
546pub struct StepTrace {
547    /// The step, in a sequential plan.
548    pub step: Option<StepRef>,
549    /// The time of the happening, in a temporal plan.
550    pub time: Option<f64>,
551    /// The events of the happening, in a temporal plan, such as `start (drive t1 a b)`,
552    /// in plan order.
553    pub events: Vec<String>,
554    /// Atoms that were false and are true after the step, sorted.
555    pub added: Vec<Atom>,
556    /// Atoms that were true and are false after the step, sorted.
557    pub deleted: Vec<Atom>,
558    /// The numeric fluents the step updated, sorted.
559    pub numeric: Vec<FluentChange>,
560}
561
562/// A numeric fluent a step updated.
563#[derive(Debug, Clone, PartialEq)]
564#[non_exhaustive]
565pub struct FluentChange {
566    /// The fluent, such as `(total-cost)`.
567    pub fluent: Atom,
568    /// The value before the step; `None` if it was undefined.
569    pub before: Option<f64>,
570    /// The value after the step.
571    pub after: f64,
572}
573
574/// The value of the problem's `:metric` for a valid plan.
575#[derive(Debug, Clone, Copy, PartialEq)]
576#[non_exhaustive]
577pub struct Metric {
578    /// Whether the problem minimizes or maximizes the metric.
579    pub optimization: pddl::Optimization,
580    /// The value in the final state.
581    pub value: f64,
582}
583
584/// A construct the validator does not interpret, and where it is.
585#[derive(Debug, Clone, PartialEq, Eq)]
586#[non_exhaustive]
587pub struct Unsupported {
588    /// The construct.
589    pub construct: Construct,
590    /// Where it is, such as ``action `drive` `` or `plan`.
591    pub location: String,
592}
593
594impl Unsupported {
595    /// Builds a finding at `location`.
596    pub(crate) fn new(construct: Construct, location: impl Into<String>) -> Self {
597        Self {
598            construct,
599            location: location.into(),
600        }
601    }
602}
603
604impl fmt::Display for Unsupported {
605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606        write!(f, "{}: {} are not supported", self.location, self.construct)
607    }
608}
609
610/// The PDDL constructs the validator does not interpret yet.
611#[derive(Debug, Clone, PartialEq, Eq)]
612#[non_exhaustive]
613pub enum Construct {
614    /// A requirement flag the `pddl` parser does not know.
615    UnknownRequirement(String),
616    /// PDDL 1.2 `:extends`.
617    DomainExtension,
618    /// PDDL 1.2 `:timeless` facts.
619    Timeless,
620    /// Continuous change whose rate depends on a continuously changing fluent, or an
621    /// `over all` condition that is not linear in time (level 4 dynamics).
622    NonlinearDynamics,
623    /// Derived predicates in a temporal plan, whose interference this validator does not
624    /// decide.
625    DerivedPredicatesInTemporalPlans,
626    /// A conditional effect of a durative action with an `over all` condition, or with an
627    /// `at end` condition on an `at start` effect.
628    TimedEffectConditions,
629    /// An assignment nested inside a numeric expression of a durative action.
630    NestedAssignments,
631    /// A PDDL+ process effect that is not continuous, such as `(at start ...)` or `when`.
632    DiscreteProcessEffects,
633    /// PDDL+ dynamics that switch processes or fire events without end, such as a
634    /// process that turns itself off and on again at one instant (Zeno behaviour).
635    /// Also reported when legal dynamics need more than the validator's segment limit
636    /// (100 000 process switches or event firings between two plan happenings), so a
637    /// very busy model is unsupported rather than validated.
638    ZenoDynamics,
639    /// State-trajectory constraints.
640    Constraints,
641    /// Preferences, and `is-violated` in a metric.
642    Preferences,
643    /// Object-valued fluents.
644    ObjectFluents,
645    /// Derived predicates that depend on their own negation, so no stratification exists.
646    UnstratifiedDerivedPredicates,
647    /// Effects on `=`. The static check rejects them as malformed, so validation never
648    /// meets one; should it, the plan is not accepted.
649    EqualityEffects,
650}
651
652impl fmt::Display for Construct {
653    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
654        match self {
655            Self::UnknownRequirement(name) => write!(f, "requirements like `{name}`"),
656            Self::DomainExtension => f.write_str("domain extensions"),
657            Self::Timeless => f.write_str("timeless facts"),
658            Self::NonlinearDynamics => f.write_str("nonlinear continuous dynamics"),
659            Self::DerivedPredicatesInTemporalPlans => {
660                f.write_str("derived predicates in temporal plans")
661            }
662            Self::TimedEffectConditions => {
663                f.write_str("these timed conditions of conditional effects")
664            }
665            Self::NestedAssignments => f.write_str("nested assignments"),
666            Self::DiscreteProcessEffects => f.write_str("discrete effects of processes"),
667            Self::ZenoDynamics => f.write_str("dynamics that switch without end"),
668            Self::Constraints => f.write_str("constraints"),
669            Self::Preferences => f.write_str("preferences"),
670            Self::ObjectFluents => f.write_str("object fluents"),
671            Self::UnstratifiedDerivedPredicates => {
672                f.write_str("derived predicates that depend on their own negation")
673            }
674            Self::EqualityEffects => f.write_str("effects on `=`"),
675        }
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    //! Pins the exact text of every diagnostic, as users read it.
682
683    use alloc::string::ToString;
684    use alloc::vec;
685
686    use super::*;
687    use crate::Plan;
688
689    /// Returns step 3, `(drive t1 a b)`, of a sequential plan.
690    fn step() -> StepRef {
691        StepRef {
692            number: 3,
693            line: 0,
694            action: "(drive t1 a b)".to_string(),
695            time: None,
696        }
697    }
698
699    /// Returns the unmet atom `(at t1 a)`, which needs to be true.
700    fn at() -> Unmet {
701        Unmet::Atom {
702            atom: Atom::new("at", ["t1", "a"]),
703            expected: true,
704            derived: false,
705        }
706    }
707
708    /// Returns the syntax error of the plan text `(a`.
709    #[expect(
710        clippy::expect_used,
711        reason = "a test fails loudly on a broken fixture"
712    )]
713    fn syntax_error() -> crate::PlanError {
714        "(a".parse::<Plan>().expect_err("`(a` is not closed")
715    }
716
717    /// Returns the advice for `kind`, tied to [`step`] when `with_step` holds.
718    fn advice(kind: ViolationKind, with_step: bool) -> String {
719        let step = with_step.then(step);
720        Violation { step, kind }.advice()
721    }
722
723    #[test]
724    fn report_accessors_match_the_outcome() {
725        let unsupported = Unsupported::new(Construct::Constraints, "problem");
726        let report = Report::new(Outcome::Unsupported(unsupported.clone()), vec![]);
727        assert_eq!(report.status(), ValidationStatus::Unsupported);
728        assert_eq!(report.unsupported(), Some(&unsupported));
729        assert_eq!(report.violation(), None);
730        assert_eq!(report.outcome(), &Outcome::Unsupported(unsupported));
731
732        let report = Report::new(Outcome::Valid, vec![]);
733        assert_eq!(report.unsupported(), None);
734        assert_eq!(report.violation(), None);
735    }
736
737    #[test]
738    fn violation_kinds_display_their_diagnostic() {
739        let atom = Atom::new("fuel", ["t1"]);
740        let cases = [
741            (
742                ViolationKind::PlanSyntax(syntax_error()),
743                "cannot read the plan: line 1, column 1: `(` is never closed",
744            ),
745            (
746                ViolationKind::UnknownAction("fly".to_string()),
747                "unknown action `fly`",
748            ),
749            (
750                ViolationKind::Arity {
751                    expected: 2,
752                    found: 1,
753                },
754                "expected 2 arguments, found 1",
755            ),
756            (
757                ViolationKind::UnknownObject {
758                    parameter: "t".to_string(),
759                    object: "t9".to_string(),
760                },
761                "unknown object `t9` for ?t",
762            ),
763            (
764                ViolationKind::TypeMismatch {
765                    parameter: "t".to_string(),
766                    object: "home".to_string(),
767                    expected: "truck".to_string(),
768                },
769                "`home` is not of type `truck`, as ?t requires",
770            ),
771            (
772                ViolationKind::Undefined(atom.clone()),
773                "(fuel t1) is undefined",
774            ),
775            (
776                ViolationKind::DivisionByZero("(/ 1 (fuel t1))".to_string()),
777                "(/ 1 (fuel t1)) divides by zero",
778            ),
779            (
780                ViolationKind::NonFinite("(* 1e308 10)".to_string()),
781                "(* 1e308 10) has no finite value",
782            ),
783            (
784                ViolationKind::ConflictingUpdates(atom),
785                "(fuel t1) is updated twice in incompatible ways",
786            ),
787            (
788                ViolationKind::MissingTimestamp,
789                "the plan is timed but this step has no time",
790            ),
791            (
792                ViolationKind::MissingDuration,
793                "a durative action needs a [duration]",
794            ),
795            (
796                ViolationKind::UnexpectedDuration,
797                "an instantaneous action cannot have a [duration]",
798            ),
799            (
800                ViolationKind::NonPositiveDuration(-1.5),
801                "the duration -1.5 is not a positive, finite number",
802            ),
803            (
804                ViolationKind::InvalidTime(-2.0),
805                "the time -2 is not a non-negative, finite number",
806            ),
807            (
808                ViolationKind::SelfOverlap { other: 1 },
809                "overlaps step 1, the same action with the same arguments",
810            ),
811            (
812                ViolationKind::Interference {
813                    event: "start".to_string(),
814                    other: "end of (load t1) (step 2)".to_string(),
815                    time: 4.0,
816                    separation: 0.0,
817                },
818                "start at time 4 interferes with end of (load t1) (step 2) 0 apart",
819            ),
820            (
821                ViolationKind::EventCascade {
822                    time: 2.5,
823                    limit: 1000,
824                },
825                "events still trigger at time 2.5 after 1000 rounds",
826            ),
827        ];
828
829        for (kind, text) in cases {
830            assert_eq!(kind.to_string(), text);
831        }
832    }
833
834    #[test]
835    fn condition_violations_display_the_unmet_part() {
836        let cases = [
837            (
838                ViolationKind::PreconditionUnsatisfied(at()),
839                "unsatisfied precondition: (at t1 a)",
840            ),
841            (
842                ViolationKind::GoalUnsatisfied(at()),
843                "goal not satisfied: (at t1 a)",
844            ),
845            (
846                ViolationKind::DurationConstraint(at()),
847                "the duration violates (at t1 a)",
848            ),
849            (
850                ViolationKind::StartConditionUnsatisfied(at()),
851                "unsatisfied condition at start: (at t1 a)",
852            ),
853            (
854                ViolationKind::EndConditionUnsatisfied(at()),
855                "unsatisfied condition at end: (at t1 a)",
856            ),
857            (
858                ViolationKind::InvariantViolated {
859                    time: 1.5,
860                    unmet: at(),
861                },
862                "invariant violated at time 1.5: (at t1 a)",
863            ),
864        ];
865
866        for (kind, text) in cases {
867            assert_eq!(kind.to_string(), text);
868        }
869    }
870
871    #[test]
872    fn violation_display_names_the_step() {
873        let violation = Violation {
874            step: Some(step()),
875            kind: ViolationKind::MissingDuration,
876        };
877        assert_eq!(
878            violation.to_string(),
879            "step 3 (drive t1 a b): a durative action needs a [duration]"
880        );
881    }
882
883    #[test]
884    fn step_violations_advise_a_repair() {
885        let cases = [
886            (
887                ViolationKind::StartConditionUnsatisfied(at()),
888                "(drive t1 a b) has an unsatisfied condition at start at step 3: \
889                 (Set (at t1 a) to true)",
890            ),
891            (
892                ViolationKind::EndConditionUnsatisfied(at()),
893                "(drive t1 a b) has an unsatisfied condition at end at step 3: \
894                 (Set (at t1 a) to true)",
895            ),
896            (
897                ViolationKind::InvariantViolated {
898                    time: 1.5,
899                    unmet: at(),
900                },
901                "(drive t1 a b) has an unsatisfied invariant at time 1.5 (step 3): \
902                 (Set (at t1 a) to true)",
903            ),
904            (
905                ViolationKind::DurationConstraint(at()),
906                "Choose a duration for (drive t1 a b) at step 3 that satisfies (at t1 a)",
907            ),
908            (
909                ViolationKind::SelfOverlap { other: 1 },
910                "Start (drive t1 a b) at step 3 after step 1 ends",
911            ),
912            (
913                ViolationKind::Interference {
914                    event: "start".to_string(),
915                    other: "timed literal (open shop)".to_string(),
916                    time: 4.0,
917                    separation: 0.0,
918                },
919                "Move (drive t1 a b) at step 3 at least epsilon away from \
920                 timed literal (open shop), or reorder them",
921            ),
922            (
923                ViolationKind::UnknownAction("fly".to_string()),
924                "Replace (drive t1 a b) at step 3: the domain has no such action",
925            ),
926            (
927                ViolationKind::Arity {
928                    expected: 2,
929                    found: 1,
930                },
931                "Give (drive t1 a b) at step 3 exactly 2 arguments",
932            ),
933            (
934                ViolationKind::UnknownObject {
935                    parameter: "t".to_string(),
936                    object: "t9".to_string(),
937                },
938                "Declare `t9` or replace it in (drive t1 a b) at step 3",
939            ),
940            (
941                ViolationKind::TypeMismatch {
942                    parameter: "t".to_string(),
943                    object: "home".to_string(),
944                    expected: "truck".to_string(),
945                },
946                "Pass an object of type `truck` for ?t in (drive t1 a b) at step 3",
947            ),
948            (
949                ViolationKind::Undefined(Atom::new("fuel", ["t1"])),
950                "(Give (fuel t1) a value in :init or an earlier step)",
951            ),
952            (
953                ViolationKind::MissingDuration,
954                "a durative action needs a [duration] in (drive t1 a b) at step 3",
955            ),
956        ];
957
958        for (kind, text) in cases {
959            assert_eq!(advice(kind, true), text);
960        }
961    }
962
963    #[test]
964    fn plan_wide_violations_advise_a_repair() {
965        assert_eq!(
966            advice(ViolationKind::PlanSyntax(syntax_error()), false),
967            "Fix the plan file"
968        );
969        assert_eq!(
970            advice(ViolationKind::GoalUnsatisfied(at()), false),
971            "The goal is not satisfied: (Set (at t1 a) to true)"
972        );
973        assert_eq!(
974            advice(
975                ViolationKind::EventCascade {
976                    time: 2.5,
977                    limit: 1000
978                },
979                false
980            ),
981            "events still trigger at time 2.5 after 1000 rounds"
982        );
983    }
984
985    #[test]
986    fn unmet_conditions_display_and_advise() {
987        let derived = Unmet::Atom {
988            atom: Atom::new("reachable", ["a"]),
989            expected: false,
990            derived: true,
991        };
992        let same = Unmet::Equality {
993            left: "a".to_string(),
994            right: "b".to_string(),
995            expected: true,
996        };
997        let different = Unmet::Equality {
998            left: "a".to_string(),
999            right: "a".to_string(),
1000            expected: false,
1001        };
1002        let comparison = Unmet::Comparison {
1003            condition: "(>= (fuel t1) 5)".to_string(),
1004            left: 2.0,
1005            right: 5.0,
1006            expected: true,
1007        };
1008        let negated = Unmet::Comparison {
1009            condition: "(>= (fuel t1) 5)".to_string(),
1010            left: 7.0,
1011            right: 5.0,
1012            expected: false,
1013        };
1014        let none = Unmet::NoneOf {
1015            condition: "(exists (?t - truck) (at ?t a))".to_string(),
1016            alternatives: vec![],
1017            omitted: 0,
1018        };
1019        let either = Unmet::NoneOf {
1020            condition: "(or (at t1 a) (reachable a))".to_string(),
1021            alternatives: vec![at(), same.clone()],
1022            omitted: 0,
1023        };
1024
1025        let cases = [
1026            (
1027                derived,
1028                "(not (reachable a))",
1029                "(Make the rule of derived (reachable a) yield false)",
1030            ),
1031            (same, "(= a b)", "(Use the same object for a and b)"),
1032            (
1033                different,
1034                "(not (= a a))",
1035                "(Use different objects instead of a twice)",
1036            ),
1037            (
1038                comparison,
1039                "(>= (fuel t1) 5)",
1040                "(Make (>= (fuel t1) 5) true: the sides are 2 and 5)",
1041            ),
1042            (
1043                negated,
1044                "(not (>= (fuel t1) 5))",
1045                "(Make (>= (fuel t1) 5) false: the sides are 7 and 5)",
1046            ),
1047            (
1048                none,
1049                "(exists (?t - truck) (at ?t a))",
1050                "(No binding exists; declare a matching object)",
1051            ),
1052            (
1053                either,
1054                "(or (at t1 a) (reachable a))",
1055                "one of: (Set (at t1 a) to true) or (Use the same object for a and b)",
1056            ),
1057        ];
1058
1059        for (unmet, text, hint) in cases {
1060            assert_eq!(
1061                (unmet.to_string(), unmet.advice()),
1062                (text.to_string(), hint.to_string())
1063            );
1064        }
1065    }
1066
1067    #[test]
1068    fn constructs_display_their_name() {
1069        let cases = [
1070            (
1071                Construct::UnknownRequirement(":fancy".to_string()),
1072                "requirements like `:fancy`",
1073            ),
1074            (Construct::DomainExtension, "domain extensions"),
1075            (Construct::Timeless, "timeless facts"),
1076            (
1077                Construct::NonlinearDynamics,
1078                "nonlinear continuous dynamics",
1079            ),
1080            (
1081                Construct::DerivedPredicatesInTemporalPlans,
1082                "derived predicates in temporal plans",
1083            ),
1084            (
1085                Construct::TimedEffectConditions,
1086                "these timed conditions of conditional effects",
1087            ),
1088            (Construct::NestedAssignments, "nested assignments"),
1089            (
1090                Construct::DiscreteProcessEffects,
1091                "discrete effects of processes",
1092            ),
1093            (Construct::ZenoDynamics, "dynamics that switch without end"),
1094            (Construct::Constraints, "constraints"),
1095            (Construct::Preferences, "preferences"),
1096            (Construct::ObjectFluents, "object fluents"),
1097            (
1098                Construct::UnstratifiedDerivedPredicates,
1099                "derived predicates that depend on their own negation",
1100            ),
1101            (Construct::EqualityEffects, "effects on `=`"),
1102        ];
1103
1104        for (construct, text) in cases {
1105            assert_eq!(construct.to_string(), text);
1106        }
1107
1108        assert_eq!(
1109            Unsupported::new(Construct::Timeless, "domain").to_string(),
1110            "domain: timeless facts are not supported"
1111        );
1112    }
1113}