From d27acb2fa7c0956e9a521137c2145a833c57e2b4 Mon Sep 17 00:00:00 2001 From: Dominic Grimm Date: Sat, 10 Sep 2022 10:43:29 +0200 Subject: [PATCH] Add cli option for optimization --- henceforth/examples/test.fth | 3 ++- henceforth/src/bin/main.rs | 11 +++++++++-- henceforth/src/lib/compiler.rs | 12 ++++++------ 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/henceforth/examples/test.fth b/henceforth/examples/test.fth index 841fa7b..dda7c08 100644 --- a/henceforth/examples/test.fth +++ b/henceforth/examples/test.fth @@ -1 +1,2 @@ -random . cr +depth dup dup dup dup dup debug + diff --git a/henceforth/src/bin/main.rs b/henceforth/src/bin/main.rs index 04cc3cd..6c8b9f1 100644 --- a/henceforth/src/bin/main.rs +++ b/henceforth/src/bin/main.rs @@ -30,6 +30,8 @@ enum Commands { src: String, #[clap(value_parser)] out: Option, + #[clap(short, long, action)] + optimize: Option, #[clap(long, action)] dump: bool, }, @@ -53,11 +55,16 @@ fn main() -> Result<()> { Ok(()) } - Commands::Compile { src, out, dump } => { + Commands::Compile { + src, + out, + optimize, + dump, + } => { let source = fs::read_to_string(&src)?; let tokens = lexer::lex(source)?; let ast = parser::parse(tokens)?; - let ast = compiler::compile(ast)?; + let ast = compiler::compile(ast, optimize.unwrap_or(true))?; let assembly = ast.to_code(); if let Some(x) = out { diff --git a/henceforth/src/lib/compiler.rs b/henceforth/src/lib/compiler.rs index c5aa695..d3a321d 100644 --- a/henceforth/src/lib/compiler.rs +++ b/henceforth/src/lib/compiler.rs @@ -33,16 +33,16 @@ impl Data { } } - pub fn generate_instructions(&mut self, body: parser::ast::Body) -> Result> { + pub fn generate_instructions(&mut self, body: parser::ast::Body, optimize: bool) -> Result> { let mut instructions: Vec = vec![]; let mut iter = body.into_iter().peekable(); while let Some(node) = iter.next() { match node { - _ if iter.next_if_eq(&node).is_some() => { + _ if optimize && iter.next_if_eq(&node).is_some() => { let count = iter.by_ref().peeking_take_while(|n| *n == node).count() + 2; instructions.push(Instruction::Multiple { instruction: Box::new( - self.generate_instructions(vec![node])? + self.generate_instructions(vec![node], optimize)? .into_iter() .next() .unwrap(), @@ -75,7 +75,7 @@ impl Data { bail!("Word already exists as user word definition: {}", name); } - let ins = self.generate_instructions(body)?; + let ins = self.generate_instructions(body, optimize)?; self.words.insert( name, @@ -326,9 +326,9 @@ impl Data { } } -pub fn compile(ast: parser::ast::AST) -> Result { +pub fn compile(ast: parser::ast::AST, optimize: bool) -> Result { let mut data = Data::default(); - let instructions = data.generate_instructions(ast.body)?; + let instructions = data.generate_instructions(ast.body, optimize)?; Ok(hence::parser::ast::AST { body: data.embed(