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
Cython/Compiler/Nodes.py CHANGED
@@ -12,6 +12,7 @@ cython.declare(os=object, copy=object, chain=object,
12
12
  CppClassScope=object, UtilityCode=object, EncodedString=object,
13
13
  error_type=object)
14
14
 
15
+ from contextlib import contextmanager
15
16
  import copy
16
17
  from itertools import chain
17
18
  import enum
@@ -25,7 +26,7 @@ from .PyrexTypes import py_object_type, error_type
25
26
  from .Symtab import (ModuleScope, LocalScope, ClosureScope, PropertyScope,
26
27
  StructOrUnionScope, PyClassScope, CppClassScope, TemplateScope, GeneratorExpressionScope,
27
28
  CppScopedEnumScope, punycodify_name)
28
- from .Code import UtilityCode
29
+ from .Code import UtilityCode, CCodeWriter
29
30
  from .StringEncoding import EncodedString
30
31
  from . import Future
31
32
  from . import Options
@@ -46,7 +47,7 @@ class NoGilState(enum.IntEnum):
46
47
 
47
48
 
48
49
  def relative_position(pos):
49
- return (pos[0].get_filenametable_entry(), pos[1])
50
+ return (pos[0].get_relative_path().as_posix(), pos[1])
50
51
 
51
52
 
52
53
  def embed_position(pos, docstring):
@@ -343,13 +344,23 @@ class Node:
343
344
  return f'"{source_desc.get_escaped_description()}":{line:d}:{col:d}\n{code}\n'
344
345
 
345
346
 
346
- class CompilerDirectivesNode(Node):
347
+ class CompilerDirectivesMixin:
348
+ # directives {string:value} A dictionary holding the right value for
349
+ # *all* possible directives.
350
+ @contextmanager
351
+ def apply_directives(self, obj):
352
+ # obj is usually a scope, but doesn't have to be.
353
+ old = obj.directives
354
+ obj.directives = self.directives
355
+ yield
356
+ obj.directives = old
357
+
358
+ class CompilerDirectivesNode(CompilerDirectivesMixin, Node):
347
359
  """
348
360
  Sets compiler directives for the children nodes
349
361
  """
350
- # directives {string:value} A dictionary holding the right value for
351
- # *all* possible directives.
352
362
  # body Node
363
+ # directives from CompilerDirectivesMixin
353
364
  child_attrs = ["body"]
354
365
 
355
366
  @classmethod
@@ -363,37 +374,25 @@ class CompilerDirectivesNode(Node):
363
374
  return cls(body.pos, body=body, directives=new_directives, is_terminator=body.is_terminator)
364
375
 
365
376
  def analyse_declarations(self, env):
366
- old = env.directives
367
- env.directives = self.directives
368
- self.body.analyse_declarations(env)
369
- env.directives = old
377
+ with self.apply_directives(env):
378
+ self.body.analyse_declarations(env)
370
379
 
371
380
  def analyse_expressions(self, env):
372
- old = env.directives
373
- env.directives = self.directives
374
- self.body = self.body.analyse_expressions(env)
375
- env.directives = old
381
+ with self.apply_directives(env):
382
+ self.body = self.body.analyse_expressions(env)
376
383
  return self
377
384
 
378
385
  def generate_function_definitions(self, env, code):
379
- env_old = env.directives
380
- code_old = code.globalstate.directives
381
- code.globalstate.directives = self.directives
382
- self.body.generate_function_definitions(env, code)
383
- env.directives = env_old
384
- code.globalstate.directives = code_old
386
+ with self.apply_directives(env), self.apply_directives(code.globalstate):
387
+ self.body.generate_function_definitions(env, code)
385
388
 
386
389
  def generate_execution_code(self, code):
387
- old = code.globalstate.directives
388
- code.globalstate.directives = self.directives
389
- self.body.generate_execution_code(code)
390
- code.globalstate.directives = old
390
+ with self.apply_directives(code.globalstate):
391
+ self.body.generate_execution_code(code)
391
392
 
392
393
  def annotate(self, code):
393
- old = code.globalstate.directives
394
- code.globalstate.directives = self.directives
395
- self.body.annotate(code)
396
- code.globalstate.directives = old
394
+ with self.apply_directives(code.globalstate):
395
+ self.body.annotate(code)
397
396
 
398
397
 
399
398
  class BlockNode:
@@ -528,6 +527,9 @@ class CDeclaratorNode(Node):
528
527
  def declared_name(self):
529
528
  return None
530
529
 
530
+ def set_declared_name(self, new_name):
531
+ raise NotImplementedError()
532
+
531
533
  def analyse_templates(self):
532
534
  # Only C++ functions have templates.
533
535
  return None
@@ -545,6 +547,9 @@ class CNameDeclaratorNode(CDeclaratorNode):
545
547
  def declared_name(self):
546
548
  return self.name
547
549
 
550
+ def set_declared_name(self, new_name):
551
+ self.name = new_name
552
+
548
553
  def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
549
554
  if nonempty and self.name == '':
550
555
  # May have mistaken the name for the type.
@@ -576,6 +581,9 @@ class CPtrDeclaratorNode(CDeclaratorNode):
576
581
  def declared_name(self):
577
582
  return self.base.declared_name()
578
583
 
584
+ def set_declared_name(self, new_name):
585
+ self.base.set_declared_name(new_name)
586
+
579
587
  def analyse_templates(self):
580
588
  return self.base.analyse_templates()
581
589
 
@@ -592,6 +600,9 @@ class _CReferenceDeclaratorBaseNode(CDeclaratorNode):
592
600
  def declared_name(self):
593
601
  return self.base.declared_name()
594
602
 
603
+ def set_declared_name(self, new_name):
604
+ self.base.set_declared_name(new_name)
605
+
595
606
  def analyse_templates(self):
596
607
  return self.base.analyse_templates()
597
608
 
@@ -639,9 +650,10 @@ class CArrayDeclaratorNode(CDeclaratorNode):
639
650
  size = None
640
651
  if self.dimension:
641
652
  self.dimension = self.dimension.analyse_const_expression(env)
642
- if not self.dimension.type.is_int:
643
- error(self.dimension.pos, "Array dimension not integer")
644
- if self.dimension.type.is_const and self.dimension.entry.visibility != 'extern':
653
+ dimension_type = self.dimension.type
654
+ if not (dimension_type.is_int or dimension_type.is_enum):
655
+ error(self.dimension.pos, f"Array dimension not integer, got '{dimension_type}'")
656
+ if dimension_type.is_const and self.dimension.entry.visibility != 'extern':
645
657
  # extern const variables declaring C constants are allowed
646
658
  error(self.dimension.pos, "Array dimension cannot be const variable")
647
659
  size = (self.dimension.constant_result if isinstance(self.dimension.constant_result, int)
@@ -685,6 +697,9 @@ class CFuncDeclaratorNode(CDeclaratorNode):
685
697
  def declared_name(self):
686
698
  return self.base.declared_name()
687
699
 
700
+ def set_declared_name(self, new_name):
701
+ self.base.set_declared_name(new_name)
702
+
688
703
  def analyse_templates(self):
689
704
  if isinstance(self.base, CArrayDeclaratorNode):
690
705
  from .ExprNodes import TupleNode, NameNode
@@ -907,16 +922,20 @@ class CFuncDeclaratorNode(CDeclaratorNode):
907
922
  func_type.op_arg_struct = PyrexTypes.c_ptr_type(op_args_struct.type)
908
923
 
909
924
 
910
- class CConstDeclaratorNode(CDeclaratorNode):
925
+ class CQualifierDeclaratorNode(CDeclaratorNode):
911
926
  # base CDeclaratorNode
927
+ # is_const boolean
928
+ # is_restrict boolean
912
929
 
913
930
  child_attrs = ["base"]
914
931
 
915
932
  def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
933
+ if isinstance(self.base, CFuncDeclaratorNode) and self.is_restrict:
934
+ error(self.pos, "Restrict qualifier cannot be applied to function type")
916
935
  if base_type.is_pyobject:
917
936
  error(self.pos,
918
- "Const base type cannot be a Python object")
919
- const = PyrexTypes.c_const_type(base_type)
937
+ "Const/restrict base type cannot be a Python object")
938
+ const = PyrexTypes.c_qualifier_type(base_type, is_const=self.is_const, is_restrict=self.is_restrict)
920
939
  return self.base.analyse(const, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
921
940
 
922
941
 
@@ -937,6 +956,7 @@ class CArgDeclNode(Node):
937
956
  # is_dynamic boolean Non-literal arg stored inside CyFunction
938
957
  # pos_only boolean Is a positional-only argument
939
958
  # type_from_annotation boolean Was the type deduced from an annotation
959
+ # type_according_to_pyx PyrexType or None The type assigned by the pxd file
940
960
  #
941
961
  # name_cstring property that converts the name to a cstring taking care of unicode
942
962
  # and quoting it
@@ -960,6 +980,7 @@ class CArgDeclNode(Node):
960
980
  is_dynamic = 0
961
981
  defaults_class_key = None
962
982
  type_from_annotation = False
983
+ type_according_to_pxd = None
963
984
 
964
985
  def declared_name(self):
965
986
  return self.declarator.declared_name()
@@ -1026,7 +1047,14 @@ class CArgDeclNode(Node):
1026
1047
  arg_type = self.inject_type_from_annotations(env)
1027
1048
  if arg_type is not None:
1028
1049
  base_type = arg_type
1029
- return self.declarator.analyse(base_type, env, nonempty=nonempty)
1050
+ name, type_ = self.declarator.analyse(base_type, env, nonempty=nonempty)
1051
+ if type_ is None or type_ is py_object_type and self.type_according_to_pxd is not None:
1052
+ # Use an overridden type from the pxd if available.
1053
+ # If the type is resolved to something else, and contradicts
1054
+ # the type from the pxd this is likely an error (but generated elsewhere)
1055
+ type_ = self.type_according_to_pxd
1056
+ return name, type_
1057
+
1030
1058
 
1031
1059
  def inject_type_from_annotations(self, env):
1032
1060
  annotation = self.annotation
@@ -1481,10 +1509,11 @@ class FusedTypeNode(CBaseTypeNode):
1481
1509
  return PyrexTypes.FusedType(types, name=self.name)
1482
1510
 
1483
1511
 
1484
- class CConstOrVolatileTypeNode(CBaseTypeNode):
1512
+ class CQualifierTypeNode(CBaseTypeNode):
1485
1513
  # base_type CBaseTypeNode
1486
1514
  # is_const boolean
1487
1515
  # is_volatile boolean
1516
+ # is_restrict boolean
1488
1517
 
1489
1518
  child_attrs = ["base_type"]
1490
1519
 
@@ -1492,8 +1521,8 @@ class CConstOrVolatileTypeNode(CBaseTypeNode):
1492
1521
  base = self.base_type.analyse(env, could_be_name)
1493
1522
  if base.is_pyobject:
1494
1523
  error(self.pos,
1495
- "Const/volatile base type cannot be a Python object")
1496
- return PyrexTypes.c_const_or_volatile_type(base, self.is_const, self.is_volatile)
1524
+ "Const/volatile/restrict base type cannot be a Python object")
1525
+ return PyrexTypes.c_qualifier_type(base, self.is_const, self.is_volatile)
1497
1526
 
1498
1527
 
1499
1528
  class CVarDefNode(StatNode):
@@ -1600,7 +1629,11 @@ class CVarDefNode(StatNode):
1600
1629
  self.entry.create_wrapper = True
1601
1630
  else:
1602
1631
  if self.overridable:
1603
- error(self.pos, "Variables cannot be declared with 'cpdef'. Use 'cdef' instead.")
1632
+ if env.is_c_class_scope:
1633
+ error(self.pos,
1634
+ "Variables cannot be declared with 'cpdef'. Use 'cdef', 'cdef public' or 'cdef readonly' instead.")
1635
+ else:
1636
+ error(self.pos, "Variables cannot be declared with 'cpdef'. Use 'cdef' instead.")
1604
1637
  if self.directive_locals:
1605
1638
  error(self.pos, "Decorators can only be followed by functions")
1606
1639
  self.entry = dest_scope.declare_var(
@@ -1922,7 +1955,7 @@ class FuncDefNode(StatNode, BlockNode):
1922
1955
  # return_type PyrexType
1923
1956
  # #filename string C name of filename string const
1924
1957
  # entry Symtab.Entry
1925
- # needs_closure boolean Whether or not this function has inner functions/classes/yield
1958
+ # needs_closure FuncDefNode.NeedsClosure enum Whether or not this function has inner functions/classes/yield
1926
1959
  # needs_outer_scope boolean Whether or not this function requires outer scope
1927
1960
  # pymethdef_required boolean Force Python method struct generation
1928
1961
  # directive_locals { string : ExprNode } locals defined by cython.locals(...)
@@ -1937,8 +1970,13 @@ class FuncDefNode(StatNode, BlockNode):
1937
1970
  # by AnalyseDeclarationsTransform, so it can replace CFuncDefNodes
1938
1971
  # with fused argument types with a FusedCFuncDefNode
1939
1972
 
1973
+ class NeedsClosure(enum.IntEnum):
1974
+ NO_CLOSURE = 0
1975
+ GENERATOR_ONLY = 1
1976
+ FULL_CLOSURE = 2
1977
+
1940
1978
  py_func = None
1941
- needs_closure = False
1979
+ needs_closure = NeedsClosure.NO_CLOSURE
1942
1980
  needs_outer_scope = False
1943
1981
  pymethdef_required = False
1944
1982
  is_generator = False
@@ -2022,11 +2060,8 @@ class FuncDefNode(StatNode, BlockNode):
2022
2060
  lenv = cls(name=self.entry.name,
2023
2061
  outer_scope=genv,
2024
2062
  parent_scope=env,
2025
- scope_name=self.entry.cname)
2026
- # FIXME: why do GeneratorDefNode and GeneratorBodyDefNode use the same scope?
2027
- # This should hit the GeneratorBodyDefNode, not the GeneratorDefNode.
2028
- if self.is_generator_body or self.is_generator:
2029
- lenv.is_generator_scope = True
2063
+ scope_name=self.entry.cname,
2064
+ is_pure_generator_scope=self.needs_closure != self.NeedsClosure.FULL_CLOSURE)
2030
2065
  else:
2031
2066
  lenv = LocalScope(name=self.entry.name,
2032
2067
  outer_scope=genv,
@@ -3042,7 +3077,7 @@ class CFuncDefNode(FuncDefNode):
3042
3077
  if entry.in_closure and not arg.default:
3043
3078
  code.putln('%s = %s;' % (entry.cname, entry.original_cname))
3044
3079
  if entry.type.is_memoryviewslice:
3045
- entry.type.generate_incref_memoryviewslice(code, entry.cname, True)
3080
+ code.putln(entry.type.get_incref_memoryviewslice_code(entry.cname, True))
3046
3081
  else:
3047
3082
  code.put_var_incref(entry)
3048
3083
  code.put_var_giveref(entry)
@@ -3218,23 +3253,8 @@ class DefNode(FuncDefNode):
3218
3253
  nogil = nogil or with_gil
3219
3254
 
3220
3255
  if cfunc is None:
3221
- cfunc_args = []
3222
- for formal_arg in self.args:
3223
- name_declarator, type = formal_arg.analyse(scope, nonempty=1)
3224
- cfunc_args.append(PyrexTypes.CFuncTypeArg(name=name_declarator.name,
3225
- cname=None,
3226
- annotation=formal_arg.annotation,
3227
- type=py_object_type,
3228
- pos=formal_arg.pos))
3229
- cfunc_type = PyrexTypes.CFuncType(return_type=py_object_type,
3230
- args=cfunc_args,
3231
- has_varargs=False,
3232
- exception_value=None,
3233
- exception_check=exception_check,
3234
- nogil=nogil,
3235
- with_gil=with_gil,
3236
- is_overridable=overridable)
3237
- cfunc = CVarDefNode(self.pos, type=cfunc_type)
3256
+ cfunc_type = None
3257
+ cfunc = CVarDefNode(self.pos)
3238
3258
  else:
3239
3259
  if scope is None:
3240
3260
  scope = cfunc.scope
@@ -3248,40 +3268,49 @@ class DefNode(FuncDefNode):
3248
3268
  error(self.pos, "wrong number of arguments")
3249
3269
  error(cfunc.pos, "previous declaration here")
3250
3270
  for i, (formal_arg, type_arg) in enumerate(zip(self.args, cfunc_type.args)):
3251
- name_declarator, type = formal_arg.analyse(scope, nonempty=1,
3252
- is_self_arg=(i == 0 and scope.is_c_class_scope))
3253
- if type is None or type is PyrexTypes.py_object_type:
3254
- formal_arg.type = type_arg.type
3255
- formal_arg.name_declarator = name_declarator
3271
+ formal_arg.type_according_to_pxd = type_arg.type
3256
3272
 
3257
- if exception_value is None and cfunc_type.exception_value is not None:
3273
+ if exception_value is None and cfunc_type and cfunc_type.exception_value is not None:
3258
3274
  from .ExprNodes import ConstNode
3259
3275
  exception_value = ConstNode.for_type(
3260
3276
  self.pos, value=str(cfunc_type.exception_value), type=cfunc_type.return_type,
3261
3277
  constant_result=cfunc_type.exception_value.python_value)
3278
+
3279
+ if cfunc_type is not None:
3280
+ # If we have cfunc_type (i.e. it's come from a pxdfile)
3281
+ # we can fill in a lot more information than if we don't
3282
+ exception_check = cfunc_type.exception_check
3283
+ with_gil = cfunc_type.with_gil
3284
+ nogil = cfunc_type.nogil
3285
+ overridable = cfunc_type.is_overridable
3286
+ def_node_kwds = { 'type': cfunc_type }
3287
+ base_type = CAnalysedBaseTypeNode(self.pos, type=cfunc_type.return_type)
3288
+ else:
3289
+ def_node_kwds = {}
3290
+ base_type = CAnalysedBaseTypeNode(self.pos, type=py_object_type)
3262
3291
  declarator = CFuncDeclaratorNode(self.pos,
3263
3292
  base=CNameDeclaratorNode(self.pos, name=self.name, cname=None),
3264
3293
  args=self.args,
3265
3294
  has_varargs=False,
3266
- exception_check=cfunc_type.exception_check,
3295
+ exception_check=exception_check,
3267
3296
  exception_value=exception_value,
3268
3297
  has_explicit_exc_clause = has_explicit_exc_clause,
3269
- with_gil=cfunc_type.with_gil,
3270
- nogil=cfunc_type.nogil)
3298
+ with_gil=with_gil,
3299
+ nogil=nogil)
3271
3300
  return CFuncDefNode(self.pos,
3272
3301
  modifiers=modifiers or [],
3273
- base_type=CAnalysedBaseTypeNode(self.pos, type=cfunc_type.return_type),
3302
+ base_type = base_type,
3274
3303
  declarator=declarator,
3275
3304
  body=self.body,
3276
3305
  doc=self.doc,
3277
- overridable=cfunc_type.is_overridable,
3278
- type=cfunc_type,
3279
- with_gil=cfunc_type.with_gil,
3280
- nogil=cfunc_type.nogil,
3306
+ overridable=overridable,
3307
+ with_gil=with_gil,
3308
+ nogil=nogil,
3281
3309
  visibility='private',
3282
3310
  api=False,
3283
3311
  directive_locals=getattr(cfunc, 'directive_locals', {}),
3284
- directive_returns=returns)
3312
+ directive_returns=returns,
3313
+ **def_node_kwds)
3285
3314
 
3286
3315
  def is_cdef_func_compatible(self):
3287
3316
  """Determines if the function's signature is compatible with a
@@ -3348,6 +3377,10 @@ class DefNode(FuncDefNode):
3348
3377
  starstar_arg=self.starstar_arg,
3349
3378
  return_type=self.return_type)
3350
3379
  self.py_wrapper.analyse_declarations(env)
3380
+ if self.entry.is_special and self.entry.name in ("__cinit__", "__init__"):
3381
+ # Assume that star_arg makes vectorcall a waste of time
3382
+ # (but not starstar_arg because this is reasonably common just to sweep up arbitrary arguments)
3383
+ self.entry.tp_new_can_be_vectorcall = not self.star_arg
3351
3384
 
3352
3385
  def analyse_argument_types(self, env):
3353
3386
  self.directive_locals = env.directives.get('locals', {})
@@ -3386,6 +3419,9 @@ class DefNode(FuncDefNode):
3386
3419
  arg.accept_none = True
3387
3420
  elif arg.not_none:
3388
3421
  arg.accept_none = False
3422
+ if arg.default and arg.default.constant_result is None:
3423
+ error(arg.pos,
3424
+ "Parameter '%s' is declared 'not None' but has a default value of None" % arg.name)
3389
3425
  elif (arg.type.is_extension_type or arg.type.is_builtin_type
3390
3426
  or arg.type.is_buffer or arg.type.is_memoryviewslice):
3391
3427
  if arg.default and arg.default.constant_result is None:
@@ -3542,10 +3578,22 @@ class DefNode(FuncDefNode):
3542
3578
  warning(self.pos, "Overriding a c(p)def method with a def method. "
3543
3579
  "This can lead to different methods being called depending on the "
3544
3580
  "call context. Consider using a cpdef method for both.", 5)
3581
+
3545
3582
  entry = env.declare_pyfunction(name, self.pos, allow_redefine=not self.is_wrapper)
3546
3583
  self.entry = entry
3584
+
3585
+ if entry.is_special and name in ('__getitem__', '__setitem__', '__delitem__'):
3586
+ # We choose the more generic mapping protocol by default, but prefer the sequence
3587
+ # protocol here if the lookup key argument has a C integer type.
3588
+ if len(self.args) in (2, 3) and self.args[1].type.is_int:
3589
+ if PyrexTypes.c_py_ssize_t_type.rank > self.args[1].type.rank:
3590
+ warning(self.args[1].pos,
3591
+ f"Smaller index type '{self.args[1].type}' than 'Py_ssize_t' may get truncated in sequence protocol")
3592
+ entry.signature = TypeSlots.sequence_subscript_signatures[name]
3593
+
3547
3594
  prefix = env.next_id(env.scope_prefix)
3548
3595
  self.entry.pyfunc_cname = punycodify_name(Naming.pyfunc_prefix + prefix + name)
3596
+
3549
3597
  if Options.docstrings:
3550
3598
  entry.doc = embed_position(self.pos, self.doc)
3551
3599
  entry.doc_cname = punycodify_name(Naming.funcdoc_prefix + prefix + name)
@@ -3711,7 +3759,7 @@ class DefNode(FuncDefNode):
3711
3759
  if entry.type.is_memoryviewslice:
3712
3760
  # TODO - at some point reference count of memoryviews should
3713
3761
  # genuinely be unified with PyObjects
3714
- entry.type.generate_incref_memoryviewslice(code, entry.cname, True)
3762
+ code.putln(entry.type.get_incref_memoryviewslice_code(entry.cname, True))
3715
3763
  elif entry.xdecref_cleanup:
3716
3764
  # mostly applies to the starstar arg - this can sometimes be NULL
3717
3765
  # so must be xincrefed instead
@@ -3758,6 +3806,13 @@ class DefNodeWrapper(FuncDefNode):
3758
3806
  self.np_args_idx = self.target.np_args_idx
3759
3807
 
3760
3808
  def prepare_argument_coercion(self, env):
3809
+ target_entry = self.target.entry
3810
+ if (target_entry.is_special and target_entry.name in ("__cinit__", "__init__")
3811
+ and TypeSlots.TpVectorcallSlot("tp_vectorcall").slot_code(env) != "0"):
3812
+ # At this stage we know enough about both __cinit__, __init__ and the class scopes
3813
+ # to know if we should prefer vectorcall for class creation.
3814
+ self.signature = target_entry.signature = self.signature.with_fastcall(self.signature.FastcallUsed.TP_NEW)
3815
+
3761
3816
  # This is only really required for Cython utility code at this time,
3762
3817
  # everything else can be done during code generation. But we expand
3763
3818
  # all utility code here, simply because we cannot easily distinguish
@@ -3930,9 +3985,9 @@ class DefNodeWrapper(FuncDefNode):
3930
3985
  if sig.use_fastcall:
3931
3986
  fastcall_args = "PyObject *const *%s, Py_ssize_t %s, PyObject *%s" % (
3932
3987
  Naming.args_cname, Naming.nargs_cname, Naming.kwds_cname)
3988
+ fastcall_guard = sig.fastcall_guard
3933
3989
  arg_code_list.append(
3934
- "\n#if CYTHON_METH_FASTCALL\n%s\n#else\n%s\n#endif\n" % (
3935
- fastcall_args, varargs_args))
3990
+ f"\n#if {fastcall_guard}\n{fastcall_args}\n#else\n{varargs_args}\n#endif\n")
3936
3991
  else:
3937
3992
  arg_code_list.append(varargs_args)
3938
3993
  if entry.is_special:
@@ -4003,7 +4058,7 @@ class DefNodeWrapper(FuncDefNode):
4003
4058
  # error handling for this is checked after the declarations
4004
4059
  nargs_code = "CYTHON_UNUSED Py_ssize_t %s;" % Naming.nargs_cname
4005
4060
  if self.signature.use_fastcall:
4006
- code.putln("#if !CYTHON_METH_FASTCALL")
4061
+ code.putln(f"#if !{self.signature.fastcall_guard}")
4007
4062
  code.putln(nargs_code)
4008
4063
  code.putln("#endif")
4009
4064
  else:
@@ -4031,7 +4086,7 @@ class DefNodeWrapper(FuncDefNode):
4031
4086
  # Assign nargs variable as len(args).
4032
4087
  if self.signature_has_generic_args():
4033
4088
  if self.signature.use_fastcall:
4034
- code.putln("#if !CYTHON_METH_FASTCALL")
4089
+ code.putln(f"#if !{self.signature.fastcall_guard}")
4035
4090
  code.putln("#if CYTHON_ASSUME_SAFE_SIZE")
4036
4091
  code.putln("%s = PyTuple_GET_SIZE(%s);" % (
4037
4092
  Naming.nargs_cname, Naming.args_cname))
@@ -4128,7 +4183,7 @@ class DefNodeWrapper(FuncDefNode):
4128
4183
  code.globalstate.use_utility_code(
4129
4184
  UtilityCode.load_cached("KeywordStringCheck", "FunctionArguments.c"))
4130
4185
  code.putln(
4131
- f"if (unlikely(__Pyx_CheckKeywordStrings({function_name}, {Naming.kwds_cname}) == -1)) {goto_error}"
4186
+ f"if (unlikely(__Pyx_CheckKeywordStrings({Naming.kwds_cname}) == -1)) {goto_error}"
4132
4187
  )
4133
4188
 
4134
4189
  # If the **kwargs parameter is unused, we leave it NULL.
@@ -4437,7 +4492,7 @@ class DefNodeWrapper(FuncDefNode):
4437
4492
  def generate_arg_assignment(self, arg, item, code):
4438
4493
  if arg.type.is_pyobject:
4439
4494
  # Python default arguments were already stored in 'item' at the very beginning
4440
- if arg.type.is_builtin_type and arg.type.name in ('int', 'float'):
4495
+ if arg.type.is_pyint_type or arg.type.is_pyfloat_type:
4441
4496
  arg.type.convert_to_basetype(code, arg.pos, item, arg.accept_none, arg.name_cstring)
4442
4497
  if arg.is_generic:
4443
4498
  item = PyrexTypes.typecast(arg.type, PyrexTypes.py_object_type, item)
@@ -4719,7 +4774,7 @@ class GeneratorDefNode(DefNode):
4719
4774
  is_generator = True
4720
4775
  is_iterable_coroutine = False
4721
4776
  gen_type_name = 'Generator'
4722
- needs_closure = True
4777
+ needs_closure = FuncDefNode.NeedsClosure.GENERATOR_ONLY
4723
4778
 
4724
4779
  child_attrs = DefNode.child_attrs + ["gbody"]
4725
4780
 
@@ -4891,11 +4946,11 @@ class GeneratorBodyDefNode(DefNode):
4891
4946
  # ----- prepare target container for inlined comprehension
4892
4947
  if self.is_inlined and self.inlined_comprehension_type is not None:
4893
4948
  target_type = self.inlined_comprehension_type
4894
- if target_type is Builtin.list_type:
4949
+ if target_type.is_pylist_type:
4895
4950
  comp_init = 'PyList_New(0)'
4896
- elif target_type is Builtin.set_type:
4951
+ elif target_type.is_pyset_type:
4897
4952
  comp_init = 'PySet_New(NULL)'
4898
- elif target_type is Builtin.dict_type:
4953
+ elif target_type.is_pydict_type:
4899
4954
  comp_init = 'PyDict_New()'
4900
4955
  else:
4901
4956
  raise InternalError(
@@ -5534,8 +5589,7 @@ class CClassDefNode(ClassDefNode):
5534
5589
  base_type.is_final_type:
5535
5590
  error(base.pos, "Base class '%s' of type '%s' is final" % (
5536
5591
  base_type, self.class_name))
5537
- elif base_type.is_builtin_type and \
5538
- base_type.name in ('tuple', 'bytes'):
5592
+ elif base_type.is_pytuple_type or base_type.is_pybytes_type:
5539
5593
  error(base.pos, "inheritance from PyVarObject types like '%s' is not currently supported"
5540
5594
  % base_type.name)
5541
5595
  else:
@@ -5708,13 +5762,13 @@ class CClassDefNode(ClassDefNode):
5708
5762
  trial_type, first_base))
5709
5763
  # trial_type is a heaptype so GetSlot works in all versions of the limited API
5710
5764
  trial_type_base = "__Pyx_PyType_GetSlot((PyTypeObject*) %s, tp_base, PyTypeObject*)" % trial_type
5711
- code.putln("__Pyx_TypeName base_name = __Pyx_PyType_GetFullyQualifiedName(%s);" % trial_type_base)
5712
- code.putln("__Pyx_TypeName type_name = __Pyx_PyType_GetFullyQualifiedName(%s);" % first_base)
5713
- code.putln("PyErr_Format(PyExc_TypeError, "
5714
- "\"best base '\" __Pyx_FMT_TYPENAME \"' must be equal to first base '\" __Pyx_FMT_TYPENAME \"'\",")
5715
- code.putln(" base_name, type_name);")
5716
- code.putln("__Pyx_DECREF_TypeName(base_name);")
5717
- code.putln("__Pyx_DECREF_TypeName(type_name);")
5765
+
5766
+ code.globalstate.use_utility_code(
5767
+ UtilityCode.load_cached("RaiseErrorWithObjectTypes", "ObjectHandling.c"))
5768
+ code.putln('__Pyx_RaiseTypeErrorWithTypes('
5769
+ '"best base \'" __Pyx_FMT_TYPENAME "\' must be equal to first base \'" __Pyx_FMT_TYPENAME "\'",'
5770
+ f' {trial_type_base}, {first_base}'
5771
+ ');')
5718
5772
  code.putln(code.error_goto(self.pos))
5719
5773
  code.putln("}")
5720
5774
 
@@ -5776,9 +5830,9 @@ class CClassDefNode(ClassDefNode):
5776
5830
  if check_heap_type_bases:
5777
5831
  code.globalstate.use_utility_code(
5778
5832
  UtilityCode.load_cached('ValidateBasesTuple', 'ExtensionTypes.c'))
5779
- code.put_error_if_neg(entry.pos, "__Pyx_validate_bases_tuple(%s.name, %s, %s)" % (
5833
+ code.put_error_if_neg(entry.pos, "__Pyx_validate_bases_tuple(%s.name, %d, %s)" % (
5780
5834
  typespec_cname,
5781
- TypeSlots.get_slot_by_name("tp_dictoffset", scope.directives).slot_code(scope),
5835
+ TypeSlots.get_slot_by_name("tp_dictoffset", scope.directives).slot_code(scope) != "0",
5782
5836
  bases_tuple_cname or tuple_temp,
5783
5837
  ))
5784
5838
 
@@ -5835,11 +5889,6 @@ class CClassDefNode(ClassDefNode):
5835
5889
  code.putln("#warning \"The buffer protocol is not supported in the Limited C-API < 3.11.\"")
5836
5890
  code.putln("#endif")
5837
5891
 
5838
- code.globalstate.use_utility_code(
5839
- UtilityCode.load_cached("FixUpExtensionType", "ExtensionTypes.c"))
5840
- code.put_error_if_neg(entry.pos, "__Pyx_fix_up_extension_type_from_spec(&%s, %s)" % (
5841
- typespec_cname, typeptr_cname))
5842
-
5843
5892
  code.putln("#else")
5844
5893
  if bases_tuple_cname:
5845
5894
  code.put_incref(bases_tuple_cname, py_object_type)
@@ -5868,6 +5917,11 @@ class CClassDefNode(ClassDefNode):
5868
5917
  break
5869
5918
  base_type = base_type.base_type
5870
5919
 
5920
+ if type.has_sequence_flag or type.has_mapping_flag:
5921
+ code.globalstate.use_utility_code(
5922
+ UtilityCode.load_cached("ApplySequenceOrMappingFlag", "ExtensionTypes.c"))
5923
+ code.put_error_if_neg(
5924
+ entry.pos, f"__Pyx_ApplySequenceOrMappingFlag({typeptr_cname}, {type.has_sequence_flag:d})")
5871
5925
  code.putln("#if !CYTHON_COMPILING_IN_LIMITED_API")
5872
5926
  # FIXME: these still need to get initialised even with the limited-API
5873
5927
  for slot in TypeSlots.get_slot_table(code.globalstate.directives):
@@ -5915,7 +5969,7 @@ class CClassDefNode(ClassDefNode):
5915
5969
  func.name,
5916
5970
  code.error_goto_if_null('wrapper', entry.pos)))
5917
5971
  code.putln(
5918
- "if (__Pyx_IS_TYPE(wrapper, &PyWrapperDescr_Type)) {")
5972
+ "if (Py_IS_TYPE(wrapper, &PyWrapperDescr_Type)) {")
5919
5973
  code.putln(
5920
5974
  "%s = *((PyWrapperDescrObject *)wrapper)->d_base;" % (
5921
5975
  func.wrapperbase_cname))
@@ -6023,17 +6077,37 @@ class CPropertyNode(StatNode):
6023
6077
  is_cproperty = True
6024
6078
 
6025
6079
  @property
6026
- def cfunc(self):
6080
+ def getter_cfunc(self):
6081
+ stats = self.body.stats
6082
+ assert stats
6083
+ for stat in stats:
6084
+ if stat.declared_name() == "__get__":
6085
+ assert isinstance(stat, CFuncDefNode), stat
6086
+ return stat
6087
+ assert False, stats # we should have a getter
6088
+
6089
+ @property
6090
+ def setter_cfunc(self):
6027
6091
  stats = self.body.stats
6028
- assert stats and isinstance(stats[0], CFuncDefNode), stats
6029
- return stats[0]
6092
+ assert stats
6093
+ for stat in stats:
6094
+ if stat.declared_name() == "__set__":
6095
+ assert isinstance(stat, CFuncDefNode), stat
6096
+ return stat
6097
+ return None # we may not have a setter
6030
6098
 
6031
6099
  def analyse_declarations(self, env):
6032
6100
  scope = PropertyScope(self.name, class_scope=env)
6033
6101
  self.body.analyse_declarations(scope)
6102
+ getter = self.getter_cfunc
6034
6103
  entry = self.entry = env.declare_property(
6035
- self.name, self.doc, self.pos, ctype=self.cfunc.return_type, property_scope=scope)
6036
- entry.getter_cname = self.cfunc.entry.cname
6104
+ self.name, self.doc, self.pos, ctype=getter.return_type, property_scope=scope)
6105
+ entry.getter_cname = getter.entry.cname
6106
+ setter = self.setter_cfunc
6107
+ if setter:
6108
+ entry = self.entry = env.declare_property(
6109
+ self.name, self.doc, self.pos, ctype=setter.return_type, property_scope=scope)
6110
+ entry.setter_cname = setter.entry.cname
6037
6111
 
6038
6112
  def analyse_expressions(self, env):
6039
6113
  self.body = self.body.analyse_expressions(env)
@@ -6307,8 +6381,13 @@ class SingleAssignmentNode(AssignmentNode):
6307
6381
  self.rhs = self.rhs.analyse_types(env)
6308
6382
 
6309
6383
  if self.lhs.is_name and self.lhs.entry.type.is_const:
6310
- if env.is_module_scope and self.lhs.entry.init is None and self.rhs.has_constant_result():
6311
- self.lhs.entry.init = self.rhs.constant_result
6384
+ if self.lhs.entry.type.is_array:
6385
+ error(self.pos, f"Assignment to const array '{self.lhs.name}'. Assign to a pointer variable instead.")
6386
+ elif env.is_module_scope and self.lhs.entry.init is None and self.rhs.has_constant_result():
6387
+ if isinstance(self.rhs.constant_result, (list, tuple, set, dict, frozenset)):
6388
+ error(self.pos, f"Non-const assignment to const '{self.lhs.name}'")
6389
+ else:
6390
+ self.lhs.entry.init = self.rhs.constant_result
6312
6391
  else:
6313
6392
  error(self.pos, f"Assignment to const '{self.lhs.name}'")
6314
6393
 
@@ -6342,6 +6421,11 @@ class SingleAssignmentNode(AssignmentNode):
6342
6421
  env.use_utility_code(UtilityCode.load_cached("CppExceptionConversion", "CppSupport.cpp"))
6343
6422
  else:
6344
6423
  rhs = self.rhs.coerce_to(self.lhs.type, env)
6424
+ elif (self.lhs.type.supports_container_type and
6425
+ self.rhs.type.supports_container_type and
6426
+ not self.lhs.type.assignable_from(self.rhs.type)):
6427
+ rhs = self.rhs
6428
+ rhs.fail_assignment(self.lhs.type)
6345
6429
  else:
6346
6430
  rhs = self.rhs.coerce_to(self.lhs.type, env)
6347
6431
 
@@ -6751,65 +6835,54 @@ class PrintStatNode(StatNode):
6751
6835
  # arg_tuple TupleNode
6752
6836
  # stream ExprNode or None (stdout)
6753
6837
  # append_newline boolean
6838
+ #
6839
+ # transformed into
6840
+ # print_function_call ExprStatNode
6754
6841
 
6755
- child_attrs = ["arg_tuple", "stream"]
6756
-
6757
- def analyse_expressions(self, env):
6758
- if self.stream:
6759
- stream = self.stream.analyse_expressions(env)
6760
- self.stream = stream.coerce_to_pyobject(env)
6761
- arg_tuple = self.arg_tuple.analyse_expressions(env)
6762
- self.arg_tuple = arg_tuple.coerce_to_pyobject(env)
6763
- env.use_utility_code(printing_utility_code)
6764
- if len(self.arg_tuple.args) == 1 and self.append_newline:
6765
- env.use_utility_code(printing_one_utility_code)
6766
- return self
6842
+ print_function_call = None
6767
6843
 
6768
- nogil_check = Node.gil_error
6769
- gil_message = "Python print statement"
6844
+ child_attrs = ["arg_tuple", "stream", "print_function_call"]
6770
6845
 
6771
- def generate_execution_code(self, code):
6772
- code.mark_pos(self.pos)
6773
- if self.stream:
6774
- self.stream.generate_evaluation_code(code)
6775
- stream_result = self.stream.py_result()
6776
- else:
6777
- stream_result = '0'
6778
- if len(self.arg_tuple.args) == 1 and self.append_newline:
6779
- arg = self.arg_tuple.args[0]
6780
- arg.generate_evaluation_code(code)
6846
+ def analyse_expressions(self, env):
6847
+ from .ExprNodes import (
6848
+ DictNode, UnicodeNode, SimpleCallNode, GeneralCallNode,
6849
+ NameNode, IdentifierStringNode
6850
+ )
6781
6851
 
6782
- code.putln(
6783
- "if (__Pyx_PrintOne(%s, %s) < 0) %s" % (
6784
- stream_result,
6785
- arg.py_result(),
6786
- code.error_goto(self.pos)))
6787
- arg.generate_disposal_code(code)
6788
- arg.free_temps(code)
6852
+ func = NameNode(
6853
+ self.pos,
6854
+ name="print",
6855
+ entry=env.builtin_scope().lookup_here("print")
6856
+ )
6857
+ if self.stream or not self.append_newline:
6858
+ key_value_pairs = []
6859
+ if self.stream:
6860
+ key_value_pairs.append((
6861
+ IdentifierStringNode(self.pos, value=EncodedString("file")),
6862
+ self.stream
6863
+ ))
6864
+ if not self.append_newline:
6865
+ key_value_pairs.append((
6866
+ IdentifierStringNode(self.pos, value=EncodedString("end")),
6867
+ UnicodeNode(self.pos, value=EncodedString(" "))
6868
+ ))
6869
+ kwargs = DictNode.from_pairs(self.pos, key_value_pairs)
6870
+ call = GeneralCallNode(
6871
+ self.pos,
6872
+ function=func, positional_args=self.arg_tuple,
6873
+ keyword_args=kwargs
6874
+ )
6789
6875
  else:
6790
- self.arg_tuple.generate_evaluation_code(code)
6791
- code.putln(
6792
- "if (__Pyx_Print(%s, %s, %d) < 0) %s" % (
6793
- stream_result,
6794
- self.arg_tuple.py_result(),
6795
- self.append_newline,
6796
- code.error_goto(self.pos)))
6797
- self.arg_tuple.generate_disposal_code(code)
6798
- self.arg_tuple.free_temps(code)
6799
-
6800
- if self.stream:
6801
- self.stream.generate_disposal_code(code)
6802
- self.stream.free_temps(code)
6803
-
6804
- def generate_function_definitions(self, env, code):
6805
- if self.stream:
6806
- self.stream.generate_function_definitions(env, code)
6807
- self.arg_tuple.generate_function_definitions(env, code)
6876
+ call = SimpleCallNode(
6877
+ self.pos,
6878
+ function=func, args=self.arg_tuple.args
6879
+ )
6880
+ self.print_function_call = ExprStatNode(self.pos, expr=call).analyse_expressions(env)
6881
+ self.stream = self.arg_tuple = None # unused from now on
6882
+ return self
6808
6883
 
6809
- def annotate(self, code):
6810
- if self.stream:
6811
- self.stream.annotate(code)
6812
- self.arg_tuple.annotate(code)
6884
+ def generate_execution_code(self, code):
6885
+ self.print_function_call.generate_execution_code(code)
6813
6886
 
6814
6887
 
6815
6888
  class ExecStatNode(StatNode):
@@ -6875,7 +6948,7 @@ class DelStatNode(StatNode):
6875
6948
  self.cpp_check(env)
6876
6949
  elif arg.type.is_cpp_class:
6877
6950
  error(arg.pos, "Deletion of non-heap C++ object")
6878
- elif arg.is_subscript and arg.base.type is Builtin.bytearray_type:
6951
+ elif arg.is_subscript and arg.base.type.is_pybytearray_type:
6879
6952
  pass # del ba[i]
6880
6953
  else:
6881
6954
  error(arg.pos, "Deletion of non-Python, non-C++ object")
@@ -6894,7 +6967,7 @@ class DelStatNode(StatNode):
6894
6967
  for arg in self.args:
6895
6968
  if (arg.type.is_pyobject or
6896
6969
  arg.type.is_memoryviewslice or
6897
- arg.is_subscript and arg.base.type is Builtin.bytearray_type):
6970
+ arg.is_subscript and arg.base.type.is_pybytearray_type):
6898
6971
  arg.generate_deletion_code(
6899
6972
  code, ignore_nonexisting=self.ignore_nonexisting)
6900
6973
  elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
@@ -7017,14 +7090,36 @@ class ReturnStatNode(StatNode):
7017
7090
  return
7018
7091
 
7019
7092
  value = self.value
7020
- if self.return_type.is_pyobject:
7021
- code.put_xdecref(Naming.retval_cname, self.return_type)
7093
+ if value:
7094
+ value.generate_evaluation_code(code)
7095
+
7096
+ if self.return_type.needs_refcounting:
7097
+ code.putln("{")
7098
+ code.putln(f"{self.return_type.declaration_code(Naming.quick_temp_cname)};")
7099
+
7100
+ if self.in_parallel:
7101
+ # If we have the GIL we can rely on it for locking (unless in freethreading).
7102
+ # Where we use a critical section, we do our best to keep the contents as
7103
+ # simple as possible.
7104
+ if code.funcstate.gil_owned:
7105
+ code.putln("#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING")
7106
+ code.putln_openmp(
7107
+ # For scalar types this could be omp atomic (at least on semi-recent versions
7108
+ # of OpenMP). However, MSVC doesn't look to support that.
7109
+ "#pragma omp critical(__pyx_returning)")
7110
+ if code.funcstate.gil_owned:
7111
+ code.putln("#endif")
7112
+ code.putln("{")
7113
+
7114
+ if self.return_type.needs_refcounting:
7115
+ # decref must come after assignment because it can trigger
7116
+ # arbitrary code execution (and thus release the GIL).
7117
+ code.putln(f"{Naming.quick_temp_cname} = {Naming.retval_cname};")
7022
7118
  if value and value.is_none:
7023
7119
  # Use specialised default handling for "return None".
7024
7120
  value = None
7025
7121
 
7026
7122
  if value:
7027
- value.generate_evaluation_code(code)
7028
7123
  if self.return_type.is_memoryviewslice:
7029
7124
  from . import MemoryView
7030
7125
  MemoryView.put_acquire_memoryviewslice(
@@ -7033,22 +7128,30 @@ class ReturnStatNode(StatNode):
7033
7128
  lhs_pos=value.pos,
7034
7129
  rhs=value,
7035
7130
  code=code,
7036
- have_gil=self.in_nogil_context)
7037
- value.generate_post_assignment_code(code)
7131
+ have_gil=code.funcstate.gil_owned)
7038
7132
  else:
7039
7133
  value.make_owned_reference(code)
7040
7134
  code.putln("%s = %s;" % (
7041
7135
  Naming.retval_cname,
7042
7136
  value.result_as(self.return_type)))
7043
- value.generate_post_assignment_code(code)
7044
- value.free_temps(code)
7045
7137
  else:
7046
7138
  if self.return_type.is_pyobject:
7047
7139
  code.put_init_to_py_none(Naming.retval_cname, self.return_type)
7048
7140
  elif self.return_type.is_returncode:
7049
7141
  self.put_return(code, self.return_type.default_value)
7050
7142
 
7051
- if code.globalstate.directives['profile'] or code.globalstate.directives['linetrace']:
7143
+ code.putln("}") # end of omp critical section
7144
+ if self.return_type.needs_refcounting:
7145
+ code.put_xdecref(
7146
+ Naming.quick_temp_cname, self.return_type, have_gil=code.funcstate.gil_owned)
7147
+ code.putln("}") # end of quick_temp scope
7148
+
7149
+ if value:
7150
+ value.generate_post_assignment_code(code)
7151
+ value.free_temps(code)
7152
+ if ( # for now, avoid thread-safety issues in parallel blocks by not tracing the return value.
7153
+ not self.in_parallel and
7154
+ (code.globalstate.directives['profile'] or code.globalstate.directives['linetrace'])):
7052
7155
  code.put_trace_return(
7053
7156
  Naming.retval_cname,
7054
7157
  self.pos,
@@ -7062,8 +7165,6 @@ class ReturnStatNode(StatNode):
7062
7165
  code.put_goto(code.return_label)
7063
7166
 
7064
7167
  def put_return(self, code, value):
7065
- if self.in_parallel:
7066
- code.putln_openmp("#pragma omp critical(__pyx_returning)")
7067
7168
  code.putln("%s = %s;" % (Naming.retval_cname, value))
7068
7169
 
7069
7170
  def generate_function_definitions(self, env, code):
@@ -7099,7 +7200,7 @@ class RaiseStatNode(StatNode):
7099
7200
  if self.exc_value:
7100
7201
  exc_value = self.exc_value.analyse_types(env)
7101
7202
  if self.wrap_tuple_value:
7102
- if exc_value.type is Builtin.tuple_type or not exc_value.type.is_builtin_type:
7203
+ if exc_value.type.is_pytuple_type or not exc_value.type.is_builtin_type:
7103
7204
  # prevent tuple values from being interpreted as argument value tuples
7104
7205
  from .ExprNodes import TupleNode
7105
7206
  exc_value = TupleNode(exc_value.pos, args=[exc_value.coerce_to_pyobject(env)], slow=True)
@@ -8682,8 +8783,7 @@ class TryFinallyStatNode(StatNode):
8682
8783
  code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
8683
8784
  for _ in range(2)])
8684
8785
  exc_filename_cname = code.funcstate.allocate_temp(
8685
- PyrexTypes.CPtrType(PyrexTypes.c_const_type(PyrexTypes.c_char_type)),
8686
- manage_ref=False)
8786
+ PyrexTypes.c_const_char_ptr_type, manage_ref=False)
8687
8787
  else:
8688
8788
  exc_lineno_cnames = exc_filename_cname = None
8689
8789
  exc_vars = tuple([
@@ -8874,11 +8974,14 @@ class GILStatNode(NogilTryFinallyStatNode):
8874
8974
  child_attrs = ["condition"] + NogilTryFinallyStatNode.child_attrs
8875
8975
  state_temp = None
8876
8976
  scope_gil_state_known = True
8977
+ internally_generated = False
8877
8978
 
8878
- def __init__(self, pos, state, body, condition=None):
8979
+ def __init__(self, pos, state, body, condition=None, internally_generated=False):
8879
8980
  self.state = state
8880
8981
  self.condition = condition
8881
8982
  self.create_state_temp_if_needed(pos, state, body)
8983
+ if internally_generated:
8984
+ self.internally_generated = internally_generated
8882
8985
  TryFinallyStatNode.__init__(
8883
8986
  self, pos,
8884
8987
  body=body,
@@ -9218,6 +9321,7 @@ utility_code_for_cimports = {
9218
9321
  # TODO: Consider a generic user-level mechanism for importing
9219
9322
  'cpython.array' : lambda options: UtilityCode.load_cached("ArrayAPI", "arrayarray.h"),
9220
9323
  'cpython.array.array' : lambda options: UtilityCode.load_cached("ArrayAPI", "arrayarray.h"),
9324
+ 'cpython.frozendict' : lambda options: UtilityCode.load_cached("PyFrozenDict", "Builtins.c"),
9221
9325
  'cython.view' : cython_view_utility_code,
9222
9326
  }
9223
9327
 
@@ -9687,10 +9791,14 @@ class ParallelStatNode(StatNode, ParallelNode):
9687
9791
  elif self.parent and not self.parent.is_prange:
9688
9792
  error(self.pos, "num_threads must be declared in the parent parallel section")
9689
9793
  elif (self.num_threads.type.is_int and
9690
- self.num_threads.is_literal and
9691
- self.num_threads.compile_time_value(env) <= 0):
9692
- error(self.pos, "argument to num_threads must be greater than 0")
9794
+ self.num_threads.is_literal):
9795
+ num_threads_compile_time = self.num_threads.compile_time_value(env)
9796
+ if num_threads_compile_time < 0:
9797
+ error(self.pos, "argument to num_threads must be greater than or equal to 0")
9798
+ elif num_threads_compile_time == 0:
9799
+ self.num_threads = None
9693
9800
 
9801
+ if self.num_threads is not None:
9694
9802
  if not self.num_threads.is_simple() or self.num_threads.type.is_pyobject:
9695
9803
  self.num_threads = self.num_threads.coerce_to(
9696
9804
  PyrexTypes.c_int_type, env).coerce_to_temp(env)
@@ -9829,7 +9937,10 @@ class ParallelStatNode(StatNode, ParallelNode):
9829
9937
  Write self.num_threads if set as the num_threads OpenMP directive
9830
9938
  """
9831
9939
  if self.num_threads is not None:
9832
- code.put(" num_threads(%s)" % self.evaluate_before_block(code, self.num_threads))
9940
+ num_threads_result = self.evaluate_before_block(code, self.num_threads)
9941
+ if not self.num_threads.is_literal:
9942
+ num_threads_result = f"{num_threads_result} != 0 ? {num_threads_result} : omp_get_max_threads()"
9943
+ code.put(f" num_threads({num_threads_result})")
9833
9944
 
9834
9945
 
9835
9946
  def declare_closure_privates(self, code):
@@ -9959,16 +10070,18 @@ class ParallelStatNode(StatNode, ParallelNode):
9959
10070
  begin_code = self.begin_of_parallel_block
9960
10071
  self.begin_of_parallel_block = None
9961
10072
 
9962
- if self.error_label_used:
10073
+ if self.error_label_used or self.acquire_gil:
9963
10074
  end_code = code
9964
10075
 
9965
10076
  begin_code.putln("#ifdef _OPENMP")
9966
10077
  begin_code.put_ensure_gil(declare_gilstate=True)
9967
- begin_code.putln("Py_BEGIN_ALLOW_THREADS")
10078
+ if not self.acquire_gil:
10079
+ begin_code.putln("Py_BEGIN_ALLOW_THREADS")
9968
10080
  begin_code.putln("#endif /* _OPENMP */")
9969
10081
 
9970
10082
  end_code.putln("#ifdef _OPENMP")
9971
- end_code.putln("Py_END_ALLOW_THREADS")
10083
+ if not self.acquire_gil:
10084
+ end_code.putln("Py_END_ALLOW_THREADS")
9972
10085
  end_code.putln("#else")
9973
10086
  end_code.put_safe("{\n")
9974
10087
  end_code.put_ensure_gil()
@@ -10231,6 +10344,7 @@ class ParallelWithBlockNode(ParallelStatNode):
10231
10344
 
10232
10345
  num_threads = None
10233
10346
  threading_condition = None
10347
+ acquire_gil = False
10234
10348
 
10235
10349
  def analyse_declarations(self, env):
10236
10350
  super().analyse_declarations(env)
@@ -10314,6 +10428,7 @@ class ParallelRangeNode(ParallelStatNode):
10314
10428
  is_prange = True
10315
10429
 
10316
10430
  nogil = None
10431
+ acquire_gil = False
10317
10432
  schedule = None
10318
10433
 
10319
10434
  valid_keyword_arguments = ['schedule', 'nogil', 'num_threads', 'chunksize', 'use_threads_if']
@@ -10567,7 +10682,8 @@ class ParallelRangeNode(ParallelStatNode):
10567
10682
  code.putln("#ifdef _OPENMP")
10568
10683
 
10569
10684
  if not self.is_parallel:
10570
- code.put("#pragma omp for")
10685
+ acquire_gil_deadlock_avoidance_point = code.insertion_point()
10686
+ code.put("#pragma omp for nowait")
10571
10687
  self.privatization_insertion_point = code.insertion_point()
10572
10688
  reduction_codepoint = self.parent.privatization_insertion_point
10573
10689
  else:
@@ -10590,7 +10706,15 @@ class ParallelRangeNode(ParallelStatNode):
10590
10706
  code.putln("#if 0")
10591
10707
  else:
10592
10708
  code.putln("#ifdef _OPENMP")
10593
- code.put("#pragma omp for")
10709
+ acquire_gil_deadlock_avoidance_point = code.insertion_point()
10710
+ code.put("#pragma omp for nowait")
10711
+
10712
+ if self.acquire_gil:
10713
+ # Any firstprivate creates a barrier at least on GCC (and thus
10714
+ # a deadlock if we're using the GIL). So at very least we need
10715
+ # a barrier starting the loop
10716
+ acquire_gil_deadlock_avoidance_point.putln(
10717
+ f"PyThreadState *{Naming.parallel_loop_threadstate} = PyEval_SaveThread();")
10594
10718
 
10595
10719
  for entry, op in sorted(self.privates.items()):
10596
10720
  # Don't declare the index variable as a reduction
@@ -10629,6 +10753,14 @@ class ParallelRangeNode(ParallelStatNode):
10629
10753
  # at least it doesn't spoil indentation
10630
10754
  code.begin_block()
10631
10755
 
10756
+ if self.acquire_gil:
10757
+ code.putln("#ifdef _OPENMP")
10758
+ code.putln(f"if ({Naming.parallel_loop_threadstate}) {{")
10759
+ code.putln(f"PyEval_RestoreThread({Naming.parallel_loop_threadstate});")
10760
+ code.putln(f"{Naming.parallel_loop_threadstate} = NULL;")
10761
+ code.putln("}")
10762
+ code.putln("#endif")
10763
+
10632
10764
  code.putln("%(target)s = (%(target_type)s)(%(start)s + %(step)s * %(i)s);" % fmt_dict)
10633
10765
 
10634
10766
  if self.is_parallel and not self.is_nested_prange:
@@ -10649,6 +10781,16 @@ class ParallelRangeNode(ParallelStatNode):
10649
10781
  code.end_block() # end guard around loop body
10650
10782
  code.end_block() # end for loop block
10651
10783
 
10784
+ if self.acquire_gil:
10785
+ code.putln("#ifdef _OPENMP")
10786
+ code.putln(f"if (!{Naming.parallel_loop_threadstate}) {{")
10787
+ code.putln(f"{Naming.parallel_loop_threadstate} = PyEval_SaveThread();")
10788
+ code.putln("}")
10789
+ # synchronization point for all loops at the end of the thread but without the GIL
10790
+ code.putln("#pragma omp barrier")
10791
+ code.putln(f"PyEval_RestoreThread({Naming.parallel_loop_threadstate});")
10792
+ code.putln("#endif")
10793
+
10652
10794
  if self.is_parallel:
10653
10795
  # Release the GIL and deallocate the thread state
10654
10796
  self.end_parallel_block(code)
@@ -10783,12 +10925,6 @@ else:
10783
10925
  #define unlikely(x) (x)
10784
10926
  """
10785
10927
 
10786
- #------------------------------------------------------------------------------------
10787
-
10788
- printing_utility_code = UtilityCode.load_cached("Print", "Printing.c")
10789
- printing_one_utility_code = UtilityCode.load_cached("PrintOne", "Printing.c")
10790
-
10791
- #------------------------------------------------------------------------------------
10792
10928
 
10793
10929
  # Exception raising code
10794
10930
  #