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,978 @@
1
+ import copy
2
+ import hashlib
3
+
4
+ from . import (ExprNodes, PyrexTypes,
5
+ ParseTreeTransforms, StringEncoding, Errors,
6
+ Naming)
7
+ from .ExprNodes import CloneNode, CodeObjectNode, ProxyNode, TupleNode
8
+ from .Nodes import FuncDefNode, StatListNode, DefNode
9
+ from ..Utils import OrderedSet
10
+ from .Errors import error, CannotSpecialize
11
+
12
+
13
+ class FusedCFuncDefNode(StatListNode):
14
+ """
15
+ This node replaces a function with fused arguments. It deep-copies the
16
+ function for every permutation of fused types, and allocates a new local
17
+ scope for it. It keeps track of the original function in self.node, and
18
+ the entry of the original function in the symbol table is given the
19
+ 'fused_cfunction' attribute which points back to us.
20
+ Then when a function lookup occurs (to e.g. call it), the call can be
21
+ dispatched to the right function.
22
+
23
+ node FuncDefNode the original function
24
+ nodes [FuncDefNode] list of copies of node with different specific types
25
+ py_func DefNode the fused python function subscriptable from
26
+ Python space
27
+ __signatures__ A DictNode mapping signature specialization strings
28
+ to PyCFunction nodes
29
+ resulting_fused_function PyCFunction for the fused DefNode that delegates
30
+ to specializations
31
+ fused_func_assignment Assignment of the fused function to the function name
32
+ defaults_tuple TupleNode of defaults (letting PyCFunctionNode build
33
+ defaults would result in many different tuples)
34
+ specialized_pycfuncs List of synthesized pycfunction nodes for the
35
+ specializations
36
+
37
+ fused_compound_types All fused (compound) types (e.g. floating[:])
38
+ """
39
+
40
+ __signatures__ = None
41
+ resulting_fused_function = None
42
+ fused_func_assignment = None
43
+ py_func = None
44
+ defaults_tuple = None
45
+ decorators = None
46
+
47
+ child_attrs = StatListNode.child_attrs + [
48
+ '__signatures__', 'resulting_fused_function', 'fused_func_assignment']
49
+
50
+ def __init__(self, node, env):
51
+ super().__init__(node.pos)
52
+
53
+ self.nodes = []
54
+ self.node = node
55
+
56
+ is_def = isinstance(self.node, DefNode)
57
+ if is_def:
58
+ # self.node.decorators = []
59
+ self.copy_def(env)
60
+ else:
61
+ self.copy_cdef(env)
62
+
63
+ # Perform some sanity checks. If anything fails, it's a bug
64
+ for n in self.nodes:
65
+ assert not n.entry.type.is_fused
66
+ assert not n.local_scope.return_type.is_fused
67
+ if node.return_type.is_fused:
68
+ assert not n.return_type.is_fused
69
+
70
+ if not is_def and n.cfunc_declarator.optional_arg_count:
71
+ assert n.type.op_arg_struct
72
+
73
+ node.entry.fused_cfunction = self
74
+ # Copy the nodes as AnalyseDeclarationsTransform will prepend
75
+ # self.py_func to self.stats, as we only want specialized
76
+ # CFuncDefNodes in self.nodes
77
+ self.stats = self.nodes[:]
78
+
79
+ def copy_def(self, env):
80
+ """
81
+ Create a copy of the original def or lambda function for specialized
82
+ versions.
83
+ """
84
+ fused_compound_types = PyrexTypes.unique(
85
+ [arg.type for arg in self.node.args if arg.type.is_fused])
86
+ fused_types = self._get_fused_base_types(fused_compound_types)
87
+ permutations = PyrexTypes.get_all_specialized_permutations(fused_types)
88
+
89
+ self.fused_compound_types = fused_compound_types
90
+
91
+ if self.node.entry in env.pyfunc_entries:
92
+ env.pyfunc_entries.remove(self.node.entry)
93
+
94
+ for cname, fused_to_specific in permutations:
95
+ copied_node = copy.deepcopy(self.node)
96
+ # keep signature object identity for special casing in DefNode.analyse_declarations()
97
+ copied_node.entry.signature = self.node.entry.signature
98
+
99
+ self._specialize_function_args(copied_node.args, fused_to_specific)
100
+ copied_node.return_type = self.node.return_type.specialize(
101
+ fused_to_specific)
102
+ copied_node.code_object = CodeObjectNode(copied_node)
103
+ copied_node.analyse_declarations(env)
104
+ # copied_node.is_staticmethod = self.node.is_staticmethod
105
+ # copied_node.is_classmethod = self.node.is_classmethod
106
+ self.create_new_local_scope(copied_node, env, fused_to_specific)
107
+ self.specialize_copied_def(copied_node, cname, self.node.entry,
108
+ fused_to_specific, fused_compound_types)
109
+
110
+ PyrexTypes.specialize_entry(copied_node.entry, cname)
111
+ copied_node.entry.used = True
112
+ env.entries[copied_node.entry.name] = copied_node.entry
113
+
114
+ copied_node.name = PyrexTypes.get_fused_specialized_name(copied_node.name, self.node.args, copied_node.args)
115
+
116
+ if not self.replace_fused_typechecks(copied_node):
117
+ break
118
+
119
+ self.orig_py_func = self.node
120
+ self.py_func = self.make_fused_cpdef(self.node, env, is_def=True)
121
+
122
+ def copy_cdef(self, env):
123
+ """
124
+ Create a copy of the original c(p)def function for all specialized
125
+ versions.
126
+ """
127
+ permutations = self.node.type.get_all_specialized_permutations()
128
+ # print 'Node %s has %d specializations:' % (self.node.entry.name,
129
+ # len(permutations))
130
+ # import pprint; pprint.pprint([d for cname, d in permutations])
131
+
132
+ # Prevent copying of the python function
133
+ self.orig_py_func = orig_py_func = self.node.py_func
134
+ self.node.py_func = None
135
+ if orig_py_func:
136
+ env.pyfunc_entries.remove(orig_py_func.entry)
137
+
138
+ fused_types = self.node.type.get_fused_types()
139
+ self.fused_compound_types = fused_types
140
+
141
+ new_cfunc_entries = []
142
+ for cname, fused_to_specific in permutations:
143
+ copied_node = copy.deepcopy(self.node)
144
+
145
+ # Make the types in our CFuncType specific.
146
+ try:
147
+ type = copied_node.type.specialize(fused_to_specific)
148
+ except CannotSpecialize:
149
+ # unlike for the argument types, specializing the return type can fail
150
+ error(copied_node.pos, "Return type is a fused type that cannot "
151
+ "be determined from the function arguments")
152
+ self.py_func = None # this is just to let the compiler exit gracefully
153
+ return
154
+
155
+ # Make the argument types in the CFuncDeclarator specific
156
+ self._specialize_function_args(copied_node.cfunc_declarator.args,
157
+ fused_to_specific)
158
+ entry = copied_node.entry
159
+ type.specialize_entry(
160
+ entry, cname,
161
+ name=PyrexTypes.get_fused_specialized_name(copied_node.declared_name(), self.node.args, copied_node.args))
162
+
163
+ # Reuse existing Entries (e.g. from .pxd files).
164
+ for orig_entry in env.cfunc_entries:
165
+ if entry.cname == orig_entry.cname and type.same_as_resolved_type(orig_entry.type):
166
+ copied_node.entry = orig_entry
167
+ if not copied_node.entry.func_cname:
168
+ copied_node.entry.func_cname = entry.func_cname
169
+ entry = orig_entry
170
+ type = orig_entry.type
171
+ break
172
+ else:
173
+ new_cfunc_entries.append(entry)
174
+
175
+ copied_node.type = type
176
+ entry.type, type.entry = type, entry
177
+
178
+ entry.used = (entry.used or
179
+ self.node.entry.defined_in_pxd or
180
+ env.is_c_class_scope or
181
+ entry.is_cmethod)
182
+
183
+ if self.node.cfunc_declarator.optional_arg_count:
184
+ self.node.cfunc_declarator.declare_optional_arg_struct(
185
+ type, env, fused_cname=cname)
186
+
187
+ copied_node.return_type = type.return_type
188
+ self.create_new_local_scope(copied_node, env, fused_to_specific)
189
+
190
+ # If a cpdef, declare all specialized cpdefs (this
191
+ # also calls analyse_declarations)
192
+ copied_node.declare_cpdef_wrapper(env)
193
+ if copied_node.py_func:
194
+ env.pyfunc_entries.remove(copied_node.py_func.entry)
195
+
196
+ self.specialize_copied_def(
197
+ copied_node.py_func, cname, self.node.entry.as_variable,
198
+ fused_to_specific, fused_types)
199
+
200
+ if not self.replace_fused_typechecks(copied_node):
201
+ break
202
+
203
+ # replace old entry with new entries
204
+ if self.node.entry in env.cfunc_entries:
205
+ cindex = env.cfunc_entries.index(self.node.entry)
206
+ env.cfunc_entries[cindex:cindex+1] = new_cfunc_entries
207
+ else:
208
+ env.cfunc_entries.extend(new_cfunc_entries)
209
+
210
+ if orig_py_func:
211
+ self.py_func = self.make_fused_cpdef(orig_py_func, env,
212
+ is_def=False)
213
+ else:
214
+ self.py_func = orig_py_func
215
+
216
+ def _get_fused_base_types(self, fused_compound_types):
217
+ """
218
+ Get a list of unique basic fused types, from a list of
219
+ (possibly) compound fused types.
220
+ """
221
+ base_types = []
222
+ seen = set()
223
+ for fused_type in fused_compound_types:
224
+ fused_type.get_fused_types(result=base_types, seen=seen)
225
+ return base_types
226
+
227
+ def _specialize_function_args(self, args, fused_to_specific):
228
+ for arg in args:
229
+ if arg.type.is_fused:
230
+ arg.type = arg.type.specialize(fused_to_specific)
231
+ if arg.type.is_memoryviewslice:
232
+ arg.type.validate_memslice_dtype(arg.pos)
233
+ if arg.annotation:
234
+ # TODO might be nice if annotations were specialized instead?
235
+ # (Or might be hard to do reliably)
236
+ arg.annotation.untyped = True
237
+
238
+ def create_new_local_scope(self, node, env, f2s):
239
+ """
240
+ Create a new local scope for the copied node and append it to
241
+ self.nodes. A new local scope is needed because the arguments with the
242
+ fused types are already in the local scope, and we need the specialized
243
+ entries created after analyse_declarations on each specialized version
244
+ of the (CFunc)DefNode.
245
+ f2s is a dict mapping each fused type to its specialized version
246
+ """
247
+ node.create_local_scope(env)
248
+ node.local_scope.fused_to_specific = f2s
249
+
250
+ # This is copied from the original function, set it to false to
251
+ # stop recursion
252
+ node.has_fused_arguments = False
253
+ self.nodes.append(node)
254
+
255
+ def specialize_copied_def(self, node, cname, py_entry, f2s, fused_compound_types):
256
+ """Specialize the copy of a DefNode given the copied node,
257
+ the specialization cname and the original DefNode entry"""
258
+ fused_types = self._get_fused_base_types(fused_compound_types)
259
+ type_strings = [
260
+ PyrexTypes.specialization_signature_string(fused_type, f2s)
261
+ for fused_type in fused_types
262
+ ]
263
+
264
+ node.specialized_signature_string = '|'.join(type_strings)
265
+
266
+ node.entry.pymethdef_cname = PyrexTypes.get_fused_cname(
267
+ cname, node.entry.pymethdef_cname)
268
+ node.entry.doc = py_entry.doc
269
+ node.entry.doc_cname = py_entry.doc_cname
270
+
271
+ def replace_fused_typechecks(self, copied_node):
272
+ """
273
+ Branch-prune fused type checks like
274
+
275
+ if fused_t is int:
276
+ ...
277
+
278
+ Returns whether an error was issued and whether we should stop in
279
+ in order to prevent a flood of errors.
280
+ """
281
+ num_errors = Errors.get_errors_count()
282
+ transform = ParseTreeTransforms.ReplaceFusedTypeChecks(
283
+ copied_node.local_scope)
284
+ transform(copied_node)
285
+
286
+ if Errors.get_errors_count() > num_errors:
287
+ return False
288
+
289
+ return True
290
+
291
+ def _fused_instance_checks(self, normal_types, pyx_code, env):
292
+ """
293
+ Generate Cython code for instance checks, matching an object to
294
+ specialized types.
295
+ """
296
+ for specialized_type in normal_types:
297
+ # all_numeric = all_numeric and specialized_type.is_numeric
298
+ py_type_name = specialized_type.py_type_name()
299
+ pyx_code.put_chunk(
300
+ f"""
301
+ if isinstance(arg, {py_type_name}):
302
+ return '{specialized_type.specialization_string}'
303
+ """
304
+ )
305
+
306
+ def _dtype_name(self, dtype):
307
+ name = str(dtype).replace('_', '__').replace(' ', '_')
308
+ if dtype.is_typedef:
309
+ name = Naming.fused_dtype_prefix + name
310
+ return name
311
+
312
+ def _dtype_type(self, dtype):
313
+ if dtype.is_typedef:
314
+ return self._dtype_name(dtype)
315
+ return str(dtype)
316
+
317
+ def _sizeof_dtype(self, dtype):
318
+ if dtype.is_pyobject:
319
+ return 'sizeof(void *)'
320
+ else:
321
+ return f"sizeof({self._dtype_type(dtype)})"
322
+
323
+ def _buffer_check_numpy_dtype_setup_cases(self, pyx_code):
324
+ "Setup some common cases to match dtypes against specializations"
325
+ with pyx_code.indenter("if kind in u'iu':"):
326
+ pyx_code.putln("pass")
327
+ pyx_code.named_insertion_point("dtype_int")
328
+
329
+ with pyx_code.indenter("elif kind == u'f':"):
330
+ pyx_code.putln("pass")
331
+ pyx_code.named_insertion_point("dtype_float")
332
+
333
+ with pyx_code.indenter("elif kind == u'c':"):
334
+ pyx_code.putln("pass")
335
+ pyx_code.named_insertion_point("dtype_complex")
336
+
337
+ def _buffer_check_numpy_dtype(self, pyx_code, specialized_buffer_types, pythran_types):
338
+ """
339
+ Match a numpy dtype object to the individual specializations.
340
+ """
341
+ self._buffer_check_numpy_dtype_setup_cases(pyx_code)
342
+
343
+ for specialized_type in pythran_types+specialized_buffer_types:
344
+ final_type = specialized_type
345
+ if specialized_type.is_pythran_expr:
346
+ specialized_type = specialized_type.org_buffer
347
+ dtype = specialized_type.dtype
348
+
349
+ itemsize_match = self._sizeof_dtype(dtype) + " == itemsize"
350
+ signed_match = f" and not ({self._dtype_name(dtype)}_is_signed ^ dtype_signed)"
351
+
352
+ dtypes = [
353
+ (dtype.is_int, pyx_code['dtype_int']),
354
+ (dtype.is_float, pyx_code['dtype_float']),
355
+ (dtype.is_complex, pyx_code['dtype_complex'])
356
+ ]
357
+
358
+ for dtype_category, codewriter in dtypes:
359
+ if not dtype_category:
360
+ continue
361
+
362
+ cond = f'{itemsize_match} and (<Py_ssize_t>arg.ndim) == {specialized_type.ndim}'
363
+ if dtype.is_int:
364
+ cond += signed_match
365
+ if final_type.is_pythran_expr:
366
+ cond += ' and arg_is_pythran_compatible'
367
+
368
+ with codewriter.indenter(f"if {cond}:"):
369
+ #codewriter.putln("print 'buffer match found based on numpy dtype'")
370
+ codewriter.putln(f"return '{final_type.specialization_string}'")
371
+
372
+ def _buffer_parse_format_string_check(self, pyx_code, decl_code, specialized_type, env):
373
+ """
374
+ For each specialized type, try to coerce the object to a memoryview
375
+ slice of that type. This means obtaining a buffer and parsing the
376
+ format string.
377
+ TODO: separate buffer acquisition from format parsing
378
+ """
379
+ dtype = specialized_type.dtype
380
+ if specialized_type.is_buffer:
381
+ axes = [('direct', 'strided')] * specialized_type.ndim
382
+ else:
383
+ axes = specialized_type.axes
384
+
385
+ memslice_type = PyrexTypes.MemoryViewSliceType(dtype, axes)
386
+ memslice_type.create_from_py_utility_code(env)
387
+ coerce_from_py_func = memslice_type.from_py_function
388
+
389
+ decl_code.putln(
390
+ f"{Naming.memviewslice_cname} {coerce_from_py_func}(object, int)")
391
+
392
+ match = specialized_type.specialization_string
393
+ sizeof_dtype = self._sizeof_dtype(dtype)
394
+ ndim_dtype = specialized_type.ndim
395
+
396
+ # Use the memoryview object to check itemsize and ndim.
397
+ # In principle it could check more, but these are the easiest to do quickly.
398
+ pyx_code.put_chunk(
399
+ f"""
400
+ # try {dtype}
401
+ if (((itemsize == -1 and arg_as_memoryview.itemsize == {sizeof_dtype})
402
+ or itemsize == {sizeof_dtype})
403
+ and arg_as_memoryview.ndim == {ndim_dtype}):
404
+ memslice = {coerce_from_py_func}(arg_as_memoryview, 0)
405
+ if memslice.memview:
406
+ __PYX_XCLEAR_MEMVIEW(&memslice, 1)
407
+ # print 'found a match for the buffer through format parsing'
408
+ return '{match}'
409
+ else:
410
+ __pyx_PyErr_Clear()
411
+ """
412
+ )
413
+
414
+ def _buffer_checks(self, buffer_types, pythran_types, pyx_code, decl_code, accept_none, env):
415
+ """
416
+ Generate Cython code to match objects to buffer specializations.
417
+ First try to get a numpy dtype object and match it against the individual
418
+ specializations. If that fails, try naively to coerce the object
419
+ to each specialization, which obtains the buffer each time and tries
420
+ to match the format string.
421
+ """
422
+ # The first thing to find a match in this loop breaks out of the loop
423
+ pyx_code.put_chunk(
424
+ """
425
+ """ + ("arg_is_pythran_compatible = False" if pythran_types else "") + """
426
+ if ndarray is not None:
427
+ if isinstance(arg, ndarray):
428
+ dtype = arg.dtype
429
+ """ + ("arg_is_pythran_compatible = True" if pythran_types else "") + """
430
+ elif __pyx_memoryview_check(arg):
431
+ arg_base = arg.base
432
+ if isinstance(arg_base, ndarray):
433
+ dtype = arg_base.dtype
434
+ else:
435
+ dtype = None
436
+ else:
437
+ dtype = None
438
+
439
+ itemsize = -1
440
+ if dtype is not None:
441
+ itemsize = dtype.itemsize
442
+ kind = ord(dtype.kind)
443
+ dtype_signed = kind == u'i'
444
+ """)
445
+ pyx_code.indent(2)
446
+ if pythran_types:
447
+ pyx_code.put_chunk(
448
+ """
449
+ # Pythran only supports the endianness of the current compiler
450
+ byteorder = dtype.byteorder
451
+ if byteorder == "<" and not __Pyx_Is_Little_Endian():
452
+ arg_is_pythran_compatible = False
453
+ elif byteorder == ">" and __Pyx_Is_Little_Endian():
454
+ arg_is_pythran_compatible = False
455
+ if arg_is_pythran_compatible:
456
+ cur_stride = itemsize
457
+ shape = arg.shape
458
+ strides = arg.strides
459
+ for i in range(arg.ndim-1, -1, -1):
460
+ if (<Py_ssize_t>strides[i]) != cur_stride:
461
+ arg_is_pythran_compatible = False
462
+ break
463
+ cur_stride *= <Py_ssize_t> shape[i]
464
+ else:
465
+ arg_is_pythran_compatible = not (arg.flags.f_contiguous and (<Py_ssize_t>arg.ndim) > 1)
466
+ """)
467
+ self._buffer_check_numpy_dtype(pyx_code, buffer_types, pythran_types)
468
+ pyx_code.dedent(2)
469
+
470
+ if accept_none:
471
+ # If None is acceptable, then Cython <3.0 matched None with the
472
+ # first type. This behaviour isn't ideal, but keep it for backwards
473
+ # compatibility. Better behaviour would be to see if subsequent
474
+ # arguments give a stronger match.
475
+ pyx_code.put_chunk(
476
+ f"""
477
+ if arg is None:
478
+ return '{buffer_types[0].specialization_string}'
479
+ """
480
+ )
481
+
482
+ # creating a Cython memoryview from a Python memoryview avoids the
483
+ # need to get the buffer multiple times, and we can
484
+ # also use it to check itemsizes etc
485
+ pyx_code.put_chunk(
486
+ """
487
+ try:
488
+ arg_as_memoryview = memoryview(arg)
489
+ except (ValueError, TypeError):
490
+ pass
491
+ """)
492
+ with pyx_code.indenter("else:"):
493
+ for specialized_type in buffer_types:
494
+ self._buffer_parse_format_string_check(
495
+ pyx_code, decl_code, specialized_type, env)
496
+
497
+ def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_types):
498
+ """
499
+ If we have any buffer specializations, write out some variable and type declarations.
500
+ """
501
+ decl_code.put_chunk(
502
+ f"""
503
+ ctypedef struct {Naming.memviewslice_cname}:
504
+ void *memview
505
+
506
+ void __PYX_XCLEAR_MEMVIEW({Naming.memviewslice_cname} *, int have_gil)
507
+ bint __pyx_memoryview_check(object)
508
+ """)
509
+
510
+ pyx_code['local_variable_declarations'].put_chunk(
511
+ f"""
512
+ cdef {Naming.memviewslice_cname} memslice
513
+ cdef Py_ssize_t itemsize
514
+ cdef bint dtype_signed
515
+ cdef Py_UCS4 kind
516
+
517
+ itemsize = -1
518
+ """)
519
+
520
+ if pythran_types:
521
+ pyx_code['local_variable_declarations'].put_chunk("""
522
+ cdef bint arg_is_pythran_compatible
523
+ cdef Py_ssize_t cur_stride
524
+ cdef Py_ssize_t i
525
+ """)
526
+
527
+ pyx_code['local_variable_declarations'].put_chunk(
528
+ """
529
+ cdef memoryview arg_as_memoryview
530
+ """
531
+ )
532
+
533
+ seen_typedefs = set()
534
+ seen_int_dtypes = set()
535
+ seen_structs = set()
536
+ for buffer_type in all_buffer_types:
537
+ dtype = buffer_type.dtype
538
+ dtype_name = self._dtype_name(dtype)
539
+ if dtype.is_struct_or_union:
540
+ if dtype_name not in seen_structs:
541
+ seen_structs.add(dtype_name)
542
+ decl_code.putln(
543
+ f'ctypedef {dtype.kind} {dtype_name} "{dtype.empty_declaration_code()}": pass')
544
+
545
+ elif dtype.is_typedef:
546
+ if dtype_name not in seen_typedefs:
547
+ seen_typedefs.add(dtype_name)
548
+ decl_code.putln(
549
+ f'ctypedef {dtype.resolve()} {dtype_name} "{dtype.empty_declaration_code()}"')
550
+
551
+ # 'is_signed' is also needed for typedefs.
552
+ if dtype.is_int:
553
+ if str(dtype) not in seen_int_dtypes:
554
+ seen_int_dtypes.add(str(dtype))
555
+ dtype_type = self._dtype_type(dtype)
556
+ pyx_code['local_variable_declarations'].put_chunk(
557
+ f"""
558
+ cdef bint {dtype_name}_is_signed
559
+ {dtype_name}_is_signed = not (<{dtype_type}> -1 > 0)
560
+ """)
561
+
562
+ def _split_fused_types(self, arg):
563
+ """
564
+ Specialize fused types and split into normal types and buffer types.
565
+ """
566
+ specialized_types = PyrexTypes.get_specialized_types(arg.type)
567
+
568
+ # Prefer long over int, etc by sorting (see type classes in PyrexTypes.py)
569
+ specialized_types.sort()
570
+
571
+ seen_py_type_names = set()
572
+ normal_types, buffer_types, pythran_types = [], [], []
573
+ has_object_fallback = False
574
+ for specialized_type in specialized_types:
575
+ py_type_name = specialized_type.py_type_name()
576
+ if py_type_name:
577
+ if py_type_name in seen_py_type_names:
578
+ continue
579
+ seen_py_type_names.add(py_type_name)
580
+ if py_type_name == 'object':
581
+ has_object_fallback = True
582
+ else:
583
+ normal_types.append(specialized_type)
584
+ elif specialized_type.is_pythran_expr:
585
+ pythran_types.append(specialized_type)
586
+ elif specialized_type.is_buffer or specialized_type.is_memoryviewslice:
587
+ buffer_types.append(specialized_type)
588
+
589
+ return normal_types, buffer_types, pythran_types, has_object_fallback
590
+
591
+ def _unpack_argument(self, pyx_code, arg, arg_tuple_idx, min_positional_args, default_idx, env):
592
+ pyx_code.put_chunk(
593
+ f"""
594
+ # PROCESSING ARGUMENT {arg_tuple_idx}
595
+ if {arg_tuple_idx} < arg_count:
596
+ arg = (<tuple>args)[{arg_tuple_idx}]
597
+ elif kwargs is not None and '{arg.name}' in <dict>kwargs:
598
+ arg = (<dict>kwargs)['{arg.name}']
599
+ else:
600
+ """
601
+ )
602
+ pyx_code.indent()
603
+ if arg.default:
604
+ pyx_code.putln(
605
+ f"arg = (<tuple>defaults)[{default_idx}]")
606
+ else:
607
+ from .Code import UtilityCode
608
+ env.use_utility_code(
609
+ UtilityCode.load_cached("FusedFunctionArgTypeError", "CythonFunction.c"))
610
+ pyx_code.putln(
611
+ f'__Pyx_RaiseFusedFunctionArgTypeError("{arg.name}", {arg_tuple_idx}, {min_positional_args}, arg_count)')
612
+ pyx_code.dedent()
613
+
614
+ def make_fused_cpdef(self, orig_py_func, env, is_def):
615
+ """
616
+ This creates the function that is indexable from Python and does
617
+ runtime dispatch based on the argument types. The function gets the
618
+ arg tuple and kwargs dict (or None) and the defaults tuple
619
+ as arguments from the Binding Fused Function's tp_call.
620
+ """
621
+ from . import TreeFragment, Code, UtilityCode
622
+
623
+ min_positional_args = (
624
+ self.node.num_required_args - self.node.num_required_kw_args
625
+ if is_def else
626
+ sum(1 for arg in self.node.args if arg.default is None)
627
+ )
628
+
629
+ pyx_code = Code.PyxCodeWriter()
630
+ decl_code = Code.PyxCodeWriter()
631
+ type_mapper = Code.PyxCodeWriter()
632
+ decl_code.put_chunk(
633
+ """
634
+ cdef extern from *:
635
+ type __Pyx_ImportNumPyArrayTypeIfAvailable()
636
+
637
+ # from FusedFunction utility code
638
+ object __pyx_ff_match_signatures_single(dict signatures, dest_type)
639
+ object __pyx_ff_match_signatures(dict signatures, tuple dest_sig, dict sigindex)
640
+
641
+ # always raises:
642
+ int __Pyx_RaiseFusedFunctionArgTypeError(
643
+ object arg_name, Py_ssize_t arg_tuple_idx, Py_ssize_t min_positional_args, Py_ssize_t arg_count) except -1
644
+ """)
645
+ decl_code.indent()
646
+
647
+ pyx_code.put_chunk(
648
+ """
649
+ def __pyx_fused_cpdef(signatures, args, kwargs, defaults, _fused_sigindex={}):
650
+ # FIXME: use a typed signature - currently fails badly because
651
+ # default arguments inherit the types we specify here!
652
+
653
+ if kwargs is not None and not <dict> kwargs:
654
+ kwargs = None
655
+
656
+ arg_count = len(<tuple> args)
657
+
658
+ # instance check body
659
+ """)
660
+
661
+ pyx_code.indent() # indent following code to function body
662
+ pyx_code.named_insertion_point("imports")
663
+
664
+ fused_index = 0
665
+ default_idx = 0
666
+ all_buffer_types = OrderedSet()
667
+ seen_fused_types = set()
668
+ for i, arg in enumerate(self.node.args):
669
+ if arg.type.is_fused:
670
+ arg_fused_types = arg.type.get_fused_types()
671
+ if len(arg_fused_types) > 1:
672
+ raise NotImplementedError("Determination of more than one fused base "
673
+ "type per argument is not implemented.")
674
+ fused_type = arg_fused_types[0]
675
+
676
+ if arg.type.is_fused and fused_type not in seen_fused_types:
677
+ seen_fused_types.add(fused_type)
678
+
679
+ normal_types, buffer_types, pythran_types, has_object_fallback = self._split_fused_types(arg)
680
+ self._unpack_argument(pyx_code, arg, i, min_positional_args, default_idx, env)
681
+
682
+ mapper_arg_types = ['object', 'type']
683
+ mapper_arg_names = ['arg']
684
+ if buffer_types or pythran_types:
685
+ mapper_arg_names.append('ndarray')
686
+
687
+ mapper_sig = ', '.join(f"{atype} {aname}" for atype, aname in zip(mapper_arg_types, mapper_arg_names))
688
+ mapper_args = ', '.join(mapper_arg_names)
689
+
690
+ mapper_decl_code = type_mapper.insertion_point()
691
+ mapper_decl_code.put_chunk(
692
+ """
693
+ cdef extern from *:
694
+ void __pyx_PyErr_Clear "PyErr_Clear" ()
695
+ int __Pyx_Is_Little_Endian()
696
+ """
697
+ )
698
+ mapper_decl_code.indent()
699
+
700
+ type_mapper.putln('')
701
+ type_mapper.putln("@TYPE_MAPPER_CNAME_PLACEHOLDER")
702
+ with type_mapper.indenter(f"cdef str map_fused_type({mapper_sig}):"):
703
+
704
+ type_mapper.named_insertion_point("local_variable_declarations")
705
+
706
+ if normal_types:
707
+ self._fused_instance_checks(normal_types, type_mapper, env)
708
+
709
+ if buffer_types or pythran_types:
710
+ mapper_buffer_types = OrderedSet()
711
+ mapper_buffer_types.update(buffer_types)
712
+ mapper_buffer_types.update(ty.org_buffer for ty in pythran_types)
713
+
714
+ self._buffer_declarations(type_mapper, mapper_decl_code, mapper_buffer_types, pythran_types)
715
+
716
+ self._buffer_checks(
717
+ buffer_types, pythran_types, type_mapper, mapper_decl_code,
718
+ arg.accept_none, env)
719
+
720
+ type_mapper.putln("return 'object'" if has_object_fallback else "return None")
721
+
722
+ type_mapper_impl = type_mapper.getvalue()
723
+ type_mapper.reset()
724
+
725
+ # Generate a unique name for the mapper function based on type declarations and implementation.
726
+ impl_hash = hashlib.sha256(type_mapper_impl.encode('utf-8')).hexdigest()
727
+ type_mapper_cname = (
728
+ f"__pyx_ff_map_fused_{impl_hash[:6]}"
729
+ f"_{len(mapper_arg_names)}_{len(fused_type.types)}"
730
+ f"_{PyrexTypes.type_list_identifier(fused_type.types)}"
731
+ )
732
+ type_mapper_impl = type_mapper_impl.replace(
733
+ "\n@TYPE_MAPPER_CNAME_PLACEHOLDER\n", f"\n@cname('{type_mapper_cname}')\n")
734
+ # print(''.join(f"{i:3d} {line}" for i, line in enumerate(type_mapper_impl.splitlines(keepends=True))))
735
+
736
+ env.use_utility_code(
737
+ UtilityCode.CythonUtilityCode(type_mapper_impl, name=type_mapper_cname))
738
+
739
+ decl_code.putln(f"str {type_mapper_cname}({mapper_sig})")
740
+ pyx_code.putln(f"dest_sig{fused_index} = {type_mapper_cname}({mapper_args})")
741
+
742
+ fused_index += 1
743
+ all_buffer_types.update(buffer_types)
744
+ all_buffer_types.update(ty.org_buffer for ty in pythran_types)
745
+
746
+ if arg.default:
747
+ default_idx += 1
748
+
749
+ if all_buffer_types:
750
+ env.use_utility_code(
751
+ Code.UtilityCode.load_cached("IsLittleEndian", "ModuleSetupCode.c"))
752
+ env.use_utility_code(
753
+ Code.UtilityCode.load_cached("Import", "ImportExport.c"))
754
+ env.use_utility_code(
755
+ Code.UtilityCode.load_cached("ImportNumPyArray", "ImportExport.c"))
756
+
757
+ pyx_code['imports'].put_chunk(
758
+ """
759
+ cdef type ndarray
760
+ ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable()
761
+ """)
762
+
763
+ if len(seen_fused_types) == 1:
764
+ # Fast and common case: a single fused type across all arguments.
765
+ env.use_utility_code(
766
+ UtilityCode.CythonUtilityCode.load("match_signatures_single", "FusedFunction.pyx"))
767
+ pyx_code.put_chunk(
768
+ """
769
+ return __pyx_ff_match_signatures_single(<dict> signatures, dest_sig0)
770
+ """
771
+ )
772
+ else:
773
+ env.use_utility_code(
774
+ UtilityCode.CythonUtilityCode.load("match_signatures", "FusedFunction.pyx"))
775
+ dest_sig_tuple = ', '.join(f'dest_sig{i}' for i in range(len(seen_fused_types)))
776
+ pyx_code.put_chunk(
777
+ f"""
778
+ return __pyx_ff_match_signatures(<dict> signatures, ({dest_sig_tuple}), <dict> _fused_sigindex)
779
+ """
780
+ )
781
+
782
+ fragment_code = pyx_code.getvalue()
783
+ # print(decl_code.getvalue())
784
+ # print(fragment_code)
785
+ # print(''.join(f"{i:3d} {line}" for i, line in enumerate(fragment_code.splitlines(keepends=True))))
786
+ from .Optimize import ConstantFolding
787
+ fragment = TreeFragment.TreeFragment(
788
+ fragment_code, level='module', pipeline=[ConstantFolding()])
789
+ ast = TreeFragment.SetPosTransform(self.node.pos)(fragment.root)
790
+ UtilityCode.declare_declarations_in_scope(
791
+ decl_code.getvalue(), env.global_scope())
792
+ ast.scope = env
793
+ # FIXME: for static methods of cdef classes, we build the wrong signature here: first arg becomes 'self'
794
+ ast.analyse_declarations(env)
795
+ py_func = ast.stats[-1] # the DefNode
796
+ self.fragment_scope = ast.scope
797
+
798
+ if isinstance(self.node, DefNode):
799
+ py_func.specialized_cpdefs = self.nodes[:]
800
+ else:
801
+ py_func.specialized_cpdefs = [n.py_func for n in self.nodes]
802
+
803
+ return py_func
804
+
805
+ def attach_fused_py_funcs(self):
806
+ for node in self.nodes:
807
+ if isinstance(self.node, DefNode):
808
+ node.fused_py_func = self.py_func
809
+ else:
810
+ node.py_func.fused_py_func = self.py_func
811
+
812
+ def update_fused_defnode_entry(self, env):
813
+ copy_attributes = (
814
+ 'name', 'pos', 'cname', 'func_cname', 'pyfunc_cname',
815
+ 'pymethdef_cname', 'doc', 'doc_cname', 'is_member',
816
+ 'scope'
817
+ )
818
+
819
+ entry = self.py_func.entry
820
+
821
+ for attr in copy_attributes:
822
+ setattr(entry, attr,
823
+ getattr(self.orig_py_func.entry, attr))
824
+
825
+ self.py_func.name = self.orig_py_func.name
826
+ self.py_func.doc = self.orig_py_func.doc
827
+
828
+ env.entries.pop('__pyx_fused_cpdef', None)
829
+ if isinstance(self.node, DefNode):
830
+ env.entries[entry.name] = entry
831
+ else:
832
+ env.entries[entry.name].as_variable = entry
833
+
834
+ env.pyfunc_entries.append(entry)
835
+
836
+ self.py_func.entry.fused_cfunction = self
837
+ def_nodes = []
838
+ for node in self.nodes:
839
+ if isinstance(self.node, DefNode):
840
+ def_nodes.append(node)
841
+ else:
842
+ def_nodes.append(node.py_func)
843
+ node.entry.as_variable = entry
844
+
845
+ self.synthesize_defnodes(def_nodes)
846
+
847
+ def analyse_expressions(self, env):
848
+ """
849
+ Analyse the expressions. Take care to only evaluate default arguments
850
+ once and clone the result for all specializations
851
+ """
852
+ for fused_compound_type in self.fused_compound_types:
853
+ for fused_type in fused_compound_type.get_fused_types():
854
+ for specialization_type in fused_type.types:
855
+ if specialization_type.is_complex:
856
+ specialization_type.create_declaration_utility_code(env)
857
+
858
+ if self.py_func:
859
+ self.__signatures__ = self.__signatures__.analyse_expressions(env)
860
+ self.py_func = self.py_func.analyse_expressions(env)
861
+ self.resulting_fused_function = self.resulting_fused_function.analyse_expressions(env)
862
+ self.fused_func_assignment = self.fused_func_assignment.analyse_expressions(env)
863
+
864
+ self.defaults = defaults = []
865
+
866
+ for arg in self.node.args:
867
+ if arg.default:
868
+ arg.default = arg.default.analyse_expressions(env)
869
+ if arg.default.is_literal:
870
+ defaults.append(copy.copy(arg.default))
871
+ else:
872
+ # coerce the argument to temp since CloneNode really requires a temp
873
+ defaults.append(ProxyNode(arg.default.coerce_to_temp(env)))
874
+ else:
875
+ defaults.append(None)
876
+
877
+ for i, stat in enumerate(self.stats):
878
+ stat = self.stats[i] = stat.analyse_expressions(env)
879
+ if isinstance(stat, FuncDefNode) and stat is not self.py_func:
880
+ # the dispatcher specifically doesn't want its defaults overriding
881
+ for arg, default in zip(stat.args, defaults):
882
+ if default is not None:
883
+ if default.is_literal:
884
+ arg.default = default.coerce_to(arg.type, env)
885
+ else:
886
+ arg.default = CloneNode(default).analyse_expressions(env).coerce_to(arg.type, env)
887
+
888
+ if self.py_func:
889
+ args = [CloneNode(default) for default in defaults if default]
890
+ self.defaults_tuple = TupleNode(self.pos, args=args)
891
+ self.defaults_tuple = self.defaults_tuple.analyse_types(env, skip_children=True).coerce_to_pyobject(env)
892
+ self.defaults_tuple = ProxyNode(self.defaults_tuple)
893
+
894
+ fused_func = self.resulting_fused_function.arg
895
+ fused_func.defaults_tuple = CloneNode(self.defaults_tuple)
896
+
897
+ for i, pycfunc in enumerate(self.specialized_pycfuncs):
898
+ pycfunc = self.specialized_pycfuncs[i] = pycfunc.analyse_types(env)
899
+ pycfunc.defaults_tuple = CloneNode(self.defaults_tuple)
900
+ return self
901
+
902
+ def synthesize_defnodes(self, nodes):
903
+ """
904
+ Create the __signatures__ dict of PyCFunctionNode specializations.
905
+ """
906
+ # For the moment, fused functions do not support METH_FASTCALL
907
+ for node in nodes:
908
+ node.entry.signature.use_fastcall = node.entry.signature.FastcallUsed.NO
909
+
910
+ signatures = [StringEncoding.EncodedString(node.specialized_signature_string)
911
+ for node in nodes]
912
+ keys = [ExprNodes.UnicodeNode(node.pos, value=sig)
913
+ for node, sig in zip(nodes, signatures)]
914
+ values = [ExprNodes.PyCFunctionNode.from_defnode(node, binding=True)
915
+ for node in nodes]
916
+
917
+ self.__signatures__ = ExprNodes.DictNode.from_pairs(self.pos, zip(keys, values))
918
+
919
+ self.specialized_pycfuncs = values
920
+ for pycfuncnode in values:
921
+ pycfuncnode.is_specialization = True
922
+ # use code object from first defnode to get as close to a correct signature as possible
923
+ self.py_func.code_object = CodeObjectNode(nodes[0])
924
+
925
+ def generate_function_definitions(self, env, code):
926
+ if self.py_func:
927
+ self.py_func.pymethdef_required = True
928
+ self.fused_func_assignment.generate_function_definitions(env, code)
929
+
930
+ from . import Options
931
+ for stat in self.stats:
932
+ if isinstance(stat, FuncDefNode) and (
933
+ stat.entry.used or
934
+ (Options.cimport_from_pyx and not stat.entry.visibility == 'extern')):
935
+ code.mark_pos(stat.pos)
936
+ stat.generate_function_definitions(env, code)
937
+
938
+ def generate_execution_code(self, code):
939
+ # Note: all def function specialization are wrapped in PyCFunction
940
+ # nodes in the self.__signatures__ dictnode.
941
+ for default in self.defaults:
942
+ if default is not None:
943
+ default.generate_evaluation_code(code)
944
+
945
+ if self.py_func:
946
+ self.defaults_tuple.generate_evaluation_code(code)
947
+
948
+ super().generate_execution_code(code)
949
+
950
+ if self.__signatures__:
951
+ signatures = self.__signatures__
952
+ signatures.generate_evaluation_code(code)
953
+ fused_func = self.resulting_fused_function
954
+ fused_func.generate_evaluation_code(code)
955
+
956
+ code.putln(
957
+ f"__Pyx_as_FusedFunctionObject({fused_func.result()})->__signatures__ = {signatures.result()};")
958
+
959
+ signatures.generate_giveref(code)
960
+ signatures.generate_post_assignment_code(code)
961
+ signatures.free_temps(code)
962
+
963
+ self.fused_func_assignment.generate_execution_code(code)
964
+
965
+ # Dispose of results
966
+ fused_func.generate_disposal_code(code)
967
+ fused_func.free_temps(code)
968
+ self.defaults_tuple.generate_disposal_code(code)
969
+ self.defaults_tuple.free_temps(code)
970
+
971
+ for default in self.defaults:
972
+ if default is not None:
973
+ default.generate_disposal_code(code)
974
+ default.free_temps(code)
975
+
976
+ def annotate(self, code):
977
+ for stat in self.stats:
978
+ stat.annotate(code)