From 81542476b40b30c472c1d5522217dd88b46de36a Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Thu, 28 Apr 2011 15:57:42 +0200 Subject: [PATCH] optimise away conditional expressions (x if cond else y) based on constant condition results --- Cython/Compiler/Optimize.py | 9 +++++++++ tests/run/ifelseexpr_T267.pyx | 2 ++ 2 files changed, 11 insertions(+) diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index 53824cf2..804824d4 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -3138,6 +3138,15 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): return ExprNodes.BoolNode(node.pos, value=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): self.visitchildren(node) # eliminate dead code based on constant condition results diff --git a/tests/run/ifelseexpr_T267.pyx b/tests/run/ifelseexpr_T267.pyx index 227b4a21..062c751b 100644 --- a/tests/run/ifelseexpr_T267.pyx +++ b/tests/run/ifelseexpr_T267.pyx @@ -36,6 +36,7 @@ def nested(x): """ return 1 if x == 1 else (2 if x == 2 else 3) +@cython.test_fail_if_path_exists('//CondExprNode') def const_true(): """ >>> const_true() @@ -43,6 +44,7 @@ def const_true(): """ return 1 if 1 == 1 else 2 +@cython.test_fail_if_path_exists('//CondExprNode') def const_false(): """ >>> const_false() -- 2.26.2