Skip to content

Commit 96f6646

Browse files
authored
Merge pull request RustPython#1098 from mkurnikov/pass-if-expression-to-function
Do not pollute stack when if-expression condition evaluated to False
2 parents 4a108c1 + 8162b87 commit 96f6646

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

compiler/src/compile.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1426,11 +1426,15 @@ impl Compiler {
14261426
ast::Expression::IfExpression { test, body, orelse } => {
14271427
let no_label = self.new_label();
14281428
let end_label = self.new_label();
1429-
self.compile_test(test, None, Some(no_label), EvalContext::Expression)?;
1429+
self.compile_test(test, None, None, EvalContext::Expression)?;
1430+
self.emit(Instruction::JumpIfFalse { target: no_label });
1431+
// True case
14301432
self.compile_expression(body)?;
14311433
self.emit(Instruction::Jump { target: end_label });
1434+
// False case
14321435
self.set_label(no_label);
14331436
self.compile_expression(orelse)?;
1437+
// End
14341438
self.set_label(end_label);
14351439
}
14361440
}

tests/snippets/if_expressions.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def ret(expression):
2+
return expression
3+
4+
5+
assert ret("0" if True else "1") == "0"
6+
assert ret("0" if False else "1") == "1"
7+
8+
assert ret("0" if False else ("1" if True else "2")) == "1"
9+
assert ret("0" if False else ("1" if False else "2")) == "2"
10+
11+
assert ret(("0" if True else "1") if True else "2") == "0"
12+
assert ret(("0" if False else "1") if True else "2") == "1"
13+
14+
a = True
15+
b = False
16+
assert ret("0" if a or b else "1") == "0"
17+
assert ret("0" if a and b else "1") == "1"
18+
19+
20+
def func1():
21+
return 0
22+
23+
def func2():
24+
return 20
25+
26+
assert ret(func1() or func2()) == 20

0 commit comments

Comments
 (0)