Cython 3.1.0__py3-none-any.whl

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