mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
Fold const bool with unary not (#7357)
* Fold const bool with unary not * Fold unnecessary TO_BOOL
This commit is contained in:
@@ -9069,6 +9069,18 @@ mod tests {
|
||||
|
||||
fn compile_exec(source: &str) -> CodeObject {
|
||||
let opts = CompileOpts::default();
|
||||
compile_exec_with_options(source, opts)
|
||||
}
|
||||
|
||||
fn compile_exec_optimized(source: &str) -> CodeObject {
|
||||
let opts = CompileOpts {
|
||||
optimize: 1,
|
||||
..CompileOpts::default()
|
||||
};
|
||||
compile_exec_with_options(source, opts)
|
||||
}
|
||||
|
||||
fn compile_exec_with_options(source: &str, opts: CompileOpts) -> CodeObject {
|
||||
let source_file = SourceFileBuilder::new("source_path", source).finish();
|
||||
let parsed = ruff_python_parser::parse(
|
||||
source_file.source_text(),
|
||||
@@ -9137,6 +9149,15 @@ x = Test() and False or False
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_const_bool_not_op() {
|
||||
assert_dis_snapshot!(compile_exec_optimized(
|
||||
"\
|
||||
x = not True
|
||||
"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_double_async_with() {
|
||||
assert_dis_snapshot!(compile_exec(
|
||||
|
||||
@@ -693,6 +693,33 @@ impl CodeInfo {
|
||||
None
|
||||
}
|
||||
}
|
||||
(Instruction::LoadConst { consti }, Instruction::ToBool) => {
|
||||
let consti = consti.get(curr.arg);
|
||||
let constant = &self.metadata.consts[consti as usize];
|
||||
if let ConstantData::Boolean { .. } = constant {
|
||||
Some((curr_instr, OpArg::from(consti)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
(Instruction::LoadConst { consti }, Instruction::UnaryNot) => {
|
||||
let constant = &self.metadata.consts[consti.get(curr.arg) as usize];
|
||||
match constant {
|
||||
ConstantData::Boolean { value } => {
|
||||
let (const_idx, _) = self
|
||||
.metadata
|
||||
.consts
|
||||
.insert_full(ConstantData::Boolean { value: !value });
|
||||
Some((
|
||||
(Instruction::LoadConst {
|
||||
consti: Arg::marker(),
|
||||
}),
|
||||
OpArg::new(const_idx as u32),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
|
||||
9
crates/codegen/src/snapshots/rustpython_codegen__compile__tests__const_bool_not_op.snap
generated
Normal file
9
crates/codegen/src/snapshots/rustpython_codegen__compile__tests__const_bool_not_op.snap
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: crates/codegen/src/compile.rs
|
||||
expression: "compile_exec_optimized(\"\\\nx = not True\n\")"
|
||||
---
|
||||
1 0 RESUME (0)
|
||||
1 LOAD_CONST (False)
|
||||
2 STORE_NAME (0, x)
|
||||
3 LOAD_CONST (None)
|
||||
4 RETURN_VALUE
|
||||
Reference in New Issue
Block a user