repo
stringclasses
358 values
pull_number
int64
6
67.9k
instance_id
stringlengths
12
49
issue_numbers
listlengths
1
7
base_commit
stringlengths
40
40
patch
stringlengths
87
101M
test_patch
stringlengths
72
22.3M
problem_statement
stringlengths
3
256k
hints_text
stringlengths
0
545k
created_at
stringlengths
20
20
PASS_TO_PASS
listlengths
0
0
FAIL_TO_PASS
listlengths
0
0
cython/cython
2,607
cython__cython-2607
[ "2499" ]
c6320307ef3127af127efcfa68c5bc44a9d36155
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -4256,7 +4256,10 @@ def generate_function_definitions(self, env, code): code.put_xgiveref(Naming.retval_cname) else: code.put_xdecref_clear(Naming.retval_cname, py_object_type) + # For Py3.7, clearing is already done below. + code.putln("#if !CYTHON_USE_EXC_INFO_STACK") code.putln("__Pyx_Coroutine_ResetAndClearException(%s);" % Naming.generator_cname) + code.putln("#endif") code.putln('%s->resume_label = -1;' % Naming.generator_cname) # clean up as early as possible to help breaking any reference cycles code.putln('__Pyx_Coroutine_clear((PyObject*)%s);' % Naming.generator_cname) @@ -7408,7 +7411,9 @@ def generate_handling_code(self, code, end_label): if not self.body.is_terminator: for var in exc_vars: - code.put_decref_clear(var, py_object_type) + # FIXME: XDECREF() is needed to allow re-raising (which clears the exc_vars), + # but I don't think it's the right solution. + code.put_xdecref_clear(var, py_object_type) code.put_goto(end_label) for new_label, old_label in [(code.break_label, old_break_label), diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -145,6 +145,7 @@ def get_distutils_distro(_cache=[]): 'Coverage': 'Cython.Coverage', 'tag:ipython': 'IPython.testing.globalipapp', 'tag:jedi': 'jedi_BROKEN_AND_DISABLED', + 'tag:test.support': 'test.support', # support module for CPython unit tests } def patch_inspect_isfunction(): @@ -433,6 +434,7 @@ def get_openmp_compiler_flags(language): 'run.py35_asyncio_async_def', 'run.mod__spec__', 'run.pep526_variable_annotations', # typing module + 'run.test_exceptions', # copied from Py3.7+ ]), }
diff --git a/tests/run/test_exceptions.pyx b/tests/run/test_exceptions.pyx new file mode 100644 --- /dev/null +++ b/tests/run/test_exceptions.pyx @@ -0,0 +1,1367 @@ +# Python test set -- part 5, built-in exceptions +# Copied from CPython 3.7. + +# cython: language_level=3 +# mode: run +# tag: generator, exception, tryfinally, tryexcept, test.support + +import copy +import os +import sys +import unittest +import pickle +import weakref +import errno + +from test.support import (TESTFN, captured_stderr, check_impl_detail, + check_warnings, gc_collect, + # no_tracing, cpython_only, + unlink, import_module, script_helper, + SuppressCrashReport) + +no_tracing = unittest.skip("For nested functions, Cython generates a C call without recursion checks.") + +cpython_only = unittest.skip("Tests for _testcapi make no sense here.") + + +class NaiveException(Exception): + def __init__(self, x): + self.x = x + +class SlottedNaiveException(Exception): + __slots__ = ('x',) + def __init__(self, x): + self.x = x + +class BrokenStrException(Exception): + def __str__(self): + raise Exception("str() is broken") + +# XXX This is not really enough, each *operation* should be tested! + +class ExceptionTests(unittest.TestCase): + + def raise_catch(self, exc, excname): + try: + raise exc("spam") + except exc as err: + buf1 = str(err) + try: + raise exc("spam") + except exc as err: + buf2 = str(err) + self.assertEqual(buf1, buf2) + self.assertEqual(exc.__name__, excname) + + def testRaising(self): + self.raise_catch(AttributeError, "AttributeError") + self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") + + self.raise_catch(EOFError, "EOFError") + fp = open(TESTFN, 'w') + fp.close() + fp = open(TESTFN, 'r') + savestdin = sys.stdin + try: + try: + import marshal + marshal.loads(b'') + except EOFError: + pass + finally: + sys.stdin = savestdin + fp.close() + unlink(TESTFN) + + self.raise_catch(OSError, "OSError") + self.assertRaises(OSError, open, 'this file does not exist', 'r') + + self.raise_catch(ImportError, "ImportError") + self.assertRaises(ImportError, __import__, "undefined_module") + + self.raise_catch(IndexError, "IndexError") + x = [] + self.assertRaises(IndexError, x.__getitem__, 10) + + self.raise_catch(KeyError, "KeyError") + x = {} + self.assertRaises(KeyError, x.__getitem__, 'key') + + self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") + + self.raise_catch(MemoryError, "MemoryError") + + self.raise_catch(NameError, "NameError") + #try: x = undefined_variable + #except NameError: pass + + self.raise_catch(OverflowError, "OverflowError") + x = 1 + for dummy in range(128): + x += x # this simply shouldn't blow up + + self.raise_catch(RuntimeError, "RuntimeError") + self.raise_catch(RecursionError, "RecursionError") + + self.raise_catch(SyntaxError, "SyntaxError") + try: exec('/\n') + except SyntaxError: pass + + self.raise_catch(IndentationError, "IndentationError") + + self.raise_catch(TabError, "TabError") + try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", + '<string>', 'exec') + except TabError: pass + else: self.fail("TabError not raised") + + self.raise_catch(SystemError, "SystemError") + + self.raise_catch(SystemExit, "SystemExit") + self.assertRaises(SystemExit, sys.exit, 0) + + self.raise_catch(TypeError, "TypeError") + try: [] + () + except TypeError: pass + + self.raise_catch(ValueError, "ValueError") + self.assertRaises(ValueError, chr, 17<<16) + + self.raise_catch(ZeroDivisionError, "ZeroDivisionError") + try: x = 1/0 + except ZeroDivisionError: pass + + self.raise_catch(Exception, "Exception") + try: x = 1/0 + except Exception as e: pass + + self.raise_catch(StopAsyncIteration, "StopAsyncIteration") + + def testSyntaxErrorMessage(self): + # make sure the right exception message is raised for each of + # these code fragments + + def ckmsg(src, msg): + try: + compile(src, '<fragment>', 'exec') + except SyntaxError as e: + if e.msg != msg: + self.fail("expected %s, got %s" % (msg, e.msg)) + else: + self.fail("failed to get expected SyntaxError") + + s = '''if 1: + try: + continue + except: + pass''' + + ckmsg(s, "'continue' not properly in loop") + ckmsg("continue\n", "'continue' not properly in loop") + + def testSyntaxErrorMissingParens(self): + def ckmsg(src, msg, exception=SyntaxError): + try: + compile(src, '<fragment>', 'exec') + except exception as e: + if e.msg != msg and sys.version_info >= (3, 6): + self.fail("expected %s, got %s" % (msg, e.msg)) + else: + self.fail("failed to get expected SyntaxError") + + s = '''print "old style"''' + ckmsg(s, "Missing parentheses in call to 'print'. " + "Did you mean print(\"old style\")?") + + s = '''print "old style",''' + ckmsg(s, "Missing parentheses in call to 'print'. " + "Did you mean print(\"old style\", end=\" \")?") + + s = '''exec "old style"''' + ckmsg(s, "Missing parentheses in call to 'exec'") + + # should not apply to subclasses, see issue #31161 + s = '''if True:\nprint "No indent"''' + ckmsg(s, "expected an indented block", IndentationError) + + s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' + ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) + + def testSyntaxErrorOffset(self): + def check(src, lineno, offset): + with self.assertRaises(SyntaxError) as cm: + compile(src, '<fragment>', 'exec') + self.assertEqual(cm.exception.lineno, lineno) + self.assertEqual(cm.exception.offset, offset) + + check('def fact(x):\n\treturn x!\n', 2, 10) + check('1 +\n', 1, 4) + check('def spam():\n print(1)\n print(2)', 3, 10) + check('Python = "Python" +', 1, 20) + check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) + + @cpython_only + def testSettingException(self): + # test that setting an exception at the C level works even if the + # exception object can't be constructed. + + class BadException(Exception): + def __init__(self_): + raise RuntimeError("can't instantiate BadException") + + class InvalidException: + pass + + def test_capi1(): + import _testcapi + try: + _testcapi.raise_exception(BadException, 1) + except TypeError as err: + exc, err, tb = sys.exc_info() + co = tb.tb_frame.f_code + self.assertEqual(co.co_name, "test_capi1") + self.assertTrue(co.co_filename.endswith('test_exceptions.py')) + else: + self.fail("Expected exception") + + def test_capi2(): + import _testcapi + try: + _testcapi.raise_exception(BadException, 0) + except RuntimeError as err: + exc, err, tb = sys.exc_info() + co = tb.tb_frame.f_code + self.assertEqual(co.co_name, "__init__") + self.assertTrue(co.co_filename.endswith('test_exceptions.py')) + co2 = tb.tb_frame.f_back.f_code + self.assertEqual(co2.co_name, "test_capi2") + else: + self.fail("Expected exception") + + def test_capi3(): + import _testcapi + self.assertRaises(SystemError, _testcapi.raise_exception, + InvalidException, 1) + + if not sys.platform.startswith('java'): + test_capi1() + test_capi2() + test_capi3() + + def test_WindowsError(self): + try: + WindowsError + except NameError: + pass + else: + self.assertIs(WindowsError, OSError) + self.assertEqual(str(OSError(1001)), "1001") + self.assertEqual(str(OSError(1001, "message")), + "[Errno 1001] message") + # POSIX errno (9 aka EBADF) is untranslated + w = OSError(9, 'foo', 'bar') + self.assertEqual(w.errno, 9) + self.assertEqual(w.winerror, None) + self.assertEqual(str(w), "[Errno 9] foo: 'bar'") + # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) + w = OSError(0, 'foo', 'bar', 3) + self.assertEqual(w.errno, 2) + self.assertEqual(w.winerror, 3) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, 'bar') + self.assertEqual(w.filename2, None) + self.assertEqual(str(w), "[WinError 3] foo: 'bar'") + # Unknown win error becomes EINVAL (22) + w = OSError(0, 'foo', None, 1001) + self.assertEqual(w.errno, 22) + self.assertEqual(w.winerror, 1001) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, None) + self.assertEqual(w.filename2, None) + self.assertEqual(str(w), "[WinError 1001] foo") + # Non-numeric "errno" + w = OSError('bar', 'foo') + self.assertEqual(w.errno, 'bar') + self.assertEqual(w.winerror, None) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, None) + self.assertEqual(w.filename2, None) + + @unittest.skipUnless(sys.platform == 'win32', + 'test specific to Windows') + def test_windows_message(self): + """Should fill in unknown error code in Windows error message""" + ctypes = import_module('ctypes') + # this error code has no message, Python formats it as hexadecimal + code = 3765269347 + with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): + ctypes.pythonapi.PyErr_SetFromWindowsErr(code) + + def testAttributes(self): + # test that exception attributes are happy + + exceptionList = [ + (BaseException, (), {'args' : ()}), + (BaseException, (1, ), {'args' : (1,)}), + (BaseException, ('foo',), + {'args' : ('foo',)}), + (BaseException, ('foo', 1), + {'args' : ('foo', 1)}), + (SystemExit, ('foo',), + {'args' : ('foo',), 'code' : 'foo'}), + (OSError, ('foo',), + {'args' : ('foo',), 'filename' : None, 'filename2' : None, + 'errno' : None, 'strerror' : None}), + (OSError, ('foo', 'bar'), + {'args' : ('foo', 'bar'), + 'filename' : None, 'filename2' : None, + 'errno' : 'foo', 'strerror' : 'bar'}), + (OSError, ('foo', 'bar', 'baz'), + {'args' : ('foo', 'bar'), + 'filename' : 'baz', 'filename2' : None, + 'errno' : 'foo', 'strerror' : 'bar'}), + (OSError, ('foo', 'bar', 'baz', None, 'quux'), + {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), + (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), + {'args' : ('errnoStr', 'strErrorStr'), + 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', + 'filename' : 'filenameStr'}), + (OSError, (1, 'strErrorStr', 'filenameStr'), + {'args' : (1, 'strErrorStr'), 'errno' : 1, + 'strerror' : 'strErrorStr', + 'filename' : 'filenameStr', 'filename2' : None}), + (SyntaxError, (), {'msg' : None, 'text' : None, + 'filename' : None, 'lineno' : None, 'offset' : None, + 'print_file_and_line' : None}), + (SyntaxError, ('msgStr',), + {'args' : ('msgStr',), 'text' : None, + 'print_file_and_line' : None, 'msg' : 'msgStr', + 'filename' : None, 'lineno' : None, 'offset' : None}), + (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', + 'textStr')), + {'offset' : 'offsetStr', 'text' : 'textStr', + 'args' : ('msgStr', ('filenameStr', 'linenoStr', + 'offsetStr', 'textStr')), + 'print_file_and_line' : None, 'msg' : 'msgStr', + 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}), + (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', + 'textStr', 'print_file_and_lineStr'), + {'text' : None, + 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', + 'textStr', 'print_file_and_lineStr'), + 'print_file_and_line' : None, 'msg' : 'msgStr', + 'filename' : None, 'lineno' : None, 'offset' : None}), + (UnicodeError, (), {'args' : (),}), + (UnicodeEncodeError, ('ascii', 'a', 0, 1, + 'ordinal not in range'), + {'args' : ('ascii', 'a', 0, 1, + 'ordinal not in range'), + 'encoding' : 'ascii', 'object' : 'a', + 'start' : 0, 'reason' : 'ordinal not in range'}), + (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, + 'ordinal not in range'), + {'args' : ('ascii', bytearray(b'\xff'), 0, 1, + 'ordinal not in range'), + 'encoding' : 'ascii', 'object' : b'\xff', + 'start' : 0, 'reason' : 'ordinal not in range'}), + (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, + 'ordinal not in range'), + {'args' : ('ascii', b'\xff', 0, 1, + 'ordinal not in range'), + 'encoding' : 'ascii', 'object' : b'\xff', + 'start' : 0, 'reason' : 'ordinal not in range'}), + (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), + {'args' : ('\u3042', 0, 1, 'ouch'), + 'object' : '\u3042', 'reason' : 'ouch', + 'start' : 0, 'end' : 1}), + (NaiveException, ('foo',), + {'args': ('foo',), 'x': 'foo'}), + (SlottedNaiveException, ('foo',), + {'args': ('foo',), 'x': 'foo'}), + ] + try: + # More tests are in test_WindowsError + exceptionList.append( + (WindowsError, (1, 'strErrorStr', 'filenameStr'), + {'args' : (1, 'strErrorStr'), + 'strerror' : 'strErrorStr', 'winerror' : None, + 'errno' : 1, + 'filename' : 'filenameStr', 'filename2' : None}) + ) + except NameError: + pass + + for exc, args, expected in exceptionList: + try: + e = exc(*args) + except: + print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr) + raise + else: + # Verify module name + if not type(e).__name__.endswith('NaiveException'): + self.assertEqual(type(e).__module__, 'builtins') + # Verify no ref leaks in Exc_str() + s = str(e) + for checkArgName in expected: + value = getattr(e, checkArgName) + self.assertEqual(repr(value), + repr(expected[checkArgName]), + '%r.%s == %r, expected %r' % ( + e, checkArgName, + value, expected[checkArgName])) + + # test for pickling support + for p in [pickle]: + for protocol in range(p.HIGHEST_PROTOCOL + 1): + s = p.dumps(e, protocol) + new = p.loads(s) + for checkArgName in expected: + got = repr(getattr(new, checkArgName)) + want = repr(expected[checkArgName]) + self.assertEqual(got, want, + 'pickled "%r", attribute "%s' % + (e, checkArgName)) + + def testWithTraceback(self): + try: + raise IndexError(4) + except: + tb = sys.exc_info()[2] + + e = BaseException().with_traceback(tb) + self.assertIsInstance(e, BaseException) + self.assertEqual(e.__traceback__, tb) + + e = IndexError(5).with_traceback(tb) + self.assertIsInstance(e, IndexError) + self.assertEqual(e.__traceback__, tb) + + class MyException(Exception): + pass + + e = MyException().with_traceback(tb) + self.assertIsInstance(e, MyException) + self.assertEqual(e.__traceback__, tb) + + def testInvalidTraceback(self): + try: + Exception().__traceback__ = 5 + except TypeError as e: + self.assertIn("__traceback__ must be a traceback", str(e)) + else: + self.fail("No exception raised") + + def testInvalidAttrs(self): + self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1) + self.assertRaises(TypeError, delattr, Exception(), '__cause__') + self.assertRaises(TypeError, setattr, Exception(), '__context__', 1) + self.assertRaises(TypeError, delattr, Exception(), '__context__') + + def testNoneClearsTracebackAttr(self): + try: + raise IndexError(4) + except: + tb = sys.exc_info()[2] + + e = Exception() + e.__traceback__ = tb + e.__traceback__ = None + self.assertEqual(e.__traceback__, None) + + def testChainingAttrs(self): + e = Exception() + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + + e = TypeError() + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + + class MyException(OSError): + pass + + e = MyException() + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + + def testChainingDescriptors(self): + try: + raise Exception() + except Exception as exc: + e = exc + + self.assertIsNone(e.__context__) + self.assertIsNone(e.__cause__) + self.assertFalse(e.__suppress_context__) + + e.__context__ = NameError() + e.__cause__ = None + self.assertIsInstance(e.__context__, NameError) + self.assertIsNone(e.__cause__) + self.assertTrue(e.__suppress_context__) + e.__suppress_context__ = False + self.assertFalse(e.__suppress_context__) + + def testKeywordArgs(self): + # test that builtin exception don't take keyword args, + # but user-defined subclasses can if they want + self.assertRaises(TypeError, BaseException, a=1) + + class DerivedException(BaseException): + def __init__(self, fancy_arg): + BaseException.__init__(self) + self.fancy_arg = fancy_arg + + x = DerivedException(fancy_arg=42) + self.assertEqual(x.fancy_arg, 42) + + @no_tracing + def testInfiniteRecursion(self): + def f(): + return f() + self.assertRaises(RecursionError, f) + + def g(): + try: + return g() + except ValueError: + return -1 + self.assertRaises(RecursionError, g) + + def test_str(self): + # Make sure both instances and classes have a str representation. + self.assertTrue(str(Exception)) + self.assertTrue(str(Exception('a'))) + self.assertTrue(str(Exception('a', 'b'))) + + def testExceptionCleanupNames(self): + # Make sure the local variable bound to the exception instance by + # an "except" statement is only visible inside the except block. + try: + raise Exception() + except Exception as e: + self.assertTrue(e) + del e + self.assertNotIn('e', locals()) + + def testExceptionCleanupState(self): + # Make sure exception state is cleaned up as soon as the except + # block is left. See #2507 + + class MyException(Exception): + def __init__(self, obj): + self.obj = obj + class MyObj: + pass + + def inner_raising_func(): + # Create some references in exception value and traceback + local_ref = obj + raise MyException(obj) + + # Qualified "except" with "as" + obj = MyObj() + wr = weakref.ref(obj) + try: + inner_raising_func() + except MyException as e: + pass + obj = None + obj = wr() + self.assertIsNone(obj) + + # Qualified "except" without "as" + obj = MyObj() + wr = weakref.ref(obj) + try: + inner_raising_func() + except MyException: + pass + obj = None + obj = wr() + self.assertIsNone(obj) + + # Bare "except" + obj = MyObj() + wr = weakref.ref(obj) + try: + inner_raising_func() + except: + pass + obj = None + obj = wr() + self.assertIsNone(obj) + + # "except" with premature block leave + obj = MyObj() + wr = weakref.ref(obj) + for i in [0]: + try: + inner_raising_func() + except: + break + obj = None + obj = wr() + self.assertIsNone(obj) + + # "except" block raising another exception + obj = MyObj() + wr = weakref.ref(obj) + try: + try: + inner_raising_func() + except: + raise KeyError + except KeyError as e: + # We want to test that the except block above got rid of + # the exception raised in inner_raising_func(), but it + # also ends up in the __context__ of the KeyError, so we + # must clear the latter manually for our test to succeed. + e.__context__ = None + obj = None + obj = wr() + # guarantee no ref cycles on CPython (don't gc_collect) + if check_impl_detail(cpython=False): + gc_collect() + self.assertIsNone(obj) + + # Some complicated construct + obj = MyObj() + wr = weakref.ref(obj) + try: + inner_raising_func() + except MyException: + try: + try: + raise + finally: + raise + except MyException: + pass + obj = None + if check_impl_detail(cpython=False): + gc_collect() + obj = wr() + self.assertIsNone(obj) + + # Inside an exception-silencing "with" block + class Context: + def __enter__(self): + return self + def __exit__ (self, exc_type, exc_value, exc_tb): + return True + obj = MyObj() + wr = weakref.ref(obj) + with Context(): + inner_raising_func() + obj = None + if check_impl_detail(cpython=False): + gc_collect() + obj = wr() + self.assertIsNone(obj) + + ''' + # This is currently a compile error in Cython-3, although it works in Cython-2 => could also work in Cy-3. + def test_exception_target_in_nested_scope(self): + # issue 4617: This used to raise a SyntaxError + # "can not delete variable 'e' referenced in nested scope" + def print_error(): + e + try: + 1/0 + except Exception as e: + print_error() + # implicit "del e" here + ''' + + def test_generator_leaking(self): + # Test that generator exception state doesn't leak into the calling + # frame + def yield_raise(): + try: + raise KeyError("caught") + except KeyError: + yield sys.exc_info()[0] + yield sys.exc_info()[0] + yield sys.exc_info()[0] + g = yield_raise() + self.assertEqual(next(g), KeyError) + self.assertEqual(sys.exc_info()[0], None) + self.assertEqual(next(g), KeyError) + self.assertEqual(sys.exc_info()[0], None) + self.assertEqual(next(g), None) + + # Same test, but inside an exception handler + try: + raise TypeError("foo") + except TypeError: + g = yield_raise() + self.assertEqual(next(g), KeyError) + self.assertEqual(sys.exc_info()[0], TypeError) + self.assertEqual(next(g), KeyError) + self.assertEqual(sys.exc_info()[0], TypeError) + self.assertEqual(next(g), TypeError) + del g + self.assertEqual(sys.exc_info()[0], TypeError) + + def test_generator_leaking2(self): + # See issue 12475. + def g(): + yield + try: + raise RuntimeError + except RuntimeError: + it = g() + next(it) + try: + next(it) + except StopIteration: + pass + self.assertEqual(sys.exc_info(), (None, None, None)) + + def test_generator_leaking3(self): + # See issue #23353. When gen.throw() is called, the caller's + # exception state should be save and restored. + def g(): + try: + yield + except ZeroDivisionError: + yield sys.exc_info()[1] + it = g() + next(it) + try: + 1/0 + except ZeroDivisionError as e: + self.assertIs(sys.exc_info()[1], e) + gen_exc = it.throw(e) + self.assertIs(sys.exc_info()[1], e) + self.assertIs(gen_exc, e) + self.assertEqual(sys.exc_info(), (None, None, None)) + + def test_generator_leaking4(self): + # See issue #23353. When an exception is raised by a generator, + # the caller's exception state should still be restored. + def g(): + try: + 1/0 + except ZeroDivisionError: + yield sys.exc_info()[0] + raise + it = g() + try: + raise TypeError + except TypeError: + # The caller's exception state (TypeError) is temporarily + # saved in the generator. + tp = next(it) + self.assertIs(tp, ZeroDivisionError) + try: + next(it) + # We can't check it immediately, but while next() returns + # with an exception, it shouldn't have restored the old + # exception state (TypeError). + except ZeroDivisionError as e: + self.assertIs(sys.exc_info()[1], e) + # We used to find TypeError here. + self.assertEqual(sys.exc_info(), (None, None, None)) + + def test_generator_doesnt_retain_old_exc(self): + def g(): + self.assertIsInstance(sys.exc_info()[1], RuntimeError) + yield + self.assertEqual(sys.exc_info(), (None, None, None)) + it = g() + try: + raise RuntimeError + except RuntimeError: + next(it) + self.assertRaises(StopIteration, next, it) + + def test_generator_finalizing_and_exc_info(self): + # See #7173 + def simple_gen(): + yield 1 + def run_gen(): + gen = simple_gen() + try: + raise RuntimeError + except RuntimeError: + return next(gen) + run_gen() + gc_collect() + self.assertEqual(sys.exc_info(), (None, None, None)) + + def _check_generator_cleanup_exc_state(self, testfunc): + # Issue #12791: exception state is cleaned up as soon as a generator + # is closed (reference cycles are broken). + class MyException(Exception): + def __init__(self, obj): + self.obj = obj + class MyObj: + pass + + def raising_gen(): + try: + raise MyException(obj) + except MyException: + yield + + obj = MyObj() + wr = weakref.ref(obj) + g = raising_gen() + next(g) + testfunc(g) + g = obj = None + obj = wr() + self.assertIsNone(obj) + + def test_generator_throw_cleanup_exc_state(self): + def do_throw(g): + try: + g.throw(RuntimeError()) + except RuntimeError: + pass + self._check_generator_cleanup_exc_state(do_throw) + + def test_generator_close_cleanup_exc_state(self): + def do_close(g): + g.close() + self._check_generator_cleanup_exc_state(do_close) + + def test_generator_del_cleanup_exc_state(self): + def do_del(g): + g = None + self._check_generator_cleanup_exc_state(do_del) + + def test_generator_next_cleanup_exc_state(self): + def do_next(g): + try: + next(g) + except StopIteration: + pass + else: + self.fail("should have raised StopIteration") + self._check_generator_cleanup_exc_state(do_next) + + def test_generator_send_cleanup_exc_state(self): + def do_send(g): + try: + g.send(None) + except StopIteration: + pass + else: + self.fail("should have raised StopIteration") + self._check_generator_cleanup_exc_state(do_send) + + def test_3114(self): + # Bug #3114: in its destructor, MyObject retrieves a pointer to + # obsolete and/or deallocated objects. + class MyObject: + def __del__(self): + nonlocal e + e = sys.exc_info() + e = () + try: + raise Exception(MyObject()) + except: + pass + self.assertEqual(e, (None, None, None)) + + def test_unicode_change_attributes(self): + # See issue 7309. This was a crasher. + + u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') + self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") + u.end = 2 + self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") + u.end = 5 + u.reason = 0x345345345345345345 + self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") + u.encoding = 4000 + self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") + u.start = 1000 + self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") + + u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') + self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") + u.end = 2 + self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") + u.end = 5 + u.reason = 0x345345345345345345 + self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") + u.encoding = 4000 + self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") + u.start = 1000 + self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") + + u = UnicodeTranslateError('xxxx', 1, 5, 'foo') + self.assertEqual(str(u), "can't translate characters in position 1-4: foo") + u.end = 2 + self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") + u.end = 5 + u.reason = 0x345345345345345345 + self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") + u.start = 1000 + self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") + + def test_unicode_errors_no_object(self): + # See issue #21134. + klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError + for klass in klasses: + self.assertEqual(str(klass.__new__(klass)), "") + + @no_tracing + def test_badisinstance(self): + # Bug #2542: if issubclass(e, MyException) raises an exception, + # it should be ignored + class Meta(type): + def __subclasscheck__(cls, subclass): + raise ValueError() + class MyException(Exception, metaclass=Meta): + pass + + with captured_stderr() as stderr: + try: + raise KeyError() + except MyException as e: + self.fail("exception should not be a MyException") + except KeyError: + pass + except: + self.fail("Should have raised KeyError") + else: + self.fail("Should have raised KeyError") + + def g(): + try: + return g() + except RecursionError: + return sys.exc_info() + e, v, tb = g() + self.assertIsInstance(v, RecursionError, type(v)) + self.assertIn("maximum recursion depth exceeded", str(v)) + + @cpython_only + def test_recursion_normalizing_exception(self): + # Issue #22898. + # Test that a RecursionError is raised when tstate->recursion_depth is + # equal to recursion_limit in PyErr_NormalizeException() and check + # that a ResourceWarning is printed. + # Prior to #22898, the recursivity of PyErr_NormalizeException() was + # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst + # singleton was being used in that case, that held traceback data and + # locals indefinitely and would cause a segfault in _PyExc_Fini() upon + # finalization of these locals. + code = """if 1: + import sys + from _testcapi import get_recursion_depth + + class MyException(Exception): pass + + def setrecursionlimit(depth): + while 1: + try: + sys.setrecursionlimit(depth) + return depth + except RecursionError: + # sys.setrecursionlimit() raises a RecursionError if + # the new recursion limit is too low (issue #25274). + depth += 1 + + def recurse(cnt): + cnt -= 1 + if cnt: + recurse(cnt) + else: + generator.throw(MyException) + + def gen(): + f = open(%a, mode='rb', buffering=0) + yield + + generator = gen() + next(generator) + recursionlimit = sys.getrecursionlimit() + depth = get_recursion_depth() + try: + # Upon the last recursive invocation of recurse(), + # tstate->recursion_depth is equal to (recursion_limit - 1) + # and is equal to recursion_limit when _gen_throw() calls + # PyErr_NormalizeException(). + recurse(setrecursionlimit(depth + 2) - depth - 1) + finally: + sys.setrecursionlimit(recursionlimit) + print('Done.') + """ % __file__ + rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code) + # Check that the program does not fail with SIGABRT. + self.assertEqual(rc, 1) + self.assertIn(b'RecursionError', err) + self.assertIn(b'ResourceWarning', err) + self.assertIn(b'Done.', out) + + @cpython_only + def test_recursion_normalizing_infinite_exception(self): + # Issue #30697. Test that a RecursionError is raised when + # PyErr_NormalizeException() maximum recursion depth has been + # exceeded. + code = """if 1: + import _testcapi + try: + raise _testcapi.RecursingInfinitelyError + finally: + print('Done.') + """ + rc, out, err = script_helper.assert_python_failure("-c", code) + self.assertEqual(rc, 1) + self.assertIn(b'RecursionError: maximum recursion depth exceeded ' + b'while normalizing an exception', err) + self.assertIn(b'Done.', out) + + @cpython_only + def test_recursion_normalizing_with_no_memory(self): + # Issue #30697. Test that in the abort that occurs when there is no + # memory left and the size of the Python frames stack is greater than + # the size of the list of preallocated MemoryError instances, the + # Fatal Python error message mentions MemoryError. + code = """if 1: + import _testcapi + class C(): pass + def recurse(cnt): + cnt -= 1 + if cnt: + recurse(cnt) + else: + _testcapi.set_nomemory(0) + C() + recurse(16) + """ + with SuppressCrashReport(): + rc, out, err = script_helper.assert_python_failure("-c", code) + self.assertIn(b'Fatal Python error: Cannot recover from ' + b'MemoryErrors while normalizing exceptions.', err) + + @cpython_only + def test_MemoryError(self): + # PyErr_NoMemory always raises the same exception instance. + # Check that the traceback is not doubled. + import traceback + from _testcapi import raise_memoryerror + def raiseMemError(): + try: + raise_memoryerror() + except MemoryError as e: + tb = e.__traceback__ + else: + self.fail("Should have raises a MemoryError") + return traceback.format_tb(tb) + + tb1 = raiseMemError() + tb2 = raiseMemError() + self.assertEqual(tb1, tb2) + + @cpython_only + def test_exception_with_doc(self): + import _testcapi + doc2 = "This is a test docstring." + doc4 = "This is another test docstring." + + self.assertRaises(SystemError, _testcapi.make_exception_with_doc, + "error1") + + # test basic usage of PyErr_NewException + error1 = _testcapi.make_exception_with_doc("_testcapi.error1") + self.assertIs(type(error1), type) + self.assertTrue(issubclass(error1, Exception)) + self.assertIsNone(error1.__doc__) + + # test with given docstring + error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) + self.assertEqual(error2.__doc__, doc2) + + # test with explicit base (without docstring) + error3 = _testcapi.make_exception_with_doc("_testcapi.error3", + base=error2) + self.assertTrue(issubclass(error3, error2)) + + # test with explicit base tuple + class C(object): + pass + error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, + (error3, C)) + self.assertTrue(issubclass(error4, error3)) + self.assertTrue(issubclass(error4, C)) + self.assertEqual(error4.__doc__, doc4) + + # test with explicit dictionary + error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", + error4, {'a': 1}) + self.assertTrue(issubclass(error5, error4)) + self.assertEqual(error5.a, 1) + self.assertEqual(error5.__doc__, "") + + @cpython_only + def test_memory_error_cleanup(self): + # Issue #5437: preallocated MemoryError instances should not keep + # traceback objects alive. + from _testcapi import raise_memoryerror + class C: + pass + wr = None + def inner(): + nonlocal wr + c = C() + wr = weakref.ref(c) + raise_memoryerror() + # We cannot use assertRaises since it manually deletes the traceback + try: + inner() + except MemoryError as e: + self.assertNotEqual(wr(), None) + else: + self.fail("MemoryError not raised") + self.assertEqual(wr(), None) + + @no_tracing + def test_recursion_error_cleanup(self): + # Same test as above, but with "recursion exceeded" errors + class C: + pass + wr = None + def inner(): + nonlocal wr + c = C() + wr = weakref.ref(c) + inner() + # We cannot use assertRaises since it manually deletes the traceback + try: + inner() + except RecursionError as e: + self.assertNotEqual(wr(), None) + else: + self.fail("RecursionError not raised") + self.assertEqual(wr(), None) + + def test_errno_ENOTDIR(self): + # Issue #12802: "not a directory" errors are ENOTDIR even on Windows + with self.assertRaises(OSError) as cm: + os.listdir(__file__) + self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) + + def test_unraisable(self): + # Issue #22836: PyErr_WriteUnraisable() should give sensible reports + class BrokenDel: + def __del__(self): + exc = ValueError("del is broken") + # The following line is included in the traceback report: + raise exc + + class BrokenExceptionDel: + def __del__(self): + exc = BrokenStrException() + # The following line is included in the traceback report: + raise exc + + for test_class in (BrokenDel, BrokenExceptionDel): + with self.subTest(test_class): + obj = test_class() + with captured_stderr() as stderr: + del obj + report = stderr.getvalue() + self.assertIn("Exception ignored", report) + self.assertIn(test_class.__del__.__qualname__, report) + self.assertIn("test_exceptions.py", report) + self.assertIn("raise exc", report) + if test_class is BrokenExceptionDel: + self.assertIn("BrokenStrException", report) + if sys.version_info >= (3, 6): + self.assertIn("<exception str() failed>", report) + else: + self.assertIn("ValueError", report) + self.assertIn("del is broken", report) + if sys.version_info >= (3, 6): + self.assertTrue(report.endswith("\n")) + + def test_unhandled(self): + # Check for sensible reporting of unhandled exceptions + for exc_type in (ValueError, BrokenStrException): + with self.subTest(exc_type): + try: + exc = exc_type("test message") + # The following line is included in the traceback report: + raise exc + except exc_type: + with captured_stderr() as stderr: + sys.__excepthook__(*sys.exc_info()) + report = stderr.getvalue() + self.assertIn("test_exceptions.py", report) + self.assertIn("raise exc", report) + self.assertIn(exc_type.__name__, report) + if exc_type is BrokenStrException: + if sys.version_info >= (3, 6): + self.assertIn("<exception str() failed>", report) + else: + self.assertIn("test message", report) + if sys.version_info >= (3, 6): + self.assertTrue(report.endswith("\n")) + + @cpython_only + def test_memory_error_in_PyErr_PrintEx(self): + code = """if 1: + import _testcapi + class C(): pass + _testcapi.set_nomemory(0, %d) + C() + """ + + # Issue #30817: Abort in PyErr_PrintEx() when no memory. + # Span a large range of tests as the CPython code always evolves with + # changes that add or remove memory allocations. + for i in range(1, 20): + rc, out, err = script_helper.assert_python_failure("-c", code % i) + self.assertIn(rc, (1, 120)) + self.assertIn(b'MemoryError', err) + + def test_yield_in_nested_try_excepts(self): + #Issue #25612 + class MainError(Exception): + pass + + class SubError(Exception): + pass + + def main(): + try: + raise MainError() + except MainError: + try: + yield + except SubError: + pass + raise + + coro = main() + coro.send(None) + with self.assertRaises(MainError): + coro.throw(SubError()) + + @unittest.skip('currently fails') # FIXME: fails in the "inside" assertion but not "outside" + def test_generator_doesnt_retain_old_exc2(self): + #Issue 28884#msg282532 + def g(): + try: + raise ValueError + except ValueError: + yield 1 + self.assertEqual(sys.exc_info(), (None, None, None)) # inside + yield 2 + + gen = g() + + try: + raise IndexError + except IndexError: + self.assertEqual(next(gen), 1) + self.assertEqual(sys.exc_info(), (None, None, None)) # outside + self.assertEqual(next(gen), 2) + + def test_raise_in_generator(self): + #Issue 25612#msg304117 + def g(): + yield 1 + raise + yield 2 + + with self.assertRaises(ZeroDivisionError): + i = g() + try: + 1/0 + except: + next(i) + next(i) + + +class ImportErrorTests(unittest.TestCase): + + @unittest.skipIf(sys.version_info < (3, 6), "Requires Py3.6+") + def test_attributes(self): + # Setting 'name' and 'path' should not be a problem. + exc = ImportError('test') + self.assertIsNone(exc.name) + self.assertIsNone(exc.path) + + exc = ImportError('test', name='somemodule') + self.assertEqual(exc.name, 'somemodule') + self.assertIsNone(exc.path) + + exc = ImportError('test', path='somepath') + self.assertEqual(exc.path, 'somepath') + self.assertIsNone(exc.name) + + exc = ImportError('test', path='somepath', name='somename') + self.assertEqual(exc.name, 'somename') + self.assertEqual(exc.path, 'somepath') + + msg = ("'invalid' is an invalid keyword argument for ImportError" + if sys.version_info >= (3, 7) else ".*keyword argument.*") + with self.assertRaisesRegex(TypeError, msg): + ImportError('test', invalid='keyword') + + with self.assertRaisesRegex(TypeError, msg): + ImportError('test', name='name', invalid='keyword') + + with self.assertRaisesRegex(TypeError, msg): + ImportError('test', path='path', invalid='keyword') + + with self.assertRaisesRegex(TypeError, msg): + ImportError(invalid='keyword') + + with self.assertRaisesRegex(TypeError, msg): + ImportError('test', invalid='keyword', another=True) + + @unittest.skipIf(sys.version_info < (3, 7), "requires Py3.7+") + def test_reset_attributes(self): + exc = ImportError('test', name='name', path='path') + self.assertEqual(exc.args, ('test',)) + self.assertEqual(exc.msg, 'test') + self.assertEqual(exc.name, 'name') + self.assertEqual(exc.path, 'path') + + # Reset not specified attributes + exc.__init__() + self.assertEqual(exc.args, ()) + self.assertEqual(exc.msg, None) + self.assertEqual(exc.name, None) + self.assertEqual(exc.path, None) + + def test_non_str_argument(self): + # Issue #15778 + with check_warnings(('', BytesWarning), quiet=True): + arg = b'abc' + exc = ImportError(arg) + self.assertEqual(str(arg), str(exc)) + + @unittest.skipIf(sys.version_info < (3, 6), "Requires Py3.6+") + def test_copy_pickle(self): + for kwargs in (dict(), + dict(name='somename'), + dict(path='somepath'), + dict(name='somename', path='somepath')): + orig = ImportError('test', **kwargs) + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + exc = pickle.loads(pickle.dumps(orig, proto)) + self.assertEqual(exc.args, ('test',)) + self.assertEqual(exc.msg, 'test') + self.assertEqual(exc.name, orig.name) + self.assertEqual(exc.path, orig.path) + for c in copy.copy, copy.deepcopy: + exc = c(orig) + self.assertEqual(exc.args, ('test',)) + self.assertEqual(exc.msg, 'test') + self.assertEqual(exc.name, orig.name) + self.assertEqual(exc.path, orig.path) + + +if __name__ == '__main__': + unittest.main()
Use exception stack in Py3.7 The exception handling of generators changed significantly in Py3.7. Cython should follow. See the new CPython implementation in https://github.com/python/cpython/commit/ae3087c6382011c47db82fea4d05f8bbf514265d#diff-6b7f39a70f95725eaff0aa0640cc17f6R127 and the corresponding tracker issue in https://bugs.python.org/issue25612 The previous Cython changes in #1956 and the problem description in #1955 are incomplete.
2018-09-15T13:43:11Z
[]
[]
cython/cython
2,608
cython__cython-2608
[ "2593" ]
e59d4dcf6c93e8e4c330bca57cbad90476776531
diff --git a/Cython/Build/Inline.py b/Cython/Build/Inline.py --- a/Cython/Build/Inline.py +++ b/Cython/Build/Inline.py @@ -139,7 +139,7 @@ def _populate_unbound(kwds, unbound_symbols, locals=None, globals=None): def cython_inline(code, get_type=unsafe_type, lib_dir=os.path.join(get_cython_cache_dir(), 'inline'), cython_include_dirs=None, cython_compiler_directives=None, - force=False, quiet=False, locals=None, globals=None, **kwds): + force=False, quiet=False, locals=None, globals=None, language_level=None, **kwds): if get_type is None: get_type = lambda x: 'object' @@ -171,6 +171,11 @@ def cython_inline(code, get_type=unsafe_type, if not quiet: # Parsing from strings not fully supported (e.g. cimports). print("Could not parse code as a string (to extract unbound symbols).") + + cython_compiler_directives = dict(cython_compiler_directives or {}) + if language_level is not None: + cython_compiler_directives['language_level'] = language_level + cimports = [] for name, arg in list(kwds.items()): if arg is cython_module: @@ -178,7 +183,7 @@ def cython_inline(code, get_type=unsafe_type, del kwds[name] arg_names = sorted(kwds) arg_sigs = tuple([(get_type(kwds[arg], ctx), arg) for arg in arg_names]) - key = orig_code, arg_sigs, sys.version_info, sys.executable, Cython.__version__ + key = orig_code, arg_sigs, sys.version_info, sys.executable, language_level, Cython.__version__ module_name = "_cython_inline_" + hashlib.md5(_unicode(key).encode('utf-8')).hexdigest() if module_name in sys.modules: @@ -238,7 +243,7 @@ def __invoke(%(params)s): build_extension.extensions = cythonize( [extension], include_path=cython_include_dirs or ['.'], - compiler_directives=cython_compiler_directives or {}, + compiler_directives=cython_compiler_directives, quiet=quiet) build_extension.build_temp = os.path.dirname(pyx_file) build_extension.build_lib = lib_dir diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -67,9 +67,10 @@ class Context(object): # language_level int currently 2 or 3 for Python 2/3 cython_scope = None + language_level = None # warn when not set but default to Py2 def __init__(self, include_directories, compiler_directives, cpp=False, - language_level=2, options=None): + language_level=None, options=None): # cython_scope is a hack, set to False by subclasses, in order to break # an infinite loop. # Better code organization would fix it. @@ -91,7 +92,8 @@ def __init__(self, include_directories, compiler_directives, cpp=False, os.path.join(os.path.dirname(__file__), os.path.pardir, 'Includes'))) self.include_directories = include_directories + [standard_include_path] - self.set_language_level(language_level) + if language_level is not None: + self.set_language_level(language_level) self.gdb_debug_outputwriter = None @@ -548,9 +550,10 @@ def __init__(self, defaults=None, **kw): ', '.join(unknown_options)) raise ValueError(message) + directive_defaults = Options.get_directive_defaults() directives = dict(options['compiler_directives']) # copy mutable field # check for invalid directives - unknown_directives = set(directives) - set(Options.get_directive_defaults()) + unknown_directives = set(directives) - set(directive_defaults) if unknown_directives: message = "got unknown compiler directive%s: %s" % ( 's' if len(unknown_directives) > 1 else '', @@ -562,7 +565,9 @@ def __init__(self, defaults=None, **kw): warnings.warn("C++ mode forced when in Pythran mode!") options['cplus'] = True if 'language_level' in directives and 'language_level' not in kw: - options['language_level'] = int(directives['language_level']) + options['language_level'] = directives['language_level'] + elif not options.get('language_level'): + options['language_level'] = directive_defaults.get('language_level') if 'formal_grammar' in directives and 'formal_grammar' not in kw: options['formal_grammar'] = directives['formal_grammar'] if options['cache'] is True: @@ -824,7 +829,7 @@ def main(command_line = 0): emit_linenums = False, relative_path_in_code_position_comments = True, c_line_in_traceback = True, - language_level = 2, + language_level = None, # warn but default to 2 formal_grammar = False, gdb_debug = False, compile_time_env = None, diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -197,7 +197,7 @@ def get_directive_defaults(): 'autotestdict': True, 'autotestdict.cdef': False, 'autotestdict.all': False, - 'language_level': 2, + 'language_level': None, 'fast_getattr': False, # Undocumented until we come up with a better way to handle this everywhere. 'py2_import': False, # For backward compatibility of Cython's source code in Py3 source mode 'preliminary_late_includes_cy28': False, # Temporary directive in 0.28, to be removed in a later version (see GH#2079). @@ -299,6 +299,7 @@ def normalise_encoding_name(option_name, encoding): # Override types possibilities above, if needed directive_types = { + 'language_level': int, # values can be None/2/3, where None == 2+warning 'auto_pickle': bool, 'final' : bool, # final cdef classes and methods 'internal' : bool, # cdef class visibility in the module dict diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -3662,6 +3662,17 @@ def p_module(s, pxd, full_module_name, ctx=Ctx): directive_comments = p_compiler_directive_comments(s) s.parse_comments = False + if s.context.language_level is None: + s.context.set_language_level(2) + if pos[0].filename: + import warnings + warnings.warn( + "Cython directive 'language_level' not set, using 2 for now (Py2). " + "This will change in a later release! File: %s" % pos[0].filename, + FutureWarning, + stacklevel=1 if cython.compiled else 2, + ) + doc = p_doc_string(s) if pxd: level = 'module_pxd' diff --git a/Cython/Compiler/Scanning.py b/Cython/Compiler/Scanning.py --- a/Cython/Compiler/Scanning.py +++ b/Cython/Compiler/Scanning.py @@ -147,6 +147,8 @@ class SourceDescriptor(object): """ A SourceDescriptor should be considered immutable. """ + filename = None + _file_type = 'pyx' _escaped_description = None @@ -274,8 +276,6 @@ class StringSourceDescriptor(SourceDescriptor): Instances of this class can be used instead of a filenames if the code originates from a string object. """ - filename = None - def __init__(self, name, code): self.name = name #self.set_file_type_from_name(name) diff --git a/Cython/Compiler/TreeFragment.py b/Cython/Compiler/TreeFragment.py --- a/Cython/Compiler/TreeFragment.py +++ b/Cython/Compiler/TreeFragment.py @@ -29,7 +29,8 @@ def __init__(self, name, include_directories=None, compiler_directives=None, cpp include_directories = [] if compiler_directives is None: compiler_directives = {} - Main.Context.__init__(self, include_directories, compiler_directives, cpp=cpp) + # TODO: see if "language_level=3" also works for our internal code here. + Main.Context.__init__(self, include_directories, compiler_directives, cpp=cpp, language_level=2) self.module_name = name def find_module(self, module_name, relative_to=None, pos=None, need_pxd=1, absolute_fallback=True): diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -2295,8 +2295,8 @@ def runtests(options, cmd_args, coverage=None): sys.stderr.write("Disabling forked testing to support XML test output\n") options.fork = False - if WITH_CYTHON and options.language_level == 3: - sys.stderr.write("Using Cython language level 3.\n") + if WITH_CYTHON: + sys.stderr.write("Using Cython language level %d.\n" % options.language_level) test_bugs = False if options.tickets: diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -156,8 +156,9 @@ def compile_cython_modules(profile=False, compile_more=False, cython_with_refnan extensions[-1].sources[0] = pyx_source_file from Cython.Distutils.build_ext import new_build_ext + from Cython.Compiler.Options import get_directive_defaults + get_directive_defaults()['language_level'] = 2 if profile: - from Cython.Compiler.Options import get_directive_defaults get_directive_defaults()['profile'] = True sys.stderr.write("Enabled profiling for the Cython binary modules\n")
diff --git a/tests/run/test_coroutines_pep492.pyx b/tests/run/test_coroutines_pep492.pyx --- a/tests/run/test_coroutines_pep492.pyx +++ b/tests/run/test_coroutines_pep492.pyx @@ -76,7 +76,7 @@ def exec(code_string, l, g): old_stderr = sys.stderr try: sys.stderr = StringIO() - ns = inline(code_string, locals=l, globals=g, lib_dir=os.path.dirname(__file__)) + ns = inline(code_string, locals=l, globals=g, lib_dir=os.path.dirname(__file__), language_level=3) finally: sys.stderr = old_stderr g.update(ns)
Warn when `language_level` is not set The `language_level` is currently 2 by default and will change to 3 in Cython 3.0. To prepare for that, users should set the `language_level` of their modules/packages explicitly (and preferably migrate to Py3 code while they're at it). Cython 0.29 should emit a warning if it detects a missing `language_level` setting.
2018-09-15T16:08:09Z
[]
[]
cython/cython
2,610
cython__cython-2610
[ "2603" ]
76a8e08fc4fb7fb48e621d8360bfd6f6415258d5
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -5838,7 +5838,7 @@ def generate_result_code(self, code): elif self.type.is_memoryviewslice: assert self.is_temp exc_checks.append(self.type.error_condition(self.result())) - else: + elif func_type.exception_check != '+': exc_val = func_type.exception_value exc_check = func_type.exception_check if exc_val is not None: @@ -5859,20 +5859,22 @@ def generate_result_code(self, code): rhs = typecast(py_object_type, self.type, rhs) else: lhs = "" + if (self.overflowcheck + and self.type.is_int + and self.type.signed + and self.function.result() in ('abs', 'labs', '__Pyx_abs_longlong')): + goto_error = 'if (unlikely(%s < 0)) { PyErr_SetString(PyExc_OverflowError, "value too large"); %s; }' % ( + self.result(), code.error_goto(self.pos)) + elif exc_checks: + goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos) + else: + goto_error = "" if func_type.exception_check == '+': translate_cpp_exception(code, self.pos, '%s%s;' % (lhs, rhs), func_type.exception_value, self.nogil) + if goto_error: + code.putln(goto_error) else: - if (self.overflowcheck - and self.type.is_int - and self.type.signed - and self.function.result() in ('abs', 'labs', '__Pyx_abs_longlong')): - goto_error = 'if (unlikely(%s < 0)) { PyErr_SetString(PyExc_OverflowError, "value too large"); %s; }' % ( - self.result(), code.error_goto(self.pos)) - elif exc_checks: - goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos) - else: - goto_error = "" code.putln("%s%s; %s" % (lhs, rhs, goto_error)) if self.type.is_pyobject and self.result(): code.put_gotref(self.py_result())
diff --git a/tests/run/cpp_exceptions.pyx b/tests/run/cpp_exceptions.pyx --- a/tests/run/cpp_exceptions.pyx +++ b/tests/run/cpp_exceptions.pyx @@ -21,6 +21,8 @@ cdef extern from "cpp_exceptions_helper.h": cdef void raise_typeerror() except + cdef void raise_underflow() except + + cdef raise_or_throw(bint py) except + + cdef cppclass Foo: int bar_raw "bar"(bint fire) except + int bar_value "bar"(bint fire) except +ValueError @@ -98,6 +100,19 @@ def test_underflow(): """ raise_underflow() +def test_func_that_can_raise_or_throw(bint py): + """ + >>> test_func_that_can_raise_or_throw(0) + Traceback (most recent call last): + ... + RuntimeError: oopsie + >>> test_func_that_can_raise_or_throw(1) + Traceback (most recent call last): + ... + ValueError: oopsie + """ + raise_or_throw(py) + def test_int_raw(bint fire): """ >>> test_int_raw(False) diff --git a/tests/run/cpp_exceptions_helper.h b/tests/run/cpp_exceptions_helper.h --- a/tests/run/cpp_exceptions_helper.h +++ b/tests/run/cpp_exceptions_helper.h @@ -1,3 +1,4 @@ +#include <Python.h> #include <ios> #include <new> #include <stdexcept> @@ -61,3 +62,11 @@ void raise_typeerror() { void raise_underflow() { throw std::underflow_error("underflow_error"); } + +PyObject *raise_or_throw(int py) { + if (!py) { + throw std::runtime_error("oopsie"); + } + PyErr_SetString(PyExc_ValueError, "oopsie"); + return NULL; +}
Python exceptions can't propagate from an "except +" function I couldn't find an existing issue for this; hopefully I didn't miss one. Given this code in `test.pyx` ```python # distutils: language = c++ cdef func() except +: raise NotImplementedError() def call_func(): func() ``` the interpreter will segfault if you call `test.call_func()`. This appears to be caused by Cython [disabling all other exception handling](https://github.com/cython/cython/blob/cd594eb1d70148906d4ec9facc69d47cf5241ed5/Cython/Compiler/ExprNodes.py#L5860-L5863) if `except +` is specified, including the check for whether `NULL` was returned after a Python exception was set. My expectation was that I could use the `except +` to handle truly unexpected things like `std::bad_alloc`, while explicitly raising Python exceptions for less exceptional exceptions.
Thanks for the bug report, I'll try to fix this by the next release. On Wed, Sep 12, 2018 at 6:55 PM Matt Wozniski <[email protected]> wrote: > I couldn't find an existing issue for this; hopefully I didn't miss one. > > Given this code in test.pyx > > # distutils: language = c++ > > cdef func() except +: > raise NotImplementedError() > def call_func(): > func() > > the interpreter will segfault if you call test.call_func(). This appears > to be caused by Cython disabling all other exception handling > <https://github.com/cython/cython/blob/cd594eb1d70148906d4ec9facc69d47cf5241ed5/Cython/Compiler/ExprNodes.py#L5860-L5863> > if except + is specified, including the check for whether NULL was > returned after a Python exception was set. > > My expectation was that I could use the except + to handle truly > unexpected things like std::bad_alloc, while explicitly raising Python > exceptions for less exceptional exceptions. > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/cython/cython/issues/2603>, or mute the thread > <https://github.com/notifications/unsubscribe-auth/AAdqgdO2LlNPVzKuvQ9m9XzomJTN2lRHks5uaTyQgaJpZM4Wlylb> > . >
2018-09-17T14:01:49Z
[]
[]
cython/cython
2,620
cython__cython-2620
[ "459" ]
1a91b07ed22781f597a73fb6cf5c3391c5b691c1
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -2340,7 +2340,7 @@ def analyse_declarations(self, env): self.is_c_class_method = env.is_c_class_scope if self.directive_locals is None: self.directive_locals = {} - self.directive_locals.update(env.directives['locals']) + self.directive_locals.update(env.directives.get('locals', {})) if self.directive_returns is not None: base_type = self.directive_returns.analyse_as_type(env) if base_type is None: @@ -2907,7 +2907,7 @@ def analyse_declarations(self, env): self.py_wrapper.analyse_declarations(env) def analyse_argument_types(self, env): - self.directive_locals = env.directives['locals'] + self.directive_locals = env.directives.get('locals', {}) allow_none_for_extension_args = env.directives['allow_none_for_extension_args'] f2s = env.fused_to_specific @@ -4959,7 +4959,7 @@ def generate_type_ready_code(entry, code, heap_type_bases=False): code.putln("if (__Pyx_MergeVtables(&%s) < 0) %s" % ( typeobj_cname, code.error_goto(entry.pos))) - if not type.scope.is_internal and not type.scope.directives['internal']: + if not type.scope.is_internal and not type.scope.directives.get('internal'): # scope.is_internal is set for types defined by # Cython (such as closures), the 'internal' # directive is set by users diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -170,8 +170,6 @@ def get_directive_defaults(): 'nonecheck' : False, 'initializedcheck' : True, 'embedsignature' : False, - 'locals' : {}, - 'exceptval' : None, # (except value=None, check=True) 'auto_cpdef': False, 'auto_pickle': None, 'cdivision': False, # was True before 0.12 @@ -183,12 +181,8 @@ def get_directive_defaults(): 'wraparound' : True, 'ccomplex' : False, # use C99/C++ for complex types and arith 'callspec' : "", - 'final' : False, 'nogil' : False, - 'internal' : False, 'profile': False, - 'no_gc_clear': False, - 'no_gc': False, 'linetrace': False, 'emit_code_comments': True, # copy original source code into C code comments 'annotation_typing': True, # read type declarations from Python function annotations @@ -241,7 +235,6 @@ def get_directive_defaults(): # experimental, subject to change 'binding': None, - 'freelist': 0, 'formal_grammar': False, } @@ -301,7 +294,9 @@ def normalise_encoding_name(option_name, encoding): directive_types = { 'language_level': int, # values can be None/2/3, where None == 2+warning 'auto_pickle': bool, + 'locals': dict, 'final' : bool, # final cdef classes and methods + 'nogil' : bool, 'internal' : bool, # cdef class visibility in the module dict 'infer_types' : bool, # values can be True/None/False 'binding' : bool, @@ -310,7 +305,10 @@ def normalise_encoding_name(option_name, encoding): 'inline' : None, 'staticmethod' : None, 'cclass' : None, + 'no_gc_clear' : bool, + 'no_gc' : bool, 'returns' : type, + 'exceptval': type, # actually (type, check=True/False), but has its own parser 'set_initial_path': str, 'freelist': int, 'c_string_type': one_of('bytes', 'bytearray', 'str', 'unicode'), @@ -325,8 +323,10 @@ def normalise_encoding_name(option_name, encoding): # 'module', 'function', 'class', 'with statement' 'auto_pickle': ('module', 'cclass'), 'final' : ('cclass', 'function'), - 'nogil' : ('function',), + 'nogil' : ('function', 'with statement'), 'inline' : ('function',), + 'cfunc' : ('function', 'with statement'), + 'ccall' : ('function', 'with statement'), 'returns' : ('function',), 'exceptval' : ('function',), 'locals' : ('function',), @@ -334,6 +334,7 @@ def normalise_encoding_name(option_name, encoding): 'no_gc_clear' : ('cclass',), 'no_gc' : ('cclass',), 'internal' : ('cclass',), + 'cclass' : ('class', 'cclass', 'with statement'), 'autotestdict' : ('module',), 'autotestdict.all' : ('module',), 'autotestdict.cdef' : ('module',), diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -958,30 +958,33 @@ def try_to_parse_directive(self, optname, args, kwds, pos): else: assert False - def visit_with_directives(self, body, directives): - olddirectives = self.directives - newdirectives = copy.copy(olddirectives) - newdirectives.update(directives) - self.directives = newdirectives - assert isinstance(body, Nodes.StatListNode), body - retbody = self.visit_Node(body) - directive = Nodes.CompilerDirectivesNode(pos=retbody.pos, body=retbody, - directives=newdirectives) - self.directives = olddirectives - return directive + def visit_with_directives(self, node, directives): + if not directives: + return self.visit_Node(node) + + old_directives = self.directives + new_directives = dict(old_directives) + new_directives.update(directives) + + if new_directives == old_directives: + return self.visit_Node(node) + + self.directives = new_directives + retbody = self.visit_Node(node) + self.directives = old_directives + + if not isinstance(retbody, Nodes.StatListNode): + retbody = Nodes.StatListNode(node.pos, stats=[retbody]) + return Nodes.CompilerDirectivesNode( + pos=retbody.pos, body=retbody, directives=new_directives) # Handle decorators def visit_FuncDefNode(self, node): directives = self._extract_directives(node, 'function') - if not directives: - return self.visit_Node(node) - body = Nodes.StatListNode(node.pos, stats=[node]) - return self.visit_with_directives(body, directives) + return self.visit_with_directives(node, directives) def visit_CVarDefNode(self, node): directives = self._extract_directives(node, 'function') - if not directives: - return self.visit_Node(node) for name, value in directives.items(): if name == 'locals': node.directive_locals = value @@ -990,29 +993,19 @@ def visit_CVarDefNode(self, node): node.pos, "Cdef functions can only take cython.locals(), " "staticmethod, or final decorators, got %s." % name)) - body = Nodes.StatListNode(node.pos, stats=[node]) - return self.visit_with_directives(body, directives) + return self.visit_with_directives(node, directives) def visit_CClassDefNode(self, node): directives = self._extract_directives(node, 'cclass') - if not directives: - return self.visit_Node(node) - body = Nodes.StatListNode(node.pos, stats=[node]) - return self.visit_with_directives(body, directives) + return self.visit_with_directives(node, directives) def visit_CppClassNode(self, node): directives = self._extract_directives(node, 'cppclass') - if not directives: - return self.visit_Node(node) - body = Nodes.StatListNode(node.pos, stats=[node]) - return self.visit_with_directives(body, directives) + return self.visit_with_directives(node, directives) def visit_PyClassDefNode(self, node): directives = self._extract_directives(node, 'class') - if not directives: - return self.visit_Node(node) - body = Nodes.StatListNode(node.pos, stats=[node]) - return self.visit_with_directives(body, directives) + return self.visit_with_directives(node, directives) def _extract_directives(self, node, scope_name): if not node.decorators: @@ -1059,7 +1052,7 @@ def _extract_directives(self, node, scope_name): optdict[name] = value return optdict - # Handle with statements + # Handle with-statements def visit_WithStatNode(self, node): directive_dict = {} for directive in self.try_to_parse_directives(node.manager) or []: @@ -2385,6 +2378,10 @@ def visit_DefNode(self, node): self.visitchildren(node) return node + def visit_LambdaNode(self, node): + # No directives should modify lambdas or generator expressions (and also nothing in them). + return node + def visit_PyClassDefNode(self, node): if 'cclass' in self.directives: node = node.as_cclass()
diff --git a/tests/run/exttype_freelist.pyx b/tests/run/exttype_freelist.pyx --- a/tests/run/exttype_freelist.pyx +++ b/tests/run/exttype_freelist.pyx @@ -451,3 +451,19 @@ cdef class ExtTypeWithRefCycle: def __init__(self, obj=None): self.attribute = obj + + [email protected](3) [email protected] +class DecoratedPyClass(object): + """ + >>> obj1 = DecoratedPyClass() + >>> obj2 = DecoratedPyClass() + >>> obj3 = DecoratedPyClass() + >>> obj4 = DecoratedPyClass() + + >>> obj1 = DecoratedPyClass() + >>> obj2 = DecoratedPyClass() + >>> obj3 = DecoratedPyClass() + >>> obj4 = DecoratedPyClass() + """ diff --git a/tests/run/purecdef.py b/tests/run/purecdef.py --- a/tests/run/purecdef.py +++ b/tests/run/purecdef.py @@ -28,6 +28,17 @@ def fwith1(a): def fwith2(a): return a*4 + @cython.test_assert_path_exists( + '//CFuncDefNode', + '//LambdaNode', + '//GeneratorDefNode', + '//GeneratorBodyDefNode', + ) + def f_with_genexpr(a): + f = lambda x: x+1 + return (f(x) for x in a) + + with cclass: @cython.test_assert_path_exists('//CClassDefNode') class Egg(object): @@ -123,3 +134,14 @@ def test_typed_return(): """ x = cython.declare(int, 5) assert typed_return(cython.address(x))[0] is x + + +def test_genexpr_in_cdef(l): + """ + >>> gen = test_genexpr_in_cdef([1, 2, 3]) + >>> list(gen) + [2, 3, 4] + >>> list(gen) + [] + """ + return f_with_genexpr(l)
Allow genexprs in @cfunc functions. This fails to compile: ``` @cython.cfunc def f(): ','.join(x for x in '123') ``` The problem is that the cfunc directive forces an AdjustDefByDirectives visit. This is ok for the f node but not for the genexpr DefNode (i.e. node.body.stats[0].expr.args[0].def_node, where node is the f node) which inherits the cfunc directive from f and is also (but wrongly) transformed to a CFuncDefNode. I'm not sure whether there is a valid use case for inheriting cfunc or not. The current implementation just set the visitor directives attribute to the directives in a CompilerDirectivesNode, so the same directives are active for the entire recursive descent. An alternative is to pop the directive after applying it, in cases for which directive inheritance is undesirable. This PR does what I've just described, but only for cfunc. I consider it a dirty hack until more general criteria are discussed and adopted (for example, it seems inconsistent to me doing this for cfunc and not for ccall).
This doesn't look like the best fix, but a) this is definitely a bug, thanks for your investigation b) it's even more general as it also applies to other "directives" that shouldn't get inherited
2018-09-22T11:09:02Z
[]
[]
cython/cython
2,669
cython__cython-2669
[ "2274" ]
5dfefdadf6c20bf631ea3b6e567eede2f1ddd3d0
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -7171,6 +7171,9 @@ def analyse_expressions(self, env): gil_message = "Try-except statement" def generate_execution_code(self, code): + code.mark_pos(self.pos) # before changing the error label, in case of tracing errors + code.putln("{") + old_return_label = code.return_label old_break_label = code.break_label old_continue_label = code.continue_label @@ -7186,8 +7189,6 @@ def generate_execution_code(self, code): exc_save_vars = [code.funcstate.allocate_temp(py_object_type, False) for _ in range(3)] - code.mark_pos(self.pos) - code.putln("{") save_exc = code.insertion_point() code.putln( "/*try:*/ {") @@ -7520,7 +7521,9 @@ def analyse_expressions(self, env): gil_message = "Try-finally statement" def generate_execution_code(self, code): - code.mark_pos(self.pos) + code.mark_pos(self.pos) # before changing the error label, in case of tracing errors + code.putln("/*try:*/ {") + old_error_label = code.error_label old_labels = code.all_new_labels() new_labels = code.get_all_labels() @@ -7529,7 +7532,6 @@ def generate_execution_code(self, code): code.error_label = old_error_label catch_label = code.new_label() - code.putln("/*try:*/ {") was_in_try_finally = code.funcstate.in_try_finally code.funcstate.in_try_finally = 1
diff --git a/tests/run/line_trace.pyx b/tests/run/line_trace.pyx --- a/tests/run/line_trace.pyx +++ b/tests/run/line_trace.pyx @@ -5,7 +5,7 @@ import sys -from cpython.ref cimport PyObject, Py_INCREF, Py_XINCREF, Py_XDECREF +from cpython.ref cimport PyObject, Py_INCREF, Py_XDECREF cdef extern from "frameobject.h": ctypedef struct PyFrameObject: @@ -23,7 +23,7 @@ cdef extern from *: map_trace_types = { PyTrace_CALL: 'call', - PyTrace_EXCEPTION: 'exc', + PyTrace_EXCEPTION: 'exception', PyTrace_LINE: 'line', PyTrace_RETURN: 'return', PyTrace_C_CALL: 'ccall', @@ -74,6 +74,10 @@ def _create_trace_func(trace): local_names = {} def _trace_func(frame, event, arg): + if sys.version_info < (3,) and 'line_trace' not in frame.f_code.co_filename: + # Prevent tracing into Py2 doctest functions. + return None + trace.append((map_trace_types(event, event), frame.f_lineno - frame.f_code.co_firstlineno)) lnames = frame.f_code.co_varnames @@ -85,9 +89,9 @@ def _create_trace_func(trace): # Currently, the locals dict is empty for Cython code, but not for Python code. if frame.f_code.co_name.startswith('py_'): # Change this when we start providing proper access to locals. - assert frame.f_locals + assert frame.f_locals, frame.f_code.co_name else: - assert not frame.f_locals + assert not frame.f_locals, frame.f_code.co_name return _trace_func return _trace_func @@ -154,6 +158,13 @@ cdef int cy_add_nogil(int a, int b) nogil except -1: return x # 2 +def cy_try_except(func): + try: + return func() + except KeyError as exc: + raise AttributeError(exc.args[0]) + + def run_trace(func, *args, bint with_sys=False): """ >>> def py_add(a,b): @@ -226,6 +237,62 @@ def run_trace(func, *args, bint with_sys=False): return trace +def run_trace_with_exception(func, bint with_sys=False, bint fail=False): + """ + >>> def py_return(retval=123): return retval + >>> run_trace_with_exception(py_return) + OK: 123 + [('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('return', 0), ('return', 2)] + >>> run_trace_with_exception(py_return, with_sys=True) + OK: 123 + [('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('return', 0), ('return', 2)] + + >>> run_trace_with_exception(py_return, fail=True) + ValueError('failing line trace!') + [('call', 0)] + + #>>> run_trace_with_exception(lambda: 123, with_sys=True, fail=True) + #ValueError('huhu') + #[('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('return', 0), ('return', 2)] + + >>> def py_raise_exc(exc=KeyError('huhu')): raise exc + >>> run_trace_with_exception(py_raise_exc) + AttributeError('huhu') + [('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('exception', 0), ('return', 0), ('line', 3), ('line', 4), ('return', 4)] + >>> run_trace_with_exception(py_raise_exc, with_sys=True) + AttributeError('huhu') + [('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('exception', 0), ('return', 0), ('line', 3), ('line', 4), ('return', 4)] + >>> run_trace_with_exception(py_raise_exc, fail=True) + ValueError('failing line trace!') + [('call', 0)] + + #>>> run_trace_with_exception(raise_exc, with_sys=True, fail=True) + #ValueError('huhu') + #[('call', 0), ('line', 1), ('line', 2), ('call', 0), ('line', 0), ('exception', 0), ('return', 0), ('line', 3), ('line', 4), ('return', 4)] + """ + trace = ['cy_try_except' if fail else 'NO ERROR'] + trace_func = _create__failing_line_trace_func(trace) if fail else _create_trace_func(trace) + if with_sys: + sys.settrace(trace_func) + else: + PyEval_SetTrace(<Py_tracefunc>trace_trampoline, <PyObject*>trace_func) + try: + try: + retval = cy_try_except(func) + except ValueError as exc: + print("%s(%r)" % (type(exc).__name__, str(exc))) + except AttributeError as exc: + print("%s(%r)" % (type(exc).__name__, str(exc))) + else: + print('OK: %r' % retval) + finally: + if with_sys: + sys.settrace(None) + else: + PyEval_SetTrace(NULL, NULL) + return trace[1:] + + def fail_on_call_trace(func, *args): """ >>> def py_add(a,b):
variable '__pyx_tstate' is used uninitialized whenever 'if' condition is true Hi! I'm facing problem with generating valid c code with enabled linetracing for code like this: ``` try: return LoadJsonFromString(s, len(s)) except Exception as e: raise ValueError(str(e)) ``` cython generates: ``` /* "library/python/json/loads.pyx":9 * s = s.encode('utf-8') * * try: # <<<<<<<<<<<<<< * return LoadJsonFromString(s, len(s)) * except Exception as e: */ __Pyx_TraceLine(9,0,__PYX_ERR(0, 9, __pyx_L4_error)) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7); __Pyx_XGOTREF(__pyx_t_5); __Pyx_XGOTREF(__pyx_t_6); __Pyx_XGOTREF(__pyx_t_7); /*try:*/ { [...skipped code for generated LoadJsonFromString call...] /* "library/python/json/loads.pyx":9 * s = s.encode('utf-8') * * try: # <<<<<<<<<<<<<< * return LoadJsonFromString(s, len(s)) * except Exception as e: */ __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; [...skipped code for exception handling...] /* "library/python/json/loads.pyx":9 * s = s.encode('utf-8') * * try: # <<<<<<<<<<<<<< * return LoadJsonFromString(s, len(s)) * except Exception as e: */ __Pyx_XGIVEREF(__pyx_t_5); __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_ExceptionReset(__pyx_t_5, __pyx_t_6, __pyx_t_7); goto __pyx_L1_error; __pyx_L8_try_return:; __Pyx_XGIVEREF(__pyx_t_5); __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_ExceptionReset(__pyx_t_5, __pyx_t_6, __pyx_t_7); goto __pyx_L0; } ``` compiler error: ``` library/python/json/loads.pyx.cpp:1393:3: error: variable '__pyx_tstate' is used uninitialized whenever 'if' condition is true [-Werror,-Wsometimes-uninitialized] __Pyx_TraceLine(9,0,__PYX_ERR(0, 9, __pyx_L4_error)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ library/python/json/loads.pyx.cpp:1090:19: note: expanded from macro '__Pyx_TraceLine' if (unlikely(ret)) goto_error;\ ^~~~~~~~~~~~~ library/python/json/loads.pyx.cpp:770:23: note: expanded from macro 'unlikely' #define unlikely(x) __builtin_expect(!!(x), 0) ^~~~~~~~~~~~~~~~~~~~~~~~~~ library/python/json/loads.pyx.cpp:1482:5: note: uninitialized use occurs here __Pyx_ExceptionReset(__pyx_t_5, __pyx_t_6, __pyx_t_7); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ library/python/json/loads.pyx.cpp:1119:70: note: expanded from macro '__Pyx_ExceptionReset' #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) ^~~~~~~~~~~~ library/python/json/loads.pyx.cpp:1393:3: note: remove the 'if' if its condition is always false __Pyx_TraceLine(9,0,__PYX_ERR(0, 9, __pyx_L4_error)) ^ library/python/json/loads.pyx.cpp:1090:15: note: expanded from macro '__Pyx_TraceLine' if (unlikely(ret)) goto_error;\ ^ library/python/json/loads.pyx.cpp:1395:5: note: variable '__pyx_tstate' is declared here __Pyx_PyThreadState_declare ^ library/python/json/loads.pyx.cpp:872:38: note: expanded from macro '__Pyx_PyThreadState_declare' #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; ^ ``` which says that macro __Pyx_TraceLine(9,0,__PYX_ERR(0, 9, __pyx_L4_error)) expands into code that will jumps to __pyx_L4_error label if __Pyx_call_line_trace_func returns nonzero value. Jumping to __pyx_L4_error label will skip __pyx_tstate declaration: ``` __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign ``` which will be used later in the code expanded from __Pyx_ExceptionReset macro (___Pyx__ExceptionReset(__pyx_tstate, type, value, tb)_)
Hi, can you please provide a short standalone script to reproduce the bug? I cannot reproduce it. Thanks. Thanks for your quick response! Will something like this be enough? `cat lib.pyx` ``` cdef num(x): try: return x except AttributeError as e: raise ValueError(str(e)) ``` `git clone https://github.com/cython/cython` `python cython/cython.py -X linetrace=True --cplus lib.pyx -o lib.pyx.cpp` `clang++-5.0 -Wall -Werror -I/usr/include/python2.7/ -DCYTHON_TRACE=1 -DCYTHON_TRACE_NOGIL=1 -c lib.pyx.cpp` ``` lib.pyx.cpp:1293:3: error: variable '__pyx_tstate' is used uninitialized whenever 'if' condition is true [-Werror,-Wsometimes-uninitialized] __Pyx_TraceLine(2,0,__PYX_ERR(0, 2, __pyx_L3_error)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lib.pyx.cpp:1108:19: note: expanded from macro '__Pyx_TraceLine' if (unlikely(ret)) goto_error;\ ^~~~~~~~~~~~~ lib.pyx.cpp:788:23: note: expanded from macro 'unlikely' #define unlikely(x) __builtin_expect(!!(x), 0) ^~~~~~~~~~~~~~~~~~~~~~~~~~ lib.pyx.cpp:1371:5: note: uninitialized use occurs here __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lib.pyx.cpp:1130:70: note: expanded from macro '__Pyx_ExceptionReset' #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) ^~~~~~~~~~~~ lib.pyx.cpp:1293:3: note: remove the 'if' if its condition is always false __Pyx_TraceLine(2,0,__PYX_ERR(0, 2, __pyx_L3_error)) ^ lib.pyx.cpp:1108:15: note: expanded from macro '__Pyx_TraceLine' if (unlikely(ret)) goto_error;\ ^ lib.pyx.cpp:1295:5: note: variable '__pyx_tstate' is declared here __Pyx_PyThreadState_declare ^ lib.pyx.cpp:890:38: note: expanded from macro '__Pyx_PyThreadState_declare' #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; ^ 1 error generated. ``` I tried to make a `setup.py` rather than manually run the cython/cython.py and clang. This works. lib.pyx ```python cdef num(x): try: return x except AttributeError as e: raise ValueError(str(e)) ``` setup.py ```python from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension extensions = [ Extension("lib", ["lib.pyx"], define_macros=[('CYTHON_TRACE', '1'), ('DCYTHON_TRACE_NOGIL', '1')]) ] setup( name = "hello", ext_modules = cythonize(extensions, compiler_directives={'linetrace': True}), ) ``` Command to run: ```shell python setup.py build_ext --inplace ``` Would this workaround suits you? I'm in no way an expert in Cython, I'm only trying to help the maintainers. So maybe I'm missing something obvious. Yes, your example works for me too, but it's obviously hiding real problem. It uses gcc as compiler by default and due 14 years old gcc bug (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=18501) it doesn't detect uninitialized variable use. To reproduce problem you can run command: ``` CC=clang++-5.0 python setup.py build_ext --inplace ``` I have found similar issue - https://github.com/cython/cython/issues/2269. Pitrou didn't provide enough information, but it seems to me that gcc (at least 4.9.4) is capable to detect some cases of uninitialized variable use. It does't look like my try-except-raise case, but i believe that it's different face of the same problem and cython generates code like ``` __Pyx_TraceLine(9,0,__PYX_ERR(0, 9, __pyx_L4_error)) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign ``` which may lead to jump over __Pyx_PyThreadState_declare and __Pyx_PyThreadState_assign if__Pyx_call_line_trace_func() returns nonzero value. My workaround: ```diff +++ b/Cython/Utility/Profile.c @@ -193,6 +193,7 @@ #ifdef WITH_THREAD #define __Pyx_TraceLine(lineno, nogil, goto_error) \ if (likely(!__Pyx_use_tracing)); else { \ + if ((1)); else goto_error; \ if (nogil) { \ if (CYTHON_TRACE_NOGIL) { \ int ret = 0; \ @@ -203,23 +204,27 @@ ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \ } \ PyGILState_Release(state); \ - if (unlikely(ret)) goto_error; \ + // It's a bug - see https://github.com/cython/cython/issues/2274 \ + if (unlikely(ret)) { fprintf(stderr, "cython: line_trace_func returned %d\n", ret); } \ } \ } else { \ PyThreadState* tstate = __Pyx_PyThreadState_Current; \ if (unlikely(tstate->use_tracing && tstate->c_tracefunc && $frame_cname->f_trace)) { \ int ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \ - if (unlikely(ret)) goto_error; \ + // It's a bug - see https://github.com/cython/cython/issues/2274 \ + if (unlikely(ret)) { fprintf(stderr, "cython: line_trace_func returned %d\n", ret); } \ } \ } \ } #else #define __Pyx_TraceLine(lineno, nogil, goto_error) \ if (likely(!__Pyx_use_tracing)); else { \ + if ((1)); else goto_error; \ PyThreadState* tstate = __Pyx_PyThreadState_Current; \ if (unlikely(tstate->use_tracing && tstate->c_tracefunc && $frame_cname->f_trace)) { \ int ret = __Pyx_call_line_trace_func(tstate, $frame_cname, lineno); \ - if (unlikely(ret)) goto_error; \ + // It's a bug - see https://github.com/cython/cython/issues/2274 \ + if (unlikely(ret)) { fprintf(stderr, "cython: line_trace_func returned %d\n", ret); } \ } \ } #endif ``` It looks valid for me, because i don't understand why tracing errors should affect executing code. So, if error occurs in tracing code, we just accept this fact and should move on. Cython generated code: ```c++ /* "lib.pyx":2 * cdef num(x): * try: # <<<<<<<<<<<<<< * return x * except AttributeError as e: */ __Pyx_TraceLine(2,0,__PYX_ERR(0, 2, __pyx_L3_error)) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "lib.pyx":3 * cdef num(x): * try: * return x # <<<<<<<<<<<<<< * except AttributeError as e: * raise ValueError(str(e)) */ __Pyx_TraceLine(3,0,__PYX_ERR(0, 3, __pyx_L3_error)) __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_x); __pyx_r = __pyx_v_x; goto __pyx_L7_try_return; /* "lib.pyx":2 * cdef num(x): * try: # <<<<<<<<<<<<<< * return x * except AttributeError as e: */ } __pyx_L3_error:; /* "lib.pyx":4 * try: * return x * except AttributeError as e: # <<<<<<<<<<<<<< * raise ValueError(str(e)) * */ __Pyx_TraceLine(4,0,__PYX_ERR(0, 4, __pyx_L5_except_error)) __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_AttributeError); ``` Cython generated code with expanded macro (with my 'expanded' comments): ```c++ // expanded __Pyx_TraceLine(2,0,__PYX_ERR(0, 2, __pyx_L3_error)) if (__builtin_expect(!!(!__Pyx_use_tracing), 1)); else { if (0) { if (0) { int ret = 0; PyThreadState *tstate; PyGILState_STATE state = PyGILState_Ensure(); tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, 2); } PyGILState_Release(state); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = 1301; goto __pyx_L3_error; }; } } else { PyThreadState* tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { int ret = __Pyx_call_line_trace_func(tstate, __py x_frame, 2); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = 1301; goto __pyx_L3_error; }; } } } { // expanded __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; // expanded __Pyx_PyThreadState_assign __pyx_tstate = _PyThreadState_Current; // expanded __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx__ExceptionSave(__pyx_tstate, &__pyx_t_1, &__pyx_t_2, &__pyx_t_3); ; ; ; { # 1318 "lib.c" // expanded __Pyx_TraceLine(3,0,__PYX_ERR(0, 3, __pyx_L3_error)) if (__builtin_expect(!!(!__Pyx_use_tracing), 1)); else { if (0) { if (0) { int ret = 0; PyThreadState *tstate; PyGILState_STATE state = PyGILState_Ensure(); tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, 3); } PyGILState_Release(state); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = 1318; goto __pyx_L3_error; }; } } else { PyThreadState* tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { int ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, 3); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = 1318; goto __pyx_L3_error; }; } } } do { if ((__pyx_r) == ((void*)0)) ; else do { if ( --((PyObject*)(__pyx_r))->ob_refcnt != 0) ; else ( (*(((PyObject*)((PyObject *)(__pyx_r)))->ob_type)->tp_dealloc)((PyObject *)((PyObject *)(__pyx_r)))); } while (0); } while (0); ( ((PyObject*)(__pyx_v_x))->ob_refcnt++); __pyx_r = __pyx_v_x; goto __pyx_L7_try_return; } __pyx_L3_error:; # 1340 "lib.c" // expanded __Pyx_TraceLine(4,0,__PYX_ERR(0, 4, __pyx_L5_except_error)) if (__builtin_expect(!!(!__Pyx_use_tracing), 1)); else { if (0) { if (0) { int ret = 0; PyThreadState *tstate; PyGILState_STATE state = PyGILState_Ensure(); tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, 4); } PyGILState_Release(state); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = 1340; goto __pyx_L5_except_error; }; } } else { PyThreadState* tstate = _PyThreadState_Current; if (__builtin_expect(!!(tstate->use_tracing && tstate->c_tracefunc && __pyx_frame->f_trace), 0)) { int ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, 4); if (__builtin_expect(!!(ret), 0)) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = 1340; goto __pyx_L5_except_error; }; } } } // expanded __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_AttributeError); __pyx_t_4 = __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, __pyx_builtin_AttributeError); if (__pyx_t_4) { __Pyx_AddTraceback("lib.num", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx__GetException(__pyx_tstate, &__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) { __pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = 1344; goto __pyx_L5_except_error; } ; ; ; ``` As you can see at the first line we can perform ```goto __pyx_L3_error``` and skip ```PyThreadState *__pyx_tstate; __pyx_tstate = _PyThreadState_Current;```, which is the cause of problem, because we will use __pyx_tstate later Thanks for all those details. I don't have enough knowledge to do a PR, but hopefully someone will figure out the error and fix it with all the information you provided. Some additional info, which might be useful: it looks like pure UB and behaviour may vary from compiler to compiler. A minimalist example: ```c++ #include <stdio.h> int main(int c, char** v) { if (c > 1) { fprintf(stderr, "goto __pyx_L3_error\n"); goto __pyx_L3_error; } { fprintf(stderr, "declare *p\n"); int *__pyx_tstate; __pyx_tstate = &c; __pyx_L3_error:; fprintf(stderr, "val: %d\n", *__pyx_tstate); } return 0; } ``` ```bash ~> g++-7 -O2 1.cpp; ./a.out 2; goto __pyx_L3_error val: 2 ~> g++-7 1.cpp; ./a.out 2; goto __pyx_L3_error Segmentation fault (core dumped) ~> clang++-5.0 -O2 1.cpp; ./a.out 2; goto __pyx_L3_error val: 2 ~> clang++-5.0 1.cpp; ./a.out 2; goto __pyx_L3_error val: -1991643855 ``` I see this with clang 6.0.1 as well.
2018-10-19T19:25:56Z
[]
[]
cython/cython
2,682
cython__cython-2682
[ "2634" ]
336d8ca7489887a6582b3b997f374fc47de8133b
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -653,8 +653,9 @@ def declaration_code(self, entity_code, assert not pyrex assert not dll_linkage from . import MemoryView + base_code = str(self) if for_display else MemoryView.memviewslice_cname return self.base_declaration_code( - MemoryView.memviewslice_cname, + base_code, entity_code) def attributes_known(self):
diff --git a/tests/run/embedsignatures.pyx b/tests/run/embedsignatures.pyx --- a/tests/run/embedsignatures.pyx +++ b/tests/run/embedsignatures.pyx @@ -428,6 +428,7 @@ cdef class Foo: def m28(self, a: list(range(3))[::1]): pass def m29(self, a: list(range(3))[0:1:1]): pass def m30(self, a: list(range(3))[7, 3:2:1, ...]): pass + def m31(self, double[::1] a): pass __doc__ += ur""" >>> print(Foo.m00.__doc__) @@ -522,4 +523,7 @@ Foo.m29(self, a: list(range(3))[0:1:1]) >>> print(Foo.m30.__doc__) Foo.m30(self, a: list(range(3))[7, 3:2:1, ...]) + +>>> print(Foo.m31.__doc__) +Foo.m31(self, double[::1] a) """
Cython embedsignature gives useless information for memoryviews in Sphinx Hi, The embedsignature option in Cython gives call signature information for Sphinx to document, but it is not useful when describing memoryviews. This is the source: ``` def foo(double[::1] n): .... ``` And this is the call signature printed in Sphinx > foo(__Pyx_memviewslice n) So it loses the type information, along with the dimension and stride. Is it possible to add this in? Or is this something that should be addressed from the Sphinx-autodoc side? Thanks!
Definitely a bug, thanks for the report. The code for this is in the `EmbedSignature` tree transformation in `AutoDocTransform.py`, probably easy to fix. Want to give it a try?
2018-10-27T10:26:35Z
[]
[]
cython/cython
2,684
cython__cython-2684
[ "2536" ]
336d8ca7489887a6582b3b997f374fc47de8133b
diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -3367,7 +3367,7 @@ def _reject_cdef_modifier_in_py(s, name): def p_def_statement(s, decorators=None, is_async_def=False): # s.sy == 'def' - pos = s.position() + pos = decorators[0].pos if decorators else s.position() # PEP 492 switches the async/await keywords on in "async def" functions if is_async_def: s.enter_async()
diff --git a/tests/errors/cfunc_directive_in_pyclass.pyx b/tests/errors/cfunc_directive_in_pyclass.pyx --- a/tests/errors/cfunc_directive_in_pyclass.pyx +++ b/tests/errors/cfunc_directive_in_pyclass.pyx @@ -7,5 +7,5 @@ class Pyclass(object): pass _ERRORS = """ - 6:4: cfunc directive is not allowed here + 5:4: cfunc directive is not allowed here """ diff --git a/tests/errors/e_autotestdict.pyx b/tests/errors/e_autotestdict.pyx --- a/tests/errors/e_autotestdict.pyx +++ b/tests/errors/e_autotestdict.pyx @@ -7,5 +7,5 @@ def foo(): pass _ERRORS = u""" -6:0: The autotestdict compiler directive is not allowed in function scope +5:0: The autotestdict compiler directive is not allowed in function scope """ diff --git a/tests/errors/pure_errors.py b/tests/errors/pure_errors.py --- a/tests/errors/pure_errors.py +++ b/tests/errors/pure_errors.py @@ -53,5 +53,5 @@ def pyfunc(x): # invalid _ERRORS = """ 44:22: Calling gil-requiring function not allowed without gil 45:24: Calling gil-requiring function not allowed without gil -49:0: Python functions cannot be declared 'nogil' +48:0: Python functions cannot be declared 'nogil' """ diff --git a/tests/errors/tree_assert.pyx b/tests/errors/tree_assert.pyx --- a/tests/errors/tree_assert.pyx +++ b/tests/errors/tree_assert.pyx @@ -11,8 +11,8 @@ def test(): _ERRORS = u""" -9:0: Expected path '//ComprehensionNode' not found in result tree -9:0: Expected path '//ComprehensionNode//FuncDefNode' not found in result tree -9:0: Unexpected path '//NameNode' found in result tree -9:0: Unexpected path '//SimpleCallNode' found in result tree +5:0: Expected path '//ComprehensionNode' not found in result tree +5:0: Expected path '//ComprehensionNode//FuncDefNode' not found in result tree +5:0: Unexpected path '//NameNode' found in result tree +5:0: Unexpected path '//SimpleCallNode' found in result tree """ diff --git a/tests/run/annotation_typing.pyx b/tests/run/annotation_typing.pyx --- a/tests/run/annotation_typing.pyx +++ b/tests/run/annotation_typing.pyx @@ -242,7 +242,7 @@ _WARNINGS = """ 218:29: Ambiguous types in annotation, ignoring # BUG: 46:6: 'pytypes_cpdef' redeclared -121:0: 'struct_io' redeclared -156:0: 'struct_convert' redeclared -175:0: 'exception_default' redeclared +120:0: 'struct_io' redeclared +149:0: 'struct_convert' redeclared +168:0: 'exception_default' redeclared """ diff --git a/tests/run/cyfunction.pyx b/tests/run/cyfunction.pyx --- a/tests/run/cyfunction.pyx +++ b/tests/run/cyfunction.pyx @@ -391,3 +391,22 @@ cdef class TestOptimisedBuiltinMethod: def call(self, arg, obj=None): (obj or self).append(arg+1) # optimistically optimised => uses fast fallback method call + + +def do_nothing(f): + """Dummy decorator for `test_firstlineno_decorated_function`""" + return f + + +@do_nothing +@do_nothing +def test_firstlineno_decorated_function(): + """ + check that `test_firstlineno_decorated_function` starts 5 lines below `do_nothing` + + >>> test_firstlineno_decorated_function() + 5 + """ + l1 = do_nothing.__code__.co_firstlineno + l2 = test_firstlineno_decorated_function.__code__.co_firstlineno + return l2 - l1
Cython's co_firstlineno doesn't include decorators, like normal python Using `binding=True` fills in all the attributes to make cython function work with the inspect module, mostly. Some monkey patching is also required for it to recognize cython functions/methods as functions/methods (see at the end). However, it turns out that python's `co_firstlineno` starts from the first decorator that decorates the function, while cython's ` co_firstlineno` is set to the actual function start and does not include the decorator, which I think is a bug on cython's part. You can replicate it by inspecting `co_firstlineno` for e.g. the following function in cython and python using `binding=True`. ```py def do_nothing(f): return f @do_nothing @do_nothing def do_something(): pass ``` For reference, here's my inspect monkey patching: ```py import inspect from inspect import ismethod, isfunction def ismethod_cython(object): if ismethod(object): return True if object.__class__.__name__ == 'cython_function_or_method' and hasattr(object, '__func__'): return True return False inspect.ismethod = ismethod_cython def isfunction_cython(object): if isfunction(object): return True if object.__class__.__name__ == 'cython_function_or_method' and not hasattr(object, '__func__'): return True return False inspect.isfunction = isfunction_cython ```
Right. Probably easy to fix by keeping the first line number around explicitly. Maybe even by using the first decorator line number as the position of the function node right in the parser – if that doesn't break anything else.
2018-10-27T11:54:19Z
[]
[]
cython/cython
2,688
cython__cython-2688
[ "2685" ]
c2de8efb67f80bff59975641aac387d652324e4e
diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -1707,6 +1707,8 @@ def __setstate_cython__(self, __pyx_state): # so it can be pickled *after* self is memoized. unpickle_func = TreeFragment(u""" def %(unpickle_func_name)s(__pyx_type, long __pyx_checksum, __pyx_state): + cdef object __pyx_PickleError + cdef object __pyx_result if __pyx_checksum != %(checksum)s: from pickle import PickleError as __pyx_PickleError raise __pyx_PickleError("Incompatible checksums (%%s vs %(checksum)s = (%(members)s))" %% __pyx_checksum) @@ -1735,6 +1737,8 @@ def %(unpickle_func_name)s(__pyx_type, long __pyx_checksum, __pyx_state): pickle_func = TreeFragment(u""" def __reduce_cython__(self): + cdef tuple state + cdef object _dict cdef bint use_setstate state = (%(members)s) _dict = getattr(self, '__dict__', None)
diff --git a/tests/errors/w_undeclared.pyx b/tests/errors/w_undeclared.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/w_undeclared.pyx @@ -0,0 +1,20 @@ +# cython: warn.undeclared=True +# mode: error +# tag: werror + +def foo(): + a = 1 + return a + +cdef class Bar: + cdef int baz(self, a): + res = 0 + for i in range(3): + res += i + return res + +_ERRORS = """ +6:4: implicit declaration of 'a' +11:8: implicit declaration of 'res' +12:12: implicit declaration of 'i' +"""
warn.undeclared compiler directive is broken Using warn.undeclared with a simple empty extension type generates some warnings: ```cython #cython: language_level=3, warn.undeclared=True cdef class Foo: pass ``` ``` $ cython -Werror cython_test_undeclared.pyx Error compiling Cython file: ------------------------------------------------------------ ... def __pyx_unpickle_Foo(__pyx_type, long __pyx_checksum, __pyx_state): if __pyx_checksum != 0xd41d8cd: from pickle import PickleError as __pyx_PickleError ^ ------------------------------------------------------------ (tree fragment):3:27: implicit declaration of '__pyx_PickleError' Error compiling Cython file: ------------------------------------------------------------ ... def __pyx_unpickle_Foo(__pyx_type, long __pyx_checksum, __pyx_state): if __pyx_checksum != 0xd41d8cd: from pickle import PickleError as __pyx_PickleError raise __pyx_PickleError("Incompatible checksums (%s vs 0xd41d8cd = ())" % __pyx_checksum) __pyx_result = Foo.__new__(__pyx_type) ^ ------------------------------------------------------------ (tree fragment):5:4: implicit declaration of '__pyx_result' Error compiling Cython file: ------------------------------------------------------------ ... def __reduce_cython__(self): cdef bint use_setstate state = () ^ ------------------------------------------------------------ (tree fragment):3:4: implicit declaration of 'state' Error compiling Cython file: ------------------------------------------------------------ ... def __reduce_cython__(self): cdef bint use_setstate state = () _dict = getattr(self, '__dict__', None) ^ ------------------------------------------------------------ (tree fragment):4:4: implicit declaration of '_dict' ```
2018-10-27T13:05:25Z
[]
[]
cython/cython
2,693
cython__cython-2693
[ "2692" ]
5fdbfe49d56d756169e75c80c126eee5fc8fad52
diff --git a/Cython/Build/Dependencies.py b/Cython/Build/Dependencies.py --- a/Cython/Build/Dependencies.py +++ b/Cython/Build/Dependencies.py @@ -1056,31 +1056,25 @@ def copy_to_build_dir(filepath, root=os.getcwd()): if N <= 1: nthreads = 0 if nthreads: - # Requires multiprocessing (or Python >= 2.6) + import multiprocessing + pool = multiprocessing.Pool( + nthreads, initializer=_init_multiprocessing_helper) + # This is a bit more involved than it should be, because KeyboardInterrupts + # break the multiprocessing workers when using a normal pool.map(). + # See, for example: + # http://noswap.com/blog/python-multiprocessing-keyboardinterrupt try: - import multiprocessing - pool = multiprocessing.Pool( - nthreads, initializer=_init_multiprocessing_helper) - except (ImportError, OSError): - print("multiprocessing required for parallel cythonization") - nthreads = 0 - else: - # This is a bit more involved than it should be, because KeyboardInterrupts - # break the multiprocessing workers when using a normal pool.map(). - # See, for example: - # http://noswap.com/blog/python-multiprocessing-keyboardinterrupt - try: - result = pool.map_async(cythonize_one_helper, to_compile, chunksize=1) - pool.close() - while not result.ready(): - try: - result.get(99999) # seconds - except multiprocessing.TimeoutError: - pass - except KeyboardInterrupt: - pool.terminate() - raise - pool.join() + result = pool.map_async(cythonize_one_helper, to_compile, chunksize=1) + pool.close() + while not result.ready(): + try: + result.get(99999) # seconds + except multiprocessing.TimeoutError: + pass + except KeyboardInterrupt: + pool.terminate() + raise + pool.join() if not nthreads: for args in to_compile: cythonize_one(*args) diff --git a/Cython/Compiler/Code.py b/Cython/Compiler/Code.py --- a/Cython/Compiler/Code.py +++ b/Cython/Compiler/Code.py @@ -43,8 +43,6 @@ except ImportError: from builtins import str as basestring -KEYWORDS_MUST_BE_BYTES = sys.version_info < (2, 7) - non_portable_builtins_map = { # builtins that have different names in different Python versions @@ -259,15 +257,11 @@ def _add_utility(cls, utility, type, lines, begin_lineno, tags=None): utility[1] = code else: all_tags = utility[2] - if KEYWORDS_MUST_BE_BYTES: - type = type.encode('ASCII') all_tags[type] = code if tags: all_tags = utility[2] for name, values in tags.items(): - if KEYWORDS_MUST_BE_BYTES: - name = name.encode('ASCII') all_tags.setdefault(name, set()).update(values) @classmethod diff --git a/Cython/Compiler/Errors.py b/Cython/Compiler/Errors.py --- a/Cython/Compiler/Errors.py +++ b/Cython/Compiler/Errors.py @@ -60,8 +60,6 @@ def __init__(self, position = None, message = u""): self.message_only = message self.formatted_message = format_error(message, position) self.reported = False - # Deprecated and withdrawn in 2.6: - # self.message = message Exception.__init__(self, self.formatted_message) # Python Exception subclass pickling is broken, # see http://bugs.python.org/issue1692335 @@ -74,8 +72,6 @@ class CompileWarning(PyrexWarning): def __init__(self, position = None, message = ""): self.position = position - # Deprecated and withdrawn in 2.6: - # self.message = message Exception.__init__(self, format_position(position) + message) class InternalError(Exception): diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -9,8 +9,8 @@ import sys import io -if sys.version_info[:2] < (2, 6) or (3, 0) <= sys.version_info[:2] < (3, 3): - sys.stderr.write("Sorry, Cython requires Python 2.6+ or 3.3+, found %d.%d\n" % tuple(sys.version_info[:2])) +if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[:2] < (3, 3): + sys.stderr.write("Sorry, Cython requires Python 2.7 or 3.3+, found %d.%d\n" % tuple(sys.version_info[:2])) sys.exit(1) try: diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -635,9 +635,9 @@ def generate_module_preamble(self, env, options, cimported_modules, metadata, co code.putln("#ifndef Py_PYTHON_H") code.putln(" #error Python headers needed to compile C extensions, " "please install development version of Python.") - code.putln("#elif PY_VERSION_HEX < 0x02060000 || " + code.putln("#elif PY_VERSION_HEX < 0x02070000 || " "(0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)") - code.putln(" #error Cython requires Python 2.6+ or Python 3.3+.") + code.putln(" #error Cython requires Python 2.7+ or Python 3.3+.") code.putln("#else") code.globalstate["end"].putln("#endif /* Py_PYTHON_H */") diff --git a/Cython/Debugger/libpython.py b/Cython/Debugger/libpython.py --- a/Cython/Debugger/libpython.py +++ b/Cython/Debugger/libpython.py @@ -48,7 +48,7 @@ ''' # NOTE: some gdbs are linked with Python 3, so this file should be dual-syntax -# compatible (2.6+ and 3.0+). See #19308. +# compatible (2.7+ and 3.3+). See #19308. from __future__ import print_function import gdb @@ -1435,8 +1435,8 @@ def pretty_printer_lookup(gdbval): if the code is autoloaded by gdb when visiting libpython.so, provided that this python file is installed to the same path as the library (or its .debug file) plus a "-gdb.py" suffix, e.g: - /usr/lib/libpython2.6.so.1.0-gdb.py - /usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py + /usr/lib/libpython3.7.so.1.0-gdb.py + /usr/lib/debug/usr/lib/libpython3.7.so.1.0.debug-gdb.py """ def register (obj): if obj is None: diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -412,12 +412,7 @@ def get_openmp_compiler_flags(language): VER_DEP_MODULES = { # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e. # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x - (2,7) : (operator.lt, lambda x: x in ['run.withstat_py27', # multi context with statement - 'run.yield_inside_lambda', - 'run.test_dictviews', - 'run.pyclass_special_methods', - 'run.set_literals', - ]), + # The next line should start (3,); but this is a dictionary, so # we can only have one (3,) key. Since 2.7 is supposed to be the # last 2.x release, things would have to change drastically for this @@ -1260,8 +1255,7 @@ def run(self, result=None): try: self.success = False ext_so_path = self.runCompileTest() - # Py2.6 lacks "_TextTestResult.skipped" - failures, errors, skipped = len(result.failures), len(result.errors), len(getattr(result, 'skipped', [])) + failures, errors, skipped = len(result.failures), len(result.errors), len(result.skipped) if not self.cython_only and ext_so_path is not None: self.run_tests(result, ext_so_path) if failures == len(result.failures) and errors == len(result.errors): @@ -1445,10 +1439,6 @@ def __init__(self, base_result): _TextTestResult.__init__( self, self._StringIO(), True, base_result.dots + base_result.showAll*2) - try: - self.skipped - except AttributeError: - self.skipped = [] # Py2.6 def strip_error_results(self, results): for test_case, error in results: @@ -1473,10 +1463,7 @@ def join_results(result, data): if output: result.stream.write(output) result.errors.extend(errors) - try: - result.skipped.extend(skipped) - except AttributeError: - pass # Py2.6 + result.skipped.extend(skipped) result.failures.extend(failures) result.testsRun += tests_run @@ -2209,7 +2196,7 @@ def time_stamper(): write('\n#### %s\n' % now()) thread = threading.Thread(target=time_stamper, name='time_stamper') - thread.setDaemon(True) # Py2.6 ... + thread.setDaemon(True) # Py2 ... thread.start() try: yield
diff --git a/Cython/Debugger/Tests/TestLibCython.py b/Cython/Debugger/Tests/TestLibCython.py --- a/Cython/Debugger/Tests/TestLibCython.py +++ b/Cython/Debugger/Tests/TestLibCython.py @@ -56,13 +56,13 @@ def test_gdb(): stdout, _ = p.communicate() try: internal_python_version = list(map(int, stdout.decode('ascii', 'ignore').split())) - if internal_python_version < [2, 6]: + if internal_python_version < [2, 7]: have_gdb = False except ValueError: have_gdb = False if not have_gdb: - warnings.warn('Skipping gdb tests, need gdb >= 7.2 with Python >= 2.6') + warnings.warn('Skipping gdb tests, need gdb >= 7.2 with Python >= 2.7') return have_gdb diff --git a/tests/buffers/userbuffer.pyx b/tests/buffers/userbuffer.pyx --- a/tests/buffers/userbuffer.pyx +++ b/tests/buffers/userbuffer.pyx @@ -1,21 +1,11 @@ -import sys -__doc__ = u"" - -if sys.version_info[:2] == (2, 6): - __doc__ += u""" ->>> memoryview = _memoryview -""" - -__doc__ += u""" +__doc__ = u""" >>> b1 = UserBuffer1() >>> m1 = memoryview(b1) >>> m1.tolist() [0, 1, 2, 3, 4] >>> del m1, b1 -""" -__doc__ += u""" >>> b2 = UserBuffer2() >>> m2 = memoryview(b2) UserBuffer2: getbuffer diff --git a/tests/errors/cdefkwargs.pyx b/tests/errors/cdefkwargs.pyx --- a/tests/errors/cdefkwargs.pyx +++ b/tests/errors/cdefkwargs.pyx @@ -6,10 +6,6 @@ __doc__ = u""" >>> call4() """ -import sys, re -if sys.version_info >= (2,6): - __doc__ = re.sub(u"Error: (.*)exactly(.*)", u"Error: \\1at most\\2", __doc__) - # the calls: def call2(): diff --git a/tests/memoryview/memslice.pyx b/tests/memoryview/memslice.pyx --- a/tests/memoryview/memslice.pyx +++ b/tests/memoryview/memslice.pyx @@ -1853,11 +1853,7 @@ def test_struct_attributes_format(): """ cdef TestAttrs[10] array cdef TestAttrs[:] struct_memview = array - - if sys.version_info[:2] >= (2, 7): - print builtins.memoryview(struct_memview).format - else: - print "T{i:int_attrib:c:char_attrib:}" + print builtins.memoryview(struct_memview).format # Test padding at the end of structs in the buffer support diff --git a/tests/run/builtin_float.py b/tests/run/builtin_float.py --- a/tests/run/builtin_float.py +++ b/tests/run/builtin_float.py @@ -1,6 +1,4 @@ -import sys - def empty_float(): """ >>> float() @@ -11,24 +9,20 @@ def empty_float(): x = float() return x + def float_conjugate(): """ >>> float_call_conjugate() 1.5 """ - if sys.version_info >= (2,6): - x = 1.5 .conjugate() - else: - x = 1.5 + x = 1.5 .conjugate() return x + def float_call_conjugate(): """ >>> float_call_conjugate() 1.5 """ - if sys.version_info >= (2,6): - x = float(1.5).conjugate() - else: - x = 1.5 + x = float(1.5).conjugate() return x diff --git a/tests/run/c_type_methods_T236.pyx b/tests/run/c_type_methods_T236.pyx --- a/tests/run/c_type_methods_T236.pyx +++ b/tests/run/c_type_methods_T236.pyx @@ -1,10 +1,8 @@ # ticket: 236 -__doc__ = '' - import sys -if sys.version_info >= (2,6): - __doc__ += ''' + +__doc__ = ''' >>> float_is_integer(1.0) True >>> float_is_integer(1.1) @@ -19,7 +17,6 @@ True ''' def float_is_integer(float f): - # requires Python 2.6+ return f.is_integer() def int_bit_length(int i): diff --git a/tests/run/cpdef_enums.pyx b/tests/run/cpdef_enums.pyx --- a/tests/run/cpdef_enums.pyx +++ b/tests/run/cpdef_enums.pyx @@ -70,14 +70,8 @@ def test_as_variable_from_cython(): """ >>> test_as_variable_from_cython() """ - import sys - if sys.version_info >= (2, 7): - assert list(PyxEnum) == [TWO, THREE, FIVE], list(PyxEnum) - assert list(PxdEnum) == [RANK_0, RANK_1, RANK_2], list(PxdEnum) - else: - # No OrderedDict. - assert set(PyxEnum) == {TWO, THREE, FIVE}, list(PyxEnum) - assert set(PxdEnum) == {RANK_0, RANK_1, RANK_2}, list(PxdEnum) + assert list(PyxEnum) == [TWO, THREE, FIVE], list(PyxEnum) + assert list(PxdEnum) == [RANK_0, RANK_1, RANK_2], list(PxdEnum) cdef int verify_pure_c() nogil: cdef int x = TWO diff --git a/tests/run/extstarargs.pyx b/tests/run/extstarargs.pyx --- a/tests/run/extstarargs.pyx +++ b/tests/run/extstarargs.pyx @@ -88,15 +88,13 @@ __doc__ = u""" (1, ('a', 1), ('b', 2)) """ -import sys, re -if sys.version_info >= (2,6): - __doc__ = re.sub(u"(ELLIPSIS[^>]*Error: )[^\n]*\n", u"\\1...\n", __doc__) cdef sorteditems(d): l = list(d.items()) l.sort() return tuple(l) + cdef class Silly: def __init__(self, *a): diff --git a/tests/run/numpy_test.pyx b/tests/run/numpy_test.pyx --- a/tests/run/numpy_test.pyx +++ b/tests/run/numpy_test.pyx @@ -5,7 +5,6 @@ cimport numpy as np cimport cython import re -import sys def little_endian(): @@ -20,7 +19,7 @@ def testcase(f): def testcase_have_buffer_interface(f): major, minor, *rest = np.__version__.split('.') - if (int(major), int(minor)) >= (1, 5) and sys.version_info[:2] >= (2, 6): + if (int(major), int(minor)) >= (1, 5): __test__[f.__name__] = f.__doc__ return f diff --git a/tests/run/test_asyncgen.py b/tests/run/test_asyncgen.py --- a/tests/run/test_asyncgen.py +++ b/tests/run/test_asyncgen.py @@ -247,16 +247,6 @@ def assertRaisesRegex(self, exc_type, regex=None): else: self.assertTrue(False) - if sys.version_info < (2, 7): - def assertIn(self, x, container): - self.assertTrue(x in container) - - def assertIs(self, x, y): - self.assertTrue(x is y) - - assertRaises = assertRaisesRegex - - def compare_generators(self, sync_gen, async_gen): def sync_iterate(g): res = [] diff --git a/tests/run/test_coroutines_pep492.pyx b/tests/run/test_coroutines_pep492.pyx --- a/tests/run/test_coroutines_pep492.pyx +++ b/tests/run/test_coroutines_pep492.pyx @@ -144,17 +144,6 @@ def silence_coro_gc(): gc.collect() -def min_py27(method): - return None if sys.version_info < (2, 7) else method - - -def ignore_py26(manager): - @contextlib.contextmanager - def dummy(): - yield - return dummy() if sys.version_info < (2, 7) else manager - - @contextlib.contextmanager def captured_stderr(): try: @@ -1826,7 +1815,7 @@ class CoroutineTest(unittest.TestCase): buffer = [] async def test1(): - with ignore_py26(self.assertWarnsRegex(DeprecationWarning, "legacy")): + with self.assertWarnsRegex(DeprecationWarning, "legacy"): async for i1, i2 in AsyncIter(): buffer.append(i1 + i2) @@ -1840,7 +1829,7 @@ class CoroutineTest(unittest.TestCase): buffer = [] async def test2(): nonlocal buffer - with ignore_py26(self.assertWarnsRegex(DeprecationWarning, "legacy")): + with self.assertWarnsRegex(DeprecationWarning, "legacy"): async for i in AsyncIter(): buffer.append(i[0]) if i[0] == 20: @@ -1859,7 +1848,7 @@ class CoroutineTest(unittest.TestCase): buffer = [] async def test3(): nonlocal buffer - with ignore_py26(self.assertWarnsRegex(DeprecationWarning, "legacy")): + with self.assertWarnsRegex(DeprecationWarning, "legacy"): async for i in AsyncIter(): if i[0] > 20: continue @@ -2076,7 +2065,6 @@ class CoroutineTest(unittest.TestCase): self.assertEqual(CNT, 0) # old-style pre-Py3.5.2 protocol - no longer supported - @min_py27 def __test_for_9(self): # Test that DeprecationWarning can safely be converted into # an exception (__aiter__ should not have a chance to raise @@ -2094,7 +2082,6 @@ class CoroutineTest(unittest.TestCase): run_async(foo()) # old-style pre-Py3.5.2 protocol - no longer supported - @min_py27 def __test_for_10(self): # Test that DeprecationWarning can safely be converted into # an exception. diff --git a/tests/run/test_fstring.pyx b/tests/run/test_fstring.pyx --- a/tests/run/test_fstring.pyx +++ b/tests/run/test_fstring.pyx @@ -10,7 +10,6 @@ import contextlib import sys IS_PY2 = sys.version_info[0] < 3 -IS_PY26 = sys.version_info[:2] < (2, 7) from Cython.Build.Inline import cython_inline from Cython.TestUtils import CythonTest @@ -63,23 +62,8 @@ class TestCase(CythonTest): first = stripped_first.decode('unicode_escape') super(TestCase, self).assertEqual(first, second, msg) - if IS_PY26: - @contextlib.contextmanager - def assertRaises(self, exc): - try: - yield - except exc: - pass - else: - assert False, "exception '%s' not raised" % exc - - def assertIn(self, value, collection): - self.assertTrue(value in collection) - def test__format__lookup(self): - if IS_PY26: - return - elif IS_PY2: + if IS_PY2: raise unittest.SkipTest("Py3-only") # Make sure __format__ is looked up on the type, not the instance. @@ -288,12 +272,11 @@ f'{a * x()}'""" width = 10 precision = 4 value = decimal.Decimal('12.34567') - if not IS_PY26: - self.assertEqual(f'result: {value:{width}.{precision}}', 'result: 12.35') - self.assertEqual(f'result: {value:{width!r}.{precision}}', 'result: 12.35') - self.assertEqual(f'result: {value:{width:0}.{precision:1}}', 'result: 12.35') - self.assertEqual(f'result: {value:{1}{0:0}.{precision:1}}', 'result: 12.35') - self.assertEqual(f'result: {value:{ 1}{ 0:0}.{ precision:1}}', 'result: 12.35') + self.assertEqual(f'result: {value:{width}.{precision}}', 'result: 12.35') + self.assertEqual(f'result: {value:{width!r}.{precision}}', 'result: 12.35') + self.assertEqual(f'result: {value:{width:0}.{precision:1}}', 'result: 12.35') + self.assertEqual(f'result: {value:{1}{0:0}.{precision:1}}', 'result: 12.35') + self.assertEqual(f'result: {value:{ 1}{ 0:0}.{ precision:1}}', 'result: 12.35') self.assertEqual(f'{10:#{1}0x}', ' 0xa') self.assertEqual(f'{10:{"#"}1{0}{"x"}}', ' 0xa') self.assertEqual(f'{-10:-{"#"}1{0}x}', ' -0xa') @@ -312,8 +295,7 @@ f'{a * x()}'""" ]) # CYTHON: The nesting restriction seems rather arbitrary. Ignoring it for now and instead test that it works. - if not IS_PY26: - self.assertEqual(f'result: {value:{width:{0}}.{precision:1}}', 'result: 12.35') + self.assertEqual(f'result: {value:{width:{0}}.{precision:1}}', 'result: 12.35') #self.assertAllRaise(SyntaxError, "f-string: expressions nested too deeply", # [# Can't nest format specifiers. # "f'result: {value:{width:{0}}.{precision:1}}'", @@ -678,10 +660,9 @@ f'{a * x()}'""" def test_conversions(self): self.assertEqual(f'{3.14:10.10}', ' 3.14') - if not IS_PY26: - self.assertEqual(f'{3.14!s:10.10}', '3.14 ') - self.assertEqual(f'{3.14!r:10.10}', '3.14 ') - self.assertEqual(f'{3.14!a:10.10}', '3.14 ') + self.assertEqual(f'{3.14!s:10.10}', '3.14 ') + self.assertEqual(f'{3.14!r:10.10}', '3.14 ') + self.assertEqual(f'{3.14!a:10.10}', '3.14 ') self.assertEqual(f'{"a"}', 'a') self.assertEqual(f'{"a"!r}', "'a'") diff --git a/tests/run/test_grammar.py b/tests/run/test_grammar.py --- a/tests/run/test_grammar.py +++ b/tests/run/test_grammar.py @@ -1520,24 +1520,6 @@ async def foo(): GrammarTests.assertRaisesRegex = lambda self, exc, msg: self.assertRaises(exc) -if sys.version_info < (2, 7): - def assertRaises(self, exc_type, func=None, *args, **kwargs): - if func is not None: - return unittest.TestCase.assertRaises(self, exc_type, func, *args, **kwargs) - @contextlib.contextmanager - def assertRaisesCM(): - class Result(object): - exception = exc_type("unexpected EOF") # see usage above - try: - yield Result() - except exc_type: - self.assertTrue(True) - else: - self.assertTrue(False) - return assertRaisesCM() - GrammarTests.assertRaises = assertRaises - TokenTests.assertRaises = assertRaises - if not hasattr(unittest.TestCase, 'subTest'): @contextlib.contextmanager @@ -1550,20 +1532,10 @@ def subTest(self, source, **kwargs): GrammarTests.subTest = subTest -if not hasattr(unittest.TestCase, 'assertIn'): - def assertIn(self, member, container, msg=None): - self.assertTrue(member in container, msg) - TokenTests.assertIn = assertIn - - # FIXME: disabling some tests for real Cython bugs here del GrammarTests.test_comprehension_specials # iterable pre-calculation in generator expression del GrammarTests.test_funcdef # annotation mangling -# this test is difficult to enable in Py2.6 -if sys.version_info < (2,7): - del GrammarTests.test_former_statements_refer_to_builtins - if __name__ == '__main__': unittest.main() diff --git a/tests/run/unicodeliterals.pyx b/tests/run/unicodeliterals.pyx --- a/tests/run/unicodeliterals.pyx +++ b/tests/run/unicodeliterals.pyx @@ -87,11 +87,7 @@ __doc__ = br""" True >>> ustring_in_constant_tuple == ('a', u'abc', u'\\N{SNOWMAN}', u'x' * 3, u'\\N{SNOWMAN}' * 4 + u'O') or ustring_in_constant_tuple # unescaped by Python True -""" -if sys.version_info >= (2,6,5): - # this doesn't work well in older Python versions - __doc__ += u"""\ >>> expected = u'\U00101234' # unescaped by Cython >>> if wide_literal == expected: print(True) ... else: print(repr(wide_literal), repr(expected), sys.maxunicode)
Remove support for Py2.6 It has been annoying for a while to support Py2.6, it's long out of maintenance, and it's hard to find reasons for not switching to at least Py2.7. Let's remove the support from Cython.
+1
2018-10-30T19:21:01Z
[]
[]
cython/cython
2,748
cython__cython-2748
[ "2746" ]
1f11f194972b21bb04b3e5d2f241bf540d87c9f9
diff --git a/Cython/Compiler/Builtin.py b/Cython/Compiler/Builtin.py --- a/Cython/Compiler/Builtin.py +++ b/Cython/Compiler/Builtin.py @@ -30,17 +30,19 @@ class _BuiltinOverride(object): def __init__(self, py_name, args, ret_type, cname, py_equiv="*", utility_code=None, sig=None, func_type=None, - is_strict_signature=False, builtin_return_type=None): + is_strict_signature=False, builtin_return_type=None, + nogil=None): self.py_name, self.cname, self.py_equiv = py_name, cname, py_equiv self.args, self.ret_type = args, ret_type self.func_type, self.sig = func_type, sig self.builtin_return_type = builtin_return_type self.is_strict_signature = is_strict_signature self.utility_code = utility_code + self.nogil = nogil def build_func_type(self, sig=None, self_arg=None): if sig is None: - sig = Signature(self.args, self.ret_type) + sig = Signature(self.args, self.ret_type, nogil=self.nogil) sig.exception_check = False # not needed for the current builtins func_type = sig.function_type(self_arg) if self.is_strict_signature: @@ -92,13 +94,13 @@ def declare_in_type(self, self_type): builtin_function_table = [ # name, args, return, C API func, py equiv = "*" BuiltinFunction('abs', "d", "d", "fabs", - is_strict_signature = True), + is_strict_signature=True, nogil=True), BuiltinFunction('abs', "f", "f", "fabsf", - is_strict_signature = True), + is_strict_signature=True, nogil=True), BuiltinFunction('abs', "i", "i", "abs", - is_strict_signature = True), + is_strict_signature=True, nogil=True), BuiltinFunction('abs', "l", "l", "labs", - is_strict_signature = True), + is_strict_signature=True, nogil=True), BuiltinFunction('abs', None, None, "__Pyx_abs_longlong", utility_code = UtilityCode.load("abs_longlong", "Builtins.c"), func_type = PyrexTypes.CFuncType( diff --git a/Cython/Compiler/TypeSlots.py b/Cython/Compiler/TypeSlots.py --- a/Cython/Compiler/TypeSlots.py +++ b/Cython/Compiler/TypeSlots.py @@ -86,7 +86,7 @@ class Signature(object): 'z': "-1", } - def __init__(self, arg_format, ret_format): + def __init__(self, arg_format, ret_format, nogil=0): self.has_dummy_arg = 0 self.has_generic_args = 0 if arg_format[:1] == '-': @@ -100,6 +100,7 @@ def __init__(self, arg_format, ret_format): self.error_value = self.error_value_map.get(ret_format, None) self.exception_check = ret_format != 'r' and self.error_value is not None self.is_staticmethod = False + self.nogil = nogil def __repr__(self): return '<Signature[%s(%s%s)]>' % ( @@ -149,7 +150,8 @@ def function_type(self, self_arg_override=None): exc_value = self.exception_value() return PyrexTypes.CFuncType( ret_type, args, exception_value=exc_value, - exception_check=self.exception_check) + exception_check=self.exception_check, + nogil=self.nogil) def method_flags(self): if self.ret_format == "O":
diff --git a/tests/run/builtin_abs.pyx b/tests/run/builtin_abs.pyx --- a/tests/run/builtin_abs.pyx +++ b/tests/run/builtin_abs.pyx @@ -59,6 +59,27 @@ def int_abs(int a): """ return abs(a) [email protected](True) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'abs']") +cdef int c_int_abs(int a) nogil except *: + return abs(a) + +def test_c_int_abs(int a): + """ + >>> test_c_int_abs(-5) == 5 + True + >>> test_c_int_abs(-5.1) == 5 + True + >>> test_c_int_abs(-max_int-1) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + OverflowError: ... + >>> test_c_int_abs(max_int) == abs(max_int) or (max_int, test_c_int_abs(max_int), abs(max_int)) + True + """ + return c_int_abs(a) + @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']") @cython.test_fail_if_path_exists("//ReturnStatNode//NameNode[@entry.cname = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = 'labs']") @@ -69,6 +90,19 @@ def uint_abs(unsigned int a): """ return abs(a) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']") [email protected]_fail_if_path_exists("//ReturnStatNode//NameNode[@entry.cname = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'labs']") +cdef unsigned int c_uint_abs(unsigned int a) nogil: + return abs(a) + +def test_c_uint_abs(unsigned int a): + """ + >>> test_c_uint_abs(max_int) == abs(max_int) or (max_int, test_c_uint_abs(max_int), abs(max_int)) + True + """ + return c_uint_abs(a) + @cython.overflowcheck(True) @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = 'labs']") @@ -87,6 +121,27 @@ def long_abs(long a): """ return abs(a) [email protected](True) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'labs']") +cdef long c_long_abs(long a) nogil except *: + return abs(a) + +def test_c_long_abs(long a): + """ + >>> test_c_long_abs(-5) == 5 + True + >>> test_c_long_abs(-5.1) == 5 + True + >>> test_c_long_abs(-max_long-1) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + OverflowError: ... + >>> test_c_long_abs(max_long) == abs(max_long) or (max_long, test_c_long_abs(max_long), abs(max_long)) + True + """ + return c_long_abs(a) + @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']") @cython.test_fail_if_path_exists("//ReturnStatNode//NameNode[@entry.cname = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = 'labs']") @@ -99,6 +154,21 @@ def ulong_abs(unsigned long a): """ return abs(a) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']") [email protected]_fail_if_path_exists("//ReturnStatNode//NameNode[@entry.cname = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'labs']") +cdef unsigned long c_ulong_abs(unsigned long a) nogil: + return abs(a) + +def test_c_ulong_abs(unsigned long a): + """ + >>> test_c_ulong_abs(max_long) == abs(max_long) or (max_int, test_c_ulong_abs(max_long), abs(max_long)) + True + >>> test_c_ulong_abs(max_long + 5) == abs(max_long + 5) or (max_long + 5, test_c_ulong_abs(max_long + 5), abs(max_long + 5)) + True + """ + return c_ulong_abs(a) + @cython.overflowcheck(True) @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = '__Pyx_abs_longlong']") @@ -115,6 +185,25 @@ def long_long_abs(long long a): """ return abs(a) [email protected](True) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = '__Pyx_abs_longlong']") +cdef long long c_long_long_abs(long long a) nogil except *: + return abs(a) + +def test_c_long_long_abs(long long a): + """ + >>> test_c_long_long_abs(-(2**33)) == 2**33 + True + >>> test_c_long_long_abs(-max_long_long-1) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + OverflowError: ... + >>> test_c_long_long_abs(max_long_long) == abs(max_long_long) or (max_long_long, test_c_long_long_abs(max_long_long), abs(max_long_long)) + True + """ + return c_long_long_abs(a) + @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = 'fabs']") def double_abs(double a): @@ -126,6 +215,20 @@ def double_abs(double a): """ return abs(a) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'fabs']") +cdef double c_double_abs(double a) nogil: + return abs(a) + +def test_c_double_abs(double a): + """ + >>> test_c_double_abs(-5) + 5.0 + >>> test_c_double_abs(-5.5) + 5.5 + """ + return c_double_abs(a) + @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = 'fabsf']") def float_abs(float a): @@ -137,6 +240,20 @@ def float_abs(float a): """ return abs(a) [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = 'fabsf']") +cdef float c_float_abs(float a) nogil: + return abs(a) + +def test_c_float_abs(float a): + """ + >>> test_c_float_abs(-5) + 5.0 + >>> test_c_float_abs(-5.5) + 5.5 + """ + return c_float_abs(a) + @cython.test_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", "//ReturnStatNode//NameNode[@entry.cname = '__Pyx_c_abs_double']") def complex_abs(complex a): @@ -147,3 +264,17 @@ def complex_abs(complex a): 5.5 """ return abs(a) + [email protected]_assert_path_exists("//ReturnStatNode//NameNode[@entry.name = 'abs']", + "//ReturnStatNode//NameNode[@entry.cname = '__Pyx_c_abs_double']") +cdef double c_complex_abs(complex a) nogil: + return abs(a) + +def test_c_complex_abs(complex a): + """ + >>> test_c_complex_abs(-5j) + 5.0 + >>> test_c_complex_abs(-5.5j) + 5.5 + """ + return c_complex_abs(a)
Optimized abs should be nogil-safe From the following: ```cython cdef double foo(double x): return abs(x) cdef int bar(int x): return abs(x) ``` the resulting C/C++ code calls `fabs`/`abs` thanks to #1255. If you add `nogil` on these functions, then Cython will complain with: ``` return abs(x) ^ ------------------------------------------------------------ test_abs.pyx:2:14: Calling gil-requiring function not allowed without gil ``` Because of #1837, I'm not sure about `bar`, but at least `foo` should not require the GIL.
True. It's probably as easy as adding nogil to the declaration of the C functions in `Builtin.py`. PR welcome. Tests should go into `tests/run/builtin_abs.pyx`.
2018-12-07T09:28:47Z
[]
[]
cython/cython
2,773
cython__cython-2773
[ "2772" ]
8e7406a087cc9ffe8a190cf6867dd2b90f22fad2
diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -428,6 +428,7 @@ def get_openmp_compiler_flags(language): (3,3) : (operator.lt, lambda x: x in ['build.package_compilation', 'run.yield_from_py33', 'pyximport.pyximport_namespace', + 'run.qualname', ]), (3,4): (operator.lt, lambda x: x in ['run.py34_signature', 'run.test_unicode', # taken from Py3.7, difficult to backport
diff --git a/tests/run/decorators_T593.pyx b/tests/run/decorators_T593.pyx --- a/tests/run/decorators_T593.pyx +++ b/tests/run/decorators_T593.pyx @@ -110,8 +110,8 @@ class Base(type): class Bar(metaclass=Base): """ - >>> Bar._order - ['__module__', '__qualname__', '__doc__', 'bar'] + >>> [n for n in Bar._order if n != "__qualname__"] + ['__module__', '__doc__', 'bar'] """ @property def bar(self): diff --git a/tests/run/locals_T732.pyx b/tests/run/locals_T732.pyx --- a/tests/run/locals_T732.pyx +++ b/tests/run/locals_T732.pyx @@ -23,8 +23,8 @@ def test_class_locals_and_dir(): >>> klass = test_class_locals_and_dir() >>> 'visible' in klass.locs and 'not_visible' not in klass.locs True - >>> klass.names - ['__module__', '__qualname__', 'visible'] + >>> [n for n in klass.names if n != "__qualname__"] + ['__module__', 'visible'] """ not_visible = 1234 class Foo: diff --git a/tests/run/metaclass.pyx b/tests/run/metaclass.pyx --- a/tests/run/metaclass.pyx +++ b/tests/run/metaclass.pyx @@ -69,8 +69,8 @@ class Py3ClassMCOnly(object, metaclass=Py3MetaclassPlusAttr): 321 >>> obj.metaclass_was_here True - >>> obj._order - ['__module__', '__qualname__', '__doc__', 'bar', 'metaclass_was_here'] + >>> [n for n in obj._order if n != "__qualname__"] + ['__module__', '__doc__', 'bar', 'metaclass_was_here'] """ bar = 321 @@ -81,8 +81,8 @@ class Py3InheritedMetaclass(Py3ClassMCOnly): 345 >>> obj.metaclass_was_here True - >>> obj._order - ['__module__', '__qualname__', '__doc__', 'bar', 'metaclass_was_here'] + >>> [n for n in obj._order if n != "__qualname__"] + ['__module__', '__doc__', 'bar', 'metaclass_was_here'] """ bar = 345 @@ -109,8 +109,8 @@ class Py3Foo(object, metaclass=Py3Base, foo=123): 123 >>> obj.bar 321 - >>> obj._order - ['__module__', '__qualname__', '__doc__', 'bar', 'foo'] + >>> [n for n in obj._order if n != "__qualname__"] + ['__module__', '__doc__', 'bar', 'foo'] """ bar = 321 @@ -122,8 +122,8 @@ class Py3FooInherited(Py3Foo, foo=567): 567 >>> obj.bar 321 - >>> obj._order - ['__module__', '__qualname__', '__doc__', 'bar', 'foo'] + >>> [n for n in obj._order if n != "__qualname__"] + ['__module__', '__doc__', 'bar', 'foo'] """ bar = 321
Python 2: __qualname__ is wrong (when subclassed or on metaclass) When defining a Python `class` using Cython, the `__qualname__` attribute is always set, even on Python 2. When this Cython-defined class is either subclassed or used as metaclass in pure Python code, that new class gets the wrong `__qualname__` from Cython. Examples: ``` # In Cython class X(type): pass ``` ``` # In Python >>> class Y(X): pass >>> Y.__qualname__ X ``` ``` # In Python >>> class Y(object): __metaclass__ = X >>> Y.__qualname__ X ``` As you can see, we get a wrong `__qualname__` in both cases. This confuses for example tools like Sphinx, where it produces incorrect output. Since `__qualname__` is useless on Python 2, I suggest to simply not set `__qualname__` on Python 2. For Sphinx, not having a `__qualname__` is fine, since it will simply use `__name__` which is correct.
Personally, I consider `__qualname__` a useful debugging feature all by itself, so I'd prefer keeping it if/where possible. But the problem here is that Python doesn't override it for its own subtypes, so I understand that it gets in the way for classes. Functions should be ok (although, see #2562). Should we remove it only from classes in Py2?
2018-12-31T12:57:27Z
[]
[]
cython/cython
2,784
cython__cython-2784
[ "2776" ]
5ecb4ba9519e456c064f2d84c32ee4bd9d390374
diff --git a/Cython/Coverage.py b/Cython/Coverage.py --- a/Cython/Coverage.py +++ b/Cython/Coverage.py @@ -74,7 +74,7 @@ def file_tracer(self, filename): if c_file is None: c_file, py_file = self._find_source_files(filename) if not c_file: - return None + return None # unknown file # parse all source file paths and lines from C file # to learn about all relevant source files right away (pyx/pxi/pxd) @@ -82,7 +82,9 @@ def file_tracer(self, filename): # is not from the main .pyx file but a file with a different # name than the .c file (which prevents us from finding the # .c file) - self._parse_lines(c_file, filename) + _, code = self._parse_lines(c_file, filename) + if code is None: + return None # no source found if self._file_path_map is None: self._file_path_map = {}
diff --git a/tests/run/coverage_installed_pkg.srctree b/tests/run/coverage_installed_pkg.srctree new file mode 100644 --- /dev/null +++ b/tests/run/coverage_installed_pkg.srctree @@ -0,0 +1,71 @@ +# mode: run +# tag: coverage,trace + +""" +PYTHON setup.py build_ext -i +PYTHON -c "import shutil; shutil.move('ext_src/ext_pkg', 'ext_pkg')" +PYTHON -m coverage run coverage_test.py +PYTHON -m coverage report +""" + +######## setup.py ######## +from distutils.core import setup, Extension +from Cython.Build import cythonize + +setup(ext_modules = cythonize([ + 'pkg/*.pyx', +])) + +setup( + name='ext_pkg', + package_dir={'': 'ext_src'}, + ext_modules = cythonize([ + Extension('ext_pkg._mul', ['ext_src/ext_pkg/mul.py']) + ]), +) + + +######## .coveragerc ######## +[run] +plugins = Cython.Coverage + + +######## pkg/__init__.py ######## +from .test_ext_import import test_add + + +######## pkg/test_ext_import.pyx ######## +# cython: linetrace=True +# distutils: define_macros=CYTHON_TRACE=1 + +import ext_pkg + + +cpdef test_add(int a, int b): + return a + ext_pkg.test_mul(b, 2) + + +######## ext_src/ext_pkg/__init__.py ######## +from .mul import test_mul + + +######## ext_src/ext_pkg/mul.py ######## +from __future__ import absolute_import + + +def test_mul(a, b): + return a * b + + +try: + from ._mul import * +except ImportError: + pass + + +######## coverage_test.py ######## + +from pkg import test_add + + +assert 5 == test_add(1, 2)
Cython.Coverage produces error when using gevent Hi, I build a simple pyx with ``gevent`` module (https://github.com/wjsi/test_cython_cov/blob/master/test_cov.pyx) and try to use Cython.Coverage to get code coverage, it produces an error when ``coverage report`` is executed: ``` $ coverage run test_file.py $ coverage report Plugin 'Cython.Coverage.Plugin' did not provide a file reporter for '/Users/wenjun.swj/miniconda3/lib/python3.7/site-packages/gevent/_hub_local.py'. ``` When gevent is removed, for instance, replaced with ``time`` module, no errors raised and the report is shown normally. I uploaded all test files in https://github.com/wjsi/test_cython_cov. I'm running on MacOS 10.14 with Anaconda Python 3.7.1, cython==0.29.2 and coverage==4.5.2.
2019-01-05T04:15:47Z
[]
[]
cython/cython
2,792
cython__cython-2792
[ "2791" ]
f00af64bcc2cef4c3fb1433ed670ab5f9970e2cd
diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -99,18 +99,17 @@ def __init__(self, include_directories, compiler_directives, cpp=False, def set_language_level(self, level): from .Future import print_function, unicode_literals, absolute_import, division, generator_stop - future_directives = [] + future_directives = set() if level == '3str': - future_directives = [print_function, absolute_import, division, generator_stop] - self.future_directives.discard(unicode_literals) level = 3 else: level = int(level) if level >= 3: - future_directives = [print_function, unicode_literals, absolute_import, division, generator_stop] + future_directives.add(unicode_literals) + if level >= 3: + future_directives.update([print_function, absolute_import, division, generator_stop]) self.language_level = level - if future_directives: - self.future_directives.update(future_directives) + self.future_directives = future_directives if level >= 3: self.modules['builtins'] = self.modules['__builtin__']
diff --git a/tests/run/language_level.srctree b/tests/run/language_level.srctree --- a/tests/run/language_level.srctree +++ b/tests/run/language_level.srctree @@ -7,12 +7,19 @@ PYTHON -c "import infile2; import infile3" from Cython.Build.Dependencies import cythonize from distutils.core import setup -setup( - ext_modules = (cythonize("infile*.py") + - cythonize("directive2.py", compiler_directives={'language_level': 2}) + - cythonize("directive3.py", compiler_directives={'language_level': 3}) - ) -) +ext_modules = [] + +# Test language_level specified in the cythonize() call +ext_modules += cythonize("directive2.py", compiler_directives={'language_level': 2}) +ext_modules += cythonize("directive3.py", compiler_directives={'language_level': 3}) + +# Test language_level specified in the source file. We give a +# conflicting directive to cythonize() to check that the language_level +# is correctly overridden when compiling +ext_modules += cythonize("infile2.py", compiler_directives={'language_level': 3}) +ext_modules += cythonize("infile3.py", compiler_directives={'language_level': 2}) + +setup(ext_modules=ext_modules) ######## directive3.py ########
# cython: language_level=2 does not work as expected There seems to be a problem with handling `# cython: language_level=2` when `language_level=3str` is set globally (for example, using the `compiler_directives` flag of `cythonize()`). For some features like division, the Python 3 semantics are used anyway. Example: ``` # cython: language_level=2 def test(): ver = 3 L = [ver for ver in [2]] print(f"effective language_level for list comprehension: {ver}") cdef object a = 3 ver = int((a / 2) * 2) print(f"effective language_level for division: {ver}") ``` gives as output ``` >>> test() effective language_level for list comprehension: 2 effective language_level for division: 3 ``` Strangely enough, the opposite (`# cython: language_level=3str` when `language_level=2` is set globally) works correctly.
The problems seems to be that `set_language_level` only *adds* `future_directives` but it never removes any. PR coming...
2019-01-09T11:45:05Z
[]
[]
cython/cython
2,794
cython__cython-2794
[ "2665" ]
f00af64bcc2cef4c3fb1433ed670ab5f9970e2cd
diff --git a/Cython/Build/Cythonize.py b/Cython/Build/Cythonize.py --- a/Cython/Build/Cythonize.py +++ b/Cython/Build/Cythonize.py @@ -69,7 +69,7 @@ def parse_compile_time_env(option, name, value, parser): def find_package_base(path): base_dir, package_path = os.path.split(path) - while os.path.isfile(os.path.join(base_dir, '__init__.py')): + while is_package_dir(base_dir): base_dir, parent = os.path.split(base_dir) package_path = '%s/%s' % (parent, package_path) return base_dir, package_path diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -219,7 +219,7 @@ def find_module(self, module_name, relative_to=None, pos=None, need_pxd=1, # look for the non-existing pxd file next time. scope.pxd_file_loaded = True package_pathname = self.search_include_directories(qualified_name, ".py", pos) - if package_pathname and package_pathname.endswith('__init__.py'): + if package_pathname and package_pathname.endswith(Utils.PACKAGE_FILES): pass else: error(pos, "'%s.pxd' not found" % qualified_name.replace('.', os.sep)) diff --git a/Cython/Utils.py b/Cython/Utils.py --- a/Cython/Utils.py +++ b/Cython/Utils.py @@ -23,6 +23,8 @@ import shutil from contextlib import contextmanager +PACKAGE_FILES = ("__init__.py", "__init__.pyc", "__init__.pyx", "__init__.pxd") + modification_time = os.path.getmtime _function_caches = [] @@ -191,10 +193,7 @@ def check_package_dir(dir, package_names): @cached_function def is_package_dir(dir_path): - for filename in ("__init__.py", - "__init__.pyc", - "__init__.pyx", - "__init__.pxd"): + for filename in PACKAGE_FILES: path = os.path.join(dir_path, filename) if path_exists(path): return 1 diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -419,11 +419,12 @@ def get_openmp_compiler_flags(language): # to be unsafe... (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3', 'run.test_raisefrom', + 'run.different_package_names', ]), (3,): (operator.ge, lambda x: x in ['run.non_future_division', 'compile.extsetslice', 'compile.extdelslice', - 'run.special_methods_T561_py2' + 'run.special_methods_T561_py2', ]), (3,3) : (operator.lt, lambda x: x in ['build.package_compilation', 'run.yield_from_py33',
diff --git a/tests/run/different_package_names.srctree b/tests/run/different_package_names.srctree new file mode 100644 --- /dev/null +++ b/tests/run/different_package_names.srctree @@ -0,0 +1,43 @@ +# mode: run +# tag: import,cimport,packages + +PYTHON setup.py build_ext --inplace +PYTHON -c "import pkg_py" +PYTHON -c "import pkg_py.pkg_pyx" +PYTHON -c "import pkg_py.pkg_pyx.module as module; module.run_test()" + +######## setup.py ######## + +from distutils.core import setup +from Cython.Build import cythonize + +setup( + ext_modules=cythonize('**/*.pyx', language_level=3), +) + + +######## pkg_py/__init__.py ######## + +TYPE = 'py' + +######## pkg_py/pkg_pyx/__init__.pyx ######## + +TYPE = 'pyx' + +######## pkg_py/pkg_pyx/pkg_pxd/__init__.pxd ######## + +# Not what Python would consider a package, but Cython can use it for cimports. +from libc.math cimport fabs + +######## pkg_py/pkg_pyx/module.pyx ######## + +from pkg_py.pkg_pyx.pkg_pxd cimport fabs + +def run_test(): + import pkg_py + assert pkg_py.TYPE == 'py' + + import pkg_py.pkg_pyx + assert pkg_py.pkg_pyx.TYPE == 'pyx' + + assert fabs(-2.0) == 2.0
Support packages from __init__.pyx files I'm trying to build a project of mine on Windows, but errors out with some weird linker error. On Linux everything is fine. The project repositories are public, so this should be easy for you to try for yourself: ``` .python-win\python.exe -m pip install -U Cython Requirement already up-to-date: Cython in c:\users\me\appdata\roaming\python\python37\site-packages (0.29) You are using pip version 10.0.1, however version 18.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. .python-win\python.exe -m pip install -U https://github.com/JonasT/nettools/archive/master.zip Collecting https://github.com/JonasT/nettools/archive/master.zip Downloading https://github.com/JonasT/nettools/archive/master.zip - 133kB 930kB/s Installing collected packages: nettools Found existing installation: nettools 0.1 Uninstalling nettools-0.1: Successfully uninstalled nettools-0.1 Running setup.py install for nettools ... done Successfully installed nettools-0.1 You are using pip version 10.0.1, however version 18.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. .python-win\python.exe -m pip install -U https://github.com/JonasT/wobblui/archive/b37bcd538193ab092920e931f53d5d55c79be6ec.zip Collecting https://github.com/JonasT/wobblui/archive/b37bcd538193ab092920e931f53d5d55c79be6ec.zip Downloading https://github.com/JonasT/wobblui/archive/b37bcd538193ab092920e931f53d5d55c79be6ec.zip \ 2.0MB 25.6MB/s Requirement not upgraded as not directly required: PySDL2>=0.9.6 in c:\users\me\appdata\roaming\python\python37\site-packages (from wobblui==2018.8.post2) (0.9.6) Requirement not upgraded as not directly required: Cython in c:\users\me\appdata\roaming\python\python37\site-packages (from wobblui==2018.8.post2) (0.29) Requirement not upgraded as not directly required: Pillow in c:\users\me\appdata\roaming\python\python37\site-packages (from wobblui==2018.8.post2) (5.3.0) Requirement not upgraded as not directly required: nettools in c:\myproject\tools\windows\.python-win\lib\site-packages (from wobblui==2018.8.post2) (0.1) Installing collected packages: wobblui Running setup.py install for wobblui ... error Complete output from command C:\myproject\tools\windows\.python-win\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\me\\AppData\\Local\\Temp\\pip-req-build-rvvpu7mo\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\me\AppData\Local\Temp\pip-record-l151ayce\install-record.txt --single-version-externally-managed --compile: C:\myproject\tools\windows\.python-win\Lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) C:\myproject\tools\windows\.python-win\lib\site-packages\setuptools\dist.py:397: UserWarning: Normalizing '2018.08-2' to '2018.8.post2' normalized_version, running install running build running build_py package init file 'src\wobblui\__init__.py' not found (or not a regular file) creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\wobblui copying src\wobblui\box.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\button.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\clipboard.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\color.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\cssparse.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\filedialog.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\gfx.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\image.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\keyboard.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\label.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\list.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\menu.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\mouse.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\osinfo.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\scrollbarwidget.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\sdlinit.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\style.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\test_richtext.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\textedit.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\textentry.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\timer.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\topbar.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\uiconf.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\version.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\widgetman.py -> build\lib.win-amd64-3.7\wobblui copying src\wobblui\window.py -> build\lib.win-amd64-3.7\wobblui creating build\lib.win-amd64-3.7\wobblui\font copying src\wobblui\font\info.py -> build\lib.win-amd64-3.7\wobblui\font copying src\wobblui\font\otfttf.py -> build\lib.win-amd64-3.7\wobblui\font copying src\wobblui\font\query.py -> build\lib.win-amd64-3.7\wobblui\font copying src\wobblui\font\__init__.py -> build\lib.win-amd64-3.7\wobblui\font creating build\lib.win-amd64-3.7\wobblui\p4arecipes copying src\wobblui\p4arecipes\nettools.py -> build\lib.win-amd64-3.7\wobblui\p4arecipes copying src\wobblui\p4arecipes\wobblui.py -> build\lib.win-amd64-3.7\wobblui\p4arecipes copying src\wobblui\p4arecipes\__init__.py -> build\lib.win-amd64-3.7\wobblui\p4arecipes creating build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\SourceCodePro-Regular.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreadventor-bold.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreadventor-bolditalic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreadventor-italic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreadventor-regular.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreheros-bold.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreheros-bolditalic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreheros-italic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyreheros-regular.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyrepagella-bold.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyrepagella-bolditalic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyrepagella-italic.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyrepagella-regular.ttf -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\SourceCodePro-Regular-LICENSE.md -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts copying src\wobblui\font\packaged-fonts\texgyre-LICENSE.md -> build\lib.win-amd64-3.7\wobblui\font\packaged-fonts creating build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\add.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\arrow_left.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\cross.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\folder.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\hourglass.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\hovercircle.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\more.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\outandup.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\sandwich.png -> build\lib.win-amd64-3.7\wobblui\img copying src\wobblui\img\save.png -> build\lib.win-amd64-3.7\wobblui\img running build_ext C:\Users\me\AppData\Roaming\Python\Python37\site-packages\Cython\Compiler\Main.py:367: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\cache.pyx tree = Parsing.p_module(s, pxd, full_module_name) Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\cache.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\cache.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\event.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\event.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\perf.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\perf.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\richtext.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\richtext.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\widget.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\widget.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\widget_base.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\widget_base.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\woblog.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\woblog.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\__init__.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\__init__.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\font\manager.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\font\manager.pyx Compiling C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\font\sdlfont.pyx because it changed. [1/1] Cythonizing C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\src\wobblui\font\sdlfont.pyx building 'wobblui.cache' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\src creating build\temp.win-amd64-3.7\Release\src\wobblui C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\cache.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\cache.obj cache.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_cache build\temp.win-amd64-3.7\Release\src\wobblui\cache.obj /OUT:build\lib.win-amd64-3.7\wobblui\cache.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\cache.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\cache.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\cache.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.event' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\event.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\event.obj event.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_event build\temp.win-amd64-3.7\Release\src\wobblui\event.obj /OUT:build\lib.win-amd64-3.7\wobblui\event.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\event.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\event.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\event.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.perf' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\perf.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\perf.obj perf.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_perf build\temp.win-amd64-3.7\Release\src\wobblui\perf.obj /OUT:build\lib.win-amd64-3.7\wobblui\perf.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\perf.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\perf.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\perf.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.richtext' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\richtext.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\richtext.obj richtext.c src\wobblui\richtext.c(8277): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data src\wobblui\richtext.c(16462): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data src\wobblui\richtext.c(17881): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data src\wobblui\richtext.c(18502): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data src\wobblui\richtext.c(18803): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data src\wobblui\richtext.c(19076): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_richtext build\temp.win-amd64-3.7\Release\src\wobblui\richtext.obj /OUT:build\lib.win-amd64-3.7\wobblui\richtext.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\richtext.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\richtext.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\richtext.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.widget' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\widget.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\widget.obj widget.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_widget build\temp.win-amd64-3.7\Release\src\wobblui\widget.obj /OUT:build\lib.win-amd64-3.7\wobblui\widget.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\widget.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\widget.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\widget.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.widget_base' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\widget_base.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\widget_base.obj widget_base.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_widget_base build\temp.win-amd64-3.7\Release\src\wobblui\widget_base.obj /OUT:build\lib.win-amd64-3.7\wobblui\widget_base.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\widget_base.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\widget_base.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\widget_base.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.woblog' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\woblog.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\woblog.obj woblog.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit_woblog build\temp.win-amd64-3.7\Release\src\wobblui\woblog.obj /OUT:build\lib.win-amd64-3.7\wobblui\woblog.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\woblog.cp37-win_amd64.lib Creating library build\temp.win-amd64-3.7\Release\src\wobblui\woblog.cp37-win_amd64.lib and object build\temp.win-amd64-3.7\Release\src\wobblui\woblog.cp37-win_amd64.exp Generating code Finished generating code building 'wobblui.__init__' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\myproject\tools\windows\.python-win\include -IC:\myproject\tools\windows\.python-win\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\cppwinrt" /Tcsrc\wobblui\__init__.c /Fobuild\temp.win-amd64-3.7\Release\src\wobblui\__init__.obj __init__.c C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\myproject\tools\windows\.python-win\libs /LIBPATH:C:\myproject\tools\windows\.python-win\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.17134.0\um\x64" /EXPORT:PyInit___init__ build\temp.win-amd64-3.7\Release\src\wobblui\__init__.obj /OUT:build\lib.win-amd64-3.7\wobblui\__init__.cp37-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.7\Release\src\wobblui\__init__.cp37-win_amd64.lib LINK : error LNK2001: unresolved external symbol PyInit___init__ build\temp.win-amd64-3.7\Release\src\wobblui\__init__.cp37-win_amd64.lib : fatal error LNK1120: 1 unresolved externals error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.15.26726\\bin\\HostX86\\x64\\link.exe' failed with exit status 1120 ---------------------------------------- Command "C:\myproject\tools\windows\.python-win\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\me\\AppData\\Local\\Temp\\pip-req-build-rvvpu7mo\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\me\AppData\Local\Temp\pip-record-l151ayce\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\me\AppData\Local\Temp\pip-req-build-rvvpu7mo\ You are using pip version 10.0.1, however version 18.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. Command failed. C:\myproject\tools\windows> ```
Is there anything I could still provide for this issue? Is it some by design problem? I am using some sort of import redirection to work around this now, but it is pretty ugly and I'd like to get rid of it. Compiled package `__init__` files are not as well supported as normal modules, also due to quirks in distutils and CPython's loader. Best to avoid them and use a normal `__init__.py` instead that imports whatever you want to expose at a package level. Note that also in normal Python (although there are exceptions), it's not very common and sometimes frowned upon to have a major part of the package implementation in `__init__.py`. Ok but will you fix this? Because while distutils/setuptools indeed also have a bug related to this, it can be worked around and it seems like a cop-out if all projects just go "well it breaks with the other things as well, so why bother" instead of fixing it... The Cython issue here is much more annoying because it requires complete import redirection which makes the files much less readable. (the setuptools issue can be worked around in the setup.py itself, without affecting the code) So this has a quite bigger impact on packaging and code readability, and it would be *really good* if it could be fixed At least in Py3.5, with PEP-489 in place, this should be doable now. And, in fact, there is a test for this that works in Py3.3+: https://github.com/cython/cython/blob/master/tests/build/package_compilation.srctree Note that it uses compiled `__init__.py` files instead of `__init__.pyx` files. Maybe we just forgot to also check for the latter at some point during the translation. Investigation/PR welcome.
2019-01-11T05:51:27Z
[]
[]
cython/cython
2,842
cython__cython-2842
[ "1354" ]
f1eaa9c1f8c37d8679a259982ee9949676952f0e
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -1426,6 +1426,7 @@ def generate_dealloc_function(self, scope, code): is_final_type = scope.parent_type.is_final_type needs_gc = scope.needs_gc() + needs_trashcan = scope.needs_trashcan() weakref_slot = scope.lookup_here("__weakref__") if not scope.is_closure_class_scope else None if weakref_slot not in scope.var_entries: @@ -1464,6 +1465,11 @@ def generate_dealloc_function(self, scope, code): # running this destructor. code.putln("PyObject_GC_UnTrack(o);") + if needs_trashcan: + code.globalstate.use_utility_code( + UtilityCode.load_cached("PyTrashcan", "ExtensionTypes.c")) + code.putln("__Pyx_TRASHCAN_BEGIN(o, %s)" % slot_func_cname) + # call the user's __dealloc__ self.generate_usr_dealloc_call(scope, code) @@ -1537,6 +1543,10 @@ def generate_dealloc_function(self, scope, code): code.putln("(*Py_TYPE(o)->tp_free)(o);") if freelist_size: code.putln("}") + + if needs_trashcan: + code.putln("__Pyx_TRASHCAN_END") + code.putln( "}") diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -313,6 +313,7 @@ def normalise_encoding_name(option_name, encoding): 'freelist': int, 'c_string_type': one_of('bytes', 'bytearray', 'str', 'unicode'), 'c_string_encoding': normalise_encoding_name, + 'trashcan': bool, } for key, val in _directive_defaults.items(): @@ -355,6 +356,7 @@ def normalise_encoding_name(option_name, encoding): 'np_pythran': ('module',), 'fast_gil': ('module',), 'iterable_coroutine': ('module', 'function'), + 'trashcan' : ('cclass',), } diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -1136,6 +1136,7 @@ class PyObjectType(PyrexType): is_extern = False is_subclassed = False is_gc_simple = False + builtin_trashcan = False # builtin type using trashcan def __str__(self): return "Python object" @@ -1190,10 +1191,14 @@ def check_for_null_code(self, cname): builtin_types_that_cannot_create_refcycles = set([ - 'bool', 'int', 'long', 'float', 'complex', + 'object', 'bool', 'int', 'long', 'float', 'complex', 'bytearray', 'bytes', 'unicode', 'str', 'basestring' ]) +builtin_types_with_trashcan = set([ + 'dict', 'list', 'set', 'frozenset', 'tuple', 'type', +]) + class BuiltinObjectType(PyObjectType): # objstruct_cname string Name of PyObject struct @@ -1218,6 +1223,7 @@ def __init__(self, name, cname, objstruct_cname=None): self.typeptr_cname = "(&%s)" % cname self.objstruct_cname = objstruct_cname self.is_gc_simple = name in builtin_types_that_cannot_create_refcycles + self.builtin_trashcan = name in builtin_types_with_trashcan if name == 'type': # Special case the type type, as many C API calls (and other # libraries) actually expect a PyTypeObject* for type arguments. diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -2041,7 +2041,7 @@ def add_default_value(self, type): class CClassScope(ClassScope): # Namespace of an extension type. # - # parent_type CClassType + # parent_type PyExtensionType # #typeobj_cname string or None # #objstruct_cname string # method_table_cname string @@ -2085,6 +2085,22 @@ def needs_gc(self): return not self.parent_type.is_gc_simple return False + def needs_trashcan(self): + # If the trashcan directive is explicitly set to False, + # unconditionally disable the trashcan. + directive = self.directives.get('trashcan') + if directive is False: + return False + # If the directive is set to True and the class has Python-valued + # C attributes, then it should use the trashcan in tp_dealloc. + if directive and self.has_cyclic_pyobject_attrs: + return True + # Use the trashcan if the base class uses it + base_type = self.parent_type.base_type + if base_type and base_type.scope is not None: + return base_type.scope.needs_trashcan() + return self.parent_type.builtin_trashcan + def needs_tp_clear(self): """ Do we need to generate an implementation for the tp_clear slot? Can
diff --git a/tests/run/trashcan.pyx b/tests/run/trashcan.pyx new file mode 100644 --- /dev/null +++ b/tests/run/trashcan.pyx @@ -0,0 +1,148 @@ +# mode: run + +cimport cython + + +# Count number of times an object was deallocated twice. This should remain 0. +cdef int double_deallocations = 0 +def assert_no_double_deallocations(): + global double_deallocations + err = double_deallocations + double_deallocations = 0 + assert not err + + +# Compute x = f(f(f(...(None)...))) nested n times and throw away the result. +# The real test happens when exiting this function: then a big recursive +# deallocation of x happens. We are testing two things in the tests below: +# that Python does not crash and that no double deallocation happens. +# See also https://github.com/python/cpython/pull/11841 +def recursion_test(f, int n=2**20): + x = None + cdef int i + for i in range(n): + x = f(x) + + [email protected](True) +cdef class Recurse: + """ + >>> recursion_test(Recurse) + >>> assert_no_double_deallocations() + """ + cdef public attr + cdef int deallocated + + def __init__(self, x): + self.attr = x + + def __dealloc__(self): + # Check that we're not being deallocated twice + global double_deallocations + double_deallocations += self.deallocated + self.deallocated = 1 + + +cdef class RecurseSub(Recurse): + """ + >>> recursion_test(RecurseSub) + >>> assert_no_double_deallocations() + """ + cdef int subdeallocated + + def __dealloc__(self): + # Check that we're not being deallocated twice + global double_deallocations + double_deallocations += self.subdeallocated + self.subdeallocated = 1 + + [email protected](4) [email protected](True) +cdef class RecurseFreelist: + """ + >>> recursion_test(RecurseFreelist) + >>> recursion_test(RecurseFreelist, 1000) + >>> assert_no_double_deallocations() + """ + cdef public attr + cdef int deallocated + + def __init__(self, x): + self.attr = x + + def __dealloc__(self): + # Check that we're not being deallocated twice + global double_deallocations + double_deallocations += self.deallocated + self.deallocated = 1 + + +# Subclass of list => uses trashcan by default +# As long as https://github.com/python/cpython/pull/11841 is not fixed, +# this does lead to double deallocations, so we skip that check. +cdef class RecurseList(list): + """ + >>> RecurseList(42) + [42] + >>> recursion_test(RecurseList) + """ + def __init__(self, x): + super().__init__((x,)) + + +# Some tests where the trashcan is NOT used. When the trashcan is not used +# in a big recursive deallocation, the __dealloc__s of the base classs are +# only run after the __dealloc__s of the subclasses. +# We use this to detect trashcan usage. +cdef int base_deallocated = 0 +cdef int trashcan_used = 0 +def assert_no_trashcan_used(): + global base_deallocated, trashcan_used + err = trashcan_used + trashcan_used = base_deallocated = 0 + assert not err + + +cdef class Base: + def __dealloc__(self): + global base_deallocated + base_deallocated = 1 + + +# Trashcan disabled by default +cdef class Sub1(Base): + """ + >>> recursion_test(Sub1, 100) + >>> assert_no_trashcan_used() + """ + cdef public attr + + def __init__(self, x): + self.attr = x + + def __dealloc__(self): + global base_deallocated, trashcan_used + trashcan_used += base_deallocated + + [email protected](True) +cdef class Middle(Base): + cdef public foo + + +# Trashcan disabled explicitly [email protected](False) +cdef class Sub2(Middle): + """ + >>> recursion_test(Sub2, 1000) + >>> assert_no_trashcan_used() + """ + cdef public attr + + def __init__(self, x): + self.attr = x + + def __dealloc__(self): + global base_deallocated, trashcan_used + trashcan_used += base_deallocated
Fix cython's deep C-stacks upon deallocation Once you know about python's `trashcan` that is used in its dealloc methods and that cython does not make use of it, it's not hard to cause a crash in deallocation of a cython class: ``` cython(""" cdef class A(object): cdef object ref def __init__(self,ref): self.ref = ref """) ``` A long linked list of these will quickly exhaust the C-stack (set a ulimit on the stack if you have a lot of memory): ``` print "allocating a" a=A(None) for i in range(10**6): a=A(a) print "deleting a" del a print "done deleting a" ``` Once you interleave with a python container type (tuple, for instance), the trashcan starts to kick in. The following runs without problem. ``` b=A(None) print "allocating b" for i in range(10**6): b=A((b,)) print "deleting b" del b print "done deleting b" ``` This issue came up as a side issue on http://trac.sagemath.org/sage_trac/ticket/13896. The trashcan is a rather complicated thing to get working right. In particular, cython must take precautions to ensure that once deallocation is started on an object, it isn't put into the trashcan in deallocs of base types. This is also sage http://trac.sagemath.org/sage_trac/ticket/13901 Migrated from http://trac.cython.org/ticket/797
This is another instance: https://trac.sagemath.org/ticket/27267 > In particular, cython must take precautions to ensure that once deallocation is started on an object, it isn't put into the trashcan in deallocs of base types. Good point. I'll look into it. What about something like ```C void foo_tp_dealloc(PyObject* op) { /* Only enable the trashcan when this is the actual tp_dealloc of the type, not when we're being called recursively by the tp_dealloc of a subclass */ int do_trashcan = (Py_TYPE(op)->tp_dealloc == foo_tp_dealloc); if (!do_trashcan) goto skip_trashcan_begin; Py_TRASHCAN_SAFE_BEGIN(op); skip_trashcan_begin: /* Usual deallocator goes here */ if (!do_trashcan) goto skip_trashcan_end; Py_TRASHCAN_SAFE_END(op); skip_trashcan_end: } ``` It won't win prices for beautiful code, but I'll try to get this working. A fix for the trashcan in CPython: https://github.com/python/cpython/pull/11841
2019-02-14T09:59:26Z
[]
[]
cython/cython
2,858
cython__cython-2858
[ "2855" ]
ef5f4cc7a4747f7a5f82c0348cca258eb8b5882d
diff --git a/Cython/Build/Cythonize.py b/Cython/Build/Cythonize.py --- a/Cython/Build/Cythonize.py +++ b/Cython/Build/Cythonize.py @@ -168,9 +168,10 @@ def __call__(self, parser, namespace, values, option_string=None): help='use Python 3 syntax mode by default') parser.add_argument('--3str', dest='language_level', action='store_const', const='3str', help='use Python 3 syntax mode by default') - parser.add_argument('-a', '--annotate', dest='annotate', action='store_true', default=None, - help='generate annotated HTML page for source files') - + parser.add_argument('-a', '--annotate', nargs='?', const='default', type=str, choices={'default','fullc'}, + help='Produce a colorized HTML version of the source. ' + 'Use --annotate=fullc to include entire ' + 'generated C/C++-code.') parser.add_argument('-x', '--exclude', metavar='PATTERN', dest='excludes', action='append', default=[], help='exclude certain file patterns from the compilation') diff --git a/Cython/Build/IpythonMagic.py b/Cython/Build/IpythonMagic.py --- a/Cython/Build/IpythonMagic.py +++ b/Cython/Build/IpythonMagic.py @@ -179,8 +179,11 @@ def f(x): @magic_arguments.magic_arguments() @magic_arguments.argument( - '-a', '--annotate', action='store_true', default=False, - help="Produce a colorized HTML version of the source." + '-a', '--annotate', nargs='?', const="default", type=str, + choices={"default","fullc"}, + help="Produce a colorized HTML version of the source. " + "Use --annotate=fullc to include entire " + "generated C/C++-code." ) @magic_arguments.argument( '-+', '--cplus', action='store_true', default=False, diff --git a/Cython/Compiler/Annotate.py b/Cython/Compiler/Annotate.py --- a/Cython/Compiler/Annotate.py +++ b/Cython/Compiler/Annotate.py @@ -22,9 +22,13 @@ class AnnotationCCodeWriter(CCodeWriter): + + # also used as marker for detection of complete code emission in tests + COMPLETE_CODE_TITLE = "Complete cythonized code" - def __init__(self, create_from=None, buffer=None, copy_formatting=True): + def __init__(self, create_from=None, buffer=None, copy_formatting=True, show_entire_c_code=False): CCodeWriter.__init__(self, create_from, buffer, copy_formatting=copy_formatting) + self.show_entire_c_code = show_entire_c_code if create_from is None: self.annotation_buffer = StringIO() self.last_annotated_pos = None @@ -198,17 +202,24 @@ def _get_line_coverage(self, coverage_xml, source_filename): for line in coverage_data.iterfind('lines/line') ) - def _htmlify_code(self, code): + def _htmlify_code(self, code, language): try: from pygments import highlight - from pygments.lexers import CythonLexer + from pygments.lexers import CythonLexer, CppLexer from pygments.formatters import HtmlFormatter except ImportError: # no Pygments, just escape the code return html_escape(code) + if language == "cython": + lexer = CythonLexer(stripnl=False, stripall=False) + elif language == "c/cpp": + lexer = CppLexer(stripnl=False, stripall=False) + else: + # unknown language, use fallback + return html_escape(code) html_code = highlight( - code, CythonLexer(stripnl=False, stripall=False), + code, lexer, HtmlFormatter(nowrap=True)) return html_code @@ -228,7 +239,7 @@ def annotate(match): return u"<span class='%s'>%s</span>" % ( group_name, match.group(group_name)) - lines = self._htmlify_code(cython_code).splitlines() + lines = self._htmlify_code(cython_code, "cython").splitlines() lineno_width = len(str(len(lines))) if not covered_lines: covered_lines = None @@ -279,6 +290,19 @@ def annotate(match): outlist.append(u"<pre class='cython code score-{score} {covered}'>{code}</pre>".format( score=score, covered=covered, code=c_code)) outlist.append(u"</div>") + + # now the whole c-code if needed: + if self.show_entire_c_code: + outlist.append(u'<p><div class="cython">') + onclick_title = u"<pre class='cython line'{onclick}>+ {title}</pre>\n"; + outlist.append(onclick_title.format( + onclick=self._onclick_attr, + title=AnnotationCCodeWriter.COMPLETE_CODE_TITLE, + )) + complete_code_as_html = self._htmlify_code(self.buffer.getvalue(), "c/cpp") + outlist.append(u"<pre class='cython code'>{code}</pre>".format(code=complete_code_as_html)) + outlist.append(u"</div></p>") + return outlist diff --git a/Cython/Compiler/CmdLine.py b/Cython/Compiler/CmdLine.py --- a/Cython/Compiler/CmdLine.py +++ b/Cython/Compiler/CmdLine.py @@ -34,6 +34,7 @@ -D, --no-docstrings Strip docstrings from the compiled module. -a, --annotate Produce a colorized HTML version of the source. + Use --annotate=fullc to include entire generated C/C++-code. --annotate-coverage <cov.xml> Annotate and include coverage information from cov.xml. --line-directives Produce #line directives pointing to the .pyx source --cplus Output a C++ rather than C file. @@ -128,7 +129,7 @@ def get_param(option): elif option in ("-D", "--no-docstrings"): Options.docstrings = False elif option in ("-a", "--annotate"): - Options.annotate = True + Options.annotate = pop_value('default') elif option == "--annotate-coverage": Options.annotate = True Options.annotate_coverage_xml = pop_value() diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -341,7 +341,8 @@ def generate_c_code(self, env, options, result): modules = self.referenced_modules if Options.annotate or options.annotate: - rootwriter = Annotate.AnnotationCCodeWriter() + show_entire_c_code = Options.annotate == "fullc" or options.annotate == "fullc" + rootwriter = Annotate.AnnotationCCodeWriter(show_entire_c_code=show_entire_c_code) else: rootwriter = Code.CCodeWriter()
diff --git a/Cython/Build/Tests/TestCythonizeArgsParser.py b/Cython/Build/Tests/TestCythonizeArgsParser.py --- a/Cython/Build/Tests/TestCythonizeArgsParser.py +++ b/Cython/Build/Tests/TestCythonizeArgsParser.py @@ -1,6 +1,7 @@ from Cython.Build.Cythonize import create_args_parser, parse_args_raw, parse_args from unittest import TestCase +import argparse class TestCythonizeArgsParser(TestCase): @@ -233,13 +234,25 @@ def test_annotate_short(self): options, args = self.parse_args(['-a']) self.assertFalse(args) self.assertTrue(self.are_default(options, ['annotate'])) - self.assertEqual(options.annotate, True) + self.assertEqual(options.annotate, 'default') def test_annotate_long(self): options, args = self.parse_args(['--annotate']) self.assertFalse(args) self.assertTrue(self.are_default(options, ['annotate'])) - self.assertEqual(options.annotate, True) + self.assertEqual(options.annotate, 'default') + + def test_annotate_fullc(self): + options, args = self.parse_args(['--annotate=fullc']) + self.assertFalse(args) + self.assertTrue(self.are_default(options, ['annotate'])) + self.assertEqual(options.annotate, 'fullc') + + def test_annotate_fullc(self): + options, args = self.parse_args(['-a=default']) + self.assertFalse(args) + self.assertTrue(self.are_default(options, ['annotate'])) + self.assertEqual(options.annotate, 'default') def test_exclude_short(self): options, args = self.parse_args(['-x', '*.pyx']) @@ -360,7 +373,7 @@ def test_file_inbetween(self): options, args = self.parse_args(['-i', 'file.pyx', '-a']) self.assertEqual(args, ['file.pyx']) self.assertEqual(options.build_inplace, True) - self.assertEqual(options.annotate, True) + self.assertEqual(options.annotate, 'default') self.assertTrue(self.are_default(options, ['build_inplace', 'annotate'])) def test_option_trailing(self): diff --git a/Cython/Build/Tests/TestIpythonMagic.py b/Cython/Build/Tests/TestIpythonMagic.py --- a/Cython/Build/Tests/TestIpythonMagic.py +++ b/Cython/Build/Tests/TestIpythonMagic.py @@ -10,6 +10,7 @@ from contextlib import contextmanager from Cython.Build import IpythonMagic from Cython.TestUtils import CythonTest +from Cython.Compiler.Annotate import AnnotationCCodeWriter try: import IPython.testing.globalipapp @@ -210,3 +211,29 @@ def set_threshold(self, val): ip.ex('g = f(10)') self.assertEqual(ip.user_ns['g'], 20.0) self.assertEqual([normal_log.INFO], normal_log.thresholds) + + def test_cython_no_annotate(self): + ip = self._ip + html = ip.run_cell_magic('cython', '', code) + self.assertTrue(html is None) + + def test_cython_annotate(self): + ip = self._ip + html = ip.run_cell_magic('cython', '--annotate', code) + # somewhat brittle way to differentiate between annotated htmls + # with/without complete source code: + self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html.data) + + def test_cython_annotate_default(self): + ip = self._ip + html = ip.run_cell_magic('cython', '--a=default', code) + # somewhat brittle way to differentiate between annotated htmls + # with/without complete source code: + self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html.data) + + def test_cython_annotate_complete_c_code(self): + ip = self._ip + html = ip.run_cell_magic('cython', '--a=fullc', code) + # somewhat brittle way to differentiate between annotated htmls + # with/without complete source code: + self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE in html.data) diff --git a/Cython/Compiler/Tests/TestCmdLine.py b/Cython/Compiler/Tests/TestCmdLine.py --- a/Cython/Compiler/Tests/TestCmdLine.py +++ b/Cython/Compiler/Tests/TestCmdLine.py @@ -98,6 +98,33 @@ def test_options_with_values(self): self.assertTrue(options.gdb_debug) self.assertEqual(options.output_dir, '/gdb/outdir') + def test_no_annotate(self): + options, sources = parse_command_line([ + '--embed=huhu', 'source.pyx' + ]) + self.assertFalse(Options.annotate) + + def test_annotate_simple(self): + options, sources = parse_command_line([ + '-a', + 'source.pyx', + ]) + self.assertEqual(Options.annotate, 'default') + + def test_annotate_default(self): + options, sources = parse_command_line([ + '--annotate=default', + 'source.pyx', + ]) + self.assertEqual(Options.annotate, 'default') + + def test_annotate_fullc(self): + options, sources = parse_command_line([ + '--annotate=fullc', + 'source.pyx', + ]) + self.assertEqual(Options.annotate, 'fullc') + def test_errors(self): def error(*args): old_stderr = sys.stderr diff --git a/tests/build/cythonize_with_annotate.srctree b/tests/build/cythonize_with_annotate.srctree new file mode 100644 --- /dev/null +++ b/tests/build/cythonize_with_annotate.srctree @@ -0,0 +1,45 @@ +PYTHON setup.py build_ext --inplace +PYTHON -c "import not_annotated; not_annotated.check()" +PYTHON -c "import default_annotated; default_annotated.check()" +PYTHON -c "import fullc_annotated; fullc_annotated.check()" +######## setup.py ######## + +from Cython.Build.Dependencies import cythonize + +from distutils.core import setup + +setup( + ext_modules = cythonize(["not_annotated.pyx"], language_level=3) + + cythonize(["default_annotated.pyx"], annotate=True, language_level=3) + + cythonize(["fullc_annotated.pyx"], annotate='fullc', language_level=3) +) +######## not_annotated.pyx ######## +# check that html-file doesn't exist: +def check(): + import os.path as os_path + assert not os_path.isfile(__name__+'.html') + + + +######## default_annotated.pyx ######## +# load html-site and check that the marker isn't there: +def check(): + from codecs import open + with open(__name__+'.html', 'r', 'utf8') as html_file: + html = html_file.read() + + from Cython.Compiler.Annotate import AnnotationCCodeWriter + assert (AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html) # per default no complete c code + + + +######## fullc_annotated.pyx ######## +# load html-site and check that the marker is there: +def check(): + from codecs import open + with open(__name__+'.html', 'r', 'utf8') as html_file: + html = html_file.read() + + from Cython.Compiler.Annotate import AnnotationCCodeWriter + assert (AnnotationCCodeWriter.COMPLETE_CODE_TITLE in html) + diff --git a/tests/build/cythonize_with_annotate_via_Options.srctree b/tests/build/cythonize_with_annotate_via_Options.srctree new file mode 100644 --- /dev/null +++ b/tests/build/cythonize_with_annotate_via_Options.srctree @@ -0,0 +1,27 @@ +PYTHON setup.py build_ext --inplace +PYTHON -c "import fullc_annotated; fullc_annotated.check()" + +######## setup.py ######## + +from Cython.Build.Dependencies import cythonize +from Cython.Compiler import Options + +Options.annotate = 'fullc' + +from distutils.core import setup + +setup( + ext_modules = cythonize(["fullc_annotated.pyx"], language_level=3) +) + +######## fullc_annotated.pyx ######## +# load html-site and check that the marker is there: + +def check(): + from codecs import open + with open(__name__+'.html', 'r', 'utf8') as html_file: + html = html_file.read() + + from Cython.Compiler.Annotate import AnnotationCCodeWriter + assert (AnnotationCCodeWriter.COMPLETE_CODE_TITLE in html) + diff --git a/tests/run/annotate_html.pyx b/tests/run/annotate_html.pyx --- a/tests/run/annotate_html.pyx +++ b/tests/run/annotate_html.pyx @@ -11,6 +11,8 @@ >>> import re >>> assert re.search('<pre .*def.* .*mixed_test.*</pre>', html) +>>> from Cython.Compiler.Annotate import AnnotationCCodeWriter +>>> assert (AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html) # per default no complete c code """
Cosider adding an option to show the cythonized code in ipython-magic When prototyping with IPython there is one reason I often switch to compiling the cython extension on the command line: to see the whole cythonized code. While `--anotate` is great to spot issues it is not enough to see what is really going on. Please consider adding an option to show also the whole cythonized code.
Ok, but wouldn't this just flood your notebook with tons of hard to read C gibberish? If there is anything to improve in the `-a` output, I'd rather see that done.
2019-02-21T23:10:40Z
[]
[]
cython/cython
2,859
cython__cython-2859
[ "2854" ]
8a08c4f7f566b24686b7f5618ec3644ab8fba97f
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -2527,44 +2527,61 @@ class ImportNode(ExprNode): # relative to the current module. # None: decide the level according to language level and # directives + # get_top_level_module int true: return top-level module, false: return imported module + # module_names TupleNode the separate names of the module and submodules, or None type = py_object_type + module_names = None + get_top_level_module = False + is_temp = True - subexprs = ['module_name', 'name_list'] + subexprs = ['module_name', 'name_list', 'module_names'] def analyse_types(self, env): if self.level is None: - if (env.directives['py2_import'] or - Future.absolute_import not in env.global_scope().context.future_directives): + # For modules in packages, and without 'absolute_import' enabled, try relative (Py2) import first. + if env.global_scope().parent_module and ( + env.directives['py2_import'] or + Future.absolute_import not in env.global_scope().context.future_directives): self.level = -1 else: self.level = 0 module_name = self.module_name.analyse_types(env) self.module_name = module_name.coerce_to_pyobject(env) + assert self.module_name.is_string_literal if self.name_list: name_list = self.name_list.analyse_types(env) self.name_list = name_list.coerce_to_pyobject(env) - self.is_temp = 1 + elif '.' in self.module_name.value: + self.module_names = TupleNode(self.module_name.pos, args=[ + IdentifierStringNode(self.module_name.pos, value=part, constant_result=part) + for part in map(StringEncoding.EncodedString, self.module_name.value.split('.')) + ]).analyse_types(env) return self gil_message = "Python import" def generate_result_code(self, code): - if self.name_list: - name_list_code = self.name_list.py_result() + assert self.module_name.is_string_literal + module_name = self.module_name.value + + if self.level == 0 and not self.name_list and not self.get_top_level_module: + if self.module_names: + assert self.module_names.is_literal # make sure we create the tuple only once + code.globalstate.use_utility_code(UtilityCode.load_cached("ImportDottedModule", "ImportExport.c")) + import_code = "__Pyx_ImportDottedModule(%s, %s)" % ( + self.module_name.py_result(), + self.module_names.py_result() if self.module_names else 'NULL', + ) else: - name_list_code = "0" - - code.globalstate.use_utility_code(UtilityCode.load_cached("Import", "ImportExport.c")) - import_code = "__Pyx_Import(%s, %s, %d)" % ( - self.module_name.py_result(), - name_list_code, - self.level) + code.globalstate.use_utility_code(UtilityCode.load_cached("Import", "ImportExport.c")) + import_code = "__Pyx_Import(%s, %s, %d)" % ( + self.module_name.py_result(), + self.name_list.py_result() if self.name_list else '0', + self.level) - if (self.level <= 0 and - self.module_name.is_string_literal and - self.module_name.value in utility_code_for_imports): - helper_func, code_name, code_file = utility_code_for_imports[self.module_name.value] + if self.level <= 0 and module_name in utility_code_for_imports: + helper_func, code_name, code_file = utility_code_for_imports[module_name] code.globalstate.use_utility_code(UtilityCode.load_cached(code_name, code_file)) import_code = '%s(%s)' % (helper_func, import_code) diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -1675,11 +1675,6 @@ def p_import_statement(s): as_name=as_name, is_absolute=is_absolute) else: - if as_name and "." in dotted_name: - name_list = ExprNodes.ListNode(pos, args=[ - ExprNodes.IdentifierStringNode(pos, value=s.context.intern_ustring("*"))]) - else: - name_list = None stat = Nodes.SingleAssignmentNode( pos, lhs=ExprNodes.NameNode(pos, name=as_name or target_name), @@ -1687,7 +1682,8 @@ def p_import_statement(s): pos, module_name=ExprNodes.IdentifierStringNode(pos, value=dotted_name), level=0 if is_absolute else None, - name_list=name_list)) + get_top_level_module='.' in dotted_name and as_name is None, + name_list=None)) stats.append(stat) return Nodes.StatListNode(pos, stats=stats) diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -29,6 +29,7 @@ except (ImportError, AttributeError): IS_CPYTHON = True IS_PYPY = False +IS_PY2 = sys.version_info[0] < 3 from io import open as io_open try: @@ -1124,6 +1125,8 @@ def run_distutils(self, test_directory, module, workdir, incdir, extension = newext or extension if self.language == 'cpp': extension.language = 'c++' + if IS_PY2: + workdir = str(workdir) # work around type check in distutils that disallows unicode strings build_extension.extensions = [extension] build_extension.build_temp = workdir build_extension.build_lib = workdir @@ -1911,7 +1914,7 @@ def __init__(self, shard_num, shard_count): self.shard_num = shard_num self.shard_count = shard_count - def __call__(self, testname, tags=None, _hash=zlib.crc32, _is_py2=sys.version_info[0] < 3): + def __call__(self, testname, tags=None, _hash=zlib.crc32, _is_py2=IS_PY2): # Cannot use simple hash() here as shard processes might use different hash seeds. # CRC32 is fast and simple, but might return negative values in Py2. hashval = _hash(testname) & 0x7fffffff if _is_py2 else _hash(testname.encode()) @@ -2493,10 +2496,7 @@ def runtests(options, cmd_args, coverage=None): else: text_runner_options = {} if options.failfast: - if sys.version_info < (2, 7): - sys.stderr.write("--failfast not supported with Python < 2.7\n") - else: - text_runner_options['failfast'] = True + text_runner_options['failfast'] = True test_runner = unittest.TextTestRunner(verbosity=options.verbosity, **text_runner_options) if options.pyximport_py:
diff --git a/tests/run/importas.pyx b/tests/run/importas.pyx --- a/tests/run/importas.pyx +++ b/tests/run/importas.pyx @@ -1,4 +1,14 @@ +# mode: run +# tag: all_language_levels + __doc__ = u""" +>>> try: sys +... except NameError: pass +... else: print("sys was defined!") +>>> try: distutils +... except NameError: pass +... else: print("distutils was defined!") + >>> import sys as sous >>> import distutils.core as corey >>> from copy import deepcopy as copey diff --git a/tests/run/reimport_from_package.srctree b/tests/run/reimport_from_package.srctree --- a/tests/run/reimport_from_package.srctree +++ b/tests/run/reimport_from_package.srctree @@ -17,8 +17,8 @@ setup( import sys import a -assert a in sys.modules.values(), list(sys.modules) -assert sys.modules['a'] is a, list(sys.modules) +assert a in sys.modules.values(), sorted(sys.modules) +assert sys.modules['a'] is a, sorted(sys.modules) from atest.package import module @@ -33,8 +33,8 @@ assert 'atest.package.module' in sys.modules import a import atest.package.module as module -assert module in sys.modules.values(), list(sys.modules) -assert sys.modules['atest.package.module'] is module, list(sys.modules) +assert module in sys.modules.values(), sorted(sys.modules) +assert sys.modules['atest.package.module'] is module, sorted(sys.modules) if sys.version_info >= (3, 5): from . import pymodule diff --git a/tests/run/relativeimport_T542.srctree b/tests/run/relativeimport_T542.srctree --- a/tests/run/relativeimport_T542.srctree +++ b/tests/run/relativeimport_T542.srctree @@ -26,7 +26,8 @@ try: except ImportError: pass else: - assert False, "absolute import succeeded" + import sys + assert False, "absolute import succeeded: %s" % sorted(sys.modules) import relimport.a import relimport.bmod
Imports are slower than with CPython If I compile the following functions using Cython: ```python def _noop_bench(): pass def _import_bench(): import pyarrow.pandas_compat as pdcompat ``` And then measure their performance: ```python >>> %timeit lib._noop_bench() 66.3 ns ± 0.379 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) >>> %timeit lib._import_bench() 987 ns ± 21.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit lib._import_bench() 966 ns ± 17.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) ``` The import overhead (~ 900 ns. per import statement) appears much slower than what CPython achieves: ```python >>> %timeit import pyarrow.pandas_compat as pdcompat 253 ns ± 4.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) >>> %timeit import pyarrow.pandas_compat as pdcompat 254 ns ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) ``` This is with Python 3, Cython 0.29.4 and `language_level = 3`.
Hmm, interesting. My first thought was Py2-style imports, but you're using `language_level=3`, so that's not it. Importing has never really been a priority for optimisation, more of a "just make it work across all Python versions" kind of task. But I can't see a reason why Cython should be slower than CPython here, let alone 4x as slow. Definitely worth investigating. I investigated this. CPython imports the module by dotted name and then looks up attributes on the result until it found the final imported sub-sub-sub-…module. Cython (and probably Pyrex already) took the easy path of passing a non-empty name list into the import function (actually the list `['*']`), which then takes that as a signal to return the imported submodule instead of the top-level module. That is much slower. I'll see what I can do about it.
2019-02-22T17:21:58Z
[]
[]
cython/cython
2,871
cython__cython-2871
[ "1461" ]
060e9090e4617a82ebbf7603f58747aa3519931c
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -2653,6 +2653,9 @@ def generate_argument_type_tests(self, code): self.generate_arg_none_check(arg, code) def generate_execution_code(self, code): + if code.globalstate.directives['linetrace']: + code.mark_pos(self.pos) + code.putln("") # generate line tracing code super(CFuncDefNode, self).generate_execution_code(code) if self.py_func_stat: self.py_func_stat.generate_execution_code(code)
diff --git a/tests/run/coverage_nogil.srctree b/tests/run/coverage_nogil.srctree --- a/tests/run/coverage_nogil.srctree +++ b/tests/run/coverage_nogil.srctree @@ -25,19 +25,19 @@ plugins = Cython.Coverage # cython: linetrace=True # distutils: define_macros=CYTHON_TRACE=1 CYTHON_TRACE_NOGIL=1 -cdef int func1(int a, int b) nogil: - cdef int x # 5 - with gil: # 6 - x = 1 # 7 - cdef int c = func2(a) + b # 8 - return x + c # 9 +cdef int func1(int a, int b) nogil: # 4 + cdef int x # 5 + with gil: # 6 + x = 1 # 7 + cdef int c = func2(a) + b # 8 + return x + c # 9 -cdef int func2(int a) with gil: +cdef int func2(int a) with gil: # 12 return a * 2 # 13 -def call(int a, int b): +def call(int a, int b): # 16 a, b = b, a # 17 with nogil: # 18 result = func1(b, a) # 19 @@ -56,20 +56,18 @@ except ImportError: from coverage import coverage -import coverage_test_nogil - -assert not any(coverage_test_nogil.__file__.endswith(ext) - for ext in '.py .pyc .pyo .pyw .pyx .pxi'.split()), \ - coverage_test_nogil.__file__ - +def run_coverage(): + cov = coverage() + cov.start() -def run_coverage(module): + import coverage_test_nogil as module module_name = module.__name__ module_path = module_name + '.pyx' - - cov = coverage() - cov.start() + assert not any(module.__file__.endswith(ext) + for ext in '.py .pyc .pyo .pyw .pyx .pxi'.split()), \ + module.__file__ assert module.call(1, 2) == (1 * 2) + 2 + 1 + cov.stop() out = StringIO() @@ -84,10 +82,10 @@ def run_coverage(module): executed = set(exec_lines) - set(missing_lines) # check that everything that runs with the gil owned was executed - assert all(line in executed for line in [13, 17, 18, 20]), '%s / %s' % (exec_lines, missing_lines) + assert all(line in executed for line in [12, 13, 16, 17, 18, 20]), '%s / %s' % (exec_lines, missing_lines) # check that everything that runs in nogil sections was executed - assert all(line in executed for line in [6, 7, 8, 9]), '%s / %s' % (exec_lines, missing_lines) + assert all(line in executed for line in [4, 6, 7, 8, 9]), '%s / %s' % (exec_lines, missing_lines) if __name__ == '__main__': - run_coverage(coverage_test_nogil) + run_coverage()
Cython coverage tool blames that function definition lines are not covered I'm trying to enable a coverage for cython modules for [multidict](https://github.com/aio-libs/multidict) library. `Cython.Coverage` plugin works but the [coverage output](https://codecov.io/gh/aio-libs/multidict/src/cf1458ba151cffd74972cf00471ed09b9d6ee0dc/multidict/_multidict.pyx) looks incorrect. The tool blames that method definitions are not executed lines but it's definitely wrong because method bodies are executed and test covered. What I do wrong?
Did you try latest master? I've tried cython 0.24.1 On master I have another error: ``` INTERNALERROR> wrap_controller.send(call_outcome) INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/pytest_cov/plugin.py", line 212, in pytest_runtestloop INTERNALERROR> self.cov_controller.finish() INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/pytest_cov/engine.py", line 150, in finish INTERNALERROR> self.cov.combine() INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/coverage/control.py", line 784, in combine INTERNALERROR> self.get_data() INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/coverage/control.py", line 810, in get_data INTERNALERROR> self.collector.save_data(self.data) INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/coverage/collector.py", line 349, in save_data INTERNALERROR> covdata.add_arcs(abs_file_dict(self.data)) INTERNALERROR> File "/home/andrew/.virtualenvs/multidict/lib/python3.5/site-packages/coverage/data.py", line 365, in add_arcs INTERNALERROR> raise CoverageException("Can't add arcs to existing line data") INTERNALERROR> coverage.misc.CoverageException: Can't add arcs to existing line data ``` Aha, `coverage combine` doesn't work somehow. Anyway, even without combining I have the same behavior (method definitions are not covered) on cython master too. Steps to reproduce: 1. Clone https://github.com/aio-libs/multidict 2. Switch to `cython_coverage` branch 3. Run `pip install -r requirements-ci.txt` 4. Run `make cov-dev`, open prompted html file. Method definition lines from `multidict/_multidict.pyx` are not covered. 5. For demonstrating issue with coverage files combining run `make cov-dev-full`. Without having looked at the code, my guess is that we simply don't generate trace calls for function/method/class declarations. The whole tracing support works by explicitly calling the tracer before the C code that is generated for each line of user code that gets executed, and declarations aren't really considered user code. The trace call would need to get added to the instantiation of class objects and functions. AFAIR, we already trace the user code in the module init function, so this should generally be possible, although some C things might happen in an unexpected order in Cython. Facing the same issue... Method definitions (def/cpdef/cdef) in cdef classes are not covered, when they should be. Also found person facing the same issue on SO - http://stackoverflow.com/questions/34935796/how-to-use-coverage-analysis-with-cython Same issue here. The methods' body shows up as green, but the signature is always red. Please let me know if I can help further debug this issue. Thanks As written above, we don't generate tracing calls for the function signature line. Or, rather, if we do, then they are only executed at import time, not at call time. Probably easy to implement, but needs a test that makes sure it really behaves exactly like CPython. I also spent few hours on figuring this out. In the end, I found [a _cython-users_ Google Groups message](https://groups.google.com/d/msg/cython-users/e80vdI9G_3w/NTQTF009BAAJ) which recommends **enabling `binding` directive**. This seems to completely remove the function signature statements from the coverage and I can reach 100% coverage again. Could anyone comment on this workaround? Is it safe to use? (I should also add I only compile with `binding` directive for test and coverage, not the production) The `binding` directive is generally a good idea, mainly because it improves the Python compatibility of Cython compiled functions. However, I would not recommend using it only for testing, since disabling it for production changes the behaviour there. @scoder I don't fully grok coverage.py or Cython.Coverage, am trying to get a handle on them to make a PR. Would patching `Plugin._parse_lines` to consider these lines not-executable be a viable solution to this problem? Or would it be liable to cause more problems? <b>Update</b> On trying this out I'm seeing weird results. It looks like we need to patch the coverage results to think these lines _were_ executed, as opposed to thinking they were not executable. > Would patching Plugin._parse_lines to consider these lines not-executable be a viable solution to this problem? Or would it be liable to cause more problems? I don't know anything about the coverage.py or Cython.Coverage code, but in principle this sounds like the correct solution if the details are worked out. The following report is an example of how I am seeing this problem manifest: https://codecov.io/gh/lenskit/lkpy/src/7d705b4b9a051bca66f6cdc1873d3ab4cecdb52b/lenskit/algorithms/_funksvd.pyx `cdef` local variables with initializers are marked as hit. A `cdef` field declaration of a memory view is also being marked as hit. > consider these lines not-executable No, that sound wrong. They are executable, CPython counts them, too. Could someone find out if CPython counts them only at import time or also at call time? If the latter, then the fix is to also generate a line trace event for the function call. setting binding=True as @kysely suggested above didn't change anything for me > Could someone find out if CPython counts them only at import time or also at call time? How do we find out? btw, i'm also seeing switch statements being flagged in red as not covered, but the body of the switch branches is green https://codecov.io/gh/fonttools/openstep-plist/src/master/src/openstep_plist/_parser.pyx#L119...177 > switch statements Yes, that's a known bug. Cython generates the initial `TraceLine` call in a place where it is not executed. PR welcome, as always. > How do we find out? Run an import with coverage reporting, look at the result. Exclude the import from coverage reporting, run a function, look at the result. But, actually, I'd suggest looking at the CPython sources and finding out if a "call" trace event also triggers a "line" trace event. That would be the definite indicator. I just did that. I created two python modules `a.py` and `b.py`. The former contains `import b`, and the latter defines a function `def f(): print('hello world')`. When I run `coverage run a.py`, I can see that the signature of function `f` in the module `b.py` is green, whereas the body is red (as it was ony imported, not called). If I add a `# pragma: no cover` next to `import b` inside `a.py` module, and then I add a new line where I call the function from b, `b.f()`, after I re-run `coverage run a.py` I can see the `import b` line is now grey (excluded), and in the module `b.py` I can see that both the function signature and its body are now green. > I'd suggest looking at the CPython sources and finding out if a "call" trace event also triggers a "line" trace event. That would be the definite indicator. right. That sounds more difficult, I'm not sure where to look..
2019-03-01T17:09:36Z
[]
[]
cython/cython
2,910
cython__cython-2910
[ "2905" ]
7b41a3a312c066fcf111830beab758725991c606
diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -40,6 +40,8 @@ verbose = 0 +standard_include_path = os.path.abspath(os.path.join(os.path.dirname(__file__), + os.path.pardir, 'Includes')) class Context(object): # This class encapsulates the context needed for compiling @@ -75,10 +77,6 @@ def __init__(self, include_directories, compiler_directives, cpp=False, self.pxds = {} # full name -> node tree self._interned = {} # (type(value), value, *key_args) -> interned_value - standard_include_path = os.path.abspath(os.path.normpath( - os.path.join(os.path.dirname(__file__), os.path.pardir, 'Includes'))) - self.include_directories = include_directories + [standard_include_path] - if language_level is not None: self.set_language_level(language_level) @@ -253,8 +251,13 @@ def find_include_file(self, filename, pos): def search_include_directories(self, qualified_name, suffix, pos, include=False, sys_path=False): - return search_include_directories( - tuple(self.include_directories), qualified_name, suffix, pos, include, sys_path) + include_dirs = self.include_directories + if sys_path: + include_dirs = include_dirs + sys.path + # include_dirs must be hashable for caching in @cached_function + include_dirs = tuple(include_dirs + [standard_include_path]) + return search_include_directories(include_dirs, qualified_name, + suffix, pos, include) def find_root_package_dir(self, file_path): return Utils.find_root_package_dir(file_path) @@ -602,8 +605,7 @@ def compile(source, options = None, full_module_name = None, **kwds): @Utils.cached_function -def search_include_directories(dirs, qualified_name, suffix, pos, - include=False, sys_path=False): +def search_include_directories(dirs, qualified_name, suffix, pos, include=False): """ Search the list of include directories for the given file name. @@ -612,10 +614,7 @@ def search_include_directories(dirs, qualified_name, suffix, pos, report an error. The 'include' option will disable package dereferencing. - If 'sys_path' is True, also search sys.path. """ - if sys_path: - dirs = dirs + tuple(sys.path) if pos: file_desc = pos[0] @@ -648,7 +647,7 @@ def search_include_directories(dirs, qualified_name, suffix, pos, path = os.path.join(package_dir, module_filename) if os.path.exists(path): return path - path = os.path.join(dirname, package_dir, module_name, + path = os.path.join(package_dir, module_name, package_filename) if os.path.exists(path): return path
diff --git a/tests/compile/find_pxd.srctree b/tests/compile/find_pxd.srctree --- a/tests/compile/find_pxd.srctree +++ b/tests/compile/find_pxd.srctree @@ -6,12 +6,13 @@ from Cython.Build import cythonize from Cython.Distutils.extension import Extension import sys -sys.path.append("path") +sys.path.insert(0, "path") ext_modules = [ Extension("a", ["a.pyx"]), Extension("b", ["b.pyx"]), Extension("c", ["c.pyx"]), + Extension("d", ["d.pyx"]), ] ext_modules = cythonize(ext_modules, include_path=["include"]) @@ -37,3 +38,15 @@ ctypedef int my_type ######## path/c.pxd ######## +++syntax error just to show that this file is not actually cimported+++ + +######## path/numpy/__init__.pxd ######## + +# gh-2905: This should be found before Cython/Inlude/numpy/__init__.pxd + +ctypedef int my_type + +######## d.pyx ######## + +cimport numpy + +cdef numpy.my_type foo
BUG: cannot easily override a cython Include I am trying to vendor `numpy.pxd` (or `numpy/__init__.pxd`) into numpy. It seems the file in `Includes/numpy/__init__.pxd` is seen before mine when I try `cimport numpy`. To reproduce: copy the `__init__.pxd` from `Includes/numpy` into `site-packages/numpy`, and add garbage in the original file so using it will crash cython (I used `xxxx = xxxxxxxxx`). Then build a project that calls `cimport numpy` such as pandas. If the copy is found, `cythonize` will succeed. If the original version is found, cythonize will crash. I am willing to work on a PR, but need some direction as to where to look for the problem.
I think the problem is that `Includes` is appended to the search path [here](https://github.com/cython/cython/blob/0.29.6/Cython/Compiler/Main.py#L93), then later on `sys.path` is optionally appended to the search path [here](https://github.com/cython/cython/blob/0.29.6/Cython/Utils.py#L136). IMO if `sys_path` is True the precedence should be - user provided `include_directories` - `sys.path` - `Includes` instead of the current situation which gives precedence to `Includes` I agree about the import path order. `sys.path` and `Includes/` should be reversed. PR welcome.
2019-03-31T19:14:59Z
[]
[]
cython/cython
2,935
cython__cython-2935
[ "2934" ]
d5da2dbc8eb7b4715a1fef6d38a115801a17613a
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -734,8 +734,8 @@ def analyse(self, return_type, env, nonempty=0, directive_locals=None, visibilit self.exception_value = ConstNode( self.pos, value=return_type.exception_value, type=return_type) if self.exception_value: - self.exception_value = self.exception_value.analyse_const_expression(env) if self.exception_check == '+': + self.exception_value = self.exception_value.analyse_const_expression(env) exc_val_type = self.exception_value.type if (not exc_val_type.is_error and not exc_val_type.is_pyobject @@ -748,13 +748,11 @@ def analyse(self, return_type, env, nonempty=0, directive_locals=None, visibilit "Exception value must be a Python exception or cdef function with no arguments or *.") exc_val = self.exception_value else: - self.exception_value = self.exception_value.coerce_to( + self.exception_value = self.exception_value.analyse_types(env).coerce_to( return_type, env).analyse_const_expression(env) exc_val = self.exception_value.get_constant_c_result_code() if exc_val is None: - raise InternalError( - "get_constant_c_result_code not implemented for %s" % - self.exception_value.__class__.__name__) + error(self.exception_value.pos, "Exception value must be constant") if not return_type.assignable_from(self.exception_value.type): error(self.exception_value.pos, "Exception value incompatible with function return type")
diff --git a/tests/errors/nonconst_excval.pyx b/tests/errors/nonconst_excval.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/nonconst_excval.pyx @@ -0,0 +1,12 @@ +# mode: error + +import math + +cdef double cfunc(double x) except math.nan: + return x + + +_ERRORS = """ +5:39: Exception value must be constant +5:39: Not allowed in a constant expression +"""
Compiler crash in AnalyseDeclarationsTransform This is with Cython 0.29.7 and Python 3.6.7. There are several other issues that report "Compiler crash in AnalyseDeclarationsTransform", but I couldn't tell if this issue is a duplicate of one of those. Cython code "example.pyx": ``` import math def func(double x): return cfunc(x) cdef double cfunc(double x) except math.nan: return x ``` Result: ``` running build running build_ext cythoning example.pyx to example.c /Users/warren/miniconda36b/lib/python3.6/site-packages/Cython/Compiler/Main.py:367: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /Users/warren/code_snippets/python/cython/exception-in-cdef-function/example.pyx tree = Parsing.p_module(s, pxd, full_module_name) Error compiling Cython file: ------------------------------------------------------------ ... import math def func(double x): return cfunc(x) cdef double cfunc(double x) except math.nan: ^ ------------------------------------------------------------ example.pyx:8:39: Not allowed in a constant expression Error compiling Cython file: ------------------------------------------------------------ ... import math def func(double x): return cfunc(x) cdef double cfunc(double x) except math.nan: ^ ------------------------------------------------------------ example.pyx:8:39: Not allowed in a constant expression Error compiling Cython file: ------------------------------------------------------------ ... import math def func(double x): return cfunc(x) cdef double cfunc(double x) except math.nan: ^ ------------------------------------------------------------ example.pyx:8:17: Compiler crash in AnalyseDeclarationsTransform File 'ModuleNode.py', line 124, in analyse_declarations: ModuleNode(example.pyx:1:0, full_module_name = 'example') File 'Nodes.py', line 431, in analyse_declarations: StatListNode(example.pyx:3:0) File 'Nodes.py', line 431, in analyse_declarations: StatListNode(example.pyx:8:5) File 'Nodes.py', line 2358, in analyse_declarations: CFuncDefNode(example.pyx:8:5, modifiers = [...]/0, visibility = 'private') File 'Nodes.py', line 757, in analyse: CFuncDeclaratorNode(example.pyx:8:17, calling_convention = '') Compiler crash traceback from this point on: File "/Users/warren/miniconda36b/lib/python3.6/site-packages/Cython/Compiler/Nodes.py", line 757, in analyse self.exception_value.__class__.__name__) InternalError: Internal compiler error: get_constant_c_result_code not implemented for CoerceFromPyTypeNode building 'example' extension gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/warren/miniconda36b/include -arch x86_64 -I/Users/warren/miniconda36b/include -arch x86_64 -I/Users/warren/miniconda36b/include/python3.6m -c example.c -o build/temp.macosx-10.7-x86_64-3.6/example.o example.c:1:2: error: Do not use this file, it is the result of a failed Cython compilation. #error Do not use this file, it is the result of a failed Cython compilation. ^ 1 error generated. error: command 'gcc' failed with exit status 1 ```
2019-04-28T07:12:42Z
[]
[]
cython/cython
2,990
cython__cython-2990
[ "2967" ]
e5f8db6c5b22602fe626f8c9e78a08f718c28a69
diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -2738,9 +2738,12 @@ def create_class_from_scope(self, node, target_module_scope, inner_node=None): node.needs_outer_scope = True return + # entry.cname can contain periods (eg. a derived C method of a class). + # We want to use the cname as part of a C struct name, so we replace + # periods with double underscores. as_name = '%s_%s' % ( target_module_scope.next_id(Naming.closure_class_prefix), - node.entry.cname) + node.entry.cname.replace('.','__')) entry = target_module_scope.declare_c_class( name=as_name, pos=node.pos, defining=True,
diff --git a/tests/run/closure_in_derived_class_T2967.pyx b/tests/run/closure_in_derived_class_T2967.pyx new file mode 100644 --- /dev/null +++ b/tests/run/closure_in_derived_class_T2967.pyx @@ -0,0 +1,18 @@ +# mode: run +# tag: closures +# ticket: 2967 + +cdef class BaseClass: + cdef func(self): + pass +cdef class ClosureInsideExtensionClass(BaseClass): + """ + >>> y = ClosureInsideExtensionClass(42) + >>> y.test(42) + 43 + """ + cdef func(self): + a = 1 + return (lambda x : x+a) + def test(self, b): + return self.func()(b)
Generates invalid C when omitting self in lambda I'm using Cython version 0.29.7. Part of the error message (full message attached: [output.txt](https://github.com/cython/cython/files/3207113/output.txt)): ``` AA/bug.c:830:57: error: expected identifier or ‘(’ before ‘.’ token struct __pyx_obj_2AA_3bug___pyx_scope_struct____pyx_base.func; ``` Here's a quick example to reproduce, including a workaround. ``` # cython: language_level=3 cdef class FBase(): def __init__(self): pass def __cinit__(self): pass cdef func(self, whatever): pass cdef class Bug(FBase): def __init__(self): pass cdef check(self, x): return x cdef func(self, whatever): a = [1, 2, 3] min(a, key=lambda x: self.check(x)) # This generates correct C, but doesn't work in Python: # min(a, key=lambda self, x: self.check(x)) # Workaround: # import functools # min(a, key=functools.partial(lambda self, x: self.check(x), self)) ```
2019-06-08T22:22:27Z
[]
[]
cython/cython
2,999
cython__cython-2999
[ "2996" ]
8ac1a6a55fc44ff858cc367af556250a91f71d16
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -6039,10 +6039,8 @@ def generate_evaluation_code(self, code): self_arg = code.funcstate.allocate_temp(py_object_type, manage_ref=True) code.putln("%s = NULL;" % self_arg) - arg_offset_cname = None - if len(args) > 1: - arg_offset_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False) - code.putln("%s = 0;" % arg_offset_cname) + arg_offset_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False) + code.putln("%s = 0;" % arg_offset_cname) def attribute_is_likely_method(attr): obj = attr.obj @@ -6075,115 +6073,33 @@ def attribute_is_likely_method(attr): code.put_incref("function", py_object_type) # free method object as early to possible to enable reuse from CPython's freelist code.put_decref_set(function, "function") - if len(args) > 1: - code.putln("%s = 1;" % arg_offset_cname) + code.putln("%s = 1;" % arg_offset_cname) code.putln("}") code.putln("}") - if not args: - # fastest special case: try to avoid tuple creation - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObjectCallNoArg", "ObjectHandling.c")) - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObjectCallOneArg", "ObjectHandling.c")) - code.putln( - "%s = (%s) ? __Pyx_PyObject_CallOneArg(%s, %s) : __Pyx_PyObject_CallNoArg(%s);" % ( - self.result(), self_arg, - function, self_arg, - function)) - code.put_xdecref_clear(self_arg, py_object_type) - code.funcstate.release_temp(self_arg) - code.putln(code.error_goto_if_null(self.result(), self.pos)) - code.put_gotref(self.py_result()) - elif len(args) == 1: - # fastest special case: try to avoid tuple creation - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObjectCall2Args", "ObjectHandling.c")) - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObjectCallOneArg", "ObjectHandling.c")) - arg = args[0] - code.putln( - "%s = (%s) ? __Pyx_PyObject_Call2Args(%s, %s, %s) : __Pyx_PyObject_CallOneArg(%s, %s);" % ( - self.result(), self_arg, - function, self_arg, arg.py_result(), - function, arg.py_result())) - code.put_xdecref_clear(self_arg, py_object_type) - code.funcstate.release_temp(self_arg) - arg.generate_disposal_code(code) - arg.free_temps(code) - code.putln(code.error_goto_if_null(self.result(), self.pos)) - code.put_gotref(self.py_result()) - else: - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyFunctionFastCall", "ObjectHandling.c")) - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyCFunctionFastCall", "ObjectHandling.c")) - for test_func, call_prefix in [('PyFunction_Check', 'Py'), ('__Pyx_PyFastCFunction_Check', 'PyC')]: - code.putln("#if CYTHON_FAST_%sCALL" % call_prefix.upper()) - code.putln("if (%s(%s)) {" % (test_func, function)) - code.putln("PyObject *%s[%d] = {%s, %s};" % ( - Naming.quick_temp_cname, - len(args)+1, - self_arg, - ', '.join(arg.py_result() for arg in args))) - code.putln("%s = __Pyx_%sFunction_FastCall(%s, %s+1-%s, %d+%s); %s" % ( - self.result(), - call_prefix, - function, - Naming.quick_temp_cname, - arg_offset_cname, - len(args), - arg_offset_cname, - code.error_goto_if_null(self.result(), self.pos))) - code.put_xdecref_clear(self_arg, py_object_type) - code.put_gotref(self.py_result()) - for arg in args: - arg.generate_disposal_code(code) - code.putln("} else") - code.putln("#endif") + # actually call the function + code.globalstate.use_utility_code( + UtilityCode.load_cached("PyObjectFastCall", "ObjectHandling.c")) - code.putln("{") - args_tuple = code.funcstate.allocate_temp(py_object_type, manage_ref=True) - code.putln("%s = PyTuple_New(%d+%s); %s" % ( - args_tuple, len(args), arg_offset_cname, - code.error_goto_if_null(args_tuple, self.pos))) - code.put_gotref(args_tuple) - - if len(args) > 1: - code.putln("if (%s) {" % self_arg) - code.putln("__Pyx_GIVEREF(%s); PyTuple_SET_ITEM(%s, 0, %s); %s = NULL;" % ( - self_arg, args_tuple, self_arg, self_arg)) # stealing owned ref in this case - code.funcstate.release_temp(self_arg) - if len(args) > 1: - code.putln("}") - - for i, arg in enumerate(args): - arg.make_owned_reference(code) - code.put_giveref(arg.py_result()) - code.putln("PyTuple_SET_ITEM(%s, %d+%s, %s);" % ( - args_tuple, i, arg_offset_cname, arg.py_result())) - if len(args) > 1: - code.funcstate.release_temp(arg_offset_cname) - - for arg in args: - arg.generate_post_assignment_code(code) - arg.free_temps(code) - - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObjectCall", "ObjectHandling.c")) - code.putln( - "%s = __Pyx_PyObject_Call(%s, %s, NULL); %s" % ( - self.result(), - function, args_tuple, - code.error_goto_if_null(self.result(), self.pos))) - code.put_gotref(self.py_result()) - - code.put_decref_clear(args_tuple, py_object_type) - code.funcstate.release_temp(args_tuple) + code.putln("{") + code.putln("PyObject *__pyx_callargs[%d] = {%s, %s};" % ( + len(args)+1, + self_arg, + ', '.join(arg.py_result() for arg in args))) + code.putln("%s = __Pyx_PyObject_FastCall(%s, __pyx_callargs+1-%s, %d+%s);" % ( + self.result(), + function, + arg_offset_cname, + len(args), + arg_offset_cname)) - if len(args) == 1: - code.putln("}") - code.putln("}") # !CYTHON_FAST_PYCALL + code.put_xdecref_clear(self_arg, py_object_type) + code.funcstate.release_temp(self_arg) + for arg in args: + arg.generate_disposal_code(code) + arg.free_temps(code) + code.putln(code.error_goto_if_null(self.result(), self.pos)) + code.put_gotref(self.py_result()) if reuse_function_temp: self.function.generate_disposal_code(code) @@ -6191,6 +6107,7 @@ def attribute_is_likely_method(attr): else: code.put_decref_clear(function, py_object_type) code.funcstate.release_temp(function) + code.putln("}") class InlinedDefNodeCallNode(CallNode):
diff --git a/tests/run/iterdict.pyx b/tests/run/iterdict.pyx --- a/tests/run/iterdict.pyx +++ b/tests/run/iterdict.pyx @@ -555,3 +555,19 @@ def for_in_iteritems_of_expression(*args, **kwargs): for k, v in dict(*args, **kwargs).iteritems(): result.append((k, v)) return result + + +cdef class NotADict: + """ + >>> NotADict().listvalues() # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError: descriptor 'values' for 'mappingproxy' objects doesn't apply to a 'iterdict.NotADict' object + """ + cdef long v + def __cinit__(self): + self.v = 1 + itervalues = type(object.__dict__).values + + def listvalues(self): + return [v for v in self.itervalues()]
_PyMethodDef_RawFastCallKeywords is used unsafely The optimization #2850 is unsafe since it skips the type check of the `method_descriptor` object. Minimal crashing example: ``` cdef class X: cdef long v def __cinit__(self): self.v = 1 itervalues = type(object.__dict__).values def test(): return [v for v in X().itervalues()] ``` Suggestion: instead of using `_PyMethodDef_RawFastCallKeywords`, use the more generic `_PyObject_FastCall` or `_PyObject_Vectorcall`. I'll make a PR for this.
I think it's better to revert #2850 (commit 459a5195) and instead optimize `__Pyx_PyObject_CallOneArg`
2019-06-13T15:10:18Z
[]
[]
cython/cython
3,101
cython__cython-3101
[ "2263" ]
bc1a0d42351ca2c6d052d0ec1e484ce4c43ce9bd
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -3111,11 +3111,9 @@ def analyse_signature(self, env): # METH_VARARGS to METH_FASTCALL # 2. Special methods like __call__ always use the METH_VARGARGS # calling convention - # 3. For the moment, CyFunctions do not support METH_FASTCALL mf = sig.method_flags() - if (mf and TypeSlots.method_varargs in mf and - not self.entry.is_special and not self.is_cyfunction): - # 4. If the function uses the full args tuple, it's more + if mf and TypeSlots.method_varargs in mf and not self.entry.is_special: + # 3. If the function uses the full args tuple, it's more # efficient to use METH_VARARGS. This happens when the function # takes *args but no other positional arguments (apart from # possibly self). We don't do the analogous check for keyword diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -1939,9 +1939,6 @@ def _synthesize_assignment(self, node, env): rhs.binding = True node.is_cyfunction = rhs.binding - if rhs.binding: - # For the moment, CyFunctions do not support METH_FASTCALL - node.entry.signature.use_fastcall = False return self._create_assignment(node, rhs, env) def _create_assignment(self, def_node, rhs, env):
diff --git a/tests/run/fastcall.pyx b/tests/run/fastcall.pyx --- a/tests/run/fastcall.pyx +++ b/tests/run/fastcall.pyx @@ -68,17 +68,14 @@ cdef class SelfCast: cdef extern from *: - int PyCFunction_Check(op) int PyCFunction_GET_FLAGS(op) def has_fastcall(meth): """ - Given a builtin_function_or_method ``meth``, return whether it uses - ``METH_FASTCALL``. + Given a builtin_function_or_method or cyfunction ``meth``, + return whether it uses ``METH_FASTCALL``. """ - if not PyCFunction_Check(meth): - raise TypeError("not a builtin_function_or_method") # Hardcode METH_FASTCALL constant equal to 0x80 for simplicity return bool(PyCFunction_GET_FLAGS(meth) & 0x80) @@ -100,6 +97,13 @@ def fastcall_function(**kw): """ return kw [email protected](True) +def fastcall_cyfunction(**kw): + """ + >>> assert_fastcall(fastcall_cyfunction) + """ + return kw + cdef class Dummy: @cython.binding(False) def fastcall_method(self, x, *args, **kw): @@ -107,3 +111,18 @@ cdef class Dummy: >>> assert_fastcall(Dummy().fastcall_method) """ return tuple(args) + tuple(kw) + +cdef class CyDummy: + @cython.binding(True) + def fastcall_method(self, x, *args, **kw): + """ + >>> assert_fastcall(CyDummy.fastcall_method) + """ + return tuple(args) + tuple(kw) + +class PyDummy: + def fastcall_method(self, x, *args, **kw): + """ + >>> assert_fastcall(PyDummy.fastcall_method) + """ + return tuple(args) + tuple(kw)
Change call signature of CyFunction to FASTCALL signature The new FASTCALL calling convention in CPython 3.6 and later avoids creating argument tuples and passes them as `PyObject*` C array instead. Keyword arguments can also be passed as a key-value C array. It is described here: https://mail.python.org/pipermail/python-dev/2016-August/145793.html For Python function signatures that do not require tuple/dict arguments (i.e. that do not use `*args` or `**kwargs`), Cython should - switch the call signature of its `CyFunction` function type to the FASTCALL signature - provide a converter that unpacks the argument tuple (and keywords) from the normal `tp_call` slot (can be done in the def-wrapper function) - use FASTCALL internally when calling a `CyFunction`, thus avoiding the argument packing - export the FASTCALL signature directly in CPython 3.8+ (where [PEP 575](https://www.python.org/dev/peps/pep-0575/) will hopefully get accepted)
2019-08-27T10:16:42Z
[]
[]
cython/cython
3,112
cython__cython-3112
[ "3111" ]
70dd7561d431f248e20c2a1365111418ea494cbd
diff --git a/Cython/Compiler/FusedNode.py b/Cython/Compiler/FusedNode.py --- a/Cython/Compiler/FusedNode.py +++ b/Cython/Compiler/FusedNode.py @@ -507,20 +507,22 @@ def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_ty ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable() """) + seen_typedefs = set() seen_int_dtypes = set() for buffer_type in all_buffer_types: dtype = buffer_type.dtype + dtype_name = self._dtype_name(dtype) if dtype.is_typedef: - #decl_code.putln("ctypedef %s %s" % (dtype.resolve(), - # self._dtype_name(dtype))) - decl_code.putln('ctypedef %s %s "%s"' % (dtype.resolve(), - self._dtype_name(dtype), - dtype.empty_declaration_code())) + if dtype_name not in seen_typedefs: + seen_typedefs.add(dtype_name) + decl_code.putln( + 'ctypedef %s %s "%s"' % (dtype.resolve(), dtype_name, + dtype.empty_declaration_code())) if buffer_type.dtype.is_int: if str(dtype) not in seen_int_dtypes: seen_int_dtypes.add(str(dtype)) - pyx_code.context.update(dtype_name=self._dtype_name(dtype), + pyx_code.context.update(dtype_name=dtype_name, dtype_type=self._dtype_type(dtype)) pyx_code.local_variable_declarations.put_chunk( u"""
diff --git a/tests/compile/fused_redeclare_T3111.pyx b/tests/compile/fused_redeclare_T3111.pyx new file mode 100644 --- /dev/null +++ b/tests/compile/fused_redeclare_T3111.pyx @@ -0,0 +1,39 @@ +# ticket: 3111 +# mode: compile +# tag: warnings + +ctypedef unsigned char npy_uint8 +ctypedef unsigned short npy_uint16 + + +ctypedef fused dtype_t: + npy_uint8 + +ctypedef fused dtype_t_out: + npy_uint8 + npy_uint16 + + +def foo(dtype_t[:] a, dtype_t_out[:, :] b): + pass + + +# The primary thing we're trying to test here is the _absence_ of the warning +# "__pyxutil:16:4: '___pyx_npy_uint8' redeclared". The remaining warnings are +# unrelated to this test. +_WARNINGS = """ +22:10: 'cpdef_method' redeclared +33:10: 'cpdef_cname_method' redeclared +446:72: Argument evaluation order in C function call is undefined and may not be as expected +446:72: Argument evaluation order in C function call is undefined and may not be as expected +749:34: Argument evaluation order in C function call is undefined and may not be as expected +749:34: Argument evaluation order in C function call is undefined and may not be as expected +943:27: Ambiguous exception value, same as default return value: 0 +943:27: Ambiguous exception value, same as default return value: 0 +974:29: Ambiguous exception value, same as default return value: 0 +974:29: Ambiguous exception value, same as default return value: 0 +1002:46: Ambiguous exception value, same as default return value: 0 +1002:46: Ambiguous exception value, same as default return value: 0 +1092:29: Ambiguous exception value, same as default return value: 0 +1092:29: Ambiguous exception value, same as default return value: 0 +"""
Spurious "redeclared" warning with fused types and typedef The following code: ```cython ctypedef unsigned char npy_uint8 ctypedef unsigned short npy_uint16 ctypedef fused Foo: npy_uint8 ctypedef fused Bar: npy_uint8 npy_uint16 def baz(Foo[:] a, Bar[:, :] b): pass ``` Seems like it should compile without warnings or errors. However, in practice, it produces a spurious "redeclared" warning: ``` $ venv/bin/cython -3 example.pyx warning: __pyxutil:16:4: '___pyx_npy_uint8' redeclared !!! ``` From hacking on the code a little to make it spit out the full context for errors, it looks like the declaration it's choking on is from some code that was auto-generated internally as part of the compilation process and was pseudo-named `__pyxutil`: ```cython cdef extern from *: void __pyx_PyErr_Clear "PyErr_Clear" () type __Pyx_ImportNumPyArrayTypeIfAvailable() int __Pyx_Is_Little_Endian() __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_nn___pyx_t_15fused_redeclare_npy_uint8(object, int) __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_nn___pyx_t_15fused_redeclare_npy_uint8(object, int) __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_nn___pyx_t_15fused_redeclare_npy_uint16(object, int) ctypedef struct __Pyx_memviewslice: void *memview void __PYX_XDEC_MEMVIEW(__Pyx_memviewslice *, int have_gil) bint __pyx_memoryview_check(object) ctypedef unsigned char ___pyx_npy_uint8 "__pyx_t_15fused_redeclare_npy_uint8" ctypedef unsigned char ___pyx_npy_uint8 "__pyx_t_15fused_redeclare_npy_uint8" ctypedef unsigned short ___pyx_npy_uint16 "__pyx_t_15fused_redeclare_npy_uint16" ``` I think this is due to there being code for deduplicating integer types, but no code for deduplicating typedefs: https://github.com/cython/cython/blob/00c1dc96af0e44741dc777f96a2eb5769f572bb3/Cython/Compiler/FusedNode.py#L510-L529
2019-08-29T02:10:26Z
[]
[]
cython/cython
3,118
cython__cython-3118
[ "1772" ]
e987a08030df387d4455bf743cae257271966800
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -1573,6 +1573,8 @@ def __hash__(self): class CConstOrVolatileType(BaseType): "A C const or volatile type" + subtypes = ['cv_base_type'] + is_cv_qualified = 1 def __init__(self, base_type, is_const=0, is_volatile=0):
diff --git a/tests/errors/fused_types.pyx b/tests/errors/fused_types.pyx --- a/tests/errors/fused_types.pyx +++ b/tests/errors/fused_types.pyx @@ -1,4 +1,5 @@ # mode: error +# ticket: 1772 cimport cython from cython import fused_type @@ -64,17 +65,30 @@ ctypedef fused fused2: func(x, y) +cdef fused mix_const_t: + int + const int + +cdef cdef_func_with_mix_const_type(mix_const_t val): + print(val) + +# Mixing const and non-const type makes fused type ambiguous +cdef_func_with_mix_const_type(1) + + _ERRORS = u""" -10:15: fused_type does not take keyword arguments -15:33: Type specified multiple times -26:0: Invalid use of fused types, type cannot be specialized -26:4: Not enough types specified to specialize the function, int2_t is still fused +11:15: fused_type does not take keyword arguments +16:33: Type specified multiple times 27:0: Invalid use of fused types, type cannot be specialized 27:4: Not enough types specified to specialize the function, int2_t is still fused -28:16: Call with wrong number of arguments (expected 2, got 1) -29:16: Call with wrong number of arguments (expected 2, got 3) -36:6: Invalid base type for memoryview slice: int * -39:0: Fused lambdas not allowed -42:5: Fused types not allowed here -45:9: Fused types not allowed here +28:0: Invalid use of fused types, type cannot be specialized +28:4: Not enough types specified to specialize the function, int2_t is still fused +29:16: Call with wrong number of arguments (expected 2, got 1) +30:16: Call with wrong number of arguments (expected 2, got 3) +37:6: Invalid base type for memoryview slice: int * +40:0: Fused lambdas not allowed +43:5: Fused types not allowed here +46:9: Fused types not allowed here +76:0: Invalid use of fused types, type cannot be specialized +76:29: ambiguous overloaded method """ diff --git a/tests/memoryview/numpy_memoryview_readonly.pyx b/tests/memoryview/numpy_memoryview_readonly.pyx --- a/tests/memoryview/numpy_memoryview_readonly.pyx +++ b/tests/memoryview/numpy_memoryview_readonly.pyx @@ -1,10 +1,14 @@ # mode: run # tag: readonly, const, numpy +# ticket: 1772 import numpy as np +cimport cython -def new_array(): - return np.arange(10).astype('float') +def new_array(dtype='float', writeable=True): + array = np.arange(10, dtype=dtype) + array.setflags(write=writeable) + return array ARRAY = new_array() @@ -124,3 +128,45 @@ def test_copy(): rw[1] = 2 rw2[2] = 2 return rw[0], rw[1], rw[2], rw2[0], rw2[1], rw2[2] + + +cdef getmax_floating(const cython.floating[:] x): + """Function with fused type, should work with both ro and rw memoryviews""" + cdef cython.floating max_val = - float('inf') + for val in x: + if val > max_val: + max_val = val + return max_val + + +def test_mmview_const_fused_cdef(): + """Test cdef function with const fused type memory view as argument. + + >>> test_mmview_const_fused_cdef() + """ + cdef float[:] data_rw = new_array(dtype='float32') + assert getmax_floating(data_rw) == 9 + + cdef const float[:] data_ro = new_array(dtype='float32', writeable=False) + assert getmax_floating(data_ro) == 9 + + +def test_mmview_const_fused_def(const cython.floating[:] x): + """Test def function with const fused type memory view as argument. + + With read-write numpy array: + + >>> test_mmview_const_fused_def(new_array('float32', writeable=True)) + 0.0 + >>> test_mmview_const_fused_def(new_array('float64', writeable=True)) + 0.0 + + With read-only numpy array: + + >>> test_mmview_const_fused_def(new_array('float32', writeable=False)) + 0.0 + >>> test_mmview_const_fused_def(new_array('float64', writeable=False)) + 0.0 + """ + cdef cython.floating result = x[0] + return result diff --git a/tests/run/fused_types.pyx b/tests/run/fused_types.pyx --- a/tests/run/fused_types.pyx +++ b/tests/run/fused_types.pyx @@ -1,4 +1,5 @@ # mode: run +# ticket: 1772 cimport cython from cython.view cimport array @@ -361,6 +362,22 @@ def test_fused_memslice_dtype_repeated_2(cython.floating[:] array1, cython.float """ print cython.typeof(array1), cython.typeof(array2), cython.typeof(array3) +def test_fused_const_memslice_dtype_repeated(const cython.floating[:] array1, cython.floating[:] array2): + """Test fused types memory view with one being const + + >>> sorted(test_fused_const_memslice_dtype_repeated.__signatures__) + ['double', 'float'] + + >>> test_fused_const_memslice_dtype_repeated(get_array(8, 'd'), get_array(8, 'd')) + const double[:] double[:] + >>> test_fused_const_memslice_dtype_repeated(get_array(4, 'f'), get_array(4, 'f')) + const float[:] float[:] + >>> test_fused_const_memslice_dtype_repeated(get_array(8, 'd'), get_array(4, 'f')) + Traceback (most recent call last): + ValueError: Buffer dtype mismatch, expected 'double' but got 'float' + """ + print cython.typeof(array1), cython.typeof(array2) + def test_cython_numeric(cython.numeric arg): """ Test to see whether complex numbers have their utility code declared @@ -386,6 +403,18 @@ def test_index_fused_args(cython.floating f, ints_t i): """ _test_index_fused_args[cython.floating, ints_t](f, i) +cdef _test_index_const_fused_args(const cython.floating f, const ints_t i): + print(cython.typeof(f), cython.typeof(i)) + +def test_index_const_fused_args(const cython.floating f, const ints_t i): + """Test indexing function implementation with const fused type args + + >>> import cython + >>> test_index_const_fused_args[cython.double, cython.int](2.0, 3) + ('const double', 'const int') + """ + _test_index_const_fused_args[cython.floating, ints_t](f, i) + def test_composite(fused_composite x): """ @@ -400,3 +429,27 @@ def test_composite(fused_composite x): return x else: return 2 * x + + +cdef cdef_func_const_fused_arg(const cython.floating val, + const fused_type1 * ptr_to_const, + const (cython.floating *) const_ptr): + print(val, cython.typeof(val)) + print(ptr_to_const[0], cython.typeof(ptr_to_const[0])) + print(const_ptr[0], cython.typeof(const_ptr[0])) + + ptr_to_const = NULL # pointer is not const, value is const + const_ptr[0] = 0.0 # pointer is const, value is not const + +def test_cdef_func_with_const_fused_arg(): + """Test cdef function with const fused type argument + + >>> test_cdef_func_with_const_fused_arg() + (0.0, 'const float') + (1, 'const int') + (2.0, 'float') + """ + cdef float arg0 = 0.0 + cdef int arg1 = 1 + cdef float arg2 = 2.0 + cdef_func_const_fused_arg(arg0, &arg1, &arg2)
Support "const" modifier on fused types ```cython cdef void c_encode_by_bits(const npy_intp n, const npy_intp m, const long * a, const long bitshift, integer * out) nogil: cdef npy_intp i, j cdef long shift cdef integer value for i in range(n): value = 0 shift = 0 for j in range(m): value += a[i * m + j] << shift shift += bitshift out[i] = value cdef void c_decode_by_bits(const npy_intp n, const npy_intp m, const integer * a, const long bitshift, long * out) nogil: cdef npy_intp i, j, k cdef long shift, mask = (1 << bitshift) - 1 for i in range(n): shift = 0 for j in range(m): out[i * m + j] = (<long> a[i] >> shift) & mask shift += bitshift ``` ```cython ctypedef fused integer: char unsigned char short unsigned short int unsigned int long unsigned long ``` ``` [1/1] Cythonizing locality/helpers/encode.pyx Traceback (most recent call last): File "build.py", line 99, in <module> ext_modules = cythonize(cy_extensions) + c_extensions, File "/usr/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 934, in cythonize cythonize_one(*args) File "/usr/lib/python3.6/site-packages/Cython/Build/Dependencies.py", line 1039, in cythonize_one result = compile([pyx_file], options) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Main.py", line 686, in compile return compile_multiple(source, options) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Main.py", line 664, in compile_multiple result = run_pipeline(source, options, context=context) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Main.py", line 494, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Pipeline.py", line 340, in run_pipeline data = phase(data) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Pipeline.py", line 53, in generate_pyx_code_stage module_node.process_implementation(options, result) File "/usr/lib/python3.6/site-packages/Cython/Compiler/ModuleNode.py", line 137, in process_implementation self.generate_c_code(env, options, result) File "/usr/lib/python3.6/site-packages/Cython/Compiler/ModuleNode.py", line 365, in generate_c_code self.body.generate_function_definitions(env, code) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Nodes.py", line 436, in generate_function_definitions stat.generate_function_definitions(env, code) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Nodes.py", line 436, in generate_function_definitions stat.generate_function_definitions(env, code) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Nodes.py", line 1754, in generate_function_definitions self.generate_function_header(code, with_pymethdef=with_pymethdef) File "/usr/lib/python3.6/site-packages/Cython/Compiler/Nodes.py", line 2466, in generate_function_header arg_decl = arg.declaration_code() File "/usr/lib/python3.6/site-packages/Cython/Compiler/PyrexTypes.py", line 3050, in declaration_code return self.type.declaration_code(self.cname, for_display) File "/usr/lib/python3.6/site-packages/Cython/Compiler/PyrexTypes.py", line 2372, in declaration_code for_display, dll_linkage, pyrex) File "/usr/lib/python3.6/site-packages/Cython/Compiler/PyrexTypes.py", line 1475, in declaration_code return self.const_base_type.declaration_code("const %s" % entity_code, for_display, dll_linkage, pyrex) File "/usr/lib/python3.6/site-packages/Cython/Compiler/PyrexTypes.py", line 1533, in declaration_code raise Exception("This may never happen, please report a bug") ``` Replacing "integer" with "long" stops the exception.
I think the problem is the `const integer`. Declaring fused types as `const` after the fact seems unsupported. I would consider that a bug, constifying a fused type usage seems reasonable to me. Here is a (non-minimal) test that fails to compile for me but should probably be allowed (can go into `tests/run/fused_types.pyx`): ``` cdef fused ints_t: int long cdef ints_t cdef_const_fused(const ints_t *i): return i[0] + 2 def const_fused(const ints_t i): """ >>> const_fused(5) 12 """ return i + cdef_const_fused(&i) ``` For the record, I hit the exact same error when I tried to use const memoryview (from https://github.com/cython/cython/pull/1869) + fused types. To reproduce: ```py cdef fused floating1d: float[:] double[:] def test(const floating1d arr): pass ``` As hinted by https://github.com/cython/cython/issues/1772#issuecomment-316138653, a work-around is to use const inside the fused type definition like this: ```py cdef fused const_floating1d: const float[:] const double[:] def test(const_floating1d arr): pass ``` > As hinted by #1772 (comment), a work-around is to use const inside the fused type definition like this: As noted in #2141 this work-around has some limitations because the const memoryview and the non-const memoryview types are seen as independent so that the function signature will be generated for all possible combination of types. For example: ```python from cython cimport floating cdef fused const_floating1d: const float[:] const double[:] def test(const_floating1d ro, floating[:] rw): rw[:] = ro ``` ``` Error compiling Cython file: ------------------------------------------------------------ ... const float[:] const double[:] def test(const_floating1d ro, floating[:] rw): rw[:] = ro ^ ------------------------------------------------------------ test.pyx:10:12: Different base types for memoryviews (const float, double) I have another issue with memoyviews of fused types with `const` types. Here is a small code example: ``` cimport cython cimport numpy as np import numpy as np ctypedef np.int8_t int8 ctypedef np.int16_t int16 ctypedef fused FusedType: const int8 const int16 def func(FusedType[:] array): pass ``` The Cython compiler raises this error: ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef __Pyx_memviewslice memslice cdef Py_ssize_t itemsize cdef bint dtype_signed cdef char kind itemsize = -1 cdef bint ___pyx_const int8_is_signed ^ ------------------------------------------------------------ (tree fragment):16:27: Syntax error in C variable declaration ``` This does only happen with `ctypedef` defined types, this problem does not occur with native types (char, short). Furthermore, this problem also diappears when a simple variable, rather than a memoryview, is used. The error message suggests that `const int8` is treated entirely as type name, which is clearly wrong, since `const` is a modifier. I am using Cython version 0.28. It looks like this is not difficult but a bit of work. Basically, in `FusedNode.py`, the `fused_base_types` must be generated without `const` (i.e. `if type.is_const: type = type.const_base_type`), but then the specialisation afterwards must look into `const` types to see if they are fused, and then specialise the type into the corresponding const type again. Not sure if this can be done locally in `PyrexTypes.py` or if it requires some non-local (but probably repetitive) code changes. PR welcome. One challenge with the workaround is declaring an array or value within the function that matches the fused type without being constant. While playing with a workaround similar to @lesteve's, came up with the following tweak. To ensure interoperability between the two types, we can add an `if` check that compares the two types. Interestingly the `const_floating` will drop the `const` part of its definition here. So a direct `is`/`is not` comparison works. All that is left is to bail out of bad prototypes preferably with some error that makes the user aware. To that extent, we raise a `TypeError` explaining the type mismatch to the user. Cython also recognizes the rest of the function is unreachable so does not generate the rest of it (avoiding any compile errors on the way). Only downside is Cython will warn the rest of the function is unreachable. We can fix this by using a decorator on the function to disable the `unreachable` warning. Though this will suppress any other such warnings in the function. The other alternatively would be to move the rest of the code into an `else` branch of type check condition. Maybe other options exist here? This is pretty similar to how [`static_assert`]( https://en.cppreference.com/w/cpp/language/static_assert ) works in C++. So this is a common way of solving this sort of problem. Maybe Cython can even leverage it under the hood? ```cython cimport cython from cython cimport floating cdef fused const_floating: const float const double @cython.warn.unreachable(False) cpdef void my_safe_float_copy(floating[:] a, const_floating[:] b): if floating is not const_floating: raise TypeError("Types of a and b don't match") a[:] = b.copy() ``` > Maybe Cython can even leverage it under the hood? No, we should avoid generating the functions entirely. My comment above explains what needs to be done. We spend half a day investigating this issue with @lesteve at EuroScipy. Posting a (partial) status update in case it might be helpful. A (possibly) minimal unit test that fails can be found [in this branch](https://github.com/cython/cython/compare/master...lesteve:test-const-fused-type-memoryview), where to produce an error it is sufficient to run, ```py python -m Cython.Build.Cythonize cython/tests/memoryview/const_fused_type_memoryview.pyx ``` or alternatively, ``` python runtests.py -T 1772 ``` (though the traceback in the latter case is less detailed). Below are a few additional observation (from someone with no formal CS background or in depth understanding how Cython works, and possibly I missed some contribution docs), - Looking at the generated C code, * the difference between `float` and `const float` declaration is just a few additional "const" declaration * the difference between `float` and `floating` (fused float type) is fairly large (though this has been tested with memoryviews: with plain scalars, it might not longer be the case) so the probable expected result of the PR that would fix this issue might be a slight modification of the resulting C code. - in the overall [processing pipeline](https://github.com/cython/cython/blob/fd36ee4ab0dec15fcaec42bc0e72b30a60c27d50/Cython/Compiler/Pipeline.py#L181) the processing step which is probably affected is `AnalyseDeclarationsTransform` (cf @scoder's above comment https://github.com/cython/cython/issues/1772#issuecomment-376629824). - we had some trouble specifying breakpoints for pdb in the code as it appears that some source files are cythonized. Using `git clean -xdf` could be a possible workaround. There are probably much better ways of approaching this issue for someone with better knowledge of Cython code base.
2019-08-30T13:22:35Z
[]
[]
cython/cython
3,205
cython__cython-3205
[ "3203" ]
d86aebefd33ecd232317e4becc15bb1d2f9f4bb7
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -655,6 +655,19 @@ def analyse_as_type(self, env): # type, return that type, else None. return None + def analyse_as_specialized_type(self, env): + type = self.analyse_as_type(env) + if type and type.is_fused and env.fused_to_specific: + # while it would be nice to test "if entry.type in env.fused_to_specific" + # rather than try/catch this doesn't work reliably (mainly for nested fused types) + try: + return type.specialize(env.fused_to_specific) + except KeyError: + pass + if type and type.is_fused: + error(self.pos, "Type is not specific") + return type + def analyse_as_extension_type(self, env): # If this node can be interpreted as a reference to an # extension type or builtin type, return its type, else None. @@ -10826,7 +10839,7 @@ def analyse_types(self, env): self.error("The 'libcpp.typeinfo' module must be cimported to use the typeid() operator") return self self.type = type_info - as_type = self.operand.analyse_as_type(env) + as_type = self.operand.analyse_as_specialized_type(env) if as_type: self.arg_type = as_type self.is_type = True
diff --git a/tests/run/fused_cpp.pyx b/tests/run/fused_cpp.pyx --- a/tests/run/fused_cpp.pyx +++ b/tests/run/fused_cpp.pyx @@ -2,6 +2,8 @@ cimport cython from libcpp.vector cimport vector +from libcpp.typeinfo cimport type_info +from cython.operator cimport typeid def test_cpp_specialization(cython.floating element): """ @@ -14,3 +16,28 @@ def test_cpp_specialization(cython.floating element): cdef vector[cython.floating] *v = new vector[cython.floating]() v.push_back(element) print cython.typeof(v), cython.typeof(element), v.at(0) + +cdef fused C: + int + object + +cdef const type_info* tidint = &typeid(int) +def typeid_call(C x): + """ + For GH issue 3203 + >>> typeid_call(1) + True + """ + cdef const type_info* a = &typeid(C) + return a[0] == tidint[0] + +cimport cython + +def typeid_call2(cython.integral x): + """ + For GH issue 3203 + >>> typeid_call2[int](1) + True + """ + cdef const type_info* a = &typeid(cython.integral) + return a[0] == tidint[0] diff --git a/tests/run/fused_types.pyx b/tests/run/fused_types.pyx --- a/tests/run/fused_types.pyx +++ b/tests/run/fused_types.pyx @@ -21,6 +21,7 @@ ctypedef double *p_double ctypedef int *p_int fused_type3 = cython.fused_type(int, double) fused_composite = cython.fused_type(fused_type2, fused_type3) +just_float = cython.fused_type(float) def test_pure(): """ @@ -453,3 +454,33 @@ def test_cdef_func_with_const_fused_arg(): cdef int arg1 = 1 cdef float arg2 = 2.0 cdef_func_const_fused_arg(arg0, &arg1, &arg2) + + +cdef in_check_1(just_float x): + return just_float in floating + +cdef in_check_2(just_float x, floating y): + # the "floating" on the right-hand side of the in statement should not be specialized + # - the test should still work. + return just_float in floating + +cdef in_check_3(floating x): + # the floating on the left-hand side of the in statement should be specialized + # but the one of the right-hand side should not (so that the test can still work). + return floating in floating + +def test_fused_in_check(): + """ + It should be possible to use fused types on in "x in ...fused_type" statements + even if that type is specialized in the function. + + >>> test_fused_in_check() + True + True + True + True + """ + print(in_check_1(1.0)) + print(in_check_2(1.0, 2.0)) + print(in_check_2[float, double](1.0, 2.0)) + print(in_check_3[float](1.0))
typeid failed on fused types ```cython # cython: language=c++ # cython: language_level=3str from libcpp.typeinfo cimport type_info from cython.operator cimport typeid cdef fused C: int object cdef const type_info* i32 = &typeid(int) cdef f(C x): cdef const type_info* a = &typeid(C) return a == i32 def g(x): return (x, f(x)) ```
2019-10-24T09:39:25Z
[]
[]
cython/cython
3,228
cython__cython-3228
[ "3226" ]
b9cecd602878334173aa9f6ed635d48739bfa2b1
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -1399,8 +1399,8 @@ def generate_new_function(self, scope, code, cclass_entry): if scope.is_internal: # internal classes (should) never need None inits, normal zeroing will do py_attrs = [] - cpp_class_attrs = [entry for entry in scope.var_entries - if entry.type.is_cpp_class] + cpp_constructable_attrs = [entry for entry in scope.var_entries + if entry.type.needs_cpp_construction] cinit_func_entry = scope.lookup_here("__cinit__") if cinit_func_entry and not cinit_func_entry.is_special: @@ -1434,7 +1434,7 @@ def generate_new_function(self, scope, code, cclass_entry): need_self_cast = (type.vtabslot_cname or (py_buffers or memoryview_slices or py_attrs) or - cpp_class_attrs) + cpp_constructable_attrs) if need_self_cast: code.putln("%s;" % scope.parent_type.declaration_code("p")) if base_type: @@ -1504,7 +1504,7 @@ def generate_new_function(self, scope, code, cclass_entry): type.vtabslot_cname, struct_type_cast, type.vtabptr_cname)) - for entry in cpp_class_attrs: + for entry in cpp_constructable_attrs: code.putln("new((void*)&(p->%s)) %s();" % ( entry.cname, entry.type.empty_declaration_code())) @@ -1574,10 +1574,10 @@ def generate_dealloc_function(self, scope, code): dict_slot = None _, (py_attrs, _, memoryview_slices) = scope.get_refcounted_entries() - cpp_class_attrs = [entry for entry in scope.var_entries - if entry.type.is_cpp_class] + cpp_destructable_attrs = [entry for entry in scope.var_entries + if entry.type.needs_cpp_construction] - if py_attrs or cpp_class_attrs or memoryview_slices or weakref_slot or dict_slot: + if py_attrs or cpp_destructable_attrs or memoryview_slices or weakref_slot or dict_slot: self.generate_self_cast(scope, code) if not is_final_type: @@ -1621,7 +1621,7 @@ def generate_dealloc_function(self, scope, code): if dict_slot: code.putln("if (p->__dict__) PyDict_Clear(p->__dict__);") - for entry in cpp_class_attrs: + for entry in cpp_destructable_attrs: code.putln("__Pyx_call_destructor(p->%s);" % entry.cname) for entry in (py_attrs + memoryview_slices): diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -194,7 +194,8 @@ class PyrexType(BaseType): # is_pythran_expr boolean Is Pythran expr # is_numpy_buffer boolean Is Numpy array buffer # has_attributes boolean Has C dot-selectable attributes - # needs_refcounting boolean Needs code to be generated similar to incref/gotref/decref. + # needs_cpp_construction boolean Needs C++ constructor and destructor when used in a cdef class + # needs_refcounting boolean Needs code to be generated similar to incref/gotref/decref. # Largely used internally. # default_value string Initial value that can be assigned before first user assignment. # declaration_value string The value statically assigned on declaration (if any). @@ -262,6 +263,7 @@ class PyrexType(BaseType): is_pythran_expr = 0 is_numpy_buffer = 0 has_attributes = 0 + needs_cpp_construction = 0 needs_refcounting = 0 default_value = "" declaration_value = "" @@ -3495,7 +3497,7 @@ class CStructOrUnionType(CType): has_attributes = 1 exception_check = True - def __init__(self, name, kind, scope, typedef_flag, cname, packed=False): + def __init__(self, name, kind, scope, typedef_flag, cname, packed=False, in_cpp=False): self.name = name self.cname = cname self.kind = kind @@ -3510,6 +3512,7 @@ def __init__(self, name, kind, scope, typedef_flag, cname, packed=False): self._convert_to_py_code = None self._convert_from_py_code = None self.packed = packed + self.needs_cpp_construction = self.is_struct and in_cpp def can_coerce_to_pyobject(self, env): if self._convert_to_py_code is False: @@ -3680,6 +3683,7 @@ class CppClassType(CType): is_cpp_class = 1 has_attributes = 1 + needs_cpp_construction = 1 exception_check = True namespace = None diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -592,8 +592,10 @@ def declare_struct_or_union(self, name, kind, scope, cname = self.mangle(Naming.type_prefix, name) entry = self.lookup_here(name) if not entry: + in_cpp = self.is_cpp() type = PyrexTypes.CStructOrUnionType( - name, kind, scope, typedef_flag, cname, packed) + name, kind, scope, typedef_flag, cname, packed, + in_cpp = in_cpp) entry = self.declare_type(name, type, pos, cname, visibility = visibility, api = api, defining = scope is not None) @@ -2143,7 +2145,7 @@ class CClassScope(ClassScope): has_pyobject_attrs = False has_memoryview_attrs = False - has_cpp_class_attrs = False + has_cpp_constructable_attrs = False has_cyclic_pyobject_attrs = False defined = False implemented = False @@ -2231,14 +2233,14 @@ def declare_var(self, name, type, pos, cname = punycodify_name(cname, Naming.unicode_structmember_prefix) if type.is_cpp_class and visibility != 'extern': type.check_nullary_constructor(pos) - self.use_utility_code(Code.UtilityCode("#include <new>")) entry = self.declare(name, cname, type, pos, visibility) entry.is_variable = 1 self.var_entries.append(entry) if type.is_memoryviewslice: self.has_memoryview_attrs = True - elif type.is_cpp_class: - self.has_cpp_class_attrs = True + elif type.needs_cpp_construction: + self.use_utility_code(Code.UtilityCode("#include <new>")) + self.has_cpp_constructable_attrs = True elif type.is_pyobject and (self.is_closure_class_scope or name != '__weakref__'): self.has_pyobject_attrs = True if (not type.is_builtin_type diff --git a/Cython/Compiler/TypeSlots.py b/Cython/Compiler/TypeSlots.py --- a/Cython/Compiler/TypeSlots.py +++ b/Cython/Compiler/TypeSlots.py @@ -432,7 +432,7 @@ def _needs_own(self, scope): if (scope.parent_type.base_type and not scope.has_pyobject_attrs and not scope.has_memoryview_attrs - and not scope.has_cpp_class_attrs + and not scope.has_cpp_constructable_attrs and not (self.slot_name == 'tp_new' and scope.parent_type.vtabslot_cname)): entry = scope.lookup_here(self.method) if self.method else None if not (entry and entry.is_special):
diff --git a/tests/run/cpp_classes.pyx b/tests/run/cpp_classes.pyx --- a/tests/run/cpp_classes.pyx +++ b/tests/run/cpp_classes.pyx @@ -130,6 +130,10 @@ def test_value_call(int w): del sqr +cdef struct StructWithEmpty: + Empty empty + + def get_destructor_count(): return destructor_count @@ -146,6 +150,15 @@ def test_stack_allocation(int w, int h): print rect.method(<int>5) return destructor_count +def test_stack_allocation_in_struct(): + """ + >>> d = test_stack_allocation_in_struct() + >>> get_destructor_count() - d + 1 + """ + cdef StructWithEmpty swe + sizeof(swe.empty) # use it for something + return destructor_count cdef class EmptyHolder: cdef Empty empty @@ -153,6 +166,9 @@ cdef class EmptyHolder: cdef class AnotherEmptyHolder(EmptyHolder): cdef Empty another_empty +cdef class EmptyViaStructHolder: + cdef StructWithEmpty swe + def test_class_member(): """ >>> test_class_member() @@ -183,6 +199,18 @@ def test_derived_class_member(): assert destructor_count - start_destructor_count == 2, \ destructor_count - start_destructor_count +def test_class_in_struct_member(): + """ + >>> test_class_in_struct_member() + """ + start_constructor_count = constructor_count + start_destructor_count = destructor_count + e = EmptyViaStructHolder() + #assert constructor_count - start_constructor_count == 1, \ + # constructor_count - start_constructor_count + del e + assert destructor_count - start_destructor_count == 1, \ + destructor_count - start_destructor_count cdef class TemplateClassMember: cdef vector[int] x
Struct members of cdef'd classes don't get destroyed If I create a `cdef`'d class in a cython file having a struct as class member, and then instantiate that class in python, the structs do not get destroyed when the python object is deleted. Adding an explicit call to the struct destructor in `__dealloc__` will do the job however. Example: cppheader.hpp: ```cpp #include <vector> typedef struct MyObject { int val; std::vector<double> big_obj; } MyObject; typedef struct InfoHolder { std::vector<MyObject> v; int some_val; } InfoHolder; void increase_size(MyObject &my_obj) { my_obj.big_obj.resize(10000000, 1); } void force_destroy(InfoHolder &info_holder) { info_holder.~InfoHolder(); } ``` cyfile.pyx: ```python from libcpp.vector cimport vector cdef extern from "cppheader.hpp": ctypedef struct MyObject: int val vector[double] big_obj ctypedef struct InfoHolder: vector[MyObject] v int some_val void increase_size(MyObject &my_obj) void force_destroy(InfoHolder &info_holder) cdef class PyInfoHolder: cdef InfoHolder info_holder def __init__(self): self.info_holder.v.resize(1); increase_size(self.info_holder.v.at(0)) def say_hello(self): print("hello") ``` pyfile.py: ```python from cyfile import PyInfoHolder for i in range(100): py_obj = PyInfoHolder() py_obj.say_hello() print("end") ``` Watch the memory usage when running `python pyfile.py`, and then compare against the following alternative cython class: ```python cdef class PyInfoHolder: cdef InfoHolder info_holder def __init__(self): self.info_holder.v.resize(1); increase_size(self.info_holder.v.at(0)) def __dealloc__(self): force_destroy(self.info_holder) def say_hello(self): print("hello") ``` (For some reason, the structs also cannot call their destructor explicitly within cython - e.g. `self.info_holder.~InfoHolder()` fails to compile)
Cython doesn't handle structs in C++ any different from structs in C. If you can, use a C++ class instead. Does this seem worth turning into a feature? Yes, would be a nice addition to auto-destruct all attributes of a cdef'd class, especially considering that it's not possible to call the struct destructor in Cython unless it's wrapped in a C++ function. Also, does it mean that if I instantiate a cdef'd class with POD types like `int`, `double`, etc. that those would also not be freed when the python object is deleted?
2019-11-09T16:23:42Z
[]
[]
cython/cython
3,297
cython__cython-3297
[ "3291" ]
ada8dbd865497ff4dd32a49d56a20cd74be498dc
diff --git a/Cython/Build/IpythonMagic.py b/Cython/Build/IpythonMagic.py --- a/Cython/Build/IpythonMagic.py +++ b/Cython/Build/IpythonMagic.py @@ -56,6 +56,8 @@ import distutils.log import textwrap +IO_ENCODING = sys.getfilesystemencoding() +IS_PY2 = sys.version_info[0] < 3 try: reload @@ -73,7 +75,6 @@ from IPython.core import display from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, cell_magic -from IPython.utils import py3compat try: from IPython.paths import get_ipython_cache_dir except ImportError: @@ -101,6 +102,14 @@ PGO_CONFIG['mingw32'] = PGO_CONFIG['gcc'] +if IS_PY2: + def encode_fs(name): + return name if isinstance(name, bytes) else name.encode(IO_ENCODING) +else: + def encode_fs(name): + return name + + @magics_class class CythonMagics(Magics): @@ -306,7 +315,7 @@ def critical_function(data): key += (time.time(),) if args.name: - module_name = py3compat.unicode_to_str(args.name) + module_name = str(args.name) # no-op in Py3 else: module_name = "_cython_magic_" + hashlib.md5(str(key).encode('utf-8')).hexdigest() html_file = os.path.join(lib_dir, module_name + '.html') @@ -406,7 +415,7 @@ def _profile_pgo_wrapper(self, extension, lib_dir): def _cythonize(self, module_name, code, lib_dir, args, quiet=True): pyx_file = os.path.join(lib_dir, module_name + '.pyx') - pyx_file = py3compat.cast_bytes_py2(pyx_file, encoding=sys.getfilesystemencoding()) + pyx_file = encode_fs(pyx_file) c_include_dirs = args.include c_src_files = list(map(str, args.src)) @@ -526,10 +535,10 @@ def build_extensions(self): build_extension = _build_ext(dist) build_extension.finalize_options() if temp_dir: - temp_dir = py3compat.cast_bytes_py2(temp_dir, encoding=sys.getfilesystemencoding()) + temp_dir = encode_fs(temp_dir) build_extension.build_temp = temp_dir if lib_dir: - lib_dir = py3compat.cast_bytes_py2(lib_dir, encoding=sys.getfilesystemencoding()) + lib_dir = encode_fs(lib_dir) build_extension.build_lib = lib_dir if extension is not None: build_extension.extensions = [extension]
diff --git a/Cython/Build/Tests/TestIpythonMagic.py b/Cython/Build/Tests/TestIpythonMagic.py --- a/Cython/Build/Tests/TestIpythonMagic.py +++ b/Cython/Build/Tests/TestIpythonMagic.py @@ -13,15 +13,8 @@ try: import IPython.testing.globalipapp - from IPython.utils import py3compat except ImportError: # Disable tests and fake helpers for initialisation below. - class _py3compat(object): - def str_to_unicode(self, s): - return s - - py3compat = _py3compat() - def skip_if_not_installed(_): return None else: @@ -35,24 +28,24 @@ def skip_if_not_installed(c): except ImportError: pass -code = py3compat.str_to_unicode("""\ +code = u"""\ def f(x): return 2*x -""") +""" -cython3_code = py3compat.str_to_unicode("""\ +cython3_code = u"""\ def f(int x): return 2 / x def call(x): return f(*(x,)) -""") +""" -pgo_cython3_code = cython3_code + py3compat.str_to_unicode("""\ +pgo_cython3_code = cython3_code + u"""\ def main(): for _ in range(100): call(5) main() -""") +""" if sys.platform == 'win32': @@ -161,10 +154,10 @@ def test_cython3_pgo(self): @skip_win32('Skip on Windows') def test_extlibs(self): ip = self._ip - code = py3compat.str_to_unicode(""" + code = u""" from libc.math cimport sin x = sin(0.0) - """) + """ ip.user_ns['x'] = 1 ip.run_cell_magic('cython', '-l m', code) self.assertEqual(ip.user_ns['x'], 0)
Fix IpythonMagic for IPython >= 7.11 In IPython 7.11.0, [a number of function in the py3compat have been removed](https://github.com/ipython/ipython/blob/master/docs/source/whatsnew/version7.rst#ipython-711). Fixes https://github.com/ipython/ipython/issues/12068 ``` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-2-84ee719fa1da> in <module> ----> 1 get_ipython().run_cell_magic('cython', '', '\ndef tmp():\n return 0\n') X:\Python37\lib\site-packages\IPython\core\interactiveshell.py in run_cell_magic(self, magic_name, line, cell) 2350 with self.builtin_trap: 2351 args = (magic_arg_s, cell) -> 2352 result = fn(*args, **kwargs) 2353 return result 2354 <X:\Python37\lib\site-packages\decorator.py:decorator-gen-159> in cython(self, line, cell) X:\Python37\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k) 185 # but it's overkill for just that one bit of state. 186 def magic_deco(arg): --> 187 call = lambda f, *a, **k: f(*a, **k) 188 189 if callable(arg): X:\Python37\lib\site-packages\Cython\Build\IpythonMagic.py in cython(self, line, cell) 322 extension = None 323 if need_cythonize: --> 324 extensions = self._cythonize(module_name, code, lib_dir, args, quiet=args.quiet) 325 if extensions is None: 326 # Compilation failed and printed error message X:\Python37\lib\site-packages\Cython\Build\IpythonMagic.py in _cythonize(self, module_name, code, lib_dir, args, quiet) 407 def _cythonize(self, module_name, code, lib_dir, args, quiet=True): 408 pyx_file = os.path.join(lib_dir, module_name + '.pyx') --> 409 pyx_file = py3compat.cast_bytes_py2(pyx_file, encoding=sys.getfilesystemencoding()) 410 411 c_include_dirs = args.include AttributeError: module 'IPython.utils.py3compat' has no attribute 'cast_bytes_py2' ```
I'll reintroduce them in a 7.11.1 as I know Cython release is not fast. What I can also suggest is to be explicit as to when you use `... = no_code` and when not; like use the if `(sys.version_info < 3)`. This will make it way easier to cleanup the code later. If you have `try... except` then in a few year you will have to hunt down which versions of Python/IPython have the import and it will take you hours. See ipython/ipython#12069 I'm not going to release a 7.11.1 for now to let you test this PR. Once your happy with that let me know on ipython/ipython#12069 and I can merge and do a release. Thanks. Apparently, `str_to_unicode()` is also missing now, which is used in `TestIpythonMagic.py`. @Carreau, is `py3compat` considered an internal module? My guess is that it might have been used in the implementation because "it was there". Should we get rid of the usage all-together, and only have a couple of dedicated fallbacks for the Py2 case then? > My guess is that it might have been used in the implementation because "it was there". Should we get rid of the usage all-together, and only have a couple of dedicated fallbacks for the Py2 case then? It was probably used because the Cython magic was originally in IPython and was transplanted in Cython. It is kinda internal, as it would be better to rely on `six` for both Py2 and Py3 compact, but out utils predates six. Yes I would suggest to be explicit about the Py2/Py3 when possible, especially since you only have a couple of usage and that both of the one I see are no-op functions in Python 3.
2020-01-01T14:31:01Z
[]
[]
cython/cython
3,340
cython__cython-3340
[ "3338" ]
e83ff762f52505280c06c6bb166cd3f7517ebdfe
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -8938,12 +8938,11 @@ class ClassNode(ExprNode, ModuleNameMixin): # a name, tuple of bases and class dictionary. # # name EncodedString Name of the class - # bases ExprNode Base class tuple - # dict ExprNode Class dict (not owned by this node) + # class_def_node PyClassDefNode PyClassDefNode defining this class # doc ExprNode or None Doc string # module_name EncodedString Name of defining module - subexprs = ['bases', 'doc'] + subexprs = ['doc'] type = py_object_type is_temp = True @@ -8952,7 +8951,6 @@ def infer_type(self, env): return py_object_type def analyse_types(self, env): - self.bases = self.bases.analyse_types(env) if self.doc: self.doc = self.doc.analyse_types(env) self.doc = self.doc.coerce_to_pyobject(env) @@ -8965,12 +8963,13 @@ def may_be_none(self): gil_message = "Constructing Python class" def generate_result_code(self, code): + class_def_node = self.class_def_node cname = code.intern_identifier(self.name) if self.doc: code.put_error_if_neg(self.pos, 'PyDict_SetItem(%s, %s, %s)' % ( - self.dict.py_result(), + class_def_node.dict.py_result(), code.intern_identifier( StringEncoding.EncodedString("__doc__")), self.doc.py_result())) @@ -8979,8 +8978,8 @@ def generate_result_code(self, code): code.putln( '%s = __Pyx_CreateClass(%s, %s, %s, %s, %s); %s' % ( self.result(), - self.bases.py_result(), - self.dict.py_result(), + class_def_node.bases.py_result(), + class_def_node.dict.py_result(), cname, qualname, py_mod_name, @@ -8994,8 +8993,8 @@ class Py3ClassNode(ExprNode): # a name, tuple of bases and class dictionary. # # name EncodedString Name of the class - # dict ExprNode Class dict (not owned by this node) # module_name EncodedString Name of defining module + # class_def_node PyClassDefNode PyClassDefNode defining this class # calculate_metaclass bool should call CalculateMetaclass() # allow_py2_metaclass bool should look for Py2 metaclass @@ -9018,12 +9017,10 @@ def may_be_none(self): def generate_result_code(self, code): code.globalstate.use_utility_code(UtilityCode.load_cached("Py3ClassCreate", "ObjectHandling.c")) cname = code.intern_identifier(self.name) - if self.mkw: - mkw = self.mkw.py_result() - else: - mkw = 'NULL' - if self.metaclass: - metaclass = self.metaclass.py_result() + class_def_node = self.class_def_node + mkw = class_def_node.mkw.py_result() if class_def_node.mkw else 'NULL' + if class_def_node.metaclass: + metaclass = class_def_node.metaclass.py_result() else: metaclass = "((PyObject*)&__Pyx_DefaultClassType)" code.putln( @@ -9031,8 +9028,8 @@ def generate_result_code(self, code): self.result(), metaclass, cname, - self.bases.py_result(), - self.dict.py_result(), + class_def_node.bases.py_result(), + class_def_node.dict.py_result(), mkw, self.calculate_metaclass, self.allow_py2_metaclass, @@ -9043,8 +9040,7 @@ def generate_result_code(self, code): class PyClassMetaclassNode(ExprNode): # Helper class holds Python3 metaclass object # - # bases ExprNode Base class tuple (not owned by this node) - # mkw ExprNode Class keyword arguments (not owned by this node) + # class_def_node PyClassDefNode PyClassDefNode defining this class subexprs = [] @@ -9057,38 +9053,38 @@ def may_be_none(self): return True def generate_result_code(self, code): - if self.mkw: + bases = self.class_def_node.bases + mkw = self.class_def_node.mkw + if mkw: code.globalstate.use_utility_code( UtilityCode.load_cached("Py3MetaclassGet", "ObjectHandling.c")) call = "__Pyx_Py3MetaclassGet(%s, %s)" % ( - self.bases.result(), - self.mkw.result()) + bases.result(), + mkw.result()) else: code.globalstate.use_utility_code( UtilityCode.load_cached("CalculateMetaclass", "ObjectHandling.c")) call = "__Pyx_CalculateMetaclass(NULL, %s)" % ( - self.bases.result()) + bases.result()) code.putln( "%s = %s; %s" % ( self.result(), call, code.error_goto_if_null(self.result(), self.pos))) code.put_gotref(self.py_result()) + class PyClassNamespaceNode(ExprNode, ModuleNameMixin): # Helper class holds Python3 namespace object # # All this are not owned by this node - # metaclass ExprNode Metaclass object - # bases ExprNode Base class tuple - # mkw ExprNode Class keyword arguments + # class_def_node PyClassDefNode PyClassDefNode defining this class # doc ExprNode or None Doc string (owned) subexprs = ['doc'] def analyse_types(self, env): if self.doc: - self.doc = self.doc.analyse_types(env) - self.doc = self.doc.coerce_to_pyobject(env) + self.doc = self.doc.analyse_types(env).coerce_to_pyobject(env) self.type = py_object_type self.is_temp = 1 return self @@ -9100,23 +9096,16 @@ def generate_result_code(self, code): cname = code.intern_identifier(self.name) py_mod_name = self.get_py_mod_name(code) qualname = self.get_py_qualified_name(code) - if self.doc: - doc_code = self.doc.result() - else: - doc_code = '(PyObject *) NULL' - if self.mkw: - mkw = self.mkw.py_result() - else: - mkw = '(PyObject *) NULL' - if self.metaclass: - metaclass = self.metaclass.py_result() - else: - metaclass = "(PyObject *) NULL" + class_def_node = self.class_def_node + null = "(PyObject *) NULL" + doc_code = self.doc.result() if self.doc else null + mkw = class_def_node.mkw.py_result() if class_def_node.mkw else null + metaclass = class_def_node.metaclass.py_result() if class_def_node.metaclass else null code.putln( "%s = __Pyx_Py3MetaclassPrepare(%s, %s, %s, %s, %s, %s, %s); %s" % ( self.result(), metaclass, - self.bases.result(), + class_def_node.bases.result(), cname, qualname, mkw, diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -4503,26 +4503,22 @@ def __init__(self, pos, name, bases, doc, body, decorators=None, pass # no base classes => no inherited metaclass else: self.metaclass = ExprNodes.PyClassMetaclassNode( - pos, mkw=mkdict, bases=self.bases) + pos, class_def_node=self) needs_metaclass_calculation = False else: needs_metaclass_calculation = True self.dict = ExprNodes.PyClassNamespaceNode( - pos, name=name, doc=doc_node, - metaclass=self.metaclass, bases=self.bases, mkw=self.mkw) + pos, name=name, doc=doc_node, class_def_node=self) self.classobj = ExprNodes.Py3ClassNode( - pos, name=name, - bases=self.bases, dict=self.dict, doc=doc_node, - metaclass=self.metaclass, mkw=self.mkw, + pos, name=name, class_def_node=self, doc=doc_node, calculate_metaclass=needs_metaclass_calculation, allow_py2_metaclass=allow_py2_metaclass) else: # no bases, no metaclass => old style class creation self.dict = ExprNodes.DictNode(pos, key_value_pairs=[]) self.classobj = ExprNodes.ClassNode( - pos, name=name, - bases=bases, dict=self.dict, doc=doc_node) + pos, name=name, class_def_node=self, doc=doc_node) self.target = ExprNodes.NameNode(pos, name=name) self.class_cell = ExprNodes.ClassCellInjectorNode(self.pos) @@ -4540,7 +4536,7 @@ def as_cclass(self): visibility='private', module_name=None, class_name=self.name, - bases=self.classobj.bases or ExprNodes.TupleNode(self.pos, args=[]), + bases=self.bases or ExprNodes.TupleNode(self.pos, args=[]), decorators=self.decorators, body=self.body, in_pxd=False, @@ -4564,6 +4560,10 @@ def analyse_declarations(self, env): args=[class_result]) self.decorators = None self.class_result = class_result + if self.bases: + self.bases.analyse_declarations(env) + if self.mkw: + self.mkw.analyse_declarations(env) self.class_result.analyse_declarations(env) self.target.analyse_target_declaration(env) cenv = self.create_scope(env) @@ -4574,10 +4574,10 @@ def analyse_declarations(self, env): def analyse_expressions(self, env): if self.bases: self.bases = self.bases.analyse_expressions(env) - if self.metaclass: - self.metaclass = self.metaclass.analyse_expressions(env) if self.mkw: self.mkw = self.mkw.analyse_expressions(env) + if self.metaclass: + self.metaclass = self.metaclass.analyse_expressions(env) self.dict = self.dict.analyse_expressions(env) self.class_result = self.class_result.analyse_expressions(env) cenv = self.scope
diff --git a/tests/run/pyclass_dynamic_bases.pyx b/tests/run/pyclass_dynamic_bases.pyx --- a/tests/run/pyclass_dynamic_bases.pyx +++ b/tests/run/pyclass_dynamic_bases.pyx @@ -24,3 +24,22 @@ def cond_if_bases(x): class PyClass(A if x else B): p = 5 return PyClass + + +def make_subclass(*bases): + """ + >>> cls = make_subclass(list) + >>> issubclass(cls, list) or cls.__mro__ + True + + >>> class Cls(object): pass + >>> cls = make_subclass(Cls, list) + >>> issubclass(cls, list) or cls.__mro__ + True + >>> issubclass(cls, Cls) or cls.__mro__ + True + """ + # GH-3338 + class MadeClass(*bases): + pass + return MadeClass
Cythonization of pure Python crashes with function that passes its argument splat to a class definition. This doesn't translate properly: ```python3 def ClassMaker(*bases): class MadeClass(*bases): pass return MadeClass ``` ``` Compiling testfile.py because it changed. [1/1] Cythonizing testfile.py Traceback (most recent call last): File "setup.py", line 12, in <module> distutils.core.setup(ext_modules=Cython.Build.cythonize(packpaths, nthreads=buildthreads, compiler_directives={'language_level': 3, 'profile': True}, annotate=True)) File ".../Cython/Build/Dependencies.py", line 1096, in cythonize cythonize_one(*args) File ".../Cython/Build/Dependencies.py", line 1202, in cythonize_one result = compile_single(pyx_file, options, full_module_name=full_module_name) File ".../Cython/Compiler/Main.py", line 727, in compile_single return run_pipeline(source, options, full_module_name) File ".../Cython/Compiler/Main.py", line 515, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File ".../Cython/Compiler/Pipeline.py", line 355, in run_pipeline data = run(phase, data) File ".../Cython/Compiler/Pipeline.py", line 335, in run return phase(data) File ".../Cython/Compiler/Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File ".../Cython/Compiler/ModuleNode.py", line 143, in process_implementation self.generate_c_code(env, options, result) File ".../Cython/Compiler/ModuleNode.py", line 385, in generate_c_code self.body.generate_function_definitions(env, code) File ".../Cython/Compiler/Nodes.py", line 442, in generate_function_definitions stat.generate_function_definitions(env, code) File ".../Cython/Compiler/Nodes.py", line 442, in generate_function_definitions stat.generate_function_definitions(env, code) File ".../Cython/Compiler/Nodes.py", line 3176, in generate_function_definitions FuncDefNode.generate_function_definitions(self, env, code) File ".../Cython/Compiler/Nodes.py", line 1983, in generate_function_definitions self.generate_function_body(env, code) File ".../Cython/Compiler/Nodes.py", line 1745, in generate_function_body self.body.generate_execution_code(code) File ".../Cython/Compiler/Nodes.py", line 448, in generate_execution_code stat.generate_execution_code(code) File ".../Cython/Compiler/Nodes.py", line 4601, in generate_execution_code self.class_result.generate_evaluation_code(code) File ".../Cython/Compiler/ExprNodes.py", line 773, in generate_evaluation_code self.generate_result_code(code) File ".../Cython/Compiler/ExprNodes.py", line 9034, in generate_result_code self.bases.py_result(), File ".../Cython/Compiler/ExprNodes.py", line 525, in py_result return self.result_as(py_object_type) File ".../Cython/Compiler/ExprNodes.py", line 516, in result_as if (self.is_temp and self.type.is_pyobject and AttributeError: 'NoneType' object has no attribute 'is_pyobject' ``` The two forms below compile fine though: ```python3 def ClassMaker(bases): class MadeClass(*bases): pass return MadeClass ``` ```python3 def ClassMaker(*bases): class MadeClass(bases): pass return MadeClass ```
2020-01-30T10:09:46Z
[]
[]
cython/cython
3,427
cython__cython-3427
[ "2273" ]
e19fa590004305a9b3170c770c8244ef7f453e75
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -9436,6 +9436,9 @@ def generate_cyfunction_code(self, code): if def_node.local_scope.parent_scope.is_c_class_scope and not def_node.entry.is_anonymous: flags.append('__Pyx_CYFUNCTION_CCLASS') + if def_node.is_coroutine: + flags.append('__Pyx_CYFUNCTION_COROUTINE') + if flags: flags = ' | '.join(flags) else: diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -1665,6 +1665,8 @@ class FuncDefNode(StatNode, BlockNode): needs_outer_scope = False pymethdef_required = False is_generator = False + is_coroutine = False + is_asyncgen = False is_generator_body = False is_async_def = False modifiers = [] @@ -4308,9 +4310,7 @@ class GeneratorDefNode(DefNode): # is_generator = True - is_coroutine = False is_iterable_coroutine = False - is_asyncgen = False gen_type_name = 'Generator' needs_closure = True
diff --git a/tests/run/py35_asyncio_async_def.srctree b/tests/run/py35_asyncio_async_def.srctree --- a/tests/run/py35_asyncio_async_def.srctree +++ b/tests/run/py35_asyncio_async_def.srctree @@ -1,5 +1,5 @@ # mode: run -# tag: asyncio, gh1685 +# tag: asyncio, gh1685, gh2273 PYTHON setup.py build_ext -i PYTHON main.py @@ -19,6 +19,7 @@ setup( import asyncio import cy_test +import py_test from contextlib import closing async def main(): @@ -31,6 +32,12 @@ with closing(asyncio.get_event_loop()) as loop: print("Running Cython coroutine ...") loop.run_until_complete(cy_test.say()) +assert asyncio.iscoroutinefunction(cy_test.cy_async_def_example) == True +assert asyncio.iscoroutinefunction(cy_test.cy_async_def_example) == True +assert asyncio.iscoroutinefunction(py_test.py_async_def_example) == True +assert asyncio.iscoroutinefunction(py_test.py_async_def_example) == True +assert asyncio.iscoroutinefunction(cy_test.cy_def_example) == False +assert asyncio.iscoroutinefunction(py_test.py_def_example) == False ######## cy_test.pyx ######## @@ -51,8 +58,19 @@ async def cb(): await asyncio.sleep(0.5) print("done!") +async def cy_async_def_example(): + return 1 + +def cy_def_example(): + return 1 ######## py_test.py ######## async def py_async(): print("- and this one is from Python") + +async def py_async_def_example(): + return 1 + +def py_def_example(): + return 1
asyncio.iscoroutinefunction returns false for Cython async function objects Referring to #2092 @scoder the implementation in asyncio is ridiculous ``` def iscoroutinefunction(func): """Return True if func is a decorated coroutine function.""" return (inspect.iscoroutinefunction(func) or getattr(func, '_is_coroutine', None) is _is_coroutine) ``` So once we agreed `inspect` returns False, it happens to be that CPython just add a simple attribute to the function `_is_coroutine`, I think if Cython does this adding up this attribute it will make everything work Here: https://github.com/python/cpython/blob/789e359f51d2b27bea01b8c6c3bf090aaedf8839/Lib/asyncio/coroutines.py#L152 And here: https://github.com/python/cpython/blob/789e359f51d2b27bea01b8c6c3bf090aaedf8839/Lib/asyncio/coroutines.py#L160 So the solution as it can't be another it results in this, from my test in iPython: ``` In [46]: fut = init_connection() In [47]: asyncio.iscoroutine(fut) Out[47]: True In [49]: init_connection.__class__ Out[49]: cython_function_or_method In [50]: asyncio.iscoroutinefunction(init_connection) Out[50]: False In [56]: from asyncio.coroutines import _is_coroutine In [57]: init_connection._is_coroutine = _is_coroutine In [58]: asyncio.iscoroutinefunction(init_connection) Out[58]: True ``` Dirty but easy. Don't know if this is a 5 seconds issue or a hara-kiri, theoretically it should be easy to plug the attribute runtime from `from asyncio.coroutines import _is_coroutine`, or not. This is a super annoying problem (I don't blame anyone with the word _bug_) that make cythonized code to be very dramatic in several asyncio frameworks. `asyncio.iscoroutine` work well with cythonized funcs for the silliest reason I think. Following the `cyfunctions` above, `create_token` is NOT a coroutine, while `init_connection` is an `async` function, **this workaround works in both so it's ok if you can schedule the functions whether are coros or not**, no way to easily fix this with `asyncio.iscoroutinefunction` or at least easier than that: ``` In [59]: async def test(): ...: await create_token({}) ...: In [61]: asyncio.get_event_loop().run_until_complete(test()) TypeError: object str can't be used in 'await' expression In [73]: async def test(): ...: return await init_connection() Out[74]: <asyncpg.pool.Pool at 0x7f78e04752c8> ``` Here comes the magic: ``` In [69]: async def test(): ...: return await asyncio.coroutine(create_token)({}) In [70]: asyncio.get_event_loop().run_until_complete(test()) Out[70]: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1MjU1NTk0NTB9.v8wRZGIke6RYizIpJhl4oaypKyvuVARKaiq0KdpJg6XJ0qTB0o76BuTLera6kSQ_5qXnAb7_9DQSadwdRqgPmw' In [71]: async def test(): ...: return await asyncio.coroutine(init_connection)() In [72]: asyncio.get_event_loop().run_until_complete(test()) Out[72]: <asyncpg.pool.Pool at 0x7f78df48af48> ``` With that the workaround: ```python def nasty_iscoroutinefunction(func): is_coro = asyncio. iscoroutinefunction(func) if func.__class__.__name__ == 'cython_function_or_method': # It's cythonized, danger! is_coro = True # We'll make it possible func = asyncio.coroutine(func) return is_coro ``` This works!
Found an interesting, better and working workaround: https://github.com/timothycrosley/hug/blob/develop/hug/introspect.py#L33 ```python def is_coroutinefunction(function): """Returns True if the passed in function is a coroutine""" return function.__code__.co_flags & 0x0080 or getattr(function, '_is_coroutine', False) ``` Is there plans to fix this? @danigosa, AFAIR you suggest to replace `asyncio.iscoroutinefunction` in `asyncio` module, but I think this should be fixed on cython side instead, so the original `asyncio` method will work as expected. Hm, it looks like [tests](https://github.com/cython/cython/blob/master/tests/run/test_coroutines_pep492.pyx#L876) with code similar to [inspect.py](https://github.com/python/cpython/blob/789e359f51d2b27bea01b8c6c3bf090aaedf8839/Lib/inspect.py#L180) are disabled. The problem is that if we make Cython coroutines look too much like Python coroutines at the C level (e,g, by setting the `CO_COROUTINE` flag on them), then CPython might start doing things with them that it shouldn't. Even if we find that it doesn't do that right now, it might change at any time, and then people have their Cython modules out there that break. So this is risky business. Similarly, unconditionally patching `inspect` might have unfortunate side effects as well, even if requires an opt-in. It's impossible to guess what mixture of code end users will have on their systems. @scoder I'm half way to make PR to add `CO_COROUTINE` to coroutine wrappers. But if it will not be accepted anyway, I will stop. AFAIR, right now c wrapper looks like: ``` python def c_wrapper(...): return coroutine(...) ``` It looks like this can be changed to ``` python @types.coroutine def c_wrapper(...): return (yield from coroutine(...)) ``` In this case all stuff is on python shoulders. @scoder I have made some dirty hack and it looks like it works. Any thoughts about such solution? https://github.com/pohmelie/cython/commit/5a84869a731c848d135bf098180b5711e18ca6e3 ``` python import asyncio async def foo(): pass print("foo", foo.__code__.co_flags) print("foo", asyncio.iscoroutinefunction(foo)) print(__cython_coroutine_wrapper) ``` compiled code output: ``` ('foo', 319) ('foo', True) <function coroutine at 0x7f30b9a0e620> ``` Linked code is not working in all cases, it is just quick proof of concept. By the way, I can't find any problem with add `CO_COROUTINE` flag, since ``` python async def afoo(): ... ``` is same as ``` python def foo(): return afoo() ``` you can `await foo()` and it will be absolutely same as `await afoo()`. There is at least this code in CPython, which I'd rather not want to trigger for Cython coroutines: https://github.com/python/cpython/blob/caba55b3b735405b280273f7d99866a046c18281/Python/ceval.c#L3906-L3949 Can't say right now if it's possible to do that from Python code, probably via eval&friends. Also, what we are discussing here actually applies to these three functions in `inspect.py`: `isgeneratorfunction()`, `iscoroutinefunction()` and `isasyncgenfunction()`. https://github.com/python/cpython/blob/41254ebd5e4f40a2e095d8aaea60bf3973de4647/Lib/inspect.py#L171-L194 But why old-style `yield from` coroutines with `asyncio.coroutine` works fine? Why we can't just wrap new-style coroutines with same decorator on building ast step? @scoder Can you consider adding new flags like `CO_CYTHON_COROUTINE`? I'm using Starlette, [it requires asyncio.iscoroutinefunction() to distinguish coroutine functions](https://github.com/encode/starlette/blob/474b499141f2a2b6b7d7c203b8d1a248c45cb160/starlette/routing.py#L35). I can't fix it because Cython hides everything about coroutine functions. Can't starlette do a type-check against the Coroutine ABC instead? How can I know a function will return a coroutine without call it? > How can I know a function will return a coroutine without call it? You cannot. There is no way to do that. It's called the "halting problem". https://en.wikipedia.org/wiki/Halting_problem But CPython can: ```python >>> async def f(): ... pass ... >>> import inspect >>> inspect.iscoroutinefunction(f) True >>> import asyncio >>> asyncio.iscoroutinefunction(f) True ``` No, it can't: ```python >>> async def func(): pass >>> import inspect >>> inspect.iscoroutinefunction(func) True >>> def retfunc(): return func() >>> inspect.iscoroutinefunction(retfunc) False >>> type(func()) <class 'coroutine'> >>> type(retfunc()) <class 'coroutine'> ``` Is there currrently a way to test if a cython function or method is async? Without that, we can't programmatically fix it even on a case-by-case basis... There doesn't have to be anything special about a callable that returns an awaitable. It does not have to be an async function. It can be any callable, even including a class. The idea of guessing the return type of a callable, without actually looking at the type of the object that it returns, seems inherently flawed to me. IMHO, the work-around is to call the callable and look at the value it returns. If that is something to await, then await it. If not, then not. However, as a clean fix, I would suggest to _always_ require/pass/return something that is awaitable, and not handle the callables differently based on _their_ type. > the work-around is to call the callable and look at the value it returns I think it is bad. Since this promotes bad practice of callable returns awaitable vs awaitable is callable. This should not work like this. I don't really care that a regular function may return an awaitable, I care about compatibility (or a possibility of compatibility) with CPython. For CPython, `iscoroutinefunction` returns true if the function was defined with async. As far as I can tell, Cython does not expose this information in any way. There may be reasons for `object.__code__.co_flags & CO_COROUTINE` to not be true for async functions in Cython - but at a minimum *there must be a programmatic way to determine that a function was defined with async*. I'll accept a PR that adds an `_is_coroutine` flag to `CyFunction` and sets it for async functions. ~~There are already tests in `test_coroutine_pep492.pyx` that have their call to `inspect.iscoroutinefunction()` commented out. Note that this file is copied from CPython, so don't change it too much. Just enable those lines for the CPython versions (`sys.version_info`) that support them.~~ EDIT: sorry, we are aiming for `asyncio.iscoroutinefunction()` in this ticket, not `inspect.iscoroutinefunction()`. The test to extend is `tests/run/asyncio_generators.srctree`. @pohmelie "callable returns awaitable vs awaitable is callable" – note that for async functions, the callable is the function, and the awaitable is the return value of the call. An async function (object) is not awaitable. > There doesn't have to be anything special about a callable that returns an awaitable. > (...) > IMHO, the work-around is to call the callable and look at the value it returns. If that is something to await, then await it. If not, then not. @scoder for good or bad, Python really does not make a lot of distinctions between async / sync functions. When writing tests though, we do mock things that maybe sync / async and calling them to see if they are sync / async is just not an option. Knowing *before* calling, is extremely useful, as it enables mocks to detect bugs (eg: mocking an async function with a sync function). This is how I bumped into this bug. I work on [TestSlide](https://github.com/facebookincubator/TestSlide), which Facebook open sourced last year. The gist of it is that its mocks have significantly more interface validation than vanilla `Mock(spec=...)`. When asyncio support was added recently, `iscoroutinefunction` was used to [validate mocking of sync / async methods](https://github.com/facebookincubator/TestSlide), which turned out to be completely broken for [Thrift](https://github.com/facebook/fbthrift) clients, which are all Cython async. Perhaps having `cython.iscoroutinefunction` would be simpler to implement, so we can start using right on? I have limited bandwidth at the moment to deeply dig into this, but with some nice pointers to where to look, I might be able to craft a PR for this. Just for tracking, the corresponding python issue: https://bugs.python.org/issue38225 And a related cython issue: #3143 Repeating my comment above here, so that people know what the status of this ticket is: I'll accept a PR that adds an _is_coroutine flag to CyFunction and sets it for async functions. I also agree with the proposal in https://bugs.python.org/issue38225 that there should be an actual protocol for this.
2020-03-13T19:12:40Z
[]
[]
cython/cython
3,429
cython__cython-3429
[ "2643" ]
bd990e4a3a3f821b395b58e6d68b0bbd8f406241
diff --git a/Cython/Shadow.py b/Cython/Shadow.py --- a/Cython/Shadow.py +++ b/Cython/Shadow.py @@ -146,14 +146,16 @@ def compile(f): # Special functions def cdiv(a, b): - q = a / b - if q < 0: - q += 1 - return q + if a < 0: + a = -a + b = -b + if b < 0: + return (a + b + 1) // b + return a // b def cmod(a, b): r = a % b - if (a*b) < 0: + if (a * b) < 0 and r: r -= b return r
diff --git a/tests/run/cdivision_CEP_516.pyx b/tests/run/cdivision_CEP_516.pyx --- a/tests/run/cdivision_CEP_516.pyx +++ b/tests/run/cdivision_CEP_516.pyx @@ -27,6 +27,9 @@ True >>> [test_cdiv_cmod(a, b) for a, b in v] [(1, 7), (-1, -7), (1, -7), (-1, 7)] +>>> [test_cdiv_cmod(a, b) for a, b in [(4, -4), (4, -2), (4, -1)]] +[(-1, 0), (-2, 0), (-4, 0)] + >>> all([mod_int_py(a,b) == a % b for a in range(-10, 10) for b in range(-10, 10) if b != 0]) True >>> all([div_int_py(a,b) == a // b for a in range(-10, 10) for b in range(-10, 10) if b != 0])
cdiv and cmod incorrect? I was looking at the definitions of `cdiv` and `cmod` in Shadow.py. These seem to give incorrect results for some operands. For example, in C99: ``` 4 / -4 == -1 4 % -4 == 0 4 / -2 == -2 4 % -2 == 0 4 / -1 == -4 4 % -1 == 0 ``` But these functions would return: ``` cdiv(4, -4) == 0 cmod(4, -4) == 4 cdiv(4, -2) == -1 cmod(4, -2) == 2 cdiv(4, -1) == -3 cmod(4, -1) == 1 ``` That's based on just running those definitions in the Python interpreter. Perhaps Cython handles them specially, and doesn't in fact give the incorrect results above. Still, why not include correct Python code? The following would work: ``` def cdiv(a, b): if a < 0: a = -a b = -b if b < 0: return (a + b + 1) // b return a // b def cmod(a, b): r = a % b if (a*b) < 0 and r: r -= b return r ``` Sorry if this is just me misunderstanding some magic behind the scenes stuff.
Thanks for looking at this! Please feel free to send a PR, or if you don't have the time I can fix them. You might want to make sure that your new functions work properly with the test found here: https://github.com/cython/cython/blob/master/tests/run/cdivision_CEP_516.pyx#L27-L28
2020-03-14T05:54:12Z
[]
[]
cython/cython
3,440
cython__cython-3440
[ "3419" ]
c5f2231ec462f23f53d5ec8d0963f8da6b7145cf
diff --git a/Cython/Build/Inline.py b/Cython/Build/Inline.py --- a/Cython/Build/Inline.py +++ b/Cython/Build/Inline.py @@ -141,6 +141,10 @@ def _populate_unbound(kwds, unbound_symbols, locals=None, globals=None): else: print("Couldn't find %r" % symbol) +def _inline_key(orig_code, arg_sigs, language_level): + key = orig_code, arg_sigs, sys.version_info, sys.executable, language_level, Cython.__version__ + return hashlib.sha1(_unicode(key).encode('utf-8')).hexdigest() + def cython_inline(code, get_type=unsafe_type, lib_dir=os.path.join(get_cython_cache_dir(), 'inline'), cython_include_dirs=None, cython_compiler_directives=None, @@ -150,13 +154,20 @@ def cython_inline(code, get_type=unsafe_type, get_type = lambda x: 'object' ctx = _create_context(tuple(cython_include_dirs)) if cython_include_dirs else _cython_inline_default_context + cython_compiler_directives = dict(cython_compiler_directives or {}) + if language_level is None and 'language_level' not in cython_compiler_directives: + language_level = '3str' + if language_level is not None: + cython_compiler_directives['language_level'] = language_level + # Fast path if this has been called in this session. _unbound_symbols = _cython_inline_cache.get(code) if _unbound_symbols is not None: _populate_unbound(kwds, _unbound_symbols, locals, globals) args = sorted(kwds.items()) arg_sigs = tuple([(get_type(value, ctx), arg) for arg, value in args]) - invoke = _cython_inline_cache.get((code, arg_sigs)) + key_hash = _inline_key(code, arg_sigs, language_level) + invoke = _cython_inline_cache.get((code, arg_sigs, key_hash)) if invoke is not None: arg_list = [arg[1] for arg in args] return invoke(*arg_list) @@ -177,12 +188,6 @@ def cython_inline(code, get_type=unsafe_type, # Parsing from strings not fully supported (e.g. cimports). print("Could not parse code as a string (to extract unbound symbols).") - cython_compiler_directives = dict(cython_compiler_directives or {}) - if language_level is None and 'language_level' not in cython_compiler_directives: - language_level = '3str' - if language_level is not None: - cython_compiler_directives['language_level'] = language_level - cimports = [] for name, arg in list(kwds.items()): if arg is cython_module: @@ -190,8 +195,8 @@ def cython_inline(code, get_type=unsafe_type, del kwds[name] arg_names = sorted(kwds) arg_sigs = tuple([(get_type(kwds[arg], ctx), arg) for arg in arg_names]) - key = orig_code, arg_sigs, sys.version_info, sys.executable, language_level, Cython.__version__ - module_name = "_cython_inline_" + hashlib.sha1(_unicode(key).encode('utf-8')).hexdigest() + key_hash = _inline_key(orig_code, arg_sigs, language_level) + module_name = "_cython_inline_" + key_hash if module_name in sys.modules: module = sys.modules[module_name] @@ -258,7 +263,7 @@ def __invoke(%(params)s): module = load_dynamic(module_name, module_path) - _cython_inline_cache[orig_code, arg_sigs] = module.__invoke + _cython_inline_cache[orig_code, arg_sigs, key_hash] = module.__invoke arg_list = [kwds[arg] for arg in arg_names] return module.__invoke(*arg_list)
diff --git a/Cython/Build/Tests/TestInline.py b/Cython/Build/Tests/TestInline.py --- a/Cython/Build/Tests/TestInline.py +++ b/Cython/Build/Tests/TestInline.py @@ -74,6 +74,18 @@ def test_compiler_directives(self): 6 ) + def test_lang_version(self): + # GH-3419. Caching for inline code didn't always respect compiler directives. + inline_divcode = "def f(int a, int b): return a/b" + self.assertEqual( + inline(inline_divcode, language_level=2)['f'](5,2), + 2 + ) + self.assertEqual( + inline(inline_divcode, language_level=3)['f'](5,2), + 2.5 + ) + if has_numpy: def test_numpy(self):
Caching for `cython.inline()` does not differentiate between different compiler configurations. ```python3 >>> cython.inline('def f(int a, int b):\n\treturn a/b\nreturn f', language_level=3)(5,2) 2.5 ``` ```python3 >>> cython.inline('def f(int a, int b):\n\treturn a/b\nreturn f', language_level=2)(5,2) 2 >>> cython.inline('def f(int a, int b):\n\treturn a/b\nreturn f', language_level=3)(5,2) 2 ```
Interesting. I had added the `language_level` to the module hash, but it seems to have no effect. https://github.com/cython/cython/blob/0b81c765bf9b23138b83311e07aacec74517e778/Cython/Build/Inline.py#L193-L194 I think that hash is being skipped entirely by the fast path at the very start of the function, which only takes into account the code string and (unbound?) argument signature: https://github.com/cython/cython/blob/0b81c765bf9b23138b83311e07aacec74517e778/Cython/Build/Inline.py#L153-L162
2020-03-17T01:06:46Z
[]
[]
cython/cython
3,514
cython__cython-3514
[ "3513" ]
a0e10cf604e62b6a08ba26c87e76d735a58988af
diff --git a/Cython/CodeWriter.py b/Cython/CodeWriter.py --- a/Cython/CodeWriter.py +++ b/Cython/CodeWriter.py @@ -1,7 +1,6 @@ """ Serializes a Cython code tree to Cython code. This is primarily useful for debugging and testing purposes. - The output is in a strict format, no whitespace or comments from the input is preserved (and it could not be as it is not present in the code tree). """ @@ -10,6 +9,7 @@ from .Compiler.Visitor import TreeVisitor from .Compiler.ExprNodes import * +from .Compiler.Nodes import CNameDeclaratorNode, CSimpleBaseTypeNode class LinesResult(object): @@ -80,6 +80,14 @@ def comma_separated_list(self, items, output_rhs=False): self.visit(item.default) self.put(u", ") self.visit(items[-1]) + if output_rhs and items[-1].default is not None: + self.put(u" = ") + self.visit(items[-1].default) + + def _visit_indented(self, node): + self.indent() + self.visit(node) + self.dedent() def visit_Node(self, node): raise AssertionError("Node not handled by serializer: %r" % node) @@ -96,9 +104,7 @@ def visit_CDefExternNode(self, node): else: file = u'"%s"' % node.include_file self.putline(u"cdef extern from %s:" % file) - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) def visit_CPtrDeclaratorNode(self, node): self.put('*') @@ -133,13 +139,12 @@ def visit_CSimpleBaseTypeNode(self, node): self.put("short " * -node.longness) elif node.longness > 0: self.put("long " * node.longness) - self.put(node.name) + if node.name is not None: + self.put(node.name) def visit_CComplexBaseTypeNode(self, node): - self.put(u'(') self.visit(node.base_type) self.visit(node.declarator) - self.put(u')') def visit_CNestedBaseTypeNode(self, node): self.visit(node.base_type) @@ -159,7 +164,7 @@ def visit_CVarDefNode(self, node): self.comma_separated_list(node.declarators, output_rhs=True) self.endline() - def visit_container_node(self, node, decl, extras, attributes): + def _visit_container_node(self, node, decl, extras, attributes): # TODO: visibility self.startline(decl) if node.name: @@ -188,7 +193,7 @@ def visit_CStructOrUnionDefNode(self, node): if node.packed: decl += u'packed ' decl += node.kind - self.visit_container_node(node, decl, None, node.attributes) + self._visit_container_node(node, decl, None, node.attributes) def visit_CppClassNode(self, node): extras = "" @@ -196,10 +201,10 @@ def visit_CppClassNode(self, node): extras = u"[%s]" % ", ".join(node.templates) if node.base_classes: extras += "(%s)" % ", ".join(node.base_classes) - self.visit_container_node(node, u"cdef cppclass", extras, node.attributes) + self._visit_container_node(node, u"cdef cppclass", extras, node.attributes) def visit_CEnumDefNode(self, node): - self.visit_container_node(node, u"cdef enum", None, node.items) + self._visit_container_node(node, u"cdef enum", None, node.items) def visit_CEnumDefItemNode(self, node): self.startline(node.name) @@ -225,9 +230,7 @@ def visit_CClassDefNode(self, node): self.put(node.base_class_name) self.put(u")") self.endline(u":") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) def visit_CTypeDefNode(self, node): self.startline(u"ctypedef ") @@ -241,14 +244,45 @@ def visit_FuncDefNode(self, node): self.startline(u"def %s(" % node.name) self.comma_separated_list(node.args) self.endline(u"):") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) + + def visit_CFuncDefNode(self, node): + self.startline(u'cpdef ' if node.overridable else u'cdef ') + if node.modifiers: + self.put(' '.join(node.modifiers)) + self.put(' ') + if node.visibility != 'private': + self.put(node.visibility) + self.put(u' ') + if node.api: + self.put(u'api ') + + if node.base_type: + self.visit(node.base_type) + if node.base_type.name is not None: + self.put(u' ') + + # visit the CFuncDeclaratorNode, but put a `:` at the end of line + self.visit(node.declarator.base) + self.put(u'(') + self.comma_separated_list(node.declarator.args) + self.endline(u'):') + + self._visit_indented(node.body) def visit_CArgDeclNode(self, node): - if node.base_type.name is not None: + # For "CSimpleBaseTypeNode", the variable type may have been parsed as type. + # For other node types, the "name" is always None. + if not isinstance(node.base_type, CSimpleBaseTypeNode) or \ + node.base_type.name is not None: self.visit(node.base_type) - self.put(u" ") + + # If we printed something for "node.base_type", we may need to print an extra ' '. + # + # Special case: if "node.declarator" is a "CNameDeclaratorNode", + # its "name" might be an empty string, for example, for "cdef f(x)". + if node.declarator.declared_name(): + self.put(u" ") self.visit(node.declarator) if node.default is not None: self.put(u" = ") @@ -328,14 +362,10 @@ def visit_ForInStatNode(self, node): self.put(u" in ") self.visit(node.iterator.sequence) self.endline(u":") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) if node.else_clause is not None: self.line(u"else:") - self.indent() - self.visit(node.else_clause) - self.dedent() + self._visit_indented(node.else_clause) def visit_IfStatNode(self, node): # The IfClauseNode is handled directly without a separate match @@ -343,21 +373,30 @@ def visit_IfStatNode(self, node): self.startline(u"if ") self.visit(node.if_clauses[0].condition) self.endline(":") - self.indent() - self.visit(node.if_clauses[0].body) - self.dedent() + self._visit_indented(node.if_clauses[0].body) for clause in node.if_clauses[1:]: self.startline("elif ") self.visit(clause.condition) self.endline(":") - self.indent() - self.visit(clause.body) - self.dedent() + self._visit_indented(clause.body) if node.else_clause is not None: self.line("else:") - self.indent() - self.visit(node.else_clause) - self.dedent() + self._visit_indented(node.else_clause) + + def visit_WhileStatNode(self, node): + self.startline(u"while ") + self.visit(node.condition) + self.endline(u":") + self._visit_indented(node.body) + if node.else_clause is not None: + self.line("else:") + self._visit_indented(node.else_clause) + + def visit_ContinueStatNode(self, node): + self.line(u"continue") + + def visit_BreakStatNode(self, node): + self.line(u"break") def visit_SequenceNode(self, node): self.comma_separated_list(node.args) # Might need to discover whether we need () around tuples...hmm... @@ -382,25 +421,17 @@ def visit_WithStatNode(self, node): self.put(u" as ") self.visit(node.target) self.endline(u":") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) def visit_TryFinallyStatNode(self, node): self.line(u"try:") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) self.line(u"finally:") - self.indent() - self.visit(node.finally_clause) - self.dedent() + self._visit_indented(node.finally_clause) def visit_TryExceptStatNode(self, node): self.line(u"try:") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) for x in node.except_clauses: self.visit(x) if node.else_clause is not None: @@ -415,9 +446,7 @@ def visit_ExceptClauseNode(self, node): self.put(u", ") self.visit(node.target) self.endline(":") - self.indent() - self.visit(node.body) - self.dedent() + self._visit_indented(node.body) def visit_ReturnStatNode(self, node): self.startline("return ") @@ -480,12 +509,18 @@ def comma_separated_list(self, items): def visit_Node(self, node): raise AssertionError("Node not handled by serializer: %r" % node) - def visit_NameNode(self, node): - self.put(node.name) + def visit_IntNode(self, node): + self.put(node.value) + + def visit_FloatNode(self, node): + self.put(node.value) def visit_NoneNode(self, node): self.put(u"None") + def visit_NameNode(self, node): + self.put(node.name) + def visit_EllipsisNode(self, node): self.put(u"...") @@ -756,12 +791,13 @@ def __call__(self, node): return node def visit_CFuncDefNode(self, node): - if 'inline' in node.modifiers: - return if node.overridable: self.startline(u'cpdef ') else: self.startline(u'cdef ') + if node.modifiers: + self.put(' '.join(node.modifiers)) + self.put(' ') if node.visibility != 'private': self.put(node.visibility) self.put(u' ')
diff --git a/Cython/Tests/TestCodeWriter.py b/Cython/Tests/TestCodeWriter.py --- a/Cython/Tests/TestCodeWriter.py +++ b/Cython/Tests/TestCodeWriter.py @@ -21,6 +21,7 @@ def test_print(self): self.t(u""" print(x + y ** 2) print(x, y, z) + print(x + y, x + y * z, x * (y + z)) """) def test_if(self): @@ -46,6 +47,20 @@ def f(x = 34, y = 54, z): pass """) + def test_cdef(self): + self.t(u""" + cdef f(x, y, z): + pass + cdef public void (x = 34, y = 54, z): + pass + cdef f(int *x, void *y, Value *z): + pass + cdef f(int **x, void **y, Value **z): + pass + cdef inline f(int &x, Value &z): + pass + """) + def test_longness_and_signedness(self): self.t(u"def f(unsigned long long long long long int y):\n pass") @@ -75,6 +90,14 @@ def test_for_loop(self): print(43) """) + def test_while_loop(self): + self.t(u""" + while True: + while True: + while True: + continue + """) + def test_inplace_assignment(self): self.t(u"x += 43")
CodeWriter doesn't work for 'CFuncDefNode' ```python >>> writer = CodeWriter() >>> writer.write(TreeFragment("def fn(): \n pass").root) <Cython.CodeWriter.LinesResult at 0x121704a90> >>> writer.write(TreeFragment("cdef fn(): \n pass").root) Compiler crash traceback from this point on: File "Cython/Compiler/Visitor.py", line 180, in Cython.Compiler.Visitor.TreeVisitor._visit File "/usr/local/lib/python3.7/site-packages/Cython/CodeWriter.py", line 243, in visit_FuncDefNode self.startline(u"def %s(" % node.name) AttributeError: 'CFuncDefNode' object has no attribute 'name' ```
Interesting to see that people are actually using this. :) PR welcome.
2020-04-14T08:21:47Z
[]
[]
cython/cython
3,549
cython__cython-3549
[ "3545" ]
5204d86989493855fdd0acd20debd9d0a270bb23
diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -417,6 +417,7 @@ def get_openmp_compiler_flags(language): 'run.test_raisefrom', 'run.different_package_names', 'run.unicode_imports', # encoding problems on appveyor in Py2 + 'run.reimport_failure', # reimports don't do anything in Py2 ]), (3,): (operator.ge, lambda x: x in ['run.non_future_division', 'compile.extsetslice',
diff --git a/tests/pypy_bugs.txt b/tests/pypy_bugs.txt --- a/tests/pypy_bugs.txt +++ b/tests/pypy_bugs.txt @@ -38,6 +38,7 @@ run.index run.pyclass_special_methods run.reimport_from_package run.reimport_from_subinterpreter +run.reimport_failure pkg.cimportfrom embedded TestCyCache diff --git a/tests/run/reimport_failure.srctree b/tests/run/reimport_failure.srctree new file mode 100644 --- /dev/null +++ b/tests/run/reimport_failure.srctree @@ -0,0 +1,38 @@ +# mode: run +# tag: pep489 + +""" +PYTHON setup.py build_ext -i +PYTHON tester.py +""" + +######## setup.py ######## + +from Cython.Build.Dependencies import cythonize +from distutils.core import setup + +setup( + ext_modules = cythonize("*.pyx"), +) + + +######## failure.pyx ######## + +if globals(): # runtime True to confuse dead code removal + raise ImportError + +cdef class C: + cdef int a + + +######## tester.py ######## + +try: + try: + import failure # 1 + except ImportError: + import failure # 2 +except ImportError: + pass +else: + raise RuntimeError("ImportError was not raised on second import!")
Misleading __reduce_cython__ error on import Whenever you use an `import` instead of a `cimport` compiling will work but you might be graced with an unrelated error message at import time. Can't create easily a self-contained test: I tried and the code was failing with an expected `ImportError`, however you can reproduce it it with: ```bash git clone [email protected]:psycopg/psycopg3.git mypyerr cd mypyerr git checkout 5647fb04dc6eb3e46e2a7bde490feea5be11f2c1 cat <<HERE | patch -p1 --- a/psycopg3/types/text.pyx +++ b/psycopg3/types/text.pyx @@ -1,3 +1,4 @@ +from cpython.unicode import PyUnicode_DecodeAscii from cpython.unicode cimport PyUnicode_DecodeUTF8 cdef object load_text_binary(const char *data, size_t length, void *context): HERE python setup.py develop python -c "import psycopg3._psycopg3" ``` Which raises the error: ``` Traceback (most recent call last): File "<string>", line 1, in <module> File "psycopg3/pq/pq_cython.pyx", line 34, in init psycopg3._psycopg3 cdef class PGconn: AttributeError: type object 'psycopg3._psycopg3.PGconn' has no attribute '__reduce_cython__' ``` I believe many help requests about `__reduce_cython__` are related to this. Tested with Python 3.6 and Cython 3.0a1.
> I believe many help requests about `__reduce_cython__` are related to this. I'm not so sure. This ticket is about a programming error, and pretty much all cases I've seen so far seemed to involve pip installations or some kind of build setup problem instead. Specifically, whenever a module reloading attempt is involved, this error can occur. There's this code these days: https://github.com/cython/cython/blob/fcb44032968d8893ead5c63c7554d293d370ec1b/Cython/Compiler/ModuleNode.py#L2676-L2689 So we already raise an exception on attempts to import a module twice, and prevent re-initialising the same module instance more than once. I can't say right now why these two cases don't produce a better error message (or actually work) in your case. Investigation welcome. It could actually be that attempts to re-initialise the module come after first clearing the module dict. That would (obviously) break things, and if that's the case, then we need to find a way to actually rebuild the module dict. Or, more simply, *always* raise an exception on re-initialisation attempts. (Or keep track of full init-clear cycles, or something like that.) I already ran into this issue two or three times myself, but not yet with one of the Cython 3.0 alpha releases, so no comment about the module loading/reinitialization improvements yet. I however noticed that those errors always pop up whenever I have unnoticed cyclic imports in my code. The only problem about this error is that it doesn't say anything about it. I started googling what this method __reduce_cython__ actually is, what it does and what problems it might cause, but the actual problem was never mentioned. It took me quite a bit of time to figure it out, and now i'm much smarter in that regard, but if this error also pops up in Cython 3, I can imagine newbies getting stuck for several days with it as well. @Timtam If you have an example of the code that caused this error then it'd be useful. The example given in this issues had too many external dependencies for me to get it to run so something a bit simpler and easier to diagnose would definitely be good (if it exists) I don't have an example right now, but I might be able to put one together if I don't forget about it and find the time to do so. I'll comment if I found something out. Right: I have a simple reproducible 2-file example of this error: ``` # mod1.pyx if globals(): # don't know why the if-statement is needed. Otherwise I get an "undefined symbol error" raise ImportError cdef class C: cdef int a ``` mod1 can be compiled with `cythonize -if mod1.pyx` ``` # tester.py try: import mod1 except: import mod1 # have another go ``` Running `python tester.py` gives: AttributeError: type object 'mod1.C' has no attribute '__reduce_cython__' > "undefined symbol error" Could be due to dead code removal when the last statement is known to raise, i.e. when there is no success return case. @da-woods hmm, I tried your example in Py3.[678] with latest master but got the expected (chained) `ImportError` in both cases, not the `AttributeError`. Ah. I think I was testing it on the 0.29 branch. You're right - it seems OK in master. It's clearly harder to reproduce than I thought @scoder Move the exception before the class definition and it does break in master though. I've edited the example above
2020-04-24T21:00:25Z
[]
[]
cython/cython
3,599
cython__cython-3599
[ "3038" ]
fd71aabe0319ff3ecfa3aee291d13b98d3c6a76e
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -4207,6 +4207,9 @@ def create_from_py_utility_code(self, env): env.use_utility_code(self._convert_from_py_code) return True + def cast_code(self, expr_code): + return expr_code + def c_tuple_type(components): components = tuple(components)
diff --git a/tests/windows_bugs.txt b/tests/windows_bugs.txt --- a/tests/windows_bugs.txt +++ b/tests/windows_bugs.txt @@ -6,7 +6,6 @@ initial_file_path package_compilation carray_coercion -ctuple int_float_builtins_as_casts_T400 int_float_builtins_as_casts_T400_long_double list_pop
compiler crash with ctuple as property setter argument * Cython version: 0.29.12 * Compiler used: Visual Studio 2015 (MSVC) * Python version: Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Following small code example, named crash.pyx: ``` cdef class Foo: property bar: def __set__(Foo self, (int, int) value): print(value[0], value[1]) ``` Running with python -c "import pyximport;pyximport.install();import crash" cythonizes properly, but compilation crashes: ...\.pyxbld\temp.win32-3.6\Release\pyrex\crash.c(1286): error C2440: "Typumwandlung": "__pyx_ctuple_int__and_int" kann nicht in "__pyx_ctuple_int__and_int" konvertiert werden ...\.pyxbld\temp.win32-3.6\Release\pyrex\crash.c(1286): error C2198: "__pyx_pf_5crash_3Foo_3bar___set__": Nicht gengend Argumente fr Aufruf. Cythonized crash.c file attached. Problem is not pyximport-related and also crashes when used "normally". [crash.zip](https://github.com/cython/cython/files/3376458/crash.zip)
2020-05-11T23:39:17Z
[]
[]
cython/cython
3,605
cython__cython-3605
[ "3090" ]
917dbeef5422b3ef49874d60bbb70c294c5c45e2
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -3663,8 +3663,8 @@ def generate_stararg_copy_code(self, code): code.globalstate.use_utility_code( UtilityCode.load_cached("RaiseArgTupleInvalid", "FunctionArguments.c")) code.putln("if (unlikely(%s > 0)) {" % Naming.nargs_cname) - code.put('__Pyx_RaiseArgtupleInvalid("%s", 1, 0, 0, %s); return %s;' % ( - self.name, Naming.nargs_cname, self.error_value())) + code.put('__Pyx_RaiseArgtupleInvalid(%s, 1, 0, 0, %s); return %s;' % ( + self.name.as_c_string_literal(), Naming.nargs_cname, self.error_value())) code.putln("}") if self.starstar_arg: @@ -3678,8 +3678,8 @@ def generate_stararg_copy_code(self, code): code.globalstate.use_utility_code( UtilityCode.load_cached("KeywordStringCheck", "FunctionArguments.c")) code.putln( - "if (%s && unlikely(!__Pyx_CheckKeywordStrings(%s, \"%s\", %d))) return %s;" % ( - kwarg_check, Naming.kwds_cname, self.name, + "if (%s && unlikely(!__Pyx_CheckKeywordStrings(%s, %s, %d))) return %s;" % ( + kwarg_check, Naming.kwds_cname, self.name.as_c_string_literal(), bool(self.starstar_arg), self.error_value())) if self.starstar_arg and self.starstar_arg.entry.cf_used: diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -180,7 +180,7 @@ def get_directive_defaults(): 'cdivision_warnings': False, 'overflowcheck': False, 'overflowcheck.fold': True, - 'always_allow_keywords': False, + 'always_allow_keywords': True, 'allow_none_for_extension_args': True, 'wraparound' : True, 'ccomplex' : False, # use C99/C++ for complex types and arith
diff --git a/tests/buffers/bufaccess.pyx b/tests/buffers/bufaccess.pyx --- a/tests/buffers/bufaccess.pyx +++ b/tests/buffers/bufaccess.pyx @@ -960,6 +960,7 @@ def decref(*args): for item in args: Py_DECREF(item) @cython.binding(False) [email protected]_allow_keywords(False) def get_refcount(x): return (<PyObject*>x).ob_refcnt diff --git a/tests/compile/fused_redeclare_T3111.pyx b/tests/compile/fused_redeclare_T3111.pyx --- a/tests/compile/fused_redeclare_T3111.pyx +++ b/tests/compile/fused_redeclare_T3111.pyx @@ -22,9 +22,9 @@ def foo(dtype_t[:] a, dtype_t_out[:, :] b): # "__pyxutil:16:4: '___pyx_npy_uint8' redeclared". The remaining warnings are # unrelated to this test. _WARNINGS = """ -# cpdef redeclaration bug -22:10: 'cpdef_method' redeclared -33:10: 'cpdef_cname_method' redeclared +# cpdef redeclaration bug, from TestCythonScope.pyx +25:10: 'cpdef_method' redeclared +36:10: 'cpdef_cname_method' redeclared # from MemoryView.pyx 984:29: Ambiguous exception value, same as default return value: 0 984:29: Ambiguous exception value, same as default return value: 0 diff --git a/tests/memoryview/memoryview.pyx b/tests/memoryview/memoryview.pyx --- a/tests/memoryview/memoryview.pyx +++ b/tests/memoryview/memoryview.pyx @@ -627,6 +627,7 @@ def decref(*args): for item in args: Py_DECREF(item) @cython.binding(False) [email protected]_allow_keywords(False) def get_refcount(x): return (<PyObject*>x).ob_refcnt diff --git a/tests/memoryview/memslice.pyx b/tests/memoryview/memslice.pyx --- a/tests/memoryview/memslice.pyx +++ b/tests/memoryview/memslice.pyx @@ -1059,6 +1059,7 @@ def decref(*args): for item in args: Py_DECREF(item) @cython.binding(False) [email protected]_allow_keywords(False) def get_refcount(x): return (<PyObject*>x).ob_refcnt diff --git a/tests/run/always_allow_keywords_T295.pyx b/tests/run/always_allow_keywords_T295.pyx --- a/tests/run/always_allow_keywords_T295.pyx +++ b/tests/run/always_allow_keywords_T295.pyx @@ -1,7 +1,12 @@ +# mode: run # ticket: 295 cimport cython +import sys +IS_PY2 = sys.version_info[0] == 2 + + def assert_typeerror_no_keywords(func, *args, **kwds): # Python 3.9 produces an slightly different error message # to previous versions, so doctest isn't matching the @@ -14,13 +19,18 @@ def assert_typeerror_no_keywords(func, *args, **kwds): assert False, "call did not raise TypeError" +def func0(): + """ + >>> func0() + >>> func0(**{}) + """ + def func1(arg): """ >>> func1(None) >>> func1(*[None]) - >>> assert_typeerror_no_keywords(func1, arg=None) + >>> func1(arg=None) """ - pass @cython.always_allow_keywords(False) def func2(arg): @@ -29,7 +39,6 @@ def func2(arg): >>> func2(*[None]) >>> assert_typeerror_no_keywords(func2, arg=None) """ - pass @cython.always_allow_keywords(True) def func3(arg): @@ -40,26 +49,132 @@ def func3(arg): """ pass + cdef class A: """ - >>> A().meth1(None) - >>> A().meth1(*[None]) - >>> assert_typeerror_no_keywords(A().meth1, arg=None) - >>> A().meth2(None) - >>> A().meth2(*[None]) - >>> assert_typeerror_no_keywords(A().meth2, arg=None) - >>> A().meth3(None) - >>> A().meth3(*[None]) - >>> A().meth3(arg=None) + >>> class PyA(object): + ... def meth0(self): pass + ... def meth1(self, arg): pass + + >>> PyA().meth0() + >>> PyA.meth0(PyA()) + >>> if not IS_PY2: PyA.meth0(self=PyA()) + >>> try: PyA().meth0(self=PyA()) + ... except TypeError as exc: assert 'multiple' in str(exc), "Unexpected message: %s" % exc + ... else: assert False, "No TypeError when passing 'self' argument twice" + + >>> PyA().meth1(1) + >>> PyA.meth1(PyA(), 1) + >>> PyA.meth1(PyA(), arg=1) + >>> if not IS_PY2: PyA.meth1(self=PyA(), arg=1) """ + @cython.always_allow_keywords(False) + def meth0_nokw(self): + """ + >>> A().meth0_nokw() + >>> A().meth0_nokw(**{}) + >>> try: pass #A.meth0_nokw(self=A()) + ... except TypeError as exc: assert 'needs an argument' in str(exc), "Unexpected message: %s" % exc + ... else: pass #assert False, "No TypeError for missing 'self' positional argument" + """ + + @cython.always_allow_keywords(True) + def meth0_kw(self): + """ + >>> A().meth0_kw() + >>> A().meth0_kw(**{}) + >>> A.meth0_kw(A()) + >>> #A.meth0_kw(self=A()) + >>> try: pass #A().meth0_kw(self=A()) + ... except TypeError as exc: assert 'multiple' in str(exc), "Unexpected message: %s" % exc + ... else: pass #assert False, "No TypeError when passing 'self' argument twice" + """ + + @cython.always_allow_keywords(True) + def meth1_kw(self, arg): + """ + >>> A().meth1_kw(None) + >>> A().meth1_kw(*[None]) + >>> A().meth1_kw(arg=None) + >>> A.meth1_kw(A(), arg=None) + >>> #A.meth1_kw(self=A(), arg=None) + """ + + @cython.always_allow_keywords(False) + def meth1_nokw(self, arg): + """ + >>> A().meth1_nokw(None) + >>> A().meth1_nokw(*[None]) + >>> assert_typeerror_no_keywords(A().meth1_nokw, arg=None) + >>> assert_typeerror_no_keywords(A.meth1_nokw, A(), arg=None) + >>> try: pass # A.meth1_nokw(self=A(), arg=None) + ... except TypeError as exc: assert 'needs an argument' in str(exc), "Unexpected message: %s" % exc + ... else: pass # assert False, "No TypeError for missing 'self' positional argument" + """ + + @cython.always_allow_keywords(False) + def meth2(self, arg): + """ + >>> A().meth2(None) + >>> A().meth2(*[None]) + >>> assert_typeerror_no_keywords(A().meth2, arg=None) + """ + + @cython.always_allow_keywords(True) + def meth3(self, arg): + """ + >>> A().meth3(None) + >>> A().meth3(*[None]) + >>> A().meth3(arg=None) + """ + + +class B(object): + @cython.always_allow_keywords(False) + def meth0_nokw(self): + """ + >>> B().meth0_nokw() + >>> B().meth0_nokw(**{}) + >>> if not IS_PY2: assert_typeerror_no_keywords(B.meth0_nokw, self=B()) + """ + + @cython.always_allow_keywords(True) + def meth0_kw(self): + """ + >>> B().meth0_kw() + >>> B().meth0_kw(**{}) + >>> B.meth0_kw(B()) + >>> if not IS_PY2: B.meth0_kw(self=B()) + >>> try: B().meth0_kw(self=B()) + ... except TypeError as exc: assert 'multiple' in str(exc), "Unexpected message: %s" % exc + ... else: assert False, "No TypeError when passing 'self' argument twice" + """ + + @cython.always_allow_keywords(True) def meth1(self, arg): - pass + """ + >>> B().meth1(None) + >>> B().meth1(*[None]) + >>> B().meth1(arg=None) + >>> B.meth1(B(), arg=None) + >>> if not IS_PY2: B.meth1(self=B(), arg=None) + """ @cython.always_allow_keywords(False) def meth2(self, arg): - pass + """ + >>> B().meth2(None) + >>> B().meth2(*[None]) + >>> B.meth2(B(), None) + >>> if not IS_PY2: B.meth2(self=B(), arg=None) + >>> B().meth2(arg=None) # assert_typeerror_no_keywords(B().meth2, arg=None) -> not a cdef class! + """ @cython.always_allow_keywords(True) def meth3(self, arg): - pass + """ + >>> B().meth3(None) + >>> B().meth3(*[None]) + >>> B().meth3(arg=None) + """ diff --git a/tests/run/cyfunction_METH_O_GH1728.pyx b/tests/run/cyfunction_METH_O_GH1728.pyx --- a/tests/run/cyfunction_METH_O_GH1728.pyx +++ b/tests/run/cyfunction_METH_O_GH1728.pyx @@ -8,9 +8,9 @@ cdef class TestMethodOneArg: def call_meth(x): """ - >>> call_meth(TestMethodOneArg()) + >>> call_meth(TestMethodOneArg()) # doctest: +ELLIPSIS Traceback (most recent call last): ... - TypeError: meth() takes exactly one argument (0 given) + TypeError: meth() takes exactly ... argument (0 given) """ return x.meth() diff --git a/tests/run/exceptionrefcount.pyx b/tests/run/exceptionrefcount.pyx --- a/tests/run/exceptionrefcount.pyx +++ b/tests/run/exceptionrefcount.pyx @@ -27,8 +27,11 @@ __doc__ = u""" >>> run_test(50, test_finally) """ +cimport cython from cpython.ref cimport PyObject [email protected](False) [email protected]_allow_keywords(False) def get_refcount(obj): return (<PyObject*>obj).ob_refcnt diff --git a/tests/run/refcount_in_meth.pyx b/tests/run/refcount_in_meth.pyx --- a/tests/run/refcount_in_meth.pyx +++ b/tests/run/refcount_in_meth.pyx @@ -12,8 +12,10 @@ True True """ +cimport cython from cpython.ref cimport PyObject [email protected]_allow_keywords(False) def get_refcount(obj): return (<PyObject*>obj).ob_refcnt diff --git a/tests/run/unicode_identifiers.pyx b/tests/run/unicode_identifiers.pyx --- a/tests/run/unicode_identifiers.pyx +++ b/tests/run/unicode_identifiers.pyx @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- -# cython: language_level=3 # mode: run # tag: pep3131, traceback +# cython: language_level=3 + # Code with unicode identifiers can be compiled with Cython running either Python 2 or 3. # However Python access to unicode identifiers is only possible in Python 3. In Python 2 # it's only really safe to use the unicode identifiers for purely Cython interfaces @@ -11,10 +12,13 @@ # This is controlled by putting the Python3 only tests in the module __doc__ attribute # Most of the individual function and class docstrings are only present as a compile test +cimport cython + import sys -if sys.version_info[0]>2: - __doc__ = """ + +if sys.version_info[0] > 2: + __doc__ = u""" >>> f()() 2 >>> f().__name__ @@ -37,6 +41,9 @@ if sys.version_info[0]>2: >>> print(x.α) 200 + >>> B().Ƒ() + >>> C().Ƒ() + Test generation of locals() >>> sorted(Γναμε2().boring_function(1,2).keys()) ['self', 'somevalue', 'x', 'ναμε5', 'ναμε6'] @@ -45,6 +52,8 @@ if sys.version_info[0]>2: 0 >>> function_taking_fancy_argument(Γναμε2()).ναμε3 1 + >>> metho_function_taking_fancy_argument(Γναμε2()).ναμε3 + 1 >>> NormalClassΓΓ().ναμε 10 >>> NormalClassΓΓ().εxciting_function(None).__qualname__ @@ -81,7 +90,7 @@ cdef class A: def __init__(self): self.ναμε = 1 cdef Ƒ(self): - return self.ναμε==1 + return self.ναμε == 1 def regular_function(self): """ Can use unicode cdef functions and (private) attributes internally @@ -174,9 +183,16 @@ cdef class Derived(Γναμε2): cdef Γναμε2 global_ναμε3 = Γναμε2() + [email protected]_allow_keywords(False) # METH_O signature +def metho_function_taking_fancy_argument(Γναμε2 αrγ): + return αrγ + [email protected]_allow_keywords(True) def function_taking_fancy_argument(Γναμε2 αrγ): return αrγ + class NormalClassΓΓ(Γναμε2): """ docstring
Single-argument functions cannot be called using keyword ``` In [1]: %load_ext cython In [2]: %%cython ...: def f(k): return k In [3]: f(k=1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-2f40ef43e783> in <module>() ----> 1 f(k=1) TypeError: f() takes no keyword arguments ```
The problem is very obvious in retrospect: single-argument functions use `METH_O` which do not accept keywords. The question is what to do with this, given that nobody complained about this so far. I only found this out when trying some edge-cases for #3021. There is a compiler setting to always allow keywords, also for METH_O functions. Hmm, on second thought, I wonder if it's worth changing the default setting, now that we have all that fast-calling integration? I now think that Cython 3.0 is a good time to change the default setting. Let's just do that.
2020-05-12T20:41:45Z
[]
[]
cython/cython
3,631
cython__cython-3631
[ "3575" ]
d2d299322d74e539fc95cd92de712ec41fb83fb8
diff --git a/Cython/Compiler/FlowControl.py b/Cython/Compiler/FlowControl.py --- a/Cython/Compiler/FlowControl.py +++ b/Cython/Compiler/FlowControl.py @@ -885,6 +885,12 @@ def visit_Node(self, node): self.mark_position(node) return node + def visit_SizeofVarNode(self, node): + return node + + def visit_TypeidNode(self, node): + return node + def visit_IfStatNode(self, node): next_block = self.flow.newblock() parent = self.flow.block
diff --git a/tests/errors/w_uninitialized.pyx b/tests/errors/w_uninitialized.pyx --- a/tests/errors/w_uninitialized.pyx +++ b/tests/errors/w_uninitialized.pyx @@ -112,6 +112,10 @@ def class_py3k_args(): args = [] kwargs = {} +def uninitialized_in_sizeof(): + cdef int i + print sizeof(i) + _ERRORS = """ 6:10: local variable 'a' referenced before assignment 12:11: local variable 'a' might be referenced before assignment diff --git a/tests/errors/w_uninitialized_cpp.pyx b/tests/errors/w_uninitialized_cpp.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/w_uninitialized_cpp.pyx @@ -0,0 +1,12 @@ +# cython: warn.maybe_uninitialized=True +# mode: error +# tag: cpp, werror + +from cython.operator import typeid + +def uninitialized_in_typeid(): + cdef int i + print typeid(i) == typeid(i) + +_ERRORS = """ +"""
Referencing local variable before assignment is safe inside sizeof Referencing a variable before it is assigned to anything is usually a bad idea. It is, however, perfectly valid to do so inside the `sizeof` operator. It's even a common pattern in C when using `malloc` / `calloc`. This program produce a warning, while it should probably not. ```cython def main(): cdef int x print(sizeof(x)) main() ```
True. Can't say how difficult it is to fix, though. Maybe we could special-case `sizeof()`, and probably also `typeid()`, `varargs()` and maybe others(?) in the control flow analysis somehow, so that they won't consider the variable an actual usage.
2020-05-24T21:36:11Z
[]
[]
cython/cython
3,634
cython__cython-3634
[ "1911" ]
fba0673a877290ab3374346343c2ac554ba90ade
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -5934,6 +5934,17 @@ def generate_evaluation_code(self, code): if function.is_name or function.is_attribute: code.globalstate.use_entry_utility_code(function.entry) + abs_function_cnames = ('abs', 'labs', '__Pyx_abs_longlong') + is_signed_int = self.type.is_int and self.type.signed + if self.overflowcheck and is_signed_int and function.result() in abs_function_cnames: + code.globalstate.use_utility_code(UtilityCode.load_cached("Common", "Overflow.c")) + code.putln('if (unlikely(%s == __PYX_MIN(%s))) {\ + PyErr_SetString(PyExc_OverflowError,\ + "Trying to take the absolute value of the most negative integer is not defined."); %s; }' % ( + self.args[0].result(), + self.args[0].type.empty_declaration_code(), + code.error_goto(self.pos))) + if not function.type.is_pyobject or len(self.arg_tuple.args) > 1 or ( self.arg_tuple.args and self.arg_tuple.is_literal): super(SimpleCallNode, self).generate_evaluation_code(code) @@ -6036,13 +6047,7 @@ def generate_result_code(self, code): self.result() if self.type.is_pyobject else None, func_type.exception_value, self.nogil) else: - if (self.overflowcheck - and self.type.is_int - and self.type.signed - and self.function.result() in ('abs', 'labs', '__Pyx_abs_longlong')): - goto_error = 'if (unlikely(%s < 0)) { PyErr_SetString(PyExc_OverflowError, "value too large"); %s; }' % ( - self.result(), code.error_goto(self.pos)) - elif exc_checks: + if exc_checks: goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos) else: goto_error = ""
diff --git a/tests/run/builtin_abs.pyx b/tests/run/builtin_abs.pyx --- a/tests/run/builtin_abs.pyx +++ b/tests/run/builtin_abs.pyx @@ -1,5 +1,6 @@ # mode: run # ticket: 698 +# distutils: extra_compile_args=-fwrapv cdef extern from *: int INT_MAX
Overflow error in doctests I am trying to build Cython 0.27 and 0.27.1 for openSUSE and I am getting an OverFlow error in the docstests when I run `python3 runtests.py -vv` (but not for python2) under an x86_64 architecture. This works fine up to Cython 0.26.1, but fails for 0.27 and 0.27.1 in the same way. We are using python 3.6.2 and 2.7.13 and gcc 7.2.1. ``` ====================================================================== FAIL: int_abs (builtin_abs) Doctest: builtin_abs.int_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.int_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in int_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.int_abs Failed example: int_abs(-max_int-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -2147483648 ====================================================================== FAIL: long_abs (builtin_abs) Doctest: builtin_abs.long_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.long_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in long_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.long_abs Failed example: long_abs(-max_long-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -9223372036854775808 ====================================================================== FAIL: long_long_abs (builtin_abs) Doctest: builtin_abs.long_long_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.long_long_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in long_long_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/c/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.long_long_abs Failed example: long_long_abs(-max_long_long-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -9223372036854775808 ====================================================================== FAIL: int_abs (builtin_abs) Doctest: builtin_abs.int_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.int_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in int_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.int_abs Failed example: int_abs(-max_int-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -2147483648 ====================================================================== FAIL: long_abs (builtin_abs) Doctest: builtin_abs.long_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.long_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in long_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.long_abs Failed example: long_abs(-max_long-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -9223372036854775808 ====================================================================== FAIL: long_long_abs (builtin_abs) Doctest: builtin_abs.long_long_abs ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib64/python3.6/doctest.py", line 2199, in runTest raise self.failureException(self.format_failure(new.getvalue())) AssertionError: Failed doctest test for builtin_abs.long_long_abs File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line unknown line number, in long_long_abs ---------------------------------------------------------------------- File "/home/abuild/rpmbuild/BUILD/Cython-0.27.1/TEST_TMP/run/cpp/builtin_abs/builtin_abs.cpython-36m-x86_64-linux-gnu.so", line ?, in builtin_abs.long_long_abs Failed example: long_long_abs(-max_long_long-1) #doctest: +ELLIPSIS Expected: Traceback (most recent call last): ... OverflowError: ... Got: -9223372036854775808 ```
I was unable to reproduce this on sles-11-sp4-v20170621 with Cython 0.27.1, Python 3.6.2, and gcc `gcc version 4.3.4 [gcc-4_3-branch revision 152973] (SUSE Linux)`. I also tried `SUSE Linux Enterprise Server 12 SP3`, can't get it to fail. Also reported in Gentoo https://bugs.gentoo.org/632519 - I can reproduce it with gcc-6.4.0. I am guessing that is because gcc now default to C99 (I think) which wouldn't happen with the compilers you tried. I don't have this anymore with 0.28. I have another strange issue though that may or may not be related to this. The problem seems to be caused by `-fstrict-overflow` (implied by `-O2`). Evidence: ``` CFLAGS='-O1' ./runtests.py builtin_abs # -> pass CFLAGS='-O2' ./runtests.py builtin_abs # -> fail CFLAGS='-O2 -fno-strict-overflow' ./runtests.py builtin_abs # -> pass CFLAGS='-O1 -fstrict-overflow' ./runtests.py builtin_abs # -> fail ``` This is with gcc-6.4.0. I don't have older versions of gcc to test. This is still occurring (gcc 9.3.0, `python2-config --cflags` equal to `-I/usr/include/python2.7 -I/usr/include/python2.7 -fno-strict-aliasing -march=x86-64 -mtune=generic -O2 -pipe -fno-plt -DNDEBUG -march=x86-64 -mtune=generic -O2 -pipe -fno-plt`; I think the `O3` is the only relevant part here!). The code we're producing in all these cases is: ```C __pyx_t_1 = abs(__pyx_v_a); if (unlikely(__pyx_t_1 < 0)) { PyErr_SetString(PyExc_OverflowError, "value too large"); __PYX_ERR(0, 60, __pyx_L1_error); } ``` Calling abs with a value that cannot be converted to an absolute value is undefined behaviour, . it's return value is guaranteed to be non-negative for all defined cases, so resultantly gcc removes the branch as its dead code under C semantics. `-fno-strict-overflow` or `-fwrapv` stop this under gcc, but clang appears to always elide the conditional statement (which is probably a bug!). Yes, that looks wrong. I think we have to test the input argument upfront, not the result. The check is generated in `ExprNodes.py`, `SimpleCallNode.generate_result_code()`. I think it should use a dedicated expression node instead, to be inserted into the tree in `analyse_c_function_call()`. The fact that the safety check is currently implemented directly in the code generation of `SimpleCallNode` is rather a hack.
2020-05-25T17:05:47Z
[]
[]
cython/cython
3,644
cython__cython-3644
[ "2056" ]
0532a0919be640210eeba1144717a6273707e112
diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -178,7 +178,7 @@ def get_directive_defaults(): 'auto_pickle': None, 'cdivision': False, # was True before 0.12 'cdivision_warnings': False, - 'c_api_binop_methods': True, # Change for 3.0 + 'c_api_binop_methods': False, # was True before 3.0 'overflowcheck': False, 'overflowcheck.fold': True, 'always_allow_keywords': True,
diff --git a/tests/run/unicode_formatting.pyx b/tests/run/unicode_formatting.pyx --- a/tests/run/unicode_formatting.pyx +++ b/tests/run/unicode_formatting.pyx @@ -38,21 +38,21 @@ def mix_format(a, int b, list c): class PySubtype(unicode): def __rmod__(self, other): - return f'PyRMOD({other})' + return f'PyRMOD({self}, {other})' cdef class ExtSubtype(unicode): - def __mod__(one, other): - return f'ExtMOD({one}, {other})' + def __rmod__(self, other): + return f'ExtRMOD({self}, {other})' def subtypes(): """ >>> py, ext = subtypes() >>> print(py) - PyRMOD(-%s-) + PyRMOD(PySub, -%s-) >>> print(ext) - ExtMOD(-%s-, ExtSub) + ExtRMOD(ExtSub, -%s-) """ return [ '-%s-' % PySubtype("PySub"),
Support special binary methods ("__add__" etc.) as Python does I'm not sure if this is a bug report or a feature request, but as of cython 0.27.3 `__radd__`, `__rtruediv__` and other right side magic methods do not work: ```python In [1]: %load_ext Cython In [2]: %%cython ...: cdef class Example: ...: def __radd__(self, other): ...: print('radd', self, other) ...: def __rtruediv__(self, other): ...: print('rtruediv', self, other) ...: In [3]: 3 + Example() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-b54d8dd2451f> in <module>() ----> 1 3 + Example() TypeError: unsupported operand type(s) for +: 'int' and '_cython_magic_c1fde2d95cc29b87ed98f696ccfef975.Example' In [4]: 'foo' / Example() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-1e29a35d9b28> in <module>() ----> 1 'foo' / Example() TypeError: unsupported operand type(s) for /: 'str' and '_cython_magic_c1fde2d95cc29b87ed98f696ccfef975.Example' In [5]: import Cython In [6]: Cython.__version__ Out[6]: '0.27.3' ``` I'm using the following workaround, but it looks ugly: ```python In [7]: %%cython ...: cdef class Example: ...: def __add__(other, self): ...: print('add', self, other) ...: def __truediv__(other, self): ...: print('truediv', self, other) ...: In [8]: 3 + Example() add <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a0f0> 3 In [9]: 'foo' / Example() truediv <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a110> foo ``` and doesn't really work if we switch operands: ```python In [10]: Example() + 3 add 3 <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a110> In [11]: Example() / 'foo' truediv foo <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109468e60> ``` I'm not familiar with cython codebase, but a quick search through the source, issues and PRs doesn't show anything related.
Cython's special methods still mostly reflect the C API rather than the Python API. See http://cython.readthedocs.io/en/latest/src/userguide/special_methods.html#arithmetic-methods . Here either the first or second parameter may be self, rather than having __rxxx__ versions of the operators. (It would be nice to support this however, similar to how the comparison methods were recently added.) On Thu, Dec 28, 2017 at 3:14 AM, Dmitry Malinovsky <[email protected] > wrote: > I'm not sure if this is a bug report or a feature request, but as of > cython 0.27.3 __radd__, __rtruediv__ and other right side magic methods > do not work: > > In [1]: %load_ext Cython > > In [2]: %%cython > ...: cdef class Example: > ...: def __radd__(self, other): > ...: print('radd', self, other) > ...: def __rtruediv__(self, other): > ...: print('rtruediv', self, other) > ...: > > In [3]: 3 + Example()---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-3-b54d8dd2451f> in <module>()----> 1 3 + Example() > TypeError: unsupported operand type(s) for +: 'int' and '_cython_magic_c1fde2d95cc29b87ed98f696ccfef975.Example' > > In [4]: 'foo' / Example()---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-4-1e29a35d9b28> in <module>()----> 1 'foo' / Example() > TypeError: unsupported operand type(s) for /: 'str' and '_cython_magic_c1fde2d95cc29b87ed98f696ccfef975.Example' > > In [5]: import Cython > > In [6]: Cython.__version__ > Out[6]: '0.27.3' > > I'm using the following workaround, but it looks ugly: > > In [7]: %%cython > ...: cdef class Example: > ...: def __add__(other, self): > ...: print('add', self, other) > ...: def __truediv__(other, self): > ...: print('truediv', self, other) > ...: > > In [8]: 3 + Example() > add <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a0f0> 3 > > In [9]: 'foo' / Example() > truediv <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a110> foo > > and doesn't really work if we switch operands: > > In [10]: Example() + 3 > add 3 <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109d7a110> > > In [11]: Example() / 'foo' > truediv foo <_cython_magic_45c6eacd188f8181199b3c76f32cba5d.Example object at 0x109468e60> > > I'm not familiar with cython codebase, but a quick search through the > source, issues and PRs doesn't show anything related. > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/cython/cython/issues/2056>, or mute the thread > <https://github.com/notifications/unsubscribe-auth/AAdqgcvFpRoV1V5VQmmG1gnKEIwYNzK5ks5tE3gWgaJpZM4ROO6o> > . > We should consider whether we want to move away from the "first or second argument is self" for the arithmetic methods for 3.0. I think we should switch to normal Python semantics. As @robertwb said, in the same way as we support the comparison methods now. See [`generate_richcmp_function()`](https://github.com/cython/cython/blob/d034742afc7d9fc37a6f3eb24cda07aa86edb0ca/Cython/Compiler/ModuleNode.py#L1834-L1902) in `ModuleNode.py` together with the [`RichcmpSlot`](https://github.com/cython/cython/blob/d034742afc7d9fc37a6f3eb24cda07aa86edb0ca/Cython/Compiler/TypeSlots.py#L408-L416) in `TypeSlots.py`. The idea is to define the number slots with a new slot type `BinopSlot` that has two special Python methods as implementation, and then generate the `nb_add` etc. slots by dispatching to these methods (more precisely, their C functions) according to CPython's own logic in [`typeobject.c`](https://github.com/python/cpython/blob/d929f1838a8fba881ff0148b7fc31f6265703e3d/Objects/typeobject.c#L6128-L6166). Marking as Cython 3.0 release blocker, in case we need backwards incompatible changes for this.
2020-05-28T06:25:51Z
[]
[]
cython/cython
3,713
cython__cython-3713
[ "3712" ]
83ea5a4b9908ddd2832633b60e9471863a22a8b8
diff --git a/Cython/Compiler/FlowControl.py b/Cython/Compiler/FlowControl.py --- a/Cython/Compiler/FlowControl.py +++ b/Cython/Compiler/FlowControl.py @@ -1220,6 +1220,7 @@ def visit_TryFinallyStatNode(self, node): if self.flow.loops: self.flow.loops[-1].exceptions.append(descr) self.flow.block = body_block + body_block.add_child(entry_point) self.flow.nextblock() self._visit(node.body) self.flow.exceptions.pop()
diff --git a/tests/compile/tryfinally.pyx b/tests/compile/tryfinally.pyx --- a/tests/compile/tryfinally.pyx +++ b/tests/compile/tryfinally.pyx @@ -18,4 +18,11 @@ def f(a, b, c, x): finally: i = 42 +def use_name_in_finally(name): + # GH3712 + try: + [] + finally: + name() +
Compiler crash: `AttributeError: 'set' object has no attribute 'cf_is_null'` I am getting a compiler crash trying to install a python project: ``` Compiler crash traceback from this point on: File "Cython/Compiler/Visitor.py", line 180, in Cython.Compiler.Visitor.TreeVisitor._visit File "/home/ellie/.local/lib/python3.8/site-packages/Cython/Compiler/Optimize.py", line 2012, in visit_SimpleCallNode function = self.get_constant_value_node(function_name) File "/home/ellie/.local/lib/python3.8/site-packages/Cython/Compiler/Optimize.py", line 1996, in get_constant_value_node if name_node.cf_state.cf_is_null: AttributeError: 'set' object has no attribute 'cf_is_null' ``` This is the crashing line: \<link outdated\> This is the version of Cython I'm using: ``` $ pip3 show Cython Name: Cython Version: 0.29.20 Summary: The Cython compiler for writing C extensions for the Python language. Home-page: http://cython.org/ Author: Robert Bradshaw, Stefan Behnel, Dag Seljebotn, Greg Ewing, et al. Author-email: [email protected] License: Apache Location: /home/user/.local/lib/python3.8/site-packages Requires: Required-by: ``` Pretty sure it worked with a previous Cython version many months ago, so possibly a regression...? Not sure
It definitely looks like a bug. Here's a simplified version of your code that reproduces it: ``` def run(done_callback): try: [] # anything finally: done_callback() ``` As far as I can tell being in the `finally` block is needed for the bug to trigger. If it's in try/except/else/not-in-a-try-block then you don't see it. `cf_state` looks to be initially made a `set`, then replaced with a `ControlFlowState` object in `FlowControl.check_definitions`. It seems like in this case it isn't be replaced correctly. Unfortunately this is where I'm outsmarted, so I don't think I can fix it. If it works for older versions, then `git bisect` could help to find how this was introduced. bbef4d74841b7e979a45d9bbb59c5a1c733a55d7 - which makes sense because it was changing flow-control and finally
2020-06-28T17:45:32Z
[]
[]
cython/cython
3,812
cython__cython-3812
[ "3808" ]
4aec02117deb1d9279a81920f21459fc015d1a77
diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -316,9 +316,12 @@ def p_typecast(s): s.next() base_type = p_c_base_type(s) is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode) - is_template = isinstance(base_type, Nodes.TemplatedTypeNode) - is_const_volatile = isinstance(base_type, Nodes.CConstOrVolatileTypeNode) - if not is_memslice and not is_template and not is_const_volatile and base_type.name is None: + is_other_unnamed_type = isinstance(base_type, ( + Nodes.TemplatedTypeNode, + Nodes.CConstOrVolatileTypeNode, + Nodes.CTupleBaseTypeNode, + )) + if not (is_memslice or is_other_unnamed_type) and base_type.name is None: s.error("Unknown type") declarator = p_c_declarator(s, empty = 1) if s.sy == '?':
diff --git a/tests/run/ctuple.pyx b/tests/run/ctuple.pyx --- a/tests/run/ctuple.pyx +++ b/tests/run/ctuple.pyx @@ -142,6 +142,17 @@ cpdef (int, double) cpdef_ctuple_return_type(int x, double y): return x, y +def cast_to_ctuple(*o): + """ + >>> cast_to_ctuple(1, 2.) + (1, 2.0) + """ + cdef int x + cdef double y + x, y = <(int, double)>o + return x, y + + @cython.infer_types(True) def test_type_inference(): """
[BUG] Compiler error when casting to `ctuple` **Describe the bug** When attempting to cast to a `ctuple`, Cython runs into a compiler error. **To Reproduce** Code to reproduce the behavior: ```cython # cython: language_level=3 cdef double d cdef int i o = (3.0, 2) d, i = <(double, int)>o # <--- compiler errors here ``` <details> <summary>Exception:</summary> ```python Traceback (most recent call last): File "/Users/jkirkham/miniconda/envs/cython/bin/cython", line 11, in <module> sys.exit(setuptools_main()) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 840, in setuptools_main return main(command_line = 1) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 858, in main result = compile(sources, options) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 780, in compile return compile_multiple(source, options) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 757, in compile_multiple result = run_pipeline(source, options, context=context) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 515, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Pipeline.py", line 355, in run_pipeline data = run(phase, data) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Pipeline.py", line 335, in run return phase(data) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Pipeline.py", line 34, in parse tree = context.parse(source_desc, scope, pxd = 0, full_module_name = full_module_name) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Main.py", line 369, in parse tree = Parsing.p_module(s, pxd, full_module_name) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 3707, in p_module body = p_statement_list(s, ctx(level=level), first_statement = 1) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 2341, in p_statement_list stat = p_statement(s, ctx, first_statement = first_statement) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 2333, in p_statement return p_simple_statement_list(s, ctx, first_statement=first_statement) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 2154, in p_simple_statement_list stat = p_simple_statement(s, first_statement = first_statement) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 2148, in p_simple_statement node = p_expression_or_assignment(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 1523, in p_expression_or_assignment expr = p_testlist_star_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 1453, in p_testlist_star_expr expr = p_test_or_starred_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 210, in p_test_or_starred_expr return p_test(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 142, in p_test expr = p_or_test(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 163, in p_or_test return p_rassoc_binop_expr(s, ('or',), p_and_test) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 166, in p_rassoc_binop_expr n1 = p_subexpr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 179, in p_and_test return p_rassoc_binop_expr(s, ('and',), p_not_test) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 166, in p_rassoc_binop_expr n1 = p_subexpr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 189, in p_not_test return p_comparison(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 195, in p_comparison n1 = p_starred_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 219, in p_starred_expr expr = p_bit_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 261, in p_bit_expr return p_binop_expr(s, ('|',), p_xor_expr) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 266, in p_xor_expr return p_binop_expr(s, ('^',), p_and_expr) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 271, in p_and_expr return p_binop_expr(s, ('&',), p_shift_expr) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 276, in p_shift_expr return p_binop_expr(s, ('<<', '>>'), p_arith_expr) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 281, in p_arith_expr return p_binop_expr(s, ('+', '-'), p_term) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 286, in p_term return p_binop_expr(s, ('*', '@', '/', '%', '//'), p_factor) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 97, in p_binop_expr n1 = p_sub_expr(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 292, in p_factor return _p_factor(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 308, in _p_factor return p_typecast(s) File "/Users/jkirkham/miniconda/envs/cython/lib/python3.8/site-packages/Cython/Compiler/Parsing.py", line 322, in p_typecast and base_type.name is None): AttributeError: 'CTupleBaseTypeNode' object has no attribute 'name' ``` </details> Workaround (`ctypedef` of `ctuple`): ```cython ctypedef (double, int) double_int cdef double d cdef int i o = (3.0, 2) d, i = <double_int>o ``` **Expected behavior** The compiler error does not occur. **Environment (please complete the following information):** - OS: macOS - Python version 3.8.5 - Cython version 0.29.21 **Additional context** NA
I realize this is probably a minimized example to demonstrate the issue, but I can't see why the cast to a ctuple is useful here? I'd think `d, i = o` should work just as efficiently? Yeah it’s an oversimplified example just to demonstrate the issue. > `d, i = <(double, int)>o # <--- compiler errors here` You didn't say what error occurred, but it probably fails to parse it, right? Such a cast is not really beautiful syntax, and most likely not something that was considered when ctuples were implemented. Is there really a use case for such a cast? In an assignment, you could always type the left hand side rather than casting the right hand side. In what kind of code have you noticed this? Yeah it seems to be a parsing error. Have added the exception to the detail in the OP. Fair enough. FWIW it seems readable and seems comparable in complexity to things like `<float[:n:1]>`. Only recently learned about `ctuple`s in Cython (which is a neat feature btw :), so was doing some exploration with some existing code that could be made a little clearer by bundling a few related values together. Stumbled across this issue in the process. No strong feelings on the resolution here (including closing if that is what we deem appropriate).
2020-09-03T19:40:00Z
[]
[]
cython/cython
3,813
cython__cython-3813
[ "3805" ]
4aec02117deb1d9279a81920f21459fc015d1a77
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -1546,17 +1546,23 @@ class CEnumDefNode(StatNode): # in_pxd boolean # create_wrapper boolean # entry Entry + # doc EncodedString or None Doc string child_attrs = ["items", "underlying_type"] + doc = None def declare(self, env): + doc = None + if Options.docstrings: + doc = embed_position(self.pos, self.doc) + self.entry = env.declare_enum( self.name, self.pos, cname=self.cname, scoped=self.scoped, typedef_flag=self.typedef_flag, visibility=self.visibility, api=self.api, - create_wrapper=self.create_wrapper) + create_wrapper=self.create_wrapper, doc=doc) def analyse_declarations(self, env): scope = None diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -3168,11 +3168,13 @@ def p_c_enum_definition(s, pos, ctx): s.expect(':') items = [] + doc = None if s.sy != 'NEWLINE': p_c_enum_line(s, ctx, items) else: s.next() # 'NEWLINE' s.expect_indent() + doc = p_doc_string(s) while s.sy not in ('DEDENT', 'EOF'): p_c_enum_line(s, ctx, items) @@ -3188,7 +3190,7 @@ def p_c_enum_definition(s, pos, ctx): underlying_type=underlying_type, typedef_flag=ctx.typedef_flag, visibility=ctx.visibility, create_wrapper=ctx.overridable, - api=ctx.api, in_pxd=ctx.level == 'module_pxd') + api=ctx.api, in_pxd=ctx.level == 'module_pxd', doc=doc) def p_c_enum_line(s, ctx, items): if s.sy != 'pass': diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -4024,12 +4024,14 @@ def check_nullary_constructor(self, pos, msg="stack allocated"): class CppScopedEnumType(CType): # name string + # doc string or None # cname string is_cpp_enum = True - def __init__(self, name, cname, underlying_type, namespace=None): + def __init__(self, name, cname, underlying_type, namespace=None, doc=None): self.name = name + self.doc = doc self.cname = cname self.values = [] self.underlying_type = underlying_type @@ -4084,6 +4086,7 @@ def create_type_wrapper(self, env): "cname": self.cname.split("::")[-1], "items": tuple(self.values), "underlying_type": self.underlying_type.empty_declaration_code(), + "enum_doc": self.doc, }, outer_module_scope=env.global_scope()) @@ -4139,6 +4142,7 @@ def is_optional_template_param(type): class CEnumType(CIntLike, CType): # name string + # doc string or None # cname string or None # typedef_flag boolean # values [string], populated during declaration analysis @@ -4147,8 +4151,9 @@ class CEnumType(CIntLike, CType): signed = 1 rank = -1 # Ranks below any integer type - def __init__(self, name, cname, typedef_flag, namespace=None): + def __init__(self, name, cname, typedef_flag, namespace=None, doc=None): self.name = name + self.doc = doc self.cname = cname self.values = [] self.typedef_flag = typedef_flag @@ -4190,7 +4195,9 @@ def create_type_wrapper(self, env): env.use_utility_code(CythonUtilityCode.load( "EnumType", "CpdefEnums.pyx", context={"name": self.name, - "items": tuple(self.values)}, + "items": tuple(self.values), + "enum_doc": self.doc, + }, outer_module_scope=env.global_scope())) diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -680,7 +680,7 @@ def check_previous_visibility(self, entry, visibility, pos): entry.name, entry.visibility)) def declare_enum(self, name, pos, cname, scoped, typedef_flag, - visibility='private', api=0, create_wrapper=0): + visibility='private', api=0, create_wrapper=0, doc=None): if name: if not cname: if (self.in_cinclude or visibility == 'public' @@ -694,9 +694,9 @@ def declare_enum(self, name, pos, cname, scoped, typedef_flag, namespace = None if scoped: - type = PyrexTypes.CppScopedEnumType(name, cname, namespace) + type = PyrexTypes.CppScopedEnumType(name, cname, namespace, doc=doc) else: - type = PyrexTypes.CEnumType(name, cname, typedef_flag, namespace) + type = PyrexTypes.CEnumType(name, cname, typedef_flag, namespace, doc=doc) else: type = PyrexTypes.c_anon_enum_type entry = self.declare_type(name, type, pos, cname = cname,
diff --git a/tests/run/cpdef_enums.pxd b/tests/run/cpdef_enums.pxd --- a/tests/run/cpdef_enums.pxd +++ b/tests/run/cpdef_enums.pxd @@ -11,5 +11,19 @@ cpdef enum PxdEnum: RANK_1 = 37 RANK_2 = 389 +cpdef enum cpdefPxdDocEnum: + """Home is where... + """ + RANK_6 = 159 + +cpdef enum cpdefPxdDocLineEnum: + """Home is where...""" + RANK_7 = 889 + cdef enum PxdSecretEnum: - RANK_3 = 5077 + RANK_8 = 5077 + +cdef enum cdefPxdDocEnum: + """the heart is. + """ + RANK_9 = 2458 diff --git a/tests/run/cpdef_enums.pyx b/tests/run/cpdef_enums.pyx --- a/tests/run/cpdef_enums.pyx +++ b/tests/run/cpdef_enums.pyx @@ -11,6 +11,8 @@ True True >>> FIVE == 5 or FIVE True +>>> ELEVEN == 11 or ELEVEN +True >>> SEVEN # doctest: +ELLIPSIS Traceback (most recent call last): NameError: ...name 'SEVEN' is not defined @@ -29,6 +31,10 @@ True True >>> RANK_2 == 389 or RANK_2 True +>>> RANK_6 == 159 or RANK_6 +True +>>> RANK_7 == 889 or RANK_7 +True >>> RANK_3 # doctest: +ELLIPSIS Traceback (most recent call last): NameError: ...name 'RANK_3' is not defined @@ -48,7 +54,6 @@ Traceback (most recent call last): NameError: ...name 'IntEnum' is not defined """ - cdef extern from *: cpdef enum: # ExternPyx ONE "1" @@ -63,9 +68,24 @@ cpdef enum PyxEnum: THREE = 3 FIVE = 5 +cpdef enum cpdefPyxDocEnum: + """Home is where... + """ + ELEVEN = 11 + +cpdef enum cpdefPyxDocLineEnum: + """Home is where...""" + FOURTEEN = 14 + cdef enum SecretPyxEnum: SEVEN = 7 +cdef enum cdefPyxDocEnum: + """the heart is. + """ + FIVE_AND_SEVEN = 5077 + + def test_as_variable_from_cython(): """ >>> test_as_variable_from_cython() @@ -89,3 +109,21 @@ def verify_resolution_GH1533(): """ THREE = 100 return int(PyxEnum.THREE) + + +def check_docs(): + """ + >>> PxdEnum.__doc__ not in ("Home is where...\\n ", "Home is where...") + True + >>> PyxEnum.__doc__ not in ("Home is where...\\n ", "Home is where...") + True + >>> cpdefPyxDocEnum.__doc__ == "Home is where...\\n " + True + >>> cpdefPxdDocEnum.__doc__ == "Home is where...\\n " + True + >>> cpdefPyxDocLineEnum.__doc__ + 'Home is where...' + >>> cpdefPxdDocLineEnum.__doc__ + 'Home is where...' + """ + pass diff --git a/tests/run/cpdef_scoped_enums.pyx b/tests/run/cpdef_scoped_enums.pyx --- a/tests/run/cpdef_scoped_enums.pyx +++ b/tests/run/cpdef_scoped_enums.pyx @@ -7,14 +7,36 @@ cdef extern from *: Item1 = 1, Item2 = 2 }; + + enum class Enum2 { + Item4 = 4, + Item5 = 5 + }; """ cpdef enum class Enum1: Item1 Item2 + cpdef enum class Enum2: + """Apricots and other fruits. + """ + Item4 + Item5 + def test_enum_to_list(): """ >>> test_enum_to_list() """ assert list(Enum1) == [1, 2] + assert list(Enum2) == [4, 5] + + +def test_enum_doc(): + """ + >>> Enum2.__doc__ == "Apricots and other fruits.\\n " + True + >>> Enum1.__doc__ != "Apricots and other fruits.\\n " + True + """ + pass
[BUG] docs for cpdef enum ignored **Describe the bug** I have a `cpdef enum` and I'm trying to get the doc for it in python, but it doesn't seem to be available in the `__doc__` attribute and the expected syntax for writing it is also seemingly invalid. And this is even with `embedsignature=True`. I set up a [demo example](https://github.com/matham/cython_demo_project/blob/enum/cython_demo_project/numeric.pyx) so you can see it [failing](https://github.com/matham/cython_demo_project/runs/1063256000?check_suite_focus=true) in the [tests](https://github.com/matham/cython_demo_project/blob/enum/cython_demo_project/tests/test_doc.py#L8): **To Reproduce** First I tried the class syntax, like python's enum: ```py cpdef enum Numbers: """Number list.""" one = 1 two = 2 ``` But that gives: ``` Error compiling Cython file: ------------------------------------------------------------ ... """ return self.a + self.b cpdef enum Numbers: """Number list.""" ^ ------------------------------------------------------------ cython_demo_project\numeric.pyx:22:4: Expected an identifier ``` So I tried: ```py cpdef enum Numbers: one = 1 two = 2 """Number list.""" ``` But that gives: ```py >>> print(Numbers.__doc__) An enumeration. ``` **Expected behavior** My ultimate goal is to have the docs show up in sphinx doc generation. But, currently it doesn't seem to be at all included by Cython in the generated code. **Environment (please complete the following information):** - OS: Windows - Python version: 3.7.3. - Cython version 0.29.21
2020-09-03T23:51:11Z
[]
[]
cython/cython
3,821
cython__cython-3821
[ "3814" ]
ac0810cfd3774048dfa83bd6155a890fc09fa717
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -503,21 +503,21 @@ def result(self): else: return self.calculate_result_code() - def _make_move_result_rhs(self, result, allow_move=True): - if (self.is_temp and allow_move and - self.type.is_cpp_class and not self.type.is_reference): - self.has_temp_moved = True - return "__PYX_STD_MOVE_IF_SUPPORTED({0})".format(result) - else: + def _make_move_result_rhs(self, result, optional=False): + if optional and not (self.is_temp and self.type.is_cpp_class and not self.type.is_reference): return result + self.has_temp_moved = True + return "{}({})".format("__PYX_STD_MOVE_IF_SUPPORTED" if optional else "std::move", result) def move_result_rhs(self): - return self._make_move_result_rhs(self.result()) + return self._make_move_result_rhs(self.result(), optional=True) def move_result_rhs_as(self, type): - allow_move = (type and not type.is_reference and not type.needs_refcounting) - return self._make_move_result_rhs(self.result_as(type), - allow_move=allow_move) + result = self.result_as(type) + if not (type.is_reference or type.needs_refcounting): + requires_move = type.is_rvalue_reference and self.is_temp + result = self._make_move_result_rhs(result, optional=not requires_move) + return result def pythran_result(self, type_=None): if is_pythran_supported_node_or_none(self): @@ -5776,8 +5776,18 @@ def analyse_c_function_call(self, env): else: alternatives = overloaded_entry.all_alternatives() - entry = PyrexTypes.best_match( - [arg.type for arg in args], alternatives, self.pos, env, args) + # For any argument/parameter pair A/P, if P is a forwarding reference, + # use lvalue-reference-to-A for deduction in place of A when the + # function call argument is an lvalue. See: + # https://en.cppreference.com/w/cpp/language/template_argument_deduction#Deduction_from_a_function_call + arg_types = [arg.type for arg in args] + if func_type.is_cfunction: + for i, formal_arg in enumerate(func_type.args): + if formal_arg.is_forwarding_reference(): + if self.args[i].is_lvalue(): + arg_types[i] = PyrexTypes.c_ref_type(arg_types[i]) + + entry = PyrexTypes.best_match(arg_types, alternatives, self.pos, env, args) if not entry: self.type = PyrexTypes.error_type diff --git a/Cython/Compiler/Lexicon.py b/Cython/Compiler/Lexicon.py --- a/Cython/Compiler/Lexicon.py +++ b/Cython/Compiler/Lexicon.py @@ -77,7 +77,7 @@ def prefixed_digits(prefix, digits): punct = Any(":,;+-*/|&<>=.%`~^?!@") diphthong = Str("==", "<>", "!=", "<=", ">=", "<<", ">>", "**", "//", "+=", "-=", "*=", "/=", "%=", "|=", "^=", "&=", - "<<=", ">>=", "**=", "//=", "->", "@=") + "<<=", ">>=", "**=", "//=", "->", "@=", "&&") spaces = Rep1(Any(" \t\f")) escaped_newline = Str("\\\n") lineterm = Eol + Opt(Str("\n")) diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -542,9 +542,7 @@ def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False): return self.base.analyse(ptr_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd) -class CReferenceDeclaratorNode(CDeclaratorNode): - # base CDeclaratorNode - +class _CReferenceDeclaratorBaseNode(CDeclaratorNode): child_attrs = ["base"] def declared_name(self): @@ -553,6 +551,8 @@ def declared_name(self): def analyse_templates(self): return self.base.analyse_templates() + +class CReferenceDeclaratorNode(_CReferenceDeclaratorBaseNode): def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False): if base_type.is_pyobject: error(self.pos, "Reference base type cannot be a Python object") @@ -560,6 +560,14 @@ def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False): return self.base.analyse(ref_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd) +class CppRvalueReferenceDeclaratorNode(_CReferenceDeclaratorBaseNode): + def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False): + if base_type.is_pyobject: + error(self.pos, "Rvalue-reference base type cannot be a Python object") + ref_type = PyrexTypes.cpp_rvalue_ref_type(base_type) + return self.base.analyse(ref_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd) + + class CArrayDeclaratorNode(CDeclaratorNode): # base CDeclaratorNode # dimension ExprNode @@ -774,6 +782,13 @@ def declare_opt_arg_struct(func_type, fused_cname): error(self.pos, "cannot have both '%s' and '%s' " "calling conventions" % (current, callspec)) func_type.calling_convention = callspec + + if func_type.return_type.is_rvalue_reference: + warning(self.pos, "Rvalue-reference as function return type not supported", 1) + for arg in func_type.args: + if arg.type.is_rvalue_reference and not arg.is_forwarding_reference(): + warning(self.pos, "Rvalue-reference as function argument not supported", 1) + return self.base.analyse(func_type, env, visibility=visibility, in_pxd=in_pxd) def declare_optional_arg_struct(self, func_type, env, fused_cname=None): @@ -1379,6 +1394,8 @@ def analyse_declarations(self, env, dest_scope=None): return if type.is_reference and self.visibility != 'extern': error(declarator.pos, "C++ references cannot be declared; use a pointer instead") + if type.is_rvalue_reference and self.visibility != 'extern': + error(declarator.pos, "C++ rvalue-references cannot be declared") if type.is_cfunction: if 'staticmethod' in env.directives: type.is_static_method = True diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -2876,12 +2876,13 @@ def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag, if is_ptrptr: base = Nodes.CPtrDeclaratorNode(pos, base=base) result = Nodes.CPtrDeclaratorNode(pos, base=base) - elif s.sy == '&': + elif s.sy == '&' or (s.sy == '&&' and s.context.cpp): + node_class = Nodes.CppRvalueReferenceDeclaratorNode if s.sy == '&&' else Nodes.CReferenceDeclaratorNode s.next() - base = p_c_declarator(s, ctx, empty = empty, is_type = is_type, - cmethod_flag = cmethod_flag, - assignable = assignable, nonempty = nonempty) - result = Nodes.CReferenceDeclaratorNode(pos, base = base) + base = p_c_declarator(s, ctx, empty=empty, is_type=is_type, + cmethod_flag=cmethod_flag, + assignable=assignable, nonempty=nonempty) + result = node_class(pos, base=base) else: rhs = None if s.sy == 'IDENT': diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -175,6 +175,7 @@ class PyrexType(BaseType): # is_ptr boolean Is a C pointer type # is_null_ptr boolean Is the type of NULL # is_reference boolean Is a C reference type + # is_rvalue_reference boolean Is a C++ rvalue reference type # is_const boolean Is a C const type # is_volatile boolean Is a C volatile type # is_cv_qualified boolean Is a C const or volatile type @@ -241,6 +242,7 @@ class PyrexType(BaseType): is_ptr = 0 is_null_ptr = 0 is_reference = 0 + is_rvalue_reference = 0 is_const = 0 is_volatile = 0 is_cv_qualified = 0 @@ -2747,26 +2749,17 @@ class CNullPtrType(CPtrType): is_null_ptr = 1 -class CReferenceType(BaseType): +class CReferenceBaseType(BaseType): - is_reference = 1 is_fake_reference = 0 + # Common base type for C reference and C++ rvalue reference types. + def __init__(self, base_type): self.ref_base_type = base_type def __repr__(self): - return "<CReferenceType %s>" % repr(self.ref_base_type) - - def __str__(self): - return "%s &" % self.ref_base_type - - def declaration_code(self, entity_code, - for_display = 0, dll_linkage = None, pyrex = 0): - #print "CReferenceType.declaration_code: pointer to", self.base_type ### - return self.ref_base_type.declaration_code( - "&%s" % entity_code, - for_display, dll_linkage, pyrex) + return "<%s %s>" % repr(self.__class__.__name__, self.ref_base_type) def specialize(self, values): base_type = self.ref_base_type.specialize(values) @@ -2782,13 +2775,25 @@ def __getattr__(self, name): return getattr(self.ref_base_type, name) +class CReferenceType(CReferenceBaseType): + + is_reference = 1 + + def __str__(self): + return "%s &" % self.ref_base_type + + def declaration_code(self, entity_code, + for_display = 0, dll_linkage = None, pyrex = 0): + #print "CReferenceType.declaration_code: pointer to", self.base_type ### + return self.ref_base_type.declaration_code( + "&%s" % entity_code, + for_display, dll_linkage, pyrex) + + class CFakeReferenceType(CReferenceType): is_fake_reference = 1 - def __repr__(self): - return "<CFakeReferenceType %s>" % repr(self.ref_base_type) - def __str__(self): return "%s [&]" % self.ref_base_type @@ -2798,6 +2803,20 @@ def declaration_code(self, entity_code, return "__Pyx_FakeReference<%s> %s" % (self.ref_base_type.empty_declaration_code(), entity_code) +class CppRvalueReferenceType(CReferenceBaseType): + + is_rvalue_reference = 1 + + def __str__(self): + return "%s &&" % self.ref_base_type + + def declaration_code(self, entity_code, + for_display = 0, dll_linkage = None, pyrex = 0): + return self.ref_base_type.declaration_code( + "&&%s" % entity_code, + for_display, dll_linkage, pyrex) + + class CFuncType(CType): # return_type CType # args [CFuncTypeArg] @@ -3430,6 +3449,12 @@ def declaration_code(self, for_display = 0): def specialize(self, values): return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname) + def is_forwarding_reference(self): + if self.type.is_rvalue_reference: + if (isinstance(self.type.ref_base_type, TemplatePlaceholderType) + and not self.type.ref_base_type.is_cv_qualified): + return True + return False class ToPyStructUtilityCode(object): @@ -4921,6 +4946,10 @@ def c_ref_type(base_type): # Construct a C reference type return _construct_type_from_base(CReferenceType, base_type) +def cpp_rvalue_ref_type(base_type): + # Construct a C++ rvalue reference type + return _construct_type_from_base(CppRvalueReferenceType, base_type) + def c_const_type(base_type): # Construct a C const type. return _construct_type_from_base(CConstType, base_type)
diff --git a/tests/compile/cpp_rvalue_reference_binding.pyx b/tests/compile/cpp_rvalue_reference_binding.pyx new file mode 100644 --- /dev/null +++ b/tests/compile/cpp_rvalue_reference_binding.pyx @@ -0,0 +1,22 @@ +# tag: cpp, cpp11 +# mode: compile + +cdef extern from *: + """ + template <typename T> + void accept(T&& x) {} + """ + cdef void accept[T](T&& x) + +cdef int make_int_py() except *: + # might raise Python exception (thus needs a temp) + return 1 + +cdef int make_int_cpp() except +: + # might raise C++ exception (thus needs a temp) + return 1 + +def test_func_arg(): + # won't compile if move() isn't called on the temp: + accept(make_int_py()) + accept(make_int_cpp()) diff --git a/tests/errors/cpp_rvalue_reference_support.pyx b/tests/errors/cpp_rvalue_reference_support.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/cpp_rvalue_reference_support.pyx @@ -0,0 +1,32 @@ +# mode: error +# tag: werror, cpp, cpp11 + +# These tests check for unsupported use of rvalue-references (&&) +# and should be removed or cleaned up when support is added. + +cdef int&& x + +cdef void foo(int&& x): + pass + +cdef int&& bar(): + pass + +cdef extern from *: + """ + void baz(int x, int&& y) {} + + template <typename T> + void qux(const T&& x) {} + """ + cdef void baz(int x, int&& y) + cdef void qux[T](const T&& x) + + +_ERRORS=""" +7:8: C++ rvalue-references cannot be declared +9:13: Rvalue-reference as function argument not supported +12:14: Rvalue-reference as function return type not supported +22:17: Rvalue-reference as function argument not supported +23:20: Rvalue-reference as function argument not supported +""" diff --git a/tests/errors/e_cpp_references.pyx b/tests/errors/e_cpp_references.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/e_cpp_references.pyx @@ -0,0 +1,10 @@ +# mode: error +# tag: cpp, cpp11 + +cdef foo(object& x): pass +cdef bar(object&& x): pass + +_ERRORS=""" +4:15: Reference base type cannot be a Python object +5:15: Rvalue-reference base type cannot be a Python object +""" diff --git a/tests/run/cpp_forwarding_ref.pyx b/tests/run/cpp_forwarding_ref.pyx new file mode 100644 --- /dev/null +++ b/tests/run/cpp_forwarding_ref.pyx @@ -0,0 +1,35 @@ +# mode: run +# tag: cpp, cpp11 + +from libcpp.utility cimport move + + +cdef extern from *: + """ + #include <utility> + + const char* f(int& x) { + return "lvalue-ref"; + } + + const char* f(int&& x) { + return "rvalue-ref"; + } + + template <typename T> + const char* foo(T&& x) + { + return f(std::forward<T>(x)); + } + """ + const char* foo[T](T&& x) + + +def test_forwarding_ref(): + """ + >>> test_forwarding_ref() + """ + cdef int x = 1 + assert foo(x) == b"lvalue-ref" + assert foo(<int>(1)) == b"rvalue-ref" + assert foo(move(x)) == b"rvalue-ref"
Supporting C++11 forwarding references Based on the discussion in https://github.com/cython/cython/pull/3790 I'm looking into adding support for [C++11 forwarding references](https://en.cppreference.com/w/cpp/language/reference#Forwarding_references). I'm looking for guidance on the better of two approaches to take for doing this. Let me explain the problem and possible solutions with an example: ```cython #distutils: language=c++ #distutils: extra_compile_args=-std=c++11 cdef extern from *: """ #include <iostream> void f(int&& t) { std::cout << "Rvalue" << std::endl; } void f(int& t) { std::cout << "Lvalue" << std::endl; } void f(const int& t) { std::cout << "Const lvalue" << std::endl; } template <typename T> void foo(T&& t) { f(std::forward<T>(t)); } """ cdef void foo[T](T&& t) cdef int x = 1 foo(1) foo(x) ``` Here, `foo` is a function that accepts a forwarding reference. Based on whether the argument to `foo` is an lvalue or rvalue, it should dispatch to the appropriate overload of `f`. Thus, the expected output of this program is: ``` Rvalue Lvalue ``` --- The C++ code generated by Cython for the above currently looks like this: ```c++ __pyx_v_10forwarding_x = 1; foo<long>(1); foo<int>(__pyx_v_10forwarding_x); // this line is incorrect currently ``` Because `foo` accepts a forwarding reference, the template argument should be of the form: * `int&` if the corresponding function argument is an lvalue expression * `int` if the corresponding function argument is an rvalue expression One solution is to let [`decltype`](https://en.cppreference.com/w/cpp/language/decltype) handle producing the correct template argument. In this case, the C++ code would look like this:: ```c++ foo<decltype((1))>(1); foo<decltype((__pyx_v_10forwarding_x))>(__pyx_v_10forwarding_x); ``` The other solution is for Cython to compute the appropriate template argument _a priori_. In this case, the C++ code would look like this: ```c++ foo<long>(1); foo<int&>(__pyx_v_10forwarding_x); ``` Which of these sounds better from a Cython viewpoint? cc: @da-woods if you have any suggestions here. Thank you :)
2020-09-09T14:06:18Z
[]
[]
cython/cython
3,829
cython__cython-3829
[ "2552" ]
af1300f7655b2ccdf6308d9c9fb839d7083782e9
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -28,7 +28,7 @@ from . import StringEncoding from . import Naming from . import Nodes -from .Nodes import Node, utility_code_for_imports +from .Nodes import Node, utility_code_for_imports, SingleAssignmentNode, PassStatNode from . import PyrexTypes from .PyrexTypes import py_object_type, c_long_type, typecast, error_type, \ unspecified_type @@ -458,6 +458,9 @@ class ExprNode(Node): child_attrs = property(fget=operator.attrgetter('subexprs')) + def analyse_annotations(self, env): + pass + def not_implemented(self, method_name): print_call_chain(method_name, "not implemented") raise InternalError( @@ -1973,32 +1976,35 @@ def coerce_to(self, dst_type, env): def declare_from_annotation(self, env, as_target=False): """Implements PEP 526 annotation typing in a fairly relaxed way. - Annotations are ignored for global variables, Python class attributes and already declared variables. - String literals are allowed and ignored. - The ambiguous Python types 'int' and 'long' are ignored and the 'cython.int' form must be used instead. + Annotations are ignored for global variables. + All other annotations are stored on the entry in the symbol table. + String literals are allowed and not evaluated. + The ambiguous Python types 'int' and 'long' are not evaluated - the 'cython.int' form must be used instead. """ - if not env.directives['annotation_typing']: - return - if env.is_module_scope or env.is_py_class_scope: - # annotations never create global cdef names and Python classes don't support them anyway - return name = self.name - if self.entry or env.lookup_here(name) is not None: - # already declared => ignore annotation - return - annotation = self.annotation - if annotation.expr.is_string_literal: - # name: "description" => not a type, but still a declared variable or attribute - atype = None - else: - _, atype = annotation.analyse_type_annotation(env) - if atype is None: - atype = unspecified_type if as_target and env.directives['infer_types'] != False else py_object_type - if atype.is_fused and env.fused_to_specific: - atype = atype.specialize(env.fused_to_specific) - self.entry = env.declare_var(name, atype, self.pos, is_cdef=not as_target) - self.entry.annotation = annotation + entry = self.entry or env.lookup_here(name) + if not entry: + # annotations never create global cdef names + if env.is_module_scope: + return + if ( + # name: "description" => not a type, but still a declared variable or attribute + annotation.expr.is_string_literal + # don't do type analysis from annotations if not asked to, but still collect the annotation + or not env.directives['annotation_typing'] + ): + atype = None + else: + _, atype = annotation.analyse_type_annotation(env) + if atype is None: + atype = unspecified_type if as_target and env.directives['infer_types'] != False else py_object_type + if atype.is_fused and env.fused_to_specific: + atype = atype.specialize(env.fused_to_specific) + entry = self.entry = env.declare_var(name, atype, self.pos, is_cdef=not as_target) + # Even if the entry already exists, make sure we're supplying an annotation if we can. + if annotation and not entry.annotation: + entry.annotation = annotation def analyse_as_module(self, env): # Try to interpret this as a reference to a cimported module. @@ -9037,6 +9043,9 @@ class ClassNode(ExprNode, ModuleNameMixin): type = py_object_type is_temp = True + def analyse_annotations(self, env): + pass + def infer_type(self, env): # TODO: could return 'type' in some cases return py_object_type @@ -9107,6 +9116,26 @@ def may_be_none(self): gil_message = "Constructing Python class" + def analyse_annotations(self, env): + from .AutoDocTransforms import AnnotationWriter + position = self.class_def_node.pos + dict_items = [ + DictItemNode( + entry.pos, + key=IdentifierStringNode(entry.pos, value=entry.name), + value=entry.annotation.string + ) + for entry in env.entries.values() if entry.annotation + ] + # Annotations dict shouldn't exist for classes which don't declare any. + if dict_items: + annotations_dict = DictNode(position, key_value_pairs=dict_items) + lhs = NameNode(position, name=StringEncoding.EncodedString(u"__annotations__")) + lhs.entry = env.lookup_here(lhs.name) or env.declare_var(lhs.name, dict_type, position) + node = SingleAssignmentNode(position, lhs=lhs, rhs=annotations_dict) + node.analyse_declarations(env) + self.class_def_node.body.stats.insert(0, node) + def generate_result_code(self, code): code.globalstate.use_utility_code(UtilityCode.load_cached("Py3ClassCreate", "ObjectHandling.c")) cname = code.intern_identifier(self.name) diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -5,6 +5,7 @@ from __future__ import absolute_import import cython + cython.declare(sys=object, os=object, copy=object, Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object, py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=object, @@ -4852,6 +4853,7 @@ def analyse_declarations(self, env): if self.doc_node: self.doc_node.analyse_target_declaration(cenv) self.body.analyse_declarations(cenv) + self.class_result.analyse_annotations(cenv) def analyse_expressions(self, env): if self.bases:
diff --git a/tests/run/cython3.pyx b/tests/run/cython3.pyx --- a/tests/run/cython3.pyx +++ b/tests/run/cython3.pyx @@ -616,15 +616,15 @@ def annotation_syntax(a: "test new test", b : "other" = 2, *args: "ARGS", **kwar >>> len(annotation_syntax.__annotations__) 5 >>> print(annotation_syntax.__annotations__['a']) - u'test new test' + 'test new test' >>> print(annotation_syntax.__annotations__['b']) - u'other' + 'other' >>> print(annotation_syntax.__annotations__['args']) - u'ARGS' + 'ARGS' >>> print(annotation_syntax.__annotations__['kwargs']) - u'KWARGS' + 'KWARGS' >>> print(annotation_syntax.__annotations__['return']) - u'ret' + 'ret' """ result : int = a + b @@ -648,10 +648,10 @@ async def async_def_annotations(x: 'int') -> 'float': >>> ret, arg = sorted(async_def_annotations.__annotations__.items()) >>> print(ret[0]); print(ret[1]) return - u'float' + 'float' >>> print(arg[0]); print(arg[1]) x - u'int' + 'int' """ return float(x) diff --git a/tests/run/decorators_T593.pyx b/tests/run/decorators_T593.pyx --- a/tests/run/decorators_T593.pyx +++ b/tests/run/decorators_T593.pyx @@ -110,7 +110,7 @@ class Base(type): class Bar(metaclass=Base): """ - >>> [n for n in Bar._order if n != "__qualname__"] + >>> [n for n in Bar._order if n not in {"__qualname__", "__annotations__"}] ['__module__', '__doc__', 'bar'] """ @property diff --git a/tests/run/locals_T732.pyx b/tests/run/locals_T732.pyx --- a/tests/run/locals_T732.pyx +++ b/tests/run/locals_T732.pyx @@ -23,7 +23,7 @@ def test_class_locals_and_dir(): >>> klass = test_class_locals_and_dir() >>> 'visible' in klass.locs and 'not_visible' not in klass.locs True - >>> [n for n in klass.names if n != "__qualname__"] + >>> [n for n in klass.names if n not in {"__qualname__", "__annotations__"}] ['__module__', 'visible'] """ not_visible = 1234 diff --git a/tests/run/metaclass.pyx b/tests/run/metaclass.pyx --- a/tests/run/metaclass.pyx +++ b/tests/run/metaclass.pyx @@ -69,7 +69,7 @@ class Py3ClassMCOnly(object, metaclass=Py3MetaclassPlusAttr): 321 >>> obj.metaclass_was_here True - >>> [n for n in obj._order if n != "__qualname__"] + >>> [n for n in obj._order if n not in {"__qualname__", "__annotations__"}] ['__module__', '__doc__', 'bar', 'metaclass_was_here'] """ bar = 321 @@ -81,7 +81,7 @@ class Py3InheritedMetaclass(Py3ClassMCOnly): 345 >>> obj.metaclass_was_here True - >>> [n for n in obj._order if n != "__qualname__"] + >>> [n for n in obj._order if n not in {"__qualname__", "__annotations__"}] ['__module__', '__doc__', 'bar', 'metaclass_was_here'] """ bar = 345 @@ -109,7 +109,7 @@ class Py3Foo(object, metaclass=Py3Base, foo=123): 123 >>> obj.bar 321 - >>> [n for n in obj._order if n != "__qualname__"] + >>> [n for n in obj._order if n not in {"__qualname__", "__annotations__"}] ['__module__', '__doc__', 'bar', 'foo'] """ bar = 321 @@ -122,7 +122,7 @@ class Py3FooInherited(Py3Foo, foo=567): 567 >>> obj.bar 321 - >>> [n for n in obj._order if n != "__qualname__"] + >>> [n for n in obj._order if n not in {"__qualname__", "__annotations__"}] ['__module__', '__doc__', 'bar', 'foo'] """ bar = 321 diff --git a/tests/run/pep526_variable_annotations.py b/tests/run/pep526_variable_annotations.py --- a/tests/run/pep526_variable_annotations.py +++ b/tests/run/pep526_variable_annotations.py @@ -156,6 +156,7 @@ def iter_declared_dict_arg(d : Dict[float, float]): 37:19: Unknown type declaration in annotation, ignoring 38:12: Unknown type declaration in annotation, ignoring 39:18: Unknown type declaration in annotation, ignoring +57:19: Unknown type declaration in annotation, ignoring 73:19: Unknown type declaration in annotation, ignoring # FIXME: these are sort-of evaluated now, so the warning is misleading 126:21: Unknown type declaration in annotation, ignoring diff --git a/tests/run/pyclass_annotations_pep526.py b/tests/run/pyclass_annotations_pep526.py new file mode 100644 --- /dev/null +++ b/tests/run/pyclass_annotations_pep526.py @@ -0,0 +1,47 @@ +# cython: language_level=3 +# mode: run +# tag: pure3.7, pep526, pep484 + +from __future__ import annotations + +try: + from typing import ClassVar +except ImportError: # Py<=3.5 + ClassVar = {int: int} + + +class PyAnnotatedClass: + """ + >>> PyAnnotatedClass.__annotations__["CLASS_VAR"] + 'ClassVar[int]' + >>> PyAnnotatedClass.__annotations__["obj"] + 'str' + >>> PyAnnotatedClass.__annotations__["literal"] + "'int'" + >>> PyAnnotatedClass.__annotations__["recurse"] + "'PyAnnotatedClass'" + >>> PyAnnotatedClass.__annotations__["default"] + 'bool' + >>> PyAnnotatedClass.CLASS_VAR + 1 + >>> PyAnnotatedClass.default + False + >>> PyAnnotatedClass.obj + Traceback (most recent call last): + ... + AttributeError: type object 'PyAnnotatedClass' has no attribute 'obj' + """ + CLASS_VAR: ClassVar[int] = 1 + obj: str + literal: "int" + recurse: "PyAnnotatedClass" + default: bool = False + + +class PyVanillaClass: + """ + >>> PyVanillaClass.__annotations__ + Traceback (most recent call last): + ... + AttributeError: type object 'PyVanillaClass' has no attribute '__annotations__' + """ diff --git a/tests/run/test_grammar.py b/tests/run/test_grammar.py --- a/tests/run/test_grammar.py +++ b/tests/run/test_grammar.py @@ -477,8 +477,7 @@ class C: def __init__(self, x): self.x: int = x - # FIXME: implement class annotations - #self.assertEqual(C.__annotations__, {'_C__foo': int, 's': str}) + self.assertEqual(C.__annotations__, {'_C__foo': 'int', 's': 'str'}) with self.assertRaises(NameError): class CBad: no_such_name_defined.attr: int = 0 @@ -487,7 +486,7 @@ class Cbad2(C): x: int x.y: list = [] - @skip("Class annotations not implemented") + @skip("Not currently supported: https://github.com/cython/cython/issues/3839") def test_var_annot_metaclass_semantics(self): class CMeta(type): @classmethod
Classes lack __annotations__ (PEP-526) With python 3.7 dataclasses were introduced. They work just fine in Cython except for their standard __init__ function. How to reproduce: test.pyx ``` from dataclasses import dataclass @dataclass class TestClass: x: int y: int some_string: str ``` This file compiles to Cython code just fine. However, when ran from the python it raises an error: test2.py ``` import test test_class = test.TestClass(1, 2, 'string') ``` This raises the following: ``` Traceback (most recent call last): File ".\test2.py", line 3, in <module> test_class = test.TestClass(1, 2, 'string') TypeError: __init__() takes 1 positional argument but 4 were given ``` if you rename test.pyx to test.py and do not compile it, no such error occurs. my current workaround: setting each property after initialization separately: test.pyx remains unchanged. test.py ``` import test test_class = test.TestClass() test_class.x = 1 test_class.y = 2 test_class.some_string = 'string' ```
I don't think we currently create a `__annotations__` for classes, although the syntax tree has the necessary information available. See the description in https://www.python.org/dev/peps/pep-0526/#runtime-effects-of-type-annotations PR welcome. I'm also stumbling over this currently, especially Python 3.6-style NamedTuples not working. I don't have any experience with how Cython works under the hood, but I'd be willing to give fixing this a try if someone could point me where to start. Is there some relevant documentation somewhere? Having similliar issue with dataclasses: ``` @dataclass class Test: name: str ``` When using regular dataclass when I import the file with the dataclass, I get: ``` TypeError: 'name' is a field but has no type annotation ``` I guess that's because cython does not creation annotations for classes. As always, the most important bit are tests. I would add new ones in a file `tests/run/pyclass_annotations_pep526.py` (with a `# tag: pure36` to prevent Py<3.6 from running in uncompiled). Look at the other `pyclass` tests to see how it's done, we basically use doctests (which are executed in Python and not compiled, as opposed to the rest of the file). I first thought that this could be implemented after executing the class body, but it turns out that [PEP 526](https://www.python.org/dev/peps/pep-0526/#runtime-effects-of-type-annotations) wants the `__annotations__` dict to be available before that, so creating the empty dict and assigning it in `__Pyx_Py3MetaclassPrepare()` would be the right way. Then each `NameNode` inside of the class body (`entry.is_pyclass_attr`) which holds a `self.annotation` will have to generate C code (in `generate_assignment_code()`) to look up the `__annotations__` dict in the class scope and assign its name to its annotation `.py_result()` on an assignment (or creation of the name). I don't actually know if that happens before or after the assignment to the name (which might fail, but could be shadowed by a try-except). Probably something to test in CPython. Thus: tests. Also note that there are probably relevant tests for PEP-526 in CPython's own test suite, which could be reused. I unfortunately didn't have much time these past few weeks to look at this. I've come up with a couple of test cases, however, that should get us pretty far on the way to full support of `__annotations__`. You can check them out [here](https://github.com/ra-kete/cython/blob/pyclass-annotations-pep526/tests/run/pyclass_annotations_pep526.py). I have two main questions now: 1. Do we need full compliance with CPython or would you also consider merging something incomplete if it enables the (correct) use of dataclasses and NamedTuples? I think it should be pretty straightforward to add the annotations to the `__annotations__` dict (passing test case `Annotations` above), which should be enough for the aforementioned use cases. I'm not sure how hard it would be to satisfy some of the other test cases though. 2. @scoder's explanation above was quite helpful (thanks!), but it seems that `NameNode.generate_assignment_code` is only invoked for actual assignments. So if we have a type annotated class variable that doesn't get a value assigned (i.e. just `foo: int`), we cannot add that to `__annotations__` this way. Is there some function that's invoked for class variable declarations regardless of assignment? You could handle 2) in `ExprStatNode`, which wraps non-statement expressions, such as arbitrarily sprinkled `NameNode`s. Regarding compliance, I don't think there is all that much missing. I certainly wouldn't want a random hack that makes it mostly work but would have to be replaced completely when doing it right. I'd rather take at least some steps in the right direction. Oh, and in fact, `ExprStatNode` marks its expression as unused, so that the non-assignment `NameNode.generate_code()` should be able to know that it only needs to store its annotation and be done. Although it could be that these nodes are discarded somewhere in the compiler pipeline. In that case, they should stay if they have an annotation to share. Regarding namedtuples specifically, there is also #536 that would probably still prevent the usage even if this ticket was resolved. PRs welcome. enabling annotations on a class would be very beneficial for me: - dataclasses - pydantic classes (very similar, but available in python:3.6) - (nice to have) namedtuple, but as said this would need more fixes. @scoder : i would be willing to help, but find it difficult to assess if this is a reasonable goal for me. i have quite some python experience and a little bit of C++ experience. can you give any indication on the amount of work this might take? (days, weeks, months?). i understand that this is very difficult to say upfront. maybe also i can contribute in another way by researching some specifics / adding preliminary tests? @ra-kete : you're link to tests no longer works. can you provide them again? With PEP-563 in place, I think this now got much easier since annotations are now plain and simple strings. We might get away with building the dict in Python and adding it to the class dict as is, similar to what we do for function annotations: https://github.com/cython/cython/blob/bcae4d1f31135bdcbedadc83e751f13e18de9d0c/Cython/Compiler/ExprNodes.py#L9371-L9377 So, I think most of the work will be collecting (from CPython)/adapting/writing tests, then building the `__annotations__` dict from whatever there is in the class body, and then possibly a little bit of generated C code in the `Py3ClassNode` to add it to the class's namespace mapping. @GliderGeek want to give it a try? thanks for the quick reply. i will try to get some proper time to work on this. in the meantime i have tried a little workaround: ```python class Annotated: x: int y: int __annotations__ = {'x': int, 'y': int} ``` this seems to work properly. is this what you meant by "get away with building the dict in Python and adding it to the class dict "? Sorry, with "in Python", I meant "in the Python code of the Cython compiler", i.e. in AST nodes (that was very unclear), as opposed to "in hand written C code". As done for functions. But the end result will then be generated C code that implements pretty much what you spelled out above, yes. (Although PEP 563 would make it `__annotations__ = {'x': 'int', 'y': 'int'}`). > @ra-kete : you're link to tests no longer works. can you provide them again? Sorry, I can't. Cleaned up my repos some time ago and forgot about this issue, so those tests are gone for good, unfortunately. Popping in here - I've got a fork where I've attempted your recommendation, @scoder. I'm very unclear as to exactly what kind of `StatNode` objects to expect in the class_def body, so this is my best guess: https://github.com/seandstewart/cython/blob/master/Cython/Compiler/ExprNodes.py#L9060 I've also added a test here, based on your recommendation: https://github.com/seandstewart/cython/blob/master/tests/run/pyclass_annotations_pep526.py @seandstewart cool! I was thinking that the annotations should be collected by the nodes themselves, but looking through the constraints in PEP-526 again, it seems that even a simple solution like this might work. The test is ok as well, but should be extended to cover more declaration cases from PEP-526. Note that you don't strictly need a test function. You can use the docstring of the class as well as a doctest. Here's what CPython uses: https://github.com/python/cpython/blob/master/Lib/test/ann_module.py https://github.com/python/cpython/blob/master/Lib/test/ann_module2.py https://github.com/python/cpython/blob/master/Lib/test/ann_module3.py Test for those are here: https://github.com/python/cpython/blob/master/Lib/test/test_grammar.py https://github.com/python/cpython/blob/57572b103ebd8732ac21922f0051a7f140d0e405/Lib/test/test_parser.py#L149 I've just updated the `test_grammar.py` copy that we use in Cython from Py3.9, but excluding the tests that use the external modules. While they could be integrated, I think it's better to create a separate test set from the annotation modules. Hey @scoder - thanks for the pointers! I've made some progress here. I've got the compiler actually extracting the correct node and building the list of annotations. However, I've hit a snag. When passing in the simple `annotation.string`, building the annotations_dict seems to work fine, however `annotations_dict.py_result()` ends up `None`. I tried passing the `AnnotationNode` directly to the dict instead (this feels more compliant, since the pure-python result will either be a string object or the class itself, depending upon how it's declared) but then `annotations_dict.analyse_types(code)` fails. The relevant portions: https://github.com/seandstewart/cython/blob/master/Cython/Compiler/ExprNodes.py#L9060-L9077 https://github.com/seandstewart/cython/blob/master/Cython/Compiler/ExprNodes.py#L9096-L9098 I think this would better fit into `Nodes.PyClassDefNode` instead of `ExprNodes.Py3ClassNode`. The creation of the `DictNode()` should be done at the end of `PyClassDefNode.analyse_declarations()`, which analyses the declared names and variables in the class, long before the code generation happens. The result can be prepended (?) to the `self.body.stats` list (`self.body` is a `StatListNode`), as an assignment expressed in a `SingleAssignmentNode` (see the usages in `Parsing.py`), which should assign the `DictNode` result to an `IdentifierStringNode` for the `__annotations__` key (in Python: `__annotations__ = {…}`). The rest should then happen more or less automatically from the syntax tree nodes. I also think that it's probably a good idea to _move_ the annotations over from their owning nodes into the `DictNode` values, i.e. set them to `None`, to prevent duplicate node references in the tree. I don't think they are used elsewhere. This also seems worth a new method. :) Great, yes, I think this is definitely the preferred approach, and will be in-line with CPython’s behavior. One caveat - annotations with assignments should remain in the class body, whereas annotations without assignments can be safely removed, I think. I’ll play with CPython’s AST and see how they handle this. Oh, I just meant to set `.annotation = None`, not the whole statement node. The node can just stay there, it won't hurt. @seandstewart I don't think there's a PR for this yet, right? Could you open one, so that we can move this forward? Hey @scoder - apologies for the radio silence here, I haven't been able to work on side projects for a while. I'll try and put something together soon, I hadn't quite got the tests passing, IIRC.
2020-09-15T12:59:09Z
[]
[]
cython/cython
3,831
cython__cython-3831
[ "3636", "3636" ]
fd71114951a9e0d48f0aad324e71d3d9f8be29df
diff --git a/Cython/Coverage.py b/Cython/Coverage.py --- a/Cython/Coverage.py +++ b/Cython/Coverage.py @@ -83,6 +83,23 @@ def _find_dep_file_path(main_file, file_path, relative_path_search=False): rel_file_path = os.path.join(os.path.dirname(main_file), file_path) if os.path.exists(rel_file_path): abs_path = os.path.abspath(rel_file_path) + + abs_no_ext = os.path.splitext(abs_path)[0] + file_no_ext, extension = os.path.splitext(file_path) + # We check if the paths match by matching the directories in reverse order. + # pkg/module.pyx /long/absolute_path/bla/bla/site-packages/pkg/module.c should match. + # this will match the pairs: module-module and pkg-pkg. After which there is nothing left to zip. + abs_no_ext = os.path.normpath(abs_no_ext) + file_no_ext = os.path.normpath(file_no_ext) + matching_paths = zip(reversed(abs_no_ext.split(os.sep)), reversed(file_no_ext.split(os.sep))) + for one, other in matching_paths: + if one != other: + break + else: # No mismatches detected + matching_abs_path = os.path.splitext(main_file)[0] + extension + if os.path.exists(matching_abs_path): + return canonical_filename(matching_abs_path) + # search sys.path for external locations if a valid file hasn't been found if not os.path.exists(abs_path): for sys_path in sys.path:
diff --git a/tests/run/coverage_cmd_src_pkg_layout.srctree b/tests/run/coverage_cmd_src_pkg_layout.srctree new file mode 100644 --- /dev/null +++ b/tests/run/coverage_cmd_src_pkg_layout.srctree @@ -0,0 +1,177 @@ +# mode: run +# tag: coverage,trace + +""" +PYTHON -m pip install . +PYTHON setup.py build_ext --inplace +PYTHON -m coverage run --source=pkg coverage_test.py +PYTHON collect_coverage.py +""" + +######## setup.py ######## + +from setuptools import Extension, find_packages, setup +from Cython.Build import cythonize + +MODULES = [ + Extension("pkg.module1", ["src/pkg/module1.pyx"]), + ] + +setup( + name="pkg", + zip_safe=False, + packages=find_packages('src'), + package_data={'pkg': ['*.pxd', '*.pyx']}, + package_dir={'': 'src'}, + ext_modules= cythonize(MODULES) + ) + + +######## .coveragerc ######## +[run] +plugins = Cython.Coverage + +######## src/pkg/__init__.py ######## + +######## src/pkg/module1.pyx ######## +# cython: linetrace=True +# distutils: define_macros=CYTHON_TRACE=1 + +def func1(int a, int b): + cdef int x = 1 # 5 + c = func2(a) + b # 6 + return x + c # 7 + + +def func2(int a): + return a * 2 # 11 + +######## coverage_test.py ######## + +import os.path +from pkg import module1 + + +assert not any( + module1.__file__.endswith(ext) + for ext in '.py .pyc .pyo .pyw .pyx .pxi'.split() +), module.__file__ + + +def run_coverage(module): + assert module.func1(1, 2) == (1 * 2) + 2 + 1 + assert module.func2(2) == 2 * 2 + + +if __name__ == '__main__': + run_coverage(module1) + + +######## collect_coverage.py ######## + +import re +import sys +import os +import os.path +import subprocess +from glob import iglob + + +def run_coverage_command(*command): + env = dict(os.environ, LANG='', LC_ALL='C') + process = subprocess.Popen( + [sys.executable, '-m', 'coverage'] + list(command), + stdout=subprocess.PIPE, env=env) + stdout, _ = process.communicate() + return stdout + + +def run_report(): + stdout = run_coverage_command('report', '--show-missing') + stdout = stdout.decode('iso8859-1') # 'safe' decoding + lines = stdout.splitlines() + print(stdout) + + module_path = 'module1.pyx' + assert any(module_path in line for line in lines), ( + "'%s' not found in coverage report:\n\n%s" % (module_path, stdout)) + + files = {} + line_iter = iter(lines) + for line in line_iter: + if line.startswith('---'): + break + extend = [''] * 2 + for line in line_iter: + if not line or line.startswith('---'): + continue + name, statements, missed, covered, _missing = (line.split(None, 4) + extend)[:5] + missing = [] + for start, end in re.findall('([0-9]+)(?:-([0-9]+))?', _missing): + if end: + missing.extend(range(int(start), int(end)+1)) + else: + missing.append(int(start)) + files[os.path.basename(name)] = (statements, missed, covered, missing) + assert 5 not in files[module_path][-1], files[module_path] + assert 6 not in files[module_path][-1], files[module_path] + assert 7 not in files[module_path][-1], files[module_path] + assert 11 not in files[module_path][-1], files[module_path] + + +def run_xml_report(): + stdout = run_coverage_command('xml', '-o', '-') + print(stdout) + + import xml.etree.ElementTree as etree + data = etree.fromstring(stdout) + + files = {} + for module in data.iterfind('.//class'): + files[module.get('filename').replace('\\', '/')] = dict( + (int(line.get('number')), int(line.get('hits'))) + for line in module.findall('lines/line') + ) + + module_path = 'src/pkg/module1.pyx' + + assert files[module_path][5] > 0, files[module_path] + assert files[module_path][6] > 0, files[module_path] + assert files[module_path][7] > 0, files[module_path] + assert files[module_path][11] > 0, files[module_path] + + +def run_html_report(): + from collections import defaultdict + + stdout = run_coverage_command('html', '-d', 'html') + # coverage 6.1+ changed the order of the attributes => need to parse them separately + _parse_id = re.compile(r'id=["\'][^0-9"\']*(?P<id>[0-9]+)[^0-9"\']*["\']').search + _parse_state = re.compile(r'class=["\'][^"\']*(?P<state>mis|run|exc)[^"\']*["\']').search + + files = {} + for file_path in iglob('html/*.html'): + with open(file_path) as f: + page = f.read() + report = defaultdict(set) + for line in re.split(r'id=["\']source["\']', page)[-1].splitlines(): + lineno = _parse_id(line) + state = _parse_state(line) + if not lineno or not state: + continue + report[state.group('state')].add(int(lineno.group('id'))) + files[file_path] = report + + file_report = [data for path, data in files.items() if 'module1' in path][0] + executed, missing = file_report["run"], file_report["mis"] + assert executed + assert 5 in executed, executed + assert 6 in executed, executed + assert 7 in executed, executed + assert 11 in executed, executed + + +if __name__ == '__main__': + run_report() + run_xml_report() + run_html_report()
Coverage plugin is broken on Cython modules in packages with sources in src-layout _(Ref: https://twitter.com/webKnjaZ/status/1265373614003625987)_ Having a module under src-layout causes `Cython.Coverage.Plugin` to not set itself as a tracer in the DB. And even when it's set, it fails to matchthe module with its sources I've made a reproducer repo with GitHub Actions Workflow integrated as a demo of this bug: - https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636 - https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636/runs/718112079?check_suite_focus=true#step:13:6 When this happens, the following message is printed out during the report stage: ```console Couldn't parse '..../src/call_mymath/call_mymath.pyx' as Python source: 'invalid syntax' at line 1 ``` Reproducer details: ================== It's based on the example https://github.com/cython/cython/tree/master/Demos/libraries with a slightly modified structure: ```console |- mymath.c |- mymath.h |- setup.py |- src/ |- call_mymath/ |- call_mymath.pyx |- __init__.py |-flat_ns_call_mymath.pyx |- test_cython.py ``` `flat_ns_call_mymath.pyx` is the same as `call_mymath.pyx` (the only thing modified inside is relative path to the C-header). `setup.py` puts both `flat_ns_call_mymath.so` and `call_mymath.so` under `call_mymath` package in `site-packages`. So they are importable as `call_mymath.flat_ns_call_mymath` and `call_mymath.call_mymath`. `call_mymath.flat_ns_call_mymath` shows up in the report and `call_mymath.call_mymath` doesn't because `Cython.Coverage.Plugin` fails to map it with the source and claim the file tracing rights. STR === 1. `pip install coverage Cython` 2. `CFLAGS=-DCYTHON_TRACE=1 cythonize --inplace --directive=embedsignature=True --directive=emit_code_comments=True --directive=linetrace=True --directive=profile=True '**/*.pyx'` 3. `pip install .` 4. `coverage run -m test_cython` 5. `coverage report` -- this is where it fails with ```console Couldn't parse '..../src/call_mymath/call_mymath.pyx' as Python source: 'invalid syntax' at line 1 ``` (adding `-i` makes at least `flat_ns_call_mymath` show up correctly) When looking at `.coverage` using `sqlite3`, `flat_ns_call_mymath.pyx` is mapped to `Cython.Coverage.Plugin` in the `tracer` table while there's no record for `call_mymath.pyx` there. Coverage plugin is broken on Cython modules in packages with sources in src-layout _(Ref: https://twitter.com/webKnjaZ/status/1265373614003625987)_ Having a module under src-layout causes `Cython.Coverage.Plugin` to not set itself as a tracer in the DB. And even when it's set, it fails to matchthe module with its sources I've made a reproducer repo with GitHub Actions Workflow integrated as a demo of this bug: - https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636 - https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636/runs/718112079?check_suite_focus=true#step:13:6 When this happens, the following message is printed out during the report stage: ```console Couldn't parse '..../src/call_mymath/call_mymath.pyx' as Python source: 'invalid syntax' at line 1 ``` Reproducer details: ================== It's based on the example https://github.com/cython/cython/tree/master/Demos/libraries with a slightly modified structure: ```console |- mymath.c |- mymath.h |- setup.py |- src/ |- call_mymath/ |- call_mymath.pyx |- __init__.py |-flat_ns_call_mymath.pyx |- test_cython.py ``` `flat_ns_call_mymath.pyx` is the same as `call_mymath.pyx` (the only thing modified inside is relative path to the C-header). `setup.py` puts both `flat_ns_call_mymath.so` and `call_mymath.so` under `call_mymath` package in `site-packages`. So they are importable as `call_mymath.flat_ns_call_mymath` and `call_mymath.call_mymath`. `call_mymath.flat_ns_call_mymath` shows up in the report and `call_mymath.call_mymath` doesn't because `Cython.Coverage.Plugin` fails to map it with the source and claim the file tracing rights. STR === 1. `pip install coverage Cython` 2. `CFLAGS=-DCYTHON_TRACE=1 cythonize --inplace --directive=embedsignature=True --directive=emit_code_comments=True --directive=linetrace=True --directive=profile=True '**/*.pyx'` 3. `pip install .` 4. `coverage run -m test_cython` 5. `coverage report` -- this is where it fails with ```console Couldn't parse '..../src/call_mymath/call_mymath.pyx' as Python source: 'invalid syntax' at line 1 ``` (adding `-i` makes at least `flat_ns_call_mymath` show up correctly) When looking at `.coverage` using `sqlite3`, `flat_ns_call_mymath.pyx` is mapped to `Cython.Coverage.Plugin` in the `tracer` table while there's no record for `call_mymath.pyx` there.
So here's the reproducer: https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636/runs/718112079?check_suite_focus=true#step:13:6. @scoder ^ Turns out that Cythonize generates C-sources that don't include `src/` prefix in path comments. Just adding those comments there makes it show up in the log: ```console $ sed -i s#/\\*[[:space:]]'"'call_mymath/#/*\ '"'src/call_mymath/#g src/call_mymath/call_mymath.c ``` ```diff --- src/call_mymath/call_mymath.c.orig 2020-05-28 23:15:32.663441119 +0200 +++ src/call_mymath/call_mymath.c 2020-05-28 23:17:46.511099303 +0200 @@ -1243,7 +1243,7 @@ static PyObject *__pyx_tuple__2; /* Late includes */ -/* "call_mymath/call_mymath.pyx":4 +/* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1278,7 +1278,7 @@ __Pyx_RefNannySetupContext("call_sinc", 0); __Pyx_TraceCall("call_sinc", __pyx_f[0], 4, 0, __PYX_ERR(0, 4, __pyx_L1_error)); - /* "call_mymath/call_mymath.pyx":5 + /* "src/call_mymath/call_mymath.pyx":5 * * def call_sinc(x): * return sinc(x) # <<<<<<<<<<<<<< @@ -1292,7 +1292,7 @@ __pyx_t_2 = 0; goto __pyx_L0; - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1375,7 +1375,7 @@ __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1667,7 +1667,7 @@ #endif __Pyx_TraceCall("__Pyx_PyMODINIT_FUNC PyInit_call_mymath(void)", __pyx_f[0], 1, 0, __PYX_ERR(0, 1, __pyx_L1_error)); - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1679,7 +1679,7 @@ if (PyDict_SetItem(__pyx_d, __pyx_n_s_call_sinc, __pyx_t_1) < 0) __PYX_ERR(0, 4, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "call_mymath/call_mymath.pyx":1 + /* "src/call_mymath/call_mymath.pyx":1 * cdef extern from "../../mymath.h": # <<<<<<<<<<<<<< * double sinc(double) * ``` But this doesn't explain why `flat_ns_call_mymath.pyx` works. If both don't have `src/` both should work the same way but they don't... So when `Cython.Coverage._find_dep_file_path(main_file='/home/wk/src/github/webknjaz/cython-coverage-extern-bug-repro-issue3636/src/call_mymath/call_mymath.c', file_path='call_mymath/call_mymath.pyx', relative_path_search=True)` is called, it returns `/home/wk/src/github/webknjaz/cython-coverage-extern-bug-repro-issue3636/call_mymath/call_mymath.pyx` with `src/` missing because it doesn't do any exit checks. I'm currently confused by the design decisions: should C-files contain a full path relative to the root of the project or `_find_dep_file_path()` should guess the source correctly? So here's the reproducer: https://github.com/webknjaz/cython-coverage-extern-bug-repro-issue3636/runs/718112079?check_suite_focus=true#step:13:6. @scoder ^ Turns out that Cythonize generates C-sources that don't include `src/` prefix in path comments. Just adding those comments there makes it show up in the log: ```console $ sed -i s#/\\*[[:space:]]'"'call_mymath/#/*\ '"'src/call_mymath/#g src/call_mymath/call_mymath.c ``` ```diff --- src/call_mymath/call_mymath.c.orig 2020-05-28 23:15:32.663441119 +0200 +++ src/call_mymath/call_mymath.c 2020-05-28 23:17:46.511099303 +0200 @@ -1243,7 +1243,7 @@ static PyObject *__pyx_tuple__2; /* Late includes */ -/* "call_mymath/call_mymath.pyx":4 +/* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1278,7 +1278,7 @@ __Pyx_RefNannySetupContext("call_sinc", 0); __Pyx_TraceCall("call_sinc", __pyx_f[0], 4, 0, __PYX_ERR(0, 4, __pyx_L1_error)); - /* "call_mymath/call_mymath.pyx":5 + /* "src/call_mymath/call_mymath.pyx":5 * * def call_sinc(x): * return sinc(x) # <<<<<<<<<<<<<< @@ -1292,7 +1292,7 @@ __pyx_t_2 = 0; goto __pyx_L0; - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1375,7 +1375,7 @@ __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1667,7 +1667,7 @@ #endif __Pyx_TraceCall("__Pyx_PyMODINIT_FUNC PyInit_call_mymath(void)", __pyx_f[0], 1, 0, __PYX_ERR(0, 1, __pyx_L1_error)); - /* "call_mymath/call_mymath.pyx":4 + /* "src/call_mymath/call_mymath.pyx":4 * double sinc(double) * * def call_sinc(x): # <<<<<<<<<<<<<< @@ -1679,7 +1679,7 @@ if (PyDict_SetItem(__pyx_d, __pyx_n_s_call_sinc, __pyx_t_1) < 0) __PYX_ERR(0, 4, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "call_mymath/call_mymath.pyx":1 + /* "src/call_mymath/call_mymath.pyx":1 * cdef extern from "../../mymath.h": # <<<<<<<<<<<<<< * double sinc(double) * ``` But this doesn't explain why `flat_ns_call_mymath.pyx` works. If both don't have `src/` both should work the same way but they don't... So when `Cython.Coverage._find_dep_file_path(main_file='/home/wk/src/github/webknjaz/cython-coverage-extern-bug-repro-issue3636/src/call_mymath/call_mymath.c', file_path='call_mymath/call_mymath.pyx', relative_path_search=True)` is called, it returns `/home/wk/src/github/webknjaz/cython-coverage-extern-bug-repro-issue3636/call_mymath/call_mymath.pyx` with `src/` missing because it doesn't do any exit checks. I'm currently confused by the design decisions: should C-files contain a full path relative to the root of the project or `_find_dep_file_path()` should guess the source correctly?
2020-09-16T14:37:02Z
[]
[]
cython/cython
3,850
cython__cython-3850
[ "3830" ]
8708b74671f3583876d1e277e368f9c49f6b4a30
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -2008,7 +2008,12 @@ def declare_from_annotation(self, env, as_target=False): "'%s' cannot be specialized since its type is not a fused argument to this function" % self.name) atype = error_type - + if as_target and env.is_c_class_scope and not (atype.is_pyobject or atype.is_error): + # TODO: this will need revising slightly if either cdef dataclasses or + # annotated cdef attributes are implemented + atype = py_object_type + warning(annotation.pos, "Annotation ignored since class-level attributes must be Python objects. " + "Were you trying to set up an instance attribute?", 2) entry = self.entry = env.declare_var(name, atype, self.pos, is_cdef=not as_target) # Even if the entry already exists, make sure we're supplying an annotation if we can. if annotation and not entry.annotation:
diff --git a/tests/run/annotation_typing.pyx b/tests/run/annotation_typing.pyx --- a/tests/run/annotation_typing.pyx +++ b/tests/run/annotation_typing.pyx @@ -262,6 +262,10 @@ def py_float_default(price : float=None, ndigits=4): return price, ndigits +cdef class ClassAttribute: + cls_attr : float = 1. + + _WARNINGS = """ 8:32: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. 8:47: Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly. @@ -271,6 +275,7 @@ _WARNINGS = """ 8:85: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. 242:44: Unknown type declaration in annotation, ignoring 249:29: Ambiguous types in annotation, ignoring +266:15: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? # BUG: 46:6: 'pytypes_cpdef' redeclared 120:0: 'struct_io' redeclared diff --git a/tests/run/pep526_variable_annotations.py b/tests/run/pep526_variable_annotations.py --- a/tests/run/pep526_variable_annotations.py +++ b/tests/run/pep526_variable_annotations.py @@ -157,6 +157,7 @@ def iter_declared_dict_arg(d : Dict[float, float]): 38:12: Unknown type declaration in annotation, ignoring 39:18: Unknown type declaration in annotation, ignoring 57:19: Unknown type declaration in annotation, ignoring +73:11: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? 73:19: Unknown type declaration in annotation, ignoring # FIXME: these are sort-of evaluated now, so the warning is misleading 126:21: Unknown type declaration in annotation, ignoring
[BUG] Getting Internal Compiler Errors I am unsure if this is the right place to ask but I am running into an error that doesn't tell me where it happened, just the file it happened in. It appears to be the python end of the compiler but I don't know if that is correct. The command used to compile the files: `cythonize *.pyx --inplace -3` Here's the error: ```Compiling C:\My files\Programming\Python\Games\Game 3\lib\front__lasers.pyx because it changed. [1/1] Cythonizing C:\My files\Programming\Python\Games\Game 3\lib\front__lasers.pyx Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python38\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\user\appdata\local\programs\python\python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\user\AppData\Local\Programs\Python\Python38\Scripts\cythonize.exe\__main__.py", line 7, in <module> File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Build\Cythonize.py", line 223, in main cython_compile(path, options) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Build\Cythonize.py", line 97, in cython_compile ext_modules = cythonize( File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Build\Dependencies.py", line 1102, in cythonize cythonize_one(*args) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Build\Dependencies.py", line 1208, in cythonize_one result = compile_single(pyx_file, options, full_module_name=full_module_name) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Main.py", line 727, in compile_single return run_pipeline(source, options, full_module_name) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Main.py", line 515, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Pipeline.py", line 355, in run_pipeline data = run(phase, data) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Pipeline.py", line 335, in run return phase(data) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\ModuleNode.py", line 143, in process_implementation self.generate_c_code(env, options, result) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\ModuleNode.py", line 398, in generate_c_code self.generate_module_init_func(modules[:-1], env, globalstate['init_module']) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\ModuleNode.py", line 2474, in generate_module_init_func self.body.generate_execution_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 448, in generate_execution_code stat.generate_execution_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 448, in generate_execution_code stat.generate_execution_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 4860, in generate_execution_code self.body.generate_execution_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 448, in generate_execution_code stat.generate_execution_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 5186, in generate_execution_code self.generate_assignment_code(code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 5483, in generate_assignment_code self.lhs.generate_assignment_code(self.rhs, code) File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\ExprNodes.py", line 2292, in generate_assignment_code assert entry.type.is_pyobject, "Python global or builtin not a Python object" AssertionError: Python global or builtin not a Python object
This is a bug in the sense that it gives internal compiler errors rather that a useful message telling you what's wrong. However, there's definitely little we can tell from the details you've given. You could try: 1. The standard debugging technique of progressively removing code from your source file until you find out what bit's causing it. 2. Upgrade Cython to the 3.0 alpha branch (I think error reporting has been improved a bit, or the underlying issue may have been fixed). 3. If you're prepared to get into the Cython code then add ` + str(self.pos)` to the assertion line and that should given you more information. You may need to recompile. Where did you get `self.pos` from? Many of the classes in this file have an attribute of `pos` and I don't think the error message mentioned anything about it. Also I modified the cython compiler's assertion statement and have found what object was causing the error. A class variable was set to None by a parent class and is later reassigned as 0.5 by a subclass. I had normal python type hints for these and removing them stopped this from occuring. I'm not sure why that would cause a problem. Regardless, thanks for your help. The bug of showing this type of error still stands so I won't close the issue myself. > Where did you get `self.pos` from? Many of the classes in this file have an attribute of `pos` and I don't think the error message mentioned anything about it. All the nodes store a `pos` attribute to represent where in the source code they come from. It's just an internal detail used for error reporting. > The bug of showing this type of error still stands so I won't close the issue myself. Could you show the chunk of code that produces the error? > Could you show the chunk of code that produces the error? ``` cdef class A: COLOR:colors.RGBType = None # For whatever reason this is considered ok, but not the one directly below. Perhaps because this type that it is hinting to is a not a cython primitive? DENSITY:float = None # Here is what used to be the culprit, the type hinting. Somehow. SPREAD = None # rest of the class goes here cdef class B(A): COLOR:colors.RGBType = colors.blue DENSITY:float = 1 SPREAD = 0 # rest of the class goes here cdef class C(B): SPREAD = 10 # rest of the class goes here cdef class B2(A): COLOR:colors.RGBType = colors.red DENSITY:float = 0.5 SPREAD = 10 # rest of the class goes here cdef class C2(B2): SPREAD = 50 # rest of the class goes here ``` Sorry I'm not sure if these mock up class names are easy to read. I'll edit this comment if you like. Thanks. For what it's worth I can reproduce the error with: ``` cdef class A: DENSITY:float = 0.5 ``` but not with `Density:float = None` which just gives me `Cannot assign None to double` (as expected). I think the issue is type-hinted variables like this become instance variables rather than class variables for a `cdef class`, so it doesn't make sense to assign anything to them. But the error message should definitely be better Yea it makes a lot more sense now, but as you said the error message should definitely be better. Thanks for your help.
2020-09-29T07:09:34Z
[]
[]
cython/cython
3,872
cython__cython-3872
[ "3751" ]
434882af22b8c1941f078557b6411a1af63d099b
diff --git a/Cython/Build/IpythonMagic.py b/Cython/Build/IpythonMagic.py --- a/Cython/Build/IpythonMagic.py +++ b/Cython/Build/IpythonMagic.py @@ -82,6 +82,7 @@ from ..Compiler.Errors import CompileError from .Inline import cython_inline from .Dependencies import cythonize +from ..Utils import captured_fd PGO_CONFIG = { @@ -106,6 +107,37 @@ def encode_fs(name): return name +def get_encoding_candidates(): + candidates = [sys.getdefaultencoding()] + for stream in (sys.stdout, sys.stdin, sys.__stdout__, sys.__stdin__): + encoding = getattr(stream, 'encoding', None) + # encoding might be None (e.g. somebody redirects stdout): + if encoding is not None and encoding not in candidates: + candidates.append(encoding) + return candidates + + +def prepare_captured(captured): + captured_bytes = captured.strip() + if not captured_bytes: + return None + for encoding in get_encoding_candidates(): + try: + return captured_bytes.decode(encoding) + except UnicodeDecodeError: + pass + # last resort: print at least the readable ascii parts correctly. + return captured_bytes.decode('latin-1') + + +def print_captured(captured, output, header_line=None): + captured = prepare_captured(captured) + if captured: + if header_line: + output.write(header_line) + output.write(captured) + + @magics_class class CythonMagics(Magics): @@ -342,13 +374,25 @@ def critical_function(data): if args.pgo: self._profile_pgo_wrapper(extension, lib_dir) + def print_compiler_output(stdout, stderr, where): + # On windows, errors are printed to stdout, we redirect both to sys.stderr. + print_captured(stdout, where, u"Content of stdout:\n") + print_captured(stderr, where, u"Content of stderr:\n") + + get_stderr = get_stdout = None try: - self._build_extension(extension, lib_dir, pgo_step_name='use' if args.pgo else None, - quiet=args.quiet) - except distutils.errors.CompileError: - # Build failed and printed error message + with captured_fd(1) as get_stdout: + with captured_fd(2) as get_stderr: + self._build_extension( + extension, lib_dir, pgo_step_name='use' if args.pgo else None, quiet=args.quiet) + except (distutils.errors.CompileError, distutils.errors.LinkError): + # Build failed, print error message from compiler/linker + print_compiler_output(get_stdout(), get_stderr(), sys.stderr) return None + # Build seems ok, but we might still want to show any warnings that occurred + print_compiler_output(get_stdout(), get_stderr(), sys.stdout) + module = imp.load_dynamic(module_name, module_path) self._import_all(module)
diff --git a/Cython/Build/Tests/TestIpythonMagic.py b/Cython/Build/Tests/TestIpythonMagic.py --- a/Cython/Build/Tests/TestIpythonMagic.py +++ b/Cython/Build/Tests/TestIpythonMagic.py @@ -6,6 +6,7 @@ from __future__ import absolute_import import os +import io import sys from contextlib import contextmanager from Cython.Build import IpythonMagic @@ -29,6 +30,26 @@ def skip_if_not_installed(c): except ImportError: pass + +@contextmanager +def capture_output(): + backup = sys.stdout, sys.stderr + try: + replacement = [ + io.TextIOWrapper(io.BytesIO(), encoding=sys.stdout.encoding), + io.TextIOWrapper(io.BytesIO(), encoding=sys.stderr.encoding), + ] + sys.stdout, sys.stderr = replacement + output = [] + yield output + finally: + sys.stdout, sys.stderr = backup + for wrapper in replacement: + wrapper.seek(0) # rewind + output.append(wrapper.read()) + wrapper.close() + + code = u"""\ def f(x): return 2*x @@ -48,6 +69,27 @@ def main(): main() """ +compile_error_code = u'''\ +cdef extern from *: + """ + xxx a=1; + """ + int a; +def doit(): + return a +''' + +compile_warning_code = u'''\ +cdef extern from *: + """ + #pragma message ( "CWarning" ) + int a = 42; + """ + int a; +def doit(): + return a +''' + if sys.platform == 'win32': # not using IPython's decorators here because they depend on "nose" @@ -143,6 +185,39 @@ def test_cython2(self): self.assertEqual(ip.user_ns['g'], 2 // 10) self.assertEqual(ip.user_ns['h'], 2 // 10) + def test_cython_compile_error_shown(self): + ip = self._ip + with capture_output() as out: + ip.run_cell_magic('cython', '-3', compile_error_code) + captured_out, captured_err = out + + # it could be that c-level output is captured by distutil-extension + # (and not by us) and is printed to stdout: + captured_all = captured_out + "\n" + captured_err + self.assertTrue("error" in captured_all, msg="error in " + captured_all) + + def test_cython_link_error_shown(self): + ip = self._ip + with capture_output() as out: + ip.run_cell_magic('cython', '-3 -l=xxxxxxxx', code) + captured_out, captured_err = out + + # it could be that c-level output is captured by distutil-extension + # (and not by us) and is printed to stdout: + captured_all = captured_out + "\n!" + captured_err + self.assertTrue("error" in captured_all, msg="error in " + captured_all) + + def test_cython_warning_shown(self): + ip = self._ip + with capture_output() as out: + # force rebuild, otherwise no warning as after the first success + # no build step is performed + ip.run_cell_magic('cython', '-3 -f', compile_warning_code) + captured_out, captured_err = out + + # check that warning was printed to stdout even if build hasn't failed + self.assertTrue("CWarning" in captured_out) + @skip_win32('Skip on Windows') def test_cython3_pgo(self): # The Cython cell defines the functions f() and call().
[Jupyter] Fails silently on importing C header file in same folder The code below "evaluates" without any error messages. By myadd is never defined, and the annotation output is never produced. Removing the dependency on add.h makes everything work without a problem. ## File system: ``` src/ - add.h - Notebook.ipynb ``` ## C Header File (standalone) ```c // add.h int add(int x, int y) { return x + y; } ``` ## Jupyter Notebook: ```py # Input cell [1] %load_ext cython ``` ```py # Input cell [2] %%cython --annotate cdef extern from "add.h": int add(int x, int y) cpdef myadd(int x, int y): cdef int total = add(x, y) return total ``` --- To reproduce/use the same environment, you can use docker: ```sh docker run --rm -it -p8888:8888 jupyter/scipy-notebook:ea01ec4d9f57 ```
Changing to the following makes it work. (Notice that I added `-I.` at the top) ```py # Input cell [2] %%cython --annotate -I. cdef extern from "add.h": int add(int x, int y) cpdef myadd(int x, int y): cdef int total = add(x, y) return total ``` Would be nice if an error was thrown, saying the header file was not found. Failing silently makes it a lot harder to track down the problem. The compile output from Jupyter output appears in the terminal that Jupyter is run in, not the notebook itself. It would be nice if it could be redirected to the notebook (at least on failure) - it'd save a lot of confusion for people. I don't think capturing and redirecting it is particularly easy though. Duplicate of https://github.com/cython/cython/issues/1569 ~~Try with the --verbose option and it should be more obvious~~ On closer inspection the verbose option doesn't look to be that much more verbose. I think intercepting the compiler output is harder than it looks. I'll reopen and someone else can decide what to do with this. I think the problem comes with #3196: While in IPython one can see things printed to c-level stdout this is not the case for Jupiter-notebooks. There is `wurlitzer` (https://github.com/minrk/wurlitzer) which has the IPython-magic `%load_ext wurlizer` to capture C-level stdout for Jupiter-notebooks, sadly it works only for Linux (and probably macOS), but this is probably not the way to go. Another problem with #3196 is that while it catches `distutils.errors.CompileError` it doesn't catch the `distutils.errors.LinkError`, for which one still sees the old message. Maybe a better solution would be to catch both exceptions, but also to print to `sys.stderr` (which for Jupiter-notebook has nothing to do with C-level stderr) that an error has happened while compiling/linking and the user should see logs on C-level stderr/stdout? Isn't it enough to divert `sys.stderr` before running the extension build? That obviously introduces concurrency problems if we're not the only thread creating output at this time, but that case should be fairly rare, at least for most users. Everything beyond that, I'd say, should be improved on the side of [setuptools](https://github.com/pypa/setuptools/tree/master/setuptools/_distutils), which controls the C compiler run. @scoder > Isn't it enough to divert `sys.stderr` before running the extension build? Not sure I understand that, I think redirecting `sys.stderr` will not change where the C-level output will be written to? When compiler (or linker) is called by `distutils`, the output of the compiler/linker isn't captured (see [here](https://github.com/python/cpython/blob/497126f7ea955ee005e78f2cdd61f175d4fcdbb2/Lib/distutils/spawn.py#L74-L77)): ``` try: proc = subprocess.Popen(cmd, env=env) proc.wait() exitcode = proc.returncode ``` and goes directly to the C-level stdout/stderr bypassing the whole python-IO-machinery. In normal python/ipython session we still see linker/gcc-output, because it is the same terminal. However in a jupyter-notebook, only things printed to python's stdout/stderr are rendered in the browser, not the things printed directly to C-level stdout/stderr (which are seen in the terminal from which the jupyter was started). This is the reason why right now, even if compile step failed, a Jupyter user assumes, that everything worked as expected and sees no feedback, that the building the extension failed, see #3840 1) The best way is probably to catch stderr/stdout while calling compiler/linker in distutils and redirect this to python's stderr/stdout (not sure why this wasn't done in the first place). Not sure whether this solution makes sense or is feasible any time soon. 2) First workaround: One could catch the C-level output while executing %%cython, and redirect it to sys.stderr. There is [wurlitzer](https://github.com/minrk/wurlitzer), which does that (based on this [article](https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/)), but its approach with `ctypes` doesn't work on Windows (at least not out-of-the box, I also wasn't able to make it work, but maybe it is just me). However, it is possible to write a C-extension, which would work for Linux and Windows. I have written a prototype with Cython some time ago (https://github.com/realead/coutcatcher), not sure it is waterproof tough. 3) Minimal workaround (at core of PR #3819): notify the user, that the build didn't succeed, which gives a hint to look for the output in terminal. Even if I bug python-devs with 1) now, it will take time (if it will be considered a valid concern) to be fixed/improved. Until then 3) would be not ideal, but at least an improvement compared to the current situation. What would be a good solution from your point of view? I'll try my best to implement it and to provide a PR to solve this problem. In our test runner, we do this: https://github.com/cython/cython/blob/af757997c7d13c00b579fd00393350d9367dd12a/Cython/Utils.py#L396-L433 Admittedly, that's a bit involved, but it gets the job done. Note that the people to approach for 1) are not the CPython devs but the setuptools devs. The distutils package in the standard library has been deprecated and development has moved to setuptools. See my link above.
2020-10-07T21:44:58Z
[]
[]
cython/cython
3,886
cython__cython-3886
[ "1355" ]
0b74f1d14172c0465426238010189d3cea211ccf
diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -2698,7 +2698,7 @@ def looking_at_expr(s): s.put_back(*saved) elif s.sy == '[': s.next() - is_type = s.sy == ']' + is_type = s.sy == ']' or not looking_at_expr(s) # could be a nested template type s.put_back(*saved) dotted_path.reverse()
diff --git a/tests/compile/cpp_templates_nested.pyx b/tests/compile/cpp_templates_nested.pyx new file mode 100644 --- /dev/null +++ b/tests/compile/cpp_templates_nested.pyx @@ -0,0 +1,18 @@ +# tag: cpp +# mode: compile + +from libcpp.vector cimport vector + +cdef extern from *: + cdef cppclass Foo[T]: + pass + + cdef cppclass Bar: + pass + +cdef vector[vector[int]] a +cdef vector[vector[const int]] b +cdef vector[vector[vector[int]]] c +cdef vector[vector[vector[const int]]] d +cdef Foo[Foo[Bar]] e +cdef Foo[Foo[const Bar]] f
const fails when used as the argument to a template of a template This works: ``` from libcpp.vector cimport vector cdef extern from "Test.hpp": cdef vector[char](const) f() ``` As does this: ``` from libcpp.vector cimport vector cdef extern from "Test.hpp": cdef vector[f() ``` But this causes a Cython parse error on Cython 0.18: ``` from libcpp.vector cimport vector cdef extern from "Test.hpp": cdef vector[vector[const char](vector[char]])] f() ``` Migrated from http://trac.cython.org/ticket/798
**garrison** changed **cc** to `garrison` commented The obvious work-around is a `ctypedef`, but it seems worth fixing. The parser calls `p_buffer_or_template()` to parse the `[…]` part, which then calls `p_positional_and_keyword_args()` to parse what's inside of the brackets. I guess that simply doesn't allow template type declarations. It could, though. That would probably also help with template type parsing in function signatures. Also needs a test, probably in one of the tests/run/cpp_*.pyx modules. Taking a look
2020-10-23T16:00:25Z
[]
[]
cython/cython
3,939
cython__cython-3939
[ "3796" ]
8609e0fa7d361f1392823ff6e1a618720cd62df3
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -3340,7 +3340,7 @@ class FormattedValueNode(ExprNode): # {}-delimited portions of an f-string # # value ExprNode The expression itself - # conversion_char str or None Type conversion (!s, !r, !a, or none, or 'd' for integer conversion) + # conversion_char str or None Type conversion (!s, !r, !a, none, or 'd' for integer conversion) # format_spec JoinedStrNode or None Format string passed to __format__ # c_format_spec str or None If not None, formatting can be done at the C level diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -1081,8 +1081,8 @@ def p_f_string(s, unicode_value, pos, is_raw): if builder.chars: values.append(ExprNodes.UnicodeNode(pos, value=builder.getstring())) builder = StringEncoding.UnicodeLiteralBuilder() - next_start, expr_node = p_f_string_expr(s, unicode_value, pos, next_start, is_raw) - values.append(expr_node) + next_start, expr_nodes = p_f_string_expr(s, unicode_value, pos, next_start, is_raw) + values.extend(expr_nodes) elif c == '}': if part == '}}': builder.append('}') @@ -1098,12 +1098,16 @@ def p_f_string(s, unicode_value, pos, is_raw): def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw): - # Parses a {}-delimited expression inside an f-string. Returns a FormattedValueNode - # and the index in the string that follows the expression. + # Parses a {}-delimited expression inside an f-string. Returns a list of nodes + # [UnicodeNode?, FormattedValueNode] and the index in the string that follows + # the expression. + # + # ? = Optional i = starting_index size = len(unicode_value) conversion_char = terminal_char = format_spec = None format_spec_str = None + expr_text = None NO_CHAR = 2**30 nested_depth = 0 @@ -1143,11 +1147,17 @@ def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw): elif c == '#': error(_f_string_error_pos(pos, unicode_value, i), "format string cannot include #") - elif nested_depth == 0 and c in '!:}': - # allow != as a special case - if c == '!' and i + 1 < size and unicode_value[i + 1] == '=': - i += 1 - continue + elif nested_depth == 0 and c in '><=!:}': + # allow special cases with '!' and '=' + if i + 1 < size: + chars = c + unicode_value[i + 1] + if chars in ('!=', '==', '>=', '<='): + i += 2 # we checked 2, so we can skip 2 + continue + + if c in '><': # allow single '<' and '>' + i += 1 + continue terminal_char = c break @@ -1161,6 +1171,16 @@ def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw): error(_f_string_error_pos(pos, unicode_value, starting_index), "empty expression not allowed in f-string") + if terminal_char == '=': + i += 1 + while i < size and unicode_value[i].isspace(): + i += 1 + + if i < size: + terminal_char = unicode_value[i] + expr_text = unicode_value[starting_index:i] + # otherwise: error will be reported below + if terminal_char == '!': i += 1 if i + 2 > size: @@ -1198,6 +1218,9 @@ def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw): format_spec_str = unicode_value[start_format_spec:i] + if expr_text and conversion_char is None and format_spec_str is None: + conversion_char = 'r' + if terminal_char != '}': error(_f_string_error_pos(pos, unicode_value, i), "missing '}' in format string expression" + ( @@ -1216,8 +1239,12 @@ def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw): if format_spec_str: format_spec = ExprNodes.JoinedStrNode(pos, values=p_f_string(s, format_spec_str, pos, is_raw)) - return i + 1, ExprNodes.FormattedValueNode( - pos, value=expr, conversion_char=conversion_char, format_spec=format_spec) + nodes = [] + if expr_text: + nodes.append(ExprNodes.UnicodeNode(pos, value=StringEncoding.EncodedString(expr_text))) + nodes.append(ExprNodes.FormattedValueNode(pos, value=expr, conversion_char=conversion_char, format_spec=format_spec)) + + return i + 1, nodes # since PEP 448:
diff --git a/tests/run/test_fstring.pyx b/tests/run/test_fstring.pyx --- a/tests/run/test_fstring.pyx +++ b/tests/run/test_fstring.pyx @@ -10,6 +10,10 @@ import unittest import sys IS_PY2 = sys.version_info[0] < 3 +if IS_PY2: + # Define `ascii` as `repr` for Python2 as it functions + # the same way in that version. + ascii = repr from Cython.Build.Inline import cython_inline from Cython.TestUtils import CythonTest @@ -1122,8 +1126,7 @@ non-important content self.assertEqual(cy_eval('f"\\\n"'), '') self.assertEqual(cy_eval('f"\\\r"'), '') - """ - def __test_debug_conversion(self): + def test_debug_conversion(self): x = 'A string' self.assertEqual(f'{x=}', 'x=' + repr(x)) self.assertEqual(f'{x =}', 'x =' + repr(x)) @@ -1169,10 +1172,11 @@ non-important content self.assertEqual(f'{0!=1}', 'True') self.assertEqual(f'{0<=1}', 'True') self.assertEqual(f'{0>=1}', 'False') - self.assertEqual(f'{(x:="5")}', '5') - self.assertEqual(x, '5') - self.assertEqual(f'{(x:=5)}', '5') - self.assertEqual(x, 5) + # Walrus not implemented yet, skip + # self.assertEqual(f'{(x:="5")}', '5') + # self.assertEqual(x, '5') + # self.assertEqual(f'{(x:=5)}', '5') + # self.assertEqual(x, 5) self.assertEqual(f'{"="}', '=') x = 20 @@ -1226,7 +1230,7 @@ non-important content # the tabs to spaces just to shut up patchcheck. #self.assertEqual(f'X{x =}Y', 'Xx\t='+repr(x)+'Y') #self.assertEqual(f'X{x = }Y', 'Xx\t=\t'+repr(x)+'Y') - """ + def test_walrus(self): x = 20 @@ -1234,6 +1238,8 @@ non-important content # spec of '=10'. self.assertEqual(f'{x:=10}', ' 20') + # Note to anyone going to enable these: please have a look to the test + # above this one for more walrus cases to enable. """ # This is an assignment expression, which requires parens. self.assertEqual(f'{(x:=10)}', '10')
[BUG] self documenting expressions in f-strings **Describe the bug** Python 3.8 added support for the `=` specifier in f-strings to provide self documenting expressions. Using this feature makes a file fail to compile. **To Reproduce** test.py: ```test.py x = 1 print(f"{x=}") ``` then run: ``` $ python test.py x=1 $ cython -3 test.py Error compiling Cython file: ------------------------------------------------------------ ... x = 1 print(f"{x=}") ^ ------------------------------------------------------------ test.py:2:13: Expected ')', found '=' ``` **Expected behavior** No error compiling the file **Environment (please complete the following information):** - OS: macOS - Python version 3.8.3 - Cython version 0.29.21 **Additional context** https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging
I can confirm this also in Cython==3.0a6 on windows. Probably easy to implement in `Parsing.py`. PR welcome.
2020-12-09T14:06:48Z
[]
[]
cython/cython
3,943
cython__cython-3943
[ "3913" ]
434882af22b8c1941f078557b6411a1af63d099b
diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -2376,8 +2376,7 @@ def runtests_callback(args): def runtests(options, cmd_args, coverage=None): # faulthandler should be able to provide a limited traceback - # in the event of a segmentation fault. Hopefully better than Travis - # just keeping running until timeout. Only available on Python 3.3+ + # in the event of a segmentation fault. Only available on Python 3.3+ try: import faulthandler except ImportError: @@ -2544,8 +2543,8 @@ def runtests(options, cmd_args, coverage=None): sys.stderr.write("Backends: %s\n" % ','.join(backends)) languages = backends - if 'TRAVIS' in os.environ and sys.platform == 'darwin' and 'cpp' in languages: - bugs_file_name = 'travis_macos_cpp_bugs.txt' + if 'CI' in os.environ and sys.platform == 'darwin' and 'cpp' in languages: + bugs_file_name = 'macos_cpp_bugs.txt' exclude_selectors += [ FileListExcluder(os.path.join(ROOTDIR, bugs_file_name), verbose=verbose_excludes)
diff --git a/tests/build/common_include_dir.srctree b/tests/build/common_include_dir.srctree --- a/tests/build/common_include_dir.srctree +++ b/tests/build/common_include_dir.srctree @@ -16,18 +16,17 @@ PYTHON fake_grep.py -c '#include "common/AddTraceback_impl_.*h"' c.c import sys from Cython.Build.Dependencies import cythonize -import platform import os from distutils.core import setup -# os x on Travis specifically seems to crash with nthreads>0 -osx_on_travis = (platform.system() == "Darwin" and os.getenv("TRAVIS")) +# os x on CI specifically seems to crash with nthreads>0 +osx_on_ci = (sys.platform == "darwin" and os.getenv("CI")) # Test concurrent safety if multiprocessing is available. -# (In particular, TravisCI does not support spawning processes from tests.) +# (In particular, CI providers like Travis and Github Actions do not support spawning processes from tests.) nthreads = 0 -if not (hasattr(sys, 'pypy_version_info') or osx_on_travis): +if not (hasattr(sys, 'pypy_version_info') or osx_on_ci): try: import multiprocessing multiprocessing.Pool(2).close() diff --git a/tests/travis_macos_cpp_bugs.txt b/tests/macos_cpp_bugs.txt similarity index 100% rename from tests/travis_macos_cpp_bugs.txt rename to tests/macos_cpp_bugs.txt diff --git a/tests/pypy_bugs.txt b/tests/pypy_bugs.txt --- a/tests/pypy_bugs.txt +++ b/tests/pypy_bugs.txt @@ -10,6 +10,7 @@ sequential_parallel yield_from_pep380 memoryview_inplace_division +run.unicodeliterals run.unicodemethods run.unicode_imports run.test_genericclass @@ -64,14 +65,3 @@ run.exttype_dealloc # bugs in cpyext run.special_methods_T561 run.special_methods_T561_py2 - -# looks to be fixed in PyPy 7.3.0 -# TODO - remove when Travis updates -run.py_unicode_strings -run.unicodeliterals -run.unicode_identifiers -run.unicode_identifiers_import -errors.unicode_identifiers_e4 -run.tracebacks -run.fstring -run.unicode_identifiers_normalization
Move away from travis-ci Sadly, the current situation with travis-ci has become unbearable. Investigate Linux/macOS (and Windows) options on - circle-ci - azure - potentially also Github Actions, but that seems more work for less benefit currently (no Windows support, very different setup). We currently use [multibuild](https://github.com/matthew-brett/multibuild/) in the [cython-wheels](https://github.com/MacPython/cython-wheels) project, but should also consider [cibuildwheel](https://pypi.org/project/cibuildwheel/).
Hi, I should be able to help with this. Also I wouldn't rule out Github Actions. They actually have Windows support and their setup isn't all that different from other providers. If needed, I could help set up Github Actions as it is currently quite fresh after having to move one of our projects out of travis :sweat_smile:. Also, compared to other providers, its free for open source (the 2,000 minutes is only for private projects) and its quite fast after the first run cibuildwheel is a nice option. matplotlib has [moved to using it](https://github.com/matplotlib/matplotlib/blob/master/.github/workflows/cibuildwheel.yml). One nice thing about the wheel building model in cibuildwheel is that the different python jobs can be run consecutively in the same build step, one after another. With github actions, admins can trigger the build action from the "Actions" tab on the repo without leaving github. For arm64, one option is [shippable](https://www.shippable.com/pricing.html) which is what NumPy uses for testing. The machines are less powerful than the travis graviton machines: the builds are about 2x longer than on x86.
2020-12-13T22:53:41Z
[]
[]
cython/cython
4,001
cython__cython-4001
[ "4000" ]
75da5a9e1996830b83d5605f85caba2a9fde4690
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -6214,7 +6214,7 @@ def attribute_is_likely_method(attr): # not an attribute itself, but might have been assigned from one (e.g. bound method) for assignment in self.function.cf_state: value = assignment.rhs - if value and value.is_attribute and value.obj.type.is_pyobject: + if value and value.is_attribute and value.obj.type and value.obj.type.is_pyobject: if attribute_is_likely_method(value): likely_method = 'likely' break @@ -6938,7 +6938,11 @@ def infer_type(self, env): # FIXME: this is way too redundant with analyse_types() node = self.analyse_as_cimported_attribute_node(env, target=False) if node is not None: - return node.entry.type + if node.entry.type and node.entry.type.is_cfunction: + # special-case - function converted to pointer + return PyrexTypes.CPtrType(node.entry.type) + else: + return node.entry.type node = self.analyse_as_type_attribute(env) if node is not None: return node.entry.type
diff --git a/tests/run/cimport.srctree b/tests/run/cimport.srctree --- a/tests/run/cimport.srctree +++ b/tests/run/cimport.srctree @@ -41,6 +41,8 @@ ctypedef int my_int ######## a.pyx ######## + + from other cimport ( A, foo, @@ -48,7 +50,17 @@ from other cimport ( print(A, foo(10)) cimport other -print(other.A, other.foo(10)) + +cdef call_fooptr(int (*fptr)(int)): + return fptr(10) + +def call_other_foo(): + x = other.foo # GH4000 - failed because other was untyped + return call_fooptr(x) # check that x is correctly resolved as a function pointer + + + +print(other.A, other.foo(10), call_other_foo()) from pkg cimport sub cdef sub.my_int a = 100
[BUG] Cythonizing fails due to AttributeError when calling a cpdef function from a cimport'ed module **Describe the bug** Not sure if this is related to #1317 or #3193. In Module 2 if I first hold a reference to a cpdef function from (cimported) Module 1, and then call that function (via the reference), the compiler errors out during cythonizing with the following output: ``` $ cythonize -i -3 test_cpdef_func_ptr2.pyx Compiling /home/leofang/dev/test_cpdef_func_ptr2.pyx because it changed. [1/1] Cythonizing /home/leofang/dev/test_cpdef_func_ptr2.pyx Traceback (most recent call last): File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/bin/cythonize", line 11, in <module> sys.exit(main()) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Build/Cythonize.py", line 223, in main cython_compile(path, options) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Build/Cythonize.py", line 106, in cython_compile **options.options) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Build/Dependencies.py", line 1102, in cythonize cythonize_one(*args) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Build/Dependencies.py", line 1208, in cythonize_one result = compile_single(pyx_file, options, full_module_name=full_module_name) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Main.py", line 727, in compile_single return run_pipeline(source, options, full_module_name) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Main.py", line 515, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Pipeline.py", line 355, in run_pipeline data = run(phase, data) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Pipeline.py", line 335, in run return phase(data) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/ModuleNode.py", line 143, in process_implementation self.generate_c_code(env, options, result) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/ModuleNode.py", line 385, in generate_c_code self.body.generate_function_definitions(env, code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 442, in generate_function_definitions stat.generate_function_definitions(env, code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 442, in generate_function_definitions stat.generate_function_definitions(env, code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 3174, in generate_function_definitions FuncDefNode.generate_function_definitions(self, env, code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 1981, in generate_function_definitions self.generate_function_body(env, code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 1743, in generate_function_body self.body.generate_execution_code(code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 448, in generate_execution_code stat.generate_execution_code(code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/Nodes.py", line 5988, in generate_execution_code value.generate_evaluation_code(code) File "/home/leofang/miniconda3/envs/cupy_cuda112_dev/lib/python3.7/site-packages/Cython/Compiler/ExprNodes.py", line 6052, in generate_evaluation_code if value and value.is_attribute and value.obj.type.is_pyobject: AttributeError: 'NoneType' object has no attribute 'is_pyobject' ``` **To Reproduce** Cythonizing the second module gives the above error: `test_cpdef_func_ptr1.pxd`: ```cython cpdef int f() except? -1 ``` `test_cpdef_func_ptr1.pyx`: ```cython cpdef int f() except? -1: return 123 ``` `test_cpdef_func_ptr2.pyx`: ```cython cimport test_cpdef_func_ptr1 cpdef g(): x = test_cpdef_func_ptr1.f return x() ``` **Expected behavior** If in the 2nd module I instead cimport only `f` from the 1st module and then do `x = f`, it'd work. I expect the same behavior for my above snippet. **Environment (please complete the following information):** - OS: Linux - Python version: 3.7.9 - Cython version: 0.29.21 **Additional context** N/A
This also breaks with `cdef` methods so it isn't `cpdef` special-casing
2021-02-07T09:41:52Z
[]
[]
cython/cython
4,063
cython__cython-4063
[ "1428" ]
3048be77631d91ddf9210c34f8de436ab70d7c04
diff --git a/Cython/Build/Dependencies.py b/Cython/Build/Dependencies.py --- a/Cython/Build/Dependencies.py +++ b/Cython/Build/Dependencies.py @@ -534,7 +534,7 @@ def included_files(self, filename): for include in self.parse_dependencies(filename)[1]: include_path = join_path(os.path.dirname(filename), include) if not path_exists(include_path): - include_path = self.context.find_include_file(include, None) + include_path = self.context.find_include_file(include, source_file_path=filename) if include_path: if '.' + os.path.sep in include_path: include_path = os.path.normpath(include_path) @@ -588,17 +588,18 @@ def find_pxd(self, module, filename=None): return None # FIXME: error? module_path.pop(0) relative = '.'.join(package_path + module_path) - pxd = self.context.find_pxd_file(relative, None) + pxd = self.context.find_pxd_file(relative, source_file_path=filename) if pxd: return pxd if is_relative: return None # FIXME: error? - return self.context.find_pxd_file(module, None) + return self.context.find_pxd_file(module, source_file_path=filename) @cached_method def cimported_files(self, filename): - if filename[-4:] == '.pyx' and path_exists(filename[:-4] + '.pxd'): - pxd_list = [filename[:-4] + '.pxd'] + filename_root, filename_ext = os.path.splitext(filename) + if filename_ext in ('.pyx', '.py') and path_exists(filename_root + '.pxd'): + pxd_list = [filename_root + '.pxd'] else: pxd_list = [] # Cimports generates all possible combinations package.module
diff --git a/Cython/Build/Tests/TestRecythonize.py b/Cython/Build/Tests/TestRecythonize.py new file mode 100644 --- /dev/null +++ b/Cython/Build/Tests/TestRecythonize.py @@ -0,0 +1,212 @@ +import shutil +import os +import tempfile +import time + +import Cython.Build.Dependencies +import Cython.Utils +from Cython.TestUtils import CythonTest + + +def fresh_cythonize(*args, **kwargs): + Cython.Utils.clear_function_caches() + Cython.Build.Dependencies._dep_tree = None # discard method caches + Cython.Build.Dependencies.cythonize(*args, **kwargs) + +class TestRecythonize(CythonTest): + + def setUp(self): + CythonTest.setUp(self) + self.temp_dir = ( + tempfile.mkdtemp( + prefix='recythonize-test', + dir='TEST_TMP' if os.path.isdir('TEST_TMP') else None + ) + ) + + def tearDown(self): + CythonTest.tearDown(self) + shutil.rmtree(self.temp_dir) + + def test_recythonize_pyx_on_pxd_change(self): + + src_dir = tempfile.mkdtemp(prefix='src', dir=self.temp_dir) + + a_pxd = os.path.join(src_dir, 'a.pxd') + a_pyx = os.path.join(src_dir, 'a.pyx') + a_c = os.path.join(src_dir, 'a.c') + dep_tree = Cython.Build.Dependencies.create_dependency_tree() + + with open(a_pxd, 'w') as f: + f.write('cdef int value\n') + + with open(a_pyx, 'w') as f: + f.write('value = 1\n') + + + # The dependencies for "a.pyx" are "a.pxd" and "a.pyx". + self.assertEqual({a_pxd, a_pyx}, dep_tree.all_dependencies(a_pyx)) + + # Cythonize to create a.c + fresh_cythonize(a_pyx) + + # Sleep to address coarse time-stamp precision. + time.sleep(1) + + with open(a_c) as f: + a_c_contents1 = f.read() + + with open(a_pxd, 'w') as f: + f.write('cdef double value\n') + + fresh_cythonize(a_pyx) + + with open(a_c) as f: + a_c_contents2 = f.read() + + self.assertTrue("__pyx_v_1a_value = 1;" in a_c_contents1) + self.assertFalse("__pyx_v_1a_value = 1;" in a_c_contents2) + self.assertTrue("__pyx_v_1a_value = 1.0;" in a_c_contents2) + self.assertFalse("__pyx_v_1a_value = 1.0;" in a_c_contents1) + + + def test_recythonize_py_on_pxd_change(self): + + src_dir = tempfile.mkdtemp(prefix='src', dir=self.temp_dir) + + a_pxd = os.path.join(src_dir, 'a.pxd') + a_py = os.path.join(src_dir, 'a.py') + a_c = os.path.join(src_dir, 'a.c') + dep_tree = Cython.Build.Dependencies.create_dependency_tree() + + with open(a_pxd, 'w') as f: + f.write('cdef int value\n') + + with open(a_py, 'w') as f: + f.write('value = 1\n') + + + # The dependencies for "a.py" are "a.pxd" and "a.py". + self.assertEqual({a_pxd, a_py}, dep_tree.all_dependencies(a_py)) + + # Cythonize to create a.c + fresh_cythonize(a_py) + + # Sleep to address coarse time-stamp precision. + time.sleep(1) + + with open(a_c) as f: + a_c_contents1 = f.read() + + with open(a_pxd, 'w') as f: + f.write('cdef double value\n') + + fresh_cythonize(a_py) + + with open(a_c) as f: + a_c_contents2 = f.read() + + + self.assertTrue("__pyx_v_1a_value = 1;" in a_c_contents1) + self.assertFalse("__pyx_v_1a_value = 1;" in a_c_contents2) + self.assertTrue("__pyx_v_1a_value = 1.0;" in a_c_contents2) + self.assertFalse("__pyx_v_1a_value = 1.0;" in a_c_contents1) + + def test_recythonize_pyx_on_dep_pxd_change(self): + src_dir = tempfile.mkdtemp(prefix='src', dir=self.temp_dir) + + a_pxd = os.path.join(src_dir, 'a.pxd') + a_pyx = os.path.join(src_dir, 'a.pyx') + b_pyx = os.path.join(src_dir, 'b.pyx') + b_c = os.path.join(src_dir, 'b.c') + dep_tree = Cython.Build.Dependencies.create_dependency_tree() + + with open(a_pxd, 'w') as f: + f.write('cdef int value\n') + + with open(a_pyx, 'w') as f: + f.write('value = 1\n') + + with open(b_pyx, 'w') as f: + f.write('cimport a\n' + 'a.value = 2\n') + + + # The dependencies for "b.pyx" are "a.pxd" and "b.pyx". + self.assertEqual({a_pxd, b_pyx}, dep_tree.all_dependencies(b_pyx)) + + + # Cythonize to create b.c + fresh_cythonize([a_pyx, b_pyx]) + + # Sleep to address coarse time-stamp precision. + time.sleep(1) + + with open(b_c) as f: + b_c_contents1 = f.read() + + with open(a_pxd, 'w') as f: + f.write('cdef double value\n') + + fresh_cythonize([a_pyx, b_pyx]) + + with open(b_c) as f: + b_c_contents2 = f.read() + + + + self.assertTrue("__pyx_v_1a_value = 2;" in b_c_contents1) + self.assertFalse("__pyx_v_1a_value = 2;" in b_c_contents2) + self.assertTrue("__pyx_v_1a_value = 2.0;" in b_c_contents2) + self.assertFalse("__pyx_v_1a_value = 2.0;" in b_c_contents1) + + + + def test_recythonize_py_on_dep_pxd_change(self): + + src_dir = tempfile.mkdtemp(prefix='src', dir=self.temp_dir) + + a_pxd = os.path.join(src_dir, 'a.pxd') + a_pyx = os.path.join(src_dir, 'a.pyx') + b_pxd = os.path.join(src_dir, 'b.pxd') + b_py = os.path.join(src_dir, 'b.py') + b_c = os.path.join(src_dir, 'b.c') + dep_tree = Cython.Build.Dependencies.create_dependency_tree() + + with open(a_pxd, 'w') as f: + f.write('cdef int value\n') + + with open(a_pyx, 'w') as f: + f.write('value = 1\n') + + with open(b_pxd, 'w') as f: + f.write('cimport a\n') + + with open(b_py, 'w') as f: + f.write('a.value = 2\n') + + + # The dependencies for b.py are "a.pxd", "b.pxd" and "b.py". + self.assertEqual({a_pxd, b_pxd, b_py}, dep_tree.all_dependencies(b_py)) + + + # Cythonize to create b.c + fresh_cythonize([a_pyx, b_py]) + + # Sleep to address coarse time-stamp precision. + time.sleep(1) + + with open(b_c) as f: + b_c_contents1 = f.read() + + with open(a_pxd, 'w') as f: + f.write('cdef double value\n') + + fresh_cythonize([a_pyx, b_py]) + + with open(b_c) as f: + b_c_contents2 = f.read() + + self.assertTrue("__pyx_v_1a_value = 2;" in b_c_contents1) + self.assertFalse("__pyx_v_1a_value = 2;" in b_c_contents2) + self.assertTrue("__pyx_v_1a_value = 2.0;" in b_c_contents2) + self.assertFalse("__pyx_v_1a_value = 2.0;" in b_c_contents1)
cythonize doesn’t recompile when only the pxd has changed in pure python mode When a .py file is augmented by a .pxd one, cythonize won’t recompile the module when only the pxd has changed, or one of its dependencies, which often leads to broken code. This doesn’t happen when the base module is a .pyx one. Migrated from http://trac.cython.org/ticket/874
This is still true as of today (cython `3.0a1-79-g3de7a4b8f`): ``` $ ls a.pxd a.py setup.py ``` `$ cat setup.py` ```py from setuptools import setup from Cython.Build import cythonize setup( ext_modules = cythonize(["a.py"], language_level=3) ) ``` `$ cat a.py` ```py def afunc(x): return x+2 ``` `$ cat a.pxd` ```pyx cdef int afunc(int x) ``` ( first time compile -> ok ) ``` $ python setup.py build_ext -i Compiling a.py because it changed. [1/1] Cythonizing a.py running build_ext building 'a' extension creating build creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c a.c -o build/temp.linux-x86_64-2.7/a.o creating build/lib.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/a.o -o build/lib.linux-x86_64-2.7/a.so copying build/lib.linux-x86_64-2.7/a.so -> ``` ( second time compile -> nothing is done (ok) ) ``` $ python setup.py build_ext -i running build_ext copying build/lib.linux-x86_64-2.7/a.so -> ``` ( change `a.py` + compile -> `a.so` recompiled (ok) ) ``` $ touch a.py $ python setup.py build_ext -i Compiling a.py because it changed. [1/1] Cythonizing a.py running build_ext building 'a' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c a.c -o build/temp.linux-x86_64-2.7/a.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/a.o -o build/lib.linux-x86_64-2.7/a.so copying build/lib.linux-x86_64-2.7/a.so -> ``` ( change `a.pxd`+ compile -> `a.so` is not recompiled (**WRONG**) ) ``` $ touch a.pxd $ python setup.py build_ext -i running build_ext copying build/lib.linux-x86_64-2.7/a.so -> ``` ( `a.so` is not recompiled even if we change content of `a.pxd` (**WRONG**) ) ``` $ echo ZZZ >a.pxd $ python setup.py build_ext -i running build_ext copying build/lib.linux-x86_64-2.7/a.so -> ``` ( it recompiles and gives the error only if `a.py` is changed ) ``` $ touch a.py $ python setup.py build_ext -i Compiling a.py because it changed. [1/1] Cythonizing a.py Error compiling Cython file: ------------------------------------------------------------ ... ZZZ ^ ------------------------------------------------------------ a.pxd:1:0: undeclared name not builtin: ZZZ Traceback (most recent call last): File "setup.py", line 5, in <module> ext_modules = cythonize(["a.py"], language_level=3) File "/home/kirr/src/tools/py/cython/Cython/Build/Dependencies.py", line 1105, in cythonize cythonize_one(*args) File "/home/kirr/src/tools/py/cython/Cython/Build/Dependencies.py", line 1263, in cythonize_one raise CompileError(None, pyx_file) Cython.Compiler.Errors.CompileError: a.py ``` -------- This issue was hit for real with gevent where it was not evident why a code was crashing and only later it was discovered be a miscompilation issue: https://github.com/gevent/gevent/issues/1568#issuecomment-617432757 . PR welcome.
2021-03-23T23:06:52Z
[]
[]
cython/cython
4,086
cython__cython-4086
[ "3047" ]
369b41c5f5174ec1a0ee398fec93b114a61cce09
diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -484,6 +484,7 @@ def get_openmp_compiler_flags(language): 'run.pep526_variable_annotations', # typing module 'run.test_exceptions', # copied from Py3.7+ 'run.time_pxd', # _PyTime_GetSystemClock doesn't exist in 3.4 + 'run.cpython_capi_py35', 'embedding.embedded', # From the docs, needs Py_DecodeLocale ]), (3,7): (operator.lt, lambda x: x in ['run.pycontextvar',
diff --git a/tests/run/cpython_capi.pyx b/tests/run/cpython_capi.pyx --- a/tests/run/cpython_capi.pyx +++ b/tests/run/cpython_capi.pyx @@ -25,31 +25,6 @@ def test_pymalloc(): mem.PyMem_Free(m) -def test_pymalloc_raw(): - """ - >>> test_pymalloc_raw() - 3 - """ - cdef char* m - cdef char* m2 = NULL - with nogil: - m = <char*> mem.PyMem_RawMalloc(20) - if not m: - raise MemoryError() - try: - m[0] = 1 - m[1] = 2 - m[2] = 3 - m2 = <char*> mem.PyMem_RawRealloc(m, 10) - if m2: - m = m2 - retval = m[2] - finally: - mem.PyMem_RawFree(m) - assert m2 - return retval - - def test_gilstate(): """ >>> test_gilstate() diff --git a/tests/run/cpython_capi_py35.pyx b/tests/run/cpython_capi_py35.pyx new file mode 100644 --- /dev/null +++ b/tests/run/cpython_capi_py35.pyx @@ -0,0 +1,63 @@ +# mode: run +# tag: c-api + +# PyMem_RawMalloc tests that need to be disabled for Python < 3.5 +# (some of these would work of Python 3.4, but it's easier to disable +# them in one place) + +from cpython cimport mem + +cdef short _assert_calloc(short* s, int n) except -1 with gil: + """Assert array ``s`` of length ``n`` is zero and return 3.""" + assert not s[0] and not s[n - 1] + s[0] += 1 + s[n - 1] += 3 + for i in range(1, n - 1): + assert not s[i] + return s[n - 1] + +def test_pycalloc(): + """ + >>> test_pycalloc() + 3 + """ + cdef short* s = <short*> mem.PyMem_Calloc(10, sizeof(short)) + if not s: + raise MemoryError() + try: + return _assert_calloc(s, 10) + finally: + mem.PyMem_Free(s) + +def test_pymalloc_raw(): + """ + >>> test_pymalloc_raw() + 3 + """ + cdef short i + cdef short* s + cdef char* m + cdef char* m2 = NULL + with nogil: + s = <short*> mem.PyMem_RawCalloc(10, sizeof(short)) + if not s: + raise MemoryError() + try: + i = _assert_calloc(s, 10) + finally: + mem.PyMem_RawFree(s) + m = <char*> mem.PyMem_RawMalloc(20) + if not m: + raise MemoryError() + try: + m[0] = 1 + m[1] = 2 + m[2] = i + m2 = <char*> mem.PyMem_RawRealloc(m, 10) + if m2: + m = m2 + retval = m[2] + finally: + mem.PyMem_RawFree(m) + assert m2 + return retval
PyMem_RawCalloc missing from cpython.mem While [`cpython.mem`](http://docs.cython.org/en/latest/src/tutorial/memory_allocation.html) [contains](https://github.com/cython/cython/blob/1593b297d132df0ef894b072ade7b539cd774dd7/Cython/Includes/cpython/mem.pxd#L25-L54) the other [raw allocators](https://docs.python.org/3/c-api/memory.html#raw-memory-interface), it is missing [`PyMem_RawCalloc`](https://docs.python.org/3/c-api/memory.html#c.PyMem_RawCalloc).
PR welcome.
2021-04-04T11:18:51Z
[]
[]
cython/cython
4,091
cython__cython-4091
[ "4082" ]
5704109b327591dde14cbc23ce532cdbd16d84c6
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -6754,22 +6754,13 @@ def infer_type(self, env): return dict_type def analyse_types(self, env): - args = [ + self.keyword_args = [ arg.analyse_types(env).coerce_to_pyobject(env).as_none_safe_node( # FIXME: CPython's error message starts with the runtime function name 'argument after ** must be a mapping, not NoneType') for arg in self.keyword_args ] - if len(args) == 1 and args[0].type is dict_type: - # strip this intermediate node and use the bare dict - arg = args[0] - if arg.is_name and arg.entry.is_arg and len(arg.entry.cf_assignments) == 1: - # passing **kwargs through to function call => allow NULL - arg.allow_null = True - return arg - - self.keyword_args = args return self def may_be_none(self):
diff --git a/tests/run/dict.pyx b/tests/run/dict.pyx --- a/tests/run/dict.pyx +++ b/tests/run/dict.pyx @@ -117,3 +117,22 @@ def item_creation_sideeffect(L, sideeffect, unhashable): [2, 4, 5] """ return {1:2, sideeffect(2): 3, 3: 4, unhashable(4): 5, sideeffect(5): 6} + + +def dict_unpacking_not_for_arg_create_a_copy(): + """ + >>> dict_unpacking_not_for_arg_create_a_copy() + [('a', 'modified'), ('b', 'original')] + [('a', 'original'), ('b', 'original')] + """ + data = {'a': 'original', 'b': 'original'} + + func = lambda: {**data} + + call_once = func() + call_once['a'] = 'modified' + + call_twice = func() + + print(sorted(call_once.items())) + print(sorted(call_twice.items())) diff --git a/tests/run/kwargs_passthrough.pyx b/tests/run/kwargs_passthrough.pyx --- a/tests/run/kwargs_passthrough.pyx +++ b/tests/run/kwargs_passthrough.pyx @@ -1,7 +1,6 @@ -cimport cython +import cython - [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def wrap_passthrough(f): """ >>> def f(a=1): return a @@ -80,7 +79,7 @@ def wrap_passthrough_more(f): return wrapper [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def wrap_passthrough2(f): """ >>> def f(a=1): return a @@ -99,7 +98,7 @@ def wrap_passthrough2(f): return wrapper [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def wrap_modify(f): """ >>> def f(a=1, test=2): @@ -123,7 +122,7 @@ def wrap_modify(f): return wrapper [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def wrap_modify_mix(f): """ >>> def f(a=1, test=2): @@ -187,7 +186,21 @@ def wrap_modify_func(f): return wrapper [email protected]_assert_path_exists('//MergedDictNode') +def modify_in_function(): + """ + >>> modify_in_function() + {'foo': 'bar'} + {'foo': 'bar'} + """ + def inner(**kwds): + kwds['foo'] = 'modified' + d = {'foo': 'bar'} + print(d) + inner(**d) + print(d) + + +#@cython.test_assert_path_exists('//MergedDictNode') def wrap_modify_func_mix(f): """ >>> def f(a=1, test=2): @@ -215,12 +228,11 @@ def wrap_modify_func_mix(f): return wrapper [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def wrap_reassign(f): """ >>> def f(a=1, test=2): ... return a, test - >>> wrapped = wrap_reassign(f) >>> wrapped(1) CALLED @@ -239,7 +251,7 @@ def wrap_reassign(f): return wrapper [email protected]_fail_if_path_exists('//MergedDictNode') +#@cython.test_fail_if_path_exists('//MergedDictNode') def kwargs_metaclass(**kwargs): """ >>> K = kwargs_metaclass()
[BUG] dict has been shared when unpacking it in lambda for default dict <!-- **PLEASE READ THIS FIRST:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **To Reproduce** Code to reproduce the behaviour: ```cython import collections def just_call(): defaults = {'a': 0, 'b':0} data = collections.defaultdict(lambda: {**defaults}) for x in range(5): if x in (1, 3): value = 1 else: value = 4 data[x]['a'] += value data[x]['b'] += value print(data) return data ``` ``` In [1]: import test_default In [2]: test_default.just_call() defaultdict(<cyfunction just_call.<locals>.<lambda> at 0x7f588cf9f9a8>, {0: {'a': 14, 'b': 14}, 1: {'a': 14, 'b': 14}, 2: {'a': 14, 'b': 14}, 3: {'a': 14, 'b': 14}, 4: {'a': 14, 'b': 14}}) Out[2]: defaultdict(<cyfunction just_call.<locals>.<lambda> at 0x7f588cf9f9a8>, {0: {'a': 14, 'b': 14}, 1: {'a': 14, 'b': 14}, 2: {'a': 14, 'b': 14}, 3: {'a': 14, 'b': 14}, 4: {'a': 14, 'b': 14}}) ``` **Expected behavior** ``` In [1]: import test_default In [2]: test_default.just_call() defaultdict(<cyfunction just_call.<locals>.<lambda> at 0x7f98515d3a70>, {0: {'a': 4, 'b': 4}, 1: {'a': 1, 'b': 1}, 2: {'a': 4, 'b': 4}, 3: {'a': 1, 'b': 1}, 4: {'a': 4, 'b': 4}}) Out[2]: defaultdict(<cyfunction just_call.<locals>.<lambda> at 0x7f98515d3a70>, {0: {'a': 4, 'b': 4}, 1: {'a': 1, 'b': 1}, 2: {'a': 4, 'b': 4}, 3: {'a': 1, 'b': 1}, 4: {'a': 4, 'b': 4}}) ``` **Environment (please complete the following information):** - OS: [Linux] - Python version [e.g. 3.6.8] - Cython version [e.g. 0.29.21]
Duplicate of https://github.com/cython/cython/issues/3227 Thanks for the report. It does look like this is probably a bug
2021-04-05T09:44:52Z
[]
[]
cython/cython
4,127
cython__cython-4127
[ "3477" ]
30f5ad30542c63156e4babcab1e783ef44b09e15
diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -2496,8 +2496,6 @@ class AlignFunctionDefinitions(CythonTransform): def visit_ModuleNode(self, node): self.scope = node.scope - self.directives = node.directives - self.imported_names = set() # hack, see visit_FromImportStatNode() self.visitchildren(node) return node @@ -2535,15 +2533,45 @@ def visit_DefNode(self, node): error(pxd_def.pos, "previous declaration here") return None node = node.as_cfunction(pxd_def) - elif (self.scope.is_module_scope and self.directives['auto_cpdef'] - and node.name not in self.imported_names - and node.is_cdef_func_compatible()): - # FIXME: cpdef-ing should be done in analyse_declarations() - node = node.as_cfunction(scope=self.scope) # Enable this when nested cdef functions are allowed. # self.visitchildren(node) return node + def visit_ExprNode(self, node): + # ignore lambdas and everything else that appears in expressions + return node + + +class AutoCpdefFunctionDefinitions(CythonTransform): + + def visit_ModuleNode(self, node): + self.directives = node.directives + self.imported_names = set() # hack, see visit_FromImportStatNode() + self.scope = node.scope + self.visitchildren(node) + return node + + def visit_DefNode(self, node): + if (self.scope.is_module_scope and self.directives['auto_cpdef'] + and node.name not in self.imported_names + and node.is_cdef_func_compatible()): + # FIXME: cpdef-ing should be done in analyse_declarations() + node = node.as_cfunction(scope=self.scope) + return node + + def visit_CClassDefNode(self, node, pxd_def=None): + if pxd_def is None: + pxd_def = self.scope.lookup(node.class_name) + if pxd_def: + if not pxd_def.defined_in_pxd: + return node + outer_scope = self.scope + self.scope = pxd_def.type.scope + self.visitchildren(node) + if pxd_def: + self.scope = outer_scope + return node + def visit_FromImportStatNode(self, node): # hack to prevent conditional import fallback functions from # being cdpef-ed (global Python variables currently conflict diff --git a/Cython/Compiler/Pipeline.py b/Cython/Compiler/Pipeline.py --- a/Cython/Compiler/Pipeline.py +++ b/Cython/Compiler/Pipeline.py @@ -149,7 +149,7 @@ def create_pipeline(context, mode, exclude_classes=()): from .ParseTreeTransforms import ExpandInplaceOperators, ParallelRangeTransform from .ParseTreeTransforms import CalculateQualifiedNamesTransform from .TypeInference import MarkParallelAssignments, MarkOverflowingArithmetic - from .ParseTreeTransforms import AdjustDefByDirectives, AlignFunctionDefinitions + from .ParseTreeTransforms import AdjustDefByDirectives, AlignFunctionDefinitions, AutoCpdefFunctionDefinitions from .ParseTreeTransforms import RemoveUnreachableCode, GilCheck from .FlowControl import ControlFlowAnalysis from .AnalysedTreeTransforms import AutoTestDictTransform @@ -186,10 +186,11 @@ def create_pipeline(context, mode, exclude_classes=()): TrackNumpyAttributes(), InterpretCompilerDirectives(context, context.compiler_directives), ParallelRangeTransform(context), - AdjustDefByDirectives(context), WithTransform(context), - MarkClosureVisitor(context), + AdjustDefByDirectives(context), _align_function_definitions, + MarkClosureVisitor(context), + AutoCpdefFunctionDefinitions(context), RemoveUnreachableCode(context), ConstantFolding(), FlattenInListTransform(),
diff --git a/tests/run/pure_pxd.srctree b/tests/run/pure_pxd.srctree --- a/tests/run/pure_pxd.srctree +++ b/tests/run/pure_pxd.srctree @@ -55,6 +55,17 @@ def func(a, b, c): """ return a + b + c +def sum_generator_expression(a): + # GH-3477 - closure variables incorrectly captured in functions transformed to cdef + return sum(i for i in range(a)) + +def run_sum_generator_expression(a): + """ + >>> run_sum_generator_expression(5) + 10 + """ + return sum_generator_expression(a) + def test(module): import os.path @@ -95,3 +106,6 @@ cdef class TypedMethod: cpdef int func(x, int y, z) except? -1 # argument names should not matter, types should + + +cdef int sum_generator_expression(int a)
variable 'referenced before assignment' warning, error in all() with .pxd but not .pyx The following is a standalone example of a problem I've run into trying to accelerate some code: given allExt.py (takes a set of words and checks if 3rd letter in each is a vowel): ``` class a3v(object): def __init__(self, inset): self.myStrSet = inset # set input word list as an attribute on class instance def all3Vowels(self): # test if 3rd letter of each word is a vowel vndx = 2 # local variable for 3rd letter index inStrSet = self.myStrSet # local variable for class instance word list if all( ltr in ("a", "e", "i", "o", "u") for ltr in (w[vndx] for w in inStrSet) ): return True return False ``` and tst.py: ``` #!/usr/local/bin/python3 import allExt a3vL = allExt.a3v(["the", "bright", "flower"]) if a3vL.all3Vowels(): print('yes') else: print('no') ``` The code runs without issue, and fits with examples I have found in the cython docs. However, when augmented with allExt.pxd: ``` import cython cdef class a3v: cdef public list myStrSet @cython.locals(vndx=int, inStrSet=list, ltr=str) cpdef bint all3Vowels(self) ``` Upon compiling as shown I get: ``` rob@nova-370:01 14:45:55 atmNdx $ cythonize -3 -f -i allExt.py allExt.pxd [1/1] Cythonizing /Users/rob/sync/rgithub/cython/atmNdx/allExt.py warning: allExt.py:12:26: local variable 'vndx' referenced before assignment Error compiling Cython file: ------------------------------------------------------------ ... def all3Vowels(self): vndx = 2 inStrSet = self.myStrSet if all( ltr in ("a", "e", "i", "o", "u") for ltr in (w[vndx] for w in inStrSet) ^ ------------------------------------------------------------ allExt.py:12:41: local variable 'inStrSet' referenced before assignment Traceback (most recent call last): ``` OTOH, the equivalent (?) pyx version allExt.pyx: ``` class a3v(object): def __init__(self, inset): self.myStrSet = inset def all3Vowels(self): cdef int vndx = 2 cdef list inStrSet = self.myStrSet cdef str ltr if all( ltr in ("a", "e", "i", "o", "u") for ltr in (w[vndx] for w in inStrSet) ): return True return False ``` compiles and runs without issue. Have I missed something in the docs or some other simple issue? Thank you.
Thanks for the report. There seems to be something wrong with the nested generator expressions here and the way the type information is applied from the decorator (or maybe _when_ it is applied). You didn't mention which Cython version you were using, so I guess it's a recent release. Could you try the latest master branch, and also PR #3323? BTW, you don't need to declare `inStrSet` here because its type should get inferred from the assignment, since the attribute is typed. Thanks for the follow up. This was with Cython-0.29.16, but I have now reproduced with both 3.0a0 master and https://github.com/da-woods/cython.git (#3323). On Fri, Apr 3, 2020 at 8:45 AM Stefan Behnel <[email protected]> wrote: > Thanks for the report. There seems to be something wrong with the nested > generator expressions here and the way the type information is applied from > the decorator (or maybe *when* it is applied). > > You didn't mention which Cython version you were using, so I guess it's a > recent release. Could you try the latest master branch, and also PR #3323 > <https://github.com/cython/cython/pull/3323>? > > BTW, you don't need to declare inStrSet here because its type should get > inferred from the assignment, since the attribute is typed. > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/cython/cython/issues/3477#issuecomment-608283260>, or > unsubscribe > <https://github.com/notifications/unsubscribe-auth/AAZW3QDL4WTTE5FOZWIMHALRKWHZRANCNFSM4LY7IUIA> > . >
2021-04-17T21:48:42Z
[]
[]
cython/cython
4,129
cython__cython-4129
[ "1851" ]
3048be77631d91ddf9210c34f8de436ab70d7c04
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -7012,29 +7012,11 @@ def analyse_as_type_attribute(self, env): return None ubcm_entry = entry else: - # Create a temporary entry describing the C method - # as an ordinary function. - if entry.func_cname and not hasattr(entry.type, 'op_arg_struct'): - cname = entry.func_cname - if entry.type.is_static_method or ( - env.parent_scope and env.parent_scope.is_cpp_class_scope): - ctype = entry.type - elif type.is_cpp_class: - error(self.pos, "%s not a static member of %s" % (entry.name, type)) - ctype = PyrexTypes.error_type - else: - # Fix self type. - ctype = copy.copy(entry.type) - ctype.args = ctype.args[:] - ctype.args[0] = PyrexTypes.CFuncTypeArg('self', type, 'self', None) - else: - cname = "%s->%s" % (type.vtabptr_cname, entry.cname) - ctype = entry.type - ubcm_entry = Symtab.Entry(entry.name, cname, ctype) - ubcm_entry.is_cfunction = 1 - ubcm_entry.func_cname = entry.func_cname - ubcm_entry.is_unbound_cmethod = 1 - ubcm_entry.scope = entry.scope + ubcm_entry = self._create_unbound_cmethod_entry(type, entry, env) + ubcm_entry.overloaded_alternatives = [ + self._create_unbound_cmethod_entry(type, overloaded_alternative, env) + for overloaded_alternative in entry.overloaded_alternatives + ] return self.as_name_node(env, ubcm_entry, target=False) elif type.is_enum or type.is_cpp_enum: if self.attribute in type.values: @@ -7047,6 +7029,32 @@ def analyse_as_type_attribute(self, env): error(self.pos, "%s not a known value of %s" % (self.attribute, type)) return None + def _create_unbound_cmethod_entry(self, type, entry, env): + # Create a temporary entry describing the unbound C method in `entry` + # as an ordinary function. + if entry.func_cname and entry.type.op_arg_struct is None: + cname = entry.func_cname + if entry.type.is_static_method or ( + env.parent_scope and env.parent_scope.is_cpp_class_scope): + ctype = entry.type + elif type.is_cpp_class: + error(self.pos, "%s not a static member of %s" % (entry.name, type)) + ctype = PyrexTypes.error_type + else: + # Fix self type. + ctype = copy.copy(entry.type) + ctype.args = ctype.args[:] + ctype.args[0] = PyrexTypes.CFuncTypeArg('self', type, 'self', None) + else: + cname = "%s->%s" % (type.vtabptr_cname, entry.cname) + ctype = entry.type + ubcm_entry = Symtab.Entry(entry.name, cname, ctype) + ubcm_entry.is_cfunction = 1 + ubcm_entry.func_cname = entry.func_cname + ubcm_entry.is_unbound_cmethod = 1 + ubcm_entry.scope = entry.scope + return ubcm_entry + def analyse_as_type(self, env): module_scope = self.obj.analyse_as_module(env) if module_scope: diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -2841,12 +2841,14 @@ class CFuncType(CType): # (used for optimisation overrides) # is_const_method boolean # is_static_method boolean + # op_arg_struct CPtrType Pointer to optional argument struct is_cfunction = 1 original_sig = None cached_specialized_types = None from_fused = False is_const_method = False + op_arg_struct = None subtypes = ['return_type', 'args']
diff --git a/tests/run/cpp_static_method_overload.pyx b/tests/run/cpp_static_method_overload.pyx new file mode 100644 --- /dev/null +++ b/tests/run/cpp_static_method_overload.pyx @@ -0,0 +1,49 @@ +# mode: run +# tag: cpp + +cdef extern from *: + """ + struct Foo + { + + static const char* bar(int x, int y) { + return "second"; + } + + static const char* bar(int x) { + return "first"; + } + + const char* baz(int x, int y) { + return "second"; + } + + const char* baz(int x) { + return "first"; + } + }; + """ + cppclass Foo: + @staticmethod + const char* bar(int x) + + @staticmethod + const char* bar(int x, int y) + + const char* baz(int x) + const char* baz(int x, int y) + +def test_normal_method_overload(): + """ + >>> test_normal_method_overload() + """ + cdef Foo f + assert f.baz(1) == b"first" + assert f.baz(1, 2) == b"second" + +def test_static_method_overload(): + """ + >>> test_static_method_overload() + """ + assert Foo.bar(1) == b"first" + assert Foo.bar(1, 2) == b"second"
Multiple static functions, with same name and different parameters in a class will only expose one Example: c++: ```c++ class SqBufferIoStream : public SqIoStream { public: static std::shared_ptr<SqBufferIoStream> Open(const std::string& data); static std::shared_ptr<SqBufferIoStream> Open(); }; ``` cython: ```python cdef extern from "SqBufferIoStream.h": cdef cppclass SqBufferIoStream: @staticmethod shared_ptr[SqBufferIoStream] Open(const string s) @staticmethod shared_ptr[SqBufferIoStream] Open() ``` ``` Error compiling Cython file: ------------------------------------------------------------ for command, description in c_map: p_map[command] = description return p_map def executeCommand(self, command, parameters): cdef shared_ptr[SqInputStream] b = dynamic_pointer_cast[SqInputStream, SqBufferIoStream](SqBufferIoStream.Open(_json.dumps(parameters))) ^ ------------------------------------------------------------ SqFoundationTypes.pyx:200:118: Call with wrong number of arguments (expected 0, got 1) ``` If I change to: ```python cdef extern from "SqBufferIoStream.h": cdef cppclass SqBufferIoStream: @staticmethod shared_ptr[SqBufferIoStream] Open() @staticmethod shared_ptr[SqBufferIoStream] Open(const string s) ``` ``` Error compiling Cython file: ------------------------------------------------------------ def executeCommand(self, command, parameters): cdef shared_ptr[SqInputStream] b = dynamic_pointer_cast[SqInputStream, SqBufferIoStream](SqBufferIoStream.Open(_json.dumps(parameters))) cdef SqKeyValueList data = SqJsonParser.ParseAsSqValue(b).get().GetKeyValueList() cdef SqKeyValueList c_kvl = self.c_this.get().ExecuteCommand(command, data) cdef shared_ptr[SqBufferIoStream] buf = SqBufferIoStream.Open() ^ ------------------------------------------------------------ SqFoundationTypes.pyx:203:69: Call with wrong number of arguments (expected 1, got 0) ``` Version: ``` cython --version Cython version 0.25.2 ```
2021-04-18T21:36:05Z
[]
[]
cython/cython
4,134
cython__cython-4134
[ "1415" ]
30f5ad30542c63156e4babcab1e783ef44b09e15
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -13115,12 +13115,11 @@ def __init__(self, arg, dst_type, env): CoercionNode.__init__(self, arg) self.type = dst_type self.is_temp = 1 - self.env = env self.use_managed_ref = True self.arg = arg + self.type.create_from_py_utility_code(env) def generate_result_code(self, code): - self.type.create_from_py_utility_code(self.env) code.putln(self.type.from_py_call_code( self.arg.py_result(), self.result(),
diff --git a/tests/memoryview/memoryview_inline_pxd.srctree b/tests/memoryview/memoryview_inline_pxd.srctree new file mode 100644 --- /dev/null +++ b/tests/memoryview/memoryview_inline_pxd.srctree @@ -0,0 +1,35 @@ +# ticket: 1415 + +# Utility code from an inline function in a pxd file was not +# correctly included in a pyx file that cimported it. +# Do not add more to this test - it is intentionally minimal +# to avoid including the utility code through other means + +PYTHON setup.py build_ext --inplace +PYTHON -c "import uses_inline; uses_inline.main()" + +######## setup.py ######## + +from distutils.core import setup +from Cython.Distutils import build_ext +from Cython.Distutils.extension import Extension + +setup( + ext_modules = [ + Extension("uses_inline", ["uses_inline.pyx"]), + ], + cmdclass={'build_ext': build_ext}, +) + +######## has_inline.pxd ######## + +from libc.stdlib cimport malloc +cdef inline double[::1] mview(size_t size): + return <double[:size:1]>malloc(size * sizeof(double)) + +######## uses_inline.pyx ######## + +from has_inline cimport mview +def main(): + return mview(1) +
Invalid C code for pxd-inline function that returns memory view ``` # foo.pxd: from cython cimport numeric from libc.stdlib cimport malloc cdef inline numeric[mview(size_t size, numeric* null): return <numeric[:size:1](::1])>malloc(size * sizeof(null)) # bar.pyx: from foo cimport mview def main(): return mview(1, <double*>NULL) ``` C compiler error is: ``` bar.c: In function ‘__pyx_fuse_0__pyx_f_3foo_mview’: bar.c:1571:13: error: incompatible types when assigning to type ‘__Pyx_memviewslice’ from type ‘int’ __pyx_t_5 = __Pyx_PyObject_to_MemoryviewSlice_dc_short(((PyObject *)__pyx_t_2)); ^ ``` Originally reported here: http://thread.gmane.org/gmane.comp.python.cython.user/13946 Migrated from http://trac.cython.org/ticket/861
2021-04-24T14:15:47Z
[]
[]
cython/cython
4,156
cython__cython-4156
[ "4155" ]
16aba7eb35b2a6f0c88b53da00539a5d875ebfdf
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -6874,7 +6874,6 @@ class AttributeNode(ExprNode): is_attribute = 1 subexprs = ['obj'] - type = PyrexTypes.error_type entry = None is_called = 0 needs_none_check = True @@ -6964,6 +6963,8 @@ def analyse_target_types(self, env): return node def analyse_types(self, env, target = 0): + if not self.type: + self.type = PyrexTypes.error_type # default value if it isn't analysed successfully self.initialized_check = env.directives['initializedcheck'] node = self.analyse_as_cimported_attribute_node(env, target) if node is None and not target: @@ -10989,8 +10990,6 @@ class TypeidNode(ExprNode): # arg_type ExprNode # is_variable boolean - type = PyrexTypes.error_type - subexprs = ['operand'] arg_type = None @@ -11008,19 +11007,25 @@ def get_type_info_type(self, env): cpp_message = 'typeid operator' def analyse_types(self, env): + if not self.type: + self.type = PyrexTypes.error_type # default value if it isn't analysed successfully self.cpp_check(env) type_info = self.get_type_info_type(env) if not type_info: self.error("The 'libcpp.typeinfo' module must be cimported to use the typeid() operator") return self + if self.operand is None: + return self # already analysed, no need to repeat self.type = type_info as_type = self.operand.analyse_as_specialized_type(env) if as_type: self.arg_type = as_type self.is_type = True + self.operand = None # nothing further uses self.operand - will only cause problems if its used in code generation else: self.arg_type = self.operand.analyse_types(env) self.is_type = False + self.operand = None # nothing further uses self.operand - will only cause problems if its used in code generation if self.arg_type.type.is_pyobject: self.error("Cannot use typeid on a Python object") return self
diff --git a/tests/run/type_inference.pyx b/tests/run/type_inference.pyx --- a/tests/run/type_inference.pyx +++ b/tests/run/type_inference.pyx @@ -789,3 +789,16 @@ def test_bound_methods(): default_arg = o.default_arg assert default_arg(2) == 12, default_arg(2) assert default_arg(2, 3) == 15, default_arg(2, 2) + +def test_builtin_max(): + """ + # builtin max is slightly complicated because it gets transformed to EvalWithTempExprNode + # See https://github.com/cython/cython/issues/4155 + >>> test_builtin_max() + """ + class C: + a = 2 + def get_max(self): + a = max(self.a, self.a) + assert typeof(a) == "Python object", typeof(a) + C().get_max()
[BUG] compiler error **Describe the bug** An unexpected compiler error with `infer_types=True` **To Reproduce** ``` In [1]: %%cython ...: #cython: infer_types=True ...: class A: ...: def f(self): ...: x = max(self.a, self.a) ``` Removing `max`, or setting `infer_types=False`, or setting `x = None` first all make it compile. Error: [cpython_error.txt](https://github.com/cython/cython/files/6469216/cpython_error.txt) **Expected behavior** It should compile **Environment (please complete the following information):** - OS: Linux - Python version: 3.7.4 - Cython version: 0.29.21
2021-05-13T07:20:31Z
[]
[]
cython/cython
4,199
cython__cython-4199
[ "4198" ]
b3f8a198d96727c9111dbc707a05e286b93c974c
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -1996,6 +1996,9 @@ def declare_from_annotation(self, env, as_target=False): or not env.directives['annotation_typing'] ): atype = None + elif env.is_py_class_scope: + # For Python class scopes every attribute is a Python object + atype = py_object_type else: _, atype = annotation.analyse_type_annotation(env) if atype is None:
diff --git a/tests/run/pep526_variable_annotations.py b/tests/run/pep526_variable_annotations.py --- a/tests/run/pep526_variable_annotations.py +++ b/tests/run/pep526_variable_annotations.py @@ -165,7 +165,6 @@ def literal_list_ptr(): 37:19: Unknown type declaration in annotation, ignoring 38:12: Unknown type declaration in annotation, ignoring 39:18: Unknown type declaration in annotation, ignoring -57:19: Unknown type declaration in annotation, ignoring 73:11: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? 73:19: Unknown type declaration in annotation, ignoring # FIXME: these are sort-of evaluated now, so the warning is misleading diff --git a/tests/run/pyclass_annotations_pep526.py b/tests/run/pyclass_annotations_pep526.py --- a/tests/run/pyclass_annotations_pep526.py +++ b/tests/run/pyclass_annotations_pep526.py @@ -11,6 +11,8 @@ except ImportError: # Py<=3.5 ClassVar = {int: int} +class NotAStr: + pass class PyAnnotatedClass: """ @@ -38,6 +40,9 @@ class PyAnnotatedClass: literal: "int" recurse: "PyAnnotatedClass" default: bool = False + # https://github.com/cython/cython/issues/4196 and https://github.com/cython/cython/issues/4198 + not_object: float = 0.1 # Shouldn't try to create a c attribute + lie_about_type: str = NotAStr # Shouldn't generate a runtime type-check class PyVanillaClass:
[BUG] "Python global or builtin not a Python object" error when cythonizing a float annotation **Describe the bug** Cythonizing the code below results in the following error: ```py Traceback (most recent call last): File "C:\Program Files\Python38\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "<elided>\Scripts\cython.exe\__main__.py", line 7, in <module> File "<elided>\lib\site-packages\Cython\Compiler\Main.py", line 714, in setuptools_main return main(command_line = 1) File "<elided>\lib\site-packages\Cython\Compiler\Main.py", line 732, in main result = compile(sources, options) File "<elided>\lib\site-packages\Cython\Compiler\Main.py", line 630, in compile return compile_multiple(source, options) File "<elided>\lib\site-packages\Cython\Compiler\Main.py", line 607, in compile_multiple result = run_pipeline(source, options, context=context) File "<elided>\lib\site-packages\Cython\Compiler\Main.py", line 505, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "<elided>\lib\site-packages\Cython\Compiler\Pipeline.py", line 371, in run_pipeline data = run(phase, data) File "<elided>\lib\site-packages\Cython\Compiler\Pipeline.py", line 351, in run return phase(data) File "<elided>\lib\site-packages\Cython\Compiler\Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File "<elided>\lib\site-packages\Cython\Compiler\ModuleNode.py", line 171, in process_implementation self.generate_c_code(env, options, result) File "<elided>\lib\site-packages\Cython\Compiler\ModuleNode.py", line 483, in generate_c_code self.generate_module_init_func(modules[:-1], env, globalstate['init_module']) File "<elided>\lib\site-packages\Cython\Compiler\ModuleNode.py", line 2940, in generate_module_init_func self.body.generate_execution_code(code) File "<elided>\lib\site-packages\Cython\Compiler\Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "<elided>\lib\site-packages\Cython\Compiler\Nodes.py", line 4975, in generate_execution_code self.body.generate_execution_code(code) File "<elided>\lib\site-packages\Cython\Compiler\Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "<elided>\lib\site-packages\Cython\Compiler\Nodes.py", line 5642, in generate_execution_code self.generate_assignment_code(code) File "<elided>\lib\site-packages\Cython\Compiler\Nodes.py", line 5939, in generate_assignment_code self.lhs.generate_assignment_code(self.rhs, code) File "<elided>\lib\site-packages\Cython\Compiler\ExprNodes.py", line 2366, in generate_assignment_code assert entry.type.is_pyobject, "Python global or builtin not a Python object" AssertionError: Python global or builtin not a Python object ``` **To Reproduce** Code to reproduce the behaviour: ```cython # cython: language_level=3 class Foo: bar: float = 0.1 ``` **Expected behavior** It cythonizes without an error. **Environment:** - OS: Windows 10 - Python version: 3.8.7 - Cython version: 3.0a7 **Additional context** The error does not occur when: - Using a string annotation (`bar: "float" = 0.1`) - A different type is used (`bar: int = 1`) - No value is given (`bar: float`)
2021-05-27T16:50:07Z
[]
[]
cython/cython
4,204
cython__cython-4204
[ "4172" ]
b3f8a198d96727c9111dbc707a05e286b93c974c
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -2109,9 +2109,9 @@ def call_slot_method(method_name, reverse): "right, left" if reverse else "left, right", extra_arg) else: - return '%s_maybe_call_slot(%s, left, right %s)' % ( + return '%s_maybe_call_slot(%s->tp_base, left, right %s)' % ( func_name, - 'Py_TYPE(right)->tp_base' if reverse else 'Py_TYPE(left)->tp_base', + scope.parent_type.typeptr_cname, extra_arg) if get_slot_method_cname(slot.left_slot.method_name) and not get_slot_method_cname(slot.right_slot.method_name): @@ -2122,13 +2122,16 @@ def call_slot_method(method_name, reverse): slot.right_slot.method_name, )) + overloads_left = int(bool(get_slot_method_cname(slot.left_slot.method_name))) + overloads_right = int(bool(get_slot_method_cname(slot.right_slot.method_name))) code.putln( TempitaUtilityCode.load_as_string( "BinopSlot", "ExtensionTypes.c", context={ "func_name": func_name, "slot_name": slot.slot_name, - "overloads_left": int(bool(get_slot_method_cname(slot.left_slot.method_name))), + "overloads_left": overloads_left, + "overloads_right": overloads_right, "call_left": call_slot_method(slot.left_slot.method_name, reverse=False), "call_right": call_slot_method(slot.right_slot.method_name, reverse=True), "type_cname": scope.parent_type.typeptr_cname,
diff --git a/tests/run/binop_reverse_methods_GH2056.pyx b/tests/run/binop_reverse_methods_GH2056.pyx --- a/tests/run/binop_reverse_methods_GH2056.pyx +++ b/tests/run/binop_reverse_methods_GH2056.pyx @@ -9,6 +9,15 @@ class Base(object): >>> 2 + Base() 'Base.__radd__(Base(), 2)' + >>> Base(implemented=False) + 2 #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... + >>> 2 + Base(implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... + >>> Base() ** 2 'Base.__pow__(Base(), 2, None)' >>> 2 ** Base() @@ -16,17 +25,34 @@ class Base(object): >>> pow(Base(), 2, 100) 'Base.__pow__(Base(), 2, 100)' """ + implemented: cython.bint + + def __init__(self, *, implemented=True): + self.implemented = implemented + def __add__(self, other): - return "Base.__add__(%s, %s)" % (self, other) + if (<Base>self).implemented: + return "Base.__add__(%s, %s)" % (self, other) + else: + return NotImplemented def __radd__(self, other): - return "Base.__radd__(%s, %s)" % (self, other) + if (<Base>self).implemented: + return "Base.__radd__(%s, %s)" % (self, other) + else: + return NotImplemented def __pow__(self, other, mod): - return "Base.__pow__(%s, %s, %s)" % (self, other, mod) + if (<Base>self).implemented: + return "Base.__pow__(%s, %s, %s)" % (self, other, mod) + else: + return NotImplemented def __rpow__(self, other, mod): - return "Base.__rpow__(%s, %s, %s)" % (self, other, mod) + if (<Base>self).implemented: + return "Base.__rpow__(%s, %s, %s)" % (self, other, mod) + else: + return NotImplemented def __repr__(self): return "%s()" % (self.__class__.__name__) @@ -44,9 +70,27 @@ class OverloadLeft(Base): 'OverloadLeft.__add__(OverloadLeft(), Base())' >>> Base() + OverloadLeft() 'Base.__add__(Base(), OverloadLeft())' + + >>> OverloadLeft(implemented=False) + Base(implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... + >>> Base(implemented=False) + OverloadLeft(implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... """ + derived_implemented: cython.bint + + def __init__(self, *, implemented=True): + super().__init__(implemented=implemented) + self.derived_implemented = implemented + def __add__(self, other): - return "OverloadLeft.__add__(%s, %s)" % (self, other) + if (<OverloadLeft>self).derived_implemented: + return "OverloadLeft.__add__(%s, %s)" % (self, other) + else: + return NotImplemented @cython.c_api_binop_methods(False) @@ -62,9 +106,27 @@ class OverloadRight(Base): 'Base.__add__(OverloadRight(), Base())' >>> Base() + OverloadRight() 'OverloadRight.__radd__(OverloadRight(), Base())' + + >>> OverloadRight(implemented=False) + Base(implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... + >>> Base(implemented=False) + OverloadRight(implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... """ + derived_implemented: cython.bint + + def __init__(self, *, implemented=True): + super().__init__(implemented=implemented) + self.derived_implemented = implemented + def __radd__(self, other): - return "OverloadRight.__radd__(%s, %s)" % (self, other) + if (<OverloadRight>self).derived_implemented: + return "OverloadRight.__radd__(%s, %s)" % (self, other) + else: + return NotImplemented @cython.c_api_binop_methods(True) @cython.cclass @@ -79,7 +141,30 @@ class OverloadCApi(Base): 'OverloadCApi.__add__(OverloadCApi(), Base())' >>> Base() + OverloadCApi() 'OverloadCApi.__add__(Base(), OverloadCApi())' + + >>> OverloadCApi(derived_implemented=False) + 2 #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... + >>> 2 + OverloadCApi(derived_implemented=False) #doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: unsupported operand type... """ + derived_implemented: cython.bint + + def __init__(self, *, derived_implemented=True): + super().__init__(implemented=True) + self.derived_implemented = derived_implemented + def __add__(self, other): - return "OverloadCApi.__add__(%s, %s)" % (self, other) + if isinstance(self, OverloadCApi): + derived_implemented = (<OverloadCApi>self).derived_implemented + else: + derived_implemented = (<OverloadCApi>other).derived_implemented + if derived_implemented: + return "OverloadCApi.__add__(%s, %s)" % (self, other) + else: + return NotImplemented +# TODO: Test a class that only defines the `__r...__()` methods.
[BUG] Infinite loop/crash on __add__ <!-- **PLEASE READ THIS FIRST:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Describe the bug** It's possible to get an infinite loop for an add (and presumably other operators) operator that returns `NotImplemented` when used with a derived class. **To Reproduce** ```cython cdef class Base: def __add__(self, other): return NotImplemented class Derived(Base): pass ``` and to test: ``` >>> import hmmm >>> x = hmmm.Base() >>> y = hmmm.Derived() >>> y+x # works OK as expected Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'Derived' and 'hmmm.Base' >>> x+y ``` For `x+y` I get an infinite loop but [Pandas reports segmentation fault](https://github.com/pandas-dev/pandas/issues/34213#issuecomment-842694795) - probably just to do with tail-call recursion optimization or not. **Expected behavior** Should just be `NotImplementedError` **Environment (please complete the following information):** - OS: Linux - Python version 3.8.9 - Cython version 0e80efb82480b777057770ce2006a6b46ec46028 (close to current master) **Additional context** I think this is to do with the changes to support `__radd__` etc.. I think it's somewhere in: https://github.com/cython/cython/blob/034fc26c1c25b5b69581464b73136038bb201ce4/Cython/Utility/ExtensionTypes.c#L383 However, I haven't traced the error through in great detail so not 100% sure exactly what's gone wrong.
I was playing with this issue recently. I did git bisect and the issue first occurred in following commit: ``` 7ac25eea68798f46f79606cfa40a82fabd51534e is the first bad commit commit 7ac25eea68798f46f79606cfa40a82fabd51534e Author: Robert Bradshaw <[email protected]> Date: Wed Jun 17 13:13:28 2020 -0700 Change the default of the "c_api_binop_methods" directive to False. (GH-3644) This is a backwards incompatible change that enables Python semantics for special methods by default, while the directive allows users to opt out of it and go back to the previous C-ish Cython semantics. See https://github.com/cython/cython/issues/2056 Cython/Compiler/Options.py | 2 +- tests/run/unicode_formatting.pyx | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) bisect run success ``` I have checked the commit and the change is only changing default value of `c_api_binop_methods`. I have double-checked and it seems that also in master setting `c_api_binop_methods=True` is fixing the issue: ``` Traceback (most recent call last): File "/home/matus/dev/cython/t.py", line 2, in <module> print(test.Derived() + test.Derived()) TypeError: unsupported operand type(s) for +: 'Derived' and 'Derived' ``` I have also tried to find commit before bisected commit but I was not able to find any usable. Not sure whether my findings are useful or not... Thanks. I think the commit you identify is definitely the point where is changed. I'm not sure bisecting further back is too useful. I am looking into it (slightly slowly...). You can get it not to crash by using `specific_known_type->tp_base` rather than `Py_TYPE(left_or_right)->tp_base`, which is an improvement but doesn't quite bring it in line with Python behaviour. I suspect we'll have to compromise a bit on how closely we can hit Python behaviour though.
2021-05-31T08:20:15Z
[]
[]
cython/cython
4,216
cython__cython-4216
[ "4214" ]
169bab169907a313119c7566cdde01a9368d3bbd
diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -822,6 +822,7 @@ def declare_cfunction(self, name, type, pos, if overridable: # names of cpdef functions can be used as variables and can be assigned to var_entry = Entry(name, cname, py_object_type) # FIXME: cname? + var_entry.qualified_name = self.qualify_name(name) var_entry.is_variable = 1 var_entry.is_pyglobal = 1 var_entry.scope = entry.scope @@ -1034,6 +1035,7 @@ def declare_builtin_cfunction(self, name, type, cname, python_equiv=None, utilit else: python_equiv = EncodedString(python_equiv) var_entry = Entry(python_equiv, python_equiv, py_object_type) + var_entry.qualified_name = self.qualify_name(name) var_entry.is_variable = 1 var_entry.is_builtin = 1 var_entry.utility_code = utility_code @@ -1057,6 +1059,7 @@ def declare_builtin_type(self, name, cname, utility_code = None, objstruct_cname type = self.lookup('type').type, # make sure "type" is the first type declared... pos = entry.pos, cname = entry.type.typeptr_cname) + var_entry.qualified_name = self.qualify_name(name) var_entry.is_variable = 1 var_entry.is_cglobal = 1 var_entry.is_readonly = 1 @@ -1244,6 +1247,7 @@ def declare_builtin(self, name, pos): else: entry.is_builtin = 1 entry.name = name + entry.qualified_name = self.builtin_scope().qualify_name(name) return entry def find_module(self, module_name, pos, relative_level=-1): @@ -1707,6 +1711,7 @@ def attach_var_entry_to_c_class(self, entry): type = Builtin.type_type, pos = entry.pos, cname = entry.type.typeptr_cname) + var_entry.qualified_name = entry.qualified_name var_entry.is_variable = 1 var_entry.is_cglobal = 1 var_entry.is_readonly = 1 @@ -2290,6 +2295,7 @@ def declare_builtin_cfunction(self, name, type, cname, utility_code = None): entry = self.declare_cfunction(name, type, None, cname, visibility='extern', utility_code=utility_code) var_entry = Entry(name, name, py_object_type) + var_entry.qualified_name = name var_entry.is_variable = 1 var_entry.is_builtin = 1 var_entry.utility_code = utility_code
diff --git a/tests/run/cython3.pyx b/tests/run/cython3.pyx --- a/tests/run/cython3.pyx +++ b/tests/run/cython3.pyx @@ -1,6 +1,6 @@ -# cython: language_level=3, binding=True +# cython: language_level=3, binding=True, annotation_typing=False # mode: run -# tag: generators, python3, exceptions +# tag: generators, python3, exceptions, gh2230, gh2811 print(end='') # test that language_level 3 applies immediately at the module start, for the first token. @@ -619,6 +619,18 @@ def annotation_syntax(a: "test new test", b : "other" = 2, *args: "ARGS", **kwar return result +def builtin_as_annotation(text: str): + # See https://github.com/cython/cython/issues/2811 + """ + >>> builtin_as_annotation("abc") + a + b + c + """ + for c in text: + print(c) + + async def async_def_annotations(x: 'int') -> 'float': """ >>> ret, arg = sorted(async_def_annotations.__annotations__.items())
[BUG]: annotating argument as list[some_type] raises CompileError Trying to add pure-py annotation [here](https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/internals.pyx#L161) ``` -def append(self, others) -> BlockPlacement: +def append(self, others: list[BlockPlacement]) -> BlockPlacement: ``` raises ``` pandas/_libs/internals.pyx:166:57: Compiler crash in IterationTransform ```
2021-06-06T12:02:56Z
[]
[]
cython/cython
4,248
cython__cython-4248
[ "4243" ]
c74e08a0e4a92ac6bbe3d3b9284eefa685e5c409
diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -929,6 +929,13 @@ def visit_AttributeNode(self, node): # before they have a chance to cause compile-errors return node + def visit_AnnotationNode(self, node): + # for most transforms annotations are left unvisited (because they're unevaluated) + # however, it is important to pick up compiler directives from them + if node.expr: + self.visitchildren(node.expr) + return node + def visit_NewExprNode(self, node): self.visit(node.cppclass) self.visitchildren(node)
diff --git a/tests/run/annotation_typing.pyx b/tests/run/annotation_typing.pyx --- a/tests/run/annotation_typing.pyx +++ b/tests/run/annotation_typing.pyx @@ -3,6 +3,7 @@ cimport cython from cython cimport typeof +from cpython.ref cimport PyObject def old_dict_syntax(a: list, b: "int" = 2, c: {'ctype': 'long int'} = 3, d: {'type': 'float'} = 4) -> list: @@ -266,20 +267,32 @@ cdef class ClassAttribute: cls_attr : float = 1. [email protected] +def take_ptr(obj: cython.pointer(PyObject)): + pass + +def call_take_ptr(): + """ + >>> call_take_ptr() # really just a compile-test + """ + python_dict = {"abc": 123} + take_ptr(cython.cast(cython.pointer(PyObject), python_dict)) + + _WARNINGS = """ -8:32: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. -8:47: Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly. -8:56: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. -8:77: Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly. -8:85: Python type declaration in signature annotation does not refer to a Python type -8:85: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. -242:44: Unknown type declaration in annotation, ignoring -249:29: Ambiguous types in annotation, ignoring -266:15: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? +9:32: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. +9:47: Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly. +9:56: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. +9:77: Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly. +9:85: Python type declaration in signature annotation does not refer to a Python type +9:85: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly. +243:44: Unknown type declaration in annotation, ignoring +250:29: Ambiguous types in annotation, ignoring +267:15: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? # BUG: -46:6: 'pytypes_cpdef' redeclared -120:0: 'struct_io' redeclared -149:0: 'struct_convert' redeclared -168:0: 'exception_default' redeclared -199:0: 'exception_default_uint' redeclared +47:6: 'pytypes_cpdef' redeclared +121:0: 'struct_io' redeclared +150:0: 'struct_convert' redeclared +169:0: 'exception_default' redeclared +200:0: 'exception_default_uint' redeclared """
[BUG] casting PyObject * is broken in pure python mode **Describe the bug** For some cases casting `PyObject *` is failing during compilation with error: `Cannot convert 'PyObject *' to Python object` **To Reproduce** Following code is compiling with no error: ```cython from cpython.ref cimport PyObject foo = {"abc": 123} cdef PyObject *bar = <PyObject *> foo ``` But in pure python version is failing: ```python import cython from cython.cimports.cpython.ref import PyObject foo = {"abc": 123} bar: cython.pointer(PyObject) = cython.cast(cython.pointer(PyObject), foo) ``` **Expected behavior** Pure python mode should reflect cython language. **Environment (please complete the following information):** - OS: Linux - Python version: 3.9.2 - Cython version: master branch
This is intended. There is already a ticket where this was discussed. It only applies to module globals, which are Python objects unless explicitly declare()-d as something else. If you try the same thing inside of a function, it will probably work. I think it's ok to use a function in the documentation. Hmm, yes it seems working. I did mistake when I was generelizing bug but it seems that following code snippet fails: ```python import cython from cython.cimports.cpython.ref import PyObject @cython.cfunc def foo(obj: cython.pointer(PyObject)): pass def main(): python_dict = {"abc": 123} foo(cython.cast(cython.pointer(PyObject), python_dict)) ``` compiling fails with following error: ``` $ cython -3a test.py Error compiling Cython file: ------------------------------------------------------------ ... def foo(obj: cython.pointer(PyObject)): pass def main(): python_dict = {"abc": 123} foo(cython.cast(cython.pointer(PyObject), python_dict)) ^ ------------------------------------------------------------ test.py:12:14: Cannot convert 'PyObject *' to Python object ``` @scoder can you confirm the case? If yes I will close this issue and create new one with new snippet. The module globals issue is: https://github.com/cython/cython/issues/3944 (the issue that the the annotations on globals are ignored). Your function-based version looks like a genuine bug (I think). I don't think it's necessary to create a new issue for it though
2021-06-24T17:50:15Z
[]
[]
cython/cython
4,254
cython__cython-4254
[ "1159" ]
0be7a37283bf6f9f9b563f22659d8aa9d353db73
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -333,6 +333,8 @@ class ExprNode(Node): # result_code/temp_result can safely be set to None # is_numpy_attribute boolean Is a Numpy module attribute # annotation ExprNode or None PEP526 annotation for names or expressions + # generator_arg_tag None or Node A tag to mark ExprNodes that potentially need to + # be changed to a generator argument result_ctype = None type = None @@ -342,6 +344,7 @@ class ExprNode(Node): use_managed_ref = True # can be set by optimisation transforms result_is_used = True is_numpy_attribute = False + generator_arg_tag = None # The Analyse Expressions phase for expressions is split # into two sub-phases: @@ -2785,7 +2788,98 @@ def get_known_standard_library_import(self): return self.module_name.value -class IteratorNode(ExprNode): +class ScopedExprNode(ExprNode): + # Abstract base class for ExprNodes that have their own local + # scope, such as generator expressions. + # + # expr_scope Scope the inner scope of the expression + + subexprs = [] + expr_scope = None + + # does this node really have a local scope, e.g. does it leak loop + # variables or not? non-leaking Py3 behaviour is default, except + # for list comprehensions where the behaviour differs in Py2 and + # Py3 (set in Parsing.py based on parser context) + has_local_scope = True + + def init_scope(self, outer_scope, expr_scope=None): + if expr_scope is not None: + self.expr_scope = expr_scope + elif self.has_local_scope: + self.expr_scope = Symtab.ComprehensionScope(outer_scope) + elif not self.expr_scope: # don't unset if it's already been set + self.expr_scope = None + + def analyse_declarations(self, env): + self.init_scope(env) + + def analyse_scoped_declarations(self, env): + # this is called with the expr_scope as env + pass + + def analyse_types(self, env): + # no recursion here, the children will be analysed separately below + return self + + def analyse_scoped_expressions(self, env): + # this is called with the expr_scope as env + return self + + def generate_evaluation_code(self, code): + # set up local variables and free their references on exit + generate_inner_evaluation_code = super(ScopedExprNode, self).generate_evaluation_code + if not self.has_local_scope or not self.expr_scope.var_entries: + # no local variables => delegate, done + generate_inner_evaluation_code(code) + return + + code.putln('{ /* enter inner scope */') + py_entries = [] + for _, entry in sorted(item for item in self.expr_scope.entries.items() if item[0]): + if not entry.in_closure: + if entry.type.is_pyobject and entry.used: + py_entries.append(entry) + if not py_entries: + # no local Python references => no cleanup required + generate_inner_evaluation_code(code) + code.putln('} /* exit inner scope */') + return + + # must free all local Python references at each exit point + old_loop_labels = code.new_loop_labels() + old_error_label = code.new_error_label() + + generate_inner_evaluation_code(code) + + # normal (non-error) exit + self._generate_vars_cleanup(code, py_entries) + + # error/loop body exit points + exit_scope = code.new_label('exit_scope') + code.put_goto(exit_scope) + for label, old_label in ([(code.error_label, old_error_label)] + + list(zip(code.get_loop_labels(), old_loop_labels))): + if code.label_used(label): + code.put_label(label) + self._generate_vars_cleanup(code, py_entries) + code.put_goto(old_label) + code.put_label(exit_scope) + code.putln('} /* exit inner scope */') + + code.set_loop_labels(old_loop_labels) + code.error_label = old_error_label + + def _generate_vars_cleanup(self, code, py_entries): + for entry in py_entries: + if entry.is_cglobal: + code.put_var_gotref(entry) + code.put_var_decref_set(entry, "Py_None") + else: + code.put_var_xdecref_clear(entry) + + +class IteratorNode(ScopedExprNode): # Used as part of for statement implementation. # # Implements result = iter(sequence) @@ -2797,10 +2891,13 @@ class IteratorNode(ExprNode): counter_cname = None reversed = False # currently only used for list/tuple types (see Optimize.py) is_async = False + has_local_scope = False subexprs = ['sequence'] def analyse_types(self, env): + if self.expr_scope: + env = self.expr_scope # actually evaluate sequence in this scope instead self.sequence = self.sequence.analyse_types(env) if (self.sequence.type.is_array or self.sequence.type.is_ptr) and \ not self.sequence.type.is_string: @@ -2823,7 +2920,7 @@ def analyse_types(self, env): ])) def type_dependencies(self, env): - return self.sequence.type_dependencies(env) + return self.sequence.type_dependencies(self.expr_scope or env) def infer_type(self, env): sequence_type = self.sequence.infer_type(env) @@ -3157,7 +3254,7 @@ def generate_result_code(self, code): self.iterator.generate_iter_next_result_code(self.result(), code) -class AsyncIteratorNode(ExprNode): +class AsyncIteratorNode(ScopedExprNode): # Used as part of 'async for' statement implementation. # # Implements result = sequence.__aiter__() @@ -3169,11 +3266,14 @@ class AsyncIteratorNode(ExprNode): is_async = True type = py_object_type is_temp = 1 + has_local_scope = False def infer_type(self, env): return py_object_type def analyse_types(self, env): + if self.expr_scope: + env = self.expr_scope self.sequence = self.sequence.analyse_types(env) if not self.sequence.type.is_pyobject: error(self.pos, "async for loops not allowed on C/C++ types") @@ -8483,97 +8583,6 @@ def generate_operation_code(self, code): raise InternalError("List type never specified") -class ScopedExprNode(ExprNode): - # Abstract base class for ExprNodes that have their own local - # scope, such as generator expressions. - # - # expr_scope Scope the inner scope of the expression - - subexprs = [] - expr_scope = None - - # does this node really have a local scope, e.g. does it leak loop - # variables or not? non-leaking Py3 behaviour is default, except - # for list comprehensions where the behaviour differs in Py2 and - # Py3 (set in Parsing.py based on parser context) - has_local_scope = True - - def init_scope(self, outer_scope, expr_scope=None): - if expr_scope is not None: - self.expr_scope = expr_scope - elif self.has_local_scope: - self.expr_scope = Symtab.ComprehensionScope(outer_scope) - else: - self.expr_scope = None - - def analyse_declarations(self, env): - self.init_scope(env) - - def analyse_scoped_declarations(self, env): - # this is called with the expr_scope as env - pass - - def analyse_types(self, env): - # no recursion here, the children will be analysed separately below - return self - - def analyse_scoped_expressions(self, env): - # this is called with the expr_scope as env - return self - - def generate_evaluation_code(self, code): - # set up local variables and free their references on exit - generate_inner_evaluation_code = super(ScopedExprNode, self).generate_evaluation_code - if not self.has_local_scope or not self.expr_scope.var_entries: - # no local variables => delegate, done - generate_inner_evaluation_code(code) - return - - code.putln('{ /* enter inner scope */') - py_entries = [] - for _, entry in sorted(item for item in self.expr_scope.entries.items() if item[0]): - if not entry.in_closure: - if entry.type.is_pyobject and entry.used: - py_entries.append(entry) - if not py_entries: - # no local Python references => no cleanup required - generate_inner_evaluation_code(code) - code.putln('} /* exit inner scope */') - return - - # must free all local Python references at each exit point - old_loop_labels = code.new_loop_labels() - old_error_label = code.new_error_label() - - generate_inner_evaluation_code(code) - - # normal (non-error) exit - self._generate_vars_cleanup(code, py_entries) - - # error/loop body exit points - exit_scope = code.new_label('exit_scope') - code.put_goto(exit_scope) - for label, old_label in ([(code.error_label, old_error_label)] + - list(zip(code.get_loop_labels(), old_loop_labels))): - if code.label_used(label): - code.put_label(label) - self._generate_vars_cleanup(code, py_entries) - code.put_goto(old_label) - code.put_label(exit_scope) - code.putln('} /* exit inner scope */') - - code.set_loop_labels(old_loop_labels) - code.error_label = old_error_label - - def _generate_vars_cleanup(self, code, py_entries): - for entry in py_entries: - if entry.is_cglobal: - code.put_var_gotref(entry) - code.put_var_decref_set(entry, "Py_None") - else: - code.put_var_xdecref_clear(entry) - - class ComprehensionNode(ScopedExprNode): # A list/set/dict comprehension @@ -8588,6 +8597,12 @@ def infer_type(self, env): def analyse_declarations(self, env): self.append.target = self # this is used in the PyList_Append of the inner loop self.init_scope(env) + # setup loop scope + if isinstance(self.loop, Nodes._ForInStatNode): + assert isinstance(self.loop.iterator, ScopedExprNode), self.loop.iterator + self.loop.iterator.init_scope(None, env) + else: + assert isinstance(self.loop, Nodes.ForFromStatNode), self.loop def analyse_scoped_declarations(self, env): self.loop.analyse_declarations(env) @@ -10012,10 +10027,18 @@ class GeneratorExpressionNode(LambdaNode): # # loop ForStatNode the for-loop, containing a YieldExprNode # def_node DefNode the underlying generator 'def' node + # call_parameters [ExprNode] (Internal) parameters passed to the DefNode call name = StringEncoding.EncodedString('genexpr') binding = False + child_attrs = LambdaNode.child_attrs + ["call_parameters"] + subexprs = LambdaNode.subexprs + ["call_parameters"] + + def __init__(self, pos, *args, **kwds): + super(GeneratorExpressionNode, self).__init__(pos, *args, **kwds) + self.call_parameters = [] + def analyse_declarations(self, env): if hasattr(self, "genexpr_name"): # this if-statement makes it safe to run twice @@ -10028,13 +10051,22 @@ def analyse_declarations(self, env): self.def_node.is_cyfunction = False # Force genexpr signature self.def_node.entry.signature = TypeSlots.pyfunction_noargs + # setup loop scope + if isinstance(self.loop, Nodes._ForInStatNode): + assert isinstance(self.loop.iterator, ScopedExprNode) + self.loop.iterator.init_scope(None, env) + else: + assert isinstance(self.loop, Nodes.ForFromStatNode) def generate_result_code(self, code): + args_to_call = ([self.closure_result_code()] + + [ cp.result() for cp in self.call_parameters ]) + args_to_call = ", ".join(args_to_call) code.putln( '%s = %s(%s); %s' % ( self.result(), self.def_node.entry.pyfunc_cname, - self.closure_result_code(), + args_to_call, code.error_goto_if_null(self.result(), self.pos))) self.generate_gotref(code) diff --git a/Cython/Compiler/FlowControl.py b/Cython/Compiler/FlowControl.py --- a/Cython/Compiler/FlowControl.py +++ b/Cython/Compiler/FlowControl.py @@ -172,9 +172,9 @@ def mark_position(self, node): if self.block: self.block.positions.add(node.pos[:2]) - def mark_assignment(self, lhs, rhs, entry): + def mark_assignment(self, lhs, rhs, entry, rhs_scope=None): if self.block and self.is_tracked(entry): - assignment = NameAssignment(lhs, rhs, entry) + assignment = NameAssignment(lhs, rhs, entry, rhs_scope=rhs_scope) self.block.stats.append(assignment) self.block.gen[entry] = assignment self.entries.add(entry) @@ -315,7 +315,7 @@ def __init__(self, entry_point, finally_enter=None, finally_exit=None): class NameAssignment(object): - def __init__(self, lhs, rhs, entry): + def __init__(self, lhs, rhs, entry, rhs_scope=None): if lhs.cf_state is None: lhs.cf_state = set() self.lhs = lhs @@ -326,16 +326,18 @@ def __init__(self, lhs, rhs, entry): self.is_arg = False self.is_deletion = False self.inferred_type = None + # For generator expression targets, the rhs can have a different scope than the lhs. + self.rhs_scope = rhs_scope def __repr__(self): return '%s(entry=%r)' % (self.__class__.__name__, self.entry) def infer_type(self): - self.inferred_type = self.rhs.infer_type(self.entry.scope) + self.inferred_type = self.rhs.infer_type(self.rhs_scope or self.entry.scope) return self.inferred_type def type_dependencies(self): - return self.rhs.type_dependencies(self.entry.scope) + return self.rhs.type_dependencies(self.rhs_scope or self.entry.scope) @property def type(self): @@ -677,6 +679,14 @@ def visit_CascadedAssignmentNode(self, node): class ControlFlowAnalysis(CythonTransform): + def find_in_stack(self, env): + if env == self.env: + return self.flow + for e, flow in reversed(self.stack): + if e is env: + return flow + assert False + def visit_ModuleNode(self, node): dot_output = self.current_directives['control_flow.dot_output'] self.gv_ctx = GVContext() if dot_output else None @@ -688,10 +698,9 @@ def visit_ModuleNode(self, node): self.reductions = set() self.in_inplace_assignment = False - self.env_stack = [] self.env = node.scope - self.stack = [] self.flow = ControlFlow() + self.stack = [] # a stack of (env, flow) tuples self.object_expr = TypedExprNode(PyrexTypes.py_object_type, may_be_none=True) self.visitchildren(node) @@ -708,9 +717,8 @@ def visit_FuncDefNode(self, node): if arg.default: self.visitchildren(arg) self.visitchildren(node, ('decorators',)) - self.env_stack.append(self.env) + self.stack.append((self.env, self.flow)) self.env = node.local_scope - self.stack.append(self.flow) self.flow = ControlFlow() # Collect all entries @@ -751,8 +759,7 @@ def visit_FuncDefNode(self, node): if self.gv_ctx is not None: self.gv_ctx.add(GV(node.local_scope.name, self.flow)) - self.flow = self.stack.pop() - self.env = self.env_stack.pop() + self.env, self.flow = self.stack.pop() return node def visit_DefNode(self, node): @@ -765,7 +772,7 @@ def visit_GeneratorBodyDefNode(self, node): def visit_CTypeDefNode(self, node): return node - def mark_assignment(self, lhs, rhs=None): + def mark_assignment(self, lhs, rhs=None, rhs_scope=None): if not self.flow.block: return if self.flow.exceptions: @@ -782,7 +789,7 @@ def mark_assignment(self, lhs, rhs=None): entry = self.env.lookup(lhs.name) if entry is None: # TODO: This shouldn't happen... return - self.flow.mark_assignment(lhs, rhs, entry) + self.flow.mark_assignment(lhs, rhs, entry, rhs_scope=rhs_scope) elif lhs.is_sequence_constructor: for i, arg in enumerate(lhs.args): if arg.is_starred: @@ -979,10 +986,11 @@ def mark_forloop_target(self, node): is_special = False sequence = node.iterator.sequence target = node.target + env = node.iterator.expr_scope or self.env if isinstance(sequence, ExprNodes.SimpleCallNode): function = sequence.function if sequence.self is None and function.is_name: - entry = self.env.lookup(function.name) + entry = env.lookup(function.name) if not entry or entry.is_builtin: if function.name == 'reversed' and len(sequence.args) == 1: sequence = sequence.args[0] @@ -990,30 +998,32 @@ def mark_forloop_target(self, node): if target.is_sequence_constructor and len(target.args) == 2: iterator = sequence.args[0] if iterator.is_name: - iterator_type = iterator.infer_type(self.env) + iterator_type = iterator.infer_type(env) if iterator_type.is_builtin_type: # assume that builtin types have a length within Py_ssize_t self.mark_assignment( target.args[0], ExprNodes.IntNode(target.pos, value='PY_SSIZE_T_MAX', - type=PyrexTypes.c_py_ssize_t_type)) + type=PyrexTypes.c_py_ssize_t_type), + rhs_scope=node.iterator.expr_scope) target = target.args[1] sequence = sequence.args[0] if isinstance(sequence, ExprNodes.SimpleCallNode): function = sequence.function if sequence.self is None and function.is_name: - entry = self.env.lookup(function.name) + entry = env.lookup(function.name) if not entry or entry.is_builtin: if function.name in ('range', 'xrange'): is_special = True for arg in sequence.args[:2]: - self.mark_assignment(target, arg) + self.mark_assignment(target, arg, rhs_scope=node.iterator.expr_scope) if len(sequence.args) > 2: self.mark_assignment(target, self.constant_folder( ExprNodes.binop_node(node.pos, '+', sequence.args[0], - sequence.args[2]))) + sequence.args[2])), + rhs_scope=node.iterator.expr_scope) if not is_special: # A for-loop basically translates to subsequent calls to @@ -1022,7 +1032,7 @@ def mark_forloop_target(self, node): # Python strings, etc., while correctly falling back to an # object type when the base type cannot be handled. - self.mark_assignment(target, node.item) + self.mark_assignment(target, node.item, rhs_scope=node.iterator.expr_scope) def visit_AsyncForStatNode(self, node): return self.visit_ForInStatNode(node) @@ -1321,21 +1331,25 @@ def visit_ContinueStatNode(self, node): def visit_ComprehensionNode(self, node): if node.expr_scope: - self.env_stack.append(self.env) + self.stack.append((self.env, self.flow)) self.env = node.expr_scope # Skip append node here self._visit(node.loop) if node.expr_scope: - self.env = self.env_stack.pop() + self.env, _ = self.stack.pop() return node def visit_ScopedExprNode(self, node): + # currently this is written to deal with these two types + # (with comprehensions covered in their own function) + assert isinstance(node, (ExprNodes.IteratorNode, ExprNodes.AsyncIteratorNode)), node if node.expr_scope: - self.env_stack.append(self.env) + self.stack.append((self.env, self.flow)) + self.flow = self.find_in_stack(node.expr_scope) self.env = node.expr_scope self.visitchildren(node) if node.expr_scope: - self.env = self.env_stack.pop() + self.env, self.flow = self.stack.pop() return node def visit_PyClassDefNode(self, node): @@ -1343,14 +1357,21 @@ def visit_PyClassDefNode(self, node): 'mkw', 'bases', 'class_result')) self.flow.mark_assignment(node.target, node.classobj, self.env.lookup(node.target.name)) - self.env_stack.append(self.env) + self.stack.append((self.env, self.flow)) self.env = node.scope self.flow.nextblock() if node.doc_node: self.flow.mark_assignment(node.doc_node, fake_rhs_expr, node.doc_node.entry) self.visitchildren(node, ('body',)) self.flow.nextblock() - self.env = self.env_stack.pop() + self.env, _ = self.stack.pop() + return node + + def visit_CClassDefNode(self, node): + # just make sure the nodes scope is findable in-case there is a list comprehension in it + self.stack.append((node.scope, self.flow)) + self.visitchildren(node) + self.stack.pop() return node def visit_AmpersandNode(self, node): diff --git a/Cython/Compiler/Naming.py b/Cython/Compiler/Naming.py --- a/Cython/Compiler/Naming.py +++ b/Cython/Compiler/Naming.py @@ -17,6 +17,7 @@ builtin_prefix = pyrex_prefix + "builtin_" arg_prefix = pyrex_prefix + "arg_" +genexpr_arg_prefix = pyrex_prefix + "genexpr_arg_" funcdoc_prefix = pyrex_prefix + "doc_" enum_prefix = pyrex_prefix + "e_" func_prefix = pyrex_prefix + "f_" diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -3513,7 +3513,15 @@ def generate_argument_parsing_code(self, env, code): # Move arguments into closure if required def put_into_closure(entry): if entry.in_closure: - code.putln('%s = %s;' % (entry.cname, entry.original_cname)) + if entry.type.is_array: + # This applies to generator expressions that iterate over C arrays (and need to + # capture them by value), under most other circumstances C array arguments are dropped to + # pointers so this copy isn't used + assert entry.type.size is not None + code.globalstate.use_utility_code(UtilityCode.load_cached("IncludeStringH", "StringTools.c")) + code.putln("memcpy({0}, {1}, sizeof({0}));".format(entry.cname, entry.original_cname)) + else: + code.putln('%s = %s;' % (entry.cname, entry.original_cname)) if entry.type.is_memoryviewslice: # TODO - at some point reference count of memoryviews should # genuinely be unified with PyObjects diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -2105,7 +2105,8 @@ def visit_SimpleCallNode(self, node): return node inlined = ExprNodes.InlinedDefNodeCallNode( node.pos, function_name=function_name, - function=function, args=node.args) + function=function, args=node.args, + generator_arg_tag=node.generator_arg_tag) if inlined.can_be_inlined(): return self.replace(node, inlined) return node diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -1621,6 +1621,126 @@ def visit_ExprNode(self, node): visit_Node = VisitorTransform.recurse_to_children +class _GeneratorExpressionArgumentsMarker(TreeVisitor, SkipDeclarations): + # called from "MarkClosureVisitor" + def __init__(self, gen_expr): + super(_GeneratorExpressionArgumentsMarker, self).__init__() + self.gen_expr = gen_expr + + def visit_ExprNode(self, node): + if not node.is_literal: + # Don't bother tagging literal nodes + assert (not node.generator_arg_tag) # nobody has tagged this first + node.generator_arg_tag = self.gen_expr + self.visitchildren(node) + + def visit_Node(self, node): + # We're only interested in the expressions that make up the iterator sequence, + # so don't go beyond ExprNodes (e.g. into ForFromStatNode). + return + + def visit_GeneratorExpressionNode(self, node): + node.generator_arg_tag = self.gen_expr + # don't visit children, can't handle overlapping tags + # (and assume generator expressions don't end up optimized out in a way + # that would require overlapping tags) + + +class _HandleGeneratorArguments(VisitorTransform, SkipDeclarations): + # used from within CreateClosureClasses + + def __call__(self, node): + from . import Visitor + assert isinstance(node, ExprNodes.GeneratorExpressionNode) + self.gen_node = node + + self.args = list(node.def_node.args) + self.call_parameters = list(node.call_parameters) + self.tag_count = 0 + self.substitutions = {} + + self.visitchildren(node) + + for k, v in self.substitutions.items(): + # doing another search for replacements here (at the end) allows us to sweep up + # CloneNodes too (which are often generated by the optimizer) + # (it could arguably be done more efficiently with a single traversal though) + Visitor.recursively_replace_node(node, k, v) + + node.def_node.args = self.args + node.call_parameters = self.call_parameters + return node + + def visit_GeneratorExpressionNode(self, node): + # a generator can also be substituted itself, so handle that case + new_node = self._handle_ExprNode(node, do_visit_children=False) + # However do not traverse into it. A new _HandleGeneratorArguments visitor will be used + # elsewhere to do that. + return node + + def _handle_ExprNode(self, node, do_visit_children): + if (node.generator_arg_tag is not None and self.gen_node is not None and + self.gen_node == node.generator_arg_tag): + pos = node.pos + # The reason for using ".x" as the name is that this is how CPython + # tracks internal variables in loops (e.g. + # { locals() for v in range(10) } + # will produce "v" and ".0"). We don't replicate this behaviour completely + # but use it as a starting point + name_source = self.tag_count + self.tag_count += 1 + name = EncodedString(".{0}".format(name_source)) + def_node = self.gen_node.def_node + if not def_node.local_scope.lookup_here(name): + from . import Symtab + cname = EncodedString(Naming.genexpr_arg_prefix + Symtab.punycodify_name(str(name_source))) + name_decl = Nodes.CNameDeclaratorNode(pos=pos, name=name) + type = node.type + if type.is_reference and not type.is_fake_reference: + # It isn't obvious whether the right thing to do would be to capture by reference or by + # value (C++ itself doesn't know either for lambda functions and forces a choice). + # However, capture by reference involves converting to FakeReference which would require + # re-analysing AttributeNodes. Therefore I've picked capture-by-value out of convenience + # TODO - could probably be optimized by making the arg a reference but the closure not + # (see https://github.com/cython/cython/issues/2468) + type = type.ref_base_type + + name_decl.type = type + new_arg = Nodes.CArgDeclNode(pos=pos, declarator=name_decl, + base_type=None, default=None, annotation=None) + new_arg.name = name_decl.name + new_arg.type = type + + self.args.append(new_arg) + node.generator_arg_tag = None # avoid the possibility of this being caught again + self.call_parameters.append(node) + new_arg.entry = def_node.declare_argument(def_node.local_scope, new_arg) + new_arg.entry.cname = cname + new_arg.entry.in_closure = True + + if do_visit_children: + # now visit the Nodes's children (but remove self.gen_node to not to further + # argument substitution) + gen_node, self.gen_node = self.gen_node, None + self.visitchildren(node) + self.gen_node = gen_node + + # replace the node inside the generator with a looked-up name + name_node = ExprNodes.NameNode(pos=pos, name=name) + name_node.entry = self.gen_node.def_node.gbody.local_scope.lookup(name_node.name) + name_node.type = name_node.entry.type + self.substitutions[node] = name_node + return name_node + if do_visit_children: + self.visitchildren(node) + return node + + def visit_ExprNode(self, node): + return self._handle_ExprNode(node, True) + + visit_Node = VisitorTransform.recurse_to_children + + class DecoratorTransform(ScopeTrackingTransform, SkipDeclarations): """ Transforms method decorators in cdef classes into nested calls or properties. @@ -2332,7 +2452,7 @@ def visit_ScopedExprNode(self, node): env = self.current_env() node.analyse_declarations(env) # the node may or may not have a local scope - if node.has_local_scope: + if node.expr_scope: self.seen_vars_stack.append(set(self.seen_vars_stack[-1])) self.enter_scope(node, node.expr_scope) node.analyse_scoped_declarations(node.expr_scope) @@ -2340,6 +2460,7 @@ def visit_ScopedExprNode(self, node): self.exit_scope() self.seen_vars_stack.pop() else: + node.analyse_scoped_declarations(env) self.visitchildren(node) return node @@ -3004,6 +3125,8 @@ def visit_CArgDeclNode(self, node): class MarkClosureVisitor(CythonTransform): + # In addition to marking closures this is also responsible to finding parts of the + # generator iterable and marking them def visit_ModuleNode(self, node): self.needs_closure = False @@ -3074,6 +3197,19 @@ def visit_ClassDefNode(self, node): self.needs_closure = True return node + def visit_GeneratorExpressionNode(self, node): + node = self.visit_LambdaNode(node) + if not isinstance(node.loop, Nodes._ForInStatNode): + # Possibly should handle ForFromStatNode + # but for now do nothing + return node + itseq = node.loop.iterator.sequence + # literals do not need replacing with an argument + if itseq.is_literal: + return node + _GeneratorExpressionArgumentsMarker(node).visit(itseq) + return node + class CreateClosureClasses(CythonTransform): # Output closure classes in module scope for all functions @@ -3218,6 +3354,10 @@ def visit_CFuncDefNode(self, node): self.visitchildren(node) return node + def visit_GeneratorExpressionNode(self, node): + node = _HandleGeneratorArguments()(node) + return self.visit_LambdaNode(node) + class InjectGilHandling(VisitorTransform, SkipDeclarations): """ diff --git a/Cython/Compiler/TypeInference.py b/Cython/Compiler/TypeInference.py --- a/Cython/Compiler/TypeInference.py +++ b/Cython/Compiler/TypeInference.py @@ -104,10 +104,11 @@ def visit_ForInStatNode(self, node): is_special = False sequence = node.iterator.sequence target = node.target + iterator_scope = node.iterator.expr_scope or self.current_env() if isinstance(sequence, ExprNodes.SimpleCallNode): function = sequence.function if sequence.self is None and function.is_name: - entry = self.current_env().lookup(function.name) + entry = iterator_scope.lookup(function.name) if not entry or entry.is_builtin: if function.name == 'reversed' and len(sequence.args) == 1: sequence = sequence.args[0] @@ -115,7 +116,7 @@ def visit_ForInStatNode(self, node): if target.is_sequence_constructor and len(target.args) == 2: iterator = sequence.args[0] if iterator.is_name: - iterator_type = iterator.infer_type(self.current_env()) + iterator_type = iterator.infer_type(iterator_scope) if iterator_type.is_builtin_type: # assume that builtin types have a length within Py_ssize_t self.mark_assignment( @@ -127,7 +128,7 @@ def visit_ForInStatNode(self, node): if isinstance(sequence, ExprNodes.SimpleCallNode): function = sequence.function if sequence.self is None and function.is_name: - entry = self.current_env().lookup(function.name) + entry = iterator_scope.lookup(function.name) if not entry or entry.is_builtin: if function.name in ('range', 'xrange'): is_special = True
diff --git a/tests/bugs.txt b/tests/bugs.txt --- a/tests/bugs.txt +++ b/tests/bugs.txt @@ -6,7 +6,6 @@ class_attribute_init_values_T18 unsignedbehaviour_T184 missing_baseclass_in_predecl_T262 cfunc_call_tuple_args_T408 -genexpr_iterable_lookup_T600 generator_expressions_in_class for_from_pyvar_loop_T601 temp_sideeffects_T654 # not really a bug, Cython warns about it diff --git a/tests/run/cpp_iterators.pyx b/tests/run/cpp_iterators.pyx --- a/tests/run/cpp_iterators.pyx +++ b/tests/run/cpp_iterators.pyx @@ -10,6 +10,11 @@ cdef extern from "cpp_iterators_simple.h": DoublePointerIter(double* start, int len) double* begin() double* end() + cdef cppclass DoublePointerIterDefaultConstructible: + DoublePointerIterDefaultConstructible() + DoublePointerIterDefaultConstructible(double* start, int len) + double* begin() + double* end() def test_vector(py_v): """ @@ -98,6 +103,35 @@ def test_custom(): finally: del iter +def test_custom_deref(): + """ + >>> test_custom_deref() + [1.0, 2.0, 3.0] + """ + cdef double* values = [1, 2, 3] + cdef DoublePointerIter* iter + try: + iter = new DoublePointerIter(values, 3) + return [x for x in deref(iter)] + finally: + del iter + +def test_custom_genexp(): + """ + >>> test_custom_genexp() + [1.0, 2.0, 3.0] + """ + def to_list(g): # function to hide the intent to avoid inlined-generator expression optimization + return list(g) + cdef double* values = [1, 2, 3] + cdef DoublePointerIterDefaultConstructible* iter + try: + iter = new DoublePointerIterDefaultConstructible(values, 3) + # TODO: Only needs to copy once - currently copies twice + return to_list(x for x in iter[0]) + finally: + del iter + def test_iteration_over_heap_vector(L): """ >>> test_iteration_over_heap_vector([1,2]) diff --git a/tests/run/cpp_iterators_simple.h b/tests/run/cpp_iterators_simple.h --- a/tests/run/cpp_iterators_simple.h +++ b/tests/run/cpp_iterators_simple.h @@ -8,3 +8,14 @@ class DoublePointerIter { int len_; }; +class DoublePointerIterDefaultConstructible: public DoublePointerIter { + // an alternate version that is default-constructible +public: + DoublePointerIterDefaultConstructible() : + DoublePointerIter(0, 0) + {} + DoublePointerIterDefaultConstructible(double* start, int len) : + DoublePointerIter(start, len) + {} + +}; diff --git a/tests/run/generators_py.py b/tests/run/generators_py.py --- a/tests/run/generators_py.py +++ b/tests/run/generators_py.py @@ -387,3 +387,20 @@ def test_yield_in_const_conditional_true(): """ if True: print((yield 1)) + + +def test_generator_scope(): + """ + Tests that the function is run at the correct time + (i.e. when the generator is created, not when it's run) + >>> list(test_generator_scope()) + inner running + generator created + [0, 10] + """ + def inner(val): + print("inner running") + return [0, val] + gen = (a for a in inner(10)) + print("generator created") + return gen diff --git a/tests/run/genexpr_arg_order.py b/tests/run/genexpr_arg_order.py new file mode 100644 --- /dev/null +++ b/tests/run/genexpr_arg_order.py @@ -0,0 +1,181 @@ +# mode: run +# tag: genexpr, py3, py2 + +from __future__ import print_function + +# Tests that function arguments to generator expressions are +# evaluated in the correct order (even after optimization) +# WARNING: there may be an amount of luck in this working correctly (since it +# isn't strictly enforced). Therefore perhaps be prepared to disable these +# tests if they stop working and aren't easily fixed + +import cython + [email protected] [email protected](cython.int) +def zero(): + print("In zero") + return 0 + [email protected] [email protected](cython.int) +def five(): + print("In five") + return 5 + [email protected] [email protected](cython.int) +def one(): + print("In one") + return 1 + +# FIXME - I don't think this is easy to enforce unfortunately, but it is slightly wrong +#@cython.test_assert_path_exists("//ForFromStatNode") +#def genexp_range_argument_order(): +# """ +# >>> list(genexp_range_argument_order()) +# In zero +# In five +# [0, 1, 2, 3, 4] +# """ +# return (a for a in range(zero(), five())) +# +#@cython.test_assert_path_exists("//ForFromStatNode") +#@cython.test_assert_path_exists( +# "//InlinedGeneratorExpressionNode", +# "//ComprehensionAppendNode") +#def list_range_argument_order(): +# """ +# >>> list_range_argument_order() +# In zero +# In five +# [0, 1, 2, 3, 4] +# """ +# return list(a for a in range(zero(), five())) + [email protected]_assert_path_exists("//ForFromStatNode") +def genexp_array_slice_order(): + """ + >>> list(genexp_array_slice_order()) + In zero + In five + [0, 1, 2, 3, 4] + """ + # TODO ideally find a way to add the evaluation of x to this test too + x = cython.declare(cython.int[20]) + x = list(range(20)) + return (a for a in x[zero():five()]) + [email protected]_assert_path_exists("//ForFromStatNode") [email protected]_assert_path_exists( + "//InlinedGeneratorExpressionNode", + "//ComprehensionAppendNode") +def list_array_slice_order(): + """ + >>> list(list_array_slice_order()) + In zero + In five + [0, 1, 2, 3, 4] + """ + # TODO ideally find a way to add the evaluation of x to this test too + x = cython.declare(cython.int[20]) + x = list(range(20)) + return list(a for a in x[zero():five()]) + +class IndexableClass: + def __getitem__(self, idx): + print("In indexer") + return [ idx.start, idx.stop, idx.step ] + +class NoisyAttributeLookup: + @property + def indexer(self): + print("Getting indexer") + return IndexableClass() + + @property + def function(self): + print("Getting function") + def func(a, b, c): + print("In func") + return [a, b, c] + return func + +def genexp_index_order(): + """ + >>> list(genexp_index_order()) + Getting indexer + In zero + In five + In one + In indexer + Made generator expression + [0, 5, 1] + """ + obj = NoisyAttributeLookup() + ret = (a for a in obj.indexer[zero():five():one()]) + print("Made generator expression") + return ret + [email protected]_assert_path_exists("//InlinedGeneratorExpressionNode") +def list_index_order(): + """ + >>> list_index_order() + Getting indexer + In zero + In five + In one + In indexer + [0, 5, 1] + """ + obj = NoisyAttributeLookup() + return list(a for a in obj.indexer[zero():five():one()]) + + +def genexpr_fcall_order(): + """ + >>> list(genexpr_fcall_order()) + Getting function + In zero + In five + In one + In func + Made generator expression + [0, 5, 1] + """ + obj = NoisyAttributeLookup() + ret = (a for a in obj.function(zero(), five(), one())) + print("Made generator expression") + return ret + [email protected]_assert_path_exists("//InlinedGeneratorExpressionNode") +def list_fcall_order(): + """ + >>> list_fcall_order() + Getting function + In zero + In five + In one + In func + [0, 5, 1] + """ + obj = NoisyAttributeLookup() + return list(a for a in obj.function(zero(), five(), one())) + +def call1(): + print("In call1") + return ["a"] +def call2(): + print("In call2") + return ["b"] + +def multiple_genexps_to_call_order(): + """ + >>> multiple_genexps_to_call_order() + In call1 + In call2 + """ + def takes_two_genexps(a, b): + pass + + return takes_two_genexps((x for x in call1()), (x for x in call2())) diff --git a/tests/run/genexpr_iterable_lookup_T600.pyx b/tests/run/genexpr_iterable_lookup_T600.pyx --- a/tests/run/genexpr_iterable_lookup_T600.pyx +++ b/tests/run/genexpr_iterable_lookup_T600.pyx @@ -35,6 +35,11 @@ def genexpr_iterable_in_closure(): result = list( x*2 for x in x if x != 'b' ) assert x == 'abc' # don't leak in Py3 code assert f() == 'abc' # don't leak in Py3 code + + # Py2 cleanup (pretty irrelevant to the actual test!) + import sys + if sys.version_info[0] == 2: + result = map(bytes, result) return result @@ -51,6 +56,7 @@ def genexpr_over_complex_arg(func, L): def listcomp(): """ >>> listcomp() + [0, 1, 5, 8] """ data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] data.sort(key=lambda r: r[1]) @@ -84,3 +90,15 @@ def genexpr_in_dictcomp_dictiter(): """ d = {1:2, 3:4, 5:6} return {k:d for k,d in d.iteritems() if d != 4} + + +def genexpr_over_array_slice(): + """ + >>> list(genexpr_over_array_slice()) + [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + """ + cdef double x[10] + for i in range(10): + x[i] = i + cdef int n = 5 + return (n for n in x[:n+1]) diff --git a/tests/run/locals.pyx b/tests/run/locals.pyx --- a/tests/run/locals.pyx +++ b/tests/run/locals.pyx @@ -113,3 +113,13 @@ def buffers_in_locals(object[char, ndim=1] a): cdef object[unsigned char, ndim=1] b = a return locals() + +def set_comp_scope(): + """ + locals should be evaluated in the outer scope + >>> list(set_comp_scope()) + ['something'] + """ + something = 1 + return { b for b in locals().keys() } +
Evaluation of iterables in generator expressions uses wrong scope In Python, this works: ``` it = (1,2,3) l = list(it for it in it) ``` In current Cython, this raises an error at runtime as the iterable inside of the generator expression refers to the loop target variable, not the name in the outer scope. (So the iterable happens to be None.) The name of the iterable (or rather the entire iterable expression) must be evaluated in the outer scope. Actually, it's even different - CPython simply pre-evaluates the outermost iterable when creating the generator. Example (Py3.2): ``` >>> x = [range(10)] >>> g = (i for x in x for i in x) >>> list(g) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x = [range(10)] >>> g = (i for i in range(5) for x in x) >>> list(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <genexpr> UnboundLocalError: local variable 'x' referenced before assignment ``` So, basically, the outermost iterable should be evaluated into a closure variable of the generator, instead of letting the generator evaluate it itself. This: ``` >>> x = [range(10)] >>> g = (i for x in x for i in x) ``` should be transformed into ``` x = [range(10)] def _gen(_outer_it): for x in _outer_it: for i in x: yield i g = _gen(x) ``` Note that this also applies to list comprehensions with `language_level=3`. Migrated from http://trac.cython.org/ticket/600
**scoder** changed **description** from In Python, this works: ``` it = (1,2,3) l = list(it for it in it) ``` In current Cython, this raises an error at runtime as the iterable inside of the generator expression refers to the loop target variable, not the name in the outer scope. (So the iterable happens to be None.) The name of the iterable must be looked up before creating the entry of the target variable in the inner scope. to In Python, this works: ``` it = (1,2,3) l = list(it for it in it) ``` In current Cython, this raises an error at runtime as the iterable inside of the generator expression refers to the loop target variable, not the name in the outer scope. (So the iterable happens to be None.) The name of the iterable (or rather the entire iterable expression) must be evaluated in the outer scope. commented **scoder** changed **cc** to `vitja` **description** from In Python, this works: ``` it = (1,2,3) l = list(it for it in it) ``` In current Cython, this raises an error at runtime as the iterable inside of the generator expression refers to the loop target variable, not the name in the outer scope. (So the iterable happens to be None.) The name of the iterable (or rather the entire iterable expression) must be evaluated in the outer scope. to In Python, this works: ``` it = (1,2,3) l = list(it for it in it) ``` In current Cython, this raises an error at runtime as the iterable inside of the generator expression refers to the loop target variable, not the name in the outer scope. (So the iterable happens to be None.) The name of the iterable (or rather the entire iterable expression) must be evaluated in the outer scope. commented Actually, it's even different - CPython simply pre-evaluates the outermost iterable when creating the generator. Example (Py3.2): ``` >>> x = [g = (i for x in x for i in x) >>> list(g) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9](range(10)] >>>) >>> x = [g = (i for i in range(5) for x in x) >>> list(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <genexpr> UnboundLocalError: local variable 'x' referenced before assignment ``` So, basically, the outermost iterable should be evaluated into a closure variable of the generator, instead of letting the generator evaluate it itself. This: ``` x = [range(10)](range(10)] >>>) g = (i for x in x for i in x) ``` should be transformed into ``` x = [range(10)] def _gen(_outer_it): for x in _outer_it: for i in x: yield i g = _gen(x) ``` **scoder** commented Another test that currently works differently in Python than in Cython: ``` >>> def seff(): ... print("TEST") ... return range(10) ... >>> g = (i for i in seff()) TEST >>> list(g) [1, 2, 3, 4, 5, 6, 7, 8, 9](0,) >>> g = (i for i in (v for v in seff())) TEST ``` **scoder** changed **priority** from `major` to `critical` commented **scoder** changed **milestone** from `wishlist` to `0.20` **owner** to `scoder` **priority** from `critical` to `major` **status** from `new` to `assigned` commented Fixed here: https://github.com/cython/cython/commit/87a9bc293838913af976802a63a495b3a3fe4794 **scoder** changed **priority** from `major` to `critical` **resolution** to `fixed` **status** from `assigned` to `closed` commented **scoder** changed **milestone** from `0.20` to `wishlist` **resolution** from `fixed` to empty **status** from `closed` to `reopened` commented @scoder thanks for the cleanup--I see now how the bug described in this ticket is still a problem too. I'll see if I can do something about it... Apparently the original attempt to fix this was also reverted in a3d4461252315caeef3477399c49b4e9843cd479, which is part of my confusion as well. I'd be happy to have more people look into this, but be "warned", it's not entirely trivial. Cython looks at the iterable in several places in order to optimise loops. Moving the iterable out of the generator too early will prevent these optimisations. Moving it out too late will lead to incorrect declarations inside and/or outside of the generator. This is one of the bugs that have been languishing for a bit of a reason. Thanks for the admonition. That will help me understand better what the problem is. Nominating this as a release blocker for Cython 3.0 to keep it in sight, although it's not really a breaking change.
2021-06-28T19:43:21Z
[]
[]
cython/cython
4,309
cython__cython-4309
[ "4308" ]
e46e9dd7c37d8d7ad432a94fff5daafa7fa444e3
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -311,12 +311,12 @@ def h_entries(entries, api=0, pxd=0): h_code_main.putln('__declspec(deprecated(%s)) __inline' % ( warning_string.as_c_string_literal())) h_code_main.putln('#endif') - h_code_main.putln("static PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject* res) {") + h_code_main.putln("static PyObject* __PYX_WARN_IF_%s_INIT_CALLED(PyObject* res) {" % py3_mod_func_name) h_code_main.putln("return res;") h_code_main.putln("}") # Function call is converted to warning macro; uncalled (pointer) is not - h_code_main.putln('#define %s() __PYX_WARN_IF_INIT_CALLED(%s())' % ( - py3_mod_func_name, py3_mod_func_name)) + h_code_main.putln('#define %s() __PYX_WARN_IF_%s_INIT_CALLED(%s())' % ( + py3_mod_func_name, py3_mod_func_name, py3_mod_func_name)) h_code_main.putln('#endif') h_code_main.putln('#endif')
diff --git a/tests/run/include_multiple_modules.srctree b/tests/run/include_multiple_modules.srctree new file mode 100644 --- /dev/null +++ b/tests/run/include_multiple_modules.srctree @@ -0,0 +1,31 @@ +PYTHON setup.py build_ext --inplace + +############# setup.py ############# + +from Cython.Build.Dependencies import cythonize +from distutils.core import setup + +setup( + ext_modules = cythonize(["a.pyx", "b.pyx", "include_both.pyx"]), + ) + +############# a.pyx ############### + +cdef public f(): + pass + +############# b.pyx ############### + +cdef public g(): + pass + +############# include_both.pyx #### + +# This is just checking that a and b don't duplicate any names +# and thus it's possible to include them both in one place + +cdef extern from "a.h": + pass + +cdef extern from "b.h": + pass
[BUG] in 3.0.0x, embed multi modules cause errors : redefinition of ‘PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject*)’ **Describe the bug** in embed mode, I created three cython modules, "network, engine , market" , after compiled, include the head files in main #include "engine/engine.h" #include "engine/market.h" #include "engine/network.h" all the generated head files defined same function: __PYX_WARN_IF_INIT_CALLED will cause redefinition errors **To Reproduce** In file included from /home/arthur/work/aule/src/main.cpp:11: /home/arthur/work/aule/./engine/market.h:46:18: error: redefinition of ‘PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject*)’ 46 | static PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject* res) { | ^~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /home/arthur/work/aule/src/main.cpp:10: /home/arthur/work/aule/./engine/engine.h:75:18: note: ‘PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject*)’ previously defined here 75 | static PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject* res) { | ^~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /home/arthur/work/aule/src/main.cpp:12: /home/arthur/work/aule/./engine/network.h:46:18: error: redefinition of ‘PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject*)’ 46 | static PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject* res) { | ^~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /home/arthur/work/aule/src/main.cpp:10: /home/arthur/work/aule/./engine/engine.h:75:18: note: ‘PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject*)’ previously defined here 75 | static PyObject* __PYX_WARN_IF_INIT_CALLED(PyObject* res) { | ^~~~~~~~~~~~~~~~~~~~~~~~~ make[2]: *** [CMakeFiles/xengine.dir/build.make:193: CMakeFiles/xengine.dir/src/main.cpp.o] Error 1 make[2]: *** Waiting for unfinished jobs.... make[1]: *** [CMakeFiles/Makefile2:324: CMakeFiles/xengine.dir/all] Error 2 **Expected behavior** should the generated head file use different names? **Environment (please complete the following information):** - OS: Ubuntu 20.04 - Python version 3.9.6 - Cython version 3.0.0x - gcc version (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0 **Additional context** I set up a demo here , https://github.com/cagev/cythonembeddemo
I suspect the function definition of `__PYX_WARN_IF_INIT_CALLED` should either be in a little include-guard. Or it should be renamed `__PYX_WARN_IF_<module name>_INIT_CALLED`. Either would work
2021-07-23T17:24:22Z
[]
[]
cython/cython
4,318
cython__cython-4318
[ "4137" ]
0574dbceef7b8ee16a9cc94091c3629dfa23133d
diff --git a/Cython/Compiler/Code.py b/Cython/Compiler/Code.py --- a/Cython/Compiler/Code.py +++ b/Cython/Compiler/Code.py @@ -2337,7 +2337,7 @@ def put_release_ensured_gil(self, variable=None): self.putln("__Pyx_PyGILState_Release(%s);" % variable) self.putln("#endif") - def put_acquire_gil(self, variable=None): + def put_acquire_gil(self, variable=None, unknown_gil_state=True): """ Acquire the GIL. The thread's thread state must have been initialized by a previous `put_release_gil` @@ -2347,15 +2347,26 @@ def put_acquire_gil(self, variable=None): self.putln("__Pyx_FastGIL_Forget();") if variable: self.putln('_save = %s;' % variable) + if unknown_gil_state: + self.putln("if (_save) {") self.putln("Py_BLOCK_THREADS") + if unknown_gil_state: + self.putln("}") self.putln("#endif") - def put_release_gil(self, variable=None): + def put_release_gil(self, variable=None, unknown_gil_state=True): "Release the GIL, corresponds to `put_acquire_gil`." self.use_fast_gil_utility_code() self.putln("#ifdef WITH_THREAD") self.putln("PyThreadState *_save;") + self.putln("_save = NULL;") + if unknown_gil_state: + # we don't *know* that we don't have the GIL (since we may be inside a nogil function, + # and Py_UNBLOCK_THREADS is unsafe without the GIL) + self.putln("if (PyGILState_Check()) {") self.putln("Py_UNBLOCK_THREADS") + if unknown_gil_state: + self.putln("}") if variable: self.putln('%s = _save;' % variable) self.putln("__Pyx_FastGIL_Remember();") diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -8325,9 +8325,12 @@ class GILStatNode(NogilTryFinallyStatNode): # 'with gil' or 'with nogil' statement # # state string 'gil' or 'nogil' + # scope_gil_state_known bool For nogil functions this can be False, since they can also be run with gil + # set to False by GilCheck transform child_attrs = ["condition"] + NogilTryFinallyStatNode.child_attrs state_temp = None + scope_gil_state_known = True def __init__(self, pos, state, body, condition=None): self.state = state @@ -8390,7 +8393,7 @@ def generate_execution_code(self, code): code.put_ensure_gil(variable=variable) code.funcstate.gil_owned = True else: - code.put_release_gil(variable=variable) + code.put_release_gil(variable=variable, unknown_gil_state=not self.scope_gil_state_known) code.funcstate.gil_owned = False TryFinallyStatNode.generate_execution_code(self, code) @@ -8407,10 +8410,13 @@ class GILExitNode(StatNode): Used as the 'finally' block in a GILStatNode state string 'gil' or 'nogil' + # scope_gil_state_known bool For nogil functions this can be False, since they can also be run with gil + # set to False by GilCheck transform """ child_attrs = [] state_temp = None + scope_gil_state_known = True def analyse_expressions(self, env): return self @@ -8424,7 +8430,7 @@ def generate_execution_code(self, code): if self.state == 'gil': code.put_release_ensured_gil(variable) else: - code.put_acquire_gil(variable) + code.put_acquire_gil(variable, unknown_gil_state=not self.scope_gil_state_known) class EnsureGILNode(GILExitNode): diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -3052,6 +3052,7 @@ def visit_FuncDefNode(self, node): self.env_stack.append(node.local_scope) inner_nogil = node.local_scope.nogil + nogil_declarator_only = self.nogil_declarator_only if inner_nogil: self.nogil_declarator_only = True @@ -3060,8 +3061,9 @@ def visit_FuncDefNode(self, node): self._visit_scoped_children(node, inner_nogil) - # This cannot be nested, so it doesn't need backup/restore - self.nogil_declarator_only = False + # FuncDefNodes can be nested, because a cpdef function contains a def function + # inside it. Therefore restore to previous state + self.nogil_declarator_only = nogil_declarator_only self.env_stack.pop() return node @@ -3086,6 +3088,8 @@ def visit_GILStatNode(self, node): else: error(node.pos, "Trying to release the GIL while it was " "previously released.") + if self.nogil_declarator_only: + node.scope_gil_state_known = False if isinstance(node.finally_clause, Nodes.StatListNode): # The finally clause of the GILStatNode is a GILExitNode, @@ -3136,6 +3140,12 @@ def visit_TryFinallyStatNode(self, node): self.visitchildren(node) return node + def visit_GILExitNode(self, node): + if self.nogil_declarator_only: + node.scope_gil_state_known = False + self.visitchildren(node) + return node + def visit_Node(self, node): if self.env_stack and self.nogil and node.nogil_check: node.nogil_check(self.env_stack[-1])
diff --git a/tests/run/nogil.pyx b/tests/run/nogil.pyx --- a/tests/run/nogil.pyx +++ b/tests/run/nogil.pyx @@ -28,6 +28,46 @@ cdef int g(int x) nogil: y = x + 42 return y +cdef void release_gil_in_nogil() nogil: + # This should generate valid code with/without the GIL + with nogil: + pass + +cpdef void release_gil_in_nogil2() nogil: + # This should generate valid code with/without the GIL + with nogil: + pass + +def test_release_gil_in_nogil(): + """ + >>> test_release_gil_in_nogil() + """ + with nogil: + release_gil_in_nogil() + with nogil: + release_gil_in_nogil2() + release_gil_in_nogil() + release_gil_in_nogil2() + +cdef void get_gil_in_nogil() nogil: + with gil: + pass + +cpdef void get_gil_in_nogil2() nogil: + with gil: + pass + +def test_get_gil_in_nogil(): + """ + >>> test_get_gil_in_nogil() + """ + with nogil: + get_gil_in_nogil() + with nogil: + get_gil_in_nogil2() + get_gil_in_nogil() + get_gil_in_nogil2() + cdef int with_gil_func() except -1 with gil: raise Exception("error!")
Error when using nogil in cpdef function that has nogil in signature Code below used to compile in 0.29.21 but fails on master with error >cpdef void test(const int i) nogil: with nogil, parallel(num_threads=i): ^ main.pyx:4:9: Trying to release the GIL while it was previously released. ``` from cython.parallel import parallel cpdef void test(const int i) nogil: with nogil, parallel(num_threads=i): pass ``` The [documentation](https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html#declaring-a-function-as-callable-without-the-gil) for `nogil` states: >The function does not in itself release the GIL if it is held by the caller. So the error looks like a bug.
That does look like a bug. If you want to investigate, then `git bisect` is often useful for finding out why things have decided to stop working Thinking about it more, I'm not sure if it's a bug. I think it depends on whether a `with nogil` block claims the GIL on exit, or if it restores the previous state. I don't know off the top my head. If it claims the GIL on exit then the code was probably dodgy on Cython 0.29. I'd it restores the previous state then there's no reason to make nested `with gil` blocks an error. See also https://github.com/cython/cython/issues/3443 > If it restores the previous state then there's no reason to make nested `with gil` blocks an error. Out of the top of my head, this is how it works. I agree that it should be allowed. It looks like `with nogil` expands to: ``` #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS /* i.e. _save = PyEval_SaveThread() */ __Pyx_FastGIL_Remember(); #endif ``` then ``` #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS /* PyEval_RestoreThread(_save); */ #endif ``` The documentation for `PyEval_SaveThread` says > If the lock has been created, the current thread must have acquired it. and `PyEval_RestoreThread` says > Acquire the global interpreter lock (if it has been created) Therefore, the `with nogil` block can only be used when you genuinely hold the GIL and therefore the code that used to "work" in Cython 0.29 was broken. Personally, I think it might be worth changing this since it's quite hard to do the right thing in a function marked `nogil` (where we don't actual know whether it has the GIL or not). `with gil` uses `PyGILState_Ensure/Release` which does allow recursive calls so should be safer (but doesn't work with subinterpretters)
2021-07-28T17:34:20Z
[]
[]
cython/cython
4,339
cython__cython-4339
[ "2304" ]
cce3693f14060433fcf52e2ba034c1b77a26c9e5
diff --git a/Cython/Build/Dependencies.py b/Cython/Build/Dependencies.py --- a/Cython/Build/Dependencies.py +++ b/Cython/Build/Dependencies.py @@ -1034,7 +1034,8 @@ def copy_to_build_dir(filepath, root=os.getcwd()): # setup for out of place build directory if enabled if build_dir: if os.path.isabs(c_file): - warnings.warn("build_dir has no effect for absolute source paths") + c_file = os.path.splitdrive(c_file)[1] + c_file = c_file.split(os.sep, 1)[1] c_file = os.path.join(build_dir, c_file) dir = os.path.dirname(c_file) safe_makedirs_once(dir) diff --git a/Cython/Distutils/build_ext.py b/Cython/Distutils/build_ext.py --- a/Cython/Distutils/build_ext.py +++ b/Cython/Distutils/build_ext.py @@ -12,14 +12,32 @@ class new_build_ext(_build_ext, object): - def finalize_options(self): - if self.distribution.ext_modules: - nthreads = getattr(self, 'parallel', None) # -j option in Py3.5+ - nthreads = int(nthreads) if nthreads else None - from Cython.Build.Dependencies import cythonize - self.distribution.ext_modules[:] = cythonize( - self.distribution.ext_modules, nthreads=nthreads, force=self.force) - super(new_build_ext, self).finalize_options() + + user_options = _build_ext.user_options[:] + boolean_options = _build_ext.boolean_options[:] + + user_options.extend([ + ('cython-c-in-temp', None, + "put generated C files in temp directory"), + ]) + + boolean_options.extend([ + 'cython-c-in-temp' + ]) + + def initialize_options(self): + _build_ext.initialize_options(self) + self.cython_c_in_temp = 0 + + def build_extension(self, ext): + from Cython.Build.Dependencies import cythonize + if self.cython_c_in_temp: + build_dir = self.build_temp + else: + build_dir = None + new_ext = cythonize(ext,force=self.force, quiet=self.verbose == 0, build_dir=build_dir)[0] + ext.sources = new_ext.sources + super(new_build_ext, self).build_extension(ext) # This will become new_build_ext in the future. from .old_build_ext import old_build_ext as build_ext diff --git a/pyximport/pyxbuild.py b/pyximport/pyxbuild.py --- a/pyximport/pyxbuild.py +++ b/pyximport/pyxbuild.py @@ -10,7 +10,7 @@ from distutils.extension import Extension from distutils.util import grok_environment_error try: - from Cython.Distutils.old_build_ext import old_build_ext as build_ext + from Cython.Distutils.build_ext import new_build_ext as build_ext HAS_CYTHON = True except ImportError: HAS_CYTHON = False @@ -53,7 +53,10 @@ def pyx_to_dll(filename, ext=None, force_rebuild=0, build_in_temp=False, pyxbuil quiet = "--verbose" else: quiet = "--quiet" - args = [quiet, "build_ext"] + if build_in_temp: + args = [quiet, "build_ext", '--cython-c-in-temp'] + else: + args = [quiet, "build_ext"] if force_rebuild: args.append("--force") if inplace and package_base_dir: @@ -65,8 +68,6 @@ def pyx_to_dll(filename, ext=None, force_rebuild=0, build_in_temp=False, pyxbuil elif 'set_initial_path' not in ext.cython_directives: ext.cython_directives['set_initial_path'] = 'SOURCEFILE' - if HAS_CYTHON and build_in_temp: - args.append("--pyrex-c-in-temp") sargs = setup_args.copy() sargs.update({ "script_name": None, diff --git a/pyximport/pyximport.py b/pyximport/pyximport.py --- a/pyximport/pyximport.py +++ b/pyximport/pyximport.py @@ -351,11 +351,12 @@ def __init__(self, pyxbuild_dir=None, inplace=False, language_level=None): self.uncompilable_modules = {} self.blocked_modules = ['Cython', 'pyxbuild', 'pyximport.pyxbuild', 'distutils'] + self.blocked_packages = ['Cython.', 'distutils.'] def find_module(self, fullname, package_path=None): if fullname in sys.modules: return None - if fullname.startswith('Cython.'): + if any([fullname.startswith(pkg) for pkg in self.blocked_packages]): return None if fullname in self.blocked_modules: # prevent infinite recursion
diff --git a/tests/pyximport/pyximport_pyimport_only.srctree b/tests/pyximport/pyximport_pyimport_only.srctree new file mode 100644 --- /dev/null +++ b/tests/pyximport/pyximport_pyimport_only.srctree @@ -0,0 +1,19 @@ + +PYTHON -c "import pyimport_test; pyimport_test.test()" + +######## pyimport_test.py ######## + +import os.path +import pyximport + +pyximport.install(pyximport=False, pyimport=True, + build_dir=os.path.join(os.path.dirname(__file__), "TEST_TMP")) + +def test(): + import mymodule + assert mymodule.test_string == "TEST" + assert not mymodule.__file__.rstrip('oc').endswith('.py'), mymodule.__file__ + +######## mymodule.py ######## + +test_string = "TEST" diff --git a/tests/pyximport/pyximport_pyxbld.srctree b/tests/pyximport/pyximport_pyxbld.srctree new file mode 100644 --- /dev/null +++ b/tests/pyximport/pyximport_pyxbld.srctree @@ -0,0 +1,35 @@ + +PYTHON -c "import basic_test; basic_test.test()" + +######## basic_test.py ######## + +import os.path +import pyximport + +pyximport.install(build_dir=os.path.join(os.path.dirname(__file__), "TEST_TMP")) + +def test(): + import mymodule + assert mymodule.test_string == "TEST" + assert mymodule.header_value == 5 + assert not mymodule.__file__.rstrip('oc').endswith('.py'), mymodule.__file__ + +######## mymodule.pyxbld ######## + +def make_ext(modname, pyxfilename): + from distutils.extension import Extension + return Extension(name = modname, + sources=[pyxfilename], + include_dirs=['./headers'] ) + +######## mymodule.pyx ######## + +cdef extern from "myheader.h": + int test_value + +header_value = test_value +test_string = "TEST" + +######## headers/myheader.h ######## + +static int test_value = 5;
Pyximport does not use cythonize() internally. From @scoder 's comment in #2298 about pyximport internals: > Right, and that is totally a bug. It should really use cythonize(). Definitely something to list under "limitations" below. Since pyximport does not use Cythonize internally, it prevents the use of compiler directives at the top of the `.py` or `.pyx` files. Also, using Cythonize could potentially remove quite a bit of code (potentially, all the code in `cython/pyximport/pyxbuild.py` could be removed).
Indeed `pyximport` does not currently use `cythonize` internally as it is currently building on `old_build_ext`: https://github.com/cython/cython/blob/3de7a4b8fb7ce045222e13ca02541f6a70e89c2e/pyximport/pyxbuild.py#L13 Besides preventing to use compiler directives at the top of `.py` or `.pyx`, it also makes `pyximport` to miss recompiling when build dependency change (see e.g. https://github.com/cython/cython/issues/3121). So if we switch `pyximport` to use `new_build_ext`, or to use just `from Cython.Distutils import build_ext` and switch that build_ext to new implementation that is based on `cythonize` (#3541), then this issue will be automatically fixed. I forgot where this was documented but I have had success in getting pyximport to use cythonize by creating a "_modulename_.pyxbld" file beside the "_modulename_.pyx" file. This gets pyximport to use the result of cythonize. In my experience, the compiler directives will now work. The resulting .pyxbld file looks like this: ``` # modulename.pyxbld from Cython.Build import cythonize def make_ext(modname, pyxfilename): return cythonize(pyxfilename, language_level = 3, annotate = True)[0] ``` PR very welcome that does what @navytux and @gabrieldemarmiesse have described above. Setuptools has [distutils extensions](https://setuptools.readthedocs.io/en/latest/userguide/extension.html#creating-distutils-extensions) to allow extending the universe of commands and options available when building an `Extension`. For instance, CFFI [adds a setuptools entry point `distutils.setup_keywords`](https://foss.heptapod.net/pypy/cffi/-/blob/branch/default/setup.py#L219) function `cffi_modules` so you can do this in `setup.py`: ``` from setuptools import setup setup( name="example", version="0.1", py_modules=["readdir"], setup_requires=["cffi>=1.0.dev0"], cffi_modules=["readdir_build.py:ffi"], install_requires=["cffi>=1.0.dev0"], zip_safe=False, ) ``` The function `cffi_modules`'s signature is ``` def cffi_modules(dist, attr, value): assert attr == 'cffi_modules' ``` where `dist` is a `Distribution`, value is `["readdir_build.py:ffi"]`, and the call adds a new Extension to `dist`. Maybe cython could add something similar: add a `distutils.setup_keywords` function something like `cython_modules=["myfile1.pyx", "myfile2.pxd:myfile2.pyx"]`. The `cython_module` function would add a `Extension` to `dist` for each value. This would encapsulate the call to `cythonize` as a separate step, so cython would not override `build_ext` but could pass it compilation flags. Another option would be to add a `distutils.command` for cythonize, but I am not sure how to tie that in so that `setup.py build_ext` would notice it needs to convert `pyx` files to `c` via `cythonize`. I willing to put some work into this.
2021-08-12T19:45:04Z
[]
[]
cython/cython
4,349
cython__cython-4349
[ "4348" ]
8af0271186cc642436306274564986888d5e64c8
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -1012,11 +1012,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
diff --git a/tests/errors/cpp_bool.pyx b/tests/errors/cpp_bool.pyx new file mode 100644 --- /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 +"""
[BUG] Calling 'operator bool' results in 'AttributeError' <!-- **PLEASE READ THIS FIRST:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Describe the bug** Declaring a C++ string and then invoking an `if <identifier>:` operation on it raises an `AttributeError`: ``` [1/1] Cythonizing test.pyx Traceback (most recent call last): File "/Users/lkisskollar/tmp/cython_bug/setup.py", line 4, in <module> setup(name="test", version="0.1.0", ext_modules=cythonize(["test.pyx"], language_level=3)) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Build/Dependencies.py", line 1116, in cythonize cythonize_one(*args) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Build/Dependencies.py", line 1262, in cythonize_one result = compile_single(pyx_file, options, full_module_name=full_module_name) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Main.py", line 577, in compile_single return run_pipeline(source, options, full_module_name) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Main.py", line 505, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Pipeline.py", line 372, in run_pipeline data = run(phase, data) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Pipeline.py", line 352, in run return phase(data) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/ModuleNode.py", line 206, in process_implementation self.generate_c_code(env, options, result) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/ModuleNode.py", line 501, in generate_c_code self.body.generate_function_definitions(env, code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 403, in generate_function_definitions stat.generate_function_definitions(env, code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 2067, in generate_function_definitions self.generate_function_body(env, code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 1827, in generate_function_body self.body.generate_execution_code(code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 6798, in generate_execution_code if_clause.generate_execution_code(code, end_label, is_last=i == last) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Nodes.py", line 6837, in generate_execution_code self.condition.generate_evaluation_code(code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/ExprNodes.py", line 6210, in generate_evaluation_code self.function.generate_evaluation_code(code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/ExprNodes.py", line 829, in generate_evaluation_code self.generate_result_code(code) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/ExprNodes.py", line 7360, in generate_result_code code.intern_identifier(self.attribute), File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Code.py", line 1948, in intern_identifier return self.get_py_string_const(text, identifier=True) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Code.py", line 1938, in get_py_string_const return self.globalstate.get_py_string_const( File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Code.py", line 1379, in get_py_string_const c_string = self.get_string_const(text) File "/Users/lkisskollar/tmp/cython_bug/venv/lib/python3.9/site-packages/Cython/Compiler/Code.py", line 1350, in get_string_const if text.is_unicode: AttributeError: 'str' object has no attribute 'is_unicode' ``` **To Reproduce** Code to reproduce the behaviour: ```cython # distutils: language=c++ from libcpp.string cimport string cdef foo(): cdef string field if field: pass ``` **Expected behavior** No compiler crash and an error message that this is an invalid operation. **Environment (please complete the following information):** - OS: [e.g. Linux, Windows, macOS] macOS - Python version [e.g. 3.8.4] 3.9.4 - Cython version [e.g. 0.29.18] 0.29.24 and 3.0.0a9
2021-08-26T18:20:27Z
[]
[]
cython/cython
4,358
cython__cython-4358
[ "4354" ]
ba6eba21e82e34a14bdae4996fd0b9b297c40f72
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -9237,7 +9237,10 @@ def save_parallel_vars(self, code): if not lastprivate or entry.type.is_pyobject: continue - type_decl = entry.type.empty_declaration_code() + if entry.type.is_cpp_class and not entry.type.is_fake_reference and code.globalstate.directives['cpp_locals']: + type_decl = entry.type.cpp_optional_declaration_code("") + else: + type_decl = entry.type.empty_declaration_code() temp_cname = "__pyx_parallel_temp%d" % temp_count private_cname = entry.cname @@ -9251,10 +9254,17 @@ def save_parallel_vars(self, code): # Declare the parallel private in the outer block c.putln("%s %s%s;" % (type_decl, temp_cname, init)) + self.parallel_private_temps.append((temp_cname, private_cname, entry.type)) + + if entry.type.is_cpp_class: + # moving is fine because we're quitting the loop and so won't be directly accessing the variable again + code.globalstate.use_utility_code( + UtilityCode.load_cached("MoveIfSupported", "CppSupport.cpp")) + private_cname = "__PYX_STD_MOVE_IF_SUPPORTED(%s)" % private_cname # Initialize before escaping code.putln("%s = %s;" % (temp_cname, private_cname)) - self.parallel_private_temps.append((temp_cname, private_cname)) + code.end_block() # end critical section @@ -9375,7 +9385,10 @@ def end_parallel_control_flow_block( code.putln( "if (%s) {" % Naming.parallel_why) - for temp_cname, private_cname in self.parallel_private_temps: + for temp_cname, private_cname, temp_type in self.parallel_private_temps: + if temp_type.is_cpp_class: + # utility code was loaded earlier + temp_cname = "__PYX_STD_MOVE_IF_SUPPORTED(%s)" % temp_cname code.putln("%s = %s;" % (private_cname, temp_cname)) code.putln("switch (%s) {" % Naming.parallel_why)
diff --git a/tests/run/cpp_locals_parallel.pyx b/tests/run/cpp_locals_parallel.pyx new file mode 100644 --- /dev/null +++ b/tests/run/cpp_locals_parallel.pyx @@ -0,0 +1,33 @@ +# mode: run +# tag: cpp, cpp17, no-cpp-locals, openmp +# no-cpp-locals because the test is already run with it explicitly set + +# cython: cpp_locals=True + +from cython.parallel cimport prange + +cdef extern from *: + """ + class Test { + public: + Test() = delete; + Test(int v) : value(v) {} + + int get_value() const { return value; } + private: + int value; + }; + """ + cdef cppclass Test: + Test(int) nogil + int get_value() + +def test(): + """ + >>> test() + 9 + """ + cdef int i + for i in prange(10, nogil=True): + var = Test(i) + print(var.get_value())
[BUG] cpp_locals generates broken code for thread local temp variables **Describe the bug** When using cpp_locals(True) in combination with exception handling inside of a prange, an incorrect assignment is generated. The following code: ```cython cimport cython from cython.parallel import prange cdef extern from *: """ class Test { }; """ cdef cppclass Test: Test() nogil except + @cython.cpp_locals(True) cdef test(): cdef int i for i in prange(10, nogil=True): var = Test() ``` uses std::optional<Test> to store the variable, while it uses Test to store the thread local variable. This results in an invalid assignment: ``` CYTHON_UNUSED __Pyx_Optional_Type<Test> __pyx_v_var; __Pyx_Optional_Type<Test> __pyx_t_3; ... Test __pyx_parallel_temp1; ... __pyx_t_3 = Test(); __pyx_v_var = std::move((*__pyx_t_3)); ... __pyx_parallel_temp1 = __pyx_v_var; ``` here the last assignment to `__pyx_parallel_temp1` is invalid. **Expected behavior** The temporary variable `__pyx_parallel_temp1` should use the type `__Pyx_Optional_Type<Test>` as well.
I'd obviously missed that pranges have their own type of temp. I also wonder if the assignment to parallel_temp should use `std::move` too (although that would need a close look at the context it's used in) > I also wonder if the assignment to parallel_temp should use std::move too (although that would need a close look at the context it's used in) I wondered this too, since it would help me with my problem from https://github.com/cython/cython/issues/4352.
2021-09-01T18:50:34Z
[]
[]
cython/cython
4,375
cython__cython-4375
[ "4367" ]
aea4e6b84b38223c540266f8c57093ee2039f284
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -1750,6 +1750,8 @@ class FuncDefNode(StatNode, BlockNode): code_object = None return_type_annotation = None + outer_attrs = None # overridden by some derived classes - to be visited outside the node's scope + def analyse_default_values(self, env): default_seen = 0 for arg in self.args: diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -2054,8 +2054,6 @@ def visit_FuncDefNode(self, node): def visit_DefNode(self, node): node = self.visit_FuncDefNode(node) env = self.current_env() - if isinstance(node, Nodes.DefNode) and node.is_wrapper: - env = env.parent_scope if (not isinstance(node, Nodes.DefNode) or node.fused_py_func or node.is_generator_body or not node.needs_assignment_synthesis(env)): diff --git a/Cython/Compiler/Visitor.py b/Cython/Compiler/Visitor.py --- a/Cython/Compiler/Visitor.py +++ b/Cython/Compiler/Visitor.py @@ -370,8 +370,10 @@ def exit_scope(self): self.env_stack.pop() def visit_FuncDefNode(self, node): + outer_attrs = node.outer_attrs + self.visitchildren(node, attrs=outer_attrs) self.enter_scope(node, node.local_scope) - self._process_children(node) + self.visitchildren(node, attrs=None, exclude=outer_attrs) self.exit_scope() return node
diff --git a/tests/run/decorators.pyx b/tests/run/decorators.pyx --- a/tests/run/decorators.pyx +++ b/tests/run/decorators.pyx @@ -61,3 +61,23 @@ a = A() @a.decorate def i(x): return x - 1 + +def append_to_list_decorator(lst): + def do_append_to_list_dec(func): + def new_func(): + return lst + func() + return new_func + return do_append_to_list_dec + +def outer(arg1, arg2): + """ + ensure decorators are analysed in the correct scope + https://github.com/cython/cython/issues/4367 + mainly intended as a compile-time test (but it does run...) + >>> outer(append_to_list_decorator, [1,2,3]) + [1, 2, 3, 4] + """ + @arg1([x for x in arg2]) + def method(): + return [4] + return method()
[BUG] no member named ‘__pyx_outer_scope’ <!-- **PLEASE READ THIS FIRST:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Describe the bug** Cython generates c code which fails to compile **To Reproduce** Code to reproduce the behaviour: ```cython # test.py def func(arg1, arg2): @arg1([x for x in arg2]) async def method(): pass ``` ```console $ cython -3 test.py $ cc -I/usr/include/python3.9 -c -o test.o test.c ``` ``` test.c: In function ‘__pyx_pf_4test_func’: test.c:2209:34: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_outer_scope’ 2209 | if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) { __Pyx_RaiseClosureNameError("arg2"); __PYX_ERR(0, 2, __pyx_L1_error) } | ^~ test.c:994:43: note: in definition of macro ‘unlikely’ 994 | #define unlikely(x) __builtin_expect(!!(x), 0) | ^ test.c:2210:49: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_outer_scope’ 2210 | if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) { | ^~ test.c:993:43: note: in definition of macro ‘likely’ 993 | #define likely(x) __builtin_expect(!!(x), 1) | ^ /usr/include/python3.9/object.h:130:42: note: in expansion of macro ‘_PyObject_CAST_CONST’ 130 | #define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST_CONST(ob), type) | ^~~~~~~~~~~~~~~~~~~~ /usr/include/python3.9/listobject.h:26:31: note: in expansion of macro ‘Py_IS_TYPE’ 26 | #define PyList_CheckExact(op) Py_IS_TYPE(op, &PyList_Type) | ^~~~~~~~~~ test.c:2210:16: note: in expansion of macro ‘PyList_CheckExact’ 2210 | if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) { | ^~~~~~~~~~~~~~~~~ In file included from /usr/include/python3.9/pytime.h:6, from /usr/include/python3.9/Python.h:94, from test.c:16: test.c:2210:122: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_outer_scope’ 2210 | if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) { | ^~ /usr/include/python3.9/object.h:113:53: note: in definition of macro ‘_PyObject_CAST_CONST’ 113 | #define _PyObject_CAST_CONST(op) ((const PyObject*)(op)) | ^~ /usr/include/python3.9/tupleobject.h:28:32: note: in expansion of macro ‘Py_IS_TYPE’ 28 | #define PyTuple_CheckExact(op) Py_IS_TYPE(op, &PyTuple_Type) | ^~~~~~~~~~ test.c:2210:88: note: in expansion of macro ‘PyTuple_CheckExact’ 2210 | if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2)) { | ^~~~~~~~~~~~~~~~~~ test.c:2211:34: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_outer_scope’ 2211 | __pyx_t_4 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; | ^~ test.c:2214:67: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_outer_scope’ 2214 | __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_arg2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2, __pyx_L1_error) | ^~ test.c:2250:40: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_7genexpr__pyx_v_x’ 2250 | __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_7genexpr__pyx_v_x, __pyx_t_7); | ^~ test.c:1119:38: note: in definition of macro ‘__Pyx_XDECREF_SET’ 1119 | PyObject *tmp = (PyObject *) r;\ | ^ test.c:2250:40: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_7genexpr__pyx_v_x’ 2250 | __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_7genexpr__pyx_v_x, __pyx_t_7); | ^~ test.c:1120:9: note: in definition of macro ‘__Pyx_XDECREF_SET’ 1120 | r = v; __Pyx_XDECREF(tmp);\ | ^ test.c:2253:79: error: ‘struct __pyx_obj_4test___pyx_scope_struct__func’ has no member named ‘__pyx_7genexpr__pyx_v_x’ 2253 | if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_cur_scope->__pyx_7genexpr__pyx_v_x))) __PYX_ERR(0, 2, __pyx_L1_error) | ^~ test.c:994:43: note: in definition of macro ‘unlikely’ 994 | #define unlikely(x) __builtin_expect(!!(x), 0) | ^ ``` **Expected behavior** The code compiles without errors **Environment (please complete the following information):** - OS: Linux - Python 3.9.6 - Cython version 0.29.24 and Cython version 3.0.0a9 - cc (GCC) 11.1.0 **Additional context** This works: ```cython # test.py def func(arg1, arg2): list_ = [x for x in arg2] @arg1(list_) async def method(): pass ```
If doesn't specifically look to be related to `async` - you get the same issue with a regular def function. I suspect the decorator is just analysed in the scope of `method` at some point rather than in the scope of `func`.
2021-09-12T17:27:26Z
[]
[]
cython/cython
4,378
cython__cython-4378
[ "4377" ]
aea4e6b84b38223c540266f8c57093ee2039f284
diff --git a/Cython/Compiler/Code.py b/Cython/Compiler/Code.py --- a/Cython/Compiler/Code.py +++ b/Cython/Compiler/Code.py @@ -1138,7 +1138,8 @@ class GlobalState(object): 'pystring_table', 'cached_builtins', 'cached_constants', - 'init_globals', + 'init_constants', + 'init_globals', # (utility code called at init-time) 'init_module', 'cleanup_globals', 'cleanup_module', @@ -1209,6 +1210,11 @@ def initialize_main_c_code(self): w.putln("") w.putln("static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {") + w = self.parts['init_constants'] + w.enter_cfunc_scope() + w.putln("") + w.putln("static CYTHON_SMALL_CODE int __Pyx_InitConstants(void) {") + if not Options.generate_cleanup_code: del self.parts['cleanup_globals'] else: @@ -1284,13 +1290,14 @@ def close_global_decls(self): w.putln("}") w.exit_cfunc_scope() - w = self.parts['init_globals'] - w.putln("return 0;") - if w.label_used(w.error_label): - w.put_label(w.error_label) - w.putln("return -1;") - w.putln("}") - w.exit_cfunc_scope() + for part in ['init_globals', 'init_constants']: + w = self.parts[part] + w.putln("return 0;") + if w.label_used(w.error_label): + w.put_label(w.error_label) + w.putln("return -1;") + w.putln("}") + w.exit_cfunc_scope() if Options.generate_cleanup_code: w = self.parts['cleanup_globals'] @@ -1510,7 +1517,7 @@ def generate_cached_methods_decls(self): return decl = self.parts['decls'] - init = self.parts['init_globals'] + init = self.parts['init_constants'] cnames = [] for (type_cname, method_name), cname in sorted(self.cached_cmethods.items()): cnames.append(cname) @@ -1560,7 +1567,7 @@ def generate_string_constants(self): decls_writer.putln("static Py_UNICODE %s[] = { %s };" % (cname, utf16_array)) decls_writer.putln("#endif") - init_globals = self.parts['init_globals'] + init_constants = self.parts['init_constants'] if py_strings: self.use_utility_code(UtilityCode.load_cached("InitStrings", "StringTools.c")) py_strings.sort() @@ -1575,9 +1582,9 @@ def generate_string_constants(self): decls_writer.putln("#if !CYTHON_USE_MODULE_STATE") not_limited_api_decls_writer = decls_writer.insertion_point() decls_writer.putln("#endif") - init_globals.putln("#if CYTHON_USE_MODULE_STATE") - init_globals_in_module_state = init_globals.insertion_point() - init_globals.putln("#endif") + init_constants.putln("#if CYTHON_USE_MODULE_STATE") + init_constants_in_module_state = init_constants.insertion_point() + init_constants.putln("#endif") for idx, py_string_args in enumerate(py_strings): c_cname, _, py_string = py_string_args if not py_string.is_str or not py_string.encoding or \ @@ -1627,20 +1634,20 @@ def generate_string_constants(self): py_string.is_str, py_string.intern )) - init_globals_in_module_state.putln("if (__Pyx_InitString(%s[%d], &%s) < 0) %s;" % ( + init_constants_in_module_state.putln("if (__Pyx_InitString(%s[%d], &%s) < 0) %s;" % ( Naming.stringtab_cname, idx, py_string.cname, - init_globals.error_goto(self.module_pos))) + init_constants.error_goto(self.module_pos))) w.putln("{0, 0, 0, 0, 0, 0, 0}") w.putln("};") - init_globals.putln("#if !CYTHON_USE_MODULE_STATE") - init_globals.putln( + init_constants.putln("#if !CYTHON_USE_MODULE_STATE") + init_constants.putln( "if (__Pyx_InitStrings(%s) < 0) %s;" % ( Naming.stringtab_cname, - init_globals.error_goto(self.module_pos))) - init_globals.putln("#endif") + init_constants.error_goto(self.module_pos))) + init_constants.putln("#endif") def generate_num_constants(self): consts = [(c.py_type, c.value[0] == '-', len(c.value), c.value, c.value_code, c) @@ -1648,7 +1655,7 @@ def generate_num_constants(self): consts.sort() decls_writer = self.parts['decls'] decls_writer.putln("#if !CYTHON_USE_MODULE_STATE") - init_globals = self.parts['init_globals'] + init_constants = self.parts['init_constants'] for py_type, _, _, value, value_code, c in consts: cname = c.cname self.parts['module_state'].putln("PyObject *%s;" % cname) @@ -1669,9 +1676,9 @@ def generate_num_constants(self): function = "PyInt_FromLong(%sL)" else: function = "PyInt_FromLong(%s)" - init_globals.putln('%s = %s; %s' % ( + init_constants.putln('%s = %s; %s' % ( cname, function % value_code, - init_globals.error_goto_if_null(cname, self.module_pos))) + init_constants.error_goto_if_null(cname, self.module_pos))) decls_writer.putln("#endif") # The functions below are there in a transition phase only diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -2939,7 +2939,7 @@ def generate_module_init_func(self, imported_modules, env, code): # start of module init/exec function (pre/post PEP 489) code.putln("{") - + code.putln('int stringtab_initialized = 0;') tempdecl_code = code.insertion_point() profile = code.globalstate.directives['profile'] @@ -3012,7 +3012,10 @@ def generate_module_init_func(self, imported_modules, env, code): code.putln("#endif") code.putln("/*--- Initialize various global constants etc. ---*/") - code.put_error_if_neg(self.pos, "__Pyx_InitGlobals()") + code.put_error_if_neg(self.pos, "__Pyx_InitConstants()") + code.putln("stringtab_initialized = 1;") + code.put_error_if_neg(self.pos, "__Pyx_InitGlobals()") # calls any utility code + code.putln("#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || " "__PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)") @@ -3095,7 +3098,9 @@ def generate_module_init_func(self, imported_modules, env, code): for cname, type in code.funcstate.all_managed_temps(): code.put_xdecref(cname, type) code.putln('if (%s) {' % env.module_cname) - code.putln('if (%s) {' % env.module_dict_cname) + code.putln('if (%s && stringtab_initialized) {' % env.module_dict_cname) + # We can run into errors before the module or stringtab are initialized. + # In this case it is not safe to add a traceback (because it uses the stringtab) code.put_add_traceback(EncodedString("init %s" % env.qualified_name)) code.globalstate.use_utility_code(Nodes.traceback_utility_code) # Module reference and module dict are in global variables which might still be needed
diff --git a/tests/run/numpy_import_array_error.srctree b/tests/run/numpy_import_array_error.srctree new file mode 100644 --- /dev/null +++ b/tests/run/numpy_import_array_error.srctree @@ -0,0 +1,40 @@ +PYTHON setup.py build_ext -i +PYTHON main.py + +############# setup.py ############ + +from distutils.core import setup +from Cython.Build import cythonize + +setup(ext_modules = cythonize('cimport_numpy.pyx')) + +############# numpy.pxd ############ + +# A fake Numpy module. This defines a version of _import_array +# that always fails. The Cython-generated call to _import_array +# happens quite early (before the stringtab is initialized) +# and thus the error itself handling could cause a segmentation fault +# https://github.com/cython/cython/issues/4377 + +cdef extern from *: + """ + #define NPY_NDARRAYOBJECT_H + static int _import_array(void) { + PyErr_SetString(PyExc_ValueError, "Oh no!"); + return -1; + } + """ + int _import_array() except -1 + +############# cimport_numpy.pyx ########### + +cimport numpy + +############# main.py #################### + +try: + import cimport_numpy +except ImportError as e: + print(e) +else: + assert(False)
[BUG] segmentation fault when numpy is not available **Describe the bug** When using `cimport numpy` and `numpy` is not available at runtime, a segmentation fault is thrown. **To Reproduce** I used the following code ```cython # distutils: language=c++ # cython: language_level=3, binding=True cimport numpy as np def test(): pass ``` and uninstalled numpy before importing the module. For Cython 3.0a1 and Cython 0.29.24 this leads to an import error, while for any version newer than Cython 3.0a1 this causes a segmentation fault. **Expected behavior** No segmentation fault should be thrown. **Environment (please complete the following information):** - OS: tested on Windows and Fedora - Python version: tested on 3.7 and 3.9 - Cython version >3.0a1 **Additional context** running the import in gdb leads to the following backtrace: ``` Program received signal SIGSEGV, Segmentation fault. __Pyx_CLineForTraceback (c_line=3988, tstate=0x55555555afa0) at src/test.cpp:5923 5923 __PYX_PY_DICT_LOOKUP_IF_MODIFIED( (gdb) bt #0 __Pyx_CLineForTraceback (c_line=3988, tstate=0x55555555afa0) at src/test.cpp:5923 #1 __Pyx_AddTraceback (filename=0x7ffff7fba89b "test.pyx", py_line=2, c_line=3988, funcname=0x7ffff7fba886 "init test") at src/test.cpp:6105 #2 __pyx_pymod_exec_test (__pyx_pyinit_module=<optimized out>) at src/test.cpp:4057 #3 0x00007ffff7ddcdc3 in PyModule_ExecDef (module=<module at remote 0x7fffea250090>, def=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Objects/moduleobject.c:399 #4 0x00007ffff7ddcd34 in exec_builtin_or_dynamic (mod=<module at remote 0x7fffea250090>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/import.c:2248 #5 _imp_exec_builtin_impl (mod=<module at remote 0x7fffea250090>, module=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/import.c:2341 #6 _imp_exec_builtin (module=<optimized out>, mod=<module at remote 0x7fffea250090>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/clinic/import.c.h:388 #7 0x00007ffff7d6a36b in cfunction_vectorcall_O ( func=<built-in method exec_dynamic of module object at remote 0x7fffea3746d0>, args=0x7fffea2de8f8, nargsf=<optimized out>, kwnames=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Objects/methodobject.c:516 #8 0x00007ffff7d63fc7 in do_call_core (kwdict={}, callargs=(<module at remote 0x7fffea250090>,), func=<built-in method exec_dynamic of module object at remote 0x7fffea3746d0>, tstate=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:5095 #9 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=<optimized out>, throwflag=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:3580 #10 0x00007ffff7d5d00d in _PyEval_EvalFrame (throwflag=0, f=Frame 0x7fffea2d7ac0, for file <frozen importlib._bootstrap>, line 228, in _call_with_frames_removed (f=<built-in method exec_dynamic of module object at remote 0x7fffea3746d0>, args=(<module at remote 0x7fffea250090>,), kwds={}), tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/internal/pycore_ceval.h:40 #11 _PyEval_EvalCode (tstate=<optimized out>, _co=<optimized out>, globals=<optimized out>, locals=<optimized out>, args=<optimized out>, argcount=<optimized out>, kwnames=0x0, kwargs=0x7fffea2d7e18, kwcount=0, kwstep=1, defs=0x0, defcount=0, kwdefs=0x0, closure=0x0, name='_call_with_frames_removed', qualname='_call_with_frames_removed') at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:4327 #12 0x00007ffff7d6acee in _PyFunction_Vectorcall (func=<optimized out>, stack=<optimized out>, nargsf=<optimized out>, kwnames=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Objects/call.c:396 #13 0x00007ffff7d6305e in _PyObject_VectorcallTstate (kwnames=0x0, nargsf=<optimized out>, args=0x7fffea2d7e08, callable=<function at remote 0x7fffea38b430>, tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/cpython/abstract.h:118 #14 PyObject_Vectorcall (kwnames=0x0, nargsf=<optimized out>, args=0x7fffea2d7e08, callable=<function at remote 0x7fffea38b430>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/cpython/abstract.h:127 #15 call_function (kwnames=0x0, oparg=<optimized out>, pp_stack=<synthetic pointer>, tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:5075 #16 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=<optimized out>, throwflag=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:3487 #17 0x00007ffff7d6afe3 in _PyEval_EvalFrame (throwflag=0, f=Frame 0x7fffea2d7c80, for file <frozen importlib._bootstrap_external>, line 1181, in exec_module (self=<ExtensionFileLoader(name='rapidfuzz.test', path='/home/max/RapidFuzz/.venv/lib64/python3.9/site-packages/rapidfuzz/test.cpython-39-x86_64-linux-gnu.so') at remote 0x7fffea2498b0>, module=<module at remote 0x7fffea250090>), tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/internal/pycore_ceval.h:40 #18 function_code_fastcall (tstate=0x55555555afa0, co=<optimized out>, args=<optimized out>, nargs=2, globals=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Objects/call.c:330 #19 0x00007ffff7d5e5eb in _PyObject_VectorcallTstate (kwnames=0x0, nargsf=<optimized out>, args=0x7fffea310f50, callable=<function at remote 0x7fffea34f790>, tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/cpython/abstract.h:118 #20 PyObject_Vectorcall (kwnames=0x0, nargsf=<optimized out>, args=0x7fffea310f50, callable=<function at remote 0x7fffea34f790>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/cpython/abstract.h:127 #21 call_function (kwnames=0x0, oparg=<optimized out>, pp_stack=<synthetic pointer>, tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:5075 --Type <RET> for more, q to quit, c to continue without paging-- #22 _PyEval_EvalFrameDefault (tstate=<optimized out>, f=<optimized out>, throwflag=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Python/ceval.c:3504 #23 0x00007ffff7d6afe3 in _PyEval_EvalFrame (throwflag=0, f=Frame 0x7fffea310dd0, for file <frozen importlib._bootstrap>, line 680, in _load_unlocked (spec=<ModuleSpec(name='rapidfuzz.test', loader=<ExtensionFileLoader(name='rapidfuzz.test', path='/home/max/RapidFuzz/.venv/lib64/python3.9/site-packages/rapidfuzz/test.cpython-39-x86_64-linux-gnu.so') at remote 0x7fffea2498b0>, origin='/home/max/RapidFuzz/.venv/lib64/python3.9/site-packages/rapidfuzz/test.cpython-39-x86_64-linux-gnu.so', loader_state=None, submodule_search_locations=None, _set_fileattr=True, _cached=None, _initializing=True) at remote 0x7fffea2492b0>, module=<module at remote 0x7fffea250090>), tstate=0x55555555afa0) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Include/internal/pycore_ceval.h:40 #24 function_code_fastcall (tstate=0x55555555afa0, co=<optimized out>, args=<optimized out>, nargs=1, globals=<optimized out>) at /usr/src/debug/python3.9-3.9.7-1.fc34.x86_64/Objects/call.c:330 ``` For the full backtrace check the following file: [backtrace.txt](https://github.com/cython/cython/files/7169134/backtrace.txt)
It looks to be f18e3c9f9ce35ebf2cf2713775f35c47351e9c15 (i.e. my fault). I think this is kind of intentional (partly). If you're doing `cimport numpy` then you *should* be calling the Numpy C function `import_array` too. A lot of people were forgetting to do it (and getting odd crashes later because of it), so we started adding it in automatically. To disable this autogeneration you can do: ``` # at global scope <void>np.import_array ``` (i.e. just "use" the symbol from Cython's point of view). It looks like `np.import_array` crashes when the Numpy module isn't present, so possibly we should guard against that. But I'm not sure how right now. What I'm a little puzzled by is that the first thing `import_array` does is to try to import the Python module and raise an exception if that fails. So it should be pretty safe: https://github.com/numpy/numpy/blob/1f95d7914ff23ffeb95767de79c55b4f702e6f2f/numpy/core/code_generators/generate_numpy_api.py#L44-L52 ------------------- Edit: OK - the problem isn't in `import_array` - it actually happens if you raise any exception in `__Pyx_InitGlobals` > If you're doing cimport numpy then you should be calling the Numpy C function import_array too. A lot of people were forgetting to do it (and getting odd crashes later because of it), so we started adding it in automatically. Yes I received a bug report yesterday, about my library crashing on arm since I started to use numpy: https://github.com/maxbachmann/Levenshtein/issues/12 My first thought was that I forgot to call import_array (which I did forget :smile:) and was very surprised to find, that this is automatically done by Cython. ``` __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback) ``` but we import Numpy before initializing the string-tab... Should be fairly easily fixed I think > I received a bug report yesterday, about my library crashing on arm since I started to use numpy: maxbachmann/Levenshtein#12 > My first thought was that I forgot to call import_array (which I did forget smile) and was very surprised to find, that this is automatically done by Cython. I attempted to fix this by manually running `np.import_array` https://github.com/maxbachmann/RapidFuzz/blob/7cc1e5a053c6f2e7d84dd7348b766a2044a48c71/src/cpp_process_cdist.pyx#L44. This did indeed fix the segmentation fault. Now I am down to being binary incompatible, since pibuildwheels does not correctly use `oldest-supported-numpy` https://github.com/piwheels/packages/issues/212 ...
2021-09-15T17:59:36Z
[]
[]
cython/cython
4,413
cython__cython-4413
[ "4409" ]
c129b15e8ee249a33ca9a5dc82a3defe509ad5c0
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -13814,6 +13814,12 @@ def generate_result_code(self, code): def generate_disposal_code(self, code): pass + def generate_post_assignment_code(self, code): + # if we're assigning from a CloneNode then it's "giveref"ed away, so it does + # need a matching incref (ideally this should happen before the assignment though) + if self.is_temp: # should usually be true + code.put_incref(self.result(), self.ctype()) + def free_temps(self, code): pass diff --git a/Cython/Compiler/FusedNode.py b/Cython/Compiler/FusedNode.py --- a/Cython/Compiler/FusedNode.py +++ b/Cython/Compiler/FusedNode.py @@ -841,7 +841,8 @@ def analyse_expressions(self, env): for arg in self.node.args: if arg.default: arg.default = arg.default.analyse_expressions(env) - defaults.append(ProxyNode(arg.default)) + # coerce the argument to temp since CloneNode really requires a temp + defaults.append(ProxyNode(arg.default.coerce_to_temp(env))) else: defaults.append(None) @@ -851,7 +852,7 @@ def analyse_expressions(self, env): # the dispatcher specifically doesn't want its defaults overriding for arg, default in zip(stat.args, defaults): if default is not None: - arg.default = CloneNode(default).coerce_to(arg.type, env) + arg.default = CloneNode(default).analyse_expressions(env).coerce_to(arg.type, env) if self.py_func: args = [CloneNode(default) for default in defaults if default] diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -2348,9 +2348,11 @@ def generate_wrapper_functions(self, code): def generate_execution_code(self, code): code.mark_pos(self.pos) # Evaluate and store argument default values - for arg in self.args: - if not arg.is_dynamic: - arg.generate_assignment_code(code) + # skip this for wrappers since it's done by wrapped function + if not self.is_wrapper: + for arg in self.args: + if not arg.is_dynamic: + arg.generate_assignment_code(code) # # Special code for the __getbuffer__ function
diff --git a/tests/run/fused_cpdef.pyx b/tests/run/fused_cpdef.pyx --- a/tests/run/fused_cpdef.pyx +++ b/tests/run/fused_cpdef.pyx @@ -1,4 +1,4 @@ -# cython: language_level=3 +# cython: language_level=3str # mode: run cimport cython @@ -186,3 +186,26 @@ def test_ambiguousmatch(): Traceback (most recent call last): TypeError: Function call with ambiguous argument types """ + +# https://github.com/cython/cython/issues/4409 +# default arguments + fused cpdef were crashing +cpdef literal_default(cython.integral x, some_string="value"): + return x, some_string + +cpdef mutable_default(cython.integral x, some_value=[]): + some_value.append(x) + return some_value + +def test_defaults(): + """ + >>> literal_default(1) + (1, 'value') + >>> literal_default(1, "hello") + (1, 'hello') + >>> mutable_default(1) + [1] + >>> mutable_default(2) + [1, 2] + >>> mutable_default(3,[]) + [3] + """
[BUG] segfault on pandas with 3.0a9 Building pandas master (which works with cython 0.29.x) with the 3.0a9 I'm getting a segfault in https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/hashtable_func_helper.pxi.in#L110 lldb is pointing me towards a `__Pyx_INCREF` call: ``` frame #1: 0x000000011da6ef72 hashtable.cpython-39-darwin.so`__pyx_pw_6pandas_5_libs_9hashtable_73__pyx_fuse_12duplicated [inlined] __pyx_f_6pandas_5_libs_9hashtable_duplicated_object(__pyx_v_values=0x0000000000000000, __pyx_optional_args=<unavailable>) at hashtable.c:101383 [opt] 101380 * raise ValueError('keep must be either "first", "last" or False') 101381 * 101382 */ -> 101383 __Pyx_INCREF(__pyx_v_keep); 101384 __pyx_t_2 = __pyx_v_keep; 101385 __pyx_t_9 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_n_u_last, Py_NE)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(3, 1504, __pyx_L1_error) 101386 if (__pyx_t_9) { ``` Not sure if this means anything, but sublimetext's syntax highlighting seems to stop about 60k lines before this
It looks from that traceback as if `values` is being passed a NULL pointer (which is probably a Cython bug, but likely happening a little further up the traceback). Could you tell us what code you're running to get it to crash? `pytest pandas/tests/libs/` @jbrockmendel do you know which case is crashing here? Is the caller passing `keep` in or is it using the default value? (Note that it's not `values` being passed as `NULL` but the `keep` argument.) It's the object-dtype `duplicated` case. It segfaults with or without passing `keep`: ``` import numpy as np from pandas._libs import hashtable as ht arr = np.arange(100).astype(object) ht.duplicated(arr) # <- segfault ht.duplicated(arr, "first") # <- segfault ht.duplicated(arr, keep="first") # <- segfault ``` The following Pandas-free example reproduces the bug: ``` ctypedef fused F: double int cpdef duplicated(F val, object keep="first"): if keep not in ('last', 'first', False): raise ValueError('keep must be either "first", "last" or False') ``` It's to do with default values on `cpdef` fused functions The commit at issue looks to be ee7ae0b9ce0dea51cf17adf119afe439917ee4c0 - I suspect it just needs a little special-casing for cpdef functions
2021-10-16T07:56:34Z
[]
[]
cython/cython
4,433
cython__cython-4433
[ "2529" ]
c69992aa4eb0f7b4529f776820d20b8c66486972
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -712,6 +712,12 @@ def analyse(self, return_type, env, nonempty=0, directive_locals=None, visibilit env.add_include_file('new') # for std::bad_alloc env.add_include_file('stdexcept') env.add_include_file('typeinfo') # for std::bad_cast + elif return_type.is_pyobject and self.exception_check: + # Functions in pure Python mode default to always check return values for exceptions + # (equivalent to the "except*" declaration). In this case, the exception clause + # is silently ignored for functions returning a Python object. + self.exception_check = False + if (return_type.is_pyobject and (self.exception_value or self.exception_check) and self.exception_check != '+'):
diff --git a/tests/errors/pure_errors.py b/tests/errors/pure_errors.py --- a/tests/errors/pure_errors.py +++ b/tests/errors/pure_errors.py @@ -50,8 +50,15 @@ def pyfunc(x): # invalid return x + 1 [email protected](-1) [email protected] +def test_cdef_return_object_broken(x: object) -> object: + return x + + _ERRORS = """ 44:22: Calling gil-requiring function not allowed without gil 45:24: Calling gil-requiring function not allowed without gil 48:0: Python functions cannot be declared 'nogil' +53:0: Exception clause not allowed for function returning Python object """ diff --git a/tests/run/pure_py3.py b/tests/run/pure_py3.py --- a/tests/run/pure_py3.py +++ b/tests/run/pure_py3.py @@ -85,3 +85,19 @@ def call_cdef_inline(x): """ ret = cdef_inline(x) return ret, cython.typeof(ret) + [email protected] +def test_cdef_return_object(x: object) -> object: + """ + Test support of python object in annotations + >>> test_cdef_return_object(3) + 3 + >>> test_cdef_return_object(None) + Traceback (most recent call last): + ... + RuntimeError + """ + if x: + return x + else: + raise RuntimeError()
(@cython.cfunc + Type Annotation) Fragility Going through some of pandas' cython modules to try to make code valid-python where possible, I'm seeing cythonize-time errors. It seems like some combinations are invalid for surprising reasons, e.g: ``` cpdef object get_rule_month(object source, object default='DEC') # existing, works as expected cpdef object get_rule_month(source: object, default: object='DEC'): # seems OK cpdef get_rule_month(source: object, default: object='DEC') -> object: # breaks --> Syntax error in C variable declaration @cython.ccall def get_rule_month(source: object, default: object='DEC') -> object: # breaks --> Exception clause not allowed for function returning Python object @cython.ccall def object get_rule_month(source: object, default: object='DEC'): # breaks --> Expected '(', found 'get_rule_month' @cython.ccall @cython.returns(object) def get_rule_month(source: object, default: object='DEC'): # appears OK ``` Another example with a slightly different set of errors: ``` cdef inline bint is_null_datetime64(v): # existing, OK cdef inline is_null_datetime64(v) -> bint: # breaks --> Syntax error in C variable declaration @cython.cfunc def inline is_null_datetime64(v) -> bint: # breaks --> Expected '(', found 'is_null_datetime64 @cython.cfunc @cython.inline def is_null_datetime64(v) -> bint: # breaks --> Function signature does not match previous declaration ``` This last one here is the one that is noticeably different from the first example. Is this behavior intentional?
Thanks for that list (and for trying it in the first place). It means we clearly lack tests here, and it's good to have real-world feedback about where people encounter real-world problems. Regarding the "obvious" cases: > `def inline func()` This can never work, because `def` requires Python syntax. Similarly, `cdef`/`cpdef` syntax cannot be combined with `->` return type annotations, which are a Python `def` function feature. While `cpdef` + Python syntax is a debatable edge case, I'd suggest that providing the return type like this should stay illegal for now. Either you use Python syntax (`def ... -> type`) or Cython syntax (`cpdef type ...`), not both. There are probably ways to give better error messages here (I created #2530 for that). There is an `@cython.inline` decorator, so the (currently) only correct way to use `inline` in Python code is ```cython @cython.cfunc @cython.inline def is_null_datetime64(v) -> bint: ``` There is a (similar) test for this in our test suite, so I don't know right now why this would fail. Probably something trivial. https://github.com/cython/cython/blob/0fb73f66696e52f6614305d0ad6d42521fd128b0/tests/run/pure_py3.py#L68-L70 Similarly, `cpdef` should be expressed like this: ```cython @cython.ccall def get_rule_month(source: object, default: object='DEC') -> object: ``` which also fails for you, as you said. I remember noticing this kind of error, too, and fixing something in that corner recently. Could you try the latest master on that? > There is a (similar) test for this in our test suite, so I don't know right now why this would fail. Probably something trivial. Possibly relevant: there is an accompanying .pxd file that was unchanged throughout all these iterations with "cdef bint is_null_datetime64(v)` > I remember noticing this kind of error, too, and fixing something in that corner recently. Could you try the latest master on that? Will do. I'll also add to the list permutations involving `nogil` and `except? -1` > Similarly, cdef/cpdef syntax cannot be combined with -> return type annotations, which are a Python def function feature. Good to know, thanks. My intuition was that the parser would translate each of the supported forms to a canonical representation, allowing users to mix and match (even though doing so would be really weird in some cases). Not the first time intuition has led me astray. (Can you point me towards the part of the code responsible for this? If it doesn't require learning the entire code-base, I'd be happy to help with fleshing out the tests) > While `cpdef` + Python syntax is a debatable edge case, I'd suggest that providing the return type like this should stay illegal for now. A use case I can imagine where this would be really convenient is linting (a large part of the motivation for trying this syntax in the first place). With `cp?def` + Python syntax, we can probably cobble together something to pass `re.sub('^cp?def ', 'def', source).replace('cimport', 'import')` and be most of the way towards having something we can pass to `flake8`. > there is an accompanying .pxd file that was unchanged throughout all these iterations with "cdef bint is_null_datetime64(v)` Ah, yes, I'd be surprised if that didn't make a difference. But if you have a `.pxd` file with the types in it, why do you still need to define them in the actual source file? > part of the code responsible for this There are different aspects to this. One is the `AdjustDefByDirectives` transform, which adapts Python declarations to overrides provided in an external `.pxd` file, in decorators, or in annotations. Other tasks are done directly by certain syntax tree nodes, e.g. declaring a variable on an expression like `x: int`. Look for `annotation_typing` in the `Cython.Compiler` package. Tests for this ended up in the pure Python mode tests (`pure_*.py`), in `cython3.pyx`, in `pep526_variable_annotations.py`, and in `annotation_typing.pyx`. The pure mode tests focus on anything cythonic that can run in Python, and the last one focusses on static typing with PEP 484. `.py` files are also tested in Python. > `re.sub('^cp?def ', 'def', source).replace('cimport', 'import')` For the first part, use `def` with decorators. For the second, there isn't currently a way to use `cimport` in Python syntax. The only use case I can see is sharing declarations, and for that, it's probably best to require `.pxd` files – in which case you can get pretty far with having your implementation in `.py` files and [override](http://docs.cython.org/en/latest/src/tutorial/pure.html#augmenting-pxd) the Python declarations with C data types/functions/classes in the corresponding `.pxd` file. > But if you have a .pxd file with the types in it, why do you still need to define them in the actual source file? Not sure how this status quo developed; presumably easier for contributors/reviewers if they match. >> re.sub('^cp?def ', 'def', source).replace('cimport', 'import') > > For the first part, use def with decorators. > > For the second, there isn't currently a way to use cimport in Python syntax. This runs into a "if it were up to me..." issue where its hard to predict what maintainers will or won't have a strong opinion about. Last time I tried to move to the decorator syntax the idea was shot down. It's totally reasonable if you want to declare that Not Cython's Problem. As for the `source.replace("cimport", "import")`, that's just a hack to trick a linter into think its valid python. Feel free to ignore. I'll install from master and update results in a bit. Installed from master, no apparent change: ``` cpdef get_rule_month(source: object, default: object='DEC') -> object: # still breaks --> Syntax error in C variable declaration @cython.ccall def get_rule_month(source: object, default: object='DEC') -> object: # still breaks --> Exception clause not allowed for function returning Python object cdef inline is_null_datetime64(v) -> bint: # still breaks --> Syntax error in C variable declaration @cython.cfunc def inline is_null_datetime64(v) -> bint: # still breaks --> Expected '(', found 'is_null_datetime64 @cython.cfunc @cython.inline def is_null_datetime64(v) -> bint: # still breaks --> Function signature does not match previous declaration ``` Some more cases, these _without_ an accompanying pxd file: ``` @cython.cfunc @cython.inline def median_linear(a: float64_t*, n: int) -> float64_t nogil: # breaks --> Expected an identifier or literal @cython.cfunc @cython.inline @cython.nogil def median_linear(a: float64_t*, n: int) -> float64_t: # breaks --> Expected an identifier or literal @cython.cfunc @cython.inline @cython.nogil def median_linear(a: cython.pointer(float64_t), n: int) -> float64_t: # breaks --> Invalid directive: 'nogil'. (+1 on the error message) ``` So it looks like there exists no valid way to use type annotations on this function. A weird thing a user might do is mix/match (here using type annotation only for the `labels` kwarg: ``` @cython.boundscheck(False) @cython.wraparound(False) def group_median_float64(ndarray[float64_t, ndim=2] out, ndarray[int64_t] counts, ndarray[float64_t, ndim=2] values, labels: ndarray[int64_t], Py_ssize_t min_count=-1): # breaks --> 'int64_t' is not a constant, variable or function identifier ``` Of course the `ndim=2` bit isn't valid python (we're in the process of converting these to `foo[:, :]`), so trying to put that in the new format: ``` @cython.boundscheck(False) @cython.wraparound(False) def group_median_float64(out ndarray[float64_t, ndim=2], counts: ndarray[int64_t], values: ndarray[float64_t, ndim=2], labels: ndarray[int64_t], min_count: Py_ssize_t=-1): # breaks --> Expected ']', found '=' ``` But even with the memoryview syntax it chokes: ``` @cython.boundscheck(False) @cython.wraparound(False) def group_cumsum(out: numeric[:, :], values: numeric[:, :], labels: int64_t[:], is_datetimelike, skipna: bint=True): # breaks --> Compiler crash in AnalyseDeclarationsTransform ``` Now one with an `except? -1` clause (some of these I now know will break, but listing them for thoroughness) ``` cdef inline get_datetime64_nanos(val: object) -> int64_t except? -1: # Syntax error in C variable declaration @cython.cfunc @cython.inline @cython.exceptval(-1) def get_datetime64_nanos(val: object) -> int64_t: # OK! Even with an accompanying pxd file cdef inline int64_t get_datetime64_nanos(val: object) except? -1: # OK @cython.inline cdef int64_t get_datetime64_nanos(val: object) except? -1: # OK @cython.exceptval(-1) cdef inline int64_t get_datetime64_nanos(val: object): # breaks --> Function signature does not match previous declaration @cython.exceptval(-1) @cython.inline cdef int64_t get_datetime64_nanos(val: object): # breaks --> Function signature does not match previous declaration @cython.inline @cython.cfunc def int64_t get_datetime64_nanos(val: object) except? -1: # breaks --> Expected '(', found 'get_datetime64_nanos' @cython.inline @cython.cfunc @cython.exceptval(-1) def int64_t get_datetime64_nanos(val: object): # breaks --> Expected '(', found 'get_datetime64_nanos' ``` Thanks for testing these. ``` cpdef get_rule_month(source: object, default: object='DEC') -> object: # still breaks --> Syntax error in C variable declaration @cython.cfunc def inline is_null_datetime64(v) -> bint: # still breaks --> Expected '(', found 'is_null_datetime64 ``` I improved the error message for these. ``` @cython.cfunc @cython.inline def is_null_datetime64(v) -> bint: # still breaks --> Function signature does not match previous declaration ``` **This is a bug and should work.** ``` @cython.cfunc def inline is_null_datetime64(v) -> bint: # still breaks --> Expected '(', found 'is_null_datetime64 @cython.cfunc @cython.inline def median_linear(a: float64_t*, n: int) -> float64_t nogil: # breaks --> Expected an identifier or literal ``` These are not valid Python syntax (note that you say `def`) and are correctly rejected. Using pointer types in Python syntax requires a typedef. Improving that error is difficult, because it would be perfectly ok to write `a: int * 5`, but `a: int*` is only … half of an expression. ``` @cython.cfunc @cython.inline @cython.nogil def median_linear(a: cython.pointer(float64_t), n: int) -> float64_t: # breaks --> Invalid directive: 'nogil'. (+1 on the error message) ``` **This is a missing feature.** I created #2557 for it. ``` @cython.boundscheck(False) @cython.wraparound(False) def group_cumsum(out: numeric[:, :], values: numeric[:, :], labels: int64_t[:], is_datetimelike, skipna: bint=True): # breaks --> Compiler crash in AnalyseDeclarationsTransform ``` **This is a bug and should work.** (fixed in 7bebbddd061fad77765cd77c6a9207b8bda17cc5) ``` @cython.inline @cython.cfunc def int64_t get_datetime64_nanos(val: object) except? -1: # breaks --> Expected '(', found 'get_datetime64_nanos' ``` I improved the error message for this one. I implemented support for memoryviews in type annotations. Thanks, I'll give this a try on master and report back. Trying out 0.29 ``` @cython.cfunc @cython.inline def is_null_datetimelike(val : object) -> bint: # breaks --> pandas/_libs/tslibs/nattype.pyx:627:0: Function signature does not match previous declaration ``` Tried changing this in the accompanying pxd to match ``` @cython.cfunc def is_null_datetimelike(val : object) -> bint # breaks --> pandas/_libs/tslibs/nattype.pxd:14:0: def statement not allowed here ``` I'm having the similar issues on cython V0.29 with return types in the .pyx file. Any python object return type breaks compilation in python compatible mode. Cython types work for returns (int, float, cython.int, cython.void, etc), np.ndarray and python builtins don't. ``` @cython.ccall def get_object() -> object: ... # -> Exception clause not allowed for function returning Python object ``` ``` @cython.cfunc def get_str() -> str: ... # -> Exception clause not allowed for function returning Python object ``` Also returning None gives a different error: ``` @cython.ccall def do_something_without_return() -> None: ... # -> Not a type ``` which makes it not compatible with typed python even with just builtin types. If returning None is redundant, can cython just ignore it? or alias it to a cython void / NULL? (Should this be a separate issue?) @Yobmod It looks like that there is a workaround for `-> object` case: If we add a decorator `@cython.exceptval(check=False)` it works fine. The generated code still checks the return value for exceptions. @Yobmod I'm encountering this too. Marking this as a blocker for 3.0 since we're aiming at making the pure Python mode generally usable in that version. It's mention in the [docs](https://cython.readthedocs.io/en/latest/src/tutorial/strings.html#accepting-strings-from-python-code) (or rather inspired by `to_unicode.pyx`), so: ```python @cython.cfunc def foo(s) -> unicode: return unicode(s) ``` doesn't work, while this does: ```cython cdef unicode foo(s): return unicode(s) ``` Also ```python def foo(s) -> unicode: return unicode(s) ``` compiles fine, and to the same code as `pyx`. The same goes with ```python @cython.cfunc def foo(s) -> str: return str(s) ``` --- All of that shouldn't be a new info, but rather additional use/test cases This also should serve as a reminder to come back to the documentation and correct everything when the issue will be fixed. OK all cases raising exception: `Exception clause not allowed for function returning Python object` are caused by annotating return type as python object: ```python @cython.ccall def get_rule_month(source: object, default: object='DEC') -> object: @cython.cfunc def foo(s) -> str: @cython.cfunc def foo(s) -> unicode: ``` etc... Exception is raised here: https://github.com/cython/cython/blob/09cbf492dfcf1ad022e79660d6aec0be3f444244/Cython/Compiler/Nodes.py#L715-L718 because `self.exception_check` is set to `True`. The root cause of it is following (`self.exception_check` is set to `True` based on second item in tuple): https://github.com/cython/cython/blob/09cbf492dfcf1ad022e79660d6aec0be3f444244/Cython/Compiler/ParseTreeTransforms.py#L2508-L2510 And basically it boils down to principle: 1. cython language defaults to no exception checking and hence is not affected by this bug 2. pure python defautls to exception checking and hence by default it causes this bug. I have pretty simple solution for this issue, PR will be created.
2021-10-29T20:10:07Z
[]
[]
cython/cython
4,436
cython__cython-4436
[ "4434" ]
c69992aa4eb0f7b4529f776820d20b8c66486972
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -1437,7 +1437,7 @@ def generate_typeobj_definitions(self, env, code): warning(scope.parent_type.pos, "total_ordering directive used, but no comparison and equality methods defined") - for slot in TypeSlots.PyNumberMethods: + for slot in TypeSlots.get_slot_table(code.globalstate.directives).PyNumberMethods: if slot.is_binop and scope.defines_any_special(slot.user_methods): self.generate_binop_function(scope, slot, code, entry.pos) @@ -1845,7 +1845,7 @@ def generate_traverse_function(self, scope, code, cclass_entry): code.putln("}") def generate_clear_function(self, scope, code, cclass_entry): - tp_slot = TypeSlots.get_slot_by_name("tp_clear") + tp_slot = TypeSlots.get_slot_by_name("tp_clear", scope.directives) slot_func = scope.mangle_internal("tp_clear") base_type = scope.parent_type.base_type if tp_slot.slot_code(scope) != slot_func: @@ -2225,10 +2225,10 @@ def generate_binop_function(self, scope, slot, code, pos): if preprocessor_guard: code.putln(preprocessor_guard) - if slot.left_slot.signature == TypeSlots.binaryfunc: + if slot.left_slot.signature in (TypeSlots.binaryfunc, TypeSlots.ibinaryfunc): slot_type = 'binaryfunc' extra_arg = extra_arg_decl = '' - elif slot.left_slot.signature == TypeSlots.ternaryfunc: + elif slot.left_slot.signature in (TypeSlots.ternaryfunc, TypeSlots.iternaryfunc): slot_type = 'ternaryfunc' extra_arg = ', extra_arg' extra_arg_decl = ', PyObject* extra_arg' @@ -2519,17 +2519,17 @@ def generate_typeobj_spec(self, entry, code): ext_type = entry.type scope = ext_type.scope - members_slot = TypeSlots.get_slot_by_name("tp_members") + members_slot = TypeSlots.get_slot_by_name("tp_members", code.globalstate.directives) members_slot.generate_substructure_spec(scope, code) - buffer_slot = TypeSlots.get_slot_by_name("tp_as_buffer") + buffer_slot = TypeSlots.get_slot_by_name("tp_as_buffer", code.globalstate.directives) if not buffer_slot.is_empty(scope): code.putln("#if !CYTHON_COMPILING_IN_LIMITED_API") buffer_slot.generate_substructure(scope, code) code.putln("#endif") code.putln("static PyType_Slot %s_slots[] = {" % ext_type.typeobj_cname) - for slot in TypeSlots.slot_table: + for slot in TypeSlots.get_slot_table(code.globalstate.directives): slot.generate_spec(scope, code) code.putln("{0, 0},") code.putln("};") @@ -2543,14 +2543,14 @@ def generate_typeobj_spec(self, entry, code): code.putln('"%s.%s",' % (self.full_module_name, classname.replace('"', ''))) code.putln("sizeof(%s)," % objstruct) code.putln("0,") - code.putln("%s," % TypeSlots.get_slot_by_name("tp_flags").slot_code(scope)) + code.putln("%s," % TypeSlots.get_slot_by_name("tp_flags", scope.directives).slot_code(scope)) code.putln("%s_slots," % ext_type.typeobj_cname) code.putln("};") def generate_typeobj_definition(self, modname, entry, code): type = entry.type scope = type.scope - for suite in TypeSlots.substructures: + for suite in TypeSlots.get_slot_table(code.globalstate.directives).substructures: suite.generate_substructure(scope, code) code.putln("") if entry.visibility == 'public': @@ -2574,7 +2574,7 @@ def generate_typeobj_definition(self, modname, entry, code): "sizeof(%s), /*tp_basicsize*/" % objstruct) code.putln( "0, /*tp_itemsize*/") - for slot in TypeSlots.slot_table: + for slot in TypeSlots.get_slot_table(code.globalstate.directives): slot.generate(scope, code) code.putln( "};") diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -2417,7 +2417,7 @@ def get_preprocessor_guard(self): if not self.entry.is_special: return None name = self.entry.name - slot = TypeSlots.method_name_to_slot.get(name) + slot = TypeSlots.get_slot_table(self.local_scope.directives).get_slot_by_method_name(name) if not slot: return None if name == '__long__' and not self.entry.scope.lookup_here('__int__'): @@ -5335,7 +5335,7 @@ def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ UtilityCode.load_cached('ValidateBasesTuple', 'ExtensionTypes.c')) code.put_error_if_neg(entry.pos, "__Pyx_validate_bases_tuple(%s.name, %s, %s)" % ( typespec_cname, - TypeSlots.get_slot_by_name("tp_dictoffset").slot_code(scope), + TypeSlots.get_slot_by_name("tp_dictoffset", scope.directives).slot_code(scope), bases_tuple_cname or tuple_temp, )) @@ -5359,7 +5359,7 @@ def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ )) # The buffer interface is not currently supported by PyType_FromSpec(). - buffer_slot = TypeSlots.get_slot_by_name("tp_as_buffer") + buffer_slot = TypeSlots.get_slot_by_name("tp_as_buffer", code.globalstate.directives) if not buffer_slot.is_empty(scope): code.putln("#if !CYTHON_COMPILING_IN_LIMITED_API") code.putln("%s->%s = %s;" % ( @@ -5369,7 +5369,8 @@ def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ )) # Still need to inherit buffer methods since PyType_Ready() didn't do it for us. for buffer_method_name in ("__getbuffer__", "__releasebuffer__"): - buffer_slot = TypeSlots.get_slot_by_method_name(buffer_method_name) + buffer_slot = TypeSlots.get_slot_table( + code.globalstate.directives).get_slot_by_method_name(buffer_method_name) if buffer_slot.slot_code(scope) == "0" and not TypeSlots.get_base_slot_function(scope, buffer_slot): code.putln("if (!%s->tp_as_buffer->%s &&" " %s->tp_base->tp_as_buffer &&" @@ -5405,7 +5406,7 @@ def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ code.putln("#if !CYTHON_COMPILING_IN_LIMITED_API") # FIXME: these still need to get initialised even with the limited-API - for slot in TypeSlots.slot_table: + for slot in TypeSlots.get_slot_table(code.globalstate.directives): slot.generate_dynamic_init_code(scope, code) code.putln("#endif") @@ -5450,7 +5451,8 @@ def generate_type_ready_code(entry, code, bases_tuple_cname=None, check_heap_typ is_buffer = func.name in ('__getbuffer__', '__releasebuffer__') if (func.is_special and Options.docstrings and func.wrapperbase_cname and not is_buffer): - slot = TypeSlots.method_name_to_slot.get(func.name) + slot = TypeSlots.get_slot_table( + entry.type.scope.directives).get_slot_by_method_name(func.name) preprocessor_guard = slot.preprocessor_guard_code() if slot else None if preprocessor_guard: code.putln(preprocessor_guard) diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -20,7 +20,7 @@ from .PyrexTypes import py_object_type, unspecified_type from .TypeSlots import ( pyfunction_signature, pymethod_signature, richcmp_special_methods, - get_special_method_signature, get_property_accessor_signature) + get_slot_table, get_property_accessor_signature) from . import Future from . import Code @@ -2240,7 +2240,8 @@ def declare_var(self, name, type, pos, error(pos, "C attributes cannot be added in implementation part of" " extension type defined in a pxd") - if not self.is_closure_class_scope and get_special_method_signature(name): + if (not self.is_closure_class_scope and + get_slot_table(self.directives).get_special_method_signature(name)): error(pos, "The name '%s' is reserved for a special method." % name) @@ -2312,7 +2313,7 @@ def declare_pyfunction(self, name, pos, allow_redefine=False): "in a future version of Pyrex and Cython. Use __cinit__ instead.") entry = self.declare_var(name, py_object_type, pos, visibility='extern') - special_sig = get_special_method_signature(name) + special_sig = get_slot_table(self.directives).get_special_method_signature(name) if special_sig: # Special methods get put in the method table with a particular # signature declared in advance. @@ -2344,7 +2345,8 @@ def declare_cfunction(self, name, type, pos, cname=None, visibility='private', api=0, in_pxd=0, defining=0, modifiers=(), utility_code=None, overridable=False): name = self.mangle_class_private_name(name) - if get_special_method_signature(name) and not self.parent_type.is_builtin_type: + if (get_slot_table(self.directives).get_special_method_signature(name) + and not self.parent_type.is_builtin_type): error(pos, "Special methods must be declared with 'def', not 'cdef'") args = type.args if not type.is_static_method: diff --git a/Cython/Compiler/TypeSlots.py b/Cython/Compiler/TypeSlots.py --- a/Cython/Compiler/TypeSlots.py +++ b/Cython/Compiler/TypeSlots.py @@ -354,8 +354,8 @@ class MethodSlot(SlotDescriptor): # method_name string The __xxx__ name of the method # alternatives [string] Alternative list of __xxx__ names for the method - def __init__(self, signature, slot_name, method_name, fallback=None, - py3=True, py2=True, ifdef=None, inherited=True): + def __init__(self, signature, slot_name, method_name, method_name_to_slot, + fallback=None, py3=True, py2=True, ifdef=None, inherited=True): SlotDescriptor.__init__(self, slot_name, py3=py3, py2=py2, ifdef=ifdef, inherited=inherited) self.signature = signature @@ -509,14 +509,14 @@ def spec_value(self, scope): class BinopSlot(SyntheticSlot): - def __init__(self, signature, slot_name, left_method, **kargs): + def __init__(self, signature, slot_name, left_method, method_name_to_slot, **kargs): assert left_method.startswith('__') right_method = '__r' + left_method[2:] SyntheticSlot.__init__( self, slot_name, [left_method, right_method], "0", is_binop=True, **kargs) # MethodSlot causes special method registration. - self.left_slot = MethodSlot(signature, "", left_method, **kargs) - self.right_slot = MethodSlot(signature, "", right_method, **kargs) + self.left_slot = MethodSlot(signature, "", left_method, method_name_to_slot, **kargs) + self.right_slot = MethodSlot(signature, "", right_method, method_name_to_slot, **kargs) class RichcmpSlot(MethodSlot): @@ -570,7 +570,7 @@ class SuiteSlot(SlotDescriptor): # # sub_slots [SlotDescriptor] - def __init__(self, sub_slots, slot_type, slot_name, ifdef=None): + def __init__(self, sub_slots, slot_type, slot_name, substructures, ifdef=None): SlotDescriptor.__init__(self, slot_name, ifdef=ifdef) self.sub_slots = sub_slots self.slot_type = slot_type @@ -612,8 +612,6 @@ def generate_spec(self, scope, code): for slot in self.sub_slots: slot.generate_spec(scope, code) -substructures = [] # List of all SuiteSlot instances - class MethodTableSlot(SlotDescriptor): # Slot descriptor for the method table. @@ -633,7 +631,7 @@ def slot_code(self, scope): def get_member_specs(self, scope): return [ - get_slot_by_name("tp_dictoffset").members_slot_value(scope), + get_slot_by_name("tp_dictoffset", scope.directives).members_slot_value(scope), #get_slot_by_name("tp_weaklistoffset").spec_value(scope), ] @@ -717,12 +715,6 @@ def members_slot_value(self, scope): return None return '{"__dictoffset__", T_PYSSIZET, %s, READONLY, NULL},' % dict_offset - - -# The following dictionary maps __xxx__ method names to slot descriptors. - -method_name_to_slot = {} - ## The following slots are (or could be) initialised with an ## extern function pointer. # @@ -736,17 +728,6 @@ def members_slot_value(self, scope): # #------------------------------------------------------------------------------------------ -def get_special_method_signature(name): - # Given a method name, if it is a special method, - # return its signature, else return None. - slot = method_name_to_slot.get(name) - if slot: - return slot.signature - elif name in richcmp_special_methods: - return ibinaryfunc - else: - return None - def get_property_accessor_signature(name): # Return signature of accessor for an extension type @@ -780,21 +761,16 @@ def get_slot_function(scope, slot): return None -def get_slot_by_name(slot_name): +def get_slot_by_name(slot_name, compiler_directives): # For now, only search the type struct, no referenced sub-structs. - for slot in slot_table: + for slot in get_slot_table(compiler_directives).slot_table: if slot.slot_name == slot_name: return slot assert False, "Slot not found: %s" % slot_name -def get_slot_by_method_name(method_name): - # For now, only search the type struct, no referenced sub-structs. - return method_name_to_slot[method_name] - - def get_slot_code_by_name(scope, slot_name): - slot = get_slot_by_name(slot_name) + slot = get_slot_by_name(slot_name, scope.directives) return slot.slot_code(scope) @@ -890,203 +866,268 @@ def get_slot_code_by_name(scope, slot_name): '__del__': Signature("T", 'r') } -#------------------------------------------------------------------------------------------ -# -# Descriptor tables for the slots of the various type object -# substructures, in the order they appear in the structure. -# -#------------------------------------------------------------------------------------------ PyNumberMethods_Py2only_GUARD = "PY_MAJOR_VERSION < 3 || (CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03050000)" -PyNumberMethods = ( - BinopSlot(binaryfunc, "nb_add", "__add__"), - BinopSlot(binaryfunc, "nb_subtract", "__sub__"), - BinopSlot(binaryfunc, "nb_multiply", "__mul__"), - BinopSlot(binaryfunc, "nb_divide", "__div__", ifdef = PyNumberMethods_Py2only_GUARD), - BinopSlot(binaryfunc, "nb_remainder", "__mod__"), - BinopSlot(binaryfunc, "nb_divmod", "__divmod__"), - BinopSlot(ternaryfunc, "nb_power", "__pow__"), - MethodSlot(unaryfunc, "nb_negative", "__neg__"), - MethodSlot(unaryfunc, "nb_positive", "__pos__"), - MethodSlot(unaryfunc, "nb_absolute", "__abs__"), - MethodSlot(inquiry, "nb_bool", "__bool__", py2 = ("nb_nonzero", "__nonzero__")), - MethodSlot(unaryfunc, "nb_invert", "__invert__"), - BinopSlot(binaryfunc, "nb_lshift", "__lshift__"), - BinopSlot(binaryfunc, "nb_rshift", "__rshift__"), - BinopSlot(binaryfunc, "nb_and", "__and__"), - BinopSlot(binaryfunc, "nb_xor", "__xor__"), - BinopSlot(binaryfunc, "nb_or", "__or__"), - EmptySlot("nb_coerce", ifdef = PyNumberMethods_Py2only_GUARD), - MethodSlot(unaryfunc, "nb_int", "__int__", fallback="__long__"), - MethodSlot(unaryfunc, "nb_long", "__long__", fallback="__int__", py3 = "<RESERVED>"), - MethodSlot(unaryfunc, "nb_float", "__float__"), - MethodSlot(unaryfunc, "nb_oct", "__oct__", ifdef = PyNumberMethods_Py2only_GUARD), - MethodSlot(unaryfunc, "nb_hex", "__hex__", ifdef = PyNumberMethods_Py2only_GUARD), - - # Added in release 2.0 - MethodSlot(ibinaryfunc, "nb_inplace_add", "__iadd__"), - MethodSlot(ibinaryfunc, "nb_inplace_subtract", "__isub__"), - MethodSlot(ibinaryfunc, "nb_inplace_multiply", "__imul__"), - MethodSlot(ibinaryfunc, "nb_inplace_divide", "__idiv__", ifdef = PyNumberMethods_Py2only_GUARD), - MethodSlot(ibinaryfunc, "nb_inplace_remainder", "__imod__"), - MethodSlot(ibinaryfunc, "nb_inplace_power", "__ipow__"), # actually ternaryfunc!!! - MethodSlot(ibinaryfunc, "nb_inplace_lshift", "__ilshift__"), - MethodSlot(ibinaryfunc, "nb_inplace_rshift", "__irshift__"), - MethodSlot(ibinaryfunc, "nb_inplace_and", "__iand__"), - MethodSlot(ibinaryfunc, "nb_inplace_xor", "__ixor__"), - MethodSlot(ibinaryfunc, "nb_inplace_or", "__ior__"), - - # Added in release 2.2 - # The following require the Py_TPFLAGS_HAVE_CLASS flag - BinopSlot(binaryfunc, "nb_floor_divide", "__floordiv__"), - BinopSlot(binaryfunc, "nb_true_divide", "__truediv__"), - MethodSlot(ibinaryfunc, "nb_inplace_floor_divide", "__ifloordiv__"), - MethodSlot(ibinaryfunc, "nb_inplace_true_divide", "__itruediv__"), - - # Added in release 2.5 - MethodSlot(unaryfunc, "nb_index", "__index__"), - - # Added in release 3.5 - BinopSlot(binaryfunc, "nb_matrix_multiply", "__matmul__", ifdef="PY_VERSION_HEX >= 0x03050000"), - MethodSlot(ibinaryfunc, "nb_inplace_matrix_multiply", "__imatmul__", ifdef="PY_VERSION_HEX >= 0x03050000"), -) - -PySequenceMethods = ( - MethodSlot(lenfunc, "sq_length", "__len__"), - EmptySlot("sq_concat"), # nb_add used instead - EmptySlot("sq_repeat"), # nb_multiply used instead - SyntheticSlot("sq_item", ["__getitem__"], "0"), #EmptySlot("sq_item"), # mp_subscript used instead - MethodSlot(ssizessizeargfunc, "sq_slice", "__getslice__"), - EmptySlot("sq_ass_item"), # mp_ass_subscript used instead - SyntheticSlot("sq_ass_slice", ["__setslice__", "__delslice__"], "0"), - MethodSlot(cmpfunc, "sq_contains", "__contains__"), - EmptySlot("sq_inplace_concat"), # nb_inplace_add used instead - EmptySlot("sq_inplace_repeat"), # nb_inplace_multiply used instead -) - -PyMappingMethods = ( - MethodSlot(lenfunc, "mp_length", "__len__"), - MethodSlot(objargfunc, "mp_subscript", "__getitem__"), - SyntheticSlot("mp_ass_subscript", ["__setitem__", "__delitem__"], "0"), -) - -PyBufferProcs = ( - MethodSlot(readbufferproc, "bf_getreadbuffer", "__getreadbuffer__", py3 = False), - MethodSlot(writebufferproc, "bf_getwritebuffer", "__getwritebuffer__", py3 = False), - MethodSlot(segcountproc, "bf_getsegcount", "__getsegcount__", py3 = False), - MethodSlot(charbufferproc, "bf_getcharbuffer", "__getcharbuffer__", py3 = False), - - MethodSlot(getbufferproc, "bf_getbuffer", "__getbuffer__"), - MethodSlot(releasebufferproc, "bf_releasebuffer", "__releasebuffer__") -) - -PyAsyncMethods = ( - MethodSlot(unaryfunc, "am_await", "__await__"), - MethodSlot(unaryfunc, "am_aiter", "__aiter__"), - MethodSlot(unaryfunc, "am_anext", "__anext__"), -) - #------------------------------------------------------------------------------------------ # # The main slot table. This table contains descriptors for all the # top-level type slots, beginning with tp_dealloc, in the order they # appear in the type object. # +# It depends on some compiler directives (currently c_api_binop_methods), so the +# slot tables for each set of compiler directives are generated lazily and put in +# the _slot_table_dict +# #------------------------------------------------------------------------------------------ -slot_table = ( - ConstructorSlot("tp_dealloc", '__dealloc__'), - EmptySlot("tp_print", ifdef="PY_VERSION_HEX < 0x030800b4"), - EmptySlot("tp_vectorcall_offset", ifdef="PY_VERSION_HEX >= 0x030800b4"), - EmptySlot("tp_getattr"), - EmptySlot("tp_setattr"), - - # tp_compare (Py2) / tp_reserved (Py3<3.5) / tp_as_async (Py3.5+) is always used as tp_as_async in Py3 - MethodSlot(cmpfunc, "tp_compare", "__cmp__", ifdef="PY_MAJOR_VERSION < 3"), - SuiteSlot(PyAsyncMethods, "__Pyx_PyAsyncMethodsStruct", "tp_as_async", ifdef="PY_MAJOR_VERSION >= 3"), - - MethodSlot(reprfunc, "tp_repr", "__repr__"), - - SuiteSlot(PyNumberMethods, "PyNumberMethods", "tp_as_number"), - SuiteSlot(PySequenceMethods, "PySequenceMethods", "tp_as_sequence"), - SuiteSlot(PyMappingMethods, "PyMappingMethods", "tp_as_mapping"), - - MethodSlot(hashfunc, "tp_hash", "__hash__", inherited=False), # Py3 checks for __richcmp__ - MethodSlot(callfunc, "tp_call", "__call__"), - MethodSlot(reprfunc, "tp_str", "__str__"), - - SyntheticSlot("tp_getattro", ["__getattr__","__getattribute__"], "0"), #"PyObject_GenericGetAttr"), - SyntheticSlot("tp_setattro", ["__setattr__", "__delattr__"], "0"), #"PyObject_GenericSetAttr"), - - SuiteSlot(PyBufferProcs, "PyBufferProcs", "tp_as_buffer"), - - TypeFlagsSlot("tp_flags"), - DocStringSlot("tp_doc"), - - GCDependentSlot("tp_traverse"), - GCClearReferencesSlot("tp_clear"), - - RichcmpSlot(richcmpfunc, "tp_richcompare", "__richcmp__", inherited=False), # Py3 checks for __hash__ - - EmptySlot("tp_weaklistoffset"), - - MethodSlot(getiterfunc, "tp_iter", "__iter__"), - MethodSlot(iternextfunc, "tp_iternext", "__next__"), +class SlotTable(object): + def __init__(self, old_binops): + # The following dictionary maps __xxx__ method names to slot descriptors. + method_name_to_slot = {} + self._get_slot_by_method_name = method_name_to_slot.get + self.substructures = [] # List of all SuiteSlot instances + + bf = binaryfunc if old_binops else ibinaryfunc + tf = ternaryfunc if old_binops else iternaryfunc + + # Descriptor tables for the slots of the various type object + # substructures, in the order they appear in the structure. + self.PyNumberMethods = ( + BinopSlot(bf, "nb_add", "__add__", method_name_to_slot), + BinopSlot(bf, "nb_subtract", "__sub__", method_name_to_slot), + BinopSlot(bf, "nb_multiply", "__mul__", method_name_to_slot), + BinopSlot(bf, "nb_divide", "__div__", method_name_to_slot, + ifdef = PyNumberMethods_Py2only_GUARD), + BinopSlot(bf, "nb_remainder", "__mod__", method_name_to_slot), + BinopSlot(bf, "nb_divmod", "__divmod__", method_name_to_slot), + BinopSlot(tf, "nb_power", "__pow__", method_name_to_slot), + MethodSlot(unaryfunc, "nb_negative", "__neg__", method_name_to_slot), + MethodSlot(unaryfunc, "nb_positive", "__pos__", method_name_to_slot), + MethodSlot(unaryfunc, "nb_absolute", "__abs__", method_name_to_slot), + MethodSlot(inquiry, "nb_bool", "__bool__", method_name_to_slot, + py2 = ("nb_nonzero", "__nonzero__")), + MethodSlot(unaryfunc, "nb_invert", "__invert__", method_name_to_slot), + BinopSlot(bf, "nb_lshift", "__lshift__", method_name_to_slot), + BinopSlot(bf, "nb_rshift", "__rshift__", method_name_to_slot), + BinopSlot(bf, "nb_and", "__and__", method_name_to_slot), + BinopSlot(bf, "nb_xor", "__xor__", method_name_to_slot), + BinopSlot(bf, "nb_or", "__or__", method_name_to_slot), + EmptySlot("nb_coerce", ifdef = PyNumberMethods_Py2only_GUARD), + MethodSlot(unaryfunc, "nb_int", "__int__", method_name_to_slot, fallback="__long__"), + MethodSlot(unaryfunc, "nb_long", "__long__", method_name_to_slot, + fallback="__int__", py3 = "<RESERVED>"), + MethodSlot(unaryfunc, "nb_float", "__float__", method_name_to_slot), + MethodSlot(unaryfunc, "nb_oct", "__oct__", method_name_to_slot, + ifdef = PyNumberMethods_Py2only_GUARD), + MethodSlot(unaryfunc, "nb_hex", "__hex__", method_name_to_slot, + ifdef = PyNumberMethods_Py2only_GUARD), + + # Added in release 2.0 + MethodSlot(ibinaryfunc, "nb_inplace_add", "__iadd__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_subtract", "__isub__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_multiply", "__imul__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_divide", "__idiv__", method_name_to_slot, + ifdef = PyNumberMethods_Py2only_GUARD), + MethodSlot(ibinaryfunc, "nb_inplace_remainder", "__imod__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_power", "__ipow__", + method_name_to_slot), # actually ternaryfunc!!! + MethodSlot(ibinaryfunc, "nb_inplace_lshift", "__ilshift__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_rshift", "__irshift__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_and", "__iand__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_xor", "__ixor__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_or", "__ior__", method_name_to_slot), + + # Added in release 2.2 + # The following require the Py_TPFLAGS_HAVE_CLASS flag + BinopSlot(binaryfunc, "nb_floor_divide", "__floordiv__", method_name_to_slot), + BinopSlot(binaryfunc, "nb_true_divide", "__truediv__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_floor_divide", "__ifloordiv__", method_name_to_slot), + MethodSlot(ibinaryfunc, "nb_inplace_true_divide", "__itruediv__", method_name_to_slot), + + # Added in release 2.5 + MethodSlot(unaryfunc, "nb_index", "__index__", method_name_to_slot), + + # Added in release 3.5 + BinopSlot(binaryfunc, "nb_matrix_multiply", "__matmul__", method_name_to_slot, + ifdef="PY_VERSION_HEX >= 0x03050000"), + MethodSlot(ibinaryfunc, "nb_inplace_matrix_multiply", "__imatmul__", method_name_to_slot, + ifdef="PY_VERSION_HEX >= 0x03050000"), + ) + + self.PySequenceMethods = ( + MethodSlot(lenfunc, "sq_length", "__len__", method_name_to_slot), + EmptySlot("sq_concat"), # nb_add used instead + EmptySlot("sq_repeat"), # nb_multiply used instead + SyntheticSlot("sq_item", ["__getitem__"], "0"), #EmptySlot("sq_item"), # mp_subscript used instead + MethodSlot(ssizessizeargfunc, "sq_slice", "__getslice__", method_name_to_slot), + EmptySlot("sq_ass_item"), # mp_ass_subscript used instead + SyntheticSlot("sq_ass_slice", ["__setslice__", "__delslice__"], "0"), + MethodSlot(cmpfunc, "sq_contains", "__contains__", method_name_to_slot), + EmptySlot("sq_inplace_concat"), # nb_inplace_add used instead + EmptySlot("sq_inplace_repeat"), # nb_inplace_multiply used instead + ) + + self.PyMappingMethods = ( + MethodSlot(lenfunc, "mp_length", "__len__", method_name_to_slot), + MethodSlot(objargfunc, "mp_subscript", "__getitem__", method_name_to_slot), + SyntheticSlot("mp_ass_subscript", ["__setitem__", "__delitem__"], "0"), + ) + + self.PyBufferProcs = ( + MethodSlot(readbufferproc, "bf_getreadbuffer", "__getreadbuffer__", method_name_to_slot, + py3 = False), + MethodSlot(writebufferproc, "bf_getwritebuffer", "__getwritebuffer__", method_name_to_slot, + py3 = False), + MethodSlot(segcountproc, "bf_getsegcount", "__getsegcount__", method_name_to_slot, + py3 = False), + MethodSlot(charbufferproc, "bf_getcharbuffer", "__getcharbuffer__", method_name_to_slot, + py3 = False), + + MethodSlot(getbufferproc, "bf_getbuffer", "__getbuffer__", method_name_to_slot), + MethodSlot(releasebufferproc, "bf_releasebuffer", "__releasebuffer__", method_name_to_slot) + ) + + self.PyAsyncMethods = ( + MethodSlot(unaryfunc, "am_await", "__await__", method_name_to_slot), + MethodSlot(unaryfunc, "am_aiter", "__aiter__", method_name_to_slot), + MethodSlot(unaryfunc, "am_anext", "__anext__", method_name_to_slot), + ) + + self.slot_table = ( + ConstructorSlot("tp_dealloc", '__dealloc__'), + EmptySlot("tp_print", ifdef="PY_VERSION_HEX < 0x030800b4"), + EmptySlot("tp_vectorcall_offset", ifdef="PY_VERSION_HEX >= 0x030800b4"), + EmptySlot("tp_getattr"), + EmptySlot("tp_setattr"), + + # tp_compare (Py2) / tp_reserved (Py3<3.5) / tp_as_async (Py3.5+) is always used as tp_as_async in Py3 + MethodSlot(cmpfunc, "tp_compare", "__cmp__", method_name_to_slot, ifdef="PY_MAJOR_VERSION < 3"), + SuiteSlot(self. PyAsyncMethods, "__Pyx_PyAsyncMethodsStruct", "tp_as_async", + self.substructures, ifdef="PY_MAJOR_VERSION >= 3"), + + MethodSlot(reprfunc, "tp_repr", "__repr__", method_name_to_slot), + + SuiteSlot(self.PyNumberMethods, "PyNumberMethods", "tp_as_number", self.substructures), + SuiteSlot(self.PySequenceMethods, "PySequenceMethods", "tp_as_sequence", self.substructures), + SuiteSlot(self.PyMappingMethods, "PyMappingMethods", "tp_as_mapping", self.substructures), + + MethodSlot(hashfunc, "tp_hash", "__hash__", method_name_to_slot, + inherited=False), # Py3 checks for __richcmp__ + MethodSlot(callfunc, "tp_call", "__call__", method_name_to_slot), + MethodSlot(reprfunc, "tp_str", "__str__", method_name_to_slot), + + SyntheticSlot("tp_getattro", ["__getattr__","__getattribute__"], "0"), #"PyObject_GenericGetAttr"), + SyntheticSlot("tp_setattro", ["__setattr__", "__delattr__"], "0"), #"PyObject_GenericSetAttr"), + + SuiteSlot(self.PyBufferProcs, "PyBufferProcs", "tp_as_buffer", self.substructures), + + TypeFlagsSlot("tp_flags"), + DocStringSlot("tp_doc"), + + GCDependentSlot("tp_traverse"), + GCClearReferencesSlot("tp_clear"), + + RichcmpSlot(richcmpfunc, "tp_richcompare", "__richcmp__", method_name_to_slot, + inherited=False), # Py3 checks for __hash__ + + EmptySlot("tp_weaklistoffset"), + + MethodSlot(getiterfunc, "tp_iter", "__iter__", method_name_to_slot), + MethodSlot(iternextfunc, "tp_iternext", "__next__", method_name_to_slot), + + MethodTableSlot("tp_methods"), + MemberTableSlot("tp_members"), + GetSetSlot("tp_getset"), + + BaseClassSlot("tp_base"), #EmptySlot("tp_base"), + EmptySlot("tp_dict"), + + SyntheticSlot("tp_descr_get", ["__get__"], "0"), + SyntheticSlot("tp_descr_set", ["__set__", "__delete__"], "0"), + + DictOffsetSlot("tp_dictoffset", ifdef="!CYTHON_USE_TYPE_SPECS"), # otherwise set via "__dictoffset__" member + + MethodSlot(initproc, "tp_init", "__init__", method_name_to_slot), + EmptySlot("tp_alloc"), #FixedSlot("tp_alloc", "PyType_GenericAlloc"), + ConstructorSlot("tp_new", "__cinit__"), + EmptySlot("tp_free"), + + EmptySlot("tp_is_gc"), + EmptySlot("tp_bases"), + EmptySlot("tp_mro"), + EmptySlot("tp_cache"), + EmptySlot("tp_subclasses"), + EmptySlot("tp_weaklist"), + EmptySlot("tp_del"), + EmptySlot("tp_version_tag"), + EmptySlot("tp_finalize", ifdef="PY_VERSION_HEX >= 0x030400a1"), + EmptySlot("tp_vectorcall", ifdef="PY_VERSION_HEX >= 0x030800b1"), + EmptySlot("tp_print", ifdef="PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000"), + # PyPy specific extension - only here to avoid C compiler warnings. + EmptySlot("tp_pypy_flags", ifdef="CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM+0 >= 0x06000000"), + ) + + #------------------------------------------------------------------------------------------ + # + # Descriptors for special methods which don't appear directly + # in the type object or its substructures. These methods are + # called from slot functions synthesized by Cython. + # + #------------------------------------------------------------------------------------------ + + MethodSlot(initproc, "", "__cinit__", method_name_to_slot) + MethodSlot(destructor, "", "__dealloc__", method_name_to_slot) + MethodSlot(objobjargproc, "", "__setitem__", method_name_to_slot) + MethodSlot(objargproc, "", "__delitem__", method_name_to_slot) + MethodSlot(ssizessizeobjargproc, "", "__setslice__", method_name_to_slot) + MethodSlot(ssizessizeargproc, "", "__delslice__", method_name_to_slot) + MethodSlot(getattrofunc, "", "__getattr__", method_name_to_slot) + MethodSlot(getattrofunc, "", "__getattribute__", method_name_to_slot) + MethodSlot(setattrofunc, "", "__setattr__", method_name_to_slot) + MethodSlot(delattrofunc, "", "__delattr__", method_name_to_slot) + MethodSlot(descrgetfunc, "", "__get__", method_name_to_slot) + MethodSlot(descrsetfunc, "", "__set__", method_name_to_slot) + MethodSlot(descrdelfunc, "", "__delete__", method_name_to_slot) + + def get_special_method_signature(self, name): + # Given a method name, if it is a special method, + # return its signature, else return None. + slot = self._get_slot_by_method_name(name) + if slot: + return slot.signature + elif name in richcmp_special_methods: + return ibinaryfunc + else: + return None - MethodTableSlot("tp_methods"), - MemberTableSlot("tp_members"), - GetSetSlot("tp_getset"), + def get_slot_by_method_name(self, method_name): + # For now, only search the type struct, no referenced sub-structs. + return self._get_slot_by_method_name(method_name) - BaseClassSlot("tp_base"), #EmptySlot("tp_base"), - EmptySlot("tp_dict"), + def __iter__(self): + # make it easier to iterate over all the slots + return iter(self.slot_table) - SyntheticSlot("tp_descr_get", ["__get__"], "0"), - SyntheticSlot("tp_descr_set", ["__set__", "__delete__"], "0"), - DictOffsetSlot("tp_dictoffset", ifdef="!CYTHON_USE_TYPE_SPECS"), # otherwise set via "__dictoffset__" member +_slot_table_dict = {} - MethodSlot(initproc, "tp_init", "__init__"), - EmptySlot("tp_alloc"), #FixedSlot("tp_alloc", "PyType_GenericAlloc"), - ConstructorSlot("tp_new", "__cinit__"), - EmptySlot("tp_free"), +def get_slot_table(compiler_directives): + if not compiler_directives: + # fetch default directives here since the builtin type classes don't have + # directives set + from .Options import get_directive_defaults + compiler_directives = get_directive_defaults() - EmptySlot("tp_is_gc"), - EmptySlot("tp_bases"), - EmptySlot("tp_mro"), - EmptySlot("tp_cache"), - EmptySlot("tp_subclasses"), - EmptySlot("tp_weaklist"), - EmptySlot("tp_del"), - EmptySlot("tp_version_tag"), - EmptySlot("tp_finalize", ifdef="PY_VERSION_HEX >= 0x030400a1"), - EmptySlot("tp_vectorcall", ifdef="PY_VERSION_HEX >= 0x030800b1"), - EmptySlot("tp_print", ifdef="PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000"), - # PyPy specific extension - only here to avoid C compiler warnings. - EmptySlot("tp_pypy_flags", ifdef="CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM+0 >= 0x06000000"), -) + old_binops = compiler_directives['c_api_binop_methods'] + key = (old_binops,) + if key not in _slot_table_dict: + _slot_table_dict[key] = SlotTable(old_binops=old_binops) + return _slot_table_dict[key] -#------------------------------------------------------------------------------------------ -# -# Descriptors for special methods which don't appear directly -# in the type object or its substructures. These methods are -# called from slot functions synthesized by Cython. -# -#------------------------------------------------------------------------------------------ -MethodSlot(initproc, "", "__cinit__") -MethodSlot(destructor, "", "__dealloc__") -MethodSlot(objobjargproc, "", "__setitem__") -MethodSlot(objargproc, "", "__delitem__") -MethodSlot(ssizessizeobjargproc, "", "__setslice__") -MethodSlot(ssizessizeargproc, "", "__delslice__") -MethodSlot(getattrofunc, "", "__getattr__") -MethodSlot(getattrofunc, "", "__getattribute__") -MethodSlot(setattrofunc, "", "__setattr__") -MethodSlot(delattrofunc, "", "__delattr__") -MethodSlot(descrgetfunc, "", "__get__") -MethodSlot(descrsetfunc, "", "__set__") -MethodSlot(descrdelfunc, "", "__delete__") +# Populate "special_method_names" based on the default directives (so it can always be accessed quickly). +special_method_names = set(get_slot_table(compiler_directives=None)) # Method flags for python-exposed methods. diff --git a/Cython/Compiler/Visitor.py b/Cython/Compiler/Visitor.py --- a/Cython/Compiler/Visitor.py +++ b/Cython/Compiler/Visitor.py @@ -675,7 +675,7 @@ def _dispatch_to_method_handler(self, attr_name, self_arg, method_handler = self._find_handler( "method_%s_%s" % (type_name, attr_name), kwargs) if method_handler is None: - if (attr_name in TypeSlots.method_name_to_slot + if (attr_name in TypeSlots.special_method_names or attr_name in ['__new__', '__class__']): method_handler = self._find_handler( "slot%s" % attr_name, kwargs)
diff --git a/tests/run/binop_reverse_methods_GH2056.pyx b/tests/run/binop_reverse_methods_GH2056.pyx --- a/tests/run/binop_reverse_methods_GH2056.pyx +++ b/tests/run/binop_reverse_methods_GH2056.pyx @@ -37,25 +37,29 @@ class Base(object): self.implemented = implemented def __add__(self, other): - if (<Base>self).implemented: + assert cython.typeof(self) == "Base" + if self.implemented: return "Base.__add__(%s, %s)" % (self, other) else: return NotImplemented def __radd__(self, other): - if (<Base>self).implemented: + assert cython.typeof(self) == "Base" + if self.implemented: return "Base.__radd__(%s, %s)" % (self, other) else: return NotImplemented def __pow__(self, other, mod): - if (<Base>self).implemented: + assert cython.typeof(self) == "Base" + if self.implemented: return "Base.__pow__(%s, %s, %s)" % (self, other, mod) else: return NotImplemented def __rpow__(self, other, mod): - if (<Base>self).implemented: + assert cython.typeof(self) == "Base" + if self.implemented: return "Base.__rpow__(%s, %s, %s)" % (self, other, mod) else: return NotImplemented @@ -94,7 +98,8 @@ class OverloadLeft(Base): self.derived_implemented = implemented def __add__(self, other): - if (<OverloadLeft>self).derived_implemented: + assert cython.typeof(self) == "OverloadLeft" + if self.derived_implemented: return "OverloadLeft.__add__(%s, %s)" % (self, other) else: return NotImplemented @@ -130,7 +135,8 @@ class OverloadRight(Base): self.derived_implemented = implemented def __radd__(self, other): - if (<OverloadRight>self).derived_implemented: + assert cython.typeof(self) == "OverloadRight" + if self.derived_implemented: return "OverloadRight.__radd__(%s, %s)" % (self, other) else: return NotImplemented @@ -166,6 +172,7 @@ class OverloadCApi(Base): self.derived_implemented = derived_implemented def __add__(self, other): + assert cython.typeof(self) != "OverloadCApi" # should be untyped if isinstance(self, OverloadCApi): derived_implemented = (<OverloadCApi>self).derived_implemented else:
[BUG] __add__ method gets Python object not cython object as self. **Describe the bug** This may be working as intended if so I will have to find a workaround for it but I just wanted to confirm first. The `__eq__` method of a class in cython is given the cython version of the class even if called from python. I would expect this behaviour to apply to all dunder methods but it does not apply to the `__add__` and `__radd__` methods. These two methods are given the python object from which the internal attributes cannot be accessed. This may apply to more methods but the add methods are the only ones I have currently tested. **To Reproduce** Code to reproduce the behaviour: ```cython from cython import typeof cdef class Test: def __eq__(self, other): print("eq", typeof(self), repr(self)) return [] == other def __add__(self, other): print("add", typeof(self), repr(self)) return [] + other def __radd__(self, other): print("radd", typeof(self), repr(self)) return other + [] cdef Test test = Test() a = test == [] # eq Test <test.Test object at 0x000001267FF376C0> b = test + [] # add Python object <test.Test object at 0x000001F97E77C6C0> c = [] + test # radd Python object <test.Test object at 0x000001C24B3966C0> ``` **Expected behavior** I would expect the add methods to be given the cython version of Test so that the internal attributes can be accessed. **Environment (please complete the following information):** - OS: Windows - Python version 3.9.1 - Cython version 3.0.0a9
Thanks - I think this is something we know about but it probably does need fixing. It applies to all of the binary operators. In the past this was deliberate and [documented](https://cython.readthedocs.io/en/latest/src/userguide/special_methods.html#arithmetic-methods) because add could be called with either `self` or `other` being `Test`. Now that we implement `__radd__` correctly it should be possible to type `self` (see https://github.com/cython/cython/issues/2056). It's slightly complicated though because we do still try to support the old behaviour by default. We've [discussed this before](https://github.com/cython/cython/pull/4204#discussion_r648043848) and I think we decided it was best to add the typing even if it might cause issues. It's easily worked around though - you just assign `self` to something typed: ``` def __add__(self, other): cdef Test selft = self print("add", typeof(selft), repr(self)) return [] + other ``` I'll make this a blocker for Cython 3 I think because it's a potentially incompatible change so we want to do it there. I don't think it'll be large change.
2021-10-31T15:25:15Z
[]
[]
cython/cython
4,476
cython__cython-4476
[ "4296" ]
1f0f5f360f8835728c2b24f17e1c3434ca81c352
diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -3740,6 +3740,11 @@ def generate_argument_parsing_code(self, env, code): code.put_var_xdecref_clear(self.starstar_arg.entry) else: code.put_var_decref_clear(self.starstar_arg.entry) + for arg in self.args: + if not arg.type.is_pyobject and arg.type.needs_refcounting: + # at the moment this just catches memoryviewslices, but in future + # other non-PyObject reference counted types might need cleanup + code.put_var_xdecref(arg.entry) code.put_add_traceback(self.target.entry.qualified_name) code.put_finish_refcount_context() code.putln("return %s;" % self.error_value())
diff --git a/tests/memoryview/memoryview.pyx b/tests/memoryview/memoryview.pyx --- a/tests/memoryview/memoryview.pyx +++ b/tests/memoryview/memoryview.pyx @@ -1172,3 +1172,36 @@ def test_assign_from_byteslike(byteslike): return (<unsigned char*>buf)[:5] finally: free(buf) + +def multiple_memoryview_def(double[:] a, double[:] b): + return a[0] + b[0] + +cpdef multiple_memoryview_cpdef(double[:] a, double[:] b): + return a[0] + b[0] + +cdef multiple_memoryview_cdef(double[:] a, double[:] b): + return a[0] + b[0] + +multiple_memoryview_cdef_wrapper = multiple_memoryview_cdef + +def test_conversion_failures(): + """ + What we're concerned with here is that we don't lose references if one + of several memoryview arguments fails to convert. + + >>> test_conversion_failures() + """ + imb = IntMockBuffer("", range(1), shape=(1,)) + dmb = DoubleMockBuffer("", range(1), shape=(1,)) + for first, second in [(imb, dmb), (dmb, imb)]: + for func in [multiple_memoryview_def, multiple_memoryview_cpdef, multiple_memoryview_cdef_wrapper]: + # note - using python call of "multiple_memoryview_cpdef" deliberately + imb_before = get_refcount(imb) + dmb_before = get_refcount(dmb) + try: + func(first, second) + except: + assert get_refcount(imb) == imb_before, "before %s after %s" % (imb_before, get_refcount(imb)) + assert get_refcount(dmb) == dmb_before, "before %s after %s" % (dmb_before, get_refcount(dmb)) + else: + assert False, "Conversion should fail!"
[BUG] Reference count leak with memory view arguments **Describe the bug** When a function has multiple memory view arguments, and the argument call fails because of a type-mismatch then it can leak references to original array being viewed. **To Reproduce** In `memleak.pyx`: ```cython def foo(double[:] a, double[:] b): pass ``` and in `repro.py`: ```python import sys import numpy as np from memleak import foo a = np.random.rand(100) b = np.random.randint(100) for i in range(1000): try: foo(a, b) except: pass if i % 100 == 0: print(sys.getrefcount(a), sys.getrefcount(b)) ``` `foo` is called with a valid array for `a` but an invalid `b`. The result is `a`'s refcount is constantly increasing: ``` 4 12 204 12 404 12 604 12 804 12 1004 12 1204 12 1404 12 1604 12 1804 12 ``` **Expected behavior** The refcount of `a` should be constant, like it is for `b`. **Environment (please complete the following information):** - OS: Linux - Python version 3.8.8 - Cython version 0.29.23
I think the problem is that the cleanup: ``` __PYX_XCLEAR_MEMVIEW(&__pyx_v_a, 1); __PYX_XCLEAR_MEMVIEW(&__pyx_v_b, 1); ``` is inside the implementation function foo rather than the wrapper function. Since it fails in the wrapper function and doesn't get to the implementation function then the leak occurs. It has the signs of "might be fiddly to fix". I think it only applies to memoryviews, but in principle could affect any ref-counted, non-pyobject type added in future
2021-11-21T16:04:29Z
[]
[]
cython/cython
4,494
cython__cython-4494
[ "3938" ]
b2fac63f4a653bfd32eb4bba20bfb30b2ebad190
diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -1440,6 +1440,10 @@ def visit_PrimaryCmpNode(self, node): # note: lhs may have side effects return node + if any([arg.is_starred for arg in args]): + # Starred arguments do not directly translate to comparisons or "in" tests. + return node + lhs = UtilNodes.ResultRefNode(node.operand1) conds = []
diff --git a/tests/run/pep448_extended_unpacking.pyx b/tests/run/pep448_extended_unpacking.pyx --- a/tests/run/pep448_extended_unpacking.pyx +++ b/tests/run/pep448_extended_unpacking.pyx @@ -272,6 +272,24 @@ def unpack_list_keep_originals(a, b, c): return [*a, *b, 2, *c] +def unpack_starred_arg_for_in_operator(x, l, m): + """ + >>> l = [1,2,3] + >>> m = [4,5,6] + >>> x = 1 + >>> unpack_starred_arg_for_in_operator(x, l, m) + True + >>> x = 10 + >>> unpack_starred_arg_for_in_operator(x, l, m) + False + >>> unpack_starred_arg_for_in_operator(x, l, []) + False + >>> unpack_starred_arg_for_in_operator(x, [], []) + False + """ + return x in [*l, *m] + + ###### sets
[BUG] Multiple starred expressions in a list <!-- **PLEASE READ THIS FIRST:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> Hi ! I think Cython is not able to compile when I unpack multiple expressions separated by commas, in one list. **Describe the bug** When I want to compile my python file containing a condition like ```python if arr['name'] not in [*foo.bar.keys(), *foo.bar2.keys()]: ``` I get two error messages ``` Error compiling Cython file: ------------------------------------------------------------ if arr['name'] not in [*foo.bar.keys(), *foo.bar2.keys()]: ^ ------------------------------------------------------------ src/package/foo/bar.py:964:83: starred expression is not allowed here Error compiling Cython file: ------------------------------------------------------------ if arr['name'] not in [*foo.bar.keys(), *foo.bar2.keys()]: ^ ------------------------------------------------------------ src/package/foo/bar.py:964:83: starred expression is not allowed here ```` I know it is a very particular method and I could do ```python if arr['name'] not in [*foo.bar.keys()] + [*foo.bar2.keys()]: ``` But maybe it's possible to add this feature to Cython ? I found this [issue](https://github.com/cython/cython/issues/2939) which looks like my problem, but setting different language_level doesn't change anything. **To Reproduce** To reproduce behaviour, try to compile ```python if arr['name'] not in [*foo.bar.keys(), *foo.bar2.keys()]: ``` **Expected behavior** Errors should appear **Environment (please complete the following information):** - OS: Linux & Windows - Python version 3.7.9 - All Cython versions tested, even master branch **Additional context**
Probably an issue with the optimised `in` tests. If there is a starred expression in the `in` list, then it should not get optimised. See the `FlattenInListTransform` in `Optimize.py`. Test should go into `tests/run/pep448_extended_unpacking.py` Suitable for a backport to 0.29.x. @scoder I'd like to give this a shot Could not reproduce the issue when I test with ``` a = {1: 'a', 2: 'b'} b = {3: 'c', 4: 'd'} print(2 in [*a.keys(), *b.keys()]) ----- O/P: python3 test.py True ----- python3 -VV Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] ``` Still looks broken to me - it doesn't look like you tried to compile it with Cython. Sorry, my bad. Can replicate the issue. I'll give it a shot. ``` cython3 --embed -o test.c test.py /usr/lib/python3/dist-packages/Cython/Compiler/Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /home/arvind/test.py tree = Parsing.p_module(s, pxd, full_module_name) Error compiling Cython file: ------------------------------------------------------------ ... a = {1: 'a', 2: 'b'} b = {3: 'c', 4: 'd'} print(2 in [*a.keys()]) ^ ------------------------------------------------------------ test.py:3:12: starred expression is not allowed here ```
2021-12-09T11:35:11Z
[]
[]
cython/cython
4,498
cython__cython-4498
[ "3541" ]
ba37c35ca4da7edd099ffa6832e23764b0bf9bd9
diff --git a/Cython/Distutils/build_ext.py b/Cython/Distutils/build_ext.py --- a/Cython/Distutils/build_ext.py +++ b/Cython/Distutils/build_ext.py @@ -1,43 +1,130 @@ import sys +import os -if 'setuptools' in sys.modules: - try: - from setuptools.command.build_ext import build_ext as _build_ext - except ImportError: - # We may be in the process of importing setuptools, which tries - # to import this. - from distutils.command.build_ext import build_ext as _build_ext -else: - from distutils.command.build_ext import build_ext as _build_ext +try: + from __builtin__ import basestring +except ImportError: + basestring = str + +# Always inherit from the "build_ext" in distutils since setuptools already imports +# it from Cython if available, and does the proper distutils fallback otherwise. +# https://github.com/pypa/setuptools/blob/9f1822ee910df3df930a98ab99f66d18bb70659b/setuptools/command/build_ext.py#L16 +# setuptools imports Cython's "build_ext", so make sure we go first. +_build_ext_module = sys.modules.get('setuptools.command.build_ext') +if _build_ext_module is None: + import distutils.command.build_ext as _build_ext_module + +# setuptools remembers the original distutils "build_ext" as "_du_build_ext" +_build_ext = getattr(_build_ext_module, '_du_build_ext', None) +if _build_ext is None: + _build_ext = getattr(_build_ext_module, 'build_ext', None) +if _build_ext is None: + from distutils.command.build_ext import build_ext as _build_ext -class new_build_ext(_build_ext, object): - user_options = _build_ext.user_options[:] - boolean_options = _build_ext.boolean_options[:] +class build_ext(_build_ext, object): - user_options.extend([ + user_options = _build_ext.user_options + [ + ('cython-cplus', None, + "generate C++ source files"), + ('cython-create-listing', None, + "write errors to a listing file"), + ('cython-line-directives', None, + "emit source line directives"), + ('cython-include-dirs=', None, + "path to the Cython include files" + _build_ext.sep_by), ('cython-c-in-temp', None, "put generated C files in temp directory"), - ]) + ('cython-gen-pxi', None, + "generate .pxi file for public declarations"), + ('cython-directives=', None, + "compiler directive overrides"), + ('cython-gdb', None, + "generate debug information for cygdb"), + ('cython-compile-time-env', None, + "cython compile time environment"), + ] - boolean_options.extend([ - 'cython-c-in-temp' - ]) + boolean_options = _build_ext.boolean_options + [ + 'cython-cplus', 'cython-create-listing', 'cython-line-directives', + 'cython-c-in-temp', 'cython-gdb', + ] def initialize_options(self): - _build_ext.initialize_options(self) + super(build_ext, self).initialize_options() + self.cython_cplus = 0 + self.cython_create_listing = 0 + self.cython_line_directives = 0 + self.cython_include_dirs = None + self.cython_directives = None self.cython_c_in_temp = 0 + self.cython_gen_pxi = 0 + self.cython_gdb = False + self.cython_compile_time_env = None + + def finalize_options(self): + super(build_ext, self).finalize_options() + if self.cython_include_dirs is None: + self.cython_include_dirs = [] + elif isinstance(self.cython_include_dirs, basestring): + self.cython_include_dirs = \ + self.cython_include_dirs.split(os.pathsep) + if self.cython_directives is None: + self.cython_directives = {} + + def get_extension_attr(self, extension, option_name, default=False): + return getattr(self, option_name) or getattr(extension, option_name, default) def build_extension(self, ext): from Cython.Build.Dependencies import cythonize - if self.cython_c_in_temp: - build_dir = self.build_temp - else: - build_dir = None - new_ext = cythonize(ext,force=self.force, quiet=self.verbose == 0, build_dir=build_dir)[0] + + # Set up the include_path for the Cython compiler: + # 1. Start with the command line option. + # 2. Add in any (unique) paths from the extension + # cython_include_dirs (if Cython.Distutils.extension is used). + # 3. Add in any (unique) paths from the extension include_dirs + includes = list(self.cython_include_dirs) + for include_dir in getattr(ext, 'cython_include_dirs', []): + if include_dir not in includes: + includes.append(include_dir) + + # In case extension.include_dirs is a generator, evaluate it and keep + # result + ext.include_dirs = list(ext.include_dirs) + for include_dir in ext.include_dirs + list(self.include_dirs): + if include_dir not in includes: + includes.append(include_dir) + + # Set up Cython compiler directives: + # 1. Start with the command line option. + # 2. Add in any (unique) entries from the extension + # cython_directives (if Cython.Distutils.extension is used). + directives = dict(self.cython_directives) + if hasattr(ext, "cython_directives"): + directives.update(ext.cython_directives) + + if self.get_extension_attr(ext, 'cython_cplus'): + ext.language = 'c++' + + options = { + 'use_listing_file': self.get_extension_attr(ext, 'cython_create_listing'), + 'emit_linenums': self.get_extension_attr(ext, 'cython_line_directives'), + 'include_path': includes, + 'compiler_directives': directives, + 'build_dir': self.build_temp if self.get_extension_attr(ext, 'cython_c_in_temp') else None, + 'generate_pxi': self.get_extension_attr(ext, 'cython_gen_pxi'), + 'gdb_debug': self.get_extension_attr(ext, 'cython_gdb'), + 'c_line_in_traceback': not getattr(ext, 'no_c_in_traceback', 0), + 'compile_time_env': self.get_extension_attr(ext, 'cython_compile_time_env', default=None), + } + + new_ext = cythonize( + ext,force=self.force, quiet=self.verbose == 0, **options + )[0] + ext.sources = new_ext.sources - super(new_build_ext, self).build_extension(ext) + super(build_ext, self).build_extension(ext) -# This will become new_build_ext in the future. -from .old_build_ext import old_build_ext as build_ext +# backward compatibility +new_build_ext = build_ext diff --git a/pyximport/pyxbuild.py b/pyximport/pyxbuild.py --- a/pyximport/pyxbuild.py +++ b/pyximport/pyxbuild.py @@ -10,7 +10,7 @@ from distutils.extension import Extension from distutils.util import grok_environment_error try: - from Cython.Distutils.build_ext import new_build_ext as build_ext + from Cython.Distutils.build_ext import build_ext HAS_CYTHON = True except ImportError: HAS_CYTHON = False diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -159,7 +159,7 @@ def compile_cython_modules(profile=False, coverage=False, compile_more=False, cy # XXX hack around setuptools quirk for '*.pyx' sources extensions[-1].sources[0] = pyx_source_file - from Cython.Distutils.build_ext import new_build_ext + from Cython.Distutils.build_ext import build_ext from Cython.Compiler.Options import get_directive_defaults get_directive_defaults().update( language_level=2, @@ -175,7 +175,7 @@ def compile_cython_modules(profile=False, coverage=False, compile_more=False, cy sys.stderr.write("Enabled line tracing and profiling for the Cython binary modules\n") # not using cythonize() directly to let distutils decide whether building extensions was requested - add_command_class("build_ext", new_build_ext) + add_command_class("build_ext", build_ext) setup_args['ext_modules'] = extensions
diff --git a/tests/build/build_ext_cython_c_in_temp.srctree b/tests/build/build_ext_cython_c_in_temp.srctree new file mode 100644 --- /dev/null +++ b/tests/build/build_ext_cython_c_in_temp.srctree @@ -0,0 +1,30 @@ + +PYTHON setup.py build_ext --inplace --cython-c-in-temp +PYTHON -c 'import mymodule; assert mymodule.test_string == "TEST"' +PYTHON check_paths.py + +############# setup.py ############# + +from Cython.Distutils.extension import Extension +from Cython.Build import build_ext +from distutils.core import setup + +setup( + name='Hello world app', + ext_modules = [ + Extension( + name = 'mymodule', + sources=['mymodule.pyx'], + ) + ], + cmdclass={'build_ext': build_ext}, +) + +######## mymodule.pyx ######## + +test_string = "TEST" + +######## check_paths.py ######## + +import os +assert not os.path.exists("mymodule.c") diff --git a/tests/build/build_ext_cython_cplus.srctree b/tests/build/build_ext_cython_cplus.srctree new file mode 100644 --- /dev/null +++ b/tests/build/build_ext_cython_cplus.srctree @@ -0,0 +1,34 @@ +# tag: cpp + +PYTHON setup.py build_ext --inplace --cython-cplus +PYTHON -c "import a; a.use_vector([1,2,3])" + +######## setup.py ######## + +from Cython.Distutils.extension import Extension +from Cython.Build import build_ext +from distutils.core import setup + +setup( + name='Hello world app', + ext_modules = [ + Extension( + name = 'a', + sources=['a.pyx'], + ) + ], + cmdclass={'build_ext': build_ext}, +) + +######## a.pyx ######## + +from libcpp.vector cimport vector + +def use_vector(L): + try: + v = new vector[int]() + for a in L: + v.push_back(a) + return v.size() + finally: + del v diff --git a/tests/build/build_ext_cython_include_dirs.srctree b/tests/build/build_ext_cython_include_dirs.srctree new file mode 100644 --- /dev/null +++ b/tests/build/build_ext_cython_include_dirs.srctree @@ -0,0 +1,50 @@ + +PYTHON setup.py build_ext --inplace --cython-include-dirs=./headers1 --include-dirs=./headers2 +PYTHON -c 'import mymodule; assert mymodule.test_string == "TEST"; assert mymodule.header_value1 == 1; assert mymodule.header_value2 == 2; assert mymodule.header_value3 == 3; assert mymodule.header_value4 == 4' + +############# setup.py ############# + +from Cython.Distutils.extension import Extension +from Cython.Build import build_ext +from distutils.core import setup + +setup( + name='Hello world app', + ext_modules = [ + Extension( + name = 'mymodule', + sources=['mymodule.pyx'], + cython_include_dirs=['headers3'], + include_dirs=['./headers4'] + ) + ], + cmdclass={'build_ext': build_ext}, +) + +######## mymodule.pyx ######## + +include "myheader1.pxi" +include "myheader2.pxi" +include "myheader3.pxi" +include "myheader4.pxi" +header_value1 = test_value1 +header_value2 = test_value2 +header_value3 = test_value3 +header_value4 = test_value4 +test_string = "TEST" + +######## headers1/myheader1.pxi ######## + +cdef int test_value1 = 1 + +######## headers2/myheader2.pxi ######## + +cdef int test_value2 = 2 + +######## headers3/myheader3.pxi ######## + +cdef int test_value3 = 3 + +######## headers4/myheader4.pxi ######## + +cdef int test_value4 = 4
build_ext does not properly track dependencies (and should be deprecated / removed) Hello up there. In the context of getting [gevent miscompiled](https://github.com/gevent/gevent/issues/1568#issuecomment-617432757) the question of proper dependency tracking on Cython side was [raised](https://github.com/gevent/gevent/issues/1568#issuecomment-617636428). While original cause for that particular gevent miscompilation seems to be https://github.com/cython/cython/issues/1428, other issues were also found. This issue is probably related to https://github.com/cython/cython/issues/1436 and shows that `Cython.Distutils.build_ext` does not properly track build dependencies. In 2016 `Cython.Distutils.build_ext` was changed to use `cythonize` and the old implementation was moved into `Cython.Distutils.old_build_ext` for exactly particular reason that `old_build_ext` was not tracking dependencies properly: cb55c11b60d. A warning corresponding to the move was added: https://github.com/cython/cython/blob/3de7a4b8fb7ce045222e13ca02541f6a70e89c2e/Cython/Distutils/old_build_ext.py#L37-L42 However right after that `Cython.Distutils.build_ext` was reverted to use `old_build_ext` and new implementation became available as `new_build_ext` (4ecdd3e4) with the idea to > give projects more time to move over, and reduces the number of changes in the 0.25 series As of today (2020 April) `Cython.Distutils.build_ext` still points to `old_build_ext` and the warning is somehow **not** printed even if `old_build_ext` is imported directly(*): ``` $ python -c 'import Cython.Distutils.old_build_ext' # empty output $ python -c 'from Cython.Build import build_ext' # empty output ``` This way many projects still use `old_build_ext` = `from Cython.Build import build_ext` to compile their pyx files and miss both proper dependency tracking and the warning. As a fix I propose to make the deprecation warnings effective and to make `Cython.Build.build_ext` to refer to `new_build_ext` which uses cythonize. The rest of this issue demonstrates that `Cython.Build.build_ext` dependency handling is broken. -------- `setup.py` ```py from setuptools import setup, Extension from Cython.Distutils import build_ext setup( ext_modules = [ Extension("a", ["a.pyx"]), Extension("b", ["b.pyx"]), ], cmdclass = {'build_ext': build_ext} ) ``` `a.pyx` ```pyx # cython: language_level=2 from b cimport bfunc def afunc(): bfunc() ``` `b.pxd` ```pyx cdef bfunc() ``` `b.pyx` ```pyx # cython: language_level=2 cdef bfunc(): print "bbb" ``` ( first compile - ok ) ``` $ python setup.py build_ext -i running build_ext cythoning a.pyx to a.c cythoning b.pyx to b.c ... ``` now change `b.pxd` and `b.pyx` to add argument to bfunc: ```diff --- a/b.pxd +++ b/b.pxd @@ -1 +1 @@ -cdef bfunc() +cdef bfunc(int x) --- a/b.pyx +++ b/b.pyx @@ -1,4 +1,4 @@ # cython: language_level=2 -cdef bfunc(): - print "bbb" +cdef bfunc(int x): + print "bbb", x ``` and recompile - only `b` is rebuilt - **not** `a`: ``` (neo) (z-dev) (g.env) kirr@deco:~/tmp/trashme/pyx$ python setup.py build_ext -i running build_ext skipping 'a.c' Cython extension (up-to-date) <-- NOTE cythoning b.pyx to b.c /home/kirr/src/tools/py/cython/Cython/Compiler/Main.py:344: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/kirr/tmp/trashme/pyx/b.pxd tree = Parsing.p_module(s, pxd, full_module_name) building 'b' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c b.c -o build/temp.linux-x86_64-2.7/b.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/b.o -o /home/kirr/tmp/trashme/pyx/b.so ``` which is **WRONG** because `a` will use `b` module via outdated pxd. ( In this particular case it should be giving compilation error at Cython level: ``` $ touch a.pyx $ python setup.py build_ext -i running build_ext cythoning a.pyx to a.c Error compiling Cython file: ------------------------------------------------------------ ... # cython: language_level=2 from b cimport bfunc def afunc(): bfunc() ^ ------------------------------------------------------------ a.pyx:6:9: Call with wrong number of arguments (expected 1, got 0) ``` ) Cython `3.0a1-79-g3de7a4b8f` Thanks beforehand, Kirill /cc @robertwb P.S. Cython documentation [says](https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#distributing-cython-modules) to use `Cython.Build.new_build_ext` which should be using `cythonize` internally: > Another option is to make Cython a setup dependency of your system and use Cython’s build_ext module which runs cythonize as part of the build process: > > ```py > setup( > extensions = [Extension("*", ["*.pyx"])], > cmdclass={'build_ext': Cython.Build.new_build_ext}, > ... > ) > ``` however [Cython.Build](https://github.com/cython/cython/blob/3.0a1-79-g3de7a4b8f/Cython/Build/__init__.py) does not have it: ``` >>> import Cython.Build >>> Cython.Build.new_build_ext Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'new_build_ext' ``` because `new_build_ext` is defined only in [Cython.Distutils.build_ext](https://github.com/cython/cython/blob/3.0a1-79-g3de7a4b8f/Cython/Distutils/build_ext.py#L14) -------- (*) probably due to some logic error in _check_stack calls. if I patch Cython locally with ```diff --- a/Cython/Distutils/old_build_ext.py +++ b/Cython/Distutils/old_build_ext.py @@ -34,9 +34,7 @@ def _check_stack(path): pass return False -if (not _check_stack('setuptools/extensions.py') - and not _check_stack('pyximport/pyxbuild.py') - and not _check_stack('Cython/Distutils/build_ext.py')): +if 1: warnings.warn( "Cython.Distutils.old_build_ext does not properly handle dependencies " "and is deprecated.") ``` the warning is printed: ``` $ python -c 'import Cython.Distutils.old_build_ext' /home/kirr/src/tools/py/cython/Cython/Distutils/old_build_ext.py:39: UserWarning: Cython.Distutils.old_build_ext does not properly handle dependencies and is deprecated. "Cython.Distutils.old_build_ext does not properly handle dependencies " $ python -c 'from Cython.Build import build_ext' /home/kirr/src/tools/py/cython/Cython/Distutils/old_build_ext.py:39: UserWarning: Cython.Distutils.old_build_ext does not properly handle dependencies and is deprecated. "Cython.Distutils.old_build_ext does not properly handle dependencies " ```
Thanks for the report. The thing is, `new_build_ext` is not compatible with the setup that many users probably configured for `old_build_ext`, specifically any command options. What might work, I think, is to copy the current configuration options from `old_build_ext` to `new_build_ext`, and pass them over to `cythonize()` only if they were provided. Basically, integrate a legacy layer into `new_build_ext` that allows existing projects to build as before. We can issue a warning when we find legacy usages, but we shouldn't break the build for it. PR very welcome. Here is how the options for the old_build_ext (on the left hand side) roughly map to cythonize parameters (right hand side) used by the new_build_ext: cython_cplus : language cython_create_listing : N/A? cython_line_directives : N/A? cython_include_dirs : include_path (maybe?) cython_directives : compiler_directives cython_c_in_temp : N/A? cython_gen_pxi : N/A? cython_gdb : N/A? no_c_in_traceback : N/A? cython_compile_time_env : N/A? Given how incompatible the two build_exts are, is it worth making the new_build_ext backwards compatible with the old_build_ext, or should we just switch to the new_build_ext as a possibly breaking change for Cython 3.0?
2021-12-15T21:22:36Z
[]
[]
cython/cython
4,515
cython__cython-4515
[ "4514" ]
958df064d6c95be73bb5323de1dfa405530665f0
diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -913,6 +913,8 @@ def visit_SingleAssignmentNode(self, node): return node def visit_NameNode(self, node): + if node.annotation: + self.visit(node.annotation) if node.name in self.cython_module_names: node.is_cython_module = True else:
diff --git a/tests/run/annotation_typing.pyx b/tests/run/annotation_typing.pyx --- a/tests/run/annotation_typing.pyx +++ b/tests/run/annotation_typing.pyx @@ -278,6 +278,21 @@ def call_take_ptr(): python_dict = {"abc": 123} take_ptr(cython.cast(cython.pointer(PyObject), python_dict)) [email protected] +class HasPtr: + """ + >>> HasPtr() + HasPtr(1, 1) + """ + a: cython.pointer(cython.int) + b: cython.int + + def __init__(self): + self.b = 1 + self.a = cython.address(self.b) + def __repr__(self): + return f"HasPtr({self.a[0]}, {self.b})" + _WARNINGS = """ 9:32: Strings should no longer be used for type declarations. Use 'cython.int' etc. directly.
[BUG] Compilation fails when class attribute is annotated using `cython.pointer()` **Describe the bug** Compiler fails to compile when class attribute annotation is using `cython.pointer()`. **To Reproduce** Code to reproduce the behaviour: ```cython import cython A = cython.declare(cython.int, 3) @cython.cclass class Test: test: cython.pointer(cython.int) def __init__(self): self.test = cython.address(A) ``` Compilation fails with: ``` $ cython -3a test.py Error compiling Cython file: ------------------------------------------------------------ ... @cython.cclass class Test: test: cython.pointer(cython.int) def __init__(self): self.test = cython.address(A) ^ ------------------------------------------------------------ test.py:11:26: Cannot convert 'int *' to Python object ``` **Expected behavior** Compilation should be successful. **Environment (please complete the following information):** - OS: macOS - Python version: 3.9.7 - Cython version: master **Additional context** All following code snippets compiles succesfully: * cython version ```cython import cython cdef int A = 3 cdef class Test: cdef int *test def __init__(self): self.test = &A ``` * pure python version using `cython.p_int` annotation: ```python import cython A = cython.declare(cython.int, 3) @cython.cclass class Test: test: cython.p_int def __init__(self): self.test = cython.address(A) ```
2021-12-22T19:12:33Z
[]
[]
cython/cython
4,536
cython__cython-4536
[ "4535" ]
490d3ebaf17fb3ad369cfd913d31de902324f184
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -10423,6 +10423,7 @@ class UnopNode(ExprNode): subexprs = ['operand'] infix = True + is_inc_dec_op = False def calculate_constant_result(self): func = compile_time_unary_operators[self.operator] @@ -10534,7 +10535,10 @@ def type_error(self): self.type = PyrexTypes.error_type def analyse_cpp_operation(self, env, overload_check=True): - entry = env.lookup_operator(self.operator, [self.operand]) + operand_types = [self.operand.type] + if self.is_inc_dec_op and not self.is_prefix: + operand_types.append(PyrexTypes.c_int_type) + entry = env.lookup_operator_for_types(self.pos, self.operator, operand_types) if overload_check and not entry: self.type_error() return @@ -10548,7 +10552,12 @@ def analyse_cpp_operation(self, env, overload_check=True): else: self.exception_check = '' self.exception_value = '' - cpp_type = self.operand.type.find_cpp_operation_type(self.operator) + if self.is_inc_dec_op and not self.is_prefix: + cpp_type = self.operand.type.find_cpp_operation_type( + self.operator, operand_type=PyrexTypes.c_int_type + ) + else: + cpp_type = self.operand.type.find_cpp_operation_type(self.operator) if overload_check and cpp_type is None: error(self.pos, "'%s' operator not defined for %s" % ( self.operator, type)) @@ -10690,6 +10699,17 @@ def calculate_result_code(self): class DecrementIncrementNode(CUnopNode): # unary ++/-- operator + is_inc_dec_op = True + + def type_error(self): + if not self.operand.type.is_error: + if self.is_prefix: + error(self.pos, "No match for 'operator%s' (operand type is '%s')" % + (self.operator, self.operand.type)) + else: + error(self.pos, "No 'operator%s(int)' declared for postfix '%s' (operand type is '%s')" % + (self.operator, self.operator, self.operand.type)) + self.type = PyrexTypes.error_type def analyse_c_operation(self, env): if self.operand.type.is_numeric:
diff --git a/tests/errors/cpp_increment.pyx b/tests/errors/cpp_increment.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/cpp_increment.pyx @@ -0,0 +1,33 @@ +# mode: error + +cimport cython + +cdef extern from *: + cdef cppclass Foo: + Foo operator++() + Foo operator--() + + cdef cppclass Bar: + Bar operator++(int) + Bar operator--(int) + +cdef void foo(): + cdef Foo f + cdef Bar b + cython.operator.postincrement(f) + cython.operator.postincrement(b) + cython.operator.postdecrement(f) + cython.operator.postdecrement(b) + + cython.operator.preincrement(f) + cython.operator.preincrement(b) + cython.operator.predecrement(f) + cython.operator.predecrement(b) + + +_ERRORS = u""" +17:19: No 'operator++(int)' declared for postfix '++' (operand type is 'Foo') +19:19: No 'operator--(int)' declared for postfix '--' (operand type is 'Foo') +23:19: No match for 'operator++' (operand type is 'Bar') +25:19: No match for 'operator--' (operand type is 'Bar') +"""
[BUG] postincrement in C++ handled incorrectly **Describe the bug** In Cython both `cython.operator.preincrement` and `cython.operator.postincrement` are handled as `preincrement`. However in C++ these have two different operators (see https://en.cppreference.com/w/cpp/language/operators): |Expression | As member function | |----------------|----------------------------| | `@a` | (a).operator@() | | `a@` | (a).operator@(0) | **To Reproduce** Since both operators are treated as `@a` the following code does not compile ```cython cimport cython cdef extern from "*": cdef cppclass example: example operator++(int) def test(): cdef example a cython.operator.postincrement(a) ``` while the following incorrectly does compile: ```cython cimport cython cdef extern from "*": cdef cppclass example: example operator++() def test(): cdef example a cython.operator.postincrement(a) ``` **Expected behavior** The operator behavior should match the behavior used in C++. So `postincrement` should only work when the corresponding operator exists. **Environment (please complete the following information):** - OS: Linux - Python version 3.9 - Cython version 3.0.0a9
If I understand this correctly, the issue is in Cython identifying whether the operator is available? Looking at https://github.com/cython/cython/blob/b6a4215211839afaa850538cdbb065e3513e0dd0/Cython/Compiler/ExprNodes.py#L10494-L10498 I think the correct C++ is generated?
2021-12-26T22:59:59Z
[]
[]
cython/cython
4,552
cython__cython-4552
[ "3442" ]
6006a7e8ad4be5f9fcd269b472ee955a3ef931a4
diff --git a/Cython/Compiler/CythonScope.py b/Cython/Compiler/CythonScope.py --- a/Cython/Compiler/CythonScope.py +++ b/Cython/Compiler/CythonScope.py @@ -51,7 +51,7 @@ def lookup(self, name): def find_module(self, module_name, pos): error("cython.%s is not available" % module_name, pos) - def find_submodule(self, module_name): + def find_submodule(self, module_name, as_package=False): entry = self.entries.get(module_name, None) if not entry: self.load_cythonscope() diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -143,6 +143,29 @@ def process_pxd(self, source_desc, scope, module_name): def nonfatal_error(self, exc): return Errors.report_error(exc) + def _split_qualified_name(self, qualified_name): + # Splits qualified_name into parts in form of 2-tuples: (PART_NAME, IS_PACKAGE). + qualified_name_parts = qualified_name.split('.') + last_part = qualified_name_parts.pop() + qualified_name_parts = [(p, True) for p in qualified_name_parts] + if last_part != '__init__': + # If Last part is __init__, then it is omitted. Otherwise, we need to check whether we can find + # __init__.pyx/__init__.py file to determine if last part is package or not. + is_package = False + for suffix in ('.py', '.pyx'): + path = self.search_include_directories( + qualified_name, suffix=suffix, source_pos=None, source_file_path=None) + if path: + is_package = self._is_init_file(path) + break + + qualified_name_parts.append((last_part, is_package)) + return qualified_name_parts + + @staticmethod + def _is_init_file(path): + return os.path.basename(path) in ('__init__.pyx', '__init__.py', '__init__.pxd') if path else False + def find_module(self, module_name, relative_to=None, pos=None, need_pxd=1, absolute_fallback=True): # Finds and returns the module scope corresponding to @@ -182,16 +205,16 @@ def find_module(self, module_name, relative_to=None, pos=None, need_pxd=1, if not scope: pxd_pathname = self.find_pxd_file(qualified_name, pos) if pxd_pathname: - scope = relative_to.find_submodule(module_name) + is_package = self._is_init_file(pxd_pathname) + scope = relative_to.find_submodule(module_name, as_package=is_package) if not scope: if debug_find_module: print("...trying absolute import") if absolute_fallback: qualified_name = module_name scope = self - for name in qualified_name.split("."): - scope = scope.find_submodule(name) - + for name, is_package in self._split_qualified_name(qualified_name): + scope = scope.find_submodule(name, as_package=is_package) if debug_find_module: print("...scope = %s" % scope) if not scope.pxd_file_loaded: @@ -321,12 +344,12 @@ def lookup_submodule(self, name): # Look up a top-level module. Returns None if not found. return self.modules.get(name, None) - def find_submodule(self, name): + def find_submodule(self, name, as_package=False): # Find a top-level module, creating a new one if needed. scope = self.lookup_submodule(name) if not scope: scope = ModuleScope(name, - parent_module = None, context = self) + parent_module = None, context = self, is_package=as_package) self.modules[name] = scope return scope diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -8742,9 +8742,16 @@ def analyse_declarations(self, env): if not env.is_module_scope: error(self.pos, "cimport only allowed at module level") return - if self.relative_level and self.relative_level > env.qualified_name.count('.'): - error(self.pos, "relative cimport beyond main package is not allowed") - return + qualified_name_components = env.qualified_name.count('.') + 1 + if self.relative_level: + if self.relative_level > qualified_name_components: + # 1. case: importing beyond package: from .. import pkg + error(self.pos, "relative cimport beyond main package is not allowed") + return + elif self.relative_level == qualified_name_components and not env.is_package: + # 2. case: importing from same level but current dir is not package: from . import module + error(self.pos, "relative cimport from non-package directory is not allowed") + return module_scope = env.find_module(self.module_name, self.pos, relative_level=self.relative_level) module_name = module_scope.qualified_name env.add_imported_module(module_scope) diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -1298,19 +1298,13 @@ class ModuleScope(Scope): is_cython_builtin = 0 old_style_globals = 0 - def __init__(self, name, parent_module, context): + def __init__(self, name, parent_module, context, is_package=False): from . import Builtin self.parent_module = parent_module outer_scope = Builtin.builtin_scope Scope.__init__(self, name, outer_scope, parent_module) - if name == "__init__": - # Treat Spam/__init__.pyx specially, so that when Python loads - # Spam/__init__.so, initSpam() is defined. - self.module_name = parent_module.module_name - self.is_package = True - else: - self.module_name = name - self.is_package = False + self.is_package = is_package + self.module_name = name self.module_name = EncodedString(self.module_name) self.context = context self.module_cname = Naming.module_cname @@ -1423,9 +1417,16 @@ def find_module(self, module_name, pos, relative_level=-1): # explicit relative cimport # error of going beyond top-level is handled in cimport node relative_to = self - while relative_level > 0 and relative_to: + + top_level = 1 if self.is_package else 0 + # * top_level == 1 when file is __init__.pyx, current package (relative_to) is the current module + # i.e. dot in `from . import ...` points to the current package + # * top_level == 0 when file is regular module, current package (relative_to) is parent module + # i.e. dot in `from . import ...` points to the package where module is placed + while relative_level > top_level and relative_to: relative_to = relative_to.parent_module relative_level -= 1 + elif relative_level != 0: # -1 or None: try relative cimport first, then absolute relative_to = self.parent_module @@ -1435,7 +1436,7 @@ def find_module(self, module_name, pos, relative_level=-1): return module_scope.context.find_module( module_name, relative_to=relative_to, pos=pos, absolute_fallback=absolute_fallback) - def find_submodule(self, name): + def find_submodule(self, name, as_package=False): # Find and return scope for a submodule of this module, # creating a new empty one if necessary. Doesn't parse .pxd. if '.' in name: @@ -1444,10 +1445,10 @@ def find_submodule(self, name): submodule = None scope = self.lookup_submodule(name) if not scope: - scope = ModuleScope(name, parent_module=self, context=self.context) + scope = ModuleScope(name, parent_module=self, context=self.context, is_package=True if submodule else as_package) self.module_entries[name] = scope if submodule: - scope = scope.find_submodule(submodule) + scope = scope.find_submodule(submodule, as_package=as_package) return scope def lookup_submodule(self, name):
diff --git a/tests/errors/e_relative_cimport.pyx b/tests/errors/e_relative_cimport.pyx --- a/tests/errors/e_relative_cimport.pyx +++ b/tests/errors/e_relative_cimport.pyx @@ -9,7 +9,7 @@ from . cimport e_relative_cimport _ERRORS=""" 4:0: relative cimport beyond main package is not allowed -5:0: relative cimport beyond main package is not allowed +5:0: relative cimport from non-package directory is not allowed 6:0: relative cimport beyond main package is not allowed -7:0: relative cimport beyond main package is not allowed +7:0: relative cimport from non-package directory is not allowed """ diff --git a/tests/run/relative_cimport_compare.srctree b/tests/run/relative_cimport_compare.srctree new file mode 100644 --- /dev/null +++ b/tests/run/relative_cimport_compare.srctree @@ -0,0 +1,327 @@ +# mode: run +# tag: cimport, pep489 + +PYTHON setup.py build_ext --inplace +PYTHON -c "import test_import" +PYTHON -c "import test_cimport" + + +######## setup.py ######## + +from distutils.core import setup +from Cython.Build import cythonize +from Cython.Distutils.extension import Extension + +setup( + ext_modules=cythonize('**/*.pyx'), +) + +######## test_import.py ######## +import sys +SUPPORTS_PEP_489 = sys.version_info > (3, 5) +if SUPPORTS_PEP_489: + import cypkg.sub.submodule + import cypkg.sub.sub2.sub2module + import pypkg.module + import pypkg.sub.submodule + import pypkg.sub.sub2.sub2module + +######## test_cimport.py ######## +import sys +SUPPORTS_PEP_489 = sys.version_info > (3, 5) +if SUPPORTS_PEP_489: + import module + + +######## module.pyx ######## +cimport cypkg + +cdef cypkg.a_type a1 = 3 +assert a1 == 3 +cdef cypkg.a.a_type a2 = 3 +assert a2 == 3 +cdef cypkg.b_type b1 = 4 +assert b1 == 4 +cdef cypkg.b.b_type b2 = 4 +assert b2 == 4 + + +cimport cypkg.sub +cdef cypkg.sub.a_type a3 = 3 +assert a3 == 3 +cdef cypkg.sub.a.a_type a4 = 3 +assert a4 == 3 +cdef cypkg.sub.b_type b3 = 4 +assert b3 == 4 +cdef cypkg.sub.b.b_type b4 = 4 +assert b4 == 4 + + +cimport cypkg.sub.sub2 +cdef cypkg.sub.sub2.a_type a5 = 3 +assert a5 == 3 +cdef cypkg.sub.sub2.a.a_type a6 = 3 +assert a6 == 3 +cdef cypkg.sub.sub2.b_type b5 = 4 +assert b5 == 4 +cdef cypkg.sub.sub2.b.b_type b6 = 4 +assert b6 == 4 + +import pypkg +assert pypkg.a_value == 3 +assert pypkg.a.a_value == 3 +assert pypkg.b_value == 4 +assert pypkg.b.b_value == 4 + + +import pypkg.sub +assert pypkg.sub.a_value == 3 +assert pypkg.sub.a.a_value == 3 +assert pypkg.sub.b_value == 4 +assert pypkg.sub.b.b_value == 4 + + +import cypkg.sub.sub2 +assert pypkg.sub.sub2.a_value == 3 +assert pypkg.sub.sub2.a.a_value == 3 +assert pypkg.sub.sub2.b_value == 4 +assert pypkg.sub.sub2.b.b_value == 4 + + +######## cypkg/__init__.pxd ######## + +cimport cypkg.sub +cimport cypkg.sub.sub2 + +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from . cimport sub +from .sub cimport a +from .sub.a cimport a_type +from .sub.sub2 cimport b +from .sub.sub2.b cimport b_type + +######## cypkg/__init__.pyx ######## + + +######## cypkg/module.pyx ######## + +cimport cypkg +cimport cypkg.sub +cimport cypkg.sub.sub2 +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from . cimport sub +from .sub cimport a +from .sub.a cimport a_type +from .sub.sub2 cimport b +from .sub.sub2.b cimport b_type + + +######## cypkg/sub/__init__.pxd ######## + +cimport cypkg +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from . cimport a +from .a cimport a_type + +from .. cimport sub +from ..sub cimport a +from ..sub.a cimport a_type +from ..sub.sub2 cimport b +from ..sub.sub2.b cimport b_type + +######## cypkg/sub/__init__.pyx ######## + +######## cypkg/sub/a.pxd ######## + +ctypedef int a_type + +######## cypkg/sub/submodule.pyx ######## + +cimport cypkg +cimport cypkg.sub +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from . cimport a +from .a cimport a_type + +from .. cimport sub +from ..sub cimport a +from ..sub.a cimport a_type +from ..sub.sub2 cimport b +from ..sub.sub2.b cimport b_type + +######## cypkg/sub/sub2/__init__.pxd ######## + +cimport cypkg +cimport cypkg.sub +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from ..sub2 cimport b +from ..sub2.b cimport b_type + +from ...sub cimport a +from ...sub.a cimport a_type + +from ... cimport sub +from ...sub.sub2 cimport b +from ...sub.sub2.b cimport b_type + +######## cypkg/sub/sub2/__init__.pyx ######## + +######## cypkg/sub/sub2/b.pxd ######## + +ctypedef int b_type + + +######## cypkg/sub/sub2/sub2module.pyx ######## + +cimport cypkg +cimport cypkg.sub +from cypkg.sub cimport a +from cypkg.sub.a cimport a_type +from cypkg.sub.sub2 cimport b +from cypkg.sub.sub2.b cimport b_type + +from .. cimport sub2 +from ..sub2 cimport b +from ..sub2.b cimport b_type + +from ...sub cimport a +from ...sub.a cimport a_type + +from ... cimport sub +from ...sub.sub2 cimport b +from ...sub.sub2.b cimport b_type + +######## pypkg/__init__.py ######## + +import pypkg.sub +import pypkg.sub.sub2 + +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from . import sub +from .sub import a +from .sub.a import a_value +from .sub.sub2 import b +from .sub.sub2.b import b_value + +######## pypkg/module.py ######## + +import pypkg +import pypkg.sub +import pypkg.sub.sub2 +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from . import sub +from .sub import a +from .sub.a import a_value +from .sub.sub2 import b +from .sub.sub2.b import b_value + +######## pypkg/sub/__init__.py ######## + +import pypkg +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from . import a +from .a import a_value + +from .. import sub +from ..sub import a +from ..sub.a import a_value +from ..sub.sub2 import b +from ..sub.sub2.b import b_value + +######## pypkg/sub/a.py ######## + +a_value = 3 + +######## pypkg/sub/submodule.py ######## + +import pypkg +import pypkg.sub +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from . import a +from .a import a_value + +from .. import sub +from ..sub import a +from ..sub.a import a_value +from ..sub.sub2 import b +from ..sub.sub2.b import b_value + +######## pypkg/sub/sub2/__init__.py ######## + +import pypkg +import pypkg.sub +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from ..sub2 import b +from ..sub2.b import b_value + +from ...sub import a +from ...sub.a import a_value + +from ... import sub +from ...sub.sub2 import b +from ...sub.sub2.b import b_value + +######## pypkg/sub/sub2/b.py ######## + +b_value = 4 + + +######## pypkg/sub/sub2/sub2module.py ######## + +import pypkg +import pypkg.sub +from pypkg.sub import a +from pypkg.sub.a import a_value +from pypkg.sub.sub2 import b +from pypkg.sub.sub2.b import b_value + +from .. import sub2 +from ..sub2 import b +from ..sub2.b import b_value + +from ...sub import a +from ...sub.a import a_value + +from ... import sub +from ...sub.sub2 import b +from ...sub.sub2.b import b_value
`from . cimport modulename` tries to search in parent package from `__init__.pxd`. In `__init__.pxd` in a package, using `from . cimport modulename` attempts to find `modulename.pxd` in the parent directory of the package. Using `from . import modulename` in basic Python attempts to find `modulename.*` within the package itself, as does using `from . cimport modulename` in all `*.pxd` files *except* for `__init__.pxd` in packages. Using `from .packagename cimport modulename` in `__init__.pxd` doesn't work around this, because this (correctly) attempts to find `packagename` inside the package itself. Because of this, I think there should not be much functional code out there that depends on the relative `cimport` being based on the parent directory, meaning that it should be possible to switch it to the package directory, in line with Python behaviour, without breaking compatibility. --- #### Example structure: ``` cyrel_package/ ├── __init__.pxd ├── __init__.py ├── module.pxd ├── module.py └── subpackage ├── __init__.pxd ├── __init__.py ├── submodule.pxd └── submodule.py ``` And in `cyrel_package/subpackage/__init__.pxd`: ```python3 # from . cimport submodule # Fails, "'cyrel_package/submodule.pxd' not found" — Attempts to import relative to parent package directory instead of current package directory. # from .subpackage cimport submodule # Fails, "'cyrel_package/subpackage/subpackage/submodule.pxd' not found" — Attempts to (correctly) import relative to current package directory. from cyrel_package.subpackage cimport submodule # Works. ``` It also fails with `from . cimport module` in the topmost `cyrel_package/__init__.pxd`.
Thanks for the report. There's probably just a tiny wrong decision taken somewhere, e.g. that `__init__.pxd` is not always considered to be a package in all places or so. You tried this with the latest master, right? Could you provide a PR that adds this setup to the existing `tests/run/relative_cimport.srctree` test?
2022-01-02T21:06:48Z
[]
[]
cython/cython
4,629
cython__cython-4629
[ "4628" ]
c900b6a587801aa3efc918809e53d6c33bc8ed73
diff --git a/Cython/Build/Cythonize.py b/Cython/Build/Cythonize.py --- a/Cython/Build/Cythonize.py +++ b/Cython/Build/Cythonize.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from __future__ import absolute_import +from __future__ import absolute_import, print_function import os import shutil @@ -45,10 +45,12 @@ def find_package_base(path): package_path = '%s/%s' % (parent, package_path) return base_dir, package_path - def cython_compile(path_pattern, options): - pool = None all_paths = map(os.path.abspath, extended_iglob(path_pattern)) + _cython_compile_files(all_paths, options) + +def _cython_compile_files(all_paths, options): + pool = None try: for path in all_paths: if options.build_inplace: @@ -230,8 +232,15 @@ def parse_args(args): def main(args=None): options, paths = parse_args(args) + all_paths = [] for path in paths: - cython_compile(path, options) + expanded_path = [os.path.abspath(p) for p in extended_iglob(path)] + if not expanded_path: + import sys + print("{}: No such file or directory: '{}'".format(sys.argv[0], path), file=sys.stderr) + sys.exit(1) + all_paths.extend(expanded_path) + _cython_compile_files(all_paths, options) if __name__ == '__main__': diff --git a/Cython/Compiler/CmdLine.py b/Cython/Compiler/CmdLine.py --- a/Cython/Compiler/CmdLine.py +++ b/Cython/Compiler/CmdLine.py @@ -4,11 +4,17 @@ from __future__ import absolute_import +import sys import os from argparse import ArgumentParser, Action, SUPPRESS from . import Options +if sys.version_info < (3, 3): + # TODO: This workaround can be removed in Cython 3.1 + FileNotFoundError = IOError + + class ParseDirectivesAction(Action): def __call__(self, parser, namespace, values, option_string=None): old_directives = dict(getattr(namespace, self.dest, @@ -209,6 +215,10 @@ def filter_out_embed_options(args): def parse_command_line(args): parser = create_cython_argparser() arguments, sources = parse_command_line_raw(parser, args) + for source in sources: + if not os.path.exists(source): + import errno + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), source) options = Options.CompilationOptions(Options.default_options) for name, value in vars(arguments).items(): diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -2,7 +2,7 @@ # Cython Top Level # -from __future__ import absolute_import +from __future__ import absolute_import, print_function import os import re @@ -747,7 +747,16 @@ def main(command_line = 0): args = sys.argv[1:] any_failures = 0 if command_line: - options, sources = parse_command_line(args) + try: + options, sources = parse_command_line(args) + except IOError as e: + # TODO: IOError can be replaced with FileNotFoundError in Cython 3.1 + import errno + if errno.ENOENT != e.errno: + # Raised IOError is not caused by missing file. + raise + print("{}: No such file or directory: '{}'".format(sys.argv[0], e.filename), file=sys.stderr) + sys.exit(1) else: options = CompilationOptions(default_options) sources = args
diff --git a/Cython/Compiler/Tests/TestCmdLine.py b/Cython/Compiler/Tests/TestCmdLine.py --- a/Cython/Compiler/Tests/TestCmdLine.py +++ b/Cython/Compiler/Tests/TestCmdLine.py @@ -2,6 +2,10 @@ import sys import re from unittest import TestCase +try: + from unittest.mock import patch, Mock +except ImportError: # Py2 + from mock import patch, Mock try: from StringIO import StringIO except ImportError: @@ -12,7 +16,15 @@ from .Utils import backup_Options, restore_Options, check_global_options +unpatched_exists = os.path.exists + +def patched_exists(path): + # avoid the Cython command raising a file not found error + if path in ('source.pyx', 'file.pyx', 'file1.pyx', 'file2.pyx', 'file3.pyx', 'foo.pyx', 'bar.pyx'): + return True + return unpatched_exists(path) +@patch('os.path.exists', new=Mock(side_effect=patched_exists)) class CmdLineParserTest(TestCase): def setUp(self): self._options_backup = backup_Options() diff --git a/tests/run/cython_no_files.srctree b/tests/run/cython_no_files.srctree new file mode 100644 --- /dev/null +++ b/tests/run/cython_no_files.srctree @@ -0,0 +1,34 @@ +PYTHON test_cythonize_no_files.py +PYTHON test_cython_no_files.py + +######## a.py ########### +a = 1 + +######## b.py ########### +b = 2 + +######## c.pyx ########### +c = 3 + +######## d.pyx ########### +d = 4 + +######## test_cythonize_no_files.py ########### +import subprocess +import sys + +cmd = [sys.executable, '-c', 'from Cython.Build.Cythonize import main; main()', 'a.py', 'b.py', 'c.py', '*.pyx'] +proc = subprocess.Popen(cmd, stderr=subprocess.PIPE) +_, err = proc.communicate() +assert proc.returncode == 1, proc.returncode +assert b"No such file or directory: 'c.py'" in err, err + +######## test_cython_no_files.py ########### +import subprocess +import sys + +cmd = [sys.executable, '-c', 'from Cython.Compiler.Main import main; main(command_line = 1)', 'a.py', 'b.py', 'c.py', '*.pyx'] +proc = subprocess.Popen(cmd, stderr=subprocess.PIPE) +_, err = proc.communicate() +assert proc.returncode == 1, proc.returncode +assert b"No such file or directory: 'c.py'" in err, err
[BUG] cython and cythonize commands does not error out when file does not exist **Describe the bug** All standard linux commands print out error when file is not present: ``` $ ls missing_file ls: missing_file: No such file or directory $ cat missing_file cat: missing_file: No such file or directory $ python3.9 missing_file /usr/local/bin/python3.9: can't open file '/Users/matus/missing_file': [Errno 2] No such file or directory ``` cython and cythonize commands do not follow this semantics: ``` $ cython missing_file /Users/matus/dev/cython/missing_file $ cythonize missing_file $ ``` **To Reproduce** Run `cython` or `cythonize` commands with non-existing files **Expected behavior** Error is printed out as in other standard tools **Environment (please complete the following information):** - OS: MacOS - Python version 3.9.9 - Cython version: master
2022-02-08T18:32:21Z
[]
[]
cython/cython
4,660
cython__cython-4660
[ "3066" ]
97b8a0b9e9d9599f52d810b6f1ed52ebc1796918
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -4929,14 +4929,19 @@ def independent_spanning_type(type1, type2): type1 = type1.ref_base_type else: type2 = type2.ref_base_type - if type1 == type2: + + resolved_type1 = type1.resolve() + resolved_type2 = type2.resolve() + if resolved_type1 == resolved_type2: return type1 - elif (type1 is c_bint_type or type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric): + elif ((resolved_type1 is c_bint_type or resolved_type2 is c_bint_type) + and (type1.is_numeric and type2.is_numeric)): # special case: if one of the results is a bint and the other # is another C integer, we must prevent returning a numeric # type so that we do not lose the ability to coerce to a # Python bool if we have to. return py_object_type + span_type = _spanning_type(type1, type2) if span_type is None: return error_type
diff --git a/tests/run/ctypedef_bint.pyx b/tests/run/ctypedef_bint.pyx new file mode 100644 --- /dev/null +++ b/tests/run/ctypedef_bint.pyx @@ -0,0 +1,71 @@ +from __future__ import print_function + +from cython cimport typeof + +ctypedef bint mybool + +cdef mybool mybul = True +cdef bint bul = True +cdef int num = 42 + + +def CondExprNode_to_obj(test): + """ + >>> CondExprNode_to_obj(True) + Python object | Python object + 2 + >>> CondExprNode_to_obj(False) + Python object | Python object + 84 + """ + + print(typeof(mybul if test else num), "|", typeof(bul if test else num)) + + return (mybul if test else num) + (bul if test else num) + + +def BoolBinopNode_to_obj(): + """ + >>> BoolBinopNode_to_obj() + Python object | Python object + 2 + """ + + print(typeof(mybul or num), "|", typeof(bul or num)) + + return (mybul or num) + (bul or num) + + +cdef int test_bool(mybool arg): + return <int>arg + + +def CondExprNode_to_bool(test): + """ + >>> CondExprNode_to_bool(True) + bint | bint + 0 + >>> CondExprNode_to_bool(False) + bint | bint + 2 + """ + + print(typeof(not mybul if test else mybul), "|", typeof(not bul if test else bul)) + + # test_bool() would silently crash if one of the types is cast + # to Python object and not just assigned. + # It happens when a type is wrongly inferred as Python object + # instead of bint or mybool. + return test_bool(not mybul if test else mybul) + test_bool(not bul if test else bul) + + +def BoolBinopNode_to_bool(): + """ + >>> BoolBinopNode_to_bool() + bint | bint + 2 + """ + + print(typeof(not mybul or mybul), "|", typeof(not bul or bul)) + + return test_bool(not mybul or mybul) + test_bool(not bul or bul)
Cython incorrectly casts with ctypedef and bint Given the following code: ``` ctypedef bint mybool cdef f(): cdef mybool c cdef mybool x c = True x = True x = not x if c else x print(x) ``` Results in this C code: ``` /* "test.pyx":3 * ctypedef bint mybool * * cdef f(): # <<<<<<<<<<<<<< * cdef mybool c * cdef mybool x */ static PyObject *__pyx_f_4test_f(void) { __pyx_t_4test_mybool __pyx_v_c; __pyx_t_4test_mybool __pyx_v_x; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("f", 0); /* "test.pyx":6 * cdef mybool c * cdef mybool x * c = True # <<<<<<<<<<<<<< * x = True * x = not x if c else x */ __pyx_v_c = 1; /* "test.pyx":7 * cdef mybool x * c = True * x = True # <<<<<<<<<<<<<< * x = not x if c else x * print(x) */ __pyx_v_x = 1; /* "test.pyx":8 * c = True * x = True * x = not x if c else x # <<<<<<<<<<<<<< * print(x) */ if ((__pyx_v_c != 0)) { __pyx_t_1 = ((PyObject *)(!(__pyx_v_x != 0))); } else { __pyx_t_1 = ((PyObject *)__pyx_v_x); } __pyx_v_x = ((__pyx_t_4test_mybool)__pyx_t_1); __pyx_t_1 = 0; /* "test.pyx":9 * x = True * x = not x if c else x * print(x) # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_x); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_print, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "test.pyx":3 * ctypedef bint mybool * * cdef f(): # <<<<<<<<<<<<<< * cdef mybool c * cdef mybool x */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("test.f", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } ``` Which throws these compiler warnings: ``` $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.7 -o test test.c test.c: In function ‘__pyx_f_4test_f’: test.c:1136:18: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] __pyx_t_1 = ((PyObject *)(!(__pyx_v_x != 0))); ^ test.c:1138:18: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] __pyx_t_1 = ((PyObject *)__pyx_v_x); ^ test.c:1140:16: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] __pyx_v_x = ((__pyx_t_4test_mybool)__pyx_t_1); ``` The C boolean variable __pyx_v_x is incorrectly casted to PyObject * and back to bool. This does not happen, if bint is used directly in the cdefs.
Yes, that looks wrong. I guess we're too strict about special-casing `bint`, and should also include typedefs there. PR welcome that fixes up at least some of those places. Look for `c_bint_type`, mostly. I would like to take a stab at this issue, I may need some help though @scoder. 1. Correct me if I'm wrong, but `independent_spanning_type()` in `PyrexTypes.py` is where I should make the change? Maybe something like calling `.resolve()` on each type before comparing them to each other? 2. When writing a test for this case, how do I check that the value is not being cast to `PyObject`? If you could point me to an existing test that does something similar, that would help a lot I think.
2022-02-25T09:20:29Z
[]
[]
cython/cython
4,661
cython__cython-4661
[ "600" ]
97b8a0b9e9d9599f52d810b6f1ed52ebc1796918
diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -2439,7 +2439,8 @@ def declare_cfunction(self, name, type, pos, cname = punycodify_name(c_safe_identifier(name), Naming.unicode_vtabentry_prefix) if entry: if not entry.is_cfunction: - warning(pos, "'%s' redeclared " % name, 0) + error(pos, "'%s' redeclared " % name) + entry.already_declared_here() else: if defining and entry.func_cname: error(pos, "'%s' already defined" % name)
diff --git a/tests/errors/redeclaration_of_var_by_cfunc_T600.pyx b/tests/errors/redeclaration_of_var_by_cfunc_T600.pyx new file mode 100644 --- /dev/null +++ b/tests/errors/redeclaration_of_var_by_cfunc_T600.pyx @@ -0,0 +1,14 @@ +# ticket: 600 +# mode: error + +cdef class Bar: + cdef list _operands + + cdef int _operands(self): + return -1 + + +_ERRORS = """ +7:9: '_operands' redeclared +5:14: Previous declaration is here +"""
Mysterious error with conflicting types If you declare, for example, _operands to be a list, and cdef _operands(self) to be a function in the same class, mysterious errors can be produced such as: ``` Traceback (most recent call last): File "/home/gfurnish/sage-3.0.6/local/bin/cython", line 8, in <module> main(command_line = 1) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Main.py", line 527, in main result = compile(sources, options) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Main.py", line 505, in compile return compile_multiple(source, options) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Main.py", line 472, in compile_multiple result = context.compile(source, options) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Main.py", line 327, in compile tree.process_implementation(scope, options, result) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/ModuleNode.py", line 59, in process_implementation self.generate_c_code(env, options, result) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/ModuleNode.py", line 243, in generate_c_code self.body.generate_function_definitions(env, code, options.transforms) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Nodes.py", line 252, in generate_function_definitions stat.generate_function_definitions(env, code, transforms) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Nodes.py", line 2051, in generate_function_definitions self.entry.type.scope, code, transforms) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Nodes.py", line 252, in generate_function_definitions stat.generate_function_definitions(env, code, transforms) File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Nodes.py", line 892, in generate_function_definitions exc_check = self.caller_will_check_exceptions() File "/home/gfurnish/sage-3.0.6/local/lib/python2.5/site-packages/Cython/Compiler/Nodes.py", line 1162, in caller_will_check_exceptions return self.entry.type.exception_check AttributeError: BuiltinObjectType instance has no attribute 'exception_check' ``` Migrated from http://trac.cython.org/ticket/43
@robertwb changed **milestone** to `0.9.8.2` commented @robertwb changed **milestone** from `0.10` to `0.11` commented @dagss commented I'm not able to reproduce this? @robertwb changed **milestone** from `0.11` to `0.11.1` **priority** from `major` to `minor` commented It doesn't crash for me either, but perhaps it should be raising an error here... @robertwb changed **milestone** from `0.11.1` to `wishlist` commented
2022-02-25T12:51:09Z
[]
[]
cython/cython
4,719
cython__cython-4719
[ "4717" ]
ce5ca29d27f4c0e538f82823ef822840102bfea2
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -2769,6 +2769,8 @@ class CReferenceBaseType(BaseType): # Common base type for C reference and C++ rvalue reference types. + subtypes = ['ref_base_type'] + def __init__(self, base_type): self.ref_base_type = base_type
diff --git a/tests/run/fused_cpp.pyx b/tests/run/fused_cpp.pyx --- a/tests/run/fused_cpp.pyx +++ b/tests/run/fused_cpp.pyx @@ -41,3 +41,13 @@ def typeid_call2(cython.integral x): """ cdef const type_info* a = &typeid(cython.integral) return a[0] == tidint[0] + +cdef fused_ref(cython.integral& x): + return x*2 + +def test_fused_ref(int x): + """ + >>> test_fused_ref(5) + (10, 10) + """ + return fused_ref(x), fused_ref[int](x)
[BUG] Cannot pass fused type by reference It seems that passing fused types by reference is not currently possible. Consider the following snippet ```cython # distutils: language=c++ ctypedef fused element_t: int cdef funcr(element_t &a): pass def test(): cdef int a = 5 funcr(a) ``` which fails with the error message: ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef funcr(element_t &a): pass def test(): cdef int a = 5 funcr(a) ^ ------------------------------------------------------------ ...pyx:11:10: Cannot coerce to a type that is not specialized ``` I tried explicitly indexing to specialize the type by changing the call from `funcr(a)` to `funcr[int](a)` but got the following message. ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef funcr(element_t &a): pass def test(): cdef int a = 5 funcr[int](a) ^ ------------------------------------------------------------ ...pyx:11:9: Can only parameterize template functions. ``` The code compiles fine after changing the type definition to `ctypedef int element_t`. Similarly, passing `a` by value or by pointer works as expected. My environment is - OS: macOS Monterey 12.3 (M1 chip) - Python version: 3.9.9 (pyenv via brew) - Cython version: 0.29.28 (have also tried `master`) Happy to support if I can, but not quite sure where to get started.
2022-04-06T20:28:50Z
[]
[]
cython/cython
4,725
cython__cython-4725
[ "4716" ]
0be7a37283bf6f9f9b563f22659d8aa9d353db73
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -13,6 +13,7 @@ except NameError: from functools import reduce from functools import partial +from itertools import product from Cython.Utils import cached_function from .Code import UtilityCode, LazyUtilityCode, TempitaUtilityCode @@ -1835,7 +1836,27 @@ def __init__(self, types, name=None): for t in types: if t.is_fused: # recursively merge in subtypes - for subtype in t.types: + if isinstance(t, FusedType): + t_types = t.types + else: + # handle types that aren't a fused type themselves but contain fused types + # for example a C++ template where the template type is fused. + t_fused_types = t.get_fused_types() + t_types = [] + for substitution in product( + *[fused_type.types for fused_type in t_fused_types] + ): + t_types.append( + t.specialize( + { + fused_type: sub + for fused_type, sub in zip( + t_fused_types, substitution + ) + } + ) + ) + for subtype in t_types: if subtype not in flattened_types: flattened_types.append(subtype) elif t not in flattened_types:
diff --git a/tests/run/fused_cpp.pyx b/tests/run/fused_cpp.pyx --- a/tests/run/fused_cpp.pyx +++ b/tests/run/fused_cpp.pyx @@ -2,6 +2,7 @@ cimport cython from libcpp.vector cimport vector +from libcpp.map cimport map from libcpp.typeinfo cimport type_info from cython.operator cimport typeid @@ -51,3 +52,39 @@ def test_fused_ref(int x): (10, 10) """ return fused_ref(x), fused_ref[int](x) + +ctypedef fused nested_fused: + vector[cython.integral] + +cdef vec_of_fused(nested_fused v): + x = v[0] + return cython.typeof(x) + +def test_nested_fused(): + """ + >>> test_nested_fused() + int + long + """ + cdef vector[int] vi = [0,1] + cdef vector[long] vl = [0,1] + print vec_of_fused(vi) + print vec_of_fused(vl) + +ctypedef fused nested_fused2: + map[cython.integral, cython.floating] + +cdef map_of_fused(nested_fused2 m): + for pair in m: + return cython.typeof(pair.first), cython.typeof(pair.second) + +def test_nested_fused2(): + """ + >>> test_nested_fused2() + ('int', 'float') + ('long', 'double') + """ + cdef map[int, float] mif = { 0: 0.0 } + cdef map[long, double] mld = { 0: 0.0 } + print map_of_fused(mif) + print map_of_fused(mld)
[BUG] Cannot declare fused type for container whose elements are fused types Declaring a fused type where one element is a `libcpp` container whose elements are fused raises an `AttributeError`. See below for an example. I would have expected the code to compile. ```cython # distutils: language=c++ from libcpp.vector cimport vector ctypedef fused fused_element_type: int long ctypedef fused error: vector[fused_element_type] ``` ``` Error compiling Cython file: ------------------------------------------------------------ ... ctypedef fused fused_element_type: int long ctypedef fused error: ^ ------------------------------------------------------------ /[redacted]/_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a.pyx:11:0: Compiler crash in AnalyseDeclarationsTransform File 'ModuleNode.py', line 124, in analyse_declarations: ModuleNode(_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a.pyx:1:0, full_module_name = '_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a') File 'Nodes.py', line 431, in analyse_declarations: StatListNode(_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a.pyx:3:0) File 'Nodes.py', line 1250, in analyse_declarations: FusedTypeNode(_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a.pyx:11:0, name = 'error', types = [...]/1) File 'Nodes.py', line 1273, in analyse: FusedTypeNode(_cython_magic_8449521bb3abea1d93e6323ea9cb8d1a.pyx:11:0, name = 'error', types = [...]/1) Compiler crash traceback from this point on: File "/[redacted]/site-packages/Cython/Compiler/Nodes.py", line 1273, in analyse return PyrexTypes.FusedType(types, name=self.name) File "/[redacted]/site-packages/Cython/Compiler/PyrexTypes.py", line 1636, in __init__ for subtype in t.types: AttributeError: 'CppClassType' object has no attribute 'types' ``` **Environment** - OS: macOS Monterey 12.3 (M1 chip) - Python version: 3.9.9 (pyenv via brew) - Cython version: 0.29.28
I'm not sure if this should work or not. You should be able to write a function with a templated fused type: ``` cdef f(vector[fused_element_type] vec): ... ``` But I don't know whether a `ctypedef` would work, or whether it should be `ctypedef fused`. Sorry, maybe some context would've been helpful. I'm trying to use fused types of vectors of fused types for some recursive template programming. In the C++ world, tensors are often represented as nested vectors, e.g. a matrix is `vector<vector<double>>`. That's arguably not a great choice (a linearized representation is probably better), but, when working with third-party libraries, it's a representation we're stuck with. In the python world, numpy arrays are the de-facto standard, and I wanted to be able to convert between them. The code at the bottom of this comment does that for nested vectors of doubles using a recursive approach so we don't need different implementations for tensors of different rank. The crux for the templated recursion to work is this fused `ctypedef`. ```cython ctypedef fused vector_or_double: double # vector vector[double] # matrix vector[vector[double]] # rank-3 tensor # Add additional layers for higher-dimensional tensors. ``` But we may also want to convert `int` or `float` tensors, and I tried to replace `double` with `cython.numeric`, giving rise to the original error message. # Full example code ```cython # distutils: language=c++ # cython: boundscheck=False # cython: cdivision=True from libcpp.vector cimport vector import numpy as np cimport cython from cython.operator cimport dereference, preincrement ctypedef fused vector_or_double: double vector[double] vector[vector[double]] # Add additional layers for higher-dimensional tensors. cdef nested_to_ndarray(vector[vector_or_double] nested): """ Convert nested vectors to a numpy array. """ cdef: long size vector[long] shape = vector[long]() double[:] target size = _infer_shape(nested, shape) target = np.empty(size) _recursive_fill(nested, &target[0], size) return np.reshape(target, shape) cdef void _recursive_fill(vector[vector_or_double] source, double* target, long stride): """ Fill nested source vectors into a preallocated target. Args: source: Nested source vectors. target: Pointer to preallocated memory. stride: Stride for preallocated memory. """ stride = stride // source.size() if vector_or_double is double: iterator = source.begin() while iterator != source.end(): target[0] = dereference(iterator) preincrement(iterator) target += 1 else: iterator = source.begin() while iterator != source.end(): _recursive_fill(dereference(iterator), target, stride) preincrement(iterator) target += stride cdef long _infer_shape(vector[vector_or_double] nested, vector[long]& shape): """ Infer the shape of nested vectors. Args: nested: Nested vectors. shape: Shape vector to populate. Returns: size: Total number of elements. """ cdef long size = nested.size() # Push the current dimension. shape.push_back(size) # This is the lowest level or there are no elements. We are done here. if vector_or_double is double or size == 0: return size # Recurse down one level. return size * _infer_shape(nested.at(0), shape) ``` Ok - I follow what you're trying to do. I'm not sure if I'd expect it to work or not, but I can see why it'd be useful. What might work at a guess: go to the first line of the traceback and replace `t.types` (which only works for a first-level fused type) with `t.get_fused_types()` (which should work with any type). Edit: this does work...
2022-04-07T20:56:21Z
[]
[]
cython/cython
4,728
cython__cython-4728
[ "4704" ]
18eb280aa2488ba14889538e157281b4175da25b
diff --git a/Cython/Compiler/Dataclass.py b/Cython/Compiler/Dataclass.py --- a/Cython/Compiler/Dataclass.py +++ b/Cython/Compiler/Dataclass.py @@ -590,7 +590,7 @@ def get_field_type(pos, entry): # try to return PyType_Type. This case should only happen with # attributes defined with cdef so Cython is free to make it's own # decision - s = entry.type.declaration_code("", for_display=1) + s = EncodedString(entry.type.declaration_code("", for_display=1)) return ExprNodes.StringNode(pos, value=s)
diff --git a/tests/run/cdef_class_dataclass.pyx b/tests/run/cdef_class_dataclass.pyx --- a/tests/run/cdef_class_dataclass.pyx +++ b/tests/run/cdef_class_dataclass.pyx @@ -197,12 +197,20 @@ cdef class TestVisibility: 'double' >>> hasattr(inst, "c") True + >>> "d" in TestVisibility.__dataclass_fields__ + True + >>> TestVisibility.__dataclass_fields__["d"].type + 'object' + >>> hasattr(inst, "d") + True """ cdef double a a = 1.0 b: double = 2.0 cdef public double c c = 3.0 + cdef public object d + d = object() @dataclass(frozen=True) cdef class TestFrozen:
[BUG] Compiler crash when adding @dataclass to extension types with public/readonly object fields <!-- **PLEASE READ THIS FIRST:** - DO NOT use the bug and feature tracker for general questions and support requests. Use the `cython-users` mailing list instead. It has a wider audience, so you get more and better answers. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Describe the bug** When adding `@dataclass` to extension types with public/readonly `object` fields, the compiler will crash with the following: ``` Traceback (most recent call last): File "/home/.local/bin/cython", line 33, in <module> sys.exit(load_entry_point('Cython==3.0.0a10', 'console_scripts', 'cython')()) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py", line 713, in setuptools_main return main(command_line = 1) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py", line 731, in main result = compile(sources, options) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py", line 629, in compile return compile_multiple(source, options) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py", line 606, in compile_multiple result = run_pipeline(source, options, context=context) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py", line 504, in run_pipeline err, enddata = Pipeline.run_pipeline(pipeline, source) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Pipeline.py", line 394, in run_pipeline data = run(phase, data) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Pipeline.py", line 371, in run return phase(data) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Pipeline.py", line 52, in generate_pyx_code_stage module_node.process_implementation(options, result) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/ModuleNode.py", line 206, in process_implementation self.generate_c_code(env, options, result) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/ModuleNode.py", line 518, in generate_c_code self.generate_module_init_func(modules[:-1], env, globalstate['init_module']) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/ModuleNode.py", line 3101, in generate_module_init_func self.body.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 355, in generate_execution_code self.body.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 5340, in generate_execution_code self.body.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 355, in generate_execution_code self.body.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 409, in generate_execution_code stat.generate_execution_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 5773, in generate_execution_code self.generate_rhs_evaluation_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Nodes.py", line 6072, in generate_rhs_evaluation_code self.rhs.generate_evaluation_code(code) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/ExprNodes.py", line 1806, in generate_evaluation_code self.result_code = code.get_py_string_const( File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Code.py", line 1948, in get_py_string_const return self.globalstate.get_py_string_const( File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Code.py", line 1389, in get_py_string_const c_string = self.get_string_const(text) File "/home/.local/lib/python3.10/site-packages/Cython/Compiler/Code.py", line 1360, in get_string_const if text.is_unicode: AttributeError: 'str' object has no attribute 'is_unicode' ``` **To Reproduce** This compiles and works fine: ```cython from cython.dataclasses cimport dataclass @dataclass cdef class Foo: cdef public int bar ``` Also works with other common types like `str`, `float`, `tuple`. This does not compile: ```cython from cython.dataclasses cimport dataclass @dataclass cdef class Foo: cdef public object bar ``` Also does not work with `bint` **Environment (please complete the following information):** - OS: Linux - Python version: 3.10.3 - Cython version: [c23195ddc3bf4c139e85439c06de9b87c7bc752c](https://github.com/cython/cython/tree/c23195ddc3bf4c139e85439c06de9b87c7bc752c)
2022-04-09T13:28:37Z
[]
[]
cython/cython
4,749
cython__cython-4749
[ "3558" ]
fe98838ca28dff29d6b6d8c074c43290c9554ead
diff --git a/Cython/Compiler/Code.py b/Cython/Compiler/Code.py --- a/Cython/Compiler/Code.py +++ b/Cython/Compiler/Code.py @@ -2407,8 +2407,8 @@ def put_setup_refcount_context(self, name, acquire_gil=False): UtilityCode.load_cached("ForceInitThreads", "ModuleSetupCode.c")) self.putln('__Pyx_RefNannySetupContext("%s", %d);' % (name, acquire_gil and 1 or 0)) - def put_finish_refcount_context(self): - self.putln("__Pyx_RefNannyFinishContext();") + def put_finish_refcount_context(self, nogil=False): + self.putln("__Pyx_RefNannyFinishContextNogil()" if nogil else "__Pyx_RefNannyFinishContext();") def put_add_traceback(self, qualified_name, include_cline=True): """ diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -1862,11 +1862,12 @@ def generate_function_definitions(self, env, code): use_refnanny = not lenv.nogil or lenv.has_with_gil_block + gilstate_decl = None if acquire_gil or acquire_gil_for_var_decls_only: code.put_ensure_gil() code.funcstate.gil_owned = True - elif lenv.nogil and lenv.has_with_gil_block: - code.declare_gilstate() + else: + gilstate_decl = code.insertion_point() if profile or linetrace: if not self.is_generator: @@ -1989,6 +1990,19 @@ def generate_function_definitions(self, env, code): code.putln("") code.putln("/* function exit code */") + gil_owned = { + 'success': code.funcstate.gil_owned, + 'error': code.funcstate.gil_owned, + 'gil_state_declared': gilstate_decl is None, + } + def assure_gil(code_path): + if not gil_owned[code_path]: + if not gil_owned['gil_state_declared']: + gilstate_decl.declare_gilstate() + gil_owned['gil_state_declared'] = True + code.put_ensure_gil(declare_gilstate=False) + gil_owned[code_path] = True + # ----- Default return value if not self.body.is_terminator: if self.return_type.is_pyobject: @@ -1996,8 +2010,10 @@ def generate_function_definitions(self, env, code): # lhs = "(PyObject *)%s" % Naming.retval_cname #else: lhs = Naming.retval_cname + assure_gil('success') code.put_init_to_py_none(lhs, self.return_type) - else: + elif not self.return_type.is_memoryviewslice: + # memory view structs receive their default value on initialisation val = self.return_type.default_value if val: code.putln("%s = %s;" % (Naming.retval_cname, val)) @@ -2019,6 +2035,7 @@ def generate_function_definitions(self, env, code): code.globalstate.use_utility_code(restore_exception_utility_code) code.putln("{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;") code.putln("__Pyx_PyThreadState_declare") + assure_gil('error') code.putln("__Pyx_PyThreadState_assign") code.putln("__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);") for entry in used_buffer_entries: @@ -2038,20 +2055,14 @@ def generate_function_definitions(self, env, code): # code.globalstate.use_utility_code(get_exception_tuple_utility_code) # code.put_trace_exception() - if lenv.nogil and not lenv.has_with_gil_block: - code.putln("{") - code.put_ensure_gil() - + assure_gil('error') code.put_add_traceback(self.entry.qualified_name) - - if lenv.nogil and not lenv.has_with_gil_block: - code.put_release_ensured_gil() - code.putln("}") else: warning(self.entry.pos, "Unraisable exception in function '%s'." % self.entry.qualified_name, 0) - code.put_unraisable(self.entry.qualified_name, lenv.nogil) + assure_gil('error') + code.put_unraisable(self.entry.qualified_name) default_retval = self.return_type.default_value if err_val is None and default_retval: err_val = default_retval @@ -2062,19 +2073,33 @@ def generate_function_definitions(self, env, code): code.putln("__Pyx_pretend_to_initialize(&%s);" % Naming.retval_cname) if is_getbuffer_slot: + assure_gil('error') self.getbuffer_error_cleanup(code) # If we are using the non-error cleanup section we should # jump past it if we have an error. The if-test below determine # whether this section is used. if buffers_present or is_getbuffer_slot or self.return_type.is_memoryviewslice: + # In the buffer cases, we already called assure_gil('error') and own the GIL. + assert gil_owned['error'] or self.return_type.is_memoryviewslice code.put_goto(code.return_from_error_cleanup_label) + else: + # align error and success GIL state + if gil_owned['success']: + assure_gil('error') + elif gil_owned['error']: + code.put_release_ensured_gil() + gil_owned['error'] = False # ----- Non-error return cleanup code.put_label(code.return_label) + assert gil_owned['error'] == gil_owned['success'], "%s != %s" % (gil_owned['error'], gil_owned['success']) + for entry in used_buffer_entries: + assure_gil('success') Buffer.put_release_buffer_code(code, entry) if is_getbuffer_slot: + assure_gil('success') self.getbuffer_normal_cleanup(code) if self.return_type.is_memoryviewslice: @@ -2084,17 +2109,22 @@ def generate_function_definitions(self, env, code): cond = code.unlikely(self.return_type.error_condition(Naming.retval_cname)) code.putln( 'if (%s) {' % cond) - if env.nogil: + if not gil_owned['success']: code.put_ensure_gil() code.putln( 'PyErr_SetString(PyExc_TypeError, "Memoryview return value is not initialized");') - if env.nogil: + if not gil_owned['success']: code.put_release_ensured_gil() code.putln( '}') # ----- Return cleanup for both error and no-error return - code.put_label(code.return_from_error_cleanup_label) + if code.label_used(code.return_from_error_cleanup_label): + # If we came through the success path, then we took the same GIL decisions as for jumping here. + # If we came through the error path and did not jump, then we aligned both paths above. + # In the end, all paths are aligned from this point on. + assert gil_owned['error'] == gil_owned['success'], "%s != %s" % (gil_owned['error'], gil_owned['success']) + code.put_label(code.return_from_error_cleanup_label) for entry in lenv.var_entries: if not entry.used or entry.in_closure: @@ -2121,6 +2151,7 @@ def generate_function_definitions(self, env, code): code.put_xdecref_memoryviewslice(entry.cname, have_gil=not lenv.nogil) if self.needs_closure: + assure_gil('success') code.put_decref(Naming.cur_scope_cname, lenv.scope_class.type) # ----- Return @@ -2136,6 +2167,7 @@ def generate_function_definitions(self, env, code): if self.entry.is_special and self.entry.name == "__hash__": # Returning -1 for __hash__ is supposed to signal an error # We do as Python instances and coerce -1 into -2. + assure_gil('success') code.putln("if (unlikely(%s == -1) && !PyErr_Occurred()) %s = -2;" % ( Naming.retval_cname, Naming.retval_cname)) @@ -2145,16 +2177,16 @@ def generate_function_definitions(self, env, code): # generators are traced when iterated, not at creation if self.return_type.is_pyobject: code.put_trace_return( - Naming.retval_cname, nogil=not code.funcstate.gil_owned) + Naming.retval_cname, nogil=not gil_owned['success']) else: code.put_trace_return( - "Py_None", nogil=not code.funcstate.gil_owned) + "Py_None", nogil=not gil_owned['success']) if not lenv.nogil: # GIL holding function - code.put_finish_refcount_context() + code.put_finish_refcount_context(nogil=not gil_owned['success']) - if acquire_gil or (lenv.nogil and lenv.has_with_gil_block): + if acquire_gil or (lenv.nogil and gil_owned['success']): # release the GIL (note that with-gil blocks acquire it on exit in their EnsureGILNode) code.put_release_ensured_gil() code.funcstate.gil_owned = False diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -1859,19 +1859,6 @@ def _create_fused_function(self, env, node): return node - def _handle_nogil_cleanup(self, lenv, node): - "Handle cleanup for 'with gil' blocks in nogil functions." - if lenv.nogil and lenv.has_with_gil_block: - # Acquire the GIL for cleanup in 'nogil' functions, by wrapping - # the entire function body in try/finally. - # The corresponding release will be taken care of by - # Nodes.FuncDefNode.generate_function_definitions() - node.body = Nodes.NogilTryFinallyStatNode( - node.body.pos, - body=node.body, - finally_clause=Nodes.EnsureGILNode(node.body.pos), - finally_except_clause=Nodes.EnsureGILNode(node.body.pos)) - def _handle_fused(self, node): if node.is_generator and node.has_fused_arguments: node.has_fused_arguments = False @@ -1912,7 +1899,6 @@ def visit_FuncDefNode(self, node): node = self._create_fused_function(env, node) else: node.body.analyse_declarations(lenv) - self._handle_nogil_cleanup(lenv, node) self._super_visit_FuncDefNode(node) self.seen_vars_stack.pop()
diff --git a/tests/run/trace_nogil.pyx b/tests/run/trace_nogil.pyx new file mode 100644 --- /dev/null +++ b/tests/run/trace_nogil.pyx @@ -0,0 +1,22 @@ +# cython: linetrace=True + +cdef void foo(int err) nogil except *: + with gil: + raise ValueError(err) + + +# Test from gh-4637 +def handler(int err): + """ + >>> handler(0) + All good + >>> handler(1) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + ValueError: 1 + """ + if (err % 2): + with nogil: + foo(err) + else: + print("All good")
Broken scikit-image build with 3.0a3 : redeclaration of ‘__pyx_gilstate_save’ with no linkage The scikit-image `pre` builds is broken since Cython 3.0a3 was released yesterday. The error is as follows: ``` skimage/graph/heap.c: In function ‘__pyx_f_7skimage_5graph_4heap_10BinaryHeap__add_or_remove_level’: skimage/graph/heap.c:3299:20: error: redeclaration of ‘__pyx_gilstate_save’ with no linkage PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); ^~~~~~~~~~~~~~~~~~~ skimage/graph/heap.c:3296:20: note: previous declaration of ‘__pyx_gilstate_save’ was here PyGILState_STATE __pyx_gilstate_save; ^~~~~~~~~~~~~~~~~~~ ``` corresponding to this part of `heap.pyx` (https://github.com/scikit-image/scikit-image/blob/master/skimage/graph/heap.pyx#L190) ``` cdef void _add_or_remove_level(self, LEVELS_T add_or_remove) nogil: # init indexing ints cdef INDEX_T i, i1, i2, n # new amount of levels cdef LEVELS_T new_levels = self.levels + add_or_remove # allocate new arrays cdef INDEX_T number = 2**new_levels cdef VALUE_T *values cdef REFERENCE_T *references values = <VALUE_T *>malloc(number * 2 * sizeof(VALUE_T)) references = <REFERENCE_T *>malloc(number * sizeof(REFERENCE_T)) if values is NULL or references is NULL: free(values) free(references) with gil: raise MemoryError() ``` When I compare the generated C code with 3.0a1 and 3.0a2, only these part changed 3.0a1 ``` #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif ``` and 3.0a3 ``` #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save; #endif #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif ``` so indeed `__pyx_gilstate_save` is defined twice. Any advice about what is going on will be much appreciated :-). If it helps, here is a bit more of the C code (for 3.0a3): ``` static void __pyx_f_7skimage_5graph_4heap_10BinaryHeap__add_or_remove_level(struct __pyx_obj_7skimage_5graph_4heap_BinaryHeap *__pyx_v_self, __pyx_t_7skimage_5graph_4heap_LEVELS_T __pyx_v_add_or_remove) { __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_v_i; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_v_i1; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_v_i2; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_v_n; __pyx_t_7skimage_5graph_4heap_LEVELS_T __pyx_v_new_levels; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_v_number; __pyx_t_7skimage_5graph_4heap_VALUE_T *__pyx_v_values; __pyx_t_7skimage_5graph_4heap_REFERENCE_T *__pyx_v_references; __pyx_t_7skimage_5graph_4heap_VALUE_T *__pyx_v_old_values; __pyx_t_7skimage_5graph_4heap_REFERENCE_T *__pyx_v_old_references; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_t_3; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_t_4; __pyx_t_7skimage_5graph_4heap_INDEX_T __pyx_t_5; __pyx_t_7skimage_5graph_4heap_VALUE_T *__pyx_t_6; __pyx_t_7skimage_5graph_4heap_REFERENCE_T *__pyx_t_7; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save; #endif #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_add_or_remove_level", 0); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif ```
2022-04-18T21:16:57Z
[]
[]
cython/cython
4,812
cython__cython-4812
[ "4447" ]
918f78228b87c2d56f67b4fc634393fc3b8d2586
diff --git a/Cython/Compiler/FlowControl.py b/Cython/Compiler/FlowControl.py --- a/Cython/Compiler/FlowControl.py +++ b/Cython/Compiler/FlowControl.py @@ -589,7 +589,8 @@ def check_definitions(flow, compiler_directives): for node, entry in references.items(): if Uninitialized in node.cf_state: node.cf_maybe_null = True - if not entry.from_closure and len(node.cf_state) == 1: + if (not entry.from_closure and len(node.cf_state) == 1 + and entry.name not in entry.scope.scope_predefined_names): node.cf_is_null = True if (node.allow_null or entry.from_closure or entry.is_pyclass_attr or entry.type.is_error): diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -2662,6 +2662,9 @@ class CalculateQualifiedNamesTransform(EnvTransform): Calculate and store the '__qualname__' and the global module name on some nodes. """ + needs_qualname_assignment = False + needs_module_assignment = False + def visit_ModuleNode(self, node): self.module_name = self.global_scope().qualified_name self.qualified_name = [] @@ -2732,13 +2735,55 @@ def visit_FuncDefNode(self, node): self.qualified_name = orig_qualified_name return node + def generate_assignment(self, node, name, value): + entry = node.scope.lookup_here(name) + lhs = ExprNodes.NameNode( + node.pos, + name = EncodedString(name), + entry=entry) + rhs = ExprNodes.StringNode( + node.pos, + value=value.as_utf8_string(), + unicode_value=value) + node.body.stats.insert(0, Nodes.SingleAssignmentNode( + node.pos, + lhs=lhs, + rhs=rhs, + ).analyse_expressions(self.current_env())) + def visit_ClassDefNode(self, node): + orig_needs_qualname_assignment = self.needs_qualname_assignment + self.needs_qualname_assignment = False + orig_needs_module_assignment = self.needs_module_assignment + self.needs_module_assignment = False orig_qualified_name = self.qualified_name[:] entry = (getattr(node, 'entry', None) or # PyClass self.current_env().lookup_here(node.target.name)) # CClass self._append_entry(entry) self._super_visit_ClassDefNode(node) + if self.needs_qualname_assignment: + self.generate_assignment(node, "__qualname__", + EncodedString(".".join(self.qualified_name))) + if self.needs_module_assignment: + self.generate_assignment(node, "__module__", + EncodedString(self.module_name)) self.qualified_name = orig_qualified_name + self.needs_qualname_assignment = orig_needs_qualname_assignment + self.needs_module_assignment = orig_needs_module_assignment + return node + + def visit_NameNode(self, node): + scope = self.current_env() + if scope.is_c_class_scope: + # unlike for a PyClass scope, these attributes aren't defined in the + # dictionary when the class definition is executed, therefore we ask + # the compiler to generate an assignment to them at the start of the + # body. + # NOTE: this doesn't put them in locals() + if node.name == "__qualname__": + self.needs_qualname_assignment = True + elif node.name == "__module__": + self.needs_module_assignment = True return node diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -732,9 +732,9 @@ def attributes_known(self): self.scope = scope = Symtab.CClassScope( 'mvs_class_'+self.specialization_suffix(), None, - visibility='extern') + visibility='extern', + parent_type=self) - scope.parent_type = self scope.directives = {} scope.declare_var('_data', c_char_ptr_type, None, @@ -1729,8 +1729,9 @@ def attributes_known(self): if self.scope is None: from . import Symtab # FIXME: fake C scope, might be better represented by a struct or C++ class scope - self.scope = scope = Symtab.CClassScope('', None, visibility="extern") - scope.parent_type = self + self.scope = scope = Symtab.CClassScope( + '', None, visibility="extern", parent_type=self + ) scope.directives = {} scope.declare_var("ndim", c_long_type, pos=None, cname="value", is_cdef=True) @@ -1982,8 +1983,8 @@ def attributes_known(self): self.scope = scope = Symtab.CClassScope( '', None, - visibility="extern") - scope.parent_type = self + visibility="extern", + parent_type=self) scope.directives = {} scope.declare_cfunction( "conjugate", @@ -2437,8 +2438,8 @@ def attributes_known(self): self.scope = scope = Symtab.CClassScope( '', None, - visibility="extern") - scope.parent_type = self + visibility="extern", + parent_type=self) scope.directives = {} scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True) scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True) diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -357,6 +357,8 @@ class Scope(object): # directives dict Helper variable for the recursive # analysis, contains directive values. # is_internal boolean Is only used internally (simpler setup) + # scope_predefined_names list of str Class variable containing special names defined by + # this type of scope (e.g. __builtins__, __qualname__) is_builtin_scope = 0 is_py_class_scope = 0 @@ -376,6 +378,7 @@ class Scope(object): nogil = 0 fused_to_specific = None return_type = None + scope_predefined_names = [] # Do ambiguous type names like 'int' and 'float' refer to the C types? (Otherwise, Python types.) in_c_type_context = True @@ -412,6 +415,8 @@ def __init__(self, name, outer_scope, parent_scope): self.buffer_entries = [] self.lambda_defs = [] self.id_counters = {} + for var_name in self.scope_predefined_names: + self.declare_var(EncodedString(var_name), py_object_type, pos=None) def __deepcopy__(self, memo): return self @@ -1208,7 +1213,7 @@ def declare_builtin_type(self, name, cname, utility_code=None, objstruct_cname=None, type_class=PyrexTypes.BuiltinObjectType): name = EncodedString(name) type = type_class(name, cname, objstruct_cname) - scope = CClassScope(name, outer_scope=None, visibility='extern') + scope = CClassScope(name, outer_scope=None, visibility='extern', parent_type=type) scope.directives = {} if name == 'bool': type.is_final_type = True @@ -1270,6 +1275,10 @@ class ModuleScope(Scope): has_import_star = 0 is_cython_builtin = 0 old_style_globals = 0 + scope_predefined_names = [ + '__builtins__', '__name__', '__file__', '__doc__', '__path__', + '__spec__', '__loader__', '__package__', '__cached__', + ] def __init__(self, name, parent_module, context, is_package=False): from . import Builtin @@ -1298,9 +1307,6 @@ def __init__(self, name, parent_module, context, is_package=False): self.undeclared_cached_builtins = [] self.namespace_cname = self.module_cname self._cached_tuple_types = {} - for var_name in ['__builtins__', '__name__', '__file__', '__doc__', '__path__', - '__spec__', '__loader__', '__package__', '__cached__']: - self.declare_var(EncodedString(var_name), py_object_type, None) self.process_include(Code.IncludeCode("Python.h", initial=True)) def qualifying_scope(self): @@ -1688,7 +1694,8 @@ def declare_c_class(self, name, pos, defining=0, implementing=0, if not type.scope: if defining or implementing: scope = CClassScope(name = name, outer_scope = self, - visibility = visibility) + visibility=visibility, + parent_type=type) scope.directives = self.directives.copy() if base_type and base_type.scope: scope.declare_inherited_c_attributes(base_type.scope) @@ -2143,6 +2150,8 @@ class ClassScope(Scope): # declared in the class # doc string or None Doc string + scope_predefined_names = ['__module__', '__qualname__'] + def mangle_class_private_name(self, name): # a few utilitycode names need to specifically be ignored if name and name.lower().startswith("__pyx_"): @@ -2252,13 +2261,21 @@ class CClassScope(ClassScope): defined = False implemented = False - def __init__(self, name, outer_scope, visibility): + def __init__(self, name, outer_scope, visibility, parent_type): ClassScope.__init__(self, name, outer_scope) if visibility != 'extern': self.method_table_cname = outer_scope.mangle(Naming.methtab_prefix, name) self.getset_table_cname = outer_scope.mangle(Naming.gstab_prefix, name) self.property_entries = [] self.inherited_var_entries = [] + self.parent_type = parent_type + # Usually parent_type will be an extension type and so the typeptr_cname + # can be used to calculate the namespace_cname. Occassionally other types + # are used (e.g. numeric/complex types) and in these cases the typeptr + # isn't relevant. + if ((parent_type.is_builtin_type or parent_type.is_extension_type) + and parent_type.typeptr_cname): + self.namespace_cname = "(PyObject *)%s" % parent_type.typeptr_cname def needs_gc(self): # If the type or any of its base types have Python-valued @@ -2412,7 +2429,6 @@ def declare_var(self, name, type, pos, # xxx: is_pyglobal changes behaviour in so many places that I keep it in for now. # is_member should be enough later on entry.is_pyglobal = 1 - self.namespace_cname = "(PyObject *)%s" % self.parent_type.typeptr_cname return entry
diff --git a/tests/run/qualname.py b/tests/run/qualname.py new file mode 100644 --- /dev/null +++ b/tests/run/qualname.py @@ -0,0 +1,157 @@ +# cython: binding=True +# mode: run +# tag: cyfunction, qualname, pure3.5 + +from __future__ import print_function + +import cython +import sys + + +def test_qualname(): + """ + >>> test_qualname.__qualname__ + 'test_qualname' + >>> test_qualname.__qualname__ = 123 #doctest:+ELLIPSIS + Traceback (most recent call last): + TypeError: __qualname__ must be set to a ... object + >>> test_qualname.__qualname__ = 'foo' + >>> test_qualname.__qualname__ + 'foo' + """ + + +def test_builtin_qualname(): + """ + >>> test_builtin_qualname() + list.append + len + """ + if sys.version_info >= (3, 3): + print([1, 2, 3].append.__qualname__) + print(len.__qualname__) + else: + print('list.append') + print('len') + + +def test_nested_qualname(): + """ + >>> outer, lambda_func, XYZ = test_nested_qualname() + defining class XYZ XYZ qualname + defining class Inner XYZ.Inner qualname + + >>> outer_result = outer() + defining class Test test_nested_qualname.<locals>.outer.<locals>.Test qualname + >>> outer_result.__qualname__ + 'test_nested_qualname.<locals>.outer.<locals>.Test' + >>> outer_result.test.__qualname__ + 'test_nested_qualname.<locals>.outer.<locals>.Test.test' + + >>> outer_result().test.__qualname__ + 'test_nested_qualname.<locals>.outer.<locals>.Test.test' + + >>> outer_result_test_result = outer_result().test() + defining class XYZInner XYZinner qualname + >>> outer_result_test_result.__qualname__ + 'XYZinner' + >>> outer_result_test_result.Inner.__qualname__ + 'XYZinner.Inner' + >>> outer_result_test_result.Inner.inner.__qualname__ + 'XYZinner.Inner.inner' + + >>> lambda_func.__qualname__ + 'test_nested_qualname.<locals>.<lambda>' + + >>> XYZ.__qualname__ + 'XYZ' + >>> XYZ.Inner.__qualname__ + 'XYZ.Inner' + >>> XYZ.Inner.inner.__qualname__ + 'XYZ.Inner.inner' + """ + def outer(): + class Test(object): + print("defining class Test", __qualname__, __module__) + def test(self): + global XYZinner + class XYZinner: + print("defining class XYZInner", __qualname__, __module__) + class Inner: + def inner(self): + pass + + return XYZinner + return Test + + global XYZ + class XYZ(object): + print("defining class XYZ", __qualname__, __module__) + class Inner(object): + print("defining class Inner", __qualname__, __module__) + def inner(self): + pass + + return outer, lambda:None, XYZ + + [email protected] +class CdefClass: + """ + >>> print(CdefClass.qn, CdefClass.m) + CdefClass qualname + >>> print(CdefClass.__qualname__, CdefClass.__module__) + CdefClass qualname + + #>>> print(CdefClass.l["__qualname__"], CdefClass.l["__module__"]) + #CdefClass qualname + """ + qn = __qualname__ + m = __module__ + + # TODO - locals and cdef classes is unreliable, irrespective of qualname + # l = locals().copy() + + +# TODO - locals and cdef classes is unreliable, irrespective of qualname +#@cython.cclass +#class CdefOnlyLocals: +# """ +# >>> print(CdefOnlyLocals.l["__qualname__"], CdefOnlyLocals.l["__module__"]) +# CdefOnlyLocals qualname +# """ +# l = locals().copy() + [email protected] +class CdefModifyNames: + """ + >>> print(CdefModifyNames.qn_reassigned, CdefModifyNames.m_reassigned) + I'm not a qualname I'm not a module + + # TODO - enable when https://github.com/cython/cython/issues/4815 is fixed + #>>> hasattr(CdefModifyNames, "qn_deleted") + #False + #>>> hasattr(CdefModifyNames, "m_deleted") + #False + + #>>> print(CdefModifyNames.l["__qualname__"], CdefModifyNames.l["__module__"]) + #I'm not a qualname I'm not a module + """ + __qualname__ = "I'm not a qualname" + __module__ = "I'm not a module" + qn_reassigned = __qualname__ + m_reassigned = __module__ + # TODO - locals and cdef classes is unreliable, irrespective of qualname + #l = locals().copy() + # TODO del inside cdef class scope is broken + # https://github.com/cython/cython/issues/4815 + #del __qualname__ + #del __module__ + #try: + # qn_deleted = __qualname__ + #except NameError: + # pass + #try: + # m_deleted = __module__ + #except NameError: + # pass diff --git a/tests/run/qualname.pyx b/tests/run/qualname.pyx deleted file mode 100644 --- a/tests/run/qualname.pyx +++ /dev/null @@ -1,81 +0,0 @@ -# cython: binding=True -# mode: run -# tag: cyfunction,qualname - -import sys - - -def test_qualname(): - """ - >>> test_qualname.__qualname__ - 'test_qualname' - >>> test_qualname.__qualname__ = 123 #doctest:+ELLIPSIS - Traceback (most recent call last): - TypeError: __qualname__ must be set to a ... object - >>> test_qualname.__qualname__ = 'foo' - >>> test_qualname.__qualname__ - 'foo' - """ - - -def test_builtin_qualname(): - """ - >>> test_builtin_qualname() - list.append - len - """ - if sys.version_info >= (3, 3): - print([1, 2, 3].append.__qualname__) - print(len.__qualname__) - else: - print('list.append') - print('len') - - -def test_nested_qualname(): - """ - >>> outer, lambda_func, XYZ = test_nested_qualname() - - >>> outer().__qualname__ - 'test_nested_qualname.<locals>.outer.<locals>.Test' - >>> outer().test.__qualname__ - 'test_nested_qualname.<locals>.outer.<locals>.Test.test' - >>> outer()().test.__qualname__ - 'test_nested_qualname.<locals>.outer.<locals>.Test.test' - - >>> outer()().test().__qualname__ - 'XYZinner' - >>> outer()().test().Inner.__qualname__ - 'XYZinner.Inner' - >>> outer()().test().Inner.inner.__qualname__ - 'XYZinner.Inner.inner' - - >>> lambda_func.__qualname__ - 'test_nested_qualname.<locals>.<lambda>' - - >>> XYZ.__qualname__ - 'XYZ' - >>> XYZ.Inner.__qualname__ - 'XYZ.Inner' - >>> XYZ.Inner.inner.__qualname__ - 'XYZ.Inner.inner' - """ - def outer(): - class Test(object): - def test(self): - global XYZinner - class XYZinner: - class Inner: - def inner(self): - pass - - return XYZinner - return Test - - global XYZ - class XYZ(object): - class Inner(object): - def inner(self): - pass - - return outer, lambda:None, XYZ
[bug] __qualname__ unavailable at class scope I'm here because support for `__qualname__` is missing in Cython when used with Python 3 (3.8.9, for sure), while running the code natively works properly. E.g.: ``` #!/usr/bin/env python3 #cython: language_level=3 class foo(): print(" __name__ =", __name__) print("__qualname__ =", __qualname__) class bar(): print(" __name__ =", __name__) print("__qualname__ =", __qualname__) ``` yields this compilation error: ``` debugCython2.pyx:7:28: undeclared name not builtin: __qualname__ ``` instead of: ``` __name__ = __main__ __qualname__ = foo __name__ = __main__ __qualname__ = bar ``` _Originally posted by @RichardFoo in https://github.com/cython/cython/issues/2773#issuecomment-960363677_ Version ---------- Python 3.8.12 Current Cython master Notes -------- `foo.__qualname__` is set correctly, but unqualified `__qualname__` is not looked up right when evaluating the class body
Thanks for the clarification / bug report and quick response. Apparently, I'm very alone in this usage of `__qualname__` since it hasn't been reported before now, but I find it extremely handy (e.g., classes self-registering for callbacks automatically when their module is included). Here's to hoping the fix is easy and finds its way into the next release cycle. It's probably just a case of declaring `__qualname__` in the class scope in the same way that `__name__` etc are declared in the module scope - https://github.com/cython/cython/blob/b5f81f5e900922356ee7aeedf78a54fa96f85c71/Cython/Compiler/Symtab.py#L1272-L1274 I've poked around the Symtab.py file, and while this may be simple for a project maintainer it's much less obvious to an outsider where this fix needs to be applied. There seems to be a base ClassScope object, plus derivatives for Python, C, and C++. None of them have a structure similar to the referenced ModuleScope that might be an obvious place to tweak. Are you suggesting that in, say PyClassScope, an init() should be created with the command `self.declare_var(EncodedString('__qualname__'), py_object_type, None)` What would it take to get this "quick fix" some attention? I'm not above bribery. ;-) I had a go at the quick fix near the time this was reported and couldn't easily make it work so it's probably a little more complicated than I originally thought. I doubt it's impossible of course, but at the time the difficulty seemed higher than my level of interest in it.
2022-05-28T11:43:04Z
[]
[]
cython/cython
4,864
cython__cython-4864
[ "4861" ]
9fb8fae9295a9fa689bfe54a00f1f39642822d7c
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -8482,7 +8482,7 @@ def __init__(self, pos, args, type): if type in (list_type, tuple_type) and args and args[0].is_sequence_constructor: # construct a list directly from the first argument that we can then extend if args[0].type is not list_type: - args[0] = ListNode(args[0].pos, args=args[0].args, is_temp=True) + args[0] = ListNode(args[0].pos, args=args[0].args, is_temp=True, mult_factor=args[0].mult_factor) ExprNode.__init__(self, pos, args=args, type=type) def calculate_constant_result(self):
diff --git a/tests/run/pep448_extended_unpacking.pyx b/tests/run/pep448_extended_unpacking.pyx --- a/tests/run/pep448_extended_unpacking.pyx +++ b/tests/run/pep448_extended_unpacking.pyx @@ -185,6 +185,24 @@ def unpack_list_literal_mult(): return [*([1, 2, *([4, 5] * 2)] * 3)] +def unpack_list_tuple_mult(): + """ + >>> unpack_list_tuple_mult() + [1, 1] + """ + return [*(1,) * 2] + + +def unpack_list_tuple_bad_mult(): + """ + >>> unpack_list_tuple_bad_mult() + Traceback (most recent call last): + ... + TypeError: can't multiply sequence by non-int of type 'float' + """ + return [*(1,) * 1.5] + + @cython.test_fail_if_path_exists( "//ListNode//ListNode", "//MergedSequenceNode",
[BUG] Broken tuple multiplication behavior <!-- **PLEASE READ THIS FIRST:** - DO NOT use the bug and feature tracker for general questions and support requests. Use the `cython-users` mailing list instead. It has a wider audience, so you get more and better answers. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Describe the bug** Tuple multiplication doesn't work correctly while it is unpacked into list. It produces list with only one copy of initial tuple and also doesn't throw exception when multiplier is of float type. **To Reproduce** Code to reproduce the behaviour: ```cython [*(1,) * 1] # [1,] [*(1,) * 2] # [1,] [*(1,) * 3] # [1,] [*(1,) * 1.5] # [1,] ``` **Expected behavior** It is expected to work identically to multiplication of lists which works fine in cython: ```cython [*[1,] * 1] # [1,] [*[1,] * 2] # [1, 1] [*[1,] * 3] # [1, 1, 1] [*[1,] * 1.5] # TypeError: can't multiply sequence by non-int of type 'float' ``` **Environment (please complete the following information):** - OS: Linux, Ubuntu 20.04.3 LTS - Python version 3.9.5 - Cython version 0.29.30
2022-06-25T14:59:05Z
[]
[]
cython/cython
4,877
cython__cython-4877
[ "2732" ]
ac56a661b6d670b69f24fb92408dd852a583b08d
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -2787,6 +2787,12 @@ def from_py_call_code(self, source_code, result_code, error_pos, code, source_code, result_code, self.size) return code.error_goto_if_neg(call_code, error_pos) + def error_condition(self, result_code): + # It isn't possible to use CArrays as return type so the error_condition + # is irrelevant. Returning a falsy value does avoid an error when getting + # from_py_call_code from a typedef. + return "" + class CPtrType(CPointerBaseType): # base_type CType Reference type @@ -4257,6 +4263,25 @@ def create_from_py_utility_code(self, env): def create_to_py_utility_code(self, env): if self.to_py_function is not None: return True + if self.entry.create_wrapper: + from .UtilityCode import CythonUtilityCode + self.to_py_function = "__Pyx_Enum_%s_to_py" % self.name + if self.entry.scope != env.global_scope(): + module_name = self.entry.scope.qualified_name + else: + module_name = None + env.use_utility_code(CythonUtilityCode.load( + "EnumTypeToPy", "CpdefEnums.pyx", + context={"funcname": self.to_py_function, + "name": self.name, + "items": tuple(self.values), + "underlying_type": self.underlying_type.empty_declaration_code(), + "module_name": module_name, + "is_flag": False, + }, + outer_module_scope=self.entry.scope # ensure that "name" is findable + )) + return True if self.underlying_type.create_to_py_utility_code(env): # Using a C++11 lambda here, which is fine since # scoped enums are a C++11 feature @@ -4383,15 +4408,47 @@ def specialize(self, values): def create_type_wrapper(self, env): from .UtilityCode import CythonUtilityCode + # Generate "int"-like conversion function + old_to_py_function = self.to_py_function + self.to_py_function = None + CIntLike.create_to_py_utility_code(self, env) + enum_to_pyint_func = self.to_py_function + self.to_py_function = old_to_py_function # we don't actually want to overwrite this + env.use_utility_code(CythonUtilityCode.load( "EnumType", "CpdefEnums.pyx", context={"name": self.name, "items": tuple(self.values), "enum_doc": self.doc, + "enum_to_pyint_func": enum_to_pyint_func, "static_modname": env.qualified_name, }, outer_module_scope=env.global_scope())) + def create_to_py_utility_code(self, env): + if self.to_py_function is not None: + return self.to_py_function + if not self.entry.create_wrapper: + return super(CEnumType, self).create_to_py_utility_code(env) + from .UtilityCode import CythonUtilityCode + self.to_py_function = "__Pyx_Enum_%s_to_py" % self.name + if self.entry.scope != env.global_scope(): + module_name = self.entry.scope.qualified_name + else: + module_name = None + env.use_utility_code(CythonUtilityCode.load( + "EnumTypeToPy", "CpdefEnums.pyx", + context={"funcname": self.to_py_function, + "name": self.name, + "items": tuple(self.values), + "underlying_type": "int", + "module_name": module_name, + "is_flag": True, + }, + outer_module_scope=self.entry.scope # ensure that "name" is findable + )) + return True + class CTupleType(CType): # components [PyrexType] diff --git a/Cython/Compiler/UtilityCode.py b/Cython/Compiler/UtilityCode.py --- a/Cython/Compiler/UtilityCode.py +++ b/Cython/Compiler/UtilityCode.py @@ -173,8 +173,15 @@ def scope_transform(module_node): if self.context_types: # inject types into module scope def scope_transform(module_node): + dummy_entry = object() for name, type in self.context_types.items(): + # Restore the old type entry after declaring the type. + # We need to access types in the scope, but this shouldn't alter the entry + # that is visible from everywhere else + old_type_entry = getattr(type, "entry", dummy_entry) entry = module_node.scope.declare_type(name, type, None, visibility='extern') + if old_type_entry is not dummy_entry: + type.entry = old_type_entry entry.in_cinclude = True return module_node
diff --git a/tests/run/cpdef_enums.pyx b/tests/run/cpdef_enums.pyx --- a/tests/run/cpdef_enums.pyx +++ b/tests/run/cpdef_enums.pyx @@ -132,13 +132,28 @@ def check_docs(): """ pass + +def to_from_py_conversion(PxdEnum val): + """ + >>> to_from_py_conversion(RANK_1) is PxdEnum.RANK_1 + True + + C enums are commonly enough used as flags that it seems reasonable + to allow it in Cython + >>> to_from_py_conversion(RANK_1 | RANK_2) == (RANK_1 | RANK_2) + True + """ + return val + + def test_pickle(): """ >>> from pickle import loads, dumps >>> import sys Pickling enums won't work without the enum module, so disable the test - >>> if sys.version_info < (3, 4): + (now requires 3.6 for IntFlag) + >>> if sys.version_info < (3, 6): ... loads = dumps = lambda x: x >>> loads(dumps(PyxEnum.TWO)) == PyxEnum.TWO True diff --git a/tests/run/cpdef_enums_import.srctree b/tests/run/cpdef_enums_import.srctree --- a/tests/run/cpdef_enums_import.srctree +++ b/tests/run/cpdef_enums_import.srctree @@ -28,13 +28,23 @@ cpdef enum NamedEnumType: cpdef foo() +######## enums_without_pyx.pxd ##### + +cpdef enum EnumTypeNotInPyx: + AnotherEnumValue = 500 + ######## no_enums.pyx ######## from enums cimport * +from enums_without_pyx cimport * def get_named_enum_value(): return NamedEnumType.NamedEnumValue +def get_named_without_pyx(): + # This'll generate a warning but return a c int + return EnumTypeNotInPyx.AnotherEnumValue + ######## import_enums_test.py ######## # We can import enums with a star import. @@ -51,3 +61,6 @@ assert 'FOO' not in dir(no_enums) assert 'foo' not in dir(no_enums) assert no_enums.get_named_enum_value() == NamedEnumType.NamedEnumValue +# In this case the enum isn't accessible from Python (by design) +# but the conversion to Python goes through a reasonable fallback +assert no_enums.get_named_without_pyx() == 500 diff --git a/tests/run/cpdef_scoped_enums.pyx b/tests/run/cpdef_scoped_enums.pyx --- a/tests/run/cpdef_scoped_enums.pyx +++ b/tests/run/cpdef_scoped_enums.pyx @@ -42,6 +42,28 @@ def test_enum_doc(): pass +def to_from_py_conversion(Enum1 val): + """ + >>> to_from_py_conversion(Enum1.Item1) is Enum1.Item1 + True + + Scoped enums should not be used as flags, and therefore attempts to set them + with arbitrary values should fail + >>> to_from_py_conversion(500) + Traceback (most recent call last): + ... + ValueError: 500 is not a valid Enum1 + + # Note that the ability to bitwise-or together the two numbers is inherited + from the Python enum (so not in Cython's remit to prevent) + >>> to_from_py_conversion(Enum1.Item1 | Enum1.Item2) + Traceback (most recent call last): + ... + ValueError: 3 is not a valid Enum1 + """ + return val + + def test_pickle(): """ >>> from pickle import loads, dumps diff --git a/tests/run/cpp_stl_conversion.pyx b/tests/run/cpp_stl_conversion.pyx --- a/tests/run/cpp_stl_conversion.pyx +++ b/tests/run/cpp_stl_conversion.pyx @@ -270,7 +270,7 @@ cpdef enum Color: def test_enum_map(o): """ >>> test_enum_map({RED: GREEN}) - {0: 1} + {<Color.RED: 0>: <Color.GREEN: 1>} """ cdef map[Color, Color] m = o return m
Casting int to cpdef enum Simplified code: ``` cpdef enum MyEnum: MY_VAL=2 def my_fn(): return <MyEnum>2 ``` I'd expect my_fn() to return MyEnum.MY_VAL, but just returns the int value.
Encountered the same thing. FWIW this works: ```cython cpdef enum MyEnum: MY_VAL = 2 def my_fn(): return MyEnum(2) ``` That said, would not have expected needing the explicit construction of `MyEnum`. Guessing there would need to be some alternative handling [here]( https://github.com/cython/cython/blob/796fd06da1fa1d5481ce43a6b6c901bc87f0ce9a/Cython/Compiler/PyrexTypes.py#L495 ) to handle `cpdef enum` types conversion. Noting this in part as that code path seems to be used to generate the `int` coercion C code seen with this example. Maybe this could be done by checking if it is an instance of [`__Pyx_EnumBase`]( https://github.com/cython/cython/blob/efdf996dced075682d86b7e53a12b56b5ebfea38/Cython/Utility/CpdefEnums.pyx#L22 ). What do you think @scoder? 🙂 It is worth noting that using the construction workaround in comment ( https://github.com/cython/cython/issues/2732#issuecomment-1176893773 ) comes with fairly significant overhead. ```cython cpdef enum MyEnum: MY_VAL = 2 def my_fn1(): return MyEnum.MY_VAL def my_fn2(): return MyEnum(MyEnum.MY_VAL) ``` ```python In [3]: %timeit my_fn1() 27.6 ns ± 0.394 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) In [4]: %timeit my_fn2() 398 ns ± 5.33 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each) ``` A more performant approach might be mapping preexisting `MyEnum` Python objects to `MyEnum` C values like so. ```cython cpdef enum MyEnum: ZERO = 0 ONE = 1 cdef inline _convert_MyEnum_c_to_py(MyEnum c_enum): if c_enum == MyEnum.ZERO: return (<object>MyEnum).ZERO elif c_enum == MyEnum.ONE: return (<object>MyEnum).ONE else: raise ValueError(f"Unknown `MyEnum` value: {c_enum}") def my_fn1(): cdef MyEnum c_enum = MyEnum.ONE cdef object py_enum = <object>c_enum return py_enum def my_fn2(): cdef MyEnum c_enum = MyEnum.ONE cdef object py_enum = _convert_MyEnum_c_to_py(c_enum) return py_enum ``` ```python In [3]: %timeit my_fn1() 28.1 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) In [4]: %timeit my_fn2() 79.9 ns ± 0.537 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) ``` This still adds some overhead due to the global lookup for `MyEnum` and attribute access, but it is unclear how this would be avoided given the nature of the check. > Guessing there would need to be some alternative handling [here](https://github.com/cython/cython/blob/796fd06da1fa1d5481ce43a6b6c901bc87f0ce9a/Cython/Compiler/PyrexTypes.py#L495) to handle `cpdef enum` types conversion. Noting this in part as that code path seems to be used to generate the `int` coercion C code seen with this example. Doesn't look to go through there when I set a breakpoint there. (Although I suspect you're broadly right about where to look) > A more performant approach might be mapping preexisting MyEnum Python objects to MyEnum C values like so. It looks to me like `__Pyx_EnumBase` tries to do this already so I'm slightly surprised there's so much benefit. Possibly "ordered_dict" is the wrong structure? I agree that this behaviour should be changed. Returning the corresponding Enum object is the expected result. In the case of an invalid enum integer value, I'd also expect an exception, probably a `ValueError` as shown in https://github.com/cython/cython/issues/2732#issuecomment-1178383584. Cython can probably do something more efficient internally than the generic attribute lookup in `(<object>MyEnum).ZERO`. > > Guessing there would need to be some alternative handling [here](https://github.com/cython/cython/blob/796fd06da1fa1d5481ce43a6b6c901bc87f0ce9a/Cython/Compiler/PyrexTypes.py#L495) to handle `cpdef enum` types conversion. Noting this in part as that code path seems to be used to generate the `int` coercion C code seen with this example. > > Doesn't look to go through there when I set a breakpoint there. (Although I suspect you're broadly right about where to look) Interesting came to that conclusion by looking at the generated C code and comparing. In particular was seeing references to that conversion code when doing `<object>c_enum` That said, using the debugger seems like the more reliable way to go > > A more performant approach might be mapping preexisting MyEnum Python objects to MyEnum C values like so. > > It looks to me like `__Pyx_EnumBase` tries to do this already so I'm slightly surprised there's so much benefit. Possibly "ordered_dict" is the wrong structure? Yeah was noticing that. Think the tricky thing is we want to lookup by `int` in this case, but the keys are `str`s for each value. Wasn't seeing a mapping that went from `int`s to `IntEnum` values, but may be overlooking something > > it looks to me like `__Pyx_EnumBase` tries to do this already so I'm slightly surprised there's so much benefit. Possibly "ordered_dict" is the wrong structure? > > Yeah was noticing that. Think the tricky thing is we want to lookup by `int` in this case, but the keys are `str`s for each value. Wasn't seeing a mapping that went from `int`s to `IntEnum` values, but may be overlooking something So having looked in more detail, it uses Python's `IntEnum` on most modern versions (not the class that's listed in the utility code). If you look at that's constructor it actually have it's own int -> enum map, but presumably you're just losing time on boxing/unboxing the C int. > I agree that this behaviour should be changed. Returning the corresponding Enum object is the expected result. In the case of an invalid enum integer value, I'd also expect an exception, probably a `ValueError` as shown in [#2732 (comment)](https://github.com/cython/cython/issues/2732#issuecomment-1178383584). Cython can probably do something more efficient internally than the generic attribute lookup in `(<object>MyEnum).ZERO`. Thanks Stefan 🙏 Do you have a sense of where it would make sense to add conversion code like this? Agree there is likely a better way to handle accessing the right `IntEnum` value. Do you have thoughts on what would be the best way to approach this? Also guessing we can do some templating to simplify the branch logic (if that is the right way to go). > Do you have a sense of where it would make sense to add conversion code like this? (Not Stefan but) I have a 50% written change with the conversion code in as a `cdef __Pyx_Enum_{{name}}_to_py(int c_val)` in `CpdefEnum.pyx` (and called from the `PyrexTypes.CEnumType.create_to_py_utility_code` function). > Agree there is likely a better way to handle accessing the right IntEnum value. Do you have thoughts on what would be the best way to approach this? I'm not sure there's a better way to approach this - Cython doesn't look to have much special knowledge of the Python enum > Also guessing we can do some templating to simplify the branch logic (if that is the right way to go). yes
2022-07-08T16:55:21Z
[]
[]
cython/cython
4,954
cython__cython-4954
[ "4953" ]
5b4bc497ad04880d85c7cb64b8c6e6aa919ffdde
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -2057,15 +2057,10 @@ def declare_from_annotation(self, env, as_target=False): atype = error_type visibility = 'private' - if 'dataclasses.dataclass' in env.directives: + if env.is_c_dataclass_scope: # handle "frozen" directive - full inspection of the dataclass directives happens # in Dataclass.py - frozen_directive = None - dataclass_directive = env.directives['dataclasses.dataclass'] - if dataclass_directive: - dataclass_directive_kwds = dataclass_directive[1] - frozen_directive = dataclass_directive_kwds.get('frozen', None) - is_frozen = frozen_directive and frozen_directive.is_literal and frozen_directive.value + is_frozen = env.is_c_dataclass_scope == "frozen" if atype.is_pyobject or atype.can_coerce_to_pyobject(env): visibility = 'readonly' if is_frozen else 'public' # If the object can't be coerced that's fine - we just don't create a property @@ -2160,7 +2155,7 @@ def _analyse_target_declaration(self, env, is_assignment_expression): self.entry.known_standard_library_import = "" # already exists somewhere and so is now ambiguous if not self.entry and self.annotation is not None: # name : type = ... - is_dataclass = 'dataclasses.dataclass' in env.directives + is_dataclass = env.is_c_dataclass_scope # In a dataclass, an assignment should not prevent a name from becoming an instance attribute. # Hence, "as_target = not is_dataclass". self.declare_from_annotation(env, as_target=not is_dataclass) diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -5169,7 +5169,6 @@ class CClassDefNode(ClassDefNode): check_size = None decorators = None shadow = False - is_dataclass = False @property def punycode_class_name(self): @@ -5219,8 +5218,6 @@ def analyse_declarations(self, env): if env.in_cinclude and not self.objstruct_name: error(self.pos, "Object struct name specification required for C class defined in 'extern from' block") - if "dataclasses.dataclass" in env.directives: - self.is_dataclass = True if self.decorators: error(self.pos, "Decorators not allowed on cdef classes (used on type '%s')" % self.class_name) self.base_type = None @@ -5310,6 +5307,15 @@ def analyse_declarations(self, env): self.scope = scope = self.entry.type.scope if scope is not None: scope.directives = env.directives + if "dataclasses.dataclass" in env.directives: + is_frozen = False + # Retrieve the @dataclass config (args, kwargs), as passed into the decorator. + dataclass_config = env.directives["dataclasses.dataclass"] + if dataclass_config: + decorator_kwargs = dataclass_config[1] + frozen_flag = decorator_kwargs.get('frozen') + is_frozen = frozen_flag and frozen_flag.is_literal and frozen_flag.value + scope.is_c_dataclass_scope = "frozen" if is_frozen else True if self.doc and Options.docstrings: scope.doc = embed_position(self.pos, self.doc) diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -391,7 +391,7 @@ class DEFER_ANALYSIS_OF_ARGUMENTS: # a list of directives that (when used as a decorator) are only applied to # the object they decorate and not to its children. immediate_decorator_directives = { - 'cfunc', 'ccall', 'cclass', + 'cfunc', 'ccall', 'cclass', 'dataclasses.dataclass', # function signature directives 'inline', 'exceptval', 'returns', # class directives diff --git a/Cython/Compiler/ParseTreeTransforms.py b/Cython/Compiler/ParseTreeTransforms.py --- a/Cython/Compiler/ParseTreeTransforms.py +++ b/Cython/Compiler/ParseTreeTransforms.py @@ -1318,8 +1318,7 @@ def _extract_directives(self, node, scope_name): name, value = directive if self.directives.get(name, object()) != value: directives.append(directive) - if (directive[0] == 'staticmethod' or - (directive[0] == 'dataclasses.dataclass' and scope_name == 'class')): + if directive[0] == 'staticmethod': both.append(dec) # Adapt scope type based on decorators that change it. if directive[0] == 'cclass' and scope_name == 'class': diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -348,6 +348,7 @@ class Scope(object): # is_passthrough boolean Outer scope is passed directly # is_cpp_class_scope boolean Is a C++ class scope # is_property_scope boolean Is a extension type property scope + # is_c_dataclass_scope boolean or "frozen" is a cython.dataclasses.dataclass # scope_prefix string Disambiguator for C names # in_cinclude boolean Suppress C declaration code # qualified_name string "modname" or "modname.classname" @@ -368,6 +369,7 @@ class Scope(object): is_cpp_class_scope = 0 is_property_scope = 0 is_module_scope = 0 + is_c_dataclass_scope = False is_internal = 0 scope_prefix = "" in_cinclude = 0 @@ -2345,7 +2347,7 @@ def declare_var(self, name, type, pos, type = py_object_type else: type = type.equivalent_type - if "dataclasses.InitVar" in pytyping_modifiers and 'dataclasses.dataclass' not in self.directives: + if "dataclasses.InitVar" in pytyping_modifiers and not self.is_c_dataclass_scope: error(pos, "Use of cython.dataclasses.InitVar does not make sense outside a dataclass") if is_cdef:
diff --git a/tests/run/pure_cdef_class_dataclass.py b/tests/run/pure_cdef_class_dataclass.py --- a/tests/run/pure_cdef_class_dataclass.py +++ b/tests/run/pure_cdef_class_dataclass.py @@ -25,11 +25,17 @@ class MyDataclass: True >>> hash(inst1) != id(inst1) True + >>> inst1.func_with_annotations(2.0) + 4.0 """ a: int = 1 self: list = cython.dataclasses.field(default_factory=list, hash=False) # test that arguments of init don't conflict + def func_with_annotations(self, b: float): + c: float = b + return self.a * c + class DummyObj: def __repr__(self):
[BUG] Can't provide type for local variable in method of Dataclass ```cython @cython.dataclasses.dataclass @cython.cclass class MyClass: x : cython.int def x_times_2(self): x2 : cython.int x2 = self.x * 2 return x2 ``` This fails to compile (on 64-bit linux with Python 3.8.11 and Cython 3.0.0 Alpha 11) with the following error for the line that specifies the type of x2: `Local variable cannot be declared public` If I remove that line or remove the dataclass decorator from the class, it compiles.
2022-08-05T17:04:57Z
[]
[]
cython/cython
4,996
cython__cython-4996
[ "4995" ]
3424926e9c8f03061b55516d2516a9f98999399e
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -1632,7 +1632,6 @@ def generate_del_function(self, scope, code): entry = scope.lookup_here("__del__") if entry is None or not entry.is_special: return # nothing to wrap - slot_func_cname = scope.mangle_internal("tp_finalize") code.putln("") if tp_slot.used_ifdef: @@ -1677,7 +1676,7 @@ def generate_dealloc_function(self, scope, code): if py_attrs or cpp_destructable_attrs or memoryview_slices or weakref_slot or dict_slot: self.generate_self_cast(scope, code) - if not is_final_type: + if not is_final_type or scope.may_have_finalize(): # in Py3.4+, call tp_finalize() as early as possible code.putln("#if CYTHON_USE_TP_FINALIZE") if needs_gc: diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -5218,6 +5218,8 @@ def declare(self, env): api=self.api, buffer_defaults=self.buffer_defaults(env), shadow=self.shadow) + if self.bases and len(self.bases.args) > 1: + self.entry.type.multiple_bases = True def analyse_declarations(self, env): #print "CClassDefNode.analyse_declarations:", self.class_name @@ -5307,6 +5309,8 @@ def analyse_declarations(self, env): api=self.api, buffer_defaults=self.buffer_defaults(env), shadow=self.shadow) + if self.bases and len(self.bases.args) > 1: + self.entry.type.multiple_bases = True if self.shadow: home_scope.lookup(self.class_name).as_variable = self.entry diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -1522,6 +1522,7 @@ class PyExtensionType(PyObjectType): # is_external boolean Defined in a extern block # check_size 'warn', 'error', 'ignore' What to do if tp_basicsize does not match # dataclass_fields OrderedDict nor None Used for inheriting from dataclasses + # multiple_bases boolean Does this class have multiple bases is_extension_type = 1 has_attributes = 1 @@ -1529,6 +1530,7 @@ class PyExtensionType(PyObjectType): objtypedef_cname = None dataclass_fields = None + multiple_bases = False def __init__(self, name, typedef_flag, base_type, is_external=0, check_size=None): self.name = name diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -2314,6 +2314,25 @@ def needs_tp_clear(self): """ return self.needs_gc() and not self.directives.get('no_gc_clear', False) + def may_have_finalize(self): + """ + This covers cases where we definitely have a __del__ function + and also cases where one of the base classes could have a __del__ + function but we don't know. + """ + current_type_scope = self + while current_type_scope: + del_entry = current_type_scope.lookup_here("__del__") + if del_entry and del_entry.is_special: + return True + if (current_type_scope.parent_type.is_extern or not current_type_scope.implemented or + current_type_scope.parent_type.multiple_bases): + # we don't know if we have __del__, so assume we do and call it + return True + current_base_type = current_type_scope.parent_type.base_type + current_type_scope = current_base_type.scope if current_base_type else None + return False + def get_refcounted_entries(self, include_weakref=False, include_gc_simple=True): py_attrs = [] diff --git a/Cython/Compiler/TypeSlots.py b/Cython/Compiler/TypeSlots.py --- a/Cython/Compiler/TypeSlots.py +++ b/Cython/Compiler/TypeSlots.py @@ -556,8 +556,7 @@ def slot_code(self, scope): value += "|Py_TPFLAGS_BASETYPE" if scope.needs_gc(): value += "|Py_TPFLAGS_HAVE_GC" - entry = scope.lookup("__del__") - if entry and entry.is_special: + if scope.may_have_finalize(): value += "|Py_TPFLAGS_HAVE_FINALIZE" return value diff --git a/runtests.py b/runtests.py --- a/runtests.py +++ b/runtests.py @@ -482,6 +482,7 @@ def get_openmp_compiler_flags(language): (3,4): (operator.lt, lambda x: x in ['run.py34_signature', 'run.test_unicode', # taken from Py3.7, difficult to backport 'run.pep442_tp_finalize', + 'run.pep442_tp_finalize_cimport', ]), (3,4,999): (operator.gt, lambda x: x in ['run.initial_file_path', ]),
diff --git a/tests/run/pep442_tp_finalize.pyx b/tests/run/pep442_tp_finalize.pyx --- a/tests/run/pep442_tp_finalize.pyx +++ b/tests/run/pep442_tp_finalize.pyx @@ -1,5 +1,9 @@ # mode: run +from __future__ import print_function + +cimport cython + import gc cdef class nontrivial_del: @@ -49,6 +53,80 @@ def test_del_and_dealloc(): gc.collect() print("finish") [email protected] +cdef class FinalClass: + def __init__(self): + print("init") + def __del__(self): + print("del") + +def test_final_class(): + """ + >>> test_final_class() + start + init + del + finish + """ + print("start") + d = FinalClass() + d = None + gc.collect() + print("finish") + [email protected] +cdef class FinalInherits(nontrivial_del): + def __init__(self): + super().__init__() + print("FinalInherits init") + # no __del__ but nontrivial_del should still be called + def __dealloc__(self): + pass # define __dealloc__ so as not to fall back on base __dealloc__ + +def test_final_inherited(): + """ + >>> test_final_inherited() + start + init + FinalInherits init + del + finish + """ + print("start") + d = FinalInherits() + d = None + gc.collect() + print("finish") + +cdef class DummyBase: + pass + +class RegularClass: + __slots__ = () + def __del__(self): + print("del") + [email protected] +cdef class FinalMultipleInheritance(DummyBase, RegularClass): + def __init__(self): + super().__init__() + print("init") + def __dealloc__(self): + pass + +def test_final_multiple_inheritance(): + """ + >>> test_final_multiple_inheritance() + start + init + del + finish + """ + print("start") + d = FinalMultipleInheritance() + d = None + gc.collect() + print("finish") cdef class del_with_exception: def __init__(self): @@ -301,3 +379,4 @@ class derived_python_child(cdef_nontrivial_parent): raise RuntimeError("End function") func(derived_python_child) + diff --git a/tests/run/pep442_tp_finalize_cimport.srctree b/tests/run/pep442_tp_finalize_cimport.srctree new file mode 100644 --- /dev/null +++ b/tests/run/pep442_tp_finalize_cimport.srctree @@ -0,0 +1,67 @@ +""" +PYTHON setup.py build_ext -i +PYTHON runtests.py +""" + +####### runtests.py ####### + +import gc +from testclasses import * +import baseclasses + +def test_has_del(): + inst = HasIndirectDel() + inst = None + gc.collect() + assert baseclasses.HasDel_del_called_count + +def test_no_del(): + inst = NoIndirectDel() + inst = None + gc.collect() + # The test here is that it doesn't crash + +test_has_del() +test_no_del() + +######## setup.py ######## + +from setuptools import setup +from Cython.Build import cythonize + +setup(ext_modules = cythonize('*.pyx')) + +####### baseclasses.pxd ###### + +cdef class HasDel: + pass + +cdef class DoesntHaveDel: + pass + +####### baseclasses.pyx ###### + +HasDel_del_called_count = 0 + +cdef class HasDel: + def __del__(self): + global HasDel_del_called_count + HasDel_del_called_count += 1 + +cdef class DoesntHaveDel: + pass + +######## testclasses.pyx ###### + +cimport cython +from baseclasses cimport HasDel, DoesntHaveDel + [email protected] +cdef class HasIndirectDel(HasDel): + pass + [email protected] +cdef class NoIndirectDel(DoesntHaveDel): + # But Cython can't tell that we don't have __del__ until runtime, + # so has to generate code to call it (and not crash!) + pass
[BUG] __del__ does not work with final ### Describe the bug Support for Python's `__del__` dunder method was added fairly recently however it does not work if the final decorator is applied to the class. ### Code to reproduce the behaviour: ```cython # mod.pyx cimport cython cdef class DelTest1: def __del__(self): print("deleting1") @cython.final cdef class DelTest2: def __del__(self): print("deleting2") ``` ```py # main.py from mod import DelTest1, DelTest2 t = DelTest1() del t # deleting1 is printed here t = DelTest2() del t # deleting2 should be printed here but is not ``` ### Expected behaviour I would expect the `__del__` method to be called upon deletion of the object regardless of whether the class is marked as final or not. ### Environment OS: Windows Python version: 3.9.13 Cython version: 3.0.0a11 ### Additional context _No response_
I suspect what's happening is that the `final` lets it deduce that it doesn't need to generate `tp_dealloc` (because it believes `tp_dealloc` is a no-op and because no future base classes exist that might want to call `tp_dealloc`). But this is now wrong because `tp_dealloc` is ultimately responsible for calling `__del__`. https://github.com/cython/cython/blob/3424926e9c8f03061b55516d2516a9f98999399e/Cython/Compiler/ModuleNode.py#L1680-L1698 It looks like it's specifically checked for. I think that was because it was originally only necessary to call the `__del__` when there might be Python classes that inherit. Now that `cdef class`es can also define `__del__` the check needs to be relaxed a little
2022-08-24T21:44:10Z
[]
[]
cython/cython
5,025
cython__cython-5025
[ "2940" ]
9fcf55fa86488bba666e918ba6550e976557411f
diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -1617,7 +1617,7 @@ def declare_cfunction(self, name, type, pos, entry = self.lookup_here(name) if entry and entry.defined_in_pxd: if entry.visibility != "private": - mangled_cname = self.mangle(Naming.var_prefix, name) + mangled_cname = self.mangle(Naming.func_prefix, name) if entry.cname == mangled_cname: cname = name entry.cname = cname
diff --git a/tests/compile/pxd_mangling_names.srctree b/tests/compile/pxd_mangling_names.srctree new file mode 100644 --- /dev/null +++ b/tests/compile/pxd_mangling_names.srctree @@ -0,0 +1,46 @@ +# mode: compile +# ticket: 2940 + +PYTHON setup.py build_ext --inplace +PYTHON -c "import a; a.test()" + +######## setup.py ######## + +from Cython.Build import cythonize +from Cython.Distutils.extension import Extension +from distutils.core import setup + +setup( + ext_modules=cythonize([Extension("a", ["a.py", "b.c"])]), +) + +######## a.pxd ######## + +cdef public int foo() + +cdef extern from "b.h": + cpdef int bar() + +######## a.py ######## + +def foo(): + return 42 + +def test(): + assert bar() == 42 + +######## b.h ######## + +#ifndef B_H +#define B_H + +int bar(); + +#endif + +######## b.c ######## + +#include "a.h" + +int bar() { return foo(); } + diff --git a/tests/pypy2_bugs.txt b/tests/pypy2_bugs.txt --- a/tests/pypy2_bugs.txt +++ b/tests/pypy2_bugs.txt @@ -16,8 +16,9 @@ run.partial_circular_import # https://foss.heptapod.net/pypy/pypy/issues/3185 run.language_level run.pure_pxd +compile.pxd_mangling_names -# Silly error with doctest matching slightly different string outputs rather than +# Silly error with doctest matching slightly different string outputs rather than # an actual bug but one I can't easily resolve run.with_gil
Compiling a .py file with an augmenting .pxd leads to a mangled function name for cdef public function. I would like to use the .py, with augmenting .pxd method for my Cython project so I can debug and use an IDE while I develop. For some reason this method leads to mangled exported function names. The definition of the function in the .pxd is ```cdef public int count_cwrap(int limit)``` and the .h file produced has this definition ```__PYX_EXTERN_C int __pyx_f_19pythagorean_triples_count_cwrap(int);``` If I convert the file to .pyx and add the cython definition, the name is not mangled anymore. I tried it and this occurs in both Linux and Windows. I am attaching my source code to reproduce the issue. pythagorean_triples.py: ```Python # cython: language_level=3 import time import cython import numpy as np def count(limit): if limit < 3: raise ValueError('Invalid limit value') arr = np.zeros(10) result : cython.int = 0 a : cython.int b : cython.int c : cython.int for a in range(1, limit + 1): for b in range(a + 1, limit + 1): for c in range(b + 1, limit + 1): if c * c > a * a + b * b: break if c * c == (a * a + b * b): result += 1 return result def count_cwrap(limit): return count(limit) if __name__ == '__main__': start = time.time() result = count(1000) duration = time.time() - start print(result, duration) ``` pythagorean_triples.pxd: ```Cython # cython: language_level=3 cdef public int count_cwrap(int limit) ``` setup.py: ```Python from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize setup( ext_modules = cythonize(Extension('pythagorean_triples', sources = ['pythagorean_triples.py'])) ) ``` Is this a bug or am I doing something wrong perhaps in the setup.py? I built with ```python setup_py.py build_ext --inplace``` in windows or with ```python3 setup_py.py build_ext --inplace``` in Linux Thanks
Thanks for the report. Could be that the `private` marker is simply not copied when adapting the Python function signature from the `.pxd` file in `AlignFunctionDefinitions` syntax tree transformation (`ParseTreeTransforms.py`). Probably easy to add there. PR welcome. [Here](https://github.com/cython/cython/blob/master/tests/build/module_api.srctree) is an example of a test file that you could borrow from. It's just a bunch of files stuffed into one that the test runner extracts. Just ran into this on `3.0.0a10` and I don't know how to fix it. Has anyone been able to workaround this? It seems `AlignFunctionDefinitions.visit_DefNode` is receiving a `pxd_def` with its name mangled despite having `visibility == 'public'`. https://github.com/cython/cython/blob/ddaaa7b8bfe9885b7bed432cd0a5ab8191d112cd/Cython/Compiler/ParseTreeTransforms.py#L2598 My gut feeling is that's probably incorrect, but I don't know the codebase well enough to say for certain. I can see the `pxd_def` is generated in `ModuleScope.declare_cfunction` where it looks like the `(visibility == 'public' and defining)` condition is allowing it to be mangled. https://github.com/cython/cython/blob/ddaaa7b8bfe9885b7bed432cd0a5ab8191d112cd/Cython/Compiler/Symtab.py#L1552 Also, is it possible to specify the visibility when using the `@cython.cfunc` decorator? Something like how `@cython.declare(visibility='public')` does?
2022-09-12T21:00:13Z
[]
[]
cython/cython
5,040
cython__cython-5040
[ "1839" ]
fd71114951a9e0d48f0aad324e71d3d9f8be29df
diff --git a/Cython/Compiler/ModuleNode.py b/Cython/Compiler/ModuleNode.py --- a/Cython/Compiler/ModuleNode.py +++ b/Cython/Compiler/ModuleNode.py @@ -262,7 +262,7 @@ def h_entries(entries, api=0, pxd=0): api_guard = self.api_name(Naming.api_guard_prefix, env) h_code_start.putln("#ifndef %s" % api_guard) h_code_start.putln("") - self.generate_extern_c_macro_definition(h_code_start) + self.generate_extern_c_macro_definition(h_code_start, env.is_cpp()) h_code_start.putln("") self.generate_dl_import_macro(h_code_start) if h_extension_types: @@ -804,7 +804,7 @@ def generate_module_preamble(self, env, options, cimported_modules, metadata, co code.putln(" { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }") code.putln("") - self.generate_extern_c_macro_definition(code) + self.generate_extern_c_macro_definition(code, env.is_cpp()) code.putln("") code.putln("#define %s" % self.api_name(Naming.h_guard_prefix, env)) @@ -876,14 +876,17 @@ def generate_module_preamble(self, env, options, cimported_modules, metadata, co if has_np_pythran(env): env.use_utility_code(UtilityCode.load_cached("PythranConversion", "CppSupport.cpp")) - def generate_extern_c_macro_definition(self, code): + def generate_extern_c_macro_definition(self, code, is_cpp): name = Naming.extern_c_macro code.putln("#ifndef %s" % name) - code.putln(" #ifdef __cplusplus") - code.putln(' #define %s extern "C"' % name) - code.putln(" #else") - code.putln(" #define %s extern" % name) - code.putln(" #endif") + if is_cpp: + code.putln(' #define %s extern "C++"' % name) + else: + code.putln(" #ifdef __cplusplus") + code.putln(' #define %s extern "C"' % name) + code.putln(" #else") + code.putln(" #define %s extern" % name) + code.putln(" #endif") code.putln("#endif") def generate_dl_import_macro(self, code):
diff --git a/tests/compile/excvalcheck.h b/tests/compile/excvalcheck.h --- a/tests/compile/excvalcheck.h +++ b/tests/compile/excvalcheck.h @@ -1,12 +1,6 @@ -#ifdef __cplusplus -extern "C" { -#endif extern DL_EXPORT(int) spam(void); extern DL_EXPORT(void) grail(void); extern DL_EXPORT(char *)tomato(void); -#ifdef __cplusplus -} -#endif int spam(void) {return 0;} void grail(void) {return;} diff --git a/tests/compile/nogil.h b/tests/compile/nogil.h --- a/tests/compile/nogil.h +++ b/tests/compile/nogil.h @@ -1,25 +1,13 @@ -#ifdef __cplusplus -extern "C" { -#endif extern DL_EXPORT(void) e1(void); extern DL_EXPORT(int*) e2(void); -#ifdef __cplusplus -} -#endif void e1(void) {return;} int* e2(void) {return 0;} -#ifdef __cplusplus -extern "C" { -#endif extern DL_EXPORT(PyObject *) g(PyObject*); extern DL_EXPORT(void) g2(PyObject*); -#ifdef __cplusplus -} -#endif PyObject *g(PyObject* o) {if (o) {}; return 0;} void g2(PyObject* o) {if (o) {}; return;} diff --git a/tests/run/cpp_extern.srctree b/tests/run/cpp_extern.srctree new file mode 100644 --- /dev/null +++ b/tests/run/cpp_extern.srctree @@ -0,0 +1,151 @@ +# mode: run +# tag: cpp +# ticket: 1839 + +""" +PYTHON setup.py build_ext --inplace +PYTHON -c "from foo import test; test()" +PYTHON -c "from bar import test; test()" +PYTHON -c "from baz import test; test()" +""" + +######## setup.py ######## + +from Cython.Build import cythonize +from Cython.Distutils.extension import Extension +from distutils.core import setup + +foo = Extension( + "foo", + ["foo.pyx", "foo1.cpp", "foo2.cpp"], +) +bar = Extension( + "bar", + ["bar.pyx", "bar1.c", "bar2.cpp"], +) +baz = Extension( + "baz", + ["baz.pyx", "baz1.c", "baz2.cpp"], + define_macros = [("__PYX_EXTERN_C", 'extern "C"')], +) + +setup( + ext_modules=cythonize([foo, bar, baz]), +) + +######## foo.pyx ######## + +# distutils: language = c++ + +from libcpp cimport vector + +cdef public vector.vector[int] get_vector(): + return [1,2,3] + +cdef extern from "foo_header.h": + cdef size_t size_vector1() + cdef size_t size_vector2() + +def test(): + assert size_vector1() == 3 + assert size_vector2() == 3 + +######## foo_header.h ######## + +size_t size_vector1(); +size_t size_vector2(); + +######## foo1.cpp ######## + +#include <vector> +#include "foo.h" + +size_t size_vector1() { + return get_vector().size(); +} + +######## foo2.cpp ######## + +#include <vector> +extern "C" { +// #include within `extern "C"` is legal. +// We want to make sure here that Cython C++ functions are flagged as `extern "C++"`. +// Otherwise they would be interpreted with C-linkage if the header is include within a `extern "C"` block. +#include "foo.h" +} + +size_t size_vector2() { + return get_vector().size(); +} + +######## bar.pyx ######## + +cdef public char get_char(): + return 42 + +cdef extern from "bar_header.h": + cdef int get_int1() + cdef int get_int2() + +def test(): + assert get_int1() == 42 + assert get_int2() == 42 + +######## bar_header.h ######## + +int get_int1(); +int get_int2(); + +######## bar1.c ######## + +#include "bar.h" + +int get_int1() { return (int)get_char(); } + +######## bar2.cpp ######## + +extern "C" { +#include "bar.h" +} + +extern "C" int get_int2() { return (int)get_char(); } + +######## baz.pyx ######## + +# distutils: language = c++ + +cdef public char get_char(): + return 42 + +cdef extern from "baz_header.h": + cdef int get_int1() + cdef int get_int2() + +def test(): + assert get_int1() == 42 + assert get_int2() == 42 + +######## baz_header.h ######## + +#ifdef __cplusplus + #define BAZ_EXTERN_C extern "C" +#else + #define BAZ_EXTERN_C +#endif + +BAZ_EXTERN_C int get_int1(); +int get_int2(); + +######## baz1.c ######## + +#undef __PYX_EXTERN_C +#define __PYX_EXTERN_C +#include "baz.h" + +int get_int1() { return (int)get_char(); } + +######## baz2.cpp ######## + +#include "baz.h" + +int get_int2() { return (int)get_char(); }
Functions with C++ return type are `extern "C"` Thats a C++ compiler error. All functions with C++ in their signatures should be `extern "C++"`.
The whole error only exists when the function is `public`. I've never come across "extern C++", so I'm probably the wrong person to review this, but I'd be happy to see a pull request that contains a test showing what goes wrong here, and preferably even adds a fix. To write a test, look at the `.srctree` files under `/tests/run/`, e.g. this one: https://github.com/cython/cython/blob/master/tests/run/cpp_assignment_overload.srctree They are basically a bunch of separate files, separated by marker lines. In C++, `extern "C++"` is the default, but in this case, Cython overrides it with `extern "C"`. I also encountered this problem and made a minimal working example. ### Source mwe.cpp ```cpp #include "mwe.h" #include <vector> // this must come _after_ vector #include "mwe_pyx.h" std::vector<int> do_stuff() { std::vector<int> ret; std::vector<int> o = foo(); for (auto i : o) { ret.emplace_back(2*i); } return ret; } ``` mwe.h ```cpp #include <vector> std::vector<int> do_stuff(); ``` c_mwe.pxd ``` from libcpp.vector cimport vector cdef extern from "mwe.h": vector[int] do_stuff() ``` mwe.pyx ```py from c_mwe cimport do_stuff from libcpp.vector cimport vector cdef public vector[int] foo(): cdef vector[int] ret = [1, 2, 3] return [1, 2, 3] def func(): cdef vector[int] a = do_stuff() for i in a: print(i) ``` meson.build ```meson project('cython-test', 'cpp', version : '0.1', default_options : ['warning_level=3', 'cpp_std=c++14']) cython = find_program('cython', version: '>=0.29.14') cython_flags = ['-Wextra', '--cplus', '-3'] mwe_pyx = custom_target('mwe_pyx', output: ['mwe_pyx.cpp', 'mwe_pyx.h'], input: files('mwe.pyx'), depend_files: files('c_mwe.pxd'), command: [cython, '@INPUT@', '-o', '@OUTPUT0@'] + cython_flags, ) mwe_pyx_header = mwe_pyx[1] mwe_pyx_cpp = mwe_pyx[0] py3_mod = import('python') py3 = py3_mod.find_installation('python3') mwe_mod = py3.extension_module('mwe', mwe_pyx_cpp, 'mwe.cpp', dependencies: [py3.dependency()] ) ``` ### Compiling ``` [1/4] /usr/bin/cython ../mwe.pyx -o mwe_pyx.cpp -Wextra --cplus -3 [2/4] clang++ -Imwe.cpython-310-x86_64-linux-gnu.so.p -I. -I.. -I/usr/include/python3.10 -fcolor-diagnostics -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -std=c++14 -O0 -g -fPIC -MD -MQ mwe.cpython-310-x86_64-linux-gnu.so.p/mwe.cpp.o -MF mwe.cpython-310-x86_64-linux-gnu.so.p/mwe.cpp.o.d -o mwe.cpython-310-x86_64-linux-gnu.so.p/mwe.cpp.o -c ../mwe.cpp In file included from ../mwe.cpp:5: ./mwe_pyx.h:22:34: warning: 'foo' has C-linkage specified, but returns incomplete type 'std::vector<int>' which could be incompatible with C [-Wreturn-type-c-linkage] __PYX_EXTERN_C std::vector<int> foo(void); ^ 1 warning generated. [3/4] clang++ -Imwe.cpython-310-x86_64-linux-gnu.so.p -I. -I.. -I/usr/include/python3.10 -fcolor-diagnostics -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -std=c++14 -O0 -g -fPIC -MD -MQ mwe.cpython-310-x86_64-linux-gnu.so.p/meson-generated_.._mwe_pyx.cpp.o -MF mwe.cpython-310-x86_64-linux-gnu.so.p/meson-generated_.._mwe_pyx.cpp.o.d -o mwe.cpython-310-x86_64-linux-gnu.so.p/meson-generated_.._mwe_pyx.cpp.o -c mwe_pyx.cpp mwe_pyx.cpp:1176:34: warning: 'foo' has C-linkage specified, but returns incomplete type 'std::vector<int>' which could be incompatible with C [-Wreturn-type-c-linkage] __PYX_EXTERN_C std::vector<int> foo(void); /*proto*/ ^ 1 warning generated. [4/4] clang++ -o mwe.cpython-310-x86_64-linux-gnu.so mwe.cpython-310-x86_64-linux-gnu.so.p/meson-generated_.._mwe_pyx.cpp.o mwe.cpython-310-x86_64-linux-gnu.so.p/mwe.cpp.o -Wl,--as-needed -Wl,--allow-shlib-undefined -shared -fPIC ``` ### Fix Currently, `__PYX_EXTERN_C` is defined as: ```cpp #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif ``` AFAIK, `extern` exports the symbol to the linker, while `extern "C"` additionally avoids name mangling and makes linking to C code possible. I don't see why `extern "C"` should be necessary here at all since all code is compiled and linked with C++. Therefore, I would just suggest: ```cpp #ifndef __PYX_EXTERN_C #define __PYX_EXTERN_C extern #endif ``` Applying this to the above MWE fixes the warning, while the module compiles, links, and runs as expected.
2022-09-20T22:12:58Z
[]
[]
cython/cython
5,057
cython__cython-5057
[ "4944" ]
c0a5ab2de754eec8787693073207aff30b22a318
diff --git a/Cython/Compiler/Builtin.py b/Cython/Compiler/Builtin.py --- a/Cython/Compiler/Builtin.py +++ b/Cython/Compiler/Builtin.py @@ -427,6 +427,7 @@ def init_builtins(): global list_type, tuple_type, dict_type, set_type, frozenset_type global bytes_type, str_type, unicode_type, basestring_type, slice_type global float_type, long_type, bool_type, type_type, complex_type, bytearray_type + global int_type type_type = builtin_scope.lookup('type').type list_type = builtin_scope.lookup('list').type tuple_type = builtin_scope.lookup('tuple').type @@ -443,6 +444,8 @@ def init_builtins(): long_type = builtin_scope.lookup('long').type bool_type = builtin_scope.lookup('bool').type complex_type = builtin_scope.lookup('complex').type + # Be careful with int type while Py2 is still supported + int_type = builtin_scope.lookup('int').type # Set up type inference links between equivalent Python/C types bool_type.equivalent_type = PyrexTypes.c_bint_type diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -1538,6 +1538,11 @@ def _analyse_name_as_type(name, pos, env): global_entry = env.global_scope().lookup(name) if global_entry and global_entry.is_type: type = global_entry.type + if (not env.in_c_type_context and + name == 'int' and type is Builtin.int_type): + # While we still support Python2 this needs to be downgraded + # to a generic Python object to include both int and long + type = py_object_type if type and (type.is_pyobject or env.in_c_type_context): return type ctype = ctype or type @@ -2119,6 +2124,10 @@ def analyse_as_type(self, env): type = py_object_type elif type.is_pyobject and type.equivalent_type: type = type.equivalent_type + elif type is Builtin.int_type: + # while we still support Python 2 this must be an object + # so that it can be either int or long + type = py_object_type return type if self.name == 'object': # This is normally parsed as "simple C type", but not if we don't parse C types.
diff --git a/tests/run/annotation_typing.pyx b/tests/run/annotation_typing.pyx --- a/tests/run/annotation_typing.pyx +++ b/tests/run/annotation_typing.pyx @@ -14,10 +14,10 @@ except ImportError: def old_dict_syntax(a: list, b: "int" = 2, c: {'ctype': 'long int'} = 3, d: {'type': 'long int'} = 4) -> list: """ >>> old_dict_syntax([1]) - ('list object', 'int object', 'long', 'long') + ('list object', 'Python object', 'long', 'long') [1, 2, 3, 4] >>> old_dict_syntax([1], 3) - ('list object', 'int object', 'long', 'long') + ('list object', 'Python object', 'long', 'long') [1, 3, 3, 4] >>> old_dict_syntax(123) Traceback (most recent call last): @@ -36,13 +36,13 @@ def old_dict_syntax(a: list, b: "int" = 2, c: {'ctype': 'long int'} = 3, d: {'ty def pytypes_def(a: list, b: int = 2, c: long = 3, d: float = 4.0, n: list = None, o: Optional[tuple] = ()) -> list: """ >>> pytypes_def([1]) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 2, 3, 4.0, None, ()] >>> pytypes_def([1], 3) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 3, 3, 4.0, None, ()] >>> pytypes_def([1], 3, 2, 1, [], None) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 3, 2, 1.0, [], None] >>> pytypes_def(123) Traceback (most recent call last): @@ -63,13 +63,13 @@ def pytypes_def(a: list, b: int = 2, c: long = 3, d: float = 4.0, n: list = None cpdef pytypes_cpdef(a: list, b: int = 2, c: long = 3, d: float = 4.0, n: list = None, o: Optional[tuple] = ()): """ >>> pytypes_cpdef([1]) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 2, 3, 4.0, None, ()] >>> pytypes_cpdef([1], 3) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 3, 3, 4.0, None, ()] >>> pytypes_cpdef([1], 3, 2, 1, [], None) - ('list object', 'int object', 'Python object', 'double', 'list object', 'tuple object') + ('list object', 'Python object', 'Python object', 'double', 'list object', 'tuple object') [1, 3, 2, 1.0, [], None] >>> pytypes_cpdef(123) Traceback (most recent call last): @@ -99,10 +99,10 @@ cdef c_pytypes_cdef(a: list, b: int = 2, c: long = 3, d: float = 4.0, n: list = def pytypes_cdef(a, b=2, c=3, d=4): """ >>> pytypes_cdef([1]) - ('list object', 'int object', 'Python object', 'double', 'list object') + ('list object', 'Python object', 'Python object', 'double', 'list object') [1, 2, 3, 4.0, None] >>> pytypes_cdef([1], 3) - ('list object', 'int object', 'Python object', 'double', 'list object') + ('list object', 'Python object', 'Python object', 'double', 'list object') [1, 3, 3, 4.0, None] >>> pytypes_cdef(123) # doctest: +ELLIPSIS Traceback (most recent call last): @@ -111,6 +111,15 @@ def pytypes_cdef(a, b=2, c=3, d=4): return c_pytypes_cdef(a, b, c, d) +def pyint(a: int): + """ + >>> large_int = eval('0x'+'F'*64) # definitely bigger than C int64 + >>> pyint(large_int) == large_int + True + """ + return a + + def ctypes_def(a: list, b: cython.int = 2, c: cython.long = 3, d: cython.float = 4) -> list: """ >>> ctypes_def([1]) @@ -372,14 +381,14 @@ _WARNINGS = """ 63:70: PEP-484 recommends 'typing.Optional[...]' for arguments that can be None. 90:44: Found Python 2.x type 'long' in a Python annotation. Did you mean to use 'cython.long'? 90:70: PEP-484 recommends 'typing.Optional[...]' for arguments that can be None. -274:44: Unknown type declaration in annotation, ignoring -302:15: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? +283:44: Unknown type declaration in annotation, ignoring +311:15: Annotation ignored since class-level attributes must be Python objects. Were you trying to set up an instance attribute? # DUPLICATE: 63:44: Found Python 2.x type 'long' in a Python annotation. Did you mean to use 'cython.long'? # BUG: 63:6: 'pytypes_cpdef' redeclared -146:0: 'struct_io' redeclared -181:0: 'struct_convert' redeclared -200:0: 'exception_default' redeclared -231:0: 'exception_default_uint' redeclared +155:0: 'struct_io' redeclared +190:0: 'struct_convert' redeclared +209:0: 'exception_default' redeclared +240:0: 'exception_default_uint' redeclared """
[BUG] int annotation now sets the type to exact Python int **Describe the bug** Since 31d40c8c62acef9509675155fe5b5bb8e48dba5a an annotation of `int` now corresponds to an exact Python `int`. This matters on Python 2 because it rejects `long`. Was this intended? **To Reproduce** Code to reproduce the behaviour: ```cython def f(x: int): return x+1 ``` then from python 2 ```python import testmod testmod.f(1) # works testmod.f(long(1)) # fails ``` **Environment (please complete the following information):** - Python version: 2.7 - Cython version: current master branch **Additional context** Obviously this is the long-term plan, but I'm not sure we meant to do it now? Also, whether or not it's supported we probably need some test coverage
2022-10-02T15:37:43Z
[]
[]
cython/cython
5,058
cython__cython-5058
[ "4975" ]
ddd11a2bd503ece0c79de65e834429babbbca550
diff --git a/Cython/Compiler/Builtin.py b/Cython/Compiler/Builtin.py --- a/Cython/Compiler/Builtin.py +++ b/Cython/Compiler/Builtin.py @@ -399,7 +399,13 @@ def init_builtin_types(): objstruct_cname = "PyBaseExceptionObject" else: objstruct_cname = 'Py%sObject' % name.capitalize() - the_type = builtin_scope.declare_builtin_type(name, cname, utility, objstruct_cname) + type_class = PyrexTypes.BuiltinObjectType + if name in ['dict', 'list', 'set', 'frozenset']: + type_class = PyrexTypes.BuiltinTypeConstructorObjectType + elif name == 'tuple': + type_class = PyrexTypes.PythonTupleTypeConstructor + the_type = builtin_scope.declare_builtin_type(name, cname, utility, objstruct_cname, + type_class=type_class) builtin_types[name] = the_type for method in methods: method.declare_in_type(the_type) @@ -478,12 +484,8 @@ def get_known_standard_library_module_scope(module_name): ('Set', set_type), ('FrozenSet', frozenset_type), ]: - if name == "Tuple": - indexed_type = PyrexTypes.PythonTupleTypeConstructor(EncodedString("typing."+name), tp) - else: - indexed_type = PyrexTypes.PythonTypeConstructor(EncodedString("typing."+name), tp) name = EncodedString(name) - entry = mod.declare_type(name, indexed_type, pos = None) + entry = mod.declare_type(name, tp, pos = None) var_entry = Entry(name, None, PyrexTypes.py_object_type) var_entry.is_pyglobal = True var_entry.is_variable = True diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -3937,7 +3937,8 @@ def analyse_pytyping_modifiers(self, env): modifier_node = self while modifier_node.is_subscript: modifier_type = modifier_node.base.analyse_as_type(env) - if modifier_type.python_type_constructor_name and modifier_type.modifier_name: + if (modifier_type and modifier_type.python_type_constructor_name + and modifier_type.modifier_name): modifiers.append(modifier_type.modifier_name) modifier_node = modifier_node.index return modifiers @@ -14409,23 +14410,23 @@ def analyse_type_annotation(self, env, assigned_value=None): with env.new_c_type_context(in_c_type_context=explicit_ctype): arg_type = annotation.analyse_as_type(env) - if arg_type is None: - warning(annotation.pos, "Unknown type declaration in annotation, ignoring") - return [], arg_type + if arg_type is None: + warning(annotation.pos, "Unknown type declaration in annotation, ignoring") + return [], arg_type - if annotation.is_string_literal: - warning(annotation.pos, - "Strings should no longer be used for type declarations. Use 'cython.int' etc. directly.", - level=1) - if explicit_pytype and not explicit_ctype and not (arg_type.is_pyobject or arg_type.equivalent_type): - warning(annotation.pos, - "Python type declaration in signature annotation does not refer to a Python type") - if arg_type.is_complex: - # creating utility code needs to be special-cased for complex types - arg_type.create_declaration_utility_code(env) - - # Check for declaration modifiers, e.g. "typing.Optional[...]" or "dataclasses.InitVar[...]" - modifiers = annotation.analyse_pytyping_modifiers(env) if annotation.is_subscript else [] + if annotation.is_string_literal: + warning(annotation.pos, + "Strings should no longer be used for type declarations. Use 'cython.int' etc. directly.", + level=1) + if explicit_pytype and not explicit_ctype and not (arg_type.is_pyobject or arg_type.equivalent_type): + warning(annotation.pos, + "Python type declaration in signature annotation does not refer to a Python type") + if arg_type.is_complex: + # creating utility code needs to be special-cased for complex types + arg_type.create_declaration_utility_code(env) + + # Check for declaration modifiers, e.g. "typing.Optional[...]" or "dataclasses.InitVar[...]" + modifiers = annotation.analyse_pytyping_modifiers(env) if annotation.is_subscript else [] return modifiers, arg_type diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -4524,20 +4524,17 @@ def error_condition(self, result_code): return "dummy" -class PythonTypeConstructor(PyObjectType): +class PythonTypeConstructorMixin(object): """Used to help Cython interpret indexed types from the typing module (or similar) """ modifier_name = None - def __init__(self, name, base_type=None): + def set_python_type_constructor_name(self, name): self.python_type_constructor_name = name - self.base_type = base_type def specialize_here(self, pos, env, template_values=None): - if self.base_type: - # for a lot of the typing classes it doesn't really matter what the template is - # (i.e. typing.Dict[int] is really just a dict) - return self.base_type + # for a lot of the typing classes it doesn't really matter what the template is + # (i.e. typing.Dict[int] is really just a dict) return self def __repr__(self): @@ -4550,7 +4547,17 @@ def is_template_type(self): return True -class PythonTupleTypeConstructor(PythonTypeConstructor): +class BuiltinTypeConstructorObjectType(BuiltinObjectType, PythonTypeConstructorMixin): + """ + builtin types like list, dict etc which can be subscripted in annotations + """ + def __init__(self, name, cname, objstruct_cname=None): + super(BuiltinTypeConstructorObjectType, self).__init__( + name, cname, objstruct_cname=objstruct_cname) + self.set_python_type_constructor_name(name) + + +class PythonTupleTypeConstructor(BuiltinTypeConstructorObjectType): def specialize_here(self, pos, env, template_values=None): if (template_values and None not in template_values and not any(v.is_pyobject for v in template_values)): @@ -4561,13 +4568,14 @@ def specialize_here(self, pos, env, template_values=None): return super(PythonTupleTypeConstructor, self).specialize_here(pos, env, template_values) -class SpecialPythonTypeConstructor(PythonTypeConstructor): +class SpecialPythonTypeConstructor(PyObjectType, PythonTypeConstructorMixin): """ For things like ClassVar, Optional, etc, which are not types and disappear during type analysis. """ def __init__(self, name): - super(SpecialPythonTypeConstructor, self).__init__(name, base_type=None) + super(SpecialPythonTypeConstructor, self).__init__() + self.set_python_type_constructor_name(name) self.modifier_name = name def __repr__(self): diff --git a/Cython/Compiler/Symtab.py b/Cython/Compiler/Symtab.py --- a/Cython/Compiler/Symtab.py +++ b/Cython/Compiler/Symtab.py @@ -588,7 +588,8 @@ def declare_type(self, name, type, pos, if defining: self.type_entries.append(entry) - if not template: + # don't replace an entry that's already set + if not template and getattr(type, "entry", None) is None: type.entry = entry # here we would set as_variable to an object representing this type @@ -1161,9 +1162,9 @@ def __init__(self): Scope.__init__(self, "__builtin__", PreImportScope(), None) self.type_names = {} - for name, definition in sorted(self.builtin_entries.items()): - cname, type = definition - self.declare_var(name, type, None, cname) + # Most entries are initialized in init_builtins, except for "bool" + # which is apparently a special case because it conflicts with C++ bool + self.declare_var("bool", py_object_type, None, "((PyObject*)&PyBool_Type)") def lookup(self, name, language_level=None, str_is_str=None): # 'language_level' and 'str_is_str' are passed by ModuleScope @@ -1203,9 +1204,10 @@ def declare_builtin_cfunction(self, name, type, cname, python_equiv=None, utilit entry.as_variable = var_entry return entry - def declare_builtin_type(self, name, cname, utility_code = None, objstruct_cname = None): + def declare_builtin_type(self, name, cname, utility_code=None, + objstruct_cname=None, type_class=PyrexTypes.BuiltinObjectType): name = EncodedString(name) - type = PyrexTypes.BuiltinObjectType(name, cname, objstruct_cname) + type = type_class(name, cname, objstruct_cname) scope = CClassScope(name, outer_scope=None, visibility='extern') scope.directives = {} if name == 'bool': @@ -1237,35 +1239,6 @@ def declare_builtin_type(self, name, cname, utility_code = None, objstruct_cname def builtin_scope(self): return self - # FIXME: remove redundancy with Builtin.builtin_types_table - builtin_entries = { - - "type": ["((PyObject*)&PyType_Type)", py_object_type], - - "bool": ["((PyObject*)&PyBool_Type)", py_object_type], - "int": ["((PyObject*)&PyInt_Type)", py_object_type], - "long": ["((PyObject*)&PyLong_Type)", py_object_type], - "float": ["((PyObject*)&PyFloat_Type)", py_object_type], - "complex":["((PyObject*)&PyComplex_Type)", py_object_type], - - "bytes": ["((PyObject*)&PyBytes_Type)", py_object_type], - "bytearray": ["((PyObject*)&PyByteArray_Type)", py_object_type], - "str": ["((PyObject*)&PyString_Type)", py_object_type], - "unicode":["((PyObject*)&PyUnicode_Type)", py_object_type], - - "tuple": ["((PyObject*)&PyTuple_Type)", py_object_type], - "list": ["((PyObject*)&PyList_Type)", py_object_type], - "dict": ["((PyObject*)&PyDict_Type)", py_object_type], - "set": ["((PyObject*)&PySet_Type)", py_object_type], - "frozenset": ["((PyObject*)&PyFrozenSet_Type)", py_object_type], - - "slice": ["((PyObject*)&PySlice_Type)", py_object_type], -# "file": ["((PyObject*)&PyFile_Type)", py_object_type], # not in Py3 - - "None": ["Py_None", py_object_type], - "False": ["Py_False", py_object_type], - "True": ["Py_True", py_object_type], - } const_counter = 1 # As a temporary solution for compiling code in pxds
diff --git a/tests/run/pep526_variable_annotations.py b/tests/run/pep526_variable_annotations.py --- a/tests/run/pep526_variable_annotations.py +++ b/tests/run/pep526_variable_annotations.py @@ -1,6 +1,10 @@ # cython: language_level=3 # mode: run -# tag: pure3.6, pep526, pep484, warnings +# tag: pure3.7, pep526, pep484, warnings + +# for the benefit of the pure tests, don't require annotations +# to be evaluated +from __future__ import annotations import cython @@ -19,7 +23,9 @@ fvar: cython.float = 1.2 some_number: cython.int # variable without initial value some_list: List[cython.int] = [] # variable with initial value +another_list: list[cython.int] = [] t: Tuple[cython.int, ...] = (1, 2, 3) +t2: tuple[cython.int, ...] body: Optional[List[str]] descr_only : "descriptions are allowed but ignored" @@ -162,15 +168,24 @@ def test_subscripted_types(): """ >>> test_subscripted_types() dict object + dict object + list object + list object list object set object """ - a: typing.Dict[cython.int, cython.float] = {} - b: List[cython.int] = [] + a1: typing.Dict[cython.int, cython.float] = {} + a2: dict[cython.int, cython.float] = {} + b1: List[cython.int] = [] + b2: list[cython.int] = [] + b3: List = [] # doesn't need to be subscripted c: _SET_[object] = set() - print(cython.typeof(a) + (" object" if not cython.compiled else "")) - print(cython.typeof(b) + (" object" if not cython.compiled else "")) + print(cython.typeof(a1) + (" object" if not cython.compiled else "")) + print(cython.typeof(a2) + (" object" if not cython.compiled else "")) + print(cython.typeof(b1) + (" object" if not cython.compiled else "")) + print(cython.typeof(b2) + (" object" if not cython.compiled else "")) + print(cython.typeof(b3) + (" object" if not cython.compiled else "")) print(cython.typeof(c) + (" object" if not cython.compiled else "")) # because tuple is specifically special cased to go to ctuple where possible @@ -187,9 +202,44 @@ def test_tuple(a: typing.Tuple[cython.int, cython.float], b: typing.Tuple[cython tuple object tuple object tuple object + tuple object """ x: typing.Tuple[int, float] = (a[0], a[1]) # note: Python int/float, not cython.int/float y: Tuple[cython.int, ...] = (1,2.) + plain_tuple: Tuple = () + z = a[0] # should infer to C int + p = x[1] # should infer to Python float -> C double + + print(cython.typeof(z)) + print("int" if cython.compiled and cython.typeof(x[0]) == "Python object" else cython.typeof(x[0])) # FIXME: infer Python int + print(cython.typeof(p) if cython.compiled or cython.typeof(p) != 'float' else "Python object") # FIXME: infer C double + print(cython.typeof(x[1]) if cython.compiled or cython.typeof(p) != 'float' else "Python object") # FIXME: infer C double + print(cython.typeof(a) if cython.compiled or cython.typeof(a) != 'tuple' else "(int, float)") + print(cython.typeof(x) + (" object" if not cython.compiled else "")) + print(cython.typeof(y) + (" object" if not cython.compiled else "")) + print(cython.typeof(c) + (" object" if not cython.compiled else "")) + print(cython.typeof(plain_tuple) + (" object" if not cython.compiled else "")) + + +# because tuple is specifically special cased to go to ctuple where possible +def test_tuple_without_typing(a: tuple[cython.int, cython.float], b: tuple[cython.int, ...], + c: tuple[cython.int, object] # cannot be a ctuple + ): + """ + >>> test_tuple_without_typing((1, 1.0), (1, 1.0), (1, 1.0)) + int + int + Python object + Python object + (int, float) + tuple object + tuple object + tuple object + tuple object + """ + x: tuple[int, float] = (a[0], a[1]) # note: Python int/float, not cython.int/float + y: tuple[cython.int, ...] = (1,2.) + plain_tuple: tuple = () z = a[0] # should infer to C int p = x[1] # should infer to Python float -> C double @@ -201,6 +251,7 @@ def test_tuple(a: typing.Tuple[cython.int, cython.float], b: typing.Tuple[cython print(cython.typeof(x) + (" object" if not cython.compiled else "")) print(cython.typeof(y) + (" object" if not cython.compiled else "")) print(cython.typeof(c) + (" object" if not cython.compiled else "")) + print(cython.typeof(plain_tuple) + (" object" if not cython.compiled else "")) def test_use_typing_attributes_as_non_annotations(): @@ -226,6 +277,20 @@ def test_use_typing_attributes_as_non_annotations(): print(y1, str(y2) in allowed_optional_strings) print(z1, str(z2) in allowed_optional_strings) +try: + import numpy.typing as npt + import numpy as np +except ImportError: + # we can't actually use numpy typing right now, it was just part + # of a reproducer that caused a compiler crash. We don't need it + # available to use it in annotations, so don't fail if it's not there + pass + +def list_float_to_numpy(z: List[float]) -> List[npt.NDArray[np.float64]]: + # since we're not actually requiring numpy, don't make the return type match + assert cython.typeof(z) == 'list' + return [z[0]] + if cython.compiled: __doc__ = """ # passing non-dicts to variables declared as dict now fails
[BUG] Compiler crash in AnalyseDeclarationsTransform ### Describe the bug Cython crashes when trying to parse a Python function with the following signature: ```python def foo(self, z: List[float]) -> List[npt.NDArray[np.float64]]: ``` ``` Error compiling Cython file: ------------------------------------------------------------ ... import numpy.typing as npt from dataclasses import dataclass from typing import List class Foo: def foo(self, z: List[float]) -> List[npt.NDArray[np.float64]]: ^ ------------------------------------------------------------ test.py:7:41: Compiler crash in AnalyseDeclarationsTransform File 'ModuleNode.py', line 187, in analyse_declarations: ModuleNode(test.py:1:0, full_module_name = 'test') File 'Nodes.py', line 393, in analyse_declarations: StatListNode(test.py:1:0) File 'Nodes.py', line 393, in analyse_declarations: StatListNode(test.py:6:0) File 'Nodes.py', line 5046, in analyse_declarations: PyClassDefNode(test.py:6:0, name = 'Foo') File 'Nodes.py', line 393, in analyse_declarations: StatListNode(test.py:7:4) File 'Nodes.py', line 3159, in analyse_declarations: DefNode(test.py:7:4, modifiers = [...]/0, name = 'foo', np_args_idx = [...]/0, num_required_args = 2, outer_attrs = [...]/2, py_wrapper_required = True, reqd_kw_flags_cname = '0') File 'ExprNodes.py', line 14116, in analyse_type_annotation: AnnotationNode(test.py:7:37, result_is_used = True, use_managed_ref = True) File 'ExprNodes.py', line 3741, in analyse_pytyping_modifiers: IndexNode(test.py:7:41, is_subscript = True, result_is_used = True, use_managed_ref = True) Compiler crash traceback from this point on: File "/home/raphael/projects/github/minimal-cython-example/.venv/lib/python3.10/site-packages/Cython/Compiler/ExprNodes.py", line 3741, in analyse_pytyping_modifiers if modifier_type.python_type_constructor_name and modifier_type.modifier_name: AttributeError: 'NoneType' object has no attribute 'python_type_constructor_name' Traceback (most recent call last): File "/home/raphael/projects/github/minimal-cython-example/.venv/bin/cythonize", line 8, in <module> sys.exit(main()) File "/home/raphael/projects/github/minimal-cython-example/.venv/lib/python3.10/site-packages/Cython/Build/Cythonize.py", line 226, in main cython_compile(path, options) File "/home/raphael/projects/github/minimal-cython-example/.venv/lib/python3.10/site-packages/Cython/Build/Cythonize.py", line 68, in cython_compile ext_modules = cythonize( File "/home/raphael/projects/github/minimal-cython-example/.venv/lib/python3.10/site-packages/Cython/Build/Dependencies.py", line 1129, in cythonize cythonize_one(*args) File "/home/raphael/projects/github/minimal-cython-example/.venv/lib/python3.10/site-packages/Cython/Build/Dependencies.py", line 1296, in cythonize_one raise CompileError(None, pyx_file) Cython.Compiler.Errors.CompileError: /home/raphael/projects/github/minimal-cython-example/test.py ``` ### Code to reproduce the behaviour: ```cython import numpy as np import numpy.typing as npt from dataclasses import dataclass from typing import List class Foo: def foo(self, z: List[float]) -> List[npt.NDArray[np.float64]]: return [np.array(z)] foo = Foo() print(foo.foo([1.0])) ``` ### Expected behaviour Not crashing but compiling the code. ### Environment OS: Linux Python version 3.10.5 Cython version 3.0.0a11 ### Additional context Repository with a minimal example to reproduce the issue: https://github.com/rnestler/minimal-cython-example/tree/dd5648408bda1305d65a5a8aa22fdebbe0b7c4bf
Changing the `List` annotations to `list` fixes it. Thanks for the report. A lot of this annotation type analysis is fairly new so the bugs are still falling out. We don't do much in Cython with the annotations beyond the initial `list` so you don't lose anything by switching to that. If you want to full annotation for documentation purposes then you can always turn off the `annotation_typing` directive locally for the function.
2022-10-02T16:43:03Z
[]
[]
cython/cython
5,068
cython__cython-5068
[ "5067" ]
009b00b413258d9324675f31e838a75651f2e08c
diff --git a/Cython/Compiler/TypeSlots.py b/Cython/Compiler/TypeSlots.py --- a/Cython/Compiler/TypeSlots.py +++ b/Cython/Compiler/TypeSlots.py @@ -965,8 +965,8 @@ def __init__(self, old_binops): # Added in release 2.2 # The following require the Py_TPFLAGS_HAVE_CLASS flag - BinopSlot(binaryfunc, "nb_floor_divide", "__floordiv__", method_name_to_slot), - BinopSlot(binaryfunc, "nb_true_divide", "__truediv__", method_name_to_slot), + BinopSlot(bf, "nb_floor_divide", "__floordiv__", method_name_to_slot), + BinopSlot(bf, "nb_true_divide", "__truediv__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_floor_divide", "__ifloordiv__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_true_divide", "__itruediv__", method_name_to_slot), @@ -974,7 +974,7 @@ def __init__(self, old_binops): MethodSlot(unaryfunc, "nb_index", "__index__", method_name_to_slot), # Added in release 3.5 - BinopSlot(binaryfunc, "nb_matrix_multiply", "__matmul__", method_name_to_slot, + BinopSlot(bf, "nb_matrix_multiply", "__matmul__", method_name_to_slot, ifdef="PY_VERSION_HEX >= 0x03050000"), MethodSlot(ibinaryfunc, "nb_inplace_matrix_multiply", "__imatmul__", method_name_to_slot, ifdef="PY_VERSION_HEX >= 0x03050000"),
diff --git a/tests/run/binop_reverse_methods_GH2056.pyx b/tests/run/binop_reverse_methods_GH2056.pyx --- a/tests/run/binop_reverse_methods_GH2056.pyx +++ b/tests/run/binop_reverse_methods_GH2056.pyx @@ -30,6 +30,12 @@ class Base(object): 'Base.__rpow__(Base(), 2, None)' >>> pow(Base(), 2, 100) 'Base.__pow__(Base(), 2, 100)' + >>> Base() // 1 + True + >>> set() // Base() + True + + # version dependent tests for @ and / are external """ implemented: cython.bint @@ -67,6 +73,44 @@ class Base(object): def __repr__(self): return "%s()" % (self.__class__.__name__) + # The following methods were missed from the initial implementation + # that typed 'self'. These tests are a quick test to confirm that + # but not the full binop behaviour + def __matmul__(self, other): + return cython.typeof(self) == 'Base' + + def __rmatmul__(self, other): + return cython.typeof(self) == 'Base' + + def __truediv__(self, other): + return cython.typeof(self) == 'Base' + + def __rtruediv__(self, other): + return cython.typeof(self) == 'Base' + + def __floordiv__(self, other): + return cython.typeof(self) == 'Base' + + def __rfloordiv__(self, other): + return cython.typeof(self) == 'Base' + + +if sys.version_info >= (3, 5): + __doc__ += """ + >>> Base() @ 1 + True + >>> set() @ Base() + True + """ + +if sys.version_info >= (3, 0): + __doc__ += """ + >>> Base() / 1 + True + >>> set() / Base() + True + """ + @cython.c_api_binop_methods(False) @cython.cclass
[BUG] type of 'self' in __truediv__ method ### Describe the bug I notice the argument `self` in method `__truediv__` is not regarded as type Self@CClass currectly. ### Code to reproduce the behaviour: ```cython cdef class TestDiv: cdef int x def __cinit__(self): self.x = 1 def __mul__(self, other): return self.x def __truediv__(self, other): return self.x ``` In method `__mul__`, `self.x` is complited to `__pyx_v_self->x`, while in `__truediv__`, it is complited to `__Pyx_PyObject_GetAttrStr(__pyx_v_self, __pyx_n_s_x)`. And the same situation happens on methods including `__rtruediv__`, `__floordiv__`, `__matmul__`. ### Expected behaviour `self` in methods above should have the same behavior as `self` in other methods. ### Environment OS: Windows Python version 3.8.12 Cython version 3.0.0a10 & 3.0.0a11 ### Additional context _No response_
I suspect these have just been missed from the `c_api_binop_methods` change. It's probably a relatively simple fix.
2022-10-06T18:01:05Z
[]
[]
cython/cython
5,073
cython__cython-5073
[ "3798" ]
74bcd91438a6f7f94417dfc4d50f572cfa50f820
diff --git a/Cython/Compiler/Builtin.py b/Cython/Compiler/Builtin.py --- a/Cython/Compiler/Builtin.py +++ b/Cython/Compiler/Builtin.py @@ -6,7 +6,7 @@ from .StringEncoding import EncodedString from .Symtab import BuiltinScope, StructOrUnionScope, ModuleScope, Entry -from .Code import UtilityCode +from .Code import UtilityCode, TempitaUtilityCode from .TypeSlots import Signature from . import PyrexTypes @@ -91,6 +91,28 @@ def declare_in_type(self, self_type): self.py_name, method_type, self.cname, utility_code=self.utility_code) +class BuiltinProperty(object): + # read only for now + def __init__(self, py_name, property_type, call_cname, + exception_value=None, exception_check=None, utility_code=None): + self.py_name = py_name + self.property_type = property_type + self.call_cname = call_cname + self.utility_code = utility_code + self.exception_value = exception_value + self.exception_check = exception_check + + def declare_in_type(self, self_type): + self_type.scope.declare_cproperty( + self.py_name, + self.property_type, + self.call_cname, + exception_value=self.exception_value, + exception_check=self.exception_check, + utility_code=self.utility_code + ) + + builtin_function_table = [ # name, args, return, C API func, py equiv = "*" BuiltinFunction('abs', "d", "d", "fabs", @@ -338,6 +360,32 @@ def declare_in_type(self, self_type): ("frozenset", "PyFrozenSet_Type", []), ("Exception", "((PyTypeObject*)PyExc_Exception)[0]", []), ("StopAsyncIteration", "((PyTypeObject*)__Pyx_PyExc_StopAsyncIteration)[0]", []), + ("memoryview", "PyMemoryView_Type", [ + # TODO - format would be nice, but hard to get + # __len__ can be accessed through a direct lookup of the buffer (but probably in Optimize.c) + # error checking would ideally be limited api only + BuiltinProperty("ndim", PyrexTypes.c_int_type, '__Pyx_PyMemoryview_Get_ndim', + exception_value="-1", exception_check=True, + utility_code=TempitaUtilityCode.load_cached( + "memoryview_get_from_buffer", "Builtins.c", + context=dict(name="ndim") + ) + ), + BuiltinProperty("readonly", PyrexTypes.c_bint_type, '__Pyx_PyMemoryview_Get_readonly', + exception_value="-1", exception_check=True, + utility_code=TempitaUtilityCode.load_cached( + "memoryview_get_from_buffer", "Builtins.c", + context=dict(name="readonly") + ) + ), + BuiltinProperty("itemsize", PyrexTypes.c_py_ssize_t_type, '__Pyx_PyMemoryview_Get_itemsize', + exception_value="-1", exception_check=True, + utility_code=TempitaUtilityCode.load_cached( + "memoryview_get_from_buffer", "Builtins.c", + context=dict(name="itemsize") + ) + )] + ) ] @@ -349,6 +397,7 @@ def declare_in_type(self, self_type): 'tuple', 'list', 'dict', 'set', 'frozenset', # 'str', # only in Py3.x # 'file', # only in Py2.x + 'memoryview' }) @@ -424,10 +473,10 @@ def init_builtins(): '__debug__', PyrexTypes.c_const_type(PyrexTypes.c_bint_type), pos=None, cname='(!Py_OptimizeFlag)', is_cdef=True) - global list_type, tuple_type, dict_type, set_type, frozenset_type - global bytes_type, str_type, unicode_type, basestring_type, slice_type - global float_type, long_type, bool_type, type_type, complex_type, bytearray_type - global int_type + global type_type, list_type, tuple_type, dict_type, set_type, frozenset_type + global slice_type, bytes_type, str_type, unicode_type, basestring_type, bytearray_type + global float_type, int_type, long_type, bool_type, complex_type + global memoryview_type, py_buffer_type type_type = builtin_scope.lookup('type').type list_type = builtin_scope.lookup('list').type tuple_type = builtin_scope.lookup('tuple').type @@ -445,6 +494,7 @@ def init_builtins(): long_type = builtin_scope.lookup('long').type bool_type = builtin_scope.lookup('bool').type complex_type = builtin_scope.lookup('complex').type + memoryview_type = builtin_scope.lookup('memoryview').type # Set up type inference links between equivalent Python/C types bool_type.equivalent_type = PyrexTypes.c_bint_type @@ -456,6 +506,8 @@ def init_builtins(): complex_type.equivalent_type = PyrexTypes.c_double_complex_type PyrexTypes.c_double_complex_type.equivalent_type = complex_type + py_buffer_type = builtin_scope.lookup('Py_buffer').type + init_builtins() diff --git a/Cython/Compiler/FusedNode.py b/Cython/Compiler/FusedNode.py --- a/Cython/Compiler/FusedNode.py +++ b/Cython/Compiler/FusedNode.py @@ -401,13 +401,28 @@ def _buffer_parse_format_string_check(self, pyx_code, decl_code, pyx_code.context.update( specialized_type_name=specialized_type.specialization_string, - sizeof_dtype=self._sizeof_dtype(dtype)) + sizeof_dtype=self._sizeof_dtype(dtype), + ndim_dtype=specialized_type.ndim, + dtype_is_struct_obj=int(dtype.is_struct or dtype.is_pyobject)) + # use the memoryview object to check itemsize and ndim. + # In principle it could check more, but these are the easiest to do quickly pyx_code.put_chunk( u""" # try {{dtype}} - if itemsize == -1 or itemsize == {{sizeof_dtype}}: - memslice = {{coerce_from_py_func}}(arg, 0) + if (((itemsize == -1 and arg_as_memoryview.itemsize == {{sizeof_dtype}}) + or itemsize == {{sizeof_dtype}}) + and arg_as_memoryview.ndim == {{ndim_dtype}}): + {{if dtype_is_struct_obj}} + if __PYX_IS_PYPY2: + # I wasn't able to diagnose why, but PyPy2 fails to convert a + # memoryview to a Cython memoryview in this case + memslice = {{coerce_from_py_func}}(arg, 0) + else: + {{else}} + if True: + {{endif}} + memslice = {{coerce_from_py_func}}(arg_as_memoryview, 0) if memslice.memview: __PYX_XCLEAR_MEMVIEW(&memslice, 1) # print 'found a match for the buffer through format parsing' @@ -474,9 +489,20 @@ def _buffer_checks(self, buffer_types, pythran_types, pyx_code, decl_code, env): self._buffer_check_numpy_dtype(pyx_code, buffer_types, pythran_types) pyx_code.dedent(2) - for specialized_type in buffer_types: - self._buffer_parse_format_string_check( - pyx_code, decl_code, specialized_type, env) + # creating a Cython memoryview from a Python memoryview avoids the + # need to get the buffer multiple times, and we can + # also use it to check itemsizes etc + pyx_code.put_chunk( + """ + try: + arg_as_memoryview = memoryview(arg) + except TypeError: + pass + """) + with pyx_code.indenter("else:"): + for specialized_type in buffer_types: + self._buffer_parse_format_string_check( + pyx_code, decl_code, specialized_type, env) def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_types): """ @@ -490,6 +516,7 @@ def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_ty void __PYX_XCLEAR_MEMVIEW({{memviewslice_cname}} *, int have_gil) bint __pyx_memoryview_check(object) + bint __PYX_IS_PYPY2 "(CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION == 2)" """) pyx_code.local_variable_declarations.put_chunk( @@ -514,6 +541,12 @@ def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_ty ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable() """) + pyx_code.imports.put_chunk( + u""" + cdef memoryview arg_as_memoryview + """ + ) + seen_typedefs = set() seen_int_dtypes = set() for buffer_type in all_buffer_types: diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -2709,6 +2709,40 @@ def _handle_simple_function_bool(self, node, function, pos_args): # coerce back to Python object as that's the result we are expecting return operand.coerce_to_pyobject(self.current_env()) + PyMemoryView_FromObject_func_type = PyrexTypes.CFuncType( + Builtin.memoryview_type, [ + PyrexTypes.CFuncTypeArg("value", PyrexTypes.py_object_type, None) + ]) + + PyMemoryView_FromBuffer_func_type = PyrexTypes.CFuncType( + Builtin.memoryview_type, [ + PyrexTypes.CFuncTypeArg("value", Builtin.py_buffer_type, None) + ]) + + def _handle_simple_function_memoryview(self, node, function, pos_args): + if len(pos_args) != 1: + self._error_wrong_arg_count('memoryview', node, pos_args, '1') + return node + else: + if pos_args[0].type.is_pyobject: + return ExprNodes.PythonCapiCallNode( + node.pos, "PyMemoryView_FromObject", + self.PyMemoryView_FromObject_func_type, + args = [pos_args[0]], + is_temp = node.is_temp, + py_name = "memoryview") + elif pos_args[0].type.is_ptr and pos_args[0].base_type is Builtin.py_buffer_type: + # TODO - this currently doesn't work because the buffer fails a + # "can coerce to python object" test earlier. But it'd be nice to support + return ExprNodes.PythonCapiCallNode( + node.pos, "PyMemoryView_FromBuffer", + self.PyMemoryView_FromBuffer_func_type, + args = [pos_args[0]], + is_temp = node.is_temp, + py_name = "memoryview") + return node + + ### builtin functions Pyx_strlen_func_type = PyrexTypes.CFuncType(
diff --git a/tests/run/builtin_memory_view.pyx b/tests/run/builtin_memory_view.pyx new file mode 100644 --- /dev/null +++ b/tests/run/builtin_memory_view.pyx @@ -0,0 +1,40 @@ +# mode: run + +# Tests Python's builtin memoryview. + +from __future__ import print_function + +cimport cython +#from cpython.memoryview cimport PyMemoryView_GET_BUFFER + [email protected]_fail_if_path_exists("//SimpleCallNode") +def test_convert_from_obj(o): + """ + >>> abc = b'abc' + >>> all(x == y for x, y in zip(test_convert_from_obj(abc), abc)) + True + """ + return memoryview(o) + +# TODO - this currently doesn't work because the buffer fails a +# "can coerce to python object" test earlier. But it'd be nice to support +''' +def test_create_from_buffer(): + """ + memoryview from Py_buffer exists and is special-cased + >>> mview = test_create_from_buffer() + >>> >>> all(x == y for x, y in zip(mview, b'argh!')) + True + """ + other_view = memoryview(b'argh!') + cdef Py_buffer *buf = PyMemoryView_GET_BUFFER(other_view) + return memoryview(buf) +''' + [email protected]_fail_if_path_exists("//AttributeNode") +def test_optimized_attributes(memoryview view): + """ + >>> test_optimized_attributes(memoryview(b'zzzzz')) + 1 1 True + """ + print(view.itemsize, view.ndim, view.readonly)
[ENH] Builtin type support for `memoryview` <!-- **Note:** - Do not use the bug and feature tracker for support requests. Use the `cython-users` mailing list instead. - Did you search for similar issues already? Please do, it helps to save us precious time that we otherwise could not invest into development. - Did you try the latest master branch or pre-release? It might already have what you want to report. Also see the [Changelog](https://github.com/cython/cython/blob/master/CHANGES.rst) regarding recent changes. --> **Is your feature request related to a problem? Please describe.** It would be useful to have support for a generic builtin `memoryview`. This can come in handy when the type and dimensionality of the `memoryview` are unknown. In these cases it's tricky to use the Cython `memoryview` as we don't have enough information to type it correctly (or maybe there are tricks I don't know?). The benefit being (much like other builtin types) Cython can translate operations on the `memoryview` into more efficient Python C API calls. **Describe the solution you'd like** Here's some sample code showing how this might be used. ```cython def nbytes(memoryview m): cdef Py_ssize_t i, n = m.itemsize for i in range(m.ndim): n *= m.shape[i] return n ``` **Describe alternatives you've considered** If one knows the type and dimensionality, a Cython `memoryview` can be used. However this doesn't cover the case discussed above (unless I'm missing something). Another alternative is to use the Python C API directly (though this may be less pleasant for other readers and could be buggy if not carefully used). **Additional context** NA
What C API functions are you hoping that Cython will generate? There don't look to be a huge number and they're mostly about creating memoryviews: https://docs.python.org/3/c-api/memoryview.html. Similarly [the semi-public struct](https://github.com/python/cpython/blob/8784d3300ec4ffc58bc0e9ab3cff9a24187dbe4c/Include/memoryobject.h#L57) doesn't actually expose a lot of information - all the useful shape/strides/suboffset info is hidden an opaque array at the end. Looking at in more detail I think you'd get the information by accessing the buffer object so maybe there is something that Cython could do here... Yeah I’m hoping things like `memoryview(a)` are translated into `PyMemoryView_FromObject(a)`, `isinstance(mv, memoryview)` gets translated into an appropriate low-level type check, it may also be valuable to have a method to call `PyMemoryView_GetContiguous`, etc.. As to the underlying `Py_buffer`, I think we should be able to get access to it pretty easily as `PyMemoryView_GET_BUFFER` is a macro that does just that. Though agree queries around the buffer can routed through this mechanism. If you wanted to have a go at writing it then https://github.com/cython/cython/blob/be43235ba3f4fca32dceda46424b36afb3cb00c9/Cython/Compiler/Builtin.py#L252 is where all the types and their member functions are declared (a few are also in Optimize.py, but I think memoryviews would make most sense in Builtin.py. I think getting something basic working is likely to be fairly easy (these type declarations are pretty simple and repetitive). I suspect the hardest part will be providing fallback versions for PyPy, but that's something we can give suggestions on once it's clear what's needed. Thanks for the pointer. That seems like a good place to start. Do you think we could add [C inline properties]( https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#c-inline-properties ) for the various properties on `memoryview` as well? If so, would they ago in `Builtin.py` or would they go elsewhere? How does Cython handle this kind of thing usually? > Do you think we could add C inline properties for the various properties on memoryview as well? It doesn't look like we currently have any examples of handling this kind of thing for the core types. It'd probably need to go in `Builtin.py` with a new class (`BuiltinProperty`) alongside `BuiltinMethod` and `BuiltinAttribute` but that's easier said than done. > How does Cython handle this kind of thing usually? There is no "usually" here because most of the code in `Builtin.py` predates C inline properties by years, if not a decade or more. ;-) But yes, inline properties seem right for this. I remember seeing a somewhat recent PR (this year?) that included an unrelated refactoring of `Builtin.py` to use a class for the extension type declarations. Can't find it right now, but it might be worth basing the changes on that.
2022-10-09T09:59:39Z
[]
[]
cython/cython
5,076
cython__cython-5076
[ "3783" ]
f2e8b2f3dca7436630b1b4a4d42305adcf173ece
diff --git a/Cython/Compiler/PyrexTypes.py b/Cython/Compiler/PyrexTypes.py --- a/Cython/Compiler/PyrexTypes.py +++ b/Cython/Compiler/PyrexTypes.py @@ -1561,6 +1561,7 @@ def __hash__(self): class CConstType(BaseType): is_const = 1 + subtypes = ['const_base_type'] def __init__(self, const_base_type): self.const_base_type = const_base_type
diff --git a/tests/errors/fused_types.pyx b/tests/errors/fused_types.pyx --- a/tests/errors/fused_types.pyx +++ b/tests/errors/fused_types.pyx @@ -1,4 +1,5 @@ # mode: error +# ticket: 1772 cimport cython from cython import fused_type @@ -64,17 +65,30 @@ ctypedef fused fused2: func(x, y) +cdef fused mix_const_t: + int + const int + +cdef cdef_func_with_mix_const_type(mix_const_t val): + print(val) + +# Mixing const and non-const type makes fused type ambiguous +cdef_func_with_mix_const_type(1) + + _ERRORS = u""" -10:15: fused_type does not take keyword arguments -15:33: Type specified multiple times -26:0: Invalid use of fused types, type cannot be specialized -26:4: Not enough types specified to specialize the function, int2_t is still fused +11:15: fused_type does not take keyword arguments +16:33: Type specified multiple times 27:0: Invalid use of fused types, type cannot be specialized 27:4: Not enough types specified to specialize the function, int2_t is still fused -28:16: Call with wrong number of arguments (expected 2, got 1) -29:16: Call with wrong number of arguments (expected 2, got 3) -36:6: Invalid base type for memoryview slice: int * -39:0: Fused lambdas not allowed -42:5: Fused types not allowed here -45:9: Fused types not allowed here +28:0: Invalid use of fused types, type cannot be specialized +28:4: Not enough types specified to specialize the function, int2_t is still fused +29:16: Call with wrong number of arguments (expected 2, got 1) +30:16: Call with wrong number of arguments (expected 2, got 3) +37:6: Invalid base type for memoryview slice: int * +40:0: Fused lambdas not allowed +43:5: Fused types not allowed here +46:9: Fused types not allowed here +76:0: Invalid use of fused types, type cannot be specialized +76:29: ambiguous overloaded method """ diff --git a/tests/memoryview/numpy_memoryview_readonly.pyx b/tests/memoryview/numpy_memoryview_readonly.pyx --- a/tests/memoryview/numpy_memoryview_readonly.pyx +++ b/tests/memoryview/numpy_memoryview_readonly.pyx @@ -1,10 +1,14 @@ # mode: run # tag: readonly, const, numpy +# ticket: 1772 import numpy as np +cimport cython -def new_array(): - return np.arange(10).astype('float') +def new_array(dtype='float', writeable=True): + array = np.arange(10, dtype=dtype) + array.setflags(write=writeable) + return array ARRAY = new_array() @@ -124,3 +128,45 @@ def test_copy(): rw[1] = 2 rw2[2] = 2 return rw[0], rw[1], rw[2], rw2[0], rw2[1], rw2[2] + + +cdef getmax_floating(const cython.floating[:] x): + """Function with fused type, should work with both ro and rw memoryviews""" + cdef cython.floating max_val = - float('inf') + for val in x: + if val > max_val: + max_val = val + return max_val + + +def test_mmview_const_fused_cdef(): + """Test cdef function with const fused type memory view as argument. + + >>> test_mmview_const_fused_cdef() + """ + cdef float[:] data_rw = new_array(dtype='float32') + assert getmax_floating(data_rw) == 9 + + cdef const float[:] data_ro = new_array(dtype='float32', writeable=False) + assert getmax_floating(data_ro) == 9 + + +def test_mmview_const_fused_def(const cython.floating[:] x): + """Test def function with const fused type memory view as argument. + + With read-write numpy array: + + >>> test_mmview_const_fused_def(new_array('float32', writeable=True)) + 0.0 + >>> test_mmview_const_fused_def(new_array('float64', writeable=True)) + 0.0 + + With read-only numpy array: + + >>> test_mmview_const_fused_def(new_array('float32', writeable=False)) + 0.0 + >>> test_mmview_const_fused_def(new_array('float64', writeable=False)) + 0.0 + """ + cdef cython.floating result = x[0] + return result diff --git a/tests/run/fused_types.pyx b/tests/run/fused_types.pyx --- a/tests/run/fused_types.pyx +++ b/tests/run/fused_types.pyx @@ -1,4 +1,5 @@ # mode: run +# ticket: 1772 cimport cython from cython.view cimport array @@ -363,6 +364,22 @@ def test_fused_memslice_dtype_repeated_2(cython.floating[:] array1, cython.float """ print cython.typeof(array1), cython.typeof(array2), cython.typeof(array3) +def test_fused_const_memslice_dtype_repeated(const cython.floating[:] array1, cython.floating[:] array2): + """Test fused types memory view with one being const + + >>> sorted(test_fused_const_memslice_dtype_repeated.__signatures__) + ['double', 'float'] + + >>> test_fused_const_memslice_dtype_repeated(get_array(8, 'd'), get_array(8, 'd')) + const double[:] double[:] + >>> test_fused_const_memslice_dtype_repeated(get_array(4, 'f'), get_array(4, 'f')) + const float[:] float[:] + >>> test_fused_const_memslice_dtype_repeated(get_array(8, 'd'), get_array(4, 'f')) + Traceback (most recent call last): + ValueError: Buffer dtype mismatch, expected 'double' but got 'float' + """ + print cython.typeof(array1), cython.typeof(array2) + def test_cython_numeric(cython.numeric arg): """ Test to see whether complex numbers have their utility code declared @@ -388,6 +405,18 @@ def test_index_fused_args(cython.floating f, ints_t i): """ _test_index_fused_args[cython.floating, ints_t](f, i) +cdef _test_index_const_fused_args(const cython.floating f, const ints_t i): + print(cython.typeof(f), cython.typeof(i)) + +def test_index_const_fused_args(const cython.floating f, const ints_t i): + """Test indexing function implementation with const fused type args + + >>> import cython + >>> test_index_const_fused_args[cython.double, cython.int](2.0, 3) + ('const double', 'const int') + """ + _test_index_const_fused_args[cython.floating, ints_t](f, i) + def test_composite(fused_composite x): """ @@ -404,6 +433,30 @@ def test_composite(fused_composite x): return 2 * x +cdef cdef_func_const_fused_arg(const cython.floating val, + const fused_type1 * ptr_to_const, + const (cython.floating *) const_ptr): + print(val, cython.typeof(val)) + print(ptr_to_const[0], cython.typeof(ptr_to_const[0])) + print(const_ptr[0], cython.typeof(const_ptr[0])) + + ptr_to_const = NULL # pointer is not const, value is const + const_ptr[0] = 0.0 # pointer is const, value is not const + +def test_cdef_func_with_const_fused_arg(): + """Test cdef function with const fused type argument + + >>> test_cdef_func_with_const_fused_arg() + (0.0, 'const float') + (1, 'const int') + (2.0, 'float') + """ + cdef float arg0 = 0.0 + cdef int arg1 = 1 + cdef float arg2 = 2.0 + cdef_func_const_fused_arg(arg0, &arg1, &arg2) + + ### see GH3642 - presence of cdef inside "unrelated" caused a type to be incorrectly inferred cdef unrelated(cython.floating x): cdef cython.floating t = 1
[BUG] CompileError with `const fused_t[:, ::1]` argument **Describe the bug** Addition of a `const` identifier to the fused type declaration crashes the compiler. This is already reported in #3222 but marked as solved. Hence I am not sure whether this is related. Without the `const` it compiles fine. **To Reproduce** Code to reproduce the behaviour: ```cython %%cython -3 -a import cython cimport numpy as cnp from libc.math cimport isfinite ctypedef fused lapack_t: float double float complex double complex ctypedef float complex float_complex ctypedef fused lapack_cz_t: float complex double complex ctypedef fused lapack_sd_t: float double @cython.boundscheck(False) @cython.wraparound(False) cpdef inline bint array_chkfinite(const lapack_t[:, ::1]A): """ """ cdef size_t n = A.shape[0] cdef int r, c cdef lapack_t entry if lapack_t in lapack_cz_t: for r in xrange(n): for c in xrange(n): entry = A[r, c] if not(isfinite(entry.real) and isfinite(entry.imag)): return False else: for r in xrange(n): for c in xrange(n): if isfinite(A[r, c]): return False return True ``` This throws the following error <details> ```bash Error compiling Cython file: ------------------------------------------------------------ ... float double @cython.boundscheck(False) @cython.wraparound(False) cpdef inline bint array_chkfinite(const lapack_t[:, ::1]A): ^ ------------------------------------------------------------ C:\Users\Ilhan Polat\.ipython\cython\_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:49: Compiler crash in AnalyseDeclarationsTransform File 'ModuleNode.py', line 124, in analyse_declarations: ModuleNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:1:0, full_module_name = '_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286') File 'Nodes.py', line 431, in analyse_declarations: StatListNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:1:0) File 'Nodes.py', line 431, in analyse_declarations: StatListNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:6) File 'Nodes.py', line 375, in analyse_declarations: CompilerDirectivesNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:6) File 'Nodes.py', line 431, in analyse_declarations: StatListNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:6) File 'Nodes.py', line 2354, in analyse_declarations: CFuncDefNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:6, decorators = [...]/0, doc = '\n\n ', modifiers = [...]/1, overridable = 1, visibility = 'private') File 'Nodes.py', line 681, in analyse: CFuncDeclaratorNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:33, calling_convention = '', overridable = 1) File 'Nodes.py', line 891, in analyse: CArgDeclNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:34, is_generic = 1, outer_attrs = [...]/2) File 'Nodes.py', line 1091, in analyse: MemoryViewSliceTypeNode(_cython_magic_d06ba7f2fb4592a1e2bcd75d12e69286.pyx:21:49, is_arg = True, name = 'memoryview') Compiler crash traceback from this point on: File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Nodes.py", line 1091, in analyse self.type = PyrexTypes.MemoryViewSliceType(base_type, axes_specs) File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 625, in __init__ self.dtype_name = Buffer.mangle_dtype_name(self.dtype) File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\Buffer.py", line 631, in mangle_dtype_name return prefix + dtype.specialization_name() File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 57, in specialization_name common_subs = (self.empty_declaration_code() File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 51, in empty_declaration_code self._empty_declaration = self.declaration_code('') File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 1582, in declaration_code return self.const_base_type.declaration_code("const %s" % entity_code, for_display, dll_linkage, pyrex) File "c:\users\ilhan polat\appdata\local\programs\python\python38\lib\site-packages\Cython\Compiler\PyrexTypes.py", line 1649, in declaration_code raise Exception("This may never happen, please report a bug") Exception: This may never happen, please report a bug ``` </details> **Environment (please complete the following information):** - OS: Windows 10.1904 - Python version 3.8.0 - Cython version 0.29.21
2022-10-09T15:24:27Z
[]
[]
cython/cython
5,079
cython__cython-5079
[ "5070" ]
3a2e365d288e52652fc689841f3b8e97d00dc233
diff --git a/Cython/Compiler/ExprNodes.py b/Cython/Compiler/ExprNodes.py --- a/Cython/Compiler/ExprNodes.py +++ b/Cython/Compiler/ExprNodes.py @@ -2143,7 +2143,7 @@ def analyse_as_type(self, env): # Try to give a helpful warning when users write plain C type names. if not env.in_c_type_context and PyrexTypes.parse_basic_type(self.name): - warning(self.pos, "Found C type '%s' in a Python annotation. Did you mean to use a Python type?" % self.name) + warning(self.pos, "Found C type '%s' in a Python annotation. Did you mean to use 'cython.%s'?" % (self.name, self.name)) return None @@ -14428,6 +14428,33 @@ def analyse_as_type(self, env): # for compatibility when used as a return_type_node, have this interface too return self.analyse_type_annotation(env)[1] + def _warn_on_unknown_annotation(self, env, annotation): + """Method checks for cases when user should be warned that annotation contains unknown types.""" + if annotation.is_name: + # Validate annotation in form `var: type` + if not env.lookup(annotation.name): + warning(annotation.pos, + "Unknown type declaration '%s' in annotation, ignoring" % self.string.value, level=1) + elif annotation.is_attribute and annotation.obj.is_name: + # Validate annotation in form `var: module.type` + if not env.lookup(annotation.obj.name): + # `module` is undeclared + warning(annotation.pos, + "Unknown type declaration '%s' in annotation, ignoring" % self.string.value, level=1) + elif annotation.obj.is_cython_module: + # `module` is cython + module_scope = annotation.obj.analyse_as_module(env) + if module_scope and not module_scope.lookup_type(annotation.attribute): + error(annotation.pos, + "Unknown type declaration '%s' in annotation" % self.string.value) + else: + module_scope = annotation.obj.analyse_as_module(env) + if module_scope and module_scope.pxd_file_loaded: + warning(annotation.pos, + "Unknown type declaration '%s' in annotation, ignoring" % self.string.value, level=1) + else: + warning(annotation.pos, "Unknown type declaration in annotation, ignoring") + def analyse_type_annotation(self, env, assigned_value=None): if self.untyped: # Already applied as a fused type, not re-evaluating it here. @@ -14454,7 +14481,7 @@ def analyse_type_annotation(self, env, assigned_value=None): arg_type = annotation.analyse_as_type(env) if arg_type is None: - warning(annotation.pos, "Unknown type declaration in annotation, ignoring") + self._warn_on_unknown_annotation(env, annotation) return [], arg_type if annotation.is_string_literal: diff --git a/docs/examples/userguide/buffer/matrix.py b/docs/examples/userguide/buffer/matrix.py --- a/docs/examples/userguide/buffer/matrix.py +++ b/docs/examples/userguide/buffer/matrix.py @@ -4,10 +4,10 @@ @cython.cclass class Matrix: - ncols: cython.unsigned + ncols: cython.uint v: vector[cython.float] - def __cinit__(self, ncols: cython.unsigned): + def __cinit__(self, ncols: cython.uint): self.ncols = ncols def add_row(self):
diff --git a/tests/errors/dataclass_e5.pyx b/tests/errors/dataclass_e5.pyx --- a/tests/errors/dataclass_e5.pyx +++ b/tests/errors/dataclass_e5.pyx @@ -14,8 +14,8 @@ cdef class C: _WARNINGS = """ 9:7: Found Python 2.x type 'long' in a Python annotation. Did you mean to use 'cython.long'? -10:7: Found C type 'Py_ssize_t' in a Python annotation. Did you mean to use a Python type? -10:7: Unknown type declaration in annotation, ignoring -12:7: Found C type 'double' in a Python annotation. Did you mean to use a Python type? -12:7: Unknown type declaration in annotation, ignoring +10:7: Found C type 'Py_ssize_t' in a Python annotation. Did you mean to use 'cython.Py_ssize_t'? +10:7: Unknown type declaration 'Py_ssize_t' in annotation, ignoring +12:7: Found C type 'double' in a Python annotation. Did you mean to use 'cython.double'? +12:7: Unknown type declaration 'double' in annotation, ignoring """ diff --git a/tests/errors/pure_warnings.py b/tests/errors/pure_warnings.py new file mode 100644 --- /dev/null +++ b/tests/errors/pure_warnings.py @@ -0,0 +1,63 @@ +# mode: error +# tag: warnings + +import cython +import typing +from cython.cimports.libc import stdint + + +def main(): + foo1: typing.Tuple = None + foo1: typing.Bar = None + foo2: Bar = 1 # warning + foo3: int = 1 + foo4: cython.int = 1 + foo5: stdint.bar = 5 # warning + foo6: object = 1 + foo7: cython.bar = 1 # error + foo8: (1 + x).b + foo9: mod.a.b + foo10: func().b + with cython.annotation_typing(False): + foo8: Bar = 1 + foo9: stdint.bar = 5 + foo10: cython.bar = 1 + + [email protected] +def bar() -> cython.bar: + pass + + [email protected] +def bar2() -> Bar: + pass + [email protected] +def bar3() -> stdint.bar: + pass + +_WARNINGS = """ +12:10: Unknown type declaration 'Bar' in annotation, ignoring +15:16: Unknown type declaration 'stdint.bar' in annotation, ignoring +18:17: Unknown type declaration in annotation, ignoring +19:15: Unknown type declaration in annotation, ignoring +20:17: Unknown type declaration in annotation, ignoring +33:14: Unknown type declaration 'Bar' in annotation, ignoring +37:20: Unknown type declaration 'stdint.bar' in annotation, ignoring + +# Spurious warnings from utility code - not part of the core test +25:10: 'cpdef_method' redeclared +36:10: 'cpdef_cname_method' redeclared +979:29: Ambiguous exception value, same as default return value: 0 +1020:46: Ambiguous exception value, same as default return value: 0 +1110:29: Ambiguous exception value, same as default return value: 0 +""" + +_ERRORS = """ +17:16: Unknown type declaration 'cython.bar' in annotation +28:13: Not a type +28:19: Unknown type declaration 'cython.bar' in annotation +33:14: Not a type +37:14: Not a type +"""
[ENH] Warn when user provides undeclared symbol in type annotation ### Is your feature request related to a problem? Please describe. Cython currently ignores annotations with undeclared types - e.g. following code is compiled correctly: ```python def main(): a: Bar = 6 ``` Compiling code without warning user can lead to errors hard to find - e.g. when developer introduces typo in annotation or forgets to use correct module -e.g.: `a: Py_ssize_t` instead of `a: typing.Py_ssize_t`. ### Describe the solution you'd like. I would like Cython to raise a warning when annotation contains symbol not defined. When user disables annotation typing with `cython.annotation_typing(False)`, warnings should be silenced. ### Describe alternatives you've considered. Another possibility is to stop compilation with error but it was rejected as warning is better solution. ### Additional context See the discussion here: https://github.com/cython/cython/pull/5069#discussion_r989736451
2022-10-11T06:37:25Z
[]
[]
cython/cython
5,094
cython__cython-5094
[ "5088" ]
171ce959441cc5a96fd3e917b5a08ba4ffb0e0aa
diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -91,6 +91,8 @@ def __init__(self, include_directories, compiler_directives, cpp=False, if language_level is not None: self.set_language_level(language_level) + self.legacy_implicit_noexcept = self.compiler_directives.get('legacy_implicit_noexcept', False) + self.gdb_debug_outputwriter = None @classmethod diff --git a/Cython/Compiler/Options.py b/Cython/Compiler/Options.py --- a/Cython/Compiler/Options.py +++ b/Cython/Compiler/Options.py @@ -218,6 +218,7 @@ def copy_inherited_directives(outer_directives, **new_directives): 'np_pythran': False, 'fast_gil': False, 'cpp_locals': False, # uses std::optional for C++ locals, so that they work more like Python locals + 'legacy_implicit_noexcept': False, # set __file__ and/or __path__ to known source/target path at import time (instead of not having them available) 'set_initial_path' : None, # SOURCEFILE or "/full/path/to/module" @@ -385,6 +386,7 @@ class DEFER_ANALYSIS_OF_ARGUMENTS: 'total_ordering': ('cclass', ), 'dataclasses.dataclass' : ('class', 'cclass',), 'cpp_locals': ('module', 'function', 'cclass'), # I don't think they make sense in a with_statement + 'legacy_implicit_noexcept': ('module', ), } @@ -776,5 +778,6 @@ def to_fingerprint(item): build_dir=None, cache=None, create_extension=None, - np_pythran=False + np_pythran=False, + legacy_implicit_noexcept=None, ) diff --git a/Cython/Compiler/Parsing.py b/Cython/Compiler/Parsing.py --- a/Cython/Compiler/Parsing.py +++ b/Cython/Compiler/Parsing.py @@ -3120,6 +3120,9 @@ def p_exception_value_clause(s, ctx): exc_check = False # exc_val can be non-None even if exc_check is False, c.f. "except -1" exc_val = p_test(s) + if not exc_clause and ctx.visibility != 'extern' and s.context.legacy_implicit_noexcept: + exc_check = False + warning(s.position(), "Implicit noexcept declaration is deprecated. Function declaration should contain 'noexcept' keyword.", level=2) return exc_val, exc_check, exc_clause c_arg_list_terminators = cython.declare(frozenset, frozenset(( @@ -3888,6 +3891,9 @@ def p_compiler_directive_comments(s): if 'language_level' in new_directives: # Make sure we apply the language level already to the first token that follows the comments. s.context.set_language_level(new_directives['language_level']) + if 'legacy_implicit_noexcept' in new_directives: + s.context.legacy_implicit_noexcept = new_directives['legacy_implicit_noexcept'] + result.update(new_directives)
diff --git a/tests/run/legacy_implicit_noexcept.pyx b/tests/run/legacy_implicit_noexcept.pyx new file mode 100644 --- /dev/null +++ b/tests/run/legacy_implicit_noexcept.pyx @@ -0,0 +1,143 @@ +# cython: legacy_implicit_noexcept=True +# mode: run +# tag: warnings +import sys +import functools +import cython +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + +cdef int func_implicit(int a, int b): + raise RuntimeError + +cdef int func_noexcept(int a, int b) noexcept: + raise RuntimeError + +cdef int func_star(int a, int b) except *: + raise RuntimeError + +cdef int func_value(int a, int b) except -1: + raise RuntimeError + +cdef func_return_obj_implicit(int a, int b): + raise RuntimeError + +cdef int(*ptr_func_implicit)(int, int) +ptr_func_implicit = func_implicit + +cdef int(*ptr_func_noexcept)(int, int) noexcept +ptr_func_noexcept = func_noexcept + [email protected] +def func_pure_implicit() -> cython.int: + raise RuntimeError + [email protected](check=False) [email protected] +def func_pure_noexcept() -> cython.int: + raise RuntimeError + +def return_stderr(func): + @functools.wraps(func) + def testfunc(): + old_stderr = sys.stderr + stderr = sys.stderr = StringIO() + try: + func() + finally: + sys.stderr = old_stderr + return stderr.getvalue().strip() + + return testfunc + +@return_stderr +def test_noexcept(): + """ + >>> print(test_noexcept()) # doctest: +ELLIPSIS + RuntimeError + Exception...ignored... + """ + func_noexcept(3, 5) + +@return_stderr +def test_ptr_noexcept(): + """ + >>> print(test_ptr_noexcept()) # doctest: +ELLIPSIS + RuntimeError + Exception...ignored... + """ + ptr_func_noexcept(3, 5) + +@return_stderr +def test_implicit(): + """ + >>> print(test_implicit()) # doctest: +ELLIPSIS + RuntimeError + Exception...ignored... + """ + func_implicit(1, 2) + +@return_stderr +def test_ptr_implicit(): + """ + >>> print(test_ptr_implicit()) # doctest: +ELLIPSIS + RuntimeError + Exception...ignored... + """ + ptr_func_implicit(1, 2) + +def test_star(): + """ + >>> test_star() + Traceback (most recent call last): + ... + RuntimeError + """ + func_star(1, 2) + +def test_value(): + """ + >>> test_value() + Traceback (most recent call last): + ... + RuntimeError + """ + func_value(1, 2) + + +def test_return_obj_implicit(): + """ + >>> test_return_obj_implicit() + Traceback (most recent call last): + ... + RuntimeError + """ + func_return_obj_implicit(1, 2) + +def test_pure_implicit(): + """ + >>> test_pure_implicit() + Traceback (most recent call last): + ... + RuntimeError + """ + func_pure_implicit() + +def test_pure_noexcept(): + """ + >>> test_pure_noexcept() + Traceback (most recent call last): + ... + RuntimeError + """ + func_pure_noexcept() + +_WARNINGS = """ +12:5: Unraisable exception in function 'legacy_implicit_noexcept.func_implicit'. +12:36: Implicit noexcept declaration is deprecated. Function declaration should contain 'noexcept' keyword. +15:5: Unraisable exception in function 'legacy_implicit_noexcept.func_noexcept'. +24:43: Implicit noexcept declaration is deprecated. Function declaration should contain 'noexcept' keyword. +27:38: Implicit noexcept declaration is deprecated. Function declaration should contain 'noexcept' keyword. +""" diff --git a/tests/run/legacy_implicit_noexcept_build.srctree b/tests/run/legacy_implicit_noexcept_build.srctree new file mode 100644 --- /dev/null +++ b/tests/run/legacy_implicit_noexcept_build.srctree @@ -0,0 +1,33 @@ +PYTHON setup.py build_ext --inplace +PYTHON -c "import bar" + +######## setup.py ######## + +from Cython.Build.Dependencies import cythonize +from distutils.core import setup + +setup( + ext_modules = cythonize("*.pyx", compiler_directives={'legacy_implicit_noexcept': True}), +) + + +######## bar.pyx ######## + +cdef int func_noexcept() noexcept: + raise RuntimeError() + +cdef int func_implicit(): + raise RuntimeError() + +cdef int func_return_value() except -1: + raise RuntimeError() + +func_noexcept() +func_implicit() + +try: + func_return_value() +except RuntimeError: + pass +else: + assert False, 'Exception not raised'
[ENH] provide command line option for enabling legacy noexcept propagation ### Is your feature request related to a problem? Please describe. As mentioned in https://github.com/cython/cython/pull/4670#issuecomment-1279918128 introducing default exception propagation in #4670 can introduce compatibility issues for cython users. ### Describe the solution you'd like. New command line option should be provided enabling legacy noexcept propagation as default: ``` cython -X noexcept ... ``` ### Describe alternatives you've considered. _No response_ ### Additional context _No response_
While, on the one hand, this would probably keep users from fixing their code and benefiting from the new, safer behaviour, on the other hand, forcing users to make the complete switch before they can migrate to Cython 3.0 isn't going to help anyone. Disabling the new behaviour does not degrade existing code bases in any way, it just keeps them as buggy as they are. This new option does not reduce the burden for the migration, though. In order to migrate even just one single function, users will have to remove the option again, and then adapt the entire module, as well as potentially starting with other modules that call into the one at hand. So, the risk is high that users just add the option and leave it there, lacking the time to migrate. It would be nice if we could continue to issue the warnings if the option is provided. In any case, the option would probably have to be separate from the `noexcept` function modifier, so this should de detectable. So, it feels difficult to actually help users with the migration by providing some kind of intermediate steps. It seems the migration is either all or nothing. And this option keeps it at nothing. I understand the need, but it would be great to have something that actually helps migrating instead. > It would be nice if we could continue to issue the warnings if the option is provided. In any case, the option would probably have to be separate from the `noexcept` function modifier, so this should de detectable. That sounds feasible though, as we have the information about the CLI flag completely separately from the parsing? That way it wouldn't reset the migration to "nothing", it would just be one more warning users will eventually need to heed before they _really_ get broken by the removal. As a maintainer of a library using Cython, I think it is sensible to have a temporary `-X` option to enable the legacy `noexcept` propagation for a few release only and instructions to let users adapt their code base to use the new `noexcept` propagation. > This new option does not reduce the burden for the migration, though. In order to migrate even just one single function, users will have to remove the option again, and then adapt the entire module, as well as potentially starting with other modules that call into the one at hand. So, the risk is high that users just add the option and leave it there, lacking the time to migrate. Hmm as long as I understand this option can be enabled on per-file bases. So users can put it to all files and gradually remove it. But I am not sure if this is good approach for users or not... EDIT: If there will be agreement between Cython maintainers that we won't go this direction, I am not against closing this issue without the fix. The main advantage of the per-file basis is that I think anything else would be hard to do with the current implementation. I don't think it's terrible for users. I'm sure a lot will just turn it on for their existing code and forget about it. But it does at least provide a solution to not break everything immediately cc @shwina (in case you have thoughts on this)
2022-10-22T19:01:04Z
[]
[]