Pretty print table literals

This commit is contained in:
Joscha 2022-11-20 23:33:39 +01:00
parent f91e8ac9a2
commit 412eaffc07
3 changed files with 48 additions and 4 deletions

View file

@ -2,3 +2,5 @@ mod basic;
mod expr; mod expr;
mod lit; mod lit;
mod program; mod program;
const NEST_DEPTH: isize = 4;

View file

@ -1,6 +1,12 @@
use pretty::{DocAllocator, DocBuilder}; use pretty::{DocAllocator, DocBuilder, Pretty};
use crate::ast::Separated; use crate::ast::{Ident, Separated};
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for Ident {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
allocator.text(self.name)
}
}
impl<E, S1, S2> Separated<E, S1, S2> { impl<E, S1, S2> Separated<E, S1, S2> {
pub fn pretty<'a, D, FE, FS1, FS2>( pub fn pretty<'a, D, FE, FS1, FS2>(

View file

@ -1,6 +1,8 @@
use pretty::{DocAllocator, DocBuilder, Pretty}; use pretty::{DocAllocator, DocBuilder, Pretty};
use crate::ast::{Lit, NumLit, StringLit, StringLitElem}; use crate::ast::{Lit, NumLit, StringLit, StringLitElem, TableLit, TableLitElem};
use super::NEST_DEPTH;
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> {
@ -30,6 +32,40 @@ impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for StringLit {
} }
} }
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for TableLitElem {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
match self {
Self::Positional(expr) => expr.pretty(allocator),
Self::Named {
name,
s0,
s1,
value,
span: _,
} => name
.pretty(allocator)
.append(allocator.text(": "))
.append(value.pretty(allocator)),
}
}
}
impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for TableLit {
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D> {
self.elems
.pretty(
allocator,
|a, e| a.line().append(e.pretty(a)),
|a, (s0, s1)| a.text(","),
|a, s| a.text(","),
)
.nest(NEST_DEPTH)
.append(allocator.line())
.enclose(allocator.text("'{"), allocator.text("}"))
.group()
}
}
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 {
@ -39,7 +75,7 @@ impl<'a, D: DocAllocator<'a>> Pretty<'a, D> for Lit {
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) => string.pretty(allocator), Self::String(string) => string.pretty(allocator),
Self::Table(table) => allocator.text("<table>"), Self::Table(table) => table.pretty(allocator),
} }
} }
} }