Fold const bool with unary not (#7357)

* Fold const bool with unary not

* Fold unnecessary TO_BOOL
This commit is contained in:
Lee Dogeon
2026-03-05 23:00:47 +09:00
committed by GitHub
parent 73941b2255
commit 6f07745600
3 changed files with 57 additions and 0 deletions

View File

@@ -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(

View File

@@ -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,
}
};

View 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