Commit 81542476 authored by Stefan Behnel's avatar Stefan Behnel

optimise away conditional expressions (x if cond else y) based on constant condition results

parent b709a5a6
...@@ -3138,6 +3138,15 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): ...@@ -3138,6 +3138,15 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations):
return ExprNodes.BoolNode(node.pos, value=bool_result, return ExprNodes.BoolNode(node.pos, value=bool_result,
constant_result=bool_result) constant_result=bool_result)
def visit_CondExprNode(self, node):
self._calculate_const(node)
if node.test.constant_result is ExprNodes.not_a_constant:
return node
if node.test.constant_result:
return node.true_val
else:
return node.false_val
def visit_IfStatNode(self, node): def visit_IfStatNode(self, node):
self.visitchildren(node) self.visitchildren(node)
# eliminate dead code based on constant condition results # eliminate dead code based on constant condition results
......
...@@ -36,6 +36,7 @@ def nested(x): ...@@ -36,6 +36,7 @@ def nested(x):
""" """
return 1 if x == 1 else (2 if x == 2 else 3) return 1 if x == 1 else (2 if x == 2 else 3)
@cython.test_fail_if_path_exists('//CondExprNode')
def const_true(): def const_true():
""" """
>>> const_true() >>> const_true()
...@@ -43,6 +44,7 @@ def const_true(): ...@@ -43,6 +44,7 @@ def const_true():
""" """
return 1 if 1 == 1 else 2 return 1 if 1 == 1 else 2
@cython.test_fail_if_path_exists('//CondExprNode')
def const_false(): def const_false():
""" """
>>> const_false() >>> const_false()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment