Cython 3.1.0__py3-none-any.whl

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