Skip to content

Commit

Permalink
Fix C++ bool coercion where no "operator bool" exists (GH-4349)
Browse files Browse the repository at this point in the history
This was causing c++ classes in if-statements to crash.
Fixes #4348
  • Loading branch information
da-woods committed Sep 3, 2021
1 parent ba6eba2 commit c830db8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Cython/Compiler/ExprNodes.py
Expand Up @@ -1102,11 +1102,11 @@ def coerce_to_boolean(self, env):
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
Expand Down
13 changes: 13 additions & 0 deletions 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
"""

0 comments on commit c830db8

Please sign in to comment.