Cython 3.2.6__py3-none-any.whl → 3.3.0a2.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of Cython might be problematic. Click here for more details.

Files changed (112) hide show
  1. Cython/Build/BuildExecutable.py +1 -14
  2. Cython/Build/Dependencies.py +6 -44
  3. Cython/Build/Inline.py +7 -3
  4. Cython/Build/IpythonMagic.py +0 -1
  5. Cython/Build/SharedModule.py +1 -2
  6. Cython/Build/Tests/TestCythonizeArgsParser.py +6 -6
  7. Cython/Build/Tests/TestDependencies.py +3 -3
  8. Cython/Build/Tests/TestInline.py +3 -3
  9. Cython/Build/Tests/TestIpythonMagic.py +35 -19
  10. Cython/Build/Tests/TestStripLiterals.py +2 -2
  11. Cython/Compiler/Buffer.py +5 -5
  12. Cython/Compiler/Builtin.py +57 -46
  13. Cython/Compiler/Code.pxd +12 -9
  14. Cython/Compiler/Code.py +220 -94
  15. Cython/Compiler/Dataclass.py +78 -52
  16. Cython/Compiler/Errors.py +21 -8
  17. Cython/Compiler/ExprNodes.py +871 -459
  18. Cython/Compiler/FlowControl.pxd +8 -6
  19. Cython/Compiler/FlowControl.py +111 -8
  20. Cython/Compiler/FusedNode.py +17 -12
  21. Cython/Compiler/Lexicon.py +123 -122
  22. Cython/Compiler/Main.py +3 -4
  23. Cython/Compiler/MatchCaseNodes.py +1948 -10
  24. Cython/Compiler/MemoryView.py +62 -33
  25. Cython/Compiler/ModuleNode.py +559 -283
  26. Cython/Compiler/Naming.py +4 -0
  27. Cython/Compiler/Nodes.py +333 -197
  28. Cython/Compiler/Optimize.py +268 -112
  29. Cython/Compiler/Options.py +0 -5
  30. Cython/Compiler/ParseTreeTransforms.pxd +2 -1
  31. Cython/Compiler/ParseTreeTransforms.py +180 -76
  32. Cython/Compiler/Parsing.py +55 -38
  33. Cython/Compiler/PyrexTypes.py +364 -128
  34. Cython/Compiler/Scanning.pxd +27 -5
  35. Cython/Compiler/Scanning.py +24 -14
  36. Cython/Compiler/StringEncoding.py +1 -2
  37. Cython/Compiler/Symtab.py +27 -19
  38. Cython/Compiler/Tests/TestBuiltin.py +41 -6
  39. Cython/Compiler/Tests/TestCmdLine.py +3 -2
  40. Cython/Compiler/Tests/TestCode.py +4 -3
  41. Cython/Compiler/Tests/TestFlowControl.py +2 -2
  42. Cython/Compiler/Tests/TestParseTreeTransforms.py +2 -2
  43. Cython/Compiler/Tests/TestScanning.py +2 -4
  44. Cython/Compiler/Tests/TestSignatureMatching.py +3 -3
  45. Cython/Compiler/Tests/TestStringEncoding.py +2 -3
  46. Cython/Compiler/Tests/TestTypes.py +46 -3
  47. Cython/Compiler/Tests/TestUtilityLoad.py +4 -4
  48. Cython/Compiler/TypeInference.py +20 -0
  49. Cython/Compiler/TypeSlots.py +171 -16
  50. Cython/Compiler/UtilNodes.py +24 -0
  51. Cython/Compiler/UtilityCode.py +1 -0
  52. Cython/Compiler/Visitor.pxd +1 -1
  53. Cython/Compiler/Visitor.py +3 -2
  54. Cython/Debugger/Tests/TestLibCython.py +7 -2
  55. Cython/Debugger/Tests/test_libcython_in_gdb.py +4 -2
  56. Cython/Debugger/Tests/test_libpython_in_gdb.py +1 -1
  57. Cython/Includes/cpython/array.pxd +5 -5
  58. Cython/Includes/cpython/dict.pxd +1 -6
  59. Cython/Includes/cpython/float.pxd +19 -10
  60. Cython/Includes/cpython/frozendict.pxd +37 -0
  61. Cython/Includes/cpython/long.pxd +31 -0
  62. Cython/Includes/cpython/object.pxd +9 -12
  63. Cython/Includes/cpython/sentinel.pxd +17 -0
  64. Cython/Includes/cpython/type.pxd +93 -0
  65. Cython/Includes/libcpp/exception.pxd +90 -0
  66. Cython/LZSS.py +170 -0
  67. Cython/Shadow.py +550 -73
  68. Cython/StringIOTree.py +1 -2
  69. Cython/Tempita/_tempita.py +45 -46
  70. Cython/TestUtils.py +50 -8
  71. Cython/Tests/TestCythonUtils.py +2 -2
  72. Cython/Tests/TestJediTyper.py +1 -1
  73. Cython/Tests/TestShadow.py +7 -5
  74. Cython/Tests/TestStringIOTree.py +4 -3
  75. Cython/Tests/TestTestUtils.py +2 -3
  76. Cython/Utility/AsyncGen.c +59 -19
  77. Cython/Utility/Buffer.c +4 -3
  78. Cython/Utility/Builtins.c +139 -17
  79. Cython/Utility/CConvert.pyx +27 -12
  80. Cython/Utility/CommonStructures.c +55 -37
  81. Cython/Utility/Coroutine.c +112 -68
  82. Cython/Utility/CythonFunction.c +607 -330
  83. Cython/Utility/Embed.c +8 -0
  84. Cython/Utility/Exceptions.c +20 -3
  85. Cython/Utility/ExtensionTypes.c +414 -224
  86. Cython/Utility/FunctionArguments.c +83 -81
  87. Cython/Utility/ImportExport.c +72 -61
  88. Cython/Utility/MatchCase.c +979 -0
  89. Cython/Utility/MatchCase_Cy.pyx +12 -0
  90. Cython/Utility/MemoryView.pxd +9 -88
  91. Cython/Utility/MemoryView.pyx +173 -61
  92. Cython/Utility/MemoryView_C.c +3 -3
  93. Cython/Utility/ModuleSetupCode.c +306 -157
  94. Cython/Utility/ObjectHandling.c +483 -404
  95. Cython/Utility/Optimize.c +1117 -164
  96. Cython/Utility/Overflow.c +3 -9
  97. Cython/Utility/Profile.c +4 -0
  98. Cython/Utility/StringTools.c +187 -149
  99. Cython/Utility/Synchronization.c +39 -0
  100. Cython/Utility/TString.c +24 -13
  101. Cython/Utility/TypeConversion.c +405 -250
  102. Cython/Utility/arrayarray.h +24 -22
  103. Cython/Utils.py +11 -23
  104. Cython/__init__.py +3 -1
  105. {cython-3.2.6.dist-info → cython-3.3.0a2.dev0.dist-info}/METADATA +14 -33
  106. {cython-3.2.6.dist-info → cython-3.3.0a2.dev0.dist-info}/RECORD +109 -107
  107. {cython-3.2.6.dist-info → cython-3.3.0a2.dev0.dist-info}/WHEEL +1 -1
  108. Cython/Shadow.pyi +0 -521
  109. Cython/Utility/Printing.c +0 -86
  110. Cython/__init__.pyi +0 -7
  111. {cython-3.2.6.dist-info → cython-3.3.0a2.dev0.dist-info}/entry_points.txt +0 -0
  112. {cython-3.2.6.dist-info → cython-3.3.0a2.dev0.dist-info}/top_level.txt +0 -0
@@ -12,20 +12,7 @@ DEBUG = True
12
12
 
13
13
  import sys
14
14
  import os
15
- if sys.version_info < (3, 9):
16
- from distutils import sysconfig as _sysconfig
17
-
18
- class sysconfig:
19
-
20
- @staticmethod
21
- def get_path(name):
22
- assert name == 'include'
23
- return _sysconfig.get_python_inc()
24
-
25
- get_config_var = staticmethod(_sysconfig.get_config_var)
26
- else:
27
- # sysconfig can be trusted from cpython >= 3.8.7
28
- import sysconfig
15
+ import sysconfig
29
16
 
30
17
 
31
18
  def get_config_var(name, default=''):
@@ -987,8 +987,6 @@ def cythonize(module_list, exclude=None, nthreads=0, aliases=None, quiet=False,
987
987
  language=language,
988
988
  aliases=aliases)
989
989
 
990
- fix_windows_unicode_modules(module_list)
991
-
992
990
  deps = create_dependency_tree(ctx, quiet=quiet)
993
991
  build_dir = getattr(options, 'build_dir', None)
994
992
  if options.cache and not (options.annotate or Options.annotate):
@@ -1180,37 +1178,6 @@ def cythonize(module_list, exclude=None, nthreads=0, aliases=None, quiet=False,
1180
1178
  return module_list
1181
1179
 
1182
1180
 
1183
- def fix_windows_unicode_modules(module_list):
1184
- # Hack around a distutils 3.[5678] bug on Windows for unicode module names.
1185
- # https://bugs.python.org/issue39432
1186
- if sys.platform != "win32":
1187
- return
1188
- if sys.version_info >= (3, 8, 2):
1189
- return
1190
-
1191
- def make_filtered_list(ignored_symbol, old_entries):
1192
- class FilteredExportSymbols(list):
1193
- # export_symbols for unicode filename cause link errors on Windows
1194
- # Cython doesn't need them (it already defines PyInit with the correct linkage)
1195
- # so use this class as a temporary fix to stop them from being generated
1196
- def __contains__(self, val):
1197
- # so distutils doesn't "helpfully" add PyInit_<name>
1198
- return val == ignored_symbol or list.__contains__(self, val)
1199
-
1200
- filtered_list = FilteredExportSymbols(old_entries)
1201
- if old_entries:
1202
- filtered_list.extend(name for name in old_entries if name != ignored_symbol)
1203
- return filtered_list
1204
-
1205
- for m in module_list:
1206
- if m.name.isascii():
1207
- continue
1208
- m.export_symbols = make_filtered_list(
1209
- "PyInit_" + m.name.rsplit(".", 1)[-1],
1210
- m.export_symbols,
1211
- )
1212
-
1213
-
1214
1181
  if os.environ.get('XML_RESULTS'):
1215
1182
  compile_result_dir = os.environ['XML_RESULTS']
1216
1183
  def record_results(func):
@@ -1227,20 +1194,15 @@ if os.environ.get('XML_RESULTS'):
1227
1194
  module = fully_qualified_name(args[0])
1228
1195
  name = "cythonize." + module
1229
1196
  failures = 1 - success
1230
- if success:
1231
- failure_item = ""
1232
- else:
1233
- failure_item = "failure"
1234
- output = open(os.path.join(compile_result_dir, name + ".xml"), "w")
1235
- output.write("""
1197
+ with open(os.path.join(compile_result_dir, name + ".xml"), "w") as output:
1198
+ output.write(f"""
1236
1199
  <?xml version="1.0" ?>
1237
- <testsuite name="%(name)s" errors="0" failures="%(failures)s" tests="1" time="%(t)s">
1238
- <testcase classname="%(name)s" name="cythonize">
1239
- %(failure_item)s
1200
+ <testsuite name="{name}" errors="0" failures="{failures}" tests="1" time="{t}">
1201
+ <testcase classname="{name}" name="cythonize">
1202
+ {'' if success else 'failure'}
1240
1203
  </testcase>
1241
1204
  </testsuite>
1242
- """.strip() % locals())
1243
- output.close()
1205
+ """.strip())
1244
1206
  return with_record
1245
1207
  else:
1246
1208
  def record_results(func):
Cython/Build/Inline.py CHANGED
@@ -14,7 +14,7 @@ from ..Compiler.Main import Context
14
14
  from ..Compiler.Options import (default_options, CompilationOptions,
15
15
  get_directive_defaults)
16
16
 
17
- from ..Compiler.Visitor import CythonTransform, EnvTransform
17
+ from ..Compiler.Visitor import EnvTransform
18
18
  from ..Compiler.ParseTreeTransforms import SkipDeclarations
19
19
  from ..Compiler.TreeFragment import parse_from_strings
20
20
  from .Dependencies import strip_string_literals, cythonize, cached_function
@@ -268,7 +268,7 @@ def __invoke(%(params)s):
268
268
  build_extension.build_lib = lib_dir
269
269
  build_extension.run()
270
270
 
271
- if sys.platform == 'win32' and sys.version_info >= (3, 8):
271
+ if sys.platform == 'win32':
272
272
  with os.add_dll_directory(os.path.abspath(lib_dir)):
273
273
  module = load_dynamic(module_name, module_path)
274
274
  else:
@@ -364,6 +364,8 @@ def cymeit(code, setup_code=None, import_module=None, directives=None, timer=tim
364
364
 
365
365
  # Run for at least 0.2 seconds, either as integer nanoseconds or floating point seconds.
366
366
  min_runtime = one_second // 5 if timer_returns_nanoseconds else one_second / 5
367
+ # Jump by larger steps until we reach a reasonable time.
368
+ fast_jumptime = min_runtime // 20 if timer_returns_nanoseconds else min_runtime / 20
367
369
 
368
370
  def autorange():
369
371
  i = 1
@@ -374,12 +376,14 @@ def cymeit(code, setup_code=None, import_module=None, directives=None, timer=tim
374
376
  assert isinstance(time_taken, int if timer_returns_nanoseconds else float)
375
377
  if time_taken >= min_runtime:
376
378
  return number
379
+ elif time_taken < fast_jumptime:
380
+ break
377
381
  elif timer_returns_nanoseconds and (time_taken < 10 and number >= 10):
378
382
  # Arbitrary sanity check to prevent endless loops for non-ns timers.
379
383
  raise RuntimeError(f"Timer seems to return non-ns timings: {timer}")
380
384
  i *= 10
381
385
 
382
- autorange() # warmup
386
+ timeit(2) # warmup
383
387
  number = autorange()
384
388
 
385
389
  # Run and repeat the benchmark.
@@ -44,7 +44,6 @@ Parts of this code were taken from Cython.inline.
44
44
  #-----------------------------------------------------------------------------
45
45
 
46
46
 
47
- import io
48
47
  import os
49
48
  import re
50
49
  import sys
@@ -65,8 +65,7 @@ def create_shared_library_pipeline(context, scope, options, result):
65
65
 
66
66
 
67
67
  def generate_shared_module(options):
68
- Errors.init_thread()
69
- Errors.open_listing_file(None)
68
+ Errors.reset()
70
69
 
71
70
  dest_c_file = options.shared_c_file_path
72
71
  pyx_file = os.path.splitext(dest_c_file)[0] + '.pyx'
@@ -2,21 +2,19 @@ from Cython.Build.Cythonize import (
2
2
  create_args_parser, parse_args_raw, parse_args,
3
3
  )
4
4
 
5
+ from Cython.TestUtils import TimedTest
5
6
  from Cython.Compiler import Options
6
7
  from Cython.Compiler.Tests.Utils import backup_Options, restore_Options, check_global_options
7
8
 
8
- from unittest import TestCase
9
-
10
9
  import sys
11
10
  from io import StringIO
12
11
 
13
12
 
14
- class TestCythonizeArgsParser(TestCase):
13
+ class TestCythonizeArgsParser(TimedTest):
15
14
 
16
15
  def setUp(self):
17
- TestCase.setUp(self)
18
16
  self.parse_args = lambda x, parser=create_args_parser() : parse_args_raw(parser, x)
19
-
17
+ super().setUp()
20
18
 
21
19
  def are_default(self, options, skip):
22
20
  # empty containers
@@ -439,12 +437,14 @@ class TestCythonizeArgsParser(TestCase):
439
437
  self.assertTrue(stderr.getvalue())
440
438
 
441
439
 
442
- class TestParseArgs(TestCase):
440
+ class TestParseArgs(TimedTest):
443
441
  def setUp(self):
442
+ super().setUp()
444
443
  self._options_backup = backup_Options()
445
444
 
446
445
  def tearDown(self):
447
446
  restore_Options(self._options_backup)
447
+ super().tearDown()
448
448
 
449
449
  def check_default_global_options(self, white_list=[]):
450
450
  self.assertEqual(check_global_options(self._options_backup, white_list), "")
@@ -1,10 +1,10 @@
1
1
  import contextlib
2
- import os.path
2
+ import os
3
3
  import tempfile
4
- import unittest
5
4
  from os.path import join as pjoin
6
5
 
7
6
  from ..Dependencies import extended_iglob
7
+ from ...TestUtils import TimedTest
8
8
 
9
9
 
10
10
  @contextlib.contextmanager
@@ -13,7 +13,7 @@ def writable_file(dir_path, filename):
13
13
  yield f
14
14
 
15
15
 
16
- class TestGlobbing(unittest.TestCase):
16
+ class TestGlobbing(TimedTest):
17
17
  @classmethod
18
18
  def setUpClass(cls):
19
19
  cls._orig_dir = os.getcwd()
@@ -3,7 +3,7 @@ import tempfile
3
3
  import unittest
4
4
  from Cython.Shadow import inline
5
5
  from Cython.Build.Inline import safe_type, cymeit
6
- from Cython.TestUtils import CythonTest
6
+ from Cython.TestUtils import CythonTest, TimedTest
7
7
 
8
8
  try:
9
9
  import numpy
@@ -17,13 +17,13 @@ global_value = 100
17
17
 
18
18
  class TestInline(CythonTest):
19
19
  def setUp(self):
20
- CythonTest.setUp(self)
21
20
  self._call_kwds = dict(test_kwds)
22
21
  if os.path.isdir('TEST_TMP'):
23
22
  lib_dir = os.path.join('TEST_TMP','inline')
24
23
  else:
25
24
  lib_dir = tempfile.mkdtemp(prefix='cython_inline_')
26
25
  self._call_kwds['lib_dir'] = lib_dir
26
+ super().setUp()
27
27
 
28
28
  def test_simple(self):
29
29
  self.assertEqual(inline("return 1+2", **self._call_kwds), 3)
@@ -112,7 +112,7 @@ class TestInline(CythonTest):
112
112
  self.assertEqual(inline("return a[0,0]", a=a, **self._call_kwds), 10.0)
113
113
 
114
114
 
115
- class TestCymeit(unittest.TestCase):
115
+ class TestCymeit(TimedTest):
116
116
  def _run(self, code, setup_code=None, **kwargs):
117
117
  timings, number = cymeit(code, setup_code=setup_code, **kwargs)
118
118
 
@@ -3,36 +3,21 @@
3
3
  """Tests for the Cython magics extension."""
4
4
 
5
5
 
6
+ import builtins
6
7
  import os
7
8
  import io
8
9
  import sys
9
10
  from contextlib import contextmanager
10
- from unittest import skipIf
11
+ from unittest import skipIf, SkipTest
11
12
 
12
13
  from Cython.Build import IpythonMagic
13
14
  from Cython.TestUtils import CythonTest
14
15
  from Cython.Compiler.Annotate import AnnotationCCodeWriter
15
16
 
16
- try:
17
- import IPython.testing.globalipapp
18
- except ImportError:
19
- # Disable tests and fake helpers for initialisation below.
20
- def skip_if_not_installed(_):
21
- return None
22
- else:
23
- def skip_if_not_installed(c):
24
- return c
25
17
 
26
18
  # not using IPython's decorators here because they depend on "nose"
27
19
  skip_win32 = skipIf(sys.platform == 'win32', "Skip on Windows")
28
20
 
29
- try:
30
- # disable IPython history thread before it gets started to avoid having to clean it up
31
- from IPython.core.history import HistoryManager
32
- HistoryManager.enabled = False
33
- except ImportError:
34
- pass
35
-
36
21
 
37
22
  @contextmanager
38
23
  def capture_output():
@@ -94,14 +79,45 @@ def doit():
94
79
  '''
95
80
 
96
81
 
97
- @skip_if_not_installed
98
82
  class TestIPythonMagic(CythonTest):
83
+ _orig_builtins = None
99
84
 
100
85
  @classmethod
101
86
  def setUpClass(cls):
102
- CythonTest.setUpClass()
87
+ super().setUpClass()
88
+
89
+ # IPython modifies the builtins, so keep a clean copy before the import.
90
+ orig_builtins = dict(builtins.__dict__)
91
+
92
+ try:
93
+ import IPython.testing.globalipapp
94
+ except ImportError as exc:
95
+ # Disable tests and fake helpers for initialisation below.
96
+ raise SkipTest(f"IPython is not installed: {exc}")
97
+
98
+ try:
99
+ # disable IPython history thread before it gets started to avoid having to clean it up
100
+ from IPython.core.history import HistoryManager
101
+ HistoryManager.enabled = False
102
+ except ImportError:
103
+ pass
104
+
105
+ cls._orig_builtins = orig_builtins
103
106
  cls._ip = IPython.testing.globalipapp.get_ipython()
104
107
 
108
+ @classmethod
109
+ def tearDownClass(cls):
110
+ # Clean up builtins from IPython left-overs.
111
+ if cls._orig_builtins:
112
+ for name in list(vars(builtins)):
113
+ if name not in cls._orig_builtins:
114
+ delattr(builtins, name)
115
+ for name, value in cls._orig_builtins.items():
116
+ if getattr(builtins, name, None) is not value:
117
+ setattr(builtins, name, value)
118
+
119
+ super().tearDownClass()
120
+
105
121
  def setUp(self):
106
122
  CythonTest.setUp(self)
107
123
  self._ip.extension_manager.load_extension('cython')
@@ -1,12 +1,12 @@
1
1
  import pathlib
2
2
  import re
3
- import unittest
4
3
 
4
+ from ...TestUtils import TimedTest
5
5
  from ...Utils import open_source_file
6
6
  from ..Dependencies import strip_string_literals
7
7
 
8
8
 
9
- class TestStripLiterals(unittest.TestCase):
9
+ class TestStripLiterals(TimedTest):
10
10
  maxDiff = None
11
11
 
12
12
  @staticmethod
Cython/Compiler/Buffer.py CHANGED
@@ -343,9 +343,9 @@ def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type):
343
343
  dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype)
344
344
 
345
345
  code.globalstate.use_utility_code(acquire_utility_code)
346
- return ("__Pyx_GetBufferAndValidate(&%(pybuffernd_struct)s.rcbuffer->pybuffer, "
347
- "(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, "
348
- "%(cast)d, __pyx_stack)" % locals())
346
+ return (f"__Pyx_GetBufferAndValidate(&{pybuffernd_struct}.rcbuffer->pybuffer, "
347
+ f"(PyObject*){obj_cname}, &{dtype_typeinfo}, {flags}, {ndim:d}, "
348
+ f"{cast:d}, __pyx_stack)")
349
349
 
350
350
 
351
351
  def put_assign_to_buffer(lhs_cname, rhs_cname, buf_entry,
@@ -386,13 +386,13 @@ def put_assign_to_buffer(lhs_cname, rhs_cname, buf_entry,
386
386
  # can consider working around this later.
387
387
  exc_temps = tuple(code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
388
388
  for _ in range(3))
389
- code.putln('PyErr_Fetch(&%s, &%s, &%s);' % exc_temps)
389
+ code.putln('__Pyx_PyErr_FetchException(&%s, &%s, &%s);' % exc_temps)
390
390
  code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
391
391
  code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % exc_temps) # Do not refnanny these!
392
392
  code.globalstate.use_utility_code(raise_buffer_fallback_code)
393
393
  code.putln('__Pyx_RaiseBufferFallbackError();')
394
394
  code.putln('} else {')
395
- code.putln('PyErr_Restore(%s, %s, %s);' % exc_temps)
395
+ code.putln('__Pyx_PyErr_RestoreException(%s, %s, %s);' % exc_temps)
396
396
  code.putln('}')
397
397
  code.putln('%s = %s = %s = 0;' % exc_temps)
398
398
  for t in exc_temps:
@@ -4,7 +4,7 @@
4
4
 
5
5
 
6
6
  from .StringEncoding import EncodedString
7
- from .Symtab import BuiltinScope, CClassScope, StructOrUnionScope, ModuleScope, Entry
7
+ from .Symtab import BuiltinScope, StructOrUnionScope, ModuleScope, Entry
8
8
  from .Code import UtilityCode, TempitaUtilityCode, KNOWN_PYTHON_BUILTINS, uncachable_builtins
9
9
  from .TypeSlots import Signature
10
10
  from . import PyrexTypes
@@ -21,6 +21,8 @@ globals_utility_code = UtilityCode.load("Globals", "Builtins.c")
21
21
  range_utility_code = UtilityCode.load("PyRange_Check", "Builtins.c")
22
22
  include_std_lib_h_utility_code = UtilityCode.load("IncludeStdlibH", "ModuleSetupCode.c")
23
23
  slice_accessor_utility_code = UtilityCode.load("PySliceAccessors", "Builtins.c")
24
+ frozendict_utility_code = UtilityCode.load("PyFrozenDict", "Builtins.c")
25
+
24
26
 
25
27
  def make_sequence_multiply_method(typeobj_cname):
26
28
  pysequence_multiply_utility_code = TempitaUtilityCode.load(
@@ -346,29 +348,6 @@ builtin_function_table = [
346
348
 
347
349
 
348
350
  # Builtin types
349
- # bool
350
- # bytearray
351
- # bytes
352
- # classmethod
353
- # complex
354
- # dict
355
- # enumerate
356
- # float
357
- # frozenset
358
- # int
359
- # list
360
- # long
361
- # memoryview
362
- # object
363
- # property
364
- # range
365
- # set
366
- # slice
367
- # staticmethod
368
- # str
369
- # super
370
- # tuple
371
- # type
372
351
 
373
352
  builtin_types_table = [
374
353
 
@@ -432,6 +411,16 @@ builtin_types_table = [
432
411
  utility_code=UtilityCode.load("py_dict_clear", "Optimize.c")),
433
412
  BuiltinMethod("copy", "T", "T", "PyDict_Copy")]),
434
413
 
414
+ ("frozendict", "__Pyx_PyFrozenDict_TypePtr", [
415
+ BuiltinMethod("__contains__", "TO", "b", "PyDict_Contains"),
416
+ BuiltinMethod("items", "T", "O", "__Pyx_PyFrozenDict_Items",
417
+ utility_code=UtilityCode.load("py_frozendict_items", "Builtins.c")),
418
+ BuiltinMethod("keys", "T", "O", "__Pyx_PyFrozenDict_Keys",
419
+ utility_code=UtilityCode.load("py_frozendict_keys", "Builtins.c")),
420
+ BuiltinMethod("values", "T", "O", "__Pyx_PyFrozenDict_Values",
421
+ utility_code=UtilityCode.load("py_frozendict_values", "Builtins.c")),
422
+ ]),
423
+
435
424
  ("range", "&PyRange_Type", []),
436
425
 
437
426
  ("slice", "&PySlice_Type", [BuiltinProperty("start", PyrexTypes.py_object_type, '__Pyx_PySlice_Start',
@@ -490,15 +479,25 @@ types_that_construct_their_instance = frozenset({
490
479
  # themselves - these do:
491
480
  'type', 'bool', 'int', 'float', 'complex',
492
481
  'bytes', 'unicode', 'bytearray', 'str',
493
- 'tuple', 'list', 'dict', 'set', 'frozenset',
494
- 'memoryview', 'range',
482
+ 'tuple', 'list', 'dict', 'frozendict', 'set', 'frozenset',
483
+ 'memoryview', 'range', 'slice', 'sentinel',
495
484
  # All builtin exception types create their own instance.
496
485
  *filter(PyrexTypes.is_exception_type_name, KNOWN_PYTHON_BUILTINS),
486
+
487
+ # These types don't currently have a purpose and might become restrictive:
488
+ #'object',
489
+ #'property',
490
+ #'classmethod',
491
+ #'staticmethod',
492
+ #'super',
493
+ #'zip',
497
494
  })
498
495
 
499
496
 
500
497
  # When updating this mapping, also update "unsafe_compile_time_methods" below
501
498
  # if methods are added that are not safe to evaluate at compile time.
499
+ # 'T' - type identical to type in dictionary key
500
+ # 'I' - type from subscript - e.g. for list[int], I is `int`
502
501
  inferred_method_return_types = {
503
502
  'complex': dict(
504
503
  conjugate='complex',
@@ -523,6 +522,7 @@ inferred_method_return_types = {
523
522
  copy='T',
524
523
  count='Py_ssize_t',
525
524
  index='Py_ssize_t',
525
+ pop='I',
526
526
  ),
527
527
  'tuple': dict(
528
528
  count='Py_ssize_t',
@@ -640,6 +640,7 @@ inferred_method_return_types = {
640
640
  issuperset='bint',
641
641
  symmetric_difference='T',
642
642
  union='T',
643
+ pop='I',
643
644
  ),
644
645
  'frozenset': dict(
645
646
  # Inherited from 'set' below.
@@ -648,6 +649,12 @@ inferred_method_return_types = {
648
649
  copy='T',
649
650
  fromkeys='T', # classmethod
650
651
  popitem='tuple',
652
+ pop='I',
653
+ get='I',
654
+ ),
655
+ 'frozendict': dict(
656
+ copy='T',
657
+ fromkeys='T', # classmethod
651
658
  ),
652
659
  }
653
660
 
@@ -655,24 +662,34 @@ inferred_method_return_types['bytearray'].update(inferred_method_return_types['b
655
662
  inferred_method_return_types['frozenset'].update(inferred_method_return_types['set'])
656
663
 
657
664
 
658
- def find_return_type_of_builtin_method(builtin_type, method_name):
659
- type_name = builtin_type.name
665
+ def find_return_type_of_builtin_method(pos, env, builtin_type, method_name):
666
+ container_type = builtin_type.get_container_type()
667
+ type_name = container_type.name if container_type else builtin_type.name
660
668
  if type_name in inferred_method_return_types:
661
669
  methods = inferred_method_return_types[type_name]
662
670
  if method_name in methods:
671
+ subscripted_type_names: str = ''
663
672
  return_type_name = methods[method_name]
664
673
  if '[' in return_type_name:
665
- # TODO: Keep the "[...]" part when we add support for generics.
666
- return_type_name = return_type_name.partition('[')[0]
674
+ return_type_name, _, subscripted_type_names = return_type_name[:-1].partition('[')
667
675
  if return_type_name == 'T':
668
676
  return builtin_type
669
- if 'T' in return_type_name:
670
- return_type_name = return_type_name.replace('T', builtin_type.name)
677
+ if return_type_name == 'I':
678
+ return builtin_type.infer_indexed_type() or PyrexTypes.py_object_type
679
+ if 'T' in subscripted_type_names:
680
+ subscripted_type_names = subscripted_type_names.replace('T', builtin_type.name)
671
681
  if return_type_name == 'bint':
672
682
  return PyrexTypes.c_bint_type
673
683
  elif return_type_name == 'Py_ssize_t':
674
684
  return PyrexTypes.c_py_ssize_t_type
675
- return builtin_scope.lookup(return_type_name).type
685
+ container_type = builtin_scope.lookup(return_type_name).type
686
+ if subscripted_type_names:
687
+ subscripted_types = [
688
+ entry.type if entry else PyrexTypes.py_object_type
689
+ for entry in map(builtin_scope.lookup, subscripted_type_names.split(','))
690
+ ]
691
+ container_type = container_type.specialize_here(pos, env, subscripted_types)
692
+ return container_type
676
693
  return PyrexTypes.py_object_type
677
694
 
678
695
 
@@ -781,12 +798,15 @@ def init_builtin_types():
781
798
 
782
799
  utility_code = None
783
800
  type_class = PyrexTypes.BuiltinObjectType
784
- if name in ['dict', 'list', 'set', 'frozenset']:
801
+ if name in ['dict', 'list', 'set', 'frozenset', 'frozendict']:
785
802
  type_class = PyrexTypes.BuiltinTypeConstructorObjectType
803
+ if name == 'frozendict':
804
+ utility_code = frozendict_utility_code
786
805
  elif name == 'tuple':
787
806
  type_class = PyrexTypes.PythonTupleTypeConstructor
788
807
  elif name == 'range':
789
808
  utility_code = range_utility_code
809
+
790
810
  the_type = builtin_scope.declare_builtin_type(
791
811
  name, cname, objstruct_cname=objstruct_cname, type_class=type_class, utility_code=utility_code)
792
812
  builtin_types[name] = the_type
@@ -825,7 +845,6 @@ def init_builtin_structs():
825
845
 
826
846
 
827
847
  def init_builtins():
828
- #Errors.init_thread() # hopefully not needed - we should not emit warnings ourselves
829
848
  init_builtin_structs()
830
849
  init_builtin_types()
831
850
  init_builtin_exceptions()
@@ -836,16 +855,17 @@ def init_builtins():
836
855
  pos=None, cname='__pyx_assertions_enabled()', is_cdef=True)
837
856
  entry.utility_code = UtilityCode.load_cached("AssertionsEnabled", "Exceptions.c")
838
857
 
839
- global type_type, list_type, tuple_type, dict_type, set_type, frozenset_type
858
+ global type_type, list_type, tuple_type, dict_type, frozendict_type
859
+ global set_type, frozenset_type
840
860
  global slice_type, range_type
841
861
  global bytes_type, unicode_type, bytearray_type
842
862
  global float_type, int_type, bool_type, complex_type
843
863
  global memoryview_type, py_buffer_type
844
- global sequence_types
845
864
  type_type = builtin_scope.lookup('type').type
846
865
  list_type = builtin_scope.lookup('list').type
847
866
  tuple_type = builtin_scope.lookup('tuple').type
848
867
  dict_type = builtin_scope.lookup('dict').type
868
+ frozendict_type = builtin_scope.lookup('frozendict').type
849
869
  set_type = builtin_scope.lookup('set').type
850
870
  frozenset_type = builtin_scope.lookup('frozenset').type
851
871
  slice_type = builtin_scope.lookup('slice').type
@@ -861,15 +881,6 @@ def init_builtins():
861
881
  bool_type = builtin_scope.lookup('bool').type
862
882
  complex_type = builtin_scope.lookup('complex').type
863
883
 
864
- sequence_types = (
865
- list_type,
866
- tuple_type,
867
- bytes_type,
868
- unicode_type,
869
- bytearray_type,
870
- memoryview_type,
871
- )
872
-
873
884
  # Set up type inference links between equivalent Python/C types
874
885
  assert bool_type.name == 'bool', bool_type.name
875
886
  bool_type.equivalent_type = PyrexTypes.c_bint_type
Cython/Compiler/Code.pxd CHANGED
@@ -18,6 +18,7 @@ cdef class UtilityCode(UtilityCodeBase):
18
18
  cdef public object init
19
19
  cdef public object cleanup
20
20
  cdef object proto_block
21
+ cdef object init_block
21
22
  cdef readonly object module_state_decls
22
23
  cdef readonly object module_state_traverse
23
24
  cdef readonly object module_state_clear
@@ -55,12 +56,12 @@ cdef class FunctionState:
55
56
  cdef public bint can_trace
56
57
  cdef public bint gil_owned
57
58
 
58
- cdef list temps_allocated
59
- cdef dict temps_free
60
- cdef dict temps_used_type
59
+ cdef list[tuple] temps_allocated
60
+ cdef dict[tuple, tuple] temps_free
61
+ cdef dict[object, tuple] temps_used_type
61
62
  cdef set zombie_temps
62
63
  cdef size_t temp_counter
63
- cdef list collect_temps_stack
64
+ cdef list[set[tuple]] collect_temps_stack
64
65
 
65
66
  cdef readonly object closure_temps
66
67
  cdef bint should_declare_error_indicator
@@ -71,13 +72,13 @@ cdef class FunctionState:
71
72
 
72
73
  cpdef new_label(self, name=*)
73
74
  cpdef tuple get_loop_labels(self)
74
- cpdef set_loop_labels(self, labels)
75
+ cpdef set_loop_labels(self, labels: tuple)
75
76
  cpdef tuple get_all_labels(self)
76
- cpdef set_all_labels(self, labels)
77
+ cpdef set_all_labels(self, labels: tuple)
77
78
  cpdef start_collecting_temps(self)
78
- cpdef stop_collecting_temps(self)
79
+ cpdef set stop_collecting_temps(self)
79
80
 
80
- cpdef list temps_in_use(self)
81
+ cpdef list[tuple] temps_in_use(self)
81
82
 
82
83
 
83
84
  @cython.final
@@ -91,7 +92,7 @@ cdef class StringConst:
91
92
  cdef readonly object cname
92
93
  cdef readonly object text
93
94
  cdef readonly object escaped_value
94
- cdef readonly dict py_strings
95
+ cdef readonly dict[tuple, PyStringConst] py_strings
95
96
  cdef public bint c_used
96
97
 
97
98
  cpdef get_py_string_const(self, encoding, identifier=*)
@@ -121,6 +122,8 @@ cdef class CCodeWriter(object):
121
122
  cdef public Py_ssize_t call_level # debug-only, see Nodes.py
122
123
  cdef bint bol
123
124
 
125
+ @cython.final
126
+ cdef void handle_refnanny(self, tp, bint nanny=*)
124
127
  cpdef write(self, s)
125
128
  cdef _write_lines(self, s)
126
129
  cpdef _write_to_buffer(self, s)