Cython 3.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +250 -0
  4. Cython/Build/Dependencies.py +1275 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +342 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/Tests/TestCyCache.py +119 -0
  9. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  10. Cython/Build/Tests/TestDependencies.py +133 -0
  11. Cython/Build/Tests/TestInline.py +112 -0
  12. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  13. Cython/Build/Tests/TestRecythonize.py +212 -0
  14. Cython/Build/Tests/TestStripLiterals.py +155 -0
  15. Cython/Build/Tests/__init__.py +1 -0
  16. Cython/Build/__init__.py +8 -0
  17. Cython/CodeWriter.py +811 -0
  18. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  19. Cython/Compiler/Annotate.py +326 -0
  20. Cython/Compiler/AutoDocTransforms.py +314 -0
  21. Cython/Compiler/Buffer.py +680 -0
  22. Cython/Compiler/Builtin.py +862 -0
  23. Cython/Compiler/CmdLine.py +243 -0
  24. Cython/Compiler/Code.pxd +145 -0
  25. Cython/Compiler/Code.py +3328 -0
  26. Cython/Compiler/CodeGeneration.py +33 -0
  27. Cython/Compiler/CythonScope.py +179 -0
  28. Cython/Compiler/Dataclass.py +868 -0
  29. Cython/Compiler/DebugFlags.py +21 -0
  30. Cython/Compiler/Errors.py +295 -0
  31. Cython/Compiler/ExprNodes.py +15051 -0
  32. Cython/Compiler/FlowControl.pxd +97 -0
  33. Cython/Compiler/FlowControl.py +1438 -0
  34. Cython/Compiler/FusedNode.py +998 -0
  35. Cython/Compiler/Future.py +16 -0
  36. Cython/Compiler/Interpreter.py +57 -0
  37. Cython/Compiler/Lexicon.py +340 -0
  38. Cython/Compiler/LineTable.py +114 -0
  39. Cython/Compiler/Main.py +779 -0
  40. Cython/Compiler/MatchCaseNodes.py +259 -0
  41. Cython/Compiler/MemoryView.py +860 -0
  42. Cython/Compiler/ModuleNode.py +4065 -0
  43. Cython/Compiler/Naming.py +369 -0
  44. Cython/Compiler/Nodes.py +10557 -0
  45. Cython/Compiler/Optimize.py +5269 -0
  46. Cython/Compiler/Options.py +828 -0
  47. Cython/Compiler/ParseTreeTransforms.pxd +78 -0
  48. Cython/Compiler/ParseTreeTransforms.py +4441 -0
  49. Cython/Compiler/Parsing.pxd +9 -0
  50. Cython/Compiler/Parsing.py +4797 -0
  51. Cython/Compiler/Pipeline.py +425 -0
  52. Cython/Compiler/PyrexTypes.py +5572 -0
  53. Cython/Compiler/Pythran.py +223 -0
  54. Cython/Compiler/Scanning.pxd +40 -0
  55. Cython/Compiler/Scanning.py +574 -0
  56. Cython/Compiler/StringEncoding.py +347 -0
  57. Cython/Compiler/Symtab.py +2998 -0
  58. Cython/Compiler/Tests/TestBuffer.py +105 -0
  59. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  60. Cython/Compiler/Tests/TestCmdLine.py +573 -0
  61. Cython/Compiler/Tests/TestCode.py +86 -0
  62. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  63. Cython/Compiler/Tests/TestGrammar.py +202 -0
  64. Cython/Compiler/Tests/TestMemView.py +71 -0
  65. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  66. Cython/Compiler/Tests/TestScanning.py +134 -0
  67. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  68. Cython/Compiler/Tests/TestStringEncoding.py +33 -0
  69. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  70. Cython/Compiler/Tests/TestTreePath.py +93 -0
  71. Cython/Compiler/Tests/TestTypes.py +75 -0
  72. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  73. Cython/Compiler/Tests/TestVisitor.py +61 -0
  74. Cython/Compiler/Tests/Utils.py +36 -0
  75. Cython/Compiler/Tests/__init__.py +1 -0
  76. Cython/Compiler/TreeFragment.py +278 -0
  77. Cython/Compiler/TreePath.py +290 -0
  78. Cython/Compiler/TypeInference.py +584 -0
  79. Cython/Compiler/TypeSlots.py +1181 -0
  80. Cython/Compiler/UFuncs.py +311 -0
  81. Cython/Compiler/UtilNodes.py +387 -0
  82. Cython/Compiler/UtilityCode.py +274 -0
  83. Cython/Compiler/Version.py +8 -0
  84. Cython/Compiler/Visitor.pxd +53 -0
  85. Cython/Compiler/Visitor.py +861 -0
  86. Cython/Compiler/__init__.py +1 -0
  87. Cython/Coverage.py +443 -0
  88. Cython/Debugger/Cygdb.py +179 -0
  89. Cython/Debugger/DebugWriter.py +82 -0
  90. Cython/Debugger/Tests/TestLibCython.py +275 -0
  91. Cython/Debugger/Tests/__init__.py +1 -0
  92. Cython/Debugger/Tests/cfuncs.c +8 -0
  93. Cython/Debugger/Tests/codefile +49 -0
  94. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  95. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  96. Cython/Debugger/__init__.py +1 -0
  97. Cython/Debugger/libcython.py +1549 -0
  98. Cython/Debugger/libpython.py +2821 -0
  99. Cython/Debugging.py +20 -0
  100. Cython/Distutils/__init__.py +2 -0
  101. Cython/Distutils/build_ext.py +137 -0
  102. Cython/Distutils/extension.py +96 -0
  103. Cython/Distutils/old_build_ext.py +351 -0
  104. Cython/Includes/cpython/__init__.pxd +173 -0
  105. Cython/Includes/cpython/array.pxd +174 -0
  106. Cython/Includes/cpython/bool.pxd +37 -0
  107. Cython/Includes/cpython/buffer.pxd +112 -0
  108. Cython/Includes/cpython/bytearray.pxd +33 -0
  109. Cython/Includes/cpython/bytes.pxd +200 -0
  110. Cython/Includes/cpython/cellobject.pxd +35 -0
  111. Cython/Includes/cpython/ceval.pxd +8 -0
  112. Cython/Includes/cpython/codecs.pxd +121 -0
  113. Cython/Includes/cpython/complex.pxd +55 -0
  114. Cython/Includes/cpython/contextvars.pxd +141 -0
  115. Cython/Includes/cpython/conversion.pxd +36 -0
  116. Cython/Includes/cpython/datetime.pxd +384 -0
  117. Cython/Includes/cpython/descr.pxd +26 -0
  118. Cython/Includes/cpython/dict.pxd +187 -0
  119. Cython/Includes/cpython/exc.pxd +263 -0
  120. Cython/Includes/cpython/fileobject.pxd +57 -0
  121. Cython/Includes/cpython/float.pxd +47 -0
  122. Cython/Includes/cpython/function.pxd +65 -0
  123. Cython/Includes/cpython/genobject.pxd +25 -0
  124. Cython/Includes/cpython/getargs.pxd +12 -0
  125. Cython/Includes/cpython/instance.pxd +25 -0
  126. Cython/Includes/cpython/iterator.pxd +36 -0
  127. Cython/Includes/cpython/iterobject.pxd +24 -0
  128. Cython/Includes/cpython/list.pxd +92 -0
  129. Cython/Includes/cpython/long.pxd +149 -0
  130. Cython/Includes/cpython/longintrepr.pxd +19 -0
  131. Cython/Includes/cpython/mapping.pxd +63 -0
  132. Cython/Includes/cpython/marshal.pxd +66 -0
  133. Cython/Includes/cpython/mem.pxd +120 -0
  134. Cython/Includes/cpython/memoryview.pxd +50 -0
  135. Cython/Includes/cpython/method.pxd +49 -0
  136. Cython/Includes/cpython/module.pxd +208 -0
  137. Cython/Includes/cpython/number.pxd +258 -0
  138. Cython/Includes/cpython/object.pxd +433 -0
  139. Cython/Includes/cpython/pycapsule.pxd +143 -0
  140. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  141. Cython/Includes/cpython/pyport.pxd +8 -0
  142. Cython/Includes/cpython/pystate.pxd +95 -0
  143. Cython/Includes/cpython/pythread.pxd +53 -0
  144. Cython/Includes/cpython/ref.pxd +67 -0
  145. Cython/Includes/cpython/sequence.pxd +134 -0
  146. Cython/Includes/cpython/set.pxd +119 -0
  147. Cython/Includes/cpython/slice.pxd +70 -0
  148. Cython/Includes/cpython/time.pxd +129 -0
  149. Cython/Includes/cpython/tuple.pxd +72 -0
  150. Cython/Includes/cpython/type.pxd +53 -0
  151. Cython/Includes/cpython/unicode.pxd +639 -0
  152. Cython/Includes/cpython/version.pxd +32 -0
  153. Cython/Includes/cpython/weakref.pxd +42 -0
  154. Cython/Includes/libc/__init__.pxd +1 -0
  155. Cython/Includes/libc/complex.pxd +35 -0
  156. Cython/Includes/libc/errno.pxd +127 -0
  157. Cython/Includes/libc/float.pxd +43 -0
  158. Cython/Includes/libc/limits.pxd +28 -0
  159. Cython/Includes/libc/locale.pxd +46 -0
  160. Cython/Includes/libc/math.pxd +209 -0
  161. Cython/Includes/libc/setjmp.pxd +10 -0
  162. Cython/Includes/libc/signal.pxd +64 -0
  163. Cython/Includes/libc/stddef.pxd +9 -0
  164. Cython/Includes/libc/stdint.pxd +105 -0
  165. Cython/Includes/libc/stdio.pxd +80 -0
  166. Cython/Includes/libc/stdlib.pxd +72 -0
  167. Cython/Includes/libc/string.pxd +50 -0
  168. Cython/Includes/libc/time.pxd +47 -0
  169. Cython/Includes/libcpp/__init__.pxd +4 -0
  170. Cython/Includes/libcpp/algorithm.pxd +320 -0
  171. Cython/Includes/libcpp/any.pxd +16 -0
  172. Cython/Includes/libcpp/atomic.pxd +59 -0
  173. Cython/Includes/libcpp/bit.pxd +29 -0
  174. Cython/Includes/libcpp/cast.pxd +12 -0
  175. Cython/Includes/libcpp/cmath.pxd +518 -0
  176. Cython/Includes/libcpp/complex.pxd +106 -0
  177. Cython/Includes/libcpp/deque.pxd +165 -0
  178. Cython/Includes/libcpp/execution.pxd +15 -0
  179. Cython/Includes/libcpp/forward_list.pxd +63 -0
  180. Cython/Includes/libcpp/functional.pxd +26 -0
  181. Cython/Includes/libcpp/iterator.pxd +34 -0
  182. Cython/Includes/libcpp/limits.pxd +61 -0
  183. Cython/Includes/libcpp/list.pxd +117 -0
  184. Cython/Includes/libcpp/map.pxd +252 -0
  185. Cython/Includes/libcpp/memory.pxd +115 -0
  186. Cython/Includes/libcpp/numbers.pxd +15 -0
  187. Cython/Includes/libcpp/numeric.pxd +131 -0
  188. Cython/Includes/libcpp/optional.pxd +34 -0
  189. Cython/Includes/libcpp/pair.pxd +1 -0
  190. Cython/Includes/libcpp/queue.pxd +25 -0
  191. Cython/Includes/libcpp/random.pxd +166 -0
  192. Cython/Includes/libcpp/set.pxd +228 -0
  193. Cython/Includes/libcpp/stack.pxd +11 -0
  194. Cython/Includes/libcpp/string.pxd +333 -0
  195. Cython/Includes/libcpp/typeindex.pxd +15 -0
  196. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  197. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  198. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  199. Cython/Includes/libcpp/utility.pxd +30 -0
  200. Cython/Includes/libcpp/vector.pxd +167 -0
  201. Cython/Includes/openmp.pxd +50 -0
  202. Cython/Includes/posix/__init__.pxd +1 -0
  203. Cython/Includes/posix/dlfcn.pxd +14 -0
  204. Cython/Includes/posix/fcntl.pxd +86 -0
  205. Cython/Includes/posix/ioctl.pxd +4 -0
  206. Cython/Includes/posix/mman.pxd +101 -0
  207. Cython/Includes/posix/resource.pxd +57 -0
  208. Cython/Includes/posix/select.pxd +21 -0
  209. Cython/Includes/posix/signal.pxd +73 -0
  210. Cython/Includes/posix/stat.pxd +98 -0
  211. Cython/Includes/posix/stdio.pxd +37 -0
  212. Cython/Includes/posix/stdlib.pxd +29 -0
  213. Cython/Includes/posix/strings.pxd +9 -0
  214. Cython/Includes/posix/time.pxd +71 -0
  215. Cython/Includes/posix/types.pxd +30 -0
  216. Cython/Includes/posix/uio.pxd +26 -0
  217. Cython/Includes/posix/unistd.pxd +271 -0
  218. Cython/Includes/posix/wait.pxd +38 -0
  219. Cython/Plex/Actions.pxd +24 -0
  220. Cython/Plex/Actions.py +119 -0
  221. Cython/Plex/DFA.pxd +14 -0
  222. Cython/Plex/DFA.py +164 -0
  223. Cython/Plex/Errors.py +48 -0
  224. Cython/Plex/Lexicons.py +178 -0
  225. Cython/Plex/Machines.pxd +36 -0
  226. Cython/Plex/Machines.py +238 -0
  227. Cython/Plex/Regexps.py +539 -0
  228. Cython/Plex/Scanners.pxd +47 -0
  229. Cython/Plex/Scanners.py +360 -0
  230. Cython/Plex/Transitions.pxd +14 -0
  231. Cython/Plex/Transitions.py +239 -0
  232. Cython/Plex/__init__.py +34 -0
  233. Cython/Runtime/__init__.py +1 -0
  234. Cython/Runtime/refnanny.pyx +261 -0
  235. Cython/Shadow.py +656 -0
  236. Cython/Shadow.pyi +521 -0
  237. Cython/StringIOTree.py +170 -0
  238. Cython/Tempita/__init__.py +4 -0
  239. Cython/Tempita/_looper.py +154 -0
  240. Cython/Tempita/_tempita.py +1091 -0
  241. Cython/TestUtils.py +417 -0
  242. Cython/Tests/TestCodeWriter.py +128 -0
  243. Cython/Tests/TestCythonUtils.py +202 -0
  244. Cython/Tests/TestJediTyper.py +223 -0
  245. Cython/Tests/TestShadow.py +114 -0
  246. Cython/Tests/TestStringIOTree.py +67 -0
  247. Cython/Tests/TestTestUtils.py +90 -0
  248. Cython/Tests/__init__.py +1 -0
  249. Cython/Tests/xmlrunner.py +390 -0
  250. Cython/Utility/AsyncGen.c +1263 -0
  251. Cython/Utility/Buffer.c +875 -0
  252. Cython/Utility/Builtins.c +660 -0
  253. Cython/Utility/CConvert.pyx +134 -0
  254. Cython/Utility/CMath.c +95 -0
  255. Cython/Utility/CommonStructures.c +139 -0
  256. Cython/Utility/Complex.c +378 -0
  257. Cython/Utility/Coroutine.c +2413 -0
  258. Cython/Utility/CpdefEnums.pyx +108 -0
  259. Cython/Utility/CppConvert.pyx +279 -0
  260. Cython/Utility/CppSupport.cpp +133 -0
  261. Cython/Utility/CythonFunction.c +1851 -0
  262. Cython/Utility/Dataclasses.c +185 -0
  263. Cython/Utility/Dataclasses.py +112 -0
  264. Cython/Utility/Embed.c +125 -0
  265. Cython/Utility/Exceptions.c +1017 -0
  266. Cython/Utility/ExtensionTypes.c +797 -0
  267. Cython/Utility/FunctionArguments.c +573 -0
  268. Cython/Utility/ImportExport.c +912 -0
  269. Cython/Utility/MemoryView.pyx +1478 -0
  270. Cython/Utility/MemoryView_C.c +992 -0
  271. Cython/Utility/ModuleSetupCode.c +2501 -0
  272. Cython/Utility/NumpyImportArray.c +46 -0
  273. Cython/Utility/ObjectHandling.c +3054 -0
  274. Cython/Utility/Optimize.c +1533 -0
  275. Cython/Utility/Overflow.c +404 -0
  276. Cython/Utility/Printing.c +86 -0
  277. Cython/Utility/Profile.c +660 -0
  278. Cython/Utility/StringTools.c +1206 -0
  279. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  280. Cython/Utility/TestCythonScope.pyx +75 -0
  281. Cython/Utility/TestUtilityLoader.c +12 -0
  282. Cython/Utility/TypeConversion.c +1329 -0
  283. Cython/Utility/UFuncs.pyx +50 -0
  284. Cython/Utility/UFuncs_C.c +89 -0
  285. Cython/Utility/__init__.py +28 -0
  286. Cython/Utility/arrayarray.h +143 -0
  287. Cython/Utils.py +687 -0
  288. Cython/__init__.py +10 -0
  289. Cython/__init__.pyi +7 -0
  290. Cython/py.typed +0 -0
  291. Cython-3.1.0a1.dist-info/COPYING.txt +19 -0
  292. Cython-3.1.0a1.dist-info/LICENSE.txt +176 -0
  293. Cython-3.1.0a1.dist-info/METADATA +67 -0
  294. Cython-3.1.0a1.dist-info/RECORD +301 -0
  295. Cython-3.1.0a1.dist-info/WHEEL +5 -0
  296. Cython-3.1.0a1.dist-info/entry_points.txt +4 -0
  297. Cython-3.1.0a1.dist-info/top_level.txt +3 -0
  298. cython.py +29 -0
  299. pyximport/__init__.py +4 -0
  300. pyximport/pyxbuild.py +160 -0
  301. pyximport/pyximport.py +482 -0
@@ -0,0 +1 @@
1
+ # empty file
Cython/Coverage.py ADDED
@@ -0,0 +1,443 @@
1
+ """
2
+ A Cython plugin for coverage.py
3
+
4
+ Requires the coverage package at least in version 4.0 (which added the plugin API).
5
+
6
+ This plugin requires the generated C sources to be available, next to the extension module.
7
+ It parses the C file and reads the original source files from it, which are stored in C comments.
8
+ It then reports a source file to coverage.py when it hits one of its lines during line tracing.
9
+
10
+ Basically, Cython can (on request) emit explicit trace calls into the C code that it generates,
11
+ and as a general human debugging helper, it always copies the current source code line
12
+ (and its surrounding context) into the C files before it generates code for that line, e.g.
13
+
14
+ ::
15
+
16
+ /* "line_trace.pyx":147
17
+ * def cy_add_with_nogil(a,b):
18
+ * cdef int z, x=a, y=b # 1
19
+ * with nogil: # 2 # <<<<<<<<<<<<<<
20
+ * z = 0 # 3
21
+ * z += cy_add_nogil(x, y) # 4
22
+ */
23
+ __Pyx_TraceLine(147,6,1,__PYX_ERR(0, 147, __pyx_L4_error))
24
+ [C code generated for file line_trace.pyx, line 147, follows here]
25
+
26
+ The crux is that multiple source files can contribute code to a single C (or C++) file
27
+ (and thus, to a single extension module) besides the main module source file (.py/.pyx),
28
+ usually shared declaration files (.pxd) but also literally included files (.pxi).
29
+
30
+ Therefore, the coverage plugin doesn't actually try to look at the file that happened
31
+ to contribute the current source line for the trace call, but simply looks up the single
32
+ .c file from which the extension was compiled (which usually lies right next to it after
33
+ the build, having the same name), and parses the code copy comments from that .c file
34
+ to recover the original source files and their code as a line-to-file mapping.
35
+
36
+ That mapping is then used to report the ``__Pyx_TraceLine()`` calls to the coverage tool.
37
+ The plugin also reports the line of source code that it found in the C file to the coverage
38
+ tool to support annotated source representations. For this, again, it does not look at the
39
+ actual source files but only reports the source code that it found in the C code comments.
40
+
41
+ Apart from simplicity (read one file instead of finding and parsing many), part of the
42
+ reasoning here is that any line in the original sources for which there is no comment line
43
+ (and trace call) in the generated C code cannot count as executed, really, so the C code
44
+ comments are a very good source for coverage reporting. They already filter out purely
45
+ declarative code lines that do not contribute executable code, and such (missing) lines
46
+ can then be marked as excluded from coverage analysis.
47
+ """
48
+
49
+
50
+ import re
51
+ import os.path
52
+ import sys
53
+ from collections import defaultdict
54
+
55
+ from coverage.plugin import CoveragePlugin, FileTracer, FileReporter # requires coverage.py 4.0+
56
+ from coverage.files import canonical_filename
57
+
58
+ from .Utils import find_root_package_dir, is_package_dir, is_cython_generated_file, open_source_file
59
+
60
+
61
+ from . import __version__
62
+
63
+
64
+ C_FILE_EXTENSIONS = ['.c', '.cpp', '.cc', '.cxx']
65
+ MODULE_FILE_EXTENSIONS = set(['.py', '.pyx', '.pxd'] + C_FILE_EXTENSIONS)
66
+
67
+
68
+ def _find_c_source(base_path):
69
+ file_exists = os.path.exists
70
+ for ext in C_FILE_EXTENSIONS:
71
+ file_name = base_path + ext
72
+ if file_exists(file_name):
73
+ return file_name
74
+ return None
75
+
76
+
77
+ def _find_dep_file_path(main_file, file_path, relative_path_search=False):
78
+ abs_path = os.path.abspath(file_path)
79
+ if not os.path.exists(abs_path) and (file_path.endswith('.pxi') or
80
+ relative_path_search):
81
+ # files are looked up relative to the main source file
82
+ rel_file_path = os.path.join(os.path.dirname(main_file), file_path)
83
+ if os.path.exists(rel_file_path):
84
+ abs_path = os.path.abspath(rel_file_path)
85
+
86
+ abs_no_ext = os.path.splitext(abs_path)[0]
87
+ file_no_ext, extension = os.path.splitext(file_path)
88
+ # We check if the paths match by matching the directories in reverse order.
89
+ # pkg/module.pyx /long/absolute_path/bla/bla/site-packages/pkg/module.c should match.
90
+ # this will match the pairs: module-module and pkg-pkg. After which there is nothing left to zip.
91
+ abs_no_ext = os.path.normpath(abs_no_ext)
92
+ file_no_ext = os.path.normpath(file_no_ext)
93
+ matching_paths = zip(reversed(abs_no_ext.split(os.sep)), reversed(file_no_ext.split(os.sep)))
94
+ for one, other in matching_paths:
95
+ if one != other:
96
+ break
97
+ else: # No mismatches detected
98
+ matching_abs_path = os.path.splitext(main_file)[0] + extension
99
+ if os.path.exists(matching_abs_path):
100
+ return canonical_filename(matching_abs_path)
101
+
102
+ # search sys.path for external locations if a valid file hasn't been found
103
+ if not os.path.exists(abs_path):
104
+ for sys_path in sys.path:
105
+ test_path = os.path.realpath(os.path.join(sys_path, file_path))
106
+ if os.path.exists(test_path):
107
+ return canonical_filename(test_path)
108
+ return canonical_filename(abs_path)
109
+
110
+
111
+ def _offset_to_line(offset):
112
+ return offset >> 9
113
+
114
+
115
+ class Plugin(CoveragePlugin):
116
+ # map from traced file paths to absolute file paths
117
+ _file_path_map = None
118
+ # map from traced file paths to corresponding C files
119
+ _c_files_map = None
120
+ # map from parsed C files to their content
121
+ _parsed_c_files = None
122
+ # map from traced files to lines that are excluded from coverage
123
+ _excluded_lines_map = None
124
+ # list of regex patterns for lines to exclude
125
+ _excluded_line_patterns = ()
126
+
127
+ def sys_info(self):
128
+ return [('Cython version', __version__)]
129
+
130
+ def configure(self, config):
131
+ # Entry point for coverage "configurer".
132
+ # Read the regular expressions from the coverage config that match lines to be excluded from coverage.
133
+ self._excluded_line_patterns = config.get_option("report:exclude_lines")
134
+
135
+ def file_tracer(self, filename):
136
+ """
137
+ Try to find a C source file for a file path found by the tracer.
138
+ """
139
+ if filename.startswith('<') or filename.startswith('memory:'):
140
+ return None
141
+ c_file = py_file = None
142
+ filename = canonical_filename(os.path.abspath(filename))
143
+ if self._c_files_map and filename in self._c_files_map:
144
+ c_file = self._c_files_map[filename][0]
145
+
146
+ if c_file is None:
147
+ c_file, py_file = self._find_source_files(filename)
148
+ if not c_file:
149
+ return None # unknown file
150
+
151
+ # parse all source file paths and lines from C file
152
+ # to learn about all relevant source files right away (pyx/pxi/pxd)
153
+ # FIXME: this might already be too late if the first executed line
154
+ # is not from the main .pyx file but a file with a different
155
+ # name than the .c file (which prevents us from finding the
156
+ # .c file)
157
+ _, code = self._read_source_lines(c_file, filename)
158
+ if code is None:
159
+ return None # no source found
160
+
161
+ if self._file_path_map is None:
162
+ self._file_path_map = {}
163
+ return CythonModuleTracer(filename, py_file, c_file, self._c_files_map, self._file_path_map)
164
+
165
+ def file_reporter(self, filename):
166
+ # TODO: let coverage.py handle .py files itself
167
+ #ext = os.path.splitext(filename)[1].lower()
168
+ #if ext == '.py':
169
+ # from coverage.python import PythonFileReporter
170
+ # return PythonFileReporter(filename)
171
+
172
+ filename = canonical_filename(os.path.abspath(filename))
173
+ if self._c_files_map and filename in self._c_files_map:
174
+ c_file, rel_file_path, code = self._c_files_map[filename]
175
+ else:
176
+ c_file, _ = self._find_source_files(filename)
177
+ if not c_file:
178
+ return None # unknown file
179
+ rel_file_path, code = self._read_source_lines(c_file, filename)
180
+ if code is None:
181
+ return None # no source found
182
+ return CythonModuleReporter(
183
+ c_file,
184
+ filename,
185
+ rel_file_path,
186
+ code,
187
+ self._excluded_lines_map.get(rel_file_path, frozenset())
188
+ )
189
+
190
+ def _find_source_files(self, filename):
191
+ basename, ext = os.path.splitext(filename)
192
+ ext = ext.lower()
193
+ if ext in MODULE_FILE_EXTENSIONS:
194
+ pass
195
+ elif ext == '.pyd':
196
+ # Windows extension module
197
+ platform_suffix = re.search(r'[.]cp[0-9]+-win[_a-z0-9]*$', basename, re.I)
198
+ if platform_suffix:
199
+ basename = basename[:platform_suffix.start()]
200
+ elif ext == '.so':
201
+ # Linux/Unix/Mac extension module
202
+ platform_suffix = re.search(r'[.](?:cpython|pypy)-[0-9]+[-_a-z0-9]*$', basename, re.I)
203
+ if platform_suffix:
204
+ basename = basename[:platform_suffix.start()]
205
+ elif ext == '.pxi':
206
+ # if we get here, it means that the first traced line of a Cython module was
207
+ # not in the main module but in an include file, so try a little harder to
208
+ # find the main source file
209
+ self._find_c_source_files(os.path.dirname(filename), filename)
210
+ if filename in self._c_files_map:
211
+ return self._c_files_map[filename][0], None
212
+ else:
213
+ # none of our business
214
+ return None, None
215
+
216
+ c_file = filename if ext in C_FILE_EXTENSIONS else _find_c_source(basename)
217
+ if c_file is None:
218
+ # a module "pkg/mod.so" can have a source file "pkg/pkg.mod.c"
219
+ package_root = find_root_package_dir.uncached(filename)
220
+ package_path = os.path.relpath(basename, package_root).split(os.path.sep)
221
+ if len(package_path) > 1:
222
+ test_basepath = os.path.join(os.path.dirname(filename), '.'.join(package_path))
223
+ c_file = _find_c_source(test_basepath)
224
+
225
+ py_source_file = None
226
+ if c_file:
227
+ py_source_file = os.path.splitext(c_file)[0] + '.py'
228
+ if not os.path.exists(py_source_file):
229
+ py_source_file = None
230
+ if not is_cython_generated_file(c_file, if_not_found=False):
231
+ if py_source_file and os.path.exists(c_file):
232
+ # if we did not generate the C file,
233
+ # then we probably also shouldn't care about the .py file.
234
+ py_source_file = None
235
+ c_file = None
236
+
237
+ return c_file, py_source_file
238
+
239
+ def _find_c_source_files(self, dir_path, source_file):
240
+ """
241
+ Desperately parse all C files in the directory or its package parents
242
+ (not re-descending) to find the (included) source file in one of them.
243
+ """
244
+ if not os.path.isdir(dir_path):
245
+ return
246
+ splitext = os.path.splitext
247
+ for filename in os.listdir(dir_path):
248
+ ext = splitext(filename)[1].lower()
249
+ if ext in C_FILE_EXTENSIONS:
250
+ self._read_source_lines(os.path.join(dir_path, filename), source_file)
251
+ if source_file in self._c_files_map:
252
+ return
253
+ # not found? then try one package up
254
+ if is_package_dir(dir_path):
255
+ self._find_c_source_files(os.path.dirname(dir_path), source_file)
256
+
257
+ def _read_source_lines(self, c_file, sourcefile):
258
+ """
259
+ Parse a Cython generated C/C++ source file and find the executable lines.
260
+ Each executable line starts with a comment header that states source file
261
+ and line number, as well as the surrounding range of source code lines.
262
+ """
263
+ if self._parsed_c_files is None:
264
+ self._parsed_c_files = {}
265
+ if c_file in self._parsed_c_files:
266
+ code_lines = self._parsed_c_files[c_file]
267
+ else:
268
+ code_lines = self._parse_cfile_lines(c_file)
269
+ self._parsed_c_files[c_file] = code_lines
270
+
271
+ if self._c_files_map is None:
272
+ self._c_files_map = {}
273
+
274
+ for filename, code in code_lines.items():
275
+ abs_path = _find_dep_file_path(c_file, filename,
276
+ relative_path_search=True)
277
+ self._c_files_map[abs_path] = (c_file, filename, code)
278
+
279
+ if sourcefile not in self._c_files_map:
280
+ return (None,) * 2 # e.g. shared library file
281
+ return self._c_files_map[sourcefile][1:]
282
+
283
+ def _parse_cfile_lines(self, c_file):
284
+ """
285
+ Parse a C file and extract all source file lines that generated executable code.
286
+ """
287
+ match_source_path_line = re.compile(r' */[*] +"(.*)":([0-9]+)$').match
288
+ match_current_code_line = re.compile(r' *[*] (.*) # <<<<<<+$').match
289
+ match_comment_end = re.compile(r' *[*]/$').match
290
+ match_trace_line = re.compile(r' *__Pyx_TraceLine\(([0-9]+),').match
291
+ not_executable = re.compile(
292
+ r'\s*c(?:type)?def\s+'
293
+ r'(?:(?:public|external)\s+)?'
294
+ r'(?:struct|union|enum|class)'
295
+ r'(\s+[^:]+|)\s*:'
296
+ ).match
297
+ if self._excluded_line_patterns:
298
+ line_is_excluded = re.compile("|".join(["(?:%s)" % regex for regex in self._excluded_line_patterns])).search
299
+ else:
300
+ line_is_excluded = lambda line: False
301
+
302
+ code_lines = defaultdict(dict)
303
+ executable_lines = defaultdict(set)
304
+ current_filename = None
305
+ if self._excluded_lines_map is None:
306
+ self._excluded_lines_map = defaultdict(set)
307
+
308
+ with open(c_file, encoding='utf8') as lines:
309
+ lines = iter(lines)
310
+ for line in lines:
311
+ match = match_source_path_line(line)
312
+ if not match:
313
+ if '__Pyx_TraceLine(' in line and current_filename is not None:
314
+ trace_line = match_trace_line(line)
315
+ if trace_line:
316
+ lineno = int(trace_line.group(1))
317
+ executable_lines[current_filename].add(lineno)
318
+ continue
319
+ filename, lineno = match.groups()
320
+ current_filename = filename
321
+ lineno = int(lineno)
322
+ for comment_line in lines:
323
+ match = match_current_code_line(comment_line)
324
+ if match:
325
+ code_line = match.group(1).rstrip()
326
+ if not_executable(code_line):
327
+ break
328
+ if line_is_excluded(code_line):
329
+ self._excluded_lines_map[filename].add(lineno)
330
+ break
331
+ code_lines[filename][lineno] = code_line
332
+ break
333
+ elif match_comment_end(comment_line):
334
+ # unexpected comment format - false positive?
335
+ break
336
+
337
+ # Remove lines that generated code but are not traceable.
338
+ for filename, lines in code_lines.items():
339
+ dead_lines = set(lines).difference(executable_lines.get(filename, ()))
340
+ for lineno in dead_lines:
341
+ del lines[lineno]
342
+ return code_lines
343
+
344
+
345
+ class CythonModuleTracer(FileTracer):
346
+ """
347
+ Find the Python/Cython source file for a Cython module.
348
+ """
349
+ def __init__(self, module_file, py_file, c_file, c_files_map, file_path_map):
350
+ super().__init__()
351
+ self.module_file = module_file
352
+ self.py_file = py_file
353
+ self.c_file = c_file
354
+ self._c_files_map = c_files_map
355
+ self._file_path_map = file_path_map
356
+
357
+ def has_dynamic_source_filename(self):
358
+ return True
359
+
360
+ def dynamic_source_filename(self, filename, frame):
361
+ """
362
+ Determine source file path. Called by the function call tracer.
363
+ """
364
+ source_file = frame.f_code.co_filename
365
+ try:
366
+ return self._file_path_map[source_file]
367
+ except KeyError:
368
+ pass
369
+ abs_path = _find_dep_file_path(filename, source_file)
370
+
371
+ if self.py_file and source_file[-3:].lower() == '.py':
372
+ # always let coverage.py handle this case itself
373
+ self._file_path_map[source_file] = self.py_file
374
+ return self.py_file
375
+
376
+ assert self._c_files_map is not None
377
+ if abs_path not in self._c_files_map:
378
+ self._c_files_map[abs_path] = (self.c_file, source_file, None)
379
+ self._file_path_map[source_file] = abs_path
380
+ return abs_path
381
+
382
+
383
+ class CythonModuleReporter(FileReporter):
384
+ """
385
+ Provide detailed trace information for one source file to coverage.py.
386
+ """
387
+ def __init__(self, c_file, source_file, rel_file_path, code, excluded_lines):
388
+ super().__init__(source_file)
389
+ self.name = rel_file_path
390
+ self.c_file = c_file
391
+ self._code = code
392
+ self._excluded_lines = excluded_lines
393
+
394
+ def lines(self):
395
+ """
396
+ Return set of line numbers that are possibly executable.
397
+ """
398
+ return set(self._code)
399
+
400
+ def excluded_lines(self):
401
+ """
402
+ Return set of line numbers that are excluded from coverage.
403
+ """
404
+ return self._excluded_lines
405
+
406
+ def _iter_source_tokens(self):
407
+ current_line = 1
408
+ for line_no, code_line in sorted(self._code.items()):
409
+ while line_no > current_line:
410
+ yield []
411
+ current_line += 1
412
+ yield [('txt', code_line)]
413
+ current_line += 1
414
+
415
+ def source(self):
416
+ """
417
+ Return the source code of the file as a string.
418
+ """
419
+ if os.path.exists(self.filename):
420
+ with open_source_file(self.filename) as f:
421
+ return f.read()
422
+ else:
423
+ return '\n'.join(
424
+ (tokens[0][1] if tokens else '')
425
+ for tokens in self._iter_source_tokens())
426
+
427
+ def source_token_lines(self):
428
+ """
429
+ Iterate over the source code tokens.
430
+ """
431
+ if os.path.exists(self.filename):
432
+ with open_source_file(self.filename) as f:
433
+ for line in f:
434
+ yield [('txt', line.rstrip('\n'))]
435
+ else:
436
+ for line in self._iter_source_tokens():
437
+ yield [('txt', line)]
438
+
439
+
440
+ def coverage_init(reg, options):
441
+ plugin = Plugin()
442
+ reg.add_configurer(plugin)
443
+ reg.add_file_tracer(plugin)
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ The Cython debugger
5
+
6
+ The current directory should contain a directory named 'cython_debug', or a
7
+ path to the cython project directory should be given (the parent directory of
8
+ cython_debug).
9
+
10
+ Additional gdb args can be provided only if a path to the project directory is
11
+ given.
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import glob
17
+ import tempfile
18
+ import textwrap
19
+ import subprocess
20
+ import optparse
21
+ import logging
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def make_command_file(path_to_debug_info, prefix_code='',
27
+ no_import=False, skip_interpreter=False):
28
+ if not no_import:
29
+ pattern = os.path.join(path_to_debug_info,
30
+ 'cython_debug',
31
+ 'cython_debug_info_*')
32
+ debug_files = glob.glob(pattern)
33
+
34
+ if not debug_files:
35
+ sys.exit('%s.\nNo debug files were found in %s. Aborting.' % (
36
+ usage, os.path.abspath(path_to_debug_info)))
37
+
38
+ fd, tempfilename = tempfile.mkstemp()
39
+ f = os.fdopen(fd, 'w')
40
+ try:
41
+ f.write(prefix_code)
42
+ f.write(textwrap.dedent('''\
43
+ # This is a gdb command file
44
+ # See https://sourceware.org/gdb/onlinedocs/gdb/Command-Files.html
45
+
46
+ set breakpoint pending on
47
+ set print pretty on
48
+
49
+ python
50
+ try:
51
+ # Activate virtualenv, if we were launched from one
52
+ import os
53
+ virtualenv = os.getenv('VIRTUAL_ENV')
54
+ if virtualenv:
55
+ path_to_activate_this_py = os.path.join(virtualenv, 'bin', 'activate_this.py')
56
+ print("gdb command file: Activating virtualenv: %s; path_to_activate_this_py: %s" % (
57
+ virtualenv, path_to_activate_this_py))
58
+ with open(path_to_activate_this_py) as f:
59
+ exec(f.read(), dict(__file__=path_to_activate_this_py))
60
+ from Cython.Debugger import libcython, libpython
61
+ except Exception as ex:
62
+ from traceback import print_exc
63
+ print("There was an error in Python code originating from the file ''' + str(__file__) + '''")
64
+ print("It used the Python interpreter " + str(sys.executable))
65
+ print_exc()
66
+ exit(1)
67
+ end
68
+ '''))
69
+
70
+ if no_import:
71
+ # don't do this, this overrides file command in .gdbinit
72
+ # f.write("file %s\n" % sys.executable)
73
+ pass
74
+ else:
75
+ if not skip_interpreter:
76
+ # Point Cygdb to the interpreter that was used to generate
77
+ # the debugging information.
78
+ path = os.path.join(path_to_debug_info, "cython_debug", "interpreter")
79
+ interpreter_file = open(path)
80
+ try:
81
+ interpreter = interpreter_file.read()
82
+ finally:
83
+ interpreter_file.close()
84
+ f.write("file %s\n" % interpreter)
85
+
86
+ f.write('\n'.join('cy import %s\n' % fn for fn in debug_files))
87
+
88
+ if not skip_interpreter:
89
+ f.write(textwrap.dedent('''\
90
+ python
91
+ import sys
92
+ # Check if the Python executable provides a symbol table.
93
+ if not hasattr(gdb.selected_inferior().progspace, "symbol_file"):
94
+ sys.stderr.write(
95
+ "''' + interpreter + ''' was not compiled with debug symbols (or it was "
96
+ "stripped). Some functionality may not work (properly).\\n")
97
+ end
98
+ '''))
99
+
100
+ f.write("source .cygdbinit\n")
101
+ finally:
102
+ f.close()
103
+
104
+ return tempfilename
105
+
106
+ usage = "Usage: cygdb [options] [PATH [-- GDB_ARGUMENTS]]"
107
+
108
+ def main(path_to_debug_info=None, gdb_argv=None, no_import=False):
109
+ """
110
+ Start the Cython debugger. This tells gdb to import the Cython and Python
111
+ extensions (libcython.py and libpython.py) and it enables gdb's pending
112
+ breakpoints.
113
+
114
+ path_to_debug_info is the path to the Cython build directory
115
+ gdb_argv is the list of options to gdb
116
+ no_import tells cygdb whether it should import debug information
117
+ """
118
+ parser = optparse.OptionParser(usage=usage)
119
+ parser.add_option("--gdb-executable",
120
+ dest="gdb", default='gdb',
121
+ help="gdb executable to use [default: gdb]")
122
+ parser.add_option("--verbose", "-v",
123
+ dest="verbosity", action="count", default=0,
124
+ help="Verbose mode. Multiple -v options increase the verbosity")
125
+ parser.add_option("--skip-interpreter",
126
+ dest="skip_interpreter", default=False, action="store_true",
127
+ help="Do not automatically point GDB to the same interpreter "
128
+ "used to generate debugging information")
129
+
130
+ (options, args) = parser.parse_args()
131
+ if path_to_debug_info is None:
132
+ if len(args) > 1:
133
+ path_to_debug_info = args[0]
134
+ else:
135
+ path_to_debug_info = os.curdir
136
+
137
+ if gdb_argv is None:
138
+ gdb_argv = args[1:]
139
+
140
+ if path_to_debug_info == '--':
141
+ no_import = True
142
+
143
+ logging_level = logging.WARN
144
+ if options.verbosity == 1:
145
+ logging_level = logging.INFO
146
+ if options.verbosity >= 2:
147
+ logging_level = logging.DEBUG
148
+ logging.basicConfig(level=logging_level)
149
+
150
+ skip_interpreter = options.skip_interpreter
151
+
152
+ logger.info("verbosity = %r", options.verbosity)
153
+ logger.debug("options = %r; args = %r", options, args)
154
+ logger.debug("Done parsing command-line options. path_to_debug_info = %r, gdb_argv = %r",
155
+ path_to_debug_info, gdb_argv)
156
+
157
+ tempfilename = make_command_file(path_to_debug_info,
158
+ no_import=no_import,
159
+ skip_interpreter=skip_interpreter)
160
+ logger.info("Launching %s with command file: %s and gdb_argv: %s",
161
+ options.gdb, tempfilename, gdb_argv)
162
+ with open(tempfilename) as tempfile:
163
+ logger.debug('Command file (%s) contains: """\n%s"""', tempfilename, tempfile.read())
164
+ logger.info("Spawning %s...", options.gdb)
165
+ p = subprocess.Popen([options.gdb, '-command', tempfilename] + gdb_argv)
166
+ logger.info("Spawned %s (pid %d)", options.gdb, p.pid)
167
+ while True:
168
+ try:
169
+ logger.debug("Waiting for gdb (pid %d) to exit...", p.pid)
170
+ ret = p.wait()
171
+ logger.debug("Wait for gdb (pid %d) to exit is done. Returned: %r", p.pid, ret)
172
+ except KeyboardInterrupt:
173
+ pass
174
+ else:
175
+ break
176
+ logger.debug("Closing temp command file with fd: %s", tempfile.fileno())
177
+ logger.debug("Removing temp command file: %s", tempfilename)
178
+ os.remove(tempfilename)
179
+ logger.debug("Removed temp command file: %s", tempfilename)