From 41e1d225d8f58e575a4a4d3eede4d0d1f516fe93 Mon Sep 17 00:00:00 2001 From: da-woods Date: Fri, 3 Sep 2021 07:44:37 +0100 Subject: Fix C++ bool coercion where no "operator bool" exists (GH-4349) This was causing c++ classes in if-statements to crash. Fixes #4348 --- Cython/Compiler/ExprNodes.py | 4 ++-- tests/errors/cpp_bool.pyx | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 tests/errors/cpp_bool.pyx diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py index 719b7f2bf..9162eaad9 100644 --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -1012,11 +1012,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 +""" -- cgit v1.2.1