From 4cfaa9f6dd3d7f8ecd7da80ab224fbc3ad4be514 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Mon, 11 Mar 2013 10:33:59 +0100 Subject: [PATCH] strip down while-loops with constant condition --- Cython/Compiler/Optimize.py | 9 +++++++++ tests/run/constant_folding.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index 6c67d0b..3ea542f 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -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): diff --git a/tests/run/constant_folding.py b/tests/run/constant_folding.py index 8e6952f..1040bd6 100644 --- a/tests/run/constant_folding.py +++ b/tests/run/constant_folding.py @@ -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") -- 2.7.4