optimise away conditional expressions (x if cond else y) based on constant condition...
authorStefan Behnel <scoder@users.berlios.de>
Thu, 28 Apr 2011 13:57:42 +0000 (15:57 +0200)
committerStefan Behnel <scoder@users.berlios.de>
Thu, 28 Apr 2011 13:57:42 +0000 (15:57 +0200)
Cython/Compiler/Optimize.py
tests/run/ifelseexpr_T267.pyx

index 53824cf238c3bb6ebda3d4e147302b6dd7e5b7e1..804824d476e8db1682b51275be76f936500b4eb6 100644 (file)
@@ -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
index 227b4a2198a6833dcfadc27d66eebd461118a477..062c751b8e78fb8dfd8bd6efe2a6c4d58e026f2e 100644 (file)
@@ -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()