Cython 3.2.0__cp39-abi3-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +350 -0
  4. Cython/Build/Dependencies.py +1314 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +463 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/SharedModule.py +94 -0
  9. Cython/Build/Tests/TestCyCache.py +194 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +815 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +680 -0
  23. Cython/Compiler/Builtin.py +984 -0
  24. Cython/Compiler/CmdLine.py +263 -0
  25. Cython/Compiler/Code.pxd +149 -0
  26. Cython/Compiler/Code.py +3746 -0
  27. Cython/Compiler/Code.pyd +0 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +191 -0
  30. Cython/Compiler/Dataclass.py +864 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +297 -0
  33. Cython/Compiler/ExprNodes.py +15562 -0
  34. Cython/Compiler/FlowControl.pxd +97 -0
  35. Cython/Compiler/FlowControl.py +1451 -0
  36. Cython/Compiler/FlowControl.pyd +0 -0
  37. Cython/Compiler/FusedNode.py +971 -0
  38. Cython/Compiler/FusedNode.pyd +0 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +421 -0
  42. Cython/Compiler/LineTable.py +114 -0
  43. Cython/Compiler/LineTable.pyd +0 -0
  44. Cython/Compiler/Main.py +857 -0
  45. Cython/Compiler/MatchCaseNodes.py +259 -0
  46. Cython/Compiler/MemoryView.py +905 -0
  47. Cython/Compiler/ModuleNode.py +4235 -0
  48. Cython/Compiler/Naming.py +363 -0
  49. Cython/Compiler/Nodes.py +10831 -0
  50. Cython/Compiler/Optimize.py +5288 -0
  51. Cython/Compiler/Options.py +843 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +78 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4638 -0
  54. Cython/Compiler/Parsing.pxd +9 -0
  55. Cython/Compiler/Parsing.py +4775 -0
  56. Cython/Compiler/Parsing.pyd +0 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +5870 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.pxd +48 -0
  61. Cython/Compiler/Scanning.py +701 -0
  62. Cython/Compiler/Scanning.pyd +0 -0
  63. Cython/Compiler/StringEncoding.py +298 -0
  64. Cython/Compiler/Symtab.py +3073 -0
  65. Cython/Compiler/Tests/TestBuffer.py +105 -0
  66. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  67. Cython/Compiler/Tests/TestCmdLine.py +586 -0
  68. Cython/Compiler/Tests/TestCode.py +144 -0
  69. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  70. Cython/Compiler/Tests/TestGrammar.py +202 -0
  71. Cython/Compiler/Tests/TestMemView.py +71 -0
  72. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  73. Cython/Compiler/Tests/TestScanning.py +134 -0
  74. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  75. Cython/Compiler/Tests/TestStringEncoding.py +21 -0
  76. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  77. Cython/Compiler/Tests/TestTreePath.py +103 -0
  78. Cython/Compiler/Tests/TestTypes.py +75 -0
  79. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  80. Cython/Compiler/Tests/TestVisitor.py +61 -0
  81. Cython/Compiler/Tests/Utils.py +36 -0
  82. Cython/Compiler/Tests/__init__.py +1 -0
  83. Cython/Compiler/TreeFragment.py +278 -0
  84. Cython/Compiler/TreePath.py +303 -0
  85. Cython/Compiler/TypeInference.py +591 -0
  86. Cython/Compiler/TypeSlots.py +1174 -0
  87. Cython/Compiler/UFuncs.py +311 -0
  88. Cython/Compiler/UtilNodes.py +389 -0
  89. Cython/Compiler/UtilityCode.py +344 -0
  90. Cython/Compiler/Version.py +8 -0
  91. Cython/Compiler/Visitor.pxd +53 -0
  92. Cython/Compiler/Visitor.py +861 -0
  93. Cython/Compiler/Visitor.pyd +0 -0
  94. Cython/Compiler/__init__.py +1 -0
  95. Cython/Coverage.py +448 -0
  96. Cython/Debugger/Cygdb.py +177 -0
  97. Cython/Debugger/DebugWriter.py +82 -0
  98. Cython/Debugger/Tests/TestLibCython.py +275 -0
  99. Cython/Debugger/Tests/__init__.py +1 -0
  100. Cython/Debugger/Tests/cfuncs.c +8 -0
  101. Cython/Debugger/Tests/codefile +49 -0
  102. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  103. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  104. Cython/Debugger/__init__.py +1 -0
  105. Cython/Debugger/libcython.py +1548 -0
  106. Cython/Debugger/libpython.py +2821 -0
  107. Cython/Debugging.py +20 -0
  108. Cython/Distutils/__init__.py +2 -0
  109. Cython/Distutils/build_ext.py +139 -0
  110. Cython/Distutils/extension.py +96 -0
  111. Cython/Distutils/old_build_ext.py +351 -0
  112. Cython/Includes/cpython/__init__.pxd +173 -0
  113. Cython/Includes/cpython/array.pxd +178 -0
  114. Cython/Includes/cpython/bool.pxd +37 -0
  115. Cython/Includes/cpython/buffer.pxd +112 -0
  116. Cython/Includes/cpython/bytearray.pxd +33 -0
  117. Cython/Includes/cpython/bytes.pxd +200 -0
  118. Cython/Includes/cpython/cellobject.pxd +35 -0
  119. Cython/Includes/cpython/ceval.pxd +8 -0
  120. Cython/Includes/cpython/codecs.pxd +121 -0
  121. Cython/Includes/cpython/complex.pxd +60 -0
  122. Cython/Includes/cpython/contextvars.pxd +145 -0
  123. Cython/Includes/cpython/conversion.pxd +36 -0
  124. Cython/Includes/cpython/datetime.pxd +395 -0
  125. Cython/Includes/cpython/descr.pxd +26 -0
  126. Cython/Includes/cpython/dict.pxd +187 -0
  127. Cython/Includes/cpython/exc.pxd +263 -0
  128. Cython/Includes/cpython/fileobject.pxd +57 -0
  129. Cython/Includes/cpython/float.pxd +47 -0
  130. Cython/Includes/cpython/function.pxd +65 -0
  131. Cython/Includes/cpython/genobject.pxd +25 -0
  132. Cython/Includes/cpython/getargs.pxd +12 -0
  133. Cython/Includes/cpython/instance.pxd +25 -0
  134. Cython/Includes/cpython/iterator.pxd +36 -0
  135. Cython/Includes/cpython/iterobject.pxd +24 -0
  136. Cython/Includes/cpython/list.pxd +92 -0
  137. Cython/Includes/cpython/long.pxd +149 -0
  138. Cython/Includes/cpython/longintrepr.pxd +14 -0
  139. Cython/Includes/cpython/mapping.pxd +63 -0
  140. Cython/Includes/cpython/marshal.pxd +66 -0
  141. Cython/Includes/cpython/mem.pxd +120 -0
  142. Cython/Includes/cpython/memoryview.pxd +50 -0
  143. Cython/Includes/cpython/method.pxd +49 -0
  144. Cython/Includes/cpython/module.pxd +208 -0
  145. Cython/Includes/cpython/number.pxd +258 -0
  146. Cython/Includes/cpython/object.pxd +433 -0
  147. Cython/Includes/cpython/pycapsule.pxd +143 -0
  148. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  149. Cython/Includes/cpython/pyport.pxd +8 -0
  150. Cython/Includes/cpython/pystate.pxd +95 -0
  151. Cython/Includes/cpython/pythread.pxd +53 -0
  152. Cython/Includes/cpython/ref.pxd +141 -0
  153. Cython/Includes/cpython/sequence.pxd +134 -0
  154. Cython/Includes/cpython/set.pxd +119 -0
  155. Cython/Includes/cpython/slice.pxd +70 -0
  156. Cython/Includes/cpython/time.pxd +129 -0
  157. Cython/Includes/cpython/tuple.pxd +72 -0
  158. Cython/Includes/cpython/type.pxd +53 -0
  159. Cython/Includes/cpython/unicode.pxd +639 -0
  160. Cython/Includes/cpython/version.pxd +32 -0
  161. Cython/Includes/cpython/weakref.pxd +78 -0
  162. Cython/Includes/libc/__init__.pxd +1 -0
  163. Cython/Includes/libc/complex.pxd +35 -0
  164. Cython/Includes/libc/errno.pxd +127 -0
  165. Cython/Includes/libc/float.pxd +43 -0
  166. Cython/Includes/libc/limits.pxd +28 -0
  167. Cython/Includes/libc/locale.pxd +46 -0
  168. Cython/Includes/libc/math.pxd +209 -0
  169. Cython/Includes/libc/setjmp.pxd +10 -0
  170. Cython/Includes/libc/signal.pxd +64 -0
  171. Cython/Includes/libc/stddef.pxd +9 -0
  172. Cython/Includes/libc/stdint.pxd +105 -0
  173. Cython/Includes/libc/stdio.pxd +80 -0
  174. Cython/Includes/libc/stdlib.pxd +72 -0
  175. Cython/Includes/libc/string.pxd +50 -0
  176. Cython/Includes/libc/threads.pxd +234 -0
  177. Cython/Includes/libc/time.pxd +52 -0
  178. Cython/Includes/libcpp/__init__.pxd +4 -0
  179. Cython/Includes/libcpp/algorithm.pxd +320 -0
  180. Cython/Includes/libcpp/any.pxd +16 -0
  181. Cython/Includes/libcpp/atomic.pxd +59 -0
  182. Cython/Includes/libcpp/barrier.pxd +22 -0
  183. Cython/Includes/libcpp/bit.pxd +29 -0
  184. Cython/Includes/libcpp/cast.pxd +12 -0
  185. Cython/Includes/libcpp/cmath.pxd +518 -0
  186. Cython/Includes/libcpp/complex.pxd +106 -0
  187. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  188. Cython/Includes/libcpp/deque.pxd +165 -0
  189. Cython/Includes/libcpp/exception.pxd +86 -0
  190. Cython/Includes/libcpp/execution.pxd +15 -0
  191. Cython/Includes/libcpp/forward_list.pxd +63 -0
  192. Cython/Includes/libcpp/functional.pxd +26 -0
  193. Cython/Includes/libcpp/future.pxd +103 -0
  194. Cython/Includes/libcpp/iterator.pxd +34 -0
  195. Cython/Includes/libcpp/latch.pxd +17 -0
  196. Cython/Includes/libcpp/limits.pxd +61 -0
  197. Cython/Includes/libcpp/list.pxd +117 -0
  198. Cython/Includes/libcpp/map.pxd +252 -0
  199. Cython/Includes/libcpp/memory.pxd +115 -0
  200. Cython/Includes/libcpp/mutex.pxd +387 -0
  201. Cython/Includes/libcpp/numbers.pxd +15 -0
  202. Cython/Includes/libcpp/numeric.pxd +131 -0
  203. Cython/Includes/libcpp/optional.pxd +34 -0
  204. Cython/Includes/libcpp/pair.pxd +1 -0
  205. Cython/Includes/libcpp/queue.pxd +25 -0
  206. Cython/Includes/libcpp/random.pxd +166 -0
  207. Cython/Includes/libcpp/semaphore.pxd +43 -0
  208. Cython/Includes/libcpp/set.pxd +228 -0
  209. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  210. Cython/Includes/libcpp/span.pxd +87 -0
  211. Cython/Includes/libcpp/stack.pxd +11 -0
  212. Cython/Includes/libcpp/stop_token.pxd +117 -0
  213. Cython/Includes/libcpp/string.pxd +355 -0
  214. Cython/Includes/libcpp/string_view.pxd +183 -0
  215. Cython/Includes/libcpp/typeindex.pxd +15 -0
  216. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  217. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  218. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  219. Cython/Includes/libcpp/utility.pxd +30 -0
  220. Cython/Includes/libcpp/vector.pxd +186 -0
  221. Cython/Includes/numpy/math.pxd +150 -0
  222. Cython/Includes/openmp.pxd +50 -0
  223. Cython/Includes/posix/__init__.pxd +1 -0
  224. Cython/Includes/posix/dlfcn.pxd +14 -0
  225. Cython/Includes/posix/fcntl.pxd +86 -0
  226. Cython/Includes/posix/ioctl.pxd +4 -0
  227. Cython/Includes/posix/mman.pxd +101 -0
  228. Cython/Includes/posix/resource.pxd +57 -0
  229. Cython/Includes/posix/select.pxd +21 -0
  230. Cython/Includes/posix/signal.pxd +73 -0
  231. Cython/Includes/posix/stat.pxd +98 -0
  232. Cython/Includes/posix/stdio.pxd +37 -0
  233. Cython/Includes/posix/stdlib.pxd +29 -0
  234. Cython/Includes/posix/strings.pxd +9 -0
  235. Cython/Includes/posix/time.pxd +71 -0
  236. Cython/Includes/posix/types.pxd +30 -0
  237. Cython/Includes/posix/uio.pxd +26 -0
  238. Cython/Includes/posix/unistd.pxd +271 -0
  239. Cython/Includes/posix/wait.pxd +38 -0
  240. Cython/Plex/Actions.pxd +24 -0
  241. Cython/Plex/Actions.py +119 -0
  242. Cython/Plex/Actions.pyd +0 -0
  243. Cython/Plex/DFA.pxd +14 -0
  244. Cython/Plex/DFA.py +164 -0
  245. Cython/Plex/DFA.pyd +0 -0
  246. Cython/Plex/Errors.py +48 -0
  247. Cython/Plex/Lexicons.py +178 -0
  248. Cython/Plex/Machines.pxd +36 -0
  249. Cython/Plex/Machines.py +238 -0
  250. Cython/Plex/Machines.pyd +0 -0
  251. Cython/Plex/Regexps.py +535 -0
  252. Cython/Plex/Scanners.pxd +45 -0
  253. Cython/Plex/Scanners.py +328 -0
  254. Cython/Plex/Scanners.pyd +0 -0
  255. Cython/Plex/Transitions.pxd +14 -0
  256. Cython/Plex/Transitions.py +239 -0
  257. Cython/Plex/Transitions.pyd +0 -0
  258. Cython/Plex/__init__.py +34 -0
  259. Cython/Runtime/__init__.py +1 -0
  260. Cython/Runtime/refnanny.pyd +0 -0
  261. Cython/Runtime/refnanny.pyx +237 -0
  262. Cython/Shadow.py +690 -0
  263. Cython/Shadow.pyi +521 -0
  264. Cython/StringIOTree.py +170 -0
  265. Cython/StringIOTree.pyd +0 -0
  266. Cython/Tempita/__init__.py +4 -0
  267. Cython/Tempita/_looper.py +154 -0
  268. Cython/Tempita/_tempita.py +1091 -0
  269. Cython/Tempita/_tempita.pyd +0 -0
  270. Cython/TestUtils.py +422 -0
  271. Cython/Tests/TestCodeWriter.py +128 -0
  272. Cython/Tests/TestCythonUtils.py +202 -0
  273. Cython/Tests/TestJediTyper.py +223 -0
  274. Cython/Tests/TestShadow.py +114 -0
  275. Cython/Tests/TestStringIOTree.py +67 -0
  276. Cython/Tests/TestTestUtils.py +90 -0
  277. Cython/Tests/__init__.py +1 -0
  278. Cython/Tests/xmlrunner.py +390 -0
  279. Cython/Utility/AsyncGen.c +1031 -0
  280. Cython/Utility/Buffer.c +865 -0
  281. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  282. Cython/Utility/Builtins.c +810 -0
  283. Cython/Utility/CConvert.pyx +134 -0
  284. Cython/Utility/CMath.c +104 -0
  285. Cython/Utility/CommonStructures.c +226 -0
  286. Cython/Utility/Complex.c +378 -0
  287. Cython/Utility/Coroutine.c +2300 -0
  288. Cython/Utility/CpdefEnums.pyx +103 -0
  289. Cython/Utility/CppConvert.pyx +282 -0
  290. Cython/Utility/CppSupport.cpp +151 -0
  291. Cython/Utility/CythonFunction.c +1832 -0
  292. Cython/Utility/Dataclasses.c +101 -0
  293. Cython/Utility/Embed.c +121 -0
  294. Cython/Utility/Exceptions.c +1016 -0
  295. Cython/Utility/ExtensionTypes.c +996 -0
  296. Cython/Utility/FunctionArguments.c +1043 -0
  297. Cython/Utility/FusedFunction.pyx +44 -0
  298. Cython/Utility/ImportExport.c +907 -0
  299. Cython/Utility/MemoryView.pxd +188 -0
  300. Cython/Utility/MemoryView.pyx +1482 -0
  301. Cython/Utility/MemoryView_C.c +927 -0
  302. Cython/Utility/ModuleSetupCode.c +3203 -0
  303. Cython/Utility/NumpyImportArray.c +46 -0
  304. Cython/Utility/ObjectHandling.c +3273 -0
  305. Cython/Utility/Optimize.c +1603 -0
  306. Cython/Utility/Overflow.c +384 -0
  307. Cython/Utility/Printing.c +86 -0
  308. Cython/Utility/Profile.c +732 -0
  309. Cython/Utility/StringTools.c +1379 -0
  310. Cython/Utility/Synchronization.c +399 -0
  311. Cython/Utility/TString.c +356 -0
  312. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  313. Cython/Utility/TestCythonScope.pyx +75 -0
  314. Cython/Utility/TestUtilityLoader.c +12 -0
  315. Cython/Utility/TypeConversion.c +1385 -0
  316. Cython/Utility/UFuncs.pyx +50 -0
  317. Cython/Utility/UFuncs_C.c +89 -0
  318. Cython/Utility/__init__.py +28 -0
  319. Cython/Utility/arrayarray.h +167 -0
  320. Cython/Utils.py +687 -0
  321. Cython/Utils.pyd +0 -0
  322. Cython/__init__.py +10 -0
  323. Cython/__init__.pyi +7 -0
  324. Cython/py.typed +0 -0
  325. cython-3.2.0.dist-info/METADATA +85 -0
  326. cython-3.2.0.dist-info/RECORD +333 -0
  327. cython-3.2.0.dist-info/WHEEL +5 -0
  328. cython-3.2.0.dist-info/entry_points.txt +4 -0
  329. cython-3.2.0.dist-info/top_level.txt +3 -0
  330. cython.py +29 -0
  331. pyximport/__init__.py +4 -0
  332. pyximport/pyxbuild.py +160 -0
  333. pyximport/pyximport.py +482 -0
@@ -0,0 +1,560 @@
1
+ """
2
+ =====================
3
+ Cython related magics
4
+ =====================
5
+
6
+ Magic command interface for interactive work with Cython
7
+
8
+ .. note::
9
+
10
+ The ``Cython`` package needs to be installed separately. It
11
+ can be obtained using ``easy_install`` or ``pip``.
12
+
13
+ Usage
14
+ =====
15
+
16
+ To enable the magics below, execute ``%load_ext cython``.
17
+
18
+ ``%%cython``
19
+
20
+ {CYTHON_DOC}
21
+
22
+ ``%%cython_inline``
23
+
24
+ {CYTHON_INLINE_DOC}
25
+
26
+ ``%%cython_pyximport``
27
+
28
+ {CYTHON_PYXIMPORT_DOC}
29
+
30
+ Author:
31
+ * Brian Granger
32
+
33
+ Code moved from IPython and adapted by:
34
+ * Martín Gaitán
35
+
36
+ Parts of this code were taken from Cython.inline.
37
+ """
38
+ #-----------------------------------------------------------------------------
39
+ # Copyright (C) 2010-2011, IPython Development Team.
40
+ #
41
+ # Distributed under the terms of the Modified BSD License.
42
+ #
43
+ # The full license is in the file ipython-COPYING.rst, distributed with this software.
44
+ #-----------------------------------------------------------------------------
45
+
46
+
47
+ import io
48
+ import os
49
+ import re
50
+ import sys
51
+ import time
52
+ import copy
53
+ import distutils.log
54
+ import textwrap
55
+
56
+ IO_ENCODING = sys.getfilesystemencoding()
57
+
58
+ import hashlib
59
+ from distutils.core import Distribution, Extension
60
+ from distutils.command.build_ext import build_ext
61
+
62
+ from IPython.core import display
63
+ from IPython.core import magic_arguments
64
+ from IPython.core.magic import Magics, magics_class, cell_magic
65
+ try:
66
+ from IPython.paths import get_ipython_cache_dir
67
+ except ImportError:
68
+ # older IPython version
69
+ from IPython.utils.path import get_ipython_cache_dir
70
+ from IPython.utils.text import dedent
71
+
72
+ from ..Shadow import __version__ as cython_version
73
+ from ..Compiler.Errors import CompileError
74
+ from .Inline import cython_inline, load_dynamic
75
+ from .Dependencies import cythonize
76
+ from ..Utils import captured_fd, print_captured
77
+
78
+
79
+ PGO_CONFIG = {
80
+ 'gcc': {
81
+ 'gen': ['-fprofile-generate', '-fprofile-dir={TEMPDIR}'],
82
+ 'use': ['-fprofile-use', '-fprofile-correction', '-fprofile-dir={TEMPDIR}'],
83
+ },
84
+ # blind copy from 'configure' script in CPython 3.7
85
+ 'icc': {
86
+ 'gen': ['-prof-gen'],
87
+ 'use': ['-prof-use'],
88
+ }
89
+ }
90
+ PGO_CONFIG['mingw32'] = PGO_CONFIG['gcc']
91
+
92
+
93
+ @magics_class
94
+ class CythonMagics(Magics):
95
+
96
+ def __init__(self, shell):
97
+ super().__init__(shell)
98
+ self._reloads = {}
99
+ self._code_cache = {}
100
+ self._pyximport_installed = False
101
+
102
+ def _import_all(self, module):
103
+ mdict = module.__dict__
104
+ if '__all__' in mdict:
105
+ keys = mdict['__all__']
106
+ else:
107
+ keys = [k for k in mdict if not k.startswith('_')]
108
+
109
+ for k in keys:
110
+ try:
111
+ self.shell.push({k: mdict[k]})
112
+ except KeyError:
113
+ msg = "'module' object has no attribute '%s'" % k
114
+ raise AttributeError(msg)
115
+
116
+ @cell_magic
117
+ def cython_inline(self, line, cell):
118
+ """Compile and run a Cython code cell using Cython.inline.
119
+
120
+ This magic simply passes the body of the cell to Cython.inline
121
+ and returns the result. If the variables `a` and `b` are defined
122
+ in the user's namespace, here is a simple example that returns
123
+ their sum::
124
+
125
+ %%cython_inline
126
+ return a+b
127
+
128
+ For most purposes, we recommend the usage of the `%%cython` magic.
129
+ """
130
+ locs = self.shell.user_global_ns
131
+ globs = self.shell.user_ns
132
+ return cython_inline(cell, locals=locs, globals=globs)
133
+
134
+ @cell_magic
135
+ def cython_pyximport(self, line, cell):
136
+ """Compile and import a Cython code cell using pyximport.
137
+
138
+ The contents of the cell are written to a `.pyx` file in the current
139
+ working directory, which is then imported using `pyximport`. This
140
+ magic requires a module name to be passed::
141
+
142
+ %%cython_pyximport modulename
143
+ def f(x):
144
+ return 2.0*x
145
+
146
+ The compiled module is then imported and all of its symbols are
147
+ injected into the user's namespace. For most purposes, we recommend
148
+ the usage of the `%%cython` magic.
149
+ """
150
+ module_name = line.strip()
151
+ if not module_name:
152
+ raise ValueError('module name must be given')
153
+ fname = module_name + '.pyx'
154
+ with open(fname, 'w', encoding='utf-8') as f:
155
+ f.write(cell)
156
+ if 'pyximport' not in sys.modules or not self._pyximport_installed:
157
+ import pyximport
158
+ pyximport.install()
159
+ self._pyximport_installed = True
160
+ if module_name in self._reloads:
161
+ module = self._reloads[module_name]
162
+ # Note: reloading extension modules is not actually supported
163
+ # (requires PEP-489 reinitialisation support).
164
+ # Don't know why this should ever have worked as it reads here.
165
+ # All we really need to do is to update the globals below.
166
+ #reload(module)
167
+ else:
168
+ __import__(module_name)
169
+ module = sys.modules[module_name]
170
+ self._reloads[module_name] = module
171
+ self._import_all(module)
172
+
173
+ @magic_arguments.magic_arguments()
174
+ @magic_arguments.argument(
175
+ '-a', '--annotate', action='store_const', const='default', dest='annotate',
176
+ help="Produce a colorized HTML version of the source."
177
+ )
178
+ @magic_arguments.argument(
179
+ '--annotate-fullc', action='store_const', const='fullc', dest='annotate',
180
+ help="Produce a colorized HTML version of the source "
181
+ "which includes entire generated C/C++-code."
182
+ )
183
+ @magic_arguments.argument(
184
+ '-+', '--cplus', action='store_true', default=False,
185
+ help="Output a C++ rather than C file."
186
+ )
187
+ @magic_arguments.argument(
188
+ '-3', dest='language_level', action='store_const', const=3, default=None,
189
+ help="Select Python 3 syntax."
190
+ )
191
+ @magic_arguments.argument(
192
+ '-2', dest='language_level', action='store_const', const=2, default=None,
193
+ help="Select Python 2 syntax."
194
+ )
195
+ @magic_arguments.argument(
196
+ '-f', '--force', action='store_true', default=False,
197
+ help="Force the compilation of a new module, even if the source has been "
198
+ "previously compiled."
199
+ )
200
+ @magic_arguments.argument(
201
+ '-c', '--compile-args', action='append', default=[],
202
+ help="Extra flags to pass to compiler via the `extra_compile_args` "
203
+ "Extension flag (can be specified multiple times)."
204
+ )
205
+ @magic_arguments.argument(
206
+ '--link-args', action='append', default=[],
207
+ help="Extra flags to pass to linker via the `extra_link_args` "
208
+ "Extension flag (can be specified multiple times)."
209
+ )
210
+ @magic_arguments.argument(
211
+ '-l', '--lib', action='append', default=[],
212
+ help="Add a library to link the extension against (can be specified "
213
+ "multiple times)."
214
+ )
215
+ @magic_arguments.argument(
216
+ '-n', '--name',
217
+ help="Specify a name for the Cython module."
218
+ )
219
+ @magic_arguments.argument(
220
+ '-L', dest='library_dirs', metavar='dir', action='append', default=[],
221
+ help="Add a path to the list of library directories (can be specified "
222
+ "multiple times)."
223
+ )
224
+ @magic_arguments.argument(
225
+ '-I', '--include', action='append', default=[],
226
+ help="Add a path to the list of include directories (can be specified "
227
+ "multiple times)."
228
+ )
229
+ @magic_arguments.argument(
230
+ '-S', '--src', action='append', default=[],
231
+ help="Add a path to the list of src files (can be specified "
232
+ "multiple times)."
233
+ )
234
+ @magic_arguments.argument(
235
+ '--pgo', dest='pgo', action='store_true', default=False,
236
+ help=("Enable profile guided optimisation in the C compiler. "
237
+ "Compiles the cell twice and executes it in between to generate a runtime profile.")
238
+ )
239
+ @magic_arguments.argument(
240
+ '--verbose', dest='quiet', action='store_false', default=True,
241
+ help=("Print debug information like generated .c/.cpp file location "
242
+ "and exact gcc/g++ command invoked.")
243
+ )
244
+ @cell_magic
245
+ def cython(self, line, cell):
246
+ """Compile and import everything from a Cython code cell.
247
+
248
+ The contents of the cell are written to a `.pyx` file in the
249
+ directory returned by `get_ipython_cache_dir()/cython` using a filename
250
+ with the hash of the code. This file is then cythonized and compiled.
251
+ The resulting module is imported and all of its symbols are injected
252
+ into the user's namespace. The usage is similar to that of
253
+ `%%cython_pyximport` but you don't have to pass a module name::
254
+
255
+ %%cython
256
+ def f(x):
257
+ return 2.0*x
258
+
259
+ To compile OpenMP codes, pass the required `--compile-args`
260
+ and `--link-args`. For example with gcc::
261
+
262
+ %%cython --compile-args=-fopenmp --link-args=-fopenmp
263
+ ...
264
+
265
+ To enable profile guided optimisation, pass the ``--pgo`` option.
266
+ Note that the cell itself needs to take care of establishing a suitable
267
+ profile when executed. This can be done by implementing the functions to
268
+ optimise, and then calling them directly in the same cell on some realistic
269
+ training data like this::
270
+
271
+ %%cython --pgo
272
+ def critical_function(data):
273
+ for item in data:
274
+ ...
275
+
276
+ # execute function several times to build profile
277
+ from somewhere import some_typical_data
278
+ for _ in range(100):
279
+ critical_function(some_typical_data)
280
+
281
+ In Python 3.5 and later, you can distinguish between the profile and
282
+ non-profile runs as follows::
283
+
284
+ if "_pgo_" in __name__:
285
+ ... # execute critical code here
286
+ """
287
+ args = magic_arguments.parse_argstring(self.cython, line)
288
+ code = cell if cell.endswith('\n') else cell + '\n'
289
+ lib_dir = os.path.join(get_ipython_cache_dir(), 'cython')
290
+ key = (code, line, sys.version_info, sys.executable, cython_version)
291
+
292
+ if not os.path.exists(lib_dir):
293
+ os.makedirs(lib_dir)
294
+
295
+ if args.pgo:
296
+ key += ('pgo',)
297
+ if args.force:
298
+ # Force a new module name by adding the current time to the
299
+ # key which is hashed to determine the module name.
300
+ key += (time.time(),)
301
+
302
+ if args.name:
303
+ module_name = str(args.name) # no-op in Py3
304
+ else:
305
+ module_name = "_cython_magic_" + hashlib.sha256(str(key).encode('utf-8')).hexdigest()
306
+ html_file = os.path.join(lib_dir, module_name + '.html')
307
+ module_path = os.path.join(lib_dir, module_name + self.so_ext)
308
+
309
+ have_module = os.path.isfile(module_path)
310
+ need_cythonize = args.pgo or not have_module
311
+
312
+ if args.annotate:
313
+ if not os.path.isfile(html_file):
314
+ need_cythonize = True
315
+
316
+ extension = None
317
+ if need_cythonize:
318
+ extensions = self._cythonize(module_name, code, lib_dir, args, quiet=args.quiet)
319
+ if extensions is None:
320
+ # Compilation failed and printed error message
321
+ return None
322
+ assert len(extensions) == 1
323
+ extension = extensions[0]
324
+ self._code_cache[key] = module_name
325
+
326
+ if args.pgo:
327
+ self._profile_pgo_wrapper(extension, lib_dir)
328
+
329
+ def print_compiler_output(stdout, stderr, where):
330
+ # On windows, errors are printed to stdout, we redirect both to sys.stderr.
331
+ print_captured(stdout, where, "Content of stdout:\n")
332
+ print_captured(stderr, where, "Content of stderr:\n")
333
+
334
+ get_stderr = get_stdout = None
335
+ try:
336
+ with captured_fd(1) as get_stdout:
337
+ with captured_fd(2) as get_stderr:
338
+ self._build_extension(
339
+ extension, lib_dir, pgo_step_name='use' if args.pgo else None, quiet=args.quiet)
340
+ except (distutils.errors.CompileError, distutils.errors.LinkError):
341
+ # Build failed, print error message from compiler/linker
342
+ print_compiler_output(get_stdout(), get_stderr(), sys.stderr)
343
+ return None
344
+
345
+ # Build seems ok, but we might still want to show any warnings that occurred
346
+ print_compiler_output(get_stdout(), get_stderr(), sys.stdout)
347
+
348
+ module = load_dynamic(module_name, module_path)
349
+ self._import_all(module)
350
+
351
+ if args.annotate:
352
+ try:
353
+ with open(html_file, encoding='utf-8') as f:
354
+ annotated_html = f.read()
355
+ except OSError as e:
356
+ # File could not be opened. Most likely the user has a version
357
+ # of Cython before 0.15.1 (when `cythonize` learned the
358
+ # `force` keyword argument) and has already compiled this
359
+ # exact source without annotation.
360
+ print('Cython completed successfully but the annotated '
361
+ 'source could not be read.', file=sys.stderr)
362
+ print(e, file=sys.stderr)
363
+ else:
364
+ return display.HTML(self.clean_annotated_html(annotated_html))
365
+
366
+ def _profile_pgo_wrapper(self, extension, lib_dir):
367
+ """
368
+ Generate a .c file for a separate extension module that calls the
369
+ module init function of the original module. This makes sure that the
370
+ PGO profiler sees the correct .o file of the final module, but it still
371
+ allows us to import the module under a different name for profiling,
372
+ before recompiling it into the PGO optimised module. Overwriting and
373
+ reimporting the same shared library is not portable.
374
+ """
375
+ extension = copy.copy(extension) # shallow copy, do not modify sources in place!
376
+ module_name = extension.name
377
+ pgo_module_name = '_pgo_' + module_name
378
+ pgo_wrapper_c_file = os.path.join(lib_dir, pgo_module_name + '.c')
379
+ with open(pgo_wrapper_c_file, 'w', encoding='utf-8') as f:
380
+ f.write(textwrap.dedent("""
381
+ #include "Python.h"
382
+ extern PyMODINIT_FUNC PyInit_%(module_name)s(void);
383
+ PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void); /*proto*/
384
+ PyMODINIT_FUNC PyInit_%(pgo_module_name)s(void) {
385
+ return PyInit_%(module_name)s();
386
+ }
387
+ """ % {'module_name': module_name, 'pgo_module_name': pgo_module_name}))
388
+
389
+ extension.sources = extension.sources + [pgo_wrapper_c_file] # do not modify in place!
390
+ extension.name = pgo_module_name
391
+
392
+ self._build_extension(extension, lib_dir, pgo_step_name='gen')
393
+
394
+ # import and execute module code to generate profile
395
+ so_module_path = os.path.join(lib_dir, pgo_module_name + self.so_ext)
396
+ load_dynamic(pgo_module_name, so_module_path)
397
+
398
+ def _cythonize(self, module_name, code, lib_dir, args, quiet=True):
399
+ pyx_file = os.path.join(lib_dir, module_name + '.pyx')
400
+
401
+ c_include_dirs = args.include
402
+ c_src_files = list(map(str, args.src))
403
+ if 'numpy' in code:
404
+ import numpy
405
+ c_include_dirs.append(numpy.get_include())
406
+ with open(pyx_file, 'w', encoding='utf-8') as f:
407
+ f.write(code)
408
+ extension = Extension(
409
+ name=module_name,
410
+ sources=[pyx_file] + c_src_files,
411
+ include_dirs=c_include_dirs,
412
+ library_dirs=args.library_dirs,
413
+ extra_compile_args=args.compile_args,
414
+ extra_link_args=args.link_args,
415
+ libraries=args.lib,
416
+ language='c++' if args.cplus else 'c',
417
+ )
418
+ try:
419
+ opts = dict(
420
+ quiet=quiet,
421
+ annotate=args.annotate,
422
+ force=True,
423
+ language_level=min(3, sys.version_info[0]),
424
+ )
425
+ if args.language_level is not None:
426
+ assert args.language_level in (2, 3)
427
+ opts['language_level'] = args.language_level
428
+ return cythonize([extension], **opts)
429
+ except CompileError:
430
+ return None
431
+
432
+ def _build_extension(self, extension, lib_dir, temp_dir=None, pgo_step_name=None, quiet=True):
433
+ build_extension = self._get_build_extension(
434
+ extension, lib_dir=lib_dir, temp_dir=temp_dir, pgo_step_name=pgo_step_name)
435
+ old_threshold = None
436
+ try:
437
+ if not quiet:
438
+ old_threshold = distutils.log.set_threshold(distutils.log.DEBUG)
439
+ build_extension.run()
440
+ finally:
441
+ if not quiet and old_threshold is not None:
442
+ distutils.log.set_threshold(old_threshold)
443
+
444
+ def _add_pgo_flags(self, build_extension, step_name, temp_dir):
445
+ compiler_type = build_extension.compiler.compiler_type
446
+ if compiler_type == 'unix':
447
+ compiler_cmd = build_extension.compiler.compiler_so
448
+ # TODO: we could try to call "[cmd] --version" for better insights
449
+ if not compiler_cmd:
450
+ pass
451
+ elif 'clang' in compiler_cmd or 'clang' in compiler_cmd[0]:
452
+ compiler_type = 'clang'
453
+ elif 'icc' in compiler_cmd or 'icc' in compiler_cmd[0]:
454
+ compiler_type = 'icc'
455
+ elif 'gcc' in compiler_cmd or 'gcc' in compiler_cmd[0]:
456
+ compiler_type = 'gcc'
457
+ elif 'g++' in compiler_cmd or 'g++' in compiler_cmd[0]:
458
+ compiler_type = 'gcc'
459
+ config = PGO_CONFIG.get(compiler_type)
460
+ orig_flags = []
461
+ if config and step_name in config:
462
+ flags = [f.format(TEMPDIR=temp_dir) for f in config[step_name]]
463
+ for extension in build_extension.extensions:
464
+ orig_flags.append((extension.extra_compile_args, extension.extra_link_args))
465
+ extension.extra_compile_args = extension.extra_compile_args + flags
466
+ extension.extra_link_args = extension.extra_link_args + flags
467
+ else:
468
+ print("No PGO %s configuration known for C compiler type '%s'" % (step_name, compiler_type),
469
+ file=sys.stderr)
470
+ return orig_flags
471
+
472
+ @property
473
+ def so_ext(self):
474
+ """The extension suffix for compiled modules."""
475
+ try:
476
+ return self._so_ext
477
+ except AttributeError:
478
+ self._so_ext = self._get_build_extension().get_ext_filename('')
479
+ return self._so_ext
480
+
481
+ def _clear_distutils_mkpath_cache(self):
482
+ """clear distutils mkpath cache
483
+
484
+ prevents distutils from skipping re-creation of dirs that have been removed
485
+ """
486
+ try:
487
+ from distutils.dir_util import _path_created
488
+ except ImportError:
489
+ pass
490
+ else:
491
+ _path_created.clear()
492
+
493
+ def _get_build_extension(self, extension=None, lib_dir=None, temp_dir=None,
494
+ pgo_step_name=None, _build_ext=build_ext):
495
+ self._clear_distutils_mkpath_cache()
496
+ dist = Distribution()
497
+ config_files = dist.find_config_files()
498
+ try:
499
+ config_files.remove('setup.cfg')
500
+ except ValueError:
501
+ pass
502
+ dist.parse_config_files(config_files)
503
+
504
+ if not temp_dir:
505
+ temp_dir = lib_dir
506
+ add_pgo_flags = self._add_pgo_flags
507
+
508
+ if pgo_step_name:
509
+ base_build_ext = _build_ext
510
+ class _build_ext(_build_ext):
511
+ def build_extensions(self):
512
+ add_pgo_flags(self, pgo_step_name, temp_dir)
513
+ base_build_ext.build_extensions(self)
514
+
515
+ build_extension = _build_ext(dist)
516
+ build_extension.finalize_options()
517
+ if temp_dir:
518
+ build_extension.build_temp = temp_dir
519
+ if lib_dir:
520
+ build_extension.build_lib = lib_dir
521
+ if extension is not None:
522
+ build_extension.extensions = [extension]
523
+ return build_extension
524
+
525
+ @staticmethod
526
+ def clean_annotated_html(html, include_style=True):
527
+ """Clean up the annotated HTML source.
528
+
529
+ Strips the link to the generated C or C++ file, which we do not
530
+ present to the user.
531
+
532
+ Returns an HTML snippet (no <html>, <head>, or <body>),
533
+ containing only the style tag(s) and _contents_ of the body,
534
+ appropriate for embedding multiple times in cell output.
535
+ """
536
+ # extract CSS and body, rather than full HTML document
537
+ chunks = []
538
+ if include_style:
539
+ styles = re.findall("<style.*</style>", html, re.MULTILINE | re.DOTALL)
540
+ chunks.extend(styles)
541
+ # extract body
542
+ body = re.search(
543
+ r"<body[^>]*>(.+)</body>", html, re.MULTILINE | re.DOTALL
544
+ ).group(1)
545
+
546
+ # exclude link to generated file
547
+ r = re.compile('<p>Raw output: <a href="(.*)">(.*)</a>')
548
+ for line in body.splitlines():
549
+ if not r.match(line):
550
+ chunks.append(line)
551
+ return "\n".join(chunks)
552
+
553
+ __doc__ = __doc__.format(
554
+ # rST doesn't see the -+ flag as part of an option list, so we
555
+ # hide it from the module-level docstring.
556
+ CYTHON_DOC=dedent(CythonMagics.cython.__doc__
557
+ .replace('-+, --cplus', '--cplus ')),
558
+ CYTHON_INLINE_DOC=dedent(CythonMagics.cython_inline.__doc__),
559
+ CYTHON_PYXIMPORT_DOC=dedent(CythonMagics.cython_pyximport.__doc__),
560
+ )
@@ -0,0 +1,94 @@
1
+ import os
2
+ import re
3
+ import shutil
4
+ import tempfile
5
+
6
+ from Cython.Compiler import (
7
+ MemoryView, Code, Options, Pipeline, Errors, Main, Symtab
8
+ )
9
+ from Cython.Compiler.StringEncoding import EncodedString
10
+ from Cython.Compiler.Scanning import FileSourceDescriptor
11
+
12
+
13
+ def create_shared_library_pipeline(context, scope, options, result):
14
+
15
+ parse = Pipeline.parse_stage_factory(context)
16
+
17
+ def generate_tree_factory(context):
18
+ def generate_tree(compsrc):
19
+ tree = parse(compsrc)
20
+
21
+ tree.scope.use_utility_code(
22
+ MemoryView.get_view_utility_code(options.shared_utility_qualified_name))
23
+
24
+ tree.scope.use_utility_code(MemoryView._get_memviewslice_declare_code())
25
+ tree.scope.use_utility_code(MemoryView._get_typeinfo_to_format_code())
26
+ context.include_directories.append(Code.get_utility_dir())
27
+ return tree
28
+
29
+ return generate_tree
30
+
31
+ def generate_c_utilities(module_node):
32
+ UtilityCode = Code.UtilityCode
33
+ match_special = UtilityCode.get_special_comment_matcher('/')
34
+ for c_utility_file in os.listdir(Code.get_utility_dir()):
35
+ if not c_utility_file.endswith('.c'):
36
+ continue
37
+ for line in Code.read_utilities_hook(c_utility_file):
38
+ if not ((m := match_special(line)) and (name := m.group('name'))):
39
+ continue
40
+ if not (section_title := UtilityCode.match_section_title(name)):
41
+ continue
42
+ name, section_type = section_title.groups()
43
+ if section_type == 'export':
44
+ module_node.scope.use_utility_code(UtilityCode.load_cached(name, c_utility_file))
45
+ return module_node
46
+
47
+ orig_cimport_from_pyx = Options.cimport_from_pyx
48
+
49
+ def set_cimport_from_pyx(cimport_from_pyx):
50
+ def inner(node):
51
+ Options.cimport_from_pyx = cimport_from_pyx
52
+ return node
53
+ return inner
54
+
55
+ return [
56
+ # "cimport_from_pyx=True" to force generating __Pyx_ExportFunction
57
+ set_cimport_from_pyx(True),
58
+ generate_tree_factory(context),
59
+ *Pipeline.create_pipeline(context, 'pyx', exclude_classes=()),
60
+ generate_c_utilities,
61
+ Pipeline.inject_pxd_code_stage_factory(context),
62
+ Pipeline.inject_utility_code_stage_factory(context, internalise_c_class_entries=False),
63
+ Pipeline.inject_utility_pxd_code_stage_factory(context),
64
+ Pipeline.abort_on_errors,
65
+ Pipeline.generate_pyx_code_stage_factory(options, result),
66
+ set_cimport_from_pyx(orig_cimport_from_pyx),
67
+ ]
68
+
69
+
70
+ def generate_shared_module(options):
71
+ Errors.init_thread()
72
+ Errors.open_listing_file(None)
73
+
74
+ dest_c_file = options.shared_c_file_path
75
+ module_name = os.path.splitext(os.path.basename(dest_c_file))[0]
76
+
77
+ context = Main.Context.from_options(options)
78
+ scope = Symtab.ModuleScope('MemoryView', parent_module = None, context = context, is_package=False)
79
+
80
+ with tempfile.TemporaryDirectory() as tmpdirname:
81
+ pyx_file = os.path.join(tmpdirname, f'{module_name}.pyx')
82
+ c_file = os.path.join(tmpdirname, f'{module_name}.c')
83
+ with open(pyx_file, 'w'):
84
+ pass
85
+ source_desc = FileSourceDescriptor(pyx_file)
86
+ comp_src = Main.CompilationSource(source_desc, EncodedString(module_name), os.getcwd())
87
+ result = Main.create_default_resultobj(comp_src, options)
88
+
89
+ pipeline = create_shared_library_pipeline(context, scope, options, result)
90
+ err, enddata = Pipeline.run_pipeline(pipeline, comp_src)
91
+ if err is None:
92
+ shutil.copy(c_file, dest_c_file)
93
+
94
+ return err, enddata