fix '<int>bool(<int>x)' to always return 0 or 1 instead of plain '<int>x'
authorStefan Behnel <scoder@users.berlios.de>
Thu, 25 Nov 2010 06:03:10 +0000 (07:03 +0100)
committerStefan Behnel <scoder@users.berlios.de>
Thu, 25 Nov 2010 06:03:10 +0000 (07:03 +0100)
Cython/Compiler/Optimize.py
tests/run/boolean_context.pyx

index c8abd0d4d606f00e929cf579d7c9fff09182fa24..c39c9e7474ba6a6e09dadf93ea45d6e736a0a9dd 100644 (file)
@@ -1860,8 +1860,12 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform):
             self._error_wrong_arg_count('bool', node, pos_args, '0 or 1')
             return node
         else:
-            return pos_args[0].coerce_to_boolean(
-                self.current_env()).coerce_to_pyobject(self.current_env())
+            # => !!<bint>(x)  to make sure it's exactly 0 or 1
+            operand = pos_args[0].coerce_to_boolean(self.current_env())
+            operand = ExprNodes.NotNode(node.pos, operand = operand)
+            operand = ExprNodes.NotNode(node.pos, operand = operand)
+            # coerce back to Python object as that's the result we are expecting
+            return operand.coerce_to_pyobject(self.current_env())
 
     ### builtin functions
 
index f6d59e1b351f70e56c2e09a34bb1a45791a2c923..21269f222e46f233d707e8053f14a5c25e874571 100644 (file)
@@ -5,4 +5,13 @@ def test():
     True
     """
     cdef int x = 5
-    print bool(x)
+    return bool(x)
+
+def test_bool_and_int():
+    """
+    >>> test_bool_and_int()
+    1
+    """
+    cdef int x = 5
+    cdef int b = bool(x)
+    return b