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/Code.py CHANGED
@@ -4,14 +4,18 @@
4
4
 
5
5
 
6
6
  import cython
7
- cython.declare(os=object, re=object, operator=object, textwrap=object,
7
+ cython.declare(hashlib=object, json=object, operator=object, os=object, re=object,
8
+ shutil=object, textwrap=object,
8
9
  Template=object, Naming=object, Options=object, StringEncoding=object,
9
10
  Utils=object, SourceDescriptor=object, StringIOTree=object,
10
11
  DebugFlags=object, defaultdict=object,
11
12
  closing=object, partial=object, wraps=object,
12
- zlib_compress=object, bz2_compress=object, lzma_compress=object, zstd_compress=object)
13
+ zlib_compress=object, bz2_compress=object, lzma_compress=object, zstd_compress=object,
14
+ lzss_compress=object,
15
+ )
13
16
 
14
17
  import hashlib
18
+ import json
15
19
  import operator
16
20
  import os
17
21
  import re
@@ -30,10 +34,11 @@ from . import StringEncoding
30
34
  from .. import Utils
31
35
  from .Scanning import SourceDescriptor
32
36
  from ..StringIOTree import StringIOTree
33
-
37
+ from ..LZSS import lzss_compress
34
38
 
35
39
  # Set up available compression algorithms for maximum compression.
36
40
  from zlib import compress as zlib_compress
41
+ zlib_compress = partial(zlib_compress, level=9)
37
42
  try:
38
43
  from bz2 import compress as bz2_compress
39
44
  except ImportError:
@@ -62,7 +67,9 @@ else:
62
67
 
63
68
  compression_algorithms = [
64
69
  # Note: order is important and defines values for "CYTHON_COMPRESS_STRINGS" !
65
- (1, 'zlib', partial(zlib_compress, level=9)),
70
+ # Later algorithms are excluded if prior ones beat them.
71
+ (90, 'lzss', lzss_compress), # default compression
72
+ (1, 'zlib', zlib_compress),
66
73
  (2, 'bz2', bz2_compress),
67
74
  (3, 'zstd', zstd_compress),
68
75
  # LZMA is difficult to configure for efficient output from C code
@@ -561,9 +568,9 @@ class UtilityCodeBase(AbstractUtilityCode):
561
568
  tag_name = tag_name.rstrip()
562
569
  tag_value = tag_value.strip()
563
570
 
564
- if tag_name not in ('requires', 'substitute', 'proto_block'):
571
+ if tag_name not in ('requires', 'substitute', 'proto_block', 'init_block'):
565
572
  raise RuntimeError(f"Found unknown tag name '{tag_name}' in utility section {name}.{type}")
566
- if not re.match(r'\S+$', tag_value):
573
+ if not re.match(r'\S+(\{[^\}]*\})?$', tag_value):
567
574
  raise RuntimeError(f"Found invalid tag value '{tag_value}' in utility section {name}.{type}")
568
575
 
569
576
  tags[tag_name].add(tag_value)
@@ -602,13 +609,24 @@ class UtilityCodeBase(AbstractUtilityCode):
602
609
  continue
603
610
  # only pass lists when we have to: most argument expect one value or None
604
611
  if name == 'requires':
605
- if orig_kwargs:
606
- values = [cls.load(dep, from_file, **orig_kwargs)
607
- for dep in sorted(values)]
608
- else:
609
- # dependencies are rarely unique, so use load_cached() when we can
610
- values = [cls.load_cached(dep, from_file)
611
- for dep in sorted(values)]
612
+ dependencies = []
613
+ for dep in sorted(values):
614
+ if '{' in dep:
615
+ # Avoid passing 'context' twice
616
+ kwargs_context = kwargs.pop('context', None)
617
+ assert kwargs_context is None
618
+
619
+ split_pos = dep.index('{')
620
+ tempita_context = json.loads(dep[split_pos:])
621
+ dependency = TempitaUtilityCode.load_cached(
622
+ dep[:split_pos], from_file, context=tempita_context, **kwargs)
623
+ elif orig_kwargs:
624
+ dependency = cls.load(dep, from_file, **orig_kwargs)
625
+ else:
626
+ # dependencies are rarely unique, so use load_cached() when we can
627
+ dependency = cls.load_cached(dep, from_file)
628
+ dependencies.append(dependency)
629
+ values = dependencies
612
630
  elif name == 'substitute':
613
631
  # don't want to pass "naming" or "tempita" to the constructor
614
632
  # since these will have been handled
@@ -719,6 +737,8 @@ class UtilityCode(UtilityCodeBase):
719
737
  requires utility code dependencies
720
738
  proto_block the place in the resulting file where the prototype should
721
739
  end up
740
+ init_block the place in the resulting file where the init function should
741
+ end up
722
742
  name name of the utility code (or None)
723
743
  file filename of the utility code file this utility was loaded
724
744
  from (or None)
@@ -729,7 +749,8 @@ class UtilityCode(UtilityCodeBase):
729
749
  def __init__(self, proto=None, impl=None, init=None, cleanup=None,
730
750
  module_state_decls=None, module_state_traverse=None,
731
751
  module_state_clear=None, requires=None,
732
- proto_block='utility_code_proto', name=None, file=None, export=None):
752
+ proto_block='utility_code_proto', init_block='init_globals',
753
+ name=None, file=None, export=None):
733
754
  # proto_block: Which code block to dump prototype in. See GlobalState.
734
755
  self.proto = proto
735
756
  self.impl = impl
@@ -742,6 +763,7 @@ class UtilityCode(UtilityCodeBase):
742
763
  self._cache = {}
743
764
  self.specialize_list = []
744
765
  self.proto_block = proto_block
766
+ self.init_block = init_block
745
767
  self.name = name
746
768
  self.file = file
747
769
  self.export = export
@@ -752,14 +774,15 @@ class UtilityCode(UtilityCodeBase):
752
774
  # cached for use in hash and eq
753
775
  self._parts_tuple = tuple(getattr(self, part, None) for part in self.code_parts)
754
776
 
755
- def parse_export_functions(self, export_proto: str) -> list:
777
+ def parse_export_functions(self, export_proto: str) -> list[SharedFunctionDecl]:
756
778
 
757
779
  assert '//' not in export_proto and '/*' not in export_proto and '*/' not in export_proto, \
758
780
  f'Export block must not contain comments:\n{export_proto.strip()}\n in file {self.file}'
759
781
 
760
782
  parsed_protos = []
761
783
  proto_regex=r'''
762
- ^static\s # `static` keyword
784
+ ^(?:CYTHON_UNUSED\s)?\s* # optional CYTHON_UNUSED macro
785
+ static\s # `static` keyword
763
786
  (?P<ret_type>[^;()]+[\s*]) # return type + modifier with optional * - e.g.: int *, float, const str *, ...
764
787
  (?P<func_name>\w+)\((?P<func_params>[^)]*)\)$ # function with params - e.g. foo(int, float, *PyObject)
765
788
  '''
@@ -828,6 +851,7 @@ class UtilityCode(UtilityCodeBase):
828
851
  self.none_or_sub(self.module_state_clear, data),
829
852
  requires,
830
853
  self.proto_block,
854
+ self.init_block,
831
855
  name,
832
856
  )
833
857
 
@@ -861,10 +885,10 @@ class UtilityCode(UtilityCodeBase):
861
885
  else:
862
886
  writer.put_multilines(code_string)
863
887
 
864
- def _put_init_code_section(self, output):
888
+ def _put_init_code_section(self, output, *, init_block="init_globals"):
865
889
  if not self.init:
866
890
  return
867
- writer = output['init_globals']
891
+ writer = output[init_block]
868
892
  self._put_code_section(writer, output, 'init')
869
893
  # 'init' code can end with an 'if' statement for an error condition like:
870
894
  # if (check_ok()) ; else
@@ -907,7 +931,7 @@ class UtilityCode(UtilityCodeBase):
907
931
  self._put_code_section(globalstate['module_state_clear_contents'], globalstate, 'module_state_clear')
908
932
 
909
933
  if self.init:
910
- self._put_init_code_section(globalstate)
934
+ self._put_init_code_section(globalstate, init_block=self.init_block)
911
935
 
912
936
 
913
937
  def add_macro_processor(*macro_names, regex=None, is_module_specific=False, _last_macro_processor = [None]):
@@ -971,9 +995,10 @@ def _format_impl_code(utility_code: UtilityCode, _, impl):
971
995
 
972
996
  @add_macro_processor(
973
997
  'CALL_UNBOUND_METHOD',
998
+ 'CALL_UNBOUND_METHOD_TYPEPTR',
974
999
  is_module_specific=True,
975
1000
  regex=(
976
- r'CALL_UNBOUND_METHOD\('
1001
+ r'CALL_UNBOUND_METHOD(_TYPEPTR)?\('
977
1002
  r'([a-zA-Z_]+),\s*' # type cname
978
1003
  r'"([^"]+)",\s*' # method name
979
1004
  r'([^),\s]+)' # object cname
@@ -984,10 +1009,11 @@ def _format_impl_code(utility_code: UtilityCode, _, impl):
984
1009
  def _inject_unbound_method(output, matchobj):
985
1010
  """Replace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
986
1011
  """
987
- type_cname, method_name, obj_cname, args = matchobj.groups()
988
- type_cname = '&%s' % type_cname
1012
+ is_typeptr, type_cname, method_name, obj_cname, args = matchobj.groups()
1013
+ type_cname = type_cname if is_typeptr else f'&{type_cname}'
989
1014
  args = [arg.strip() for arg in args[1:].split(',')] if args else []
990
- assert len(args) < 3, f"CALL_UNBOUND_METHOD() does not support {len(args):d} call arguments"
1015
+ assert len(args) < 3, \
1016
+ f"CALL_UNBOUND_METHOD{'_TYPEPTR' if is_typeptr else ''}() does not support {len(args):d} call arguments"
991
1017
  return output.cached_unbound_method_call_code(
992
1018
  f"{Naming.modulestateglobal_cname}->",
993
1019
  obj_cname, type_cname, method_name, args)
@@ -1032,6 +1058,8 @@ def _inject_cglobal(output, matchobj):
1032
1058
  is_named, name = matchobj.groups()
1033
1059
  if is_named:
1034
1060
  name = getattr(Naming, name)
1061
+ else:
1062
+ assert re.match(r'\w+', name), repr(name) # Detect simple typos.
1035
1063
  return f"{Naming.modulestateglobal_cname}->{name}"
1036
1064
 
1037
1065
 
@@ -1248,7 +1276,7 @@ class FunctionState:
1248
1276
 
1249
1277
  # temp handling
1250
1278
 
1251
- def allocate_temp(self, type, manage_ref, static=False, reusable=True):
1279
+ def allocate_temp(self, type, manage_ref: bool, static: bool = False, reusable: bool = True):
1252
1280
  """
1253
1281
  Allocates a temporary (which may create a new one or get a previously
1254
1282
  allocated and released one of the same type). Type is simply registered
@@ -1561,6 +1589,7 @@ class GlobalState:
1561
1589
  'init_constants',
1562
1590
  'init_codeobjects',
1563
1591
  'init_globals', # (utility code called at init-time)
1592
+ 'init_after_shared_utility',
1564
1593
  'cleanup_globals',
1565
1594
  'cleanup_module',
1566
1595
  'main_method',
@@ -1631,6 +1660,9 @@ class GlobalState:
1631
1660
  w = self.parts['init_globals']
1632
1661
  w.start_initcfunc("int __Pyx_InitGlobals(void)")
1633
1662
 
1663
+ w = self.parts['init_after_shared_utility']
1664
+ w.start_initcfunc("int __Pyx_InitAfterSharedUtility(void)")
1665
+
1634
1666
  w = self.parts['init_constants']
1635
1667
  w.start_initcfunc(
1636
1668
  "int __Pyx_InitConstants("
@@ -1719,7 +1751,7 @@ class GlobalState:
1719
1751
  w.putln("}")
1720
1752
  w.exit_cfunc_scope()
1721
1753
 
1722
- for part in ['init_globals', 'init_constants']:
1754
+ for part in ['init_globals', 'init_constants', 'init_after_shared_utility']:
1723
1755
  w = self.parts[part]
1724
1756
  w.putln("return 0;")
1725
1757
  if w.label_used(w.error_label):
@@ -1776,7 +1808,7 @@ class GlobalState:
1776
1808
  self.dedup_const_index[dedup_key] = const
1777
1809
  return const
1778
1810
 
1779
- def get_argument_default_const(self, type):
1811
+ def get_argument_default_const(self, type) -> PyObjectConst:
1780
1812
  cname = self.new_const_cname('')
1781
1813
  c = PyObjectConst(cname, type)
1782
1814
  self.arg_default_constants.append(c)
@@ -1991,6 +2023,8 @@ class GlobalState:
1991
2023
 
1992
2024
  decl = self.parts['module_state']
1993
2025
  init = self.parts['cached_builtins']
2026
+ traverse = self.parts['module_state_traverse']
2027
+ clear = self.parts['module_state_clear']
1994
2028
 
1995
2029
  init.putln("")
1996
2030
  init.putln("/* Cached unbound methods */")
@@ -2008,6 +2042,9 @@ class GlobalState:
2008
2042
  init.putln(
2009
2043
  f'{init.name_in_main_c_code_module_state(cname)}.method_name = '
2010
2044
  f'&{init.name_in_main_c_code_module_state(method_name_cname)};')
2045
+ # method is owned - Other PyObjects in __Pyx_CachedCFunction are borrowed.
2046
+ clear.putln(f'Py_CLEAR(clear_module_state->{cname}.method);')
2047
+ traverse.putln(f'Py_VISIT(traverse_module_state->{cname}.method);')
2011
2048
 
2012
2049
  if Options.generate_cleanup_code:
2013
2050
  cleanup = self.parts['cleanup_globals']
@@ -2015,17 +2052,19 @@ class GlobalState:
2015
2052
  cleanup.putln(f"Py_CLEAR({init.name_in_main_c_code_module_state(cname)}.method);")
2016
2053
 
2017
2054
  def generate_string_constants(self):
2018
- c_consts = []
2019
- py_bytes_consts = []
2020
- py_unicode_consts = []
2055
+ c_consts: list[tuple] = []
2056
+ py_bytes_consts: list[tuple] = []
2057
+ py_unicode_consts: list[tuple] = []
2021
2058
 
2022
2059
  # Split into buckets.
2023
- for _, _, c in sorted([(len(c.cname), c.cname, c) for c in self.string_const_index.values()]):
2024
- if c.c_used:
2025
- c_consts.append((len(c.cname), c.cname, c.escaped_value))
2026
- if c.py_strings:
2027
- for py_string in c.py_strings.values():
2028
- text = c.text
2060
+ sc: StringConst
2061
+ for _, _, sc in sorted([(len(sc.cname), sc.cname, sc) for sc in self.string_const_index.values()]):
2062
+ if sc.c_used:
2063
+ c_consts.append((len(sc.cname), sc.cname, sc.escaped_value))
2064
+ if sc.py_strings:
2065
+ py_string: PyStringConst
2066
+ for py_string in sc.py_strings.values():
2067
+ text = sc.text
2029
2068
  if py_string.is_unicode and not isinstance(text, str):
2030
2069
  text = StringEncoding.EncodedString(text.decode(py_string.encoding or 'UTF-8'))
2031
2070
 
@@ -2035,11 +2074,8 @@ class GlobalState:
2035
2074
  text,
2036
2075
  ))
2037
2076
 
2038
- c_consts.sort()
2039
- py_bytes_consts.sort()
2040
- py_unicode_consts.sort()
2041
-
2042
2077
  # Generate C string constants.
2078
+ c_consts.sort()
2043
2079
  decls_writer = self.parts['string_decls']
2044
2080
  for _, cname, escaped_value in c_consts:
2045
2081
  cliteral = StringEncoding.split_string_literal(escaped_value)
@@ -2067,7 +2103,7 @@ class GlobalState:
2067
2103
 
2068
2104
  self.generate_pystring_constants(py_unicode_consts, py_bytes_consts)
2069
2105
 
2070
- def generate_pystring_constants(self, text_strings: list, byte_strings: list):
2106
+ def generate_pystring_constants(self, text_strings: list[tuple], byte_strings: list[tuple]):
2071
2107
  # Concatenate all strings into one byte sequence and build a length index array.
2072
2108
  defines = self.parts['constant_name_defines']
2073
2109
 
@@ -2075,54 +2111,91 @@ class GlobalState:
2075
2111
  first_interned: cython.Py_ssize_t = -1
2076
2112
  stringtab_pos: cython.Py_ssize_t = 0
2077
2113
 
2078
- # For (Unicode) text strings, the index stores the character lengths after UTF8 decoding.
2079
- for i, (is_interned, cname, text) in enumerate(text_strings):
2114
+ # For (Unicode) text strings, the length index stores the byte lengths after UTF8 decoding.
2115
+ text_strings.sort(key=operator.itemgetter(0, 2))
2116
+ for is_interned, cname, text in text_strings:
2080
2117
  bytes_values.append(text.encode('utf-8'))
2081
- if first_interned == -1 and is_interned:
2082
- first_interned = i
2118
+ if first_interned == -1:
2119
+ if is_interned:
2120
+ first_interned = stringtab_pos
2121
+ else:
2122
+ assert is_interned, (
2123
+ f"All string entries after {first_interned} must be interned, but {stringtab_pos} is not: {text!r}")
2083
2124
  defines.putln(f"#define {cname} {Naming.stringtab_cname}[{stringtab_pos}]")
2084
2125
  stringtab_pos += 1
2085
2126
 
2127
+ str_index = list(map(len, bytes_values))
2128
+
2086
2129
  stringtab_bytes_start: cython.Py_ssize_t = len(text_strings)
2087
2130
 
2088
- # For bytes objects, the index stores the byte lengths, ignoring the initial Unicode string.
2089
- for _, cname, text in byte_strings:
2090
- bytes_values.append(text.byteencode() if text.encoding else text.utf8encode())
2131
+ # For bytes objects, the length index stores the encoded byte lengths.
2132
+ byte_strings = [
2133
+ ((text.byteencode() if text.encoding else text.utf8encode()), cname)
2134
+ for _, cname, text in byte_strings
2135
+ ]
2136
+ byte_strings.sort()
2137
+ for text, cname in byte_strings:
2138
+ bytes_values.append(text)
2091
2139
  defines.putln(f"#define {cname} {Naming.stringtab_cname}[{stringtab_pos}]")
2092
2140
  stringtab_pos += 1
2093
2141
 
2094
- index = list(map(len, bytes_values))
2142
+ bytes_index = list(map(len, bytes_values[stringtab_bytes_start:]))
2095
2143
  concat_bytes = b''.join(bytes_values)
2096
2144
 
2097
2145
  w = self.parts['init_constants']
2098
2146
  w.putln("{") # Start code block.
2099
2147
 
2100
2148
  # Store the index of string lengths.
2101
- w.putln(
2102
- "const struct { "
2103
- f"const unsigned int length: {max(index).bit_length()}; "
2104
- "} "
2105
- f"index[] = {{{','.join(['{%d}' % length for length in index])}}};",
2106
- )
2149
+ for stype, index in [('str', str_index), ('bytes', bytes_index)]:
2150
+ if not index:
2151
+ continue
2152
+ w.putln(
2153
+ "const struct { "
2154
+ f"const unsigned int length: {max(index).bit_length()}; "
2155
+ "} "
2156
+ f"{stype}_length_index[] = {{{','.join(['{%d}' % length for length in index])}}};",
2157
+ )
2107
2158
 
2108
2159
  # Store and decompress the string data.
2109
- self.use_utility_code(UtilityCode.load_cached("DecompressString", "StringTools.c"))
2110
2160
 
2111
- has_if = False
2112
- for algo_number, algo_name, compress in reversed(compression_algorithms):
2161
+ compressions = []
2162
+ default_compression = 0 # no compression
2163
+ min_size_seen = None
2164
+ for algo_number, algo_name, compress in compression_algorithms:
2113
2165
  if compress is None:
2114
2166
  continue
2167
+
2115
2168
  compressed_bytes = compress(concat_bytes)
2116
- if len(compressed_bytes) >= len(concat_bytes) - 10:
2169
+ compressed_size = len(compressed_bytes)
2170
+ # The decompression function adds its size, so be conservative about the gains.
2171
+ if compressed_size > len(concat_bytes) - 200:
2172
+ continue
2173
+
2174
+ if algo_number == 90:
2175
+ default_compression = 90
2176
+
2177
+ if min_size_seen is None or compressed_size < min_size_seen:
2178
+ min_size_seen = compressed_size
2179
+ elif algo_number != 90:
2180
+ # Avoid less widely used algorithms if they don't beat more common ones
2181
+ # on the data at hand, including the default compression.
2117
2182
  continue
2118
2183
 
2119
- if algo_name == 'zlib':
2120
- # Use zlib as fallback if the selected compression module is not available.
2121
- assert algo_number == 1, f"Compression algorithm no. 1 must be 'zlib' to be used as fallback."
2122
- guard = "(CYTHON_COMPRESS_STRINGS) != 0"
2123
- elif algo_name == 'zstd':
2184
+ compressions.append((algo_number, algo_name, compressed_bytes))
2185
+
2186
+ if compressions:
2187
+ w.putln("#ifndef CYTHON_COMPRESS_STRINGS")
2188
+ w.putln(f" #define CYTHON_COMPRESS_STRINGS {default_compression}")
2189
+ w.putln("#endif")
2190
+
2191
+ has_if = False
2192
+ for algo_number, algo_name, compressed_bytes in reversed(compressions):
2193
+ if algo_name == 'zstd':
2124
2194
  # 'compression.zstd' was added in Python 3.14.
2125
2195
  guard = f"(CYTHON_COMPRESS_STRINGS) == {algo_number} && __PYX_LIMITED_VERSION_HEX >= 0x030e0000"
2196
+ elif algo_name == 'lzss':
2197
+ # We use this as default if compression is requested but the selected compression isn't available.
2198
+ guard = f"(CYTHON_COMPRESS_STRINGS) > 0 && (CYTHON_COMPRESS_STRINGS) <= {algo_number}"
2126
2199
  else:
2127
2200
  guard = f"(CYTHON_COMPRESS_STRINGS) == {algo_number}"
2128
2201
 
@@ -2131,7 +2204,15 @@ class GlobalState:
2131
2204
  escaped_bytes = StringEncoding.split_string_literal(
2132
2205
  StringEncoding.escape_byte_string(compressed_bytes))
2133
2206
  w.putln(f'const char* const cstring = "{escaped_bytes}";', safe=True)
2134
- w.putln(f'PyObject *data = __Pyx_DecompressString(cstring, {len(compressed_bytes)}, {algo_number});')
2207
+ if algo_name == 'lzss':
2208
+ self.use_utility_code(UtilityCode.load_cached("DecompressString_LZSS", "StringTools.c"))
2209
+ w.putln(f'PyObject *data = __Pyx_DecompressString_LZSS(cstring, {len(compressed_bytes)}, {len(concat_bytes)});')
2210
+ w.putln("#define __Pyx_DecompressString_UNUSED")
2211
+ else:
2212
+ self.use_utility_code(UtilityCode.load_cached("DecompressString", "StringTools.c"))
2213
+ w.putln(f'PyObject *data = __Pyx_DecompressString(cstring, {len(compressed_bytes)}, {algo_number});')
2214
+ w.putln("#define __Pyx_DecompressString_LZSS_UNUSED")
2215
+
2135
2216
  w.putln(w.error_goto_if_null('data', self.module_pos))
2136
2217
 
2137
2218
  w.putln('const char* const bytes = __Pyx_PyBytes_AsString(data);')
@@ -2139,13 +2220,16 @@ class GlobalState:
2139
2220
  w.putln(f'if (likely(bytes)); else {{ Py_DECREF(data); {w.error_goto(self.module_pos)} }}')
2140
2221
  w.putln('#endif')
2141
2222
 
2142
- if has_if:
2143
- w.putln(f"#else /* compression: none ({len(concat_bytes)} bytes) */")
2223
+ w.putln(f"{'#else ' if has_if else ''}/* compression: none ({len(concat_bytes)} bytes) */")
2144
2224
  escaped_bytes = StringEncoding.split_string_literal(
2145
2225
  StringEncoding.escape_byte_string(concat_bytes))
2146
2226
  w.putln(f'const char* const bytes = "{escaped_bytes}";', safe=True)
2147
2227
  w.putln('PyObject *data = NULL;') # Always allow xdecref below.
2148
- w.putln("CYTHON_UNUSED_VAR(__Pyx_DecompressString);")
2228
+
2229
+ if compressions:
2230
+ w.putln("#define __Pyx_DecompressString_UNUSED")
2231
+ w.putln("#define __Pyx_DecompressString_LZSS_UNUSED")
2232
+
2149
2233
  if has_if:
2150
2234
  w.putln("#endif")
2151
2235
 
@@ -2162,7 +2246,7 @@ class GlobalState:
2162
2246
  # because it must copy Unicode slices between different character sizes.
2163
2247
  # We avoid this by repeatedly calling PyUnicode_DecodeUTF8() for each substring.
2164
2248
  w.putln(f"for ({'int' if stringtab_bytes_start < 2**15 else 'Py_ssize_t'} i = 0; i < {stringtab_bytes_start}; i++) {{")
2165
- w.putln("Py_ssize_t bytes_length = index[i].length;")
2249
+ w.putln("Py_ssize_t bytes_length = str_length_index[i].length;")
2166
2250
 
2167
2251
  w.putln("PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL);")
2168
2252
  if first_interned >= 0:
@@ -2177,9 +2261,9 @@ class GlobalState:
2177
2261
  w.putln("}") # for()
2178
2262
 
2179
2263
  # Unpack byte strings.
2180
- if stringtab_bytes_start < len(index):
2181
- w.putln(f"for ({'int' if len(index) < 2**15 else 'Py_ssize_t'} i = {stringtab_bytes_start}; i < {len(index)}; i++) {{")
2182
- w.putln("Py_ssize_t bytes_length = index[i].length;")
2264
+ if stringtab_bytes_start < len(bytes_values):
2265
+ w.putln(f"for ({'int' if len(bytes_values) < 2**15 else 'Py_ssize_t'} i = {stringtab_bytes_start}; i < {len(bytes_values)}; i++) {{")
2266
+ w.putln(f"Py_ssize_t bytes_length = bytes_length_index[i-{stringtab_bytes_start}].length;")
2183
2267
 
2184
2268
  w.putln("PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length);")
2185
2269
  w.putln("stringtab[i] = string;")
@@ -2195,7 +2279,7 @@ class GlobalState:
2195
2279
  w.putln("Py_XDECREF(data);")
2196
2280
 
2197
2281
  # Set up hash values.
2198
- w.putln(f"for (Py_ssize_t i = 0; i < {len(index)}; i++) {{")
2282
+ w.putln(f"for (Py_ssize_t i = 0; i < {len(bytes_values)}; i++) {{")
2199
2283
  w.putln("if (unlikely(PyObject_Hash(stringtab[i]) == -1)) {")
2200
2284
  w.putln(w.error_goto(self.module_pos))
2201
2285
  w.putln('}')
@@ -2204,8 +2288,8 @@ class GlobalState:
2204
2288
  # Unicode strings are not trivially immortal but require certain rules.
2205
2289
  # See https://github.com/python/cpython/blob/920de7ccdcfa7284b6d23a124771b17c66dd3e4f/Objects/unicodeobject.c#L713-L739
2206
2290
  # But we can make bytes strings immortal.
2207
- if stringtab_bytes_start < len(index):
2208
- self.immortalize_constants(f"stringtab + {stringtab_bytes_start}", len(index) - stringtab_bytes_start, w)
2291
+ if stringtab_bytes_start < len(bytes_values):
2292
+ self.immortalize_constants(f"stringtab + {stringtab_bytes_start}", len(bytes_values) - stringtab_bytes_start, w)
2209
2293
 
2210
2294
  w.putln("}") # close block
2211
2295
 
@@ -2240,6 +2324,9 @@ class GlobalState:
2240
2324
  max_line = max(max_line, def_node.pos[1])
2241
2325
 
2242
2326
  w.put(textwrap.dedent(f"""\
2327
+ #ifdef __cplusplus
2328
+ namespace {{
2329
+ #endif
2243
2330
  typedef struct {{
2244
2331
  unsigned int argcount : {max_func_args.bit_length()};
2245
2332
  unsigned int num_posonly_args : {max_posonly_args.bit_length()};
@@ -2248,6 +2335,9 @@ class GlobalState:
2248
2335
  unsigned int flags : {max_flags.bit_length()};
2249
2336
  unsigned int first_line : {max_line.bit_length()};
2250
2337
  }} __Pyx_PyCode_New_function_description;
2338
+ #ifdef __cplusplus
2339
+ }} /* anonymous namespace */
2340
+ #endif
2251
2341
  """))
2252
2342
 
2253
2343
  self.use_utility_code(UtilityCode.load_cached("NewCodeObj", "ModuleSetupCode.c"))
@@ -2315,8 +2405,7 @@ class GlobalState:
2315
2405
  w = self.parts['init_constants']
2316
2406
  defines = self.parts['constant_name_defines']
2317
2407
 
2318
- def store_array(w, name: str, ctype: str, constants: list):
2319
- c: tuple
2408
+ def store_array(w, name: str, ctype: str, constants: list[tuple]):
2320
2409
  values = ','.join([c[1] for c in constants])
2321
2410
  w.putln(f"{ctype} const {name}[] = {{{values}}};")
2322
2411
 
@@ -2746,16 +2835,24 @@ class CCodeWriter:
2746
2835
  if refnanny:
2747
2836
  self.put_declare_refcount_context()
2748
2837
 
2749
- def start_slotfunc(self, class_scope, return_type, c_slot_name, args_signature, needs_funcstate=True, needs_prototype=False):
2838
+ def start_slotfunc(self, class_scope, return_type, c_slot_name, args_signature,
2839
+ needs_funcstate=True, needs_prototype=False,
2840
+ guard=None):
2750
2841
  # Slot functions currently live in the class scope as they don't have direct access to the module state.
2751
2842
  slotfunc_cname = class_scope.mangle_internal(c_slot_name)
2752
2843
  declaration = f"static {return_type.declaration_code(slotfunc_cname)}({args_signature})"
2753
2844
 
2754
2845
  if needs_prototype:
2846
+ if guard:
2847
+ self.globalstate['decls'].putln(f"#if {guard}")
2755
2848
  self.globalstate['decls'].putln(declaration.replace("CYTHON_UNUSED ", "") + "; /*proto*/")
2849
+ if guard:
2850
+ self.globalstate['decls'].putln("#endif")
2756
2851
  if needs_funcstate:
2757
2852
  self.enter_cfunc_scope(class_scope)
2758
2853
  self.putln("")
2854
+ if guard:
2855
+ self.putln(f"#if {guard}")
2759
2856
  self.putln(declaration + " {")
2760
2857
 
2761
2858
  # constant handling
@@ -2872,14 +2969,14 @@ class CCodeWriter:
2872
2969
  self.write_trace_line(pos)
2873
2970
 
2874
2971
  @cython.final
2875
- def write_trace_line(self, pos):
2972
+ def write_trace_line(self, pos: tuple):
2876
2973
  if self.funcstate and self.funcstate.can_trace and self.globalstate.directives['linetrace']:
2877
2974
  self.indent()
2878
2975
  self._write_lines(
2879
2976
  f'__Pyx_TraceLine({pos[1]:d},{self.pos_to_offset(pos):d},{not self.funcstate.gil_owned:d},{self.error_goto(pos)})\n')
2880
2977
 
2881
2978
  @cython.final
2882
- def _build_marker(self, pos):
2979
+ def _build_marker(self, pos: tuple):
2883
2980
  source_desc, line, col = pos
2884
2981
  assert isinstance(source_desc, SourceDescriptor)
2885
2982
  contents = self.globalstate.commented_file_contents(source_desc)
@@ -3077,50 +3174,72 @@ class CCodeWriter:
3077
3174
  from .PyrexTypes import py_object_type, typecast
3078
3175
  return typecast(py_object_type, type, cname)
3079
3176
 
3177
+ def handle_refnanny(self, tp, nanny=True):
3178
+ if tp.supports_refnanny and nanny:
3179
+ self.funcstate.needs_refnanny = True
3180
+
3080
3181
  def put_gotref(self, cname, type):
3081
- type.generate_gotref(self, cname)
3182
+ self.handle_refnanny(type)
3183
+ self.putln(type.get_gotref_code(cname))
3082
3184
 
3083
3185
  def put_giveref(self, cname, type):
3084
- type.generate_giveref(self, cname)
3186
+ self.handle_refnanny(type)
3187
+ self.putln(type.get_giveref_code(cname))
3085
3188
 
3086
3189
  def put_xgiveref(self, cname, type):
3087
- type.generate_xgiveref(self, cname)
3190
+ self.handle_refnanny(type)
3191
+ self.putln(type.get_xgiveref_code(cname))
3088
3192
 
3089
3193
  def put_xgotref(self, cname, type):
3090
- type.generate_xgotref(self, cname)
3194
+ self.handle_refnanny(type)
3195
+ self.putln(type.get_xgotref_code(cname))
3091
3196
 
3092
3197
  def put_incref(self, cname, type, nanny=True):
3093
3198
  # Note: original put_Memslice_Incref/Decref also added in some utility code
3094
3199
  # this is unnecessary since the relevant utility code is loaded anyway if a memoryview is used
3095
3200
  # and so has been removed. However, it's potentially a feature that might be useful here
3096
- type.generate_incref(self, cname, nanny=nanny)
3201
+ if nanny:
3202
+ self.handle_refnanny(type)
3203
+ self.putln(type.get_incref_code(cname, nanny=nanny))
3097
3204
 
3098
3205
  def put_xincref(self, cname, type, nanny=True):
3099
- type.generate_xincref(self, cname, nanny=nanny)
3206
+ if nanny:
3207
+ self.handle_refnanny(type)
3208
+ self.putln(type.get_xincref_code(cname, nanny=nanny))
3100
3209
 
3101
3210
  def put_decref(self, cname, type, nanny=True, have_gil=True):
3102
- type.generate_decref(self, cname, nanny=nanny, have_gil=have_gil)
3211
+ if nanny:
3212
+ self.handle_refnanny(type)
3213
+ self.putln(type.get_decref_code(cname, nanny=nanny, have_gil=have_gil))
3103
3214
 
3104
3215
  def put_xdecref(self, cname, type, nanny=True, have_gil=True):
3105
- type.generate_xdecref(self, cname, nanny=nanny, have_gil=have_gil)
3216
+ if nanny:
3217
+ self.handle_refnanny(type)
3218
+ self.putln(type.get_xdecref_code(cname, nanny=nanny, have_gil=have_gil))
3106
3219
 
3107
3220
  def put_decref_clear(self, cname, type, clear_before_decref=False, nanny=True, have_gil=True):
3108
- type.generate_decref_clear(self, cname, clear_before_decref=clear_before_decref,
3109
- nanny=nanny, have_gil=have_gil)
3221
+ if nanny:
3222
+ self.handle_refnanny(type)
3223
+ self.putln(type.get_decref_clear_code(
3224
+ cname, clear_before_decref=clear_before_decref, nanny=nanny, have_gil=have_gil))
3110
3225
 
3111
3226
  def put_xdecref_clear(self, cname, type, clear_before_decref=False, nanny=True, have_gil=True):
3112
- type.generate_xdecref_clear(self, cname, clear_before_decref=clear_before_decref,
3113
- nanny=nanny, have_gil=have_gil)
3227
+ if nanny:
3228
+ self.handle_refnanny(type)
3229
+ self.putln(type.get_xdecref_clear_code(
3230
+ cname, clear_before_decref=clear_before_decref, nanny=nanny, have_gil=have_gil))
3114
3231
 
3115
3232
  def put_decref_set(self, cname, type, rhs_cname):
3116
- type.generate_decref_set(self, cname, rhs_cname)
3233
+ self.handle_refnanny(type)
3234
+ self.putln(type.get_decref_set_code(cname, rhs_cname))
3117
3235
 
3118
3236
  def put_xdecref_set(self, cname, type, rhs_cname):
3119
- type.generate_xdecref_set(self, cname, rhs_cname)
3237
+ self.handle_refnanny(type)
3238
+ self.putln(type.get_xdecref_set_code(cname, rhs_cname))
3120
3239
 
3121
3240
  def put_incref_memoryviewslice(self, slice_cname, type, have_gil):
3122
3241
  # TODO ideally this would just be merged into "put_incref"
3123
- type.generate_incref_memoryviewslice(self, slice_cname, have_gil=have_gil)
3242
+ self.putln(type.get_incref_memoryviewslice_code(slice_cname, have_gil=have_gil))
3124
3243
 
3125
3244
  def put_var_incref_memoryviewslice(self, entry, have_gil):
3126
3245
  self.put_incref_memoryviewslice(entry.cname, entry.type, have_gil=have_gil)
@@ -3763,6 +3882,7 @@ class ClosureTempAllocator:
3763
3882
  self.temps_allocated = {}
3764
3883
  self.temps_free = {}
3765
3884
  self.temps_count = 0
3885
+ self.carray_count = 0
3766
3886
 
3767
3887
  def reset(self):
3768
3888
  for type, cnames in self.temps_allocated.items():
@@ -3779,3 +3899,9 @@ class ClosureTempAllocator:
3779
3899
  self.temps_allocated[type].append(cname)
3780
3900
  self.temps_count += 1
3781
3901
  return cname
3902
+
3903
+ def allocate_carray(self, array_type, pos):
3904
+ cname = f'{Naming.carray_literal_prefix}{self.carray_count:d}'
3905
+ self.klass.declare_var(pos=pos, name=cname, cname=cname, type=array_type, is_cdef=True)
3906
+ self.carray_count += 1
3907
+ return f"{Naming.cur_scope_cname}->{cname}"