Skip to content

Commit 02b9ef2

Browse files
bpo-32439: Clean up the code for compiling comparison expressions. (#5029)
1 parent f111b3d commit 02b9ef2

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

Python/compile.c

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3420,35 +3420,32 @@ static int
34203420
compiler_compare(struct compiler *c, expr_ty e)
34213421
{
34223422
Py_ssize_t i, n;
3423-
basicblock *cleanup = NULL;
34243423

3425-
/* XXX the logic can be cleaned up for 1 or multiple comparisons */
34263424
VISIT(c, expr, e->v.Compare.left);
3427-
n = asdl_seq_LEN(e->v.Compare.ops);
3428-
assert(n > 0);
3429-
if (n > 1) {
3430-
cleanup = compiler_new_block(c);
3425+
assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3426+
n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3427+
if (n == 0) {
3428+
VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3429+
ADDOP_I(c, COMPARE_OP,
3430+
cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3431+
}
3432+
else {
3433+
basicblock *cleanup = compiler_new_block(c);
34313434
if (cleanup == NULL)
34323435
return 0;
3433-
VISIT(c, expr,
3434-
(expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3435-
}
3436-
for (i = 1; i < n; i++) {
3437-
ADDOP(c, DUP_TOP);
3438-
ADDOP(c, ROT_THREE);
3439-
ADDOP_I(c, COMPARE_OP,
3440-
cmpop((cmpop_ty)(asdl_seq_GET(
3441-
e->v.Compare.ops, i - 1))));
3442-
ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3443-
NEXT_BLOCK(c);
3444-
if (i < (n - 1))
3436+
for (i = 0; i < n; i++) {
34453437
VISIT(c, expr,
34463438
(expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3447-
}
3448-
VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3449-
ADDOP_I(c, COMPARE_OP,
3450-
cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3451-
if (n > 1) {
3439+
ADDOP(c, DUP_TOP);
3440+
ADDOP(c, ROT_THREE);
3441+
ADDOP_I(c, COMPARE_OP,
3442+
cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3443+
ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3444+
NEXT_BLOCK(c);
3445+
}
3446+
VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3447+
ADDOP_I(c, COMPARE_OP,
3448+
cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
34523449
basicblock *end = compiler_new_block(c);
34533450
if (end == NULL)
34543451
return 0;

0 commit comments

Comments
 (0)