diff options
author | da-woods <dw-git@d-woods.co.uk> | 2021-09-03 07:44:37 +0100 |
---|---|---|
committer | Stefan Behnel <stefan_ml@behnel.de> | 2021-09-03 08:45:45 +0200 |
commit | 41e1d225d8f58e575a4a4d3eede4d0d1f516fe93 (patch) | |
tree | 4d552a840cff77fcd0501daf4ac3e04b4ea873e0 | |
parent | 54b0bf52a86126a98d76823dbc5d780f7e940895 (diff) | |
download | cython-41e1d225d8f58e575a4a4d3eede4d0d1f516fe93.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.py | 4 | ||||
-rw-r--r-- | tests/errors/cpp_bool.pyx | 13 |
2 files changed, 15 insertions, 2 deletions
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 +""" |