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,934 @@
1
+ #
2
+ # Builtin Definitions
3
+ #
4
+
5
+
6
+ from .StringEncoding import EncodedString
7
+ from .Symtab import BuiltinScope, StructOrUnionScope, ModuleScope, Entry
8
+ from .Code import UtilityCode, TempitaUtilityCode
9
+ from .TypeSlots import Signature
10
+ from . import PyrexTypes
11
+
12
+
13
+ # C-level implementations of builtin types, functions and methods
14
+
15
+ iter_next_utility_code = UtilityCode.load("IterNext", "ObjectHandling.c")
16
+ getattr_utility_code = UtilityCode.load("GetAttr", "ObjectHandling.c")
17
+ getattr3_utility_code = UtilityCode.load("GetAttr3", "Builtins.c")
18
+ pyexec_utility_code = UtilityCode.load("PyExec", "Builtins.c")
19
+ pyexec_globals_utility_code = UtilityCode.load("PyExecGlobals", "Builtins.c")
20
+ globals_utility_code = UtilityCode.load("Globals", "Builtins.c")
21
+ include_std_lib_h_utility_code = UtilityCode.load("IncludeStdlibH", "ModuleSetupCode.c")
22
+ pysequence_multiply_utility_code = UtilityCode.load("PySequenceMultiply", "ObjectHandling.c")
23
+ slice_accessor_utility_code = UtilityCode.load("PySliceAccessors", "Builtins.c")
24
+
25
+ # mapping from builtins to their C-level equivalents
26
+
27
+ class _BuiltinOverride:
28
+ def __init__(self, py_name, args, ret_type, cname, py_equiv="*",
29
+ utility_code=None, sig=None, func_type=None,
30
+ is_strict_signature=False, builtin_return_type=None,
31
+ nogil=None, specialiser=None):
32
+ self.py_name, self.cname, self.py_equiv = py_name, cname, py_equiv
33
+ self.args, self.ret_type = args, ret_type
34
+ self.func_type, self.sig = func_type, sig
35
+ self.builtin_return_type = builtin_return_type
36
+ self.is_strict_signature = is_strict_signature
37
+ self.utility_code = utility_code
38
+ self.nogil = nogil
39
+ self.specialiser = specialiser
40
+
41
+ def build_func_type(self, sig=None, self_arg=None):
42
+ if sig is None:
43
+ sig = Signature(self.args, self.ret_type, nogil=self.nogil)
44
+ sig.exception_check = False # not needed for the current builtins
45
+ func_type = sig.function_type(self_arg)
46
+ if self.is_strict_signature:
47
+ func_type.is_strict_signature = True
48
+ if self.builtin_return_type:
49
+ func_type.return_type = builtin_types[self.builtin_return_type]
50
+ return func_type
51
+
52
+
53
+ class BuiltinAttribute:
54
+ def __init__(self, py_name, cname=None, field_type=None, field_type_name=None):
55
+ self.py_name = py_name
56
+ self.cname = cname or py_name
57
+ self.field_type_name = field_type_name # can't do the lookup before the type is declared!
58
+ self.field_type = field_type
59
+
60
+ def declare_in_type(self, self_type):
61
+ if self.field_type_name is not None:
62
+ # lazy type lookup
63
+ field_type = builtin_scope.lookup(self.field_type_name).type
64
+ else:
65
+ field_type = self.field_type or PyrexTypes.py_object_type
66
+ entry = self_type.scope.declare(self.py_name, self.cname, field_type, None, 'private')
67
+ entry.is_variable = True
68
+
69
+
70
+ class BuiltinFunction(_BuiltinOverride):
71
+ def declare_in_scope(self, scope):
72
+ func_type, sig = self.func_type, self.sig
73
+ if func_type is None:
74
+ func_type = self.build_func_type(sig)
75
+ scope.declare_builtin_cfunction(
76
+ self.py_name, func_type, self.cname, self.py_equiv, self.utility_code,
77
+ specialiser=self.specialiser,
78
+ )
79
+
80
+
81
+ class BuiltinMethod(_BuiltinOverride):
82
+ def declare_in_type(self, self_type):
83
+ method_type, sig = self.func_type, self.sig
84
+ if method_type is None:
85
+ # override 'self' type (first argument)
86
+ self_arg = PyrexTypes.CFuncTypeArg("", self_type, None)
87
+ self_arg.not_none = True
88
+ self_arg.accept_builtin_subtypes = True
89
+ method_type = self.build_func_type(sig, self_arg)
90
+ self_type.scope.declare_builtin_cfunction(
91
+ self.py_name, method_type, self.cname, utility_code=self.utility_code)
92
+
93
+
94
+ class BuiltinProperty:
95
+ # read only for now
96
+ def __init__(self, py_name, property_type, call_cname,
97
+ exception_value=None, exception_check=None, utility_code=None):
98
+ self.py_name = py_name
99
+ self.property_type = property_type
100
+ self.call_cname = call_cname
101
+ self.utility_code = utility_code
102
+ self.exception_value = exception_value
103
+ self.exception_check = exception_check
104
+
105
+ def declare_in_type(self, self_type):
106
+ self_type.scope.declare_cproperty(
107
+ self.py_name,
108
+ self.property_type,
109
+ self.call_cname,
110
+ exception_value=self.exception_value,
111
+ exception_check=self.exception_check,
112
+ utility_code=self.utility_code
113
+ )
114
+
115
+
116
+ ### Special builtin implementations generated at runtime.
117
+
118
+ def _generate_divmod_function(scope, argument_types):
119
+ if len(argument_types) != 2:
120
+ return None
121
+ type_op1, type_op2 = argument_types
122
+
123
+ # Resolve internal typedefs to avoid useless code duplication.
124
+ if type_op1.is_typedef:
125
+ type_op1 = type_op1.resolve_known_type()
126
+ if type_op2.is_typedef:
127
+ type_op2 = type_op2.resolve_known_type()
128
+
129
+ if type_op1.is_float or type_op1 is float_type or type_op2.is_float and (type_op1.is_int or type_op1 is int_type):
130
+ impl = "float"
131
+ # TODO: support 'long double'? Currently fails to handle the error return value.
132
+ number_type = PyrexTypes.c_double_type
133
+ elif type_op1.is_int and type_op2.is_int:
134
+ impl = "int"
135
+ number_type = type_op1 if type_op1.rank >= type_op2.rank else type_op2
136
+ else:
137
+ return None
138
+
139
+ nogil = scope.nogil
140
+ cfunc_suffix = f"{'nogil_' if nogil else ''}{impl}_{'td_' if number_type.is_typedef else ''}{number_type.specialization_name()}"
141
+ function_cname = f"__Pyx_divmod_{cfunc_suffix}"
142
+
143
+ # Reuse an existing specialisation, if available.
144
+ builtin_scope = scope.builtin_scope()
145
+ existing_entry = builtin_scope.lookup_here("divmod")
146
+ if existing_entry is not None:
147
+ for entry in existing_entry.all_alternatives():
148
+ if entry.cname == function_cname:
149
+ return entry
150
+
151
+ # Generate a new specialisation.
152
+ ctuple_entry = scope.declare_tuple_type(None, [number_type]*2)
153
+ ctuple_entry.used = True
154
+ return_type = ctuple_entry.type
155
+
156
+ function_type = PyrexTypes.CFuncType(
157
+ return_type, [
158
+ PyrexTypes.CFuncTypeArg("a", number_type, None),
159
+ PyrexTypes.CFuncTypeArg("b", number_type, None),
160
+ ],
161
+ exception_value=f"__Pyx_divmod_ERROR_VALUE_{cfunc_suffix}",
162
+ exception_check=True,
163
+ is_strict_signature=True,
164
+ nogil=nogil,
165
+ )
166
+
167
+ utility_code = TempitaUtilityCode.load(
168
+ f"divmod_{impl}", "Builtins.c", context={
169
+ 'CFUNC_SUFFIX': cfunc_suffix,
170
+ 'MATH_SUFFIX': number_type.math_h_modifier if number_type.is_float else '',
171
+ 'TYPE': number_type.empty_declaration_code(),
172
+ 'RETURN_TYPE': return_type.empty_declaration_code(),
173
+ 'NOGIL': nogil,
174
+ })
175
+
176
+ entry = builtin_scope.declare_builtin_cfunction(
177
+ "divmod", function_type, function_cname, utility_code=utility_code)
178
+
179
+ return entry
180
+
181
+
182
+ ### List of builtin functions and their implementation.
183
+
184
+ builtin_function_table = [
185
+ # name, args, return, C API func, py equiv = "*"
186
+ BuiltinFunction('abs', "d", "d", "fabs",
187
+ is_strict_signature=True, nogil=True,
188
+ utility_code=include_std_lib_h_utility_code),
189
+ BuiltinFunction('abs', "f", "f", "fabsf",
190
+ is_strict_signature=True, nogil=True,
191
+ utility_code=include_std_lib_h_utility_code),
192
+ BuiltinFunction('abs', "i", "i", "abs",
193
+ is_strict_signature=True, nogil=True,
194
+ utility_code=include_std_lib_h_utility_code),
195
+ BuiltinFunction('abs', "l", "l", "labs",
196
+ is_strict_signature=True, nogil=True,
197
+ utility_code=include_std_lib_h_utility_code),
198
+ BuiltinFunction('abs', None, None, "__Pyx_abs_longlong",
199
+ utility_code = UtilityCode.load("abs_longlong", "Builtins.c"),
200
+ func_type = PyrexTypes.CFuncType(
201
+ PyrexTypes.c_longlong_type, [
202
+ PyrexTypes.CFuncTypeArg("arg", PyrexTypes.c_longlong_type, None)
203
+ ],
204
+ is_strict_signature = True, nogil=True)),
205
+ ] + list(
206
+ BuiltinFunction('abs', None, None, "/*abs_{}*/".format(t.specialization_name()),
207
+ func_type = PyrexTypes.CFuncType(
208
+ t,
209
+ [PyrexTypes.CFuncTypeArg("arg", t, None)],
210
+ is_strict_signature = True, nogil=True))
211
+ for t in (PyrexTypes.c_uint_type, PyrexTypes.c_ulong_type, PyrexTypes.c_ulonglong_type)
212
+ ) + list(
213
+ BuiltinFunction('abs', None, None, "__Pyx_c_abs{}".format(t.funcsuffix),
214
+ func_type = PyrexTypes.CFuncType(
215
+ t.real_type, [
216
+ PyrexTypes.CFuncTypeArg("arg", t, None)
217
+ ],
218
+ is_strict_signature = True, nogil=True))
219
+ for t in (PyrexTypes.c_float_complex_type,
220
+ PyrexTypes.c_double_complex_type,
221
+ PyrexTypes.c_longdouble_complex_type)
222
+ ) + [
223
+ BuiltinFunction('abs', "O", "O", "__Pyx_PyNumber_Absolute",
224
+ utility_code=UtilityCode.load("py_abs", "Builtins.c")),
225
+ #('all', "", "", ""),
226
+ #('any', "", "", ""),
227
+ #('ascii', "", "", ""),
228
+ #('bin', "", "", ""),
229
+ BuiltinFunction('callable', "O", "b", "__Pyx_PyCallable_Check",
230
+ utility_code = UtilityCode.load("CallableCheck", "ObjectHandling.c")),
231
+ BuiltinFunction('chr', "i", "O", "PyUnicode_FromOrdinal", builtin_return_type='str'),
232
+ #('cmp', "", "", "", ""), # int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
233
+ #('compile', "", "", ""), # PyObject* Py_CompileString( char *str, char *filename, int start)
234
+ BuiltinFunction('delattr', "OO", "r", "PyObject_DelAttr"),
235
+ BuiltinFunction('dir', "O", "O", "PyObject_Dir"),
236
+ BuiltinFunction('divmod', "OO", "O", "PyNumber_Divmod",
237
+ specialiser=_generate_divmod_function),
238
+ BuiltinFunction('exec', "O", "O", "__Pyx_PyExecGlobals",
239
+ utility_code = pyexec_globals_utility_code),
240
+ BuiltinFunction('exec', "OO", "O", "__Pyx_PyExec2",
241
+ utility_code = pyexec_utility_code),
242
+ BuiltinFunction('exec', "OOO", "O", "__Pyx_PyExec3",
243
+ utility_code = pyexec_utility_code),
244
+ #('eval', "", "", ""),
245
+ #('execfile', "", "", ""),
246
+ #('filter', "", "", ""),
247
+ BuiltinFunction('getattr3', "OOO", "O", "__Pyx_GetAttr3", "getattr",
248
+ utility_code=getattr3_utility_code), # Pyrex legacy
249
+ BuiltinFunction('getattr', "OOO", "O", "__Pyx_GetAttr3",
250
+ utility_code=getattr3_utility_code),
251
+ BuiltinFunction('getattr', "OO", "O", "__Pyx_GetAttr",
252
+ utility_code=getattr_utility_code),
253
+ BuiltinFunction('hasattr', "OO", "b", "__Pyx_HasAttr",
254
+ utility_code = UtilityCode.load("HasAttr", "Builtins.c")),
255
+ BuiltinFunction('hash', "O", "h", "PyObject_Hash"),
256
+ #('hex', "", "", ""),
257
+ #('id', "", "", ""),
258
+ #('input', "", "", ""),
259
+ BuiltinFunction('intern', "O", "O", "__Pyx_Intern",
260
+ utility_code = UtilityCode.load("Intern", "Builtins.c")),
261
+ BuiltinFunction('isinstance', "OO", "b", "PyObject_IsInstance"),
262
+ BuiltinFunction('issubclass', "OO", "b", "PyObject_IsSubclass"),
263
+ BuiltinFunction('iter', "OO", "O", "PyCallIter_New"),
264
+ BuiltinFunction('iter', "O", "O", "PyObject_GetIter"),
265
+ BuiltinFunction('len', "O", "z", "PyObject_Length"),
266
+ BuiltinFunction('locals', "", "O", "__pyx_locals"),
267
+ #('map', "", "", ""),
268
+ #('max', "", "", ""),
269
+ #('min', "", "", ""),
270
+ BuiltinFunction('next', "O", "O", "__Pyx_PyIter_Next",
271
+ utility_code = iter_next_utility_code), # not available in Py2 => implemented here
272
+ BuiltinFunction('next', "OO", "O", "__Pyx_PyIter_Next2",
273
+ utility_code = iter_next_utility_code), # not available in Py2 => implemented here
274
+ #('oct', "", "", ""),
275
+ #('open', "ss", "O", "PyFile_FromString"), # not in Py3
276
+ ] + [
277
+ BuiltinFunction('ord', None, None, "__Pyx_long_cast",
278
+ func_type=PyrexTypes.CFuncType(
279
+ PyrexTypes.c_long_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
280
+ is_strict_signature=True))
281
+ for c_type in [PyrexTypes.c_py_ucs4_type, PyrexTypes.c_py_unicode_type]
282
+ ] + [
283
+ BuiltinFunction('ord', None, None, "__Pyx_uchar_cast",
284
+ func_type=PyrexTypes.CFuncType(
285
+ PyrexTypes.c_uchar_type, [PyrexTypes.CFuncTypeArg("c", c_type, None)],
286
+ is_strict_signature=True))
287
+ for c_type in [PyrexTypes.c_char_type, PyrexTypes.c_schar_type, PyrexTypes.c_uchar_type]
288
+ ] + [
289
+ BuiltinFunction('ord', None, None, "__Pyx_PyObject_Ord",
290
+ utility_code=UtilityCode.load_cached("object_ord", "Builtins.c"),
291
+ func_type=PyrexTypes.CFuncType(
292
+ PyrexTypes.c_long_type, [
293
+ PyrexTypes.CFuncTypeArg("c", PyrexTypes.py_object_type, None)
294
+ ],
295
+ exception_value="(long)(Py_UCS4)-1")),
296
+ BuiltinFunction('pow', "OOO", "O", "PyNumber_Power"),
297
+ BuiltinFunction('pow', "OO", "O", "__Pyx_PyNumber_Power2",
298
+ utility_code = UtilityCode.load("pow2", "Builtins.c")),
299
+ #('range', "", "", ""),
300
+ #('raw_input', "", "", ""),
301
+ #('reduce', "", "", ""),
302
+ BuiltinFunction('reload', "O", "O", "PyImport_ReloadModule"),
303
+ BuiltinFunction('repr', "O", "O", "PyObject_Repr", builtin_return_type='str'),
304
+ #('round', "", "", ""),
305
+ BuiltinFunction('setattr', "OOO", "r", "PyObject_SetAttr"),
306
+ #('sum', "", "", ""),
307
+ #('sorted', "", "", ""),
308
+ #('type', "O", "O", "PyObject_Type"),
309
+ BuiltinFunction('unichr', "i", "O", "PyUnicode_FromOrdinal", builtin_return_type='str'),
310
+ #('vars', "", "", ""),
311
+ #('zip', "", "", ""),
312
+ # Can't do these easily until we have builtin type entries.
313
+ #('typecheck', "OO", "i", "PyObject_TypeCheck", False),
314
+ #('issubtype', "OO", "i", "PyType_IsSubtype", False),
315
+
316
+ # Put in namespace append optimization.
317
+ BuiltinFunction('__Pyx_PyObject_Append', "OO", "O", "__Pyx_PyObject_Append"),
318
+
319
+ # This is conditionally looked up based on a compiler directive.
320
+ BuiltinFunction('__Pyx_Globals', "", "O", "__Pyx_Globals",
321
+ utility_code=globals_utility_code),
322
+ ]
323
+
324
+
325
+ # Builtin types
326
+ # bool
327
+ # buffer
328
+ # classmethod
329
+ # dict
330
+ # enumerate
331
+ # file
332
+ # float
333
+ # int
334
+ # list
335
+ # long
336
+ # object
337
+ # property
338
+ # slice
339
+ # staticmethod
340
+ # super
341
+ # str
342
+ # tuple
343
+ # type
344
+ # xrange
345
+
346
+ builtin_types_table = [
347
+
348
+ ("type", "&PyType_Type", []),
349
+
350
+ # This conflicts with the C++ bool type, and unfortunately
351
+ # C++ is too liberal about PyObject* <-> bool conversions,
352
+ # resulting in unintuitive runtime behavior and segfaults.
353
+ # ("bool", "&PyBool_Type", []),
354
+
355
+ ("int", "&PyLong_Type", []),
356
+ ("float", "&PyFloat_Type", []),
357
+
358
+ ("complex", "&PyComplex_Type", [BuiltinAttribute('cval', field_type_name = 'Py_complex'),
359
+ BuiltinAttribute('real', 'cval.real', field_type = PyrexTypes.c_double_type),
360
+ BuiltinAttribute('imag', 'cval.imag', field_type = PyrexTypes.c_double_type),
361
+ ]),
362
+
363
+ ("bytearray", "&PyByteArray_Type", [
364
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
365
+ utility_code=pysequence_multiply_utility_code),
366
+ ]),
367
+ ("bytes", "&PyBytes_Type", [BuiltinMethod("join", "TO", "O", "__Pyx_PyBytes_Join",
368
+ utility_code=UtilityCode.load("StringJoin", "StringTools.c")),
369
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
370
+ utility_code=pysequence_multiply_utility_code),
371
+ ]),
372
+ ("str", "&PyUnicode_Type", [BuiltinMethod("__contains__", "TO", "b", "PyUnicode_Contains"),
373
+ BuiltinMethod("join", "TO", "T", "PyUnicode_Join"),
374
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
375
+ utility_code=pysequence_multiply_utility_code),
376
+ ]),
377
+
378
+ ("tuple", "&PyTuple_Type", [BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
379
+ utility_code=pysequence_multiply_utility_code),
380
+ ]),
381
+
382
+ ("list", "&PyList_Type", [BuiltinMethod("insert", "TzO", "r", "PyList_Insert"),
383
+ BuiltinMethod("reverse", "T", "r", "PyList_Reverse"),
384
+ BuiltinMethod("append", "TO", "r", "__Pyx_PyList_Append",
385
+ utility_code=UtilityCode.load("ListAppend", "Optimize.c")),
386
+ BuiltinMethod("extend", "TO", "r", "__Pyx_PyList_Extend",
387
+ utility_code=UtilityCode.load("ListExtend", "Optimize.c")),
388
+ BuiltinMethod("__mul__", "Tz", "T", "__Pyx_PySequence_Multiply",
389
+ utility_code=pysequence_multiply_utility_code),
390
+ ]),
391
+
392
+ ("dict", "&PyDict_Type", [BuiltinMethod("__contains__", "TO", "b", "PyDict_Contains"),
393
+ BuiltinMethod("has_key", "TO", "b", "PyDict_Contains"),
394
+ BuiltinMethod("items", "T", "O", "__Pyx_PyDict_Items",
395
+ utility_code=UtilityCode.load("py_dict_items", "Builtins.c")),
396
+ BuiltinMethod("keys", "T", "O", "__Pyx_PyDict_Keys",
397
+ utility_code=UtilityCode.load("py_dict_keys", "Builtins.c")),
398
+ BuiltinMethod("values", "T", "O", "__Pyx_PyDict_Values",
399
+ utility_code=UtilityCode.load("py_dict_values", "Builtins.c")),
400
+ BuiltinMethod("iteritems", "T", "O", "__Pyx_PyDict_IterItems",
401
+ utility_code=UtilityCode.load("py_dict_iteritems", "Builtins.c")),
402
+ BuiltinMethod("iterkeys", "T", "O", "__Pyx_PyDict_IterKeys",
403
+ utility_code=UtilityCode.load("py_dict_iterkeys", "Builtins.c")),
404
+ BuiltinMethod("itervalues", "T", "O", "__Pyx_PyDict_IterValues",
405
+ utility_code=UtilityCode.load("py_dict_itervalues", "Builtins.c")),
406
+ BuiltinMethod("viewitems", "T", "O", "__Pyx_PyDict_ViewItems",
407
+ utility_code=UtilityCode.load("py_dict_viewitems", "Builtins.c")),
408
+ BuiltinMethod("viewkeys", "T", "O", "__Pyx_PyDict_ViewKeys",
409
+ utility_code=UtilityCode.load("py_dict_viewkeys", "Builtins.c")),
410
+ BuiltinMethod("viewvalues", "T", "O", "__Pyx_PyDict_ViewValues",
411
+ utility_code=UtilityCode.load("py_dict_viewvalues", "Builtins.c")),
412
+ BuiltinMethod("clear", "T", "r", "__Pyx_PyDict_Clear",
413
+ utility_code=UtilityCode.load("py_dict_clear", "Optimize.c")),
414
+ BuiltinMethod("copy", "T", "T", "PyDict_Copy")]),
415
+
416
+ ("slice", "&PySlice_Type", [BuiltinProperty("start", PyrexTypes.py_object_type, '__Pyx_PySlice_Start',
417
+ utility_code=slice_accessor_utility_code),
418
+ BuiltinProperty("stop", PyrexTypes.py_object_type, '__Pyx_PySlice_Stop',
419
+ utility_code=slice_accessor_utility_code),
420
+ BuiltinProperty("step", PyrexTypes.py_object_type, '__Pyx_PySlice_Step',
421
+ utility_code=slice_accessor_utility_code),
422
+ ]),
423
+
424
+ ("set", "&PySet_Type", [BuiltinMethod("clear", "T", "r", "PySet_Clear"),
425
+ # discard() and remove() have a special treatment for unhashable values
426
+ BuiltinMethod("discard", "TO", "r", "__Pyx_PySet_Discard",
427
+ utility_code=UtilityCode.load("py_set_discard", "Optimize.c")),
428
+ BuiltinMethod("remove", "TO", "r", "__Pyx_PySet_Remove",
429
+ utility_code=UtilityCode.load("py_set_remove", "Optimize.c")),
430
+ # update is actually variadic (see Github issue #1645)
431
+ # BuiltinMethod("update", "TO", "r", "__Pyx_PySet_Update",
432
+ # utility_code=UtilityCode.load_cached("PySet_Update", "Builtins.c")),
433
+ BuiltinMethod("add", "TO", "r", "PySet_Add"),
434
+ BuiltinMethod("pop", "T", "O", "PySet_Pop")]),
435
+ ("frozenset", "&PyFrozenSet_Type", []),
436
+ ("BaseException", "((PyTypeObject*)PyExc_BaseException)", []),
437
+ ("Exception", "((PyTypeObject*)PyExc_Exception)", []),
438
+ ("memoryview", "&PyMemoryView_Type", [
439
+ # TODO - format would be nice, but hard to get
440
+ # __len__ can be accessed through a direct lookup of the buffer (but probably in Optimize.c)
441
+ # error checking would ideally be limited api only
442
+ BuiltinProperty("ndim", PyrexTypes.c_int_type, '__Pyx_PyMemoryView_Get_ndim',
443
+ exception_value=-1, exception_check=True,
444
+ utility_code=TempitaUtilityCode.load_cached(
445
+ "memoryview_get_from_buffer", "Builtins.c",
446
+ context=dict(name="ndim")
447
+ )
448
+ ),
449
+ BuiltinProperty("readonly", PyrexTypes.c_bint_type, '__Pyx_PyMemoryView_Get_readonly',
450
+ exception_value=-1, exception_check=True,
451
+ utility_code=TempitaUtilityCode.load_cached(
452
+ "memoryview_get_from_buffer", "Builtins.c",
453
+ context=dict(name="readonly")
454
+ )
455
+ ),
456
+ BuiltinProperty("itemsize", PyrexTypes.c_py_ssize_t_type, '__Pyx_PyMemoryView_Get_itemsize',
457
+ exception_value=-1, exception_check=True,
458
+ utility_code=TempitaUtilityCode.load_cached(
459
+ "memoryview_get_from_buffer", "Builtins.c",
460
+ context=dict(name="itemsize")
461
+ )
462
+ )]
463
+ )
464
+ ]
465
+
466
+
467
+ types_that_construct_their_instance = frozenset({
468
+ # some builtin types do not always return an instance of
469
+ # themselves - these do:
470
+ 'type', 'bool', 'int', 'float', 'complex',
471
+ 'bytes', 'unicode', 'bytearray', 'str',
472
+ 'tuple', 'list', 'dict', 'set', 'frozenset',
473
+ 'memoryview'
474
+ })
475
+
476
+
477
+ # When updating this mapping, also update "unsafe_compile_time_methods" below
478
+ # if methods are added that are not safe to evaluate at compile time.
479
+ inferred_method_return_types = {
480
+ 'complex': dict(
481
+ conjugate='complex',
482
+ ),
483
+ 'int': dict(
484
+ as_integer_ratio='tuple[int,int]',
485
+ bit_count='T',
486
+ bit_length='T',
487
+ conjugate='T',
488
+ from_bytes='T', # classmethod
489
+ is_integer='bint',
490
+ to_bytes='bytes',
491
+ ),
492
+ 'float': dict(
493
+ as_integer_ratio='tuple[int,int]',
494
+ conjugate='T',
495
+ fromhex='T', # classmethod
496
+ hex='str',
497
+ is_integer='bint',
498
+ ),
499
+ 'list': dict(
500
+ copy='T',
501
+ count='Py_ssize_t',
502
+ index='Py_ssize_t',
503
+ ),
504
+ 'tuple': dict(
505
+ count='Py_ssize_t',
506
+ index='Py_ssize_t',
507
+ ),
508
+ 'str': dict(
509
+ capitalize='T',
510
+ casefold='T',
511
+ center='T',
512
+ count='Py_ssize_t',
513
+ encode='bytes',
514
+ endswith='bint',
515
+ expandtabs='T',
516
+ find='Py_ssize_t',
517
+ format='T',
518
+ format_map='T',
519
+ index='Py_ssize_t',
520
+ isalnum='bint',
521
+ isalpha='bint',
522
+ isascii='bint',
523
+ isdecimal='bint',
524
+ isdigit='bint',
525
+ isidentifier='bint',
526
+ islower='bint',
527
+ isnumeric='bint',
528
+ isprintable='bint',
529
+ isspace='bint',
530
+ istitle='bint',
531
+ isupper='bint',
532
+ join='T',
533
+ ljust='T',
534
+ lower='T',
535
+ lstrip='T',
536
+ maketrans='dict[int,object]', # staticmethod
537
+ partition='tuple[T,T,T]',
538
+ removeprefix='T',
539
+ removesuffix='T',
540
+ replace='T',
541
+ rfind='Py_ssize_t',
542
+ rindex='Py_ssize_t',
543
+ rjust='T',
544
+ rpartition='tuple[T,T,T]',
545
+ rsplit='list[T]',
546
+ rstrip='T',
547
+ split='list[T]',
548
+ splitlines='list[T]',
549
+ startswith='bint',
550
+ strip='T',
551
+ swapcase='T',
552
+ title='T',
553
+ translate='T',
554
+ upper='T',
555
+ zfill='T',
556
+ ),
557
+ 'bytes': dict(
558
+ capitalize='T',
559
+ center='T',
560
+ count='Py_ssize_t',
561
+ decode='str',
562
+ endswith='bint',
563
+ expandtabs='T',
564
+ find='Py_ssize_t',
565
+ fromhex='T', # classmethod
566
+ hex='str',
567
+ index='Py_ssize_t',
568
+ isalnum='bint',
569
+ isalpha='bint',
570
+ isascii='bint',
571
+ isdigit='bint',
572
+ islower='bint',
573
+ isspace='bint',
574
+ istitle='bint',
575
+ isupper='bint',
576
+ join='T',
577
+ ljust='T',
578
+ lower='T',
579
+ lstrip='T',
580
+ maketrans='bytes', # staticmethod
581
+ partition='tuple[T,T,T]',
582
+ removeprefix='T',
583
+ removesuffix='T',
584
+ replace='T',
585
+ rfind='Py_ssize_t',
586
+ rindex='Py_ssize_t',
587
+ rjust='T',
588
+ rpartition='tuple[T,T,T]',
589
+ rsplit='list[T]',
590
+ rstrip='T',
591
+ split='list[T]',
592
+ splitlines='list[T]',
593
+ startswith='bint',
594
+ strip='T',
595
+ swapcase='T',
596
+ title='T',
597
+ translate='T',
598
+ upper='T',
599
+ zfill='T',
600
+ ),
601
+ 'bytearray': dict(
602
+ # Inherited from 'bytes' below.
603
+ ),
604
+ 'memoryview': dict(
605
+ cast='T',
606
+ hex='str',
607
+ tobytes='bytes',
608
+ tolist='list',
609
+ toreadonly='T',
610
+ ),
611
+ 'set': dict(
612
+ copy='T',
613
+ difference='T',
614
+ intersection='T',
615
+ isdisjoint='bint',
616
+ issubset='bint',
617
+ issuperset='bint',
618
+ symmetric_difference='T',
619
+ union='T',
620
+ ),
621
+ 'frozenset': dict(
622
+ # Inherited from 'set' below.
623
+ ),
624
+ 'dict': dict(
625
+ copy='T',
626
+ fromkeys='T', # classmethod
627
+ popitem='tuple',
628
+ ),
629
+ }
630
+
631
+ inferred_method_return_types['bytearray'].update(inferred_method_return_types['bytes'])
632
+ inferred_method_return_types['frozenset'].update(inferred_method_return_types['set'])
633
+
634
+
635
+ def find_return_type_of_builtin_method(builtin_type, method_name):
636
+ type_name = builtin_type.name
637
+ if type_name in inferred_method_return_types:
638
+ methods = inferred_method_return_types[type_name]
639
+ if method_name in methods:
640
+ return_type_name = methods[method_name]
641
+ if '[' in return_type_name:
642
+ # TODO: Keep the "[...]" part when we add support for generics.
643
+ return_type_name = return_type_name.partition('[')[0]
644
+ if return_type_name == 'T':
645
+ return builtin_type
646
+ if 'T' in return_type_name:
647
+ return_type_name = return_type_name.replace('T', builtin_type.name)
648
+ if return_type_name == 'bint':
649
+ return PyrexTypes.c_bint_type
650
+ elif return_type_name == 'Py_ssize_t':
651
+ return PyrexTypes.c_py_ssize_t_type
652
+ return builtin_scope.lookup(return_type_name).type
653
+ return PyrexTypes.py_object_type
654
+
655
+
656
+ unsafe_compile_time_methods = {
657
+ # We name here only unsafe and non-portable methods if:
658
+ # - the type has a literal representation, allowing for constant folding.
659
+ # - the return type is not None (thus excluding modifier methods)
660
+ # and is listed in 'inferred_method_return_types' above.
661
+ #
662
+ # See the consistency check in TestBuiltin.py.
663
+ #
664
+ 'complex': set(),
665
+ 'int': {
666
+ 'bit_count', # Py3.10+
667
+ 'from_bytes', # classmethod
668
+ 'is_integer', # Py3.12+
669
+ 'to_bytes', # changed in Py3.11
670
+ },
671
+ 'float': {
672
+ 'fromhex', # classmethod
673
+ },
674
+ 'list': {
675
+ 'copy',
676
+ },
677
+ 'tuple': set(),
678
+ 'str': {
679
+ 'replace', # changed in Py3.13+
680
+ 'maketrans', # staticmethod
681
+ 'removeprefix', # Py3.9+
682
+ 'removesuffix', # Py3.9+
683
+ },
684
+ 'bytes': {
685
+ 'fromhex', # classmethod
686
+ 'maketrans', # staticmethod
687
+ 'removeprefix', # Py3.9+
688
+ 'removesuffix', # Py3.9+
689
+ },
690
+ 'set': set(),
691
+ }
692
+
693
+
694
+ def is_safe_compile_time_method(builtin_type_name: str, method_name: str):
695
+ unsafe_methods = unsafe_compile_time_methods.get(builtin_type_name)
696
+ if unsafe_methods is None:
697
+ # Not a literal type.
698
+ return False
699
+ if method_name in unsafe_methods:
700
+ # Not a safe method.
701
+ return False
702
+ known_methods = inferred_method_return_types.get(builtin_type_name)
703
+ if known_methods is None or method_name not in known_methods:
704
+ # Not a known method.
705
+ return False
706
+ return True
707
+
708
+
709
+ builtin_structs_table = [
710
+ ('Py_buffer', 'Py_buffer',
711
+ [("buf", PyrexTypes.c_void_ptr_type),
712
+ ("obj", PyrexTypes.py_object_type),
713
+ ("len", PyrexTypes.c_py_ssize_t_type),
714
+ ("itemsize", PyrexTypes.c_py_ssize_t_type),
715
+ ("readonly", PyrexTypes.c_bint_type),
716
+ ("ndim", PyrexTypes.c_int_type),
717
+ ("format", PyrexTypes.c_char_ptr_type),
718
+ ("shape", PyrexTypes.c_py_ssize_t_ptr_type),
719
+ ("strides", PyrexTypes.c_py_ssize_t_ptr_type),
720
+ ("suboffsets", PyrexTypes.c_py_ssize_t_ptr_type),
721
+ ("smalltable", PyrexTypes.CArrayType(PyrexTypes.c_py_ssize_t_type, 2)),
722
+ ("internal", PyrexTypes.c_void_ptr_type),
723
+ ]),
724
+ ('Py_complex', 'Py_complex',
725
+ [('real', PyrexTypes.c_double_type),
726
+ ('imag', PyrexTypes.c_double_type),
727
+ ])
728
+ ]
729
+
730
+ # set up builtin scope
731
+
732
+ builtin_scope = BuiltinScope()
733
+
734
+ def init_builtin_funcs():
735
+ for bf in builtin_function_table:
736
+ bf.declare_in_scope(builtin_scope)
737
+
738
+ builtin_types = {}
739
+
740
+ def init_builtin_types():
741
+ global builtin_types
742
+ for name, cname, methods in builtin_types_table:
743
+ if name == 'frozenset':
744
+ objstruct_cname = 'PySetObject'
745
+ elif name == 'bytearray':
746
+ objstruct_cname = 'PyByteArrayObject'
747
+ elif name == 'int':
748
+ objstruct_cname = 'PyLongObject'
749
+ elif name == 'str':
750
+ objstruct_cname = 'PyUnicodeObject'
751
+ elif name == 'bool':
752
+ objstruct_cname = None
753
+ elif name == 'BaseException':
754
+ objstruct_cname = "PyBaseExceptionObject"
755
+ elif name == 'Exception':
756
+ objstruct_cname = "PyBaseExceptionObject"
757
+ else:
758
+ objstruct_cname = 'Py%sObject' % name.capitalize()
759
+ type_class = PyrexTypes.BuiltinObjectType
760
+ if name in ['dict', 'list', 'set', 'frozenset']:
761
+ type_class = PyrexTypes.BuiltinTypeConstructorObjectType
762
+ elif name == 'tuple':
763
+ type_class = PyrexTypes.PythonTupleTypeConstructor
764
+ the_type = builtin_scope.declare_builtin_type(
765
+ name, cname, objstruct_cname=objstruct_cname, type_class=type_class)
766
+ builtin_types[name] = the_type
767
+ for method in methods:
768
+ method.declare_in_type(the_type)
769
+
770
+
771
+ def init_builtin_structs():
772
+ for name, cname, attribute_types in builtin_structs_table:
773
+ scope = StructOrUnionScope(name)
774
+ for attribute_name, attribute_type in attribute_types:
775
+ scope.declare_var(attribute_name, attribute_type, None,
776
+ attribute_name, allow_pyobject=True)
777
+ builtin_scope.declare_struct_or_union(
778
+ name, "struct", scope, 1, None, cname = cname)
779
+
780
+
781
+ def init_builtins():
782
+ #Errors.init_thread() # hopefully not needed - we should not emit warnings ourselves
783
+ init_builtin_structs()
784
+ init_builtin_types()
785
+ init_builtin_funcs()
786
+
787
+ entry = builtin_scope.declare_var(
788
+ '__debug__', PyrexTypes.c_const_type(PyrexTypes.c_bint_type),
789
+ pos=None, cname='__pyx_assertions_enabled()', is_cdef=True)
790
+ entry.utility_code = UtilityCode.load_cached("AssertionsEnabled", "Exceptions.c")
791
+
792
+ global type_type, list_type, tuple_type, dict_type, set_type, frozenset_type, slice_type
793
+ global bytes_type, unicode_type, bytearray_type
794
+ global float_type, int_type, bool_type, complex_type
795
+ global memoryview_type, py_buffer_type
796
+ global sequence_types
797
+ type_type = builtin_scope.lookup('type').type
798
+ list_type = builtin_scope.lookup('list').type
799
+ tuple_type = builtin_scope.lookup('tuple').type
800
+ dict_type = builtin_scope.lookup('dict').type
801
+ set_type = builtin_scope.lookup('set').type
802
+ frozenset_type = builtin_scope.lookup('frozenset').type
803
+ slice_type = builtin_scope.lookup('slice').type
804
+
805
+ bytes_type = builtin_scope.lookup('bytes').type
806
+ unicode_type = builtin_scope.lookup('str').type
807
+ bytearray_type = builtin_scope.lookup('bytearray').type
808
+ memoryview_type = builtin_scope.lookup('memoryview').type
809
+
810
+ float_type = builtin_scope.lookup('float').type
811
+ int_type = builtin_scope.lookup('int').type
812
+ bool_type = builtin_scope.lookup('bool').type
813
+ complex_type = builtin_scope.lookup('complex').type
814
+
815
+ sequence_types = (
816
+ list_type,
817
+ tuple_type,
818
+ bytes_type,
819
+ unicode_type,
820
+ bytearray_type,
821
+ memoryview_type,
822
+ )
823
+
824
+ # Set up type inference links between equivalent Python/C types
825
+ bool_type.equivalent_type = PyrexTypes.c_bint_type
826
+ PyrexTypes.c_bint_type.equivalent_type = bool_type
827
+
828
+ float_type.equivalent_type = PyrexTypes.c_double_type
829
+ PyrexTypes.c_double_type.equivalent_type = float_type
830
+
831
+ complex_type.equivalent_type = PyrexTypes.c_double_complex_type
832
+ PyrexTypes.c_double_complex_type.equivalent_type = complex_type
833
+
834
+ py_buffer_type = builtin_scope.lookup('Py_buffer').type
835
+
836
+
837
+ init_builtins()
838
+
839
+ ##############################
840
+ # Support for a few standard library modules that Cython understands (currently typing and dataclasses)
841
+ ##############################
842
+ _known_module_scopes = {}
843
+
844
+ def get_known_standard_library_module_scope(module_name):
845
+ mod = _known_module_scopes.get(module_name)
846
+ if mod:
847
+ return mod
848
+
849
+ if module_name == "typing":
850
+ mod = ModuleScope(module_name, None, None)
851
+ for name, tp in [
852
+ ('Dict', dict_type),
853
+ ('List', list_type),
854
+ ('Tuple', tuple_type),
855
+ ('Set', set_type),
856
+ ('FrozenSet', frozenset_type),
857
+ ]:
858
+ name = EncodedString(name)
859
+ entry = mod.declare_type(name, tp, pos = None)
860
+ var_entry = Entry(name, None, PyrexTypes.py_object_type)
861
+ var_entry.is_pyglobal = True
862
+ var_entry.is_variable = True
863
+ var_entry.scope = mod
864
+ entry.as_variable = var_entry
865
+ entry.known_standard_library_import = "%s.%s" % (module_name, name)
866
+
867
+ for name in ['ClassVar', 'Optional', 'Union']:
868
+ name = EncodedString(name)
869
+ indexed_type = PyrexTypes.SpecialPythonTypeConstructor(EncodedString("typing."+name))
870
+ entry = mod.declare_type(name, indexed_type, pos = None)
871
+ var_entry = Entry(name, None, PyrexTypes.py_object_type)
872
+ var_entry.is_pyglobal = True
873
+ var_entry.is_variable = True
874
+ var_entry.scope = mod
875
+ entry.as_variable = var_entry
876
+ entry.known_standard_library_import = "%s.%s" % (module_name, name)
877
+ _known_module_scopes[module_name] = mod
878
+ elif module_name == "dataclasses":
879
+ mod = ModuleScope(module_name, None, None)
880
+ indexed_type = PyrexTypes.SpecialPythonTypeConstructor(EncodedString("dataclasses.InitVar"))
881
+ initvar_string = EncodedString("InitVar")
882
+ entry = mod.declare_type(initvar_string, indexed_type, pos = None)
883
+ var_entry = Entry(initvar_string, None, PyrexTypes.py_object_type)
884
+ var_entry.is_pyglobal = True
885
+ var_entry.scope = mod
886
+ entry.as_variable = var_entry
887
+ entry.known_standard_library_import = "%s.InitVar" % module_name
888
+ for name in ["dataclass", "field"]:
889
+ mod.declare_var(EncodedString(name), PyrexTypes.py_object_type, pos=None)
890
+ _known_module_scopes[module_name] = mod
891
+ elif module_name == "functools":
892
+ mod = ModuleScope(module_name, None, None)
893
+ for name in ["total_ordering"]:
894
+ mod.declare_var(EncodedString(name), PyrexTypes.py_object_type, pos=None)
895
+ _known_module_scopes[module_name] = mod
896
+
897
+ return mod
898
+
899
+
900
+ def get_known_standard_library_entry(qualified_name):
901
+ name_parts = qualified_name.split(".")
902
+ module_name = EncodedString(name_parts[0])
903
+ rest = name_parts[1:]
904
+
905
+ if len(rest) > 1: # for now, we don't know how to deal with any nested modules
906
+ return None
907
+
908
+ mod = get_known_standard_library_module_scope(module_name)
909
+
910
+ # eventually handle more sophisticated multiple lookups if needed
911
+ if mod and rest:
912
+ return mod.lookup_here(rest[0])
913
+ return None
914
+
915
+
916
+ def exprnode_to_known_standard_library_name(node, env):
917
+ qualified_name_parts = []
918
+ known_name = None
919
+ while node.is_attribute:
920
+ qualified_name_parts.append(node.attribute)
921
+ node = node.obj
922
+ if node.is_name:
923
+ entry = env.lookup(node.name)
924
+ if entry and entry.known_standard_library_import:
925
+ if get_known_standard_library_entry(
926
+ entry.known_standard_library_import):
927
+ known_name = entry.known_standard_library_import
928
+ else:
929
+ standard_env = get_known_standard_library_module_scope(
930
+ entry.known_standard_library_import)
931
+ if standard_env:
932
+ qualified_name_parts.append(standard_env.name)
933
+ known_name = ".".join(reversed(qualified_name_parts))
934
+ return known_name