Skip to main content

pddl_core/pretty_print/
gd.rs

1//! Pretty-printing of goal descriptions, preferences and constraints.
2
3use crate::pretty_print::{sealed, PrettyRenderer};
4use crate::types::{
5    ConstraintGoalDescription, ConstraintGoalDescriptionInner, GoalDescription,
6    PreconditionGoalDescription, PreconditionGoalDescriptions, Preference,
7    PreferenceConstraintGoalDescription, PreferenceConstraintGoalDescriptions,
8    PreferenceGoalDescription,
9};
10use crate::visitor::{Accept, Visitor};
11use pretty::RcDoc;
12
13impl sealed::Sealed for GoalDescription {}
14impl sealed::Sealed for PreconditionGoalDescription {}
15impl sealed::Sealed for PreconditionGoalDescriptions {}
16impl sealed::Sealed for PreferenceGoalDescription {}
17impl sealed::Sealed for Preference {}
18impl sealed::Sealed for PreferenceConstraintGoalDescription {}
19impl sealed::Sealed for PreferenceConstraintGoalDescriptions {}
20impl sealed::Sealed for ConstraintGoalDescription {}
21impl sealed::Sealed for ConstraintGoalDescriptionInner {}
22
23impl Visitor<GoalDescription, RcDoc<'static>> for PrettyRenderer {
24    fn visit(&self, value: &GoalDescription) -> RcDoc<'static> {
25        match value {
26            GoalDescription::AtomicFormula(af) => af.accept(self),
27            GoalDescription::Literal(lit) => lit.accept(self),
28            GoalDescription::And(items) => {
29                if items.is_empty() {
30                    RcDoc::text("(and)")
31                } else {
32                    self.sexpr("and", items.iter().map(|gd| self.visit(gd)))
33                }
34            }
35            GoalDescription::Or(items) => {
36                if items.is_empty() {
37                    RcDoc::text("(or)")
38                } else {
39                    self.sexpr("or", items.iter().map(|gd| self.visit(gd)))
40                }
41            }
42            GoalDescription::Not(gd) => self.sexpr("not", [self.visit(&**gd)]),
43            GoalDescription::Imply(a, b) => {
44                self.sexpr("imply", [self.visit(&**a), self.visit(&**b)])
45            }
46            GoalDescription::Exists(vars, body) => self.sexpr(
47                "exists",
48                [
49                    RcDoc::text("(").append(vars.accept(self)).append(")"),
50                    self.visit(&**body),
51                ],
52            ),
53            GoalDescription::ForAll(vars, body) => self.sexpr(
54                "forall",
55                [
56                    RcDoc::text("(").append(vars.accept(self)).append(")"),
57                    self.visit(&**body),
58                ],
59            ),
60            GoalDescription::FluentComparison(fc) => fc.accept(self),
61        }
62    }
63}
64
65impl Visitor<PreconditionGoalDescription, RcDoc<'static>> for PrettyRenderer {
66    fn visit(&self, value: &PreconditionGoalDescription) -> RcDoc<'static> {
67        match value {
68            PreconditionGoalDescription::Preference(pref_gd) => self.visit(pref_gd),
69            PreconditionGoalDescription::Forall(vars, gds) => self.sexpr(
70                "forall",
71                [
72                    RcDoc::text("(").append(vars.accept(self)).append(")"),
73                    RcDoc::intersperse(gds.iter().map(|gd| self.visit(gd)), RcDoc::softline()),
74                ],
75            ),
76        }
77    }
78}
79
80impl Visitor<PreconditionGoalDescriptions, RcDoc<'static>> for PrettyRenderer {
81    fn visit(&self, value: &PreconditionGoalDescriptions) -> RcDoc<'static> {
82        if value.is_empty() {
83            RcDoc::text("(and)")
84        } else if value.len() == 1 {
85            value[0].accept(self)
86        } else {
87            self.sexpr("and", value.iter().map(|gd| self.visit(gd)))
88        }
89    }
90}
91
92impl Visitor<PreferenceGoalDescription, RcDoc<'static>> for PrettyRenderer {
93    fn visit(&self, value: &PreferenceGoalDescription) -> RcDoc<'static> {
94        match value {
95            PreferenceGoalDescription::Goal(gd) => self.visit(gd),
96            PreferenceGoalDescription::Preference(pref) => self.visit(pref),
97        }
98    }
99}
100
101impl Visitor<Preference, RcDoc<'static>> for PrettyRenderer {
102    fn visit(&self, value: &Preference) -> RcDoc<'static> {
103        let children: Vec<RcDoc<'static>> = match value.name() {
104            Some(name) => {
105                vec![name.accept(self), self.visit(value.goal())]
106            }
107            None => {
108                vec![self.visit(value.goal())]
109            }
110        };
111        self.sexpr("preference", children)
112    }
113}
114
115impl Visitor<PreferenceConstraintGoalDescription, RcDoc<'static>> for PrettyRenderer {
116    fn visit(&self, value: &PreferenceConstraintGoalDescription) -> RcDoc<'static> {
117        match value {
118            PreferenceConstraintGoalDescription::Goal(gd) => self.visit(gd),
119            PreferenceConstraintGoalDescription::Forall(vars, gds) => self.sexpr(
120                "forall",
121                [
122                    RcDoc::text("(").append(vars.accept(self)).append(")"),
123                    RcDoc::intersperse(gds.iter().map(|gd| self.visit(gd)), RcDoc::softline()),
124                ],
125            ),
126            PreferenceConstraintGoalDescription::Preference(name, gd) => {
127                let children: Vec<RcDoc<'static>> = match name {
128                    Some(n) => vec![n.accept(self), self.visit(gd)],
129                    None => vec![self.visit(gd)],
130                };
131                self.sexpr("preference", children)
132            }
133        }
134    }
135}
136
137impl Visitor<PreferenceConstraintGoalDescriptions, RcDoc<'static>> for PrettyRenderer {
138    fn visit(&self, value: &PreferenceConstraintGoalDescriptions) -> RcDoc<'static> {
139        RcDoc::intersperse(value.iter().map(|gd| self.visit(gd)), RcDoc::softline())
140    }
141}
142
143impl Visitor<ConstraintGoalDescription, RcDoc<'static>> for PrettyRenderer {
144    fn visit(&self, value: &ConstraintGoalDescription) -> RcDoc<'static> {
145        match value {
146            ConstraintGoalDescription::And(items) => {
147                if items.is_empty() {
148                    RcDoc::text("(and)")
149                } else {
150                    self.sexpr("and", items.iter().map(|gd| self.visit(gd)))
151                }
152            }
153            ConstraintGoalDescription::Forall(vars, body) => self.sexpr(
154                "forall",
155                [
156                    RcDoc::text("(").append(vars.accept(self)).append(")"),
157                    self.visit(&**body),
158                ],
159            ),
160            ConstraintGoalDescription::AtEnd(gd) => {
161                self.sexpr("at", [RcDoc::text("end"), self.visit(gd)])
162            }
163            ConstraintGoalDescription::Always(gd) => self.sexpr("always", [self.visit(gd)]),
164            ConstraintGoalDescription::Sometime(gd) => self.sexpr("sometime", [self.visit(gd)]),
165            ConstraintGoalDescription::Within(n, gd) => {
166                self.sexpr("within", [n.accept(self), self.visit(gd)])
167            }
168            ConstraintGoalDescription::AtMostOnce(gd) => {
169                self.sexpr("at-most-once", [self.visit(gd)])
170            }
171            ConstraintGoalDescription::SometimeAfter(a, b) => {
172                self.sexpr("sometime-after", [self.visit(a), self.visit(b)])
173            }
174            ConstraintGoalDescription::SometimeBefore(a, b) => {
175                self.sexpr("sometime-before", [self.visit(a), self.visit(b)])
176            }
177            ConstraintGoalDescription::AlwaysWithin(n, a, b) => self.sexpr(
178                "always-within",
179                [n.accept(self), self.visit(a), self.visit(b)],
180            ),
181            ConstraintGoalDescription::HoldDuring(s, e, gd) => self.sexpr(
182                "hold-during",
183                [s.accept(self), e.accept(self), self.visit(gd)],
184            ),
185            ConstraintGoalDescription::HoldAfter(n, gd) => {
186                self.sexpr("hold-after", [n.accept(self), self.visit(gd)])
187            }
188        }
189    }
190}
191
192impl Visitor<ConstraintGoalDescriptionInner, RcDoc<'static>> for PrettyRenderer {
193    fn visit(&self, value: &ConstraintGoalDescriptionInner) -> RcDoc<'static> {
194        match value {
195            ConstraintGoalDescriptionInner::Goal(gd) => self.visit(gd),
196            ConstraintGoalDescriptionInner::Nested(gd) => self.visit(&**gd),
197        }
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::pretty_print::prettify;
205    use crate::visitor::Accept;
206    use crate::{
207        AtomicFormula, BinaryComparison, FluentComparison, FluentExpression, Literal, Name, Number,
208        Predicate, Term, Variable,
209    };
210    use assert2::check;
211
212    fn make_simple_gd() -> GoalDescription {
213        let af: AtomicFormula<Term> = AtomicFormula::predicate(
214            Predicate::string("at"),
215            vec![
216                Term::new_variable(Variable::from("r")),
217                Term::new_name(Name::new("loc1")),
218            ],
219        );
220        GoalDescription::atomic_formula(af)
221    }
222
223    #[test]
224    fn goal_atomic_formula_works() {
225        let gd = make_simple_gd();
226        check!(prettify!(gd, 40) == "(at ?r loc1)");
227    }
228
229    #[test]
230    fn goal_and_works() {
231        let af: AtomicFormula<Term> = AtomicFormula::predicate(
232            Predicate::string("at"),
233            vec![
234                Term::new_variable(Variable::from("r")),
235                Term::new_name(Name::new("loc1")),
236            ],
237        );
238        let gd = GoalDescription::and([
239            GoalDescription::atomic_formula(af.clone()),
240            GoalDescription::atomic_formula(af),
241        ]);
242        check!(prettify!(gd, 40) == "(and (at ?r loc1) (at ?r loc1))");
243    }
244
245    #[test]
246    fn goal_and_empty_works() {
247        let gd = GoalDescription::and(Vec::<GoalDescription>::new());
248        check!(prettify!(gd, 40) == "(and)");
249    }
250
251    #[test]
252    fn goal_or_works() {
253        let af: AtomicFormula<Term> = AtomicFormula::predicate(
254            Predicate::string("at"),
255            vec![
256                Term::new_variable(Variable::from("r")),
257                Term::new_name(Name::new("loc1")),
258            ],
259        );
260        let gd = GoalDescription::or([
261            GoalDescription::atomic_formula(af.clone()),
262            GoalDescription::atomic_formula(af),
263        ]);
264        check!(prettify!(gd, 40) == "(or (at ?r loc1) (at ?r loc1))");
265    }
266
267    #[test]
268    fn goal_not_works() {
269        let af: AtomicFormula<Term> = AtomicFormula::predicate(
270            Predicate::string("at"),
271            vec![
272                Term::new_variable(Variable::from("r")),
273                Term::new_name(Name::new("loc1")),
274            ],
275        );
276        let gd = GoalDescription::not(GoalDescription::atomic_formula(af));
277        check!(prettify!(gd, 40) == "(not (at ?r loc1))");
278    }
279
280    #[test]
281    fn goal_imply_works() {
282        let af: AtomicFormula<Term> = AtomicFormula::predicate(
283            Predicate::string("at"),
284            vec![
285                Term::new_variable(Variable::from("r")),
286                Term::new_name(Name::new("loc1")),
287            ],
288        );
289        let gd = GoalDescription::imply(
290            GoalDescription::atomic_formula(af.clone()),
291            GoalDescription::atomic_formula(af),
292        );
293        check!(prettify!(gd, 40) == "(imply (at ?r loc1) (at ?r loc1))");
294    }
295
296    #[test]
297    fn goal_fcomp_works() {
298        let a = FluentExpression::number(crate::Number::from(3));
299        let b = FluentExpression::number(crate::Number::from(4));
300        let fc = FluentComparison::new(BinaryComparison::GreaterThan, a, b);
301        let gd = GoalDescription::fluent_comparison(fc);
302        check!(prettify!(gd, 10) == "(> 3 4)");
303    }
304
305    #[test]
306    fn preference_gd_goal_works() {
307        let gd = make_simple_gd();
308        let pgd = PreferenceGoalDescription::from_gd(gd);
309        check!(prettify!(pgd, 40) == "(at ?r loc1)");
310    }
311
312    #[test]
313    fn preference_gd_preference_works() {
314        use crate::PreferenceName;
315        let gd = make_simple_gd();
316        let pref = Preference::new(Some(PreferenceName::string("p1")), gd);
317        let pgd = PreferenceGoalDescription::from_preference(pref);
318        check!(prettify!(pgd, 40) == "(preference p1 (at ?r loc1))");
319    }
320
321    #[test]
322    fn preference_no_name_works() {
323        let gd = make_simple_gd();
324        let pref = Preference::new(None, gd);
325        check!(prettify!(pref, 40) == "(preference (at ?r loc1))");
326    }
327
328    #[test]
329    fn con_gd_and_works() {
330        let gd = make_simple_gd();
331        let con = ConstraintGoalDescription::and([ConstraintGoalDescription::at_end(gd)]);
332        check!(prettify!(con, 40) == "(and (at end (at ?r loc1)))");
333    }
334
335    #[test]
336    fn con_gd_at_end_works() {
337        let gd = make_simple_gd();
338        let con = ConstraintGoalDescription::at_end(gd);
339        check!(prettify!(con, 40) == "(at end (at ?r loc1))");
340    }
341
342    #[test]
343    fn con_gd_always_works() {
344        let gd = make_simple_gd();
345        let con2 = ConstraintGoalDescriptionInner::goal(gd);
346        let con = ConstraintGoalDescription::always(con2);
347        check!(prettify!(con, 40) == "(always (at ?r loc1))");
348    }
349
350    #[test]
351    fn con_gd_within_works() {
352        let gd = make_simple_gd();
353        let con2 = ConstraintGoalDescriptionInner::goal(gd);
354        let con = ConstraintGoalDescription::within(Number::from(10), con2);
355        check!(prettify!(con, 40) == "(within 10 (at ?r loc1))");
356    }
357
358    #[test]
359    fn con_gd_sometime_after_works() {
360        let gd1 = make_simple_gd();
361        let gd2 = make_simple_gd();
362        let con = ConstraintGoalDescription::sometime_after(
363            ConstraintGoalDescriptionInner::goal(gd1),
364            ConstraintGoalDescriptionInner::goal(gd2),
365        );
366        check!(prettify!(con, 40) == "(sometime-after (at ?r loc1) (at ?r\n        loc1))");
367    }
368
369    #[test]
370    fn con_gd_hold_during_works() {
371        let gd = make_simple_gd();
372        let con2 = ConstraintGoalDescriptionInner::goal(gd);
373        let con = ConstraintGoalDescription::hold_during(Number::from(5), Number::from(15), con2);
374        check!(prettify!(con, 40) == "(hold-during 5 15 (at ?r loc1))");
375    }
376
377    #[test]
378    fn goal_literal_works() {
379        let af: AtomicFormula<Term> = AtomicFormula::predicate(
380            Predicate::string("at"),
381            vec![Term::new_name(Name::new("x"))],
382        );
383        let lit = Literal::new(af);
384        let gd = GoalDescription::literal(lit);
385        check!(prettify!(gd, 20) == "(at x)");
386    }
387
388    #[test]
389    fn goal_or_empty_works() {
390        let gd = GoalDescription::or(Vec::<GoalDescription>::new());
391        check!(prettify!(gd, 20) == "(or)");
392    }
393
394    #[test]
395    fn goal_exists_works() {
396        use crate::{ToTyped, Type, TypedVariables, Variable};
397        let vars: TypedVariables = vec![Variable::string("x").to_typed(Type::OBJECT)].into();
398        let inner = make_simple_gd();
399        let gd = GoalDescription::exists(vars, inner);
400        check!(prettify!(gd, 40) == "(exists (?x) (at ?r loc1))");
401    }
402
403    #[test]
404    fn goal_forall_works() {
405        use crate::{ToTyped, Type, TypedVariables, Variable};
406        let vars: TypedVariables = vec![Variable::string("x").to_typed(Type::OBJECT)].into();
407        let inner = make_simple_gd();
408        let gd = GoalDescription::forall(vars, inner);
409        check!(prettify!(gd, 40) == "(forall (?x) (at ?r loc1))");
410    }
411
412    #[test]
413    fn precondition_goal_description_preference_works() {
414        use crate::PreferenceGoalDescription;
415        let gd = make_simple_gd();
416        let preference = PreferenceGoalDescription::from_gd(gd);
417        let precondition = PreconditionGoalDescription::preference(preference);
418        check!(prettify!(precondition, 40) == "(at ?r loc1)");
419    }
420
421    #[test]
422    fn precondition_goal_description_forall_works() {
423        use crate::{ToTyped, Type, TypedVariables, Variable};
424        let vars: TypedVariables = vec![Variable::string("x").to_typed(Type::OBJECT)].into();
425        let inner = PreconditionGoalDescriptions::default();
426        let pre_gd = PreconditionGoalDescription::forall(vars, inner);
427        // The visitor renders as "forall (?x)" with the body being empty PreconditionGoalDescriptions rendering as (and)
428        let out = prettify!(pre_gd, 40);
429        check!(out.contains("forall"));
430        check!(out.contains("?x"));
431    }
432
433    #[test]
434    fn precondition_goal_descriptions_empty_works() {
435        let pgds = PreconditionGoalDescriptions::default();
436        check!(prettify!(pgds, 20) == "(and)");
437    }
438
439    #[test]
440    fn precondition_goal_descriptions_single_works() {
441        let gd = make_simple_gd();
442        let pre_gd =
443            PreconditionGoalDescription::preference(PreferenceGoalDescription::from_gd(gd));
444        let pgds = PreconditionGoalDescriptions::new(vec![pre_gd]);
445        check!(prettify!(pgds, 40) == "(at ?r loc1)");
446    }
447
448    #[test]
449    fn precondition_goal_descriptions_multi_works() {
450        let gd1 = make_simple_gd();
451        let gd2 = make_simple_gd();
452        let pgds = PreconditionGoalDescriptions::new(vec![
453            PreconditionGoalDescription::preference(PreferenceGoalDescription::from_gd(gd1)),
454            PreconditionGoalDescription::preference(PreferenceGoalDescription::from_gd(gd2)),
455        ]);
456        check!(prettify!(pgds, 40) == "(and (at ?r loc1) (at ?r loc1))");
457    }
458
459    #[test]
460    fn pref_con_gd_forall_works() {
461        use crate::{ToTyped, Type, TypedVariables, Variable};
462        let vars: TypedVariables = vec![Variable::string("x").to_typed(Type::OBJECT)].into();
463        let _inner = ConstraintGoalDescription::and(Vec::new());
464        let pgds = PreferenceConstraintGoalDescriptions::new(vec![
465            PreferenceConstraintGoalDescription::goal(ConstraintGoalDescription::always(
466                ConstraintGoalDescriptionInner::goal(make_simple_gd()),
467            )),
468        ]);
469        let pgd = PreferenceConstraintGoalDescription::forall(vars, pgds);
470        check!(prettify!(pgd, 40) == "(forall (?x) (always (at ?r loc1)))");
471    }
472
473    #[test]
474    fn pref_con_gd_preference_with_name_works() {
475        use crate::PreferenceName;
476        let gd = make_simple_gd();
477        let con = ConstraintGoalDescription::at_end(gd);
478        let pcgd = PreferenceConstraintGoalDescription::preference(
479            Some(PreferenceName::string("p1")),
480            con,
481        );
482        check!(prettify!(pcgd, 40) == "(preference p1 (at end (at ?r loc1)))");
483    }
484
485    #[test]
486    fn pref_con_gd_preference_no_name_works() {
487        let gd = make_simple_gd();
488        let con = ConstraintGoalDescription::at_end(gd);
489        let pcgd = PreferenceConstraintGoalDescription::preference(None, con);
490        check!(prettify!(pcgd, 40) == "(preference (at end (at ?r loc1)))");
491    }
492
493    #[test]
494    fn pref_con_gds_multi_works() {
495        let gd1 = make_simple_gd();
496        let gd2 = make_simple_gd();
497        let pgds = PreferenceConstraintGoalDescriptions::new(vec![
498            PreferenceConstraintGoalDescription::goal(ConstraintGoalDescription::at_end(gd1)),
499            PreferenceConstraintGoalDescription::goal(ConstraintGoalDescription::at_end(gd2)),
500        ]);
501        let out = prettify!(pgds, 40);
502        check!(out.contains("(at end"));
503    }
504
505    #[test]
506    fn con_gd_sometime_works() {
507        let gd = make_simple_gd();
508        let con2 = ConstraintGoalDescriptionInner::goal(gd);
509        let con = ConstraintGoalDescription::sometime(con2);
510        check!(prettify!(con, 40) == "(sometime (at ?r loc1))");
511    }
512
513    #[test]
514    fn con_gd_at_most_once_works() {
515        let gd = make_simple_gd();
516        let con2 = ConstraintGoalDescriptionInner::goal(gd);
517        let con = ConstraintGoalDescription::at_most_once(con2);
518        check!(prettify!(con, 40) == "(at-most-once (at ?r loc1))");
519    }
520
521    #[test]
522    fn con_gd_sometime_before_works() {
523        let gd1 = make_simple_gd();
524        let gd2 = make_simple_gd();
525        let con = ConstraintGoalDescription::sometime_before(
526            ConstraintGoalDescriptionInner::goal(gd1),
527            ConstraintGoalDescriptionInner::goal(gd2),
528        );
529        check!(prettify!(con, 40) == "(sometime-before (at ?r loc1) (at ?r\n        loc1))");
530    }
531
532    #[test]
533    fn con_gd_always_within_works() {
534        let gd1 = make_simple_gd();
535        let gd2 = make_simple_gd();
536        let con = ConstraintGoalDescription::always_within(
537            Number::from(10),
538            ConstraintGoalDescriptionInner::goal(gd1),
539            ConstraintGoalDescriptionInner::goal(gd2),
540        );
541        check!(prettify!(con, 40) == "(always-within 10 (at ?r loc1) (at ?r\n        loc1))");
542    }
543
544    #[test]
545    fn con_gd_hold_after_works() {
546        let gd = make_simple_gd();
547        let con2 = ConstraintGoalDescriptionInner::goal(gd);
548        let con = ConstraintGoalDescription::hold_after(Number::from(15), con2);
549        check!(prettify!(con, 40) == "(hold-after 15 (at ?r loc1))");
550    }
551
552    #[test]
553    fn con_gd_forall_works() {
554        use crate::{ToTyped, Type, TypedVariables, Variable};
555        let vars: TypedVariables = vec![Variable::string("x").to_typed(Type::OBJECT)].into();
556        let inner = ConstraintGoalDescription::at_end(make_simple_gd());
557        let con = ConstraintGoalDescription::forall(vars, inner);
558        check!(prettify!(con, 40) == "(forall (?x) (at end (at ?r loc1)))");
559    }
560
561    #[test]
562    fn con2_gd_nested_works() {
563        let gd = make_simple_gd();
564        let con = ConstraintGoalDescription::at_end(gd);
565        let con2 = ConstraintGoalDescriptionInner::nested(con);
566        check!(prettify!(con2, 40) == "(at end (at ?r loc1))");
567    }
568}