Cython 3.1.0a1__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.
Files changed (301) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +250 -0
  4. Cython/Build/Dependencies.py +1275 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +342 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/Tests/TestCyCache.py +119 -0
  9. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  10. Cython/Build/Tests/TestDependencies.py +133 -0
  11. Cython/Build/Tests/TestInline.py +112 -0
  12. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  13. Cython/Build/Tests/TestRecythonize.py +212 -0
  14. Cython/Build/Tests/TestStripLiterals.py +155 -0
  15. Cython/Build/Tests/__init__.py +1 -0
  16. Cython/Build/__init__.py +8 -0
  17. Cython/CodeWriter.py +811 -0
  18. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  19. Cython/Compiler/Annotate.py +326 -0
  20. Cython/Compiler/AutoDocTransforms.py +314 -0
  21. Cython/Compiler/Buffer.py +680 -0
  22. Cython/Compiler/Builtin.py +862 -0
  23. Cython/Compiler/CmdLine.py +243 -0
  24. Cython/Compiler/Code.pxd +145 -0
  25. Cython/Compiler/Code.py +3328 -0
  26. Cython/Compiler/CodeGeneration.py +33 -0
  27. Cython/Compiler/CythonScope.py +179 -0
  28. Cython/Compiler/Dataclass.py +868 -0
  29. Cython/Compiler/DebugFlags.py +21 -0
  30. Cython/Compiler/Errors.py +295 -0
  31. Cython/Compiler/ExprNodes.py +15051 -0
  32. Cython/Compiler/FlowControl.pxd +97 -0
  33. Cython/Compiler/FlowControl.py +1438 -0
  34. Cython/Compiler/FusedNode.py +998 -0
  35. Cython/Compiler/Future.py +16 -0
  36. Cython/Compiler/Interpreter.py +57 -0
  37. Cython/Compiler/Lexicon.py +340 -0
  38. Cython/Compiler/LineTable.py +114 -0
  39. Cython/Compiler/Main.py +779 -0
  40. Cython/Compiler/MatchCaseNodes.py +259 -0
  41. Cython/Compiler/MemoryView.py +860 -0
  42. Cython/Compiler/ModuleNode.py +4065 -0
  43. Cython/Compiler/Naming.py +369 -0
  44. Cython/Compiler/Nodes.py +10557 -0
  45. Cython/Compiler/Optimize.py +5269 -0
  46. Cython/Compiler/Options.py +828 -0
  47. Cython/Compiler/ParseTreeTransforms.pxd +78 -0
  48. Cython/Compiler/ParseTreeTransforms.py +4441 -0
  49. Cython/Compiler/Parsing.pxd +9 -0
  50. Cython/Compiler/Parsing.py +4797 -0
  51. Cython/Compiler/Pipeline.py +425 -0
  52. Cython/Compiler/PyrexTypes.py +5572 -0
  53. Cython/Compiler/Pythran.py +223 -0
  54. Cython/Compiler/Scanning.pxd +40 -0
  55. Cython/Compiler/Scanning.py +574 -0
  56. Cython/Compiler/StringEncoding.py +347 -0
  57. Cython/Compiler/Symtab.py +2998 -0
  58. Cython/Compiler/Tests/TestBuffer.py +105 -0
  59. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  60. Cython/Compiler/Tests/TestCmdLine.py +573 -0
  61. Cython/Compiler/Tests/TestCode.py +86 -0
  62. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  63. Cython/Compiler/Tests/TestGrammar.py +202 -0
  64. Cython/Compiler/Tests/TestMemView.py +71 -0
  65. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  66. Cython/Compiler/Tests/TestScanning.py +134 -0
  67. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  68. Cython/Compiler/Tests/TestStringEncoding.py +33 -0
  69. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  70. Cython/Compiler/Tests/TestTreePath.py +93 -0
  71. Cython/Compiler/Tests/TestTypes.py +75 -0
  72. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  73. Cython/Compiler/Tests/TestVisitor.py +61 -0
  74. Cython/Compiler/Tests/Utils.py +36 -0
  75. Cython/Compiler/Tests/__init__.py +1 -0
  76. Cython/Compiler/TreeFragment.py +278 -0
  77. Cython/Compiler/TreePath.py +290 -0
  78. Cython/Compiler/TypeInference.py +584 -0
  79. Cython/Compiler/TypeSlots.py +1181 -0
  80. Cython/Compiler/UFuncs.py +311 -0
  81. Cython/Compiler/UtilNodes.py +387 -0
  82. Cython/Compiler/UtilityCode.py +274 -0
  83. Cython/Compiler/Version.py +8 -0
  84. Cython/Compiler/Visitor.pxd +53 -0
  85. Cython/Compiler/Visitor.py +861 -0
  86. Cython/Compiler/__init__.py +1 -0
  87. Cython/Coverage.py +443 -0
  88. Cython/Debugger/Cygdb.py +179 -0
  89. Cython/Debugger/DebugWriter.py +82 -0
  90. Cython/Debugger/Tests/TestLibCython.py +275 -0
  91. Cython/Debugger/Tests/__init__.py +1 -0
  92. Cython/Debugger/Tests/cfuncs.c +8 -0
  93. Cython/Debugger/Tests/codefile +49 -0
  94. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  95. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  96. Cython/Debugger/__init__.py +1 -0
  97. Cython/Debugger/libcython.py +1549 -0
  98. Cython/Debugger/libpython.py +2821 -0
  99. Cython/Debugging.py +20 -0
  100. Cython/Distutils/__init__.py +2 -0
  101. Cython/Distutils/build_ext.py +137 -0
  102. Cython/Distutils/extension.py +96 -0
  103. Cython/Distutils/old_build_ext.py +351 -0
  104. Cython/Includes/cpython/__init__.pxd +173 -0
  105. Cython/Includes/cpython/array.pxd +174 -0
  106. Cython/Includes/cpython/bool.pxd +37 -0
  107. Cython/Includes/cpython/buffer.pxd +112 -0
  108. Cython/Includes/cpython/bytearray.pxd +33 -0
  109. Cython/Includes/cpython/bytes.pxd +200 -0
  110. Cython/Includes/cpython/cellobject.pxd +35 -0
  111. Cython/Includes/cpython/ceval.pxd +8 -0
  112. Cython/Includes/cpython/codecs.pxd +121 -0
  113. Cython/Includes/cpython/complex.pxd +55 -0
  114. Cython/Includes/cpython/contextvars.pxd +141 -0
  115. Cython/Includes/cpython/conversion.pxd +36 -0
  116. Cython/Includes/cpython/datetime.pxd +384 -0
  117. Cython/Includes/cpython/descr.pxd +26 -0
  118. Cython/Includes/cpython/dict.pxd +187 -0
  119. Cython/Includes/cpython/exc.pxd +263 -0
  120. Cython/Includes/cpython/fileobject.pxd +57 -0
  121. Cython/Includes/cpython/float.pxd +47 -0
  122. Cython/Includes/cpython/function.pxd +65 -0
  123. Cython/Includes/cpython/genobject.pxd +25 -0
  124. Cython/Includes/cpython/getargs.pxd +12 -0
  125. Cython/Includes/cpython/instance.pxd +25 -0
  126. Cython/Includes/cpython/iterator.pxd +36 -0
  127. Cython/Includes/cpython/iterobject.pxd +24 -0
  128. Cython/Includes/cpython/list.pxd +92 -0
  129. Cython/Includes/cpython/long.pxd +149 -0
  130. Cython/Includes/cpython/longintrepr.pxd +19 -0
  131. Cython/Includes/cpython/mapping.pxd +63 -0
  132. Cython/Includes/cpython/marshal.pxd +66 -0
  133. Cython/Includes/cpython/mem.pxd +120 -0
  134. Cython/Includes/cpython/memoryview.pxd +50 -0
  135. Cython/Includes/cpython/method.pxd +49 -0
  136. Cython/Includes/cpython/module.pxd +208 -0
  137. Cython/Includes/cpython/number.pxd +258 -0
  138. Cython/Includes/cpython/object.pxd +433 -0
  139. Cython/Includes/cpython/pycapsule.pxd +143 -0
  140. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  141. Cython/Includes/cpython/pyport.pxd +8 -0
  142. Cython/Includes/cpython/pystate.pxd +95 -0
  143. Cython/Includes/cpython/pythread.pxd +53 -0
  144. Cython/Includes/cpython/ref.pxd +67 -0
  145. Cython/Includes/cpython/sequence.pxd +134 -0
  146. Cython/Includes/cpython/set.pxd +119 -0
  147. Cython/Includes/cpython/slice.pxd +70 -0
  148. Cython/Includes/cpython/time.pxd +129 -0
  149. Cython/Includes/cpython/tuple.pxd +72 -0
  150. Cython/Includes/cpython/type.pxd +53 -0
  151. Cython/Includes/cpython/unicode.pxd +639 -0
  152. Cython/Includes/cpython/version.pxd +32 -0
  153. Cython/Includes/cpython/weakref.pxd +42 -0
  154. Cython/Includes/libc/__init__.pxd +1 -0
  155. Cython/Includes/libc/complex.pxd +35 -0
  156. Cython/Includes/libc/errno.pxd +127 -0
  157. Cython/Includes/libc/float.pxd +43 -0
  158. Cython/Includes/libc/limits.pxd +28 -0
  159. Cython/Includes/libc/locale.pxd +46 -0
  160. Cython/Includes/libc/math.pxd +209 -0
  161. Cython/Includes/libc/setjmp.pxd +10 -0
  162. Cython/Includes/libc/signal.pxd +64 -0
  163. Cython/Includes/libc/stddef.pxd +9 -0
  164. Cython/Includes/libc/stdint.pxd +105 -0
  165. Cython/Includes/libc/stdio.pxd +80 -0
  166. Cython/Includes/libc/stdlib.pxd +72 -0
  167. Cython/Includes/libc/string.pxd +50 -0
  168. Cython/Includes/libc/time.pxd +47 -0
  169. Cython/Includes/libcpp/__init__.pxd +4 -0
  170. Cython/Includes/libcpp/algorithm.pxd +320 -0
  171. Cython/Includes/libcpp/any.pxd +16 -0
  172. Cython/Includes/libcpp/atomic.pxd +59 -0
  173. Cython/Includes/libcpp/bit.pxd +29 -0
  174. Cython/Includes/libcpp/cast.pxd +12 -0
  175. Cython/Includes/libcpp/cmath.pxd +518 -0
  176. Cython/Includes/libcpp/complex.pxd +106 -0
  177. Cython/Includes/libcpp/deque.pxd +165 -0
  178. Cython/Includes/libcpp/execution.pxd +15 -0
  179. Cython/Includes/libcpp/forward_list.pxd +63 -0
  180. Cython/Includes/libcpp/functional.pxd +26 -0
  181. Cython/Includes/libcpp/iterator.pxd +34 -0
  182. Cython/Includes/libcpp/limits.pxd +61 -0
  183. Cython/Includes/libcpp/list.pxd +117 -0
  184. Cython/Includes/libcpp/map.pxd +252 -0
  185. Cython/Includes/libcpp/memory.pxd +115 -0
  186. Cython/Includes/libcpp/numbers.pxd +15 -0
  187. Cython/Includes/libcpp/numeric.pxd +131 -0
  188. Cython/Includes/libcpp/optional.pxd +34 -0
  189. Cython/Includes/libcpp/pair.pxd +1 -0
  190. Cython/Includes/libcpp/queue.pxd +25 -0
  191. Cython/Includes/libcpp/random.pxd +166 -0
  192. Cython/Includes/libcpp/set.pxd +228 -0
  193. Cython/Includes/libcpp/stack.pxd +11 -0
  194. Cython/Includes/libcpp/string.pxd +333 -0
  195. Cython/Includes/libcpp/typeindex.pxd +15 -0
  196. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  197. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  198. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  199. Cython/Includes/libcpp/utility.pxd +30 -0
  200. Cython/Includes/libcpp/vector.pxd +167 -0
  201. Cython/Includes/openmp.pxd +50 -0
  202. Cython/Includes/posix/__init__.pxd +1 -0
  203. Cython/Includes/posix/dlfcn.pxd +14 -0
  204. Cython/Includes/posix/fcntl.pxd +86 -0
  205. Cython/Includes/posix/ioctl.pxd +4 -0
  206. Cython/Includes/posix/mman.pxd +101 -0
  207. Cython/Includes/posix/resource.pxd +57 -0
  208. Cython/Includes/posix/select.pxd +21 -0
  209. Cython/Includes/posix/signal.pxd +73 -0
  210. Cython/Includes/posix/stat.pxd +98 -0
  211. Cython/Includes/posix/stdio.pxd +37 -0
  212. Cython/Includes/posix/stdlib.pxd +29 -0
  213. Cython/Includes/posix/strings.pxd +9 -0
  214. Cython/Includes/posix/time.pxd +71 -0
  215. Cython/Includes/posix/types.pxd +30 -0
  216. Cython/Includes/posix/uio.pxd +26 -0
  217. Cython/Includes/posix/unistd.pxd +271 -0
  218. Cython/Includes/posix/wait.pxd +38 -0
  219. Cython/Plex/Actions.pxd +24 -0
  220. Cython/Plex/Actions.py +119 -0
  221. Cython/Plex/DFA.pxd +14 -0
  222. Cython/Plex/DFA.py +164 -0
  223. Cython/Plex/Errors.py +48 -0
  224. Cython/Plex/Lexicons.py +178 -0
  225. Cython/Plex/Machines.pxd +36 -0
  226. Cython/Plex/Machines.py +238 -0
  227. Cython/Plex/Regexps.py +539 -0
  228. Cython/Plex/Scanners.pxd +47 -0
  229. Cython/Plex/Scanners.py +360 -0
  230. Cython/Plex/Transitions.pxd +14 -0
  231. Cython/Plex/Transitions.py +239 -0
  232. Cython/Plex/__init__.py +34 -0
  233. Cython/Runtime/__init__.py +1 -0
  234. Cython/Runtime/refnanny.pyx +261 -0
  235. Cython/Shadow.py +656 -0
  236. Cython/Shadow.pyi +521 -0
  237. Cython/StringIOTree.py +170 -0
  238. Cython/Tempita/__init__.py +4 -0
  239. Cython/Tempita/_looper.py +154 -0
  240. Cython/Tempita/_tempita.py +1091 -0
  241. Cython/TestUtils.py +417 -0
  242. Cython/Tests/TestCodeWriter.py +128 -0
  243. Cython/Tests/TestCythonUtils.py +202 -0
  244. Cython/Tests/TestJediTyper.py +223 -0
  245. Cython/Tests/TestShadow.py +114 -0
  246. Cython/Tests/TestStringIOTree.py +67 -0
  247. Cython/Tests/TestTestUtils.py +90 -0
  248. Cython/Tests/__init__.py +1 -0
  249. Cython/Tests/xmlrunner.py +390 -0
  250. Cython/Utility/AsyncGen.c +1263 -0
  251. Cython/Utility/Buffer.c +875 -0
  252. Cython/Utility/Builtins.c +660 -0
  253. Cython/Utility/CConvert.pyx +134 -0
  254. Cython/Utility/CMath.c +95 -0
  255. Cython/Utility/CommonStructures.c +139 -0
  256. Cython/Utility/Complex.c +378 -0
  257. Cython/Utility/Coroutine.c +2413 -0
  258. Cython/Utility/CpdefEnums.pyx +108 -0
  259. Cython/Utility/CppConvert.pyx +279 -0
  260. Cython/Utility/CppSupport.cpp +133 -0
  261. Cython/Utility/CythonFunction.c +1851 -0
  262. Cython/Utility/Dataclasses.c +185 -0
  263. Cython/Utility/Dataclasses.py +112 -0
  264. Cython/Utility/Embed.c +125 -0
  265. Cython/Utility/Exceptions.c +1017 -0
  266. Cython/Utility/ExtensionTypes.c +797 -0
  267. Cython/Utility/FunctionArguments.c +573 -0
  268. Cython/Utility/ImportExport.c +912 -0
  269. Cython/Utility/MemoryView.pyx +1478 -0
  270. Cython/Utility/MemoryView_C.c +992 -0
  271. Cython/Utility/ModuleSetupCode.c +2501 -0
  272. Cython/Utility/NumpyImportArray.c +46 -0
  273. Cython/Utility/ObjectHandling.c +3054 -0
  274. Cython/Utility/Optimize.c +1533 -0
  275. Cython/Utility/Overflow.c +404 -0
  276. Cython/Utility/Printing.c +86 -0
  277. Cython/Utility/Profile.c +660 -0
  278. Cython/Utility/StringTools.c +1206 -0
  279. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  280. Cython/Utility/TestCythonScope.pyx +75 -0
  281. Cython/Utility/TestUtilityLoader.c +12 -0
  282. Cython/Utility/TypeConversion.c +1329 -0
  283. Cython/Utility/UFuncs.pyx +50 -0
  284. Cython/Utility/UFuncs_C.c +89 -0
  285. Cython/Utility/__init__.py +28 -0
  286. Cython/Utility/arrayarray.h +143 -0
  287. Cython/Utils.py +687 -0
  288. Cython/__init__.py +10 -0
  289. Cython/__init__.pyi +7 -0
  290. Cython/py.typed +0 -0
  291. Cython-3.1.0a1.dist-info/COPYING.txt +19 -0
  292. Cython-3.1.0a1.dist-info/LICENSE.txt +176 -0
  293. Cython-3.1.0a1.dist-info/METADATA +67 -0
  294. Cython-3.1.0a1.dist-info/RECORD +301 -0
  295. Cython-3.1.0a1.dist-info/WHEEL +5 -0
  296. Cython-3.1.0a1.dist-info/entry_points.txt +4 -0
  297. Cython-3.1.0a1.dist-info/top_level.txt +3 -0
  298. cython.py +29 -0
  299. pyximport/__init__.py +4 -0
  300. pyximport/pyxbuild.py +160 -0
  301. pyximport/pyximport.py +482 -0
@@ -0,0 +1,3328 @@
1
+ #
2
+ # Code output module
3
+ #
4
+
5
+
6
+ import cython
7
+ cython.declare(os=object, re=object, operator=object, textwrap=object,
8
+ Template=object, Naming=object, Options=object, StringEncoding=object,
9
+ Utils=object, SourceDescriptor=object, StringIOTree=object,
10
+ DebugFlags=object, defaultdict=object,
11
+ closing=object, partial=object, wraps=object)
12
+
13
+ import hashlib
14
+ import operator
15
+ import os
16
+ import re
17
+ import shutil
18
+ import textwrap
19
+ from string import Template
20
+ from functools import partial, wraps
21
+ from contextlib import closing, contextmanager
22
+ from collections import defaultdict
23
+
24
+ from . import Naming
25
+ from . import Options
26
+ from . import DebugFlags
27
+ from . import StringEncoding
28
+ from .. import Utils
29
+ from .Scanning import SourceDescriptor
30
+ from ..StringIOTree import StringIOTree
31
+
32
+
33
+ renamed_py2_builtins_map = {
34
+ # builtins that had different names in Py2 code
35
+ 'unicode' : 'str',
36
+ 'basestring' : 'str',
37
+ 'xrange' : 'range',
38
+ 'raw_input' : 'input',
39
+ }
40
+
41
+ ctypedef_builtins_map = {
42
+ # types of builtins in "ctypedef class" statements which we don't
43
+ # import either because the names conflict with C types or because
44
+ # the type simply is not exposed.
45
+ 'py_int' : '&PyLong_Type',
46
+ 'py_long' : '&PyLong_Type',
47
+ 'py_float' : '&PyFloat_Type',
48
+ 'wrapper_descriptor' : '&PyWrapperDescr_Type',
49
+ }
50
+
51
+ basicsize_builtins_map = {
52
+ # builtins whose type has a different tp_basicsize than sizeof(...)
53
+ 'PyTypeObject': 'PyHeapTypeObject',
54
+ }
55
+
56
+ # Builtins as of Python version ...
57
+ KNOWN_PYTHON_BUILTINS_VERSION = (3, 13, 0, 'alpha', 5)
58
+ KNOWN_PYTHON_BUILTINS = frozenset([
59
+ 'ArithmeticError',
60
+ 'AssertionError',
61
+ 'AttributeError',
62
+ 'BaseException',
63
+ 'BaseExceptionGroup',
64
+ 'BlockingIOError',
65
+ 'BrokenPipeError',
66
+ 'BufferError',
67
+ 'BytesWarning',
68
+ 'ChildProcessError',
69
+ 'ConnectionAbortedError',
70
+ 'ConnectionError',
71
+ 'ConnectionRefusedError',
72
+ 'ConnectionResetError',
73
+ 'DeprecationWarning',
74
+ 'EOFError',
75
+ 'Ellipsis',
76
+ 'EncodingWarning',
77
+ 'EnvironmentError',
78
+ 'Exception',
79
+ 'ExceptionGroup',
80
+ 'False',
81
+ 'FileExistsError',
82
+ 'FileNotFoundError',
83
+ 'FloatingPointError',
84
+ 'FutureWarning',
85
+ 'GeneratorExit',
86
+ 'IOError',
87
+ 'ImportError',
88
+ 'ImportWarning',
89
+ '_IncompleteInputError',
90
+ 'IndentationError',
91
+ 'IndexError',
92
+ 'InterruptedError',
93
+ 'IsADirectoryError',
94
+ 'KeyError',
95
+ 'KeyboardInterrupt',
96
+ 'LookupError',
97
+ 'MemoryError',
98
+ 'ModuleNotFoundError',
99
+ 'NameError',
100
+ 'None',
101
+ 'NotADirectoryError',
102
+ 'NotImplemented',
103
+ 'NotImplementedError',
104
+ 'OSError',
105
+ 'OverflowError',
106
+ 'PendingDeprecationWarning',
107
+ 'PermissionError',
108
+ 'ProcessLookupError',
109
+ 'PythonFinalizationError',
110
+ 'RecursionError',
111
+ 'ReferenceError',
112
+ 'ResourceWarning',
113
+ 'RuntimeError',
114
+ 'RuntimeWarning',
115
+ 'StopAsyncIteration',
116
+ 'StopIteration',
117
+ 'SyntaxError',
118
+ 'SyntaxWarning',
119
+ 'SystemError',
120
+ 'SystemExit',
121
+ 'TabError',
122
+ 'TimeoutError',
123
+ 'True',
124
+ 'TypeError',
125
+ 'UnboundLocalError',
126
+ 'UnicodeDecodeError',
127
+ 'UnicodeEncodeError',
128
+ 'UnicodeError',
129
+ 'UnicodeTranslateError',
130
+ 'UnicodeWarning',
131
+ 'UserWarning',
132
+ 'ValueError',
133
+ 'Warning',
134
+ 'WindowsError',
135
+ 'ZeroDivisionError',
136
+ '__build_class__',
137
+ '__debug__',
138
+ '__import__',
139
+ 'abs',
140
+ 'aiter',
141
+ 'all',
142
+ 'anext',
143
+ 'any',
144
+ 'ascii',
145
+ 'bin',
146
+ 'bool',
147
+ 'breakpoint',
148
+ 'bytearray',
149
+ 'bytes',
150
+ 'callable',
151
+ 'chr',
152
+ 'classmethod',
153
+ 'compile',
154
+ 'complex',
155
+ 'copyright',
156
+ 'credits',
157
+ 'delattr',
158
+ 'dict',
159
+ 'dir',
160
+ 'divmod',
161
+ 'enumerate',
162
+ 'eval',
163
+ 'exec',
164
+ 'exit',
165
+ 'filter',
166
+ 'float',
167
+ 'format',
168
+ 'frozenset',
169
+ 'getattr',
170
+ 'globals',
171
+ 'hasattr',
172
+ 'hash',
173
+ 'help',
174
+ 'hex',
175
+ 'id',
176
+ 'input',
177
+ 'int',
178
+ 'isinstance',
179
+ 'issubclass',
180
+ 'iter',
181
+ 'len',
182
+ 'license',
183
+ 'list',
184
+ 'locals',
185
+ 'map',
186
+ 'max',
187
+ 'memoryview',
188
+ 'min',
189
+ 'next',
190
+ 'object',
191
+ 'oct',
192
+ 'open',
193
+ 'ord',
194
+ 'pow',
195
+ 'print',
196
+ 'property',
197
+ 'quit',
198
+ 'range',
199
+ 'repr',
200
+ 'reversed',
201
+ 'round',
202
+ 'set',
203
+ 'setattr',
204
+ 'slice',
205
+ 'sorted',
206
+ 'staticmethod',
207
+ 'str',
208
+ 'sum',
209
+ 'super',
210
+ 'tuple',
211
+ 'type',
212
+ 'vars',
213
+ 'zip',
214
+ ])
215
+
216
+ uncachable_builtins = [
217
+ # Global/builtin names that cannot be cached because they may or may not
218
+ # be available at import time, for various reasons:
219
+ ## Python 3.13+
220
+ '_IncompleteInputError',
221
+ 'PythonFinalizationError',
222
+ ## Python 3.11+
223
+ 'BaseExceptionGroup',
224
+ 'ExceptionGroup',
225
+ ## - Py3.10+
226
+ 'aiter',
227
+ 'anext',
228
+ 'EncodingWarning',
229
+ ## - Py3.7+
230
+ 'breakpoint', # might deserve an implementation in Cython
231
+ ## - platform specific
232
+ 'WindowsError',
233
+ ## - others
234
+ '_', # e.g. used by gettext
235
+ ]
236
+
237
+ special_py_methods = cython.declare(frozenset, frozenset((
238
+ '__cinit__', '__dealloc__', '__richcmp__', '__next__',
239
+ '__await__', '__aiter__', '__anext__',
240
+ '__getbuffer__', '__releasebuffer__',
241
+ )))
242
+
243
+ modifier_output_mapper = {
244
+ 'inline': 'CYTHON_INLINE'
245
+ }.get
246
+
247
+ cleanup_level_for_type_prefix = cython.declare(object, {
248
+ 'ustring': None,
249
+ 'tuple': 2,
250
+ 'slice': 2,
251
+ }.get)
252
+
253
+
254
+ class IncludeCode:
255
+ """
256
+ An include file and/or verbatim C code to be included in the
257
+ generated sources.
258
+ """
259
+ # attributes:
260
+ #
261
+ # pieces {order: unicode}: pieces of C code to be generated.
262
+ # For the included file, the key "order" is zero.
263
+ # For verbatim include code, the "order" is the "order"
264
+ # attribute of the original IncludeCode where this piece
265
+ # of C code was first added. This is needed to prevent
266
+ # duplication if the same include code is found through
267
+ # multiple cimports.
268
+ # location int: where to put this include in the C sources, one
269
+ # of the constants INITIAL, EARLY, LATE
270
+ # order int: sorting order (automatically set by increasing counter)
271
+
272
+ # Constants for location. If the same include occurs with different
273
+ # locations, the earliest one takes precedense.
274
+ INITIAL = 0
275
+ EARLY = 1
276
+ LATE = 2
277
+
278
+ counter = 1 # Counter for "order"
279
+
280
+ def __init__(self, include=None, verbatim=None, late=True, initial=False):
281
+ self.order = self.counter
282
+ type(self).counter += 1
283
+ self.pieces = {}
284
+
285
+ if include:
286
+ if include[0] == '<' and include[-1] == '>':
287
+ self.pieces[0] = '#include {}'.format(include)
288
+ late = False # system include is never late
289
+ else:
290
+ self.pieces[0] = '#include "{}"'.format(include)
291
+
292
+ if verbatim:
293
+ self.pieces[self.order] = verbatim
294
+
295
+ if initial:
296
+ self.location = self.INITIAL
297
+ elif late:
298
+ self.location = self.LATE
299
+ else:
300
+ self.location = self.EARLY
301
+
302
+ def dict_update(self, d, key):
303
+ """
304
+ Insert `self` in dict `d` with key `key`. If that key already
305
+ exists, update the attributes of the existing value with `self`.
306
+ """
307
+ if key in d:
308
+ other = d[key]
309
+ other.location = min(self.location, other.location)
310
+ other.pieces.update(self.pieces)
311
+ else:
312
+ d[key] = self
313
+
314
+ def sortkey(self):
315
+ return self.order
316
+
317
+ def mainpiece(self):
318
+ """
319
+ Return the main piece of C code, corresponding to the include
320
+ file. If there was no include file, return None.
321
+ """
322
+ return self.pieces.get(0)
323
+
324
+ def write(self, code):
325
+ # Write values of self.pieces dict, sorted by the keys
326
+ for k in sorted(self.pieces):
327
+ code.putln(self.pieces[k])
328
+
329
+
330
+ def get_utility_dir():
331
+ # make this a function and not global variables:
332
+ # http://trac.cython.org/cython_trac/ticket/475
333
+ Cython_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
334
+ return os.path.join(Cython_dir, "Utility")
335
+
336
+ read_utilities_hook = None
337
+ """
338
+ Override the hook for reading a utilities file that contains code fragments used
339
+ by the codegen.
340
+
341
+ The hook functions takes the path of the utilities file, and returns a list
342
+ of strings, one per line.
343
+
344
+ The default behavior is to open a file relative to get_utility_dir().
345
+ """
346
+
347
+ def read_utilities_from_utility_dir(path):
348
+ """
349
+ Read all lines of the file at the provided path from a path relative
350
+ to get_utility_dir().
351
+ """
352
+ filename = os.path.join(get_utility_dir(), path)
353
+ with closing(Utils.open_source_file(filename, encoding='UTF-8')) as f:
354
+ return f.readlines()
355
+
356
+ # by default, read utilities from the utility directory.
357
+ read_utilities_hook = read_utilities_from_utility_dir
358
+
359
+ class UtilityCodeBase:
360
+ """
361
+ Support for loading utility code from a file.
362
+
363
+ Code sections in the file can be specified as follows:
364
+
365
+ ##### MyUtility.proto #####
366
+
367
+ [proto declarations]
368
+
369
+ ##### MyUtility.init #####
370
+
371
+ [code run at module initialization]
372
+
373
+ ##### MyUtility #####
374
+ #@requires: MyOtherUtility
375
+ #@substitute: naming
376
+
377
+ [definitions]
378
+
379
+ ##### MyUtility #####
380
+ #@substitute: tempita
381
+
382
+ [requires tempita substitution
383
+ - context can't be specified here though so only
384
+ tempita utility that requires no external context
385
+ will benefit from this tag
386
+ - only necessary when @required from non-tempita code]
387
+
388
+ for prototypes and implementation respectively. For non-python or
389
+ -cython files backslashes should be used instead. 5 to 30 comment
390
+ characters may be used on either side.
391
+
392
+ If the @cname decorator is not used and this is a CythonUtilityCode,
393
+ one should pass in the 'name' keyword argument to be used for name
394
+ mangling of such entries.
395
+ """
396
+
397
+ is_cython_utility = False
398
+ _utility_cache = {}
399
+
400
+ @classmethod
401
+ def _add_utility(cls, utility, name, type, lines, begin_lineno, tags=None):
402
+ if utility is None:
403
+ return
404
+
405
+ code = '\n'.join(lines)
406
+ if tags and 'substitute' in tags and 'naming' in tags['substitute']:
407
+ try:
408
+ new_code = Template(code).substitute(vars(Naming))
409
+ except (KeyError, ValueError) as e:
410
+ raise RuntimeError(
411
+ f"Error parsing templated utility code '{name}.{type}' at line {begin_lineno:d}: {e}")
412
+ if new_code == code:
413
+ raise RuntimeError(
414
+ f"Found useless 'substitute: naming' declaration without replacements. ({name}.{type}:{begin_lineno:d})")
415
+ code = new_code
416
+
417
+ # remember correct line numbers at least until after templating
418
+ code = '\n' * begin_lineno + code
419
+
420
+ if type == 'proto':
421
+ utility[0] = code
422
+ elif type == 'impl':
423
+ utility[1] = code
424
+ else:
425
+ all_tags = utility[2]
426
+ all_tags[type] = code
427
+
428
+ if tags:
429
+ all_tags = utility[2]
430
+ for name, values in tags.items():
431
+ all_tags.setdefault(name, set()).update(values)
432
+
433
+ @classmethod
434
+ def load_utilities_from_file(cls, path):
435
+ utilities = cls._utility_cache.get(path)
436
+ if utilities:
437
+ return utilities
438
+
439
+ _, ext = os.path.splitext(path)
440
+ if ext in ('.pyx', '.py', '.pxd', '.pxi'):
441
+ comment = '#'
442
+ strip_comments = partial(re.compile(r'^\s*#(?!\s*cython\s*:).*').sub, '')
443
+ rstrip = str.rstrip
444
+ else:
445
+ comment = '/'
446
+ strip_comments = partial(re.compile(r'^\s*//.*|/\*[^*]*\*/').sub, '')
447
+ rstrip = partial(re.compile(r'\s+(\\?)$').sub, r'\1')
448
+ match_special = re.compile(
449
+ (r'^%(C)s{5,30}\s*(?P<name>(?:\w|\.)+)\s*%(C)s{5,30}|'
450
+ r'^%(C)s+@(?P<tag>\w+)\s*:\s*(?P<value>(?:\w|[.:])+)') %
451
+ {'C': comment}).match
452
+ match_type = re.compile(r'(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup|module_state_decls)$').match
453
+
454
+ all_lines = read_utilities_hook(path)
455
+
456
+ utilities = defaultdict(lambda: [None, None, {}])
457
+ lines = []
458
+ tags = defaultdict(set)
459
+ utility = name = type = None
460
+ begin_lineno = 0
461
+
462
+ for lineno, line in enumerate(all_lines):
463
+ m = match_special(line)
464
+ if m:
465
+ if m.group('name'):
466
+ cls._add_utility(utility, name, type, lines, begin_lineno, tags)
467
+
468
+ begin_lineno = lineno + 1
469
+ del lines[:]
470
+ tags.clear()
471
+
472
+ name = m.group('name')
473
+ mtype = match_type(name)
474
+ if mtype:
475
+ name, type = mtype.groups()
476
+ else:
477
+ type = 'impl'
478
+ utility = utilities[name]
479
+ else:
480
+ tags[m.group('tag')].add(m.group('value'))
481
+ lines.append('') # keep line number correct
482
+ else:
483
+ lines.append(rstrip(strip_comments(line)))
484
+
485
+ if utility is None:
486
+ raise ValueError("Empty utility code file")
487
+
488
+ # Don't forget to add the last utility code
489
+ cls._add_utility(utility, name, type, lines, begin_lineno, tags)
490
+
491
+ utilities = dict(utilities) # un-defaultdict-ify
492
+ cls._utility_cache[path] = utilities
493
+ return utilities
494
+
495
+ @classmethod
496
+ def load(cls, util_code_name, from_file, **kwargs):
497
+ """
498
+ Load utility code from a file specified by from_file (relative to
499
+ Cython/Utility) and name util_code_name.
500
+ """
501
+
502
+ if '::' in util_code_name:
503
+ from_file, util_code_name = util_code_name.rsplit('::', 1)
504
+ assert from_file
505
+ utilities = cls.load_utilities_from_file(from_file)
506
+ proto, impl, tags = utilities[util_code_name]
507
+
508
+ if tags:
509
+ if "substitute" in tags and "tempita" in tags["substitute"]:
510
+ if not issubclass(cls, TempitaUtilityCode):
511
+ return TempitaUtilityCode.load(util_code_name, from_file, **kwargs)
512
+ orig_kwargs = kwargs.copy()
513
+ for name, values in tags.items():
514
+ if name in kwargs:
515
+ continue
516
+ # only pass lists when we have to: most argument expect one value or None
517
+ if name == 'requires':
518
+ if orig_kwargs:
519
+ values = [cls.load(dep, from_file, **orig_kwargs)
520
+ for dep in sorted(values)]
521
+ else:
522
+ # dependencies are rarely unique, so use load_cached() when we can
523
+ values = [cls.load_cached(dep, from_file)
524
+ for dep in sorted(values)]
525
+ elif name == 'substitute':
526
+ # don't want to pass "naming" or "tempita" to the constructor
527
+ # since these will have been handled
528
+ values = values - {'naming', 'tempita'}
529
+ if not values:
530
+ continue
531
+ elif not values:
532
+ values = None
533
+ elif len(values) == 1:
534
+ values = list(values)[0]
535
+ kwargs[name] = values
536
+
537
+ if proto is not None:
538
+ kwargs['proto'] = proto
539
+ if impl is not None:
540
+ kwargs['impl'] = impl
541
+
542
+ if 'name' not in kwargs:
543
+ kwargs['name'] = util_code_name
544
+
545
+ if 'file' not in kwargs and from_file:
546
+ kwargs['file'] = from_file
547
+ return cls(**kwargs)
548
+
549
+ @classmethod
550
+ def load_cached(cls, utility_code_name, from_file, __cache={}):
551
+ """
552
+ Calls .load(), but using a per-type cache based on utility name and file name.
553
+ """
554
+ key = (utility_code_name, from_file, cls)
555
+ try:
556
+ return __cache[key]
557
+ except KeyError:
558
+ pass
559
+ code = __cache[key] = cls.load(utility_code_name, from_file)
560
+ return code
561
+
562
+ @classmethod
563
+ def load_as_string(cls, util_code_name, from_file, include_requires=False, **kwargs):
564
+ """
565
+ Load a utility code as a string. Returns (proto, implementation).
566
+
567
+ If 'include_requires=True', concatenates all requirements before the actually
568
+ requested utility code, separately for proto and impl part.
569
+
570
+ In a lot of cases it may be better to use regular "load" and "CCodeWriter.put_code_here"
571
+ since that is able to apply the code transformations to the code too.
572
+ """
573
+ util = cls.load(util_code_name, from_file, **kwargs)
574
+
575
+ if not include_requires:
576
+ return (util.format_code(util.proto),
577
+ util.format_code(util.impl))
578
+
579
+ protos, impls = [], []
580
+ def prepend(util_code):
581
+ if util_code.requires:
582
+ for dep in util_code.requires:
583
+ prepend(dep)
584
+ if util_code.proto:
585
+ protos.append(util_code.format_code(util_code.proto))
586
+ if util_code.impl:
587
+ impls.append(util_code.format_code(util_code.impl))
588
+
589
+ prepend(util)
590
+ return "".join(protos), "".join(impls)
591
+
592
+ def format_code(self, code_string, replace_empty_lines=re.compile(r'\n\n+').sub):
593
+ """
594
+ Format a code section for output.
595
+ """
596
+ if code_string:
597
+ code_string = replace_empty_lines('\n', code_string.strip()) + '\n\n'
598
+ return code_string
599
+
600
+ def __repr__(self):
601
+ return "<%s(%s)>" % (type(self).__name__, self.name)
602
+
603
+ def get_tree(self, **kwargs):
604
+ return None
605
+
606
+ def __deepcopy__(self, memodict=None):
607
+ # No need to deep-copy utility code since it's essentially immutable.
608
+ return self
609
+
610
+
611
+ class UtilityCode(UtilityCodeBase):
612
+ """
613
+ Stores utility code to add during code generation.
614
+
615
+ See GlobalState.put_utility_code.
616
+
617
+ hashes/equals by instance
618
+
619
+ proto C prototypes
620
+ impl implementation code
621
+ init code to call on module initialization
622
+ requires utility code dependencies
623
+ proto_block the place in the resulting file where the prototype should
624
+ end up
625
+ name name of the utility code (or None)
626
+ file filename of the utility code file this utility was loaded
627
+ from (or None)
628
+ """
629
+ code_parts = ["proto", "impl", "init", "cleanup", "module_state_decls"]
630
+
631
+ def __init__(self, proto=None, impl=None, init=None, cleanup=None,
632
+ module_state_decls=None, requires=None,
633
+ proto_block='utility_code_proto', name=None, file=None):
634
+ # proto_block: Which code block to dump prototype in. See GlobalState.
635
+ self.proto = proto
636
+ self.impl = impl
637
+ self.init = init
638
+ self.cleanup = cleanup
639
+ self.module_state_decls = module_state_decls
640
+ self.requires = requires
641
+ self._cache = {}
642
+ self.specialize_list = []
643
+ self.proto_block = proto_block
644
+ self.name = name
645
+ self.file = file
646
+
647
+ # cached for use in hash and eq
648
+ self._parts_tuple = tuple(getattr(self, part, None) for part in self.code_parts)
649
+
650
+ def __hash__(self):
651
+ return hash(self._parts_tuple)
652
+
653
+ def __eq__(self, other):
654
+ if self is other:
655
+ return True
656
+ self_type, other_type = type(self), type(other)
657
+ if self_type is not other_type and not (isinstance(other, self_type) or isinstance(self, other_type)):
658
+ return False
659
+
660
+ return self._parts_tuple == other._parts_tuple
661
+
662
+ def none_or_sub(self, s, context):
663
+ """
664
+ Format a string in this utility code with context. If None, do nothing.
665
+ """
666
+ if s is None:
667
+ return None
668
+ return s % context
669
+
670
+ def specialize(self, pyrex_type=None, **data):
671
+ name = self.name
672
+ if pyrex_type is not None:
673
+ data['type'] = pyrex_type.empty_declaration_code()
674
+ data['type_name'] = pyrex_type.specialization_name()
675
+ name = "%s[%s]" % (name, data['type_name'])
676
+ # Dicts aren't hashable...
677
+ key = tuple(sorted(data.items()))
678
+ try:
679
+ return self._cache[key]
680
+ except KeyError:
681
+ if self.requires is None:
682
+ requires = None
683
+ else:
684
+ requires = [r.specialize(data) for r in self.requires]
685
+
686
+ s = self._cache[key] = UtilityCode(
687
+ self.none_or_sub(self.proto, data),
688
+ self.none_or_sub(self.impl, data),
689
+ self.none_or_sub(self.init, data),
690
+ self.none_or_sub(self.cleanup, data),
691
+ self.none_or_sub(self.module_state_decls, data),
692
+ requires,
693
+ self.proto_block,
694
+ name,
695
+ )
696
+
697
+ self.specialize_list.append(s)
698
+ return s
699
+
700
+ def _put_code_section(self, writer: "CCodeWriter", output: "GlobalState", code_type: str):
701
+ code_string = getattr(self, code_type)
702
+ if not code_string:
703
+ return
704
+
705
+ can_be_reused = code_type in ('proto', 'impl')
706
+
707
+ code_string, result_is_module_specific = process_utility_ccode(self, output, code_string)
708
+
709
+ code_type_name = code_type if code_type != 'impl' else ''
710
+ writer.putln(f"/* {self.name}{'.' if code_type_name else ''}{code_type_name} */")
711
+
712
+ if can_be_reused and not result_is_module_specific:
713
+ # can be reused across modules
714
+ writer.put_or_include(code_string, f'{self.name}_{code_type}')
715
+ else:
716
+ writer.put(code_string)
717
+
718
+ def _put_init_code_section(self, output):
719
+ if not self.init:
720
+ return
721
+ writer = output['init_globals']
722
+ self._put_code_section(writer, output, 'init')
723
+ # 'init' code can end with an 'if' statement for an error condition like:
724
+ # if (check_ok()) ; else
725
+ writer.putln(writer.error_goto_if_PyErr(output.module_pos))
726
+ writer.putln()
727
+
728
+ def put_code(self, output):
729
+ if self.requires:
730
+ for dependency in self.requires:
731
+ output.use_utility_code(dependency)
732
+
733
+ if self.proto:
734
+ self._put_code_section(output[self.proto_block], output, 'proto')
735
+ if self.impl:
736
+ self._put_code_section(output['utility_code_def'], output, 'impl')
737
+ if self.cleanup and Options.generate_cleanup_code:
738
+ self._put_code_section(output['cleanup_globals'], output, 'cleanup')
739
+ if self.module_state_decls:
740
+ self._put_code_section(output['module_state_contents'], output, 'module_state_decls')
741
+
742
+ if self.init:
743
+ self._put_init_code_section(output)
744
+
745
+
746
+ def add_macro_processor(*macro_names, regex=None, is_module_specific=False, _last_macro_processor = [None]):
747
+ """Decorator to chain the code macro processors below.
748
+ """
749
+ last_processor = _last_macro_processor[0]
750
+
751
+ def build_processor(func):
752
+ @wraps(func)
753
+ def process(utility_code: UtilityCode, output, code_string: str):
754
+ # First, call the processing chain in FIFO function definition order.
755
+ result_is_module_specific = False
756
+ if last_processor is not None:
757
+ code_string, result_is_module_specific = last_processor(utility_code, output, code_string)
758
+
759
+ # Detect if we need to do something.
760
+ if macro_names:
761
+ for macro in macro_names:
762
+ if macro in code_string:
763
+ break
764
+ else:
765
+ return code_string, result_is_module_specific
766
+
767
+ # Process the code.
768
+ if regex is None:
769
+ code_string = func(utility_code, output, code_string)
770
+ else:
771
+ code_string = re.sub(regex, partial(func, output), code_string)
772
+
773
+ # Make sure we found and replaced all macro occurrences.
774
+ for macro in macro_names:
775
+ if macro in code_string:
776
+ raise RuntimeError(f"Left-over utility code macro '{macro}()' found in '{utility_code.name}'")
777
+
778
+ result_is_module_specific |= is_module_specific
779
+ return code_string, result_is_module_specific
780
+
781
+ _last_macro_processor[0] = process
782
+ return process
783
+
784
+ return build_processor
785
+
786
+
787
+ @add_macro_processor(
788
+ 'CSTRING',
789
+ regex=r'CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\)',
790
+ )
791
+ def _wrap_c_string(_, matchobj):
792
+ """Replace CSTRING('''xyz''') by a C compatible string, taking care of line breaks.
793
+ """
794
+ content = matchobj.group(1).replace('"', r'\042')
795
+ return ''.join(
796
+ f'"{line}\\n"\n' if not line.endswith('\\') or line.endswith('\\\\') else f'"{line[:-1]}"\n'
797
+ for line in content.splitlines())
798
+
799
+
800
+ @add_macro_processor()
801
+ def _format_impl_code(utility_code: UtilityCode, _, impl):
802
+ return utility_code.format_code(impl)
803
+
804
+
805
+ @add_macro_processor(
806
+ 'CALL_UNBOUND_METHOD',
807
+ is_module_specific=True,
808
+ regex=(
809
+ r'CALL_UNBOUND_METHOD\('
810
+ r'([a-zA-Z_]+),\s*' # type cname
811
+ r'"([^"]+)",\s*' # method name
812
+ r'([^),\s]+)' # object cname
813
+ r'((?:,[^),]+)*)' # args*
814
+ r'\)'
815
+ ),
816
+ )
817
+ def _inject_unbound_method(output, matchobj):
818
+ """Replace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
819
+ """
820
+ type_cname, method_name, obj_cname, args = matchobj.groups()
821
+ type_cname = '&%s' % type_cname
822
+ args = [arg.strip() for arg in args[1:].split(',')] if args else []
823
+ assert len(args) < 3, f"CALL_UNBOUND_METHOD() does not support {len(args):d} call arguments"
824
+ return output.cached_unbound_method_call_code(
825
+ f"{Naming.modulestateglobal_cname}->",
826
+ obj_cname, type_cname, method_name, args)
827
+
828
+
829
+ @add_macro_processor(
830
+ 'PYIDENT', 'PYUNICODE',
831
+ is_module_specific=True,
832
+ regex=r'PY(IDENT|UNICODE)\("([^"]+)"\)',
833
+ )
834
+ def _inject_string_constant(output, matchobj):
835
+ """Replace 'PYIDENT("xyz")' by a constant Python identifier cname.
836
+ """
837
+ str_type, name = matchobj.groups()
838
+ return "%s->%s" % (
839
+ Naming.modulestateglobal_cname,
840
+ output.get_py_string_const(
841
+ StringEncoding.EncodedString(name), identifier=str_type == 'IDENT').cname)
842
+
843
+
844
+ @add_macro_processor(
845
+ 'EMPTY',
846
+ # As long as we use the same C access macros for these names, they are not module specific.
847
+ # is_module_specific=True,
848
+ regex=r'EMPTY\((bytes|unicode|tuple)\)',
849
+ )
850
+ def _inject_empty_collection_constant(output, matchobj):
851
+ """Replace 'EMPTY(bytes|tuple|...)' by a constant Python identifier cname.
852
+ """
853
+ type_name = matchobj.group(1)
854
+ return "%s->%s" % (
855
+ Naming.modulestateglobal_cname,
856
+ getattr(Naming, f'empty_{type_name}'))
857
+
858
+
859
+ @add_macro_processor(
860
+ 'CGLOBAL', # 'NAMED_CGLOBAL', # first is part of second and thus not needed
861
+ is_module_specific=False,
862
+ regex=r'(NAMED_)?CGLOBAL\(([^)]+)\)',
863
+ )
864
+ def _inject_cglobal(output, matchobj):
865
+ is_named, name = matchobj.groups()
866
+ if is_named:
867
+ name = getattr(Naming, name)
868
+ return f"{Naming.modulestateglobal_cname}->{name}"
869
+
870
+
871
+ @add_macro_processor()
872
+ def process_utility_ccode(utility_code, _, code_string):
873
+ """Entry point for code processors, must be defined last.
874
+ """
875
+ return code_string
876
+
877
+
878
+ def sub_tempita(s, context, file=None, name=None, __cache={}):
879
+ "Run tempita on string s with given context."
880
+ if not s:
881
+ return None
882
+
883
+ if file:
884
+ name = f"{file}:{name}"
885
+ if name:
886
+ context['__name'] = name
887
+
888
+ try:
889
+ template = __cache[s]
890
+ except KeyError:
891
+ from ..Tempita import Template
892
+ template = __cache[s] = Template(s, name=name)
893
+
894
+ return template.substitute(context)
895
+
896
+
897
+ class TempitaUtilityCode(UtilityCode):
898
+ def __init__(self, name=None, proto=None, impl=None, init=None, file=None, context=None, **kwargs):
899
+ if context is None:
900
+ context = {}
901
+ proto = sub_tempita(proto, context, file, name)
902
+ impl = sub_tempita(impl, context, file, name)
903
+ init = sub_tempita(init, context, file, name)
904
+ super().__init__(
905
+ proto, impl, init=init, name=name, file=file, **kwargs)
906
+
907
+ @classmethod
908
+ def load_cached(cls, utility_code_name, from_file=None, context=None, __cache={}):
909
+ context_key = tuple(sorted(context.items())) if context else None
910
+ assert hash(context_key) is not None # raise TypeError if not hashable
911
+ key = (cls, from_file, utility_code_name, context_key)
912
+ try:
913
+ return __cache[key]
914
+ except KeyError:
915
+ pass
916
+ code = __cache[key] = cls.load(utility_code_name, from_file, context=context)
917
+ return code
918
+
919
+ def none_or_sub(self, s, context):
920
+ """
921
+ Format a string in this utility code with context. If None, do nothing.
922
+ """
923
+ if s is None:
924
+ return None
925
+ return sub_tempita(s, context, self.file, self.name)
926
+
927
+
928
+ class LazyUtilityCode(UtilityCodeBase):
929
+ """
930
+ Utility code that calls a callback with the root code writer when
931
+ available. Useful when you only have 'env' but not 'code'.
932
+ """
933
+ __name__ = '<lazy>'
934
+ requires = None
935
+
936
+ def __init__(self, callback):
937
+ self.callback = callback
938
+
939
+ def put_code(self, globalstate):
940
+ utility = self.callback(globalstate.rootwriter)
941
+ globalstate.use_utility_code(utility)
942
+
943
+
944
+ class FunctionState:
945
+ # return_label string function return point label
946
+ # error_label string error catch point label
947
+ # error_without_exception boolean Can go to the error label without an exception (e.g. __next__ can return NULL)
948
+ # continue_label string loop continue point label
949
+ # break_label string loop break point label
950
+ # return_from_error_cleanup_label string
951
+ # label_counter integer counter for naming labels
952
+ # in_try_finally boolean inside try of try...finally
953
+ # exc_vars (string * 3) exception variables for reraise, or None
954
+ # can_trace boolean line tracing is supported in the current context
955
+ # scope Scope the scope object of the current function
956
+
957
+ # Not used for now, perhaps later
958
+ def __init__(self, owner, names_taken=set(), scope=None):
959
+ self.names_taken = names_taken
960
+ self.owner = owner
961
+ self.scope = scope
962
+
963
+ self.error_label = None
964
+ self.label_counter = 0
965
+ self.labels_used = set()
966
+ self.return_label = self.new_label()
967
+ self.new_error_label()
968
+ self.continue_label = None
969
+ self.break_label = None
970
+ self.yield_labels = []
971
+
972
+ self.in_try_finally = 0
973
+ self.exc_vars = None
974
+ self.current_except = None
975
+ self.can_trace = False
976
+ self.gil_owned = True
977
+
978
+ self.temps_allocated = [] # of (name, type, manage_ref, static)
979
+ self.temps_free = {} # (type, manage_ref) -> list of free vars with same type/managed status
980
+ self.temps_used_type = {} # name -> (type, manage_ref)
981
+ self.zombie_temps = set() # temps that must not be reused after release
982
+ self.temp_counter = 0
983
+ self.closure_temps = None
984
+
985
+ # This is used to collect temporaries, useful to find out which temps
986
+ # need to be privatized in parallel sections
987
+ self.collect_temps_stack = []
988
+
989
+ # This is used for the error indicator, which needs to be local to the
990
+ # function. It used to be global, which relies on the GIL being held.
991
+ # However, exceptions may need to be propagated through 'nogil'
992
+ # sections, in which case we introduce a race condition.
993
+ self.should_declare_error_indicator = False
994
+ self.uses_error_indicator = False
995
+
996
+ self.error_without_exception = False
997
+
998
+ self.needs_refnanny = False
999
+
1000
+ # safety checks
1001
+
1002
+ def validate_exit(self):
1003
+ # validate that all allocated temps have been freed
1004
+ if self.temps_allocated:
1005
+ leftovers = self.temps_in_use()
1006
+ if leftovers:
1007
+ msg = "TEMPGUARD: Temps left over at end of '%s': %s" % (self.scope.name, ', '.join([
1008
+ '%s [%s]' % (name, ctype)
1009
+ for name, ctype, is_pytemp in sorted(leftovers)]),
1010
+ )
1011
+ #print(msg)
1012
+ raise RuntimeError(msg)
1013
+
1014
+ # labels
1015
+
1016
+ def new_label(self, name=None):
1017
+ n: cython.size_t = self.label_counter
1018
+ self.label_counter = n + 1
1019
+ label = "%s%d" % (Naming.label_prefix, n)
1020
+ if name is not None:
1021
+ label += '_' + name
1022
+ return label
1023
+
1024
+ def new_yield_label(self, expr_type='yield'):
1025
+ label = self.new_label('resume_from_%s' % expr_type)
1026
+ num_and_label = (len(self.yield_labels) + 1, label)
1027
+ self.yield_labels.append(num_and_label)
1028
+ return num_and_label
1029
+
1030
+ def new_error_label(self, prefix=""):
1031
+ old_err_lbl = self.error_label
1032
+ self.error_label = self.new_label(prefix + 'error')
1033
+ return old_err_lbl
1034
+
1035
+ def get_loop_labels(self):
1036
+ return (
1037
+ self.continue_label,
1038
+ self.break_label)
1039
+
1040
+ def set_loop_labels(self, labels):
1041
+ (self.continue_label,
1042
+ self.break_label) = labels
1043
+
1044
+ def new_loop_labels(self, prefix=""):
1045
+ old_labels = self.get_loop_labels()
1046
+ self.set_loop_labels(
1047
+ (self.new_label(prefix + "continue"),
1048
+ self.new_label(prefix + "break")))
1049
+ return old_labels
1050
+
1051
+ def get_all_labels(self):
1052
+ return (
1053
+ self.continue_label,
1054
+ self.break_label,
1055
+ self.return_label,
1056
+ self.error_label)
1057
+
1058
+ def set_all_labels(self, labels):
1059
+ (self.continue_label,
1060
+ self.break_label,
1061
+ self.return_label,
1062
+ self.error_label) = labels
1063
+
1064
+ def all_new_labels(self):
1065
+ old_labels = self.get_all_labels()
1066
+ new_labels = []
1067
+ for old_label, name in zip(old_labels, ['continue', 'break', 'return', 'error']):
1068
+ if old_label:
1069
+ new_labels.append(self.new_label(name))
1070
+ else:
1071
+ new_labels.append(old_label)
1072
+ self.set_all_labels(new_labels)
1073
+ return old_labels
1074
+
1075
+ def use_label(self, lbl):
1076
+ self.labels_used.add(lbl)
1077
+
1078
+ def label_used(self, lbl):
1079
+ return lbl in self.labels_used
1080
+
1081
+ # temp handling
1082
+
1083
+ def allocate_temp(self, type, manage_ref, static=False, reusable=True):
1084
+ """
1085
+ Allocates a temporary (which may create a new one or get a previously
1086
+ allocated and released one of the same type). Type is simply registered
1087
+ and handed back, but will usually be a PyrexType.
1088
+
1089
+ If type.needs_refcounting, manage_ref comes into play. If manage_ref is set to
1090
+ True, the temp will be decref-ed on return statements and in exception
1091
+ handling clauses. Otherwise the caller has to deal with any reference
1092
+ counting of the variable.
1093
+
1094
+ If not type.needs_refcounting, then manage_ref will be ignored, but it
1095
+ still has to be passed. It is recommended to pass False by convention
1096
+ if it is known that type will never be a reference counted type.
1097
+
1098
+ static=True marks the temporary declaration with "static".
1099
+ This is only used when allocating backing store for a module-level
1100
+ C array literals.
1101
+
1102
+ if reusable=False, the temp will not be reused after release.
1103
+
1104
+ A C string referring to the variable is returned.
1105
+ """
1106
+ if type.is_cv_qualified and not type.is_reference:
1107
+ type = type.cv_base_type
1108
+ elif type.is_reference and not type.is_fake_reference:
1109
+ type = type.ref_base_type
1110
+ elif type.is_cfunction:
1111
+ from . import PyrexTypes
1112
+ type = PyrexTypes.c_ptr_type(type) # A function itself isn't an l-value
1113
+ elif type.is_cpp_class and not type.is_fake_reference and self.scope.directives['cpp_locals']:
1114
+ self.scope.use_utility_code(UtilityCode.load_cached("OptionalLocals", "CppSupport.cpp"))
1115
+ if not type.needs_refcounting:
1116
+ # Make manage_ref canonical, so that manage_ref will always mean
1117
+ # a decref is needed.
1118
+ manage_ref = False
1119
+
1120
+ freelist = self.temps_free.get((type, manage_ref))
1121
+ if reusable and freelist is not None and freelist[0]:
1122
+ result = freelist[0].pop()
1123
+ freelist[1].remove(result)
1124
+ else:
1125
+ while True:
1126
+ self.temp_counter += 1
1127
+ result = "%s%d" % (Naming.codewriter_temp_prefix, self.temp_counter)
1128
+ if result not in self.names_taken: break
1129
+ self.temps_allocated.append((result, type, manage_ref, static))
1130
+ if not reusable:
1131
+ self.zombie_temps.add(result)
1132
+ self.temps_used_type[result] = (type, manage_ref)
1133
+ if DebugFlags.debug_temp_code_comments:
1134
+ self.owner.putln("/* %s allocated (%s)%s */" % (result, type, "" if reusable else " - zombie"))
1135
+
1136
+ if self.collect_temps_stack:
1137
+ self.collect_temps_stack[-1].add((result, type))
1138
+
1139
+ return result
1140
+
1141
+ def release_temp(self, name):
1142
+ """
1143
+ Releases a temporary so that it can be reused by other code needing
1144
+ a temp of the same type.
1145
+ """
1146
+ type, manage_ref = self.temps_used_type[name]
1147
+ freelist = self.temps_free.get((type, manage_ref))
1148
+ if freelist is None:
1149
+ freelist = ([], set()) # keep order in list and make lookups in set fast
1150
+ self.temps_free[(type, manage_ref)] = freelist
1151
+ if name in freelist[1]:
1152
+ raise RuntimeError("Temp %s freed twice!" % name)
1153
+ if name not in self.zombie_temps:
1154
+ freelist[0].append(name)
1155
+ freelist[1].add(name)
1156
+ if DebugFlags.debug_temp_code_comments:
1157
+ self.owner.putln("/* %s released %s*/" % (
1158
+ name, " - zombie" if name in self.zombie_temps else ""))
1159
+
1160
+ def temps_in_use(self):
1161
+ """Return a list of (cname,type,manage_ref) tuples of temp names and their type
1162
+ that are currently in use.
1163
+ """
1164
+ used = []
1165
+ for name, type, manage_ref, static in self.temps_allocated:
1166
+ freelist = self.temps_free.get((type, manage_ref))
1167
+ if freelist is None or name not in freelist[1]:
1168
+ used.append((name, type, manage_ref and type.needs_refcounting))
1169
+ return used
1170
+
1171
+ def temps_holding_reference(self):
1172
+ """Return a list of (cname,type) tuples of temp names and their type
1173
+ that are currently in use. This includes only temps
1174
+ with a reference counted type which owns its reference.
1175
+ """
1176
+ return [(name, type)
1177
+ for name, type, manage_ref in self.temps_in_use()
1178
+ if manage_ref and type.needs_refcounting]
1179
+
1180
+ def all_managed_temps(self):
1181
+ """Return a list of (cname, type) tuples of refcount-managed Python objects.
1182
+ """
1183
+ return [(cname, type)
1184
+ for cname, type, manage_ref, static in self.temps_allocated
1185
+ if manage_ref]
1186
+
1187
+ def all_free_managed_temps(self):
1188
+ """Return a list of (cname, type) tuples of refcount-managed Python
1189
+ objects that are not currently in use. This is used by
1190
+ try-except and try-finally blocks to clean up temps in the
1191
+ error case.
1192
+ """
1193
+ return sorted([ # Enforce deterministic order.
1194
+ (cname, type)
1195
+ for (type, manage_ref), freelist in self.temps_free.items() if manage_ref
1196
+ for cname in freelist[0]
1197
+ ])
1198
+
1199
+ def start_collecting_temps(self):
1200
+ """
1201
+ Useful to find out which temps were used in a code block
1202
+ """
1203
+ self.collect_temps_stack.append(set())
1204
+
1205
+ def stop_collecting_temps(self):
1206
+ return self.collect_temps_stack.pop()
1207
+
1208
+ def init_closure_temps(self, scope):
1209
+ self.closure_temps = ClosureTempAllocator(scope)
1210
+
1211
+
1212
+ class NumConst:
1213
+ """Global info about a Python number constant held by GlobalState.
1214
+
1215
+ cname string
1216
+ value string
1217
+ py_type string int, long, float
1218
+ value_code string evaluation code if different from value
1219
+ """
1220
+
1221
+ def __init__(self, cname, value, py_type, value_code=None):
1222
+ self.cname = cname
1223
+ self.value = value
1224
+ self.py_type = py_type
1225
+ self.value_code = value_code or value
1226
+
1227
+
1228
+ class PyObjectConst:
1229
+ """Global info about a generic constant held by GlobalState.
1230
+ """
1231
+ # cname string
1232
+ # type PyrexType
1233
+
1234
+ def __init__(self, cname, type):
1235
+ self.cname = cname
1236
+ self.type = type
1237
+
1238
+
1239
+ cython.declare(possible_unicode_identifier=object, possible_bytes_identifier=object,
1240
+ replace_identifier=object, find_alphanums=object)
1241
+ possible_unicode_identifier = re.compile(r"(?![0-9])\w+$", re.U).match
1242
+ possible_bytes_identifier = re.compile(br"(?![0-9])\w+$").match
1243
+ replace_identifier = re.compile(r'[^a-zA-Z0-9_]+').sub
1244
+ find_alphanums = re.compile('([a-zA-Z0-9]+)').findall
1245
+
1246
+ class StringConst:
1247
+ """Global info about a C string constant held by GlobalState.
1248
+ """
1249
+ # cname string
1250
+ # text EncodedString or BytesLiteral
1251
+ # py_strings {(identifier, encoding) : PyStringConst}
1252
+
1253
+ def __init__(self, cname, text, byte_string):
1254
+ self.cname = cname
1255
+ self.text = text
1256
+ self.escaped_value = StringEncoding.escape_byte_string(byte_string)
1257
+ self.py_strings = None
1258
+
1259
+ def get_py_string_const(self, encoding, identifier=None):
1260
+ text = self.text
1261
+ intern: cython.bint
1262
+ is_unicode: cython.bint
1263
+
1264
+ if identifier or encoding is None:
1265
+ # unicode string
1266
+ encoding = encoding_key = None
1267
+ is_unicode = True
1268
+ else:
1269
+ # bytes
1270
+ is_unicode = False
1271
+ encoding = encoding.lower()
1272
+ if encoding in ('utf8', 'utf-8', 'ascii', 'usascii', 'us-ascii'):
1273
+ encoding = None
1274
+ encoding_key = None
1275
+ else:
1276
+ encoding_key = ''.join(find_alphanums(encoding))
1277
+
1278
+ if identifier:
1279
+ intern = True
1280
+ elif identifier is None:
1281
+ if isinstance(text, bytes):
1282
+ intern = bool(possible_bytes_identifier(text))
1283
+ else:
1284
+ intern = bool(possible_unicode_identifier(text))
1285
+ else:
1286
+ intern = False
1287
+
1288
+ key = (intern, is_unicode, encoding_key)
1289
+ if self.py_strings is None:
1290
+ self.py_strings = {}
1291
+ else:
1292
+ try:
1293
+ return self.py_strings[key]
1294
+ except KeyError:
1295
+ pass
1296
+
1297
+ pystring_cname = (
1298
+ f"{Naming.interned_prefixes['str'] if intern else Naming.py_const_prefix}"
1299
+ f"{'u' if is_unicode else 'b'}"
1300
+ f"{'_' + encoding_key if encoding_key else ''}"
1301
+ f"_{self.cname[len(Naming.const_prefix):]}"
1302
+ )
1303
+
1304
+ py_string = PyStringConst(pystring_cname, encoding, intern, is_unicode)
1305
+ self.py_strings[key] = py_string
1306
+ return py_string
1307
+
1308
+
1309
+ class PyStringConst:
1310
+ """Global info about a Python string constant held by GlobalState.
1311
+ """
1312
+ # cname string
1313
+ # encoding string
1314
+ # intern boolean
1315
+ # is_unicode boolean
1316
+
1317
+ def __init__(self, cname, encoding, intern=False, is_unicode=False):
1318
+ self.cname = cname
1319
+ self.encoding = encoding
1320
+ self.is_unicode = is_unicode
1321
+ self.intern = intern
1322
+
1323
+ def __lt__(self, other):
1324
+ return self.cname < other.cname
1325
+
1326
+
1327
+ class GlobalState:
1328
+ # filename_table {string : int} for finding filename table indexes
1329
+ # filename_list [string] filenames in filename table order
1330
+ # input_file_contents dict contents (=list of lines) of any file that was used as input
1331
+ # to create this output C code. This is
1332
+ # used to annotate the comments.
1333
+ #
1334
+ # utility_codes set IDs of used utility code (to avoid reinsertion)
1335
+ #
1336
+ # declared_cnames {string:Entry} used in a transition phase to merge pxd-declared
1337
+ # constants etc. into the pyx-declared ones (i.e,
1338
+ # check if constants are already added).
1339
+ # In time, hopefully the literals etc. will be
1340
+ # supplied directly instead.
1341
+ #
1342
+ # const_cnames_used dict global counter for unique constant identifiers
1343
+ #
1344
+
1345
+ # parts {string:CCodeWriter}
1346
+
1347
+
1348
+ # interned_strings
1349
+ # consts
1350
+ # interned_nums
1351
+
1352
+ # directives set Temporary variable used to track
1353
+ # the current set of directives in the code generation
1354
+ # process.
1355
+
1356
+ directives = {}
1357
+
1358
+ code_layout = [
1359
+ 'h_code',
1360
+ 'filename_table',
1361
+ 'utility_code_proto_before_types',
1362
+ 'numeric_typedefs', # Let these detailed individual parts stay!,
1363
+ 'complex_type_declarations', # as the proper solution is to make a full DAG...
1364
+ 'type_declarations', # More coarse-grained blocks would simply hide
1365
+ 'utility_code_proto', # the ugliness, not fix it
1366
+ 'module_declarations',
1367
+ 'typeinfo',
1368
+ 'before_global_var',
1369
+ 'global_var',
1370
+ 'string_decls',
1371
+ 'decls',
1372
+ 'late_includes',
1373
+ 'module_state',
1374
+ 'module_state_contents', # can be used to inject declarations into the modulestate struct
1375
+ 'module_state_end',
1376
+ 'constant_name_defines',
1377
+ 'module_state_clear',
1378
+ 'module_state_traverse',
1379
+ 'module_code', # user code goes here
1380
+ 'module_exttypes',
1381
+ 'initfunc_declarations',
1382
+ 'init_module',
1383
+ 'pystring_table',
1384
+ 'cached_builtins',
1385
+ 'cached_constants',
1386
+ 'init_constants',
1387
+ 'init_codeobjects',
1388
+ 'init_globals', # (utility code called at init-time)
1389
+ 'cleanup_globals',
1390
+ 'cleanup_module',
1391
+ 'main_method',
1392
+ 'utility_code_pragmas', # silence some irrelevant warnings in utility code
1393
+ 'utility_code_def',
1394
+ 'utility_code_pragmas_end', # clean-up the utility_code_pragmas
1395
+ 'end'
1396
+ ]
1397
+
1398
+ # h files can only have a much smaller list of sections
1399
+ h_code_layout = [
1400
+ 'h_code',
1401
+ 'utility_code_proto_before_types',
1402
+ 'type_declarations',
1403
+ 'utility_code_proto',
1404
+ 'end'
1405
+ ]
1406
+
1407
+ def __init__(self, writer, module_node, code_config, common_utility_include_dir=None):
1408
+ self.filename_table = {}
1409
+ self.filename_list = []
1410
+ self.input_file_contents = {}
1411
+ self.utility_codes = set()
1412
+ self.declared_cnames = {}
1413
+ self.in_utility_code_generation = False
1414
+ self.code_config = code_config
1415
+ self.common_utility_include_dir = common_utility_include_dir
1416
+ self.parts = {}
1417
+ self.module_node = module_node # because some utility code generation needs it
1418
+ # (generating backwards-compatible Get/ReleaseBuffer
1419
+
1420
+ self.const_cnames_used = {}
1421
+ self.string_const_index = {}
1422
+ self.dedup_const_index = {}
1423
+ self.pyunicode_ptr_const_index = {}
1424
+ self.codeobject_constants = []
1425
+ self.num_const_index = {}
1426
+ self.arg_default_constants = []
1427
+ self.const_array_counters = {} # counts of differently prefixed arrays of constants
1428
+ self.cached_cmethods = {}
1429
+ self.initialised_constants = set()
1430
+
1431
+ writer.set_global_state(self)
1432
+ self.rootwriter = writer
1433
+
1434
+ def initialize_main_c_code(self):
1435
+ rootwriter = self.rootwriter
1436
+ for i, part in enumerate(self.code_layout):
1437
+ w = self.parts[part] = rootwriter.insertion_point()
1438
+ if i > 0:
1439
+ w.putln("/* #### Code section: %s ### */" % part)
1440
+
1441
+ if not Options.cache_builtins:
1442
+ del self.parts['cached_builtins']
1443
+ else:
1444
+ w = self.parts['cached_builtins']
1445
+ w.start_initcfunc(
1446
+ "int __Pyx_InitCachedBuiltins("
1447
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})")
1448
+ w.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
1449
+
1450
+ w = self.parts['cached_constants']
1451
+ w.start_initcfunc(
1452
+ "int __Pyx_InitCachedConstants("
1453
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})",
1454
+ refnanny=True)
1455
+ w.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
1456
+ w.put_setup_refcount_context(StringEncoding.EncodedString("__Pyx_InitCachedConstants"))
1457
+
1458
+ w = self.parts['init_globals']
1459
+ w.start_initcfunc("int __Pyx_InitGlobals(void)")
1460
+
1461
+ w = self.parts['init_constants']
1462
+ w.start_initcfunc(
1463
+ "int __Pyx_InitConstants("
1464
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})")
1465
+ w.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
1466
+
1467
+ if not Options.generate_cleanup_code:
1468
+ del self.parts['cleanup_globals']
1469
+ else:
1470
+ w = self.parts['cleanup_globals']
1471
+ w.start_initcfunc(
1472
+ "void __Pyx_CleanupGlobals("
1473
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})")
1474
+ w.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
1475
+
1476
+ code = self.parts['utility_code_proto']
1477
+ code.putln("")
1478
+ code.putln("/* --- Runtime support code (head) --- */")
1479
+
1480
+ code = self.parts['utility_code_def']
1481
+ if self.code_config.emit_linenums:
1482
+ code.write('\n#line 1 "cython_utility"\n')
1483
+ code.putln("")
1484
+ code.putln("/* --- Runtime support code --- */")
1485
+
1486
+ def initialize_main_h_code(self):
1487
+ rootwriter = self.rootwriter
1488
+ for part in self.h_code_layout:
1489
+ self.parts[part] = rootwriter.insertion_point()
1490
+
1491
+ def finalize_main_c_code(self):
1492
+ self.close_global_decls()
1493
+
1494
+ #
1495
+ # utility_code_def
1496
+ #
1497
+ code = self.parts['utility_code_def']
1498
+ util = TempitaUtilityCode.load_cached("TypeConversions", "TypeConversion.c")
1499
+ code.put(util.format_code(util.impl))
1500
+ code.putln("")
1501
+
1502
+ #
1503
+ # utility code pragmas
1504
+ #
1505
+ code = self.parts['utility_code_pragmas']
1506
+ util = UtilityCode.load_cached("UtilityCodePragmas", "ModuleSetupCode.c")
1507
+ code.putln(util.format_code(util.impl))
1508
+ code.putln("")
1509
+ code = self.parts['utility_code_pragmas_end']
1510
+ util = UtilityCode.load_cached("UtilityCodePragmasEnd", "ModuleSetupCode.c")
1511
+ code.putln(util.format_code(util.impl))
1512
+ code.putln("")
1513
+
1514
+ def __getitem__(self, key):
1515
+ return self.parts[key]
1516
+
1517
+ #
1518
+ # Global constants, interned objects, etc.
1519
+ #
1520
+ def close_global_decls(self):
1521
+ # This is called when it is known that no more global declarations will
1522
+ # declared.
1523
+ self.generate_const_declarations()
1524
+ if Options.cache_builtins:
1525
+ w = self.parts['cached_builtins']
1526
+ w.putln("return 0;")
1527
+ if w.label_used(w.error_label):
1528
+ w.put_label(w.error_label)
1529
+ w.putln("return -1;")
1530
+ w.putln("}")
1531
+ w.exit_cfunc_scope()
1532
+
1533
+ w = self.parts['cached_constants']
1534
+ w.put_finish_refcount_context()
1535
+ w.putln("return 0;")
1536
+ if w.label_used(w.error_label):
1537
+ w.put_label(w.error_label)
1538
+ w.put_finish_refcount_context()
1539
+ w.putln("return -1;")
1540
+ w.putln("}")
1541
+ w.exit_cfunc_scope()
1542
+
1543
+ for part in ['init_globals', 'init_constants']:
1544
+ w = self.parts[part]
1545
+ w.putln("return 0;")
1546
+ if w.label_used(w.error_label):
1547
+ w.put_label(w.error_label)
1548
+ w.putln("return -1;")
1549
+ w.putln("}")
1550
+ w.exit_cfunc_scope()
1551
+
1552
+ if Options.generate_cleanup_code:
1553
+ w = self.parts['cleanup_globals']
1554
+ w.putln("}")
1555
+ w.exit_cfunc_scope()
1556
+
1557
+ if Options.generate_cleanup_code:
1558
+ w = self.parts['cleanup_module']
1559
+ w.putln("}")
1560
+ w.exit_cfunc_scope()
1561
+
1562
+ def put_pyobject_decl(self, entry):
1563
+ self['global_var'].putln("static PyObject *%s;" % entry.cname)
1564
+
1565
+ # constant handling at code generation time
1566
+
1567
+ def get_cached_constants_writer(self, target=None):
1568
+ if target is not None:
1569
+ if target in self.initialised_constants:
1570
+ # Return None on second/later calls to prevent duplicate creation code.
1571
+ return None
1572
+ self.initialised_constants.add(target)
1573
+ return self.parts['cached_constants']
1574
+
1575
+ def get_int_const(self, str_value, longness=False):
1576
+ py_type = longness and 'long' or 'int'
1577
+ try:
1578
+ c = self.num_const_index[(str_value, py_type)]
1579
+ except KeyError:
1580
+ c = self.new_num_const(str_value, py_type)
1581
+ return c
1582
+
1583
+ def get_float_const(self, str_value, value_code):
1584
+ try:
1585
+ c = self.num_const_index[(str_value, 'float')]
1586
+ except KeyError:
1587
+ c = self.new_num_const(str_value, 'float', value_code)
1588
+ return c
1589
+
1590
+ def get_py_const(self, prefix, dedup_key=None):
1591
+ if dedup_key is not None:
1592
+ const = self.dedup_const_index.get(dedup_key)
1593
+ if const is not None:
1594
+ return const
1595
+ const = self.new_array_const_cname(prefix)
1596
+ if dedup_key is not None:
1597
+ self.dedup_const_index[dedup_key] = const
1598
+ return const
1599
+
1600
+ def get_argument_default_const(self, type):
1601
+ cname = self.new_const_cname('')
1602
+ c = PyObjectConst(cname, type)
1603
+ self.arg_default_constants.append(c)
1604
+ # Argument default constants aren't currently cleaned up.
1605
+ # If that changes, it needs to account for the fact that they
1606
+ # aren't just Python objects
1607
+ return c
1608
+
1609
+ def get_string_const(self, text):
1610
+ # return a C string constant, creating a new one if necessary
1611
+ if text.is_unicode:
1612
+ byte_string = text.utf8encode()
1613
+ else:
1614
+ byte_string = text.byteencode()
1615
+ try:
1616
+ c = self.string_const_index[byte_string]
1617
+ except KeyError:
1618
+ c = self.new_string_const(text, byte_string)
1619
+ return c
1620
+
1621
+ def get_pyunicode_ptr_const(self, text):
1622
+ # return a Py_UNICODE[] constant, creating a new one if necessary
1623
+ assert text.is_unicode
1624
+ try:
1625
+ c = self.pyunicode_ptr_const_index[text]
1626
+ except KeyError:
1627
+ c = self.pyunicode_ptr_const_index[text] = self.new_const_cname()
1628
+ return c
1629
+
1630
+ def get_py_string_const(self, text, identifier=None):
1631
+ # return a Python string constant, creating a new one if necessary
1632
+ c_string = self.get_string_const(text)
1633
+ py_string = c_string.get_py_string_const(text.encoding, identifier)
1634
+ return py_string
1635
+
1636
+ def get_py_codeobj_const(self, node):
1637
+ idx = len(self.codeobject_constants)
1638
+ name = f"{Naming.codeobjtab_cname}[{idx}]"
1639
+ self.codeobject_constants.append(node)
1640
+ return name
1641
+
1642
+ def get_interned_identifier(self, text):
1643
+ return self.get_py_string_const(text, identifier=True)
1644
+
1645
+ def new_string_const(self, text, byte_string):
1646
+ cname = self.new_string_const_cname(byte_string)
1647
+ c = StringConst(cname, text, byte_string)
1648
+ self.string_const_index[byte_string] = c
1649
+ return c
1650
+
1651
+ def new_num_const(self, value, py_type, value_code=None):
1652
+ cname = self.new_num_const_cname(value, py_type)
1653
+ c = NumConst(cname, value, py_type, value_code)
1654
+ self.num_const_index[(value, py_type)] = c
1655
+ return c
1656
+
1657
+ def new_string_const_cname(self, bytes_value):
1658
+ # Create a new globally-unique nice name for a C string constant.
1659
+ value = bytes_value.decode('ASCII', 'ignore')
1660
+ return self.new_const_cname(value=value)
1661
+
1662
+ def unique_const_cname(self, format_str): # type: (str) -> str
1663
+ used = self.const_cnames_used
1664
+ cname = value = format_str.format(sep='', counter='')
1665
+ while cname in used:
1666
+ counter = used[value] = used[value] + 1
1667
+ cname = format_str.format(sep='_', counter=counter)
1668
+ used[cname] = 1
1669
+ return cname
1670
+
1671
+ def new_num_const_cname(self, value, py_type): # type: (str, str) -> str
1672
+ if py_type == 'long':
1673
+ value += 'L'
1674
+ py_type = 'int'
1675
+ prefix = Naming.interned_prefixes[py_type]
1676
+
1677
+ value = value.replace('.', '_').replace('+', '_').replace('-', 'neg_')
1678
+ if len(value) > 42:
1679
+ # update tests/run/large_integer_T5290.py in case the amount is changed
1680
+ cname = self.unique_const_cname(
1681
+ prefix + "large{counter}_" + value[:18] + "_xxx_" + value[-18:])
1682
+ else:
1683
+ cname = "%s%s" % (prefix, value)
1684
+ return cname
1685
+
1686
+ def new_const_cname(self, prefix='', value=''):
1687
+ value = replace_identifier('_', value)[:32].strip('_')
1688
+ name_suffix = self.unique_const_cname(value + "{sep}{counter}")
1689
+ if prefix:
1690
+ prefix = Naming.interned_prefixes[prefix]
1691
+ else:
1692
+ prefix = Naming.const_prefix
1693
+ return "%s%s" % (prefix, name_suffix)
1694
+
1695
+ def new_array_const_cname(self, prefix: str):
1696
+ count = self.const_array_counters.get(prefix, 0)
1697
+ self.const_array_counters[prefix] = count+1
1698
+ return f"{Naming.pyrex_prefix}{prefix}[{count}]"
1699
+
1700
+ def get_cached_unbound_method(self, type_cname, method_name):
1701
+ key = (type_cname, method_name)
1702
+ try:
1703
+ cname = self.cached_cmethods[key]
1704
+ except KeyError:
1705
+ cname = self.cached_cmethods[key] = self.new_const_cname(
1706
+ 'umethod', '%s_%s' % (type_cname, method_name))
1707
+ return cname
1708
+
1709
+ def cached_unbound_method_call_code(self, modulestate_cname, obj_cname, type_cname, method_name, arg_cnames):
1710
+ # admittedly, not the best place to put this method, but it is reused by UtilityCode and ExprNodes ...
1711
+ utility_code_name = "CallUnboundCMethod%d" % len(arg_cnames)
1712
+ self.use_utility_code(UtilityCode.load_cached(utility_code_name, "ObjectHandling.c"))
1713
+ cache_cname = self.get_cached_unbound_method(type_cname, method_name)
1714
+ args = [obj_cname] + arg_cnames
1715
+ return "__Pyx_%s(&%s%s, %s)" % (
1716
+ utility_code_name,
1717
+ modulestate_cname,
1718
+ cache_cname,
1719
+ ', '.join(args),
1720
+ )
1721
+
1722
+ def add_cached_builtin_decl(self, entry):
1723
+ if entry.is_builtin and entry.is_const:
1724
+ if self.should_declare(entry.cname, entry):
1725
+ self.put_pyobject_decl(entry)
1726
+ name = entry.name
1727
+ if name in renamed_py2_builtins_map:
1728
+ name = renamed_py2_builtins_map[name]
1729
+ self.put_cached_builtin_init(
1730
+ entry.pos, StringEncoding.EncodedString(name),
1731
+ entry.cname)
1732
+
1733
+ def put_cached_builtin_init(self, pos, name, cname):
1734
+ w = self.parts['cached_builtins']
1735
+ cname_in_modulestate = w.name_in_main_c_code_module_state(
1736
+ self.get_interned_identifier(name).cname)
1737
+ self.use_utility_code(
1738
+ UtilityCode.load_cached("GetBuiltinName", "ObjectHandling.c"))
1739
+ w.putln('%s = __Pyx_GetBuiltinName(%s); if (!%s) %s' % (
1740
+ cname,
1741
+ cname_in_modulestate,
1742
+ cname,
1743
+ w.error_goto(pos)))
1744
+
1745
+ def generate_const_declarations(self):
1746
+ self.generate_cached_methods_decls()
1747
+ self.generate_object_constant_decls()
1748
+ self.generate_codeobject_constants()
1749
+ # generate code for string and numeric constants as late as possible
1750
+ # to allow new constants be to created by the earlier stages.
1751
+ # (although the constants themselves are written early)
1752
+ self.generate_string_constants()
1753
+ self.generate_num_constants()
1754
+
1755
+ def _generate_module_array_traverse_and_clear(self, struct_attr_cname, count, may_have_refcycles=True):
1756
+ counter_type = 'int' if count < 2**15 else 'Py_ssize_t'
1757
+ visit_call = "Py_VISIT" if may_have_refcycles else "__Pyx_VISIT_CONST"
1758
+
1759
+ writer = self.parts['module_state_traverse']
1760
+ writer.putln(f"for ({counter_type} i=0; i<{count}; ++i) {{ {visit_call}(traverse_module_state->{struct_attr_cname}[i]); }}")
1761
+
1762
+ writer = self.parts['module_state_clear']
1763
+ writer.putln(f"for ({counter_type} i=0; i<{count}; ++i) {{ Py_CLEAR(clear_module_state->{struct_attr_cname}[i]); }}")
1764
+
1765
+ def generate_object_constant_decls(self):
1766
+ consts = [(len(c.cname), c.cname, c)
1767
+ for c in self.arg_default_constants]
1768
+ consts.sort()
1769
+ for _, cname, c in consts:
1770
+ self.parts['module_state'].putln("%s;" % c.type.declaration_code(cname))
1771
+ if not c.type.needs_refcounting:
1772
+ # Note that py_constants is used for all argument defaults
1773
+ # which aren't necessarily PyObjects, so aren't appropriate
1774
+ # to clear.
1775
+ continue
1776
+
1777
+ self.parts['module_state_clear'].put_xdecref_clear(
1778
+ f"clear_module_state->{cname}",
1779
+ c.type,
1780
+ clear_before_decref=True,
1781
+ nanny=False,
1782
+ )
1783
+
1784
+ if c.type.is_memoryviewslice:
1785
+ # TODO: Implement specific to type like CodeWriter.put_xdecref_clear()
1786
+ cname += "->memview"
1787
+
1788
+ self.parts['module_state_traverse'].putln(
1789
+ f"Py_VISIT(traverse_module_state->{cname});")
1790
+
1791
+ for prefix, count in sorted(self.const_array_counters.items()):
1792
+ struct_attr_cname = f"{Naming.pyrex_prefix}{prefix}"
1793
+ self.parts['module_state'].putln(f"PyObject *{struct_attr_cname}[{count}];")
1794
+
1795
+ # The constant tuples/slices that we create can never participate in reference cycles.
1796
+ self._generate_module_array_traverse_and_clear(struct_attr_cname, count, may_have_refcycles=False)
1797
+
1798
+ cleanup_level = cleanup_level_for_type_prefix(prefix)
1799
+ if cleanup_level is not None and cleanup_level <= Options.generate_cleanup_code:
1800
+ part_writer = self.parts['cleanup_globals']
1801
+ part_writer.put(f"for (size_t i=0; i<{count}; ++i) ")
1802
+ part_writer.putln(
1803
+ "{ Py_CLEAR(%s); }" %
1804
+ part_writer.name_in_main_c_code_module_state(f"{struct_attr_cname}[i]")
1805
+ )
1806
+
1807
+ def generate_cached_methods_decls(self):
1808
+ if not self.cached_cmethods:
1809
+ return
1810
+
1811
+ decl = self.parts['module_state']
1812
+ init = self.parts['init_constants']
1813
+ cnames = []
1814
+ for (type_cname, method_name), cname in sorted(self.cached_cmethods.items()):
1815
+ cnames.append(cname)
1816
+ method_name_cname = self.get_interned_identifier(StringEncoding.EncodedString(method_name)).cname
1817
+ decl.putln('__Pyx_CachedCFunction %s;' % (
1818
+ cname))
1819
+ # split type reference storage as it might not be static
1820
+ init.putln('%s.type = (PyObject*)%s;' % (
1821
+ init.name_in_main_c_code_module_state(cname), type_cname))
1822
+ # method name string isn't static in limited api
1823
+ init.putln(
1824
+ f'{init.name_in_main_c_code_module_state(cname)}.method_name = '
1825
+ f'&{init.name_in_main_c_code_module_state(method_name_cname)};')
1826
+
1827
+ if Options.generate_cleanup_code:
1828
+ cleanup = self.parts['cleanup_globals']
1829
+ for cname in cnames:
1830
+ cleanup.putln(f"Py_CLEAR({init.name_in_main_c_code_module_state(cname)}.method);")
1831
+
1832
+ def generate_string_constants(self):
1833
+ c_consts = [(len(c.cname), c.cname, c) for c in self.string_const_index.values()]
1834
+ c_consts.sort()
1835
+ py_strings = []
1836
+ longest_pystring = 0
1837
+ encodings = set()
1838
+
1839
+ def normalise_encoding_name(py_string):
1840
+ if py_string.encoding and py_string.encoding not in (
1841
+ 'ASCII', 'USASCII', 'US-ASCII', 'UTF8', 'UTF-8'):
1842
+ return f'"{py_string.encoding.lower()}"'
1843
+ else:
1844
+ return '0'
1845
+
1846
+ decls_writer = self.parts['string_decls']
1847
+ for _, cname, c in c_consts:
1848
+ cliteral = StringEncoding.split_string_literal(c.escaped_value)
1849
+ decls_writer.putln(
1850
+ f'static const char {cname}[] = "{cliteral}";',
1851
+ safe=True) # Braces in user strings are not for indentation.
1852
+ if c.py_strings is not None:
1853
+ if len(c.escaped_value) > longest_pystring:
1854
+ # This is not an accurate count since it adds up C escape characters,
1855
+ # but it's probably good enough for an upper bound.
1856
+ longest_pystring = len(c.escaped_value)
1857
+ for py_string in c.py_strings.values():
1858
+ encodings.add(normalise_encoding_name(py_string))
1859
+ py_strings.append((c.cname, len(py_string.cname), py_string))
1860
+
1861
+ for c, cname in sorted(self.pyunicode_ptr_const_index.items()):
1862
+ utf16_array, utf32_array = StringEncoding.encode_pyunicode_string(c)
1863
+ if utf16_array:
1864
+ # Narrow and wide representations differ
1865
+ decls_writer.putln("#ifdef Py_UNICODE_WIDE")
1866
+ decls_writer.putln("static Py_UNICODE %s[] = { %s };" % (cname, utf32_array))
1867
+ if utf16_array:
1868
+ decls_writer.putln("#else")
1869
+ decls_writer.putln("static Py_UNICODE %s[] = { %s };" % (cname, utf16_array))
1870
+ decls_writer.putln("#endif")
1871
+
1872
+ if not py_strings:
1873
+ return
1874
+
1875
+ py_strings.sort()
1876
+
1877
+ w = self.parts['pystring_table']
1878
+ w.putln("")
1879
+
1880
+ # We use only type size macros from "pyport.h" here.
1881
+ w.put(textwrap.dedent("""\
1882
+ typedef struct {
1883
+ const char *s;
1884
+ #if %(max_length)d <= 65535
1885
+ const unsigned short n;
1886
+ #elif %(max_length)d / 2 < INT_MAX
1887
+ const unsigned int n;
1888
+ #elif %(max_length)d / 2 < LONG_MAX
1889
+ const unsigned long n;
1890
+ #else
1891
+ const Py_ssize_t n;
1892
+ #endif
1893
+ #if %(num_encodings)d <= 31
1894
+ const unsigned int encoding : 5;
1895
+ #elif %(num_encodings)d <= 255
1896
+ const unsigned char encoding;
1897
+ #elif %(num_encodings)d <= 65535
1898
+ const unsigned short encoding;
1899
+ #else
1900
+ const Py_ssize_t encoding;
1901
+ #endif
1902
+ const unsigned int is_unicode : 1;
1903
+ const unsigned int intern : 1;
1904
+ } __Pyx_StringTabEntry;
1905
+ """ % dict(
1906
+ max_length=longest_pystring,
1907
+ num_encodings=len(encodings),
1908
+ )))
1909
+
1910
+ py_string_count = len(py_strings)
1911
+ self.parts['module_state'].putln(f"PyObject *{Naming.stringtab_cname}[{py_string_count}];")
1912
+ self._generate_module_array_traverse_and_clear(Naming.stringtab_cname, py_string_count, may_have_refcycles=False)
1913
+
1914
+ encodings = sorted(encodings)
1915
+ encodings.sort(key=len) # stable sort to make sure '0' comes first, index 0
1916
+ assert not encodings or '0' not in encodings or encodings[0] == '0', encodings
1917
+ encodings_map = {encoding: i for i, encoding in enumerate(encodings)}
1918
+ w.putln("static const char * const %s[] = { %s };" % (
1919
+ Naming.stringtab_encodings_cname,
1920
+ ', '.join(encodings),
1921
+ ))
1922
+
1923
+ w.putln("static const __Pyx_StringTabEntry %s[] = {" % Naming.stringtab_cname)
1924
+ for n, (c_cname, _, py_string) in enumerate(py_strings):
1925
+ encodings_index = encodings_map[normalise_encoding_name(py_string)]
1926
+ is_unicode = py_string.is_unicode
1927
+
1928
+ self.parts['constant_name_defines'].putln("#define %s %s[%s]" % (
1929
+ py_string.cname,
1930
+ Naming.stringtab_cname,
1931
+ n))
1932
+
1933
+ w.putln("{%s, sizeof(%s), %d, %d, %d}, /* PyObject cname: %s */" % (
1934
+ c_cname,
1935
+ c_cname,
1936
+ encodings_index,
1937
+ is_unicode,
1938
+ py_string.intern,
1939
+ py_string.cname
1940
+ ))
1941
+ w.putln("{0, 0, 0, 0, 0}")
1942
+ w.putln("};")
1943
+
1944
+ self.use_utility_code(UtilityCode.load_cached("InitStrings", "StringTools.c"))
1945
+
1946
+ init_constants = self.parts['init_constants']
1947
+ init_constants.putln(
1948
+ "if (__Pyx_InitStrings(%s, %s, %s) < 0) %s;" % (
1949
+ Naming.stringtab_cname,
1950
+ init_constants.name_in_main_c_code_module_state(Naming.stringtab_cname),
1951
+ Naming.stringtab_encodings_cname,
1952
+ init_constants.error_goto(self.module_pos)))
1953
+
1954
+ def generate_codeobject_constants(self):
1955
+ w = self.parts['init_codeobjects']
1956
+ init_function = (
1957
+ f"int __Pyx_CreateCodeObjects({Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})"
1958
+ )
1959
+
1960
+ if not self.codeobject_constants:
1961
+ w.start_initcfunc(init_function)
1962
+ w.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
1963
+ w.putln("return 0;")
1964
+ w.exit_cfunc_scope()
1965
+ w.putln("}")
1966
+ return
1967
+
1968
+ # Create a downsized config struct and build code objects from it.
1969
+ max_flags = 0x3ff # to be adapted when we start using new flags
1970
+ max_func_args = 1
1971
+ max_kwonly_args = 1
1972
+ max_posonly_args = 1
1973
+ max_vars = 1
1974
+ max_line = 1
1975
+ max_positions = 1
1976
+ for node in self.codeobject_constants:
1977
+ def_node = node.def_node
1978
+ if not def_node.is_generator_expression:
1979
+ max_func_args = max(max_func_args, len(def_node.args) - def_node.num_kwonly_args)
1980
+ max_kwonly_args = max(max_kwonly_args, def_node.num_kwonly_args)
1981
+ max_posonly_args = max(max_posonly_args, def_node.num_posonly_args)
1982
+ max_vars = max(max_vars, len(node.varnames))
1983
+ max_line = max(max_line, def_node.pos[1])
1984
+ max_positions = max(max_positions, len(def_node.node_positions))
1985
+
1986
+ # Even for full 64-bit line/column values, one entry in the line table can never be larger than 45 bytes.
1987
+ max_linetable_len = max_positions * 47
1988
+
1989
+ w.put(textwrap.dedent(f"""\
1990
+ typedef struct {{
1991
+ unsigned int argcount : {max_func_args.bit_length()};
1992
+ unsigned int num_posonly_args : {max_posonly_args.bit_length()};
1993
+ unsigned int num_kwonly_args : {max_kwonly_args.bit_length()};
1994
+ unsigned int nlocals : {max_vars.bit_length()};
1995
+ unsigned int flags : {max_flags.bit_length()};
1996
+ unsigned int first_line : {max_line.bit_length()};
1997
+ unsigned int line_table_length : {max_linetable_len.bit_length()};
1998
+ }} __Pyx_PyCode_New_function_description;
1999
+ """))
2000
+
2001
+ self.use_utility_code(UtilityCode.load_cached("NewCodeObj", "ModuleSetupCode.c"))
2002
+
2003
+ w.start_initcfunc(init_function)
2004
+
2005
+ w.putln("PyObject* tuple_dedup_map = PyDict_New();")
2006
+ w.putln("if (unlikely(!tuple_dedup_map)) return -1;")
2007
+
2008
+ for node in self.codeobject_constants:
2009
+ node.generate_codeobj(w, "bad")
2010
+
2011
+ w.putln("Py_DECREF(tuple_dedup_map);")
2012
+ w.putln("return 0;")
2013
+
2014
+ w.putln("bad:")
2015
+ w.putln("Py_DECREF(tuple_dedup_map);")
2016
+ w.putln("return -1;")
2017
+ w.exit_cfunc_scope()
2018
+ w.putln("}")
2019
+
2020
+ code_object_count = len(self.codeobject_constants)
2021
+ self.parts['module_state'].putln(f"PyObject *{Naming.codeobjtab_cname}[{code_object_count}];")
2022
+ # The code objects that we generate only contain plain constants and can never participate in reference cycles.
2023
+ self._generate_module_array_traverse_and_clear(Naming.codeobjtab_cname, code_object_count, may_have_refcycles=False)
2024
+
2025
+ def generate_num_constants(self):
2026
+ consts = [(c.py_type, c.value[0] == '-', len(c.value), c.value, c.value_code, c)
2027
+ for c in self.num_const_index.values()]
2028
+ consts.sort()
2029
+ init_constants = self.parts['init_constants']
2030
+ for py_type, _, _, value, value_code, c in consts:
2031
+ cname = c.cname
2032
+ self.parts['module_state'].putln("PyObject *%s;" % cname)
2033
+ self.parts['module_state_clear'].putln(
2034
+ "Py_CLEAR(clear_module_state->%s);" % cname)
2035
+ self.parts['module_state_traverse'].putln(
2036
+ "__Pyx_VISIT_CONST(traverse_module_state->%s);" % cname)
2037
+ if py_type == 'float':
2038
+ function = 'PyFloat_FromDouble(%s)'
2039
+ elif py_type == 'long':
2040
+ function = 'PyLong_FromString("%s", 0, 0)'
2041
+ elif Utils.long_literal(value):
2042
+ function = 'PyLong_FromString("%s", 0, 0)'
2043
+ elif len(value.lstrip('-')) > 4:
2044
+ function = "PyLong_FromLong(%sL)"
2045
+ else:
2046
+ function = "PyLong_FromLong(%s)"
2047
+ init_cname = init_constants.name_in_main_c_code_module_state(cname)
2048
+ init_constants.putln('%s = %s; %s' % (
2049
+ init_cname, function % value_code,
2050
+ init_constants.error_goto_if_null(init_cname, self.module_pos)))
2051
+
2052
+ # The functions below are there in a transition phase only
2053
+ # and will be deprecated. They are called from Nodes.BlockNode.
2054
+ # The copy&paste duplication is intentional in order to be able
2055
+ # to see quickly how BlockNode worked, until this is replaced.
2056
+
2057
+ def should_declare(self, cname, entry):
2058
+ if cname in self.declared_cnames:
2059
+ other = self.declared_cnames[cname]
2060
+ assert str(entry.type) == str(other.type)
2061
+ assert entry.init == other.init
2062
+ return False
2063
+ else:
2064
+ self.declared_cnames[cname] = entry
2065
+ return True
2066
+
2067
+ #
2068
+ # File name state
2069
+ #
2070
+
2071
+ def lookup_filename(self, source_desc):
2072
+ entry = source_desc.get_filenametable_entry()
2073
+ try:
2074
+ index = self.filename_table[entry]
2075
+ except KeyError:
2076
+ index = len(self.filename_list)
2077
+ self.filename_list.append(source_desc)
2078
+ self.filename_table[entry] = index
2079
+ return index
2080
+
2081
+ def commented_file_contents(self, source_desc):
2082
+ try:
2083
+ return self.input_file_contents[source_desc]
2084
+ except KeyError:
2085
+ pass
2086
+ source_file = source_desc.get_lines(encoding='ASCII',
2087
+ error_handling='ignore')
2088
+ try:
2089
+ F = [' * ' + line.rstrip().replace(
2090
+ '*/', '*[inserted by cython to avoid comment closer]/'
2091
+ ).replace(
2092
+ '/*', '/[inserted by cython to avoid comment start]*'
2093
+ )
2094
+ for line in source_file]
2095
+ finally:
2096
+ if hasattr(source_file, 'close'):
2097
+ source_file.close()
2098
+ if not F: F.append('')
2099
+ self.input_file_contents[source_desc] = F
2100
+ return F
2101
+
2102
+ #
2103
+ # Utility code state
2104
+ #
2105
+
2106
+ def use_utility_code(self, utility_code):
2107
+ """
2108
+ Adds code to the C file. utility_code should
2109
+ a) implement __eq__/__hash__ for the purpose of knowing whether the same
2110
+ code has already been included
2111
+ b) implement put_code, which takes a globalstate instance
2112
+
2113
+ See UtilityCode.
2114
+ """
2115
+ if utility_code and utility_code not in self.utility_codes:
2116
+ self.utility_codes.add(utility_code)
2117
+ utility_code.put_code(self)
2118
+
2119
+ def use_entry_utility_code(self, entry):
2120
+ if entry is None:
2121
+ return
2122
+ if entry.utility_code:
2123
+ self.use_utility_code(entry.utility_code)
2124
+ if entry.utility_code_definition:
2125
+ self.use_utility_code(entry.utility_code_definition)
2126
+
2127
+
2128
+ def funccontext_property(func):
2129
+ name = func.__name__
2130
+ attribute_of = operator.attrgetter(name)
2131
+ def get(self):
2132
+ return attribute_of(self.funcstate)
2133
+ def set(self, value):
2134
+ setattr(self.funcstate, name, value)
2135
+ return property(get, set)
2136
+
2137
+
2138
+ class CCodeConfig:
2139
+ # emit_linenums boolean write #line pragmas?
2140
+ # emit_code_comments boolean copy the original code into C comments?
2141
+ # c_line_in_traceback boolean append the c file and line number to the traceback for exceptions?
2142
+
2143
+ def __init__(self, emit_linenums=True, emit_code_comments=True, c_line_in_traceback=True):
2144
+ self.emit_code_comments = emit_code_comments
2145
+ self.emit_linenums = emit_linenums
2146
+ self.c_line_in_traceback = c_line_in_traceback
2147
+
2148
+
2149
+ class CCodeWriter:
2150
+ """
2151
+ Utility class to output C code.
2152
+
2153
+ When creating an insertion point one must care about the state that is
2154
+ kept:
2155
+ - formatting state (level, bol) is cloned and used in insertion points
2156
+ as well
2157
+ - labels, temps, exc_vars: One must construct a scope in which these can
2158
+ exist by calling enter_cfunc_scope/exit_cfunc_scope (these are for
2159
+ sanity checking and forward compatibility). Created insertion points
2160
+ looses this scope and cannot access it.
2161
+ - marker: Not copied to insertion point
2162
+ - filename_table, filename_list, input_file_contents: All codewriters
2163
+ coming from the same root share the same instances simultaneously.
2164
+ """
2165
+
2166
+ # f file output file
2167
+ # buffer StringIOTree
2168
+
2169
+ # level int indentation level
2170
+ # bol bool beginning of line?
2171
+ # marker string comment to emit before next line
2172
+ # funcstate FunctionState contains state local to a C function used for code
2173
+ # generation (labels and temps state etc.)
2174
+ # globalstate GlobalState contains state global for a C file (input file info,
2175
+ # utility code, declared constants etc.)
2176
+ # pyclass_stack list used during recursive code generation to pass information
2177
+ # about the current class one is in
2178
+ # code_config CCodeConfig configuration options for the C code writer
2179
+
2180
+ @cython.locals(create_from='CCodeWriter')
2181
+ def __init__(self, create_from=None, buffer=None, copy_formatting=False):
2182
+ if buffer is None: buffer = StringIOTree()
2183
+ self.buffer = buffer
2184
+ self.last_pos = None
2185
+ self.last_marked_pos = None
2186
+ self.pyclass_stack = []
2187
+
2188
+ self.funcstate = None
2189
+ self.globalstate = None
2190
+ self.code_config = None
2191
+ self.level = 0
2192
+ self.call_level = 0
2193
+ self.bol = 1
2194
+
2195
+ if create_from is not None:
2196
+ # Use same global state
2197
+ self.set_global_state(create_from.globalstate)
2198
+ self.funcstate = create_from.funcstate
2199
+ # Clone formatting state
2200
+ if copy_formatting:
2201
+ self.level = create_from.level
2202
+ self.bol = create_from.bol
2203
+ self.call_level = create_from.call_level
2204
+ self.last_pos = create_from.last_pos
2205
+ self.last_marked_pos = create_from.last_marked_pos
2206
+
2207
+ def create_new(self, create_from, buffer, copy_formatting):
2208
+ # polymorphic constructor -- very slightly more versatile
2209
+ # than using __class__
2210
+ result = CCodeWriter(create_from, buffer, copy_formatting)
2211
+ return result
2212
+
2213
+ def set_global_state(self, global_state):
2214
+ assert self.globalstate is None # prevent overwriting once it's set
2215
+ self.globalstate = global_state
2216
+ self.code_config = global_state.code_config
2217
+
2218
+ def copyto(self, f):
2219
+ self.buffer.copyto(f)
2220
+
2221
+ def getvalue(self):
2222
+ return self.buffer.getvalue()
2223
+
2224
+ def write(self, s):
2225
+ if '\n' in s:
2226
+ self._write_lines(s)
2227
+ else:
2228
+ self._write_to_buffer(s)
2229
+
2230
+ def _write_lines(self, s):
2231
+ # Cygdb needs to know which Cython source line corresponds to which C line.
2232
+ # Therefore, we write this information into "self.buffer.markers" and then write it from there
2233
+ # into cython_debug/cython_debug_info_* (see ModuleNode._serialize_lineno_map).
2234
+ filename_line = self.last_marked_pos[:2] if self.last_marked_pos else (None, 0)
2235
+ self.buffer.markers.extend([filename_line] * s.count('\n'))
2236
+
2237
+ self._write_to_buffer(s)
2238
+
2239
+ def _write_to_buffer(self, s):
2240
+ self.buffer.write(s)
2241
+
2242
+ def insertion_point(self):
2243
+ other = self.create_new(create_from=self, buffer=self.buffer.insertion_point(), copy_formatting=True)
2244
+ return other
2245
+
2246
+ def new_writer(self):
2247
+ """
2248
+ Creates a new CCodeWriter connected to the same global state, which
2249
+ can later be inserted using insert.
2250
+ """
2251
+ return CCodeWriter(create_from=self)
2252
+
2253
+ def insert(self, writer):
2254
+ """
2255
+ Inserts the contents of another code writer (created with
2256
+ the same global state) in the current location.
2257
+
2258
+ It is ok to write to the inserted writer also after insertion.
2259
+ """
2260
+ assert writer.globalstate is self.globalstate
2261
+ self.buffer.insert(writer.buffer)
2262
+
2263
+ # Properties delegated to function scope
2264
+ @funccontext_property
2265
+ def label_counter(self): pass
2266
+ @funccontext_property
2267
+ def return_label(self): pass
2268
+ @funccontext_property
2269
+ def error_label(self): pass
2270
+ @funccontext_property
2271
+ def labels_used(self): pass
2272
+ @funccontext_property
2273
+ def continue_label(self): pass
2274
+ @funccontext_property
2275
+ def break_label(self): pass
2276
+ @funccontext_property
2277
+ def return_from_error_cleanup_label(self): pass
2278
+ @funccontext_property
2279
+ def yield_labels(self): pass
2280
+
2281
+ def label_interceptor(self, new_labels, orig_labels, skip_to_label=None, pos=None, trace=True):
2282
+ """
2283
+ Helper for generating multiple label interceptor code blocks.
2284
+
2285
+ @param new_labels: the new labels that should be intercepted
2286
+ @param orig_labels: the original labels that we should dispatch to after the interception
2287
+ @param skip_to_label: a label to skip to before starting the code blocks
2288
+ @param pos: the node position to mark for each interceptor block
2289
+ @param trace: add a trace line for the pos marker or not
2290
+ """
2291
+ for label, orig_label in zip(new_labels, orig_labels):
2292
+ if not self.label_used(label):
2293
+ continue
2294
+ if skip_to_label:
2295
+ # jump over the whole interception block
2296
+ self.put_goto(skip_to_label)
2297
+ skip_to_label = None
2298
+
2299
+ if pos is not None:
2300
+ self.mark_pos(pos, trace=trace)
2301
+ self.put_label(label)
2302
+ yield (label, orig_label)
2303
+ self.put_goto(orig_label)
2304
+
2305
+ # Functions delegated to function scope
2306
+ def new_label(self, name=None): return self.funcstate.new_label(name)
2307
+ def new_error_label(self, *args): return self.funcstate.new_error_label(*args)
2308
+ def new_yield_label(self, *args): return self.funcstate.new_yield_label(*args)
2309
+ def get_loop_labels(self): return self.funcstate.get_loop_labels()
2310
+ def set_loop_labels(self, labels): return self.funcstate.set_loop_labels(labels)
2311
+ def new_loop_labels(self, *args): return self.funcstate.new_loop_labels(*args)
2312
+ def get_all_labels(self): return self.funcstate.get_all_labels()
2313
+ def set_all_labels(self, labels): return self.funcstate.set_all_labels(labels)
2314
+ def all_new_labels(self): return self.funcstate.all_new_labels()
2315
+ def use_label(self, lbl): return self.funcstate.use_label(lbl)
2316
+ def label_used(self, lbl): return self.funcstate.label_used(lbl)
2317
+
2318
+
2319
+ def enter_cfunc_scope(self, scope):
2320
+ self.funcstate = FunctionState(self, scope=scope)
2321
+
2322
+ def exit_cfunc_scope(self):
2323
+ if self.funcstate is None:
2324
+ return
2325
+ self.funcstate.validate_exit()
2326
+ self.funcstate = None
2327
+
2328
+ def start_initcfunc(self, signature, scope=None, refnanny=False):
2329
+ """
2330
+ Init code helper function to start a cfunc scope and generate
2331
+ the prototype and function header ("static SIG {") of the function.
2332
+ """
2333
+ proto = self.globalstate.parts['initfunc_declarations']
2334
+ proto.putln(f"static CYTHON_SMALL_CODE {signature}; /*proto*/")
2335
+ self.enter_cfunc_scope(scope)
2336
+ self.putln("")
2337
+ self.putln(f"static {signature} {{")
2338
+ if refnanny:
2339
+ self.put_declare_refcount_context()
2340
+
2341
+ def start_slotfunc(self, class_scope, return_type, c_slot_name, args_signature, needs_funcstate=True, needs_prototype=False):
2342
+ # Slot functions currently live in the class scope as they don't have direct access to the module state.
2343
+ slotfunc_cname = class_scope.mangle_internal(c_slot_name)
2344
+ declaration = f"static {return_type.declaration_code(slotfunc_cname)}({args_signature})"
2345
+
2346
+ if needs_prototype:
2347
+ self.globalstate['decls'].putln(declaration.replace("CYTHON_UNUSED ", "") + "; /*proto*/")
2348
+ if needs_funcstate:
2349
+ self.enter_cfunc_scope(class_scope)
2350
+ self.putln("")
2351
+ self.putln(declaration + " {")
2352
+
2353
+ # constant handling
2354
+
2355
+ def get_py_int(self, str_value, longness):
2356
+ return self.name_in_module_state(
2357
+ self.globalstate.get_int_const(str_value, longness).cname
2358
+ )
2359
+
2360
+ def get_py_float(self, str_value, value_code):
2361
+ return self.name_in_module_state(
2362
+ self.globalstate.get_float_const(str_value, value_code).cname
2363
+ )
2364
+
2365
+ def get_py_const(self, prefix, dedup_key=None):
2366
+ return self.name_in_module_state(
2367
+ self.globalstate.get_py_const(prefix, dedup_key)
2368
+ )
2369
+
2370
+ def get_string_const(self, text):
2371
+ return self.globalstate.get_string_const(text).cname
2372
+
2373
+ def get_pyunicode_ptr_const(self, text):
2374
+ return self.globalstate.get_pyunicode_ptr_const(text)
2375
+
2376
+ def get_py_string_const(self, text, identifier=None):
2377
+ cname = self.globalstate.get_py_string_const(
2378
+ text, identifier).cname
2379
+ return self.name_in_module_state(cname)
2380
+
2381
+ def get_py_codeobj_const(self, node):
2382
+ return self.name_in_module_state(self.globalstate.get_py_codeobj_const(node))
2383
+
2384
+ def get_argument_default_const(self, type):
2385
+ return self.name_in_module_state(self.globalstate.get_argument_default_const(type).cname)
2386
+
2387
+ def intern(self, text):
2388
+ return self.get_py_string_const(text)
2389
+
2390
+ def intern_identifier(self, text):
2391
+ return self.get_py_string_const(text, identifier=True)
2392
+
2393
+ def get_cached_constants_writer(self, target=None):
2394
+ return self.globalstate.get_cached_constants_writer(target)
2395
+
2396
+ def name_in_module_state(self, cname):
2397
+ if self.funcstate.scope is None:
2398
+ # This is a mess. For example, within the codeobj generation
2399
+ # funcstate.scope is None while evaluating the strings, but not while
2400
+ # evaluating the code objects themselves. Right now it doesn't matter
2401
+ # because it all ends up going to the same place, but to actually turn
2402
+ # it into something useful this mess will need to be fixed.
2403
+ return self.name_in_main_c_code_module_state(cname)
2404
+ return self.funcstate.scope.name_in_module_state(cname)
2405
+
2406
+ @staticmethod
2407
+ def name_in_main_c_code_module_state(cname):
2408
+ # The functions where this applies to have the modulestate passed
2409
+ # as an argument to them and so it's better use that argument than
2410
+ # to try to get it from a global variable.
2411
+ return f"{Naming.modulestatevalue_cname}->{cname}"
2412
+
2413
+ @staticmethod
2414
+ def name_in_slot_module_state(cname):
2415
+ # TODO - eventually this will go through PyType_GetModuleByDef
2416
+ # in cases where it's supported.
2417
+ return f"{Naming.modulestateglobal_cname}->{cname}"
2418
+
2419
+ def namespace_cname_in_module_state(self, scope):
2420
+ if scope.is_py_class_scope:
2421
+ return scope.namespace_cname
2422
+ else:
2423
+ return self.name_in_module_state(scope.namespace_cname)
2424
+
2425
+ def typeptr_cname_in_module_state(self, type):
2426
+ if type.is_extension_type:
2427
+ return self.name_in_module_state(type.typeptr_cname)
2428
+ else:
2429
+ return type.typeptr_cname
2430
+
2431
+ # code generation
2432
+
2433
+ def putln(self, code="", safe=False):
2434
+ if self.last_pos and self.bol:
2435
+ self.emit_marker()
2436
+ if self.code_config.emit_linenums and self.last_marked_pos:
2437
+ source_desc, line, _ = self.last_marked_pos
2438
+ self._write_lines(f'\n#line {line} "{source_desc.get_escaped_description()}"\n')
2439
+ if code:
2440
+ if safe:
2441
+ self.put_safe(code)
2442
+ else:
2443
+ self.put(code)
2444
+ self._write_lines("\n")
2445
+ self.bol = 1
2446
+
2447
+ def mark_pos(self, pos, trace=True):
2448
+ if pos is None:
2449
+ return
2450
+ if self.last_marked_pos and self.last_marked_pos[:2] == pos[:2]:
2451
+ return
2452
+ self.last_pos = (pos, trace)
2453
+
2454
+ def emit_marker(self):
2455
+ pos, trace = self.last_pos
2456
+ self.last_marked_pos = pos
2457
+ self.last_pos = None
2458
+ self._write_lines("\n")
2459
+ if self.code_config.emit_code_comments:
2460
+ self.indent()
2461
+ self._write_lines(self._build_marker(pos))
2462
+ if trace:
2463
+ self.write_trace_line(pos)
2464
+
2465
+ def write_trace_line(self, pos):
2466
+ if self.funcstate and self.funcstate.can_trace and self.globalstate.directives['linetrace']:
2467
+ self.indent()
2468
+ self._write_lines(
2469
+ f'__Pyx_TraceLine({pos[1]:d},{self.pos_to_offset(pos):d},{not self.funcstate.gil_owned:d},{self.error_goto(pos)})\n')
2470
+
2471
+ def _build_marker(self, pos):
2472
+ source_desc, line, col = pos
2473
+ assert isinstance(source_desc, SourceDescriptor)
2474
+ contents = self.globalstate.commented_file_contents(source_desc)
2475
+ lines = contents[max(0, line-3):line] # line numbers start at 1
2476
+ lines[-1] += ' # <<<<<<<<<<<<<<'
2477
+ lines += contents[line:line+2]
2478
+ code = "\n".join(lines)
2479
+ return f'/* "{source_desc.get_escaped_description()}":{line:d}\n{code}\n*/\n'
2480
+
2481
+ def put_safe(self, code):
2482
+ # put code, but ignore {}
2483
+ self.write(code)
2484
+ self.bol = 0
2485
+
2486
+ def put_or_include(self, code, name):
2487
+ include_dir = self.globalstate.common_utility_include_dir
2488
+ if include_dir and len(code) > 1024:
2489
+ hash = hashlib.sha256(code.encode('utf8')).hexdigest()
2490
+ include_file = f"{name}_{hash}.h"
2491
+ path = os.path.join(include_dir, include_file)
2492
+ if not os.path.exists(path):
2493
+ tmp_path = f'{path}.tmp{os.getpid()}'
2494
+ with Utils.open_new_file(tmp_path) as f:
2495
+ f.write(code)
2496
+ shutil.move(tmp_path, path)
2497
+ # We use forward slashes in the include path to assure identical code generation
2498
+ # under Windows and Posix. C/C++ compilers should still understand it.
2499
+ c_path = path.replace('\\', '/')
2500
+ code = f'#include "{c_path}"\n'
2501
+ self.put(code)
2502
+
2503
+ def put(self, code):
2504
+ fix_indent = False
2505
+ if "{" in code:
2506
+ dl = code.count("{")
2507
+ else:
2508
+ dl = 0
2509
+ if "}" in code:
2510
+ dl -= code.count("}")
2511
+ if dl < 0:
2512
+ self.level += dl
2513
+ elif dl == 0 and code[0] == "}":
2514
+ # special cases like "} else {" need a temporary dedent
2515
+ fix_indent = True
2516
+ self.level -= 1
2517
+ if self.bol:
2518
+ self.indent()
2519
+ self.write(code)
2520
+ self.bol = 0
2521
+ if dl > 0:
2522
+ self.level += dl
2523
+ elif fix_indent:
2524
+ self.level += 1
2525
+
2526
+ def put_code_here(self, utility: UtilityCode):
2527
+ # Puts the impl section of the utility code directly to the current position.
2528
+ # Ensure we don't have a proto section (but do allow init and cleanup sections
2529
+ # because they might be useful in future).
2530
+ assert not utility.proto, utility.name
2531
+ utility._put_code_section(self, self.globalstate, "impl")
2532
+ utility._put_init_code_section(self.globalstate)
2533
+ if utility.cleanup and Options.generate_cleanup_code:
2534
+ utility._put_code_section(
2535
+ self.globalstate['cleanup_globals'], self.globalstate, "cleanup")
2536
+
2537
+ def increase_indent(self):
2538
+ self.level += 1
2539
+
2540
+ def decrease_indent(self):
2541
+ self.level -= 1
2542
+
2543
+ def begin_block(self):
2544
+ self.putln("{")
2545
+ self.increase_indent()
2546
+
2547
+ def end_block(self):
2548
+ self.decrease_indent()
2549
+ self.putln("}")
2550
+
2551
+ def indent(self):
2552
+ self._write_to_buffer(" " * self.level)
2553
+
2554
+ def get_py_version_hex(self, pyversion):
2555
+ return "0x%02X%02X%02X%02X" % (tuple(pyversion) + (0,0,0,0))[:4]
2556
+
2557
+ def put_label(self, lbl):
2558
+ if lbl in self.funcstate.labels_used:
2559
+ self.putln("%s:;" % lbl)
2560
+
2561
+ def put_goto(self, lbl):
2562
+ self.funcstate.use_label(lbl)
2563
+ self.putln("goto %s;" % lbl)
2564
+
2565
+ def put_var_declaration(self, entry, storage_class="",
2566
+ dll_linkage=None, definition=True):
2567
+ #print "Code.put_var_declaration:", entry.name, "definition =", definition ###
2568
+ if entry.visibility == 'private' and not (definition or entry.defined_in_pxd):
2569
+ #print "...private and not definition, skipping", entry.cname ###
2570
+ return
2571
+ if entry.visibility == "private" and not entry.used:
2572
+ #print "...private and not used, skipping", entry.cname ###
2573
+ return
2574
+ if not entry.cf_used:
2575
+ self.put('CYTHON_UNUSED ')
2576
+ if storage_class:
2577
+ self.put("%s " % storage_class)
2578
+ if entry.is_cpp_optional:
2579
+ self.put(entry.type.cpp_optional_declaration_code(
2580
+ entry.cname, dll_linkage=dll_linkage))
2581
+ else:
2582
+ self.put(entry.type.declaration_code(
2583
+ entry.cname, dll_linkage=dll_linkage))
2584
+ if entry.init is not None:
2585
+ self.put_safe(" = %s" % entry.type.literal_code(entry.init))
2586
+ elif entry.type.is_pyobject:
2587
+ self.put(" = NULL")
2588
+ self.putln(";")
2589
+ self.funcstate.scope.use_entry_utility_code(entry)
2590
+
2591
+ def put_temp_declarations(self, func_context):
2592
+ for name, type, manage_ref, static in func_context.temps_allocated:
2593
+ if type.is_cpp_class and not type.is_fake_reference and func_context.scope.directives['cpp_locals']:
2594
+ decl = type.cpp_optional_declaration_code(name)
2595
+ else:
2596
+ decl = type.declaration_code(name)
2597
+ if type.is_pyobject:
2598
+ self.putln("%s = NULL;" % decl)
2599
+ elif type.is_memoryviewslice:
2600
+ self.putln("%s = %s;" % (decl, type.literal_code(type.default_value)))
2601
+ else:
2602
+ self.putln("%s%s;" % (static and "static " or "", decl))
2603
+
2604
+ if func_context.should_declare_error_indicator:
2605
+ if self.funcstate.uses_error_indicator:
2606
+ unused = ''
2607
+ else:
2608
+ unused = 'CYTHON_UNUSED '
2609
+ # Initialize these variables to silence compiler warnings
2610
+ self.putln("%sint %s = 0;" % (unused, Naming.lineno_cname))
2611
+ self.putln("%sconst char *%s = NULL;" % (unused, Naming.filename_cname))
2612
+ self.putln("%sint %s = 0;" % (unused, Naming.clineno_cname))
2613
+
2614
+ def put_generated_by(self):
2615
+ self.putln(Utils.GENERATED_BY_MARKER)
2616
+ self.putln("")
2617
+
2618
+ def put_h_guard(self, guard):
2619
+ self.putln("#ifndef %s" % guard)
2620
+ self.putln("#define %s" % guard)
2621
+
2622
+ def unlikely(self, cond):
2623
+ if Options.gcc_branch_hints:
2624
+ return 'unlikely(%s)' % cond
2625
+ else:
2626
+ return cond
2627
+
2628
+ def build_function_modifiers(self, modifiers, mapper=modifier_output_mapper):
2629
+ if not modifiers:
2630
+ return ''
2631
+ return '%s ' % ' '.join([mapper(m,m) for m in modifiers])
2632
+
2633
+ # Python objects and reference counting
2634
+
2635
+ def entry_as_pyobject(self, entry):
2636
+ type = entry.type
2637
+ if (not entry.is_self_arg and not entry.type.is_complete()
2638
+ or entry.type.is_extension_type):
2639
+ return "(PyObject *)" + entry.cname
2640
+ else:
2641
+ return entry.cname
2642
+
2643
+ def as_pyobject(self, cname, type):
2644
+ from .PyrexTypes import py_object_type, typecast
2645
+ return typecast(py_object_type, type, cname)
2646
+
2647
+ def put_gotref(self, cname, type):
2648
+ type.generate_gotref(self, cname)
2649
+
2650
+ def put_giveref(self, cname, type):
2651
+ type.generate_giveref(self, cname)
2652
+
2653
+ def put_xgiveref(self, cname, type):
2654
+ type.generate_xgiveref(self, cname)
2655
+
2656
+ def put_xgotref(self, cname, type):
2657
+ type.generate_xgotref(self, cname)
2658
+
2659
+ def put_incref(self, cname, type, nanny=True):
2660
+ # Note: original put_Memslice_Incref/Decref also added in some utility code
2661
+ # this is unnecessary since the relevant utility code is loaded anyway if a memoryview is used
2662
+ # and so has been removed. However, it's potentially a feature that might be useful here
2663
+ type.generate_incref(self, cname, nanny=nanny)
2664
+
2665
+ def put_xincref(self, cname, type, nanny=True):
2666
+ type.generate_xincref(self, cname, nanny=nanny)
2667
+
2668
+ def put_decref(self, cname, type, nanny=True, have_gil=True):
2669
+ type.generate_decref(self, cname, nanny=nanny, have_gil=have_gil)
2670
+
2671
+ def put_xdecref(self, cname, type, nanny=True, have_gil=True):
2672
+ type.generate_xdecref(self, cname, nanny=nanny, have_gil=have_gil)
2673
+
2674
+ def put_decref_clear(self, cname, type, clear_before_decref=False, nanny=True, have_gil=True):
2675
+ type.generate_decref_clear(self, cname, clear_before_decref=clear_before_decref,
2676
+ nanny=nanny, have_gil=have_gil)
2677
+
2678
+ def put_xdecref_clear(self, cname, type, clear_before_decref=False, nanny=True, have_gil=True):
2679
+ type.generate_xdecref_clear(self, cname, clear_before_decref=clear_before_decref,
2680
+ nanny=nanny, have_gil=have_gil)
2681
+
2682
+ def put_decref_set(self, cname, type, rhs_cname):
2683
+ type.generate_decref_set(self, cname, rhs_cname)
2684
+
2685
+ def put_xdecref_set(self, cname, type, rhs_cname):
2686
+ type.generate_xdecref_set(self, cname, rhs_cname)
2687
+
2688
+ def put_incref_memoryviewslice(self, slice_cname, type, have_gil):
2689
+ # TODO ideally this would just be merged into "put_incref"
2690
+ type.generate_incref_memoryviewslice(self, slice_cname, have_gil=have_gil)
2691
+
2692
+ def put_var_incref_memoryviewslice(self, entry, have_gil):
2693
+ self.put_incref_memoryviewslice(entry.cname, entry.type, have_gil=have_gil)
2694
+
2695
+ def put_var_gotref(self, entry):
2696
+ self.put_gotref(entry.cname, entry.type)
2697
+
2698
+ def put_var_giveref(self, entry):
2699
+ self.put_giveref(entry.cname, entry.type)
2700
+
2701
+ def put_var_xgotref(self, entry):
2702
+ self.put_xgotref(entry.cname, entry.type)
2703
+
2704
+ def put_var_xgiveref(self, entry):
2705
+ self.put_xgiveref(entry.cname, entry.type)
2706
+
2707
+ def put_var_incref(self, entry, **kwds):
2708
+ self.put_incref(entry.cname, entry.type, **kwds)
2709
+
2710
+ def put_var_xincref(self, entry, **kwds):
2711
+ self.put_xincref(entry.cname, entry.type, **kwds)
2712
+
2713
+ def put_var_decref(self, entry, **kwds):
2714
+ self.put_decref(entry.cname, entry.type, **kwds)
2715
+
2716
+ def put_var_xdecref(self, entry, **kwds):
2717
+ self.put_xdecref(entry.cname, entry.type, **kwds)
2718
+
2719
+ def put_var_decref_clear(self, entry, **kwds):
2720
+ self.put_decref_clear(entry.cname, entry.type, clear_before_decref=entry.in_closure, **kwds)
2721
+
2722
+ def put_var_decref_set(self, entry, rhs_cname, **kwds):
2723
+ self.put_decref_set(entry.cname, entry.type, rhs_cname, **kwds)
2724
+
2725
+ def put_var_xdecref_set(self, entry, rhs_cname, **kwds):
2726
+ self.put_xdecref_set(entry.cname, entry.type, rhs_cname, **kwds)
2727
+
2728
+ def put_var_xdecref_clear(self, entry, **kwds):
2729
+ self.put_xdecref_clear(entry.cname, entry.type, clear_before_decref=entry.in_closure, **kwds)
2730
+
2731
+ def put_var_decrefs(self, entries, used_only = 0):
2732
+ for entry in entries:
2733
+ if not used_only or entry.used:
2734
+ if entry.xdecref_cleanup:
2735
+ self.put_var_xdecref(entry)
2736
+ else:
2737
+ self.put_var_decref(entry)
2738
+
2739
+ def put_var_xdecrefs(self, entries):
2740
+ for entry in entries:
2741
+ self.put_var_xdecref(entry)
2742
+
2743
+ def put_var_xdecrefs_clear(self, entries):
2744
+ for entry in entries:
2745
+ self.put_var_xdecref_clear(entry)
2746
+
2747
+ def put_init_to_py_none(self, cname, type, nanny=True):
2748
+ from .PyrexTypes import py_object_type, typecast
2749
+ py_none = typecast(type, py_object_type, "Py_None")
2750
+ if nanny:
2751
+ self.putln("%s = %s; __Pyx_INCREF(Py_None);" % (cname, py_none))
2752
+ else:
2753
+ self.putln("%s = %s; Py_INCREF(Py_None);" % (cname, py_none))
2754
+
2755
+ def put_init_var_to_py_none(self, entry, template = "%s", nanny=True):
2756
+ code = template % entry.cname
2757
+ #if entry.type.is_extension_type:
2758
+ # code = "((PyObject*)%s)" % code
2759
+ self.put_init_to_py_none(code, entry.type, nanny)
2760
+ if entry.in_closure:
2761
+ self.put_giveref('Py_None')
2762
+
2763
+ def put_pymethoddef(self, entry, term, allow_skip=True, wrapper_code_writer=None):
2764
+ is_number_slot = False
2765
+ if entry.is_special or entry.name == '__getattribute__':
2766
+ from . import TypeSlots
2767
+ if entry.name not in special_py_methods:
2768
+ if TypeSlots.is_binop_number_slot(entry.name):
2769
+ # It's useful if numeric binops are created with meth coexist
2770
+ # so they can be called directly by looking up the name, skipping the
2771
+ # dispatch wrapper that enables the reverse slots. This is most useful
2772
+ # when c_api_binop_methods is False, but there's no reason not to do it
2773
+ # all the time
2774
+ is_number_slot = True
2775
+ elif entry.name == '__getattr__' and not self.globalstate.directives['fast_getattr']:
2776
+ pass
2777
+ # Python's typeobject.c will automatically fill in our slot
2778
+ # in add_operators() (called by PyType_Ready) with a value
2779
+ # that's better than ours.
2780
+ elif allow_skip:
2781
+ return
2782
+
2783
+ method_flags = entry.signature.method_flags()
2784
+ if not method_flags:
2785
+ return
2786
+ if entry.is_special:
2787
+ method_flags += [TypeSlots.method_coexist]
2788
+ func_ptr = wrapper_code_writer.put_pymethoddef_wrapper(entry) if wrapper_code_writer else entry.func_cname
2789
+ # Add required casts, but try not to shadow real warnings.
2790
+ cast = entry.signature.method_function_type()
2791
+ if cast != 'PyCFunction':
2792
+ func_ptr = '(void*)(%s)%s' % (cast, func_ptr)
2793
+ entry_name = entry.name.as_c_string_literal()
2794
+ if is_number_slot:
2795
+ # Unlike most special functions, binop numeric operator slots are actually generated here
2796
+ # (to ensure that they can be looked up). However, they're sometimes guarded by the preprocessor
2797
+ # so a bit of extra logic is needed
2798
+ slot = TypeSlots.get_slot_table(self.globalstate.directives).get_slot_by_method_name(entry.name)
2799
+ preproc_guard = slot.preprocessor_guard_code()
2800
+ if preproc_guard:
2801
+ self.putln(preproc_guard)
2802
+ self.putln(
2803
+ '{%s, (PyCFunction)%s, %s, %s}%s' % (
2804
+ entry_name,
2805
+ func_ptr,
2806
+ "|".join(method_flags),
2807
+ entry.doc_cname if entry.doc else '0',
2808
+ term))
2809
+ if is_number_slot and preproc_guard:
2810
+ self.putln("#endif")
2811
+
2812
+ def put_pymethoddef_wrapper(self, entry):
2813
+ func_cname = entry.func_cname
2814
+ if entry.is_special:
2815
+ method_flags = entry.signature.method_flags() or []
2816
+ from .TypeSlots import method_noargs
2817
+ if method_noargs in method_flags:
2818
+ # Special NOARGS methods really take no arguments besides 'self', but PyCFunction expects one.
2819
+ func_cname = Naming.method_wrapper_prefix + func_cname
2820
+ self.putln("static PyObject *%s(PyObject *self, CYTHON_UNUSED PyObject *arg) {" % func_cname)
2821
+ func_call = "%s(self)" % entry.func_cname
2822
+ if entry.name == "__next__":
2823
+ self.putln("PyObject *res = %s;" % func_call)
2824
+ # tp_iternext can return NULL without an exception
2825
+ self.putln("if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); }")
2826
+ self.putln("return res;")
2827
+ else:
2828
+ self.putln("return %s;" % func_call)
2829
+ self.putln("}")
2830
+ return func_cname
2831
+
2832
+ # GIL methods
2833
+
2834
+ def use_fast_gil_utility_code(self):
2835
+ if self.globalstate.directives['fast_gil']:
2836
+ self.globalstate.use_utility_code(UtilityCode.load_cached("FastGil", "ModuleSetupCode.c"))
2837
+ else:
2838
+ self.globalstate.use_utility_code(UtilityCode.load_cached("NoFastGil", "ModuleSetupCode.c"))
2839
+
2840
+ def put_ensure_gil(self, declare_gilstate=True, variable=None):
2841
+ """
2842
+ Acquire the GIL. The generated code is safe even when no PyThreadState
2843
+ has been allocated for this thread (for threads not initialized by
2844
+ using the Python API). Additionally, the code generated by this method
2845
+ may be called recursively.
2846
+ """
2847
+ self.globalstate.use_utility_code(
2848
+ UtilityCode.load_cached("ForceInitThreads", "ModuleSetupCode.c"))
2849
+ self.use_fast_gil_utility_code()
2850
+ if not variable:
2851
+ variable = '__pyx_gilstate_save'
2852
+ if declare_gilstate:
2853
+ self.put("PyGILState_STATE ")
2854
+ self.putln("%s = __Pyx_PyGILState_Ensure();" % variable)
2855
+
2856
+ def put_release_ensured_gil(self, variable=None):
2857
+ """
2858
+ Releases the GIL, corresponds to `put_ensure_gil`.
2859
+ """
2860
+ self.use_fast_gil_utility_code()
2861
+ if not variable:
2862
+ variable = '__pyx_gilstate_save'
2863
+ self.putln("__Pyx_PyGILState_Release(%s);" % variable)
2864
+
2865
+ def put_acquire_freethreading_lock(self):
2866
+ self.putln("#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING")
2867
+ self.putln(f"PyMutex_Lock(&{Naming.parallel_freethreading_mutex});")
2868
+ self.putln("#endif")
2869
+
2870
+ def put_release_freethreading_lock(self):
2871
+ self.putln("#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING")
2872
+ self.putln(f"PyMutex_Unlock(&{Naming.parallel_freethreading_mutex});")
2873
+ self.putln("#endif")
2874
+
2875
+ def put_acquire_gil(self, variable=None, unknown_gil_state=True):
2876
+ """
2877
+ Acquire the GIL. The thread's thread state must have been initialized
2878
+ by a previous `put_release_gil`
2879
+ """
2880
+ self.use_fast_gil_utility_code()
2881
+ self.putln("__Pyx_FastGIL_Forget();")
2882
+ if variable:
2883
+ self.putln('_save = %s;' % variable)
2884
+ if unknown_gil_state:
2885
+ self.putln("if (_save) {")
2886
+ self.putln("Py_BLOCK_THREADS")
2887
+ if unknown_gil_state:
2888
+ self.putln("}")
2889
+
2890
+ def put_release_gil(self, variable=None, unknown_gil_state=True):
2891
+ "Release the GIL, corresponds to `put_acquire_gil`."
2892
+ self.use_fast_gil_utility_code()
2893
+ self.putln("PyThreadState *_save;")
2894
+ self.putln("_save = NULL;")
2895
+ if unknown_gil_state:
2896
+ # we don't *know* that we don't have the GIL (since we may be inside a nogil function,
2897
+ # and Py_UNBLOCK_THREADS is unsafe without the GIL)
2898
+ self.putln("if (PyGILState_Check()) {")
2899
+ self.putln("Py_UNBLOCK_THREADS")
2900
+ if unknown_gil_state:
2901
+ self.putln("}")
2902
+ if variable:
2903
+ self.putln('%s = _save;' % variable)
2904
+ self.putln("__Pyx_FastGIL_Remember();")
2905
+
2906
+ def declare_gilstate(self):
2907
+ self.putln("PyGILState_STATE __pyx_gilstate_save;")
2908
+
2909
+ # error handling
2910
+
2911
+ def put_error_if_neg(self, pos, value):
2912
+ # TODO this path is almost _never_ taken, yet this macro makes is slower!
2913
+ # return self.putln("if (unlikely(%s < 0)) %s" % (value, self.error_goto(pos)))
2914
+ return self.putln("if (%s < 0) %s" % (value, self.error_goto(pos)))
2915
+
2916
+ def put_error_if_unbound(self, pos, entry, in_nogil_context=False, unbound_check_code=None):
2917
+ if entry.from_closure:
2918
+ func = '__Pyx_RaiseClosureNameError'
2919
+ self.globalstate.use_utility_code(
2920
+ UtilityCode.load_cached("RaiseClosureNameError", "ObjectHandling.c"))
2921
+ elif entry.type.is_memoryviewslice and in_nogil_context:
2922
+ func = '__Pyx_RaiseUnboundMemoryviewSliceNogil'
2923
+ self.globalstate.use_utility_code(
2924
+ UtilityCode.load_cached("RaiseUnboundMemoryviewSliceNogil", "ObjectHandling.c"))
2925
+ elif entry.type.is_cpp_class and entry.is_cglobal:
2926
+ func = '__Pyx_RaiseCppGlobalNameError'
2927
+ self.globalstate.use_utility_code(
2928
+ UtilityCode.load_cached("RaiseCppGlobalNameError", "ObjectHandling.c"))
2929
+ elif entry.type.is_cpp_class and entry.is_variable and not entry.is_member and entry.scope.is_c_class_scope:
2930
+ # there doesn't seem to be a good way to detecting an instance-attribute of a C class
2931
+ # (is_member is only set for class attributes)
2932
+ func = '__Pyx_RaiseCppAttributeError'
2933
+ self.globalstate.use_utility_code(
2934
+ UtilityCode.load_cached("RaiseCppAttributeError", "ObjectHandling.c"))
2935
+ else:
2936
+ func = '__Pyx_RaiseUnboundLocalError'
2937
+ self.globalstate.use_utility_code(
2938
+ UtilityCode.load_cached("RaiseUnboundLocalError", "ObjectHandling.c"))
2939
+
2940
+ if not unbound_check_code:
2941
+ unbound_check_code = entry.type.check_for_null_code(entry.cname)
2942
+ self.putln('if (unlikely(!%s)) { %s("%s"); %s }' % (
2943
+ unbound_check_code,
2944
+ func,
2945
+ entry.name,
2946
+ self.error_goto(pos)))
2947
+
2948
+ def set_error_info(self, pos, used=False):
2949
+ self.funcstate.should_declare_error_indicator = True
2950
+ if used:
2951
+ self.funcstate.uses_error_indicator = True
2952
+ return "__PYX_MARK_ERR_POS(%s, %s)" % (
2953
+ self.lookup_filename(pos[0]),
2954
+ pos[1])
2955
+
2956
+ def error_goto(self, pos, used=True):
2957
+ lbl = self.funcstate.error_label
2958
+ self.funcstate.use_label(lbl)
2959
+ if pos is None:
2960
+ return 'goto %s;' % lbl
2961
+ self.funcstate.should_declare_error_indicator = True
2962
+ if used:
2963
+ self.funcstate.uses_error_indicator = True
2964
+ return "__PYX_ERR(%s, %s, %s)" % (
2965
+ self.lookup_filename(pos[0]),
2966
+ pos[1],
2967
+ lbl)
2968
+
2969
+ def error_goto_if(self, cond, pos):
2970
+ return "if (%s) %s" % (self.unlikely(cond), self.error_goto(pos))
2971
+
2972
+ def error_goto_if_null(self, cname, pos):
2973
+ return self.error_goto_if("!%s" % cname, pos)
2974
+
2975
+ def error_goto_if_neg(self, cname, pos):
2976
+ # Add extra parentheses to silence clang warnings about constant conditions.
2977
+ return self.error_goto_if("(%s < 0)" % cname, pos)
2978
+
2979
+ def error_goto_if_PyErr(self, pos):
2980
+ return self.error_goto_if("PyErr_Occurred()", pos)
2981
+
2982
+ def lookup_filename(self, filename):
2983
+ return self.globalstate.lookup_filename(filename)
2984
+
2985
+ def put_declare_refcount_context(self):
2986
+ self.putln('__Pyx_RefNannyDeclarations')
2987
+
2988
+ def put_setup_refcount_context(self, name, acquire_gil=False):
2989
+ name = name.as_c_string_literal() # handle unicode names
2990
+ if acquire_gil:
2991
+ self.globalstate.use_utility_code(
2992
+ UtilityCode.load_cached("ForceInitThreads", "ModuleSetupCode.c"))
2993
+ self.putln('__Pyx_RefNannySetupContext(%s, %d);' % (name, acquire_gil and 1 or 0))
2994
+
2995
+ def put_finish_refcount_context(self, nogil=False):
2996
+ self.putln("__Pyx_RefNannyFinishContextNogil()" if nogil else "__Pyx_RefNannyFinishContext();")
2997
+
2998
+ def put_add_traceback(self, qualified_name, include_cline=True):
2999
+ """
3000
+ Build a Python traceback for propagating exceptions.
3001
+
3002
+ qualified_name should be the qualified name of the function.
3003
+ """
3004
+ qualified_name = qualified_name.as_c_string_literal() # handle unicode names
3005
+ format_tuple = (
3006
+ qualified_name,
3007
+ Naming.clineno_cname if include_cline else 0,
3008
+ Naming.lineno_cname,
3009
+ Naming.filename_cname,
3010
+ )
3011
+
3012
+ self.funcstate.uses_error_indicator = True
3013
+ self.putln('__Pyx_AddTraceback(%s, %s, %s, %s);' % format_tuple)
3014
+
3015
+ def put_unraisable(self, qualified_name, nogil=False):
3016
+ """
3017
+ Generate code to print a Python warning for an unraisable exception.
3018
+
3019
+ qualified_name should be the qualified name of the function.
3020
+ """
3021
+ format_tuple = (
3022
+ qualified_name,
3023
+ Naming.clineno_cname,
3024
+ Naming.lineno_cname,
3025
+ Naming.filename_cname,
3026
+ self.globalstate.directives['unraisable_tracebacks'],
3027
+ nogil,
3028
+ )
3029
+ self.funcstate.uses_error_indicator = True
3030
+ self.putln('__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);' % format_tuple)
3031
+ self.globalstate.use_utility_code(
3032
+ UtilityCode.load_cached("WriteUnraisableException", "Exceptions.c"))
3033
+
3034
+ def is_tracing(self):
3035
+ return self.globalstate.directives['profile'] or self.globalstate.directives['linetrace']
3036
+
3037
+ def pos_to_offset(self, pos):
3038
+ """
3039
+ Calculate a fake 'instruction offset' from a node position as 31 bit int (32 bit signed).
3040
+ """
3041
+ scope = self.funcstate.scope
3042
+ while scope and pos not in scope.node_positions_to_offset:
3043
+ scope = scope.parent_scope
3044
+ return scope.node_positions_to_offset[pos] if scope else 0
3045
+
3046
+ def put_trace_declarations(self, is_generator=False):
3047
+ self.putln('__Pyx_TraceDeclarationsGen' if is_generator else '__Pyx_TraceDeclarationsFunc')
3048
+
3049
+ def put_trace_frame_init(self, codeobj=None):
3050
+ if codeobj:
3051
+ self.putln('__Pyx_TraceFrameInit(%s)' % codeobj)
3052
+
3053
+ def put_trace_start(self, name, pos, nogil=False, is_generator=False, is_cpdef_func=False):
3054
+ trace_func = "__Pyx_TraceStartGen" if is_generator else "__Pyx_TraceStartFunc"
3055
+ self.putln(
3056
+ f'{trace_func}('
3057
+ f'{name.as_c_string_literal()}, '
3058
+ f'{Naming.filetable_cname}[{self.lookup_filename(pos[0])}], '
3059
+ f'{pos[1]}, '
3060
+ f'{self.pos_to_offset(pos):d}, '
3061
+ f'{nogil:d}, '
3062
+ f'{Naming.skip_dispatch_cname if is_cpdef_func else "0"}, '
3063
+ f'{self.error_goto(pos)}'
3064
+ ');'
3065
+ )
3066
+
3067
+ def put_trace_exit(self):
3068
+ self.putln("__Pyx_PyMonitoring_ExitScope();")
3069
+
3070
+ def put_trace_yield(self, retvalue_cname, pos):
3071
+ error_goto = self.error_goto(pos)
3072
+ self.putln(f"__Pyx_TraceYield({retvalue_cname}, {self.pos_to_offset(pos)}, {error_goto});")
3073
+
3074
+ def put_trace_resume(self, pos):
3075
+ scope = self.funcstate.scope
3076
+ # pos[1] is probably not the first line, so try to find the first line of the generator function.
3077
+ first_line = scope.scope_class.pos[1] if scope.scope_class else pos[1]
3078
+ name = scope.name.as_c_string_literal()
3079
+ filename_index = self.lookup_filename(pos[0])
3080
+ error_goto = self.error_goto(pos)
3081
+ self.putln(
3082
+ '__Pyx_TraceResumeGen('
3083
+ f'{name}, '
3084
+ f'{Naming.filetable_cname}[{filename_index}], '
3085
+ f'{first_line}, '
3086
+ f'{self.pos_to_offset(pos)}, '
3087
+ f'{error_goto}'
3088
+ ');'
3089
+ )
3090
+
3091
+ def put_trace_exception(self, pos, reraise=False, fresh=False):
3092
+ self.putln(f"__Pyx_TraceException({self.pos_to_offset(pos)}, {bool(reraise):d}, {bool(fresh):d});")
3093
+
3094
+ def put_trace_exception_propagating(self):
3095
+ self.putln(f"__Pyx_TraceException({Naming.lineno_cname}, 0, 0);")
3096
+
3097
+ def put_trace_exception_handled(self, pos):
3098
+ self.putln(f"__Pyx_TraceExceptionHandled({self.pos_to_offset(pos)});")
3099
+
3100
+ def put_trace_unwind(self, pos, nogil=False):
3101
+ self.putln(f"__Pyx_TraceExceptionUnwind({self.pos_to_offset(pos)}, {bool(nogil):d});")
3102
+
3103
+ def put_trace_stopiteration(self, pos, value):
3104
+ error_goto = self.error_goto(pos)
3105
+ self.putln(f"__Pyx_TraceStopIteration({value}, {self.pos_to_offset(pos)}, {error_goto});")
3106
+
3107
+ def put_trace_return(self, retvalue_cname, pos, return_type=None, nogil=False):
3108
+ extra_arg = ""
3109
+ trace_func = "__Pyx_TraceReturnValue"
3110
+
3111
+ if return_type is None:
3112
+ pass
3113
+ elif return_type.is_pyobject:
3114
+ retvalue_cname = return_type.as_pyobject(retvalue_cname)
3115
+ elif return_type.is_void:
3116
+ retvalue_cname = 'Py_None'
3117
+ elif return_type.to_py_function:
3118
+ trace_func = "__Pyx_TraceReturnCValue"
3119
+ extra_arg = f", {return_type.to_py_function}"
3120
+ else:
3121
+ # We don't have a Python visible return value but we still need to report that we returned.
3122
+ # 'None' may not be a misleading (it's false, for one), but it's hopefully better than nothing.
3123
+ retvalue_cname = 'Py_None'
3124
+
3125
+ error_handling = self.error_goto(pos)
3126
+ self.putln(f"{trace_func}({retvalue_cname}{extra_arg}, {self.pos_to_offset(pos)}, {bool(nogil):d}, {error_handling});")
3127
+
3128
+ def putln_openmp(self, string):
3129
+ self.putln("#ifdef _OPENMP")
3130
+ self.putln(string)
3131
+ self.putln("#endif /* _OPENMP */")
3132
+
3133
+ def undef_builtin_expect(self, cond):
3134
+ """
3135
+ Redefine the macros likely() and unlikely to no-ops, depending on
3136
+ condition 'cond'
3137
+ """
3138
+ self.putln("#if %s" % cond)
3139
+ self.putln(" #undef likely")
3140
+ self.putln(" #undef unlikely")
3141
+ self.putln(" #define likely(x) (x)")
3142
+ self.putln(" #define unlikely(x) (x)")
3143
+ self.putln("#endif")
3144
+
3145
+ def redef_builtin_expect(self, cond):
3146
+ self.putln("#if %s" % cond)
3147
+ self.putln(" #undef likely")
3148
+ self.putln(" #undef unlikely")
3149
+ self.putln(" #define likely(x) __builtin_expect(!!(x), 1)")
3150
+ self.putln(" #define unlikely(x) __builtin_expect(!!(x), 0)")
3151
+ self.putln("#endif")
3152
+
3153
+
3154
+ class PyrexCodeWriter:
3155
+ # f file output file
3156
+ # level int indentation level
3157
+
3158
+ def __init__(self, outfile_name):
3159
+ self.f = Utils.open_new_file(outfile_name)
3160
+ self.level = 0
3161
+
3162
+ def putln(self, code):
3163
+ self.f.write("%s%s\n" % (" " * self.level, code))
3164
+
3165
+ def indent(self):
3166
+ self.level += 1
3167
+
3168
+ def dedent(self):
3169
+ self.level -= 1
3170
+
3171
+
3172
+ class PyxCodeWriter:
3173
+ """
3174
+ Can be used for writing out some Cython code.
3175
+ """
3176
+
3177
+ def __init__(self, buffer=None, indent_level=0, context=None, encoding='ascii'):
3178
+ self.buffer = buffer or StringIOTree()
3179
+ self.level = indent_level
3180
+ self.original_level = indent_level
3181
+ self.context = context
3182
+ self.encoding = encoding
3183
+ self._insertion_points = {}
3184
+
3185
+ def indent(self, levels=1):
3186
+ self.level += levels
3187
+ return True
3188
+
3189
+ def dedent(self, levels=1):
3190
+ self.level -= levels
3191
+
3192
+ @contextmanager
3193
+ def indenter(self, line):
3194
+ """
3195
+ with pyx_code.indenter("for i in range(10):"):
3196
+ pyx_code.putln("print i")
3197
+ """
3198
+ self.putln(line)
3199
+ self.indent()
3200
+ yield
3201
+ self.dedent()
3202
+
3203
+ def empty(self):
3204
+ return self.buffer.empty()
3205
+
3206
+ def getvalue(self):
3207
+ result = self.buffer.getvalue()
3208
+ if isinstance(result, bytes):
3209
+ result = result.decode(self.encoding)
3210
+ return result
3211
+
3212
+ def putln(self, line, context=None):
3213
+ if context is None:
3214
+ if self.context is not None:
3215
+ context = self.context
3216
+ if context is not None:
3217
+ line = sub_tempita(line, context)
3218
+ # Avoid indenting empty lines.
3219
+ self.buffer.write(f"{self.level * ' '}{line}\n" if line else "\n")
3220
+
3221
+ def put_chunk(self, chunk, context=None):
3222
+ if context is None:
3223
+ if self.context is not None:
3224
+ context = self.context
3225
+ if context is not None:
3226
+ chunk = sub_tempita(chunk, context)
3227
+
3228
+ chunk = _indent_chunk(chunk, self.level * 4)
3229
+ self.buffer.write(chunk)
3230
+
3231
+ def insertion_point(self):
3232
+ return type(self)(self.buffer.insertion_point(), self.level, self.context)
3233
+
3234
+ def reset(self):
3235
+ # resets the buffer so that nothing gets written. Most useful
3236
+ # for abandoning all work in a specific insertion point
3237
+ self.buffer.reset()
3238
+ self.level = self.original_level
3239
+
3240
+ def named_insertion_point(self, name):
3241
+ self._insertion_points[name] = self.insertion_point()
3242
+
3243
+ def __getitem__(self, name):
3244
+ return self._insertion_points[name]
3245
+
3246
+
3247
+ @cython.final
3248
+ @cython.ccall
3249
+ def _indent_chunk(chunk: str, indentation_length: cython.int) -> str:
3250
+ """Normalise leading space to the intended indentation and strip empty lines.
3251
+ """
3252
+ assert '\t' not in chunk
3253
+ lines = chunk.splitlines(keepends=True)
3254
+ if not lines:
3255
+ return chunk
3256
+ last_line = lines[-1].rstrip(' ')
3257
+ if last_line:
3258
+ lines[-1] = last_line
3259
+ else:
3260
+ del lines[-1]
3261
+ if not lines:
3262
+ return '\n'
3263
+
3264
+ # Count minimal (non-empty) indentation and strip empty lines.
3265
+ min_indentation: cython.int = len(chunk) + 1
3266
+ line_indentation: cython.int
3267
+ line: str
3268
+ i: cython.int
3269
+ for i, line in enumerate(lines):
3270
+ line_indentation = _count_indentation(line)
3271
+ if line_indentation + 1 == len(line):
3272
+ lines[i] = '\n'
3273
+ elif line_indentation < min_indentation:
3274
+ min_indentation = line_indentation
3275
+
3276
+ if min_indentation > len(chunk):
3277
+ # All empty lines.
3278
+ min_indentation = 0
3279
+
3280
+ if min_indentation < indentation_length:
3281
+ add_indent = ' ' * (indentation_length - min_indentation)
3282
+ lines = [
3283
+ add_indent + line if line != '\n' else '\n'
3284
+ for line in lines
3285
+ ]
3286
+ elif min_indentation > indentation_length:
3287
+ start: cython.int = min_indentation - indentation_length
3288
+ lines = [
3289
+ line[start:] if line != '\n' else '\n'
3290
+ for line in lines
3291
+ ]
3292
+
3293
+ return ''.join(lines)
3294
+
3295
+
3296
+ @cython.exceptval(-1)
3297
+ @cython.cfunc
3298
+ def _count_indentation(s: str) -> cython.int:
3299
+ i: cython.int = 0
3300
+ ch: cython.Py_UCS4
3301
+ for i, ch in enumerate(s):
3302
+ if ch != ' ':
3303
+ break
3304
+ return i
3305
+
3306
+
3307
+ class ClosureTempAllocator:
3308
+ def __init__(self, klass):
3309
+ self.klass = klass
3310
+ self.temps_allocated = {}
3311
+ self.temps_free = {}
3312
+ self.temps_count = 0
3313
+
3314
+ def reset(self):
3315
+ for type, cnames in self.temps_allocated.items():
3316
+ self.temps_free[type] = list(cnames)
3317
+
3318
+ def allocate_temp(self, type):
3319
+ if type not in self.temps_allocated:
3320
+ self.temps_allocated[type] = []
3321
+ self.temps_free[type] = []
3322
+ elif self.temps_free[type]:
3323
+ return self.temps_free[type].pop(0)
3324
+ cname = '%s%d' % (Naming.codewriter_temp_prefix, self.temps_count)
3325
+ self.klass.declare_var(pos=None, name=cname, cname=cname, type=type, is_cdef=True)
3326
+ self.temps_allocated[type].append(cname)
3327
+ self.temps_count += 1
3328
+ return cname