Skip to content

Commit

Permalink
pythonGH-95921: Fix positions for some chained comparisons (pythonGH-…
Browse files Browse the repository at this point in the history
brandtbucher authored Sep 20, 2022
1 parent 8563966 commit dfc73b5
Showing 3 changed files with 28 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
@@ -1077,6 +1077,31 @@ def aug():
check_op_count(aug, "STORE_SLICE", 1)
check_op_count(aug, "BUILD_SLICE", 0)

def test_compare_positions(self):
for opname, op in [
("COMPARE_OP", "<"),
("COMPARE_OP", "<="),
("COMPARE_OP", ">"),
("COMPARE_OP", ">="),
("CONTAINS_OP", "in"),
("CONTAINS_OP", "not in"),
("IS_OP", "is"),
("IS_OP", "is not"),
]:
expr = f'a {op} b {op} c'
expected_positions = 2 * [(2, 2, 0, len(expr))]
for source in [
f"\\\n{expr}", f'if \\\n{expr}: x', f"x if \\\n{expr} else y"
]:
code = compile(source, "<test>", "exec")
actual_positions = [
instruction.positions
for instruction in dis.get_instructions(code)
if instruction.opname == opname
]
with self.subTest(source):
self.assertEqual(actual_positions, expected_positions)


@requires_debug_ranges()
class TestSourcePositions(unittest.TestCase):
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix overly-broad source position information for chained comparisons used as
branching conditions.
1 change: 1 addition & 0 deletions Python/compile.c
Original file line number Diff line number Diff line change
@@ -2905,6 +2905,7 @@ compiler_jump_if(struct compiler *c, expr_ty e, jump_target_label next, int cond
return 1;
}
case Compare_kind: {
SET_LOC(c, e);
Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
if (n > 0) {
if (!check_compare(c, e)) {

0 comments on commit dfc73b5

Please sign in to comment.