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
@@ -6,13 +6,13 @@
6
6
  import cython
7
7
  cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object,
8
8
  error=object, warning=object, py_object_type=object, UtilityCode=object,
9
- EncodedString=object, re=object)
9
+ EncodedString=object, itertools=object, operator=object, re=object)
10
10
 
11
11
  from collections import defaultdict
12
+ import itertools
12
13
  import json
13
14
  import operator
14
15
  import os
15
- import pathlib
16
16
  import re
17
17
  import sys
18
18
  from typing import Sequence
@@ -892,8 +892,8 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
892
892
  code.putln("#ifndef Py_PYTHON_H")
893
893
  code.putln(" #error Python headers needed to compile C extensions, "
894
894
  "please install development version of Python.")
895
- code.putln("#elif PY_VERSION_HEX < 0x03080000")
896
- code.putln(" #error Cython requires Python 3.8+.")
895
+ code.putln("#elif PY_VERSION_HEX < 0x03090000")
896
+ code.putln(" #error Cython requires Python 3.9+.")
897
897
  code.putln("#else")
898
898
  code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
899
899
 
@@ -1075,17 +1075,12 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1075
1075
  code.putln_openmp("#include <omp.h>")
1076
1076
 
1077
1077
  def generate_filename_table(self, code):
1078
- from os.path import isabs, basename
1079
1078
  code.putln("")
1080
1079
  code.putln("static const char* const %s[] = {" % Naming.filetable_cname)
1081
1080
  if code.globalstate.filename_list:
1082
1081
  for source_desc in code.globalstate.filename_list:
1083
- file_path = source_desc.get_filenametable_entry()
1084
- if isabs(file_path):
1085
- # never include absolute paths
1086
- file_path = source_desc.get_description()
1087
1082
  # Always use / as separator
1088
- file_path = pathlib.Path(file_path).as_posix()
1083
+ file_path = source_desc.get_relative_path().as_posix()
1089
1084
  escaped_filename = as_encoded_filename(file_path)
1090
1085
  code.putln('%s,' % escaped_filename.as_c_string_literal())
1091
1086
  else:
@@ -1581,6 +1576,8 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1581
1576
  if scope: # could be None if there was an error
1582
1577
  self.generate_exttype_vtable(scope, code)
1583
1578
  self.generate_new_function(scope, code, entry)
1579
+ self.generate_vectorcall_new_function(scope, code)
1580
+ self.generate_init_function(scope, code)
1584
1581
  self.generate_del_function(scope, code)
1585
1582
  self.generate_dealloc_function(scope, code)
1586
1583
 
@@ -1588,8 +1585,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1588
1585
  self.generate_traverse_function(scope, code, entry)
1589
1586
  if scope.needs_tp_clear():
1590
1587
  self.generate_clear_function(scope, code, entry)
1588
+
1591
1589
  if scope.defines_any_special(["__getitem__"]):
1592
- self.generate_getitem_int_function(scope, code)
1590
+ self.generate_getitem_function(scope, code)
1593
1591
  if scope.defines_any_special(["__setitem__", "__delitem__"]):
1594
1592
  self.generate_ass_subscript_function(scope, code)
1595
1593
  if scope.defines_any_special(["__getslice__", "__setslice__", "__delslice__"]):
@@ -1597,8 +1595,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1597
1595
  "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, "
1598
1596
  "use __getitem__, __setitem__, and __delitem__ instead", 1)
1599
1597
  code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.")
1600
- if scope.defines_any_special(["__setslice__", "__delslice__"]):
1601
- self.generate_ass_slice_function(scope, code)
1598
+
1602
1599
  if scope.defines_any_special(["__getattr__", "__getattribute__"]):
1603
1600
  self.generate_getattro_function(scope, code)
1604
1601
  if scope.defines_any_special(["__setattr__", "__delattr__"]):
@@ -1664,12 +1661,162 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1664
1661
  if tp_slot.slot_code(scope) != slot_func:
1665
1662
  return # never used
1666
1663
 
1664
+ vectorcall_tp_slot = TypeSlots.get_slot_by_name("tp_vectorcall", scope.directives)
1665
+ vectorcall_slot_func = scope.mangle_internal("tp_vectorcall")
1666
+ is_vectorcall = vectorcall_tp_slot.slot_code(scope) == vectorcall_slot_func
1667
+ tp_new_vectorcall_slot = TypeSlots.ConstructorSlot("tp_new_vectorcall", "__cinit__")
1668
+
1669
+ if is_vectorcall:
1670
+ format_vectorcall_conditional = "\n#if CYTHON_VECTORCALL_TPNEW\n {}\n#else\n {}\n#endif\n".format
1671
+ else:
1672
+ format_vectorcall_conditional = lambda vc, non_vc: non_vc
1673
+
1674
+ signature = format_vectorcall_conditional(
1675
+ "{unused_marker}PyObject *const *args, {unused_marker}Py_ssize_t nargs, {unused_marker}PyObject *kwnames",
1676
+ "{unused_marker}PyObject *a, {unused_marker}PyObject *k")
1677
+ call_args = format_vectorcall_conditional(
1678
+ "args, nargs, kwnames",
1679
+ "a, k")
1680
+
1681
+ self._generate_tpnew_initialisation_function(scope, code, cclass_entry, is_vectorcall, signature, call_args)
1682
+
1683
+ code.start_slotfunc(
1684
+ scope, PyrexTypes.py_objptr_type,
1685
+ "tp_new_vectorcall" if is_vectorcall else "tp_new",
1686
+ f"PyTypeObject *t, {signature.format(unused_marker='')}", needs_prototype=True)
1687
+
1688
+ code.putln("PyObject *o;")
1689
+
1690
+ base_type = scope.parent_type.base_type
1691
+ if base_type:
1692
+ self._generate_allocation_from_basetype(
1693
+ scope, code, tp_new_vectorcall_slot if is_vectorcall else tp_slot, base_type, call_args)
1694
+ else:
1695
+ freelist_size = scope.directives.get('freelist', 0)
1696
+ if freelist_size:
1697
+ self._generate_allocation_from_freelist(scope, code, freelist_size)
1698
+ # ends with a guarded "} else"
1699
+ code.putln("{")
1700
+
1701
+ code.globalstate.use_utility_code(
1702
+ UtilityCode.load_cached("AllocateExtensionType", "ExtensionTypes.c")
1703
+ )
1704
+ is_final_type = scope.parent_type.is_final_type
1705
+ code.putln(f"o = __Pyx_AllocateExtensionType(t, {is_final_type:d});")
1706
+ if freelist_size:
1707
+ code.putln('}')
1708
+
1709
+ code.putln("if (unlikely(!o)) return 0;")
1710
+ code.putln(f'return {scope.mangle_internal("tp_new__initialisation")}(o, {call_args});')
1711
+ code.putln("}")
1712
+ code.exit_cfunc_scope()
1713
+
1714
+ if is_vectorcall:
1715
+ self._generate_tpnew_to_vectorcall(scope, code)
1716
+
1717
+ def _generate_tpnew_to_vectorcall(self, scope, code):
1718
+ code.globalstate.use_utility_code(
1719
+ TempitaUtilityCode.load_cached(
1720
+ "CallSlotAsVectorcall", "ExtensionTypes.c",
1721
+ context=dict(ret_type="PyObject *", name="tpnew", obj_type="PyTypeObject*", error_value="NULL"))
1722
+ )
1723
+
1724
+ code.start_slotfunc(
1725
+ scope, PyrexTypes.py_objptr_type,
1726
+ "tp_new",
1727
+ f"PyTypeObject *t, PyObject *a, PyObject *k",
1728
+ needs_prototype=True, guard="CYTHON_VECTORCALL_TPNEW")
1729
+
1730
+ code.putln(f"return __Pyx_CallTpnewAsVectorcall({scope.mangle_internal('tp_new_vectorcall')}, t, a, k);")
1731
+ code.putln("}")
1732
+ code.exit_cfunc_scope()
1733
+ code.putln("#endif") # CYTHON_VECTORCALL_TPNEW
1734
+
1735
+ decls = code.globalstate['decls']
1736
+ decls.putln("#if !CYTHON_VECTORCALL_TPNEW")
1737
+ decls.putln(f"#define {scope.mangle_internal('tp_new')} {scope.mangle_internal('tp_new_vectorcall')}")
1738
+ decls.putln("#endif")
1739
+
1740
+ def _generate_allocation_from_basetype(self, scope, code, tp_slot, base_type, call_args):
1741
+ base_type_typeptr_cname = base_type.typeptr_cname
1742
+ if not base_type.is_builtin_type:
1743
+ base_type_typeptr_cname = code.name_in_slot_module_state(base_type_typeptr_cname)
1744
+
1745
+ tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
1746
+ if tp_new is None:
1747
+ code.putln(f"newfunc base_tp_new = __Pyx_PyType_TryGetSlot({base_type_typeptr_cname}, tp_new, newfunc);")
1748
+ tp_new = "base_tp_new"
1749
+ code.putln("#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_VEX < 0x030A0000")
1750
+ code.putln(f"if (unlikely(!base_tp_new)) {{")
1751
+ code.globalstate.use_utility_code(
1752
+ UtilityCode.load_cached("RaiseErrorWithObjectTypes", "ObjectHandling.c"))
1753
+ code.putln('__Pyx_RaiseTypeErrorWithTypes('
1754
+ '"Type " __Pyx_FMT_TYPENAME " cannot be instantiated because it '
1755
+ 'cannot access tp_new of its base " __Pyx_FMT_TYPENAME ". '
1756
+ 'This is probably because the base is not a heap type and is a '
1757
+ 'restriction of the Limited API in Python<=3.9", '
1758
+ f"t, {base_type_typeptr_cname});")
1759
+ code.putln("o = NULL;")
1760
+ code.putln("} else")
1761
+ code.putln("#endif")
1762
+
1763
+ code.putln(f"o = {tp_new}(t, {call_args});")
1764
+
1765
+ def _generate_allocation_from_freelist(self, scope, code, freelist_size):
1766
+ freelist_name = scope.mangle_internal(Naming.freelist_name)
1767
+ freecount_name = scope.mangle_internal(Naming.freecount_name)
1768
+
1769
+ module_state = code.globalstate['module_state_contents']
1770
+ module_state.putln("")
1771
+ module_state.putln("#if CYTHON_USE_FREELISTS")
1772
+ module_state.putln("%s[%d];" % (
1773
+ scope.parent_type.declaration_code(freelist_name),
1774
+ freelist_size))
1775
+ module_state.putln("int %s;" % freecount_name)
1776
+ module_state.putln("#endif")
1777
+
1778
+ code.globalstate.use_utility_code(
1779
+ UtilityCode.load_cached("IncludeStringH", "StringTools.c"))
1780
+
1781
+ code.putln("#if CYTHON_USE_FREELISTS")
1782
+ freecount_name = code.name_in_slot_module_state(freecount_name)
1783
+ freelist_name = code.name_in_slot_module_state(freelist_name)
1784
+
1785
+ type = scope.parent_type
1786
+ self.generate_freelist_condition(code, f"{freecount_name} > 0", "t", type)
1787
+ code.putln("{")
1788
+
1789
+ code.putln(f"o = (PyObject*){freelist_name}[--{freecount_name}];")
1790
+
1791
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
1792
+ # We still hold a reference to the type object held by the previous
1793
+ # user of the freelist object - release it.
1794
+ code.putln("Py_DECREF(Py_TYPE(o));")
1795
+ code.putln("#endif")
1796
+
1797
+ obj_struct = type.declaration_code("", deref=True)
1798
+ code.putln("memset(o, 0, sizeof(%s));" % obj_struct)
1799
+
1800
+ code.putln("#if CYTHON_COMPILING_IN_LIMITED_API")
1801
+ # Although PyObject_INIT should be part of the Limited API, it causes
1802
+ # link errors on some combinations of Python versions and OSs.
1803
+ code.putln("(void) PyObject_Init(o, t);")
1804
+ code.putln("#else")
1805
+ code.putln("(void) PyObject_INIT(o, t);")
1806
+ code.putln("#endif")
1807
+
1808
+ if scope.needs_gc():
1809
+ code.putln("PyObject_GC_Track(o);")
1810
+
1811
+ code.putln("} else")
1812
+ code.putln("#endif")
1813
+
1814
+ def _generate_tpnew_initialisation_function(self, scope, code, cclass_entry,
1815
+ use_vectorcall: bool, signature: str, cinit_args: str):
1667
1816
  type = scope.parent_type
1668
- base_type = type.base_type
1669
1817
 
1670
1818
  have_entries, (py_attrs, py_buffers, memoryview_slices) = \
1671
1819
  scope.get_refcounted_entries()
1672
- is_final_type = scope.parent_type.is_final_type
1673
1820
  if scope.is_internal:
1674
1821
  # internal classes (should) never need None inits, normal zeroing will do
1675
1822
  py_attrs = []
@@ -1682,89 +1829,24 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1682
1829
  if cinit_func_entry and not cinit_func_entry.is_special:
1683
1830
  cinit_func_entry = None
1684
1831
 
1685
- if base_type or (cinit_func_entry and not cinit_func_entry.trivial_signature):
1832
+ if cinit_func_entry and not cinit_func_entry.trivial_signature:
1686
1833
  unused_marker = ''
1687
1834
  else:
1688
1835
  unused_marker = 'CYTHON_UNUSED '
1689
-
1690
- if base_type:
1691
- freelist_size = 0 # not currently supported
1692
- else:
1693
- freelist_size = scope.directives.get('freelist', 0)
1694
- freelist_name = scope.mangle_internal(Naming.freelist_name)
1695
- freecount_name = scope.mangle_internal(Naming.freecount_name)
1696
-
1697
- if freelist_size:
1698
- module_state = code.globalstate['module_state_contents']
1699
- module_state.putln("")
1700
- module_state.putln("#if CYTHON_USE_FREELISTS")
1701
- module_state.putln("%s[%d];" % (
1702
- scope.parent_type.declaration_code(freelist_name),
1703
- freelist_size))
1704
- module_state.putln("int %s;" % freecount_name)
1705
- module_state.putln("#endif")
1706
-
1707
- code.start_slotfunc(
1708
- scope, PyrexTypes.py_objptr_type, "tp_new",
1709
- f"PyTypeObject *t, {unused_marker}PyObject *a, {unused_marker}PyObject *k", needs_prototype=True)
1836
+ signature = signature.format(unused_marker=unused_marker)
1710
1837
 
1711
1838
  need_self_cast = (type.vtabslot_cname or
1712
1839
  (py_buffers or memoryview_slices or py_attrs) or
1713
1840
  explicitly_constructable_attrs)
1841
+
1842
+ code.start_slotfunc(
1843
+ scope, PyrexTypes.py_objptr_type, "tp_new__initialisation",
1844
+ f"PyObject *o, {signature}", needs_prototype=True)
1845
+
1714
1846
  if need_self_cast:
1715
- code.putln("%s;" % scope.parent_type.declaration_code("p"))
1716
- if base_type:
1717
- tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
1718
- base_type_typeptr_cname = base_type.typeptr_cname
1719
- if not base_type.is_builtin_type:
1720
- base_type_typeptr_cname = code.name_in_slot_module_state(base_type_typeptr_cname)
1721
- if tp_new is None:
1722
- tp_new = f"__Pyx_PyType_GetSlot({base_type_typeptr_cname}, tp_new, newfunc)"
1723
- code.putln("PyObject *o = %s(t, a, k);" % tp_new)
1724
- else:
1725
- code.putln("PyObject *o;")
1726
- if freelist_size:
1727
- code.globalstate.use_utility_code(
1728
- UtilityCode.load_cached("IncludeStringH", "StringTools.c"))
1729
- code.putln("#if CYTHON_USE_FREELISTS")
1730
- freecount_name = code.name_in_slot_module_state(freecount_name)
1731
- freelist_name = code.name_in_slot_module_state(freelist_name)
1732
- self.generate_freelist_condition(code, f"{freecount_name} > 0", "t", type)
1733
- code.putln("{")
1734
- code.putln("o = (PyObject*)%s[--%s];" % (
1735
- freelist_name,
1736
- freecount_name))
1737
- obj_struct = type.declaration_code("", deref=True)
1738
- code.putln("#if CYTHON_USE_TYPE_SPECS")
1739
- # We still hold a reference to the type object held by the previous
1740
- # user of the freelist object - release it.
1741
- code.putln("Py_DECREF(Py_TYPE(o));")
1742
- code.putln("#endif")
1743
- code.putln("memset(o, 0, sizeof(%s));" % obj_struct)
1744
- code.putln("#if CYTHON_COMPILING_IN_LIMITED_API")
1745
- # Although PyObject_INIT should be part of the Limited API, it causes
1746
- # link errors on some combinations of Python versions and OSs.
1747
- code.putln("(void) PyObject_Init(o, t);")
1748
- code.putln("#else")
1749
- code.putln("(void) PyObject_INIT(o, t);")
1750
- code.putln("#endif")
1751
- if scope.needs_gc():
1752
- code.putln("PyObject_GC_Track(o);")
1753
- code.putln("} else")
1754
- code.putln("#endif")
1755
- code.putln("{")
1756
- code.globalstate.use_utility_code(
1757
- UtilityCode.load_cached("AllocateExtensionType", "ExtensionTypes.c")
1758
- )
1759
- code.putln(f"o = __Pyx_AllocateExtensionType(t, {is_final_type:d});")
1760
- code.putln("if (unlikely(!o)) return 0;")
1761
- if freelist_size and not base_type:
1762
- code.putln('}')
1763
- if need_self_cast:
1764
- code.putln("p = %s;" % type.cast_code("o"))
1847
+ code.putln(f'{scope.parent_type.declaration_code("p")} = {type.cast_code("o")};')
1765
1848
  #if need_self_cast:
1766
1849
  # self.generate_self_cast(scope, code)
1767
-
1768
1850
  # from this point on, ensure DECREF(o) on failure
1769
1851
  needs_error_cleanup = False
1770
1852
 
@@ -1803,16 +1885,28 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1803
1885
  code.putln("p->from_slice.memview = NULL;")
1804
1886
 
1805
1887
  if cinit_func_entry:
1888
+ needs_error_cleanup = True
1889
+ code.putln("{")
1806
1890
  if cinit_func_entry.trivial_signature:
1807
- cinit_args = f"o, {Naming.modulestateglobal_cname}->{Naming.empty_tuple}, NULL"
1891
+ noargs = code.name_in_slot_module_state(Naming.empty_tuple)
1892
+ cinit_args = f"{noargs}, NULL"
1893
+
1894
+ if use_vectorcall and cinit_func_entry.trivial_signature:
1895
+ code.putln(f"int cinit_result = {cinit_func_entry.func_cname}(")
1896
+ code.putln("#if CYTHON_VECTORCALL_TPNEW")
1897
+ code.putln(f"o, NULL, 0, NULL);")
1898
+ code.putln("#else")
1899
+ code.putln(f"o, {cinit_args});")
1900
+ code.putln("#endif")
1808
1901
  else:
1809
- cinit_args = "o, a, k"
1810
- needs_error_cleanup = True
1811
- code.putln("if (unlikely(%s(%s) < 0)) goto bad;" % (
1812
- cinit_func_entry.func_cname, cinit_args))
1902
+ code.putln(f"int cinit_result = {cinit_func_entry.func_cname}(o, {cinit_args});")
1903
+
1904
+ code.putln("if (unlikely(cinit_result)) goto bad;")
1905
+ code.putln("}")
1813
1906
 
1814
1907
  code.putln(
1815
1908
  "return o;")
1909
+
1816
1910
  if needs_error_cleanup:
1817
1911
  code.putln("bad:")
1818
1912
  code.put_decref_clear("o", py_object_type, nanny=False)
@@ -1821,6 +1915,77 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1821
1915
  "}")
1822
1916
  code.exit_cfunc_scope()
1823
1917
 
1918
+ def generate_vectorcall_new_function(self, scope, code):
1919
+ tp_slot = TypeSlots.get_slot_by_name("tp_vectorcall", scope.directives)
1920
+ slot_func = scope.mangle_internal("tp_vectorcall")
1921
+ if tp_slot.slot_code(scope) != slot_func:
1922
+ return # never used
1923
+ code.start_slotfunc(
1924
+ scope, PyrexTypes.py_objptr_type, "tp_vectorcall",
1925
+ f"PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames",
1926
+ needs_prototype=True, guard="CYTHON_VECTORCALL_TPNEW")
1927
+
1928
+ # This is unlikely to happen because tp_vectorcall isn't inherited.
1929
+ # But in this case we should fall back to the regular type construction approach.
1930
+ code.putln("if (unlikely("
1931
+ f"(PyTypeObject*)t != {code.name_in_slot_module_state(scope.parent_type.typeptr_cname)} || "
1932
+ "__Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) {")
1933
+ code.globalstate.use_utility_code(
1934
+ UtilityCode.load_cached("CallNewInitFromVectorcall", "ExtensionTypes.c"))
1935
+ code.putln("return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames);")
1936
+ code.putln("}")
1937
+
1938
+ code.putln("Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);")
1939
+ call = TypeSlots.get_slot_by_name("tp_new", scope.directives).to_vectorcall_slot().slot_code(scope)
1940
+ code.putln(f"PyObject *o = {call}((PyTypeObject*)t, args, nargs, kwnames);")
1941
+
1942
+ init_tp = scope.parent_type
1943
+ tp_init = None
1944
+ while init_tp and not tp_init:
1945
+ tp_init = init_tp.scope.lookup_here("__init__")
1946
+ if tp_init and not tp_init.is_special:
1947
+ tp_init = None
1948
+ init_tp = init_tp.base_type
1949
+ if tp_init:
1950
+ code.putln("if (likely(o)) {")
1951
+ code.putln("assert(Py_TYPE(o) == (PyTypeObject*)t);")
1952
+ code.putln(f"if (unlikely({tp_init.func_cname}(o, args, nargs, kwnames) < 0)) {{")
1953
+ code.putln("Py_CLEAR(o);")
1954
+ code.putln("}")
1955
+ code.putln("}")
1956
+
1957
+ code.putln("return o;")
1958
+ code.putln("}")
1959
+ code.exit_cfunc_scope()
1960
+ code.putln("#endif") # CYTHON_VECTORCALL_TPNEW
1961
+
1962
+ def generate_init_function(self, scope, code):
1963
+ tp_slot = TypeSlots.get_slot_by_name("tp_init", scope.directives)
1964
+ slot_func_cname = scope.mangle_internal("tp_init")
1965
+ if tp_slot.slot_code(scope) != slot_func_cname:
1966
+ # never used, or used but with the correct signature so a wrapper isn't needed.
1967
+ return
1968
+
1969
+ code.start_slotfunc(
1970
+ scope, PyrexTypes.c_int_type, "tp_init",
1971
+ f"PyObject *o, PyObject *args, PyObject *kwds",
1972
+ needs_prototype=True, guard="CYTHON_VECTORCALL_TPNEW")
1973
+ code.globalstate.use_utility_code(
1974
+ TempitaUtilityCode.load_cached(
1975
+ "CallSlotAsVectorcall", "ExtensionTypes.c",
1976
+ context=dict(ret_type="int", name="tpinit", obj_type="PyObject*", error_value="-1"))
1977
+ )
1978
+ entry = scope.lookup_here("__init__")
1979
+ code.putln(f"return __Pyx_CallTpinitAsVectorcall({entry.func_cname}, o, args, kwds);")
1980
+ code.putln("}")
1981
+ code.exit_cfunc_scope()
1982
+ code.putln("#endif") # CYTHON_VECTORCALL_TPNEW
1983
+
1984
+ decls = code.globalstate['decls']
1985
+ decls.putln("#if !CYTHON_VECTORCALL_TPNEW")
1986
+ decls.putln(f"#define {slot_func_cname} {entry.func_cname}")
1987
+ decls.putln("#endif")
1988
+
1824
1989
  def generate_del_function(self, scope, code):
1825
1990
  tp_slot = TypeSlots.get_slot_by_name("tp_finalize", scope.directives)
1826
1991
  slot_func_cname = scope.mangle_internal("tp_finalize")
@@ -1837,9 +2002,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1837
2002
 
1838
2003
  code.start_slotfunc(scope, PyrexTypes.c_void_type, "tp_finalize", "PyObject *o", needs_funcstate=False)
1839
2004
  code.putln("PyObject *etype, *eval, *etb;")
1840
- code.putln("PyErr_Fetch(&etype, &eval, &etb);")
2005
+ code.putln("__Pyx_PyErr_FetchException(&etype, &eval, &etb);")
1841
2006
  code.putln("%s(o);" % entry.func_cname)
1842
- code.putln("PyErr_Restore(etype, eval, etb);")
2007
+ code.putln("__Pyx_PyErr_RestoreException(etype, eval, etb);")
1843
2008
  code.putln("}")
1844
2009
  code.exit_cfunc_scope()
1845
2010
 
@@ -1931,6 +2096,11 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1931
2096
  if not base_type.is_builtin_type:
1932
2097
  base_cname = code.name_in_slot_module_state(base_cname)
1933
2098
  tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
2099
+ if tp_dealloc is None:
2100
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
2101
+ # Reference to tp is owned by the instance o.
2102
+ code.putln("PyObject *tp = (PyObject*)Py_TYPE(o);")
2103
+ code.putln("#endif")
1934
2104
  if tp_dealloc is not None:
1935
2105
  if needs_gc and base_type.scope and base_type.scope.needs_gc():
1936
2106
  # We know that the base class uses GC, so probably expects it to be tracked.
@@ -1963,6 +2133,17 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
1963
2133
  code.putln("__Pyx_call_next_tp_dealloc(o, %s);" % slot_func_cname)
1964
2134
  code.globalstate.use_utility_code(
1965
2135
  UtilityCode.load_cached("CallNextTpDealloc", "ExtensionTypes.c"))
2136
+
2137
+ if tp_dealloc is None:
2138
+ # A builtin type or an external extension type.
2139
+ # Undo the incref of the type only for the lowest heaptype in the inheritance.
2140
+ # (This is what Python does in subtype_dealloc so we should assume it's what
2141
+ # other well-behaved types do).
2142
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
2143
+ code.putln(f"if (!__Pyx_PyType_HasFeature({base_cname}, Py_TPFLAGS_HEAPTYPE)) {{")
2144
+ code.putln("Py_DECREF(tp);")
2145
+ code.putln("}")
2146
+ code.putln("#endif")
1966
2147
  else:
1967
2148
  freelist_size = scope.directives.get('freelist', 0)
1968
2149
  if freelist_size:
@@ -2015,15 +2196,18 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2015
2196
  if not entry or not entry.is_special:
2016
2197
  return
2017
2198
 
2199
+ code.globalstate.use_utility_code(
2200
+ UtilityCode.load_cached("DeallocKeepAlive", "ExtensionTypes.c"))
2018
2201
  code.putln("{")
2019
2202
  code.putln("PyObject *etype, *eval, *etb;")
2020
- code.putln("PyErr_Fetch(&etype, &eval, &etb);")
2021
- # increase the refcount while we are calling into user code
2022
- # to prevent recursive deallocation
2023
- code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1);")
2203
+ code.putln("__Pyx_PyErr_FetchException(&etype, &eval, &etb);")
2204
+ # Keep the object alive while we are calling into user code, to prevent
2205
+ # the user code from triggering recursive deallocation. On free-threading
2206
+ # this must not use Py_SET_REFCNT() (see DeallocKeepAlive in ExtensionTypes.c).
2207
+ code.putln("__Pyx_DeallocKeepAliveBegin(o);")
2024
2208
  code.putln("%s(o);" % entry.func_cname)
2025
- code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1);")
2026
- code.putln("PyErr_Restore(etype, eval, etb);")
2209
+ code.putln("__Pyx_DeallocKeepAliveEnd(o);")
2210
+ code.putln("__Pyx_PyErr_RestoreException(etype, eval, etb);")
2027
2211
  code.putln("}")
2028
2212
 
2029
2213
  def generate_traverse_function(self, scope, code, cclass_entry):
@@ -2191,89 +2375,139 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2191
2375
  code.putln("}")
2192
2376
  code.exit_cfunc_scope()
2193
2377
 
2194
- def generate_getitem_int_function(self, scope, code):
2195
- # This function is put into the sq_item slot when
2196
- # a __getitem__ method is present. It converts its
2197
- # argument to a Python integer and calls mp_subscript.
2198
- code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "sq_item", "PyObject *o, Py_ssize_t i", needs_funcstate=False)
2199
- code.putln(
2200
- "PyObject *r;")
2201
- code.putln(
2202
- "PyObject *x = PyLong_FromSsize_t(i); if(!x) return 0;")
2203
- # Note that PyType_GetSlot only works on heap-types before 3.10, so not using type slots
2204
- # and defining cdef classes as non-heap types is probably impossible
2205
- code.putln("#if CYTHON_USE_TYPE_SLOTS || (!CYTHON_USE_TYPE_SPECS && __PYX_LIMITED_VERSION_HEX < 0x030A0000)")
2206
- code.putln(
2207
- "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
2208
- code.putln("#else")
2209
- code.putln("r = ((binaryfunc)PyType_GetSlot(Py_TYPE(o), Py_mp_subscript))(o, x);")
2210
- code.putln("#endif")
2211
- code.putln(
2212
- "Py_DECREF(x);")
2213
- code.putln(
2214
- "return r;")
2215
- code.putln(
2216
- "}")
2217
- code.exit_cfunc_scope()
2378
+ def generate_getitem_function(self, scope, code):
2379
+ # Implement 'sq_item()' and/or 'mp_subscript()', whichever is more suitable.
2380
+ get_entry = scope.lookup_here("__getitem__")
2381
+ is_sequence_get = get_entry.signature == TypeSlots.sequence_subscript_signatures['__getitem__']
2382
+ implements_mapping_get = TypeSlots.SubscriptSlot.implements_slot(scope, 'mp_subscript')
2383
+
2384
+ # Sequence protocol
2385
+ if TypeSlots.SubscriptSlot.implements_slot(scope, 'sq_item'):
2386
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "sq_item", "PyObject *o, Py_ssize_t i", needs_funcstate=False)
2387
+ if is_sequence_get:
2388
+ code.putln(f"return {get_entry.func_cname}(o, i);")
2389
+ else:
2390
+ code.putln("PyObject *r;")
2391
+ code.putln("PyObject *x = PyLong_FromSsize_t(i); if (unlikely(!x)) return NULL;")
2392
+ # Note that PyType_GetSlot() only works on heap-types before 3.10, so not using type slots
2393
+ # and defining cdef classes as non-heap types is probably impossible.
2394
+ code.putln("#if CYTHON_USE_TYPE_SLOTS || (!CYTHON_USE_TYPE_SPECS && __PYX_LIMITED_VERSION_HEX < 0x030A0000)")
2395
+ if implements_mapping_get:
2396
+ code.putln("binaryfunc f = Py_TYPE(o)->tp_as_mapping->mp_subscript;")
2397
+ else:
2398
+ code.putln("PyMappingMethods *mapping_methods = Py_TYPE(o)->tp_as_mapping;")
2399
+ code.putln("binaryfunc f = mapping_methods ? mapping_methods->mp_subscript : NULL;")
2400
+ code.putln("#else")
2401
+ code.putln("binaryfunc f = ((binaryfunc)PyType_GetSlot(Py_TYPE(o), Py_mp_subscript));")
2402
+ code.putln("#endif")
2403
+ if not implements_mapping_get:
2404
+ code.putln(f"if (unlikely(!f)) f = (binaryfunc) {get_entry.func_cname};")
2405
+ code.putln("r = f(o, x);")
2406
+ code.putln("Py_DECREF(x);")
2407
+ code.putln("return r;")
2408
+
2409
+ code.putln("}")
2410
+ code.exit_cfunc_scope()
2411
+
2412
+ # Mapping protocol.
2413
+ if implements_mapping_get:
2414
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "mp_subscript", "PyObject *o, PyObject *i", needs_funcstate=False)
2415
+ if is_sequence_get:
2416
+ code.putln("Py_ssize_t x = __Pyx_PyIndex_AsSsize_t(i); if (unlikely(x == -1 && PyErr_Occurred())) return NULL;")
2417
+ code.putln(f"return {get_entry.func_cname}(o, x);")
2418
+ else:
2419
+ code.putln(f"return {get_entry.func_cname}(o, i);")
2420
+ code.putln("}")
2421
+ code.exit_cfunc_scope()
2218
2422
 
2219
2423
  def generate_ass_subscript_function(self, scope, code):
2220
- # Setting and deleting an item are both done through
2221
- # the ass_subscript method, so we dispatch to user's __setitem__
2222
- # or __delitem__, or raise an exception.
2424
+ # Setting and deleting an item are both done through the ass_item/ass_subscript slots,
2425
+ # so we dispatch to user's __setitem__ or __delitem__, or raise an exception.
2426
+ set_entry = TypeSlots.SubscriptSlot.find_special_method(scope, '__setitem__')
2427
+ del_entry = TypeSlots.SubscriptSlot.find_special_method(scope, '__delitem__')
2223
2428
  base_type = scope.parent_type.base_type
2224
- set_entry = scope.lookup_here("__setitem__")
2225
- del_entry = scope.lookup_here("__delitem__")
2226
- code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "mp_ass_subscript", "PyObject *o, PyObject *i, PyObject *v")
2227
- code.putln(
2228
- "if (v) {")
2229
- if set_entry:
2230
- code.putln("return %s(o, i, v);" % set_entry.func_cname)
2231
- else:
2232
- code.putln(
2233
- "__Pyx_TypeName o_type_name;")
2234
- self.generate_guarded_basetype_call(
2235
- base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2236
- code.putln(
2237
- "o_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(o));")
2238
- code.putln(
2239
- "PyErr_Format(PyExc_NotImplementedError,")
2240
- code.putln(
2241
- ' "Subscript assignment not supported by " __Pyx_FMT_TYPENAME, o_type_name);')
2242
- code.putln(
2243
- "__Pyx_DECREF_TypeName(o_type_name);")
2244
- code.putln(
2245
- "return -1;")
2246
- code.putln(
2247
- "}")
2248
- code.putln(
2249
- "else {")
2250
- if del_entry:
2251
- code.putln(
2252
- "return %s(o, i);" % (
2253
- del_entry.func_cname))
2254
- else:
2255
- code.putln(
2256
- "__Pyx_TypeName o_type_name;")
2257
- self.generate_guarded_basetype_call(
2258
- base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2259
- code.putln(
2260
- "o_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(o));")
2261
- code.putln(
2262
- "PyErr_Format(PyExc_NotImplementedError,")
2263
- code.putln(
2264
- ' "Subscript deletion not supported by " __Pyx_FMT_TYPENAME, o_type_name);')
2265
- code.putln(
2266
- "__Pyx_DECREF_TypeName(o_type_name);")
2429
+
2430
+ is_sequence_set = set_entry and set_entry.signature == TypeSlots.sequence_subscript_signatures['__setitem__']
2431
+ is_sequence_del = del_entry and del_entry.signature == TypeSlots.sequence_subscript_signatures['__delitem__']
2432
+
2433
+ def handle_not_supported(op_name):
2434
+ code.globalstate.use_utility_code(
2435
+ UtilityCode.load_cached("RaiseErrorWithObjectType1", "ObjectHandling.c"))
2267
2436
  code.putln(
2268
- "return -1;")
2269
- code.putln(
2270
- "}")
2271
- code.putln(
2272
- "}")
2273
- code.exit_cfunc_scope()
2437
+ '__Pyx_RaiseErrorWithObjectType1(PyExc_NotImplementedError,'
2438
+ ' "Subscript %.10s not supported by " __Pyx_FMT_TYPENAME,'
2439
+ f' "{op_name}", o);'
2440
+ )
2441
+ code.putln("return -1;")
2442
+
2443
+ set_or_del = "likely(v)" if not del_entry else "unlikely(v)" if not set_entry else "v"
2444
+
2445
+ # Sequence protocol.
2446
+ if TypeSlots.SubscriptSlot.implements_slot(scope, 'sq_ass_item'):
2447
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "sq_ass_item", "PyObject *o, Py_ssize_t i, PyObject *v")
2448
+ code.putln("if (%s) {" % set_or_del)
2449
+
2450
+ if is_sequence_set:
2451
+ code.putln(f"return {set_entry.func_cname}(o, i, v);")
2452
+ elif set_entry:
2453
+ code.putln("PyObject *x = PyLong_FromSsize_t(i); if (unlikely(!x)) return -1;")
2454
+ code.putln(f"int r = {set_entry.func_cname}(o, x, v);")
2455
+ code.putln("Py_DECREF(x);")
2456
+ code.putln("return r;")
2457
+ else:
2458
+ self.generate_guarded_basetype_call(
2459
+ base_type, "tp_as_sequence", "sq_ass_item", "ssizeobjargproc", "o, i, v", code)
2460
+ handle_not_supported("assignment")
2461
+
2462
+ code.putln("} else {")
2463
+ if is_sequence_del:
2464
+ code.putln(f"return {del_entry.func_cname}(o, i);")
2465
+ elif del_entry:
2466
+ code.putln("PyObject *x = PyLong_FromSsize_t(i); if (unlikely(!x)) return -1;")
2467
+ code.putln(f"int r = {del_entry.func_cname}(o, x);")
2468
+ code.putln("Py_DECREF(x);")
2469
+ code.putln("return r;")
2470
+ else:
2471
+ self.generate_guarded_basetype_call(
2472
+ base_type, "tp_as_sequence", "sq_ass_item", "ssizeobjargproc", "o, i, v", code)
2473
+ handle_not_supported("deletion")
2474
+
2475
+ code.putln("}")
2476
+ code.putln("}")
2477
+ code.exit_cfunc_scope()
2478
+
2479
+ # Mapping protocol.
2480
+ if TypeSlots.SubscriptSlot.implements_slot(scope, 'mp_ass_subscript'):
2481
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "mp_ass_subscript", "PyObject *o, PyObject *i, PyObject *v")
2482
+ code.putln("if (%s) {" % set_or_del)
2483
+
2484
+ if is_sequence_set:
2485
+ code.putln("Py_ssize_t x = __Pyx_PyIndex_AsSsize_t(i); if (unlikely(x == -1 && PyErr_Occurred())) return -1;")
2486
+ code.putln(f"return {set_entry.func_cname}(o, x, v);")
2487
+ elif set_entry:
2488
+ code.putln(f"return {set_entry.func_cname}(o, i, v);")
2489
+ else:
2490
+ self.generate_guarded_basetype_call(
2491
+ base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2492
+ handle_not_supported("assignment")
2493
+
2494
+ code.putln("} else {")
2495
+ if is_sequence_del:
2496
+ code.putln("Py_ssize_t x = __Pyx_PyIndex_AsSsize_t(i); if (unlikely(x == -1 && PyErr_Occurred())) return -1;")
2497
+ code.putln(f"return {del_entry.func_cname}(o, x);")
2498
+ elif del_entry:
2499
+ code.putln(f"return {del_entry.func_cname}(o, i);")
2500
+ else:
2501
+ self.generate_guarded_basetype_call(
2502
+ base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2503
+ handle_not_supported("deletion")
2504
+
2505
+ code.putln("}")
2506
+ code.putln("}")
2507
+ code.exit_cfunc_scope()
2274
2508
 
2275
2509
  def generate_guarded_basetype_call(
2276
- self, base_type, substructure, slot, functype, args, code):
2510
+ self, base_type, substructure, slot, functype, args, code, likely=True):
2277
2511
  if base_type:
2278
2512
  base_tpname = code.typeptr_cname_in_module_state(base_type)
2279
2513
  # Note that the limited API versions will only work for non-heaptypes on Python3.10+.
@@ -2284,8 +2518,8 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2284
2518
  else:
2285
2519
  code.putln(
2286
2520
  f"{functype} f = __Pyx_PyType_TryGetSlot({base_tpname}, {slot}, {functype});")
2287
- code.putln("if (f)")
2288
- code.putln(f"return f({args});")
2521
+ can_call = "likely(f)" if likely else "f"
2522
+ code.putln(f"if ({can_call}) return f({args});")
2289
2523
 
2290
2524
  def generate_richcmp_function(self, scope, code):
2291
2525
  if scope.lookup_here("__richcmp__"):
@@ -2567,7 +2801,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2567
2801
  set_entry.func_cname))
2568
2802
  else:
2569
2803
  self.generate_guarded_basetype_call(
2570
- base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code)
2804
+ base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code, likely=False)
2571
2805
  code.putln(
2572
2806
  "return PyObject_GenericSetAttr(o, n, v);")
2573
2807
  code.putln(
@@ -2580,7 +2814,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2580
2814
  del_entry.func_cname))
2581
2815
  else:
2582
2816
  self.generate_guarded_basetype_call(
2583
- base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code)
2817
+ base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code, likely=False)
2584
2818
  code.putln(
2585
2819
  "return PyObject_GenericSetAttr(o, n, 0);")
2586
2820
  code.putln(
@@ -2761,22 +2995,6 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2761
2995
  code.putln("{0, 0, 0, 0, 0}")
2762
2996
  code.putln("};")
2763
2997
 
2764
- if weakref_entry:
2765
- position = format_position(weakref_entry.pos)
2766
- weakref_warn_mesage = (
2767
- f"{position}: __weakref__ is unsupported in the Limited API when "
2768
- "running on Python <3.9.")
2769
- # Note: Limited API rather than USE_TYPE_SPECS - we work round the issue
2770
- # with USE_TYPE_SPECS outside the limited API
2771
- code.putln("#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000")
2772
- code.putln("#if defined(__GNUC__) || defined(__clang__)")
2773
- code.putln(f'#warning "{weakref_warn_mesage}"')
2774
- code.putln("#elif defined(_MSC_VER)")
2775
- code.putln(f'#pragma message("{weakref_warn_mesage}")')
2776
- code.putln("#endif")
2777
- code.putln("#endif")
2778
-
2779
-
2780
2998
  code.putln("static PyType_Slot %s_slots[] = {" % ext_type.typeobj_cname)
2781
2999
  for slot in TypeSlots.get_slot_table(code.globalstate.directives):
2782
3000
  slot.generate_spec(scope, code)
@@ -2906,70 +3124,132 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2906
3124
  entry.type.create_from_py_utility_code(env)
2907
3125
 
2908
3126
  def generate_import_star(self, env, code):
2909
- env.use_utility_code(UtilityCode.load_cached("CStringEquals", "StringTools.c"))
2910
3127
  code.start_initcfunc(
2911
3128
  f"int {Naming.import_star_set}("
2912
- f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname},"
2913
- "PyObject *o, PyObject* py_name, const char *name)")
2914
-
2915
- code.putln("static const char* internal_type_names[] = {")
2916
- for name, entry in sorted(env.entries.items()):
2917
- if entry.is_type:
2918
- code.putln('"%s",' % name)
2919
- code.putln("0")
2920
- code.putln("};")
3129
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname}, "
3130
+ "PyObject* o, PyObject* py_name)")
2921
3131
 
2922
- code.putln("const char** type_name = internal_type_names;")
2923
- code.putln("while (*type_name) {")
2924
- code.putln("if (__Pyx_StrEq(name, *type_name)) {")
2925
- code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);')
2926
- code.putln('goto bad;')
2927
- code.putln("}")
2928
- code.putln("type_name++;")
2929
- code.putln("}")
3132
+ code.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
2930
3133
 
2931
3134
  old_error_label = code.new_error_label()
2932
- code.putln("if (0);") # so the first one can be "else if"
2933
- msvc_count = 0
2934
- for name, entry in sorted(env.entries.items()):
2935
- if entry.is_cglobal and entry.used and not entry.type.is_const:
2936
- msvc_count += 1
2937
- if msvc_count % 100 == 0:
2938
- code.putln("#ifdef _MSC_VER")
2939
- code.putln("if (0); /* Workaround for MSVC C1061. */")
2940
- code.putln("#endif")
2941
- code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name)
2942
- if entry.type.is_pyobject:
2943
- if entry.type.is_extension_type or entry.type.is_builtin_type:
2944
- type_test = entry.type.type_test_code(
2945
- env, "o")
2946
- code.putln("if (!(%s)) %s;" % (
2947
- type_test,
2948
- code.error_goto(entry.pos)))
2949
- code.putln("Py_INCREF(o);")
2950
- code.put_decref(entry.cname, entry.type, nanny=False)
2951
- code.putln("%s = %s;" % (
2952
- entry.cname,
2953
- PyrexTypes.typecast(entry.type, py_object_type, "o")))
2954
- elif entry.type.create_from_py_utility_code(env):
2955
- # if available, utility code was already created in self.prepare_utility_code()
2956
- code.putln(entry.type.from_py_call_code(
2957
- 'o', entry.cname, entry.pos, code))
2958
- else:
2959
- code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (
2960
- name, entry.type))
2961
- code.putln(code.error_goto(entry.pos))
2962
- code.putln("}")
2963
- code.putln("else {")
2964
- code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
3135
+ cannot_overwrite = code.new_label("cannot_overwrite")
3136
+ cannot_convert = code.new_label("cannot_convert")
3137
+ done = code.new_label("done")
3138
+
3139
+ # Always compare and store plain, interned 'str' objects.
3140
+ code.putln("PyObject *__pyx_interned_name = PyUnicode_FromObject(py_name);")
3141
+ code.putln("if (unlikely(!__pyx_interned_name)) return -1;")
3142
+ code.putln("Py_ssize_t __pyx_slen = PyUnicode_GetLength(__pyx_interned_name);")
3143
+ code.putln("if (unlikely(__pyx_slen < 1)) {")
3144
+ code.put("if (__pyx_slen < 0) goto bad; else ")
3145
+ code.put_goto(done)
2965
3146
  code.putln("}")
3147
+ code.putln("PyUnicode_InternInPlace(&__pyx_interned_name);")
3148
+ # Replace borrowed argument reference with borrowed local reference.
3149
+ code.putln("py_name = __pyx_interned_name;")
3150
+
3151
+ # Specific C assignments.
3152
+
3153
+ entries = env.entries
3154
+ cglobal_names = [
3155
+ name for name, entry in entries.items()
3156
+ if not (entry.scope.is_internal or name.lower().startswith('__pyx_')) and (
3157
+ entry.is_cglobal and entry.used and not entry.type.is_const
3158
+ or entry.is_cclass
3159
+ )
3160
+ ]
3161
+ cglobal_names.sort()
3162
+
3163
+ def handle_entry(name, entry):
3164
+ py_name = code.get_py_string_const(name, identifier=True)
3165
+ code.put(f'if (py_name == {py_name}) ') # Compare the two interned names.
3166
+ if entry.is_cclass:
3167
+ code.put_goto(cannot_overwrite)
3168
+ return
3169
+
3170
+ code.putln('{')
3171
+ if entry.type.is_pyobject:
3172
+ if entry.type.is_extension_type or entry.type.is_builtin_type:
3173
+ type_test = entry.type.type_test_code(
3174
+ env, "o")
3175
+ code.putln("if (!(%s)) %s;" % (
3176
+ type_test,
3177
+ code.error_goto(entry.pos)))
3178
+ code.putln("Py_INCREF(o);")
3179
+ code.putln(f"{entry.type.declaration_code(Naming.quick_temp_cname)} = {entry.cname};")
3180
+ code.putln("%s = %s;" % (
3181
+ entry.cname,
3182
+ PyrexTypes.typecast(entry.type, py_object_type, "o")))
3183
+ code.put_decref(Naming.quick_temp_cname, entry.type, nanny=False)
3184
+ code.put_goto(done)
3185
+ elif entry.type.create_from_py_utility_code(env):
3186
+ # if available, utility code was already created in self.prepare_utility_code()
3187
+ code.putln(entry.type.from_py_call_code(
3188
+ 'o', entry.cname, entry.pos, code))
3189
+ code.put_goto(done)
3190
+ else:
3191
+ code.put(f"failed_type = {EncodedString(entry.type).as_c_string_literal()}; ")
3192
+ code.put_goto(cannot_convert)
3193
+ code.putln('}')
3194
+
3195
+ if cglobal_names:
3196
+ prefix_groups = [
3197
+ (start_letter, list(names))
3198
+ for start_letter, names in itertools.groupby(cglobal_names, key=operator.itemgetter(0))
3199
+ ]
3200
+
3201
+ code.putln("{")
3202
+ code.putln("const char* failed_type = NULL;")
3203
+
3204
+ code.putln("Py_UCS4 __pyx_start_letter = __Pyx_PyUnicode_READ_CHAR(py_name, 0);")
3205
+ code.putln("#if !CYTHON_ASSUME_SAFE_MACROS")
3206
+ code.putln("if (unlikely(__pyx_start_letter) == (Py_UCS4) -1) goto bad;")
3207
+ code.putln("#endif")
3208
+
3209
+ code.putln("switch (__pyx_start_letter) {")
3210
+ for start_letter, names in prefix_groups:
3211
+ code.putln(f"case {ord(start_letter)}:")
3212
+ for name in names:
3213
+ handle_entry(name, entries[name])
3214
+ code.putln("break;")
3215
+ code.putln("}")
3216
+
3217
+ if not code.label_used(cannot_convert):
3218
+ code.putln("CYTHON_UNUSED_VAR(failed_type);")
3219
+
3220
+ pysetattr = code.new_label("python_setattr")
3221
+ code.put_goto(pysetattr)
3222
+
3223
+ if code.label_used(cannot_convert):
3224
+ code.put_label(cannot_convert)
3225
+ code.putln(
3226
+ f'PyErr_Format(PyExc_TypeError, "Cannot convert Python object %.200U to %.200s", py_name, failed_type);')
3227
+ code.putln("goto bad;")
3228
+
3229
+ if code.label_used(cannot_overwrite):
3230
+ code.put_label(cannot_overwrite)
3231
+ code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %.200U", py_name);')
3232
+ code.putln("goto bad;")
3233
+
3234
+ code.put_label(pysetattr)
3235
+ code.putln("}")
3236
+
3237
+ # Generic module dict assignment.
3238
+
3239
+ code.putln(f"if (PyObject_SetAttr({Naming.module_cname}, py_name, o) < 0) goto bad;")
3240
+
3241
+ # Error handling and function exit.
3242
+
3243
+ code.put_label(done)
2966
3244
  code.putln("return 0;")
3245
+
2967
3246
  if code.label_used(code.error_label):
2968
3247
  code.put_label(code.error_label)
2969
- # This helps locate the offending name.
3248
+ # This helps locate the offending name, but we can only jump here with a known valid code position.
2970
3249
  code.put_add_traceback(EncodedString(self.full_module_name))
2971
3250
  code.error_label = old_error_label
2972
3251
  code.putln("bad:")
3252
+ code.putln("Py_DECREF(__pyx_interned_name);")
2973
3253
  code.putln("return -1;")
2974
3254
  code.putln("}")
2975
3255
  code.putln("")
@@ -2978,6 +3258,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2978
3258
 
2979
3259
  def generate_module_state_start(self, env, code):
2980
3260
  # TODO: Refactor to move module state struct decl closer to the static decl
3261
+ code.putln("#ifdef __cplusplus")
3262
+ code.putln("namespace {")
3263
+ code.putln("#endif")
2981
3264
  code.putln('typedef struct {')
2982
3265
  code.putln('PyObject *%s;' % env.module_dict_cname)
2983
3266
  code.putln('PyObject *%s;' % Naming.builtins_cname)
@@ -2993,6 +3276,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
2993
3276
  module_state_clear = globalstate['module_state_clear_end']
2994
3277
  module_state_traverse = globalstate['module_state_traverse_end']
2995
3278
  module_state.putln('} %s;' % Naming.modulestatetype_cname)
3279
+ module_state.putln("#ifdef __cplusplus")
3280
+ module_state.putln("} /* anonymous namespace */")
3281
+ module_state.putln("#endif")
2996
3282
  module_state.putln('')
2997
3283
  globalstate.use_utility_code(
2998
3284
  UtilityCode.load("MultiPhaseInitModuleState", "ModuleSetupCode.c")
@@ -3235,8 +3521,11 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3235
3521
 
3236
3522
  shared_utility_exporter.call_export_code(code)
3237
3523
 
3238
- with subfunction("Type init code") as inner_code:
3239
- self.generate_type_init_code(env, inner_code)
3524
+ code.putln("/*--- Type init code ---*/")
3525
+
3526
+ shared_utility_exporter.call_import_code(code)
3527
+
3528
+ self.generate_type_init_code(env, subfunction, code)
3240
3529
 
3241
3530
  with subfunction("Type import code") as inner_code:
3242
3531
  for module in imported_modules:
@@ -3251,8 +3540,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3251
3540
  self.specialize_fused_types(module)
3252
3541
  self.generate_c_function_import_code_for_module(module, env, inner_code)
3253
3542
 
3254
- shared_utility_exporter.call_import_code(code)
3255
-
3543
+ code.put_error_if_neg(self.pos, "__Pyx_InitAfterSharedUtility()")
3256
3544
  code.putln("/*--- Execution code ---*/")
3257
3545
  code.mark_pos(None)
3258
3546
 
@@ -3313,9 +3601,9 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3313
3601
  # fetch/restore the error indicator because PyState_RemoveModule might fail itself
3314
3602
  code.putln("if (pystate_addmodule_run) {")
3315
3603
  code.putln("PyObject *tp, *value, *tb;")
3316
- code.putln("PyErr_Fetch(&tp, &value, &tb);")
3604
+ code.putln("__Pyx_PyErr_FetchException(&tp, &value, &tb);")
3317
3605
  code.putln("PyState_RemoveModule(&%s);" % Naming.pymoduledef_cname)
3318
- code.putln("PyErr_Restore(tp, value, tb);")
3606
+ code.putln("__Pyx_PyErr_RestoreException(tp, value, tb);")
3319
3607
  code.putln("}")
3320
3608
  code.putln("#endif")
3321
3609
  code.putln('} else if (!PyErr_Occurred()) {')
@@ -3350,8 +3638,8 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3350
3638
 
3351
3639
  class ModInitSubfunction:
3352
3640
  def __init__(self, code_type):
3353
- cname = '_'.join(code_type.lower().split())
3354
- assert re.match("^[a-z0-9_]+$", cname)
3641
+ cname = '_'.join(code_type.split())
3642
+ assert re.match("^[a-zA-Z0-9_]+$", cname)
3355
3643
  self.cfunc_name = "__Pyx_modinit_%s" % cname
3356
3644
  self.description = code_type
3357
3645
  self.tempdecl_code = None
@@ -3536,23 +3824,10 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3536
3824
  scope.mangle_internal(Naming.freelist_name))
3537
3825
  freecount_name = code.name_in_main_c_code_module_state(
3538
3826
  scope.mangle_internal(Naming.freecount_name))
3827
+ code.globalstate.use_utility_code(
3828
+ UtilityCode.load_cached("ClearFreelist", "ExtensionTypes.c"))
3539
3829
  code.putln('#if CYTHON_USE_FREELISTS')
3540
- code.putln("while (%s > 0) {" % freecount_name)
3541
- code.putln("PyObject* o = (PyObject*)%s[--%s];" % (
3542
- freelist_name, freecount_name))
3543
- code.putln("PyTypeObject *tp = Py_TYPE(o);")
3544
- code.putln("#if CYTHON_USE_TYPE_SLOTS")
3545
- code.putln("(*tp->tp_free)(o);")
3546
- code.putln("#else")
3547
- # Asking for PyType_GetSlot(..., Py_tp_free) seems to cause an error in pypy
3548
- code.putln("freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free);")
3549
- code.putln("if (tp_free) tp_free(o);")
3550
- code.putln("#endif")
3551
- code.putln("#if CYTHON_USE_TYPE_SPECS")
3552
- # Release the reference that "o" owned for its type.
3553
- code.putln("Py_DECREF(tp);")
3554
- code.putln("#endif")
3555
- code.putln("}")
3830
+ code.putln(f"__Pyx_ClearFreelist((PyObject **)&{freelist_name}, &{freecount_name});")
3556
3831
  code.putln('#endif') # CYTHON_USE_FREELISTS
3557
3832
  # for entry in env.pynum_entries:
3558
3833
  # code.put_decref_clear(entry.cname,
@@ -3911,7 +4186,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3911
4186
  _generate_import_code(
3912
4187
  code, self.pos, imports, module.qualified_name, f"__Pyx_ImportFunction_{Naming.cyversion}", "void (**{name})(void)")
3913
4188
 
3914
- def generate_type_init_code(self, env, code):
4189
+ def generate_type_init_code(self, env, subfunction, code):
3915
4190
  # Generate type import code for extern extension types
3916
4191
  # and type ready code for non-extern ones.
3917
4192
  with ModuleImportGenerator(code) as import_generator:
@@ -3920,9 +4195,10 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3920
4195
  self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator)
3921
4196
  else:
3922
4197
  self.generate_base_type_import_code(env, entry, code, import_generator)
3923
- self.generate_exttype_vtable_init_code(entry, code)
3924
- if entry.type.early_init:
3925
- self.generate_type_ready_code(entry, code)
4198
+ with subfunction("Exttype " + entry.type.objstruct_cname) as inner_code:
4199
+ self.generate_exttype_vtable_init_code(entry, inner_code)
4200
+ if entry.type.early_init:
4201
+ self.generate_type_ready_code(entry, inner_code)
3926
4202
 
3927
4203
  def generate_base_type_import_code(self, env, entry, code, import_generator):
3928
4204
  base_type = entry.type.base_type
@@ -3945,11 +4221,10 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3945
4221
  if type.vtabptr_cname:
3946
4222
  code.globalstate.use_utility_code(
3947
4223
  UtilityCode.load_cached('GetVTable', 'ImportExport.c'))
3948
- code.putln("%s = (struct %s*)__Pyx_GetVtable(%s); %s" % (
3949
- type.vtabptr_cname,
3950
- type.vtabstruct_cname,
4224
+ code.putln(code.error_goto_if("__Pyx_GetVtable(%s, (void**)&%s) != 1" % (
3951
4225
  code.name_in_main_c_code_module_state(type.typeptr_cname),
3952
- code.error_goto_if_null(type.vtabptr_cname, pos)))
4226
+ type.vtabptr_cname,
4227
+ ), pos))
3953
4228
  env.types_imported.add(type)
3954
4229
 
3955
4230
  def generate_type_import_call(self, type, code, import_generator, error_code=None, error_pos=None, is_api=False):
@@ -3958,7 +4233,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
3958
4233
  type_name = type.name
3959
4234
  is_builtin = module_name in ('__builtin__', 'builtins')
3960
4235
  if not is_builtin:
3961
- module_name = f'"{module_name}"'
4236
+ module_name = module_name.as_c_string_literal()
3962
4237
  elif type_name in Code.ctypedef_builtins_map:
3963
4238
  # Fast path for special builtins, don't actually import
3964
4239
  code.putln(
@@ -4013,6 +4288,7 @@ class ModuleNode(Nodes.Node, Nodes.BlockNode):
4013
4288
  code.put(f'__Pyx_ImportType_CheckSize_{check_size.title()}_{Naming.cyversion});')
4014
4289
 
4015
4290
  code.putln(f' if (!{typeptr_cname}) {error_code}')
4291
+
4016
4292
  def generate_type_ready_code(self, entry, code):
4017
4293
  Nodes.CClassDefNode.generate_type_ready_code(entry, code)
4018
4294