Cython 3.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (316) hide show
  1. Cython/Build/BuildExecutable.py +169 -0
  2. Cython/Build/Cache.py +199 -0
  3. Cython/Build/Cythonize.py +323 -0
  4. Cython/Build/Dependencies.py +1306 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +463 -0
  7. Cython/Build/IpythonMagic.py +560 -0
  8. Cython/Build/SharedModule.py +76 -0
  9. Cython/Build/Tests/TestCyCache.py +194 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +481 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +287 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +8 -0
  18. Cython/CodeWriter.py +811 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +326 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +680 -0
  23. Cython/Compiler/Builtin.py +934 -0
  24. Cython/Compiler/CmdLine.py +259 -0
  25. Cython/Compiler/Code.pxd +148 -0
  26. Cython/Compiler/Code.py +3375 -0
  27. Cython/Compiler/CodeGeneration.py +33 -0
  28. Cython/Compiler/CythonScope.py +187 -0
  29. Cython/Compiler/Dataclass.py +868 -0
  30. Cython/Compiler/DebugFlags.py +24 -0
  31. Cython/Compiler/Errors.py +295 -0
  32. Cython/Compiler/ExprNodes.py +15267 -0
  33. Cython/Compiler/FlowControl.pxd +97 -0
  34. Cython/Compiler/FlowControl.py +1455 -0
  35. Cython/Compiler/FusedNode.py +1002 -0
  36. Cython/Compiler/Future.py +16 -0
  37. Cython/Compiler/Interpreter.py +57 -0
  38. Cython/Compiler/Lexicon.py +340 -0
  39. Cython/Compiler/LineTable.py +114 -0
  40. Cython/Compiler/Main.py +853 -0
  41. Cython/Compiler/MatchCaseNodes.py +259 -0
  42. Cython/Compiler/MemoryView.py +922 -0
  43. Cython/Compiler/ModuleNode.py +4024 -0
  44. Cython/Compiler/Naming.py +374 -0
  45. Cython/Compiler/Nodes.py +10826 -0
  46. Cython/Compiler/Optimize.py +5256 -0
  47. Cython/Compiler/Options.py +835 -0
  48. Cython/Compiler/ParseTreeTransforms.pxd +77 -0
  49. Cython/Compiler/ParseTreeTransforms.py +4509 -0
  50. Cython/Compiler/Parsing.pxd +9 -0
  51. Cython/Compiler/Parsing.py +4789 -0
  52. Cython/Compiler/Pipeline.py +439 -0
  53. Cython/Compiler/PyrexTypes.py +5762 -0
  54. Cython/Compiler/Pythran.py +232 -0
  55. Cython/Compiler/Scanning.pxd +40 -0
  56. Cython/Compiler/Scanning.py +577 -0
  57. Cython/Compiler/StringEncoding.py +347 -0
  58. Cython/Compiler/Symtab.py +3080 -0
  59. Cython/Compiler/Tests/TestBuffer.py +105 -0
  60. Cython/Compiler/Tests/TestBuiltin.py +72 -0
  61. Cython/Compiler/Tests/TestCmdLine.py +586 -0
  62. Cython/Compiler/Tests/TestCode.py +86 -0
  63. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  64. Cython/Compiler/Tests/TestGrammar.py +202 -0
  65. Cython/Compiler/Tests/TestMemView.py +71 -0
  66. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  67. Cython/Compiler/Tests/TestScanning.py +134 -0
  68. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  69. Cython/Compiler/Tests/TestStringEncoding.py +33 -0
  70. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  71. Cython/Compiler/Tests/TestTreePath.py +103 -0
  72. Cython/Compiler/Tests/TestTypes.py +75 -0
  73. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  74. Cython/Compiler/Tests/TestVisitor.py +61 -0
  75. Cython/Compiler/Tests/Utils.py +36 -0
  76. Cython/Compiler/Tests/__init__.py +1 -0
  77. Cython/Compiler/TreeFragment.py +278 -0
  78. Cython/Compiler/TreePath.py +303 -0
  79. Cython/Compiler/TypeInference.py +584 -0
  80. Cython/Compiler/TypeSlots.py +1181 -0
  81. Cython/Compiler/UFuncs.py +311 -0
  82. Cython/Compiler/UtilNodes.py +389 -0
  83. Cython/Compiler/UtilityCode.py +344 -0
  84. Cython/Compiler/Version.py +8 -0
  85. Cython/Compiler/Visitor.pxd +53 -0
  86. Cython/Compiler/Visitor.py +861 -0
  87. Cython/Compiler/__init__.py +1 -0
  88. Cython/Coverage.py +448 -0
  89. Cython/Debugger/Cygdb.py +175 -0
  90. Cython/Debugger/DebugWriter.py +82 -0
  91. Cython/Debugger/Tests/TestLibCython.py +275 -0
  92. Cython/Debugger/Tests/__init__.py +1 -0
  93. Cython/Debugger/Tests/cfuncs.c +8 -0
  94. Cython/Debugger/Tests/codefile +49 -0
  95. Cython/Debugger/Tests/test_libcython_in_gdb.py +578 -0
  96. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  97. Cython/Debugger/__init__.py +1 -0
  98. Cython/Debugger/libcython.py +1548 -0
  99. Cython/Debugger/libpython.py +2821 -0
  100. Cython/Debugging.py +20 -0
  101. Cython/Distutils/__init__.py +2 -0
  102. Cython/Distutils/build_ext.py +139 -0
  103. Cython/Distutils/extension.py +96 -0
  104. Cython/Distutils/old_build_ext.py +351 -0
  105. Cython/Includes/cpython/__init__.pxd +173 -0
  106. Cython/Includes/cpython/array.pxd +174 -0
  107. Cython/Includes/cpython/bool.pxd +37 -0
  108. Cython/Includes/cpython/buffer.pxd +112 -0
  109. Cython/Includes/cpython/bytearray.pxd +33 -0
  110. Cython/Includes/cpython/bytes.pxd +200 -0
  111. Cython/Includes/cpython/cellobject.pxd +35 -0
  112. Cython/Includes/cpython/ceval.pxd +8 -0
  113. Cython/Includes/cpython/codecs.pxd +121 -0
  114. Cython/Includes/cpython/complex.pxd +60 -0
  115. Cython/Includes/cpython/contextvars.pxd +145 -0
  116. Cython/Includes/cpython/conversion.pxd +36 -0
  117. Cython/Includes/cpython/datetime.pxd +395 -0
  118. Cython/Includes/cpython/descr.pxd +26 -0
  119. Cython/Includes/cpython/dict.pxd +187 -0
  120. Cython/Includes/cpython/exc.pxd +263 -0
  121. Cython/Includes/cpython/fileobject.pxd +57 -0
  122. Cython/Includes/cpython/float.pxd +47 -0
  123. Cython/Includes/cpython/function.pxd +65 -0
  124. Cython/Includes/cpython/genobject.pxd +25 -0
  125. Cython/Includes/cpython/getargs.pxd +12 -0
  126. Cython/Includes/cpython/instance.pxd +25 -0
  127. Cython/Includes/cpython/iterator.pxd +36 -0
  128. Cython/Includes/cpython/iterobject.pxd +24 -0
  129. Cython/Includes/cpython/list.pxd +92 -0
  130. Cython/Includes/cpython/long.pxd +149 -0
  131. Cython/Includes/cpython/longintrepr.pxd +14 -0
  132. Cython/Includes/cpython/mapping.pxd +63 -0
  133. Cython/Includes/cpython/marshal.pxd +66 -0
  134. Cython/Includes/cpython/mem.pxd +120 -0
  135. Cython/Includes/cpython/memoryview.pxd +50 -0
  136. Cython/Includes/cpython/method.pxd +49 -0
  137. Cython/Includes/cpython/module.pxd +208 -0
  138. Cython/Includes/cpython/number.pxd +258 -0
  139. Cython/Includes/cpython/object.pxd +433 -0
  140. Cython/Includes/cpython/pycapsule.pxd +143 -0
  141. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  142. Cython/Includes/cpython/pyport.pxd +8 -0
  143. Cython/Includes/cpython/pystate.pxd +95 -0
  144. Cython/Includes/cpython/pythread.pxd +53 -0
  145. Cython/Includes/cpython/ref.pxd +67 -0
  146. Cython/Includes/cpython/sequence.pxd +134 -0
  147. Cython/Includes/cpython/set.pxd +119 -0
  148. Cython/Includes/cpython/slice.pxd +70 -0
  149. Cython/Includes/cpython/time.pxd +129 -0
  150. Cython/Includes/cpython/tuple.pxd +72 -0
  151. Cython/Includes/cpython/type.pxd +53 -0
  152. Cython/Includes/cpython/unicode.pxd +639 -0
  153. Cython/Includes/cpython/version.pxd +32 -0
  154. Cython/Includes/cpython/weakref.pxd +78 -0
  155. Cython/Includes/libc/__init__.pxd +1 -0
  156. Cython/Includes/libc/complex.pxd +35 -0
  157. Cython/Includes/libc/errno.pxd +127 -0
  158. Cython/Includes/libc/float.pxd +43 -0
  159. Cython/Includes/libc/limits.pxd +28 -0
  160. Cython/Includes/libc/locale.pxd +46 -0
  161. Cython/Includes/libc/math.pxd +209 -0
  162. Cython/Includes/libc/setjmp.pxd +10 -0
  163. Cython/Includes/libc/signal.pxd +64 -0
  164. Cython/Includes/libc/stddef.pxd +9 -0
  165. Cython/Includes/libc/stdint.pxd +105 -0
  166. Cython/Includes/libc/stdio.pxd +80 -0
  167. Cython/Includes/libc/stdlib.pxd +72 -0
  168. Cython/Includes/libc/string.pxd +50 -0
  169. Cython/Includes/libc/threads.pxd +84 -0
  170. Cython/Includes/libc/time.pxd +51 -0
  171. Cython/Includes/libcpp/__init__.pxd +4 -0
  172. Cython/Includes/libcpp/algorithm.pxd +320 -0
  173. Cython/Includes/libcpp/any.pxd +16 -0
  174. Cython/Includes/libcpp/atomic.pxd +59 -0
  175. Cython/Includes/libcpp/barrier.pxd +22 -0
  176. Cython/Includes/libcpp/bit.pxd +29 -0
  177. Cython/Includes/libcpp/cast.pxd +12 -0
  178. Cython/Includes/libcpp/cmath.pxd +518 -0
  179. Cython/Includes/libcpp/complex.pxd +106 -0
  180. Cython/Includes/libcpp/deque.pxd +165 -0
  181. Cython/Includes/libcpp/exception.pxd +86 -0
  182. Cython/Includes/libcpp/execution.pxd +15 -0
  183. Cython/Includes/libcpp/forward_list.pxd +63 -0
  184. Cython/Includes/libcpp/functional.pxd +26 -0
  185. Cython/Includes/libcpp/future.pxd +103 -0
  186. Cython/Includes/libcpp/iterator.pxd +34 -0
  187. Cython/Includes/libcpp/latch.pxd +17 -0
  188. Cython/Includes/libcpp/limits.pxd +61 -0
  189. Cython/Includes/libcpp/list.pxd +117 -0
  190. Cython/Includes/libcpp/map.pxd +252 -0
  191. Cython/Includes/libcpp/memory.pxd +115 -0
  192. Cython/Includes/libcpp/mutex.pxd +130 -0
  193. Cython/Includes/libcpp/numbers.pxd +15 -0
  194. Cython/Includes/libcpp/numeric.pxd +131 -0
  195. Cython/Includes/libcpp/optional.pxd +34 -0
  196. Cython/Includes/libcpp/pair.pxd +1 -0
  197. Cython/Includes/libcpp/queue.pxd +25 -0
  198. Cython/Includes/libcpp/random.pxd +166 -0
  199. Cython/Includes/libcpp/semaphore.pxd +44 -0
  200. Cython/Includes/libcpp/set.pxd +228 -0
  201. Cython/Includes/libcpp/shared_mutex.pxd +72 -0
  202. Cython/Includes/libcpp/span.pxd +87 -0
  203. Cython/Includes/libcpp/stack.pxd +11 -0
  204. Cython/Includes/libcpp/stop_token.pxd +105 -0
  205. Cython/Includes/libcpp/string.pxd +355 -0
  206. Cython/Includes/libcpp/string_view.pxd +181 -0
  207. Cython/Includes/libcpp/typeindex.pxd +15 -0
  208. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  209. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  210. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  211. Cython/Includes/libcpp/utility.pxd +30 -0
  212. Cython/Includes/libcpp/vector.pxd +186 -0
  213. Cython/Includes/openmp.pxd +50 -0
  214. Cython/Includes/posix/__init__.pxd +1 -0
  215. Cython/Includes/posix/dlfcn.pxd +14 -0
  216. Cython/Includes/posix/fcntl.pxd +86 -0
  217. Cython/Includes/posix/ioctl.pxd +4 -0
  218. Cython/Includes/posix/mman.pxd +101 -0
  219. Cython/Includes/posix/resource.pxd +57 -0
  220. Cython/Includes/posix/select.pxd +21 -0
  221. Cython/Includes/posix/signal.pxd +73 -0
  222. Cython/Includes/posix/stat.pxd +98 -0
  223. Cython/Includes/posix/stdio.pxd +37 -0
  224. Cython/Includes/posix/stdlib.pxd +29 -0
  225. Cython/Includes/posix/strings.pxd +9 -0
  226. Cython/Includes/posix/time.pxd +71 -0
  227. Cython/Includes/posix/types.pxd +30 -0
  228. Cython/Includes/posix/uio.pxd +26 -0
  229. Cython/Includes/posix/unistd.pxd +271 -0
  230. Cython/Includes/posix/wait.pxd +38 -0
  231. Cython/Plex/Actions.pxd +24 -0
  232. Cython/Plex/Actions.py +119 -0
  233. Cython/Plex/DFA.pxd +14 -0
  234. Cython/Plex/DFA.py +164 -0
  235. Cython/Plex/Errors.py +48 -0
  236. Cython/Plex/Lexicons.py +178 -0
  237. Cython/Plex/Machines.pxd +36 -0
  238. Cython/Plex/Machines.py +238 -0
  239. Cython/Plex/Regexps.py +539 -0
  240. Cython/Plex/Scanners.pxd +47 -0
  241. Cython/Plex/Scanners.py +360 -0
  242. Cython/Plex/Transitions.pxd +14 -0
  243. Cython/Plex/Transitions.py +239 -0
  244. Cython/Plex/__init__.py +34 -0
  245. Cython/Runtime/__init__.py +1 -0
  246. Cython/Runtime/refnanny.pyx +237 -0
  247. Cython/Shadow.py +690 -0
  248. Cython/Shadow.pyi +521 -0
  249. Cython/StringIOTree.py +170 -0
  250. Cython/Tempita/__init__.py +4 -0
  251. Cython/Tempita/_looper.py +154 -0
  252. Cython/Tempita/_tempita.py +1091 -0
  253. Cython/TestUtils.py +410 -0
  254. Cython/Tests/TestCodeWriter.py +128 -0
  255. Cython/Tests/TestCythonUtils.py +202 -0
  256. Cython/Tests/TestJediTyper.py +223 -0
  257. Cython/Tests/TestShadow.py +114 -0
  258. Cython/Tests/TestStringIOTree.py +67 -0
  259. Cython/Tests/TestTestUtils.py +90 -0
  260. Cython/Tests/__init__.py +1 -0
  261. Cython/Tests/xmlrunner.py +390 -0
  262. Cython/Utility/AsyncGen.c +1002 -0
  263. Cython/Utility/Buffer.c +875 -0
  264. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  265. Cython/Utility/Builtins.c +776 -0
  266. Cython/Utility/CConvert.pyx +134 -0
  267. Cython/Utility/CMath.c +104 -0
  268. Cython/Utility/CommonStructures.c +118 -0
  269. Cython/Utility/Complex.c +378 -0
  270. Cython/Utility/Coroutine.c +2206 -0
  271. Cython/Utility/CpdefEnums.pyx +103 -0
  272. Cython/Utility/CppConvert.pyx +279 -0
  273. Cython/Utility/CppSupport.cpp +143 -0
  274. Cython/Utility/CythonFunction.c +1794 -0
  275. Cython/Utility/Dataclasses.c +185 -0
  276. Cython/Utility/Dataclasses.py +112 -0
  277. Cython/Utility/Embed.c +125 -0
  278. Cython/Utility/Exceptions.c +1012 -0
  279. Cython/Utility/ExtensionTypes.c +809 -0
  280. Cython/Utility/FunctionArguments.c +965 -0
  281. Cython/Utility/ImportExport.c +987 -0
  282. Cython/Utility/Lock.c +136 -0
  283. Cython/Utility/MemoryView.pxd +187 -0
  284. Cython/Utility/MemoryView.pyx +1481 -0
  285. Cython/Utility/MemoryView_C.c +1046 -0
  286. Cython/Utility/ModuleSetupCode.c +3059 -0
  287. Cython/Utility/NumpyImportArray.c +46 -0
  288. Cython/Utility/ObjectHandling.c +3342 -0
  289. Cython/Utility/Optimize.c +1589 -0
  290. Cython/Utility/Overflow.c +404 -0
  291. Cython/Utility/Printing.c +86 -0
  292. Cython/Utility/Profile.c +709 -0
  293. Cython/Utility/StringTools.c +1259 -0
  294. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  295. Cython/Utility/TestCythonScope.pyx +75 -0
  296. Cython/Utility/TestUtilityLoader.c +12 -0
  297. Cython/Utility/TypeConversion.c +1284 -0
  298. Cython/Utility/UFuncs.pyx +50 -0
  299. Cython/Utility/UFuncs_C.c +89 -0
  300. Cython/Utility/__init__.py +28 -0
  301. Cython/Utility/arrayarray.h +148 -0
  302. Cython/Utils.py +687 -0
  303. Cython/__init__.py +10 -0
  304. Cython/__init__.pyi +7 -0
  305. Cython/py.typed +0 -0
  306. cython-3.1.0.dist-info/COPYING.txt +19 -0
  307. cython-3.1.0.dist-info/LICENSE.txt +176 -0
  308. cython-3.1.0.dist-info/METADATA +636 -0
  309. cython-3.1.0.dist-info/RECORD +316 -0
  310. cython-3.1.0.dist-info/WHEEL +5 -0
  311. cython-3.1.0.dist-info/entry_points.txt +4 -0
  312. cython-3.1.0.dist-info/top_level.txt +3 -0
  313. cython.py +29 -0
  314. pyximport/__init__.py +4 -0
  315. pyximport/pyxbuild.py +160 -0
  316. pyximport/pyximport.py +482 -0
@@ -0,0 +1,1002 @@
1
+ import copy
2
+
3
+ from . import (ExprNodes, PyrexTypes, MemoryView,
4
+ ParseTreeTransforms, StringEncoding, Errors,
5
+ Naming)
6
+ from .ExprNodes import CloneNode, CodeObjectNode, ProxyNode, TupleNode
7
+ from .Nodes import FuncDefNode, StatListNode, DefNode
8
+ from ..Utils import OrderedSet
9
+ from .Errors import error, CannotSpecialize
10
+
11
+
12
+ class FusedCFuncDefNode(StatListNode):
13
+ """
14
+ This node replaces a function with fused arguments. It deep-copies the
15
+ function for every permutation of fused types, and allocates a new local
16
+ scope for it. It keeps track of the original function in self.node, and
17
+ the entry of the original function in the symbol table is given the
18
+ 'fused_cfunction' attribute which points back to us.
19
+ Then when a function lookup occurs (to e.g. call it), the call can be
20
+ dispatched to the right function.
21
+
22
+ node FuncDefNode the original function
23
+ nodes [FuncDefNode] list of copies of node with different specific types
24
+ py_func DefNode the fused python function subscriptable from
25
+ Python space
26
+ __signatures__ A DictNode mapping signature specialization strings
27
+ to PyCFunction nodes
28
+ resulting_fused_function PyCFunction for the fused DefNode that delegates
29
+ to specializations
30
+ fused_func_assignment Assignment of the fused function to the function name
31
+ defaults_tuple TupleNode of defaults (letting PyCFunctionNode build
32
+ defaults would result in many different tuples)
33
+ specialized_pycfuncs List of synthesized pycfunction nodes for the
34
+ specializations
35
+
36
+ fused_compound_types All fused (compound) types (e.g. floating[:])
37
+ """
38
+
39
+ __signatures__ = None
40
+ resulting_fused_function = None
41
+ fused_func_assignment = None
42
+ py_func = None
43
+ defaults_tuple = None
44
+ decorators = None
45
+
46
+ child_attrs = StatListNode.child_attrs + [
47
+ '__signatures__', 'resulting_fused_function', 'fused_func_assignment']
48
+
49
+ def __init__(self, node, env):
50
+ super().__init__(node.pos)
51
+
52
+ self.nodes = []
53
+ self.node = node
54
+
55
+ is_def = isinstance(self.node, DefNode)
56
+ if is_def:
57
+ # self.node.decorators = []
58
+ self.copy_def(env)
59
+ else:
60
+ self.copy_cdef(env)
61
+
62
+ # Perform some sanity checks. If anything fails, it's a bug
63
+ for n in self.nodes:
64
+ assert not n.entry.type.is_fused
65
+ assert not n.local_scope.return_type.is_fused
66
+ if node.return_type.is_fused:
67
+ assert not n.return_type.is_fused
68
+
69
+ if not is_def and n.cfunc_declarator.optional_arg_count:
70
+ assert n.type.op_arg_struct
71
+
72
+ node.entry.fused_cfunction = self
73
+ # Copy the nodes as AnalyseDeclarationsTransform will prepend
74
+ # self.py_func to self.stats, as we only want specialized
75
+ # CFuncDefNodes in self.nodes
76
+ self.stats = self.nodes[:]
77
+
78
+ def copy_def(self, env):
79
+ """
80
+ Create a copy of the original def or lambda function for specialized
81
+ versions.
82
+ """
83
+ fused_compound_types = PyrexTypes.unique(
84
+ [arg.type for arg in self.node.args if arg.type.is_fused])
85
+ fused_types = self._get_fused_base_types(fused_compound_types)
86
+ permutations = PyrexTypes.get_all_specialized_permutations(fused_types)
87
+
88
+ self.fused_compound_types = fused_compound_types
89
+
90
+ if self.node.entry in env.pyfunc_entries:
91
+ env.pyfunc_entries.remove(self.node.entry)
92
+
93
+ for cname, fused_to_specific in permutations:
94
+ copied_node = copy.deepcopy(self.node)
95
+ # keep signature object identity for special casing in DefNode.analyse_declarations()
96
+ copied_node.entry.signature = self.node.entry.signature
97
+
98
+ self._specialize_function_args(copied_node.args, fused_to_specific)
99
+ copied_node.return_type = self.node.return_type.specialize(
100
+ fused_to_specific)
101
+ copied_node.code_object = CodeObjectNode(copied_node)
102
+ copied_node.analyse_declarations(env)
103
+ # copied_node.is_staticmethod = self.node.is_staticmethod
104
+ # copied_node.is_classmethod = self.node.is_classmethod
105
+ self.create_new_local_scope(copied_node, env, fused_to_specific)
106
+ self.specialize_copied_def(copied_node, cname, self.node.entry,
107
+ fused_to_specific, fused_compound_types)
108
+
109
+ PyrexTypes.specialize_entry(copied_node.entry, cname)
110
+ copied_node.entry.used = True
111
+ env.entries[copied_node.entry.name] = copied_node.entry
112
+
113
+ specialised_type_names = [
114
+ sarg.type.declaration_code('', for_display=True)
115
+ for (farg, sarg) in zip(self.node.args, copied_node.args)
116
+ if farg.type.is_fused
117
+ ]
118
+ copied_node.name = StringEncoding.EncodedString(f"{copied_node.name}[{','.join(specialised_type_names)}]")
119
+
120
+ if not self.replace_fused_typechecks(copied_node):
121
+ break
122
+
123
+ self.orig_py_func = self.node
124
+ self.py_func = self.make_fused_cpdef(self.node, env, is_def=True)
125
+ self.py_func.code_object = CodeObjectNode(self.py_func)
126
+
127
+ def copy_cdef(self, env):
128
+ """
129
+ Create a copy of the original c(p)def function for all specialized
130
+ versions.
131
+ """
132
+ permutations = self.node.type.get_all_specialized_permutations()
133
+ # print 'Node %s has %d specializations:' % (self.node.entry.name,
134
+ # len(permutations))
135
+ # import pprint; pprint.pprint([d for cname, d in permutations])
136
+
137
+ # Prevent copying of the python function
138
+ self.orig_py_func = orig_py_func = self.node.py_func
139
+ self.node.py_func = None
140
+ if orig_py_func:
141
+ env.pyfunc_entries.remove(orig_py_func.entry)
142
+
143
+ fused_types = self.node.type.get_fused_types()
144
+ self.fused_compound_types = fused_types
145
+
146
+ new_cfunc_entries = []
147
+ for cname, fused_to_specific in permutations:
148
+ copied_node = copy.deepcopy(self.node)
149
+
150
+ # Make the types in our CFuncType specific.
151
+ try:
152
+ type = copied_node.type.specialize(fused_to_specific)
153
+ except CannotSpecialize:
154
+ # unlike for the argument types, specializing the return type can fail
155
+ error(copied_node.pos, "Return type is a fused type that cannot "
156
+ "be determined from the function arguments")
157
+ self.py_func = None # this is just to let the compiler exit gracefully
158
+ return
159
+ entry = copied_node.entry
160
+ type.specialize_entry(entry, cname)
161
+
162
+ # Reuse existing Entries (e.g. from .pxd files).
163
+ for orig_entry in env.cfunc_entries:
164
+ if entry.cname == orig_entry.cname and type.same_as_resolved_type(orig_entry.type):
165
+ copied_node.entry = orig_entry
166
+ if not copied_node.entry.func_cname:
167
+ copied_node.entry.func_cname = entry.func_cname
168
+ entry = orig_entry
169
+ type = orig_entry.type
170
+ break
171
+ else:
172
+ new_cfunc_entries.append(entry)
173
+
174
+ copied_node.type = type
175
+ entry.type, type.entry = type, entry
176
+
177
+ entry.used = (entry.used or
178
+ self.node.entry.defined_in_pxd or
179
+ env.is_c_class_scope or
180
+ entry.is_cmethod)
181
+
182
+ if self.node.cfunc_declarator.optional_arg_count:
183
+ self.node.cfunc_declarator.declare_optional_arg_struct(
184
+ type, env, fused_cname=cname)
185
+
186
+ copied_node.return_type = type.return_type
187
+ self.create_new_local_scope(copied_node, env, fused_to_specific)
188
+
189
+ # Make the argument types in the CFuncDeclarator specific
190
+ self._specialize_function_args(copied_node.cfunc_declarator.args,
191
+ fused_to_specific)
192
+
193
+ # If a cpdef, declare all specialized cpdefs (this
194
+ # also calls analyse_declarations)
195
+ copied_node.declare_cpdef_wrapper(env)
196
+ if copied_node.py_func:
197
+ env.pyfunc_entries.remove(copied_node.py_func.entry)
198
+
199
+ self.specialize_copied_def(
200
+ copied_node.py_func, cname, self.node.entry.as_variable,
201
+ fused_to_specific, fused_types)
202
+
203
+ if not self.replace_fused_typechecks(copied_node):
204
+ break
205
+
206
+ # replace old entry with new entries
207
+ if self.node.entry in env.cfunc_entries:
208
+ cindex = env.cfunc_entries.index(self.node.entry)
209
+ env.cfunc_entries[cindex:cindex+1] = new_cfunc_entries
210
+ else:
211
+ env.cfunc_entries.extend(new_cfunc_entries)
212
+
213
+ if orig_py_func:
214
+ self.py_func = self.make_fused_cpdef(orig_py_func, env,
215
+ is_def=False)
216
+ else:
217
+ self.py_func = orig_py_func
218
+
219
+ def _get_fused_base_types(self, fused_compound_types):
220
+ """
221
+ Get a list of unique basic fused types, from a list of
222
+ (possibly) compound fused types.
223
+ """
224
+ base_types = []
225
+ seen = set()
226
+ for fused_type in fused_compound_types:
227
+ fused_type.get_fused_types(result=base_types, seen=seen)
228
+ return base_types
229
+
230
+ def _specialize_function_args(self, args, fused_to_specific):
231
+ for arg in args:
232
+ if arg.type.is_fused:
233
+ arg.type = arg.type.specialize(fused_to_specific)
234
+ if arg.type.is_memoryviewslice:
235
+ arg.type.validate_memslice_dtype(arg.pos)
236
+ if arg.annotation:
237
+ # TODO might be nice if annotations were specialized instead?
238
+ # (Or might be hard to do reliably)
239
+ arg.annotation.untyped = True
240
+
241
+ def create_new_local_scope(self, node, env, f2s):
242
+ """
243
+ Create a new local scope for the copied node and append it to
244
+ self.nodes. A new local scope is needed because the arguments with the
245
+ fused types are already in the local scope, and we need the specialized
246
+ entries created after analyse_declarations on each specialized version
247
+ of the (CFunc)DefNode.
248
+ f2s is a dict mapping each fused type to its specialized version
249
+ """
250
+ node.create_local_scope(env)
251
+ node.local_scope.fused_to_specific = f2s
252
+
253
+ # This is copied from the original function, set it to false to
254
+ # stop recursion
255
+ node.has_fused_arguments = False
256
+ self.nodes.append(node)
257
+
258
+ def specialize_copied_def(self, node, cname, py_entry, f2s, fused_compound_types):
259
+ """Specialize the copy of a DefNode given the copied node,
260
+ the specialization cname and the original DefNode entry"""
261
+ fused_types = self._get_fused_base_types(fused_compound_types)
262
+ type_strings = [
263
+ PyrexTypes.specialization_signature_string(fused_type, f2s)
264
+ for fused_type in fused_types
265
+ ]
266
+
267
+ node.specialized_signature_string = '|'.join(type_strings)
268
+
269
+ node.entry.pymethdef_cname = PyrexTypes.get_fused_cname(
270
+ cname, node.entry.pymethdef_cname)
271
+ node.entry.doc = py_entry.doc
272
+ node.entry.doc_cname = py_entry.doc_cname
273
+
274
+ def replace_fused_typechecks(self, copied_node):
275
+ """
276
+ Branch-prune fused type checks like
277
+
278
+ if fused_t is int:
279
+ ...
280
+
281
+ Returns whether an error was issued and whether we should stop in
282
+ in order to prevent a flood of errors.
283
+ """
284
+ num_errors = Errors.get_errors_count()
285
+ transform = ParseTreeTransforms.ReplaceFusedTypeChecks(
286
+ copied_node.local_scope)
287
+ transform(copied_node)
288
+
289
+ if Errors.get_errors_count() > num_errors:
290
+ return False
291
+
292
+ return True
293
+
294
+ def _fused_instance_checks(self, normal_types, pyx_code, env):
295
+ """
296
+ Generate Cython code for instance checks, matching an object to
297
+ specialized types.
298
+ """
299
+ for specialized_type in normal_types:
300
+ # all_numeric = all_numeric and specialized_type.is_numeric
301
+ py_type_name = specialized_type.py_type_name()
302
+ pyx_code.context.update(
303
+ py_type_name=py_type_name,
304
+ specialized_type_name=specialized_type.specialization_string,
305
+ )
306
+ pyx_code.put_chunk(
307
+ """
308
+ if isinstance(arg, {{py_type_name}}):
309
+ dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'; break
310
+ """)
311
+
312
+ def _dtype_name(self, dtype):
313
+ name = str(dtype).replace('_', '__').replace(' ', '_')
314
+ if dtype.is_typedef:
315
+ name = Naming.fused_dtype_prefix + name
316
+ return name
317
+
318
+ def _dtype_type(self, dtype):
319
+ if dtype.is_typedef:
320
+ return self._dtype_name(dtype)
321
+ return str(dtype)
322
+
323
+ def _sizeof_dtype(self, dtype):
324
+ if dtype.is_pyobject:
325
+ return 'sizeof(void *)'
326
+ else:
327
+ return "sizeof(%s)" % self._dtype_type(dtype)
328
+
329
+ def _buffer_check_numpy_dtype_setup_cases(self, pyx_code):
330
+ "Setup some common cases to match dtypes against specializations"
331
+ with pyx_code.indenter("if kind in u'iu':"):
332
+ pyx_code.putln("pass")
333
+ pyx_code.named_insertion_point("dtype_int")
334
+
335
+ with pyx_code.indenter("elif kind == u'f':"):
336
+ pyx_code.putln("pass")
337
+ pyx_code.named_insertion_point("dtype_float")
338
+
339
+ with pyx_code.indenter("elif kind == u'c':"):
340
+ pyx_code.putln("pass")
341
+ pyx_code.named_insertion_point("dtype_complex")
342
+
343
+ match = "dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'"
344
+ no_match = "dest_sig[{{dest_sig_idx}}] = None"
345
+ def _buffer_check_numpy_dtype(self, pyx_code, specialized_buffer_types, pythran_types):
346
+ """
347
+ Match a numpy dtype object to the individual specializations.
348
+ """
349
+ self._buffer_check_numpy_dtype_setup_cases(pyx_code)
350
+
351
+ for specialized_type in pythran_types+specialized_buffer_types:
352
+ final_type = specialized_type
353
+ if specialized_type.is_pythran_expr:
354
+ specialized_type = specialized_type.org_buffer
355
+ dtype = specialized_type.dtype
356
+ pyx_code.context.update(
357
+ itemsize_match=self._sizeof_dtype(dtype) + " == itemsize",
358
+ signed_match="not (%s_is_signed ^ dtype_signed)" % self._dtype_name(dtype),
359
+ dtype=dtype,
360
+ specialized_type_name=final_type.specialization_string)
361
+
362
+ dtypes = [
363
+ (dtype.is_int, pyx_code['dtype_int']),
364
+ (dtype.is_float, pyx_code['dtype_float']),
365
+ (dtype.is_complex, pyx_code['dtype_complex'])
366
+ ]
367
+
368
+ for dtype_category, codewriter in dtypes:
369
+ if not dtype_category:
370
+ continue
371
+ cond = '{{itemsize_match}} and (<Py_ssize_t>arg.ndim) == %d' % (
372
+ specialized_type.ndim,)
373
+ if dtype.is_int:
374
+ cond += ' and {{signed_match}}'
375
+
376
+ if final_type.is_pythran_expr:
377
+ cond += ' and arg_is_pythran_compatible'
378
+
379
+ with codewriter.indenter("if %s:" % cond):
380
+ #codewriter.putln("print 'buffer match found based on numpy dtype'")
381
+ codewriter.putln(self.match)
382
+ codewriter.putln("break")
383
+
384
+ def _buffer_parse_format_string_check(self, pyx_code, decl_code,
385
+ specialized_type, env):
386
+ """
387
+ For each specialized type, try to coerce the object to a memoryview
388
+ slice of that type. This means obtaining a buffer and parsing the
389
+ format string.
390
+ TODO: separate buffer acquisition from format parsing
391
+ """
392
+ dtype = specialized_type.dtype
393
+ if specialized_type.is_buffer:
394
+ axes = [('direct', 'strided')] * specialized_type.ndim
395
+ else:
396
+ axes = specialized_type.axes
397
+
398
+ memslice_type = PyrexTypes.MemoryViewSliceType(dtype, axes)
399
+ memslice_type.create_from_py_utility_code(env)
400
+ pyx_code.context.update(
401
+ coerce_from_py_func=memslice_type.from_py_function,
402
+ dtype=dtype)
403
+ decl_code.putln(
404
+ "{{memviewslice_cname}} {{coerce_from_py_func}}(object, int)")
405
+
406
+ pyx_code.context.update(
407
+ specialized_type_name=specialized_type.specialization_string,
408
+ sizeof_dtype=self._sizeof_dtype(dtype),
409
+ ndim_dtype=specialized_type.ndim)
410
+
411
+ # use the memoryview object to check itemsize and ndim.
412
+ # In principle it could check more, but these are the easiest to do quickly
413
+ pyx_code.put_chunk(
414
+ """
415
+ # try {{dtype}}
416
+ if (((itemsize == -1 and arg_as_memoryview.itemsize == {{sizeof_dtype}})
417
+ or itemsize == {{sizeof_dtype}})
418
+ and arg_as_memoryview.ndim == {{ndim_dtype}}):
419
+ memslice = {{coerce_from_py_func}}(arg_as_memoryview, 0)
420
+ if memslice.memview:
421
+ __PYX_XCLEAR_MEMVIEW(&memslice, 1)
422
+ # print 'found a match for the buffer through format parsing'
423
+ %s
424
+ break
425
+ else:
426
+ __pyx_PyErr_Clear()
427
+ """ % self.match)
428
+
429
+ def _buffer_checks(self, buffer_types, pythran_types, pyx_code, decl_code, accept_none, env):
430
+ """
431
+ Generate Cython code to match objects to buffer specializations.
432
+ First try to get a numpy dtype object and match it against the individual
433
+ specializations. If that fails, try naively to coerce the object
434
+ to each specialization, which obtains the buffer each time and tries
435
+ to match the format string.
436
+ """
437
+ # The first thing to find a match in this loop breaks out of the loop
438
+ pyx_code.put_chunk(
439
+ """
440
+ """ + ("arg_is_pythran_compatible = False" if pythran_types else "") + """
441
+ if ndarray is not None:
442
+ if isinstance(arg, ndarray):
443
+ dtype = arg.dtype
444
+ """ + ("arg_is_pythran_compatible = True" if pythran_types else "") + """
445
+ elif __pyx_memoryview_check(arg):
446
+ arg_base = arg.base
447
+ if isinstance(arg_base, ndarray):
448
+ dtype = arg_base.dtype
449
+ else:
450
+ dtype = None
451
+ else:
452
+ dtype = None
453
+
454
+ itemsize = -1
455
+ if dtype is not None:
456
+ itemsize = dtype.itemsize
457
+ kind = ord(dtype.kind)
458
+ dtype_signed = kind == u'i'
459
+ """)
460
+ pyx_code.indent(2)
461
+ if pythran_types:
462
+ pyx_code.put_chunk(
463
+ """
464
+ # Pythran only supports the endianness of the current compiler
465
+ byteorder = dtype.byteorder
466
+ if byteorder == "<" and not __Pyx_Is_Little_Endian():
467
+ arg_is_pythran_compatible = False
468
+ elif byteorder == ">" and __Pyx_Is_Little_Endian():
469
+ arg_is_pythran_compatible = False
470
+ if arg_is_pythran_compatible:
471
+ cur_stride = itemsize
472
+ shape = arg.shape
473
+ strides = arg.strides
474
+ for i in range(arg.ndim-1, -1, -1):
475
+ if (<Py_ssize_t>strides[i]) != cur_stride:
476
+ arg_is_pythran_compatible = False
477
+ break
478
+ cur_stride *= <Py_ssize_t> shape[i]
479
+ else:
480
+ arg_is_pythran_compatible = not (arg.flags.f_contiguous and (<Py_ssize_t>arg.ndim) > 1)
481
+ """)
482
+ self._buffer_check_numpy_dtype(pyx_code, buffer_types, pythran_types)
483
+ pyx_code.dedent(2)
484
+
485
+ if accept_none:
486
+ # If None is acceptable, then Cython <3.0 matched None with the
487
+ # first type. This behaviour isn't ideal, but keep it for backwards
488
+ # compatibility. Better behaviour would be to see if subsequent
489
+ # arguments give a stronger match.
490
+ pyx_code.context.update(
491
+ specialized_type_name=buffer_types[0].specialization_string
492
+ )
493
+ pyx_code.put_chunk(
494
+ """
495
+ if arg is None:
496
+ %s
497
+ break
498
+ """ % self.match)
499
+
500
+ # creating a Cython memoryview from a Python memoryview avoids the
501
+ # need to get the buffer multiple times, and we can
502
+ # also use it to check itemsizes etc
503
+ pyx_code.put_chunk(
504
+ """
505
+ try:
506
+ arg_as_memoryview = memoryview(arg)
507
+ except (ValueError, TypeError):
508
+ pass
509
+ """)
510
+ with pyx_code.indenter("else:"):
511
+ for specialized_type in buffer_types:
512
+ self._buffer_parse_format_string_check(
513
+ pyx_code, decl_code, specialized_type, env)
514
+
515
+ def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_types):
516
+ """
517
+ If we have any buffer specializations, write out some variable
518
+ declarations and imports.
519
+ """
520
+ decl_code.put_chunk(
521
+ """
522
+ ctypedef struct {{memviewslice_cname}}:
523
+ void *memview
524
+
525
+ void __PYX_XCLEAR_MEMVIEW({{memviewslice_cname}} *, int have_gil)
526
+ bint __pyx_memoryview_check(object)
527
+ """)
528
+
529
+ pyx_code['local_variable_declarations'].put_chunk(
530
+ """
531
+ cdef {{memviewslice_cname}} memslice
532
+ cdef Py_ssize_t itemsize
533
+ cdef bint dtype_signed
534
+ cdef Py_UCS4 kind
535
+
536
+ itemsize = -1
537
+ """)
538
+
539
+ if pythran_types:
540
+ pyx_code['local_variable_declarations'].put_chunk("""
541
+ cdef bint arg_is_pythran_compatible
542
+ cdef Py_ssize_t cur_stride
543
+ """)
544
+
545
+ pyx_code['imports'].put_chunk(
546
+ """
547
+ cdef type ndarray
548
+ ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable()
549
+ """)
550
+
551
+ pyx_code['imports'].put_chunk(
552
+ """
553
+ cdef memoryview arg_as_memoryview
554
+ """
555
+ )
556
+
557
+ seen_typedefs = set()
558
+ seen_int_dtypes = set()
559
+ for buffer_type in all_buffer_types:
560
+ dtype = buffer_type.dtype
561
+ dtype_name = self._dtype_name(dtype)
562
+ if dtype.is_typedef:
563
+ if dtype_name not in seen_typedefs:
564
+ seen_typedefs.add(dtype_name)
565
+ decl_code.putln(
566
+ 'ctypedef %s %s "%s"' % (dtype.resolve(), dtype_name,
567
+ dtype.empty_declaration_code()))
568
+
569
+ if buffer_type.dtype.is_int:
570
+ if str(dtype) not in seen_int_dtypes:
571
+ seen_int_dtypes.add(str(dtype))
572
+ pyx_code.context.update(dtype_name=dtype_name,
573
+ dtype_type=self._dtype_type(dtype))
574
+ pyx_code['local_variable_declarations'].put_chunk(
575
+ """
576
+ cdef bint {{dtype_name}}_is_signed
577
+ {{dtype_name}}_is_signed = not (<{{dtype_type}}> -1 > 0)
578
+ """)
579
+
580
+ def _split_fused_types(self, arg):
581
+ """
582
+ Specialize fused types and split into normal types and buffer types.
583
+ """
584
+ specialized_types = PyrexTypes.get_specialized_types(arg.type)
585
+
586
+ # Prefer long over int, etc by sorting (see type classes in PyrexTypes.py)
587
+ specialized_types.sort()
588
+
589
+ seen_py_type_names = set()
590
+ normal_types, buffer_types, pythran_types = [], [], []
591
+ has_object_fallback = False
592
+ for specialized_type in specialized_types:
593
+ py_type_name = specialized_type.py_type_name()
594
+ if py_type_name:
595
+ if py_type_name in seen_py_type_names:
596
+ continue
597
+ seen_py_type_names.add(py_type_name)
598
+ if py_type_name == 'object':
599
+ has_object_fallback = True
600
+ else:
601
+ normal_types.append(specialized_type)
602
+ elif specialized_type.is_pythran_expr:
603
+ pythran_types.append(specialized_type)
604
+ elif specialized_type.is_buffer or specialized_type.is_memoryviewslice:
605
+ buffer_types.append(specialized_type)
606
+
607
+ return normal_types, buffer_types, pythran_types, has_object_fallback
608
+
609
+ def _unpack_argument(self, pyx_code):
610
+ pyx_code.put_chunk(
611
+ """
612
+ # PROCESSING ARGUMENT {{arg_tuple_idx}}
613
+ if {{arg_tuple_idx}} < len(<tuple>args):
614
+ arg = (<tuple>args)[{{arg_tuple_idx}}]
615
+ elif kwargs is not None and '{{arg.name}}' in <dict>kwargs:
616
+ arg = (<dict>kwargs)['{{arg.name}}']
617
+ else:
618
+ {{if arg.default}}
619
+ arg = (<tuple>defaults)[{{default_idx}}]
620
+ {{else}}
621
+ {{if arg_tuple_idx < min_positional_args}}
622
+ raise TypeError("Expected at least %d argument%s, got %d" % (
623
+ {{min_positional_args}}, {{'"s"' if min_positional_args != 1 else '""'}}, len(<tuple>args)))
624
+ {{else}}
625
+ raise TypeError("Missing keyword-only argument: '%s'" % "{{arg.default}}")
626
+ {{endif}}
627
+ {{endif}}
628
+ """)
629
+
630
+ def _fused_signature_index(self, pyx_code):
631
+ """
632
+ Generate Cython code for constructing a persistent nested dictionary index of
633
+ fused type specialization signatures.
634
+ """
635
+ # Note on thread-safety:
636
+ # Filling in "fused_sigindex" should only happen once. However, in a multi-threaded
637
+ # environment it's possible that multiple threads can all start to fill it in
638
+ # independently (especially on freehtreading builds).
639
+ # Therefore:
640
+ # * "_fused_sigindex_ref" is a list of length 1 where the first element is either None,
641
+ # or a dictionary of signatures to lookup.
642
+ # * We rely on being able to get/set list elements atomically (which is true on
643
+ # freethreading and regular Python).
644
+ # * It doesn't really matter if multiple threads start generating their own version
645
+ # of this - the contents will end up the same. The main point is that no thread
646
+ # sees a half filled-in sigindex
647
+ pyx_code.put_chunk(
648
+ """
649
+ fused_sigindex = <dict> _fused_sigindex_ref[0]
650
+ if fused_sigindex is None:
651
+ fused_sigindex = {}
652
+ for sig in <dict> signatures:
653
+ sigindex_node = fused_sigindex
654
+ *sig_series, last_type = sig.strip('()').split('|')
655
+ for sig_type in sig_series:
656
+ if sig_type not in sigindex_node:
657
+ sigindex_node[sig_type] = sigindex_node = {}
658
+ else:
659
+ sigindex_node = <dict> sigindex_node[sig_type]
660
+ sigindex_node[last_type] = sig
661
+ _fused_sigindex_ref[0] = fused_sigindex
662
+ """
663
+ )
664
+
665
+ def make_fused_cpdef(self, orig_py_func, env, is_def):
666
+ """
667
+ This creates the function that is indexable from Python and does
668
+ runtime dispatch based on the argument types. The function gets the
669
+ arg tuple and kwargs dict (or None) and the defaults tuple
670
+ as arguments from the Binding Fused Function's tp_call.
671
+ """
672
+ from . import TreeFragment, Code, UtilityCode
673
+
674
+ fused_types = self._get_fused_base_types([
675
+ arg.type for arg in self.node.args if arg.type.is_fused])
676
+
677
+ context = {
678
+ 'memviewslice_cname': MemoryView.memviewslice_cname,
679
+ 'func_args': self.node.args,
680
+ 'n_fused': len(fused_types),
681
+ 'min_positional_args':
682
+ self.node.num_required_args - self.node.num_required_kw_args
683
+ if is_def else
684
+ sum(1 for arg in self.node.args if arg.default is None),
685
+ 'name': orig_py_func.entry.name,
686
+ }
687
+
688
+ pyx_code = Code.PyxCodeWriter(context=context)
689
+ decl_code = Code.PyxCodeWriter(context=context)
690
+ decl_code.put_chunk(
691
+ """
692
+ cdef extern from *:
693
+ void __pyx_PyErr_Clear "PyErr_Clear" ()
694
+ type __Pyx_ImportNumPyArrayTypeIfAvailable()
695
+ int __Pyx_Is_Little_Endian()
696
+ """)
697
+ decl_code.indent()
698
+
699
+ pyx_code.put_chunk(
700
+ """
701
+ def __pyx_fused_cpdef(signatures, args, kwargs, defaults, _fused_sigindex_ref=[None]):
702
+ # FIXME: use a typed signature - currently fails badly because
703
+ # default arguments inherit the types we specify here!
704
+
705
+ cdef list search_list
706
+ cdef dict sigindex_node
707
+
708
+ dest_sig = [None] * {{n_fused}}
709
+
710
+ if kwargs is not None and not kwargs:
711
+ kwargs = None
712
+
713
+ cdef Py_ssize_t i
714
+
715
+ # instance check body
716
+ """)
717
+
718
+ pyx_code.indent() # indent following code to function body
719
+ pyx_code.named_insertion_point("imports")
720
+ pyx_code.named_insertion_point("local_variable_declarations")
721
+
722
+ fused_index = 0
723
+ default_idx = 0
724
+ all_buffer_types = OrderedSet()
725
+ seen_fused_types = set()
726
+ for i, arg in enumerate(self.node.args):
727
+ if arg.type.is_fused:
728
+ arg_fused_types = arg.type.get_fused_types()
729
+ if len(arg_fused_types) > 1:
730
+ raise NotImplementedError("Determination of more than one fused base "
731
+ "type per argument is not implemented.")
732
+ fused_type = arg_fused_types[0]
733
+
734
+ if arg.type.is_fused and fused_type not in seen_fused_types:
735
+ seen_fused_types.add(fused_type)
736
+
737
+ context.update(
738
+ arg_tuple_idx=i,
739
+ arg=arg,
740
+ dest_sig_idx=fused_index,
741
+ default_idx=default_idx,
742
+ )
743
+
744
+ normal_types, buffer_types, pythran_types, has_object_fallback = self._split_fused_types(arg)
745
+ self._unpack_argument(pyx_code)
746
+
747
+ # 'unrolled' loop, first match breaks out of it
748
+ with pyx_code.indenter("while 1:"):
749
+ if normal_types:
750
+ self._fused_instance_checks(normal_types, pyx_code, env)
751
+ if buffer_types or pythran_types:
752
+ env.use_utility_code(Code.UtilityCode.load_cached("IsLittleEndian", "ModuleSetupCode.c"))
753
+ self._buffer_checks(
754
+ buffer_types, pythran_types, pyx_code, decl_code,
755
+ arg.accept_none, env)
756
+ if has_object_fallback:
757
+ pyx_code.context.update(specialized_type_name='object')
758
+ pyx_code.putln(self.match)
759
+ else:
760
+ pyx_code.putln(self.no_match)
761
+ pyx_code.putln("break")
762
+
763
+ fused_index += 1
764
+ all_buffer_types.update(buffer_types)
765
+ all_buffer_types.update(ty.org_buffer for ty in pythran_types)
766
+
767
+ if arg.default:
768
+ default_idx += 1
769
+
770
+ if all_buffer_types:
771
+ self._buffer_declarations(pyx_code, decl_code, all_buffer_types, pythran_types)
772
+ env.use_utility_code(Code.UtilityCode.load_cached("Import", "ImportExport.c"))
773
+ env.use_utility_code(Code.UtilityCode.load_cached("ImportNumPyArray", "ImportExport.c"))
774
+
775
+ self._fused_signature_index(pyx_code)
776
+
777
+ pyx_code.put_chunk(
778
+ """
779
+ sigindex_matches = []
780
+ sigindex_candidates = [fused_sigindex]
781
+
782
+ for dst_type in dest_sig:
783
+ found_matches = []
784
+ found_candidates = []
785
+ # Make two separate lists: One for signature sub-trees
786
+ # with at least one definite match, and another for
787
+ # signature sub-trees with only ambiguous matches
788
+ # (where `dest_sig[i] is None`).
789
+ if dst_type is None:
790
+ for sn in sigindex_matches:
791
+ found_matches.extend((<dict> sn).values())
792
+ for sn in sigindex_candidates:
793
+ found_candidates.extend((<dict> sn).values())
794
+ else:
795
+ for search_list in (sigindex_matches, sigindex_candidates):
796
+ for sn in search_list:
797
+ type_match = (<dict> sn).get(dst_type)
798
+ if type_match is not None:
799
+ found_matches.append(type_match)
800
+ sigindex_matches = found_matches
801
+ sigindex_candidates = found_candidates
802
+ if not (found_matches or found_candidates):
803
+ break
804
+
805
+ candidates = sigindex_matches
806
+
807
+ if not candidates:
808
+ raise TypeError("No matching signature found")
809
+ elif len(candidates) > 1:
810
+ raise TypeError("Function call with ambiguous argument types")
811
+ else:
812
+ return (<dict>signatures)[candidates[0]]
813
+ """)
814
+
815
+ fragment_code = pyx_code.getvalue()
816
+ # print decl_code.getvalue()
817
+ # print fragment_code
818
+ from .Optimize import ConstantFolding
819
+ fragment = TreeFragment.TreeFragment(
820
+ fragment_code, level='module', pipeline=[ConstantFolding()])
821
+ ast = TreeFragment.SetPosTransform(self.node.pos)(fragment.root)
822
+ UtilityCode.declare_declarations_in_scope(
823
+ decl_code.getvalue(), env.global_scope())
824
+ ast.scope = env
825
+ # FIXME: for static methods of cdef classes, we build the wrong signature here: first arg becomes 'self'
826
+ ast.analyse_declarations(env)
827
+ py_func = ast.stats[-1] # the DefNode
828
+ self.fragment_scope = ast.scope
829
+
830
+ if isinstance(self.node, DefNode):
831
+ py_func.specialized_cpdefs = self.nodes[:]
832
+ else:
833
+ py_func.specialized_cpdefs = [n.py_func for n in self.nodes]
834
+
835
+ return py_func
836
+
837
+ def update_fused_defnode_entry(self, env):
838
+ copy_attributes = (
839
+ 'name', 'pos', 'cname', 'func_cname', 'pyfunc_cname',
840
+ 'pymethdef_cname', 'doc', 'doc_cname', 'is_member',
841
+ 'scope'
842
+ )
843
+
844
+ entry = self.py_func.entry
845
+
846
+ for attr in copy_attributes:
847
+ setattr(entry, attr,
848
+ getattr(self.orig_py_func.entry, attr))
849
+
850
+ self.py_func.name = self.orig_py_func.name
851
+ self.py_func.doc = self.orig_py_func.doc
852
+
853
+ env.entries.pop('__pyx_fused_cpdef', None)
854
+ if isinstance(self.node, DefNode):
855
+ env.entries[entry.name] = entry
856
+ else:
857
+ env.entries[entry.name].as_variable = entry
858
+
859
+ env.pyfunc_entries.append(entry)
860
+
861
+ self.py_func.entry.fused_cfunction = self
862
+ def_nodes = []
863
+ for node in self.nodes:
864
+ if isinstance(self.node, DefNode):
865
+ def_nodes.append(node)
866
+ node.fused_py_func = self.py_func
867
+ else:
868
+ def_nodes.append(node.py_func)
869
+ node.py_func.fused_py_func = self.py_func
870
+ node.entry.as_variable = entry
871
+
872
+ self.synthesize_defnodes(def_nodes)
873
+
874
+ def analyse_expressions(self, env):
875
+ """
876
+ Analyse the expressions. Take care to only evaluate default arguments
877
+ once and clone the result for all specializations
878
+ """
879
+ for fused_compound_type in self.fused_compound_types:
880
+ for fused_type in fused_compound_type.get_fused_types():
881
+ for specialization_type in fused_type.types:
882
+ if specialization_type.is_complex:
883
+ specialization_type.create_declaration_utility_code(env)
884
+
885
+ if self.py_func:
886
+ self.__signatures__ = self.__signatures__.analyse_expressions(env)
887
+ self.py_func = self.py_func.analyse_expressions(env)
888
+ self.resulting_fused_function = self.resulting_fused_function.analyse_expressions(env)
889
+ self.fused_func_assignment = self.fused_func_assignment.analyse_expressions(env)
890
+
891
+ self.defaults = defaults = []
892
+
893
+ for arg in self.node.args:
894
+ if arg.default:
895
+ arg.default = arg.default.analyse_expressions(env)
896
+ if arg.default.is_literal:
897
+ defaults.append(copy.copy(arg.default))
898
+ else:
899
+ # coerce the argument to temp since CloneNode really requires a temp
900
+ defaults.append(ProxyNode(arg.default.coerce_to_temp(env)))
901
+ else:
902
+ defaults.append(None)
903
+
904
+ for i, stat in enumerate(self.stats):
905
+ stat = self.stats[i] = stat.analyse_expressions(env)
906
+ if isinstance(stat, FuncDefNode) and stat is not self.py_func:
907
+ # the dispatcher specifically doesn't want its defaults overriding
908
+ for arg, default in zip(stat.args, defaults):
909
+ if default is not None:
910
+ if default.is_literal:
911
+ arg.default = default.coerce_to(arg.type, env)
912
+ else:
913
+ arg.default = CloneNode(default).analyse_expressions(env).coerce_to(arg.type, env)
914
+
915
+ if self.py_func:
916
+ args = [CloneNode(default) for default in defaults if default]
917
+ self.defaults_tuple = TupleNode(self.pos, args=args)
918
+ self.defaults_tuple = self.defaults_tuple.analyse_types(env, skip_children=True).coerce_to_pyobject(env)
919
+ self.defaults_tuple = ProxyNode(self.defaults_tuple)
920
+
921
+ fused_func = self.resulting_fused_function.arg
922
+ fused_func.defaults_tuple = CloneNode(self.defaults_tuple)
923
+
924
+ for i, pycfunc in enumerate(self.specialized_pycfuncs):
925
+ pycfunc = self.specialized_pycfuncs[i] = pycfunc.analyse_types(env)
926
+ pycfunc.defaults_tuple = CloneNode(self.defaults_tuple)
927
+ return self
928
+
929
+ def synthesize_defnodes(self, nodes):
930
+ """
931
+ Create the __signatures__ dict of PyCFunctionNode specializations.
932
+ """
933
+ # For the moment, fused functions do not support METH_FASTCALL
934
+ for node in nodes:
935
+ node.entry.signature.use_fastcall = False
936
+
937
+ signatures = [StringEncoding.EncodedString(node.specialized_signature_string)
938
+ for node in nodes]
939
+ keys = [ExprNodes.UnicodeNode(node.pos, value=sig)
940
+ for node, sig in zip(nodes, signatures)]
941
+ values = [ExprNodes.PyCFunctionNode.from_defnode(node, binding=True)
942
+ for node in nodes]
943
+
944
+ self.__signatures__ = ExprNodes.DictNode.from_pairs(self.pos, zip(keys, values))
945
+
946
+ self.specialized_pycfuncs = values
947
+ for pycfuncnode in values:
948
+ pycfuncnode.is_specialization = True
949
+
950
+ def generate_function_definitions(self, env, code):
951
+ if self.py_func:
952
+ self.py_func.pymethdef_required = True
953
+ self.fused_func_assignment.generate_function_definitions(env, code)
954
+
955
+ from . import Options
956
+ for stat in self.stats:
957
+ if isinstance(stat, FuncDefNode) and (
958
+ stat.entry.used or
959
+ (Options.cimport_from_pyx and not stat.entry.visibility == 'extern')):
960
+ code.mark_pos(stat.pos)
961
+ stat.generate_function_definitions(env, code)
962
+
963
+ def generate_execution_code(self, code):
964
+ # Note: all def function specialization are wrapped in PyCFunction
965
+ # nodes in the self.__signatures__ dictnode.
966
+ for default in self.defaults:
967
+ if default is not None:
968
+ default.generate_evaluation_code(code)
969
+
970
+ if self.py_func:
971
+ self.defaults_tuple.generate_evaluation_code(code)
972
+
973
+ super().generate_execution_code(code)
974
+
975
+ if self.__signatures__:
976
+ self.__signatures__.generate_evaluation_code(code)
977
+ self.resulting_fused_function.generate_evaluation_code(code)
978
+
979
+ code.putln(
980
+ "((__pyx_FusedFunctionObject *) %s)->__signatures__ = %s;" %
981
+ (self.resulting_fused_function.result(),
982
+ self.__signatures__.result()))
983
+ self.__signatures__.generate_giveref(code)
984
+ self.__signatures__.generate_post_assignment_code(code)
985
+ self.__signatures__.free_temps(code)
986
+
987
+ self.fused_func_assignment.generate_execution_code(code)
988
+
989
+ # Dispose of results
990
+ self.resulting_fused_function.generate_disposal_code(code)
991
+ self.resulting_fused_function.free_temps(code)
992
+ self.defaults_tuple.generate_disposal_code(code)
993
+ self.defaults_tuple.free_temps(code)
994
+
995
+ for default in self.defaults:
996
+ if default is not None:
997
+ default.generate_disposal_code(code)
998
+ default.free_temps(code)
999
+
1000
+ def annotate(self, code):
1001
+ for stat in self.stats:
1002
+ stat.annotate(code)