oxython 0.1.0__py3-none-any.whl

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