From 565d3c54f1440bc5b5e3c460ff2bc40b9168584d Mon Sep 17 00:00:00 2001 From: Jeff Date: Sun, 13 Oct 2024 07:56:11 -0400 Subject: [PATCH] Add format option to the CLI --- dust-lang/src/chunk.rs | 7 ------- dust-shell/src/main.rs | 44 +++++++++++++++++++++++++++--------------- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/dust-lang/src/chunk.rs b/dust-lang/src/chunk.rs index c58e2be..7f30d67 100644 --- a/dust-lang/src/chunk.rs +++ b/dust-lang/src/chunk.rs @@ -460,7 +460,6 @@ impl<'a> ChunkDisassembler<'a> { disassembly.push('│'); } - disassembly.push_str(&line_length.to_string()); disassembly.push('\n'); if !remainder.is_empty() { @@ -642,12 +641,6 @@ impl<'a> ChunkDisassembler<'a> { push_border(&bottom_border, &mut disassembly); - if let Some(source) = self.source { - let formatted = Formatter::new(source).origin(self.name).format(); - - disassembly.push_str(&formatted); - } - let expected_length = self.predict_length(); let actual_length = disassembly.len(); diff --git a/dust-shell/src/main.rs b/dust-shell/src/main.rs index 49d774d..8d3d139 100644 --- a/dust-shell/src/main.rs +++ b/dust-shell/src/main.rs @@ -2,7 +2,7 @@ use std::{fs::read_to_string, io::Write}; use clap::Parser; use colored::Colorize; -use dust_lang::{parse, run}; +use dust_lang::{parse, run, Formatter}; use log::Level; #[derive(Parser)] @@ -10,6 +10,9 @@ struct Cli { #[arg(short, long)] command: Option, + #[arg(short, long)] + format: bool, + #[arg(short, long)] parse: bool, @@ -43,24 +46,33 @@ fn main() { let args = Cli::parse(); - if let Some(command) = &args.command { - if args.parse { - parse_and_display(command, args.styled); - } else { - run_and_display(command); - } - } else if let Some(path) = &args.path { - let source = read_to_string(path).expect("Failed to read file"); + let source = if let Some(path) = &args.path { + &read_to_string(path).expect("Failed to read file") + } else if let Some(command) = &args.command { + command + } else { + eprintln!("No input provided"); + return; + }; - if args.parse { - parse_and_display(&source, args.styled); - } else { - run_and_display(&source); - } + if args.parse { + parse_source(source, args.styled); + } + + if args.format { + format_source(source); + } + + if !args.format && !args.parse { + run_source(source); } } -fn parse_and_display(source: &str, styled: bool) { +fn format_source(source: &str) { + println!("{}", Formatter::new(source).format()) +} + +fn parse_source(source: &str, styled: bool) { match parse(source) { Ok(chunk) => println!( "{}", @@ -76,7 +88,7 @@ fn parse_and_display(source: &str, styled: bool) { } } -fn run_and_display(source: &str) { +fn run_source(source: &str) { match run(source) { Ok(Some(value)) => println!("{}", value), Ok(_) => {}