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
@@ -3,11 +3,6 @@
3
3
  #
4
4
 
5
5
 
6
- import os
7
-
8
- from .. import Utils
9
-
10
-
11
6
  class ShouldBeFromDirective:
12
7
 
13
8
  known_directives = []
@@ -51,7 +51,7 @@ cdef class YieldNodeCollector(TreeVisitor):
51
51
 
52
52
  @cython.final
53
53
  cdef class MarkClosureVisitor(CythonTransform):
54
- cdef bint needs_closure
54
+ cdef int needs_closure # actually enum
55
55
  cdef list excludes
56
56
 
57
57
  @cython.final
@@ -72,6 +72,7 @@ cdef class GilCheck(VisitorTransform):
72
72
  cdef int nogil_state
73
73
  cdef int nogil_state_at_current_gilstatnode
74
74
  cdef object in_lock_block
75
+ cdef bint in_critical_section
75
76
 
76
77
  cdef class TransformBuiltinMethods(EnvTransform):
77
78
  cdef dict def_node_body_insertions
@@ -2,12 +2,11 @@ import cython
2
2
  cython.declare(PyrexTypes=object, Naming=object, ExprNodes=object, Nodes=object,
3
3
  Options=object, UtilNodes=object, LetNode=object,
4
4
  LetRefNode=object, TreeFragment=object, EncodedString=object,
5
- error=object, warning=object, copy=object, hashlib=object, sys=object,
5
+ error=object, warning=object, copy=object, hashlib=object,
6
6
  itemgetter=object)
7
7
 
8
8
  import copy
9
9
  import hashlib
10
- import sys
11
10
  from operator import itemgetter
12
11
 
13
12
  from . import Code
@@ -245,7 +244,7 @@ class PostParse(ScopeTrackingTransform):
245
244
  newdecls = []
246
245
  for decl in node.declarators:
247
246
  declbase = decl
248
- while isinstance(declbase, (Nodes.CPtrDeclaratorNode, Nodes.CConstDeclaratorNode)):
247
+ while isinstance(declbase, (Nodes.CPtrDeclaratorNode, Nodes.CQualifierDeclaratorNode)):
249
248
  declbase = declbase.base
250
249
  if isinstance(declbase, Nodes.CNameDeclaratorNode):
251
250
  if declbase.default is not None:
@@ -962,10 +961,9 @@ class InterpretCompilerDirectives(CythonTransform):
962
961
  node.cython_module_names = self.cython_module_names
963
962
  return node
964
963
 
965
- def visit_CompilerDirectivesNode(self, node):
966
- old_directives, self.directives = self.directives, node.directives
967
- self.visitchildren(node)
968
- self.directives = old_directives
964
+ def visit_CompilerDirectivesMixin(self, node):
965
+ with node.apply_directives(self):
966
+ self.visitchildren(node)
969
967
  return node
970
968
 
971
969
  # The following four functions track imports and cimports that
@@ -1373,7 +1371,8 @@ class InterpretCompilerDirectives(CythonTransform):
1373
1371
  error(dec.pos, "Cannot apply @cfunc to @ufunc, please reverse the decorators.")
1374
1372
  directives.append(directive)
1375
1373
  current_opt_dict[name] = value
1376
- else:
1374
+ elif name not in ['profile', 'linetrace']:
1375
+ # Exclude some decorators that people may leave around, but warn about useless ones.
1377
1376
  warning(dec.pos, "Directive does not change previous value (%s%s)" % (
1378
1377
  name, '=%r' % value if value is not None else ''))
1379
1378
  if directive[0] == 'staticmethod':
@@ -1868,13 +1867,24 @@ class DecoratorTransform(ScopeTrackingTransform, SkipDeclarations):
1868
1867
 
1869
1868
  ret_node = node
1870
1869
  decorator_node = self._find_property_decorator(node)
1871
- if decorator_node:
1870
+ if decorator_node and (name := node.declared_name()):
1872
1871
  if decorator_node.decorator.is_name:
1873
- name = node.declared_name()
1874
- if name:
1875
- ret_node = self._add_property(node, name, decorator_node)
1872
+ ret_node = self._add_property(node, name, decorator_node)
1876
1873
  else:
1877
- error(decorator_node.pos, "C property decorator can only be @property")
1874
+ handler_name = self._map_property_attribute(decorator_node.decorator.attribute)
1875
+ if handler_name:
1876
+ if handler_name == "__del__":
1877
+ error(decorator_node.pos,
1878
+ "Cannot have deleter for C property")
1879
+ ret_node = None
1880
+ elif decorator_node.decorator.obj.name != name:
1881
+ # CPython does not generate an error or warning, but not something useful either.
1882
+ error(decorator_node.pos,
1883
+ "Mismatching C property names, expected '%s', got '%s'" % (
1884
+ decorator_node.decorator.obj.name, name))
1885
+ ret_node = None
1886
+ else:
1887
+ ret_node = self._add_to_property(node, handler_name, decorator_node)
1878
1888
 
1879
1889
  if node.decorators:
1880
1890
  return self._reject_decorated_property(node, node.decorators[0])
@@ -1938,6 +1948,17 @@ class DecoratorTransform(ScopeTrackingTransform, SkipDeclarations):
1938
1948
  error(deco.pos, "Property methods with additional decorators are not supported")
1939
1949
  return node
1940
1950
 
1951
+ def _get_property_function_name(self, node):
1952
+ if isinstance(node, Nodes.CFuncDefNode):
1953
+ return node.declared_name()
1954
+ return node.name
1955
+
1956
+ def _rename_property_function(self, node, name):
1957
+ if isinstance(node, Nodes.CFuncDefNode):
1958
+ node.declarator.set_declared_name(name)
1959
+ else:
1960
+ node.name = name
1961
+
1941
1962
  def _add_property(self, node, name, decorator_node):
1942
1963
  if len(node.decorators) > 1:
1943
1964
  return self._reject_decorated_property(node, decorator_node)
@@ -1945,40 +1966,42 @@ class DecoratorTransform(ScopeTrackingTransform, SkipDeclarations):
1945
1966
  properties = self._properties[-1]
1946
1967
  is_cproperty = isinstance(node, Nodes.CFuncDefNode)
1947
1968
  body = Nodes.StatListNode(node.pos, stats=[node])
1969
+ node_type = Nodes.PropertyNode
1948
1970
  if is_cproperty:
1949
- if name in properties:
1950
- error(node.pos, "C property redeclared")
1951
1971
  if 'inline' not in node.modifiers:
1952
1972
  error(node.pos, "C property method must be declared 'inline'")
1953
- prop = Nodes.CPropertyNode(node.pos, doc=node.doc, name=name, body=body)
1954
- elif name in properties:
1973
+ node_type = Nodes.CPropertyNode
1974
+ if name in properties:
1955
1975
  prop = properties[name]
1956
1976
  if prop.is_cproperty:
1957
1977
  error(node.pos, "C property redeclared")
1958
1978
  else:
1959
- node.name = EncodedString("__get__")
1979
+ self._rename_property_function(node, EncodedString("__get__"))
1960
1980
  prop.pos = node.pos
1961
1981
  prop.doc = node.doc
1962
1982
  prop.body.stats = [node]
1963
1983
  return None
1964
1984
  else:
1965
- node.name = EncodedString("__get__")
1966
- prop = Nodes.PropertyNode(
1985
+ self._rename_property_function(node, EncodedString("__get__"))
1986
+ prop = node_type(
1967
1987
  node.pos, name=name, doc=node.doc, body=body)
1968
1988
  properties[name] = prop
1969
1989
  return prop
1970
1990
 
1971
1991
  def _add_to_property(self, node, name, decorator):
1972
1992
  properties = self._properties[-1]
1973
- prop = properties[node.name]
1974
- if prop.is_cproperty:
1975
- error(node.pos, "C property redeclared")
1976
- return None
1977
- node.name = name
1993
+ prop = properties[self._get_property_function_name(node)]
1994
+ self._rename_property_function(node, name)
1995
+ if isinstance(node, Nodes.CFuncDefNode):
1996
+ if 'inline' not in node.modifiers:
1997
+ error(node.pos, "C property method must be declared 'inline'")
1978
1998
  node.decorators.remove(decorator)
1979
1999
  stats = prop.body.stats
1980
2000
  for i, stat in enumerate(stats):
1981
- if stat.name == name:
2001
+ if self._get_property_function_name(stat) == name:
2002
+ if prop.is_cproperty:
2003
+ error(node.pos, "C property redeclared")
2004
+ return None
1982
2005
  stats[i] = node
1983
2006
  break
1984
2007
  else:
@@ -2066,12 +2089,10 @@ class ForwardDeclareTypes(CythonTransform):
2066
2089
  before declaring everything (else) in source code order.
2067
2090
  """
2068
2091
 
2069
- def visit_CompilerDirectivesNode(self, node):
2092
+ def visit_CompilerDirectivesMixin(self, node):
2070
2093
  env = self.module_scope
2071
- old = env.directives
2072
- env.directives = node.directives
2073
- self.visitchildren(node)
2074
- env.directives = old
2094
+ with node.apply_directives(env):
2095
+ self.visitchildren(node)
2075
2096
  return node
2076
2097
 
2077
2098
  def visit_ModuleNode(self, node):
@@ -2122,23 +2143,29 @@ class AnalyseDeclarationsTransform(EnvTransform):
2122
2143
  basic_property = TreeFragment("""
2123
2144
  property NAME:
2124
2145
  def __get__(self):
2125
- return ATTR
2146
+ with CRITICAL_SECTION(self):
2147
+ return ATTR
2126
2148
  def __set__(self, value):
2127
- ATTR = value
2149
+ with CRITICAL_SECTION(self):
2150
+ ATTR = value
2128
2151
  """, level='c_class', pipeline=[NormalizeTree(None)])
2129
2152
  basic_pyobject_property = TreeFragment("""
2130
2153
  property NAME:
2131
2154
  def __get__(self):
2132
- return ATTR
2155
+ with CRITICAL_SECTION(self):
2156
+ return ATTR
2133
2157
  def __set__(self, value):
2134
- ATTR = value
2158
+ with CRITICAL_SECTION(self):
2159
+ ATTR = value
2135
2160
  def __del__(self):
2136
- ATTR = None
2161
+ with CRITICAL_SECTION(self):
2162
+ ATTR = None
2137
2163
  """, level='c_class', pipeline=[NormalizeTree(None)])
2138
2164
  basic_property_ro = TreeFragment("""
2139
2165
  property NAME:
2140
2166
  def __get__(self):
2141
- return ATTR
2167
+ with CRITICAL_SECTION(self):
2168
+ return ATTR
2142
2169
  """, level='c_class', pipeline=[NormalizeTree(None)])
2143
2170
 
2144
2171
  struct_or_union_wrapper = TreeFragment("""
@@ -2332,8 +2359,9 @@ if VALUE is not None:
2332
2359
  cdef tuple state
2333
2360
  cdef object _dict
2334
2361
  cdef bint use_setstate
2335
- state = ({members})
2336
- _dict = getattr(self, '__dict__', None)
2362
+ with CRITICAL_SECTION(self):
2363
+ state = ({members})
2364
+ _dict = getattr(self, '__dict__', None)
2337
2365
  if _dict is not None and _dict:
2338
2366
  state += (_dict,)
2339
2367
  use_setstate = True
@@ -2348,7 +2376,10 @@ if VALUE is not None:
2348
2376
  {unpickle_func_name}__set_state(self, __pyx_state)
2349
2377
  """
2350
2378
 
2351
- pickle_func = TreeFragment(pickle_code, level='c_class', pipeline=[NormalizeTree(None)]).substitute({})
2379
+ pickle_func = TreeFragment(pickle_code, level='c_class', pipeline=[NormalizeTree(None)]).substitute(
2380
+ {'CRITICAL_SECTION': self._create_critical_section_name_node(node.scope, node.pos)}
2381
+ )
2382
+ pickle_func = InterpretCompilerDirectives(None, {})(pickle_func)
2352
2383
  pickle_func.analyse_declarations(node.scope)
2353
2384
 
2354
2385
  self.enter_scope(node, node.scope) # functions should be visited in the class scope
@@ -2389,7 +2420,8 @@ if VALUE is not None:
2389
2420
  self.visitchild(node, 'py_func')
2390
2421
  node.update_fused_defnode_entry(env)
2391
2422
  # For the moment, fused functions do not support METH_FASTCALL
2392
- node.py_func.entry.signature.use_fastcall = False
2423
+ call_signature = node.py_func.entry.signature
2424
+ call_signature.use_fastcall = call_signature.FastcallUsed.NO
2393
2425
  pycfunc = ExprNodes.PyCFunctionNode.from_defnode(node.py_func, binding=True)
2394
2426
  pycfunc = ExprNodes.ProxyNode(pycfunc.coerce_to_temp(env))
2395
2427
  node.resulting_fused_function = pycfunc
@@ -2715,9 +2747,11 @@ if VALUE is not None:
2715
2747
  "ATTR": ExprNodes.AttributeNode(pos=entry.pos,
2716
2748
  obj=ExprNodes.NameNode(pos=entry.pos, name="self"),
2717
2749
  attribute=entry.name),
2750
+ "CRITICAL_SECTION": self._create_critical_section_name_node(self.current_env(), entry.pos)
2718
2751
  },
2719
- pos=entry.pos,
2752
+ pos=entry.pos
2720
2753
  ).stats[0]
2754
+ property = InterpretCompilerDirectives(None, {})(property)
2721
2755
  property.name = entry.name
2722
2756
  property.doc = entry.doc
2723
2757
  return property
@@ -2727,18 +2761,24 @@ if VALUE is not None:
2727
2761
  node.analyse_declarations(self.current_env())
2728
2762
  return node
2729
2763
 
2764
+ def _create_critical_section_name_node(self, env, pos):
2765
+ return ExprNodes.NameNode(
2766
+ pos,
2767
+ name="critical_section",
2768
+ cython_attribute="critical_section"
2769
+ )
2770
+
2730
2771
 
2731
2772
  def _calculate_pickle_checksums(member_names):
2732
2773
  # Cython 0.x used MD5 for the checksum, which a few Python installations remove for security reasons.
2733
2774
  # SHA-256 should be ok for years to come, but early Cython 3.0 alpha releases used SHA-1,
2734
2775
  # which may not be.
2735
2776
  member_names_string = ' '.join(member_names).encode('utf-8')
2736
- hash_kwargs = {'usedforsecurity': False} if sys.version_info >= (3, 9) else {}
2737
2777
  checksums = []
2738
2778
  for algo_name in ['sha256', 'sha1', 'md5']:
2739
2779
  try:
2740
2780
  mkchecksum = getattr(hashlib, algo_name)
2741
- checksum = mkchecksum(member_names_string, **hash_kwargs).hexdigest()
2781
+ checksum = mkchecksum(member_names_string, usedforsecurity=False).hexdigest()
2742
2782
  except (AttributeError, ValueError):
2743
2783
  # The algorithm (i.e. MD5) might not be there at all, or might be blocked at runtime.
2744
2784
  continue
@@ -3082,11 +3122,9 @@ class AdjustDefByDirectives(CythonTransform, SkipDeclarations):
3082
3122
  self.visitchildren(node)
3083
3123
  return node
3084
3124
 
3085
- def visit_CompilerDirectivesNode(self, node):
3086
- old_directives = self.directives
3087
- self.directives = node.directives
3088
- self.visitchildren(node)
3089
- self.directives = old_directives
3125
+ def visit_CompilerDirectivesMixin(self, node):
3126
+ with node.apply_directives(self):
3127
+ self.visitchildren(node)
3090
3128
  return node
3091
3129
 
3092
3130
  def visit_DefNode(self, node):
@@ -3140,6 +3178,11 @@ class AdjustDefByDirectives(CythonTransform, SkipDeclarations):
3140
3178
  value = self.directives["critical_section"]
3141
3179
  if value is not None:
3142
3180
  error(node.pos, "critical_section decorator does not take arguments")
3181
+ if self.in_py_class:
3182
+ warning(
3183
+ node.pos,
3184
+ "@critical_section on method of a class that is not an extension type is unlikely to be useful",
3185
+ 2)
3143
3186
  new_body = Nodes.CriticalSectionStatNode(
3144
3187
  node.pos,
3145
3188
  args=[ExprNodes.FirstArgumentForCriticalSectionNode(node.pos, func_node=node)],
@@ -3394,16 +3437,16 @@ class MarkClosureVisitor(CythonTransform):
3394
3437
  # generator iterable and marking them
3395
3438
 
3396
3439
  def visit_ModuleNode(self, node):
3397
- self.needs_closure = False
3440
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.NO_CLOSURE
3398
3441
  self.excludes = []
3399
3442
  self.visitchildren(node)
3400
3443
  return node
3401
3444
 
3402
3445
  def visit_FuncDefNode(self, node):
3403
- self.needs_closure = False
3446
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.NO_CLOSURE
3404
3447
  self.visitchildren(node)
3405
3448
  node.needs_closure = self.needs_closure
3406
- self.needs_closure = True
3449
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.FULL_CLOSURE
3407
3450
 
3408
3451
  collector = YieldNodeCollector(self.excludes)
3409
3452
  collector.visitchildren(node)
@@ -3441,27 +3484,31 @@ class MarkClosureVisitor(CythonTransform):
3441
3484
  gbody=gbody, lambda_name=node.lambda_name,
3442
3485
  return_type_annotation=node.return_type_annotation,
3443
3486
  is_generator_expression=node.is_generator_expression)
3487
+ if node.needs_closure:
3488
+ # We may have determined that we need a "full closure"
3489
+ # so upgrade the coroutine to signal that
3490
+ coroutine.needs_closure = node.needs_closure
3444
3491
  return coroutine
3445
3492
 
3446
3493
  def visit_CFuncDefNode(self, node):
3447
- self.needs_closure = False
3494
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.NO_CLOSURE
3448
3495
  self.visitchildren(node)
3449
3496
  node.needs_closure = self.needs_closure
3450
- self.needs_closure = True
3497
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.FULL_CLOSURE
3451
3498
  if node.needs_closure and node.overridable:
3452
3499
  error(node.pos, "closures inside cpdef functions not yet supported")
3453
3500
  return node
3454
3501
 
3455
3502
  def visit_LambdaNode(self, node):
3456
- self.needs_closure = False
3503
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.NO_CLOSURE
3457
3504
  self.visitchildren(node)
3458
3505
  node.needs_closure = self.needs_closure
3459
- self.needs_closure = True
3506
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.FULL_CLOSURE
3460
3507
  return node
3461
3508
 
3462
3509
  def visit_ClassDefNode(self, node):
3463
3510
  self.visitchildren(node)
3464
- self.needs_closure = True
3511
+ self.needs_closure = Nodes.FuncDefNode.NeedsClosure.FULL_CLOSURE
3465
3512
  return node
3466
3513
 
3467
3514
  def visit_GeneratorExpressionNode(self, node):
@@ -3521,7 +3568,7 @@ class CreateClosureClasses(CythonTransform):
3521
3568
  in_closure.sort()
3522
3569
 
3523
3570
  # Now from the beginning
3524
- node.needs_closure = False
3571
+ node.needs_closure = Nodes.FuncDefNode.NeedsClosure.NO_CLOSURE
3525
3572
  node.needs_outer_scope = False
3526
3573
 
3527
3574
  func_scope = node.local_scope
@@ -3587,7 +3634,7 @@ class CreateClosureClasses(CythonTransform):
3587
3634
  is_cdef=True)
3588
3635
  if entry.is_declared_generic:
3589
3636
  closure_entry.is_declared_generic = 1
3590
- node.needs_closure = True
3637
+ node.needs_closure = Nodes.FuncDefNode.NeedsClosure.FULL_CLOSURE
3591
3638
  # Do it here because other classes are already checked
3592
3639
  target_module_scope.check_c_class(func_scope.scope_class)
3593
3640
 
@@ -3644,7 +3691,7 @@ class InjectGilHandling(VisitorTransform, SkipDeclarations):
3644
3691
  def _inject_gil_in_nogil(self, node):
3645
3692
  """Allow the (Python statement) node in nogil sections by wrapping it in a 'with gil' block."""
3646
3693
  if self.nogil:
3647
- node = Nodes.GILStatNode(node.pos, state='gil', body=node)
3694
+ node = Nodes.GILStatNode(node.pos, state='gil', body=node, internally_generated=True)
3648
3695
  return node
3649
3696
 
3650
3697
  visit_RaiseStatNode = _inject_gil_in_nogil
@@ -3697,6 +3744,7 @@ class GilCheck(VisitorTransform):
3697
3744
  def __call__(self, root):
3698
3745
  self.env_stack = [root.scope]
3699
3746
  self.nogil_state = Nodes.NoGilState.HasGil
3747
+ self.in_critical_section = False
3700
3748
 
3701
3749
  self.nogil_state_at_current_gilstatnode = Nodes.NoGilState.HasGil
3702
3750
  return super().__call__(root)
@@ -3724,7 +3772,9 @@ class GilCheck(VisitorTransform):
3724
3772
  if inner_nogil and node.nogil_check:
3725
3773
  node.nogil_check(node.local_scope)
3726
3774
 
3775
+ in_critical_section, self.in_critical_section = self.in_critical_section, False
3727
3776
  self._visit_scoped_children(node, self.nogil_state)
3777
+ self.in_critical_section = in_critical_section
3728
3778
 
3729
3779
  # FuncDefNodes can be nested, because a cpdef function contains a def function
3730
3780
  # inside it. Therefore restore to previous state
@@ -3766,45 +3816,88 @@ class GilCheck(VisitorTransform):
3766
3816
  nogil_state = Nodes.NoGilState.NoGil if is_nogil else Nodes.NoGilState.HasGil
3767
3817
  self._visit_scoped_children(node, nogil_state)
3768
3818
  self.nogil_state_at_current_gilstatnode = nogil_state_at_current_gilstatnode
3819
+
3820
+ # Drop pointless nested `with gil: with nogil:` blocks.
3821
+ # These can occur during the generation of prange/parallel sections for example.
3822
+ node_body = node.body
3823
+ if (isinstance(node_body, Nodes.StatListNode) and len(node_body.stats) == 1):
3824
+ node_body = node_body.stats[0]
3825
+ if isinstance(node_body, Nodes.GILStatNode) and node_body.state != node.state and (
3826
+ # Don't optimize out user-inserted `with nogil` for now. They have the
3827
+ # side-effect of deliberately allowing a thread-switch even if they might
3828
+ # appear useless, so they might be deliberate.
3829
+ (node_body.state == "nogil" and node_body.internally_generated) or
3830
+ (node.state == "nogil" and node.internally_generated)):
3831
+ if not node.scope_gil_state_known:
3832
+ node_body.scope_gil_state_known = False
3833
+ node_body.finally_clause.scope_gil_state_known = False
3834
+ if node_body.finally_except_clause is not None:
3835
+ node_body.finally_except_clause.scope_gil_state_known = False
3836
+ return node_body
3837
+ else:
3838
+ return node_body.body
3839
+
3769
3840
  return node
3770
3841
 
3771
3842
  def visit_ParallelRangeNode(self, node):
3772
- if node.nogil or self.nogil_state == Nodes.NoGilState.NoGilScope:
3843
+ if self.nogil_state == Nodes.NoGilState.HasGil and not node.nogil:
3844
+ # We still release the GIL then reacquire it to avoid deadlocks.
3845
+ node.acquire_gil = True
3846
+ if (node.nogil or self.nogil_state == Nodes.NoGilState.NoGilScope or
3847
+ (self.nogil_state == Nodes.NoGilState.HasGil and not node.parent)):
3773
3848
  node_was_nogil, node.nogil = node.nogil, False
3774
- node = Nodes.GILStatNode(node.pos, state='nogil', body=node)
3849
+ node = Nodes.GILStatNode(node.pos, state='nogil', body=node, internally_generated=True)
3775
3850
  if not node_was_nogil and self.nogil_state == Nodes.NoGilState.NoGilScope:
3776
3851
  # We're in a "nogil" function, but that doesn't prove we
3777
3852
  # didn't have the gil
3778
3853
  node.scope_gil_state_known = False
3779
3854
  return self.visit_GILStatNode(node)
3780
3855
 
3781
- if not self.nogil_state:
3782
- error(node.pos, "prange() can only be used without the GIL")
3783
- # Forget about any GIL-related errors that may occur in the body
3784
- return None
3856
+ if node.acquire_gil:
3857
+ if not self.env_stack[-1].directives['freethreading_compatible']:
3858
+ warning(
3859
+ node.pos,
3860
+ "prange without releasing the GIL will only work well on freethreaded Python",
3861
+ level=2)
3862
+ was_nogil = self.nogil_state
3863
+ self.nogil_state = Nodes.NoGilState.HasGil
3785
3864
 
3786
3865
  node.nogil_check(self.env_stack[-1])
3787
3866
  self.visitchildren(node)
3867
+
3868
+ if node.acquire_gil:
3869
+ self.nogil_state = was_nogil
3788
3870
  return node
3789
3871
 
3790
3872
  def visit_ParallelWithBlockNode(self, node):
3791
- if not self.nogil_state:
3792
- error(node.pos, "The parallel section may only be used without "
3793
- "the GIL")
3794
- return None
3795
- if self.nogil_state == Nodes.NoGilState.NoGilScope:
3796
- # We're in a "nogil" function but that doesn't prove we didn't
3797
- # have the gil, so release it
3798
- node = Nodes.GILStatNode(node.pos, state='nogil', body=node)
3799
- node.scope_gil_state_known = False
3873
+ if self.nogil_state != Nodes.NoGilState.NoGil:
3874
+ # Ensure that the GIL is released
3875
+ if self.nogil_state == Nodes.NoGilState.HasGil:
3876
+ # Even if we intend the block to have the GIL it's easier to release
3877
+ # and reacquire it to void deadlocks.
3878
+ node.acquire_gil = True
3879
+ node = Nodes.GILStatNode(node.pos, state='nogil', body=node, internally_generated=True)
3880
+ if self.nogil_state == Nodes.NoGilState.NoGilScope:
3881
+ node.scope_gil_state_known = False
3800
3882
  return self.visit_GILStatNode(node)
3801
3883
 
3884
+ if node.acquire_gil:
3885
+ if not self.env_stack[-1].directives['freethreading_compatible']:
3886
+ warning(
3887
+ node.pos,
3888
+ "Parallel section without releasing the GIL will only work well on freethreaded Python",
3889
+ level=2)
3890
+ was_nogil = self.nogil_state
3891
+ self.nogil_state = Nodes.NoGilState.HasGil
3892
+
3802
3893
  if node.nogil_check:
3803
3894
  # It does not currently implement this, but test for it anyway to
3804
3895
  # avoid potential future surprises
3805
3896
  node.nogil_check(self.env_stack[-1])
3806
3897
 
3807
3898
  self.visitchildren(node)
3899
+ if node.acquire_gil:
3900
+ self.nogil_state = was_nogil
3808
3901
  return node
3809
3902
 
3810
3903
  def visit_TryFinallyStatNode(self, node):
@@ -3821,7 +3914,10 @@ class GilCheck(VisitorTransform):
3821
3914
 
3822
3915
  def visit_CriticalSectionStatNode(self, node):
3823
3916
  # skip normal "try/finally node" handling
3824
- return self.visit_Node(node)
3917
+ in_critical_section, self.in_critical_section = self.in_critical_section, True
3918
+ result = self.visit_Node(node)
3919
+ self.in_critical_section = in_critical_section
3920
+ return result
3825
3921
 
3826
3922
  def visit_CythonLockStatNode(self, node):
3827
3923
  # skip normal "try/finally node" handling
@@ -3865,6 +3961,14 @@ class GilCheck(VisitorTransform):
3865
3961
  )
3866
3962
  return self.visit_Node(node)
3867
3963
 
3964
+ def visit_AttributeNode(self, node):
3965
+ if self.in_critical_section and node.is_py_attr:
3966
+ warning(
3967
+ node.pos,
3968
+ "Python attribute access is not usefully protected by critical_section",
3969
+ 1)
3970
+ return self.visit_Node(node)
3971
+
3868
3972
 
3869
3973
  class CoerceCppTemps(EnvTransform, SkipDeclarations):
3870
3974
  """