Cython 3.1.0a1__py3-none-any.whl

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