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