Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pretty-printing implementations #58

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "pddl"
version = "0.0.8-unstable"
description ="A PDDL 3.1 parser"
description = "A PDDL 3.1 parser, strongly typed"
license = "EUPL-1.2"
documentation = "https://docs.rs/pddl"
categories = ["parser-implementations", "science", "simulation"]
Expand All @@ -13,7 +13,7 @@ edition = "2021"
rust-version = "1.68.0"

[features]
default = ["parser", "interning"]
default = ["parser", "interning", "pretty"]
parser = ["dep:nom", "dep:nom-greedyerror", "dep:nom_locate", "dep:thiserror"]
interning = ["dep:lazy_static"]

Expand All @@ -22,6 +22,7 @@ lazy_static = { version = "1.4.0", optional = true }
nom = { version = "7.1.3", optional = true }
nom-greedyerror = { version = "0.5.0", optional = true }
nom_locate = { version = "4.2.0", optional = true }
pretty = { version = "0.12.1", optional = true }
thiserror = { version = "1.0.61", optional = true }

[package.metadata.docs.rs]
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,7 @@ pub use parsers::Parser;

// re-export types
pub use types::*;

#[cfg_attr(docsrs, doc(cfg(feature = "pretty")))]
#[cfg(feature = "pretty")]
pub(crate) mod pretty_print;
29 changes: 29 additions & 0 deletions src/pretty_print/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#![allow(dead_code)]
use pretty::RcDoc;

mod name;
mod r#type;

#[derive(Default)]
pub struct PrettyRenderer;

impl PrettyRenderer {
pub fn to_pretty(&self, doc: RcDoc<'_>, width: usize) -> String {
let mut w = Vec::new();
doc.render(width, &mut w).unwrap();
String::from_utf8(w).unwrap()
}
}

/// Helper macro to quickly prettify an element.
#[cfg(test)]
macro_rules! prettify {
($x:expr, $n:literal) => {{
let renderer = PrettyRenderer::default();
let doc = $x.accept(&renderer);
renderer.to_pretty(doc, $n)
}};
}

#[cfg(test)]
pub(crate) use prettify;
47 changes: 47 additions & 0 deletions src/pretty_print/name.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use crate::pretty_print::PrettyRenderer;
use crate::types::{FunctionSymbol, Name, Variable};
use crate::visitor::Visitor;
use pretty::RcDoc;

impl<'a> Visitor<Name, RcDoc<'a>> for PrettyRenderer {
fn visit(&self, value: &Name) -> RcDoc<'a> {
RcDoc::text(value.to_string())
}
}

impl<'a> Visitor<Variable, RcDoc<'a>> for PrettyRenderer {
fn visit(&self, value: &Variable) -> RcDoc<'a> {
RcDoc::text(value.to_string())
}
}

impl<'a> Visitor<FunctionSymbol, RcDoc<'a>> for PrettyRenderer {
fn visit(&self, value: &FunctionSymbol) -> RcDoc<'a> {
RcDoc::text(value.to_string())
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::pretty_print::prettify;
use crate::visitor::Accept;

#[test]
fn name_works() {
let x = Name::new("name");
assert_eq!(prettify!(x, 10), "name");
}

#[test]
fn variable_works() {
let x = Variable::from("var");
assert_eq!(prettify!(x, 10), "?var");
}

#[test]
fn function_symbol_works() {
let x = FunctionSymbol::from("fun-sym");
assert_eq!(prettify!(x, 10), "fun-sym");
}
}
56 changes: 56 additions & 0 deletions src/pretty_print/type.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use crate::pretty_print::PrettyRenderer;
use crate::types::{PrimitiveType, Type};
use crate::visitor::{Accept, Visitor};
use pretty::RcDoc;

impl<'a> Visitor<PrimitiveType, RcDoc<'a>> for PrettyRenderer {
fn visit(&self, value: &PrimitiveType) -> RcDoc<'a> {
RcDoc::text(value.to_string())
}
}

impl<'a> Visitor<Type, RcDoc<'a>> for PrettyRenderer {
fn visit(&self, value: &Type) -> RcDoc<'a> {
match value {
Type::Exactly(t) => RcDoc::text(t.to_string()),
Type::EitherOf(ts) => RcDoc::text("(either")
.append(RcDoc::softline())
.group()
.nest(4)
.append(RcDoc::intersperse(
ts.iter().map(|t| t.accept(self)),
RcDoc::softline(),
))
.nest(4)
.group()
.append(")"),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::pretty_print::prettify;
use crate::visitor::Accept;

#[test]
fn primitive_type_works() {
let x = PrimitiveType::from("pt");
assert_eq!(prettify!(x, 10), "pt");
}

#[test]
fn simple_type_works() {
let x = Type::from("a");
assert_eq!(prettify!(x, 10), "a");
}

#[test]
fn either_type_works() {
let x = Type::from_iter(["a", "b"]);
assert_eq!(prettify!(x, 12), "(either a b)");
assert_eq!(prettify!(x, 10), "(either a\n b)");
assert_eq!(prettify!(x, 8), "(either\n a b)");
}
}
12 changes: 12 additions & 0 deletions src/types/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ impl PartialEq<String> for Name {
}
}

impl<'a> Display for Name {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

impl ToTyped<Name> for Name {
fn to_typed<I: Into<Type>>(self, r#type: I) -> Typed<Name> {
Typed::new(self, r#type.into())
Expand Down Expand Up @@ -260,6 +266,12 @@ mod tests {
use super::*;
use nom_greedyerror::AsStr;

#[test]
fn test_display() {
let name = Name::new("x");
assert_eq!(format!("{name}"), "x");
}

#[test]
fn map_to_static_works() {
let object = Name::map_to_static("object").expect("mapping works");
Expand Down
41 changes: 40 additions & 1 deletion src/types/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use crate::types::iterators::FlatteningIntoIterator;
use crate::types::Name;
use std::fmt::{Display, Formatter};
use std::ops::Deref;

/// The `object` type.
Expand Down Expand Up @@ -44,6 +45,14 @@ impl Type {
/// The predefined type `number`.
pub const NUMBER: Type = Type::Exactly(TYPE_NUMBER);

pub fn new_exactly<S: Into<PrimitiveType>>(t: S) -> Self {
Self::Exactly(t.into())
}

pub fn new_either<T: IntoIterator<Item = P>, P: Into<PrimitiveType>>(iter: T) -> Self {
Self::EitherOf(iter.into_iter().map(|x| x.into()).collect())
}

pub fn len(&self) -> usize {
match self {
Type::Exactly(_) => 1,
Expand Down Expand Up @@ -114,7 +123,7 @@ impl AsRef<str> for PrimitiveType {
}

impl Deref for PrimitiveType {
type Target = str;
type Target = Name;

fn deref(&self) -> &Self::Target {
&self.0
Expand All @@ -133,12 +142,36 @@ impl IntoIterator for Type {
}
}

impl<'a> Display for PrimitiveType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

impl<'a> Display for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Type::Exactly(x) => write!(f, "{}", x),
Type::EitherOf(xs) => {
let xs: Vec<_> = xs.iter().map(|p| p.to_string()).collect();
write!(f, "(either {})", xs.join(" "))
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::parsers::Span;
use crate::Parser;

#[test]
fn simple_works() {
let t = Type::new_exactly("location");
assert_eq!(format!("{t}"), "location");
}

#[test]
fn flatten_with_single_element_works() {
let (_, t) = Type::parse(Span::new("object")).unwrap();
Expand All @@ -157,4 +190,10 @@ mod tests {
assert!(iter.next().is_some());
assert!(iter.next().is_none());
}

#[test]
fn either_works() {
let t = Type::new_either(["location", "memory"]);
assert_eq!(format!("{t}"), "(either location memory)");
}
}
Loading