summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorda-woods <dw-git@d-woods.co.uk>2021-09-03 07:44:37 +0100
committerGitHub <noreply@github.com>2021-09-03 08:44:37 +0200
commitc830db8111be7a7eb1753f4c2fa04c4dbbe3ffdc (patch)
treefa332cd3ebd4123ae0c80b9ee829e63d6fbcc647
parentba6eba21e82e34a14bdae4996fd0b9b297c40f72 (diff)
downloadcython-c830db8111be7a7eb1753f4c2fa04c4dbbe3ffdc.tar.gz
Fix C++ bool coercion where no "operator bool" exists (GH-4349)
This was causing c++ classes in if-statements to crash. Fixes #4348
-rw-r--r--Cython/Compiler/ExprNodes.py4
-rw-r--r--tests/errors/cpp_bool.pyx13
2 files changed, 15 insertions, 2 deletions
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py
index a2ccc465c..193eece7e 100644
--- a/Cython/Compiler/ExprNodes.py
+++ b/Cython/Compiler/ExprNodes.py
@@ -1102,11 +1102,11 @@ class ExprNode(Node):
return self
elif type.is_pyobject or type.is_int or type.is_ptr or type.is_float:
return CoerceToBooleanNode(self, env)
- elif type.is_cpp_class:
+ elif type.is_cpp_class and type.scope and type.scope.lookup("operator bool"):
return SimpleCallNode(
self.pos,
function=AttributeNode(
- self.pos, obj=self, attribute='operator bool'),
+ self.pos, obj=self, attribute=StringEncoding.EncodedString('operator bool')),
args=[]).analyse_types(env)
elif type.is_ctuple:
bool_value = len(type.components) == 0
diff --git a/tests/errors/cpp_bool.pyx b/tests/errors/cpp_bool.pyx
new file mode 100644
index 000000000..15fa4d510
--- /dev/null
+++ b/tests/errors/cpp_bool.pyx
@@ -0,0 +1,13 @@
+# tag: cpp
+# mode: error
+
+from libcpp.string cimport string
+
+cdef foo():
+ cdef string field
+ if field: # field cannot be coerced to book
+ pass
+
+_ERRORS = u"""
+8:7: Type 'string' not acceptable as a boolean
+"""