Pretty print string literals

This commit is contained in:
Joscha 2022-11-20 23:06:04 +01:00
parent e6bbb37323
commit f91e8ac9a2

View file

@ -1,6 +1,6 @@
use pretty::{DocAllocator, DocBuilder, Pretty}; use pretty::{DocAllocator, DocBuilder, Pretty};
use crate::ast::{Lit, NumLit}; use crate::ast::{Lit, NumLit, StringLit, StringLitElem};
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for NumLit { impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for NumLit {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> { fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
@ -8,6 +8,28 @@ impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for NumLit {
} }
} }
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for StringLitElem {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
match self {
Self::Plain(str) => allocator.text(str),
Self::Unicode(char) => allocator.text(format!("\\u{{{:x}}}", char as u32)),
Self::Backslash => allocator.text("\\\\"),
Self::DoubleQuote => allocator.text("\\\""),
Self::Tab => allocator.text("\\t"),
Self::CarriageReturn => allocator.text("\\r"),
Self::Newline => allocator.text("\\n"),
}
}
}
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for StringLit {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
allocator
.concat(self.elems.into_iter().map(|e| e.pretty(allocator)))
.enclose(allocator.text("\""), allocator.text("\""))
}
}
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for Lit { impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for Lit {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> { fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
match self { match self {
@ -16,7 +38,7 @@ impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for Lit {
Self::Bool(true, _) => allocator.text("true"), Self::Bool(true, _) => allocator.text("true"),
Self::Builtin(builtin, _) => allocator.text(format!("{builtin:?}")), Self::Builtin(builtin, _) => allocator.text(format!("{builtin:?}")),
Self::Num(num) => num.pretty(allocator), Self::Num(num) => num.pretty(allocator),
Self::String(string) => allocator.text("<string>"), Self::String(string) => string.pretty(allocator),
Self::Table(table) => allocator.text("<table>"), Self::Table(table) => allocator.text("<table>"),
} }
} }