8000 Fold const bool with unary not (#7357) · RustPython/RustPython@6f07745 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6f07745

Browse files
authored
Fold const bool with unary not (#7357)
* Fold const bool with unary not * Fold unnecessary TO_BOOL
1 parent 73941b2 commit 6f07745

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

crates/codegen/src/compile.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9069,6 +9069,18 @@ mod tests {
90699069

90709070
fn compile_exec(source: &str) -> CodeObject {
90719071
let opts = CompileOpts::default();
9072+
compile_exec_with_options(source, opts)
9073+
}
9074+
9075+
fn compile_exec_optimized(source: &str) -> CodeObject {
9076+
let opts = CompileOpts {
9077+
optimize: 1,
9078+
..CompileOpts::default()
9079+
};
9080+
compile_exec_with_options(source, opts)
9081+
}
9082+
9083+
fn compile_exec_with_options(source: &str, opts: CompileOpts) -> CodeObject {
90729084
let source_file = SourceFileBuilder::new("source_path", source).finish();
90739085
let parsed = ruff_python_parser::parse(
90749086
source_file.source_text(),
@@ -9137,6 +9149,15 @@ x = Test() and False or False
91379149
));
91389150
}
91399151

9152+
#[test]
9153+
fn test_const_bool_not_op() {
9154+
assert_dis_snapshot!(compile_exec_optimized(
9155+
"\
9156+
x = not True
9157+
"
9158+
));
9159+
}
9160+
91409161
#[test]
91419162
fn test_nested_double_async_with() {
91429163
assert_dis_snapshot!(compile_exec(

crates/codegen/src/ir.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,33 @@ impl CodeInfo {
693693
None
694694
}
695695
}
696+
(Instruction::LoadConst { consti }, Instruction::ToBool) => {
697+
let consti = consti.get(curr.arg);
698+
let constant = &self.metadata.consts[consti as usize];
699+
if let ConstantData::Boolean { .. } = constant {
700+
Some((curr_instr, OpArg::from(consti)))
701+
} else {
702+
None
703+
}
704+
}
705+
(Instruction::LoadConst { consti }, Instruction::UnaryNot) => {
706+
let constant = &self.metadata.consts[consti.get(curr.arg) as usize];
707+
match constant {
708+
ConstantData::Boolean { value } => {
709+
let (const_idx, _) = self
710+
.metadata
711+
.consts
712+
.insert_full(ConstantData::Boolean { value: !value });
713+
Some((
714+
(Instruction::LoadConst {
715+
consti: Arg::marker(),
716+
}),
717+
OpArg::new(const_idx as u32),
718+
))
719+
}
720+
_ => None,
721+
}
722+
}
696723
_ => None,
697724
}
698725
};

crates/codegen/src/snapshots/rustpython_codegen__compile__tests__const_bool_not_op.snap

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
0