From 68b24fae5c061a3c5480b040aecaaa793817e02c Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Tue, 4 May 2010 21:11:33 +0200 Subject: [PATCH] collapse BoolBinopNode during constant folding, small fix for BoolNode folding --- Cython/Compiler/Optimize.py | 23 ++++++++++++++++++++++- tests/run/bint_binop_T145.pyx | 6 ++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index 3a36989d..35ae0ac5 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -2526,6 +2526,24 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): self._calculate_const(node) return node + def visit_BoolBinopNode(self, node): + self._calculate_const(node) + if node.constant_result is ExprNodes.not_a_constant: + return node + if not node.operand1.is_literal or not node.operand2.is_literal: + # We calculate other constants to make them available to + # the compiler, but we only aggregate constant nodes + # recursively, so non-const nodes are straight out. + return node + + if node.constant_result == node.operand1.constant_result and node.operand1.is_literal: + return node.operand1 + elif node.constant_result == node.operand2.constant_result and node.operand2.is_literal: + return node.operand2 + else: + # FIXME: we could do more ... + return node + def visit_BinopNode(self, node): self._calculate_const(node) if node.constant_result is ExprNodes.not_a_constant: @@ -2568,7 +2586,10 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): new_node = target_class(pos=node.pos, type = widest_type) new_node.constant_result = node.constant_result - new_node.value = str(node.constant_result) + if isinstance(node, ExprNodes.BoolNode): + new_node.value = node.constant_result + else: + new_node.value = str(node.constant_result) #new_node = new_node.coerce_to(node.type, self.current_scope) return new_node diff --git a/tests/run/bint_binop_T145.pyx b/tests/run/bint_binop_T145.pyx index c23232a8..2717272e 100644 --- a/tests/run/bint_binop_T145.pyx +++ b/tests/run/bint_binop_T145.pyx @@ -1,4 +1,7 @@ +cimport cython + +@cython.test_fail_if_path_exists('//BoolBinopNode') def or_literal_bint(): """ >>> True or 5 @@ -8,6 +11,7 @@ def or_literal_bint(): """ return True or 5 +@cython.test_fail_if_path_exists('//BoolBinopNode') def and_literal_bint(): """ >>> 5 and True @@ -17,6 +21,7 @@ def and_literal_bint(): """ return 5 and True +@cython.test_fail_if_path_exists('//BoolBinopNode') def False_and_True_or_0(): """ >>> False and True or 0 @@ -26,6 +31,7 @@ def False_and_True_or_0(): """ return False and True or 0 +@cython.test_fail_if_path_exists('//BoolBinopNode') def True_and_True_or_0(): """ >>> True and True or 0 -- 2.26.2