Cython 3.2.0__cp39-abi3-win32.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 (333) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +350 -0
  4. Cython/Build/Dependencies.py +1314 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +463 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/SharedModule.py +94 -0
  9. Cython/Build/Tests/TestCyCache.py +194 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +815 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +680 -0
  23. Cython/Compiler/Builtin.py +984 -0
  24. Cython/Compiler/CmdLine.py +263 -0
  25. Cython/Compiler/Code.pxd +149 -0
  26. Cython/Compiler/Code.py +3746 -0
  27. Cython/Compiler/Code.pyd +0 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +191 -0
  30. Cython/Compiler/Dataclass.py +864 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +297 -0
  33. Cython/Compiler/ExprNodes.py +15562 -0
  34. Cython/Compiler/FlowControl.pxd +97 -0
  35. Cython/Compiler/FlowControl.py +1451 -0
  36. Cython/Compiler/FlowControl.pyd +0 -0
  37. Cython/Compiler/FusedNode.py +971 -0
  38. Cython/Compiler/FusedNode.pyd +0 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +421 -0
  42. Cython/Compiler/LineTable.py +114 -0
  43. Cython/Compiler/LineTable.pyd +0 -0
  44. Cython/Compiler/Main.py +857 -0
  45. Cython/Compiler/MatchCaseNodes.py +259 -0
  46. Cython/Compiler/MemoryView.py +905 -0
  47. Cython/Compiler/ModuleNode.py +4235 -0
  48. Cython/Compiler/Naming.py +363 -0
  49. Cython/Compiler/Nodes.py +10831 -0
  50. Cython/Compiler/Optimize.py +5288 -0
  51. Cython/Compiler/Options.py +843 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +78 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4638 -0
  54. Cython/Compiler/Parsing.pxd +9 -0
  55. Cython/Compiler/Parsing.py +4775 -0
  56. Cython/Compiler/Parsing.pyd +0 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +5870 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.pxd +48 -0
  61. Cython/Compiler/Scanning.py +701 -0
  62. Cython/Compiler/Scanning.pyd +0 -0
  63. Cython/Compiler/StringEncoding.py +298 -0
  64. Cython/Compiler/Symtab.py +3073 -0
  65. Cython/Compiler/Tests/TestBuffer.py +105 -0
  66. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  67. Cython/Compiler/Tests/TestCmdLine.py +586 -0
  68. Cython/Compiler/Tests/TestCode.py +144 -0
  69. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  70. Cython/Compiler/Tests/TestGrammar.py +202 -0
  71. Cython/Compiler/Tests/TestMemView.py +71 -0
  72. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  73. Cython/Compiler/Tests/TestScanning.py +134 -0
  74. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  75. Cython/Compiler/Tests/TestStringEncoding.py +21 -0
  76. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  77. Cython/Compiler/Tests/TestTreePath.py +103 -0
  78. Cython/Compiler/Tests/TestTypes.py +75 -0
  79. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  80. Cython/Compiler/Tests/TestVisitor.py +61 -0
  81. Cython/Compiler/Tests/Utils.py +36 -0
  82. Cython/Compiler/Tests/__init__.py +1 -0
  83. Cython/Compiler/TreeFragment.py +278 -0
  84. Cython/Compiler/TreePath.py +303 -0
  85. Cython/Compiler/TypeInference.py +591 -0
  86. Cython/Compiler/TypeSlots.py +1174 -0
  87. Cython/Compiler/UFuncs.py +311 -0
  88. Cython/Compiler/UtilNodes.py +389 -0
  89. Cython/Compiler/UtilityCode.py +344 -0
  90. Cython/Compiler/Version.py +8 -0
  91. Cython/Compiler/Visitor.pxd +53 -0
  92. Cython/Compiler/Visitor.py +861 -0
  93. Cython/Compiler/Visitor.pyd +0 -0
  94. Cython/Compiler/__init__.py +1 -0
  95. Cython/Coverage.py +448 -0
  96. Cython/Debugger/Cygdb.py +177 -0
  97. Cython/Debugger/DebugWriter.py +82 -0
  98. Cython/Debugger/Tests/TestLibCython.py +275 -0
  99. Cython/Debugger/Tests/__init__.py +1 -0
  100. Cython/Debugger/Tests/cfuncs.c +8 -0
  101. Cython/Debugger/Tests/codefile +49 -0
  102. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  103. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  104. Cython/Debugger/__init__.py +1 -0
  105. Cython/Debugger/libcython.py +1548 -0
  106. Cython/Debugger/libpython.py +2821 -0
  107. Cython/Debugging.py +20 -0
  108. Cython/Distutils/__init__.py +2 -0
  109. Cython/Distutils/build_ext.py +139 -0
  110. Cython/Distutils/extension.py +96 -0
  111. Cython/Distutils/old_build_ext.py +351 -0
  112. Cython/Includes/cpython/__init__.pxd +173 -0
  113. Cython/Includes/cpython/array.pxd +178 -0
  114. Cython/Includes/cpython/bool.pxd +37 -0
  115. Cython/Includes/cpython/buffer.pxd +112 -0
  116. Cython/Includes/cpython/bytearray.pxd +33 -0
  117. Cython/Includes/cpython/bytes.pxd +200 -0
  118. Cython/Includes/cpython/cellobject.pxd +35 -0
  119. Cython/Includes/cpython/ceval.pxd +8 -0
  120. Cython/Includes/cpython/codecs.pxd +121 -0
  121. Cython/Includes/cpython/complex.pxd +60 -0
  122. Cython/Includes/cpython/contextvars.pxd +145 -0
  123. Cython/Includes/cpython/conversion.pxd +36 -0
  124. Cython/Includes/cpython/datetime.pxd +395 -0
  125. Cython/Includes/cpython/descr.pxd +26 -0
  126. Cython/Includes/cpython/dict.pxd +187 -0
  127. Cython/Includes/cpython/exc.pxd +263 -0
  128. Cython/Includes/cpython/fileobject.pxd +57 -0
  129. Cython/Includes/cpython/float.pxd +47 -0
  130. Cython/Includes/cpython/function.pxd +65 -0
  131. Cython/Includes/cpython/genobject.pxd +25 -0
  132. Cython/Includes/cpython/getargs.pxd +12 -0
  133. Cython/Includes/cpython/instance.pxd +25 -0
  134. Cython/Includes/cpython/iterator.pxd +36 -0
  135. Cython/Includes/cpython/iterobject.pxd +24 -0
  136. Cython/Includes/cpython/list.pxd +92 -0
  137. Cython/Includes/cpython/long.pxd +149 -0
  138. Cython/Includes/cpython/longintrepr.pxd +14 -0
  139. Cython/Includes/cpython/mapping.pxd +63 -0
  140. Cython/Includes/cpython/marshal.pxd +66 -0
  141. Cython/Includes/cpython/mem.pxd +120 -0
  142. Cython/Includes/cpython/memoryview.pxd +50 -0
  143. Cython/Includes/cpython/method.pxd +49 -0
  144. Cython/Includes/cpython/module.pxd +208 -0
  145. Cython/Includes/cpython/number.pxd +258 -0
  146. Cython/Includes/cpython/object.pxd +433 -0
  147. Cython/Includes/cpython/pycapsule.pxd +143 -0
  148. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  149. Cython/Includes/cpython/pyport.pxd +8 -0
  150. Cython/Includes/cpython/pystate.pxd +95 -0
  151. Cython/Includes/cpython/pythread.pxd +53 -0
  152. Cython/Includes/cpython/ref.pxd +141 -0
  153. Cython/Includes/cpython/sequence.pxd +134 -0
  154. Cython/Includes/cpython/set.pxd +119 -0
  155. Cython/Includes/cpython/slice.pxd +70 -0
  156. Cython/Includes/cpython/time.pxd +129 -0
  157. Cython/Includes/cpython/tuple.pxd +72 -0
  158. Cython/Includes/cpython/type.pxd +53 -0
  159. Cython/Includes/cpython/unicode.pxd +639 -0
  160. Cython/Includes/cpython/version.pxd +32 -0
  161. Cython/Includes/cpython/weakref.pxd +78 -0
  162. Cython/Includes/libc/__init__.pxd +1 -0
  163. Cython/Includes/libc/complex.pxd +35 -0
  164. Cython/Includes/libc/errno.pxd +127 -0
  165. Cython/Includes/libc/float.pxd +43 -0
  166. Cython/Includes/libc/limits.pxd +28 -0
  167. Cython/Includes/libc/locale.pxd +46 -0
  168. Cython/Includes/libc/math.pxd +209 -0
  169. Cython/Includes/libc/setjmp.pxd +10 -0
  170. Cython/Includes/libc/signal.pxd +64 -0
  171. Cython/Includes/libc/stddef.pxd +9 -0
  172. Cython/Includes/libc/stdint.pxd +105 -0
  173. Cython/Includes/libc/stdio.pxd +80 -0
  174. Cython/Includes/libc/stdlib.pxd +72 -0
  175. Cython/Includes/libc/string.pxd +50 -0
  176. Cython/Includes/libc/threads.pxd +234 -0
  177. Cython/Includes/libc/time.pxd +52 -0
  178. Cython/Includes/libcpp/__init__.pxd +4 -0
  179. Cython/Includes/libcpp/algorithm.pxd +320 -0
  180. Cython/Includes/libcpp/any.pxd +16 -0
  181. Cython/Includes/libcpp/atomic.pxd +59 -0
  182. Cython/Includes/libcpp/barrier.pxd +22 -0
  183. Cython/Includes/libcpp/bit.pxd +29 -0
  184. Cython/Includes/libcpp/cast.pxd +12 -0
  185. Cython/Includes/libcpp/cmath.pxd +518 -0
  186. Cython/Includes/libcpp/complex.pxd +106 -0
  187. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  188. Cython/Includes/libcpp/deque.pxd +165 -0
  189. Cython/Includes/libcpp/exception.pxd +86 -0
  190. Cython/Includes/libcpp/execution.pxd +15 -0
  191. Cython/Includes/libcpp/forward_list.pxd +63 -0
  192. Cython/Includes/libcpp/functional.pxd +26 -0
  193. Cython/Includes/libcpp/future.pxd +103 -0
  194. Cython/Includes/libcpp/iterator.pxd +34 -0
  195. Cython/Includes/libcpp/latch.pxd +17 -0
  196. Cython/Includes/libcpp/limits.pxd +61 -0
  197. Cython/Includes/libcpp/list.pxd +117 -0
  198. Cython/Includes/libcpp/map.pxd +252 -0
  199. Cython/Includes/libcpp/memory.pxd +115 -0
  200. Cython/Includes/libcpp/mutex.pxd +387 -0
  201. Cython/Includes/libcpp/numbers.pxd +15 -0
  202. Cython/Includes/libcpp/numeric.pxd +131 -0
  203. Cython/Includes/libcpp/optional.pxd +34 -0
  204. Cython/Includes/libcpp/pair.pxd +1 -0
  205. Cython/Includes/libcpp/queue.pxd +25 -0
  206. Cython/Includes/libcpp/random.pxd +166 -0
  207. Cython/Includes/libcpp/semaphore.pxd +43 -0
  208. Cython/Includes/libcpp/set.pxd +228 -0
  209. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  210. Cython/Includes/libcpp/span.pxd +87 -0
  211. Cython/Includes/libcpp/stack.pxd +11 -0
  212. Cython/Includes/libcpp/stop_token.pxd +117 -0
  213. Cython/Includes/libcpp/string.pxd +355 -0
  214. Cython/Includes/libcpp/string_view.pxd +183 -0
  215. Cython/Includes/libcpp/typeindex.pxd +15 -0
  216. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  217. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  218. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  219. Cython/Includes/libcpp/utility.pxd +30 -0
  220. Cython/Includes/libcpp/vector.pxd +186 -0
  221. Cython/Includes/numpy/math.pxd +150 -0
  222. Cython/Includes/openmp.pxd +50 -0
  223. Cython/Includes/posix/__init__.pxd +1 -0
  224. Cython/Includes/posix/dlfcn.pxd +14 -0
  225. Cython/Includes/posix/fcntl.pxd +86 -0
  226. Cython/Includes/posix/ioctl.pxd +4 -0
  227. Cython/Includes/posix/mman.pxd +101 -0
  228. Cython/Includes/posix/resource.pxd +57 -0
  229. Cython/Includes/posix/select.pxd +21 -0
  230. Cython/Includes/posix/signal.pxd +73 -0
  231. Cython/Includes/posix/stat.pxd +98 -0
  232. Cython/Includes/posix/stdio.pxd +37 -0
  233. Cython/Includes/posix/stdlib.pxd +29 -0
  234. Cython/Includes/posix/strings.pxd +9 -0
  235. Cython/Includes/posix/time.pxd +71 -0
  236. Cython/Includes/posix/types.pxd +30 -0
  237. Cython/Includes/posix/uio.pxd +26 -0
  238. Cython/Includes/posix/unistd.pxd +271 -0
  239. Cython/Includes/posix/wait.pxd +38 -0
  240. Cython/Plex/Actions.pxd +24 -0
  241. Cython/Plex/Actions.py +119 -0
  242. Cython/Plex/Actions.pyd +0 -0
  243. Cython/Plex/DFA.pxd +14 -0
  244. Cython/Plex/DFA.py +164 -0
  245. Cython/Plex/DFA.pyd +0 -0
  246. Cython/Plex/Errors.py +48 -0
  247. Cython/Plex/Lexicons.py +178 -0
  248. Cython/Plex/Machines.pxd +36 -0
  249. Cython/Plex/Machines.py +238 -0
  250. Cython/Plex/Machines.pyd +0 -0
  251. Cython/Plex/Regexps.py +535 -0
  252. Cython/Plex/Scanners.pxd +45 -0
  253. Cython/Plex/Scanners.py +328 -0
  254. Cython/Plex/Scanners.pyd +0 -0
  255. Cython/Plex/Transitions.pxd +14 -0
  256. Cython/Plex/Transitions.py +239 -0
  257. Cython/Plex/Transitions.pyd +0 -0
  258. Cython/Plex/__init__.py +34 -0
  259. Cython/Runtime/__init__.py +1 -0
  260. Cython/Runtime/refnanny.pyd +0 -0
  261. Cython/Runtime/refnanny.pyx +237 -0
  262. Cython/Shadow.py +690 -0
  263. Cython/Shadow.pyi +521 -0
  264. Cython/StringIOTree.py +170 -0
  265. Cython/StringIOTree.pyd +0 -0
  266. Cython/Tempita/__init__.py +4 -0
  267. Cython/Tempita/_looper.py +154 -0
  268. Cython/Tempita/_tempita.py +1091 -0
  269. Cython/Tempita/_tempita.pyd +0 -0
  270. Cython/TestUtils.py +422 -0
  271. Cython/Tests/TestCodeWriter.py +128 -0
  272. Cython/Tests/TestCythonUtils.py +202 -0
  273. Cython/Tests/TestJediTyper.py +223 -0
  274. Cython/Tests/TestShadow.py +114 -0
  275. Cython/Tests/TestStringIOTree.py +67 -0
  276. Cython/Tests/TestTestUtils.py +90 -0
  277. Cython/Tests/__init__.py +1 -0
  278. Cython/Tests/xmlrunner.py +390 -0
  279. Cython/Utility/AsyncGen.c +1031 -0
  280. Cython/Utility/Buffer.c +865 -0
  281. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  282. Cython/Utility/Builtins.c +810 -0
  283. Cython/Utility/CConvert.pyx +134 -0
  284. Cython/Utility/CMath.c +104 -0
  285. Cython/Utility/CommonStructures.c +226 -0
  286. Cython/Utility/Complex.c +378 -0
  287. Cython/Utility/Coroutine.c +2300 -0
  288. Cython/Utility/CpdefEnums.pyx +103 -0
  289. Cython/Utility/CppConvert.pyx +282 -0
  290. Cython/Utility/CppSupport.cpp +151 -0
  291. Cython/Utility/CythonFunction.c +1832 -0
  292. Cython/Utility/Dataclasses.c +101 -0
  293. Cython/Utility/Embed.c +121 -0
  294. Cython/Utility/Exceptions.c +1016 -0
  295. Cython/Utility/ExtensionTypes.c +996 -0
  296. Cython/Utility/FunctionArguments.c +1043 -0
  297. Cython/Utility/FusedFunction.pyx +44 -0
  298. Cython/Utility/ImportExport.c +907 -0
  299. Cython/Utility/MemoryView.pxd +188 -0
  300. Cython/Utility/MemoryView.pyx +1482 -0
  301. Cython/Utility/MemoryView_C.c +927 -0
  302. Cython/Utility/ModuleSetupCode.c +3203 -0
  303. Cython/Utility/NumpyImportArray.c +46 -0
  304. Cython/Utility/ObjectHandling.c +3273 -0
  305. Cython/Utility/Optimize.c +1603 -0
  306. Cython/Utility/Overflow.c +384 -0
  307. Cython/Utility/Printing.c +86 -0
  308. Cython/Utility/Profile.c +732 -0
  309. Cython/Utility/StringTools.c +1379 -0
  310. Cython/Utility/Synchronization.c +399 -0
  311. Cython/Utility/TString.c +356 -0
  312. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  313. Cython/Utility/TestCythonScope.pyx +75 -0
  314. Cython/Utility/TestUtilityLoader.c +12 -0
  315. Cython/Utility/TypeConversion.c +1385 -0
  316. Cython/Utility/UFuncs.pyx +50 -0
  317. Cython/Utility/UFuncs_C.c +89 -0
  318. Cython/Utility/__init__.py +28 -0
  319. Cython/Utility/arrayarray.h +167 -0
  320. Cython/Utils.py +687 -0
  321. Cython/Utils.pyd +0 -0
  322. Cython/__init__.py +10 -0
  323. Cython/__init__.pyi +7 -0
  324. Cython/py.typed +0 -0
  325. cython-3.2.0.dist-info/METADATA +85 -0
  326. cython-3.2.0.dist-info/RECORD +333 -0
  327. cython-3.2.0.dist-info/WHEEL +5 -0
  328. cython-3.2.0.dist-info/entry_points.txt +4 -0
  329. cython-3.2.0.dist-info/top_level.txt +3 -0
  330. cython.py +29 -0
  331. pyximport/__init__.py +4 -0
  332. pyximport/pyxbuild.py +160 -0
  333. pyximport/pyximport.py +482 -0
@@ -0,0 +1,4235 @@
1
+ #
2
+ # Module parse tree node
3
+ #
4
+
5
+
6
+ import cython
7
+ cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object,
8
+ error=object, warning=object, py_object_type=object, UtilityCode=object,
9
+ EncodedString=object, re=object)
10
+
11
+ from collections import defaultdict
12
+ import json
13
+ import operator
14
+ import os
15
+ import pathlib
16
+ import re
17
+ import sys
18
+ from typing import Sequence
19
+
20
+ from .PyrexTypes import CPtrType
21
+ from . import Future
22
+ from . import Annotate
23
+ from . import Code
24
+ from . import Naming
25
+ from . import Nodes
26
+ from . import Options
27
+ from . import TypeSlots
28
+ from . import PyrexTypes
29
+ from . import Pythran
30
+
31
+ from .Errors import error, warning, CompileError, format_position
32
+ from .PyrexTypes import py_object_type, get_all_subtypes
33
+ from ..Utils import open_new_file, replace_suffix, decode_filename, build_hex_version, is_cython_generated_file
34
+ from .Code import UtilityCode, IncludeCode, TempitaUtilityCode
35
+ from .StringEncoding import EncodedString, bytes_literal, encoded_string_or_bytes_literal
36
+ from .Pythran import has_np_pythran
37
+
38
+
39
+ def replace_suffix_encoded(path, newsuf):
40
+ # calls replace suffix and returns a EncodedString or BytesLiteral with the encoding set
41
+ newpath = replace_suffix(path, newsuf)
42
+ return as_encoded_filename(newpath)
43
+
44
+ def as_encoded_filename(path):
45
+ # wraps the path with either EncodedString or BytesLiteral (depending on its input type)
46
+ # and sets the encoding to the file system encoding
47
+ return encoded_string_or_bytes_literal(path, sys.getfilesystemencoding())
48
+
49
+
50
+ def check_c_declarations_pxd(module_node):
51
+ module_node.scope.check_c_classes_pxd()
52
+ return module_node
53
+
54
+
55
+ def check_c_declarations(module_node):
56
+ module_node.scope.check_c_classes()
57
+ module_node.scope.check_c_functions()
58
+ return module_node
59
+
60
+
61
+ def generate_c_code_config(env, options):
62
+ if Options.annotate or options.annotate:
63
+ emit_linenums = False
64
+ else:
65
+ emit_linenums = options.emit_linenums
66
+
67
+ if hasattr(options, "emit_code_comments"):
68
+ print('Warning: option emit_code_comments is deprecated. '
69
+ 'Instead, use compiler directive emit_code_comments.')
70
+
71
+ return Code.CCodeConfig(
72
+ emit_linenums=emit_linenums,
73
+ emit_code_comments=env.directives['emit_code_comments'],
74
+ c_line_in_traceback=options.c_line_in_traceback)
75
+
76
+ # The code required to generate one comparison from another.
77
+ # The keys are (from, to).
78
+ # The comparison operator always goes first, with equality possibly second.
79
+ # The first value specifies if the comparison is inverted. The second is the
80
+ # logic op to use, and the third is if the equality is inverted or not.
81
+ TOTAL_ORDERING = {
82
+ # a > b from (not a < b) and (a != b)
83
+ ('__lt__', '__gt__'): (True, '&&', True),
84
+ # a <= b from (a < b) or (a == b)
85
+ ('__lt__', '__le__'): (False, '||', False),
86
+ # a >= b from (not a < b).
87
+ ('__lt__', '__ge__'): (True, '', None),
88
+
89
+ # a >= b from (not a <= b) or (a == b)
90
+ ('__le__', '__ge__'): (True, '||', False),
91
+ # a < b, from (a <= b) and (a != b)
92
+ ('__le__', '__lt__'): (False, '&&', True),
93
+ # a > b from (not a <= b)
94
+ ('__le__', '__gt__'): (True, '', None),
95
+
96
+ # a < b from (not a > b) and (a != b)
97
+ ('__gt__', '__lt__'): (True, '&&', True),
98
+ # a >= b from (a > b) or (a == b)
99
+ ('__gt__', '__ge__'): (False, '||', False),
100
+ # a <= b from (not a > b)
101
+ ('__gt__', '__le__'): (True, '', None),
102
+
103
+ # Return a <= b from (not a >= b) or (a == b)
104
+ ('__ge__', '__le__'): (True, '||', False),
105
+ # a > b from (a >= b) and (a != b)
106
+ ('__ge__', '__gt__'): (False, '&&', True),
107
+ # a < b from (not a >= b)
108
+ ('__ge__', '__lt__'): (True, '', None),
109
+ }
110
+
111
+ class SharedUtilityExporter:
112
+ """
113
+ Class responsible for generating code that imports and exports shared utility functions.
114
+
115
+ Mark the positions where the functions should be called with `call_import_code()`/`call_export_code()`.
116
+ The function calls and import/export functions are generated when `generate_exporting_functions()`
117
+ is called. This approach is needed because the list of the shared functions is only known in the later
118
+ stages of compilation.
119
+ """
120
+ def __init__(self, pos, mod_init_subfunction, scope):
121
+ self.in_shared_utility_module = bool(scope.context.shared_c_file_path)
122
+ self.using_shared_utility_module = bool(scope.context.shared_utility_qualified_name)
123
+ self.pos = pos
124
+ self.scope = scope
125
+ self.import_code = mod_init_subfunction("Shared function import code")
126
+ self.export_code = mod_init_subfunction("Shared function export code")
127
+
128
+ def has_shared_exports(self, shared_func_definitions: Sequence[Code.SharedFunctionDecl]) -> bool:
129
+ return bool(self.in_shared_utility_module and shared_func_definitions)
130
+
131
+ def has_shared_imports(self, shared_func_definitions: Sequence[Code.SharedFunctionDecl]) -> bool:
132
+ return bool(self.using_shared_utility_module and shared_func_definitions)
133
+
134
+ def call_import_code(self, code):
135
+ self.import_code.set_call_code(code)
136
+
137
+ def call_export_code(self, code):
138
+ self.export_code.set_call_code(code)
139
+
140
+ def _generate_c_shared_function_export_code(self, code, shared_function_definitions: Sequence[Code.SharedFunctionDecl]):
141
+ # We use the function cname also as exported name.
142
+ exports = [
143
+ (f"{shared_func_def.ret}({shared_func_def.params})", shared_func_def.name, shared_func_def.name)
144
+ for shared_func_def in shared_function_definitions
145
+ ]
146
+ code.globalstate.use_utility_code(
147
+ UtilityCode.load_cached("FunctionExport", "ImportExport.c"))
148
+
149
+ _generate_export_code(code, self.pos, exports, "__Pyx_ExportFunction", "void (*{name})(void)")
150
+
151
+ def _generate_c_shared_function_import_code_for_module(self, code, function_definitions: Sequence[Code.SharedFunctionDecl]):
152
+ # We use the function cname also as exported name.
153
+
154
+ imports = [
155
+ (f"{shared_func_def.ret}({shared_func_def.params})", shared_func_def.name, shared_func_def.name)
156
+ for shared_func_def in function_definitions
157
+ ]
158
+ code.globalstate.use_utility_code(
159
+ UtilityCode.load_cached("FunctionImport", "ImportExport.c"))
160
+
161
+ shared_utility_qualified_name = EncodedString(self.scope.context.shared_utility_qualified_name)
162
+ import_func = f"__Pyx_ImportFunction_{Naming.cyversion}"
163
+ _generate_import_code(
164
+ code, self.pos, imports, shared_utility_qualified_name, import_func, "void (**{name})(void)")
165
+
166
+ def _generate_exports(self, shared_utility_functions: Sequence[Code.SharedFunctionDecl]):
167
+ if self.has_shared_exports(shared_utility_functions):
168
+ with self.export_code as inner_code:
169
+ self._generate_c_shared_function_export_code(
170
+ inner_code,
171
+ shared_utility_functions
172
+ )
173
+
174
+ def _generate_imports(self, shared_utility_functions: Sequence[Code.SharedFunctionDecl]):
175
+ if self.has_shared_imports(shared_utility_functions):
176
+ with self.import_code as inner_code:
177
+ self._generate_c_shared_function_import_code_for_module(
178
+ inner_code,
179
+ shared_utility_functions
180
+ )
181
+
182
+ def generate_exporting_functions(self, code):
183
+ shared_utility_functions = code.globalstate.shared_utility_functions
184
+ code.enter_cfunc_scope(self.scope)
185
+ self._generate_exports(shared_utility_functions)
186
+ self._generate_imports(shared_utility_functions)
187
+ code.exit_cfunc_scope()
188
+
189
+
190
+ class ModuleNode(Nodes.Node, Nodes.BlockNode):
191
+ # doc string or None
192
+ # body StatListNode
193
+ #
194
+ # referenced_modules [ModuleScope]
195
+ # full_module_name string
196
+ #
197
+ # scope The module scope.
198
+ # compilation_source A CompilationSource (see Main)
199
+ # directives Top-level compiler directives
200
+
201
+ child_attrs = ["body"]
202
+ directives = None
203
+ # internal - used in merging
204
+ pxd_stats = None
205
+ utility_code_stats = None
206
+
207
+ @property
208
+ def local_scope(self):
209
+ # Make the module node (and its init function) look like a FuncDefNode.
210
+ return self.scope
211
+
212
+ def merge_in(self, tree, scope, stage):
213
+ # Merges in the contents of another tree, and possibly scope. With the
214
+ # current implementation below, this must be done right prior
215
+ # to code generation.
216
+ # Stage is one of "pxd" or "utility" to indicate pxd file or utility
217
+ # code. This helps define the order.
218
+ #
219
+ # Note: This way of doing it seems strange -- I believe the
220
+ # right concept is to split ModuleNode into a ModuleNode and a
221
+ # CodeGenerator, and tell that CodeGenerator to generate code
222
+ # from multiple sources.
223
+ assert isinstance(self.body, Nodes.StatListNode)
224
+ assert stage in ('pxd', 'utility')
225
+
226
+ if self.pxd_stats is None:
227
+ self.pxd_stats = Nodes.StatListNode(self.body.pos, stats=[])
228
+ self.utility_code_stats = Nodes.StatListNode(self.body.pos, stats=[])
229
+ self.body.stats.insert(0, self.pxd_stats)
230
+ self.body.stats.insert(0, self.utility_code_stats)
231
+
232
+ if scope.directives != self.scope.directives:
233
+ # merged in nodes should keep their original compiler directives
234
+ # (for example inline cdef functions)
235
+ tree = Nodes.CompilerDirectivesNode(tree.pos, body=tree, directives=scope.directives)
236
+
237
+ target_stats = self.pxd_stats if stage == "pxd" else self.utility_code_stats
238
+ if isinstance(tree, Nodes.StatListNode):
239
+ target_stats.stats.extend(tree.stats)
240
+ else:
241
+ target_stats.stats.append(tree)
242
+
243
+ self.scope.utility_code_list.extend(scope.utility_code_list)
244
+
245
+ for inc in scope.c_includes.values():
246
+ self.scope.process_include(inc)
247
+
248
+ def extend_if_not_in(L1, L2):
249
+ for x in L2:
250
+ if x not in L1:
251
+ L1.append(x)
252
+
253
+ extend_if_not_in(self.scope.included_files, scope.included_files)
254
+
255
+ def merge_scope(self, scope, internalise_c_class_entries=True):
256
+ # Ensure that we don't generate import code for these entries!
257
+ for entry in scope.c_class_entries:
258
+ entry.type.module_name = self.full_module_name
259
+ entry.type.scope.directives["internal"] = internalise_c_class_entries
260
+
261
+ self.scope.merge_in(scope)
262
+
263
+ def with_compiler_directives(self):
264
+ # When merging a utility code module into the user code we need to preserve
265
+ # the original compiler directives. This returns the body of the module node,
266
+ # wrapped in its set of directives.
267
+ body = Nodes.CompilerDirectivesNode(self.pos, directives=self.directives, body=self.body)
268
+ return body
269
+
270
+ def analyse_declarations(self, env):
271
+ if has_np_pythran(env):
272
+ Pythran.include_pythran_generic(env)
273
+ if self.directives:
274
+ env.old_style_globals = self.directives['old_style_globals']
275
+ if not Options.docstrings:
276
+ env.doc = self.doc = None
277
+ elif Options.embed_pos_in_docstring:
278
+ env.doc = EncodedString('File: %s (starting at line %s)' % Nodes.relative_position(self.pos))
279
+ if self.doc is not None:
280
+ env.doc = EncodedString(env.doc + '\n' + self.doc)
281
+ env.doc.encoding = self.doc.encoding
282
+ else:
283
+ env.doc = self.doc
284
+ env.directives = self.directives
285
+
286
+ self.body.analyse_declarations(env)
287
+
288
+ cy_pymutex_type = PyrexTypes.get_cy_pymutex_type()
289
+ if env.find_shared_usages_of_type(cy_pymutex_type):
290
+ # Be very suspicious of cython locks that are shared.
291
+ # They have the potential to cause ABI issues.
292
+ self.scope.use_utility_code(
293
+ UtilityCode.load_cached(
294
+ "CythonPyMutexPublicCheck", "Synchronization.c"
295
+ ))
296
+
297
+ def prepare_utility_code(self):
298
+ # prepare any utility code that must be created before code generation
299
+ # specifically: CythonUtilityCode
300
+ env = self.scope
301
+ if env.has_import_star:
302
+ self.create_import_star_conversion_utility_code(env)
303
+ for name, entry in sorted(env.entries.items()):
304
+ if (entry.create_wrapper and entry.scope is env
305
+ and entry.is_type and (entry.type.is_enum or entry.type.is_cpp_enum)):
306
+ entry.type.create_type_wrapper(env)
307
+
308
+ def process_implementation(self, options, result):
309
+ env = self.scope
310
+ env.return_type = PyrexTypes.c_void_type
311
+ self.referenced_modules = []
312
+ self.find_referenced_modules(env, self.referenced_modules, {})
313
+ self.sort_cdef_classes(env)
314
+ self.generate_c_code(env, options, result)
315
+ self.generate_h_code(env, options, result)
316
+ self.generate_api_code(env, options, result)
317
+
318
+ def has_imported_c_functions(self):
319
+ for module in self.referenced_modules:
320
+ for entry in module.cfunc_entries:
321
+ if entry.defined_in_pxd:
322
+ return 1
323
+ return 0
324
+
325
+ def assure_safe_target(self, path, allow_failed=False):
326
+ # Check for a common gotcha for new users: naming your .pyx file after the .c file you want to wrap
327
+ if not is_cython_generated_file(path, allow_failed=allow_failed, if_not_found=True):
328
+ # Raising a fatal CompileError instead of calling error() to prevent castrating an existing file.
329
+ raise CompileError(
330
+ self.pos, 'The output file already exists and does not look like it was generated by Cython: "%s"' %
331
+ os.path.basename(path))
332
+
333
+ def generate_h_code(self, env, options, result):
334
+ def h_entries(entries, api=0, pxd=0):
335
+ return [entry for entry in entries
336
+ if ((entry.visibility == 'public') or
337
+ (api and entry.api) or
338
+ (pxd and entry.defined_in_pxd))]
339
+ h_types = h_entries(env.type_entries, api=1)
340
+ h_vars = h_entries(env.var_entries)
341
+ h_funcs = h_entries(env.cfunc_entries)
342
+ h_extension_types = h_entries(env.c_class_entries)
343
+
344
+ if h_types or h_vars or h_funcs or h_extension_types:
345
+ result.h_file = replace_suffix_encoded(result.c_file, ".h")
346
+ self.assure_safe_target(result.h_file)
347
+
348
+ h_code_writer = Code.CCodeWriter()
349
+ c_code_config = generate_c_code_config(env, options)
350
+ globalstate = Code.GlobalState(h_code_writer, self, c_code_config)
351
+ globalstate.initialize_main_h_code() # in-case utility code is used in the header
352
+ h_code_start = globalstate.parts['h_code']
353
+ h_code_main = globalstate.parts['type_declarations']
354
+ h_code_end = globalstate.parts['end']
355
+ if options.generate_pxi:
356
+ result.i_file = replace_suffix_encoded(result.c_file, ".pxi")
357
+ i_code = Code.PyrexCodeWriter(result.i_file)
358
+ else:
359
+ i_code = None
360
+
361
+ h_code_start.put_generated_by()
362
+ h_guard = self.api_name(Naming.h_guard_prefix, env)
363
+ h_code_start.put_h_guard(h_guard)
364
+ h_code_start.putln("")
365
+ h_code_start.putln('#include "Python.h"')
366
+ self.generate_type_header_code(h_types, h_code_main)
367
+ if options.capi_reexport_cincludes:
368
+ self.generate_includes(env, [], h_code_main)
369
+ h_code_main.putln("")
370
+ api_guard = self.api_name(Naming.api_guard_prefix, env)
371
+ h_code_main.putln("#ifndef %s" % api_guard)
372
+ h_code_main.putln("")
373
+ self.generate_extern_c_macro_definition(h_code_main, env.is_cpp())
374
+ h_code_main.putln("")
375
+ self.generate_dl_import_macro(h_code_main)
376
+ if h_extension_types:
377
+ h_code_main.putln("")
378
+ for entry in h_extension_types:
379
+ self.generate_cclass_header_code(entry.type, h_code_main)
380
+ if i_code:
381
+ self.generate_cclass_include_code(entry.type, i_code)
382
+ globalstate.use_entry_utility_code(entry)
383
+ if h_funcs:
384
+ h_code_main.putln("")
385
+ for entry in h_funcs:
386
+ self.generate_public_declaration(entry, h_code_main, i_code)
387
+ globalstate.use_entry_utility_code(entry)
388
+ if h_vars:
389
+ h_code_main.putln("")
390
+ for entry in h_vars:
391
+ self.generate_public_declaration(entry, h_code_main, i_code)
392
+ globalstate.use_entry_utility_code(entry)
393
+ h_code_main.putln("")
394
+ h_code_main.putln("#endif /* !%s */" % api_guard)
395
+ h_code_main.putln("")
396
+ h_code_main.putln("/* WARNING: the interface of the module init function changed in CPython 3.5. */")
397
+ h_code_main.putln("/* It now returns a PyModuleDef instance instead of a PyModule instance. */")
398
+ h_code_main.putln("")
399
+ py3_mod_func_name = self.mod_init_func_cname('PyInit', env)
400
+ warning_string = EncodedString('Use PyImport_AppendInittab(%s, %s) instead of calling %s directly.' % (
401
+ env.module_name.as_c_string_literal(), py3_mod_func_name, py3_mod_func_name))
402
+ h_code_main.putln('/* WARNING: %s from Python 3.5 */' % warning_string.rstrip('.'))
403
+ h_code_main.putln("PyMODINIT_FUNC %s(void);" % py3_mod_func_name)
404
+ h_code_main.putln("")
405
+ h_code_main.putln("#if PY_VERSION_HEX >= 0x03050000 "
406
+ "&& (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) "
407
+ "|| (defined(__cplusplus) && __cplusplus >= 201402L))")
408
+ h_code_main.putln("#if defined(__cplusplus) && __cplusplus >= 201402L")
409
+ h_code_main.putln("[[deprecated(%s)]] inline" % warning_string.as_c_string_literal())
410
+ h_code_main.putln("#elif defined(__GNUC__) || defined(__clang__)")
411
+ h_code_main.putln('__attribute__ ((__deprecated__(%s), __unused__)) __inline__' % (
412
+ warning_string.as_c_string_literal()))
413
+ h_code_main.putln("#elif defined(_MSC_VER)")
414
+ h_code_main.putln('__declspec(deprecated(%s)) __inline' % (
415
+ warning_string.as_c_string_literal()))
416
+ h_code_main.putln('#endif')
417
+ h_code_main.putln("static PyObject* __PYX_WARN_IF_%s_INIT_CALLED(PyObject* res) {" % py3_mod_func_name)
418
+ h_code_main.putln("return res;")
419
+ h_code_main.putln("}")
420
+ # Function call is converted to warning macro; uncalled (pointer) is not
421
+ h_code_main.putln('#define %s() __PYX_WARN_IF_%s_INIT_CALLED(%s())' % (
422
+ py3_mod_func_name, py3_mod_func_name, py3_mod_func_name))
423
+ h_code_main.putln('#endif')
424
+
425
+ h_code_end.putln("")
426
+ h_code_end.putln("#endif /* !%s */" % h_guard)
427
+
428
+ with open_new_file(result.h_file) as f:
429
+ h_code_writer.copyto(f)
430
+
431
+ def generate_public_declaration(self, entry, h_code, i_code):
432
+ h_code.putln("%s %s;" % (
433
+ Naming.extern_c_macro,
434
+ entry.type.declaration_code(entry.cname)))
435
+ if i_code:
436
+ i_code.putln("cdef extern %s" % (
437
+ entry.type.declaration_code(entry.cname, pyrex=1)))
438
+
439
+ def api_name(self, prefix, env):
440
+ api_name = self.punycode_module_name(prefix, env.qualified_name)
441
+ return api_name.replace(".", "__")
442
+
443
+ def generate_api_code(self, env, options, result):
444
+ def api_entries(entries, pxd=0):
445
+ return [entry for entry in entries
446
+ if entry.api or (pxd and entry.defined_in_pxd)]
447
+ api_vars = api_entries(env.var_entries)
448
+ api_funcs = api_entries(env.cfunc_entries)
449
+ api_extension_types = api_entries(env.c_class_entries)
450
+
451
+ if not (api_vars or api_funcs or api_extension_types):
452
+ return
453
+
454
+ result.api_file = replace_suffix_encoded(result.c_file, "_api.h")
455
+ self.assure_safe_target(result.api_file)
456
+
457
+ h_code = Code.CCodeWriter()
458
+ c_code_config = generate_c_code_config(env, options)
459
+ globalstate = Code.GlobalState(h_code, self, c_code_config)
460
+ globalstate.initialize_main_h_code() # in-case utility code is used in the header
461
+ h_code.put_generated_by()
462
+ api_guard = self.api_name(Naming.api_guard_prefix, env)
463
+ h_code.put_h_guard(api_guard)
464
+ # Work around https://bugs.python.org/issue4709
465
+ h_code.putln('#ifdef __MINGW64__')
466
+ h_code.putln('#define MS_WIN64')
467
+ h_code.putln('#endif')
468
+
469
+ def put_utility_code(name, src_file, include_requires=True):
470
+ proto, impl = UtilityCode.load_as_string(name, src_file, include_requires=include_requires)
471
+ if proto:
472
+ h_code.put(proto)
473
+ if impl:
474
+ h_code.put(impl)
475
+
476
+ h_code.putln('#include "Python.h"')
477
+ if result.h_file:
478
+ h_filename = os.path.basename(result.h_file)
479
+ h_filename = as_encoded_filename(h_filename)
480
+ h_code.putln('#include %s' % h_filename.as_c_string_literal())
481
+ if api_extension_types:
482
+ h_code.putln("")
483
+ for entry in api_extension_types:
484
+ type = entry.type
485
+ h_code.putln("static PyTypeObject *%s = 0;" % type.typeptr_cname)
486
+ h_code.putln("#define %s (*%s)" % (
487
+ type.typeobj_cname, type.typeptr_cname))
488
+ h_code.globalstate.use_entry_utility_code(entry)
489
+ if api_funcs:
490
+ h_code.putln("")
491
+ for entry in api_funcs:
492
+ type = CPtrType(entry.type)
493
+ cname = env.mangle(Naming.func_prefix_api, entry.name)
494
+ h_code.putln("static %s = 0;" % type.declaration_code(cname))
495
+ h_code.putln("#define %s %s" % (entry.name, cname))
496
+ h_code.globalstate.use_entry_utility_code(entry)
497
+ if api_vars:
498
+ h_code.putln("")
499
+ for entry in api_vars:
500
+ type = CPtrType(entry.type)
501
+ cname = env.mangle(Naming.varptr_prefix_api, entry.name)
502
+ h_code.putln("static %s = 0;" % type.declaration_code(cname))
503
+ h_code.putln("#define %s (*%s)" % (entry.name, cname))
504
+ h_code.globalstate.use_entry_utility_code(entry)
505
+ if api_vars:
506
+ put_utility_code("VoidPtrImport", "ImportExport.c")
507
+ if api_funcs:
508
+ put_utility_code("FunctionImport", "ImportExport.c")
509
+ if api_extension_types:
510
+ put_utility_code("TypeImport", "ImportExport.c")
511
+ h_code.putln("")
512
+ h_code.putln("static int %s(void) {" % self.api_name("import", env))
513
+ h_code.putln("PyObject *module = 0;")
514
+ h_code.putln('module = PyImport_ImportModule(%s);' % env.qualified_name.as_c_string_literal())
515
+ h_code.putln("if (!module) goto bad;")
516
+ for entry in api_funcs:
517
+ cname = env.mangle(Naming.func_prefix_api, entry.name)
518
+ sig = entry.type.signature_string()
519
+ h_code.putln(
520
+ 'if (__Pyx_ImportFunction_%s(module, %s, (void (**)(void))&%s, "%s") < 0) goto bad;'
521
+ % (Naming.cyversion, entry.name.as_c_string_literal(), cname, sig))
522
+ for entry in api_vars:
523
+ cname = env.mangle(Naming.varptr_prefix_api, entry.name)
524
+ sig = entry.type.empty_declaration_code()
525
+ h_code.putln(
526
+ 'if (__Pyx_ImportVoidPtr_%s(module, %s, (void **)&%s, "%s") < 0) goto bad;'
527
+ % (Naming.cyversion, entry.name.as_c_string_literal(), cname, sig))
528
+ with ModuleImportGenerator(h_code, imported_modules={env.qualified_name: 'module'}) as import_generator:
529
+ for entry in api_extension_types:
530
+ self.generate_type_import_call(entry.type, h_code, import_generator, error_code="goto bad;", is_api=True)
531
+ h_code.putln("Py_DECREF(module); module = 0;")
532
+ h_code.putln("return 0;")
533
+ h_code.putln("bad:")
534
+ h_code.putln("Py_XDECREF(module);")
535
+ h_code.putln("return -1;")
536
+ h_code.putln("}")
537
+ h_code.putln("")
538
+ h_code.putln("#endif /* !%s */" % api_guard)
539
+
540
+ f = open_new_file(result.api_file)
541
+ try:
542
+ h_code.copyto(f)
543
+ finally:
544
+ f.close()
545
+
546
+ def generate_cclass_header_code(self, type, h_code):
547
+ h_code.putln("%s %s %s;" % (
548
+ Naming.extern_c_macro,
549
+ PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"),
550
+ type.typeobj_cname))
551
+
552
+ def generate_cclass_include_code(self, type, i_code):
553
+ i_code.putln("cdef extern class %s.%s:" % (
554
+ type.module_name, type.name))
555
+ i_code.indent()
556
+ var_entries = type.scope.var_entries
557
+ if var_entries:
558
+ for entry in var_entries:
559
+ i_code.putln("cdef %s" % (
560
+ entry.type.declaration_code(entry.cname, pyrex=1)))
561
+ else:
562
+ i_code.putln("pass")
563
+ i_code.dedent()
564
+
565
+ def generate_c_code(self, env, options, result):
566
+ self.assure_safe_target(result.c_file, allow_failed=True)
567
+ modules = self.referenced_modules
568
+
569
+ if Options.annotate or options.annotate:
570
+ show_entire_c_code = Options.annotate == "fullc" or options.annotate == "fullc"
571
+ rootwriter = Annotate.AnnotationCCodeWriter(
572
+ show_entire_c_code=show_entire_c_code,
573
+ source_desc=self.compilation_source.source_desc,
574
+ )
575
+ else:
576
+ rootwriter = Code.CCodeWriter()
577
+
578
+ c_code_config = generate_c_code_config(env, options)
579
+
580
+ globalstate = Code.GlobalState(
581
+ rootwriter, self,
582
+ code_config=c_code_config,
583
+ common_utility_include_dir=options.common_utility_include_dir,
584
+ )
585
+ globalstate.initialize_main_c_code()
586
+ h_code = globalstate['h_code']
587
+
588
+ globalstate.module_pos = self.pos
589
+ globalstate.directives = self.directives
590
+
591
+ self.generate_module_preamble(env, options, modules, result.embedded_metadata, h_code)
592
+
593
+ globalstate.use_utility_code(refnanny_utility_code)
594
+
595
+ code = globalstate['before_global_var']
596
+ code.putln('#define __Pyx_MODULE_NAME %s' %
597
+ self.full_module_name.as_c_string_literal())
598
+ module_is_main = self.is_main_module_flag_cname()
599
+ code.putln("extern int %s;" % module_is_main)
600
+ code.putln("int %s = 0;" % module_is_main)
601
+ code.putln("")
602
+ code.putln("/* Implementation of %s */" % env.qualified_name.as_c_string_literal())
603
+
604
+ code = globalstate['late_includes']
605
+ self.generate_includes(env, modules, code, early=False)
606
+
607
+ code = globalstate['module_code']
608
+
609
+ self.generate_cached_builtins_decls(env, code)
610
+
611
+ # generate normal variable and function definitions
612
+ self.generate_lambda_definitions(env, code)
613
+ self.generate_variable_definitions(env, code)
614
+ self.body.generate_function_definitions(env, code)
615
+
616
+ # generate extension types and methods
617
+ code = globalstate['module_exttypes']
618
+ self.generate_typeobj_definitions(env, code)
619
+ self.generate_method_table(env, code)
620
+ if env.has_import_star:
621
+ self.generate_import_star(env, code)
622
+
623
+ # initialise the macro to reduce the code size of one-time functionality
624
+ globalstate['module_state'].put_code_here(
625
+ UtilityCode.load("SmallCodeConfig", "ModuleSetupCode.c"))
626
+
627
+ self.generate_module_state_start(env, globalstate['module_state'])
628
+ self.generate_module_state_clear(env, globalstate['module_state_clear'])
629
+ self.generate_module_state_traverse(env, globalstate['module_state_traverse'])
630
+
631
+ shared_utility_exporter = SharedUtilityExporter(
632
+ self.pos,
633
+ self.mod_init_subfunction(self.pos, self.scope, globalstate['init_module']),
634
+ self.scope
635
+ )
636
+
637
+ # init_globals is inserted before this
638
+ self.generate_module_init_func(
639
+ modules[:-1], shared_utility_exporter, env, globalstate['init_module']
640
+ )
641
+ self.generate_module_cleanup_func(env, globalstate['cleanup_module'])
642
+ if Options.embed:
643
+ self.generate_main_method(env, globalstate['main_method'])
644
+ self.generate_filename_table(globalstate['filename_table'])
645
+
646
+ self.generate_declarations_for_modules(env, modules, globalstate)
647
+ h_code.write('\n')
648
+
649
+ for utilcode in env.utility_code_list[:]:
650
+ globalstate.use_utility_code(utilcode)
651
+
652
+ shared_utility_exporter.generate_exporting_functions(code)
653
+
654
+ globalstate.finalize_main_c_code()
655
+
656
+ self.generate_module_state_end(env, modules, globalstate)
657
+
658
+ f = open_new_file(result.c_file)
659
+ try:
660
+ rootwriter.copyto(f)
661
+ finally:
662
+ f.close()
663
+ result.c_file_generated = 1
664
+ if options.gdb_debug:
665
+ self._serialize_lineno_map(env, rootwriter)
666
+ if Options.annotate or options.annotate:
667
+ self._generate_annotations(rootwriter, result, options)
668
+
669
+ def _generate_annotations(self, rootwriter, result, options):
670
+ self.annotate(rootwriter)
671
+
672
+ coverage_xml_filename = Options.annotate_coverage_xml or options.annotate_coverage_xml
673
+ if coverage_xml_filename and os.path.exists(coverage_xml_filename):
674
+ import xml.etree.ElementTree as ET
675
+ coverage_xml = ET.parse(coverage_xml_filename).getroot()
676
+ for el in coverage_xml.iter():
677
+ el.tail = None # save some memory
678
+ else:
679
+ coverage_xml = None
680
+
681
+ rootwriter.save_annotation(result.main_source_file, result.c_file, coverage_xml=coverage_xml)
682
+
683
+ # if we included files, additionally generate one annotation file for each
684
+ if not self.scope.included_files:
685
+ return
686
+
687
+ search_include_file = self.scope.context.search_include_directories
688
+ target_dir = os.path.abspath(os.path.dirname(result.c_file))
689
+ for included_file in self.scope.included_files:
690
+ target_file = os.path.abspath(os.path.join(target_dir, included_file))
691
+ target_file_dir = os.path.dirname(target_file)
692
+ if not target_file_dir.startswith(target_dir):
693
+ # any other directories may not be writable => avoid trying
694
+ continue
695
+ source_file = search_include_file(included_file, source_pos=self.pos, include=True)
696
+ if not source_file:
697
+ continue
698
+ if target_file_dir != target_dir and not os.path.exists(target_file_dir):
699
+ try:
700
+ os.makedirs(target_file_dir)
701
+ except OSError as e:
702
+ import errno
703
+ if e.errno != errno.EEXIST:
704
+ raise
705
+ rootwriter.save_annotation(source_file, target_file, coverage_xml=coverage_xml)
706
+
707
+ def _serialize_lineno_map(self, env, ccodewriter):
708
+ tb = env.context.gdb_debug_outputwriter
709
+ markers = ccodewriter.buffer.allmarkers()
710
+
711
+ d = defaultdict(list)
712
+ for c_lineno, (src_desc, src_lineno) in enumerate(markers):
713
+ if src_lineno > 0 and src_desc.filename is not None:
714
+ d[src_desc, src_lineno].append(c_lineno + 1)
715
+
716
+ tb.start('LineNumberMapping')
717
+ for (src_desc, src_lineno), c_linenos in sorted(d.items()):
718
+ assert src_desc.filename is not None
719
+ tb.add_entry(
720
+ 'LineNumber',
721
+ c_linenos=' '.join(map(str, c_linenos)),
722
+ src_path=src_desc.filename,
723
+ src_lineno=str(src_lineno),
724
+ )
725
+ tb.end('LineNumberMapping')
726
+ tb.serialize()
727
+
728
+ def find_referenced_modules(self, env, module_list, modules_seen):
729
+ if env not in modules_seen:
730
+ modules_seen[env] = 1
731
+ for imported_module in env.cimported_modules:
732
+ self.find_referenced_modules(imported_module, module_list, modules_seen)
733
+ module_list.append(env)
734
+
735
+ def sort_types_by_inheritance(self, type_dict, type_order, getkey):
736
+ subclasses = defaultdict(list) # maps type key to list of subclass keys
737
+ for key in type_order:
738
+ new_entry = type_dict[key]
739
+ # collect all base classes to check for children
740
+ base = new_entry.type.base_type
741
+ while base:
742
+ base_key = getkey(base)
743
+ subclasses[base_key].append(key)
744
+ base_entry = type_dict.get(base_key)
745
+ if base_entry is None:
746
+ break
747
+ base = base_entry.type.base_type
748
+
749
+ # Simple topological sort using recursive DFS, based on
750
+ # https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
751
+ seen = set()
752
+ result = []
753
+ def dfs(u):
754
+ if u in seen:
755
+ return
756
+ seen.add(u)
757
+ for v in subclasses[getkey(u.type)]:
758
+ dfs(type_dict[v])
759
+ result.append(u)
760
+
761
+ for key in reversed(type_order):
762
+ dfs(type_dict[key])
763
+
764
+ result.reverse()
765
+ return result
766
+
767
+ def sort_type_hierarchy(self, module_list, env):
768
+ # poor developer's OrderedDict
769
+ vtab_dict, vtab_dict_order = {}, []
770
+ vtabslot_dict, vtabslot_dict_order = {}, []
771
+
772
+ for module in module_list:
773
+ for entry in module.c_class_entries:
774
+ if entry.used and not entry.in_cinclude:
775
+ type = entry.type
776
+ key = type.vtabstruct_cname
777
+ if not key:
778
+ continue
779
+ if key in vtab_dict:
780
+ # FIXME: this should *never* happen, but apparently it does
781
+ # for Cython generated utility code
782
+ from .UtilityCode import NonManglingModuleScope
783
+ assert isinstance(entry.scope, NonManglingModuleScope), str(entry.scope)
784
+ assert isinstance(vtab_dict[key].scope, NonManglingModuleScope), str(vtab_dict[key].scope)
785
+ else:
786
+ vtab_dict[key] = entry
787
+ vtab_dict_order.append(key)
788
+ all_defined_here = module is env
789
+ for entry in module.type_entries:
790
+ if entry.used and (all_defined_here or entry.defined_in_pxd):
791
+ type = entry.type
792
+ if type.is_extension_type and not entry.in_cinclude:
793
+ type = entry.type
794
+ key = type.objstruct_cname
795
+ assert key not in vtabslot_dict, key
796
+ vtabslot_dict[key] = entry
797
+ vtabslot_dict_order.append(key)
798
+
799
+ def vtabstruct_cname(entry_type):
800
+ return entry_type.vtabstruct_cname
801
+ vtab_list = self.sort_types_by_inheritance(
802
+ vtab_dict, vtab_dict_order, vtabstruct_cname)
803
+
804
+ def objstruct_cname(entry_type):
805
+ return entry_type.objstruct_cname
806
+ vtabslot_list = self.sort_types_by_inheritance(
807
+ vtabslot_dict, vtabslot_dict_order, objstruct_cname)
808
+
809
+ return (vtab_list, vtabslot_list)
810
+
811
+ def sort_cdef_classes(self, env):
812
+ key_func = operator.attrgetter('objstruct_cname')
813
+ entry_dict, entry_order = {}, []
814
+ for entry in env.c_class_entries:
815
+ key = key_func(entry.type)
816
+ assert key not in entry_dict, key
817
+ entry_dict[key] = entry
818
+ entry_order.append(key)
819
+ env.c_class_entries[:] = self.sort_types_by_inheritance(
820
+ entry_dict, entry_order, key_func)
821
+
822
+ def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code):
823
+ # TODO: Why are these separated out?
824
+ for entry in vtabslot_list:
825
+ self.generate_objstruct_predeclaration(entry.type, code)
826
+ vtabslot_entries = set(vtabslot_list)
827
+ ctuple_names = set()
828
+ for module in modules:
829
+ definition = module is env
830
+ type_entries = []
831
+ for entry in module.type_entries:
832
+ if entry.type.is_ctuple and entry.used:
833
+ if entry.name not in ctuple_names:
834
+ ctuple_names.add(entry.name)
835
+ type_entries.append(entry)
836
+ elif definition or entry.defined_in_pxd:
837
+ type_entries.append(entry)
838
+ type_entries = [t for t in type_entries if t not in vtabslot_entries]
839
+ self.generate_type_header_code(type_entries, code)
840
+ for entry in vtabslot_list:
841
+ self.generate_objstruct_definition(entry.type, code)
842
+ self.generate_typeobj_predeclaration(entry, code)
843
+ for entry in vtab_list:
844
+ self.generate_typeobj_predeclaration(entry, code)
845
+ self.generate_exttype_vtable_struct(entry, code)
846
+ self.generate_exttype_vtabptr_declaration(entry, code)
847
+ self.generate_exttype_final_methods_declaration(entry, code)
848
+
849
+ def generate_declarations_for_modules(self, env, modules, globalstate):
850
+ typecode = globalstate['type_declarations']
851
+ typecode.putln("")
852
+ typecode.putln("/*--- Type declarations ---*/")
853
+ # This is to work around the fact that array.h isn't part of the C-API,
854
+ # but we need to declare it earlier than utility code.
855
+ if 'cpython.array' in [m.qualified_name for m in modules]:
856
+ typecode.putln('#ifndef _ARRAYARRAY_H')
857
+ typecode.putln('struct arrayobject;')
858
+ typecode.putln('typedef struct arrayobject arrayobject;')
859
+ typecode.putln('#endif')
860
+ vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env)
861
+ self.generate_type_definitions(
862
+ env, modules, vtab_list, vtabslot_list, typecode)
863
+ modulecode = globalstate['module_declarations']
864
+ for module in modules:
865
+ defined_here = module is env
866
+ modulecode.putln("")
867
+ modulecode.putln("/* Module declarations from %s */" % module.qualified_name.as_c_string_literal())
868
+ self.generate_c_class_declarations(module, modulecode, defined_here, globalstate)
869
+ self.generate_cvariable_declarations(module, modulecode, defined_here)
870
+ self.generate_cfunction_declarations(module, modulecode, defined_here)
871
+
872
+ @staticmethod
873
+ def _put_setup_code(code, name):
874
+ code.put_code_here(UtilityCode.load(name, "ModuleSetupCode.c"))
875
+
876
+ def generate_module_preamble(self, env, options, cimported_modules, metadata, code):
877
+ code.put_generated_by()
878
+ if metadata:
879
+ code.putln("/* BEGIN: Cython Metadata")
880
+ code.putln(json.dumps(metadata, indent=4, sort_keys=True))
881
+ code.putln("END: Cython Metadata */")
882
+ code.putln("")
883
+
884
+ code.putln("#ifndef PY_SSIZE_T_CLEAN")
885
+ code.putln("#define PY_SSIZE_T_CLEAN")
886
+ code.putln("#endif /* PY_SSIZE_T_CLEAN */")
887
+ self._put_setup_code(code, "InitLimitedAPI")
888
+
889
+ for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey):
890
+ if inc.location == inc.INITIAL:
891
+ inc.write(code)
892
+ code.putln("#ifndef Py_PYTHON_H")
893
+ code.putln(" #error Python headers needed to compile C extensions, "
894
+ "please install development version of Python.")
895
+ code.putln("#elif PY_VERSION_HEX < 0x03080000")
896
+ code.putln(" #error Cython requires Python 3.8+.")
897
+ code.putln("#else")
898
+ code.globalstate["end"].putln("#endif /* Py_PYTHON_H */")
899
+
900
+ from .. import __version__
901
+ code.putln(f'#define __PYX_ABI_VERSION "{__version__.replace(".", "_")}"')
902
+ code.putln('#define CYTHON_HEX_VERSION %s' % build_hex_version(__version__))
903
+ code.putln("#define CYTHON_FUTURE_DIVISION %d" % (
904
+ Future.division in env.context.future_directives))
905
+
906
+ code.globalstate.use_utility_code(
907
+ UtilityCode.load("CythonABIVersion", "ModuleSetupCode.c"))
908
+
909
+ self._put_setup_code(code, "CModulePreamble")
910
+ if env.context.options.cplus:
911
+ self._put_setup_code(code, "CppInitCode")
912
+ else:
913
+ self._put_setup_code(code, "CInitCode")
914
+ self._put_setup_code(code, "PythonCompatibility")
915
+ self._put_setup_code(code, "MathInitCode")
916
+
917
+ # Error handling and position macros.
918
+ # Using "(void)cname" to prevent "unused" warnings.
919
+ mark_errpos_code = (
920
+ "#define __PYX_MARK_ERR_POS(f_index, lineno) {"
921
+ f" {Naming.filename_cname} = {Naming.filetable_cname}[f_index];"
922
+ f" (void) {Naming.filename_cname};"
923
+ f" {Naming.lineno_cname} = lineno;"
924
+ f" (void) {Naming.lineno_cname};"
925
+ "%s" # for C line info
926
+ f" (void) {Naming.clineno_cname}; " # always suppress warnings
927
+ "}"
928
+ )
929
+ cline_info = f" {Naming.clineno_cname} = {Naming.line_c_macro};"
930
+
931
+ # Show the C code line in tracebacks or not? C macros take precedence over (deprecated) options.
932
+ # 1) "CYTHON_CLINE_IN_TRACEBACK=0" always disables C lines in tracebacks
933
+ # 2) "CYTHON_CLINE_IN_TRACEBACK_RUNTIME=1" enables the feature + runtime configuration
934
+ # 2a) "options.c_line_in_traceback=True" changes the default to CYTHON_CLINE_IN_TRACEBACK_RUNTIME=1
935
+ # 2b) "options.c_line_in_traceback=False" changes the default to disable C lines
936
+ # 4) "CYTHON_CLINE_IN_TRACEBACK=1" enables C lines without runtime configuration
937
+ # 5) if nothing is set, the default is to disable the feature
938
+
939
+ default_cline_runtime = 0
940
+ if options.c_line_in_traceback is not None:
941
+ # explicitly set by user
942
+ default_cline_runtime = int(options.c_line_in_traceback)
943
+
944
+ code.putln("#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME")
945
+ code.putln(f"#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME {default_cline_runtime}")
946
+ code.putln("#endif")
947
+
948
+ code.putln("#ifndef CYTHON_CLINE_IN_TRACEBACK")
949
+ code.putln("#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME")
950
+ code.putln("#endif")
951
+
952
+ code.putln("#if CYTHON_CLINE_IN_TRACEBACK")
953
+ code.putln(mark_errpos_code % cline_info)
954
+ code.putln("#else")
955
+ code.putln(mark_errpos_code % "")
956
+ code.putln("#endif")
957
+
958
+ code.putln("#define __PYX_ERR(f_index, lineno, Ln_error) \\")
959
+ code.putln(" { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }")
960
+
961
+ code.putln("")
962
+ self.generate_extern_c_macro_definition(code, env.is_cpp())
963
+ code.putln("")
964
+
965
+ code.putln("#define %s" % self.api_name(Naming.h_guard_prefix, env))
966
+ code.putln("#define %s" % self.api_name(Naming.api_guard_prefix, env))
967
+ code.putln("/* Early includes */")
968
+ self.generate_includes(env, cimported_modules, code, late=False)
969
+ code.putln("")
970
+ code.putln("#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)")
971
+ code.putln("#define CYTHON_WITHOUT_ASSERTIONS")
972
+ code.putln("#endif")
973
+ code.putln("")
974
+
975
+ if env.directives['ccomplex']:
976
+ code.putln("")
977
+ code.putln("#if !defined(CYTHON_CCOMPLEX)")
978
+ code.putln("#define CYTHON_CCOMPLEX 1")
979
+ code.putln("#endif")
980
+ code.putln("")
981
+
982
+ c_string_type = env.directives['c_string_type']
983
+ c_string_encoding = env.directives['c_string_encoding']
984
+ if c_string_type not in ('bytes', 'bytearray') and not c_string_encoding:
985
+ error(self.pos, "a default encoding must be provided if c_string_type is not a byte type")
986
+ code.putln(f"#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII {int(c_string_encoding == 'ascii')}")
987
+ code.putln(f"#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 {int(c_string_encoding == 'utf8')}")
988
+ if c_string_encoding not in ('ascii', 'utf8'):
989
+ code.putln(f'#define __PYX_DEFAULT_STRING_ENCODING "{c_string_encoding}"')
990
+ if c_string_type == 'bytearray':
991
+ c_string_func_name = 'ByteArray'
992
+ elif c_string_type == 'str':
993
+ c_string_func_name = 'Unicode'
994
+ else:
995
+ c_string_func_name = c_string_type.title()
996
+ code.putln(f'#define __Pyx_PyObject_FromString __Pyx_Py{c_string_func_name}_FromString')
997
+ code.putln(f'#define __Pyx_PyObject_FromStringAndSize __Pyx_Py{c_string_func_name}_FromStringAndSize')
998
+ code.put(UtilityCode.load_as_string("TypeConversions", "TypeConversion.c")[0])
999
+ env.use_utility_code(UtilityCode.load_cached("FormatTypeName", "ObjectHandling.c"))
1000
+
1001
+ # These utility functions are assumed to exist and used elsewhere.
1002
+ PyrexTypes.c_long_type.create_to_py_utility_code(env)
1003
+ PyrexTypes.c_long_type.create_from_py_utility_code(env)
1004
+ PyrexTypes.c_int_type.create_from_py_utility_code(env)
1005
+
1006
+ code.put(Nodes.branch_prediction_macros)
1007
+
1008
+ self._put_setup_code(code, "PretendToInitialize")
1009
+ code.putln('')
1010
+ code.putln('#if !CYTHON_USE_MODULE_STATE')
1011
+ code.putln('static PyObject *%s = NULL;' % env.module_cname)
1012
+ if Options.pre_import is not None:
1013
+ code.putln('static PyObject *%s;' % Naming.preimport_cname)
1014
+ code.putln('#endif')
1015
+
1016
+ code.putln('static int %s;' % Naming.lineno_cname)
1017
+ code.putln('static int %s = 0;' % Naming.clineno_cname)
1018
+ code.putln('static const char * const %s = %s;' % (Naming.cfilenm_cname, Naming.file_c_macro))
1019
+ code.putln('static const char *%s;' % Naming.filename_cname)
1020
+
1021
+ env.use_utility_code(UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c"))
1022
+ env.use_utility_code(UtilityCode.load("GetRuntimeVersion", "ModuleSetupCode.c"))
1023
+ env.use_utility_code(UtilityCode.load_cached("AddModuleRef", "ModuleSetupCode.c"))
1024
+ if has_np_pythran(env):
1025
+ env.use_utility_code(UtilityCode.load_cached("PythranConversion", "CppSupport.cpp"))
1026
+
1027
+ def generate_extern_c_macro_definition(self, code, is_cpp):
1028
+ name = Naming.extern_c_macro
1029
+ code.putln("#ifdef CYTHON_EXTERN_C")
1030
+ # make sure that user overrides always take precedence
1031
+ code.putln(' #undef %s' % name)
1032
+ code.putln(' #define %s CYTHON_EXTERN_C' % name)
1033
+ code.putln("#elif defined(%s)" % name)
1034
+ code.putln(" #ifdef _MSC_VER")
1035
+ code.putln(" #pragma message (\"Please do not define the '%s' macro externally. Use 'CYTHON_EXTERN_C' instead.\")" % name)
1036
+ code.putln(" #else")
1037
+ code.putln(" #warning Please do not define the '%s' macro externally. Use 'CYTHON_EXTERN_C' instead." % name)
1038
+ code.putln(" #endif")
1039
+ code.putln("#else")
1040
+ if is_cpp:
1041
+ code.putln(' #define %s extern "C++"' % name)
1042
+ else:
1043
+ code.putln(" #ifdef __cplusplus")
1044
+ code.putln(' #define %s extern "C"' % name)
1045
+ code.putln(" #else")
1046
+ code.putln(" #define %s extern" % name)
1047
+ code.putln(" #endif")
1048
+ code.putln("#endif")
1049
+
1050
+ def generate_dl_import_macro(self, code):
1051
+ code.putln("#ifndef DL_IMPORT")
1052
+ code.putln(" #define DL_IMPORT(_T) _T")
1053
+ code.putln("#endif")
1054
+
1055
+ def generate_includes(self, env, cimported_modules, code, early=True, late=True):
1056
+ for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey):
1057
+ if inc.location == inc.EARLY:
1058
+ if early:
1059
+ inc.write(code)
1060
+ elif inc.location == inc.LATE:
1061
+ if late:
1062
+ inc.write(code)
1063
+ if early:
1064
+ code.putln_openmp("#include <omp.h>")
1065
+
1066
+ def generate_filename_table(self, code):
1067
+ from os.path import isabs, basename
1068
+ code.putln("")
1069
+ code.putln("static const char* const %s[] = {" % Naming.filetable_cname)
1070
+ if code.globalstate.filename_list:
1071
+ for source_desc in code.globalstate.filename_list:
1072
+ file_path = source_desc.get_filenametable_entry()
1073
+ if isabs(file_path):
1074
+ # never include absolute paths
1075
+ file_path = source_desc.get_description()
1076
+ # Always use / as separator
1077
+ file_path = pathlib.Path(file_path).as_posix()
1078
+ escaped_filename = as_encoded_filename(file_path)
1079
+ code.putln('%s,' % escaped_filename.as_c_string_literal())
1080
+ else:
1081
+ # Some C compilers don't like an empty array
1082
+ code.putln("0")
1083
+ code.putln("};")
1084
+
1085
+ def generate_type_predeclarations(self, env, code):
1086
+ pass
1087
+
1088
+ def generate_type_header_code(self, type_entries, code):
1089
+ # Generate definitions of structs/unions/enums/typedefs/objstructs.
1090
+ #self.generate_gcc33_hack(env, code) # Is this still needed?
1091
+ # Forward declarations
1092
+ for entry in type_entries:
1093
+ if not entry.in_cinclude:
1094
+ #print "generate_type_header_code:", entry.name, repr(entry.type) ###
1095
+ type = entry.type
1096
+ if type.is_typedef: # Must test this first!
1097
+ pass
1098
+ elif type.is_struct_or_union or type.is_cpp_class:
1099
+ self.generate_struct_union_predeclaration(entry, code)
1100
+ elif type.is_ctuple and not type.is_fused and entry.used:
1101
+ self.generate_struct_union_predeclaration(entry.type.struct_entry, code)
1102
+ elif type.is_extension_type:
1103
+ self.generate_objstruct_predeclaration(type, code)
1104
+ # Actual declarations
1105
+ for entry in type_entries:
1106
+ if not entry.in_cinclude:
1107
+ #print "generate_type_header_code:", entry.name, repr(entry.type) ###
1108
+ type = entry.type
1109
+ if type.is_typedef: # Must test this first!
1110
+ self.generate_typedef(entry, code)
1111
+ elif type.is_enum or type.is_cpp_enum:
1112
+ self.generate_enum_definition(entry, code)
1113
+ elif type.is_struct_or_union:
1114
+ self.generate_struct_union_definition(entry, code)
1115
+ elif type.is_ctuple and not type.is_fused and entry.used:
1116
+ self.generate_struct_union_definition(entry.type.struct_entry, code)
1117
+ elif type.is_cpp_class:
1118
+ self.generate_cpp_class_definition(entry, code)
1119
+ elif type.is_extension_type:
1120
+ self.generate_objstruct_definition(type, code)
1121
+ if getattr(type, "scope", None):
1122
+ for var_entry in type.scope.var_entries:
1123
+ code.globalstate.use_entry_utility_code(var_entry)
1124
+
1125
+ def generate_gcc33_hack(self, env, code):
1126
+ # Workaround for spurious warning generation in gcc 3.3
1127
+ code.putln("")
1128
+ for entry in env.c_class_entries:
1129
+ type = entry.type
1130
+ if not type.typedef_flag:
1131
+ name = type.objstruct_cname
1132
+ if name.startswith("__pyx_"):
1133
+ tail = name[6:]
1134
+ else:
1135
+ tail = name
1136
+ code.putln("typedef struct %s __pyx_gcc33_%s;" % (
1137
+ name, tail))
1138
+
1139
+ def generate_typedef(self, entry, code):
1140
+ base_type = entry.type.typedef_base_type
1141
+ enclosing_scope = entry.scope
1142
+ if base_type.is_numeric and not enclosing_scope.is_cpp_class_scope:
1143
+ try:
1144
+ writer = code.globalstate['numeric_typedefs']
1145
+ except KeyError:
1146
+ writer = code
1147
+ else:
1148
+ writer = code
1149
+ writer.mark_pos(entry.pos)
1150
+ writer.putln("typedef %s;" % base_type.declaration_code(entry.cname))
1151
+
1152
+ def sue_predeclaration(self, type, kind, name):
1153
+ if type.typedef_flag:
1154
+ return "%s %s;\ntypedef %s %s %s;" % (
1155
+ kind, name,
1156
+ kind, name, name)
1157
+ else:
1158
+ return "%s %s;" % (kind, name)
1159
+
1160
+ def generate_struct_union_predeclaration(self, entry, code):
1161
+ type = entry.type
1162
+ if type.is_cpp_class and type.templates:
1163
+ code.putln("template <typename %s>" % ", typename ".join(
1164
+ [T.empty_declaration_code() for T in type.templates]))
1165
+ code.putln(self.sue_predeclaration(type, type.kind, type.cname))
1166
+
1167
+ def sue_header_footer(self, type, kind, name):
1168
+ header = "%s %s {" % (kind, name)
1169
+ footer = "};"
1170
+ return header, footer
1171
+
1172
+ def generate_struct_union_definition(self, entry, code):
1173
+ code.mark_pos(entry.pos)
1174
+ type = entry.type
1175
+ scope = type.scope
1176
+ if scope:
1177
+ kind = type.kind
1178
+ packed = type.is_struct and type.packed
1179
+ if packed:
1180
+ kind = "%s %s" % (type.kind, "__Pyx_PACKED")
1181
+ code.globalstate.use_utility_code(packed_struct_utility_code)
1182
+ header, footer = \
1183
+ self.sue_header_footer(type, kind, type.cname)
1184
+ if packed:
1185
+ code.putln("#if defined(__SUNPRO_C)")
1186
+ code.putln(" #pragma pack(1)")
1187
+ code.putln("#elif !defined(__GNUC__)")
1188
+ code.putln(" #pragma pack(push, 1)")
1189
+ code.putln("#endif")
1190
+ code.putln(header)
1191
+ var_entries = scope.var_entries
1192
+ for attr in var_entries:
1193
+ code.putln(
1194
+ "%s;" % attr.type.declaration_code(attr.cname))
1195
+ code.putln(footer)
1196
+ if packed:
1197
+ code.putln("#if defined(__SUNPRO_C)")
1198
+ code.putln(" #pragma pack()")
1199
+ code.putln("#elif !defined(__GNUC__)")
1200
+ code.putln(" #pragma pack(pop)")
1201
+ code.putln("#endif")
1202
+
1203
+ def generate_cpp_constructor_code(self, arg_decls, arg_names, is_implementing, py_attrs, constructor, type, code):
1204
+ if is_implementing:
1205
+ code.putln("%s(%s) {" % (type.cname, ", ".join(arg_decls)))
1206
+ needs_gil = py_attrs or (constructor and not constructor.type.nogil)
1207
+ if needs_gil:
1208
+ code.put_ensure_gil()
1209
+ if py_attrs:
1210
+ for attr in py_attrs:
1211
+ code.put_init_var_to_py_none(attr, nanny=False)
1212
+ if constructor:
1213
+ code.putln("%s(%s);" % (constructor.cname, ", ".join(arg_names)))
1214
+ if needs_gil:
1215
+ code.put_release_ensured_gil()
1216
+ code.putln("}")
1217
+ else:
1218
+ code.putln("%s(%s);" % (type.cname, ", ".join(arg_decls)))
1219
+
1220
+ def generate_cpp_class_definition(self, entry, code):
1221
+ code.mark_pos(entry.pos)
1222
+ type = entry.type
1223
+ scope = type.scope
1224
+ if scope:
1225
+ if type.templates:
1226
+ code.putln("template <class %s>" % ", class ".join(
1227
+ [T.empty_declaration_code() for T in type.templates]))
1228
+ # Just let everything be public.
1229
+ code.put("struct %s" % type.cname)
1230
+ if type.base_classes:
1231
+ base_class_decl = ", public ".join(
1232
+ [base_class.empty_declaration_code() for base_class in type.base_classes])
1233
+ code.put(" : public %s" % base_class_decl)
1234
+ code.putln(" {")
1235
+ self.generate_type_header_code(scope.type_entries, code)
1236
+ py_attrs = [e for e in scope.entries.values()
1237
+ if e.type.is_pyobject and not e.is_inherited]
1238
+ has_virtual_methods = False
1239
+ constructor = None
1240
+ destructor = None
1241
+ for attr in scope.var_entries:
1242
+ if attr.type.is_cfunction and attr.type.is_static_method:
1243
+ code.put("static ")
1244
+ elif attr.name == "<init>":
1245
+ constructor = scope.lookup_here("<init>")
1246
+ elif attr.name == "<del>":
1247
+ destructor = attr
1248
+ elif attr.type.is_cfunction:
1249
+ code.put("virtual ")
1250
+ has_virtual_methods = True
1251
+ code.putln("%s;" % attr.type.declaration_code(attr.cname))
1252
+ is_implementing = 'init_module' in code.globalstate.parts
1253
+
1254
+ if constructor or py_attrs:
1255
+ if constructor:
1256
+ for constructor_alternative in constructor.all_alternatives():
1257
+ arg_decls = []
1258
+ arg_names = []
1259
+ for arg in constructor_alternative.type.original_args[
1260
+ :len(constructor_alternative.type.args)-constructor_alternative.type.optional_arg_count]:
1261
+ arg_decls.append(arg.declaration_code())
1262
+ arg_names.append(arg.cname)
1263
+ if constructor_alternative.type.optional_arg_count:
1264
+ arg_decls.append(constructor_alternative.type.op_arg_struct.declaration_code(Naming.optional_args_cname))
1265
+ arg_names.append(Naming.optional_args_cname)
1266
+ if not arg_decls:
1267
+ default_constructor = True
1268
+ arg_decls = []
1269
+ self.generate_cpp_constructor_code(arg_decls, arg_names, is_implementing, py_attrs, constructor_alternative, type, code)
1270
+ else:
1271
+ arg_decls = []
1272
+ arg_names = []
1273
+ self.generate_cpp_constructor_code(arg_decls, arg_names, is_implementing, py_attrs, constructor, type, code)
1274
+
1275
+ if destructor or py_attrs or has_virtual_methods:
1276
+ if has_virtual_methods:
1277
+ code.put("virtual ")
1278
+ if is_implementing:
1279
+ code.putln("~%s() {" % type.cname)
1280
+ if py_attrs:
1281
+ code.put_ensure_gil()
1282
+ if destructor:
1283
+ code.putln("%s();" % destructor.cname)
1284
+ if py_attrs:
1285
+ for attr in py_attrs:
1286
+ code.put_var_xdecref(attr, nanny=False)
1287
+ code.put_release_ensured_gil()
1288
+ code.putln("}")
1289
+ else:
1290
+ code.putln("~%s();" % type.cname)
1291
+ if py_attrs:
1292
+ # Also need copy constructor and assignment operators.
1293
+ if is_implementing:
1294
+ code.putln("%s(const %s& __Pyx_other) {" % (type.cname, type.cname))
1295
+ code.put_ensure_gil()
1296
+ for attr in scope.var_entries:
1297
+ if not attr.type.is_cfunction:
1298
+ code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname))
1299
+ code.put_var_incref(attr, nanny=False)
1300
+ code.put_release_ensured_gil()
1301
+ code.putln("}")
1302
+ code.putln("%s& operator=(const %s& __Pyx_other) {" % (type.cname, type.cname))
1303
+ code.putln("if (this != &__Pyx_other) {")
1304
+ code.put_ensure_gil()
1305
+ for attr in scope.var_entries:
1306
+ if not attr.type.is_cfunction:
1307
+ code.put_var_xdecref(attr, nanny=False)
1308
+ code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname))
1309
+ code.put_var_incref(attr, nanny=False)
1310
+ code.put_release_ensured_gil()
1311
+ code.putln("}")
1312
+ code.putln("return *this;")
1313
+ code.putln("}")
1314
+ else:
1315
+ code.putln("%s(const %s& __Pyx_other);" % (type.cname, type.cname))
1316
+ code.putln("%s& operator=(const %s& __Pyx_other);" % (type.cname, type.cname))
1317
+ code.putln("};")
1318
+
1319
+ def generate_enum_definition(self, entry, code):
1320
+ code.mark_pos(entry.pos)
1321
+ type = entry.type
1322
+ name = entry.cname or entry.name or ""
1323
+
1324
+ kind = "enum class" if entry.type.is_cpp_enum else "enum"
1325
+ header, footer = self.sue_header_footer(type, kind, name)
1326
+ code.putln(header)
1327
+ enum_values = entry.enum_values
1328
+ if not enum_values:
1329
+ error(entry.pos, "Empty enum definition not allowed outside a 'cdef extern from' block")
1330
+ else:
1331
+ last_entry = enum_values[-1]
1332
+ # this does not really generate code, just builds the result value
1333
+ for value_entry in enum_values:
1334
+ if value_entry.value_node is not None:
1335
+ value_entry.value_node.generate_evaluation_code(code)
1336
+
1337
+ for value_entry in enum_values:
1338
+ if value_entry.value_node is None:
1339
+ value_code = value_entry.cname.split("::")[-1]
1340
+ else:
1341
+ value_code = ("%s = %s" % (
1342
+ value_entry.cname.split("::")[-1],
1343
+ value_entry.value_node.result()))
1344
+ if value_entry is not last_entry:
1345
+ value_code += ","
1346
+ code.putln(value_code)
1347
+ code.putln(footer)
1348
+
1349
+ if entry.type.is_enum:
1350
+ if entry.type.typedef_flag:
1351
+ # Not pre-declared.
1352
+ code.putln("typedef enum %s %s;" % (name, name))
1353
+
1354
+ def generate_typeobj_predeclaration(self, entry, code):
1355
+ code.putln("")
1356
+ name = entry.type.typeobj_cname
1357
+ if name:
1358
+ if entry.visibility == 'extern' and not entry.in_cinclude:
1359
+ code.putln("%s %s %s;" % (
1360
+ Naming.extern_c_macro,
1361
+ PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"),
1362
+ name))
1363
+ elif entry.visibility == 'public':
1364
+ code.putln("%s %s %s;" % (
1365
+ Naming.extern_c_macro,
1366
+ PyrexTypes.public_decl("PyTypeObject", "DL_EXPORT"),
1367
+ name))
1368
+ # ??? Do we really need the rest of this? ???
1369
+ #else:
1370
+ # code.putln("static PyTypeObject %s;" % name)
1371
+
1372
+ def generate_exttype_vtable_struct(self, entry, code):
1373
+ if not entry.used:
1374
+ return
1375
+
1376
+ code.mark_pos(entry.pos)
1377
+ # Generate struct declaration for an extension type's vtable.
1378
+ type = entry.type
1379
+ scope = type.scope
1380
+
1381
+ self.specialize_fused_types(scope)
1382
+
1383
+ if type.vtabstruct_cname:
1384
+ code.putln("")
1385
+ code.putln("struct %s {" % type.vtabstruct_cname)
1386
+ if type.base_type and type.base_type.vtabstruct_cname:
1387
+ code.putln("struct %s %s;" % (
1388
+ type.base_type.vtabstruct_cname,
1389
+ Naming.obj_base_cname))
1390
+ for method_entry in scope.cfunc_entries:
1391
+ if not method_entry.is_inherited:
1392
+ code.putln("%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.cname))
1393
+ code.putln("};")
1394
+
1395
+ def generate_exttype_vtabptr_declaration(self, entry, code):
1396
+ if not entry.used:
1397
+ return
1398
+
1399
+ code.mark_pos(entry.pos)
1400
+ # Generate declaration of pointer to an extension type's vtable.
1401
+ type = entry.type
1402
+ if type.vtabptr_cname:
1403
+ code.putln("static struct %s *%s;" % (
1404
+ type.vtabstruct_cname,
1405
+ type.vtabptr_cname))
1406
+
1407
+ def generate_exttype_final_methods_declaration(self, entry, code):
1408
+ if not entry.used:
1409
+ return
1410
+
1411
+ code.mark_pos(entry.pos)
1412
+ # Generate final methods prototypes
1413
+ for method_entry in entry.type.scope.cfunc_entries:
1414
+ if not method_entry.is_inherited and method_entry.final_func_cname:
1415
+ declaration = method_entry.type.declaration_code(
1416
+ method_entry.final_func_cname)
1417
+ modifiers = code.build_function_modifiers(method_entry.func_modifiers)
1418
+ code.putln("static %s%s;" % (modifiers, declaration))
1419
+
1420
+ def generate_objstruct_predeclaration(self, type, code):
1421
+ if not type.scope:
1422
+ return
1423
+ code.putln(self.sue_predeclaration(type, "struct", type.objstruct_cname))
1424
+
1425
+ def generate_objstruct_definition(self, type, code):
1426
+ code.mark_pos(type.pos)
1427
+ # Generate object struct definition for an
1428
+ # extension type.
1429
+ if not type.scope:
1430
+ return # Forward declared but never defined
1431
+ header, footer = \
1432
+ self.sue_header_footer(type, "struct", type.objstruct_cname)
1433
+ code.putln(header)
1434
+ base_type = type.base_type
1435
+ if base_type:
1436
+ basestruct_cname = base_type.objstruct_cname
1437
+ if basestruct_cname == "PyTypeObject":
1438
+ # User-defined subclasses of type are heap allocated.
1439
+ basestruct_cname = "PyHeapTypeObject"
1440
+ code.putln(
1441
+ "%s%s %s;" % (
1442
+ ("struct ", "")[base_type.typedef_flag],
1443
+ basestruct_cname,
1444
+ Naming.obj_base_cname))
1445
+ else:
1446
+ code.putln(
1447
+ "PyObject_HEAD")
1448
+ if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname):
1449
+ code.putln(
1450
+ "struct %s *%s;" % (
1451
+ type.vtabstruct_cname,
1452
+ type.vtabslot_cname))
1453
+ for attr in type.scope.var_entries:
1454
+ if attr.is_declared_generic:
1455
+ attr_type = py_object_type
1456
+ else:
1457
+ attr_type = attr.type
1458
+ if attr.is_cpp_optional:
1459
+ decl = attr_type.cpp_optional_declaration_code(attr.cname)
1460
+ else:
1461
+ decl = attr_type.declaration_code(attr.cname)
1462
+ code.globalstate.use_entry_utility_code(attr)
1463
+ code.putln("%s;" % decl)
1464
+ code.putln(footer)
1465
+ if type.objtypedef_cname is not None:
1466
+ # Only for exposing public typedef name.
1467
+ code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname))
1468
+
1469
+ def generate_c_class_declarations(self, env, code, definition, globalstate):
1470
+ module_state = globalstate['module_state']
1471
+ module_state_clear = globalstate['module_state_clear']
1472
+ module_state_traverse = globalstate['module_state_traverse']
1473
+ module_state_typeobj = module_state.insertion_point()
1474
+ for entry in env.c_class_entries:
1475
+ if definition or entry.defined_in_pxd:
1476
+ module_state.putln("PyTypeObject *%s;" % entry.type.typeptr_cname)
1477
+ module_state_clear.putln(
1478
+ "Py_CLEAR(clear_module_state->%s);" %
1479
+ entry.type.typeptr_cname)
1480
+ module_state_traverse.putln(
1481
+ "Py_VISIT(traverse_module_state->%s);" %
1482
+ entry.type.typeptr_cname)
1483
+ if entry.type.typeobj_cname is not None:
1484
+ module_state_typeobj.putln("PyObject *%s;" % entry.type.typeobj_cname)
1485
+ module_state_clear.putln(
1486
+ "Py_CLEAR(clear_module_state->%s);" % (
1487
+ entry.type.typeobj_cname))
1488
+ module_state_traverse.putln(
1489
+ "Py_VISIT(traverse_module_state->%s);" % (
1490
+ entry.type.typeobj_cname))
1491
+
1492
+ def generate_cvariable_declarations(self, env, code, definition):
1493
+ if env.is_cython_builtin:
1494
+ return
1495
+ for entry in env.var_entries:
1496
+ if (entry.in_cinclude or entry.in_closure or
1497
+ (entry.visibility == 'private' and not (entry.defined_in_pxd or entry.used))):
1498
+ continue
1499
+
1500
+ storage_class = None
1501
+ dll_linkage = None
1502
+ init = None
1503
+
1504
+ if entry.visibility == 'extern':
1505
+ storage_class = Naming.extern_c_macro
1506
+ dll_linkage = "DL_IMPORT"
1507
+ elif entry.visibility == 'public':
1508
+ storage_class = Naming.extern_c_macro
1509
+ if definition:
1510
+ dll_linkage = "DL_EXPORT"
1511
+ else:
1512
+ dll_linkage = "DL_IMPORT"
1513
+ elif entry.visibility == 'private':
1514
+ storage_class = "static"
1515
+ dll_linkage = None
1516
+ if entry.init is not None:
1517
+ init = entry.type.literal_code(entry.init)
1518
+ type = entry.type
1519
+ cname = entry.cname
1520
+
1521
+ if entry.defined_in_pxd and not definition:
1522
+ storage_class = "static"
1523
+ dll_linkage = None
1524
+ type = CPtrType(type)
1525
+ cname = env.mangle(Naming.varptr_prefix, entry.name)
1526
+ init = 0
1527
+
1528
+ if storage_class:
1529
+ code.put("%s " % storage_class)
1530
+ if entry.is_cpp_optional:
1531
+ code.put(type.cpp_optional_declaration_code(
1532
+ cname, dll_linkage=dll_linkage))
1533
+ else:
1534
+ code.put(type.declaration_code(
1535
+ cname, dll_linkage=dll_linkage))
1536
+ if init is not None:
1537
+ code.put_safe(" = %s" % init)
1538
+ code.putln(";")
1539
+ if entry.cname != cname:
1540
+ code.putln("#define %s (*%s)" % (entry.cname, cname))
1541
+ code.globalstate.use_entry_utility_code(entry)
1542
+
1543
+ def generate_cfunction_declarations(self, env, code, definition):
1544
+ for entry in env.cfunc_entries:
1545
+ from_pyx = Options.cimport_from_pyx and not entry.visibility == 'extern'
1546
+ if (entry.used
1547
+ or entry.visibility == 'public'
1548
+ or entry.api
1549
+ or from_pyx):
1550
+ generate_cfunction_declaration(entry, env, code, definition)
1551
+
1552
+ def generate_variable_definitions(self, env, code):
1553
+ for entry in env.var_entries:
1554
+ if not entry.in_cinclude and entry.visibility == "public":
1555
+ code.put(entry.type.declaration_code(entry.cname))
1556
+ if entry.init is not None:
1557
+ init = entry.type.literal_code(entry.init)
1558
+ code.put_safe(" = %s" % init)
1559
+ code.putln(";")
1560
+
1561
+ def generate_typeobj_definitions(self, env, code):
1562
+ full_module_name = env.qualified_name
1563
+ for entry in env.c_class_entries:
1564
+ #print "generate_typeobj_definitions:", entry.name
1565
+ #print "...visibility =", entry.visibility
1566
+ if entry.visibility != 'extern':
1567
+ type = entry.type
1568
+ scope = type.scope
1569
+ if scope: # could be None if there was an error
1570
+ self.generate_exttype_vtable(scope, code)
1571
+ self.generate_new_function(scope, code, entry)
1572
+ self.generate_del_function(scope, code)
1573
+ self.generate_dealloc_function(scope, code)
1574
+
1575
+ if scope.needs_gc():
1576
+ self.generate_traverse_function(scope, code, entry)
1577
+ if scope.needs_tp_clear():
1578
+ self.generate_clear_function(scope, code, entry)
1579
+ if scope.defines_any_special(["__getitem__"]):
1580
+ self.generate_getitem_int_function(scope, code)
1581
+ if scope.defines_any_special(["__setitem__", "__delitem__"]):
1582
+ self.generate_ass_subscript_function(scope, code)
1583
+ if scope.defines_any_special(["__getslice__", "__setslice__", "__delslice__"]):
1584
+ warning(self.pos,
1585
+ "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, "
1586
+ "use __getitem__, __setitem__, and __delitem__ instead", 1)
1587
+ code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.")
1588
+ if scope.defines_any_special(["__setslice__", "__delslice__"]):
1589
+ self.generate_ass_slice_function(scope, code)
1590
+ if scope.defines_any_special(["__getattr__", "__getattribute__"]):
1591
+ self.generate_getattro_function(scope, code)
1592
+ if scope.defines_any_special(["__setattr__", "__delattr__"]):
1593
+ self.generate_setattro_function(scope, code)
1594
+ if scope.defines_any_special(["__get__"]):
1595
+ self.generate_descr_get_function(scope, code)
1596
+ if scope.defines_any_special(["__set__", "__delete__"]):
1597
+ self.generate_descr_set_function(scope, code)
1598
+ if not (scope.is_closure_class_scope or scope.is_defaults_class_scope) and scope.defines_any(["__dict__"]):
1599
+ self.generate_dict_getter_function(scope, code)
1600
+
1601
+ if scope.defines_any_special(TypeSlots.richcmp_special_methods):
1602
+ self.generate_richcmp_function(scope, code)
1603
+ elif 'total_ordering' in scope.directives:
1604
+ # Warn if this is used when it can't have any effect.
1605
+ warning(scope.parent_type.pos,
1606
+ "total_ordering directive used, but no comparison and equality methods defined")
1607
+
1608
+ for slot in TypeSlots.get_slot_table(code.globalstate.directives).PyNumberMethods:
1609
+ if slot.is_binop and scope.defines_any_special(slot.user_methods):
1610
+ self.generate_binop_function(scope, slot, code, entry.pos)
1611
+
1612
+ self.generate_property_accessors(scope, code)
1613
+ self.generate_method_table(scope, code)
1614
+ self.generate_getset_table(scope, code)
1615
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
1616
+ self.generate_typeobj_spec(entry, code)
1617
+ code.putln("#else")
1618
+ self.generate_typeobj_definition(full_module_name, entry, code)
1619
+ code.putln("#endif")
1620
+
1621
+ def generate_exttype_vtable(self, scope, code):
1622
+ # Generate the definition of an extension type's vtable.
1623
+ type = scope.parent_type
1624
+ if type.vtable_cname:
1625
+ code.putln("static struct %s %s;" % (
1626
+ type.vtabstruct_cname,
1627
+ type.vtable_cname))
1628
+
1629
+ def generate_self_cast(self, scope, code):
1630
+ type = scope.parent_type
1631
+ code.putln(
1632
+ "%s = (%s)o;" % (
1633
+ type.declaration_code("p"),
1634
+ type.empty_declaration_code()))
1635
+
1636
+ @staticmethod
1637
+ def generate_freelist_condition(code, size_check, type_cname, type):
1638
+ code.globalstate.use_utility_code(
1639
+ UtilityCode.load_cached("CheckTypeForFreelists", "ExtensionTypes.c"))
1640
+ if type.is_final_type:
1641
+ freelist_check = '__PYX_CHECK_FINAL_TYPE_FOR_FREELISTS'
1642
+ else:
1643
+ freelist_check = '__PYX_CHECK_TYPE_FOR_FREELISTS'
1644
+ obj_struct = type.declaration_code("", deref=True)
1645
+ typeptr_cname = code.name_in_slot_module_state(type.typeptr_cname)
1646
+ code.putln(
1647
+ f"if (likely((int)({size_check}) & {freelist_check}({type_cname}, {typeptr_cname}, sizeof({obj_struct}))))")
1648
+
1649
+ def generate_new_function(self, scope, code, cclass_entry):
1650
+ tp_slot = TypeSlots.ConstructorSlot("tp_new", "__cinit__")
1651
+ slot_func = scope.mangle_internal("tp_new")
1652
+ if tp_slot.slot_code(scope) != slot_func:
1653
+ return # never used
1654
+
1655
+ type = scope.parent_type
1656
+ base_type = type.base_type
1657
+
1658
+ have_entries, (py_attrs, py_buffers, memoryview_slices) = \
1659
+ scope.get_refcounted_entries()
1660
+ is_final_type = scope.parent_type.is_final_type
1661
+ if scope.is_internal:
1662
+ # internal classes (should) never need None inits, normal zeroing will do
1663
+ py_attrs = []
1664
+ explicitly_constructable_attrs = [
1665
+ entry for entry in scope.var_entries
1666
+ if entry.type.needs_explicit_construction(scope)
1667
+ ]
1668
+
1669
+ cinit_func_entry = scope.lookup_here("__cinit__")
1670
+ if cinit_func_entry and not cinit_func_entry.is_special:
1671
+ cinit_func_entry = None
1672
+
1673
+ if base_type or (cinit_func_entry and not cinit_func_entry.trivial_signature):
1674
+ unused_marker = ''
1675
+ else:
1676
+ unused_marker = 'CYTHON_UNUSED '
1677
+
1678
+ if base_type:
1679
+ freelist_size = 0 # not currently supported
1680
+ else:
1681
+ freelist_size = scope.directives.get('freelist', 0)
1682
+ freelist_name = scope.mangle_internal(Naming.freelist_name)
1683
+ freecount_name = scope.mangle_internal(Naming.freecount_name)
1684
+
1685
+ if freelist_size:
1686
+ module_state = code.globalstate['module_state_contents']
1687
+ module_state.putln("")
1688
+ module_state.putln("#if CYTHON_USE_FREELISTS")
1689
+ module_state.putln("%s[%d];" % (
1690
+ scope.parent_type.declaration_code(freelist_name),
1691
+ freelist_size))
1692
+ module_state.putln("int %s;" % freecount_name)
1693
+ module_state.putln("#endif")
1694
+
1695
+ code.start_slotfunc(
1696
+ scope, PyrexTypes.py_objptr_type, "tp_new",
1697
+ f"PyTypeObject *t, {unused_marker}PyObject *a, {unused_marker}PyObject *k", needs_prototype=True)
1698
+
1699
+ need_self_cast = (type.vtabslot_cname or
1700
+ (py_buffers or memoryview_slices or py_attrs) or
1701
+ explicitly_constructable_attrs)
1702
+ if need_self_cast:
1703
+ code.putln("%s;" % scope.parent_type.declaration_code("p"))
1704
+ if base_type:
1705
+ tp_new = TypeSlots.get_base_slot_function(scope, tp_slot)
1706
+ base_type_typeptr_cname = base_type.typeptr_cname
1707
+ if not base_type.is_builtin_type:
1708
+ base_type_typeptr_cname = code.name_in_slot_module_state(base_type_typeptr_cname)
1709
+ if tp_new is None:
1710
+ tp_new = f"__Pyx_PyType_GetSlot({base_type_typeptr_cname}, tp_new, newfunc)"
1711
+ code.putln("PyObject *o = %s(t, a, k);" % tp_new)
1712
+ else:
1713
+ code.putln("PyObject *o;")
1714
+ if freelist_size:
1715
+ code.globalstate.use_utility_code(
1716
+ UtilityCode.load_cached("IncludeStringH", "StringTools.c"))
1717
+ code.putln("#if CYTHON_USE_FREELISTS")
1718
+ freecount_name = code.name_in_slot_module_state(freecount_name)
1719
+ freelist_name = code.name_in_slot_module_state(freelist_name)
1720
+ self.generate_freelist_condition(code, f"{freecount_name} > 0", "t", type)
1721
+ code.putln("{")
1722
+ code.putln("o = (PyObject*)%s[--%s];" % (
1723
+ freelist_name,
1724
+ freecount_name))
1725
+ obj_struct = type.declaration_code("", deref=True)
1726
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
1727
+ # We still hold a reference to the type object held by the previous
1728
+ # user of the freelist object - release it.
1729
+ code.putln("Py_DECREF(Py_TYPE(o));")
1730
+ code.putln("#endif")
1731
+ code.putln("memset(o, 0, sizeof(%s));" % obj_struct)
1732
+ code.putln("#if CYTHON_COMPILING_IN_LIMITED_API")
1733
+ # Although PyObject_INIT should be part of the Limited API, it causes
1734
+ # link errors on some combinations of Python versions and OSs.
1735
+ code.putln("(void) PyObject_Init(o, t);")
1736
+ code.putln("#else")
1737
+ code.putln("(void) PyObject_INIT(o, t);")
1738
+ code.putln("#endif")
1739
+ if scope.needs_gc():
1740
+ code.putln("PyObject_GC_Track(o);")
1741
+ code.putln("} else")
1742
+ code.putln("#endif")
1743
+ code.putln("{")
1744
+ code.globalstate.use_utility_code(
1745
+ UtilityCode.load_cached("AllocateExtensionType", "ExtensionTypes.c")
1746
+ )
1747
+ code.putln(f"o = __Pyx_AllocateExtensionType(t, {is_final_type:d});")
1748
+ code.putln("if (unlikely(!o)) return 0;")
1749
+ if freelist_size and not base_type:
1750
+ code.putln('}')
1751
+ if need_self_cast:
1752
+ code.putln("p = %s;" % type.cast_code("o"))
1753
+ #if need_self_cast:
1754
+ # self.generate_self_cast(scope, code)
1755
+
1756
+ # from this point on, ensure DECREF(o) on failure
1757
+ needs_error_cleanup = False
1758
+
1759
+ if type.vtabslot_cname:
1760
+ vtab_base_type = type
1761
+ while vtab_base_type.base_type and vtab_base_type.base_type.vtabstruct_cname:
1762
+ vtab_base_type = vtab_base_type.base_type
1763
+ if vtab_base_type is not type:
1764
+ struct_type_cast = "(struct %s*)" % vtab_base_type.vtabstruct_cname
1765
+ else:
1766
+ struct_type_cast = ""
1767
+ code.putln("p->%s = %s%s;" % (
1768
+ type.vtabslot_cname,
1769
+ struct_type_cast, type.vtabptr_cname))
1770
+
1771
+ for entry in explicitly_constructable_attrs:
1772
+ entry.type.generate_explicit_construction(
1773
+ code, entry, extra_access_code="p->")
1774
+
1775
+ for entry in py_attrs:
1776
+ if entry.name == "__dict__":
1777
+ needs_error_cleanup = True
1778
+ code.put("p->%s = PyDict_New(); if (unlikely(!p->%s)) goto bad;" % (
1779
+ entry.cname, entry.cname))
1780
+ else:
1781
+ code.put_init_var_to_py_none(entry, "p->%s", nanny=False)
1782
+
1783
+ for entry in memoryview_slices:
1784
+ code.putln("p->%s.data = NULL;" % entry.cname)
1785
+ code.putln("p->%s.memview = NULL;" % entry.cname)
1786
+
1787
+ for entry in py_buffers:
1788
+ code.putln("p->%s.obj = NULL;" % entry.cname)
1789
+
1790
+ if cclass_entry.cname == '__pyx_memoryviewslice':
1791
+ code.putln("p->from_slice.memview = NULL;")
1792
+
1793
+ if cinit_func_entry:
1794
+ if cinit_func_entry.trivial_signature:
1795
+ cinit_args = f"o, {Naming.modulestateglobal_cname}->{Naming.empty_tuple}, NULL"
1796
+ else:
1797
+ cinit_args = "o, a, k"
1798
+ needs_error_cleanup = True
1799
+ code.putln("if (unlikely(%s(%s) < 0)) goto bad;" % (
1800
+ cinit_func_entry.func_cname, cinit_args))
1801
+
1802
+ code.putln(
1803
+ "return o;")
1804
+ if needs_error_cleanup:
1805
+ code.putln("bad:")
1806
+ code.put_decref_clear("o", py_object_type, nanny=False)
1807
+ code.putln("return NULL;")
1808
+ code.putln(
1809
+ "}")
1810
+ code.exit_cfunc_scope()
1811
+
1812
+ def generate_del_function(self, scope, code):
1813
+ tp_slot = TypeSlots.get_slot_by_name("tp_finalize", scope.directives)
1814
+ slot_func_cname = scope.mangle_internal("tp_finalize")
1815
+ if tp_slot.slot_code(scope) != slot_func_cname:
1816
+ return # never used
1817
+
1818
+ entry = scope.lookup_here("__del__")
1819
+ if entry is None or not entry.is_special:
1820
+ return # nothing to wrap
1821
+ code.putln("")
1822
+
1823
+ if tp_slot.used_ifdef:
1824
+ code.putln("#if %s" % tp_slot.used_ifdef)
1825
+
1826
+ code.start_slotfunc(scope, PyrexTypes.c_void_type, "tp_finalize", "PyObject *o", needs_funcstate=False)
1827
+ code.putln("PyObject *etype, *eval, *etb;")
1828
+ code.putln("PyErr_Fetch(&etype, &eval, &etb);")
1829
+ code.putln("%s(o);" % entry.func_cname)
1830
+ code.putln("PyErr_Restore(etype, eval, etb);")
1831
+ code.putln("}")
1832
+ code.exit_cfunc_scope()
1833
+
1834
+ if tp_slot.used_ifdef:
1835
+ code.putln("#endif")
1836
+
1837
+ def generate_dealloc_function(self, scope, code):
1838
+ tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__')
1839
+ slot_func = scope.mangle_internal("tp_dealloc")
1840
+ base_type = scope.parent_type.base_type
1841
+ if tp_slot.slot_code(scope) != slot_func:
1842
+ return # never used
1843
+
1844
+ slot_func_cname = scope.mangle_internal("tp_dealloc")
1845
+ code.start_slotfunc(scope, PyrexTypes.c_void_type, "tp_dealloc", "PyObject *o")
1846
+
1847
+ is_final_type = scope.parent_type.is_final_type
1848
+ needs_gc = scope.needs_gc()
1849
+ needs_trashcan = scope.needs_trashcan()
1850
+
1851
+ weakref_slot = scope.lookup_here("__weakref__") if not (scope.is_closure_class_scope or scope.is_defaults_class_scope) else None
1852
+ if weakref_slot not in scope.var_entries:
1853
+ weakref_slot = None
1854
+
1855
+ dict_slot = scope.lookup_here("__dict__") if not (scope.is_closure_class_scope or scope.is_defaults_class_scope) else None
1856
+ if dict_slot not in scope.var_entries:
1857
+ dict_slot = None
1858
+
1859
+ _, (py_attrs, _, memoryview_slices) = scope.get_refcounted_entries()
1860
+ explicitly_destructable_attrs = [
1861
+ entry for entry in scope.var_entries
1862
+ if entry.type.needs_explicit_destruction(scope)
1863
+ ]
1864
+
1865
+ if py_attrs or explicitly_destructable_attrs or memoryview_slices or weakref_slot or dict_slot:
1866
+ self.generate_self_cast(scope, code)
1867
+
1868
+ if not is_final_type or scope.may_have_finalize():
1869
+ # in Py3.4+, call tp_finalize() as early as possible
1870
+ code.putln("#if CYTHON_USE_TP_FINALIZE")
1871
+ if needs_gc:
1872
+ finalised_check = '!__Pyx_PyObject_GC_IsFinalized(o)'
1873
+ else:
1874
+ finalised_check = (
1875
+ '(!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))')
1876
+ code.putln(
1877
+ "if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && %s) {" % finalised_check)
1878
+
1879
+ code.putln("if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == %s) {" % slot_func_cname)
1880
+ # if instance was resurrected by finaliser, return
1881
+ code.putln("if (PyObject_CallFinalizerFromDealloc(o)) return;")
1882
+ code.putln("}")
1883
+ code.putln("}")
1884
+ code.putln("#endif")
1885
+
1886
+ if needs_gc:
1887
+ # We must mark this object as (gc) untracked while tearing
1888
+ # it down, lest the garbage collection is invoked while
1889
+ # running this destructor.
1890
+ code.putln("PyObject_GC_UnTrack(o);")
1891
+
1892
+ if needs_trashcan:
1893
+ code.globalstate.use_utility_code(
1894
+ UtilityCode.load_cached("PyTrashcan", "ExtensionTypes.c"))
1895
+ code.putln("__Pyx_TRASHCAN_BEGIN(o, %s)" % slot_func_cname)
1896
+
1897
+ if weakref_slot:
1898
+ # We must clean the weakreferences before calling the user's __dealloc__
1899
+ # because if the __dealloc__ releases the GIL, a weakref can be
1900
+ # dereferenced accessing the object in an inconsistent state or
1901
+ # resurrecting it.
1902
+ code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);")
1903
+
1904
+ # call the user's __dealloc__
1905
+ self.generate_usr_dealloc_call(scope, code)
1906
+
1907
+ if dict_slot:
1908
+ code.putln("if (p->__dict__) PyDict_Clear(p->__dict__);")
1909
+
1910
+ for entry in explicitly_destructable_attrs:
1911
+ entry.type.generate_explicit_destruction(code, entry, extra_access_code="p->")
1912
+
1913
+ for entry in (py_attrs + memoryview_slices):
1914
+ code.put_xdecref_clear("p->%s" % entry.cname, entry.type, nanny=False,
1915
+ clear_before_decref=True, have_gil=True)
1916
+
1917
+ if base_type:
1918
+ base_cname = base_type.typeptr_cname
1919
+ if not base_type.is_builtin_type:
1920
+ base_cname = code.name_in_slot_module_state(base_cname)
1921
+ tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot)
1922
+ if tp_dealloc is not None:
1923
+ if needs_gc and base_type.scope and base_type.scope.needs_gc():
1924
+ # We know that the base class uses GC, so probably expects it to be tracked.
1925
+ # Undo the untracking above.
1926
+ code.putln("PyObject_GC_Track(o);")
1927
+ code.putln("%s(o);" % tp_dealloc)
1928
+ elif base_type.is_builtin_type:
1929
+ if needs_gc and base_type.scope and base_type.scope.needs_gc():
1930
+ # We know that the base class uses GC, so probably expects it to be tracked.
1931
+ # Undo the untracking above.
1932
+ code.putln("PyObject_GC_Track(o);")
1933
+ code.putln("__Pyx_PyType_GetSlot(%s, tp_dealloc, destructor)(o);" % base_cname)
1934
+ else:
1935
+ if needs_gc:
1936
+ # We don't know if the base class uses GC or not, so must find out at runtime
1937
+ # whether we should undo the untracking above or not.
1938
+ code.putln("if (PyType_IS_GC(%s)) PyObject_GC_Track(o);" % base_cname)
1939
+ # This is an externally defined type. Calling through the
1940
+ # cimported base type pointer directly interacts badly with
1941
+ # the module cleanup, which may already have cleared it.
1942
+ # In that case, fall back to traversing the type hierarchy.
1943
+ # If we're using the module state then always go through the
1944
+ # type hierarchy, because our access to the module state may
1945
+ # have been lost (at least for the limited API version of
1946
+ # using module state).
1947
+ code.putln("#if !CYTHON_USE_MODULE_STATE")
1948
+ code.putln("if (likely(%s)) __Pyx_PyType_GetSlot(%s, tp_dealloc, destructor)(o); else" % (
1949
+ base_cname, base_cname))
1950
+ code.putln("#endif")
1951
+ code.putln("__Pyx_call_next_tp_dealloc(o, %s);" % slot_func_cname)
1952
+ code.globalstate.use_utility_code(
1953
+ UtilityCode.load_cached("CallNextTpDealloc", "ExtensionTypes.c"))
1954
+ else:
1955
+ freelist_size = scope.directives.get('freelist', 0)
1956
+ if freelist_size:
1957
+ freelist_name = code.name_in_slot_module_state(
1958
+ scope.mangle_internal(Naming.freelist_name))
1959
+ freecount_name = code.name_in_slot_module_state(
1960
+ scope.mangle_internal(Naming.freecount_name))
1961
+
1962
+ type = scope.parent_type
1963
+ code.putln("#if CYTHON_USE_FREELISTS")
1964
+ self.generate_freelist_condition(
1965
+ code, f"{freecount_name} < {freelist_size}",
1966
+ "Py_TYPE(o)", type)
1967
+ code.putln("{")
1968
+ code.putln("%s[%s++] = %s;" % (
1969
+ freelist_name,
1970
+ freecount_name,
1971
+ type.cast_code("o")))
1972
+ # Deliberately don't DECREF the type object for objects returned to the freelist:
1973
+ # we hold a reference to the type to allow them to be cleaned up properly.
1974
+ code.putln("} else")
1975
+ code.putln("#endif")
1976
+ code.putln("{")
1977
+ code.putln("PyTypeObject *tp = Py_TYPE(o);")
1978
+ code.putln("#if CYTHON_USE_TYPE_SLOTS")
1979
+ # Asking for PyType_GetSlot(..., Py_tp_free) seems to cause an error in pypy
1980
+ code.putln("(*tp->tp_free)(o);")
1981
+ code.putln("#else")
1982
+ code.putln("{")
1983
+ code.putln("freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free);")
1984
+ code.putln("if (tp_free) tp_free(o);")
1985
+ code.putln("}")
1986
+ code.putln("#endif")
1987
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
1988
+ # Undo the INCREF of the type object in tp_new
1989
+ code.putln("Py_DECREF(tp);")
1990
+ code.putln("#endif")
1991
+ if freelist_size:
1992
+ code.putln("}")
1993
+
1994
+ if needs_trashcan:
1995
+ code.putln("__Pyx_TRASHCAN_END")
1996
+
1997
+ code.putln(
1998
+ "}")
1999
+ code.exit_cfunc_scope()
2000
+
2001
+ def generate_usr_dealloc_call(self, scope, code):
2002
+ entry = scope.lookup_here("__dealloc__")
2003
+ if not entry or not entry.is_special:
2004
+ return
2005
+
2006
+ code.putln("{")
2007
+ code.putln("PyObject *etype, *eval, *etb;")
2008
+ code.putln("PyErr_Fetch(&etype, &eval, &etb);")
2009
+ # increase the refcount while we are calling into user code
2010
+ # to prevent recursive deallocation
2011
+ code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1);")
2012
+ code.putln("%s(o);" % entry.func_cname)
2013
+ code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1);")
2014
+ code.putln("PyErr_Restore(etype, eval, etb);")
2015
+ code.putln("}")
2016
+
2017
+ def generate_traverse_function(self, scope, code, cclass_entry):
2018
+ tp_slot = TypeSlots.GCDependentSlot("tp_traverse")
2019
+ slot_func = scope.mangle_internal("tp_traverse")
2020
+ base_type = scope.parent_type.base_type
2021
+ if tp_slot.slot_code(scope) != slot_func:
2022
+ return # never used
2023
+
2024
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "tp_traverse", "PyObject *o, visitproc v, void *a")
2025
+
2026
+ have_entries, (py_attrs, py_buffers, memoryview_slices) = (
2027
+ scope.get_refcounted_entries(include_gc_simple=False))
2028
+
2029
+ needs_type_traverse = not base_type
2030
+ # we don't know statically if we need to traverse the type
2031
+ maybe_needs_type_traverse = False
2032
+
2033
+ code.putln("int e;")
2034
+
2035
+ if py_attrs or py_buffers:
2036
+ self.generate_self_cast(scope, code)
2037
+
2038
+ if base_type:
2039
+ # want to call it explicitly if possible so inlining can be performed
2040
+ static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
2041
+ if static_call:
2042
+ code.putln("e = %s(o, v, a); if (e) return e;" % static_call)
2043
+ # No need to call type traverse - base class will do it
2044
+ elif base_type.is_builtin_type:
2045
+ base_cname = base_type.typeptr_cname
2046
+ code.putln("{")
2047
+ code.putln(
2048
+ f"traverseproc traverse = __Pyx_PyType_GetSlot({base_cname}, tp_traverse, traverseproc);")
2049
+ code.putln("if (!traverse); else { e = traverse(o,v,a); if (e) return e; }")
2050
+ code.putln("}")
2051
+ maybe_needs_type_traverse = True
2052
+ else:
2053
+ # This is an externally defined type. Calling through the
2054
+ # cimported base type pointer directly interacts badly with
2055
+ # the module cleanup, which may already have cleared it.
2056
+ # In that case, fall back to traversing the type hierarchy.
2057
+ # If we're using the module state then always go through the
2058
+ # type hierarchy, because our access to the module state may
2059
+ # have been lost (at least for the limited API version of
2060
+ # using module state).
2061
+ base_cname = code.name_in_slot_module_state(base_type.typeptr_cname)
2062
+ code.putln("#if !CYTHON_USE_MODULE_STATE")
2063
+ code.putln("e = 0;")
2064
+ code.putln("if (likely(%s)) {" % base_cname)
2065
+ code.putln(
2066
+ f"traverseproc traverse = __Pyx_PyType_GetSlot({base_cname}, tp_traverse, traverseproc);")
2067
+ code.putln("if (traverse) { e = traverse(o, v, a); }")
2068
+ code.putln("} else")
2069
+ code.putln("#endif")
2070
+ code.putln("{ e = __Pyx_call_next_tp_traverse(o, v, a, %s); }" % slot_func)
2071
+ code.putln("if (e) return e;")
2072
+ code.globalstate.use_utility_code(
2073
+ UtilityCode.load_cached("CallNextTpTraverse", "ExtensionTypes.c"))
2074
+ maybe_needs_type_traverse = True
2075
+ if needs_type_traverse or maybe_needs_type_traverse:
2076
+ code.putln("{")
2077
+ code.putln(f"e = __Pyx_call_type_traverse(o, {int(not maybe_needs_type_traverse)}, v, a);")
2078
+ code.putln("if (e) return e;")
2079
+ code.putln("}")
2080
+ code.globalstate.use_utility_code(
2081
+ UtilityCode.load_cached("CallTypeTraverse", "ExtensionTypes.c"))
2082
+
2083
+ for entry in py_attrs:
2084
+ var_code = "p->%s" % entry.cname
2085
+ var_as_pyobject = PyrexTypes.typecast(py_object_type, entry.type, var_code)
2086
+ code.putln("if (%s) {" % var_code)
2087
+ code.putln("e = (*v)(%s, a); if (e) return e;" % var_as_pyobject)
2088
+ code.putln("}")
2089
+
2090
+ # Traverse buffer exporting objects.
2091
+ # Note: not traversing memoryview attributes of memoryview slices!
2092
+ # When triggered by the GC, it would cause multiple visits (gc_refs
2093
+ # subtractions which is not matched by its reference count!)
2094
+ for entry in py_buffers:
2095
+ cname = entry.cname + ".obj"
2096
+ code.putln("if (p->%s) {" % cname)
2097
+ code.putln("e = (*v)(p->%s, a); if (e) return e;" % cname)
2098
+ code.putln("}")
2099
+
2100
+ code.putln("return 0;")
2101
+ code.putln("}")
2102
+ code.exit_cfunc_scope()
2103
+
2104
+ def generate_clear_function(self, scope, code, cclass_entry):
2105
+ tp_slot = TypeSlots.get_slot_by_name("tp_clear", scope.directives)
2106
+ slot_func = scope.mangle_internal("tp_clear")
2107
+ base_type = scope.parent_type.base_type
2108
+ if tp_slot.slot_code(scope) != slot_func:
2109
+ return # never used
2110
+
2111
+ have_entries, (py_attrs, py_buffers, memoryview_slices) = (
2112
+ scope.get_refcounted_entries(include_gc_simple=False))
2113
+
2114
+ if py_attrs or py_buffers or base_type:
2115
+ unused = ''
2116
+ else:
2117
+ unused = 'CYTHON_UNUSED '
2118
+
2119
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "tp_clear", f"{unused}PyObject *o")
2120
+
2121
+ if py_attrs and Options.clear_to_none:
2122
+ code.putln("PyObject* tmp;")
2123
+
2124
+ if py_attrs or py_buffers:
2125
+ self.generate_self_cast(scope, code)
2126
+
2127
+ if base_type:
2128
+ # want to call it explicitly if possible so inlining can be performed
2129
+ static_call = TypeSlots.get_base_slot_function(scope, tp_slot)
2130
+ if static_call:
2131
+ code.putln("%s(o);" % static_call)
2132
+ elif base_type.is_builtin_type:
2133
+ base_cname = base_type.typeptr_cname
2134
+ code.putln("{")
2135
+ code.putln(f"inquiry clear = __Pyx_PyType_GetSlot({base_cname}, tp_clear, inquiry);")
2136
+ code.putln("if (clear) clear(o);")
2137
+ code.putln("}")
2138
+ else:
2139
+ # This is an externally defined type. Calling through the
2140
+ # cimported base type pointer directly interacts badly with
2141
+ # the module cleanup, which may already have cleared it.
2142
+ # In that case, fall back to traversing the type hierarchy.
2143
+ # If we're using the module state then always go through the
2144
+ # type hierarchy, because our access to the module state may
2145
+ # have been lost (at least for the limited API version of
2146
+ # using module state).
2147
+ base_cname = code.name_in_slot_module_state(base_type.typeptr_cname)
2148
+ code.putln("#if !CYTHON_USE_MODULE_STATE")
2149
+ code.putln("if (likely(%s)) {" % base_cname)
2150
+ code.putln(f"inquiry clear = __Pyx_PyType_GetSlot({base_cname}, tp_clear, inquiry);")
2151
+ code.putln("if (clear) clear(o);")
2152
+ code.putln("} else")
2153
+ code.putln("#endif")
2154
+ code.putln("{ __Pyx_call_next_tp_clear(o, %s); }" % slot_func)
2155
+ code.globalstate.use_utility_code(
2156
+ UtilityCode.load_cached("CallNextTpClear", "ExtensionTypes.c"))
2157
+
2158
+ if Options.clear_to_none:
2159
+ for entry in py_attrs:
2160
+ name = "p->%s" % entry.cname
2161
+ code.putln("tmp = ((PyObject*)%s);" % name)
2162
+ if entry.is_declared_generic:
2163
+ code.put_init_to_py_none(name, py_object_type, nanny=False)
2164
+ else:
2165
+ code.put_init_to_py_none(name, entry.type, nanny=False)
2166
+ code.putln("Py_XDECREF(tmp);")
2167
+ else:
2168
+ for entry in py_attrs:
2169
+ code.putln("Py_CLEAR(p->%s);" % entry.cname)
2170
+
2171
+ for entry in py_buffers:
2172
+ # Note: shouldn't this call PyBuffer_Release ??
2173
+ code.putln("Py_CLEAR(p->%s.obj);" % entry.cname)
2174
+
2175
+ if cclass_entry.cname == '__pyx_memoryviewslice':
2176
+ code.putln("__PYX_XCLEAR_MEMVIEW(&p->from_slice, 1);")
2177
+
2178
+ code.putln("return 0;")
2179
+ code.putln("}")
2180
+ code.exit_cfunc_scope()
2181
+
2182
+ def generate_getitem_int_function(self, scope, code):
2183
+ # This function is put into the sq_item slot when
2184
+ # a __getitem__ method is present. It converts its
2185
+ # argument to a Python integer and calls mp_subscript.
2186
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "sq_item", "PyObject *o, Py_ssize_t i", needs_funcstate=False)
2187
+ code.putln(
2188
+ "PyObject *r;")
2189
+ code.putln(
2190
+ "PyObject *x = PyLong_FromSsize_t(i); if(!x) return 0;")
2191
+ # Note that PyType_GetSlot only works on heap-types before 3.10, so not using type slots
2192
+ # and defining cdef classes as non-heap types is probably impossible
2193
+ code.putln("#if CYTHON_USE_TYPE_SLOTS || (!CYTHON_USE_TYPE_SPECS && __PYX_LIMITED_VERSION_HEX < 0x030A0000)")
2194
+ code.putln(
2195
+ "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);")
2196
+ code.putln("#else")
2197
+ code.putln("r = ((binaryfunc)PyType_GetSlot(Py_TYPE(o), Py_mp_subscript))(o, x);")
2198
+ code.putln("#endif")
2199
+ code.putln(
2200
+ "Py_DECREF(x);")
2201
+ code.putln(
2202
+ "return r;")
2203
+ code.putln(
2204
+ "}")
2205
+ code.exit_cfunc_scope()
2206
+
2207
+ def generate_ass_subscript_function(self, scope, code):
2208
+ # Setting and deleting an item are both done through
2209
+ # the ass_subscript method, so we dispatch to user's __setitem__
2210
+ # or __delitem__, or raise an exception.
2211
+ base_type = scope.parent_type.base_type
2212
+ set_entry = scope.lookup_here("__setitem__")
2213
+ del_entry = scope.lookup_here("__delitem__")
2214
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "mp_ass_subscript", "PyObject *o, PyObject *i, PyObject *v")
2215
+ code.putln(
2216
+ "if (v) {")
2217
+ if set_entry:
2218
+ code.putln("return %s(o, i, v);" % set_entry.func_cname)
2219
+ else:
2220
+ code.putln(
2221
+ "__Pyx_TypeName o_type_name;")
2222
+ self.generate_guarded_basetype_call(
2223
+ base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2224
+ code.putln(
2225
+ "o_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(o));")
2226
+ code.putln(
2227
+ "PyErr_Format(PyExc_NotImplementedError,")
2228
+ code.putln(
2229
+ ' "Subscript assignment not supported by " __Pyx_FMT_TYPENAME, o_type_name);')
2230
+ code.putln(
2231
+ "__Pyx_DECREF_TypeName(o_type_name);")
2232
+ code.putln(
2233
+ "return -1;")
2234
+ code.putln(
2235
+ "}")
2236
+ code.putln(
2237
+ "else {")
2238
+ if del_entry:
2239
+ code.putln(
2240
+ "return %s(o, i);" % (
2241
+ del_entry.func_cname))
2242
+ else:
2243
+ code.putln(
2244
+ "__Pyx_TypeName o_type_name;")
2245
+ self.generate_guarded_basetype_call(
2246
+ base_type, "tp_as_mapping", "mp_ass_subscript", "objobjargproc", "o, i, v", code)
2247
+ code.putln(
2248
+ "o_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(o));")
2249
+ code.putln(
2250
+ "PyErr_Format(PyExc_NotImplementedError,")
2251
+ code.putln(
2252
+ ' "Subscript deletion not supported by " __Pyx_FMT_TYPENAME, o_type_name);')
2253
+ code.putln(
2254
+ "__Pyx_DECREF_TypeName(o_type_name);")
2255
+ code.putln(
2256
+ "return -1;")
2257
+ code.putln(
2258
+ "}")
2259
+ code.putln(
2260
+ "}")
2261
+ code.exit_cfunc_scope()
2262
+
2263
+ def generate_guarded_basetype_call(
2264
+ self, base_type, substructure, slot, functype, args, code):
2265
+ if base_type:
2266
+ base_tpname = code.typeptr_cname_in_module_state(base_type)
2267
+ # Note that the limited API versions will only work for non-heaptypes on Python3.10+.
2268
+ # I think that's unavoidable and the best we can do.
2269
+ if substructure:
2270
+ code.putln(
2271
+ f"{functype} f = __Pyx_PyType_TryGetSubSlot({base_tpname}, {substructure}, {slot}, {functype});")
2272
+ else:
2273
+ code.putln(
2274
+ f"{functype} f = __Pyx_PyType_TryGetSlot({base_tpname}, {slot}, {functype});")
2275
+ code.putln("if (f)")
2276
+ code.putln(f"return f({args});")
2277
+
2278
+ def generate_richcmp_function(self, scope, code):
2279
+ if scope.lookup_here("__richcmp__"):
2280
+ # user implemented, nothing to do
2281
+ return
2282
+ # otherwise, we have to generate it from the Python special methods
2283
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "tp_richcompare", "PyObject *o1, PyObject *o2, int op")
2284
+ code.putln("switch (op) {")
2285
+
2286
+ class_scopes = []
2287
+ cls = scope.parent_type
2288
+ while cls is not None and not cls.entry.visibility == 'extern':
2289
+ class_scopes.append(cls.scope)
2290
+ cls = cls.scope.parent_type.base_type
2291
+ assert scope in class_scopes
2292
+
2293
+ extern_parent = None
2294
+ if cls and cls.entry.visibility == 'extern':
2295
+ # need to call up into base classes as we may not know all implemented comparison methods
2296
+ extern_parent = cls if cls.typeptr_cname else scope.parent_type.base_type
2297
+
2298
+ total_ordering = 'total_ordering' in scope.directives
2299
+
2300
+ comp_entry = {}
2301
+
2302
+ for cmp_method in TypeSlots.richcmp_special_methods:
2303
+ for class_scope in class_scopes:
2304
+ entry = class_scope.lookup_here(cmp_method)
2305
+ if entry is not None:
2306
+ comp_entry[cmp_method] = entry
2307
+ break
2308
+
2309
+ if total_ordering:
2310
+ # Check this is valid - we must have at least 1 operation defined.
2311
+ comp_names = [from_name for from_name, to_name in TOTAL_ORDERING if from_name in comp_entry]
2312
+ if not comp_names:
2313
+ if '__eq__' not in comp_entry and '__ne__' not in comp_entry:
2314
+ warning(scope.parent_type.pos,
2315
+ "total_ordering directive used, but no comparison and equality methods defined")
2316
+ else:
2317
+ warning(scope.parent_type.pos,
2318
+ "total_ordering directive used, but no comparison methods defined")
2319
+ total_ordering = False
2320
+ else:
2321
+ if '__eq__' not in comp_entry and '__ne__' not in comp_entry:
2322
+ warning(scope.parent_type.pos, "total_ordering directive used, but no equality method defined")
2323
+ total_ordering = False
2324
+
2325
+ # Same priority as functools, prefers
2326
+ # __lt__ to __le__ to __gt__ to __ge__
2327
+ ordering_source = max(comp_names)
2328
+
2329
+ for cmp_method in TypeSlots.richcmp_special_methods:
2330
+ cmp_type = cmp_method.strip('_').upper() # e.g. "__eq__" -> EQ
2331
+ entry = comp_entry.get(cmp_method)
2332
+ if entry is None and (not total_ordering or cmp_type in ('NE', 'EQ')):
2333
+ # No definition, fall back to superclasses.
2334
+ # eq/ne methods shouldn't use the total_ordering code.
2335
+ continue
2336
+
2337
+ code.putln("case Py_%s: {" % cmp_type)
2338
+ if entry is None:
2339
+ assert total_ordering
2340
+ # We need to generate this from the other methods.
2341
+ invert_comp, comp_op, invert_equals = TOTAL_ORDERING[ordering_source, cmp_method]
2342
+
2343
+ # First we always do the comparison.
2344
+ code.putln("PyObject *ret;")
2345
+ code.putln("ret = %s(o1, o2);" % comp_entry[ordering_source].func_cname)
2346
+ code.putln("if (likely(ret && ret != Py_NotImplemented)) {")
2347
+ code.putln("int order_res = __Pyx_PyObject_IsTrue(ret);")
2348
+ code.putln("Py_DECREF(ret);")
2349
+ code.putln("if (unlikely(order_res < 0)) return NULL;")
2350
+ # We may need to check equality too. For some combos it's never required.
2351
+ if invert_equals is not None:
2352
+ # Implement the and/or check with an if.
2353
+ if comp_op == '&&':
2354
+ code.putln("if (%s order_res) {" % ('!!' if invert_comp else '!'))
2355
+ code.putln("ret = __Pyx_NewRef(Py_False);")
2356
+ code.putln("} else {")
2357
+ elif comp_op == '||':
2358
+ code.putln("if (%s order_res) {" % ('!' if invert_comp else ''))
2359
+ code.putln("ret = __Pyx_NewRef(Py_True);")
2360
+ code.putln("} else {")
2361
+ else:
2362
+ raise AssertionError('Unknown op %s' % (comp_op, ))
2363
+ if '__eq__' in comp_entry:
2364
+ eq_func = '__eq__'
2365
+ else:
2366
+ # Fall back to NE, which is defined here.
2367
+ eq_func = '__ne__'
2368
+ invert_equals = not invert_equals
2369
+
2370
+ code.putln("ret = %s(o1, o2);" % comp_entry[eq_func].func_cname)
2371
+ code.putln("if (likely(ret && ret != Py_NotImplemented)) {")
2372
+ code.putln("int eq_res = __Pyx_PyObject_IsTrue(ret);")
2373
+ code.putln("Py_DECREF(ret);")
2374
+ code.putln("if (unlikely(eq_res < 0)) return NULL;")
2375
+ if invert_equals:
2376
+ code.putln("ret = eq_res ? Py_False : Py_True;")
2377
+ else:
2378
+ code.putln("ret = eq_res ? Py_True : Py_False;")
2379
+ code.putln("Py_INCREF(ret);")
2380
+ code.putln("}") # equals success
2381
+ code.putln("}") # Needs to try equals
2382
+ else:
2383
+ # Convert direct to a boolean.
2384
+ if invert_comp:
2385
+ code.putln("ret = order_res ? Py_False : Py_True;")
2386
+ else:
2387
+ code.putln("ret = order_res ? Py_True : Py_False;")
2388
+ code.putln("Py_INCREF(ret);")
2389
+ code.putln("}") # comp_op
2390
+ code.putln("return ret;")
2391
+ else:
2392
+ code.putln("return %s(o1, o2);" % entry.func_cname)
2393
+ code.putln("}") # Case
2394
+
2395
+ if '__eq__' in comp_entry and '__ne__' not in comp_entry and not extern_parent:
2396
+ code.putln("case Py_NE: {")
2397
+ code.putln("PyObject *ret;")
2398
+ # Python itself does not do this optimisation, it seems...
2399
+ #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);")
2400
+ code.putln("ret = %s(o1, o2);" % comp_entry['__eq__'].func_cname)
2401
+ code.putln("if (likely(ret && ret != Py_NotImplemented)) {")
2402
+ code.putln("int b = __Pyx_PyObject_IsTrue(ret);")
2403
+ code.putln("Py_DECREF(ret);")
2404
+ code.putln("if (unlikely(b < 0)) return NULL;")
2405
+ code.putln("ret = (b) ? Py_False : Py_True;")
2406
+ code.putln("Py_INCREF(ret);")
2407
+ code.putln("}")
2408
+ code.putln("return ret;")
2409
+ code.putln("}")
2410
+
2411
+ code.putln("default: {")
2412
+ if extern_parent and extern_parent.typeptr_cname:
2413
+ code.putln("if (likely(%s->tp_richcompare)) return %s->tp_richcompare(o1, o2, op);" % (
2414
+ extern_parent.typeptr_cname, extern_parent.typeptr_cname))
2415
+ code.putln("return __Pyx_NewRef(Py_NotImplemented);")
2416
+ code.putln("}")
2417
+
2418
+ code.putln("}") # switch
2419
+ code.putln("}")
2420
+ code.exit_cfunc_scope()
2421
+
2422
+ def generate_binop_function(self, scope, slot, code, pos):
2423
+ func_name = scope.mangle_internal(slot.slot_name)
2424
+ if scope.directives['c_api_binop_methods']:
2425
+ code.putln('#define %s %s' % (func_name, slot.left_slot.slot_code(scope)))
2426
+ return
2427
+
2428
+ if slot.left_slot.signature in (TypeSlots.binaryfunc, TypeSlots.ibinaryfunc):
2429
+ slot_type = 'binaryfunc'
2430
+ extra_arg = extra_arg_decl = ''
2431
+ elif slot.left_slot.signature in (TypeSlots.powternaryfunc, TypeSlots.ipowternaryfunc):
2432
+ slot_type = 'ternaryfunc'
2433
+ extra_arg = ', extra_arg'
2434
+ extra_arg_decl = ', PyObject* extra_arg'
2435
+ else:
2436
+ error(pos, "Unexpected type slot signature: %s" % slot)
2437
+ return
2438
+
2439
+ def get_slot_method_cname(method_name):
2440
+ entry = scope.lookup(method_name)
2441
+ return entry.func_cname if entry and entry.is_special else None
2442
+
2443
+ def call_slot_method(method_name, reverse):
2444
+ func_cname = get_slot_method_cname(method_name)
2445
+ if func_cname:
2446
+ return "%s(%s%s)" % (
2447
+ func_cname,
2448
+ "right, left" if reverse else "left, right",
2449
+ extra_arg)
2450
+ else:
2451
+ return '%s_maybe_call_slot(__Pyx_PyType_GetSlot(%s, tp_base, PyTypeObject*), left, right %s)' % (
2452
+ func_name,
2453
+ code.name_in_module_state(scope.parent_type.typeptr_cname),
2454
+ extra_arg)
2455
+
2456
+ if get_slot_method_cname(slot.left_slot.method_name) and not get_slot_method_cname(slot.right_slot.method_name):
2457
+ warning(pos, "Extension type implements %s() but not %s(). "
2458
+ "The behaviour has changed from previous Cython versions to match Python semantics. "
2459
+ "You can implement both special methods in a backwards compatible way." % (
2460
+ slot.left_slot.method_name,
2461
+ slot.right_slot.method_name,
2462
+ ))
2463
+
2464
+ code.putln()
2465
+ preprocessor_guard = slot.preprocessor_guard_code()
2466
+ if preprocessor_guard:
2467
+ code.putln(preprocessor_guard)
2468
+ code.enter_cfunc_scope(scope) # C class scope, not function scope
2469
+
2470
+ overloads_left = int(bool(get_slot_method_cname(slot.left_slot.method_name)))
2471
+ overloads_right = int(bool(get_slot_method_cname(slot.right_slot.method_name)))
2472
+ parent_type_cname = scope.parent_type.typeptr_cname
2473
+ if scope.parent_type.is_extension_type:
2474
+ parent_type_cname = code.name_in_module_state(parent_type_cname)
2475
+ code.putln(
2476
+ TempitaUtilityCode.load_as_string(
2477
+ "BinopSlot", "ExtensionTypes.c",
2478
+ context={
2479
+ "func_name": func_name,
2480
+ "slot_name": slot.slot_name,
2481
+ "overloads_left": overloads_left,
2482
+ "overloads_right": overloads_right,
2483
+ "call_left": call_slot_method(slot.left_slot.method_name, reverse=False),
2484
+ "call_right": call_slot_method(slot.right_slot.method_name, reverse=True),
2485
+ "type_cname": parent_type_cname,
2486
+ "slot_type": slot_type,
2487
+ "extra_arg": extra_arg,
2488
+ "extra_arg_decl": extra_arg_decl,
2489
+ })[1])
2490
+
2491
+ code.exit_cfunc_scope()
2492
+ if preprocessor_guard:
2493
+ code.putln("#endif")
2494
+
2495
+ def generate_getattro_function(self, scope, code):
2496
+ # First try to get the attribute using __getattribute__, if defined, or
2497
+ # PyObject_GenericGetAttr.
2498
+ #
2499
+ # If that raises an AttributeError, call the __getattr__ if defined.
2500
+ #
2501
+ # In both cases, defined can be in this class, or any base class.
2502
+ def lookup_here_or_base(n, tp=None, extern_return=None):
2503
+ # Recursive lookup
2504
+ if tp is None:
2505
+ tp = scope.parent_type
2506
+ r = tp.scope.lookup_here(n)
2507
+ if r is None:
2508
+ if tp.is_external and extern_return is not None:
2509
+ return extern_return
2510
+ if tp.base_type is not None:
2511
+ return lookup_here_or_base(n, tp.base_type)
2512
+ return r
2513
+
2514
+ getattr_entry = lookup_here_or_base("__getattr__")
2515
+ getattribute_entry = lookup_here_or_base("__getattribute__")
2516
+
2517
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "tp_getattro", "PyObject *o, PyObject *n", needs_funcstate=False)
2518
+ if getattribute_entry is not None:
2519
+ code.putln(
2520
+ "PyObject *v = %s(o, n);" % (
2521
+ getattribute_entry.func_cname))
2522
+ else:
2523
+ code.putln(
2524
+ "PyObject *v = PyObject_GenericGetAttr(o, n);")
2525
+ if getattr_entry is not None:
2526
+ code.putln(
2527
+ "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {")
2528
+ code.putln(
2529
+ "PyErr_Clear();")
2530
+ code.putln(
2531
+ "v = %s(o, n);" % (
2532
+ getattr_entry.func_cname))
2533
+ code.putln(
2534
+ "}")
2535
+ code.putln(
2536
+ "return v;")
2537
+ code.putln(
2538
+ "}")
2539
+ code.exit_cfunc_scope()
2540
+
2541
+ def generate_setattro_function(self, scope, code):
2542
+ # Setting and deleting an attribute are both done through
2543
+ # the setattro method, so we dispatch to user's __setattr__
2544
+ # or __delattr__ or fall back on PyObject_GenericSetAttr.
2545
+ base_type = scope.parent_type.base_type
2546
+ set_entry = scope.lookup_here("__setattr__")
2547
+ del_entry = scope.lookup_here("__delattr__")
2548
+
2549
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "tp_setattro", "PyObject *o, PyObject *n, PyObject *v")
2550
+ code.putln(
2551
+ "if (v) {")
2552
+ if set_entry:
2553
+ code.putln(
2554
+ "return %s(o, n, v);" % (
2555
+ set_entry.func_cname))
2556
+ else:
2557
+ self.generate_guarded_basetype_call(
2558
+ base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code)
2559
+ code.putln(
2560
+ "return PyObject_GenericSetAttr(o, n, v);")
2561
+ code.putln(
2562
+ "}")
2563
+ code.putln(
2564
+ "else {")
2565
+ if del_entry:
2566
+ code.putln(
2567
+ "return %s(o, n);" % (
2568
+ del_entry.func_cname))
2569
+ else:
2570
+ self.generate_guarded_basetype_call(
2571
+ base_type, None, "tp_setattro", "setattrofunc", "o, n, v", code)
2572
+ code.putln(
2573
+ "return PyObject_GenericSetAttr(o, n, 0);")
2574
+ code.putln(
2575
+ "}")
2576
+ code.putln(
2577
+ "}")
2578
+ code.exit_cfunc_scope()
2579
+
2580
+ def generate_descr_get_function(self, scope, code):
2581
+ # The __get__ function of a descriptor object can be
2582
+ # called with NULL for the second or third arguments
2583
+ # under some circumstances, so we replace them with
2584
+ # None in that case.
2585
+ user_get_entry = scope.lookup_here("__get__")
2586
+
2587
+ code.start_slotfunc(scope, PyrexTypes.py_objptr_type, "tp_descr_get", "PyObject *o, PyObject *i, PyObject *c", needs_funcstate=False)
2588
+ code.putln(
2589
+ "PyObject *r = 0;")
2590
+ code.putln(
2591
+ "if (!i) i = Py_None;")
2592
+ code.putln(
2593
+ "if (!c) c = Py_None;")
2594
+ #code.put_incref("i", py_object_type)
2595
+ #code.put_incref("c", py_object_type)
2596
+ code.putln(
2597
+ "r = %s(o, i, c);" % (
2598
+ user_get_entry.func_cname))
2599
+ #code.put_decref("i", py_object_type)
2600
+ #code.put_decref("c", py_object_type)
2601
+ code.putln(
2602
+ "return r;")
2603
+ code.putln(
2604
+ "}")
2605
+ code.exit_cfunc_scope()
2606
+
2607
+ def generate_descr_set_function(self, scope, code):
2608
+ # Setting and deleting are both done through the __set__
2609
+ # method of a descriptor, so we dispatch to user's __set__
2610
+ # or __delete__ or raise an exception.
2611
+ base_type = scope.parent_type.base_type
2612
+ user_set_entry = scope.lookup_here("__set__")
2613
+ user_del_entry = scope.lookup_here("__delete__")
2614
+
2615
+ code.start_slotfunc(scope, PyrexTypes.c_returncode_type, "tp_descr_set", "PyObject *o, PyObject *i, PyObject *v")
2616
+ code.putln(
2617
+ "if (v) {")
2618
+ if user_set_entry:
2619
+ code.putln(
2620
+ "return %s(o, i, v);" % (
2621
+ user_set_entry.func_cname))
2622
+ else:
2623
+ self.generate_guarded_basetype_call(
2624
+ base_type, None, "tp_descr_set", "descrsetfunc", "o, i, v", code)
2625
+ code.putln(
2626
+ 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
2627
+ code.putln(
2628
+ "return -1;")
2629
+ code.putln(
2630
+ "}")
2631
+ code.putln(
2632
+ "else {")
2633
+ if user_del_entry:
2634
+ code.putln(
2635
+ "return %s(o, i);" % (
2636
+ user_del_entry.func_cname))
2637
+ else:
2638
+ self.generate_guarded_basetype_call(
2639
+ base_type, None, "tp_descr_set", "descrsetfunc", "o, i, v", code)
2640
+ code.putln(
2641
+ 'PyErr_SetString(PyExc_NotImplementedError, "__delete__");')
2642
+ code.putln(
2643
+ "return -1;")
2644
+ code.putln(
2645
+ "}")
2646
+ code.putln(
2647
+ "}")
2648
+ code.exit_cfunc_scope()
2649
+
2650
+ def generate_property_accessors(self, cclass_scope, code):
2651
+ for entry in cclass_scope.property_entries:
2652
+ property_scope = entry.scope
2653
+ if property_scope.defines_any(["__get__"]):
2654
+ self.generate_property_get_function(entry, code)
2655
+ if property_scope.defines_any(["__set__", "__del__"]):
2656
+ self.generate_property_set_function(entry, code)
2657
+
2658
+ def generate_property_get_function(self, property_entry, code):
2659
+ property_scope = property_entry.scope
2660
+ property_entry.getter_cname = property_scope.parent_scope.mangle(
2661
+ Naming.prop_get_prefix, property_entry.name)
2662
+ get_entry = property_scope.lookup_here("__get__")
2663
+
2664
+ code.putln("")
2665
+ code.putln(
2666
+ "static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % (
2667
+ property_entry.getter_cname))
2668
+ code.putln(
2669
+ "return %s(o);" % (
2670
+ get_entry.func_cname))
2671
+ code.putln(
2672
+ "}")
2673
+
2674
+ def generate_property_set_function(self, property_entry, code):
2675
+ property_scope = property_entry.scope
2676
+ property_entry.setter_cname = property_scope.parent_scope.mangle(
2677
+ Naming.prop_set_prefix, property_entry.name)
2678
+ set_entry = property_scope.lookup_here("__set__")
2679
+ del_entry = property_scope.lookup_here("__del__")
2680
+
2681
+ code.putln("")
2682
+ code.putln(
2683
+ "static int %s(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) {" % (
2684
+ property_entry.setter_cname))
2685
+ code.putln(
2686
+ "if (v) {")
2687
+ if set_entry:
2688
+ code.putln(
2689
+ "return %s(o, v);" % (
2690
+ set_entry.func_cname))
2691
+ else:
2692
+ code.putln(
2693
+ 'PyErr_SetString(PyExc_NotImplementedError, "__set__");')
2694
+ code.putln(
2695
+ "return -1;")
2696
+ code.putln(
2697
+ "}")
2698
+ code.putln(
2699
+ "else {")
2700
+ if del_entry:
2701
+ code.putln(
2702
+ "return %s(o);" % (
2703
+ del_entry.func_cname))
2704
+ else:
2705
+ code.putln(
2706
+ 'PyErr_SetString(PyExc_NotImplementedError, "__del__");')
2707
+ code.putln(
2708
+ "return -1;")
2709
+ code.putln(
2710
+ "}")
2711
+ code.putln(
2712
+ "}")
2713
+
2714
+ def generate_typeobj_spec(self, entry, code):
2715
+ ext_type = entry.type
2716
+ scope = ext_type.scope
2717
+
2718
+ members_slot = TypeSlots.get_slot_by_name("tp_members", code.globalstate.directives)
2719
+ members_slot.generate_substructure_spec(scope, code)
2720
+
2721
+ buffer_slot = TypeSlots.get_slot_by_name("tp_as_buffer", code.globalstate.directives)
2722
+ if not buffer_slot.is_empty(scope):
2723
+ code.putln("#if !CYTHON_COMPILING_IN_LIMITED_API")
2724
+ buffer_slot.generate_substructure(scope, code)
2725
+ code.putln("#endif")
2726
+
2727
+ if ext_type.typedef_flag:
2728
+ objstruct = ext_type.objstruct_cname
2729
+ else:
2730
+ objstruct = "struct %s" % ext_type.objstruct_cname
2731
+
2732
+ weakref_entry = scope.lookup_here("__weakref__") if not scope.is_closure_class_scope else None
2733
+ if weakref_entry and weakref_entry.is_inherited:
2734
+ weakref_entry = None # only generate it for the defining class
2735
+ generate_members = bool(weakref_entry)
2736
+ if generate_members:
2737
+ code.globalstate.use_utility_code(
2738
+ UtilityCode.load_cached("IncludeStructmemberH", "ModuleSetupCode.c"))
2739
+ code.putln("static PyMemberDef %s_members[] = {" % ext_type.typeobj_cname)
2740
+ code.putln("#if !CYTHON_USE_TYPE_SLOTS")
2741
+ if weakref_entry:
2742
+ # Note that unlike the assignment of tp_weaklistoffset in the type-ready code
2743
+ # used in the non-limited API case, this doesn't preserve the weaklistoffset
2744
+ # from base classes.
2745
+ # Practically that doesn't matter, but it isn't exactly the identical.
2746
+ code.putln('{"__weaklistoffset__", T_PYSSIZET, offsetof(%s, %s), READONLY, 0},'
2747
+ % (objstruct, weakref_entry.cname))
2748
+ code.putln("#endif")
2749
+ code.putln("{0, 0, 0, 0, 0}")
2750
+ code.putln("};")
2751
+
2752
+ if weakref_entry:
2753
+ position = format_position(weakref_entry.pos)
2754
+ weakref_warn_mesage = (
2755
+ f"{position}: __weakref__ is unsupported in the Limited API when "
2756
+ "running on Python <3.9.")
2757
+ # Note: Limited API rather than USE_TYPE_SPECS - we work round the issue
2758
+ # with USE_TYPE_SPECS outside the limited API
2759
+ code.putln("#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000")
2760
+ code.putln("#if defined(__GNUC__) || defined(__clang__)")
2761
+ code.putln(f'#warning "{weakref_warn_mesage}"')
2762
+ code.putln("#elif defined(_MSC_VER)")
2763
+ code.putln(f'#pragma message("{weakref_warn_mesage}")')
2764
+ code.putln("#endif")
2765
+ code.putln("#endif")
2766
+
2767
+
2768
+ code.putln("static PyType_Slot %s_slots[] = {" % ext_type.typeobj_cname)
2769
+ for slot in TypeSlots.get_slot_table(code.globalstate.directives):
2770
+ slot.generate_spec(scope, code)
2771
+ if generate_members:
2772
+ code.putln("{Py_tp_members, (void*)%s_members}," % ext_type.typeobj_cname)
2773
+ code.putln("{0, 0},")
2774
+ code.putln("};")
2775
+
2776
+ classname = scope.class_name.as_c_string_literal()
2777
+ code.putln("static PyType_Spec %s_spec = {" % ext_type.typeobj_cname)
2778
+ code.putln('"%s.%s",' % (self.full_module_name, classname.replace('"', '')))
2779
+ code.putln("sizeof(%s)," % objstruct)
2780
+ code.putln("0,")
2781
+ code.putln("%s," % TypeSlots.get_slot_by_name("tp_flags", scope.directives).slot_code(scope))
2782
+ code.putln("%s_slots," % ext_type.typeobj_cname)
2783
+ code.putln("};")
2784
+
2785
+ def generate_typeobj_definition(self, modname, entry, code):
2786
+ type = entry.type
2787
+ scope = type.scope
2788
+ for suite in TypeSlots.get_slot_table(code.globalstate.directives).substructures:
2789
+ suite.generate_substructure(scope, code)
2790
+ code.putln("")
2791
+ if entry.visibility == 'public':
2792
+ header = "DL_EXPORT(PyTypeObject) %s = {"
2793
+ else:
2794
+ header = "static PyTypeObject %s = {"
2795
+ #code.putln(header % scope.parent_type.typeobj_cname)
2796
+ code.putln(header % type.typeobj_cname)
2797
+ code.putln(
2798
+ "PyVarObject_HEAD_INIT(0, 0)")
2799
+ classname = scope.class_name.as_c_string_literal()
2800
+ code.putln(
2801
+ '"%s."%s, /*tp_name*/' % (
2802
+ self.full_module_name,
2803
+ classname))
2804
+ if type.typedef_flag:
2805
+ objstruct = type.objstruct_cname
2806
+ else:
2807
+ objstruct = "struct %s" % type.objstruct_cname
2808
+ code.putln(
2809
+ "sizeof(%s), /*tp_basicsize*/" % objstruct)
2810
+ code.putln(
2811
+ "0, /*tp_itemsize*/")
2812
+ for slot in TypeSlots.get_slot_table(code.globalstate.directives):
2813
+ slot.generate(scope, code)
2814
+ code.putln(
2815
+ "};")
2816
+
2817
+ def generate_method_table(self, env, code):
2818
+ if env.is_c_class_scope and not env.pyfunc_entries:
2819
+ return
2820
+ binding = env.directives['binding']
2821
+
2822
+ code.putln("")
2823
+ wrapper_code_writer = code.insertion_point()
2824
+
2825
+ code.putln(
2826
+ "static PyMethodDef %s[] = {" % (
2827
+ env.method_table_cname))
2828
+ for entry in env.pyfunc_entries:
2829
+ if not entry.fused_cfunction and not (binding and entry.is_overridable):
2830
+ code.put_pymethoddef(entry, ",", wrapper_code_writer=wrapper_code_writer)
2831
+ code.putln(
2832
+ "{0, 0, 0, 0}")
2833
+ code.putln(
2834
+ "};")
2835
+
2836
+ if wrapper_code_writer.getvalue():
2837
+ wrapper_code_writer.putln("")
2838
+
2839
+ def generate_dict_getter_function(self, scope, code):
2840
+ dict_attr = scope.lookup_here("__dict__")
2841
+ if not dict_attr or not dict_attr.is_variable:
2842
+ return
2843
+ func_name = scope.mangle_internal("__dict__getter")
2844
+ dict_name = dict_attr.cname
2845
+
2846
+ code.putln("")
2847
+ code.putln("#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000")
2848
+ code.putln("static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % func_name)
2849
+ self.generate_self_cast(scope, code)
2850
+ code.putln("if (unlikely(!p->%s)){" % dict_name)
2851
+ code.putln("p->%s = PyDict_New();" % dict_name)
2852
+ code.putln("}")
2853
+ code.putln("Py_XINCREF(p->%s);" % dict_name)
2854
+ code.putln("return p->%s;" % dict_name)
2855
+ code.putln("}")
2856
+ code.putln("#else")
2857
+ # PyObject_GenericGetDict has the advantage that it's freethreading thread-safe,
2858
+ # handles both managed and unmanaged dicts (in case we switch to managed in future),
2859
+ # and can potentially do optimizations with per-class shared keys.
2860
+ code.putln(f"#define {func_name} PyObject_GenericGetDict")
2861
+ code.putln("#endif")
2862
+
2863
+ def generate_getset_table(self, env, code):
2864
+ if env.property_entries:
2865
+ code.putln("")
2866
+ code.putln(
2867
+ "static struct PyGetSetDef %s[] = {" %
2868
+ env.getset_table_cname)
2869
+ for entry in env.property_entries:
2870
+ doc = entry.doc
2871
+ if doc:
2872
+ if doc.is_unicode:
2873
+ doc = doc.as_utf8_string()
2874
+ doc_code = "PyDoc_STR(%s)" % doc.as_c_string_literal()
2875
+ else:
2876
+ doc_code = "0"
2877
+ code.putln(
2878
+ '{%s, %s, %s, %s, 0},' % (
2879
+ entry.name.as_c_string_literal(),
2880
+ entry.getter_cname or "0",
2881
+ entry.setter_cname or "0",
2882
+ doc_code))
2883
+ code.putln(
2884
+ "{0, 0, 0, 0, 0}")
2885
+ code.putln(
2886
+ "};")
2887
+
2888
+ def create_import_star_conversion_utility_code(self, env):
2889
+ # Create all conversion helpers that are needed for "import *" assignments.
2890
+ # Must be done before code generation to support CythonUtilityCode.
2891
+ for name, entry in sorted(env.entries.items()):
2892
+ if entry.is_cglobal and entry.used:
2893
+ if not entry.type.is_pyobject:
2894
+ entry.type.create_from_py_utility_code(env)
2895
+
2896
+ def generate_import_star(self, env, code):
2897
+ env.use_utility_code(UtilityCode.load_cached("CStringEquals", "StringTools.c"))
2898
+ code.start_initcfunc(
2899
+ f"int {Naming.import_star_set}("
2900
+ f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname},"
2901
+ "PyObject *o, PyObject* py_name, const char *name)")
2902
+
2903
+ code.putln("static const char* internal_type_names[] = {")
2904
+ for name, entry in sorted(env.entries.items()):
2905
+ if entry.is_type:
2906
+ code.putln('"%s",' % name)
2907
+ code.putln("0")
2908
+ code.putln("};")
2909
+
2910
+ code.putln("const char** type_name = internal_type_names;")
2911
+ code.putln("while (*type_name) {")
2912
+ code.putln("if (__Pyx_StrEq(name, *type_name)) {")
2913
+ code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);')
2914
+ code.putln('goto bad;')
2915
+ code.putln("}")
2916
+ code.putln("type_name++;")
2917
+ code.putln("}")
2918
+
2919
+ old_error_label = code.new_error_label()
2920
+ code.putln("if (0);") # so the first one can be "else if"
2921
+ msvc_count = 0
2922
+ for name, entry in sorted(env.entries.items()):
2923
+ if entry.is_cglobal and entry.used and not entry.type.is_const:
2924
+ msvc_count += 1
2925
+ if msvc_count % 100 == 0:
2926
+ code.putln("#ifdef _MSC_VER")
2927
+ code.putln("if (0); /* Workaround for MSVC C1061. */")
2928
+ code.putln("#endif")
2929
+ code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name)
2930
+ if entry.type.is_pyobject:
2931
+ if entry.type.is_extension_type or entry.type.is_builtin_type:
2932
+ type_test = entry.type.type_test_code(
2933
+ env, "o")
2934
+ code.putln("if (!(%s)) %s;" % (
2935
+ type_test,
2936
+ code.error_goto(entry.pos)))
2937
+ code.putln("Py_INCREF(o);")
2938
+ code.put_decref(entry.cname, entry.type, nanny=False)
2939
+ code.putln("%s = %s;" % (
2940
+ entry.cname,
2941
+ PyrexTypes.typecast(entry.type, py_object_type, "o")))
2942
+ elif entry.type.create_from_py_utility_code(env):
2943
+ # if available, utility code was already created in self.prepare_utility_code()
2944
+ code.putln(entry.type.from_py_call_code(
2945
+ 'o', entry.cname, entry.pos, code))
2946
+ else:
2947
+ code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % (
2948
+ name, entry.type))
2949
+ code.putln(code.error_goto(entry.pos))
2950
+ code.putln("}")
2951
+ code.putln("else {")
2952
+ code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname)
2953
+ code.putln("}")
2954
+ code.putln("return 0;")
2955
+ if code.label_used(code.error_label):
2956
+ code.put_label(code.error_label)
2957
+ # This helps locate the offending name.
2958
+ code.put_add_traceback(EncodedString(self.full_module_name))
2959
+ code.error_label = old_error_label
2960
+ code.putln("bad:")
2961
+ code.putln("return -1;")
2962
+ code.putln("}")
2963
+ code.putln("")
2964
+ code.put_code_here(UtilityCode.load("ImportStar", "ImportExport.c"))
2965
+ code.exit_cfunc_scope() # done with labels
2966
+
2967
+ def generate_module_state_start(self, env, code):
2968
+ # TODO: Refactor to move module state struct decl closer to the static decl
2969
+ code.putln('typedef struct {')
2970
+ code.putln('PyObject *%s;' % env.module_dict_cname)
2971
+ code.putln('PyObject *%s;' % Naming.builtins_cname)
2972
+ code.putln('PyObject *%s;' % Naming.cython_runtime_cname)
2973
+ code.putln('PyObject *%s;' % Naming.empty_tuple)
2974
+ code.putln('PyObject *%s;' % Naming.empty_bytes)
2975
+ code.putln('PyObject *%s;' % Naming.empty_unicode)
2976
+ if Options.pre_import is not None:
2977
+ code.putln('PyObject *%s;' % Naming.preimport_cname)
2978
+
2979
+ def generate_module_state_end(self, env, modules, globalstate):
2980
+ module_state = globalstate['module_state_end']
2981
+ module_state_clear = globalstate['module_state_clear_end']
2982
+ module_state_traverse = globalstate['module_state_traverse_end']
2983
+ module_state.putln('} %s;' % Naming.modulestatetype_cname)
2984
+ module_state.putln('')
2985
+ globalstate.use_utility_code(
2986
+ UtilityCode.load("MultiPhaseInitModuleState", "ModuleSetupCode.c")
2987
+ )
2988
+ module_state.putln("#if CYTHON_USE_MODULE_STATE")
2989
+ module_state.putln('#ifdef __cplusplus')
2990
+ module_state.putln('namespace {')
2991
+ module_state.putln('extern struct PyModuleDef %s;' % Naming.pymoduledef_cname)
2992
+ module_state.putln('} /* anonymous namespace */')
2993
+ module_state.putln('#else')
2994
+ module_state.putln('static struct PyModuleDef %s;' % Naming.pymoduledef_cname)
2995
+ module_state.putln('#endif')
2996
+ module_state.putln('')
2997
+ module_state.putln('#define %s (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&%s)))' % (
2998
+ Naming.modulestateglobal_cname,
2999
+ Naming.pymoduledef_cname))
3000
+ module_state.putln('')
3001
+ module_state.putln('#define %s (__Pyx_State_FindModule(&%s))' % (
3002
+ env.module_cname,
3003
+ Naming.pymoduledef_cname))
3004
+ module_state.putln("#else")
3005
+ module_state.putln('static %s %s_static =' % (
3006
+ Naming.modulestatetype_cname,
3007
+ Naming.modulestateglobal_cname
3008
+ ))
3009
+ module_state.putln('#ifdef __cplusplus')
3010
+ # C++ likes to be initialized with {} to avoid "missing initializer" warnings
3011
+ # but it isn't valid C
3012
+ module_state.putln(' {};')
3013
+ module_state.putln('#else')
3014
+ module_state.putln(' {0};')
3015
+ module_state.putln('#endif')
3016
+ module_state.putln('static %s * const %s = &%s_static;' % (
3017
+ Naming.modulestatetype_cname,
3018
+ Naming.modulestateglobal_cname,
3019
+ Naming.modulestateglobal_cname
3020
+ ))
3021
+ module_state.putln("#endif")
3022
+ module_state_clear.putln("return 0;")
3023
+ module_state_clear.putln("}")
3024
+ module_state_clear.putln("#endif")
3025
+ module_state_traverse.putln("return 0;")
3026
+ module_state_traverse.putln("}")
3027
+ module_state_traverse.putln("#endif")
3028
+
3029
+
3030
+ def generate_module_state_clear(self, env, code):
3031
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3032
+ code.putln("static CYTHON_SMALL_CODE int %s_clear(PyObject *m) {" % Naming.module_cname)
3033
+ code.putln(f"{Naming.modulestatetype_cname} *clear_module_state = __Pyx_PyModule_GetState(m);")
3034
+ code.putln("if (!clear_module_state) return 0;")
3035
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3036
+ env.module_dict_cname)
3037
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3038
+ Naming.builtins_cname)
3039
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3040
+ Naming.cython_runtime_cname)
3041
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3042
+ Naming.empty_tuple)
3043
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3044
+ Naming.empty_bytes)
3045
+ code.putln('Py_CLEAR(clear_module_state->%s);' %
3046
+ Naming.empty_unicode)
3047
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3048
+ # In this case we have to remove the module from our lookup table ourself
3049
+ # because Python isn't going to do it.
3050
+ code.putln("__Pyx_State_RemoveModule(NULL);")
3051
+ code.putln("#endif")
3052
+
3053
+ def generate_module_state_traverse(self, env, code):
3054
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3055
+ code.putln("static CYTHON_SMALL_CODE int %s_traverse(PyObject *m, visitproc visit, void *arg) {" % Naming.module_cname)
3056
+ code.putln(f"{Naming.modulestatetype_cname} *traverse_module_state = __Pyx_PyModule_GetState(m);")
3057
+ code.putln("if (!traverse_module_state) return 0;")
3058
+ code.putln(f'Py_VISIT(traverse_module_state->{env.module_dict_cname});')
3059
+ code.putln(f'Py_VISIT(traverse_module_state->{Naming.builtins_cname});')
3060
+ code.putln(f'Py_VISIT(traverse_module_state->{Naming.cython_runtime_cname});')
3061
+ code.putln(f'__Pyx_VISIT_CONST(traverse_module_state->{Naming.empty_tuple});')
3062
+ code.putln(f'__Pyx_VISIT_CONST(traverse_module_state->{Naming.empty_bytes});')
3063
+ code.putln(f'__Pyx_VISIT_CONST(traverse_module_state->{Naming.empty_unicode});')
3064
+
3065
+ def generate_module_init_func(self, imported_modules, shared_utility_exporter, env, code):
3066
+ subfunction = self.mod_init_subfunction(self.pos, self.scope, code)
3067
+
3068
+ self.generate_pymoduledef_struct(env, code)
3069
+
3070
+ code.enter_cfunc_scope(self.scope)
3071
+ code.putln("")
3072
+ code.put_code_here(UtilityCode.load("PyModInitFuncType", "ModuleSetupCode.c"))
3073
+
3074
+ modinit_func_name = EncodedString(f"PyInit_{env.module_name}")
3075
+ header3 = "__Pyx_PyMODINIT_FUNC %s(void)" % self.mod_init_func_cname('PyInit', env)
3076
+ # Optimise for small code size as the module init function is only executed once.
3077
+ code.putln("%s CYTHON_SMALL_CODE; /*proto*/" % header3)
3078
+ if self.scope.is_package:
3079
+ code.putln("#if !defined(CYTHON_NO_PYINIT_EXPORT) && (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))")
3080
+ code.putln("__Pyx_PyMODINIT_FUNC PyInit___init__(void) { return %s(); }" % (
3081
+ self.mod_init_func_cname('PyInit', env)))
3082
+ code.putln("#endif")
3083
+ # Hack for a distutils bug - https://bugs.python.org/issue39432
3084
+ # distutils attempts to make visible a slightly wrong PyInitU module name. Just create a dummy
3085
+ # function to keep it quiet
3086
+ wrong_punycode_module_name = self.wrong_punycode_module_name(env.module_name)
3087
+ if wrong_punycode_module_name:
3088
+ code.putln("#if !defined(CYTHON_NO_PYINIT_EXPORT) && (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))")
3089
+ code.putln("void %s(void) {} /* workaround for https://bugs.python.org/issue39432 */" % wrong_punycode_module_name)
3090
+ code.putln("#endif")
3091
+ code.putln(header3)
3092
+
3093
+ # CPython 3.5+ supports multi-phase module initialisation (gives access to __spec__, __file__, etc.)
3094
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3095
+ code.putln("{")
3096
+ code.putln("return PyModuleDef_Init(&%s);" % Naming.pymoduledef_cname)
3097
+ code.putln("}")
3098
+
3099
+ mod_create_func = UtilityCode.load("ModuleCreationPEP489", "ModuleSetupCode.c")
3100
+ code.put_code_here(mod_create_func)
3101
+
3102
+ code.putln("")
3103
+ # main module init code lives in Py_mod_exec function, not in PyInit function
3104
+ code.putln("static CYTHON_SMALL_CODE int %s(PyObject *%s)" % (
3105
+ self.module_init_func_cname(),
3106
+ Naming.pymodinit_module_arg))
3107
+ code.putln("#endif") # PEP489
3108
+
3109
+ # start of module init/exec function (pre/post PEP 489)
3110
+ code.putln("{")
3111
+ code.putln('int stringtab_initialized = 0;')
3112
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3113
+ code.putln('int pystate_addmodule_run = 0;')
3114
+ code.putln("#endif")
3115
+ code.putln(f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname} = NULL;")
3116
+
3117
+ tempdecl_code = code.insertion_point()
3118
+
3119
+ profile = code.globalstate.directives['profile']
3120
+ linetrace = code.globalstate.directives['linetrace']
3121
+ if profile or linetrace:
3122
+ if linetrace:
3123
+ code.use_fast_gil_utility_code()
3124
+ code.globalstate.use_utility_code(UtilityCode.load_cached("Profile", "Profile.c"))
3125
+
3126
+ code.put_declare_refcount_context()
3127
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3128
+ # Most extension modules simply can't deal with it, and Cython isn't ready either.
3129
+ # See issues listed here: https://docs.python.org/3/c-api/init.html#sub-interpreter-support
3130
+ code.putln("if (%s) {" % Naming.module_cname)
3131
+ # Hack: enforce single initialisation.
3132
+ code.putln("if (%s == %s) return 0;" % (
3133
+ Naming.module_cname,
3134
+ Naming.pymodinit_module_arg,
3135
+ ))
3136
+ code.putln('PyErr_SetString(PyExc_RuntimeError,'
3137
+ ' "Module \'%s\' has already been imported. Re-initialisation is not supported.");' %
3138
+ env.module_name.as_c_string_literal()[1:-1])
3139
+ code.putln("return -1;")
3140
+ code.putln("}")
3141
+ code.putln("#else")
3142
+ # Hack: enforce single initialisation also on reimports under different names (with PEP 3121/489).
3143
+ code.putln("if (%s) return __Pyx_NewRef(%s);" % (
3144
+ Naming.module_cname,
3145
+ Naming.module_cname,
3146
+ ))
3147
+ code.putln("#endif")
3148
+
3149
+ code.putln("/*--- Module creation code ---*/")
3150
+ self.generate_module_creation_code(env, code)
3151
+
3152
+ if profile or linetrace:
3153
+ tempdecl_code.put_trace_declarations()
3154
+ code.put_trace_frame_init()
3155
+
3156
+ refnanny_import_code = UtilityCode.load("ImportRefnannyAPI", "ModuleSetupCode.c")
3157
+ code.put_code_here(refnanny_import_code)
3158
+ code.put_setup_refcount_context(modinit_func_name)
3159
+
3160
+ code.putln("__Pyx_init_runtime_version();")
3161
+ env.use_utility_code(UtilityCode.load("CheckBinaryVersion", "ModuleSetupCode.c"))
3162
+ code.put_error_if_neg(self.pos, "__Pyx_check_binary_version("
3163
+ "__PYX_LIMITED_VERSION_HEX, "
3164
+ "__Pyx_get_runtime_version(), "
3165
+ "CYTHON_COMPILING_IN_LIMITED_API)"
3166
+ )
3167
+
3168
+ empty_tuple = code.name_in_main_c_code_module_state(Naming.empty_tuple)
3169
+ code.putln("%s = PyTuple_New(0); %s" % (
3170
+ empty_tuple, code.error_goto_if_null(empty_tuple, self.pos)))
3171
+ empty_bytes = code.name_in_main_c_code_module_state(Naming.empty_bytes)
3172
+ code.putln("%s = PyBytes_FromStringAndSize(\"\", 0); %s" % (
3173
+ empty_bytes, code.error_goto_if_null(empty_bytes, self.pos)))
3174
+ empty_unicode = code.name_in_main_c_code_module_state(Naming.empty_unicode)
3175
+ code.putln("%s = PyUnicode_FromStringAndSize(\"\", 0); %s" % (
3176
+ empty_unicode, code.error_goto_if_null(empty_unicode, self.pos)))
3177
+
3178
+
3179
+ code.putln("/*--- Library function declarations ---*/")
3180
+ if env.directives['np_pythran']:
3181
+ code.put_error_if_neg(self.pos, "_import_array()")
3182
+
3183
+ code.putln("/*--- Initialize various global constants etc. ---*/")
3184
+ code.put_error_if_neg(self.pos, f"__Pyx_InitConstants({Naming.modulestatevalue_cname})")
3185
+ code.putln("stringtab_initialized = 1;")
3186
+ code.put_error_if_neg(self.pos, "__Pyx_InitGlobals()") # calls any utility code
3187
+
3188
+ code.putln("if (%s) {" % self.is_main_module_flag_cname())
3189
+ code.put_error_if_neg(self.pos, 'PyObject_SetAttr(%s, %s, %s)' % (
3190
+ env.module_cname,
3191
+ code.intern_identifier(EncodedString("__name__")),
3192
+ code.intern_identifier(EncodedString("__main__"))))
3193
+ code.putln("}")
3194
+
3195
+ # set up __file__ and __path__, then add the module to sys.modules
3196
+ self.generate_module_import_setup(env, code)
3197
+
3198
+ if Options.cache_builtins:
3199
+ code.putln("/*--- Builtin init code ---*/")
3200
+ code.put_error_if_neg(
3201
+ self.pos,
3202
+ f"__Pyx_InitCachedBuiltins({Naming.modulestatevalue_cname})")
3203
+
3204
+ code.putln("/*--- Constants init code ---*/")
3205
+ code.put_error_if_neg(
3206
+ self.pos,
3207
+ f"__Pyx_InitCachedConstants({Naming.modulestatevalue_cname})")
3208
+ # code objects come after the other globals (since they use strings and tuples)
3209
+ code.put_error_if_neg(
3210
+ self.pos,
3211
+ f"__Pyx_CreateCodeObjects({Naming.modulestatevalue_cname})")
3212
+
3213
+ code.putln("/*--- Global type/function init code ---*/")
3214
+
3215
+ with subfunction("Global init code") as inner_code:
3216
+ self.generate_global_init_code(env, inner_code)
3217
+
3218
+ with subfunction("Variable export code") as inner_code:
3219
+ self.generate_c_variable_export_code(env, inner_code)
3220
+
3221
+ with subfunction("Function export code") as inner_code:
3222
+ self.generate_c_function_export_code(env, inner_code)
3223
+
3224
+ shared_utility_exporter.call_export_code(code)
3225
+
3226
+ with subfunction("Type init code") as inner_code:
3227
+ self.generate_type_init_code(env, inner_code)
3228
+
3229
+ with subfunction("Type import code") as inner_code:
3230
+ for module in imported_modules:
3231
+ self.generate_type_import_code_for_module(module, env, inner_code)
3232
+
3233
+ with subfunction("Variable import code") as inner_code:
3234
+ for module in imported_modules:
3235
+ self.generate_c_variable_import_code_for_module(module, env, inner_code)
3236
+
3237
+ with subfunction("Function import code") as inner_code:
3238
+ for module in imported_modules:
3239
+ self.specialize_fused_types(module)
3240
+ self.generate_c_function_import_code_for_module(module, env, inner_code)
3241
+
3242
+ shared_utility_exporter.call_import_code(code)
3243
+
3244
+ code.putln("/*--- Execution code ---*/")
3245
+ code.mark_pos(None)
3246
+
3247
+ if profile or linetrace:
3248
+ assert code.funcstate.gil_owned
3249
+ code.put_trace_start(modinit_func_name, self.pos)
3250
+ code.funcstate.can_trace = True
3251
+
3252
+ code.mark_pos(None)
3253
+ self.body.generate_execution_code(code)
3254
+ code.mark_pos(None)
3255
+
3256
+ if profile or linetrace:
3257
+ code.funcstate.can_trace = False
3258
+ assert code.funcstate.gil_owned
3259
+ code.put_trace_return("Py_None", pos=self.pos)
3260
+ code.put_trace_exit()
3261
+
3262
+ code.putln()
3263
+ code.putln("/*--- Wrapped vars code ---*/")
3264
+ self.generate_wrapped_entries_code(env, code)
3265
+ code.putln()
3266
+
3267
+ if Options.generate_cleanup_code:
3268
+ code.globalstate.use_utility_code(
3269
+ UtilityCode.load_cached("RegisterModuleCleanup", "ModuleSetupCode.c"))
3270
+ code.putln("if (__Pyx_RegisterCleanup()) %s" % code.error_goto(self.pos))
3271
+
3272
+ code.put_goto(code.return_label)
3273
+ code.put_label(code.error_label)
3274
+ for cname, type in code.funcstate.all_managed_temps():
3275
+ code.put_xdecref(cname, type)
3276
+
3277
+ if profile or linetrace:
3278
+ code.put_trace_exception_propagating()
3279
+ code.put_trace_unwind(self.pos)
3280
+
3281
+ code.putln('if (%s) {' % env.module_cname)
3282
+ code.putln(
3283
+ f'if ({code.name_in_main_c_code_module_state(env.module_dict_cname)} && stringtab_initialized) {{')
3284
+ # We can run into errors before the module or stringtab are initialized.
3285
+ # In this case it is not safe to add a traceback (because it uses the stringtab)
3286
+ code.put_add_traceback(EncodedString("init %s" % env.qualified_name))
3287
+ code.globalstate.use_utility_code(Nodes.traceback_utility_code)
3288
+ # Module reference and module dict are in global variables which might still be needed
3289
+ # for cleanup, atexit code, etc., so leaking is better than crashing.
3290
+ # At least clearing the module dict here might be a good idea, but could still break
3291
+ # user code in atexit or other global registries.
3292
+ ##code.put_decref_clear(env.module_dict_cname, py_object_type, nanny=False)
3293
+ code.putln('}')
3294
+ code.putln("#if !CYTHON_USE_MODULE_STATE")
3295
+ code.put_decref_clear(env.module_cname, py_object_type, nanny=False, clear_before_decref=True)
3296
+ code.putln("#else")
3297
+ # This section is mainly for the limited API. env.module_cname still owns a reference so
3298
+ # decrement that
3299
+ code.put_decref(env.module_cname, py_object_type, nanny=False)
3300
+ # Also remove the failed module from the module state lookup
3301
+ # fetch/restore the error indicator because PyState_RemoveModule might fail itself
3302
+ code.putln("if (pystate_addmodule_run) {")
3303
+ code.putln("PyObject *tp, *value, *tb;")
3304
+ code.putln("PyErr_Fetch(&tp, &value, &tb);")
3305
+ code.putln("PyState_RemoveModule(&%s);" % Naming.pymoduledef_cname)
3306
+ code.putln("PyErr_Restore(tp, value, tb);")
3307
+ code.putln("}")
3308
+ code.putln("#endif")
3309
+ code.putln('} else if (!PyErr_Occurred()) {')
3310
+ code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' %
3311
+ env.qualified_name.as_c_string_literal()[1:-1])
3312
+ code.putln('}')
3313
+ code.put_label(code.return_label)
3314
+
3315
+ code.put_finish_refcount_context()
3316
+
3317
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3318
+ code.putln("return (%s != NULL) ? 0 : -1;" % env.module_cname)
3319
+ code.putln("#else")
3320
+ code.putln("return %s;" % env.module_cname)
3321
+ code.putln("#endif")
3322
+ code.putln('}')
3323
+
3324
+ tempdecl_code.put_temp_declarations(code.funcstate)
3325
+
3326
+ code.exit_cfunc_scope()
3327
+
3328
+ def mod_init_subfunction(self, pos, scope, orig_code):
3329
+ """
3330
+ Return a context manager that allows deviating the module init code generation
3331
+ into a separate function and instead inserts a call to it.
3332
+
3333
+ Can be reused sequentially to create multiple functions.
3334
+ The functions get inserted at the point where the context manager was created.
3335
+ The call gets inserted where the context manager is used (on entry).
3336
+ """
3337
+ function_code = orig_code.insertion_point()
3338
+
3339
+ class ModInitSubfunction:
3340
+ def __init__(self, code_type):
3341
+ cname = '_'.join(code_type.lower().split())
3342
+ assert re.match("^[a-z0-9_]+$", cname)
3343
+ self.cfunc_name = "__Pyx_modinit_%s" % cname
3344
+ self.description = code_type
3345
+ self.tempdecl_code = None
3346
+ self.call_code = None
3347
+
3348
+ def set_call_code(self, code):
3349
+ self.call_code = code.insertion_point()
3350
+
3351
+ def __enter__(self):
3352
+ if self.call_code is None:
3353
+ self.call_code = orig_code.insertion_point()
3354
+ code = function_code
3355
+ code.start_initcfunc(
3356
+ f"int {self.cfunc_name}({Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname})",
3357
+ scope, refnanny=True)
3358
+ code.putln(f"CYTHON_UNUSED_VAR({Naming.modulestatevalue_cname});")
3359
+ self.tempdecl_code = code.insertion_point()
3360
+ code.put_setup_refcount_context(EncodedString(self.cfunc_name))
3361
+ # Leave a grepable marker that makes it easy to find the generator source.
3362
+ code.putln("/*--- %s ---*/" % self.description)
3363
+ return code
3364
+
3365
+ def __exit__(self, exc_type, exc_value, exc_tb):
3366
+ if exc_type is not None:
3367
+ # Don't generate any code or do any validations on errors.
3368
+ self.tempdecl_code = self.call_code = None
3369
+ return
3370
+
3371
+ code = function_code
3372
+ code.put_finish_refcount_context()
3373
+ code.putln("return 0;")
3374
+
3375
+ self.tempdecl_code.put_temp_declarations(code.funcstate)
3376
+ self.tempdecl_code = None
3377
+
3378
+ needs_error_handling = code.label_used(code.error_label)
3379
+ if needs_error_handling:
3380
+ code.put_label(code.error_label)
3381
+ for cname, type in code.funcstate.all_managed_temps():
3382
+ code.put_xdecref(cname, type)
3383
+ code.put_finish_refcount_context()
3384
+ code.putln("return -1;")
3385
+ code.putln("}")
3386
+ code.exit_cfunc_scope()
3387
+
3388
+ if needs_error_handling:
3389
+ self.call_code.putln(
3390
+ self.call_code.error_goto_if_neg("%s(%s)" % (
3391
+ self.cfunc_name, Naming.modulestatevalue_cname), pos))
3392
+ else:
3393
+ self.call_code.putln(
3394
+ f"(void){self.cfunc_name}({Naming.modulestatevalue_cname});")
3395
+ self.call_code = None
3396
+
3397
+ return ModInitSubfunction
3398
+
3399
+ def generate_module_import_setup(self, env, code):
3400
+ module_path = env.directives['set_initial_path']
3401
+ if module_path == 'SOURCEFILE':
3402
+ module_path = self.pos[0].filename
3403
+
3404
+ if module_path:
3405
+ code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {')
3406
+ code.putln('if (PyObject_SetAttrString(%s, "__file__", %s) < 0) %s;' % (
3407
+ env.module_cname,
3408
+ code.get_py_string_const(
3409
+ EncodedString(decode_filename(module_path))),
3410
+ code.error_goto(self.pos)))
3411
+ code.putln("}")
3412
+
3413
+ if env.is_package:
3414
+ # set __path__ to mark the module as package
3415
+ code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {')
3416
+ temp = code.funcstate.allocate_temp(py_object_type, True)
3417
+ code.putln('%s = Py_BuildValue("[O]", %s); %s' % (
3418
+ temp,
3419
+ code.get_py_string_const(
3420
+ EncodedString(decode_filename(
3421
+ os.path.dirname(module_path)))),
3422
+ code.error_goto_if_null(temp, self.pos)))
3423
+ code.put_gotref(temp, py_object_type)
3424
+ code.putln(
3425
+ 'if (PyObject_SetAttrString(%s, "__path__", %s) < 0) %s;' % (
3426
+ env.module_cname, temp, code.error_goto(self.pos)))
3427
+ code.put_decref_clear(temp, py_object_type)
3428
+ code.funcstate.release_temp(temp)
3429
+ code.putln("}")
3430
+
3431
+ elif env.is_package:
3432
+ # packages require __path__, so all we can do is try to figure
3433
+ # out the module path at runtime by rerunning the import lookup
3434
+ code.putln("if (!CYTHON_PEP489_MULTI_PHASE_INIT) {")
3435
+ code.globalstate.use_utility_code(UtilityCode.load(
3436
+ "SetPackagePathFromImportLib", "ImportExport.c"))
3437
+ code.putln(code.error_goto_if_neg(
3438
+ '__Pyx_SetPackagePathFromImportLib(%s)' % (
3439
+ code.get_py_string_const(
3440
+ EncodedString(self.full_module_name))),
3441
+ self.pos))
3442
+ code.putln("}")
3443
+
3444
+ # CPython may not have put us into sys.modules yet, but relative imports and reimports require it
3445
+ fq_module_name = self.full_module_name
3446
+ if fq_module_name.endswith('.__init__'):
3447
+ fq_module_name = EncodedString(fq_module_name[:-len('.__init__')])
3448
+ fq_module_name_cstring = fq_module_name.as_c_string_literal()
3449
+ code.putln("{")
3450
+ code.putln("PyObject *modules = PyImport_GetModuleDict(); %s" %
3451
+ code.error_goto_if_null("modules", self.pos))
3452
+ code.putln('if (!PyDict_GetItemString(modules, %s)) {' % fq_module_name_cstring)
3453
+ code.putln(code.error_goto_if_neg('PyDict_SetItemString(modules, %s, %s)' % (
3454
+ fq_module_name_cstring, env.module_cname), self.pos))
3455
+ code.putln("}")
3456
+ code.putln("}")
3457
+
3458
+ def generate_module_cleanup_func(self, env, code):
3459
+ if not Options.generate_cleanup_code:
3460
+ return
3461
+
3462
+ code.putln('static void %s(CYTHON_UNUSED PyObject *self) {' %
3463
+ Naming.cleanup_cname)
3464
+ code.enter_cfunc_scope(env)
3465
+ code.putln(f"{Naming.modulestatetype_cname} *{Naming.modulestatevalue_cname};")
3466
+
3467
+ # TODO - this should go away when module-state has been refactored more and
3468
+ # we are able to access the module state through "self". Currently the
3469
+ # `#define` for each entry forces us to access it through PyState_FindModule
3470
+ # which is sometime unreliable during destruction
3471
+ # (e.g. during interpreter shutdown).
3472
+ # In that case the safest thing is to give up.
3473
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3474
+ code.putln(f"if (!__Pyx_State_FindModule(&{Naming.pymoduledef_cname})) return;")
3475
+ code.putln("#endif")
3476
+ code.putln(f"{Naming.modulestatevalue_cname} = __Pyx_PyModule_GetState(self);")
3477
+
3478
+ if Options.generate_cleanup_code >= 2:
3479
+ code.putln("/*--- Global cleanup code ---*/")
3480
+ rev_entries = list(env.var_entries)
3481
+ rev_entries.reverse()
3482
+ for entry in rev_entries:
3483
+ if entry.visibility != 'extern':
3484
+ if entry.type.is_pyobject and entry.used:
3485
+ if entry.is_cglobal:
3486
+ # TODO - eventually these should probably be in the module state too
3487
+ entry_cname = entry.cname
3488
+ else:
3489
+ entry_cname = code.name_in_module_state(entry.cname)
3490
+ code.put_xdecref_clear(
3491
+ entry_cname, entry.type,
3492
+ clear_before_decref=True,
3493
+ nanny=False)
3494
+ if entry.type.needs_explicit_destruction(env):
3495
+ entry.type.generate_explicit_destruction(code, entry)
3496
+ code.putln(f"__Pyx_CleanupGlobals({Naming.modulestatevalue_cname});")
3497
+ if Options.generate_cleanup_code >= 3:
3498
+ code.putln("/*--- Type import cleanup code ---*/")
3499
+ for ext_type in sorted(env.types_imported, key=operator.attrgetter('typeptr_cname')):
3500
+ typeptr_cname = code.name_in_main_c_code_module_state(ext_type.typeptr_cname)
3501
+ code.put_xdecref_clear(
3502
+ typeptr_cname, ext_type,
3503
+ clear_before_decref=True,
3504
+ nanny=False)
3505
+ if Options.cache_builtins:
3506
+ code.putln("/*--- Builtin cleanup code ---*/")
3507
+ for entry in env.cached_builtins:
3508
+ code.put_xdecref_clear(
3509
+ entry.cname, PyrexTypes.py_object_type,
3510
+ clear_before_decref=True,
3511
+ nanny=False)
3512
+ code.putln("/*--- Intern cleanup code ---*/")
3513
+ code.put_decref_clear(f"{code.name_in_main_c_code_module_state(Naming.empty_tuple)}",
3514
+ PyrexTypes.py_object_type,
3515
+ clear_before_decref=True,
3516
+ nanny=False)
3517
+ for entry in env.c_class_entries:
3518
+ cclass_type = entry.type
3519
+ if cclass_type.is_external or cclass_type.base_type:
3520
+ continue
3521
+ if cclass_type.scope.directives.get('freelist', 0):
3522
+ scope = cclass_type.scope
3523
+ freelist_name = code.name_in_main_c_code_module_state(
3524
+ scope.mangle_internal(Naming.freelist_name))
3525
+ freecount_name = code.name_in_main_c_code_module_state(
3526
+ scope.mangle_internal(Naming.freecount_name))
3527
+ code.putln('#if CYTHON_USE_FREELISTS')
3528
+ code.putln("while (%s > 0) {" % freecount_name)
3529
+ code.putln("PyObject* o = (PyObject*)%s[--%s];" % (
3530
+ freelist_name, freecount_name))
3531
+ code.putln("PyTypeObject *tp = Py_TYPE(o);")
3532
+ code.putln("#if CYTHON_USE_TYPE_SLOTS")
3533
+ code.putln("(*tp->tp_free)(o);")
3534
+ code.putln("#else")
3535
+ # Asking for PyType_GetSlot(..., Py_tp_free) seems to cause an error in pypy
3536
+ code.putln("freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free);")
3537
+ code.putln("if (tp_free) tp_free(o);")
3538
+ code.putln("#endif")
3539
+ code.putln("#if CYTHON_USE_TYPE_SPECS")
3540
+ # Release the reference that "o" owned for its type.
3541
+ code.putln("Py_DECREF(tp);")
3542
+ code.putln("#endif")
3543
+ code.putln("}")
3544
+ code.putln('#endif') # CYTHON_USE_FREELISTS
3545
+ # for entry in env.pynum_entries:
3546
+ # code.put_decref_clear(entry.cname,
3547
+ # PyrexTypes.py_object_type,
3548
+ # nanny=False)
3549
+ # for entry in env.all_pystring_entries:
3550
+ # if entry.is_interned:
3551
+ # code.put_decref_clear(entry.pystring_cname,
3552
+ # PyrexTypes.py_object_type,
3553
+ # nanny=False)
3554
+ # for entry in env.default_entries:
3555
+ # if entry.type.is_pyobject and entry.used:
3556
+ # code.putln("Py_DECREF(%s); %s = 0;" % (
3557
+ # code.entry_as_pyobject(entry), entry.cname))
3558
+ if Options.pre_import is not None:
3559
+ code.put_decref_clear(Naming.preimport_cname, py_object_type,
3560
+ nanny=False, clear_before_decref=True)
3561
+ for cname in [Naming.cython_runtime_cname, Naming.builtins_cname]:
3562
+ cname = code.name_in_main_c_code_module_state(cname)
3563
+ code.put_decref_clear(cname, py_object_type, nanny=False, clear_before_decref=True)
3564
+ code.put_decref_clear(
3565
+ code.name_in_main_c_code_module_state(env.module_dict_cname),
3566
+ py_object_type, nanny=False, clear_before_decref=True)
3567
+
3568
+ def generate_main_method(self, env, code):
3569
+ module_is_main = self.is_main_module_flag_cname()
3570
+ if Options.embed == "main":
3571
+ wmain = "wmain"
3572
+ else:
3573
+ wmain = Options.embed
3574
+ main_method = TempitaUtilityCode.load_cached(
3575
+ "MainFunction", "Embed.c",
3576
+ context={
3577
+ 'module_name': env.module_name,
3578
+ 'module_is_main': module_is_main,
3579
+ 'main_method': Options.embed,
3580
+ 'wmain_method': wmain,
3581
+ 'embed_modules': tuple(Options.embed_modules)})
3582
+ code.globalstate.use_utility_code(main_method)
3583
+
3584
+ def punycode_module_name(self, prefix, name):
3585
+ # adapted from PEP483
3586
+ if name.isascii():
3587
+ name = '_' + name
3588
+ else:
3589
+ name = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
3590
+ return "%s%s" % (prefix, name)
3591
+
3592
+ def wrong_punycode_module_name(self, name):
3593
+ # to work around a distutils bug by also generating an incorrect symbol...
3594
+ if name.isascii():
3595
+ return None # workaround is not needed
3596
+ return "PyInitU" + ("_"+name).encode('punycode').replace(b'-', b'_').decode('ascii')
3597
+
3598
+ def mod_init_func_cname(self, prefix, env):
3599
+ # from PEP483
3600
+ return self.punycode_module_name(prefix, env.module_name)
3601
+
3602
+ # Returns the name of the C-function that corresponds to the module initialisation.
3603
+ # (module initialisation == the cython code outside of functions)
3604
+ # Note that this should never be the name of a wrapper and always the name of the
3605
+ # function containing the actual code. Otherwise, cygdb will experience problems.
3606
+ def module_init_func_cname(self):
3607
+ env = self.scope
3608
+ return self.mod_init_func_cname(Naming.pymodule_exec_func_cname, env)
3609
+
3610
+ def generate_pymoduledef_struct(self, env, code):
3611
+ if env.doc:
3612
+ doc = "%s" % code.get_string_const(env.doc)
3613
+ else:
3614
+ doc = "0"
3615
+ if Options.generate_cleanup_code:
3616
+ cleanup_func = "(freefunc)%s" % Naming.cleanup_cname
3617
+ else:
3618
+ cleanup_func = 'NULL'
3619
+
3620
+ code.putln("")
3621
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3622
+ exec_func_cname = self.module_init_func_cname()
3623
+ code.putln("static PyObject* %s(PyObject *spec, PyModuleDef *def); /*proto*/" %
3624
+ Naming.pymodule_create_func_cname)
3625
+ code.putln("static int %s(PyObject* module); /*proto*/" % exec_func_cname)
3626
+
3627
+ code.putln("static PyModuleDef_Slot %s[] = {" % Naming.pymoduledef_slots_cname)
3628
+ code.putln("{Py_mod_create, (void*)%s}," % Naming.pymodule_create_func_cname)
3629
+ code.putln("{Py_mod_exec, (void*)%s}," % exec_func_cname)
3630
+ code.putln("#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING")
3631
+ gil_option = ("Py_MOD_GIL_NOT_USED"
3632
+ if env.directives["freethreading_compatible"]
3633
+ else "Py_MOD_GIL_USED")
3634
+ code.putln("{Py_mod_gil, %s}," % gil_option)
3635
+ code.putln("#endif")
3636
+ code.putln("#if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE")
3637
+ subinterp_option = {
3638
+ 'no': 'Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED',
3639
+ 'shared_gil': 'Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED',
3640
+ 'own_gil': 'Py_MOD_PER_INTERPRETER_GIL_SUPPORTED'
3641
+ }.get(env.directives["subinterpreters_compatible"])
3642
+ code.putln("{Py_mod_multiple_interpreters, %s}," % subinterp_option)
3643
+ code.putln("#endif")
3644
+ code.putln("{0, NULL}")
3645
+ code.putln("};")
3646
+ if not env.module_name.isascii():
3647
+ code.putln("#else /* CYTHON_PEP489_MULTI_PHASE_INIT */")
3648
+ code.putln('#error "Unicode module names are only supported with multi-phase init'
3649
+ ' as per PEP489"')
3650
+ code.putln("#endif")
3651
+
3652
+ code.putln("")
3653
+ code.putln('#ifdef __cplusplus')
3654
+ code.putln('namespace {')
3655
+ code.putln("struct PyModuleDef %s =" % Naming.pymoduledef_cname)
3656
+ code.putln('#else')
3657
+ code.putln("static struct PyModuleDef %s =" % Naming.pymoduledef_cname)
3658
+ code.putln('#endif')
3659
+ code.putln('{')
3660
+ code.putln(" PyModuleDef_HEAD_INIT,")
3661
+ code.putln(' %s,' % env.module_name.as_c_string_literal())
3662
+ code.putln(" %s, /* m_doc */" % doc)
3663
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3664
+ code.putln(f" sizeof({Naming.modulestatetype_cname}), /* m_size */")
3665
+ code.putln("#else")
3666
+ code.putln(" (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */")
3667
+ code.putln("#endif")
3668
+ code.putln(" %s /* m_methods */," % env.method_table_cname)
3669
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3670
+ code.putln(" %s, /* m_slots */" % Naming.pymoduledef_slots_cname)
3671
+ code.putln("#else")
3672
+ code.putln(" NULL, /* m_reload */")
3673
+ code.putln("#endif")
3674
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3675
+ code.putln(" %s_traverse, /* m_traverse */" % Naming.module_cname)
3676
+ code.putln(" %s_clear, /* m_clear */" % Naming.module_cname)
3677
+ code.putln(" %s /* m_free */" % cleanup_func)
3678
+ code.putln("#else")
3679
+ code.putln(" NULL, /* m_traverse */")
3680
+ code.putln(" NULL, /* m_clear */")
3681
+ code.putln(" %s /* m_free */" % cleanup_func)
3682
+ code.putln("#endif")
3683
+ code.putln("};")
3684
+ code.putln('#ifdef __cplusplus')
3685
+ code.putln('} /* anonymous namespace */')
3686
+ code.putln('#endif')
3687
+
3688
+ def generate_module_creation_code(self, env, code):
3689
+ # Generate code to create the module object and
3690
+ # install the builtins.
3691
+ if env.doc:
3692
+ doc = "%s" % code.get_string_const(env.doc)
3693
+ else:
3694
+ doc = "0"
3695
+
3696
+ # manage_ref is False (and refnanny calls are omitted) because refnanny isn't yet initialized.
3697
+ module_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=False)
3698
+ code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT")
3699
+ code.putln("%s = %s;" % (
3700
+ module_temp,
3701
+ Naming.pymodinit_module_arg))
3702
+ code.put_incref(module_temp, py_object_type, nanny=False)
3703
+ code.putln("#else")
3704
+ code.putln(
3705
+ "%s = PyModule_Create(&%s); %s" % (
3706
+ module_temp,
3707
+ Naming.pymoduledef_cname,
3708
+ code.error_goto_if_null(module_temp, self.pos)))
3709
+ code.putln("#endif")
3710
+
3711
+ code.putln("#if CYTHON_USE_MODULE_STATE")
3712
+ code.putln("{")
3713
+ # So that PyState_FindModule works in the init function:
3714
+ code.putln("int add_module_result = __Pyx_State_AddModule(%s, &%s);" % (
3715
+ module_temp, Naming.pymoduledef_cname))
3716
+ code.putln("%s = 0; /* transfer ownership from %s to %s pseudovariable */" % (
3717
+ module_temp, module_temp, env.module_name.as_c_string_literal()
3718
+ ))
3719
+ # At this stage the module likely has a refcount of 2 - one owned by the list
3720
+ # inside PyState_AddModule and one owned by "__pyx_m" (and returned from this
3721
+ # function as a new reference).
3722
+ code.putln(code.error_goto_if_neg("add_module_result", self.pos))
3723
+ code.putln("pystate_addmodule_run = 1;")
3724
+ code.putln("}")
3725
+ code.putln('#else') # !CYTHON_USE_MODULE_STATE
3726
+ code.putln(f"{env.module_cname} = {module_temp};")
3727
+ code.putln("#endif")
3728
+ code.funcstate.release_temp(module_temp)
3729
+
3730
+ code.putln("#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING")
3731
+ gil_option = ("Py_MOD_GIL_NOT_USED"
3732
+ if env.directives["freethreading_compatible"]
3733
+ else "Py_MOD_GIL_USED")
3734
+ code.putln(f"PyUnstable_Module_SetGIL({env.module_cname}, {gil_option});")
3735
+ code.putln("#endif")
3736
+
3737
+ code.putln(f"{Naming.modulestatevalue_cname} = {Naming.modulestateglobal_cname};")
3738
+ code.putln("CYTHON_UNUSED_VAR(%s);" % module_temp) # only used in limited API
3739
+
3740
+ dict_cname = code.name_in_main_c_code_module_state(env.module_dict_cname)
3741
+ code.putln(
3742
+ "%s = PyModule_GetDict(%s); %s" % (
3743
+ dict_cname, env.module_cname,
3744
+ code.error_goto_if_null(dict_cname, self.pos)))
3745
+ code.put_incref(dict_cname, py_object_type, nanny=False)
3746
+
3747
+ builtins_cname = code.name_in_main_c_code_module_state(Naming.builtins_cname)
3748
+ code.putln(
3749
+ '%s = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); %s' % (
3750
+ builtins_cname,
3751
+ code.error_goto_if_null(builtins_cname, self.pos)))
3752
+ runtime_cname = code.name_in_main_c_code_module_state(Naming.cython_runtime_cname)
3753
+ code.putln(
3754
+ '%s = __Pyx_PyImport_AddModuleRef("cython_runtime"); %s' % (
3755
+ runtime_cname,
3756
+ code.error_goto_if_null(runtime_cname, self.pos)))
3757
+ code.putln(
3758
+ 'if (PyObject_SetAttrString(%s, "__builtins__", %s) < 0) %s' % (
3759
+ env.module_cname,
3760
+ builtins_cname,
3761
+ code.error_goto(self.pos)))
3762
+ if Options.pre_import is not None:
3763
+ code.putln(
3764
+ '%s = __Pyx_PyImport_AddModuleRef("%s"); %s' % (
3765
+ Naming.preimport_cname,
3766
+ Options.pre_import,
3767
+ code.error_goto_if_null(Naming.preimport_cname, self.pos)))
3768
+
3769
+ def generate_global_init_code(self, env, code):
3770
+ # Generate code to initialise global PyObject *
3771
+ # variables to None.
3772
+ for entry in env.var_entries:
3773
+ if entry.visibility != 'extern':
3774
+ if entry.used:
3775
+ entry.type.global_init_code(entry, code)
3776
+ if entry.type.needs_explicit_construction(env):
3777
+ # TODO - this is slightly redundant with global_init_code
3778
+ entry.type.generate_explicit_construction(code, entry)
3779
+
3780
+ def generate_wrapped_entries_code(self, env, code):
3781
+ for name, entry in sorted(env.entries.items()):
3782
+ if (entry.create_wrapper
3783
+ and not entry.is_type
3784
+ and entry.scope is env):
3785
+ if not entry.type.create_to_py_utility_code(env):
3786
+ error(entry.pos, "Cannot convert '%s' to Python object" % entry.type)
3787
+ code.putln("{")
3788
+ code.putln("PyObject* wrapped = %s(%s);" % (
3789
+ entry.type.to_py_function,
3790
+ entry.cname))
3791
+ code.putln(code.error_goto_if_null("wrapped", entry.pos))
3792
+ code.putln(
3793
+ 'if (PyObject_SetAttrString(%s, "%s", wrapped) < 0) %s;' % (
3794
+ env.module_cname,
3795
+ name,
3796
+ code.error_goto(entry.pos)))
3797
+ code.putln("}")
3798
+
3799
+ def _select_exported_entries(self, all_entries):
3800
+ return [
3801
+ entry for entry in all_entries
3802
+ if entry.api or entry.defined_in_pxd or (Options.cimport_from_pyx and entry.visibility != 'extern')
3803
+ ]
3804
+
3805
+ def generate_c_variable_export_code(self, env, code):
3806
+ """Generate code to create PyCFunction wrappers for exported C functions.
3807
+ """
3808
+ entries = self._select_exported_entries(env.var_entries)
3809
+ if not entries:
3810
+ return
3811
+
3812
+ exports = [
3813
+ # (signature, name, cname)
3814
+ (entry.type.empty_declaration_code(), entry.name, entry.cname)
3815
+ for entry in entries
3816
+ ]
3817
+ code.globalstate.use_utility_code(
3818
+ UtilityCode.load_cached("VoidPtrExport", "ImportExport.c"))
3819
+
3820
+ _generate_export_code(code, self.pos, exports, "__Pyx_ExportVoidPtr", "void *{name}")
3821
+
3822
+ def generate_c_function_export_code(self, env, code):
3823
+ """Generate code to create PyCFunction wrappers for exported C functions.
3824
+ """
3825
+ entries = self._select_exported_entries(env.cfunc_entries)
3826
+ if not entries:
3827
+ return
3828
+
3829
+ exports = [
3830
+ # (signature, name, cname)
3831
+ (entry.type.signature_string(), entry.name, entry.cname)
3832
+ for entry in entries
3833
+ ]
3834
+ code.globalstate.use_utility_code(
3835
+ UtilityCode.load_cached("FunctionExport", "ImportExport.c"))
3836
+
3837
+ _generate_export_code(code, self.pos, exports, "__Pyx_ExportFunction", "void (*{name})(void)")
3838
+
3839
+ def generate_type_import_code_for_module(self, module, env, code):
3840
+ # Generate type import code for all exported extension types in
3841
+ # an imported module.
3842
+ #if module.c_class_entries:
3843
+ with ModuleImportGenerator(code) as import_generator:
3844
+ for entry in module.c_class_entries:
3845
+ if entry.defined_in_pxd:
3846
+ self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator)
3847
+
3848
+ def specialize_fused_types(self, pxd_env):
3849
+ """
3850
+ If fused c(p)def functions are defined in an imported pxd, but not
3851
+ used in this implementation file, we still have fused entries and
3852
+ not specialized ones. This method replaces any fused entries with their
3853
+ specialized ones.
3854
+ """
3855
+ for entry in pxd_env.cfunc_entries[:]:
3856
+ if entry.type.is_fused:
3857
+ # This call modifies the cfunc_entries in-place
3858
+ entry.type.get_all_specialized_function_types()
3859
+
3860
+ def _select_imported_entries(self, all_entries, used_only=False):
3861
+ return [
3862
+ entry for entry in all_entries
3863
+ if entry.defined_in_pxd and (not used_only or entry.used)
3864
+ ]
3865
+
3866
+ def generate_c_variable_import_code_for_module(self, module, env, code):
3867
+ """Generate import code for all exported C functions in a cimported module.
3868
+ """
3869
+ entries = self._select_imported_entries(module.var_entries, used_only=False)
3870
+ if not entries:
3871
+ return
3872
+
3873
+ is_module_scope = env is module
3874
+ imports = [
3875
+ # (signature, name, cname)
3876
+ (entry.type.empty_declaration_code(),
3877
+ entry.name,
3878
+ entry.cname if is_module_scope else module.mangle(Naming.varptr_prefix, entry.name))
3879
+ for entry in entries
3880
+ ]
3881
+ code.globalstate.use_utility_code(
3882
+ UtilityCode.load_cached("VoidPtrImport", "ImportExport.c"))
3883
+
3884
+ _generate_import_code(
3885
+ code, self.pos, imports, module.qualified_name, f"__Pyx_ImportVoidPtr_{Naming.cyversion}", "void **{name}")
3886
+
3887
+ def generate_c_function_import_code_for_module(self, module, env, code):
3888
+ """Generate import code for all exported C functions in a cimported module.
3889
+ """
3890
+ entries = self._select_imported_entries(module.cfunc_entries, used_only=True)
3891
+ if not entries:
3892
+ return
3893
+
3894
+ imports = [
3895
+ # (signature, name, cname)
3896
+ (entry.type.signature_string(), entry.name, entry.cname)
3897
+ for entry in entries
3898
+ ]
3899
+ code.globalstate.use_utility_code(
3900
+ UtilityCode.load_cached("FunctionImport", "ImportExport.c"))
3901
+
3902
+ _generate_import_code(
3903
+ code, self.pos, imports, module.qualified_name, f"__Pyx_ImportFunction_{Naming.cyversion}", "void (**{name})(void)")
3904
+
3905
+ def generate_type_init_code(self, env, code):
3906
+ # Generate type import code for extern extension types
3907
+ # and type ready code for non-extern ones.
3908
+ with ModuleImportGenerator(code) as import_generator:
3909
+ for entry in env.c_class_entries:
3910
+ if entry.visibility == 'extern' and not entry.utility_code_definition:
3911
+ self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator)
3912
+ else:
3913
+ self.generate_base_type_import_code(env, entry, code, import_generator)
3914
+ self.generate_exttype_vtable_init_code(entry, code)
3915
+ if entry.type.early_init:
3916
+ self.generate_type_ready_code(entry, code)
3917
+
3918
+ def generate_base_type_import_code(self, env, entry, code, import_generator):
3919
+ base_type = entry.type.base_type
3920
+ if (base_type and base_type.module_name != env.qualified_name and not
3921
+ (base_type.is_builtin_type or base_type.is_cython_builtin_type)
3922
+ and not entry.utility_code_definition):
3923
+ self.generate_type_import_code(env, base_type, self.pos, code, import_generator)
3924
+
3925
+ def generate_type_import_code(self, env, type, pos, code, import_generator):
3926
+ # If not already done, generate code to import the typeobject of an
3927
+ # extension type defined in another module, and extract its C method
3928
+ # table pointer if any.
3929
+ if type in env.types_imported:
3930
+ return
3931
+ if type.name not in Code.ctypedef_builtins_map:
3932
+ # see corresponding condition in generate_type_import_call() below!
3933
+ code.globalstate.use_utility_code(
3934
+ UtilityCode.load_cached("TypeImport", "ImportExport.c"))
3935
+ self.generate_type_import_call(type, code, import_generator, error_pos=pos)
3936
+ if type.vtabptr_cname:
3937
+ code.globalstate.use_utility_code(
3938
+ UtilityCode.load_cached('GetVTable', 'ImportExport.c'))
3939
+ code.putln("%s = (struct %s*)__Pyx_GetVtable(%s); %s" % (
3940
+ type.vtabptr_cname,
3941
+ type.vtabstruct_cname,
3942
+ code.name_in_main_c_code_module_state(type.typeptr_cname),
3943
+ code.error_goto_if_null(type.vtabptr_cname, pos)))
3944
+ env.types_imported.add(type)
3945
+
3946
+ def generate_type_import_call(self, type, code, import_generator, error_code=None, error_pos=None, is_api=False):
3947
+ sizeof_objstruct = objstruct = type.objstruct_cname if type.typedef_flag else f"struct {type.objstruct_cname}"
3948
+ module_name = type.module_name
3949
+ type_name = type.name
3950
+ is_builtin = module_name in ('__builtin__', 'builtins')
3951
+ if not is_builtin:
3952
+ module_name = f'"{module_name}"'
3953
+ elif type_name in Code.ctypedef_builtins_map:
3954
+ # Fast path for special builtins, don't actually import
3955
+ code.putln(
3956
+ f'{code.name_in_module_state(type.typeptr_cname)} = {Code.ctypedef_builtins_map[type_name]};')
3957
+ return
3958
+ else:
3959
+ module_name = '__Pyx_BUILTIN_MODULE_NAME'
3960
+ if type_name in Code.renamed_py2_builtins_map:
3961
+ type_name = Code.renamed_py2_builtins_map[type_name]
3962
+ if objstruct in Code.basicsize_builtins_map:
3963
+ # Some builtin types have a tp_basicsize which differs from sizeof(...):
3964
+ sizeof_objstruct = Code.basicsize_builtins_map[objstruct]
3965
+
3966
+ if not error_code:
3967
+ assert error_pos is not None
3968
+ error_code = code.error_goto(error_pos)
3969
+
3970
+ module = import_generator.imported_module(module_name, error_code)
3971
+ typeptr_cname = type.typeptr_cname
3972
+ if not is_api:
3973
+ typeptr_cname = code.name_in_main_c_code_module_state(typeptr_cname)
3974
+
3975
+ code.putln(
3976
+ f"{typeptr_cname} = __Pyx_ImportType_{Naming.cyversion}("
3977
+ f"{module}, {module_name}, {type.name.as_c_string_literal()},"
3978
+ )
3979
+
3980
+ alignment_func = f"__PYX_GET_STRUCT_ALIGNMENT_{Naming.cyversion}"
3981
+ code.putln("#if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000")
3982
+ code.putln(f'sizeof({objstruct}), {alignment_func}({objstruct}),')
3983
+ code.putln("#elif CYTHON_COMPILING_IN_LIMITED_API")
3984
+ if is_builtin:
3985
+ # Builtin types are opaque in when the limited API is enabled
3986
+ # and subsequents attempt to access their fields will trigger
3987
+ # compile errors. Skip the struct size check here so things keep
3988
+ # working when a builtin type is imported but not actually used.
3989
+ code.putln('0, 0,')
3990
+ else:
3991
+ code.putln(f'sizeof({objstruct}), {alignment_func}({objstruct}),')
3992
+ code.putln('#else')
3993
+ code.putln(f'sizeof({sizeof_objstruct}), {alignment_func}({sizeof_objstruct}),')
3994
+ code.putln("#endif")
3995
+
3996
+ # check_size
3997
+ if type.check_size and type.check_size in ('error', 'warn', 'ignore'):
3998
+ check_size = type.check_size
3999
+ elif not type.is_external or type.is_subclassed:
4000
+ check_size = 'error'
4001
+ else:
4002
+ raise RuntimeError(
4003
+ f"invalid value for check_size '{type.check_size}' when compiling {module_name}.{type.name}")
4004
+ code.put(f'__Pyx_ImportType_CheckSize_{check_size.title()}_{Naming.cyversion});')
4005
+
4006
+ code.putln(f' if (!{typeptr_cname}) {error_code}')
4007
+ def generate_type_ready_code(self, entry, code):
4008
+ Nodes.CClassDefNode.generate_type_ready_code(entry, code)
4009
+
4010
+ def is_main_module_flag_cname(self):
4011
+ full_module_name = self.full_module_name.replace('.', '__')
4012
+ return self.punycode_module_name(Naming.module_is_main, full_module_name)
4013
+
4014
+ def generate_exttype_vtable_init_code(self, entry, code):
4015
+ # Generate code to initialise the C method table of an
4016
+ # extension type.
4017
+ type = entry.type
4018
+ if type.vtable_cname:
4019
+ code.putln(
4020
+ "%s = &%s;" % (
4021
+ type.vtabptr_cname,
4022
+ type.vtable_cname))
4023
+ if type.base_type and type.base_type.vtabptr_cname:
4024
+ code.putln(
4025
+ "%s.%s = *%s;" % (
4026
+ type.vtable_cname,
4027
+ Naming.obj_base_cname,
4028
+ type.base_type.vtabptr_cname))
4029
+
4030
+ c_method_entries = [
4031
+ entry for entry in type.scope.cfunc_entries
4032
+ if entry.func_cname]
4033
+ if c_method_entries:
4034
+ for meth_entry in c_method_entries:
4035
+ vtable_type = meth_entry.vtable_type or meth_entry.type
4036
+ cast = vtable_type.signature_cast_string()
4037
+ code.putln(
4038
+ "%s.%s = %s%s;" % (
4039
+ type.vtable_cname,
4040
+ meth_entry.cname,
4041
+ cast,
4042
+ meth_entry.func_cname))
4043
+
4044
+
4045
+ # cimport/export code for functions and pointers.
4046
+
4047
+ def _deduplicate_inout_signatures(item_tuples):
4048
+ # We can save runtime space for identical signatures by reusing the same C strings.
4049
+ # To deduplicate the signatures, we sort by them and store duplicates as empty C strings.
4050
+ signatures, names, items = zip(*sorted(item_tuples))
4051
+ signatures = list(signatures) # tuple -> list, to allow reassignments again
4052
+
4053
+ last_sig = None
4054
+ for i, signature in enumerate(signatures):
4055
+ if signature == last_sig:
4056
+ signatures[i] = ''
4057
+ else:
4058
+ last_sig = signature
4059
+
4060
+ return signatures, names, items
4061
+
4062
+
4063
+ def _generate_import_export_code(code: Code.CCodeWriter, pos, inout_item_tuples, per_item_func, target, pointer_decl, use_pybytes, is_import):
4064
+ signatures, names, inout_items = _deduplicate_inout_signatures(inout_item_tuples)
4065
+
4066
+ pyx = f"{Naming.pyrex_prefix}{'import' if is_import else 'export'}_"
4067
+
4068
+ pointer_cast = pointer_decl.format(name='')
4069
+ sig_bytes = '\0'.join(signatures).encode('utf-8')
4070
+ names_bytes = '\0'.join(names).encode('utf-8')
4071
+ pointers = [f"({pointer_cast})&{item_cname}" for item_cname in inout_items]
4072
+
4073
+ sigs_and_names_bytes = bytes_literal(sig_bytes + b'\0' + names_bytes, 'utf-8')
4074
+ if use_pybytes:
4075
+ code.putln(f"const char * {pyx}signature = __Pyx_PyBytes_AsString({code.get_py_string_const(sigs_and_names_bytes)});")
4076
+ code.putln("#if !CYTHON_ASSUME_SAFE_MACROS")
4077
+ code.putln(code.error_goto_if_null(f'{pyx}signature', pos))
4078
+ code.putln("#endif")
4079
+ else:
4080
+ code.putln(f"const char * {pyx}signature = {sigs_and_names_bytes.as_c_string_literal()};")
4081
+
4082
+ code.putln(f"const char * {pyx}name = {pyx}signature + {len(sig_bytes) + 1};")
4083
+ code.putln(f"{pointer_decl.format(name=f'const {pyx}pointers[]')} = {{{', '.join(pointers)}, ({pointer_cast}) NULL}};")
4084
+
4085
+ code.globalstate.use_utility_code(
4086
+ UtilityCode.load_cached("IncludeStringH", "StringTools.c"))
4087
+
4088
+ code.putln(f"{pointer_decl.format(name=f'const *{pyx}pointer')} = {pyx}pointers;")
4089
+ code.putln(f"const char *{pyx}current_signature = {pyx}signature;")
4090
+ code.putln(f"while (*{pyx}pointer) {{")
4091
+
4092
+ code.put_error_if_neg(
4093
+ pos,
4094
+ f"{per_item_func}({target}, {pyx}name, *{pyx}pointer, {pyx}current_signature)"
4095
+ )
4096
+ code.putln(f"++{pyx}pointer;")
4097
+ code.putln(f"{pyx}name = strchr({pyx}name, '\\0') + 1;")
4098
+ code.putln(f"{pyx}signature = strchr({pyx}signature, '\\0') + 1;")
4099
+ # Keep reusing the current signature until we find a new non-empty one.
4100
+ code.putln(f"if (*{pyx}signature != '\\0') {pyx}current_signature = {pyx}signature;")
4101
+
4102
+ code.putln("}") # while
4103
+
4104
+
4105
+ def _generate_export_code(code: Code.CCodeWriter, pos, exports, export_func, pointer_decl):
4106
+ """Generate function/pointer export code.
4107
+
4108
+ 'exports' is a list of (signature, name, exported_cname) tuples.
4109
+ """
4110
+ code.putln("{")
4111
+
4112
+ api_dict = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
4113
+ code.globalstate.use_utility_code(
4114
+ UtilityCode.load_cached("GetApiDict", "ImportExport.c"))
4115
+ code.putln(
4116
+ f"{api_dict} = __Pyx_ApiExport_GetApiDict(); "
4117
+ f"{code.error_goto_if_null(api_dict, pos)}"
4118
+ )
4119
+ code.put_gotref(api_dict, py_object_type)
4120
+
4121
+ _generate_import_export_code(code, pos, exports, export_func, api_dict, pointer_decl, use_pybytes=True, is_import=False)
4122
+
4123
+ code.put_decref_clear(api_dict, py_object_type)
4124
+ code.funcstate.release_temp(api_dict)
4125
+
4126
+ code.putln("}")
4127
+
4128
+
4129
+ def _generate_import_code(code, pos, imports, qualified_module_name, import_func, pointer_decl):
4130
+ """Generate function/pointer import code.
4131
+
4132
+ 'imports' is a list of (signature, name, imported_cname) tuples.
4133
+ """
4134
+ code.putln("{")
4135
+
4136
+ module_ref = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
4137
+ code.putln(
4138
+ f'{module_ref} = PyImport_ImportModule({qualified_module_name.as_c_string_literal()}); '
4139
+ f'{code.error_goto_if_null(module_ref, pos)}'
4140
+ )
4141
+ code.put_gotref(module_ref, py_object_type)
4142
+
4143
+ _generate_import_export_code(code, pos, imports, import_func, module_ref, pointer_decl, use_pybytes=True, is_import=True)
4144
+
4145
+ code.put_decref_clear(module_ref, py_object_type)
4146
+ code.funcstate.release_temp(module_ref)
4147
+
4148
+ code.putln("}")
4149
+
4150
+
4151
+ # Module import helper
4152
+
4153
+ class ModuleImportGenerator:
4154
+ """
4155
+ Helper to generate module import while importing external types.
4156
+ This is used to avoid excessive re-imports of external modules when multiple types are looked up.
4157
+ """
4158
+ def __init__(self, code, imported_modules=None):
4159
+ self.code = code
4160
+ self.imported = {}
4161
+ if imported_modules:
4162
+ for name, cname in imported_modules.items():
4163
+ self.imported['"%s"' % name] = cname
4164
+ self.temps = [] # remember original import order for freeing
4165
+
4166
+ def imported_module(self, module_name_string, error_code):
4167
+ if module_name_string in self.imported:
4168
+ return self.imported[module_name_string]
4169
+
4170
+ code = self.code
4171
+ temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
4172
+ self.temps.append(temp)
4173
+ code.putln('%s = PyImport_ImportModule(%s); if (unlikely(!%s)) %s' % (
4174
+ temp, module_name_string, temp, error_code))
4175
+ code.put_gotref(temp, py_object_type)
4176
+ self.imported[module_name_string] = temp
4177
+ return temp
4178
+
4179
+ def __enter__(self):
4180
+ return self
4181
+
4182
+ def __exit__(self, *exc):
4183
+ code = self.code
4184
+ for temp in self.temps:
4185
+ code.put_decref_clear(temp, py_object_type)
4186
+ code.funcstate.release_temp(temp)
4187
+
4188
+
4189
+ def generate_cfunction_declaration(entry, env, code, definition):
4190
+ from_cy_utility = entry.used and entry.utility_code_definition
4191
+ if entry.used and entry.inline_func_in_pxd or (not entry.in_cinclude and (
4192
+ definition or entry.defined_in_pxd or entry.visibility == 'extern' or from_cy_utility)):
4193
+ if entry.visibility == 'extern':
4194
+ storage_class = Naming.extern_c_macro
4195
+ dll_linkage = "DL_IMPORT"
4196
+ elif entry.visibility == 'public':
4197
+ storage_class = Naming.extern_c_macro
4198
+ dll_linkage = None
4199
+ elif entry.visibility == 'private':
4200
+ storage_class = "static"
4201
+ dll_linkage = None
4202
+ else:
4203
+ storage_class = "static"
4204
+ dll_linkage = None
4205
+ type = entry.type
4206
+
4207
+ if entry.defined_in_pxd and not definition:
4208
+ storage_class = "static"
4209
+ dll_linkage = None
4210
+ type = CPtrType(type)
4211
+
4212
+ header = type.declaration_code(
4213
+ entry.cname, dll_linkage=dll_linkage)
4214
+ modifiers = code.build_function_modifiers(entry.func_modifiers)
4215
+ code.putln("%s %s%s; /*proto*/" % (
4216
+ storage_class,
4217
+ modifiers,
4218
+ header))
4219
+ code.globalstate.use_entry_utility_code(entry)
4220
+
4221
+ #------------------------------------------------------------------------------------
4222
+ #
4223
+ # Runtime support code
4224
+ #
4225
+ #------------------------------------------------------------------------------------
4226
+
4227
+ refnanny_utility_code = UtilityCode.load("Refnanny", "ModuleSetupCode.c")
4228
+
4229
+ packed_struct_utility_code = UtilityCode(proto="""
4230
+ #if defined(__GNUC__)
4231
+ #define __Pyx_PACKED __attribute__((__packed__))
4232
+ #else
4233
+ #define __Pyx_PACKED
4234
+ #endif
4235
+ """, impl="", proto_block='utility_code_proto_before_types')