Add "pretty" subcommand

This commit is contained in:
Joscha 2022-11-20 18:27:25 +01:00
parent 43d5b6d5ae
commit 407786b98c
4 changed files with 74 additions and 1 deletions

View file

@ -1,12 +1,14 @@
use std::fs;
use std::path::PathBuf;
use ::pretty::{Pretty, RcAllocator};
use chumsky::Parser as _;
use clap::Parser;
mod ast;
mod builtin;
mod parser;
mod pretty;
mod span;
mod table;
mod value;
@ -14,6 +16,7 @@ mod value;
#[derive(Parser)]
enum Command {
Parse { file: PathBuf },
Pretty { file: PathBuf },
}
#[derive(Parser)]
@ -31,7 +34,27 @@ fn main() -> anyhow::Result<()> {
let content = fs::read_to_string(&file)?;
let stream = span::stream_from_str(&content);
match parser::parser().parse(stream) {
Ok(lit) => println!("Successful parse: {lit:#?}"),
Ok(program) => println!("Successful parse: {program:#?}"),
Err(errs) => {
println!("Parsing failed");
for err in errs {
println!("{err:?}");
}
}
}
}
Command::Pretty { file } => {
let content = fs::read_to_string(&file)?;
let stream = span::stream_from_str(&content);
match parser::parser().parse(stream) {
Ok(program) => {
println!("Successful parse");
let doc = program.pretty(&RcAllocator);
let mut out = vec![];
doc.render(100, &mut out)?;
let str = String::from_utf8(out)?;
println!("{str}");
}
Err(errs) => {
println!("Parsing failed");
for err in errs {

9
src/pretty.rs Normal file
View file

@ -0,0 +1,9 @@
use pretty::{DocAllocator, DocBuilder, Pretty};
use crate::ast::Program;
impl<'a, A: DocAllocator<'a>> Pretty<'a, A> for Program {
fn pretty(self, allocator: &'a A) -> DocBuilder<'a, A, ()> {
allocator.text("Hello world")
}
}