strip down while-loops with constant condition
authorStefan Behnel <stefan_ml@behnel.de>
Mon, 11 Mar 2013 09:33:59 +0000 (10:33 +0100)
committerStefan Behnel <stefan_ml@behnel.de>
Mon, 11 Mar 2013 09:33:59 +0000 (10:33 +0100)
Cython/Compiler/Optimize.py
tests/run/constant_folding.py

index 6c67d0b..3ea542f 100644 (file)
@@ -3241,6 +3241,15 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations):
             node.iterator.sequence = sequence.as_tuple()
         return node
 
+    def visit_WhileStatNode(self, node):
+        self.visitchildren(node)
+        if node.condition.has_constant_result():
+            if node.condition.constant_result:
+                node.else_clause = None
+            else:
+                return node.else_clause
+        return node
+
     def _find_genexpr_yield_stat(self, node):
         body_node_types = (Nodes.ForInStatNode, Nodes.IfStatNode)
         while isinstance(node, body_node_types):
index 8e6952f..1040bd6 100644 (file)
@@ -143,3 +143,45 @@ def str_in_and_not_in():
     """
     if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': return True
     else: return False
+
+
+@cython.test_fail_if_path_exists(
+    "//WhileStatNode",
+)
+def while_false():
+    """
+    >>> while_false()
+    """
+    while 1 == 0:
+        return False
+
+
+@cython.test_fail_if_path_exists(
+    "//WhileStatNode",
+    )
+def while_false_else():
+    """
+    >>> while_false_else()
+    True
+    """
+    while 1 == 0:
+        return False
+    else:
+        return True
+
+
+@cython.test_fail_if_path_exists(
+    "//WhileStatNode//PrintStatNode",
+)
+@cython.test_assert_path_exists(
+    "//WhileStatNode",
+)
+def while_true():
+    """
+    >>> while_true()
+    True
+    """
+    while 1 == 1:
+        return True
+    else:
+        print("FAIL")