mirror of
https://github.com/RustPython/Parser.git
synced 2025-07-22 12:35:22 +00:00
Add constant optimization test
This commit is contained in:
parent
e9ad1f64ee
commit
a01853fad5
2 changed files with 26 additions and 2 deletions
|
@ -117,7 +117,7 @@ pub(crate) type Label = usize;
|
||||||
|
|
||||||
impl<O> Default for Compiler<O>
|
impl<O> Default for Compiler<O>
|
||||||
where
|
where
|
||||||
O: OutputStream + Default,
|
O: OutputStream,
|
||||||
{
|
{
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Compiler::new(0)
|
Compiler::new(0)
|
||||||
|
@ -1916,7 +1916,7 @@ mod tests {
|
||||||
use rustpython_parser::parser;
|
use rustpython_parser::parser;
|
||||||
|
|
||||||
fn compile_exec(source: &str) -> CodeObject {
|
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.source_path = Some("source_path".to_string());
|
||||||
compiler.push_new_code_object("<module>".to_string());
|
compiler.push_new_code_object("<module>".to_string());
|
||||||
let ast = parser::parse_program(&source.to_string()).unwrap();
|
let ast = parser::parse_program(&source.to_string()).unwrap();
|
||||||
|
@ -2003,4 +2003,24 @@ mod tests {
|
||||||
code.instructions
|
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,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -79,6 +79,10 @@ impl<O: OutputStream> PeepholeOptimizer<O> {
|
||||||
(op!(Subtract), lc!(Float, lhs), lc!(Float, rhs)) => {
|
(op!(Subtract), lc!(Float, lhs), lc!(Float, rhs)) => {
|
||||||
emitconst!(Float, lhs - 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)) => {
|
(op!(Power), lc!(Float, lhs), lc!(Float, rhs)) => {
|
||||||
emitconst!(Float, lhs.powf(rhs))
|
emitconst!(Float, lhs.powf(rhs))
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue