Cython 3.3.0__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. Cython/Build/BuildExecutable.py +156 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +349 -0
  4. Cython/Build/Dependencies.py +1281 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +467 -0
  7. Cython/Build/IpythonMagic.py +559 -0
  8. Cython/Build/SharedModule.py +165 -0
  9. Cython/Build/Tests/TestCyCache.py +195 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +480 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +303 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +825 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +679 -0
  23. Cython/Compiler/Builtin.py +1102 -0
  24. Cython/Compiler/CmdLine.py +373 -0
  25. Cython/Compiler/Code.cp315-win_amd64.pyd +0 -0
  26. Cython/Compiler/Code.pxd +154 -0
  27. Cython/Compiler/Code.py +3760 -0
  28. Cython/Compiler/CodeGeneration.py +33 -0
  29. Cython/Compiler/CythonScope.py +208 -0
  30. Cython/Compiler/Dataclass.py +890 -0
  31. Cython/Compiler/DebugFlags.py +24 -0
  32. Cython/Compiler/Errors.py +310 -0
  33. Cython/Compiler/ExprNodes.py +16273 -0
  34. Cython/Compiler/FlowControl.cp315-win_amd64.pyd +0 -0
  35. Cython/Compiler/FlowControl.pxd +112 -0
  36. Cython/Compiler/FlowControl.py +1573 -0
  37. Cython/Compiler/FusedNode.cp315-win_amd64.pyd +0 -0
  38. Cython/Compiler/FusedNode.py +978 -0
  39. Cython/Compiler/Future.py +16 -0
  40. Cython/Compiler/Interpreter.py +57 -0
  41. Cython/Compiler/Lexicon.py +422 -0
  42. Cython/Compiler/LineTable.cp315-win_amd64.pyd +0 -0
  43. Cython/Compiler/LineTable.py +114 -0
  44. Cython/Compiler/Main.py +856 -0
  45. Cython/Compiler/MatchCaseNodes.py +2200 -0
  46. Cython/Compiler/MemoryView.py +930 -0
  47. Cython/Compiler/ModuleNode.py +4548 -0
  48. Cython/Compiler/Naming.py +370 -0
  49. Cython/Compiler/Nodes.py +11304 -0
  50. Cython/Compiler/Optimize.py +5564 -0
  51. Cython/Compiler/Options.py +840 -0
  52. Cython/Compiler/ParseTreeTransforms.pxd +80 -0
  53. Cython/Compiler/ParseTreeTransforms.py +4808 -0
  54. Cython/Compiler/Parsing.cp315-win_amd64.pyd +0 -0
  55. Cython/Compiler/Parsing.pxd +9 -0
  56. Cython/Compiler/Parsing.py +4809 -0
  57. Cython/Compiler/Pipeline.py +439 -0
  58. Cython/Compiler/PyrexTypes.py +6588 -0
  59. Cython/Compiler/Pythran.py +232 -0
  60. Cython/Compiler/Scanning.cp315-win_amd64.pyd +0 -0
  61. Cython/Compiler/Scanning.pxd +70 -0
  62. Cython/Compiler/Scanning.py +720 -0
  63. Cython/Compiler/StringEncoding.cp315-win_amd64.pyd +0 -0
  64. Cython/Compiler/StringEncoding.py +354 -0
  65. Cython/Compiler/Symtab.py +3121 -0
  66. Cython/Compiler/Tests/TestBuffer.py +105 -0
  67. Cython/Compiler/Tests/TestBuiltin.py +196 -0
  68. Cython/Compiler/Tests/TestCmdLine.py +652 -0
  69. Cython/Compiler/Tests/TestCode.py +145 -0
  70. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  71. Cython/Compiler/Tests/TestGrammar.py +202 -0
  72. Cython/Compiler/Tests/TestMemView.py +71 -0
  73. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  74. Cython/Compiler/Tests/TestScanning.py +132 -0
  75. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  76. Cython/Compiler/Tests/TestStringEncoding.py +20 -0
  77. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  78. Cython/Compiler/Tests/TestTreePath.py +103 -0
  79. Cython/Compiler/Tests/TestTypes.py +119 -0
  80. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  81. Cython/Compiler/Tests/TestVisitor.py +119 -0
  82. Cython/Compiler/Tests/Utils.py +36 -0
  83. Cython/Compiler/Tests/__init__.py +1 -0
  84. Cython/Compiler/TreeFragment.py +279 -0
  85. Cython/Compiler/TreePath.py +303 -0
  86. Cython/Compiler/TypeInference.py +611 -0
  87. Cython/Compiler/TypeSlots.py +1329 -0
  88. Cython/Compiler/UFuncs.py +317 -0
  89. Cython/Compiler/UtilNodes.py +389 -0
  90. Cython/Compiler/UtilityCode.py +354 -0
  91. Cython/Compiler/Version.py +8 -0
  92. Cython/Compiler/Visitor.cp315-win_amd64.pyd +0 -0
  93. Cython/Compiler/Visitor.pxd +52 -0
  94. Cython/Compiler/Visitor.py +914 -0
  95. Cython/Compiler/__init__.py +1 -0
  96. Cython/Coverage.py +448 -0
  97. Cython/Debugger/Cygdb.py +214 -0
  98. Cython/Debugger/DebugWriter.py +82 -0
  99. Cython/Debugger/Tests/TestLibCython.py +280 -0
  100. Cython/Debugger/Tests/__init__.py +1 -0
  101. Cython/Debugger/Tests/cfuncs.c +8 -0
  102. Cython/Debugger/Tests/codefile +49 -0
  103. Cython/Debugger/Tests/test_libcython_in_gdb.py +580 -0
  104. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  105. Cython/Debugger/__init__.py +1 -0
  106. Cython/Debugger/libcython.py +1548 -0
  107. Cython/Debugger/libpython.py +2821 -0
  108. Cython/Debugging.py +20 -0
  109. Cython/Distutils/__init__.py +2 -0
  110. Cython/Distutils/build_ext.py +143 -0
  111. Cython/Distutils/extension.py +96 -0
  112. Cython/Distutils/old_build_ext.py +351 -0
  113. Cython/Includes/cpython/__init__.pxd +173 -0
  114. Cython/Includes/cpython/array.pxd +152 -0
  115. Cython/Includes/cpython/bool.pxd +37 -0
  116. Cython/Includes/cpython/buffer.pxd +112 -0
  117. Cython/Includes/cpython/bytearray.pxd +33 -0
  118. Cython/Includes/cpython/bytes.pxd +200 -0
  119. Cython/Includes/cpython/cellobject.pxd +35 -0
  120. Cython/Includes/cpython/ceval.pxd +8 -0
  121. Cython/Includes/cpython/codecs.pxd +121 -0
  122. Cython/Includes/cpython/complex.pxd +60 -0
  123. Cython/Includes/cpython/contextvars.pxd +145 -0
  124. Cython/Includes/cpython/conversion.pxd +36 -0
  125. Cython/Includes/cpython/datetime.pxd +395 -0
  126. Cython/Includes/cpython/descr.pxd +26 -0
  127. Cython/Includes/cpython/dict.pxd +268 -0
  128. Cython/Includes/cpython/exc.pxd +263 -0
  129. Cython/Includes/cpython/fileobject.pxd +57 -0
  130. Cython/Includes/cpython/float.pxd +56 -0
  131. Cython/Includes/cpython/frozendict.pxd +37 -0
  132. Cython/Includes/cpython/function.pxd +65 -0
  133. Cython/Includes/cpython/genobject.pxd +25 -0
  134. Cython/Includes/cpython/getargs.pxd +12 -0
  135. Cython/Includes/cpython/instance.pxd +25 -0
  136. Cython/Includes/cpython/iterator.pxd +36 -0
  137. Cython/Includes/cpython/iterobject.pxd +24 -0
  138. Cython/Includes/cpython/list.pxd +144 -0
  139. Cython/Includes/cpython/long.pxd +180 -0
  140. Cython/Includes/cpython/longintrepr.pxd +14 -0
  141. Cython/Includes/cpython/mapping.pxd +63 -0
  142. Cython/Includes/cpython/marshal.pxd +66 -0
  143. Cython/Includes/cpython/mem.pxd +120 -0
  144. Cython/Includes/cpython/memoryview.pxd +50 -0
  145. Cython/Includes/cpython/method.pxd +49 -0
  146. Cython/Includes/cpython/module.pxd +208 -0
  147. Cython/Includes/cpython/number.pxd +258 -0
  148. Cython/Includes/cpython/object.pxd +430 -0
  149. Cython/Includes/cpython/pycapsule.pxd +143 -0
  150. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  151. Cython/Includes/cpython/pyport.pxd +8 -0
  152. Cython/Includes/cpython/pystate.pxd +95 -0
  153. Cython/Includes/cpython/pythread.pxd +53 -0
  154. Cython/Includes/cpython/ref.pxd +141 -0
  155. Cython/Includes/cpython/sentinel.pxd +17 -0
  156. Cython/Includes/cpython/sequence.pxd +134 -0
  157. Cython/Includes/cpython/set.pxd +119 -0
  158. Cython/Includes/cpython/slice.pxd +70 -0
  159. Cython/Includes/cpython/time.pxd +129 -0
  160. Cython/Includes/cpython/tuple.pxd +72 -0
  161. Cython/Includes/cpython/type.pxd +146 -0
  162. Cython/Includes/cpython/unicode.pxd +639 -0
  163. Cython/Includes/cpython/version.pxd +32 -0
  164. Cython/Includes/cpython/weakref.pxd +78 -0
  165. Cython/Includes/libc/__init__.pxd +1 -0
  166. Cython/Includes/libc/complex.pxd +35 -0
  167. Cython/Includes/libc/errno.pxd +127 -0
  168. Cython/Includes/libc/float.pxd +43 -0
  169. Cython/Includes/libc/limits.pxd +28 -0
  170. Cython/Includes/libc/locale.pxd +46 -0
  171. Cython/Includes/libc/math.pxd +209 -0
  172. Cython/Includes/libc/setjmp.pxd +10 -0
  173. Cython/Includes/libc/signal.pxd +64 -0
  174. Cython/Includes/libc/stddef.pxd +9 -0
  175. Cython/Includes/libc/stdint.pxd +105 -0
  176. Cython/Includes/libc/stdio.pxd +80 -0
  177. Cython/Includes/libc/stdlib.pxd +72 -0
  178. Cython/Includes/libc/string.pxd +50 -0
  179. Cython/Includes/libc/threads.pxd +234 -0
  180. Cython/Includes/libc/time.pxd +52 -0
  181. Cython/Includes/libcpp/__init__.pxd +4 -0
  182. Cython/Includes/libcpp/algorithm.pxd +320 -0
  183. Cython/Includes/libcpp/any.pxd +16 -0
  184. Cython/Includes/libcpp/atomic.pxd +59 -0
  185. Cython/Includes/libcpp/barrier.pxd +22 -0
  186. Cython/Includes/libcpp/bit.pxd +29 -0
  187. Cython/Includes/libcpp/cast.pxd +12 -0
  188. Cython/Includes/libcpp/cmath.pxd +518 -0
  189. Cython/Includes/libcpp/complex.pxd +106 -0
  190. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  191. Cython/Includes/libcpp/deque.pxd +165 -0
  192. Cython/Includes/libcpp/exception.pxd +216 -0
  193. Cython/Includes/libcpp/execution.pxd +15 -0
  194. Cython/Includes/libcpp/forward_list.pxd +63 -0
  195. Cython/Includes/libcpp/functional.pxd +26 -0
  196. Cython/Includes/libcpp/future.pxd +103 -0
  197. Cython/Includes/libcpp/iterator.pxd +34 -0
  198. Cython/Includes/libcpp/latch.pxd +17 -0
  199. Cython/Includes/libcpp/limits.pxd +61 -0
  200. Cython/Includes/libcpp/list.pxd +117 -0
  201. Cython/Includes/libcpp/map.pxd +252 -0
  202. Cython/Includes/libcpp/memory.pxd +115 -0
  203. Cython/Includes/libcpp/mutex.pxd +387 -0
  204. Cython/Includes/libcpp/numbers.pxd +15 -0
  205. Cython/Includes/libcpp/numeric.pxd +131 -0
  206. Cython/Includes/libcpp/optional.pxd +34 -0
  207. Cython/Includes/libcpp/pair.pxd +1 -0
  208. Cython/Includes/libcpp/queue.pxd +25 -0
  209. Cython/Includes/libcpp/random.pxd +166 -0
  210. Cython/Includes/libcpp/semaphore.pxd +43 -0
  211. Cython/Includes/libcpp/set.pxd +228 -0
  212. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  213. Cython/Includes/libcpp/span.pxd +87 -0
  214. Cython/Includes/libcpp/stack.pxd +11 -0
  215. Cython/Includes/libcpp/stop_token.pxd +117 -0
  216. Cython/Includes/libcpp/string.pxd +355 -0
  217. Cython/Includes/libcpp/string_view.pxd +183 -0
  218. Cython/Includes/libcpp/typeindex.pxd +15 -0
  219. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  220. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  221. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  222. Cython/Includes/libcpp/utility.pxd +30 -0
  223. Cython/Includes/libcpp/vector.pxd +186 -0
  224. Cython/Includes/numpy/math.pxd +150 -0
  225. Cython/Includes/openmp.pxd +50 -0
  226. Cython/Includes/posix/__init__.pxd +1 -0
  227. Cython/Includes/posix/dlfcn.pxd +14 -0
  228. Cython/Includes/posix/fcntl.pxd +86 -0
  229. Cython/Includes/posix/ioctl.pxd +4 -0
  230. Cython/Includes/posix/mman.pxd +101 -0
  231. Cython/Includes/posix/resource.pxd +57 -0
  232. Cython/Includes/posix/select.pxd +21 -0
  233. Cython/Includes/posix/signal.pxd +73 -0
  234. Cython/Includes/posix/stat.pxd +98 -0
  235. Cython/Includes/posix/stdio.pxd +37 -0
  236. Cython/Includes/posix/stdlib.pxd +29 -0
  237. Cython/Includes/posix/strings.pxd +9 -0
  238. Cython/Includes/posix/time.pxd +71 -0
  239. Cython/Includes/posix/types.pxd +30 -0
  240. Cython/Includes/posix/uio.pxd +26 -0
  241. Cython/Includes/posix/unistd.pxd +271 -0
  242. Cython/Includes/posix/wait.pxd +38 -0
  243. Cython/LZSS.cp315-win_amd64.pyd +0 -0
  244. Cython/LZSS.py +184 -0
  245. Cython/Plex/Actions.cp315-win_amd64.pyd +0 -0
  246. Cython/Plex/Actions.pxd +24 -0
  247. Cython/Plex/Actions.py +119 -0
  248. Cython/Plex/DFA.cp315-win_amd64.pyd +0 -0
  249. Cython/Plex/DFA.pxd +14 -0
  250. Cython/Plex/DFA.py +164 -0
  251. Cython/Plex/Errors.py +48 -0
  252. Cython/Plex/Lexicons.py +178 -0
  253. Cython/Plex/Machines.cp315-win_amd64.pyd +0 -0
  254. Cython/Plex/Machines.pxd +36 -0
  255. Cython/Plex/Machines.py +238 -0
  256. Cython/Plex/Regexps.py +535 -0
  257. Cython/Plex/Scanners.cp315-win_amd64.pyd +0 -0
  258. Cython/Plex/Scanners.pxd +45 -0
  259. Cython/Plex/Scanners.py +328 -0
  260. Cython/Plex/Transitions.cp315-win_amd64.pyd +0 -0
  261. Cython/Plex/Transitions.pxd +14 -0
  262. Cython/Plex/Transitions.py +239 -0
  263. Cython/Plex/__init__.py +34 -0
  264. Cython/Runtime/__init__.py +1 -0
  265. Cython/Runtime/refnanny.cp315-win_amd64.pyd +0 -0
  266. Cython/Runtime/refnanny.pyx +237 -0
  267. Cython/Shadow.py +1174 -0
  268. Cython/StringIOTree.cp315-win_amd64.pyd +0 -0
  269. Cython/StringIOTree.py +169 -0
  270. Cython/Tempita/__init__.py +4 -0
  271. Cython/Tempita/_looper.py +154 -0
  272. Cython/Tempita/_tempita.cp315-win_amd64.pyd +0 -0
  273. Cython/Tempita/_tempita.py +1087 -0
  274. Cython/TestUtils.py +472 -0
  275. Cython/Tests/TestCodeWriter.py +128 -0
  276. Cython/Tests/TestCythonUtils.py +202 -0
  277. Cython/Tests/TestJediTyper.py +223 -0
  278. Cython/Tests/TestShadow.py +125 -0
  279. Cython/Tests/TestStringIOTree.py +68 -0
  280. Cython/Tests/TestTestUtils.py +89 -0
  281. Cython/Tests/__init__.py +1 -0
  282. Cython/Tests/xmlrunner.py +390 -0
  283. Cython/Utility/AsyncGen.c +1152 -0
  284. Cython/Utility/Buffer.c +866 -0
  285. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  286. Cython/Utility/Builtins.c +1068 -0
  287. Cython/Utility/CConvert.pyx +153 -0
  288. Cython/Utility/CMath.c +104 -0
  289. Cython/Utility/CommonStructures.c +244 -0
  290. Cython/Utility/Complex.c +378 -0
  291. Cython/Utility/Coroutine.c +2344 -0
  292. Cython/Utility/CpdefEnums.pyx +119 -0
  293. Cython/Utility/CppConvert.pyx +282 -0
  294. Cython/Utility/CppSupport.cpp +151 -0
  295. Cython/Utility/CythonFunction.c +2185 -0
  296. Cython/Utility/Dataclasses.c +101 -0
  297. Cython/Utility/Embed.c +129 -0
  298. Cython/Utility/Exceptions.c +1331 -0
  299. Cython/Utility/Exceptions_Cy.pyx +109 -0
  300. Cython/Utility/ExtensionTypes.c +1199 -0
  301. Cython/Utility/FunctionArguments.c +1052 -0
  302. Cython/Utility/FusedFunction.pyx +44 -0
  303. Cython/Utility/ImportExport.c +972 -0
  304. Cython/Utility/MatchCase.c +981 -0
  305. Cython/Utility/MatchCase_Cy.pyx +12 -0
  306. Cython/Utility/MemoryView.pxd +108 -0
  307. Cython/Utility/MemoryView.pyx +1499 -0
  308. Cython/Utility/MemoryView_C.c +1056 -0
  309. Cython/Utility/ModuleSetupCode.c +3319 -0
  310. Cython/Utility/NumpyImportArray.c +46 -0
  311. Cython/Utility/ObjectHandling.c +3404 -0
  312. Cython/Utility/Optimize.c +2564 -0
  313. Cython/Utility/Overflow.c +378 -0
  314. Cython/Utility/Profile.c +736 -0
  315. Cython/Utility/StringTools.c +1534 -0
  316. Cython/Utility/Synchronization.c +438 -0
  317. Cython/Utility/TString.c +369 -0
  318. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  319. Cython/Utility/TestCythonScope.pyx +75 -0
  320. Cython/Utility/TestUtilityLoader.c +12 -0
  321. Cython/Utility/TypeConversion.c +1588 -0
  322. Cython/Utility/UFuncs.pyx +50 -0
  323. Cython/Utility/UFuncs_C.c +89 -0
  324. Cython/Utility/__init__.py +28 -0
  325. Cython/Utility/arrayarray.h +172 -0
  326. Cython/Utils.cp315-win_amd64.pyd +0 -0
  327. Cython/Utils.py +680 -0
  328. Cython/__init__.py +12 -0
  329. Cython/_shared.cp315-win_amd64.pyd +0 -0
  330. Cython/py.typed +0 -0
  331. cython-3.3.0.dist-info/METADATA +555 -0
  332. cython-3.3.0.dist-info/RECORD +339 -0
  333. cython-3.3.0.dist-info/WHEEL +5 -0
  334. cython-3.3.0.dist-info/entry_points.txt +4 -0
  335. cython-3.3.0.dist-info/top_level.txt +3 -0
  336. cython.py +29 -0
  337. pyximport/__init__.py +4 -0
  338. pyximport/pyxbuild.py +160 -0
  339. pyximport/pyximport.py +482 -0
@@ -0,0 +1,914 @@
1
+ # cython: infer_types=True
2
+
3
+ #
4
+ # Tree visitor and transform framework
5
+ #
6
+
7
+
8
+ import sys
9
+ import inspect
10
+
11
+ from . import TypeSlots
12
+ from . import Builtin
13
+ from . import Nodes
14
+ from . import ExprNodes
15
+ from . import Errors
16
+ from . import DebugFlags
17
+ from . import Future
18
+
19
+ import cython
20
+
21
+
22
+ _PRINTABLE = cython.declare(tuple, (bytes, str, int, float, complex))
23
+
24
+
25
+ class TreeVisitor:
26
+ """
27
+ Base class for writing visitors for a Cython tree, contains utilities for
28
+ recursing such trees using visitors. Each node is
29
+ expected to have a child_attrs iterable containing the names of attributes
30
+ containing child nodes or lists of child nodes. Lists are not considered
31
+ part of the tree structure (i.e. contained nodes are considered direct
32
+ children of the parent node).
33
+
34
+ visit_children visits each of the children of a given node (see the visit_children
35
+ documentation). When recursing the tree using visit_children, an attribute
36
+ access_path is maintained which gives information about the current location
37
+ in the tree as a stack of tuples: (parent_node, attrname, index), representing
38
+ the node, attribute and optional list index that was taken in each step in the path to
39
+ the current node.
40
+
41
+ Example:
42
+
43
+ >>> class SampleNode(object):
44
+ ... child_attrs = ["head", "body"]
45
+ ... def __init__(self, value, head=None, body=None):
46
+ ... self.value = value
47
+ ... self.head = head
48
+ ... self.body = body
49
+ ... def __repr__(self): return "SampleNode(%s)" % self.value
50
+ ...
51
+ >>> tree = SampleNode(0, SampleNode(1), [SampleNode(2), SampleNode(3)])
52
+ >>> class MyVisitor(TreeVisitor):
53
+ ... def visit_SampleNode(self, node):
54
+ ... print("in %s %s" % (node.value, self.access_path))
55
+ ... self.visitchildren(node)
56
+ ... print("out %s" % node.value)
57
+ ...
58
+ >>> MyVisitor().visit(tree)
59
+ in 0 []
60
+ in 1 [(SampleNode(0), 'head', None)]
61
+ out 1
62
+ in 2 [(SampleNode(0), 'body', 0)]
63
+ out 2
64
+ in 3 [(SampleNode(0), 'body', 1)]
65
+ out 3
66
+ out 0
67
+ """
68
+ def __init__(self):
69
+ super().__init__()
70
+ self.dispatch_table = {}
71
+ self.access_path = []
72
+
73
+ def dump_node(self, node):
74
+ ignored = list(node.child_attrs or []) + [
75
+ 'child_attrs', 'pos', 'gil_message', 'cpp_message', 'subexprs']
76
+ values = []
77
+ pos = getattr(node, 'pos', None)
78
+ if pos:
79
+ source = pos[0]
80
+ if source:
81
+ import os.path
82
+ source = os.path.basename(source.get_description())
83
+ values.append('%s:%s:%s' % (source, pos[1], pos[2]))
84
+ attribute_names = dir(node)
85
+ for attr in attribute_names:
86
+ if attr in ignored:
87
+ continue
88
+ if attr.startswith('_') or attr.endswith('_'):
89
+ continue
90
+ try:
91
+ value = getattr(node, attr)
92
+ except AttributeError:
93
+ continue
94
+ if value is None or value == 0:
95
+ continue
96
+ elif isinstance(value, list):
97
+ value = '[...]/%d' % len(value)
98
+ elif not isinstance(value, _PRINTABLE):
99
+ continue
100
+ else:
101
+ value = repr(value)
102
+ values.append('%s = %s' % (attr, value))
103
+ return '%s(%s)' % (node.__class__.__name__, ',\n '.join(values))
104
+
105
+ def _find_node_path(self, stacktrace):
106
+ import os.path
107
+ last_traceback = stacktrace
108
+ nodes = []
109
+ while hasattr(stacktrace, 'tb_frame'):
110
+ frame = stacktrace.tb_frame
111
+ node = frame.f_locals.get('self')
112
+ if isinstance(node, Nodes.Node):
113
+ code = frame.f_code
114
+ method_name = code.co_name
115
+ pos = (os.path.basename(code.co_filename),
116
+ frame.f_lineno)
117
+ nodes.append((node, method_name, pos))
118
+ last_traceback = stacktrace
119
+ stacktrace = stacktrace.tb_next
120
+ return (last_traceback, nodes)
121
+
122
+ def _raise_compiler_error(self, child, e):
123
+ trace = ['']
124
+ for parent, attribute, index in self.access_path:
125
+ node = getattr(parent, attribute)
126
+ if index is None:
127
+ index = ''
128
+ else:
129
+ node = node[index]
130
+ index = '[%d]' % index
131
+ trace.append('%s.%s%s = %s' % (
132
+ parent.__class__.__name__, attribute, index,
133
+ self.dump_node(node)))
134
+ stacktrace, called_nodes = self._find_node_path(sys.exc_info()[2])
135
+ last_node = child
136
+ for node, method_name, pos in called_nodes:
137
+ last_node = node
138
+ trace.append("File '%s', line %d, in %s: %s" % (
139
+ pos[0], pos[1], method_name, self.dump_node(node)))
140
+ raise Errors.CompilerCrash(
141
+ getattr(last_node, 'pos', None), self.__class__.__name__,
142
+ '\n'.join(trace), e, stacktrace)
143
+
144
+ @cython.final
145
+ def find_handler(self, obj):
146
+ # to resolve, try entire hierarchy
147
+ cls = type(obj)
148
+ mro = inspect.getmro(cls)
149
+ for mro_cls in mro:
150
+ handler_method = getattr(self, "visit_" + mro_cls.__name__, None)
151
+ if handler_method is not None:
152
+ return handler_method
153
+
154
+ print(type(self), cls)
155
+ if self.access_path:
156
+ print(self.access_path)
157
+ print(self.access_path[-1][0].pos)
158
+ print(self.access_path[-1][0].__dict__)
159
+ raise RuntimeError("Visitor %r does not accept object: %s" % (self, obj))
160
+
161
+ def visit(self, obj):
162
+ # generic def entry point for calls from Python subclasses
163
+ return self._visit(obj)
164
+
165
+ @cython.final
166
+ def _visit(self, obj):
167
+ # fast cdef entry point for calls from Cython subclasses
168
+ try:
169
+ try:
170
+ handler_method = self.dispatch_table[type(obj)]
171
+ except KeyError:
172
+ handler_method = self.find_handler(obj)
173
+ self.dispatch_table[type(obj)] = handler_method
174
+ return handler_method(obj)
175
+ except Errors.CompileError:
176
+ raise
177
+ except Errors.AbortError:
178
+ raise
179
+ except Exception as e:
180
+ if DebugFlags.debug_no_exception_intercept:
181
+ raise
182
+ self._raise_compiler_error(obj, e)
183
+
184
+ @cython.final
185
+ def _visitchild(self, child, parent, attrname, idx):
186
+ # fast cdef entry point for calls from Cython subclasses
187
+ self.access_path.append((parent, attrname, idx))
188
+ result = self._visit(child)
189
+ self.access_path.pop()
190
+ return result
191
+
192
+ def visitchildren(self, parent, attrs=None, exclude=None):
193
+ # generic def entry point for calls from Python subclasses
194
+ return self._visitchildren(parent, attrs, exclude)
195
+
196
+ @cython.final
197
+ def _visitchildren(self, parent, attrs, exclude):
198
+ # fast cdef entry point for calls from Cython subclasses
199
+ """
200
+ Visits the children of the given parent. If parent is None, returns
201
+ immediately (returning None).
202
+
203
+ The return value is a dictionary giving the results for each
204
+ child (mapping the attribute name to either the return value
205
+ or a list of return values (in the case of multiple children
206
+ in an attribute)).
207
+ """
208
+ idx: cython.Py_ssize_t
209
+
210
+ if parent is None: return None
211
+ result = {}
212
+ for attr in parent.child_attrs:
213
+ if attrs is not None and attr not in attrs: continue
214
+ if exclude is not None and attr in exclude: continue
215
+ child = getattr(parent, attr)
216
+ if child is not None:
217
+ if type(child) is list:
218
+ childretval = [self._visitchild(x, parent, attr, idx) for idx, x in enumerate(child)]
219
+ else:
220
+ childretval = self._visitchild(child, parent, attr, None)
221
+ assert not isinstance(childretval, list), 'Cannot insert list here: %s in %r' % (attr, parent)
222
+ result[attr] = childretval
223
+ return result
224
+
225
+
226
+ @cython.cfunc
227
+ def _flatten_list(orig_list: list) -> list:
228
+ """
229
+ Flatten the list one level and remove any None.
230
+
231
+ Assumes input lists to be reusable and mutable.
232
+ May return the original list if it remains unchanged.
233
+ """
234
+ # Start lazy until we know that we really have to construct a different list.
235
+ newlist = None
236
+ i: cython.Py_ssize_t
237
+ use_before: cython.Py_ssize_t = 0
238
+
239
+ for i, x in enumerate(orig_list):
240
+ if x is None:
241
+ # Exclude x by not appending it to 'newlist' and not increasing 'use_before'.
242
+ continue
243
+ x_is_list: bool = type(x) is list
244
+ if x_is_list and not x:
245
+ continue
246
+
247
+ if newlist is not None:
248
+ # Non-lazy list building.
249
+ if x_is_list:
250
+ newlist.extend(x)
251
+ else:
252
+ newlist.append(x)
253
+ elif x_is_list:
254
+ # Stop being lazy and replace list object x by its content.
255
+ if use_before == 0:
256
+ # Start newlist from x.
257
+ newlist = x # May mutate the input list in x.
258
+ else:
259
+ # Build newlist up to the last used item.
260
+ newlist = orig_list[:use_before]
261
+ newlist.extend(x)
262
+ elif use_before == i:
263
+ # Keep counting single items lazily.
264
+ use_before = i + 1
265
+ else:
266
+ # Stop being lazy and close the gap.
267
+ newlist = orig_list[:use_before]
268
+ newlist.append(x)
269
+
270
+ if newlist is not None:
271
+ return newlist
272
+ elif use_before < len(orig_list):
273
+ return orig_list[:use_before]
274
+ else:
275
+ return orig_list # Original input list, no copy.
276
+
277
+
278
+ def _test_flatten_list(orig_list: list) -> list:
279
+ """
280
+ Test entry point when compiled.
281
+ """
282
+ return _flatten_list(orig_list)
283
+
284
+
285
+ class VisitorTransform(TreeVisitor):
286
+ """
287
+ A tree transform is a base class for visitors that wants to do stream
288
+ processing of the structure (rather than attributes etc.) of a tree.
289
+
290
+ It implements __call__ to simply visit the argument node.
291
+
292
+ It requires the visitor methods to return the nodes which should take
293
+ the place of the visited node in the result tree (which can be the same
294
+ or one or more replacement). Specifically, if the return value from
295
+ a visitor method is:
296
+
297
+ - [] or None; the visited node will be removed (set to None if an attribute and
298
+ removed if in a list)
299
+ - A single node; the visited node will be replaced by the returned node.
300
+ - A list of nodes; the visited nodes will be replaced by all the nodes in the
301
+ list. This will only work if the node was already a member of a list; if it
302
+ was not, an exception will be raised. (Typically you want to ensure that you
303
+ are within a StatListNode or similar before doing this.)
304
+ """
305
+ def visitchildren(self, parent, attrs=None, exclude=None):
306
+ # generic def entry point for calls from Python subclasses
307
+ return self._process_children(parent, attrs, exclude)
308
+
309
+ @cython.final
310
+ def _process_children(self, parent, attrs=None, exclude=None):
311
+ # fast cdef entry point for calls from Cython subclasses
312
+ result = self._visitchildren(parent, attrs, exclude)
313
+ for attr, newnode in result.items():
314
+ if type(newnode) is list:
315
+ newnode = _flatten_list(newnode)
316
+ setattr(parent, attr, newnode)
317
+ return result
318
+
319
+ def visitchild(self, parent, attr, idx=0):
320
+ # Helper to visit specific children from Python subclasses
321
+ child = getattr(parent, attr)
322
+ if child is not None:
323
+ node = self._visitchild(child, parent, attr, idx)
324
+ if node is not child:
325
+ setattr(parent, attr, node)
326
+ child = node
327
+ return child
328
+
329
+ def recurse_to_children(self, node):
330
+ self._process_children(node)
331
+ return node
332
+
333
+ def __call__(self, root):
334
+ return self._visit(root)
335
+
336
+
337
+ class CythonTransform(VisitorTransform):
338
+ """
339
+ Certain common conventions and utilities for Cython transforms.
340
+
341
+ - Sets up the context of the pipeline in self.context
342
+ - Tracks directives in effect in self.current_directives
343
+ """
344
+ def __init__(self, context):
345
+ super().__init__()
346
+ self.context = context
347
+
348
+ def __call__(self, node):
349
+ from .ModuleNode import ModuleNode
350
+ if isinstance(node, ModuleNode):
351
+ self.current_directives = node.directives
352
+ return super().__call__(node)
353
+
354
+ def visit_CompilerDirectivesMixin(self, node):
355
+ old = self.current_directives
356
+ self.current_directives = node.directives
357
+ self._process_children(node)
358
+ self.current_directives = old
359
+ return node
360
+
361
+ def visit_Node(self, node):
362
+ self._process_children(node)
363
+ return node
364
+
365
+
366
+ class ScopeTrackingTransform(CythonTransform):
367
+ # Keeps track of type of scopes
368
+ #scope_type: can be either of 'module', 'function', 'cclass', 'pyclass', 'struct'
369
+ #scope_node: the node that owns the current scope
370
+
371
+ def __init__(self, context):
372
+ super().__init__(context)
373
+ self.scope_type = 'module'
374
+ self.scope_node = None
375
+
376
+ @cython.final
377
+ def _visit_scope(self, node, scope_type):
378
+ outer_scope_type, outer_scope_node = self.scope_type, self.scope_node
379
+ self.scope_type = scope_type
380
+ self.scope_node = node
381
+ self._process_children(node)
382
+ self.scope_type, self.scope_node = outer_scope_type, outer_scope_node
383
+ return node
384
+
385
+ def visit_ModuleNode(self, node):
386
+ return self._visit_scope(node, 'module')
387
+
388
+ def visit_CClassDefNode(self, node):
389
+ return self._visit_scope(node, 'cclass')
390
+
391
+ def visit_PyClassDefNode(self, node):
392
+ return self._visit_scope(node, 'pyclass')
393
+
394
+ def visit_FuncDefNode(self, node):
395
+ return self._visit_scope(node, 'function')
396
+
397
+ def visit_CStructOrUnionDefNode(self, node):
398
+ return self._visit_scope(node, 'struct')
399
+
400
+
401
+ class EnvTransform(CythonTransform):
402
+ """
403
+ This transformation keeps a stack of the environments.
404
+ """
405
+ def __call__(self, root):
406
+ self.env_stack = []
407
+ self.enter_scope(root, root.scope)
408
+ return super().__call__(root)
409
+
410
+ def current_env(self):
411
+ return self.env_stack[-1][1]
412
+
413
+ def current_scope_node(self):
414
+ return self.env_stack[-1][0]
415
+
416
+ def global_scope(self):
417
+ return self.current_env().global_scope()
418
+
419
+ def enter_scope(self, node, scope):
420
+ self.env_stack.append((node, scope))
421
+
422
+ def exit_scope(self):
423
+ self.env_stack.pop()
424
+
425
+ def visit_FuncDefNode(self, node):
426
+ self.visit_func_outer_attrs(node)
427
+ self.enter_scope(node, node.local_scope)
428
+ self.visitchildren(node, attrs=None, exclude=node.outer_attrs)
429
+ self.exit_scope()
430
+ return node
431
+
432
+ def visit_func_outer_attrs(self, node):
433
+ self.visitchildren(node, attrs=node.outer_attrs)
434
+
435
+ def visit_GeneratorBodyDefNode(self, node):
436
+ self._process_children(node)
437
+ return node
438
+
439
+ def visit_ClassDefNode(self, node):
440
+ self.enter_scope(node, node.scope)
441
+ self._process_children(node)
442
+ self.exit_scope()
443
+ return node
444
+
445
+ def visit_CStructOrUnionDefNode(self, node):
446
+ self.enter_scope(node, node.scope)
447
+ self._process_children(node)
448
+ self.exit_scope()
449
+ return node
450
+
451
+ def visit_ScopedExprNode(self, node):
452
+ if node.expr_scope:
453
+ self.enter_scope(node, node.expr_scope)
454
+ self._process_children(node)
455
+ self.exit_scope()
456
+ else:
457
+ self._process_children(node)
458
+ return node
459
+
460
+ def visit_CArgDeclNode(self, node):
461
+ # default arguments are evaluated in the outer scope
462
+ if node.default:
463
+ attrs = [attr for attr in node.child_attrs if attr != 'default']
464
+ self._process_children(node, attrs)
465
+ self.enter_scope(node, self.current_env().outer_scope)
466
+ self.visitchildren(node, ('default',))
467
+ self.exit_scope()
468
+ else:
469
+ self._process_children(node)
470
+ return node
471
+
472
+
473
+ class NodeRefCleanupMixin:
474
+ """
475
+ Clean up references to nodes that were replaced.
476
+
477
+ NOTE: this implementation assumes that the replacement is
478
+ done first, before hitting any further references during
479
+ normal tree traversal. This needs to be arranged by calling
480
+ "self.visitchildren()" at a proper place in the transform
481
+ and by ordering the "child_attrs" of nodes appropriately.
482
+ """
483
+ def __init__(self, *args):
484
+ super().__init__(*args)
485
+ self._replacements = {}
486
+
487
+ def visit_CloneNode(self, node):
488
+ arg = node.arg
489
+ if arg not in self._replacements:
490
+ self.visitchildren(arg)
491
+ node.arg = self._replacements.get(arg, arg)
492
+ return node
493
+
494
+ def visit_ResultRefNode(self, node):
495
+ expr = node.expression
496
+ if expr is None or expr not in self._replacements:
497
+ self.visitchildren(node)
498
+ expr = node.expression
499
+ if expr is not None:
500
+ node.expression = self._replacements.get(expr, expr)
501
+ return node
502
+
503
+ def replace(self, node, replacement):
504
+ self._replacements[node] = replacement
505
+ return replacement
506
+
507
+
508
+ find_special_method_for_binary_operator = {
509
+ '<': '__lt__',
510
+ '<=': '__le__',
511
+ '==': '__eq__',
512
+ '!=': '__ne__',
513
+ '>=': '__ge__',
514
+ '>': '__gt__',
515
+ '+': '__add__',
516
+ '&': '__and__',
517
+ '/': '__div__',
518
+ '//': '__floordiv__',
519
+ '<<': '__lshift__',
520
+ '%': '__mod__',
521
+ '*': '__mul__',
522
+ '|': '__or__',
523
+ '**': '__pow__',
524
+ '>>': '__rshift__',
525
+ '-': '__sub__',
526
+ '^': '__xor__',
527
+ 'in': '__contains__',
528
+ }.get
529
+
530
+
531
+ find_special_method_for_unary_operator = {
532
+ 'not': '__not__',
533
+ '~': '__inv__',
534
+ '-': '__neg__',
535
+ '+': '__pos__',
536
+ }.get
537
+
538
+
539
+ class MethodDispatcherTransform(EnvTransform):
540
+ """
541
+ Base class for transformations that want to intercept on specific
542
+ builtin functions or methods of builtin types, including special
543
+ methods triggered by Python operators. Must run after declaration
544
+ analysis when entries were assigned.
545
+
546
+ Naming pattern for handler methods is as follows:
547
+
548
+ * builtin functions: _handle_(general|simple|any)_function_NAME
549
+
550
+ * builtin methods: _handle_(general|simple|any)_method_TYPENAME_METHODNAME
551
+ """
552
+ # only visit call nodes and Python operations
553
+ def visit_GeneralCallNode(self, node):
554
+ self._process_children(node)
555
+ function = node.function
556
+ if not function.type.is_pyobject:
557
+ return node
558
+ arg_tuple = node.positional_args
559
+ if not isinstance(arg_tuple, ExprNodes.TupleNode):
560
+ return node
561
+ keyword_args = node.keyword_args
562
+ if keyword_args and not isinstance(keyword_args, ExprNodes.DictNode):
563
+ # can't handle **kwargs
564
+ return node
565
+ args = arg_tuple.args
566
+ return self._dispatch_to_handler(node, function, args, keyword_args)
567
+
568
+ def visit_SimpleCallNode(self, node):
569
+ self._process_children(node)
570
+ function = node.function
571
+ if function.type.is_pyobject:
572
+ arg_tuple = node.arg_tuple
573
+ if not isinstance(arg_tuple, ExprNodes.TupleNode):
574
+ return node
575
+ args = arg_tuple.args
576
+ else:
577
+ args = node.args
578
+ return self._dispatch_to_handler(node, function, args, None)
579
+
580
+ def visit_PrimaryCmpNode(self, node):
581
+ if node.cascade:
582
+ # not currently handled below
583
+ self._process_children(node)
584
+ return node
585
+ return self._visit_binop_node(node)
586
+
587
+ def visit_BinopNode(self, node):
588
+ return self._visit_binop_node(node)
589
+
590
+ def _visit_binop_node(self, node):
591
+ self._process_children(node)
592
+ # FIXME: could special case 'not_in'
593
+ special_method_name = find_special_method_for_binary_operator(node.operator)
594
+ if special_method_name:
595
+ operand1, operand2 = node.operand1, node.operand2
596
+ if special_method_name == '__contains__':
597
+ operand1, operand2 = operand2, operand1
598
+ elif special_method_name == '__div__':
599
+ if Future.division in self.current_env().context.future_directives:
600
+ special_method_name = '__truediv__'
601
+ obj_type = operand1.type
602
+ if obj_type.is_builtin_type and not obj_type.is_exception_type:
603
+ type_name = obj_type.name
604
+ else:
605
+ type_name = "object" # safety measure
606
+ node = self._dispatch_to_method_handler(
607
+ special_method_name, None, False, type_name,
608
+ node, None, [operand1, operand2], None)
609
+ return node
610
+
611
+ def visit_UnopNode(self, node):
612
+ self._process_children(node)
613
+ special_method_name = find_special_method_for_unary_operator(node.operator)
614
+ if special_method_name:
615
+ operand = node.operand
616
+ obj_type = operand.type
617
+ if obj_type.is_builtin_type and not obj_type.is_exception_type:
618
+ type_name = obj_type.name
619
+ else:
620
+ type_name = "object" # safety measure
621
+ node = self._dispatch_to_method_handler(
622
+ special_method_name, None, False, type_name,
623
+ node, None, [operand], None)
624
+ return node
625
+
626
+ ### dispatch to specific handlers
627
+
628
+ def _find_handler(self, match_name, has_kwargs):
629
+ if not match_name.isascii():
630
+ # Classes with unicode names won't have specific handlers.
631
+ return None
632
+
633
+ call_type = 'general' if has_kwargs else 'simple'
634
+ handler = getattr(self, f'_handle_{call_type}_{match_name}', None)
635
+ if handler is None:
636
+ handler = getattr(self, f'_handle_any_{match_name}', None)
637
+ return handler
638
+
639
+ def _delegate_to_assigned_value(self, node, function, arg_list, kwargs):
640
+ assignment = function.cf_state[0]
641
+ value = assignment.rhs
642
+ if value.is_name:
643
+ if not value.entry or len(value.entry.cf_assignments) > 1:
644
+ # the variable might have been reassigned => play safe
645
+ return node
646
+ elif value.is_attribute and value.obj.is_name:
647
+ if not value.obj.entry or len(value.obj.entry.cf_assignments) > 1:
648
+ # the underlying variable might have been reassigned => play safe
649
+ return node
650
+ else:
651
+ return node
652
+ return self._dispatch_to_handler(
653
+ node, value, arg_list, kwargs)
654
+
655
+ def _dispatch_to_handler(self, node, function, arg_list, kwargs):
656
+ if function.is_name:
657
+ # we only consider functions that are either builtin
658
+ # Python functions or builtins that were already replaced
659
+ # into a C function call (defined in the builtin scope)
660
+ if not function.entry:
661
+ return node
662
+ entry = function.entry
663
+ is_builtin = (
664
+ entry.is_builtin or
665
+ entry is self.current_env().builtin_scope().lookup_here(function.name))
666
+ if not is_builtin:
667
+ if function.cf_state and function.cf_state.is_single:
668
+ # we know the value of the variable
669
+ # => see if it's usable instead
670
+ return self._delegate_to_assigned_value(
671
+ node, function, arg_list, kwargs)
672
+ if (arg_list and entry.is_cmethod and entry.scope and
673
+ entry.scope.parent_type.is_builtin_type and not entry.scope.parent_type.is_exception_type):
674
+ if entry.scope.parent_type is arg_list[0].type:
675
+ # Optimised (unbound) method of a builtin type => try to "de-optimise".
676
+ return self._dispatch_to_method_handler(
677
+ entry.name, self_arg=None, is_unbound_method=True,
678
+ type_name=entry.scope.parent_type.name,
679
+ node=node, function=function, arg_list=arg_list, kwargs=kwargs)
680
+ return node
681
+ function_handler = self._find_handler(
682
+ f"function_{function.name}", kwargs)
683
+ if function_handler is None:
684
+ return self._handle_function(node, function.name, function, arg_list, kwargs)
685
+ if kwargs:
686
+ return function_handler(node, function, arg_list, kwargs)
687
+ else:
688
+ return function_handler(node, function, arg_list)
689
+ elif function.is_attribute:
690
+ attr_name = function.attribute
691
+ if function.type.is_pyobject:
692
+ self_arg = function.obj
693
+ elif node.self and function.entry:
694
+ entry = function.entry.as_variable
695
+ if not entry or not entry.is_builtin:
696
+ return node
697
+ # C implementation of a Python builtin method - see if we find further matches
698
+ self_arg = node.self
699
+ arg_list = arg_list[1:] # drop CloneNode of self argument
700
+ else:
701
+ return node
702
+ obj_type = self_arg.type
703
+ is_unbound_method = False
704
+ # Exceptions aren't necessarily exact types so could have unknown methods
705
+ if obj_type.is_builtin_type and not obj_type.is_exception_type:
706
+ if obj_type is Builtin.type_type and self_arg.is_name and arg_list and arg_list[0].type.is_pyobject:
707
+ # calling an unbound method like 'list.append(L,x)'
708
+ # (ignoring 'type.mro()' here ...)
709
+ type_name = self_arg.name
710
+ self_arg = None
711
+ is_unbound_method = True
712
+ else:
713
+ type_name = obj_type.name
714
+ if type_name == 'str':
715
+ # We traditionally used the type name 'unicode' for 'str' dispatch methods.
716
+ type_name = 'unicode'
717
+ else:
718
+ type_name = "object" # safety measure
719
+ return self._dispatch_to_method_handler(
720
+ attr_name, self_arg, is_unbound_method, type_name,
721
+ node, function, arg_list, kwargs)
722
+ else:
723
+ return node
724
+
725
+ def _dispatch_to_method_handler(self, attr_name, self_arg,
726
+ is_unbound_method, type_name,
727
+ node, function, arg_list, kwargs):
728
+ method_handler = self._find_handler(
729
+ f"method_{type_name}_{attr_name}", kwargs)
730
+ if method_handler is None:
731
+ if (attr_name in TypeSlots.special_method_names
732
+ or attr_name in ['__new__', '__class__']):
733
+ method_handler = self._find_handler(
734
+ f"slot{attr_name}", kwargs)
735
+ if method_handler is None:
736
+ return self._handle_method(
737
+ node, type_name, attr_name, function,
738
+ arg_list, is_unbound_method, kwargs)
739
+ if self_arg is not None:
740
+ arg_list = [self_arg] + list(arg_list)
741
+ if kwargs:
742
+ result = method_handler(
743
+ node, function, arg_list, is_unbound_method, kwargs)
744
+ else:
745
+ result = method_handler(
746
+ node, function, arg_list, is_unbound_method)
747
+ return result
748
+
749
+ def _handle_function(self, node, function_name, function, arg_list, kwargs):
750
+ """Fallback handler"""
751
+ return node
752
+
753
+ def _handle_method(self, node, type_name, attr_name, function,
754
+ arg_list, is_unbound_method, kwargs):
755
+ """Fallback handler"""
756
+ return node
757
+
758
+
759
+ class RecursiveNodeReplacer(VisitorTransform):
760
+ """
761
+ Recursively replace all occurrences of a node in a subtree by
762
+ another node.
763
+ """
764
+ def __init__(self, orig_node, new_node):
765
+ super().__init__()
766
+ self.orig_node, self.new_node = orig_node, new_node
767
+
768
+ def visit_CloneNode(self, node):
769
+ if node is self.orig_node:
770
+ return self.new_node
771
+ if node.arg is self.orig_node:
772
+ node.arg = self.new_node
773
+ return node
774
+
775
+ def visit_Node(self, node):
776
+ self._process_children(node)
777
+ if node is self.orig_node:
778
+ return self.new_node
779
+ else:
780
+ return node
781
+
782
+ def recursively_replace_node(tree, old_node, new_node):
783
+ replace_in = RecursiveNodeReplacer(old_node, new_node)
784
+ replace_in(tree)
785
+
786
+
787
+ class NodeFinder(TreeVisitor):
788
+ """
789
+ Find out if a node appears in a subtree.
790
+ """
791
+ def __init__(self, node):
792
+ super().__init__()
793
+ self.node = node
794
+ self.found = False
795
+
796
+ def visit_Node(self, node):
797
+ if self.found:
798
+ pass # short-circuit
799
+ elif node is self.node:
800
+ self.found = True
801
+ else:
802
+ self._visitchildren(node, None, None)
803
+
804
+ def tree_contains(tree, node):
805
+ finder = NodeFinder(node)
806
+ finder.visit(tree)
807
+ return finder.found
808
+
809
+
810
+ # Utils
811
+ def replace_node(ptr, value):
812
+ """Replaces a node. ptr is of the form used on the access path stack
813
+ (parent, attrname, listidx|None)
814
+ """
815
+ parent, attrname, listidx = ptr
816
+ if listidx is None:
817
+ setattr(parent, attrname, value)
818
+ else:
819
+ getattr(parent, attrname)[listidx] = value
820
+
821
+
822
+ class PrintTree(TreeVisitor):
823
+ """Prints a representation of the tree to standard output.
824
+ Subclass and override repr_of to provide more information
825
+ about nodes. """
826
+ def __init__(self, start=None, end=None):
827
+ TreeVisitor.__init__(self)
828
+ self._indent = ""
829
+ if start is not None or end is not None:
830
+ self._line_range = (start or 0, end or 2**30)
831
+ else:
832
+ self._line_range = None
833
+
834
+ def indent(self):
835
+ self._indent += " "
836
+
837
+ def unindent(self):
838
+ self._indent = self._indent[:-2]
839
+
840
+ def __call__(self, tree, phase=None):
841
+ print("Parse tree dump at phase '%s'" % phase)
842
+ self.visit(tree)
843
+ return tree
844
+
845
+ # Don't do anything about process_list, the defaults gives
846
+ # nice-looking name[idx] nodes which will visually appear
847
+ # under the parent-node, not displaying the list itself in
848
+ # the hierarchy.
849
+ def visit_Node(self, node):
850
+ self._print_node(node)
851
+ self.indent()
852
+ self.visitchildren(node)
853
+ self.unindent()
854
+ return node
855
+
856
+ def visit_CloneNode(self, node):
857
+ self._print_node(node)
858
+ self.indent()
859
+ line = node.pos[1]
860
+ if self._line_range is None or self._line_range[0] <= line <= self._line_range[1]:
861
+ print("%s- %s: %s" % (self._indent, 'arg', self.repr_of(node.arg)))
862
+ self.indent()
863
+ self.visitchildren(node.arg)
864
+ self.unindent()
865
+ self.unindent()
866
+ return node
867
+
868
+ def _print_node(self, node):
869
+ line = node.pos[1]
870
+ if self._line_range is None or self._line_range[0] <= line <= self._line_range[1]:
871
+ if len(self.access_path) == 0:
872
+ name = "(root)"
873
+ else:
874
+ parent, attr, idx = self.access_path[-1]
875
+ if idx is not None:
876
+ name = "%s[%d]" % (attr, idx)
877
+ else:
878
+ name = attr
879
+ print("%s- %s: %s" % (self._indent, name, self.repr_of(node)))
880
+
881
+ def repr_of(self, node):
882
+ if node is None:
883
+ return "(none)"
884
+ else:
885
+ result = node.__class__.__name__
886
+ if isinstance(node, ExprNodes.NameNode):
887
+ result += "(type=%s, name=\"%s\")" % (repr(node.type), node.name)
888
+ elif isinstance(node, Nodes.DefNode):
889
+ result += "(name=\"%s\")" % node.name
890
+ elif isinstance(node, Nodes.CFuncDefNode):
891
+ result += "(name=\"%s\", type=\"%s\")" % (
892
+ node.declared_name(), getattr(node, "type", None))
893
+ elif isinstance(node, ExprNodes.AttributeNode):
894
+ result += "(type=%s, attribute=\"%s\")" % (repr(node.type), node.attribute)
895
+ elif isinstance(node,
896
+ (ExprNodes.ConstNode, ExprNodes.PyConstNode, ExprNodes.ImagNode)):
897
+ result += "(type=%s, value=%r)" % (repr(node.type), node.value)
898
+ elif isinstance(node, ExprNodes.ExprNode):
899
+ t = node.type
900
+ result += "(type=%s)" % repr(t)
901
+ elif node.pos:
902
+ pos = node.pos
903
+ path = pos[0].get_description()
904
+ if '/' in path:
905
+ path = path.split('/')[-1]
906
+ if '\\' in path:
907
+ path = path.split('\\')[-1]
908
+ result += "(pos=(%s:%s:%s))" % (path, pos[1], pos[2])
909
+
910
+ return result
911
+
912
+ if __name__ == "__main__":
913
+ import doctest
914
+ doctest.testmod()