Cython 3.3.0__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. Cython/Build/BuildExecutable.py +156 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +349 -0
  4. Cython/Build/Dependencies.py +1281 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +467 -0
  7. Cython/Build/IpythonMagic.py +559 -0
  8. Cython/Build/SharedModule.py +165 -0
  9. Cython/Build/Tests/TestCyCache.py +195 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +480 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +303 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +825 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +679 -0
  23. Cython/Compiler/Builtin.py +1102 -0
  24. Cython/Compiler/CmdLine.py +373 -0
  25. Cython/Compiler/Code.cp315-win_amd64.pyd +0 -0
  26. Cython/Compiler/Code.pxd +154 -0
  27. Cython/Compiler/Code.py +3760 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +208 -0
  30. Cython/Compiler/Dataclass.py +890 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +310 -0
  33. Cython/Compiler/ExprNodes.py +16273 -0
  34. Cython/Compiler/FlowControl.cp315-win_amd64.pyd +0 -0
  35. Cython/Compiler/FlowControl.pxd +112 -0
  36. Cython/Compiler/FlowControl.py +1573 -0
  37. Cython/Compiler/FusedNode.cp315-win_amd64.pyd +0 -0
  38. Cython/Compiler/FusedNode.py +978 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +422 -0
  42. Cython/Compiler/LineTable.cp315-win_amd64.pyd +0 -0
  43. Cython/Compiler/LineTable.py +114 -0
  44. Cython/Compiler/Main.py +856 -0
  45. Cython/Compiler/MatchCaseNodes.py +2200 -0
  46. Cython/Compiler/MemoryView.py +930 -0
  47. Cython/Compiler/ModuleNode.py +4548 -0
  48. Cython/Compiler/Naming.py +370 -0
  49. Cython/Compiler/Nodes.py +11304 -0
  50. Cython/Compiler/Optimize.py +5564 -0
  51. Cython/Compiler/Options.py +840 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +80 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4808 -0
  54. Cython/Compiler/Parsing.cp315-win_amd64.pyd +0 -0
  55. Cython/Compiler/Parsing.pxd +9 -0
  56. Cython/Compiler/Parsing.py +4809 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +6588 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.cp315-win_amd64.pyd +0 -0
  61. Cython/Compiler/Scanning.pxd +70 -0
  62. Cython/Compiler/Scanning.py +720 -0
  63. Cython/Compiler/StringEncoding.cp315-win_amd64.pyd +0 -0
  64. Cython/Compiler/StringEncoding.py +354 -0
  65. Cython/Compiler/Symtab.py +3121 -0
  66. Cython/Compiler/Tests/TestBuffer.py +105 -0
  67. Cython/Compiler/Tests/TestBuiltin.py +196 -0
  68. Cython/Compiler/Tests/TestCmdLine.py +652 -0
  69. Cython/Compiler/Tests/TestCode.py +145 -0
  70. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  71. Cython/Compiler/Tests/TestGrammar.py +202 -0
  72. Cython/Compiler/Tests/TestMemView.py +71 -0
  73. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  74. Cython/Compiler/Tests/TestScanning.py +132 -0
  75. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  76. Cython/Compiler/Tests/TestStringEncoding.py +20 -0
  77. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  78. Cython/Compiler/Tests/TestTreePath.py +103 -0
  79. Cython/Compiler/Tests/TestTypes.py +119 -0
  80. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  81. Cython/Compiler/Tests/TestVisitor.py +119 -0
  82. Cython/Compiler/Tests/Utils.py +36 -0
  83. Cython/Compiler/Tests/__init__.py +1 -0
  84. Cython/Compiler/TreeFragment.py +279 -0
  85. Cython/Compiler/TreePath.py +303 -0
  86. Cython/Compiler/TypeInference.py +611 -0
  87. Cython/Compiler/TypeSlots.py +1329 -0
  88. Cython/Compiler/UFuncs.py +317 -0
  89. Cython/Compiler/UtilNodes.py +389 -0
  90. Cython/Compiler/UtilityCode.py +354 -0
  91. Cython/Compiler/Version.py +8 -0
  92. Cython/Compiler/Visitor.cp315-win_amd64.pyd +0 -0
  93. Cython/Compiler/Visitor.pxd +52 -0
  94. Cython/Compiler/Visitor.py +914 -0
  95. Cython/Compiler/__init__.py +1 -0
  96. Cython/Coverage.py +448 -0
  97. Cython/Debugger/Cygdb.py +214 -0
  98. Cython/Debugger/DebugWriter.py +82 -0
  99. Cython/Debugger/Tests/TestLibCython.py +280 -0
  100. Cython/Debugger/Tests/__init__.py +1 -0
  101. Cython/Debugger/Tests/cfuncs.c +8 -0
  102. Cython/Debugger/Tests/codefile +49 -0
  103. Cython/Debugger/Tests/test_libcython_in_gdb.py +580 -0
  104. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  105. Cython/Debugger/__init__.py +1 -0
  106. Cython/Debugger/libcython.py +1548 -0
  107. Cython/Debugger/libpython.py +2821 -0
  108. Cython/Debugging.py +20 -0
  109. Cython/Distutils/__init__.py +2 -0
  110. Cython/Distutils/build_ext.py +143 -0
  111. Cython/Distutils/extension.py +96 -0
  112. Cython/Distutils/old_build_ext.py +351 -0
  113. Cython/Includes/cpython/__init__.pxd +173 -0
  114. Cython/Includes/cpython/array.pxd +152 -0
  115. Cython/Includes/cpython/bool.pxd +37 -0
  116. Cython/Includes/cpython/buffer.pxd +112 -0
  117. Cython/Includes/cpython/bytearray.pxd +33 -0
  118. Cython/Includes/cpython/bytes.pxd +200 -0
  119. Cython/Includes/cpython/cellobject.pxd +35 -0
  120. Cython/Includes/cpython/ceval.pxd +8 -0
  121. Cython/Includes/cpython/codecs.pxd +121 -0
  122. Cython/Includes/cpython/complex.pxd +60 -0
  123. Cython/Includes/cpython/contextvars.pxd +145 -0
  124. Cython/Includes/cpython/conversion.pxd +36 -0
  125. Cython/Includes/cpython/datetime.pxd +395 -0
  126. Cython/Includes/cpython/descr.pxd +26 -0
  127. Cython/Includes/cpython/dict.pxd +268 -0
  128. Cython/Includes/cpython/exc.pxd +263 -0
  129. Cython/Includes/cpython/fileobject.pxd +57 -0
  130. Cython/Includes/cpython/float.pxd +56 -0
  131. Cython/Includes/cpython/frozendict.pxd +37 -0
  132. Cython/Includes/cpython/function.pxd +65 -0
  133. Cython/Includes/cpython/genobject.pxd +25 -0
  134. Cython/Includes/cpython/getargs.pxd +12 -0
  135. Cython/Includes/cpython/instance.pxd +25 -0
  136. Cython/Includes/cpython/iterator.pxd +36 -0
  137. Cython/Includes/cpython/iterobject.pxd +24 -0
  138. Cython/Includes/cpython/list.pxd +144 -0
  139. Cython/Includes/cpython/long.pxd +180 -0
  140. Cython/Includes/cpython/longintrepr.pxd +14 -0
  141. Cython/Includes/cpython/mapping.pxd +63 -0
  142. Cython/Includes/cpython/marshal.pxd +66 -0
  143. Cython/Includes/cpython/mem.pxd +120 -0
  144. Cython/Includes/cpython/memoryview.pxd +50 -0
  145. Cython/Includes/cpython/method.pxd +49 -0
  146. Cython/Includes/cpython/module.pxd +208 -0
  147. Cython/Includes/cpython/number.pxd +258 -0
  148. Cython/Includes/cpython/object.pxd +430 -0
  149. Cython/Includes/cpython/pycapsule.pxd +143 -0
  150. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  151. Cython/Includes/cpython/pyport.pxd +8 -0
  152. Cython/Includes/cpython/pystate.pxd +95 -0
  153. Cython/Includes/cpython/pythread.pxd +53 -0
  154. Cython/Includes/cpython/ref.pxd +141 -0
  155. Cython/Includes/cpython/sentinel.pxd +17 -0
  156. Cython/Includes/cpython/sequence.pxd +134 -0
  157. Cython/Includes/cpython/set.pxd +119 -0
  158. Cython/Includes/cpython/slice.pxd +70 -0
  159. Cython/Includes/cpython/time.pxd +129 -0
  160. Cython/Includes/cpython/tuple.pxd +72 -0
  161. Cython/Includes/cpython/type.pxd +146 -0
  162. Cython/Includes/cpython/unicode.pxd +639 -0
  163. Cython/Includes/cpython/version.pxd +32 -0
  164. Cython/Includes/cpython/weakref.pxd +78 -0
  165. Cython/Includes/libc/__init__.pxd +1 -0
  166. Cython/Includes/libc/complex.pxd +35 -0
  167. Cython/Includes/libc/errno.pxd +127 -0
  168. Cython/Includes/libc/float.pxd +43 -0
  169. Cython/Includes/libc/limits.pxd +28 -0
  170. Cython/Includes/libc/locale.pxd +46 -0
  171. Cython/Includes/libc/math.pxd +209 -0
  172. Cython/Includes/libc/setjmp.pxd +10 -0
  173. Cython/Includes/libc/signal.pxd +64 -0
  174. Cython/Includes/libc/stddef.pxd +9 -0
  175. Cython/Includes/libc/stdint.pxd +105 -0
  176. Cython/Includes/libc/stdio.pxd +80 -0
  177. Cython/Includes/libc/stdlib.pxd +72 -0
  178. Cython/Includes/libc/string.pxd +50 -0
  179. Cython/Includes/libc/threads.pxd +234 -0
  180. Cython/Includes/libc/time.pxd +52 -0
  181. Cython/Includes/libcpp/__init__.pxd +4 -0
  182. Cython/Includes/libcpp/algorithm.pxd +320 -0
  183. Cython/Includes/libcpp/any.pxd +16 -0
  184. Cython/Includes/libcpp/atomic.pxd +59 -0
  185. Cython/Includes/libcpp/barrier.pxd +22 -0
  186. Cython/Includes/libcpp/bit.pxd +29 -0
  187. Cython/Includes/libcpp/cast.pxd +12 -0
  188. Cython/Includes/libcpp/cmath.pxd +518 -0
  189. Cython/Includes/libcpp/complex.pxd +106 -0
  190. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  191. Cython/Includes/libcpp/deque.pxd +165 -0
  192. Cython/Includes/libcpp/exception.pxd +216 -0
  193. Cython/Includes/libcpp/execution.pxd +15 -0
  194. Cython/Includes/libcpp/forward_list.pxd +63 -0
  195. Cython/Includes/libcpp/functional.pxd +26 -0
  196. Cython/Includes/libcpp/future.pxd +103 -0
  197. Cython/Includes/libcpp/iterator.pxd +34 -0
  198. Cython/Includes/libcpp/latch.pxd +17 -0
  199. Cython/Includes/libcpp/limits.pxd +61 -0
  200. Cython/Includes/libcpp/list.pxd +117 -0
  201. Cython/Includes/libcpp/map.pxd +252 -0
  202. Cython/Includes/libcpp/memory.pxd +115 -0
  203. Cython/Includes/libcpp/mutex.pxd +387 -0
  204. Cython/Includes/libcpp/numbers.pxd +15 -0
  205. Cython/Includes/libcpp/numeric.pxd +131 -0
  206. Cython/Includes/libcpp/optional.pxd +34 -0
  207. Cython/Includes/libcpp/pair.pxd +1 -0
  208. Cython/Includes/libcpp/queue.pxd +25 -0
  209. Cython/Includes/libcpp/random.pxd +166 -0
  210. Cython/Includes/libcpp/semaphore.pxd +43 -0
  211. Cython/Includes/libcpp/set.pxd +228 -0
  212. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  213. Cython/Includes/libcpp/span.pxd +87 -0
  214. Cython/Includes/libcpp/stack.pxd +11 -0
  215. Cython/Includes/libcpp/stop_token.pxd +117 -0
  216. Cython/Includes/libcpp/string.pxd +355 -0
  217. Cython/Includes/libcpp/string_view.pxd +183 -0
  218. Cython/Includes/libcpp/typeindex.pxd +15 -0
  219. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  220. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  221. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  222. Cython/Includes/libcpp/utility.pxd +30 -0
  223. Cython/Includes/libcpp/vector.pxd +186 -0
  224. Cython/Includes/numpy/math.pxd +150 -0
  225. Cython/Includes/openmp.pxd +50 -0
  226. Cython/Includes/posix/__init__.pxd +1 -0
  227. Cython/Includes/posix/dlfcn.pxd +14 -0
  228. Cython/Includes/posix/fcntl.pxd +86 -0
  229. Cython/Includes/posix/ioctl.pxd +4 -0
  230. Cython/Includes/posix/mman.pxd +101 -0
  231. Cython/Includes/posix/resource.pxd +57 -0
  232. Cython/Includes/posix/select.pxd +21 -0
  233. Cython/Includes/posix/signal.pxd +73 -0
  234. Cython/Includes/posix/stat.pxd +98 -0
  235. Cython/Includes/posix/stdio.pxd +37 -0
  236. Cython/Includes/posix/stdlib.pxd +29 -0
  237. Cython/Includes/posix/strings.pxd +9 -0
  238. Cython/Includes/posix/time.pxd +71 -0
  239. Cython/Includes/posix/types.pxd +30 -0
  240. Cython/Includes/posix/uio.pxd +26 -0
  241. Cython/Includes/posix/unistd.pxd +271 -0
  242. Cython/Includes/posix/wait.pxd +38 -0
  243. Cython/LZSS.cp315-win_amd64.pyd +0 -0
  244. Cython/LZSS.py +184 -0
  245. Cython/Plex/Actions.cp315-win_amd64.pyd +0 -0
  246. Cython/Plex/Actions.pxd +24 -0
  247. Cython/Plex/Actions.py +119 -0
  248. Cython/Plex/DFA.cp315-win_amd64.pyd +0 -0
  249. Cython/Plex/DFA.pxd +14 -0
  250. Cython/Plex/DFA.py +164 -0
  251. Cython/Plex/Errors.py +48 -0
  252. Cython/Plex/Lexicons.py +178 -0
  253. Cython/Plex/Machines.cp315-win_amd64.pyd +0 -0
  254. Cython/Plex/Machines.pxd +36 -0
  255. Cython/Plex/Machines.py +238 -0
  256. Cython/Plex/Regexps.py +535 -0
  257. Cython/Plex/Scanners.cp315-win_amd64.pyd +0 -0
  258. Cython/Plex/Scanners.pxd +45 -0
  259. Cython/Plex/Scanners.py +328 -0
  260. Cython/Plex/Transitions.cp315-win_amd64.pyd +0 -0
  261. Cython/Plex/Transitions.pxd +14 -0
  262. Cython/Plex/Transitions.py +239 -0
  263. Cython/Plex/__init__.py +34 -0
  264. Cython/Runtime/__init__.py +1 -0
  265. Cython/Runtime/refnanny.cp315-win_amd64.pyd +0 -0
  266. Cython/Runtime/refnanny.pyx +237 -0
  267. Cython/Shadow.py +1174 -0
  268. Cython/StringIOTree.cp315-win_amd64.pyd +0 -0
  269. Cython/StringIOTree.py +169 -0
  270. Cython/Tempita/__init__.py +4 -0
  271. Cython/Tempita/_looper.py +154 -0
  272. Cython/Tempita/_tempita.cp315-win_amd64.pyd +0 -0
  273. Cython/Tempita/_tempita.py +1087 -0
  274. Cython/TestUtils.py +472 -0
  275. Cython/Tests/TestCodeWriter.py +128 -0
  276. Cython/Tests/TestCythonUtils.py +202 -0
  277. Cython/Tests/TestJediTyper.py +223 -0
  278. Cython/Tests/TestShadow.py +125 -0
  279. Cython/Tests/TestStringIOTree.py +68 -0
  280. Cython/Tests/TestTestUtils.py +89 -0
  281. Cython/Tests/__init__.py +1 -0
  282. Cython/Tests/xmlrunner.py +390 -0
  283. Cython/Utility/AsyncGen.c +1152 -0
  284. Cython/Utility/Buffer.c +866 -0
  285. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  286. Cython/Utility/Builtins.c +1068 -0
  287. Cython/Utility/CConvert.pyx +153 -0
  288. Cython/Utility/CMath.c +104 -0
  289. Cython/Utility/CommonStructures.c +244 -0
  290. Cython/Utility/Complex.c +378 -0
  291. Cython/Utility/Coroutine.c +2344 -0
  292. Cython/Utility/CpdefEnums.pyx +119 -0
  293. Cython/Utility/CppConvert.pyx +282 -0
  294. Cython/Utility/CppSupport.cpp +151 -0
  295. Cython/Utility/CythonFunction.c +2185 -0
  296. Cython/Utility/Dataclasses.c +101 -0
  297. Cython/Utility/Embed.c +129 -0
  298. Cython/Utility/Exceptions.c +1331 -0
  299. Cython/Utility/Exceptions_Cy.pyx +109 -0
  300. Cython/Utility/ExtensionTypes.c +1199 -0
  301. Cython/Utility/FunctionArguments.c +1052 -0
  302. Cython/Utility/FusedFunction.pyx +44 -0
  303. Cython/Utility/ImportExport.c +972 -0
  304. Cython/Utility/MatchCase.c +981 -0
  305. Cython/Utility/MatchCase_Cy.pyx +12 -0
  306. Cython/Utility/MemoryView.pxd +108 -0
  307. Cython/Utility/MemoryView.pyx +1499 -0
  308. Cython/Utility/MemoryView_C.c +1056 -0
  309. Cython/Utility/ModuleSetupCode.c +3319 -0
  310. Cython/Utility/NumpyImportArray.c +46 -0
  311. Cython/Utility/ObjectHandling.c +3404 -0
  312. Cython/Utility/Optimize.c +2564 -0
  313. Cython/Utility/Overflow.c +378 -0
  314. Cython/Utility/Profile.c +736 -0
  315. Cython/Utility/StringTools.c +1534 -0
  316. Cython/Utility/Synchronization.c +438 -0
  317. Cython/Utility/TString.c +369 -0
  318. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  319. Cython/Utility/TestCythonScope.pyx +75 -0
  320. Cython/Utility/TestUtilityLoader.c +12 -0
  321. Cython/Utility/TypeConversion.c +1588 -0
  322. Cython/Utility/UFuncs.pyx +50 -0
  323. Cython/Utility/UFuncs_C.c +89 -0
  324. Cython/Utility/__init__.py +28 -0
  325. Cython/Utility/arrayarray.h +172 -0
  326. Cython/Utils.cp315-win_amd64.pyd +0 -0
  327. Cython/Utils.py +680 -0
  328. Cython/__init__.py +12 -0
  329. Cython/_shared.cp315-win_amd64.pyd +0 -0
  330. Cython/py.typed +0 -0
  331. cython-3.3.0.dist-info/METADATA +555 -0
  332. cython-3.3.0.dist-info/RECORD +339 -0
  333. cython-3.3.0.dist-info/WHEEL +5 -0
  334. cython-3.3.0.dist-info/entry_points.txt +4 -0
  335. cython-3.3.0.dist-info/top_level.txt +3 -0
  336. cython.py +29 -0
  337. pyximport/__init__.py +4 -0
  338. pyximport/pyxbuild.py +160 -0
  339. pyximport/pyximport.py +482 -0
@@ -0,0 +1,1281 @@
1
+ import cython
2
+
3
+ import collections
4
+ import os
5
+ import re, sys, time
6
+ from glob import iglob
7
+ from io import StringIO
8
+ from os.path import relpath as _relpath
9
+ from .Cache import Cache, FingerprintFlags
10
+
11
+ from collections.abc import Iterable
12
+
13
+ try:
14
+ import pythran
15
+ except Exception:
16
+ pythran = None
17
+
18
+ from .. import Utils
19
+ from ..Utils import (cached_function, cached_method, path_exists,
20
+ safe_makedirs, copy_file_to_dir_if_newer, is_package_dir, write_depfile)
21
+ from ..Compiler import Errors
22
+ from ..Compiler.Main import Context
23
+ from ..Compiler import Options
24
+ from ..Compiler.Options import (CompilationOptions, default_options,
25
+ get_directive_defaults)
26
+
27
+ join_path = cached_function(os.path.join)
28
+ copy_once_if_newer = cached_function(copy_file_to_dir_if_newer)
29
+ safe_makedirs_once = cached_function(safe_makedirs)
30
+
31
+
32
+ @cython.cfunc
33
+ def _make_relative(file_paths, base=None) -> list[str]:
34
+ if not base:
35
+ base = os.getcwd()
36
+ if base[-1] != os.path.sep:
37
+ base += os.path.sep
38
+ return [_relpath(path, base) if path.startswith(base) else path
39
+ for path in file_paths]
40
+
41
+
42
+ def extended_iglob(pattern):
43
+ if '{' in pattern:
44
+ m = re.match('(.*){([^}]+)}(.*)', pattern)
45
+ if m:
46
+ before, switch, after = m.groups()
47
+ for case in switch.split(','):
48
+ for path in extended_iglob(before + case + after):
49
+ yield path
50
+ return
51
+
52
+ # We always accept '/' and also '\' on Windows,
53
+ # because '/' is generally common for relative paths.
54
+ if '**/' in pattern or os.sep == '\\' and '**\\' in pattern:
55
+ seen = set()
56
+ first, rest = re.split(r'\*\*[%s]' % ('/\\\\' if os.sep == '\\' else '/'), pattern, maxsplit=1)
57
+ if first:
58
+ first = iglob(first + os.sep)
59
+ else:
60
+ first = ['']
61
+ for root in first:
62
+ for path in extended_iglob(join_path(root, rest)):
63
+ if path not in seen:
64
+ seen.add(path)
65
+ yield path
66
+ for path in extended_iglob(join_path(root, '*', '**', rest)):
67
+ if path not in seen:
68
+ seen.add(path)
69
+ yield path
70
+ else:
71
+ for path in iglob(pattern):
72
+ yield path
73
+
74
+
75
+ def nonempty(it, error_msg="expected non-empty iterator"):
76
+ empty = True
77
+ for value in it:
78
+ empty = False
79
+ yield value
80
+ if empty:
81
+ raise ValueError(error_msg)
82
+
83
+
84
+ def update_pythran_extension(ext):
85
+ if pythran is None:
86
+ raise RuntimeError("You first need to install Pythran to use the np_pythran directive.")
87
+ try:
88
+ pythran_ext = pythran.config.make_extension(python=True)
89
+ except TypeError: # older pythran version only
90
+ pythran_ext = pythran.config.make_extension()
91
+
92
+ ext.include_dirs.extend(pythran_ext['include_dirs'])
93
+ ext.extra_compile_args.extend(pythran_ext['extra_compile_args'])
94
+ ext.extra_link_args.extend(pythran_ext['extra_link_args'])
95
+ ext.define_macros.extend(pythran_ext['define_macros'])
96
+ ext.undef_macros.extend(pythran_ext['undef_macros'])
97
+ ext.library_dirs.extend(pythran_ext['library_dirs'])
98
+ ext.libraries.extend(pythran_ext['libraries'])
99
+ ext.language = 'c++'
100
+
101
+ # These options are not compatible with the way normal Cython extensions work
102
+ for bad_option in ["-fwhole-program", "-fvisibility=hidden"]:
103
+ try:
104
+ ext.extra_compile_args.remove(bad_option)
105
+ except ValueError:
106
+ pass
107
+
108
+
109
+ def parse_list(s):
110
+ """
111
+ >>> parse_list("")
112
+ []
113
+ >>> parse_list("a")
114
+ ['a']
115
+ >>> parse_list("a b c")
116
+ ['a', 'b', 'c']
117
+ >>> parse_list("[a, b, c]")
118
+ ['a', 'b', 'c']
119
+ >>> parse_list('a " " b')
120
+ ['a', ' ', 'b']
121
+ >>> parse_list('[a, ",a", "a,", ",", ]')
122
+ ['a', ',a', 'a,', ',']
123
+ """
124
+ if len(s) >= 2 and s[0] == '[' and s[-1] == ']':
125
+ s = s[1:-1]
126
+ delimiter = ','
127
+ else:
128
+ delimiter = ' '
129
+ s, literals = strip_string_literals(s)
130
+ def unquote(literal):
131
+ literal = literal.strip()
132
+ if literal[0] in "'\"":
133
+ return literals[literal[1:-1]]
134
+ else:
135
+ return literal
136
+ return [unquote(item) for item in s.split(delimiter) if item.strip()]
137
+
138
+
139
+ transitive_str = object()
140
+ transitive_list = object()
141
+ bool_or = object()
142
+
143
+ distutils_settings = {
144
+ 'name': str,
145
+ 'sources': list,
146
+ 'define_macros': list,
147
+ 'undef_macros': list,
148
+ 'libraries': transitive_list,
149
+ 'library_dirs': transitive_list,
150
+ 'runtime_library_dirs': transitive_list,
151
+ 'include_dirs': transitive_list,
152
+ 'extra_objects': list,
153
+ 'extra_compile_args': transitive_list,
154
+ 'extra_link_args': transitive_list,
155
+ 'export_symbols': list,
156
+ 'depends': transitive_list,
157
+ 'language': transitive_str,
158
+ 'np_pythran': bool_or
159
+ }
160
+
161
+
162
+ @cython.cfunc
163
+ def _legacy_strtobool(val):
164
+ # Used to be "distutils.util.strtobool", adapted for deprecation warnings.
165
+ if val == "True":
166
+ return True
167
+ elif val == "False":
168
+ return False
169
+
170
+ import warnings
171
+ warnings.warn("The 'np_python' option requires 'True' or 'False'", category=DeprecationWarning)
172
+ val = val.lower()
173
+ if val in ('y', 'yes', 't', 'true', 'on', '1'):
174
+ return True
175
+ elif val in ('n', 'no', 'f', 'false', 'off', '0'):
176
+ return False
177
+ else:
178
+ raise ValueError("invalid truth value %r" % (val,))
179
+
180
+
181
+ class DistutilsInfo:
182
+
183
+ def __init__(self, source=None, exn=None):
184
+ self.values = {}
185
+ if source is not None:
186
+ source_lines = StringIO(source) if isinstance(source, str) else source
187
+ for line in source_lines:
188
+ line = line.lstrip()
189
+ if not line:
190
+ continue
191
+ if line[0] != '#':
192
+ break
193
+ line = line[1:].lstrip()
194
+ kind = next((k for k in ("distutils:","cython:") if line.startswith(k)), None)
195
+ if kind is not None:
196
+ key, _, value = [s.strip() for s in line[len(kind):].partition('=')]
197
+ type = distutils_settings.get(key, None)
198
+ if line.startswith("cython:") and type is None: continue
199
+ if type in (list, transitive_list):
200
+ value = parse_list(value)
201
+ if key == 'define_macros':
202
+ value = [tuple(macro.split('=', 1))
203
+ if '=' in macro else (macro, None)
204
+ for macro in value]
205
+ if type is bool_or:
206
+ value = _legacy_strtobool(value)
207
+ self.values[key] = value
208
+ elif exn is not None:
209
+ for key in distutils_settings:
210
+ if key in ('name', 'sources','np_pythran'):
211
+ continue
212
+ value = getattr(exn, key, None)
213
+ if value:
214
+ self.values[key] = value
215
+
216
+ def merge(self, other):
217
+ if other is None:
218
+ return self
219
+ for key, value in other.values.items():
220
+ type = distutils_settings[key]
221
+ if type is transitive_str and key not in self.values:
222
+ self.values[key] = value
223
+ elif type is transitive_list:
224
+ if key in self.values:
225
+ # Change a *copy* of the list (Trac #845)
226
+ all = self.values[key][:]
227
+ for v in value:
228
+ if v not in all:
229
+ all.append(v)
230
+ value = all
231
+ self.values[key] = value
232
+ elif type is bool_or:
233
+ self.values[key] = self.values.get(key, False) | value
234
+ return self
235
+
236
+ def subs(self, aliases):
237
+ if aliases is None:
238
+ return self
239
+ resolved = DistutilsInfo()
240
+ for key, value in self.values.items():
241
+ type = distutils_settings[key]
242
+ if type in [list, transitive_list]:
243
+ new_value_list = []
244
+ for v in value:
245
+ if v in aliases:
246
+ v = aliases[v]
247
+ if isinstance(v, list):
248
+ new_value_list += v
249
+ else:
250
+ new_value_list.append(v)
251
+ value = new_value_list
252
+ else:
253
+ if value in aliases:
254
+ value = aliases[value]
255
+ resolved.values[key] = value
256
+ return resolved
257
+
258
+ def apply(self, extension):
259
+ for key, value in self.values.items():
260
+ type = distutils_settings[key]
261
+ if type in [list, transitive_list]:
262
+ value = getattr(extension, key) + list(value)
263
+ setattr(extension, key, value)
264
+
265
+
266
+ _FIND_TOKEN = cython.declare(object, re.compile(r"""
267
+ (?P<comment> [#] ) |
268
+ (?P<brace> [{}] ) |
269
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
270
+ """, re.VERBOSE).search)
271
+
272
+ _FIND_STRING_TOKEN = cython.declare(object, re.compile(r"""
273
+ (?P<escape> [\\]+ ) (?P<escaped_quote> ['"] ) |
274
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
275
+ """, re.VERBOSE).search)
276
+
277
+ _FIND_FSTRING_TOKEN = cython.declare(object, re.compile(r"""
278
+ (?P<braces> [{]+ | [}]+ ) |
279
+ (?P<escape> [\\]+ ) (?P<escaped_quote> ['"] ) |
280
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
281
+ """, re.VERBOSE).search)
282
+
283
+
284
+ def strip_string_literals(code: str, prefix: str = '__Pyx_L'):
285
+ """
286
+ Normalizes every string literal to be of the form '__Pyx_Lxxx',
287
+ returning the normalized code and a mapping of labels to
288
+ string literals.
289
+ """
290
+ new_code: list = []
291
+ literals: dict = {}
292
+ counter: cython.Py_ssize_t = 0
293
+ find_token = _FIND_TOKEN
294
+
295
+ def append_new_label(literal):
296
+ nonlocal counter
297
+ counter += 1
298
+ label = f"{prefix}{counter}_"
299
+ literals[label] = literal
300
+ new_code.append(label)
301
+
302
+ def parse_string(quote_type: str, start: cython.Py_ssize_t, is_fstring: cython.bint) -> cython.Py_ssize_t:
303
+ charpos: cython.Py_ssize_t = start
304
+
305
+ find_token = _FIND_FSTRING_TOKEN if is_fstring else _FIND_STRING_TOKEN
306
+
307
+ while charpos != -1:
308
+ token = find_token(code, charpos)
309
+ if token is None:
310
+ # This probably indicates an unclosed string literal, i.e. a broken file.
311
+ append_new_label(code[start:])
312
+ charpos = -1
313
+ break
314
+ charpos = token.end()
315
+
316
+ if token['escape']:
317
+ if len(token['escape']) % 2 == 0 and token['escaped_quote'] == quote_type[0]:
318
+ # Quote is not actually escaped and might be part of a terminator, look at it next.
319
+ charpos -= 1
320
+
321
+ elif is_fstring and token['braces']:
322
+ # Formats or brace(s) in fstring.
323
+ if len(token['braces']) % 2 == 0:
324
+ # Normal brace characters in string.
325
+ continue
326
+ if token['braces'][-1] == '{':
327
+ if start < charpos-1:
328
+ append_new_label(code[start : charpos-1])
329
+ new_code.append('{')
330
+ start = charpos = parse_code(charpos, in_fstring=True)
331
+
332
+ elif token['quote'].startswith(quote_type):
333
+ # Closing quote found (potentially together with further, unrelated quotes).
334
+ charpos = token.start('quote')
335
+ if charpos > start:
336
+ append_new_label(code[start : charpos])
337
+ new_code.append(quote_type)
338
+ charpos += len(quote_type)
339
+ break
340
+
341
+ return charpos
342
+
343
+ def parse_code(start: cython.Py_ssize_t, in_fstring: cython.bint = False) -> cython.Py_ssize_t:
344
+ charpos: cython.Py_ssize_t = start
345
+ end: cython.Py_ssize_t
346
+ quote: str
347
+
348
+ while charpos != -1:
349
+ token = find_token(code, charpos)
350
+ if token is None:
351
+ new_code.append(code[start:])
352
+ charpos = -1
353
+ break
354
+ charpos = end = token.end()
355
+
356
+ if token['quote']:
357
+ quote = token['quote']
358
+ if len(quote) >= 6:
359
+ # Ignore empty tripple-quoted strings: '''''' or """"""
360
+ quote = quote[:len(quote) % 6]
361
+ if quote and len(quote) != 2:
362
+ if len(quote) > 3:
363
+ end -= len(quote) - 3
364
+ quote = quote[:3]
365
+ new_code.append(code[start:end])
366
+ start = charpos = parse_string(quote, end, is_fstring=token['fstring'])
367
+
368
+ elif token['comment']:
369
+ new_code.append(code[start:end])
370
+ charpos = code.find('\n', end)
371
+ append_new_label(code[end : charpos if charpos != -1 else None])
372
+ if charpos == -1:
373
+ break # EOF
374
+ start = charpos
375
+
376
+ elif in_fstring and token['brace']:
377
+ if token['brace'] == '}':
378
+ # Closing '}' of f-string.
379
+ charpos = end = token.start() + 1
380
+ new_code.append(code[start:end]) # with '}'
381
+ break
382
+ else:
383
+ # Starting a calculated format modifier inside of an f-string format.
384
+ end = token.start() + 1
385
+ new_code.append(code[start:end]) # with '{'
386
+ start = charpos = parse_code(end, in_fstring=True)
387
+
388
+ return charpos
389
+
390
+ parse_code(0)
391
+ return "".join(new_code), literals
392
+
393
+
394
+ # We need to allow spaces to allow for conditional compilation like
395
+ # IF ...:
396
+ # cimport ...
397
+ dependency_regex = re.compile(
398
+ r"(?:^ [ \t\f]* from [ \t\f]+ cython\.cimports\.([\w.]+) [ \t\f]+ c?import ) |"
399
+ r"(?:^ [ \t\f]* from [ \t\f]+ ([\w.]+) [ \t\f]+ cimport ) |"
400
+ r"(?:^ [ \t\f]* c?import [ \t\f]+ cython\.cimports\.([\w.]+) ) |"
401
+ r"(?:^ [ \t\f]* cimport [ \t\f]+ ([\w.]+ (?:[ \t\f]* , [ \t\f]* [\w.]+)*) ) |"
402
+ r"(?:^ [ \t\f]* cdef [ \t\f]+ extern [ \t\f]+ from [ \t\f]+ ['\"] ([^'\"]+) ['\"] ) |"
403
+ r"(?:^ [ \t\f]* include [ \t\f]+ ['\"] ([^'\"]+) ['\"] )",
404
+ re.MULTILINE | re.VERBOSE)
405
+ dependency_after_from_regex = re.compile(
406
+ r"(?:^ [ \t\f]+ \( ([\w., \t\f]*) \) [ \t\f]* [#\n]) |"
407
+ r"(?:^ [ \t\f]+ ([\w., \t\f]*) [ \t\f]* [#\n])",
408
+ re.MULTILINE | re.VERBOSE)
409
+
410
+
411
+ def normalize_existing(base_path, rel_paths):
412
+ return normalize_existing0(os.path.dirname(base_path), tuple(set(rel_paths)))
413
+
414
+
415
+ @cached_function
416
+ def normalize_existing0(base_dir, rel_paths):
417
+ """
418
+ Given some base directory ``base_dir`` and a list of path names
419
+ ``rel_paths``, normalize each relative path name ``rel`` by
420
+ replacing it by ``os.path.join(base, rel)`` if that file exists.
421
+
422
+ Return a couple ``(normalized, needed_base)`` where ``normalized``
423
+ if the list of normalized file names and ``needed_base`` is
424
+ ``base_dir`` if we actually needed ``base_dir``. If no paths were
425
+ changed (for example, if all paths were already absolute), then
426
+ ``needed_base`` is ``None``.
427
+ """
428
+ normalized = []
429
+ needed_base = None
430
+ for rel in rel_paths:
431
+ if os.path.isabs(rel):
432
+ normalized.append(rel)
433
+ continue
434
+ path = join_path(base_dir, rel)
435
+ if path_exists(path):
436
+ normalized.append(os.path.normpath(path))
437
+ needed_base = base_dir
438
+ else:
439
+ normalized.append(rel)
440
+ return (normalized, needed_base)
441
+
442
+
443
+ def resolve_depends(depends, include_dirs):
444
+ include_dirs = tuple(include_dirs)
445
+ resolved = []
446
+ for depend in depends:
447
+ path = resolve_depend(depend, include_dirs)
448
+ if path is not None:
449
+ resolved.append(path)
450
+ return resolved
451
+
452
+
453
+ @cached_function
454
+ def resolve_depend(depend, include_dirs):
455
+ if depend[0] == '<' and depend[-1] == '>':
456
+ return None
457
+ for dir in include_dirs:
458
+ path = join_path(dir, depend)
459
+ if path_exists(path):
460
+ return os.path.normpath(path)
461
+ return None
462
+
463
+
464
+ @cached_function
465
+ def package(filename):
466
+ dir = os.path.dirname(os.path.abspath(str(filename)))
467
+ if dir != filename and is_package_dir(dir):
468
+ return package(dir) + (os.path.basename(dir),)
469
+ else:
470
+ return ()
471
+
472
+
473
+ @cached_function
474
+ def fully_qualified_name(filename):
475
+ module = os.path.splitext(os.path.basename(filename))[0]
476
+ return '.'.join(package(filename) + (module,))
477
+
478
+
479
+ @cached_function
480
+ def parse_dependencies(source_filename):
481
+ # Actual parsing is way too slow, so we use regular expressions.
482
+ # The only catch is that we must strip comments and string
483
+ # literals ahead of time.
484
+ with Utils.open_source_file(source_filename, error_handling='ignore') as fh:
485
+ source = fh.read()
486
+ distutils_info = DistutilsInfo(source)
487
+ source, literals = strip_string_literals(source)
488
+ source = source.replace('\\\n', ' ').replace('\t', ' ')
489
+
490
+ # TODO: pure mode
491
+ cimports = []
492
+ includes = []
493
+ externs = []
494
+ for m in dependency_regex.finditer(source):
495
+ pycimports_from, cimport_from, pycimports_list, cimport_list, extern, include = m.groups()
496
+ if pycimports_from:
497
+ cimport_from = pycimports_from
498
+ if pycimports_list:
499
+ cimport_list = pycimports_list
500
+
501
+ if cimport_from:
502
+ cimports.append(cimport_from)
503
+ m_after_from = dependency_after_from_regex.search(source, pos=m.end())
504
+ if m_after_from:
505
+ multiline, one_line = m_after_from.groups()
506
+ subimports = multiline or one_line
507
+ cimports.extend("{}.{}".format(cimport_from, s.strip())
508
+ for s in subimports.split(','))
509
+
510
+ elif cimport_list:
511
+ cimports.extend(x.strip() for x in cimport_list.split(","))
512
+ elif extern:
513
+ externs.append(literals[extern])
514
+ else:
515
+ includes.append(literals[include])
516
+ return cimports, includes, externs, distutils_info
517
+
518
+
519
+ class DependencyTree:
520
+
521
+ def __init__(self, context, quiet=False):
522
+ self.context = context
523
+ self.quiet = quiet
524
+ self._transitive_cache = {}
525
+
526
+ def parse_dependencies(self, source_filename):
527
+ if path_exists(source_filename):
528
+ source_filename = os.path.normpath(source_filename)
529
+ return parse_dependencies(source_filename)
530
+
531
+ @cached_method
532
+ def included_files(self, filename):
533
+ # This is messy because included files are textually included, resolving
534
+ # cimports (but not includes) relative to the including file.
535
+ all = set()
536
+ for include in self.parse_dependencies(filename)[1]:
537
+ include_path = join_path(os.path.dirname(filename), include)
538
+ if not path_exists(include_path):
539
+ include_path = self.context.find_include_file(include, source_file_path=filename)
540
+ if include_path:
541
+ if '.' + os.path.sep in include_path:
542
+ include_path = os.path.normpath(include_path)
543
+ all.add(include_path)
544
+ all.update(self.included_files(include_path))
545
+ elif not self.quiet:
546
+ print("Unable to locate '%s' referenced from '%s'" % (filename, include))
547
+ return all
548
+
549
+ @cached_method
550
+ def cimports_externs_incdirs(self, filename):
551
+ # This is really ugly. Nested cimports are resolved with respect to the
552
+ # includer, but includes are resolved with respect to the includee.
553
+ cimports, includes, externs = self.parse_dependencies(filename)[:3]
554
+ cimports = set(cimports)
555
+ externs = set(externs)
556
+ incdirs = set()
557
+ for include in self.included_files(filename):
558
+ included_cimports, included_externs, included_incdirs = self.cimports_externs_incdirs(include)
559
+ cimports.update(included_cimports)
560
+ externs.update(included_externs)
561
+ incdirs.update(included_incdirs)
562
+ externs, incdir = normalize_existing(filename, externs)
563
+ if incdir:
564
+ incdirs.add(incdir)
565
+ return tuple(cimports), externs, incdirs
566
+
567
+ def cimports(self, filename):
568
+ return self.cimports_externs_incdirs(filename)[0]
569
+
570
+ def package(self, filename):
571
+ return package(filename)
572
+
573
+ def fully_qualified_name(self, filename):
574
+ return fully_qualified_name(filename)
575
+
576
+ @cached_method
577
+ def find_pxd(self, module, filename=None):
578
+ is_relative = module[0] == '.'
579
+ if is_relative and not filename:
580
+ raise NotImplementedError("New relative imports.")
581
+ if filename is not None:
582
+ module_path = module.split('.')
583
+ if is_relative:
584
+ module_path.pop(0) # just explicitly relative
585
+ package_path = list(self.package(filename))
586
+ while module_path and not module_path[0]:
587
+ try:
588
+ package_path.pop()
589
+ except IndexError:
590
+ return None # FIXME: error?
591
+ module_path.pop(0)
592
+ relative = '.'.join(package_path + module_path)
593
+ pxd = self.context.find_pxd_file(relative, source_file_path=filename)
594
+ if pxd:
595
+ return pxd
596
+ if is_relative:
597
+ return None # FIXME: error?
598
+ return self.context.find_pxd_file(module, source_file_path=filename)
599
+
600
+ @cached_method
601
+ def cimported_files(self, filename):
602
+ filename_root, filename_ext = os.path.splitext(filename)
603
+ if filename_ext in ('.pyx', '.py') and path_exists(filename_root + '.pxd'):
604
+ pxd_list = [filename_root + '.pxd']
605
+ else:
606
+ pxd_list = []
607
+ # Cimports generates all possible combinations package.module
608
+ # when imported as from package cimport module.
609
+ for module in self.cimports(filename):
610
+ if module[:7] == 'cython.' or module == 'cython':
611
+ continue
612
+ pxd_file = self.find_pxd(module, filename)
613
+ if pxd_file is not None:
614
+ pxd_list.append(pxd_file)
615
+ return tuple(pxd_list)
616
+
617
+ @cached_method
618
+ def immediate_dependencies(self, filename):
619
+ all_deps = {filename}
620
+ all_deps.update(self.cimported_files(filename))
621
+ all_deps.update(self.included_files(filename))
622
+ return all_deps
623
+
624
+ def all_dependencies(self, filename):
625
+ return self.transitive_merge(filename, self.immediate_dependencies, set.union)
626
+
627
+ @cached_method
628
+ def timestamp(self, filename):
629
+ return os.path.getmtime(filename)
630
+
631
+ def extract_timestamp(self, filename):
632
+ return self.timestamp(filename), filename
633
+
634
+ def newest_dependency(self, filename):
635
+ return max([self.extract_timestamp(f) for f in self.all_dependencies(filename)])
636
+
637
+ def distutils_info0(self, filename):
638
+ info = self.parse_dependencies(filename)[3]
639
+ kwds = info.values
640
+ cimports, externs, incdirs = self.cimports_externs_incdirs(filename)
641
+ basedir = os.getcwd()
642
+ # Add dependencies on "cdef extern from ..." files
643
+ if externs:
644
+ externs = _make_relative(externs, basedir)
645
+ if 'depends' in kwds:
646
+ kwds['depends'] = list(set(kwds['depends']).union(externs))
647
+ else:
648
+ kwds['depends'] = list(externs)
649
+ # Add include_dirs to ensure that the C compiler will find the
650
+ # "cdef extern from ..." files
651
+ if incdirs:
652
+ include_dirs = list(kwds.get('include_dirs', []))
653
+ for inc in _make_relative(incdirs, basedir):
654
+ if inc not in include_dirs:
655
+ include_dirs.append(inc)
656
+ kwds['include_dirs'] = include_dirs
657
+ return info
658
+
659
+ def distutils_info(self, filename, aliases=None, base=None):
660
+ return (self.transitive_merge(filename, self.distutils_info0, DistutilsInfo.merge)
661
+ .subs(aliases)
662
+ .merge(base))
663
+
664
+ def transitive_merge(self, node, extract, merge):
665
+ try:
666
+ seen = self._transitive_cache[extract, merge]
667
+ except KeyError:
668
+ seen = self._transitive_cache[extract, merge] = {}
669
+ return self.transitive_merge_helper(
670
+ node, extract, merge, seen, {}, self.cimported_files)[0]
671
+
672
+ def transitive_merge_helper(self, node, extract, merge, seen, stack, outgoing):
673
+ if node in seen:
674
+ return seen[node], None
675
+ deps = extract(node)
676
+ if node in stack:
677
+ return deps, node
678
+ try:
679
+ stack[node] = len(stack)
680
+ loop = None
681
+ for next in outgoing(node):
682
+ sub_deps, sub_loop = self.transitive_merge_helper(next, extract, merge, seen, stack, outgoing)
683
+ if sub_loop is not None:
684
+ if loop is not None and stack[loop] < stack[sub_loop]:
685
+ pass
686
+ else:
687
+ loop = sub_loop
688
+ deps = merge(deps, sub_deps)
689
+ if loop == node:
690
+ loop = None
691
+ if loop is None:
692
+ seen[node] = deps
693
+ return deps, loop
694
+ finally:
695
+ del stack[node]
696
+
697
+
698
+ _dep_tree = None
699
+
700
+ def create_dependency_tree(ctx=None, quiet=False):
701
+ global _dep_tree
702
+ if _dep_tree is None:
703
+ if ctx is None:
704
+ ctx = Context(["."], get_directive_defaults(),
705
+ options=CompilationOptions(default_options))
706
+ _dep_tree = DependencyTree(ctx, quiet=quiet)
707
+ return _dep_tree
708
+
709
+
710
+ # If this changes, change also docs/src/reference/compilation.rst
711
+ # which mentions this function
712
+ def default_create_extension(template, kwds):
713
+ if 'depends' in kwds:
714
+ include_dirs = kwds.get('include_dirs', []) + ["."]
715
+ depends = resolve_depends(kwds['depends'], include_dirs)
716
+ kwds['depends'] = sorted(set(depends + template.depends))
717
+
718
+ t = template.__class__
719
+ ext = t(**kwds)
720
+ if hasattr(template, "py_limited_api"):
721
+ ext.py_limited_api = template.py_limited_api
722
+ metadata = dict(distutils=kwds, module_name=kwds['name'])
723
+ return (ext, metadata)
724
+
725
+
726
+ # This may be useful for advanced users?
727
+ def create_extension_list(patterns, exclude=None, ctx=None, aliases=None, quiet=False, language=None,
728
+ exclude_failures=False):
729
+ if language is not None:
730
+ print('Warning: passing language={0!r} to cythonize() is deprecated. '
731
+ 'Instead, put "# distutils: language={0}" in your .pyx or .pxd file(s)'.format(language))
732
+ if exclude is None:
733
+ exclude = []
734
+ if patterns is None:
735
+ return [], {}
736
+ elif isinstance(patterns, str) or not isinstance(patterns, Iterable):
737
+ patterns = [patterns]
738
+
739
+ from distutils.extension import Extension
740
+ if 'setuptools' in sys.modules:
741
+ # Support setuptools Extension instances as well.
742
+ extension_classes = (
743
+ Extension, # should normally be the same as 'setuptools.extension._Extension'
744
+ sys.modules['setuptools.extension']._Extension,
745
+ sys.modules['setuptools'].Extension,
746
+ )
747
+ else:
748
+ extension_classes = (Extension,)
749
+
750
+ explicit_modules = {m.name for m in patterns if isinstance(m, extension_classes)}
751
+ deps = create_dependency_tree(ctx, quiet=quiet)
752
+ shared_utility_qualified_name = ctx.shared_utility_qualified_name
753
+
754
+ to_exclude = set()
755
+ if not isinstance(exclude, list):
756
+ exclude = [exclude]
757
+ for pattern in exclude:
758
+ to_exclude.update(map(os.path.abspath, extended_iglob(pattern)))
759
+
760
+ module_list = []
761
+ module_metadata = {}
762
+
763
+ # if no create_extension() function is defined, use a simple
764
+ # default function.
765
+ create_extension = ctx.options.create_extension or default_create_extension
766
+
767
+ seen = set()
768
+ for pattern in patterns:
769
+ if isinstance(pattern, str):
770
+ filepattern = pattern
771
+ template = Extension(pattern, []) # Fake Extension without sources
772
+ name = '*'
773
+ base = None
774
+ ext_language = language
775
+ elif isinstance(pattern, extension_classes):
776
+ cython_sources = [s for s in pattern.sources
777
+ if os.path.splitext(s)[1] in ('.py', '.pyx')]
778
+ template = pattern
779
+ name = template.name
780
+ base = DistutilsInfo(exn=template)
781
+ ext_language = None # do not override whatever the Extension says
782
+ if cython_sources:
783
+ filepattern = cython_sources[0]
784
+ if len(cython_sources) > 1:
785
+ print("Warning: Multiple cython sources found for extension '%s': %s\n"
786
+ "See https://cython.readthedocs.io/en/latest/src/userguide/sharing_declarations.html "
787
+ "for sharing declarations among Cython files." % (pattern.name, cython_sources))
788
+ elif shared_utility_qualified_name and pattern.name == shared_utility_qualified_name:
789
+ # This is the shared utility code file.
790
+ sources = pattern.sources or [
791
+ shared_utility_qualified_name.replace('.', os.sep) + ('.cpp' if pattern.language == 'c++' else '.c')]
792
+ m, _ = create_extension(pattern, dict(
793
+ name=shared_utility_qualified_name,
794
+ sources=sources,
795
+ language=pattern.language,
796
+ # shared utility code uses only parameters specified as argument of Extension() class
797
+ **base.values
798
+ ))
799
+ m.np_pythran = False
800
+ m.shared_utility_qualified_name = None
801
+ module_list.append(m)
802
+ continue
803
+ else:
804
+ # ignore non-cython modules
805
+ module_list.append(pattern)
806
+ continue
807
+ else:
808
+ msg = str("pattern is not of type str nor subclass of Extension (%s)"
809
+ " but of type %s and class %s" % (repr(Extension),
810
+ type(pattern),
811
+ pattern.__class__))
812
+ raise TypeError(msg)
813
+
814
+ for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
815
+ if os.path.abspath(file) in to_exclude:
816
+ continue
817
+ module_name = deps.fully_qualified_name(file)
818
+ if '*' in name:
819
+ if module_name in explicit_modules:
820
+ continue
821
+ elif name:
822
+ module_name = name
823
+
824
+ Utils.raise_error_if_module_name_forbidden(module_name)
825
+
826
+ if module_name not in seen:
827
+ try:
828
+ kwds = deps.distutils_info(file, aliases, base).values
829
+ except Exception:
830
+ if exclude_failures:
831
+ continue
832
+ raise
833
+ if base is not None:
834
+ for key, value in base.values.items():
835
+ if key not in kwds:
836
+ kwds[key] = value
837
+
838
+ kwds['name'] = module_name
839
+
840
+ sources = [file] + [m for m in template.sources if m != filepattern]
841
+ if 'sources' in kwds:
842
+ # allow users to add .c files etc.
843
+ for source in kwds['sources']:
844
+ if source not in sources:
845
+ sources.append(source)
846
+ kwds['sources'] = sources
847
+
848
+ if ext_language and 'language' not in kwds:
849
+ kwds['language'] = ext_language
850
+
851
+ np_pythran = kwds.pop('np_pythran', False)
852
+
853
+ # Create the new extension
854
+ m, metadata = create_extension(template, kwds)
855
+ m.np_pythran = np_pythran or getattr(m, 'np_pythran', False)
856
+ m.shared_utility_qualified_name = shared_utility_qualified_name
857
+ if m.np_pythran:
858
+ update_pythran_extension(m)
859
+ module_list.append(m)
860
+
861
+ # Store metadata (this will be written as JSON in the
862
+ # generated C file but otherwise has no purpose)
863
+ module_metadata[module_name] = metadata
864
+
865
+ if file not in m.sources:
866
+ # Old setuptools unconditionally replaces .pyx with .c/.cpp
867
+ target_file = os.path.splitext(file)[0] + ('.cpp' if m.language == 'c++' else '.c')
868
+ try:
869
+ m.sources.remove(target_file)
870
+ except ValueError:
871
+ # never seen this in the wild, but probably better to warn about this unexpected case
872
+ print("Warning: Cython source file not found in sources list, adding %s" % file)
873
+ m.sources.insert(0, file)
874
+ seen.add(name)
875
+ return module_list, module_metadata
876
+
877
+
878
+ # This is the user-exposed entry point.
879
+ def cythonize(module_list, exclude=None, nthreads=0, aliases=None, quiet=False, force=None, language=None,
880
+ exclude_failures=False, show_all_warnings=False, **options):
881
+ """
882
+ Compile a set of source modules into C/C++ files and return a list of distutils
883
+ Extension objects for them.
884
+
885
+ :param module_list: As module list, pass either a glob pattern, a list of glob
886
+ patterns or a list of Extension objects. The latter
887
+ allows you to configure the extensions separately
888
+ through the normal distutils options.
889
+ You can also pass Extension objects that have
890
+ glob patterns as their sources. Then, cythonize
891
+ will resolve the pattern and create a
892
+ copy of the Extension for every matching file.
893
+
894
+ :param exclude: When passing glob patterns as ``module_list``, you can exclude certain
895
+ module names explicitly by passing them into the ``exclude`` option.
896
+
897
+ :param nthreads: The number of concurrent builds for parallel compilation
898
+ (requires the ``multiprocessing`` module).
899
+
900
+ :param aliases: If you want to use compiler directives like ``# distutils: ...`` but
901
+ can only know at compile time (when running the ``setup.py``) which values
902
+ to use, you can use aliases and pass a dictionary mapping those aliases
903
+ to Python strings when calling :func:`cythonize`. As an example, say you
904
+ want to use the compiler
905
+ directive ``# distutils: include_dirs = ../static_libs/include/``
906
+ but this path isn't always fixed and you want to find it when running
907
+ the ``setup.py``. You can then do ``# distutils: include_dirs = MY_HEADERS``,
908
+ find the value of ``MY_HEADERS`` in the ``setup.py``, put it in a python
909
+ variable called ``foo`` as a string, and then call
910
+ ``cythonize(..., aliases={'MY_HEADERS': foo})``.
911
+
912
+ :param quiet: If True, Cython won't print error, warning, or status messages during the
913
+ compilation.
914
+
915
+ :param force: Forces the recompilation of the Cython modules, even if the timestamps
916
+ don't indicate that a recompilation is necessary.
917
+
918
+ :param language: To globally enable C++ mode, you can pass ``language='c++'``. Otherwise, this
919
+ will be determined at a per-file level based on compiler directives. This
920
+ affects only modules found based on file names. Extension instances passed
921
+ into :func:`cythonize` will not be changed. It is recommended to rather
922
+ use the compiler directive ``# distutils: language = c++`` than this option.
923
+
924
+ :param exclude_failures: For a broad 'try to compile' mode that ignores compilation
925
+ failures and simply excludes the failed extensions,
926
+ pass ``exclude_failures=True``. Note that this only
927
+ really makes sense for compiling ``.py`` files which can also
928
+ be used without compilation.
929
+
930
+ :param show_all_warnings: By default, not all Cython warnings are printed.
931
+ Set to true to show all warnings.
932
+
933
+ :param annotate: If ``True``, will produce a HTML file for each of the ``.pyx`` or ``.py``
934
+ files compiled. The HTML file gives an indication
935
+ of how much Python interaction there is in
936
+ each of the source code lines, compared to plain C code.
937
+ It also allows you to see the C/C++ code
938
+ generated for each line of Cython code. This report is invaluable when
939
+ optimizing a function for speed,
940
+ and for determining when to :ref:`release the GIL <nogil>`:
941
+ in general, a ``nogil`` block may contain only "white" code.
942
+ See examples in :ref:`determining_where_to_add_types` or
943
+ :ref:`primes`.
944
+
945
+
946
+ :param annotate-fullc: If ``True`` will produce a colorized HTML version of
947
+ the source which includes entire generated C/C++-code.
948
+
949
+
950
+ :param compiler_directives: Allow to set compiler directives in the ``setup.py`` like this:
951
+ ``compiler_directives={'embedsignature': True}``.
952
+ See :ref:`compiler-directives`.
953
+
954
+ :param depfile: produce depfiles for the sources if True.
955
+ :param cache: If ``True`` the cache enabled with default path. If the value is a path to a directory,
956
+ then the directory is used to cache generated ``.c``/``.cpp`` files. By default cache is disabled.
957
+ See :ref:`cython-cache`.
958
+ """
959
+ if exclude is None:
960
+ exclude = []
961
+ if 'include_path' not in options:
962
+ options['include_path'] = ['.']
963
+ if 'common_utility_include_dir' in options:
964
+ safe_makedirs(options['common_utility_include_dir'])
965
+
966
+ depfile = options.pop('depfile', None)
967
+
968
+ if pythran is None:
969
+ pythran_options = None
970
+ else:
971
+ pythran_options = CompilationOptions(**options)
972
+ pythran_options.cplus = True
973
+ pythran_options.np_pythran = True
974
+
975
+ if force is None:
976
+ force = os.environ.get("CYTHON_FORCE_REGEN") == "1" # allow global overrides for build systems
977
+
978
+ c_options = CompilationOptions(**options)
979
+ cpp_options = CompilationOptions(**options); cpp_options.cplus = True
980
+ ctx = Context.from_options(c_options)
981
+ options = c_options
982
+ shared_utility_qualified_name = ctx.shared_utility_qualified_name
983
+ module_list, module_metadata = create_extension_list(
984
+ module_list,
985
+ exclude=exclude,
986
+ ctx=ctx,
987
+ quiet=quiet,
988
+ exclude_failures=exclude_failures,
989
+ language=language,
990
+ aliases=aliases)
991
+
992
+ deps = create_dependency_tree(ctx, quiet=quiet)
993
+ build_dir = getattr(options, 'build_dir', None)
994
+ if options.cache and not (options.annotate or Options.annotate):
995
+ # cache is enabled when:
996
+ # * options.cache is True (the default path to the cache base dir is used)
997
+ # * options.cache is the explicit path to the cache base dir
998
+ # * annotations are not generated
999
+ cache_path = None if options.cache is True else options.cache
1000
+ cache = Cache(cache_path, getattr(options, 'cache_size', None))
1001
+ else:
1002
+ cache = None
1003
+
1004
+ def copy_to_build_dir(filepath, root=os.getcwd()):
1005
+ filepath_abs = os.path.abspath(filepath)
1006
+ if os.path.isabs(filepath):
1007
+ filepath = filepath_abs
1008
+ if filepath_abs.startswith(root):
1009
+ # distutil extension depends are relative to cwd
1010
+ mod_dir = join_path(build_dir,
1011
+ os.path.dirname(_relpath(filepath, root)))
1012
+ copy_once_if_newer(filepath_abs, mod_dir)
1013
+
1014
+ def file_in_build_dir(c_file):
1015
+ if not build_dir:
1016
+ return c_file
1017
+ if os.path.isabs(c_file):
1018
+ c_file = os.path.splitdrive(c_file)[1]
1019
+ c_file = c_file.split(os.sep, 1)[1]
1020
+ c_file = os.path.join(build_dir, c_file)
1021
+ dir = os.path.dirname(c_file)
1022
+ safe_makedirs_once(dir)
1023
+ return c_file
1024
+
1025
+ modules_by_cfile = collections.defaultdict(list)
1026
+ to_compile = []
1027
+ for m in module_list:
1028
+ if build_dir:
1029
+ for dep in m.depends:
1030
+ copy_to_build_dir(dep)
1031
+
1032
+ cy_sources = [
1033
+ source for source in m.sources
1034
+ if os.path.splitext(source)[1] in ('.pyx', '.py')]
1035
+ if len(cy_sources) == 1:
1036
+ # normal "special" case: believe the Extension module name to allow user overrides
1037
+ full_module_name = m.name
1038
+ else:
1039
+ # infer FQMN from source files
1040
+ full_module_name = None
1041
+
1042
+ np_pythran = getattr(m, 'np_pythran', False)
1043
+ py_limited_api = getattr(m, 'py_limited_api', False)
1044
+
1045
+ if np_pythran:
1046
+ options = pythran_options
1047
+ elif m.language == 'c++':
1048
+ options = cpp_options
1049
+ else:
1050
+ options = c_options
1051
+
1052
+ new_sources = []
1053
+ for source in m.sources:
1054
+ base, ext = os.path.splitext(source)
1055
+ if ext in ('.pyx', '.py'):
1056
+ c_file = base + ('.cpp' if m.language == 'c++' or np_pythran else '.c')
1057
+
1058
+ # setup for out of place build directory if enabled
1059
+ c_file = file_in_build_dir(c_file)
1060
+
1061
+ # write out the depfile, if requested
1062
+ if depfile:
1063
+ dependencies = deps.all_dependencies(source)
1064
+ write_depfile(c_file, source, dependencies)
1065
+
1066
+ # Missing files and those generated by other Cython versions should always be recreated.
1067
+ if Utils.file_generated_by_this_cython(c_file):
1068
+ c_timestamp = os.path.getmtime(c_file)
1069
+ else:
1070
+ c_timestamp = -1
1071
+
1072
+ # Priority goes first to modified files, second to direct
1073
+ # dependents, and finally to indirect dependents.
1074
+ if c_timestamp < deps.timestamp(source):
1075
+ dep_timestamp, dep = deps.timestamp(source), source
1076
+ priority = 0
1077
+ else:
1078
+ dep_timestamp, dep = deps.newest_dependency(source)
1079
+ priority = 2 - (dep in deps.immediate_dependencies(source))
1080
+ if force or c_timestamp < dep_timestamp:
1081
+ if not quiet and not force:
1082
+ if source == dep:
1083
+ print("Compiling %s because it changed." % Utils.decode_filename(source))
1084
+ else:
1085
+ print("Compiling %s because it depends on %s." % (
1086
+ Utils.decode_filename(source),
1087
+ Utils.decode_filename(dep),
1088
+ ))
1089
+ if not force and cache:
1090
+ fingerprint = cache.transitive_fingerprint(
1091
+ source, deps.all_dependencies(source), options,
1092
+ FingerprintFlags(m.language or 'c', py_limited_api, np_pythran)
1093
+ )
1094
+ else:
1095
+ fingerprint = None
1096
+ to_compile.append((
1097
+ priority, source, c_file, fingerprint, quiet,
1098
+ options, not exclude_failures, module_metadata.get(m.name),
1099
+ full_module_name, show_all_warnings))
1100
+ modules_by_cfile[c_file].append(m)
1101
+ elif shared_utility_qualified_name and m.name == shared_utility_qualified_name:
1102
+ # Generate shared utility code module now.
1103
+ c_file = file_in_build_dir(source)
1104
+ module_options = CompilationOptions(
1105
+ options, shared_c_file_path=c_file, shared_utility_qualified_name=None)
1106
+ if not Utils.is_cython_generated_file(c_file):
1107
+ print(f"Warning: Shared module source file is not a Cython file - not creating '{m.name}' as '{c_file}'")
1108
+ elif force or not Utils.file_generated_by_this_cython(c_file):
1109
+ from .SharedModule import generate_shared_module
1110
+ if not quiet:
1111
+ print(f"Generating shared module '{m.name}'")
1112
+ generate_shared_module(module_options)
1113
+ else:
1114
+ c_file = source
1115
+ if build_dir:
1116
+ copy_to_build_dir(source)
1117
+
1118
+ new_sources.append(c_file)
1119
+
1120
+ m.sources = new_sources
1121
+
1122
+ to_compile.sort()
1123
+ N = len(to_compile)
1124
+
1125
+ # Drop "priority" sorting component of "to_compile" entries
1126
+ # and add a simple progress indicator and the remaining arguments.
1127
+ build_progress_indicator = ("[{0:%d}/%d] " % (len(str(N)), N)).format
1128
+ to_compile = [
1129
+ task[1:] + (build_progress_indicator(i), cache)
1130
+ for i, task in enumerate(to_compile, 1)
1131
+ ]
1132
+
1133
+ if N <= 1:
1134
+ nthreads = 0
1135
+ try:
1136
+ from concurrent.futures import ProcessPoolExecutor
1137
+ except ImportError:
1138
+ nthreads = 0
1139
+
1140
+ if nthreads:
1141
+ with ProcessPoolExecutor(
1142
+ max_workers=nthreads,
1143
+ initializer=_init_multiprocessing_helper,
1144
+ ) as proc_pool:
1145
+ try:
1146
+ list(proc_pool.map(cythonize_one_helper, to_compile, chunksize=1))
1147
+ except KeyboardInterrupt:
1148
+ proc_pool.terminate_workers()
1149
+ proc_pool.shutdown(cancel_futures=True)
1150
+ raise
1151
+ else:
1152
+ for args in to_compile:
1153
+ cythonize_one(*args)
1154
+
1155
+ if exclude_failures:
1156
+ failed_modules = set()
1157
+ for c_file, modules in modules_by_cfile.items():
1158
+ if not os.path.exists(c_file):
1159
+ failed_modules.update(modules)
1160
+ elif os.path.getsize(c_file) < 200:
1161
+ f = open(c_file, 'r', encoding='iso8859-1')
1162
+ try:
1163
+ if f.read(len('#error ')) == '#error ':
1164
+ # dead compilation result
1165
+ failed_modules.update(modules)
1166
+ finally:
1167
+ f.close()
1168
+ if failed_modules:
1169
+ for module in failed_modules:
1170
+ module_list.remove(module)
1171
+ print("Failed compilations: %s" % ', '.join(sorted([
1172
+ module.name for module in failed_modules])))
1173
+
1174
+ if cache:
1175
+ cache.cleanup_cache()
1176
+
1177
+ # cythonize() is often followed by the (non-Python-buffered)
1178
+ # compiler output, flush now to avoid interleaving output.
1179
+ sys.stdout.flush()
1180
+ return module_list
1181
+
1182
+
1183
+ if os.environ.get('XML_RESULTS'):
1184
+ compile_result_dir = os.environ['XML_RESULTS']
1185
+ def record_results(func):
1186
+ def with_record(*args):
1187
+ t = time.time()
1188
+ success = False
1189
+ try:
1190
+ func(*args)
1191
+ success = True
1192
+ except Exception:
1193
+ # It's not obvious that we should really swallow the exception here,
1194
+ # rather than fail loudly after writing the XML result file,
1195
+ # but that's how it's currently implemented.
1196
+ pass
1197
+ finally:
1198
+ t = time.time() - t
1199
+ module = fully_qualified_name(args[0])
1200
+ name = "cythonize." + module
1201
+ failures = 1 - success
1202
+ with open(os.path.join(compile_result_dir, name + ".xml"), "w") as output:
1203
+ output.write(f"""
1204
+ <?xml version="1.0" ?>
1205
+ <testsuite name="{name}" errors="0" failures="{failures}" tests="1" time="{t}">
1206
+ <testcase classname="{name}" name="cythonize">
1207
+ {'' if success else 'failure'}
1208
+ </testcase>
1209
+ </testsuite>
1210
+ """.strip())
1211
+ return with_record
1212
+ else:
1213
+ def record_results(func):
1214
+ return func
1215
+
1216
+
1217
+ # TODO: Share context? Issue: pyx processing leaks into pxd module
1218
+ @record_results
1219
+ def cythonize_one(pyx_file, c_file,
1220
+ fingerprint=None, quiet=False, options=None,
1221
+ raise_on_failure=True, embedded_metadata=None,
1222
+ full_module_name=None, show_all_warnings=False,
1223
+ progress="", cache=None):
1224
+ from ..Compiler.Main import compile_single, default_options
1225
+ from ..Compiler.Errors import CompileError, PyrexError
1226
+
1227
+ if not quiet:
1228
+ if cache and fingerprint and cache.lookup_cache(c_file, fingerprint):
1229
+ print(f"{progress}Found compiled {pyx_file} in cache")
1230
+ else:
1231
+ print(f"{progress}Cythonizing {Utils.decode_filename(pyx_file)}")
1232
+ if options is None:
1233
+ options = CompilationOptions(default_options)
1234
+ options.output_file = c_file
1235
+ options.embedded_metadata = embedded_metadata
1236
+
1237
+ old_warning_level = Errors.LEVEL
1238
+ if show_all_warnings:
1239
+ Errors.LEVEL = 0
1240
+
1241
+ any_failures = 0
1242
+ try:
1243
+ result = compile_single(pyx_file, options, full_module_name=full_module_name, cache=cache, fingerprint=fingerprint)
1244
+ if result.num_errors > 0:
1245
+ any_failures = 1
1246
+ except (OSError, PyrexError) as e:
1247
+ sys.stderr.write('%s\n' % e)
1248
+ any_failures = 1
1249
+ # XXX
1250
+ import traceback
1251
+ traceback.print_exc()
1252
+ except Exception:
1253
+ if raise_on_failure:
1254
+ raise
1255
+ import traceback
1256
+ traceback.print_exc()
1257
+ any_failures = 1
1258
+ finally:
1259
+ if show_all_warnings:
1260
+ Errors.LEVEL = old_warning_level
1261
+
1262
+ if any_failures:
1263
+ if raise_on_failure:
1264
+ raise CompileError(None, pyx_file)
1265
+ elif os.path.exists(c_file):
1266
+ os.remove(c_file)
1267
+
1268
+
1269
+ def cythonize_one_helper(m):
1270
+ import traceback
1271
+ try:
1272
+ return cythonize_one(*m)
1273
+ except Exception:
1274
+ traceback.print_exc()
1275
+ raise
1276
+
1277
+
1278
+ def _init_multiprocessing_helper():
1279
+ # KeyboardInterrupt kills workers, so don't let them get it
1280
+ import signal
1281
+ signal.signal(signal.SIGINT, signal.SIG_IGN)