Skip to content

Do not pollute stack when if-expression condition evaluated to False #1098

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion compiler/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1426,11 +1426,15 @@ impl Compiler {
ast::Expression::IfExpression { test, body, orelse } => {
let no_label = self.new_label();
let end_label = self.new_label();
self.compile_test(test, None, Some(no_label), EvalContext::Expression)?;
self.compile_test(test, None, None, EvalContext::Expression)?;
self.emit(Instruction::JumpIfFalse { target: no_label });
// True case
self.compile_expression(body)?;
self.emit(Instruction::Jump { target: end_label });
// False case
self.set_label(no_label);
self.compile_expression(orelse)?;
// End
self.set_label(end_label);
}
}
Expand Down
26 changes: 26 additions & 0 deletions tests/snippets/if_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def ret(expression):
return expression


assert ret("0" if True else "1") == "0"
assert ret("0" if False else "1") == "1"

assert ret("0" if False else ("1" if True else "2")) == "1"
assert ret("0" if False else ("1" if False else "2")) == "2"

assert ret(("0" if True else "1") if True else "2") == "0"
assert ret(("0" if False else "1") if True else "2") == "1"

a = True
b = False
assert ret("0" if a or b else "1") == "0"
assert ret("0" if a and b else "1") == "1"


def func1():
return 0

def func2():
return 20

assert ret(func1() or func2()) == 20