mypy-dev 1.9.0.dev0__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 (1018) hide show
  1. mypy/__init__.py +1 -0
  2. mypy/__main__.py +37 -0
  3. mypy/api.py +94 -0
  4. mypy/applytype.py +156 -0
  5. mypy/argmap.py +268 -0
  6. mypy/binder.py +538 -0
  7. mypy/bogus_type.py +27 -0
  8. mypy/build.py +3562 -0
  9. mypy/checker.py +8372 -0
  10. mypy/checkexpr.py +6615 -0
  11. mypy/checkmember.py +1356 -0
  12. mypy/checkpattern.py +801 -0
  13. mypy/checkstrformat.py +1109 -0
  14. mypy/config_parser.py +670 -0
  15. mypy/constant_fold.py +187 -0
  16. mypy/constraints.py +1624 -0
  17. mypy/copytype.py +133 -0
  18. mypy/defaults.py +46 -0
  19. mypy/dmypy/__init__.py +0 -0
  20. mypy/dmypy/__main__.py +6 -0
  21. mypy/dmypy/client.py +749 -0
  22. mypy/dmypy_os.py +42 -0
  23. mypy/dmypy_server.py +1107 -0
  24. mypy/dmypy_util.py +117 -0
  25. mypy/erasetype.py +278 -0
  26. mypy/errorcodes.py +285 -0
  27. mypy/errors.py +1280 -0
  28. mypy/evalexpr.py +205 -0
  29. mypy/expandtype.py +510 -0
  30. mypy/exprtotype.py +206 -0
  31. mypy/fastparse.py +2147 -0
  32. mypy/find_sources.py +243 -0
  33. mypy/fixup.py +426 -0
  34. mypy/freetree.py +23 -0
  35. mypy/fscache.py +309 -0
  36. mypy/fswatcher.py +106 -0
  37. mypy/gclogger.py +47 -0
  38. mypy/git.py +34 -0
  39. mypy/graph_utils.py +112 -0
  40. mypy/indirection.py +121 -0
  41. mypy/infer.py +75 -0
  42. mypy/inspections.py +627 -0
  43. mypy/ipc.py +310 -0
  44. mypy/join.py +866 -0
  45. mypy/literals.py +306 -0
  46. mypy/lookup.py +61 -0
  47. mypy/main.py +1574 -0
  48. mypy/maptype.py +106 -0
  49. mypy/meet.py +1140 -0
  50. mypy/memprofile.py +121 -0
  51. mypy/message_registry.py +326 -0
  52. mypy/messages.py +3171 -0
  53. mypy/metastore.py +225 -0
  54. mypy/mixedtraverser.py +112 -0
  55. mypy/modulefinder.py +875 -0
  56. mypy/moduleinspect.py +184 -0
  57. mypy/mro.py +62 -0
  58. mypy/nodes.py +4112 -0
  59. mypy/operators.py +126 -0
  60. mypy/options.py +556 -0
  61. mypy/parse.py +30 -0
  62. mypy/partially_defined.py +675 -0
  63. mypy/patterns.py +150 -0
  64. mypy/plugin.py +901 -0
  65. mypy/plugins/__init__.py +0 -0
  66. mypy/plugins/attrs.py +1152 -0
  67. mypy/plugins/common.py +440 -0
  68. mypy/plugins/ctypes.py +245 -0
  69. mypy/plugins/dataclasses.py +1101 -0
  70. mypy/plugins/default.py +518 -0
  71. mypy/plugins/enums.py +259 -0
  72. mypy/plugins/functools.py +104 -0
  73. mypy/plugins/proper_plugin.py +175 -0
  74. mypy/plugins/singledispatch.py +224 -0
  75. mypy/py.typed +1 -0
  76. mypy/pyinfo.py +78 -0
  77. mypy/reachability.py +362 -0
  78. mypy/refinfo.py +92 -0
  79. mypy/renaming.py +568 -0
  80. mypy/report.py +924 -0
  81. mypy/scope.py +125 -0
  82. mypy/semanal.py +7023 -0
  83. mypy/semanal_classprop.py +187 -0
  84. mypy/semanal_enum.py +253 -0
  85. mypy/semanal_infer.py +128 -0
  86. mypy/semanal_main.py +511 -0
  87. mypy/semanal_namedtuple.py +670 -0
  88. mypy/semanal_newtype.py +273 -0
  89. mypy/semanal_pass1.py +156 -0
  90. mypy/semanal_shared.py +490 -0
  91. mypy/semanal_typeargs.py +265 -0
  92. mypy/semanal_typeddict.py +575 -0
  93. mypy/server/__init__.py +0 -0
  94. mypy/server/astdiff.py +518 -0
  95. mypy/server/astmerge.py +562 -0
  96. mypy/server/aststrip.py +281 -0
  97. mypy/server/deps.py +1137 -0
  98. mypy/server/mergecheck.py +83 -0
  99. mypy/server/objgraph.py +101 -0
  100. mypy/server/subexpr.py +198 -0
  101. mypy/server/target.py +11 -0
  102. mypy/server/trigger.py +26 -0
  103. mypy/server/update.py +1339 -0
  104. mypy/sharedparse.py +112 -0
  105. mypy/solve.py +562 -0
  106. mypy/split_namespace.py +35 -0
  107. mypy/state.py +28 -0
  108. mypy/stats.py +489 -0
  109. mypy/strconv.py +641 -0
  110. mypy/stubdoc.py +491 -0
  111. mypy/stubgen.py +1873 -0
  112. mypy/stubgenc.py +993 -0
  113. mypy/stubinfo.py +173 -0
  114. mypy/stubtest.py +2079 -0
  115. mypy/stubutil.py +807 -0
  116. mypy/subtypes.py +1967 -0
  117. mypy/suggestions.py +1046 -0
  118. mypy/test/__init__.py +0 -0
  119. mypy/test/config.py +28 -0
  120. mypy/test/data.py +823 -0
  121. mypy/test/helpers.py +476 -0
  122. mypy/test/meta/__init__.py +0 -0
  123. mypy/test/meta/_pytest.py +72 -0
  124. mypy/test/meta/test_diff_helper.py +47 -0
  125. mypy/test/meta/test_parse_data.py +73 -0
  126. mypy/test/meta/test_update_data.py +135 -0
  127. mypy/test/test_find_sources.py +376 -0
  128. mypy/test/test_ref_info.py +45 -0
  129. mypy/test/testapi.py +45 -0
  130. mypy/test/testargs.py +77 -0
  131. mypy/test/testcheck.py +322 -0
  132. mypy/test/testcmdline.py +152 -0
  133. mypy/test/testconstraints.py +134 -0
  134. mypy/test/testdaemon.py +132 -0
  135. mypy/test/testdeps.py +77 -0
  136. mypy/test/testdiff.py +67 -0
  137. mypy/test/testerrorstream.py +46 -0
  138. mypy/test/testfinegrained.py +438 -0
  139. mypy/test/testfinegrainedcache.py +18 -0
  140. mypy/test/testformatter.py +85 -0
  141. mypy/test/testfscache.py +101 -0
  142. mypy/test/testgraph.py +83 -0
  143. mypy/test/testinfer.py +373 -0
  144. mypy/test/testipc.py +119 -0
  145. mypy/test/testmerge.py +238 -0
  146. mypy/test/testmodulefinder.py +278 -0
  147. mypy/test/testmypyc.py +14 -0
  148. mypy/test/testparse.py +107 -0
  149. mypy/test/testpep561.py +211 -0
  150. mypy/test/testpythoneval.py +117 -0
  151. mypy/test/testreports.py +55 -0
  152. mypy/test/testsemanal.py +209 -0
  153. mypy/test/testsolve.py +285 -0
  154. mypy/test/teststubgen.py +1412 -0
  155. mypy/test/teststubinfo.py +12 -0
  156. mypy/test/teststubtest.py +2492 -0
  157. mypy/test/testsubtypes.py +303 -0
  158. mypy/test/testtransform.py +64 -0
  159. mypy/test/testtypegen.py +83 -0
  160. mypy/test/testtypes.py +1551 -0
  161. mypy/test/testutil.py +111 -0
  162. mypy/test/typefixture.py +415 -0
  163. mypy/test/update_data.py +87 -0
  164. mypy/test/visitors.py +63 -0
  165. mypy/traverser.py +961 -0
  166. mypy/treetransform.py +800 -0
  167. mypy/tvar_scope.py +147 -0
  168. mypy/type_visitor.py +564 -0
  169. mypy/typeanal.py +2510 -0
  170. mypy/typeops.py +1082 -0
  171. mypy/types.py +3686 -0
  172. mypy/types_utils.py +166 -0
  173. mypy/typeshed/LICENSE +237 -0
  174. mypy/typeshed/stdlib/VERSIONS +308 -0
  175. mypy/typeshed/stdlib/__future__.pyi +36 -0
  176. mypy/typeshed/stdlib/__main__.pyi +3 -0
  177. mypy/typeshed/stdlib/_ast.pyi +587 -0
  178. mypy/typeshed/stdlib/_bisect.pyi +84 -0
  179. mypy/typeshed/stdlib/_bootlocale.pyi +1 -0
  180. mypy/typeshed/stdlib/_codecs.pyi +133 -0
  181. mypy/typeshed/stdlib/_collections_abc.pyi +94 -0
  182. mypy/typeshed/stdlib/_compat_pickle.pyi +8 -0
  183. mypy/typeshed/stdlib/_compression.pyi +25 -0
  184. mypy/typeshed/stdlib/_csv.pyi +90 -0
  185. mypy/typeshed/stdlib/_ctypes.pyi +205 -0
  186. mypy/typeshed/stdlib/_curses.pyi +557 -0
  187. mypy/typeshed/stdlib/_decimal.pyi +281 -0
  188. mypy/typeshed/stdlib/_dummy_thread.pyi +27 -0
  189. mypy/typeshed/stdlib/_dummy_threading.pyi +164 -0
  190. mypy/typeshed/stdlib/_heapq.pyi +11 -0
  191. mypy/typeshed/stdlib/_imp.pyi +28 -0
  192. mypy/typeshed/stdlib/_json.pyi +49 -0
  193. mypy/typeshed/stdlib/_locale.pyi +100 -0
  194. mypy/typeshed/stdlib/_markupbase.pyi +16 -0
  195. mypy/typeshed/stdlib/_msi.pyi +91 -0
  196. mypy/typeshed/stdlib/_operator.pyi +147 -0
  197. mypy/typeshed/stdlib/_osx_support.pyi +34 -0
  198. mypy/typeshed/stdlib/_posixsubprocess.pyi +32 -0
  199. mypy/typeshed/stdlib/_py_abc.pyi +14 -0
  200. mypy/typeshed/stdlib/_pydecimal.pyi +43 -0
  201. mypy/typeshed/stdlib/_random.pyi +12 -0
  202. mypy/typeshed/stdlib/_sitebuiltins.pyi +16 -0
  203. mypy/typeshed/stdlib/_socket.pyi +802 -0
  204. mypy/typeshed/stdlib/_stat.pyi +103 -0
  205. mypy/typeshed/stdlib/_thread.pyi +52 -0
  206. mypy/typeshed/stdlib/_threading_local.pyi +17 -0
  207. mypy/typeshed/stdlib/_tkinter.pyi +120 -0
  208. mypy/typeshed/stdlib/_tracemalloc.pyi +17 -0
  209. mypy/typeshed/stdlib/_typeshed/__init__.pyi +347 -0
  210. mypy/typeshed/stdlib/_typeshed/dbapi.pyi +37 -0
  211. mypy/typeshed/stdlib/_typeshed/wsgi.pyi +44 -0
  212. mypy/typeshed/stdlib/_typeshed/xml.pyi +9 -0
  213. mypy/typeshed/stdlib/_warnings.pyi +55 -0
  214. mypy/typeshed/stdlib/_weakref.pyi +41 -0
  215. mypy/typeshed/stdlib/_weakrefset.pyi +51 -0
  216. mypy/typeshed/stdlib/_winapi.pyi +251 -0
  217. mypy/typeshed/stdlib/abc.pyi +49 -0
  218. mypy/typeshed/stdlib/aifc.pyi +91 -0
  219. mypy/typeshed/stdlib/antigravity.pyi +3 -0
  220. mypy/typeshed/stdlib/argparse.pyi +571 -0
  221. mypy/typeshed/stdlib/array.pyi +92 -0
  222. mypy/typeshed/stdlib/ast.pyi +277 -0
  223. mypy/typeshed/stdlib/asynchat.pyi +21 -0
  224. mypy/typeshed/stdlib/asyncio/__init__.pyi +41 -0
  225. mypy/typeshed/stdlib/asyncio/base_events.pyi +440 -0
  226. mypy/typeshed/stdlib/asyncio/base_futures.pyi +19 -0
  227. mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +63 -0
  228. mypy/typeshed/stdlib/asyncio/base_tasks.pyi +9 -0
  229. mypy/typeshed/stdlib/asyncio/constants.pyi +20 -0
  230. mypy/typeshed/stdlib/asyncio/coroutines.pyi +26 -0
  231. mypy/typeshed/stdlib/asyncio/events.pyi +574 -0
  232. mypy/typeshed/stdlib/asyncio/exceptions.pyi +43 -0
  233. mypy/typeshed/stdlib/asyncio/format_helpers.pyi +20 -0
  234. mypy/typeshed/stdlib/asyncio/futures.pyi +57 -0
  235. mypy/typeshed/stdlib/asyncio/locks.pyi +121 -0
  236. mypy/typeshed/stdlib/asyncio/log.pyi +3 -0
  237. mypy/typeshed/stdlib/asyncio/mixins.pyi +9 -0
  238. mypy/typeshed/stdlib/asyncio/proactor_events.pyi +64 -0
  239. mypy/typeshed/stdlib/asyncio/protocols.pyi +34 -0
  240. mypy/typeshed/stdlib/asyncio/queues.pyi +47 -0
  241. mypy/typeshed/stdlib/asyncio/runners.pyi +32 -0
  242. mypy/typeshed/stdlib/asyncio/selector_events.pyi +8 -0
  243. mypy/typeshed/stdlib/asyncio/sslproto.pyi +163 -0
  244. mypy/typeshed/stdlib/asyncio/staggered.pyi +10 -0
  245. mypy/typeshed/stdlib/asyncio/streams.pyi +148 -0
  246. mypy/typeshed/stdlib/asyncio/subprocess.pyi +229 -0
  247. mypy/typeshed/stdlib/asyncio/taskgroups.pyi +25 -0
  248. mypy/typeshed/stdlib/asyncio/tasks.pyi +477 -0
  249. mypy/typeshed/stdlib/asyncio/threads.pyi +9 -0
  250. mypy/typeshed/stdlib/asyncio/timeouts.pyi +19 -0
  251. mypy/typeshed/stdlib/asyncio/transports.pyi +47 -0
  252. mypy/typeshed/stdlib/asyncio/trsock.pyi +98 -0
  253. mypy/typeshed/stdlib/asyncio/unix_events.pyi +173 -0
  254. mypy/typeshed/stdlib/asyncio/windows_events.pyi +83 -0
  255. mypy/typeshed/stdlib/asyncio/windows_utils.pyi +49 -0
  256. mypy/typeshed/stdlib/asyncore.pyi +90 -0
  257. mypy/typeshed/stdlib/atexit.pyi +12 -0
  258. mypy/typeshed/stdlib/audioop.pyi +42 -0
  259. mypy/typeshed/stdlib/base64.pyi +59 -0
  260. mypy/typeshed/stdlib/bdb.pyi +102 -0
  261. mypy/typeshed/stdlib/binascii.pyi +36 -0
  262. mypy/typeshed/stdlib/binhex.pyi +45 -0
  263. mypy/typeshed/stdlib/bisect.pyi +4 -0
  264. mypy/typeshed/stdlib/builtins.pyi +1937 -0
  265. mypy/typeshed/stdlib/bz2.pyi +146 -0
  266. mypy/typeshed/stdlib/cProfile.pyi +35 -0
  267. mypy/typeshed/stdlib/calendar.pyi +206 -0
  268. mypy/typeshed/stdlib/cgi.pyi +118 -0
  269. mypy/typeshed/stdlib/cgitb.pyi +32 -0
  270. mypy/typeshed/stdlib/chunk.pyi +20 -0
  271. mypy/typeshed/stdlib/cmath.pyi +36 -0
  272. mypy/typeshed/stdlib/cmd.pyi +45 -0
  273. mypy/typeshed/stdlib/code.pyi +33 -0
  274. mypy/typeshed/stdlib/codecs.pyi +285 -0
  275. mypy/typeshed/stdlib/codeop.pyi +13 -0
  276. mypy/typeshed/stdlib/collections/__init__.pyi +477 -0
  277. mypy/typeshed/stdlib/collections/abc.pyi +2 -0
  278. mypy/typeshed/stdlib/colorsys.pyi +13 -0
  279. mypy/typeshed/stdlib/compileall.pyi +111 -0
  280. mypy/typeshed/stdlib/concurrent/__init__.pyi +0 -0
  281. mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +32 -0
  282. mypy/typeshed/stdlib/concurrent/futures/_base.pyi +120 -0
  283. mypy/typeshed/stdlib/concurrent/futures/process.pyi +233 -0
  284. mypy/typeshed/stdlib/concurrent/futures/thread.pyi +80 -0
  285. mypy/typeshed/stdlib/configparser.pyi +313 -0
  286. mypy/typeshed/stdlib/contextlib.pyi +207 -0
  287. mypy/typeshed/stdlib/contextvars.pyi +63 -0
  288. mypy/typeshed/stdlib/copy.pyi +16 -0
  289. mypy/typeshed/stdlib/copyreg.pyi +21 -0
  290. mypy/typeshed/stdlib/crypt.pyi +12 -0
  291. mypy/typeshed/stdlib/csv.pyi +147 -0
  292. mypy/typeshed/stdlib/ctypes/__init__.pyi +187 -0
  293. mypy/typeshed/stdlib/ctypes/_endian.pyi +19 -0
  294. mypy/typeshed/stdlib/ctypes/util.pyi +6 -0
  295. mypy/typeshed/stdlib/ctypes/wintypes.pyi +298 -0
  296. mypy/typeshed/stdlib/curses/__init__.pyi +21 -0
  297. mypy/typeshed/stdlib/curses/ascii.pyi +63 -0
  298. mypy/typeshed/stdlib/curses/has_key.pyi +4 -0
  299. mypy/typeshed/stdlib/curses/panel.pyi +25 -0
  300. mypy/typeshed/stdlib/curses/textpad.pyi +13 -0
  301. mypy/typeshed/stdlib/dataclasses.pyi +313 -0
  302. mypy/typeshed/stdlib/datetime.pyi +295 -0
  303. mypy/typeshed/stdlib/dbm/__init__.pyi +95 -0
  304. mypy/typeshed/stdlib/dbm/dumb.pyi +31 -0
  305. mypy/typeshed/stdlib/dbm/gnu.pyi +40 -0
  306. mypy/typeshed/stdlib/dbm/ndbm.pyi +36 -0
  307. mypy/typeshed/stdlib/decimal.pyi +2 -0
  308. mypy/typeshed/stdlib/difflib.pyi +140 -0
  309. mypy/typeshed/stdlib/dis.pyi +144 -0
  310. mypy/typeshed/stdlib/distutils/__init__.pyi +5 -0
  311. mypy/typeshed/stdlib/distutils/archive_util.pyi +20 -0
  312. mypy/typeshed/stdlib/distutils/bcppcompiler.pyi +3 -0
  313. mypy/typeshed/stdlib/distutils/ccompiler.pyi +152 -0
  314. mypy/typeshed/stdlib/distutils/cmd.pyi +66 -0
  315. mypy/typeshed/stdlib/distutils/command/__init__.pyi +0 -0
  316. mypy/typeshed/stdlib/distutils/command/bdist.pyi +25 -0
  317. mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi +21 -0
  318. mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi +45 -0
  319. mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi +0 -0
  320. mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi +52 -0
  321. mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi +16 -0
  322. mypy/typeshed/stdlib/distutils/command/build.pyi +31 -0
  323. mypy/typeshed/stdlib/distutils/command/build_clib.pyi +27 -0
  324. mypy/typeshed/stdlib/distutils/command/build_ext.pyi +50 -0
  325. mypy/typeshed/stdlib/distutils/command/build_py.pyi +44 -0
  326. mypy/typeshed/stdlib/distutils/command/build_scripts.pyi +24 -0
  327. mypy/typeshed/stdlib/distutils/command/check.pyi +39 -0
  328. mypy/typeshed/stdlib/distutils/command/clean.pyi +17 -0
  329. mypy/typeshed/stdlib/distutils/command/config.pyi +83 -0
  330. mypy/typeshed/stdlib/distutils/command/install.pyi +63 -0
  331. mypy/typeshed/stdlib/distutils/command/install_data.pyi +19 -0
  332. mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi +18 -0
  333. mypy/typeshed/stdlib/distutils/command/install_headers.pyi +16 -0
  334. mypy/typeshed/stdlib/distutils/command/install_lib.pyi +25 -0
  335. mypy/typeshed/stdlib/distutils/command/install_scripts.pyi +18 -0
  336. mypy/typeshed/stdlib/distutils/command/register.pyi +18 -0
  337. mypy/typeshed/stdlib/distutils/command/sdist.pyi +42 -0
  338. mypy/typeshed/stdlib/distutils/command/upload.pyi +17 -0
  339. mypy/typeshed/stdlib/distutils/config.pyi +17 -0
  340. mypy/typeshed/stdlib/distutils/core.pyi +57 -0
  341. mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi +20 -0
  342. mypy/typeshed/stdlib/distutils/debug.pyi +1 -0
  343. mypy/typeshed/stdlib/distutils/dep_util.pyi +3 -0
  344. mypy/typeshed/stdlib/distutils/dir_util.pyi +13 -0
  345. mypy/typeshed/stdlib/distutils/dist.pyi +146 -0
  346. mypy/typeshed/stdlib/distutils/errors.pyi +19 -0
  347. mypy/typeshed/stdlib/distutils/extension.pyi +36 -0
  348. mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +34 -0
  349. mypy/typeshed/stdlib/distutils/file_util.pyi +14 -0
  350. mypy/typeshed/stdlib/distutils/filelist.pyi +50 -0
  351. mypy/typeshed/stdlib/distutils/log.pyi +25 -0
  352. mypy/typeshed/stdlib/distutils/msvccompiler.pyi +3 -0
  353. mypy/typeshed/stdlib/distutils/spawn.pyi +2 -0
  354. mypy/typeshed/stdlib/distutils/sysconfig.pyi +22 -0
  355. mypy/typeshed/stdlib/distutils/text_file.pyi +21 -0
  356. mypy/typeshed/stdlib/distutils/unixccompiler.pyi +3 -0
  357. mypy/typeshed/stdlib/distutils/util.pyi +46 -0
  358. mypy/typeshed/stdlib/distutils/version.pyi +36 -0
  359. mypy/typeshed/stdlib/doctest.pyi +248 -0
  360. mypy/typeshed/stdlib/dummy_threading.pyi +2 -0
  361. mypy/typeshed/stdlib/email/__init__.pyi +29 -0
  362. mypy/typeshed/stdlib/email/_header_value_parser.pyi +392 -0
  363. mypy/typeshed/stdlib/email/_policybase.pyi +51 -0
  364. mypy/typeshed/stdlib/email/base64mime.pyi +13 -0
  365. mypy/typeshed/stdlib/email/charset.pyi +34 -0
  366. mypy/typeshed/stdlib/email/contentmanager.pyi +11 -0
  367. mypy/typeshed/stdlib/email/encoders.pyi +8 -0
  368. mypy/typeshed/stdlib/email/errors.pyi +39 -0
  369. mypy/typeshed/stdlib/email/feedparser.pyi +23 -0
  370. mypy/typeshed/stdlib/email/generator.pyi +40 -0
  371. mypy/typeshed/stdlib/email/header.pyi +31 -0
  372. mypy/typeshed/stdlib/email/headerregistry.pyi +178 -0
  373. mypy/typeshed/stdlib/email/iterators.pyi +12 -0
  374. mypy/typeshed/stdlib/email/message.pyi +161 -0
  375. mypy/typeshed/stdlib/email/mime/__init__.pyi +0 -0
  376. mypy/typeshed/stdlib/email/mime/application.pyi +17 -0
  377. mypy/typeshed/stdlib/email/mime/audio.pyi +17 -0
  378. mypy/typeshed/stdlib/email/mime/base.pyi +8 -0
  379. mypy/typeshed/stdlib/email/mime/image.pyi +17 -0
  380. mypy/typeshed/stdlib/email/mime/message.pyi +8 -0
  381. mypy/typeshed/stdlib/email/mime/multipart.pyi +18 -0
  382. mypy/typeshed/stdlib/email/mime/nonmultipart.pyi +5 -0
  383. mypy/typeshed/stdlib/email/mime/text.pyi +9 -0
  384. mypy/typeshed/stdlib/email/parser.pyi +26 -0
  385. mypy/typeshed/stdlib/email/policy.pyi +38 -0
  386. mypy/typeshed/stdlib/email/quoprimime.pyi +28 -0
  387. mypy/typeshed/stdlib/email/utils.pyi +66 -0
  388. mypy/typeshed/stdlib/encodings/__init__.pyi +10 -0
  389. mypy/typeshed/stdlib/encodings/utf_8.pyi +21 -0
  390. mypy/typeshed/stdlib/encodings/utf_8_sig.pyi +22 -0
  391. mypy/typeshed/stdlib/ensurepip/__init__.pyi +12 -0
  392. mypy/typeshed/stdlib/enum.pyi +317 -0
  393. mypy/typeshed/stdlib/errno.pyi +222 -0
  394. mypy/typeshed/stdlib/faulthandler.pyi +13 -0
  395. mypy/typeshed/stdlib/fcntl.pyi +127 -0
  396. mypy/typeshed/stdlib/filecmp.pyi +57 -0
  397. mypy/typeshed/stdlib/fileinput.pyi +213 -0
  398. mypy/typeshed/stdlib/fnmatch.pyi +9 -0
  399. mypy/typeshed/stdlib/formatter.pyi +88 -0
  400. mypy/typeshed/stdlib/fractions.pyi +150 -0
  401. mypy/typeshed/stdlib/ftplib.pyi +178 -0
  402. mypy/typeshed/stdlib/functools.pyi +200 -0
  403. mypy/typeshed/stdlib/gc.pyi +37 -0
  404. mypy/typeshed/stdlib/genericpath.pyi +52 -0
  405. mypy/typeshed/stdlib/getopt.pyi +11 -0
  406. mypy/typeshed/stdlib/getpass.pyi +8 -0
  407. mypy/typeshed/stdlib/gettext.pyi +169 -0
  408. mypy/typeshed/stdlib/glob.pyi +42 -0
  409. mypy/typeshed/stdlib/graphlib.pyi +28 -0
  410. mypy/typeshed/stdlib/grp.pyi +21 -0
  411. mypy/typeshed/stdlib/gzip.pyi +160 -0
  412. mypy/typeshed/stdlib/hashlib.pyi +165 -0
  413. mypy/typeshed/stdlib/heapq.pyi +17 -0
  414. mypy/typeshed/stdlib/hmac.pyi +38 -0
  415. mypy/typeshed/stdlib/html/__init__.pyi +6 -0
  416. mypy/typeshed/stdlib/html/entities.pyi +6 -0
  417. mypy/typeshed/stdlib/html/parser.pyi +34 -0
  418. mypy/typeshed/stdlib/http/__init__.pyi +105 -0
  419. mypy/typeshed/stdlib/http/client.pyi +259 -0
  420. mypy/typeshed/stdlib/http/cookiejar.pyi +159 -0
  421. mypy/typeshed/stdlib/http/cookies.pyi +60 -0
  422. mypy/typeshed/stdlib/http/server.pyi +83 -0
  423. mypy/typeshed/stdlib/imaplib.pyi +168 -0
  424. mypy/typeshed/stdlib/imghdr.pyi +17 -0
  425. mypy/typeshed/stdlib/imp.pyi +62 -0
  426. mypy/typeshed/stdlib/importlib/__init__.pyi +24 -0
  427. mypy/typeshed/stdlib/importlib/_abc.pyi +15 -0
  428. mypy/typeshed/stdlib/importlib/abc.pyi +172 -0
  429. mypy/typeshed/stdlib/importlib/machinery.pyi +179 -0
  430. mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +276 -0
  431. mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +40 -0
  432. mypy/typeshed/stdlib/importlib/readers.pyi +68 -0
  433. mypy/typeshed/stdlib/importlib/resources/__init__.pyi +46 -0
  434. mypy/typeshed/stdlib/importlib/resources/abc.pyi +12 -0
  435. mypy/typeshed/stdlib/importlib/resources/readers.pyi +14 -0
  436. mypy/typeshed/stdlib/importlib/resources/simple.pyi +49 -0
  437. mypy/typeshed/stdlib/importlib/simple.pyi +11 -0
  438. mypy/typeshed/stdlib/importlib/util.pyi +43 -0
  439. mypy/typeshed/stdlib/inspect.pyi +631 -0
  440. mypy/typeshed/stdlib/io.pyi +204 -0
  441. mypy/typeshed/stdlib/ipaddress.pyi +208 -0
  442. mypy/typeshed/stdlib/itertools.pyi +293 -0
  443. mypy/typeshed/stdlib/json/__init__.pyi +61 -0
  444. mypy/typeshed/stdlib/json/decoder.pyi +32 -0
  445. mypy/typeshed/stdlib/json/encoder.pyi +38 -0
  446. mypy/typeshed/stdlib/json/tool.pyi +1 -0
  447. mypy/typeshed/stdlib/keyword.pyi +21 -0
  448. mypy/typeshed/stdlib/lib2to3/__init__.pyi +0 -0
  449. mypy/typeshed/stdlib/lib2to3/btm_matcher.pyi +28 -0
  450. mypy/typeshed/stdlib/lib2to3/fixer_base.pyi +42 -0
  451. mypy/typeshed/stdlib/lib2to3/fixes/__init__.pyi +0 -0
  452. mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi +8 -0
  453. mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi +10 -0
  454. mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi +8 -0
  455. mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi +8 -0
  456. mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi +16 -0
  457. mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi +14 -0
  458. mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi +8 -0
  459. mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi +8 -0
  460. mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi +13 -0
  461. mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi +9 -0
  462. mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi +8 -0
  463. mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi +8 -0
  464. mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi +8 -0
  465. mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi +8 -0
  466. mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi +15 -0
  467. mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi +16 -0
  468. mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi +21 -0
  469. mypy/typeshed/stdlib/lib2to3/fixes/fix_imports2.pyi +6 -0
  470. mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi +11 -0
  471. mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi +9 -0
  472. mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi +8 -0
  473. mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi +9 -0
  474. mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi +7 -0
  475. mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi +7 -0
  476. mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi +9 -0
  477. mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi +17 -0
  478. mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi +10 -0
  479. mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi +8 -0
  480. mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi +19 -0
  481. mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi +8 -0
  482. mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi +8 -0
  483. mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi +12 -0
  484. mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi +8 -0
  485. mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi +12 -0
  486. mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi +8 -0
  487. mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi +8 -0
  488. mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi +8 -0
  489. mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi +9 -0
  490. mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi +17 -0
  491. mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi +8 -0
  492. mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi +7 -0
  493. mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi +8 -0
  494. mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi +9 -0
  495. mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi +8 -0
  496. mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi +17 -0
  497. mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi +8 -0
  498. mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi +12 -0
  499. mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi +15 -0
  500. mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi +12 -0
  501. mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi +20 -0
  502. mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi +8 -0
  503. mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi +9 -0
  504. mypy/typeshed/stdlib/lib2to3/main.pyi +42 -0
  505. mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi +9 -0
  506. mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +27 -0
  507. mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +24 -0
  508. mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi +7 -0
  509. mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +30 -0
  510. mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +50 -0
  511. mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi +67 -0
  512. mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +96 -0
  513. mypy/typeshed/stdlib/lib2to3/pygram.pyi +114 -0
  514. mypy/typeshed/stdlib/lib2to3/pytree.pyi +117 -0
  515. mypy/typeshed/stdlib/lib2to3/refactor.pyi +82 -0
  516. mypy/typeshed/stdlib/linecache.pyi +23 -0
  517. mypy/typeshed/stdlib/locale.pyi +152 -0
  518. mypy/typeshed/stdlib/logging/__init__.pyi +655 -0
  519. mypy/typeshed/stdlib/logging/config.pyi +134 -0
  520. mypy/typeshed/stdlib/logging/handlers.pyi +275 -0
  521. mypy/typeshed/stdlib/lzma.pyi +197 -0
  522. mypy/typeshed/stdlib/mailbox.pyi +256 -0
  523. mypy/typeshed/stdlib/mailcap.pyi +11 -0
  524. mypy/typeshed/stdlib/marshal.pyi +33 -0
  525. mypy/typeshed/stdlib/math.pyi +125 -0
  526. mypy/typeshed/stdlib/mimetypes.pyi +46 -0
  527. mypy/typeshed/stdlib/mmap.pyi +113 -0
  528. mypy/typeshed/stdlib/modulefinder.pyi +66 -0
  529. mypy/typeshed/stdlib/msilib/__init__.pyi +176 -0
  530. mypy/typeshed/stdlib/msilib/schema.pyi +94 -0
  531. mypy/typeshed/stdlib/msilib/sequence.pyi +13 -0
  532. mypy/typeshed/stdlib/msilib/text.pyi +7 -0
  533. mypy/typeshed/stdlib/msvcrt.pyi +32 -0
  534. mypy/typeshed/stdlib/multiprocessing/__init__.pyi +90 -0
  535. mypy/typeshed/stdlib/multiprocessing/connection.pyi +75 -0
  536. mypy/typeshed/stdlib/multiprocessing/context.pyi +187 -0
  537. mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +77 -0
  538. mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +39 -0
  539. mypy/typeshed/stdlib/multiprocessing/forkserver.pyi +31 -0
  540. mypy/typeshed/stdlib/multiprocessing/heap.pyi +36 -0
  541. mypy/typeshed/stdlib/multiprocessing/managers.pyi +212 -0
  542. mypy/typeshed/stdlib/multiprocessing/pool.pyi +103 -0
  543. mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi +23 -0
  544. mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi +16 -0
  545. mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi +20 -0
  546. mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi +30 -0
  547. mypy/typeshed/stdlib/multiprocessing/process.pyi +39 -0
  548. mypy/typeshed/stdlib/multiprocessing/queues.pyi +41 -0
  549. mypy/typeshed/stdlib/multiprocessing/reduction.pyi +89 -0
  550. mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi +20 -0
  551. mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi +18 -0
  552. mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +40 -0
  553. mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +101 -0
  554. mypy/typeshed/stdlib/multiprocessing/spawn.pyi +32 -0
  555. mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +54 -0
  556. mypy/typeshed/stdlib/multiprocessing/util.pyi +79 -0
  557. mypy/typeshed/stdlib/netrc.pyi +23 -0
  558. mypy/typeshed/stdlib/nis.pyi +9 -0
  559. mypy/typeshed/stdlib/nntplib.pyi +125 -0
  560. mypy/typeshed/stdlib/nt.pyi +111 -0
  561. mypy/typeshed/stdlib/ntpath.pyi +119 -0
  562. mypy/typeshed/stdlib/nturl2path.pyi +2 -0
  563. mypy/typeshed/stdlib/numbers.pyi +154 -0
  564. mypy/typeshed/stdlib/opcode.pyi +59 -0
  565. mypy/typeshed/stdlib/operator.pyi +110 -0
  566. mypy/typeshed/stdlib/optparse.pyi +252 -0
  567. mypy/typeshed/stdlib/os/__init__.pyi +1139 -0
  568. mypy/typeshed/stdlib/os/path.pyi +8 -0
  569. mypy/typeshed/stdlib/ossaudiodev.pyi +131 -0
  570. mypy/typeshed/stdlib/parser.pyi +24 -0
  571. mypy/typeshed/stdlib/pathlib.pyi +232 -0
  572. mypy/typeshed/stdlib/pdb.pyi +181 -0
  573. mypy/typeshed/stdlib/pickle.pyi +270 -0
  574. mypy/typeshed/stdlib/pickletools.pyi +167 -0
  575. mypy/typeshed/stdlib/pipes.pyi +16 -0
  576. mypy/typeshed/stdlib/pkgutil.pyi +53 -0
  577. mypy/typeshed/stdlib/platform.pyi +42 -0
  578. mypy/typeshed/stdlib/plistlib.pyi +113 -0
  579. mypy/typeshed/stdlib/poplib.pyi +71 -0
  580. mypy/typeshed/stdlib/posix.pyi +359 -0
  581. mypy/typeshed/stdlib/posixpath.pyi +161 -0
  582. mypy/typeshed/stdlib/pprint.pyi +112 -0
  583. mypy/typeshed/stdlib/profile.pyi +31 -0
  584. mypy/typeshed/stdlib/pstats.pyi +78 -0
  585. mypy/typeshed/stdlib/pty.pyi +19 -0
  586. mypy/typeshed/stdlib/pwd.pyi +27 -0
  587. mypy/typeshed/stdlib/py_compile.pyi +34 -0
  588. mypy/typeshed/stdlib/pyclbr.pyi +74 -0
  589. mypy/typeshed/stdlib/pydoc.pyi +261 -0
  590. mypy/typeshed/stdlib/pydoc_data/__init__.pyi +0 -0
  591. mypy/typeshed/stdlib/pydoc_data/topics.pyi +1 -0
  592. mypy/typeshed/stdlib/pyexpat/__init__.pyi +80 -0
  593. mypy/typeshed/stdlib/pyexpat/errors.pyi +49 -0
  594. mypy/typeshed/stdlib/pyexpat/model.pyi +11 -0
  595. mypy/typeshed/stdlib/queue.pyi +58 -0
  596. mypy/typeshed/stdlib/quopri.pyi +11 -0
  597. mypy/typeshed/stdlib/random.pyi +138 -0
  598. mypy/typeshed/stdlib/re.pyi +290 -0
  599. mypy/typeshed/stdlib/readline.pyi +36 -0
  600. mypy/typeshed/stdlib/reprlib.pyi +65 -0
  601. mypy/typeshed/stdlib/resource.pyi +92 -0
  602. mypy/typeshed/stdlib/rlcompleter.pyi +9 -0
  603. mypy/typeshed/stdlib/runpy.pyi +24 -0
  604. mypy/typeshed/stdlib/sched.pyi +42 -0
  605. mypy/typeshed/stdlib/secrets.pyi +15 -0
  606. mypy/typeshed/stdlib/select.pyi +151 -0
  607. mypy/typeshed/stdlib/selectors.pyi +67 -0
  608. mypy/typeshed/stdlib/shelve.pyi +46 -0
  609. mypy/typeshed/stdlib/shlex.pyi +43 -0
  610. mypy/typeshed/stdlib/shutil.pyi +189 -0
  611. mypy/typeshed/stdlib/signal.pyi +189 -0
  612. mypy/typeshed/stdlib/site.pyi +27 -0
  613. mypy/typeshed/stdlib/smtpd.pyi +91 -0
  614. mypy/typeshed/stdlib/smtplib.pyi +204 -0
  615. mypy/typeshed/stdlib/sndhdr.pyi +14 -0
  616. mypy/typeshed/stdlib/socket.pyi +825 -0
  617. mypy/typeshed/stdlib/socketserver.pyi +168 -0
  618. mypy/typeshed/stdlib/spwd.pyi +40 -0
  619. mypy/typeshed/stdlib/sqlite3/__init__.pyi +1 -0
  620. mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +469 -0
  621. mypy/typeshed/stdlib/sre_compile.pyi +11 -0
  622. mypy/typeshed/stdlib/sre_constants.pyi +130 -0
  623. mypy/typeshed/stdlib/sre_parse.pyi +104 -0
  624. mypy/typeshed/stdlib/ssl.pyi +529 -0
  625. mypy/typeshed/stdlib/stat.pyi +1 -0
  626. mypy/typeshed/stdlib/statistics.pyi +132 -0
  627. mypy/typeshed/stdlib/string.pyi +83 -0
  628. mypy/typeshed/stdlib/stringprep.pyi +27 -0
  629. mypy/typeshed/stdlib/struct.pyi +26 -0
  630. mypy/typeshed/stdlib/subprocess.pyi +2614 -0
  631. mypy/typeshed/stdlib/sunau.pyi +86 -0
  632. mypy/typeshed/stdlib/symbol.pyi +93 -0
  633. mypy/typeshed/stdlib/symtable.pyi +58 -0
  634. mypy/typeshed/stdlib/sys/__init__.pyi +373 -0
  635. mypy/typeshed/stdlib/sys/_monitoring.pyi +52 -0
  636. mypy/typeshed/stdlib/sysconfig.pyi +43 -0
  637. mypy/typeshed/stdlib/syslog.pyi +46 -0
  638. mypy/typeshed/stdlib/tabnanny.pyi +16 -0
  639. mypy/typeshed/stdlib/tarfile.pyi +438 -0
  640. mypy/typeshed/stdlib/telnetlib.pyi +122 -0
  641. mypy/typeshed/stdlib/tempfile.pyi +477 -0
  642. mypy/typeshed/stdlib/termios.pyi +267 -0
  643. mypy/typeshed/stdlib/textwrap.pyi +103 -0
  644. mypy/typeshed/stdlib/this.pyi +2 -0
  645. mypy/typeshed/stdlib/threading.pyi +187 -0
  646. mypy/typeshed/stdlib/time.pyi +107 -0
  647. mypy/typeshed/stdlib/timeit.pyi +32 -0
  648. mypy/typeshed/stdlib/tkinter/__init__.pyi +3641 -0
  649. mypy/typeshed/stdlib/tkinter/colorchooser.pyi +20 -0
  650. mypy/typeshed/stdlib/tkinter/commondialog.pyi +14 -0
  651. mypy/typeshed/stdlib/tkinter/constants.pyi +80 -0
  652. mypy/typeshed/stdlib/tkinter/dialog.pyi +16 -0
  653. mypy/typeshed/stdlib/tkinter/dnd.pyi +20 -0
  654. mypy/typeshed/stdlib/tkinter/filedialog.pyi +151 -0
  655. mypy/typeshed/stdlib/tkinter/font.pyi +116 -0
  656. mypy/typeshed/stdlib/tkinter/messagebox.pyi +44 -0
  657. mypy/typeshed/stdlib/tkinter/scrolledtext.pyi +10 -0
  658. mypy/typeshed/stdlib/tkinter/simpledialog.pyi +54 -0
  659. mypy/typeshed/stdlib/tkinter/tix.pyi +299 -0
  660. mypy/typeshed/stdlib/tkinter/ttk.pyi +1191 -0
  661. mypy/typeshed/stdlib/token.pyi +159 -0
  662. mypy/typeshed/stdlib/tokenize.pyi +177 -0
  663. mypy/typeshed/stdlib/tomllib.pyi +10 -0
  664. mypy/typeshed/stdlib/trace.pyi +79 -0
  665. mypy/typeshed/stdlib/traceback.pyi +260 -0
  666. mypy/typeshed/stdlib/tracemalloc.pyi +124 -0
  667. mypy/typeshed/stdlib/tty.pyi +30 -0
  668. mypy/typeshed/stdlib/turtle.pyi +713 -0
  669. mypy/typeshed/stdlib/types.pyi +605 -0
  670. mypy/typeshed/stdlib/typing.pyi +968 -0
  671. mypy/typeshed/stdlib/typing_extensions.pyi +503 -0
  672. mypy/typeshed/stdlib/unicodedata.pyi +71 -0
  673. mypy/typeshed/stdlib/unittest/__init__.pyi +67 -0
  674. mypy/typeshed/stdlib/unittest/_log.pyi +27 -0
  675. mypy/typeshed/stdlib/unittest/async_case.pyi +21 -0
  676. mypy/typeshed/stdlib/unittest/case.pyi +342 -0
  677. mypy/typeshed/stdlib/unittest/loader.pyi +51 -0
  678. mypy/typeshed/stdlib/unittest/main.pyi +69 -0
  679. mypy/typeshed/stdlib/unittest/mock.pyi +430 -0
  680. mypy/typeshed/stdlib/unittest/result.pyi +46 -0
  681. mypy/typeshed/stdlib/unittest/runner.pyi +72 -0
  682. mypy/typeshed/stdlib/unittest/signals.pyi +15 -0
  683. mypy/typeshed/stdlib/unittest/suite.pyi +22 -0
  684. mypy/typeshed/stdlib/unittest/util.pyi +23 -0
  685. mypy/typeshed/stdlib/urllib/__init__.pyi +0 -0
  686. mypy/typeshed/stdlib/urllib/error.pyi +23 -0
  687. mypy/typeshed/stdlib/urllib/parse.pyi +210 -0
  688. mypy/typeshed/stdlib/urllib/request.pyi +399 -0
  689. mypy/typeshed/stdlib/urllib/response.pyi +43 -0
  690. mypy/typeshed/stdlib/urllib/robotparser.pyi +20 -0
  691. mypy/typeshed/stdlib/uu.pyi +13 -0
  692. mypy/typeshed/stdlib/uuid.pyi +100 -0
  693. mypy/typeshed/stdlib/venv/__init__.pyi +79 -0
  694. mypy/typeshed/stdlib/warnings.pyi +112 -0
  695. mypy/typeshed/stdlib/wave.pyi +85 -0
  696. mypy/typeshed/stdlib/weakref.pyi +150 -0
  697. mypy/typeshed/stdlib/webbrowser.pyi +74 -0
  698. mypy/typeshed/stdlib/winreg.pyi +103 -0
  699. mypy/typeshed/stdlib/winsound.pyi +28 -0
  700. mypy/typeshed/stdlib/wsgiref/__init__.pyi +0 -0
  701. mypy/typeshed/stdlib/wsgiref/handlers.pyi +91 -0
  702. mypy/typeshed/stdlib/wsgiref/headers.pyi +26 -0
  703. mypy/typeshed/stdlib/wsgiref/simple_server.pyi +37 -0
  704. mypy/typeshed/stdlib/wsgiref/types.pyi +32 -0
  705. mypy/typeshed/stdlib/wsgiref/util.pyi +24 -0
  706. mypy/typeshed/stdlib/wsgiref/validate.pyi +50 -0
  707. mypy/typeshed/stdlib/xdrlib.pyi +57 -0
  708. mypy/typeshed/stdlib/xml/__init__.pyi +1 -0
  709. mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi +19 -0
  710. mypy/typeshed/stdlib/xml/dom/__init__.pyi +69 -0
  711. mypy/typeshed/stdlib/xml/dom/domreg.pyi +8 -0
  712. mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi +100 -0
  713. mypy/typeshed/stdlib/xml/dom/minicompat.pyi +22 -0
  714. mypy/typeshed/stdlib/xml/dom/minidom.pyi +404 -0
  715. mypy/typeshed/stdlib/xml/dom/pulldom.pyi +94 -0
  716. mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +108 -0
  717. mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +28 -0
  718. mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +34 -0
  719. mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +321 -0
  720. mypy/typeshed/stdlib/xml/etree/__init__.pyi +0 -0
  721. mypy/typeshed/stdlib/xml/etree/cElementTree.pyi +1 -0
  722. mypy/typeshed/stdlib/xml/parsers/__init__.pyi +1 -0
  723. mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi +1 -0
  724. mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi +1 -0
  725. mypy/typeshed/stdlib/xml/parsers/expat/model.pyi +1 -0
  726. mypy/typeshed/stdlib/xml/sax/__init__.pyi +25 -0
  727. mypy/typeshed/stdlib/xml/sax/_exceptions.pyi +19 -0
  728. mypy/typeshed/stdlib/xml/sax/handler.pyi +55 -0
  729. mypy/typeshed/stdlib/xml/sax/saxutils.pyi +60 -0
  730. mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +87 -0
  731. mypy/typeshed/stdlib/xmlrpc/__init__.pyi +0 -0
  732. mypy/typeshed/stdlib/xmlrpc/client.pyi +296 -0
  733. mypy/typeshed/stdlib/xmlrpc/server.pyi +143 -0
  734. mypy/typeshed/stdlib/xxlimited.pyi +22 -0
  735. mypy/typeshed/stdlib/zipapp.pyi +20 -0
  736. mypy/typeshed/stdlib/zipfile/__init__.pyi +306 -0
  737. mypy/typeshed/stdlib/zipfile/_path.pyi +95 -0
  738. mypy/typeshed/stdlib/zipimport.pyi +32 -0
  739. mypy/typeshed/stdlib/zlib.pyi +56 -0
  740. mypy/typeshed/stdlib/zoneinfo/__init__.pyi +38 -0
  741. mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +218 -0
  742. mypy/typestate.py +323 -0
  743. mypy/typetraverser.py +142 -0
  744. mypy/typevars.py +93 -0
  745. mypy/typevartuples.py +32 -0
  746. mypy/util.py +869 -0
  747. mypy/version.py +1 -0
  748. mypy/visitor.py +621 -0
  749. mypy/xml/mypy-html.css +104 -0
  750. mypy/xml/mypy-html.xslt +81 -0
  751. mypy/xml/mypy-txt.xslt +100 -0
  752. mypy/xml/mypy.xsd +50 -0
  753. mypy_dev-1.9.0.dev0.dist-info/LICENSE +229 -0
  754. mypy_dev-1.9.0.dev0.dist-info/METADATA +39 -0
  755. mypy_dev-1.9.0.dev0.dist-info/RECORD +1018 -0
  756. mypy_dev-1.9.0.dev0.dist-info/WHEEL +5 -0
  757. mypy_dev-1.9.0.dev0.dist-info/entry_points.txt +6 -0
  758. mypy_dev-1.9.0.dev0.dist-info/top_level.txt +2 -0
  759. mypyc/README.md +133 -0
  760. mypyc/__init__.py +0 -0
  761. mypyc/__main__.py +57 -0
  762. mypyc/analysis/__init__.py +0 -0
  763. mypyc/analysis/attrdefined.py +436 -0
  764. mypyc/analysis/blockfreq.py +32 -0
  765. mypyc/analysis/dataflow.py +624 -0
  766. mypyc/analysis/ircheck.py +429 -0
  767. mypyc/analysis/selfleaks.py +207 -0
  768. mypyc/build.py +616 -0
  769. mypyc/codegen/__init__.py +0 -0
  770. mypyc/codegen/cstring.py +54 -0
  771. mypyc/codegen/emit.py +1193 -0
  772. mypyc/codegen/emitclass.py +1060 -0
  773. mypyc/codegen/emitfunc.py +846 -0
  774. mypyc/codegen/emitmodule.py +1131 -0
  775. mypyc/codegen/emitwrapper.py +979 -0
  776. mypyc/codegen/literals.py +302 -0
  777. mypyc/common.py +136 -0
  778. mypyc/crash.py +31 -0
  779. mypyc/doc/Makefile +20 -0
  780. mypyc/doc/bool_operations.rst +27 -0
  781. mypyc/doc/compilation_units.rst +20 -0
  782. mypyc/doc/conf.py +59 -0
  783. mypyc/doc/cpython-timings.md +25 -0
  784. mypyc/doc/dev-intro.md +548 -0
  785. mypyc/doc/dict_operations.rst +59 -0
  786. mypyc/doc/differences_from_python.rst +332 -0
  787. mypyc/doc/float_operations.rst +50 -0
  788. mypyc/doc/future.md +42 -0
  789. mypyc/doc/getting_started.rst +240 -0
  790. mypyc/doc/index.rst +61 -0
  791. mypyc/doc/int_operations.rst +162 -0
  792. mypyc/doc/introduction.rst +150 -0
  793. mypyc/doc/list_operations.rst +65 -0
  794. mypyc/doc/make.bat +35 -0
  795. mypyc/doc/native_classes.rst +206 -0
  796. mypyc/doc/native_operations.rst +55 -0
  797. mypyc/doc/performance_tips_and_tricks.rst +244 -0
  798. mypyc/doc/set_operations.rst +47 -0
  799. mypyc/doc/str_operations.rst +35 -0
  800. mypyc/doc/tuple_operations.rst +33 -0
  801. mypyc/doc/using_type_annotations.rst +398 -0
  802. mypyc/errors.py +29 -0
  803. mypyc/external/googletest/LICENSE +28 -0
  804. mypyc/external/googletest/README.md +280 -0
  805. mypyc/external/googletest/include/gtest/gtest-death-test.h +294 -0
  806. mypyc/external/googletest/include/gtest/gtest-message.h +250 -0
  807. mypyc/external/googletest/include/gtest/gtest-param-test.h +1444 -0
  808. mypyc/external/googletest/include/gtest/gtest-param-test.h.pump +510 -0
  809. mypyc/external/googletest/include/gtest/gtest-printers.h +993 -0
  810. mypyc/external/googletest/include/gtest/gtest-spi.h +232 -0
  811. mypyc/external/googletest/include/gtest/gtest-test-part.h +179 -0
  812. mypyc/external/googletest/include/gtest/gtest-typed-test.h +263 -0
  813. mypyc/external/googletest/include/gtest/gtest.h +2236 -0
  814. mypyc/external/googletest/include/gtest/gtest_pred_impl.h +358 -0
  815. mypyc/external/googletest/include/gtest/gtest_prod.h +58 -0
  816. mypyc/external/googletest/include/gtest/internal/custom/gtest-port.h +69 -0
  817. mypyc/external/googletest/include/gtest/internal/custom/gtest-printers.h +42 -0
  818. mypyc/external/googletest/include/gtest/internal/custom/gtest.h +41 -0
  819. mypyc/external/googletest/include/gtest/internal/gtest-death-test-internal.h +319 -0
  820. mypyc/external/googletest/include/gtest/internal/gtest-filepath.h +206 -0
  821. mypyc/external/googletest/include/gtest/internal/gtest-internal.h +1238 -0
  822. mypyc/external/googletest/include/gtest/internal/gtest-linked_ptr.h +243 -0
  823. mypyc/external/googletest/include/gtest/internal/gtest-param-util-generated.h +5146 -0
  824. mypyc/external/googletest/include/gtest/internal/gtest-param-util-generated.h.pump +286 -0
  825. mypyc/external/googletest/include/gtest/internal/gtest-param-util.h +731 -0
  826. mypyc/external/googletest/include/gtest/internal/gtest-port-arch.h +93 -0
  827. mypyc/external/googletest/include/gtest/internal/gtest-port.h +2560 -0
  828. mypyc/external/googletest/include/gtest/internal/gtest-string.h +167 -0
  829. mypyc/external/googletest/include/gtest/internal/gtest-tuple.h +1020 -0
  830. mypyc/external/googletest/include/gtest/internal/gtest-tuple.h.pump +347 -0
  831. mypyc/external/googletest/include/gtest/internal/gtest-type-util.h +3331 -0
  832. mypyc/external/googletest/include/gtest/internal/gtest-type-util.h.pump +297 -0
  833. mypyc/external/googletest/make/Makefile +61 -0
  834. mypyc/external/googletest/src/gtest-all.cc +48 -0
  835. mypyc/external/googletest/src/gtest-death-test.cc +1342 -0
  836. mypyc/external/googletest/src/gtest-filepath.cc +387 -0
  837. mypyc/external/googletest/src/gtest-internal-inl.h +1183 -0
  838. mypyc/external/googletest/src/gtest-port.cc +1259 -0
  839. mypyc/external/googletest/src/gtest-printers.cc +373 -0
  840. mypyc/external/googletest/src/gtest-test-part.cc +110 -0
  841. mypyc/external/googletest/src/gtest-typed-test.cc +118 -0
  842. mypyc/external/googletest/src/gtest.cc +5388 -0
  843. mypyc/external/googletest/src/gtest_main.cc +38 -0
  844. mypyc/ir/__init__.py +0 -0
  845. mypyc/ir/class_ir.py +499 -0
  846. mypyc/ir/func_ir.py +370 -0
  847. mypyc/ir/module_ir.py +88 -0
  848. mypyc/ir/ops.py +1642 -0
  849. mypyc/ir/pprint.py +496 -0
  850. mypyc/ir/rtypes.py +1038 -0
  851. mypyc/irbuild/__init__.py +0 -0
  852. mypyc/irbuild/ast_helpers.py +120 -0
  853. mypyc/irbuild/builder.py +1398 -0
  854. mypyc/irbuild/callable_class.py +173 -0
  855. mypyc/irbuild/classdef.py +850 -0
  856. mypyc/irbuild/constant_fold.py +95 -0
  857. mypyc/irbuild/context.py +186 -0
  858. mypyc/irbuild/env_class.py +223 -0
  859. mypyc/irbuild/expression.py +1067 -0
  860. mypyc/irbuild/for_helpers.py +1046 -0
  861. mypyc/irbuild/format_str_tokenizer.py +250 -0
  862. mypyc/irbuild/function.py +1089 -0
  863. mypyc/irbuild/generator.py +346 -0
  864. mypyc/irbuild/ll_builder.py +2407 -0
  865. mypyc/irbuild/main.py +153 -0
  866. mypyc/irbuild/mapper.py +221 -0
  867. mypyc/irbuild/match.py +355 -0
  868. mypyc/irbuild/nonlocalcontrol.py +197 -0
  869. mypyc/irbuild/prebuildvisitor.py +203 -0
  870. mypyc/irbuild/prepare.py +609 -0
  871. mypyc/irbuild/specialize.py +822 -0
  872. mypyc/irbuild/statement.py +1017 -0
  873. mypyc/irbuild/targets.py +57 -0
  874. mypyc/irbuild/util.py +189 -0
  875. mypyc/irbuild/visitor.py +401 -0
  876. mypyc/irbuild/vtable.py +82 -0
  877. mypyc/lib-rt/CPy.h +643 -0
  878. mypyc/lib-rt/bytes_ops.c +143 -0
  879. mypyc/lib-rt/dict_ops.c +446 -0
  880. mypyc/lib-rt/exc_ops.c +259 -0
  881. mypyc/lib-rt/float_ops.c +192 -0
  882. mypyc/lib-rt/generic_ops.c +64 -0
  883. mypyc/lib-rt/getargs.c +450 -0
  884. mypyc/lib-rt/getargsfast.c +569 -0
  885. mypyc/lib-rt/init.c +13 -0
  886. mypyc/lib-rt/int_ops.c +803 -0
  887. mypyc/lib-rt/list_ops.c +335 -0
  888. mypyc/lib-rt/misc_ops.c +942 -0
  889. mypyc/lib-rt/module_shim.tmpl +18 -0
  890. mypyc/lib-rt/mypyc_util.h +118 -0
  891. mypyc/lib-rt/pythoncapi_compat.h +497 -0
  892. mypyc/lib-rt/pythonsupport.h +548 -0
  893. mypyc/lib-rt/set_ops.c +17 -0
  894. mypyc/lib-rt/setup.py +70 -0
  895. mypyc/lib-rt/str_ops.c +241 -0
  896. mypyc/lib-rt/test_capi.cc +585 -0
  897. mypyc/lib-rt/tuple_ops.c +61 -0
  898. mypyc/namegen.py +115 -0
  899. mypyc/options.py +32 -0
  900. mypyc/primitives/__init__.py +0 -0
  901. mypyc/primitives/bytes_ops.py +101 -0
  902. mypyc/primitives/dict_ops.py +325 -0
  903. mypyc/primitives/exc_ops.py +101 -0
  904. mypyc/primitives/float_ops.py +168 -0
  905. mypyc/primitives/generic_ops.py +384 -0
  906. mypyc/primitives/int_ops.py +304 -0
  907. mypyc/primitives/list_ops.py +300 -0
  908. mypyc/primitives/misc_ops.py +241 -0
  909. mypyc/primitives/registry.py +323 -0
  910. mypyc/primitives/set_ops.py +121 -0
  911. mypyc/primitives/str_ops.py +229 -0
  912. mypyc/primitives/tuple_ops.py +83 -0
  913. mypyc/rt_subtype.py +77 -0
  914. mypyc/sametype.py +83 -0
  915. mypyc/subtype.py +88 -0
  916. mypyc/test/__init__.py +0 -0
  917. mypyc/test/config.py +13 -0
  918. mypyc/test/test_alwaysdefined.py +46 -0
  919. mypyc/test/test_analysis.py +77 -0
  920. mypyc/test/test_cheader.py +45 -0
  921. mypyc/test/test_commandline.py +82 -0
  922. mypyc/test/test_emit.py +69 -0
  923. mypyc/test/test_emitclass.py +35 -0
  924. mypyc/test/test_emitfunc.py +926 -0
  925. mypyc/test/test_emitwrapper.py +60 -0
  926. mypyc/test/test_exceptions.py +56 -0
  927. mypyc/test/test_external.py +49 -0
  928. mypyc/test/test_irbuild.py +87 -0
  929. mypyc/test/test_ircheck.py +199 -0
  930. mypyc/test/test_literals.py +90 -0
  931. mypyc/test/test_namegen.py +48 -0
  932. mypyc/test/test_pprint.py +42 -0
  933. mypyc/test/test_rarray.py +48 -0
  934. mypyc/test/test_refcount.py +59 -0
  935. mypyc/test/test_run.py +426 -0
  936. mypyc/test/test_serialization.py +108 -0
  937. mypyc/test/test_struct.py +112 -0
  938. mypyc/test/test_tuplename.py +33 -0
  939. mypyc/test/test_typeops.py +97 -0
  940. mypyc/test/testutil.py +283 -0
  941. mypyc/test-data/alwaysdefined.test +732 -0
  942. mypyc/test-data/analysis.test +603 -0
  943. mypyc/test-data/commandline.test +245 -0
  944. mypyc/test-data/driver/driver.py +48 -0
  945. mypyc/test-data/exceptions-freq.test +125 -0
  946. mypyc/test-data/exceptions.test +713 -0
  947. mypyc/test-data/fixtures/ir.py +373 -0
  948. mypyc/test-data/fixtures/testutil.py +103 -0
  949. mypyc/test-data/fixtures/typing-full.pyi +169 -0
  950. mypyc/test-data/irbuild-any.test +238 -0
  951. mypyc/test-data/irbuild-basic.test +3690 -0
  952. mypyc/test-data/irbuild-bool.test +463 -0
  953. mypyc/test-data/irbuild-bytes.test +184 -0
  954. mypyc/test-data/irbuild-classes.test +1303 -0
  955. mypyc/test-data/irbuild-constant-fold.test +480 -0
  956. mypyc/test-data/irbuild-dict.test +585 -0
  957. mypyc/test-data/irbuild-dunders.test +223 -0
  958. mypyc/test-data/irbuild-float.test +497 -0
  959. mypyc/test-data/irbuild-generics.test +151 -0
  960. mypyc/test-data/irbuild-glue-methods.test +437 -0
  961. mypyc/test-data/irbuild-i16.test +526 -0
  962. mypyc/test-data/irbuild-i32.test +598 -0
  963. mypyc/test-data/irbuild-i64.test +2164 -0
  964. mypyc/test-data/irbuild-int.test +235 -0
  965. mypyc/test-data/irbuild-isinstance.test +109 -0
  966. mypyc/test-data/irbuild-lists.test +547 -0
  967. mypyc/test-data/irbuild-match.test +1708 -0
  968. mypyc/test-data/irbuild-math.test +64 -0
  969. mypyc/test-data/irbuild-nested.test +807 -0
  970. mypyc/test-data/irbuild-optional.test +536 -0
  971. mypyc/test-data/irbuild-set.test +838 -0
  972. mypyc/test-data/irbuild-singledispatch.test +257 -0
  973. mypyc/test-data/irbuild-statements.test +1149 -0
  974. mypyc/test-data/irbuild-str.test +314 -0
  975. mypyc/test-data/irbuild-strip-asserts.test +12 -0
  976. mypyc/test-data/irbuild-try.test +523 -0
  977. mypyc/test-data/irbuild-tuple.test +462 -0
  978. mypyc/test-data/irbuild-u8.test +543 -0
  979. mypyc/test-data/irbuild-unreachable.test +241 -0
  980. mypyc/test-data/irbuild-vectorcall.test +153 -0
  981. mypyc/test-data/refcount.test +1588 -0
  982. mypyc/test-data/run-async.test +145 -0
  983. mypyc/test-data/run-attrs.test +318 -0
  984. mypyc/test-data/run-bench.test +196 -0
  985. mypyc/test-data/run-bools.test +229 -0
  986. mypyc/test-data/run-bytes.test +302 -0
  987. mypyc/test-data/run-classes.test +2505 -0
  988. mypyc/test-data/run-dicts.test +334 -0
  989. mypyc/test-data/run-dunders.test +945 -0
  990. mypyc/test-data/run-exceptions.test +448 -0
  991. mypyc/test-data/run-floats.test +516 -0
  992. mypyc/test-data/run-functions.test +1310 -0
  993. mypyc/test-data/run-generators.test +681 -0
  994. mypyc/test-data/run-i16.test +338 -0
  995. mypyc/test-data/run-i32.test +336 -0
  996. mypyc/test-data/run-i64.test +1519 -0
  997. mypyc/test-data/run-imports.test +265 -0
  998. mypyc/test-data/run-integers.test +540 -0
  999. mypyc/test-data/run-lists.test +411 -0
  1000. mypyc/test-data/run-loops.test +485 -0
  1001. mypyc/test-data/run-match.test +283 -0
  1002. mypyc/test-data/run-math.test +106 -0
  1003. mypyc/test-data/run-misc.test +1168 -0
  1004. mypyc/test-data/run-multimodule.test +887 -0
  1005. mypyc/test-data/run-mypy-sim.test +138 -0
  1006. mypyc/test-data/run-primitives.test +375 -0
  1007. mypyc/test-data/run-python37.test +159 -0
  1008. mypyc/test-data/run-python38.test +88 -0
  1009. mypyc/test-data/run-sets.test +150 -0
  1010. mypyc/test-data/run-singledispatch.test +698 -0
  1011. mypyc/test-data/run-strings.test +641 -0
  1012. mypyc/test-data/run-traits.test +411 -0
  1013. mypyc/test-data/run-tuples.test +258 -0
  1014. mypyc/test-data/run-u8.test +303 -0
  1015. mypyc/transform/__init__.py +0 -0
  1016. mypyc/transform/exceptions.py +182 -0
  1017. mypyc/transform/refcount.py +294 -0
  1018. mypyc/transform/uninit.py +190 -0
@@ -0,0 +1,2407 @@
1
+ """A "low-level" IR builder class.
2
+
3
+ LowLevelIRBuilder provides core abstractions we use for constructing
4
+ IR as well as a number of higher-level ones (accessing attributes,
5
+ calling functions and methods, and coercing between types, for
6
+ example). The core principle of the low-level IR builder is that all
7
+ of its facilities operate solely on the IR level and not the AST
8
+ level---it has *no knowledge* of mypy types or expressions.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Callable, Final, Optional, Sequence, Tuple
14
+
15
+ from mypy.argmap import map_actuals_to_formals
16
+ from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
17
+ from mypy.operators import op_methods
18
+ from mypy.types import AnyType, TypeOfAny
19
+ from mypyc.common import (
20
+ BITMAP_BITS,
21
+ FAST_ISINSTANCE_MAX_SUBCLASSES,
22
+ MAX_LITERAL_SHORT_INT,
23
+ MAX_SHORT_INT,
24
+ MIN_LITERAL_SHORT_INT,
25
+ MIN_SHORT_INT,
26
+ PLATFORM_SIZE,
27
+ use_method_vectorcall,
28
+ use_vectorcall,
29
+ )
30
+ from mypyc.errors import Errors
31
+ from mypyc.ir.class_ir import ClassIR, all_concrete_classes
32
+ from mypyc.ir.func_ir import FuncDecl, FuncSignature
33
+ from mypyc.ir.ops import (
34
+ ERR_FALSE,
35
+ ERR_NEVER,
36
+ NAMESPACE_MODULE,
37
+ NAMESPACE_STATIC,
38
+ NAMESPACE_TYPE,
39
+ Assign,
40
+ AssignMulti,
41
+ BasicBlock,
42
+ Box,
43
+ Branch,
44
+ Call,
45
+ CallC,
46
+ Cast,
47
+ ComparisonOp,
48
+ Extend,
49
+ Float,
50
+ FloatComparisonOp,
51
+ FloatNeg,
52
+ FloatOp,
53
+ GetAttr,
54
+ GetElementPtr,
55
+ Goto,
56
+ Integer,
57
+ IntOp,
58
+ KeepAlive,
59
+ LoadAddress,
60
+ LoadErrorValue,
61
+ LoadLiteral,
62
+ LoadMem,
63
+ LoadStatic,
64
+ MethodCall,
65
+ Op,
66
+ RaiseStandardError,
67
+ Register,
68
+ SetMem,
69
+ Truncate,
70
+ TupleGet,
71
+ TupleSet,
72
+ Unbox,
73
+ Unreachable,
74
+ Value,
75
+ float_comparison_op_to_id,
76
+ float_op_to_id,
77
+ int_op_to_id,
78
+ )
79
+ from mypyc.ir.rtypes import (
80
+ PyListObject,
81
+ PyObject,
82
+ PySetObject,
83
+ PyVarObject,
84
+ RArray,
85
+ RInstance,
86
+ RPrimitive,
87
+ RTuple,
88
+ RType,
89
+ RUnion,
90
+ bit_rprimitive,
91
+ bitmap_rprimitive,
92
+ bool_rprimitive,
93
+ bytes_rprimitive,
94
+ c_int_rprimitive,
95
+ c_pointer_rprimitive,
96
+ c_pyssize_t_rprimitive,
97
+ c_size_t_rprimitive,
98
+ check_native_int_range,
99
+ dict_rprimitive,
100
+ float_rprimitive,
101
+ int_rprimitive,
102
+ is_bit_rprimitive,
103
+ is_bool_rprimitive,
104
+ is_bytes_rprimitive,
105
+ is_dict_rprimitive,
106
+ is_fixed_width_rtype,
107
+ is_float_rprimitive,
108
+ is_int16_rprimitive,
109
+ is_int32_rprimitive,
110
+ is_int64_rprimitive,
111
+ is_int_rprimitive,
112
+ is_list_rprimitive,
113
+ is_none_rprimitive,
114
+ is_set_rprimitive,
115
+ is_short_int_rprimitive,
116
+ is_str_rprimitive,
117
+ is_tagged,
118
+ is_tuple_rprimitive,
119
+ is_uint8_rprimitive,
120
+ list_rprimitive,
121
+ none_rprimitive,
122
+ object_pointer_rprimitive,
123
+ object_rprimitive,
124
+ optional_value_type,
125
+ pointer_rprimitive,
126
+ short_int_rprimitive,
127
+ str_rprimitive,
128
+ )
129
+ from mypyc.irbuild.mapper import Mapper
130
+ from mypyc.irbuild.util import concrete_arg_kind
131
+ from mypyc.options import CompilerOptions
132
+ from mypyc.primitives.bytes_ops import bytes_compare
133
+ from mypyc.primitives.dict_ops import (
134
+ dict_build_op,
135
+ dict_new_op,
136
+ dict_ssize_t_size_op,
137
+ dict_update_in_display_op,
138
+ )
139
+ from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op
140
+ from mypyc.primitives.float_ops import copysign_op, int_to_float_op
141
+ from mypyc.primitives.generic_ops import (
142
+ generic_len_op,
143
+ generic_ssize_t_len_op,
144
+ py_call_op,
145
+ py_call_with_kwargs_op,
146
+ py_getattr_op,
147
+ py_method_call_op,
148
+ py_vectorcall_method_op,
149
+ py_vectorcall_op,
150
+ )
151
+ from mypyc.primitives.int_ops import (
152
+ int16_divide_op,
153
+ int16_mod_op,
154
+ int16_overflow,
155
+ int32_divide_op,
156
+ int32_mod_op,
157
+ int32_overflow,
158
+ int64_divide_op,
159
+ int64_mod_op,
160
+ int64_to_int_op,
161
+ int_comparison_op_mapping,
162
+ int_to_int32_op,
163
+ int_to_int64_op,
164
+ ssize_t_to_int_op,
165
+ uint8_overflow,
166
+ )
167
+ from mypyc.primitives.list_ops import list_build_op, list_extend_op, new_list_op
168
+ from mypyc.primitives.misc_ops import bool_op, fast_isinstance_op, none_object_op
169
+ from mypyc.primitives.registry import (
170
+ ERR_NEG_INT,
171
+ CFunctionDescription,
172
+ binary_ops,
173
+ method_call_ops,
174
+ unary_ops,
175
+ )
176
+ from mypyc.primitives.set_ops import new_set_op
177
+ from mypyc.primitives.str_ops import str_check_if_true, str_ssize_t_size_op, unicode_compare
178
+ from mypyc.primitives.tuple_ops import list_tuple_op, new_tuple_op, new_tuple_with_length_op
179
+ from mypyc.rt_subtype import is_runtime_subtype
180
+ from mypyc.sametype import is_same_type
181
+ from mypyc.subtype import is_subtype
182
+
183
+ DictEntry = Tuple[Optional[Value], Value]
184
+
185
+ # If the number of items is less than the threshold when initializing
186
+ # a list, we would inline the generate IR using SetMem and expanded
187
+ # for-loop. Otherwise, we would call `list_build_op` for larger lists.
188
+ # TODO: The threshold is a randomly chosen number which needs further
189
+ # study on real-world projects for a better balance.
190
+ LIST_BUILDING_EXPANSION_THRESHOLD = 10
191
+
192
+ # From CPython
193
+ PY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1)
194
+
195
+ FIXED_WIDTH_INT_BINARY_OPS: Final = {
196
+ "+",
197
+ "-",
198
+ "*",
199
+ "//",
200
+ "%",
201
+ "&",
202
+ "|",
203
+ "^",
204
+ "<<",
205
+ ">>",
206
+ "+=",
207
+ "-=",
208
+ "*=",
209
+ "//=",
210
+ "%=",
211
+ "&=",
212
+ "|=",
213
+ "^=",
214
+ "<<=",
215
+ ">>=",
216
+ }
217
+
218
+ # Binary operations on bools that are specialized and don't just promote operands to int
219
+ BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="}
220
+
221
+
222
+ class LowLevelIRBuilder:
223
+ def __init__(
224
+ self, current_module: str, errors: Errors, mapper: Mapper, options: CompilerOptions
225
+ ) -> None:
226
+ self.current_module = current_module
227
+ self.errors = errors
228
+ self.mapper = mapper
229
+ self.options = options
230
+ self.args: list[Register] = []
231
+ self.blocks: list[BasicBlock] = []
232
+ # Stack of except handler entry blocks
233
+ self.error_handlers: list[BasicBlock | None] = [None]
234
+ # Values that we need to keep alive as long as we have borrowed
235
+ # temporaries. Use flush_keep_alives() to mark the end of the live range.
236
+ self.keep_alives: list[Value] = []
237
+
238
+ def set_module(self, module_name: str, module_path: str) -> None:
239
+ """Set the name and path of the current module."""
240
+ self.module_name = module_name
241
+ self.module_path = module_path
242
+
243
+ # Basic operations
244
+
245
+ def add(self, op: Op) -> Value:
246
+ """Add an op."""
247
+ assert not self.blocks[-1].terminated, "Can't add to finished block"
248
+ self.blocks[-1].ops.append(op)
249
+ return op
250
+
251
+ def goto(self, target: BasicBlock) -> None:
252
+ """Add goto to a basic block."""
253
+ if not self.blocks[-1].terminated:
254
+ self.add(Goto(target))
255
+
256
+ def activate_block(self, block: BasicBlock) -> None:
257
+ """Add a basic block and make it the active one (target of adds)."""
258
+ if self.blocks:
259
+ assert self.blocks[-1].terminated
260
+
261
+ block.error_handler = self.error_handlers[-1]
262
+ self.blocks.append(block)
263
+
264
+ def goto_and_activate(self, block: BasicBlock) -> None:
265
+ """Add goto a block and make it the active block."""
266
+ self.goto(block)
267
+ self.activate_block(block)
268
+
269
+ def keep_alive(self, values: list[Value], *, steal: bool = False) -> None:
270
+ self.add(KeepAlive(values, steal=steal))
271
+
272
+ def push_error_handler(self, handler: BasicBlock | None) -> None:
273
+ self.error_handlers.append(handler)
274
+
275
+ def pop_error_handler(self) -> BasicBlock | None:
276
+ return self.error_handlers.pop()
277
+
278
+ def self(self) -> Register:
279
+ """Return reference to the 'self' argument.
280
+
281
+ This only works in a method.
282
+ """
283
+ return self.args[0]
284
+
285
+ def flush_keep_alives(self) -> None:
286
+ if self.keep_alives:
287
+ self.add(KeepAlive(self.keep_alives.copy()))
288
+ self.keep_alives = []
289
+
290
+ # Type conversions
291
+
292
+ def box(self, src: Value) -> Value:
293
+ if src.type.is_unboxed:
294
+ if isinstance(src, Integer) and is_tagged(src.type):
295
+ return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive))
296
+ return self.add(Box(src))
297
+ else:
298
+ return src
299
+
300
+ def unbox_or_cast(
301
+ self, src: Value, target_type: RType, line: int, *, can_borrow: bool = False
302
+ ) -> Value:
303
+ if target_type.is_unboxed:
304
+ return self.add(Unbox(src, target_type, line))
305
+ else:
306
+ if can_borrow:
307
+ self.keep_alives.append(src)
308
+ return self.add(Cast(src, target_type, line, borrow=can_borrow))
309
+
310
+ def coerce(
311
+ self,
312
+ src: Value,
313
+ target_type: RType,
314
+ line: int,
315
+ force: bool = False,
316
+ *,
317
+ can_borrow: bool = False,
318
+ ) -> Value:
319
+ """Generate a coercion/cast from one type to other (only if needed).
320
+
321
+ For example, int -> object boxes the source int; int -> int emits nothing;
322
+ object -> int unboxes the object. All conversions preserve object value.
323
+
324
+ If force is true, always generate an op (even if it is just an assignment) so
325
+ that the result will have exactly target_type as the type.
326
+
327
+ Returns the register with the converted value (may be same as src).
328
+ """
329
+ src_type = src.type
330
+ if src_type.is_unboxed and not target_type.is_unboxed:
331
+ # Unboxed -> boxed
332
+ return self.box(src)
333
+ if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype(
334
+ src_type, target_type
335
+ ):
336
+ if (
337
+ isinstance(src, Integer)
338
+ and is_short_int_rprimitive(src_type)
339
+ and is_fixed_width_rtype(target_type)
340
+ ):
341
+ value = src.numeric_value()
342
+ if not check_native_int_range(target_type, value):
343
+ self.error(f'Value {value} is out of range for "{target_type}"', line)
344
+ return Integer(src.value >> 1, target_type)
345
+ elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
346
+ return self.coerce_int_to_fixed_width(src, target_type, line)
347
+ elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type):
348
+ return self.coerce_fixed_width_to_int(src, line)
349
+ elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
350
+ return self.coerce_short_int_to_fixed_width(src, target_type, line)
351
+ elif (
352
+ isinstance(src_type, RPrimitive)
353
+ and isinstance(target_type, RPrimitive)
354
+ and src_type.is_native_int
355
+ and target_type.is_native_int
356
+ and src_type.size == target_type.size
357
+ and src_type.is_signed == target_type.is_signed
358
+ ):
359
+ # Equivalent types
360
+ return src
361
+ elif (is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)) and is_tagged(
362
+ target_type
363
+ ):
364
+ shifted = self.int_op(
365
+ bool_rprimitive, src, Integer(1, bool_rprimitive), IntOp.LEFT_SHIFT
366
+ )
367
+ return self.add(Extend(shifted, target_type, signed=False))
368
+ elif (
369
+ is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)
370
+ ) and is_fixed_width_rtype(target_type):
371
+ return self.add(Extend(src, target_type, signed=False))
372
+ elif isinstance(src, Integer) and is_float_rprimitive(target_type):
373
+ if is_tagged(src_type):
374
+ return Float(float(src.value // 2))
375
+ return Float(float(src.value))
376
+ elif is_tagged(src_type) and is_float_rprimitive(target_type):
377
+ return self.int_to_float(src, line)
378
+ elif (
379
+ isinstance(src_type, RTuple)
380
+ and isinstance(target_type, RTuple)
381
+ and len(src_type.types) == len(target_type.types)
382
+ ):
383
+ # Coerce between two tuple types by coercing each item separately
384
+ values = []
385
+ for i in range(len(src_type.types)):
386
+ v = None
387
+ if isinstance(src, TupleSet):
388
+ item = src.items[i]
389
+ # We can't reuse register values, since they can be modified.
390
+ if not isinstance(item, Register):
391
+ v = item
392
+ if v is None:
393
+ v = TupleGet(src, i)
394
+ self.add(v)
395
+ values.append(v)
396
+ return self.add(
397
+ TupleSet(
398
+ [self.coerce(v, t, line) for v, t in zip(values, target_type.types)], line
399
+ )
400
+ )
401
+ # To go between any other unboxed types, we go through a boxed
402
+ # in-between value, for simplicity.
403
+ tmp = self.box(src)
404
+ return self.unbox_or_cast(tmp, target_type, line)
405
+ if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype(
406
+ src_type, target_type
407
+ ):
408
+ return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow)
409
+ elif force:
410
+ tmp = Register(target_type)
411
+ self.add(Assign(tmp, src))
412
+ return tmp
413
+ return src
414
+
415
+ def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
416
+ assert is_fixed_width_rtype(target_type), target_type
417
+ assert isinstance(target_type, RPrimitive)
418
+
419
+ res = Register(target_type)
420
+
421
+ fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock()
422
+
423
+ check = self.check_tagged_short_int(src, line)
424
+ self.add(Branch(check, fast, slow, Branch.BOOL))
425
+
426
+ self.activate_block(fast)
427
+
428
+ size = target_type.size
429
+ if size < int_rprimitive.size:
430
+ # Add a range check when the target type is smaller than the source tyoe
431
+ fast2, fast3 = BasicBlock(), BasicBlock()
432
+ upper_bound = 1 << (size * 8 - 1)
433
+ if not target_type.is_signed:
434
+ upper_bound *= 2
435
+ check2 = self.add(ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT))
436
+ self.add(Branch(check2, fast2, slow, Branch.BOOL))
437
+ self.activate_block(fast2)
438
+ if target_type.is_signed:
439
+ lower_bound = -upper_bound
440
+ else:
441
+ lower_bound = 0
442
+ check3 = self.add(ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE))
443
+ self.add(Branch(check3, fast3, slow, Branch.BOOL))
444
+ self.activate_block(fast3)
445
+ tmp = self.int_op(
446
+ c_pyssize_t_rprimitive,
447
+ src,
448
+ Integer(1, c_pyssize_t_rprimitive),
449
+ IntOp.RIGHT_SHIFT,
450
+ line,
451
+ )
452
+ tmp = self.add(Truncate(tmp, target_type))
453
+ else:
454
+ if size > int_rprimitive.size:
455
+ tmp = self.add(Extend(src, target_type, signed=True))
456
+ else:
457
+ tmp = src
458
+ tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
459
+
460
+ self.add(Assign(res, tmp))
461
+ self.goto(end)
462
+
463
+ self.activate_block(slow)
464
+ if is_int64_rprimitive(target_type) or (
465
+ is_int32_rprimitive(target_type) and size == int_rprimitive.size
466
+ ):
467
+ # Slow path calls a library function that handles more complex logic
468
+ ptr = self.int_op(
469
+ pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line
470
+ )
471
+ ptr2 = Register(c_pointer_rprimitive)
472
+ self.add(Assign(ptr2, ptr))
473
+ if is_int64_rprimitive(target_type):
474
+ conv_op = int_to_int64_op
475
+ else:
476
+ conv_op = int_to_int32_op
477
+ tmp = self.call_c(conv_op, [ptr2], line)
478
+ self.add(Assign(res, tmp))
479
+ self.add(KeepAlive([src]))
480
+ self.goto(end)
481
+ elif is_int32_rprimitive(target_type):
482
+ # Slow path just always generates an OverflowError
483
+ self.call_c(int32_overflow, [], line)
484
+ self.add(Unreachable())
485
+ elif is_int16_rprimitive(target_type):
486
+ # Slow path just always generates an OverflowError
487
+ self.call_c(int16_overflow, [], line)
488
+ self.add(Unreachable())
489
+ elif is_uint8_rprimitive(target_type):
490
+ # Slow path just always generates an OverflowError
491
+ self.call_c(uint8_overflow, [], line)
492
+ self.add(Unreachable())
493
+ else:
494
+ assert False, target_type
495
+
496
+ self.activate_block(end)
497
+ return res
498
+
499
+ def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
500
+ if is_int64_rprimitive(target_type):
501
+ return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
502
+ # TODO: i32
503
+ assert False, (src.type, target_type)
504
+
505
+ def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value:
506
+ if (
507
+ (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8)
508
+ or is_int16_rprimitive(src.type)
509
+ or is_uint8_rprimitive(src.type)
510
+ ):
511
+ # Simple case -- just sign extend and shift.
512
+ extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=src.type.is_signed))
513
+ return self.int_op(
514
+ int_rprimitive,
515
+ extended,
516
+ Integer(1, c_pyssize_t_rprimitive),
517
+ IntOp.LEFT_SHIFT,
518
+ line,
519
+ )
520
+
521
+ assert is_fixed_width_rtype(src.type)
522
+ assert isinstance(src.type, RPrimitive)
523
+ src_type = src.type
524
+
525
+ res = Register(int_rprimitive)
526
+
527
+ fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
528
+
529
+ c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE))
530
+ self.add(Branch(c1, fast, slow, Branch.BOOL))
531
+
532
+ self.activate_block(fast)
533
+ c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE))
534
+ self.add(Branch(c2, fast2, slow, Branch.BOOL))
535
+
536
+ self.activate_block(slow)
537
+ if is_int64_rprimitive(src_type):
538
+ conv_op = int64_to_int_op
539
+ elif is_int32_rprimitive(src_type):
540
+ assert PLATFORM_SIZE == 4
541
+ conv_op = ssize_t_to_int_op
542
+ else:
543
+ assert False, src_type
544
+ x = self.call_c(conv_op, [src], line)
545
+ self.add(Assign(res, x))
546
+ self.goto(end)
547
+
548
+ self.activate_block(fast2)
549
+ if int_rprimitive.size < src_type.size:
550
+ tmp = self.add(Truncate(src, c_pyssize_t_rprimitive))
551
+ else:
552
+ tmp = src
553
+ s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line)
554
+ self.add(Assign(res, s))
555
+ self.goto(end)
556
+
557
+ self.activate_block(end)
558
+ return res
559
+
560
+ def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value:
561
+ """Generate a coercion from a potentially null value."""
562
+ if src.type.is_unboxed == target_type.is_unboxed and (
563
+ (target_type.is_unboxed and is_runtime_subtype(src.type, target_type))
564
+ or (not target_type.is_unboxed and is_subtype(src.type, target_type))
565
+ ):
566
+ return src
567
+
568
+ target = Register(target_type)
569
+
570
+ valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock()
571
+ self.add(Branch(src, invalid, valid, Branch.IS_ERROR))
572
+
573
+ self.activate_block(valid)
574
+ coerced = self.coerce(src, target_type, line)
575
+ self.add(Assign(target, coerced, line))
576
+ self.goto(out)
577
+
578
+ self.activate_block(invalid)
579
+ error = self.add(LoadErrorValue(target_type))
580
+ self.add(Assign(target, error, line))
581
+
582
+ self.goto_and_activate(out)
583
+ return target
584
+
585
+ # Attribute access
586
+
587
+ def get_attr(
588
+ self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False
589
+ ) -> Value:
590
+ """Get a native or Python attribute of an object."""
591
+ if (
592
+ isinstance(obj.type, RInstance)
593
+ and obj.type.class_ir.is_ext_class
594
+ and obj.type.class_ir.has_attr(attr)
595
+ ):
596
+ op = GetAttr(obj, attr, line, borrow=borrow)
597
+ # For non-refcounted attribute types, the borrow might be
598
+ # disabled even if requested, so don't check 'borrow'.
599
+ if op.is_borrowed:
600
+ self.keep_alives.append(obj)
601
+ return self.add(op)
602
+ elif isinstance(obj.type, RUnion):
603
+ return self.union_get_attr(obj, obj.type, attr, result_type, line)
604
+ else:
605
+ return self.py_get_attr(obj, attr, line)
606
+
607
+ def union_get_attr(
608
+ self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int
609
+ ) -> Value:
610
+ """Get an attribute of an object with a union type."""
611
+
612
+ def get_item_attr(value: Value) -> Value:
613
+ return self.get_attr(value, attr, result_type, line)
614
+
615
+ return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line)
616
+
617
+ def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
618
+ """Get a Python attribute (slow).
619
+
620
+ Prefer get_attr() which generates optimized code for native classes.
621
+ """
622
+ key = self.load_str(attr)
623
+ return self.call_c(py_getattr_op, [obj, key], line)
624
+
625
+ # isinstance() checks
626
+
627
+ def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value:
628
+ """Fast path for isinstance() that checks against a list of native classes."""
629
+ if not class_irs:
630
+ return self.false()
631
+ ret = self.isinstance_native(obj, class_irs[0], line)
632
+ for class_ir in class_irs[1:]:
633
+
634
+ def other() -> Value:
635
+ return self.isinstance_native(obj, class_ir, line)
636
+
637
+ ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
638
+ return ret
639
+
640
+ def get_type_of_obj(self, obj: Value, line: int) -> Value:
641
+ ob_type_address = self.add(GetElementPtr(obj, PyObject, "ob_type", line))
642
+ ob_type = self.add(LoadMem(object_rprimitive, ob_type_address))
643
+ self.add(KeepAlive([obj]))
644
+ return ob_type
645
+
646
+ def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value:
647
+ typ = self.get_type_of_obj(obj, line)
648
+ return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line))
649
+
650
+ def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value:
651
+ """Fast isinstance() check for a native class.
652
+
653
+ If there are three or fewer concrete (non-trait) classes among the class
654
+ and all its children, use even faster type comparison checks `type(obj)
655
+ is typ`.
656
+ """
657
+ concrete = all_concrete_classes(class_ir)
658
+ if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
659
+ return self.call_c(fast_isinstance_op, [obj, self.get_native_type(class_ir)], line)
660
+ if not concrete:
661
+ # There can't be any concrete instance that matches this.
662
+ return self.false()
663
+ type_obj = self.get_native_type(concrete[0])
664
+ ret = self.type_is_op(obj, type_obj, line)
665
+ for c in concrete[1:]:
666
+
667
+ def other() -> Value:
668
+ return self.type_is_op(obj, self.get_native_type(c), line)
669
+
670
+ ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
671
+ return ret
672
+
673
+ # Calls
674
+
675
+ def _construct_varargs(
676
+ self,
677
+ args: Sequence[tuple[Value, ArgKind, str | None]],
678
+ line: int,
679
+ *,
680
+ has_star: bool,
681
+ has_star2: bool,
682
+ ) -> tuple[Value | None, Value | None]:
683
+ """Construct *args and **kwargs from a collection of arguments
684
+
685
+ This is pretty complicated, and almost all of the complication here stems from
686
+ one of two things (but mostly the second):
687
+ * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs
688
+ values in one go as we can, so we collect values until our hand is forced, and
689
+ then we emit creation of the list/tuple, and expand it from there if needed.
690
+
691
+ * Support potentially nullable argument values. This has very narrow applicability,
692
+ as this will never be done by our compiled Python code, but is critically used
693
+ by gen_glue_method when generating glue methods to mediate between the function
694
+ signature of a parent class and its subclasses.
695
+
696
+ For named-only arguments, this is quite simple: if it is
697
+ null, don't put it in the dict.
698
+
699
+ For positional-or-named arguments, things are much more complicated.
700
+ * First, anything that was passed as a positional arg
701
+ must be forwarded along as a positional arg. It *must
702
+ not* be converted to a named arg. This is because mypy
703
+ does not enforce that positional-or-named arguments
704
+ have the same name in subclasses, and it is not
705
+ uncommon for code to have different names in
706
+ subclasses (a bunch of mypy's visitors do this, for
707
+ example!). This is arguably a bug in both mypy and code doing
708
+ this, and they ought to be using positional-only arguments, but
709
+ positional-only arguments are new and ugly.
710
+
711
+ * On the flip side, we're willing to accept the
712
+ infelicity of sometimes turning an argument that was
713
+ passed by keyword into a positional argument. It's wrong,
714
+ but it's very marginal, and avoiding it would require passing
715
+ a bitmask of which arguments were named with every function call,
716
+ or something similar.
717
+ (See some discussion of this in testComplicatedArgs)
718
+
719
+ Thus, our strategy for positional-or-named arguments is to
720
+ always pass them as positional, except in the one
721
+ situation where we can not, and where we can be absolutely
722
+ sure they were passed by name: when an *earlier*
723
+ positional argument was missing its value.
724
+
725
+ This means that if we have a method `f(self, x: int=..., y: object=...)`:
726
+ * x and y present: args=(x, y), kwargs={}
727
+ * x present, y missing: args=(x,), kwargs={}
728
+ * x missing, y present: args=(), kwargs={'y': y}
729
+
730
+ To implement this, when we have multiple optional
731
+ positional arguments, we maintain a flag in a register
732
+ that tracks whether an argument has been missing, and for
733
+ each such optional argument (except the first), we check
734
+ the flag to determine whether to append the argument to
735
+ the *args list or add it to the **kwargs dict. What a
736
+ mess!
737
+
738
+ This is what really makes everything here such a tangle;
739
+ otherwise the *args and **kwargs code could be separated.
740
+
741
+ The arguments has_star and has_star2 indicate whether the target function
742
+ takes an ARG_STAR and ARG_STAR2 argument, respectively.
743
+ (These will always be true when making a pycall, and be based
744
+ on the actual target signature for a native call.)
745
+ """
746
+
747
+ star_result: Value | None = None
748
+ star2_result: Value | None = None
749
+ # We aggregate values that need to go into *args and **kwargs
750
+ # in these lists. Once all arguments are processed (in the
751
+ # happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a
752
+ # nullable arg, then we create the list and/or dict.
753
+ star_values: list[Value] = []
754
+ star2_keys: list[Value] = []
755
+ star2_values: list[Value] = []
756
+
757
+ seen_empty_reg: Register | None = None
758
+
759
+ for value, kind, name in args:
760
+ if kind == ARG_STAR:
761
+ if star_result is None:
762
+ star_result = self.new_list_op(star_values, line)
763
+ self.call_c(list_extend_op, [star_result, value], line)
764
+ elif kind == ARG_STAR2:
765
+ if star2_result is None:
766
+ star2_result = self._create_dict(star2_keys, star2_values, line)
767
+
768
+ self.call_c(dict_update_in_display_op, [star2_result, value], line=line)
769
+ else:
770
+ nullable = kind.is_optional()
771
+ maybe_pos = kind.is_positional() and has_star
772
+ maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2)
773
+
774
+ # If the argument is nullable, we need to create the
775
+ # relevant args/kwargs objects so that we can
776
+ # conditionally modify them.
777
+ if nullable:
778
+ if maybe_pos and star_result is None:
779
+ star_result = self.new_list_op(star_values, line)
780
+ if maybe_named and star2_result is None:
781
+ star2_result = self._create_dict(star2_keys, star2_values, line)
782
+
783
+ # Easy cases: just collect the argument.
784
+ if maybe_pos and star_result is None:
785
+ star_values.append(value)
786
+ continue
787
+
788
+ if maybe_named and star2_result is None:
789
+ assert name is not None
790
+ key = self.load_str(name)
791
+ star2_keys.append(key)
792
+ star2_values.append(value)
793
+ continue
794
+
795
+ # OK, anything that is nullable or *after* a nullable arg needs to be here
796
+ # TODO: We could try harder to avoid creating basic blocks in the common case
797
+ new_seen_empty_reg = seen_empty_reg
798
+
799
+ out = BasicBlock()
800
+ if nullable:
801
+ # If this is the first nullable positional arg we've seen, create
802
+ # a register to track whether anything has been null.
803
+ # (We won't *check* the register until the next argument, though.)
804
+ if maybe_pos and not seen_empty_reg:
805
+ new_seen_empty_reg = Register(bool_rprimitive)
806
+ self.add(Assign(new_seen_empty_reg, self.false(), line))
807
+
808
+ skip = BasicBlock() if maybe_pos else out
809
+ keep = BasicBlock()
810
+ self.add(Branch(value, skip, keep, Branch.IS_ERROR))
811
+ self.activate_block(keep)
812
+
813
+ # If this could be positional or named and we /might/ have seen a missing
814
+ # positional arg, then we need to compile *both* a positional and named
815
+ # version! What a pain!
816
+ if maybe_pos and maybe_named and seen_empty_reg:
817
+ pos_block, named_block = BasicBlock(), BasicBlock()
818
+ self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL))
819
+ else:
820
+ pos_block = named_block = BasicBlock()
821
+ self.goto(pos_block)
822
+
823
+ if maybe_pos:
824
+ self.activate_block(pos_block)
825
+ assert star_result
826
+ self.translate_special_method_call(
827
+ star_result, "append", [value], result_type=None, line=line
828
+ )
829
+ self.goto(out)
830
+
831
+ if maybe_named and (not maybe_pos or seen_empty_reg):
832
+ self.activate_block(named_block)
833
+ assert name is not None
834
+ key = self.load_str(name)
835
+ assert star2_result
836
+ self.translate_special_method_call(
837
+ star2_result, "__setitem__", [key, value], result_type=None, line=line
838
+ )
839
+ self.goto(out)
840
+
841
+ if nullable and maybe_pos and new_seen_empty_reg:
842
+ assert skip is not out
843
+ self.activate_block(skip)
844
+ self.add(Assign(new_seen_empty_reg, self.true(), line))
845
+ self.goto(out)
846
+
847
+ self.activate_block(out)
848
+
849
+ seen_empty_reg = new_seen_empty_reg
850
+
851
+ assert not (star_result or star_values) or has_star
852
+ assert not (star2_result or star2_values) or has_star2
853
+ if has_star:
854
+ # If we managed to make it this far without creating a
855
+ # *args list, then we can directly create a
856
+ # tuple. Otherwise create the tuple from the list.
857
+ if star_result is None:
858
+ star_result = self.new_tuple(star_values, line)
859
+ else:
860
+ star_result = self.call_c(list_tuple_op, [star_result], line)
861
+ if has_star2 and star2_result is None:
862
+ star2_result = self._create_dict(star2_keys, star2_values, line)
863
+
864
+ return star_result, star2_result
865
+
866
+ def py_call(
867
+ self,
868
+ function: Value,
869
+ arg_values: list[Value],
870
+ line: int,
871
+ arg_kinds: list[ArgKind] | None = None,
872
+ arg_names: Sequence[str | None] | None = None,
873
+ ) -> Value:
874
+ """Call a Python function (non-native and slow).
875
+
876
+ Use py_call_op or py_call_with_kwargs_op for Python function call.
877
+ """
878
+ if use_vectorcall(self.options.capi_version):
879
+ # More recent Python versions support faster vectorcalls.
880
+ result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names)
881
+ if result is not None:
882
+ return result
883
+
884
+ # If all arguments are positional, we can use py_call_op.
885
+ if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
886
+ return self.call_c(py_call_op, [function] + arg_values, line)
887
+
888
+ # Otherwise fallback to py_call_with_kwargs_op.
889
+ assert arg_names is not None
890
+
891
+ pos_args_tuple, kw_args_dict = self._construct_varargs(
892
+ list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True
893
+ )
894
+ assert pos_args_tuple and kw_args_dict
895
+
896
+ return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line)
897
+
898
+ def _py_vector_call(
899
+ self,
900
+ function: Value,
901
+ arg_values: list[Value],
902
+ line: int,
903
+ arg_kinds: list[ArgKind] | None = None,
904
+ arg_names: Sequence[str | None] | None = None,
905
+ ) -> Value | None:
906
+ """Call function using the vectorcall API if possible.
907
+
908
+ Return the return value if successful. Return None if a non-vectorcall
909
+ API should be used instead.
910
+ """
911
+ # We can do this if all args are positional or named (no *args or **kwargs, not optional).
912
+ if arg_kinds is None or all(
913
+ not kind.is_star() and not kind.is_optional() for kind in arg_kinds
914
+ ):
915
+ if arg_values:
916
+ # Create a C array containing all arguments as boxed values.
917
+ coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values]
918
+ arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True)
919
+ else:
920
+ arg_ptr = Integer(0, object_pointer_rprimitive)
921
+ num_pos = num_positional_args(arg_values, arg_kinds)
922
+ keywords = self._vectorcall_keywords(arg_names)
923
+ value = self.call_c(
924
+ py_vectorcall_op,
925
+ [function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords],
926
+ line,
927
+ )
928
+ if arg_values:
929
+ # Make sure arguments won't be freed until after the call.
930
+ # We need this because RArray doesn't support automatic
931
+ # memory management.
932
+ self.add(KeepAlive(coerced_args))
933
+ return value
934
+ return None
935
+
936
+ def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value:
937
+ """Return a reference to a tuple literal with keyword argument names.
938
+
939
+ Return null pointer if there are no keyword arguments.
940
+ """
941
+ if arg_names:
942
+ kw_list = [name for name in arg_names if name is not None]
943
+ if kw_list:
944
+ return self.add(LoadLiteral(tuple(kw_list), object_rprimitive))
945
+ return Integer(0, object_rprimitive)
946
+
947
+ def py_method_call(
948
+ self,
949
+ obj: Value,
950
+ method_name: str,
951
+ arg_values: list[Value],
952
+ line: int,
953
+ arg_kinds: list[ArgKind] | None,
954
+ arg_names: Sequence[str | None] | None,
955
+ ) -> Value:
956
+ """Call a Python method (non-native and slow)."""
957
+ if use_method_vectorcall(self.options.capi_version):
958
+ # More recent Python versions support faster vectorcalls.
959
+ result = self._py_vector_method_call(
960
+ obj, method_name, arg_values, line, arg_kinds, arg_names
961
+ )
962
+ if result is not None:
963
+ return result
964
+
965
+ if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
966
+ # Use legacy method call API
967
+ method_name_reg = self.load_str(method_name)
968
+ return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line)
969
+ else:
970
+ # Use py_call since it supports keyword arguments (and vectorcalls).
971
+ method = self.py_get_attr(obj, method_name, line)
972
+ return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names)
973
+
974
+ def _py_vector_method_call(
975
+ self,
976
+ obj: Value,
977
+ method_name: str,
978
+ arg_values: list[Value],
979
+ line: int,
980
+ arg_kinds: list[ArgKind] | None,
981
+ arg_names: Sequence[str | None] | None,
982
+ ) -> Value | None:
983
+ """Call method using the vectorcall API if possible.
984
+
985
+ Return the return value if successful. Return None if a non-vectorcall
986
+ API should be used instead.
987
+ """
988
+ if arg_kinds is None or all(
989
+ not kind.is_star() and not kind.is_optional() for kind in arg_kinds
990
+ ):
991
+ method_name_reg = self.load_str(method_name)
992
+ coerced_args = [
993
+ self.coerce(arg, object_rprimitive, line) for arg in [obj] + arg_values
994
+ ]
995
+ arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, object_ptr=True)
996
+ num_pos = num_positional_args(arg_values, arg_kinds)
997
+ keywords = self._vectorcall_keywords(arg_names)
998
+ value = self.call_c(
999
+ py_vectorcall_method_op,
1000
+ [
1001
+ method_name_reg,
1002
+ arg_ptr,
1003
+ Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive),
1004
+ keywords,
1005
+ ],
1006
+ line,
1007
+ )
1008
+ # Make sure arguments won't be freed until after the call.
1009
+ # We need this because RArray doesn't support automatic
1010
+ # memory management.
1011
+ self.add(KeepAlive(coerced_args))
1012
+ return value
1013
+ return None
1014
+
1015
+ def call(
1016
+ self,
1017
+ decl: FuncDecl,
1018
+ args: Sequence[Value],
1019
+ arg_kinds: list[ArgKind],
1020
+ arg_names: Sequence[str | None],
1021
+ line: int,
1022
+ *,
1023
+ bitmap_args: list[Register] | None = None,
1024
+ ) -> Value:
1025
+ """Call a native function.
1026
+
1027
+ If bitmap_args is given, they override the values of (some) of the bitmap
1028
+ arguments used to track the presence of values for certain arguments. By
1029
+ default, the values of the bitmap arguments are inferred from args.
1030
+ """
1031
+ # Normalize args to positionals.
1032
+ args = self.native_args_to_positional(
1033
+ args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args
1034
+ )
1035
+ return self.add(Call(decl, args, line))
1036
+
1037
+ def native_args_to_positional(
1038
+ self,
1039
+ args: Sequence[Value],
1040
+ arg_kinds: list[ArgKind],
1041
+ arg_names: Sequence[str | None],
1042
+ sig: FuncSignature,
1043
+ line: int,
1044
+ *,
1045
+ bitmap_args: list[Register] | None = None,
1046
+ ) -> list[Value]:
1047
+ """Prepare arguments for a native call.
1048
+
1049
+ Given args/kinds/names and a target signature for a native call, map
1050
+ keyword arguments to their appropriate place in the argument list,
1051
+ fill in error values for unspecified default arguments,
1052
+ package arguments that will go into *args/**kwargs into a tuple/dict,
1053
+ and coerce arguments to the appropriate type.
1054
+ """
1055
+
1056
+ sig_args = sig.args
1057
+ n = sig.num_bitmap_args
1058
+ if n:
1059
+ sig_args = sig_args[:-n]
1060
+
1061
+ sig_arg_kinds = [arg.kind for arg in sig_args]
1062
+ sig_arg_names = [arg.name for arg in sig_args]
1063
+
1064
+ concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]
1065
+ formal_to_actual = map_actuals_to_formals(
1066
+ concrete_kinds,
1067
+ arg_names,
1068
+ sig_arg_kinds,
1069
+ sig_arg_names,
1070
+ lambda n: AnyType(TypeOfAny.special_form),
1071
+ )
1072
+
1073
+ # First scan for */** and construct those
1074
+ has_star = has_star2 = False
1075
+ star_arg_entries = []
1076
+ for lst, arg in zip(formal_to_actual, sig_args):
1077
+ if arg.kind.is_star():
1078
+ star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst])
1079
+ has_star = has_star or arg.kind == ARG_STAR
1080
+ has_star2 = has_star2 or arg.kind == ARG_STAR2
1081
+
1082
+ star_arg, star2_arg = self._construct_varargs(
1083
+ star_arg_entries, line, has_star=has_star, has_star2=has_star2
1084
+ )
1085
+
1086
+ # Flatten out the arguments, loading error values for default
1087
+ # arguments, constructing tuples/dicts for star args, and
1088
+ # coercing everything to the expected type.
1089
+ output_args: list[Value] = []
1090
+ for lst, arg in zip(formal_to_actual, sig_args):
1091
+ if arg.kind == ARG_STAR:
1092
+ assert star_arg
1093
+ output_arg = star_arg
1094
+ elif arg.kind == ARG_STAR2:
1095
+ assert star2_arg
1096
+ output_arg = star2_arg
1097
+ elif not lst:
1098
+ if is_fixed_width_rtype(arg.type):
1099
+ output_arg = Integer(0, arg.type)
1100
+ elif is_float_rprimitive(arg.type):
1101
+ output_arg = Float(0.0)
1102
+ else:
1103
+ output_arg = self.add(LoadErrorValue(arg.type, is_borrowed=True))
1104
+ else:
1105
+ base_arg = args[lst[0]]
1106
+
1107
+ if arg_kinds[lst[0]].is_optional():
1108
+ output_arg = self.coerce_nullable(base_arg, arg.type, line)
1109
+ else:
1110
+ output_arg = self.coerce(base_arg, arg.type, line)
1111
+
1112
+ output_args.append(output_arg)
1113
+
1114
+ for i in reversed(range(n)):
1115
+ if bitmap_args and i < len(bitmap_args):
1116
+ # Use override provided by caller
1117
+ output_args.append(bitmap_args[i])
1118
+ continue
1119
+ # Infer values of bitmap args
1120
+ bitmap = 0
1121
+ c = 0
1122
+ for lst, arg in zip(formal_to_actual, sig_args):
1123
+ if arg.kind.is_optional() and arg.type.error_overlap:
1124
+ if i * BITMAP_BITS <= c < (i + 1) * BITMAP_BITS:
1125
+ if lst:
1126
+ bitmap |= 1 << (c & (BITMAP_BITS - 1))
1127
+ c += 1
1128
+ output_args.append(Integer(bitmap, bitmap_rprimitive))
1129
+
1130
+ return output_args
1131
+
1132
+ def gen_method_call(
1133
+ self,
1134
+ base: Value,
1135
+ name: str,
1136
+ arg_values: list[Value],
1137
+ result_type: RType | None,
1138
+ line: int,
1139
+ arg_kinds: list[ArgKind] | None = None,
1140
+ arg_names: list[str | None] | None = None,
1141
+ can_borrow: bool = False,
1142
+ ) -> Value:
1143
+ """Generate either a native or Python method call."""
1144
+ # If we have *args, then fallback to Python method call.
1145
+ if arg_kinds is not None and any(kind.is_star() for kind in arg_kinds):
1146
+ return self.py_method_call(base, name, arg_values, base.line, arg_kinds, arg_names)
1147
+
1148
+ # If the base type is one of ours, do a MethodCall
1149
+ if (
1150
+ isinstance(base.type, RInstance)
1151
+ and base.type.class_ir.is_ext_class
1152
+ and not base.type.class_ir.builtin_base
1153
+ ):
1154
+ if base.type.class_ir.has_method(name):
1155
+ decl = base.type.class_ir.method_decl(name)
1156
+ if arg_kinds is None:
1157
+ assert arg_names is None, "arg_kinds not present but arg_names is"
1158
+ arg_kinds = [ARG_POS for _ in arg_values]
1159
+ arg_names = [None for _ in arg_values]
1160
+ else:
1161
+ assert arg_names is not None, "arg_kinds present but arg_names is not"
1162
+
1163
+ # Normalize args to positionals.
1164
+ assert decl.bound_sig
1165
+ arg_values = self.native_args_to_positional(
1166
+ arg_values, arg_kinds, arg_names, decl.bound_sig, line
1167
+ )
1168
+ return self.add(MethodCall(base, name, arg_values, line))
1169
+ elif base.type.class_ir.has_attr(name):
1170
+ function = self.add(GetAttr(base, name, line))
1171
+ return self.py_call(
1172
+ function, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names
1173
+ )
1174
+
1175
+ elif isinstance(base.type, RUnion):
1176
+ return self.union_method_call(
1177
+ base, base.type, name, arg_values, result_type, line, arg_kinds, arg_names
1178
+ )
1179
+
1180
+ # Try to do a special-cased method call
1181
+ if not arg_kinds or arg_kinds == [ARG_POS] * len(arg_values):
1182
+ target = self.translate_special_method_call(
1183
+ base, name, arg_values, result_type, line, can_borrow=can_borrow
1184
+ )
1185
+ if target:
1186
+ return target
1187
+
1188
+ # Fall back to Python method call
1189
+ return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)
1190
+
1191
+ def union_method_call(
1192
+ self,
1193
+ base: Value,
1194
+ obj_type: RUnion,
1195
+ name: str,
1196
+ arg_values: list[Value],
1197
+ return_rtype: RType | None,
1198
+ line: int,
1199
+ arg_kinds: list[ArgKind] | None,
1200
+ arg_names: list[str | None] | None,
1201
+ ) -> Value:
1202
+ """Generate a method call with a union type for the object."""
1203
+ # Union method call needs a return_rtype for the type of the output register.
1204
+ # If we don't have one, use object_rprimitive.
1205
+ return_rtype = return_rtype or object_rprimitive
1206
+
1207
+ def call_union_item(value: Value) -> Value:
1208
+ return self.gen_method_call(
1209
+ value, name, arg_values, return_rtype, line, arg_kinds, arg_names
1210
+ )
1211
+
1212
+ return self.decompose_union_helper(base, obj_type, return_rtype, call_union_item, line)
1213
+
1214
+ # Loading various values
1215
+
1216
+ def none(self) -> Value:
1217
+ """Load unboxed None value (type: none_rprimitive)."""
1218
+ return Integer(1, none_rprimitive)
1219
+
1220
+ def true(self) -> Value:
1221
+ """Load unboxed True value (type: bool_rprimitive)."""
1222
+ return Integer(1, bool_rprimitive)
1223
+
1224
+ def false(self) -> Value:
1225
+ """Load unboxed False value (type: bool_rprimitive)."""
1226
+ return Integer(0, bool_rprimitive)
1227
+
1228
+ def none_object(self) -> Value:
1229
+ """Load Python None value (type: object_rprimitive)."""
1230
+ return self.add(LoadAddress(none_object_op.type, none_object_op.src, line=-1))
1231
+
1232
+ def load_int(self, value: int) -> Value:
1233
+ """Load a tagged (Python) integer literal value."""
1234
+ if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:
1235
+ return self.add(LoadLiteral(value, int_rprimitive))
1236
+ else:
1237
+ return Integer(value)
1238
+
1239
+ def load_float(self, value: float) -> Value:
1240
+ """Load a float literal value."""
1241
+ return Float(value)
1242
+
1243
+ def load_str(self, value: str) -> Value:
1244
+ """Load a str literal value.
1245
+
1246
+ This is useful for more than just str literals; for example, method calls
1247
+ also require a PyObject * form for the name of the method.
1248
+ """
1249
+ return self.add(LoadLiteral(value, str_rprimitive))
1250
+
1251
+ def load_bytes(self, value: bytes) -> Value:
1252
+ """Load a bytes literal value."""
1253
+ return self.add(LoadLiteral(value, bytes_rprimitive))
1254
+
1255
+ def load_complex(self, value: complex) -> Value:
1256
+ """Load a complex literal value."""
1257
+ return self.add(LoadLiteral(value, object_rprimitive))
1258
+
1259
+ def load_static_checked(
1260
+ self,
1261
+ typ: RType,
1262
+ identifier: str,
1263
+ module_name: str | None = None,
1264
+ namespace: str = NAMESPACE_STATIC,
1265
+ line: int = -1,
1266
+ error_msg: str | None = None,
1267
+ ) -> Value:
1268
+ if error_msg is None:
1269
+ error_msg = f'name "{identifier}" is not defined'
1270
+ ok_block, error_block = BasicBlock(), BasicBlock()
1271
+ value = self.add(LoadStatic(typ, identifier, module_name, namespace, line=line))
1272
+ self.add(Branch(value, error_block, ok_block, Branch.IS_ERROR, rare=True))
1273
+ self.activate_block(error_block)
1274
+ self.add(RaiseStandardError(RaiseStandardError.NAME_ERROR, error_msg, line))
1275
+ self.add(Unreachable())
1276
+ self.activate_block(ok_block)
1277
+ return value
1278
+
1279
+ def load_module(self, name: str) -> Value:
1280
+ return self.add(LoadStatic(object_rprimitive, name, namespace=NAMESPACE_MODULE))
1281
+
1282
+ def get_native_type(self, cls: ClassIR) -> Value:
1283
+ """Load native type object."""
1284
+ fullname = f"{cls.module_name}.{cls.name}"
1285
+ return self.load_native_type_object(fullname)
1286
+
1287
+ def load_native_type_object(self, fullname: str) -> Value:
1288
+ module, name = fullname.rsplit(".", 1)
1289
+ return self.add(LoadStatic(object_rprimitive, name, module, NAMESPACE_TYPE))
1290
+
1291
+ # Other primitive operations
1292
+
1293
+ def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1294
+ """Perform a binary operation.
1295
+
1296
+ Generate specialized operations based on operand types, with a fallback
1297
+ to generic operations.
1298
+ """
1299
+ ltype = lreg.type
1300
+ rtype = rreg.type
1301
+
1302
+ # Special case tuple comparison here so that nested tuples can be supported
1303
+ if isinstance(ltype, RTuple) and isinstance(rtype, RTuple) and op in ("==", "!="):
1304
+ return self.compare_tuples(lreg, rreg, op, line)
1305
+
1306
+ # Special case == and != when we can resolve the method call statically
1307
+ if op in ("==", "!="):
1308
+ value = self.translate_eq_cmp(lreg, rreg, op, line)
1309
+ if value is not None:
1310
+ return value
1311
+
1312
+ # Special case various ops
1313
+ if op in ("is", "is not"):
1314
+ return self.translate_is_op(lreg, rreg, op, line)
1315
+ # TODO: modify 'str' to use same interface as 'compare_bytes' as it avoids
1316
+ # call to PyErr_Occurred()
1317
+ if is_str_rprimitive(ltype) and is_str_rprimitive(rtype) and op in ("==", "!="):
1318
+ return self.compare_strings(lreg, rreg, op, line)
1319
+ if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype) and op in ("==", "!="):
1320
+ return self.compare_bytes(lreg, rreg, op, line)
1321
+ if is_tagged(ltype) and is_tagged(rtype) and op in int_comparison_op_mapping:
1322
+ return self.compare_tagged(lreg, rreg, op, line)
1323
+ if is_bool_rprimitive(ltype) and is_bool_rprimitive(rtype) and op in BOOL_BINARY_OPS:
1324
+ if op in ComparisonOp.signed_ops:
1325
+ return self.bool_comparison_op(lreg, rreg, op, line)
1326
+ else:
1327
+ return self.bool_bitwise_op(lreg, rreg, op[0], line)
1328
+ if isinstance(rtype, RInstance) and op in ("in", "not in"):
1329
+ return self.translate_instance_contains(rreg, lreg, op, line)
1330
+ if is_fixed_width_rtype(ltype):
1331
+ if op in FIXED_WIDTH_INT_BINARY_OPS:
1332
+ if op.endswith("="):
1333
+ op = op[:-1]
1334
+ if op != "//":
1335
+ op_id = int_op_to_id[op]
1336
+ else:
1337
+ op_id = IntOp.DIV
1338
+ if is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype):
1339
+ rreg = self.coerce(rreg, ltype, line)
1340
+ rtype = ltype
1341
+ if is_fixed_width_rtype(rtype) or is_tagged(rtype):
1342
+ return self.fixed_width_int_op(ltype, lreg, rreg, op_id, line)
1343
+ if isinstance(rreg, Integer):
1344
+ return self.fixed_width_int_op(
1345
+ ltype, lreg, self.coerce(rreg, ltype, line), op_id, line
1346
+ )
1347
+ elif op in ComparisonOp.signed_ops:
1348
+ if is_int_rprimitive(rtype):
1349
+ rreg = self.coerce_int_to_fixed_width(rreg, ltype, line)
1350
+ elif is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype):
1351
+ rreg = self.coerce(rreg, ltype, line)
1352
+ op_id = ComparisonOp.signed_ops[op]
1353
+ if is_fixed_width_rtype(rreg.type):
1354
+ return self.comparison_op(lreg, rreg, op_id, line)
1355
+ if isinstance(rreg, Integer):
1356
+ return self.comparison_op(lreg, self.coerce(rreg, ltype, line), op_id, line)
1357
+ elif is_fixed_width_rtype(rtype):
1358
+ if op in FIXED_WIDTH_INT_BINARY_OPS:
1359
+ if op.endswith("="):
1360
+ op = op[:-1]
1361
+ if op != "//":
1362
+ op_id = int_op_to_id[op]
1363
+ else:
1364
+ op_id = IntOp.DIV
1365
+ if isinstance(lreg, Integer):
1366
+ return self.fixed_width_int_op(
1367
+ rtype, self.coerce(lreg, rtype, line), rreg, op_id, line
1368
+ )
1369
+ if is_tagged(ltype):
1370
+ return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
1371
+ if is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype):
1372
+ lreg = self.coerce(lreg, rtype, line)
1373
+ return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
1374
+ elif op in ComparisonOp.signed_ops:
1375
+ if is_int_rprimitive(ltype):
1376
+ lreg = self.coerce_int_to_fixed_width(lreg, rtype, line)
1377
+ elif is_bool_rprimitive(ltype) or is_bit_rprimitive(ltype):
1378
+ lreg = self.coerce(lreg, rtype, line)
1379
+ op_id = ComparisonOp.signed_ops[op]
1380
+ if isinstance(lreg, Integer):
1381
+ return self.comparison_op(self.coerce(lreg, rtype, line), rreg, op_id, line)
1382
+ if is_fixed_width_rtype(lreg.type):
1383
+ return self.comparison_op(lreg, rreg, op_id, line)
1384
+
1385
+ # Mixed int comparisons
1386
+ if op in ("==", "!="):
1387
+ op_id = ComparisonOp.signed_ops[op]
1388
+ if is_tagged(ltype) and is_subtype(rtype, ltype):
1389
+ rreg = self.coerce(rreg, int_rprimitive, line)
1390
+ return self.comparison_op(lreg, rreg, op_id, line)
1391
+ if is_tagged(rtype) and is_subtype(ltype, rtype):
1392
+ lreg = self.coerce(lreg, int_rprimitive, line)
1393
+ return self.comparison_op(lreg, rreg, op_id, line)
1394
+ elif op in op in int_comparison_op_mapping:
1395
+ if is_tagged(ltype) and is_subtype(rtype, ltype):
1396
+ rreg = self.coerce(rreg, short_int_rprimitive, line)
1397
+ return self.compare_tagged(lreg, rreg, op, line)
1398
+ if is_tagged(rtype) and is_subtype(ltype, rtype):
1399
+ lreg = self.coerce(lreg, short_int_rprimitive, line)
1400
+ return self.compare_tagged(lreg, rreg, op, line)
1401
+ if is_float_rprimitive(ltype) or is_float_rprimitive(rtype):
1402
+ if isinstance(lreg, Integer):
1403
+ lreg = Float(float(lreg.numeric_value()))
1404
+ elif isinstance(rreg, Integer):
1405
+ rreg = Float(float(rreg.numeric_value()))
1406
+ elif is_int_rprimitive(lreg.type):
1407
+ lreg = self.int_to_float(lreg, line)
1408
+ elif is_int_rprimitive(rreg.type):
1409
+ rreg = self.int_to_float(rreg, line)
1410
+ if is_float_rprimitive(lreg.type) and is_float_rprimitive(rreg.type):
1411
+ if op in float_comparison_op_to_id:
1412
+ return self.compare_floats(lreg, rreg, float_comparison_op_to_id[op], line)
1413
+ if op.endswith("="):
1414
+ base_op = op[:-1]
1415
+ else:
1416
+ base_op = op
1417
+ if base_op in float_op_to_id:
1418
+ return self.float_op(lreg, rreg, base_op, line)
1419
+
1420
+ call_c_ops_candidates = binary_ops.get(op, [])
1421
+ target = self.matching_call_c(call_c_ops_candidates, [lreg, rreg], line)
1422
+ assert target, "Unsupported binary operation: %s" % op
1423
+ return target
1424
+
1425
+ def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) -> Value:
1426
+ """Check if a tagged integer is a short integer.
1427
+
1428
+ Return the result of the check (value of type 'bit').
1429
+ """
1430
+ int_tag = Integer(1, c_pyssize_t_rprimitive, line)
1431
+ bitwise_and = self.int_op(c_pyssize_t_rprimitive, val, int_tag, IntOp.AND, line)
1432
+ zero = Integer(0, c_pyssize_t_rprimitive, line)
1433
+ op = ComparisonOp.NEQ if negated else ComparisonOp.EQ
1434
+ check = self.comparison_op(bitwise_and, zero, op, line)
1435
+ return check
1436
+
1437
+ def compare_tagged(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
1438
+ """Compare two tagged integers using given operator (value context)."""
1439
+ # generate fast binary logic ops on short ints
1440
+ if is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type):
1441
+ return self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line)
1442
+ op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op]
1443
+ result = Register(bool_rprimitive)
1444
+ short_int_block, int_block, out = BasicBlock(), BasicBlock(), BasicBlock()
1445
+ check_lhs = self.check_tagged_short_int(lhs, line)
1446
+ if op in ("==", "!="):
1447
+ check = check_lhs
1448
+ else:
1449
+ # for non-equality logical ops (less/greater than, etc.), need to check both sides
1450
+ check_rhs = self.check_tagged_short_int(rhs, line)
1451
+ check = self.int_op(bit_rprimitive, check_lhs, check_rhs, IntOp.AND, line)
1452
+ self.add(Branch(check, short_int_block, int_block, Branch.BOOL))
1453
+ self.activate_block(short_int_block)
1454
+ eq = self.comparison_op(lhs, rhs, op_type, line)
1455
+ self.add(Assign(result, eq, line))
1456
+ self.goto(out)
1457
+ self.activate_block(int_block)
1458
+ if swap_op:
1459
+ args = [rhs, lhs]
1460
+ else:
1461
+ args = [lhs, rhs]
1462
+ call = self.call_c(c_func_desc, args, line)
1463
+ if negate_result:
1464
+ # TODO: introduce UnaryIntOp?
1465
+ call_result = self.unary_op(call, "not", line)
1466
+ else:
1467
+ call_result = call
1468
+ self.add(Assign(result, call_result, line))
1469
+ self.goto_and_activate(out)
1470
+ return result
1471
+
1472
+ def compare_tagged_condition(
1473
+ self, lhs: Value, rhs: Value, op: str, true: BasicBlock, false: BasicBlock, line: int
1474
+ ) -> None:
1475
+ """Compare two tagged integers using given operator (conditional context).
1476
+
1477
+ Assume lhs and rhs are tagged integers.
1478
+
1479
+ Args:
1480
+ lhs: Left operand
1481
+ rhs: Right operand
1482
+ op: Operation, one of '==', '!=', '<', '<=', '>', '<='
1483
+ true: Branch target if comparison is true
1484
+ false: Branch target if comparison is false
1485
+ """
1486
+ is_eq = op in ("==", "!=")
1487
+ if (is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type)) or (
1488
+ is_eq and (is_short_int_rprimitive(lhs.type) or is_short_int_rprimitive(rhs.type))
1489
+ ):
1490
+ # We can skip the tag check
1491
+ check = self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line)
1492
+ self.flush_keep_alives()
1493
+ self.add(Branch(check, true, false, Branch.BOOL))
1494
+ return
1495
+ op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op]
1496
+ int_block, short_int_block = BasicBlock(), BasicBlock()
1497
+ check_lhs = self.check_tagged_short_int(lhs, line, negated=True)
1498
+ if is_eq or is_short_int_rprimitive(rhs.type):
1499
+ self.flush_keep_alives()
1500
+ self.add(Branch(check_lhs, int_block, short_int_block, Branch.BOOL))
1501
+ else:
1502
+ # For non-equality logical ops (less/greater than, etc.), need to check both sides
1503
+ rhs_block = BasicBlock()
1504
+ self.add(Branch(check_lhs, int_block, rhs_block, Branch.BOOL))
1505
+ self.activate_block(rhs_block)
1506
+ check_rhs = self.check_tagged_short_int(rhs, line, negated=True)
1507
+ self.flush_keep_alives()
1508
+ self.add(Branch(check_rhs, int_block, short_int_block, Branch.BOOL))
1509
+ # Arbitrary integers (slow path)
1510
+ self.activate_block(int_block)
1511
+ if swap_op:
1512
+ args = [rhs, lhs]
1513
+ else:
1514
+ args = [lhs, rhs]
1515
+ call = self.call_c(c_func_desc, args, line)
1516
+ if negate_result:
1517
+ self.add(Branch(call, false, true, Branch.BOOL))
1518
+ else:
1519
+ self.flush_keep_alives()
1520
+ self.add(Branch(call, true, false, Branch.BOOL))
1521
+ # Short integers (fast path)
1522
+ self.activate_block(short_int_block)
1523
+ eq = self.comparison_op(lhs, rhs, op_type, line)
1524
+ self.add(Branch(eq, true, false, Branch.BOOL))
1525
+
1526
+ def compare_strings(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
1527
+ """Compare two strings"""
1528
+ compare_result = self.call_c(unicode_compare, [lhs, rhs], line)
1529
+ error_constant = Integer(-1, c_int_rprimitive, line)
1530
+ compare_error_check = self.add(
1531
+ ComparisonOp(compare_result, error_constant, ComparisonOp.EQ, line)
1532
+ )
1533
+ exception_check, propagate, final_compare = BasicBlock(), BasicBlock(), BasicBlock()
1534
+ branch = Branch(compare_error_check, exception_check, final_compare, Branch.BOOL)
1535
+ branch.negated = False
1536
+ self.add(branch)
1537
+ self.activate_block(exception_check)
1538
+ check_error_result = self.call_c(err_occurred_op, [], line)
1539
+ null = Integer(0, pointer_rprimitive, line)
1540
+ compare_error_check = self.add(
1541
+ ComparisonOp(check_error_result, null, ComparisonOp.NEQ, line)
1542
+ )
1543
+ branch = Branch(compare_error_check, propagate, final_compare, Branch.BOOL)
1544
+ branch.negated = False
1545
+ self.add(branch)
1546
+ self.activate_block(propagate)
1547
+ self.call_c(keep_propagating_op, [], line)
1548
+ self.goto(final_compare)
1549
+ self.activate_block(final_compare)
1550
+ op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
1551
+ return self.add(ComparisonOp(compare_result, Integer(0, c_int_rprimitive), op_type, line))
1552
+
1553
+ def compare_bytes(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
1554
+ compare_result = self.call_c(bytes_compare, [lhs, rhs], line)
1555
+ op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
1556
+ return self.add(ComparisonOp(compare_result, Integer(1, c_int_rprimitive), op_type, line))
1557
+
1558
+ def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Value:
1559
+ """Compare two tuples item by item"""
1560
+ # type cast to pass mypy check
1561
+ assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple)
1562
+ equal = True if op == "==" else False
1563
+ result = Register(bool_rprimitive)
1564
+ # empty tuples
1565
+ if len(lhs.type.types) == 0 and len(rhs.type.types) == 0:
1566
+ self.add(Assign(result, self.true() if equal else self.false(), line))
1567
+ return result
1568
+ length = len(lhs.type.types)
1569
+ false_assign, true_assign, out = BasicBlock(), BasicBlock(), BasicBlock()
1570
+ check_blocks = [BasicBlock() for _ in range(length)]
1571
+ lhs_items = [self.add(TupleGet(lhs, i, line)) for i in range(length)]
1572
+ rhs_items = [self.add(TupleGet(rhs, i, line)) for i in range(length)]
1573
+
1574
+ if equal:
1575
+ early_stop, final = false_assign, true_assign
1576
+ else:
1577
+ early_stop, final = true_assign, false_assign
1578
+
1579
+ for i in range(len(lhs.type.types)):
1580
+ if i != 0:
1581
+ self.activate_block(check_blocks[i])
1582
+ lhs_item = lhs_items[i]
1583
+ rhs_item = rhs_items[i]
1584
+ compare = self.binary_op(lhs_item, rhs_item, op, line)
1585
+ # Cast to bool if necessary since most types uses comparison returning a object type
1586
+ # See generic_ops.py for more information
1587
+ if not is_bool_rprimitive(compare.type):
1588
+ compare = self.call_c(bool_op, [compare], line)
1589
+ if i < len(lhs.type.types) - 1:
1590
+ branch = Branch(compare, early_stop, check_blocks[i + 1], Branch.BOOL)
1591
+ else:
1592
+ branch = Branch(compare, early_stop, final, Branch.BOOL)
1593
+ # if op is ==, we branch on false, else branch on true
1594
+ branch.negated = equal
1595
+ self.add(branch)
1596
+ self.activate_block(false_assign)
1597
+ self.add(Assign(result, self.false(), line))
1598
+ self.goto(out)
1599
+ self.activate_block(true_assign)
1600
+ self.add(Assign(result, self.true(), line))
1601
+ self.goto_and_activate(out)
1602
+ return result
1603
+
1604
+ def translate_instance_contains(self, inst: Value, item: Value, op: str, line: int) -> Value:
1605
+ res = self.gen_method_call(inst, "__contains__", [item], None, line)
1606
+ if not is_bool_rprimitive(res.type):
1607
+ res = self.call_c(bool_op, [res], line)
1608
+ if op == "not in":
1609
+ res = self.bool_bitwise_op(res, Integer(1, rtype=bool_rprimitive), "^", line)
1610
+ return res
1611
+
1612
+ def bool_bitwise_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1613
+ if op == "&":
1614
+ code = IntOp.AND
1615
+ elif op == "|":
1616
+ code = IntOp.OR
1617
+ elif op == "^":
1618
+ code = IntOp.XOR
1619
+ else:
1620
+ assert False, op
1621
+ return self.add(IntOp(bool_rprimitive, lreg, rreg, code, line))
1622
+
1623
+ def bool_comparison_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1624
+ op_id = ComparisonOp.signed_ops[op]
1625
+ return self.comparison_op(lreg, rreg, op_id, line)
1626
+
1627
+ def unary_not(self, value: Value, line: int) -> Value:
1628
+ mask = Integer(1, value.type, line)
1629
+ return self.int_op(value.type, value, mask, IntOp.XOR, line)
1630
+
1631
+ def unary_op(self, value: Value, expr_op: str, line: int) -> Value:
1632
+ typ = value.type
1633
+ if is_bool_rprimitive(typ) or is_bit_rprimitive(typ):
1634
+ if expr_op == "not":
1635
+ return self.unary_not(value, line)
1636
+ if expr_op == "+":
1637
+ return value
1638
+ if is_fixed_width_rtype(typ):
1639
+ if expr_op == "-":
1640
+ # Translate to '0 - x'
1641
+ return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)
1642
+ elif expr_op == "~":
1643
+ if typ.is_signed:
1644
+ # Translate to 'x ^ -1'
1645
+ return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line)
1646
+ else:
1647
+ # Translate to 'x ^ 0xff...'
1648
+ mask = (1 << (typ.size * 8)) - 1
1649
+ return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line)
1650
+ elif expr_op == "+":
1651
+ return value
1652
+ if is_float_rprimitive(typ):
1653
+ if expr_op == "-":
1654
+ return self.add(FloatNeg(value, line))
1655
+ elif expr_op == "+":
1656
+ return value
1657
+
1658
+ if isinstance(value, Integer):
1659
+ # TODO: Overflow? Unsigned?
1660
+ num = value.value
1661
+ if is_short_int_rprimitive(typ):
1662
+ num >>= 1
1663
+ return Integer(-num, typ, value.line)
1664
+ if is_tagged(typ) and expr_op == "+":
1665
+ return value
1666
+ if isinstance(value, Float):
1667
+ return Float(-value.value, value.line)
1668
+ if isinstance(typ, RInstance):
1669
+ if expr_op == "-":
1670
+ method = "__neg__"
1671
+ elif expr_op == "+":
1672
+ method = "__pos__"
1673
+ elif expr_op == "~":
1674
+ method = "__invert__"
1675
+ else:
1676
+ method = ""
1677
+ if method and typ.class_ir.has_method(method):
1678
+ return self.gen_method_call(value, method, [], None, line)
1679
+ call_c_ops_candidates = unary_ops.get(expr_op, [])
1680
+ target = self.matching_call_c(call_c_ops_candidates, [value], line)
1681
+ assert target, "Unsupported unary operation: %s" % expr_op
1682
+ return target
1683
+
1684
+ def make_dict(self, key_value_pairs: Sequence[DictEntry], line: int) -> Value:
1685
+ result: Value | None = None
1686
+ keys: list[Value] = []
1687
+ values: list[Value] = []
1688
+ for key, value in key_value_pairs:
1689
+ if key is not None:
1690
+ # key:value
1691
+ if result is None:
1692
+ keys.append(key)
1693
+ values.append(value)
1694
+ continue
1695
+
1696
+ self.translate_special_method_call(
1697
+ result, "__setitem__", [key, value], result_type=None, line=line
1698
+ )
1699
+ else:
1700
+ # **value
1701
+ if result is None:
1702
+ result = self._create_dict(keys, values, line)
1703
+
1704
+ self.call_c(dict_update_in_display_op, [result, value], line=line)
1705
+
1706
+ if result is None:
1707
+ result = self._create_dict(keys, values, line)
1708
+
1709
+ return result
1710
+
1711
+ def new_list_op_with_length(self, length: Value, line: int) -> Value:
1712
+ """This function returns an uninitialized list.
1713
+
1714
+ If the length is non-zero, the caller must initialize the list, before
1715
+ it can be made visible to user code -- otherwise the list object is broken.
1716
+ You might need further initialization with `new_list_set_item_op` op.
1717
+
1718
+ Args:
1719
+ length: desired length of the new list. The rtype should be
1720
+ c_pyssize_t_rprimitive
1721
+ line: line number
1722
+ """
1723
+ return self.call_c(new_list_op, [length], line)
1724
+
1725
+ def new_list_op(self, values: list[Value], line: int) -> Value:
1726
+ length: list[Value] = [Integer(len(values), c_pyssize_t_rprimitive, line)]
1727
+ if len(values) >= LIST_BUILDING_EXPANSION_THRESHOLD:
1728
+ return self.call_c(list_build_op, length + values, line)
1729
+
1730
+ # If the length of the list is less than the threshold,
1731
+ # LIST_BUILDING_EXPANSION_THRESHOLD, we directly expand the
1732
+ # for-loop and inline the SetMem operation, which is faster
1733
+ # than list_build_op, however generates more code.
1734
+ result_list = self.call_c(new_list_op, length, line)
1735
+ if not values:
1736
+ return result_list
1737
+ args = [self.coerce(item, object_rprimitive, line) for item in values]
1738
+ ob_item_ptr = self.add(GetElementPtr(result_list, PyListObject, "ob_item", line))
1739
+ ob_item_base = self.add(LoadMem(pointer_rprimitive, ob_item_ptr, line))
1740
+ for i in range(len(values)):
1741
+ if i == 0:
1742
+ item_address = ob_item_base
1743
+ else:
1744
+ offset = Integer(PLATFORM_SIZE * i, c_pyssize_t_rprimitive, line)
1745
+ item_address = self.add(
1746
+ IntOp(pointer_rprimitive, ob_item_base, offset, IntOp.ADD, line)
1747
+ )
1748
+ self.add(SetMem(object_rprimitive, item_address, args[i], line))
1749
+ self.add(KeepAlive([result_list]))
1750
+ return result_list
1751
+
1752
+ def new_set_op(self, values: list[Value], line: int) -> Value:
1753
+ return self.call_c(new_set_op, values, line)
1754
+
1755
+ def setup_rarray(
1756
+ self, item_type: RType, values: Sequence[Value], *, object_ptr: bool = False
1757
+ ) -> Value:
1758
+ """Declare and initialize a new RArray, returning its address."""
1759
+ array = Register(RArray(item_type, len(values)))
1760
+ self.add(AssignMulti(array, list(values)))
1761
+ return self.add(
1762
+ LoadAddress(object_pointer_rprimitive if object_ptr else c_pointer_rprimitive, array)
1763
+ )
1764
+
1765
+ def shortcircuit_helper(
1766
+ self,
1767
+ op: str,
1768
+ expr_type: RType,
1769
+ left: Callable[[], Value],
1770
+ right: Callable[[], Value],
1771
+ line: int,
1772
+ ) -> Value:
1773
+ # Having actual Phi nodes would be really nice here!
1774
+ target = Register(expr_type)
1775
+ # left_body takes the value of the left side, right_body the right
1776
+ left_body, right_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()
1777
+ # true_body is taken if the left is true, false_body if it is false.
1778
+ # For 'and' the value is the right side if the left is true, and for 'or'
1779
+ # it is the right side if the left is false.
1780
+ true_body, false_body = (right_body, left_body) if op == "and" else (left_body, right_body)
1781
+
1782
+ left_value = left()
1783
+ self.add_bool_branch(left_value, true_body, false_body)
1784
+
1785
+ self.activate_block(left_body)
1786
+ left_coerced = self.coerce(left_value, expr_type, line)
1787
+ self.add(Assign(target, left_coerced))
1788
+ self.goto(next_block)
1789
+
1790
+ self.activate_block(right_body)
1791
+ right_value = right()
1792
+ right_coerced = self.coerce(right_value, expr_type, line)
1793
+ self.add(Assign(target, right_coerced))
1794
+ self.goto(next_block)
1795
+
1796
+ self.activate_block(next_block)
1797
+ return target
1798
+
1799
+ def bool_value(self, value: Value) -> Value:
1800
+ """Return bool(value).
1801
+
1802
+ The result type can be bit_rprimitive or bool_rprimitive.
1803
+ """
1804
+ if is_bool_rprimitive(value.type) or is_bit_rprimitive(value.type):
1805
+ result = value
1806
+ elif is_runtime_subtype(value.type, int_rprimitive):
1807
+ zero = Integer(0, short_int_rprimitive)
1808
+ result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line)
1809
+ elif is_fixed_width_rtype(value.type):
1810
+ zero = Integer(0, value.type)
1811
+ result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ))
1812
+ elif is_same_type(value.type, str_rprimitive):
1813
+ result = self.call_c(str_check_if_true, [value], value.line)
1814
+ elif is_same_type(value.type, list_rprimitive) or is_same_type(
1815
+ value.type, dict_rprimitive
1816
+ ):
1817
+ length = self.builtin_len(value, value.line)
1818
+ zero = Integer(0)
1819
+ result = self.binary_op(length, zero, "!=", value.line)
1820
+ elif (
1821
+ isinstance(value.type, RInstance)
1822
+ and value.type.class_ir.is_ext_class
1823
+ and value.type.class_ir.has_method("__bool__")
1824
+ ):
1825
+ # Directly call the __bool__ method on classes that have it.
1826
+ result = self.gen_method_call(value, "__bool__", [], bool_rprimitive, value.line)
1827
+ elif is_float_rprimitive(value.type):
1828
+ result = self.compare_floats(value, Float(0.0), FloatComparisonOp.NEQ, value.line)
1829
+ else:
1830
+ value_type = optional_value_type(value.type)
1831
+ if value_type is not None:
1832
+ not_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
1833
+ always_truthy = False
1834
+ if isinstance(value_type, RInstance):
1835
+ # check whether X.__bool__ is always just the default (object.__bool__)
1836
+ if not value_type.class_ir.has_method(
1837
+ "__bool__"
1838
+ ) and value_type.class_ir.is_method_final("__bool__"):
1839
+ always_truthy = True
1840
+
1841
+ if always_truthy:
1842
+ result = not_none
1843
+ else:
1844
+ # "X | None" where X may be falsey and requires a check
1845
+ result = Register(bit_rprimitive)
1846
+ true, false, end = BasicBlock(), BasicBlock(), BasicBlock()
1847
+ branch = Branch(not_none, true, false, Branch.BOOL)
1848
+ self.add(branch)
1849
+ self.activate_block(true)
1850
+ # unbox_or_cast instead of coerce because we want the
1851
+ # type to change even if it is a subtype.
1852
+ remaining = self.unbox_or_cast(value, value_type, value.line)
1853
+ as_bool = self.bool_value(remaining)
1854
+ self.add(Assign(result, as_bool))
1855
+ self.goto(end)
1856
+ self.activate_block(false)
1857
+ self.add(Assign(result, Integer(0, bit_rprimitive)))
1858
+ self.goto(end)
1859
+ self.activate_block(end)
1860
+ else:
1861
+ result = self.call_c(bool_op, [value], value.line)
1862
+ return result
1863
+
1864
+ def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
1865
+ opt_value_type = optional_value_type(value.type)
1866
+ if opt_value_type is None:
1867
+ bool_value = self.bool_value(value)
1868
+ self.add(Branch(bool_value, true, false, Branch.BOOL))
1869
+ else:
1870
+ # Special-case optional types
1871
+ is_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
1872
+ branch = Branch(is_none, true, false, Branch.BOOL)
1873
+ self.add(branch)
1874
+ always_truthy = False
1875
+ if isinstance(opt_value_type, RInstance):
1876
+ # check whether X.__bool__ is always just the default (object.__bool__)
1877
+ if not opt_value_type.class_ir.has_method(
1878
+ "__bool__"
1879
+ ) and opt_value_type.class_ir.is_method_final("__bool__"):
1880
+ always_truthy = True
1881
+
1882
+ if not always_truthy:
1883
+ # Optional[X] where X may be falsey and requires a check
1884
+ branch.true = BasicBlock()
1885
+ self.activate_block(branch.true)
1886
+ # unbox_or_cast instead of coerce because we want the
1887
+ # type to change even if it is a subtype.
1888
+ remaining = self.unbox_or_cast(value, opt_value_type, value.line)
1889
+ self.add_bool_branch(remaining, true, false)
1890
+
1891
+ def call_c(
1892
+ self,
1893
+ desc: CFunctionDescription,
1894
+ args: list[Value],
1895
+ line: int,
1896
+ result_type: RType | None = None,
1897
+ ) -> Value:
1898
+ """Call function using C/native calling convention (not a Python callable)."""
1899
+ # Handle void function via singleton RVoid instance
1900
+ coerced = []
1901
+ # Coerce fixed number arguments
1902
+ for i in range(min(len(args), len(desc.arg_types))):
1903
+ formal_type = desc.arg_types[i]
1904
+ arg = args[i]
1905
+ arg = self.coerce(arg, formal_type, line)
1906
+ coerced.append(arg)
1907
+ # Reorder args if necessary
1908
+ if desc.ordering is not None:
1909
+ assert desc.var_arg_type is None
1910
+ coerced = [coerced[i] for i in desc.ordering]
1911
+ # Coerce any var_arg
1912
+ var_arg_idx = -1
1913
+ if desc.var_arg_type is not None:
1914
+ var_arg_idx = len(desc.arg_types)
1915
+ for i in range(len(desc.arg_types), len(args)):
1916
+ arg = args[i]
1917
+ arg = self.coerce(arg, desc.var_arg_type, line)
1918
+ coerced.append(arg)
1919
+ # Add extra integer constant if any
1920
+ for item in desc.extra_int_constants:
1921
+ val, typ = item
1922
+ extra_int_constant = Integer(val, typ, line)
1923
+ coerced.append(extra_int_constant)
1924
+ error_kind = desc.error_kind
1925
+ if error_kind == ERR_NEG_INT:
1926
+ # Handled with an explicit comparison
1927
+ error_kind = ERR_NEVER
1928
+ target = self.add(
1929
+ CallC(
1930
+ desc.c_function_name,
1931
+ coerced,
1932
+ desc.return_type,
1933
+ desc.steals,
1934
+ desc.is_borrowed,
1935
+ error_kind,
1936
+ line,
1937
+ var_arg_idx,
1938
+ )
1939
+ )
1940
+ if desc.is_borrowed:
1941
+ # If the result is borrowed, force the arguments to be
1942
+ # kept alive afterwards, as otherwise the result might be
1943
+ # immediately freed, at the risk of a dangling pointer.
1944
+ for arg in coerced:
1945
+ if not isinstance(arg, (Integer, LoadLiteral)):
1946
+ self.keep_alives.append(arg)
1947
+ if desc.error_kind == ERR_NEG_INT:
1948
+ comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)
1949
+ comp.error_kind = ERR_FALSE
1950
+ self.add(comp)
1951
+
1952
+ if desc.truncated_type is None:
1953
+ result = target
1954
+ else:
1955
+ truncate = self.add(Truncate(target, desc.truncated_type))
1956
+ result = truncate
1957
+ if result_type and not is_runtime_subtype(result.type, result_type):
1958
+ if is_none_rprimitive(result_type):
1959
+ # Special case None return. The actual result may actually be a bool
1960
+ # and so we can't just coerce it.
1961
+ result = self.none()
1962
+ else:
1963
+ result = self.coerce(target, result_type, line, can_borrow=desc.is_borrowed)
1964
+ return result
1965
+
1966
+ def matching_call_c(
1967
+ self,
1968
+ candidates: list[CFunctionDescription],
1969
+ args: list[Value],
1970
+ line: int,
1971
+ result_type: RType | None = None,
1972
+ can_borrow: bool = False,
1973
+ ) -> Value | None:
1974
+ matching: CFunctionDescription | None = None
1975
+ for desc in candidates:
1976
+ if len(desc.arg_types) != len(args):
1977
+ continue
1978
+ if all(
1979
+ is_subtype(actual.type, formal) for actual, formal in zip(args, desc.arg_types)
1980
+ ) and (not desc.is_borrowed or can_borrow):
1981
+ if matching:
1982
+ assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format(
1983
+ matching, desc
1984
+ )
1985
+ if desc.priority > matching.priority:
1986
+ matching = desc
1987
+ else:
1988
+ matching = desc
1989
+ if matching:
1990
+ target = self.call_c(matching, args, line, result_type)
1991
+ return target
1992
+ return None
1993
+
1994
+ def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value:
1995
+ """Generate a native integer binary op.
1996
+
1997
+ Use native/C semantics, which sometimes differ from Python
1998
+ semantics.
1999
+
2000
+ Args:
2001
+ type: Either int64_rprimitive or int32_rprimitive
2002
+ op: IntOp.* constant (e.g. IntOp.ADD)
2003
+ """
2004
+ return self.add(IntOp(type, lhs, rhs, op, line))
2005
+
2006
+ def float_op(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
2007
+ """Generate a native float binary arithmetic operation.
2008
+
2009
+ This follows Python semantics (e.g. raise exception on division by zero).
2010
+ Add a FloatOp directly if you want low-level semantics.
2011
+
2012
+ Args:
2013
+ op: Binary operator (e.g. '+' or '*')
2014
+ """
2015
+ op_id = float_op_to_id[op]
2016
+ if op_id in (FloatOp.DIV, FloatOp.MOD):
2017
+ if not (isinstance(rhs, Float) and rhs.value != 0.0):
2018
+ c = self.compare_floats(rhs, Float(0.0), FloatComparisonOp.EQ, line)
2019
+ err, ok = BasicBlock(), BasicBlock()
2020
+ self.add(Branch(c, err, ok, Branch.BOOL, rare=True))
2021
+ self.activate_block(err)
2022
+ if op_id == FloatOp.DIV:
2023
+ msg = "float division by zero"
2024
+ else:
2025
+ msg = "float modulo"
2026
+ self.add(RaiseStandardError(RaiseStandardError.ZERO_DIVISION_ERROR, msg, line))
2027
+ self.add(Unreachable())
2028
+ self.activate_block(ok)
2029
+ if op_id == FloatOp.MOD:
2030
+ # Adjust the result to match Python semantics (FloatOp follows C semantics).
2031
+ return self.float_mod(lhs, rhs, line)
2032
+ else:
2033
+ return self.add(FloatOp(lhs, rhs, op_id, line))
2034
+
2035
+ def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value:
2036
+ """Perform x % y on floats using Python semantics."""
2037
+ mod = self.add(FloatOp(lhs, rhs, FloatOp.MOD, line))
2038
+ res = Register(float_rprimitive)
2039
+ self.add(Assign(res, mod))
2040
+ tricky, adjust, copysign, done = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
2041
+ is_zero = self.add(FloatComparisonOp(res, Float(0.0), FloatComparisonOp.EQ, line))
2042
+ self.add(Branch(is_zero, copysign, tricky, Branch.BOOL))
2043
+ self.activate_block(tricky)
2044
+ same_signs = self.is_same_float_signs(lhs, rhs, line)
2045
+ self.add(Branch(same_signs, done, adjust, Branch.BOOL))
2046
+ self.activate_block(adjust)
2047
+ adj = self.float_op(res, rhs, "+", line)
2048
+ self.add(Assign(res, adj))
2049
+ self.add(Goto(done))
2050
+ self.activate_block(copysign)
2051
+ # If the remainder is zero, CPython ensures the result has the
2052
+ # same sign as the denominator.
2053
+ adj = self.call_c(copysign_op, [Float(0.0), rhs], line)
2054
+ self.add(Assign(res, adj))
2055
+ self.add(Goto(done))
2056
+ self.activate_block(done)
2057
+ return res
2058
+
2059
+ def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
2060
+ return self.add(FloatComparisonOp(lhs, rhs, op, line))
2061
+
2062
+ def fixed_width_int_op(
2063
+ self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int
2064
+ ) -> Value:
2065
+ """Generate a binary op using Python fixed-width integer semantics.
2066
+
2067
+ These may differ in overflow/rounding behavior from native/C ops.
2068
+
2069
+ Args:
2070
+ type: Either int64_rprimitive or int32_rprimitive
2071
+ op: IntOp.* constant (e.g. IntOp.ADD)
2072
+ """
2073
+ lhs = self.coerce(lhs, type, line)
2074
+ rhs = self.coerce(rhs, type, line)
2075
+ if op == IntOp.DIV:
2076
+ if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
2077
+ if not type.is_signed:
2078
+ return self.int_op(type, lhs, rhs, IntOp.DIV, line)
2079
+ else:
2080
+ # Inline simple division by a constant, so that C
2081
+ # compilers can optimize more
2082
+ return self.inline_fixed_width_divide(type, lhs, rhs, line)
2083
+ if is_int64_rprimitive(type):
2084
+ prim = int64_divide_op
2085
+ elif is_int32_rprimitive(type):
2086
+ prim = int32_divide_op
2087
+ elif is_int16_rprimitive(type):
2088
+ prim = int16_divide_op
2089
+ elif is_uint8_rprimitive(type):
2090
+ self.check_for_zero_division(rhs, type, line)
2091
+ return self.int_op(type, lhs, rhs, op, line)
2092
+ else:
2093
+ assert False, type
2094
+ return self.call_c(prim, [lhs, rhs], line)
2095
+ if op == IntOp.MOD:
2096
+ if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
2097
+ if not type.is_signed:
2098
+ return self.int_op(type, lhs, rhs, IntOp.MOD, line)
2099
+ else:
2100
+ # Inline simple % by a constant, so that C
2101
+ # compilers can optimize more
2102
+ return self.inline_fixed_width_mod(type, lhs, rhs, line)
2103
+ if is_int64_rprimitive(type):
2104
+ prim = int64_mod_op
2105
+ elif is_int32_rprimitive(type):
2106
+ prim = int32_mod_op
2107
+ elif is_int16_rprimitive(type):
2108
+ prim = int16_mod_op
2109
+ elif is_uint8_rprimitive(type):
2110
+ self.check_for_zero_division(rhs, type, line)
2111
+ return self.int_op(type, lhs, rhs, op, line)
2112
+ else:
2113
+ assert False, type
2114
+ return self.call_c(prim, [lhs, rhs], line)
2115
+ return self.int_op(type, lhs, rhs, op, line)
2116
+
2117
+ def check_for_zero_division(self, rhs: Value, type: RType, line: int) -> None:
2118
+ err, ok = BasicBlock(), BasicBlock()
2119
+ is_zero = self.binary_op(rhs, Integer(0, type), "==", line)
2120
+ self.add(Branch(is_zero, err, ok, Branch.BOOL))
2121
+ self.activate_block(err)
2122
+ self.add(
2123
+ RaiseStandardError(
2124
+ RaiseStandardError.ZERO_DIVISION_ERROR, "integer division or modulo by zero", line
2125
+ )
2126
+ )
2127
+ self.add(Unreachable())
2128
+ self.activate_block(ok)
2129
+
2130
+ def inline_fixed_width_divide(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
2131
+ # Perform floor division (native division truncates)
2132
+ res = Register(type)
2133
+ div = self.int_op(type, lhs, rhs, IntOp.DIV, line)
2134
+ self.add(Assign(res, div))
2135
+ same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
2136
+ tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
2137
+ self.add(Branch(same_signs, done, tricky, Branch.BOOL))
2138
+ self.activate_block(tricky)
2139
+ mul = self.int_op(type, res, rhs, IntOp.MUL, line)
2140
+ mul_eq = self.add(ComparisonOp(mul, lhs, ComparisonOp.EQ, line))
2141
+ self.add(Branch(mul_eq, done, adjust, Branch.BOOL))
2142
+ self.activate_block(adjust)
2143
+ adj = self.int_op(type, res, Integer(1, type), IntOp.SUB, line)
2144
+ self.add(Assign(res, adj))
2145
+ self.add(Goto(done))
2146
+ self.activate_block(done)
2147
+ return res
2148
+
2149
+ def inline_fixed_width_mod(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
2150
+ # Perform floor modulus
2151
+ res = Register(type)
2152
+ mod = self.int_op(type, lhs, rhs, IntOp.MOD, line)
2153
+ self.add(Assign(res, mod))
2154
+ same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
2155
+ tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
2156
+ self.add(Branch(same_signs, done, tricky, Branch.BOOL))
2157
+ self.activate_block(tricky)
2158
+ is_zero = self.add(ComparisonOp(res, Integer(0, type), ComparisonOp.EQ, line))
2159
+ self.add(Branch(is_zero, done, adjust, Branch.BOOL))
2160
+ self.activate_block(adjust)
2161
+ adj = self.int_op(type, res, rhs, IntOp.ADD, line)
2162
+ self.add(Assign(res, adj))
2163
+ self.add(Goto(done))
2164
+ self.activate_block(done)
2165
+ return res
2166
+
2167
+ def is_same_native_int_signs(self, type: RType, a: Value, b: Value, line: int) -> Value:
2168
+ neg1 = self.add(ComparisonOp(a, Integer(0, type), ComparisonOp.SLT, line))
2169
+ neg2 = self.add(ComparisonOp(b, Integer(0, type), ComparisonOp.SLT, line))
2170
+ return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
2171
+
2172
+ def is_same_float_signs(self, a: Value, b: Value, line: int) -> Value:
2173
+ neg1 = self.add(FloatComparisonOp(a, Float(0.0), FloatComparisonOp.LT, line))
2174
+ neg2 = self.add(FloatComparisonOp(b, Float(0.0), FloatComparisonOp.LT, line))
2175
+ return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
2176
+
2177
+ def comparison_op(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
2178
+ return self.add(ComparisonOp(lhs, rhs, op, line))
2179
+
2180
+ def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:
2181
+ """Generate len(val).
2182
+
2183
+ Return short_int_rprimitive by default.
2184
+ Return c_pyssize_t if use_pyssize_t is true (unshifted).
2185
+ """
2186
+ typ = val.type
2187
+ size_value = None
2188
+ if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ):
2189
+ elem_address = self.add(GetElementPtr(val, PyVarObject, "ob_size"))
2190
+ size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address))
2191
+ self.add(KeepAlive([val]))
2192
+ elif is_set_rprimitive(typ):
2193
+ elem_address = self.add(GetElementPtr(val, PySetObject, "used"))
2194
+ size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address))
2195
+ self.add(KeepAlive([val]))
2196
+ elif is_dict_rprimitive(typ):
2197
+ size_value = self.call_c(dict_ssize_t_size_op, [val], line)
2198
+ elif is_str_rprimitive(typ):
2199
+ size_value = self.call_c(str_ssize_t_size_op, [val], line)
2200
+
2201
+ if size_value is not None:
2202
+ if use_pyssize_t:
2203
+ return size_value
2204
+ offset = Integer(1, c_pyssize_t_rprimitive, line)
2205
+ return self.int_op(short_int_rprimitive, size_value, offset, IntOp.LEFT_SHIFT, line)
2206
+
2207
+ if isinstance(typ, RInstance):
2208
+ # TODO: Support use_pyssize_t
2209
+ assert not use_pyssize_t
2210
+ length = self.gen_method_call(val, "__len__", [], int_rprimitive, line)
2211
+ length = self.coerce(length, int_rprimitive, line)
2212
+ ok, fail = BasicBlock(), BasicBlock()
2213
+ self.compare_tagged_condition(length, Integer(0), ">=", ok, fail, line)
2214
+ self.activate_block(fail)
2215
+ self.add(
2216
+ RaiseStandardError(
2217
+ RaiseStandardError.VALUE_ERROR, "__len__() should return >= 0", line
2218
+ )
2219
+ )
2220
+ self.add(Unreachable())
2221
+ self.activate_block(ok)
2222
+ return length
2223
+
2224
+ # generic case
2225
+ if use_pyssize_t:
2226
+ return self.call_c(generic_ssize_t_len_op, [val], line)
2227
+ else:
2228
+ return self.call_c(generic_len_op, [val], line)
2229
+
2230
+ def new_tuple(self, items: list[Value], line: int) -> Value:
2231
+ size: Value = Integer(len(items), c_pyssize_t_rprimitive)
2232
+ return self.call_c(new_tuple_op, [size] + items, line)
2233
+
2234
+ def new_tuple_with_length(self, length: Value, line: int) -> Value:
2235
+ """This function returns an uninitialized tuple.
2236
+
2237
+ If the length is non-zero, the caller must initialize the tuple, before
2238
+ it can be made visible to user code -- otherwise the tuple object is broken.
2239
+ You might need further initialization with `new_tuple_set_item_op` op.
2240
+
2241
+ Args:
2242
+ length: desired length of the new tuple. The rtype should be
2243
+ c_pyssize_t_rprimitive
2244
+ line: line number
2245
+ """
2246
+ return self.call_c(new_tuple_with_length_op, [length], line)
2247
+
2248
+ def int_to_float(self, n: Value, line: int) -> Value:
2249
+ return self.call_c(int_to_float_op, [n], line)
2250
+
2251
+ # Internal helpers
2252
+
2253
+ def decompose_union_helper(
2254
+ self,
2255
+ obj: Value,
2256
+ rtype: RUnion,
2257
+ result_type: RType,
2258
+ process_item: Callable[[Value], Value],
2259
+ line: int,
2260
+ ) -> Value:
2261
+ """Generate isinstance() + specialized operations for union items.
2262
+
2263
+ Say, for Union[A, B] generate ops resembling this (pseudocode):
2264
+
2265
+ if isinstance(obj, A):
2266
+ result = <result of process_item(cast(A, obj)>
2267
+ else:
2268
+ result = <result of process_item(cast(B, obj)>
2269
+
2270
+ Args:
2271
+ obj: value with a union type
2272
+ rtype: the union type
2273
+ result_type: result of the operation
2274
+ process_item: callback to generate op for a single union item (arg is coerced
2275
+ to union item type)
2276
+ line: line number
2277
+ """
2278
+ # TODO: Optimize cases where a single operation can handle multiple union items
2279
+ # (say a method is implemented in a common base class)
2280
+ fast_items = []
2281
+ rest_items = []
2282
+ for item in rtype.items:
2283
+ if isinstance(item, RInstance):
2284
+ fast_items.append(item)
2285
+ else:
2286
+ # For everything but RInstance we fall back to C API
2287
+ rest_items.append(item)
2288
+ exit_block = BasicBlock()
2289
+ result = Register(result_type)
2290
+ for i, item in enumerate(fast_items):
2291
+ more_types = i < len(fast_items) - 1 or rest_items
2292
+ if more_types:
2293
+ # We are not at the final item so we need one more branch
2294
+ op = self.isinstance_native(obj, item.class_ir, line)
2295
+ true_block, false_block = BasicBlock(), BasicBlock()
2296
+ self.add_bool_branch(op, true_block, false_block)
2297
+ self.activate_block(true_block)
2298
+ coerced = self.coerce(obj, item, line)
2299
+ temp = process_item(coerced)
2300
+ temp2 = self.coerce(temp, result_type, line)
2301
+ self.add(Assign(result, temp2))
2302
+ self.goto(exit_block)
2303
+ if more_types:
2304
+ self.activate_block(false_block)
2305
+ if rest_items:
2306
+ # For everything else we use generic operation. Use force=True to drop the
2307
+ # union type.
2308
+ coerced = self.coerce(obj, object_rprimitive, line, force=True)
2309
+ temp = process_item(coerced)
2310
+ temp2 = self.coerce(temp, result_type, line)
2311
+ self.add(Assign(result, temp2))
2312
+ self.goto(exit_block)
2313
+ self.activate_block(exit_block)
2314
+ return result
2315
+
2316
+ def translate_special_method_call(
2317
+ self,
2318
+ base_reg: Value,
2319
+ name: str,
2320
+ args: list[Value],
2321
+ result_type: RType | None,
2322
+ line: int,
2323
+ can_borrow: bool = False,
2324
+ ) -> Value | None:
2325
+ """Translate a method call which is handled nongenerically.
2326
+
2327
+ These are special in the sense that we have code generated specifically for them.
2328
+ They tend to be method calls which have equivalents in C that are more direct
2329
+ than calling with the PyObject api.
2330
+
2331
+ Return None if no translation found; otherwise return the target register.
2332
+ """
2333
+ call_c_ops_candidates = method_call_ops.get(name, [])
2334
+ call_c_op = self.matching_call_c(
2335
+ call_c_ops_candidates, [base_reg] + args, line, result_type, can_borrow=can_borrow
2336
+ )
2337
+ return call_c_op
2338
+
2339
+ def translate_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None:
2340
+ """Add a equality comparison operation.
2341
+
2342
+ Args:
2343
+ expr_op: either '==' or '!='
2344
+ """
2345
+ ltype = lreg.type
2346
+ rtype = rreg.type
2347
+ if not (isinstance(ltype, RInstance) and ltype == rtype):
2348
+ return None
2349
+
2350
+ class_ir = ltype.class_ir
2351
+ # Check whether any subclasses of the operand redefines __eq__
2352
+ # or it might be redefined in a Python parent class or by
2353
+ # dataclasses
2354
+ cmp_varies_at_runtime = (
2355
+ not class_ir.is_method_final("__eq__")
2356
+ or not class_ir.is_method_final("__ne__")
2357
+ or class_ir.inherits_python
2358
+ or class_ir.is_augmented
2359
+ )
2360
+
2361
+ if cmp_varies_at_runtime:
2362
+ # We might need to call left.__eq__(right) or right.__eq__(left)
2363
+ # depending on which is the more specific type.
2364
+ return None
2365
+
2366
+ if not class_ir.has_method("__eq__"):
2367
+ # There's no __eq__ defined, so just use object identity.
2368
+ identity_ref_op = "is" if expr_op == "==" else "is not"
2369
+ return self.translate_is_op(lreg, rreg, identity_ref_op, line)
2370
+
2371
+ return self.gen_method_call(lreg, op_methods[expr_op], [rreg], ltype, line)
2372
+
2373
+ def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
2374
+ """Create equality comparison operation between object identities
2375
+
2376
+ Args:
2377
+ expr_op: either 'is' or 'is not'
2378
+ """
2379
+ op = ComparisonOp.EQ if expr_op == "is" else ComparisonOp.NEQ
2380
+ lhs = self.coerce(lreg, object_rprimitive, line)
2381
+ rhs = self.coerce(rreg, object_rprimitive, line)
2382
+ return self.add(ComparisonOp(lhs, rhs, op, line))
2383
+
2384
+ def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Value:
2385
+ """Create a dictionary(possibly empty) using keys and values"""
2386
+ # keys and values should have the same number of items
2387
+ size = len(keys)
2388
+ if size > 0:
2389
+ size_value: Value = Integer(size, c_pyssize_t_rprimitive)
2390
+ # merge keys and values
2391
+ items = [i for t in list(zip(keys, values)) for i in t]
2392
+ return self.call_c(dict_build_op, [size_value] + items, line)
2393
+ else:
2394
+ return self.call_c(dict_new_op, [], line)
2395
+
2396
+ def error(self, msg: str, line: int) -> None:
2397
+ self.errors.error(msg, self.module_path, line)
2398
+
2399
+
2400
+ def num_positional_args(arg_values: list[Value], arg_kinds: list[ArgKind] | None) -> int:
2401
+ if arg_kinds is None:
2402
+ return len(arg_values)
2403
+ num_pos = 0
2404
+ for kind in arg_kinds:
2405
+ if kind == ARG_POS:
2406
+ num_pos += 1
2407
+ return num_pos