Skip to main content

pddl_core/
pretty_print.rs

1//! Renders PDDL types back to PDDL text, wrapped to a target line width.
2//!
3//! Each type gets a [`Visitor`] impl on [`PrettyRenderer`] that turns it into a
4//! [`pretty`] document; [`Pretty::pretty`] renders that document through `Display`.
5//! The output parses back to an equal value, with two exceptions for values the
6//! parser never builds. PDDL has no negative literals, so a negative number in
7//! an expression prints as `(- 5)` and parses back as a negation of `5`.
8//! A `MultiOp` built directly with one extra operand prints as `(+ a b)`, which
9//! parses back as a `BinaryOp`, and with none it prints as its only operand;
10//! the `multi_op` constructors build those equal forms instead.
11
12use std::fmt;
13
14use crate::visitor::{Accept, Visitor};
15use pretty::RcDoc;
16
17mod action;
18mod atomic_formula;
19mod decl;
20mod domain;
21mod effect;
22mod f_exp;
23mod formula_skeleton;
24mod function_type;
25mod gd;
26mod name;
27mod number;
28mod ops;
29mod predicate;
30mod problem;
31mod term;
32mod timed;
33mod timeless;
34mod r#type;
35mod typed_list;
36
37/// Keeps [`PrettyVisit`] implemented only for this crate's types.
38mod sealed {
39    /// Marks a type that has a pretty-print [`Visitor`](crate::visitor::Visitor) impl.
40    pub trait Sealed {}
41}
42
43/// Converts a value into a [`pretty`] document through its [`Visitor`] impl on
44/// [`PrettyRenderer`]. Implemented for every type that [`Pretty`] supports.
45pub trait PrettyVisit: sealed::Sealed {
46    /// Builds the document for `self` with the renderer `r`.
47    fn to_doc(&self, r: &PrettyRenderer) -> RcDoc<'static>;
48}
49
50impl<T> PrettyVisit for T
51where
52    T: sealed::Sealed,
53    PrettyRenderer: Visitor<T, RcDoc<'static>>,
54{
55    fn to_doc(&self, r: &PrettyRenderer) -> RcDoc<'static> {
56        self.accept(r)
57    }
58}
59
60impl<T: PrettyVisit> Pretty for T {
61    fn pretty(&self, width: usize) -> PrettyPrinted<'_, Self> {
62        PrettyPrinted { value: self, width }
63    }
64}
65
66impl<T: PrettyVisit> fmt::Display for PrettyPrinted<'_, T> {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        let renderer = PrettyRenderer;
69        let doc = self.value.to_doc(&renderer);
70        doc.render_fmt(self.width, f)
71    }
72}
73
74/// Renders PDDL values as [`pretty`] documents. It holds no state; each value's
75/// layout comes from its [`Visitor`] impl, built from the helpers below.
76#[derive(Default)]
77pub struct PrettyRenderer;
78
79impl PrettyRenderer {
80    /// Renders `doc` to a string, wrapping lines longer than `width`.
81    #[must_use]
82    pub fn to_pretty(&self, doc: &RcDoc<'static>, width: usize) -> String {
83        doc.pretty(width).to_string()
84    }
85
86    /// `(head child ...)` on one line if it fits within the width, otherwise
87    /// with the children on their own lines, indented by four.
88    pub fn sexpr(
89        &self,
90        head: &'static str,
91        children: impl IntoIterator<Item = RcDoc<'static>>,
92    ) -> RcDoc<'static> {
93        RcDoc::text("(")
94            .append(RcDoc::text(head))
95            .append(RcDoc::softline())
96            .append(RcDoc::intersperse(children, RcDoc::softline()))
97            .nest(4)
98            .group()
99            .append(")")
100    }
101
102    /// `(head` followed by each child on its own line, indented by four, and the
103    /// closing `)` on a line of its own. Used for top-level forms such as `define`.
104    pub fn sexpr_nested(
105        &self,
106        head: &'static str,
107        children: impl IntoIterator<Item = RcDoc<'static>>,
108    ) -> RcDoc<'static> {
109        RcDoc::text("(")
110            .append(RcDoc::text(head))
111            .append(
112                RcDoc::hardline()
113                    .append(RcDoc::intersperse(children, RcDoc::hardline()))
114                    .nest(4),
115            )
116            .append(RcDoc::hardline())
117            .append(")")
118    }
119
120    /// A section `(:keyword body ...)`, laid out like [`sexpr`](Self::sexpr);
121    /// `keyword` is given without its colon.
122    pub fn section(
123        &self,
124        keyword: &'static str,
125        body: impl IntoIterator<Item = RcDoc<'static>>,
126    ) -> RcDoc<'static> {
127        RcDoc::text("(")
128            .append(RcDoc::text(":"))
129            .append(RcDoc::text(keyword))
130            .append(RcDoc::softline())
131            .append(RcDoc::intersperse(body, RcDoc::softline()))
132            .nest(4)
133            .group()
134            .append(")")
135    }
136
137    /// The keyword `:name`, e.g. `:parameters` before an action's parameter list.
138    #[must_use]
139    pub fn keyword_line(&self, name: &'static str) -> RcDoc<'static> {
140        RcDoc::text(":").append(RcDoc::text(name))
141    }
142
143    /// The `items` separated by `sep`, without surrounding parentheses.
144    pub fn list(
145        &self,
146        items: impl IntoIterator<Item = RcDoc<'static>>,
147        sep: RcDoc<'static>,
148    ) -> RcDoc<'static> {
149        RcDoc::intersperse(items, sep)
150    }
151}
152
153/// A value paired with a target line width, printable via [`std::fmt::Display`].
154///
155/// Produced by [`Pretty::pretty`]. The `Display` impl runs the pretty-printer
156/// at the stored `width`.
157pub struct PrettyPrinted<'a, T> {
158    /// The value to print.
159    value: &'a T,
160    /// The line width to wrap at.
161    width: usize,
162}
163
164/// Extension trait to obtain a [`Display`](fmt::Display)-able pretty-printed
165/// adapter for any type with a registered pretty-print visitor impl.
166pub trait Pretty: Sized {
167    /// Wrap `self` together with a target line `width`. The returned value
168    /// implements [`Display`](fmt::Display).
169    fn pretty(&self, width: usize) -> PrettyPrinted<'_, Self>;
170}
171
172/// Helper macro to quickly prettify an element.
173#[cfg(test)]
174macro_rules! prettify {
175    ($x:expr, $n:literal) => {{
176        let renderer = PrettyRenderer::default();
177        let doc = $x.accept(&renderer);
178        renderer.to_pretty(&doc, $n)
179    }};
180}
181
182#[cfg(test)]
183pub(crate) use prettify;
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::Name;
189    use assert2::check;
190
191    #[test]
192    fn to_pretty_works() {
193        let renderer = PrettyRenderer;
194        let doc = RcDoc::text("hello");
195        check!(renderer.to_pretty(&doc, 80) == "hello");
196    }
197
198    #[test]
199    fn sexpr_nested_works() {
200        let renderer = PrettyRenderer;
201        let doc = renderer.sexpr_nested("head", [RcDoc::text("a"), RcDoc::text("b")]);
202        let out = renderer.to_pretty(&doc, 80);
203        check!(out.starts_with("(head"));
204        check!(out.contains('\n'));
205    }
206
207    #[test]
208    fn list_works() {
209        let renderer = PrettyRenderer;
210        let doc = renderer.list([RcDoc::text("a"), RcDoc::text("b")], RcDoc::text(", "));
211        check!(renderer.to_pretty(&doc, 80) == "a, b");
212    }
213
214    #[test]
215    fn pretty_display_works() {
216        let out = Name::new("x").pretty(10).to_string();
217        check!(out == "x");
218    }
219
220    #[test]
221    fn keyword_line_works() {
222        let renderer = PrettyRenderer;
223        let doc = renderer.keyword_line("foo");
224        check!(renderer.to_pretty(&doc, 80) == ":foo");
225    }
226}