summaryrefslogtreecommitdiff
path: root/src/pretty.rs
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-01-06 01:32:59 +0100
committerLaurenz <laurmaedje@gmail.com>2021-01-06 01:32:59 +0100
commit7b4d4d6002a9c3da8fafd912f3c7b2da617f19c0 (patch)
treee491f5fcf33c1032c63746003ac7bef6c3c5478f /src/pretty.rs
parent2e77b1c836220766398e379ae0157736fb448874 (diff)
Pretty printing 🦋
- Syntax tree and value pretty printing - Better value evaluation (top-level strings and content are evaluated plainly, everything else is pretty printed)
Diffstat (limited to 'src/pretty.rs')
-rw-r--r--src/pretty.rs68
1 files changed, 68 insertions, 0 deletions
diff --git a/src/pretty.rs b/src/pretty.rs
new file mode 100644
index 00000000..a7482869
--- /dev/null
+++ b/src/pretty.rs
@@ -0,0 +1,68 @@
+//! Pretty printing.
+
+use std::fmt::{Arguments, Result, Write};
+
+/// Pretty print an item and return the resulting string.
+pub fn pretty<T>(item: &T) -> String
+where
+ T: Pretty,
+{
+ let mut p = Printer::new();
+ item.pretty(&mut p);
+ p.finish()
+}
+
+/// Pretty printing.
+pub trait Pretty {
+ /// Pretty print this item into the given printer.
+ fn pretty(&self, p: &mut Printer);
+}
+
+/// A buffer into which items are printed.
+pub struct Printer {
+ buf: String,
+}
+
+impl Printer {
+ /// Create a new pretty printer.
+ pub fn new() -> Self {
+ Self { buf: String::new() }
+ }
+
+ /// Push a string into the buffer.
+ pub fn push_str(&mut self, string: &str) {
+ self.buf.push_str(string);
+ }
+
+ /// Write formatted items into the buffer.
+ pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
+ Write::write_fmt(self, fmt)
+ }
+
+ /// Write a comma-separated list of items.
+ pub fn join<T, I, F>(&mut self, items: I, joiner: &str, mut write_item: F)
+ where
+ I: IntoIterator<Item = T>,
+ F: FnMut(T, &mut Self),
+ {
+ let mut iter = items.into_iter();
+ if let Some(first) = iter.next() {
+ write_item(first, self);
+ }
+ for item in iter {
+ self.push_str(joiner);
+ write_item(item, self);
+ }
+ }
+
+ /// Finish pretty printing and return the underlying buffer.
+ pub fn finish(self) -> String {
+ self.buf
+ }
+}
+
+impl Write for Printer {
+ fn write_str(&mut self, s: &str) -> Result {
+ Ok(self.push_str(s))
+ }
+}