From a01853fad5cb9e09a5e8b1ae8b9ffe6b24aa8ca0 Mon Sep 17 00:00:00 2001 From: coolreader18 <33094578+coolreader18@users.noreply.github.com> Date: Sat, 3 Aug 2019 22:44:36 -0500 Subject: [PATCH] Add constant optimization test --- src/compile.rs | 24 ++++++++++++++++++++++-- src/peephole.rs | 4 ++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/compile.rs b/src/compile.rs index 37d66f0..ef481df 100644 --- a/src/compile.rs +++ b/src/compile.rs @@ -117,7 +117,7 @@ pub(crate) type Label = usize; impl Default for Compiler where - O: OutputStream + Default, + O: OutputStream, { fn default() -> Self { Compiler::new(0) @@ -1916,7 +1916,7 @@ mod tests { use rustpython_parser::parser; fn compile_exec(source: &str) -> CodeObject { - let mut compiler = Compiler::default(); + let mut compiler: Compiler = Default::default(); compiler.source_path = Some("source_path".to_string()); compiler.push_new_code_object("".to_string()); let ast = parser::parse_program(&source.to_string()).unwrap(); @@ -2003,4 +2003,24 @@ mod tests { code.instructions ); } + + #[test] + fn test_constant_optimization() { + let code = compile_exec("1 + 2 + 3 + 4\n1.5 * 2.5"); + assert_eq!( + code.instructions, + vec![ + LoadConst { + value: Integer { value: 10.into() } + }, + Pop, + LoadConst { + value: Float { value: 3.75 } + }, + Pop, + LoadConst { value: None }, + ReturnValue, + ] + ); + } } diff --git a/src/peephole.rs b/src/peephole.rs index 0db9507..31aad96 100644 --- a/src/peephole.rs +++ b/src/peephole.rs @@ -79,6 +79,10 @@ impl PeepholeOptimizer { (op!(Subtract), lc!(Float, lhs), lc!(Float, rhs)) => { emitconst!(Float, lhs - rhs) } + (op!(Multiply), lc!(Float, lhs), lc!(Float, rhs)) => { + emitconst!(Float, lhs * rhs) + } + (op!(Divide), lc!(Float, lhs), lc!(Float, rhs)) => emitconst!(Float, lhs / rhs), (op!(Power), lc!(Float, lhs), lc!(Float, rhs)) => { emitconst!(Float, lhs.powf(rhs)) }