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
mypy/types.py ADDED
@@ -0,0 +1,3686 @@
1
+ """Classes for representing mypy types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from abc import abstractmethod
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ ClassVar,
11
+ Dict,
12
+ Final,
13
+ Iterable,
14
+ NamedTuple,
15
+ NewType,
16
+ Sequence,
17
+ TypeVar,
18
+ Union,
19
+ cast,
20
+ )
21
+ from typing_extensions import Self, TypeAlias as _TypeAlias, TypeGuard, overload
22
+
23
+ import mypy.nodes
24
+ from mypy.bogus_type import Bogus
25
+ from mypy.nodes import (
26
+ ARG_POS,
27
+ ARG_STAR,
28
+ ARG_STAR2,
29
+ INVARIANT,
30
+ ArgKind,
31
+ FakeInfo,
32
+ FuncDef,
33
+ SymbolNode,
34
+ )
35
+ from mypy.options import Options
36
+ from mypy.state import state
37
+ from mypy.util import IdMapper
38
+
39
+ T = TypeVar("T")
40
+
41
+ JsonDict: _TypeAlias = Dict[str, Any]
42
+
43
+ # The set of all valid expressions that can currently be contained
44
+ # inside of a Literal[...].
45
+ #
46
+ # Literals can contain bytes and enum-values: we special-case both of these
47
+ # and store the value as a string. We rely on the fallback type that's also
48
+ # stored with the Literal to determine how a string is being used.
49
+ #
50
+ # TODO: confirm that we're happy with representing enums (and the
51
+ # other types) in the manner described above.
52
+ #
53
+ # Note: if we change the set of types included below, we must also
54
+ # make sure to audit the following methods:
55
+ #
56
+ # 1. types.LiteralType's serialize and deserialize methods: this method
57
+ # needs to make sure it can convert the below types into JSON and back.
58
+ #
59
+ # 2. types.LiteralType's 'value_repr` method: this method is ultimately used
60
+ # by TypeStrVisitor's visit_literal_type to generate a reasonable
61
+ # repr-able output.
62
+ #
63
+ # 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this
64
+ # method assumes that the following types supports equality checks and
65
+ # hashability.
66
+ #
67
+ # Note: Although "Literal[None]" is a valid type, we internally always convert
68
+ # such a type directly into "None". So, "None" is not a valid parameter of
69
+ # LiteralType and is omitted from this list.
70
+ #
71
+ # Note: Float values are only used internally. They are not accepted within
72
+ # Literal[...].
73
+ LiteralValue: _TypeAlias = Union[int, str, bool, float]
74
+
75
+
76
+ # If we only import type_visitor in the middle of the file, mypy
77
+ # breaks, and if we do it at the top, it breaks at runtime because of
78
+ # import cycle issues, so we do it at the top while typechecking and
79
+ # then again in the middle at runtime.
80
+ # We should be able to remove this once we are switched to the new
81
+ # semantic analyzer!
82
+ if TYPE_CHECKING:
83
+ from mypy.type_visitor import (
84
+ SyntheticTypeVisitor as SyntheticTypeVisitor,
85
+ TypeVisitor as TypeVisitor,
86
+ )
87
+
88
+ TYPED_NAMEDTUPLE_NAMES: Final = ("typing.NamedTuple", "typing_extensions.NamedTuple")
89
+
90
+ # Supported names of TypedDict type constructors.
91
+ TPDICT_NAMES: Final = (
92
+ "typing.TypedDict",
93
+ "typing_extensions.TypedDict",
94
+ "mypy_extensions.TypedDict",
95
+ )
96
+
97
+ # Supported fallback instance type names for TypedDict types.
98
+ TPDICT_FB_NAMES: Final = (
99
+ "typing._TypedDict",
100
+ "typing_extensions._TypedDict",
101
+ "mypy_extensions._TypedDict",
102
+ )
103
+
104
+ # Supported names of Protocol base class.
105
+ PROTOCOL_NAMES: Final = ("typing.Protocol", "typing_extensions.Protocol")
106
+
107
+ # Supported TypeAlias names.
108
+ TYPE_ALIAS_NAMES: Final = ("typing.TypeAlias", "typing_extensions.TypeAlias")
109
+
110
+ # Supported Final type names.
111
+ FINAL_TYPE_NAMES: Final = ("typing.Final", "typing_extensions.Final")
112
+
113
+ # Supported @final decorator names.
114
+ FINAL_DECORATOR_NAMES: Final = ("typing.final", "typing_extensions.final")
115
+
116
+ # Supported @type_check_only names.
117
+ TYPE_CHECK_ONLY_NAMES: Final = ("typing.type_check_only", "typing_extensions.type_check_only")
118
+
119
+ # Supported Literal type names.
120
+ LITERAL_TYPE_NAMES: Final = ("typing.Literal", "typing_extensions.Literal")
121
+
122
+ # Supported Annotated type names.
123
+ ANNOTATED_TYPE_NAMES: Final = ("typing.Annotated", "typing_extensions.Annotated")
124
+
125
+ # Supported @deprecated type names
126
+ DEPRECATED_TYPE_NAMES: Final = ("warnings.deprecated", "typing_extensions.deprecated")
127
+
128
+ # We use this constant in various places when checking `tuple` subtyping:
129
+ TUPLE_LIKE_INSTANCE_NAMES: Final = (
130
+ "builtins.tuple",
131
+ "typing.Iterable",
132
+ "typing.Container",
133
+ "typing.Sequence",
134
+ "typing.Reversible",
135
+ )
136
+
137
+ IMPORTED_REVEAL_TYPE_NAMES: Final = ("typing.reveal_type", "typing_extensions.reveal_type")
138
+ REVEAL_TYPE_NAMES: Final = ("builtins.reveal_type", *IMPORTED_REVEAL_TYPE_NAMES)
139
+
140
+ ASSERT_TYPE_NAMES: Final = ("typing.assert_type", "typing_extensions.assert_type")
141
+
142
+ OVERLOAD_NAMES: Final = ("typing.overload", "typing_extensions.overload")
143
+
144
+ # Attributes that can optionally be defined in the body of a subclass of
145
+ # enum.Enum but are removed from the class __dict__ by EnumMeta.
146
+ ENUM_REMOVED_PROPS: Final = ("_ignore_", "_order_", "__order__")
147
+
148
+ NEVER_NAMES: Final = (
149
+ "typing.NoReturn",
150
+ "typing_extensions.NoReturn",
151
+ "mypy_extensions.NoReturn",
152
+ "typing.Never",
153
+ "typing_extensions.Never",
154
+ )
155
+
156
+ # Mypyc fixed-width native int types (compatible with builtins.int)
157
+ MYPYC_NATIVE_INT_NAMES: Final = (
158
+ "mypy_extensions.i64",
159
+ "mypy_extensions.i32",
160
+ "mypy_extensions.i16",
161
+ "mypy_extensions.u8",
162
+ )
163
+
164
+ DATACLASS_TRANSFORM_NAMES: Final = (
165
+ "typing.dataclass_transform",
166
+ "typing_extensions.dataclass_transform",
167
+ )
168
+ # Supported @override decorator names.
169
+ OVERRIDE_DECORATOR_NAMES: Final = ("typing.override", "typing_extensions.override")
170
+
171
+ # A placeholder used for Bogus[...] parameters
172
+ _dummy: Final[Any] = object()
173
+
174
+ # A placeholder for int parameters
175
+ _dummy_int: Final = -999999
176
+
177
+
178
+ class TypeOfAny:
179
+ """
180
+ This class describes different types of Any. Each 'Any' can be of only one type at a time.
181
+ """
182
+
183
+ __slots__ = ()
184
+
185
+ # Was this Any type inferred without a type annotation?
186
+ unannotated: Final = 1
187
+ # Does this Any come from an explicit type annotation?
188
+ explicit: Final = 2
189
+ # Does this come from an unfollowed import? See --disallow-any-unimported option
190
+ from_unimported_type: Final = 3
191
+ # Does this Any type come from omitted generics?
192
+ from_omitted_generics: Final = 4
193
+ # Does this Any come from an error?
194
+ from_error: Final = 5
195
+ # Is this a type that can't be represented in mypy's type system? For instance, type of
196
+ # call to NewType(...). Even though these types aren't real Anys, we treat them as such.
197
+ # Also used for variables named '_'.
198
+ special_form: Final = 6
199
+ # Does this Any come from interaction with another Any?
200
+ from_another_any: Final = 7
201
+ # Does this Any come from an implementation limitation/bug?
202
+ implementation_artifact: Final = 8
203
+ # Does this Any come from use in the suggestion engine? This is
204
+ # used to ignore Anys inserted by the suggestion engine when
205
+ # generating constraints.
206
+ suggestion_engine: Final = 9
207
+
208
+
209
+ def deserialize_type(data: JsonDict | str) -> Type:
210
+ if isinstance(data, str):
211
+ return Instance.deserialize(data)
212
+ classname = data[".class"]
213
+ method = deserialize_map.get(classname)
214
+ if method is not None:
215
+ return method(data)
216
+ raise NotImplementedError(f"unexpected .class {classname}")
217
+
218
+
219
+ class Type(mypy.nodes.Context):
220
+ """Abstract base class for all types."""
221
+
222
+ __slots__ = ("_can_be_true", "_can_be_false")
223
+ # 'can_be_true' and 'can_be_false' mean whether the value of the
224
+ # expression can be true or false in a boolean context. They are useful
225
+ # when inferring the type of logic expressions like `x and y`.
226
+ #
227
+ # For example:
228
+ # * the literal `False` can't be true while `True` can.
229
+ # * a value with type `bool` can be true or false.
230
+ # * `None` can't be true
231
+ # * ...
232
+
233
+ def __init__(self, line: int = -1, column: int = -1) -> None:
234
+ super().__init__(line, column)
235
+ # Value of these can be -1 (use the default, lazy init), 0 (false) or 1 (true)
236
+ self._can_be_true = -1
237
+ self._can_be_false = -1
238
+
239
+ @property
240
+ def can_be_true(self) -> bool:
241
+ if self._can_be_true == -1: # Lazy init helps mypyc
242
+ self._can_be_true = self.can_be_true_default()
243
+ return bool(self._can_be_true)
244
+
245
+ @can_be_true.setter
246
+ def can_be_true(self, v: bool) -> None:
247
+ self._can_be_true = v
248
+
249
+ @property
250
+ def can_be_false(self) -> bool:
251
+ if self._can_be_false == -1: # Lazy init helps mypyc
252
+ self._can_be_false = self.can_be_false_default()
253
+ return bool(self._can_be_false)
254
+
255
+ @can_be_false.setter
256
+ def can_be_false(self, v: bool) -> None:
257
+ self._can_be_false = v
258
+
259
+ def can_be_true_default(self) -> bool:
260
+ return True
261
+
262
+ def can_be_false_default(self) -> bool:
263
+ return True
264
+
265
+ def accept(self, visitor: TypeVisitor[T]) -> T:
266
+ raise RuntimeError("Not implemented", type(self))
267
+
268
+ def __repr__(self) -> str:
269
+ return self.accept(TypeStrVisitor(options=Options()))
270
+
271
+ def str_with_options(self, options: Options) -> str:
272
+ return self.accept(TypeStrVisitor(options=options))
273
+
274
+ def serialize(self) -> JsonDict | str:
275
+ raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
276
+
277
+ @classmethod
278
+ def deserialize(cls, data: JsonDict) -> Type:
279
+ raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance")
280
+
281
+ def is_singleton_type(self) -> bool:
282
+ return False
283
+
284
+
285
+ class TypeAliasType(Type):
286
+ """A type alias to another type.
287
+
288
+ To support recursive type aliases we don't immediately expand a type alias
289
+ during semantic analysis, but create an instance of this type that records the target alias
290
+ definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases).
291
+
292
+ This is very similar to how TypeInfo vs Instance interact, where a recursive class-based
293
+ structure like
294
+ class Node:
295
+ value: int
296
+ children: List[Node]
297
+ can be represented in a tree-like manner.
298
+ """
299
+
300
+ __slots__ = ("alias", "args", "type_ref")
301
+
302
+ def __init__(
303
+ self,
304
+ alias: mypy.nodes.TypeAlias | None,
305
+ args: list[Type],
306
+ line: int = -1,
307
+ column: int = -1,
308
+ ) -> None:
309
+ super().__init__(line, column)
310
+ self.alias = alias
311
+ self.args = args
312
+ self.type_ref: str | None = None
313
+
314
+ def _expand_once(self) -> Type:
315
+ """Expand to the target type exactly once.
316
+
317
+ This doesn't do full expansion, i.e. the result can contain another
318
+ (or even this same) type alias. Use this internal helper only when really needed,
319
+ its public wrapper mypy.types.get_proper_type() is preferred.
320
+ """
321
+ assert self.alias is not None
322
+ if self.alias.no_args:
323
+ # We know that no_args=True aliases like L = List must have an instance
324
+ # as their target.
325
+ assert isinstance(self.alias.target, Instance) # type: ignore[misc]
326
+ return self.alias.target.copy_modified(args=self.args)
327
+
328
+ # TODO: this logic duplicates the one in expand_type_by_instance().
329
+ if self.alias.tvar_tuple_index is None:
330
+ mapping = {v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args)}
331
+ else:
332
+ prefix = self.alias.tvar_tuple_index
333
+ suffix = len(self.alias.alias_tvars) - self.alias.tvar_tuple_index - 1
334
+ start, middle, end = split_with_prefix_and_suffix(tuple(self.args), prefix, suffix)
335
+ tvar = self.alias.alias_tvars[prefix]
336
+ assert isinstance(tvar, TypeVarTupleType)
337
+ mapping = {tvar.id: TupleType(list(middle), tvar.tuple_fallback)}
338
+ for tvar, sub in zip(
339
+ self.alias.alias_tvars[:prefix] + self.alias.alias_tvars[prefix + 1 :], start + end
340
+ ):
341
+ mapping[tvar.id] = sub
342
+
343
+ new_tp = self.alias.target.accept(InstantiateAliasVisitor(mapping))
344
+ new_tp.accept(LocationSetter(self.line, self.column))
345
+ new_tp.line = self.line
346
+ new_tp.column = self.column
347
+ return new_tp
348
+
349
+ def _partial_expansion(self, nothing_args: bool = False) -> tuple[ProperType, bool]:
350
+ # Private method mostly for debugging and testing.
351
+ unroller = UnrollAliasVisitor(set())
352
+ if nothing_args:
353
+ alias = self.copy_modified(args=[UninhabitedType()] * len(self.args))
354
+ else:
355
+ alias = self
356
+ unrolled = alias.accept(unroller)
357
+ assert isinstance(unrolled, ProperType)
358
+ return unrolled, unroller.recursed
359
+
360
+ def expand_all_if_possible(self, nothing_args: bool = False) -> ProperType | None:
361
+ """Attempt a full expansion of the type alias (including nested aliases).
362
+
363
+ If the expansion is not possible, i.e. the alias is (mutually-)recursive,
364
+ return None. If nothing_args is True, replace all type arguments with an
365
+ UninhabitedType() (used to detect recursively defined aliases).
366
+ """
367
+ unrolled, recursed = self._partial_expansion(nothing_args=nothing_args)
368
+ if recursed:
369
+ return None
370
+ return unrolled
371
+
372
+ @property
373
+ def is_recursive(self) -> bool:
374
+ """Whether this type alias is recursive.
375
+
376
+ Note this doesn't check generic alias arguments, but only if this alias
377
+ *definition* is recursive. The property value thus can be cached on the
378
+ underlying TypeAlias node. If you want to include all nested types, use
379
+ has_recursive_types() function.
380
+ """
381
+ assert self.alias is not None, "Unfixed type alias"
382
+ is_recursive = self.alias._is_recursive
383
+ if is_recursive is None:
384
+ is_recursive = self.expand_all_if_possible(nothing_args=True) is None
385
+ # We cache the value on the underlying TypeAlias node as an optimization,
386
+ # since the value is the same for all instances of the same alias.
387
+ self.alias._is_recursive = is_recursive
388
+ return is_recursive
389
+
390
+ def can_be_true_default(self) -> bool:
391
+ if self.alias is not None:
392
+ return self.alias.target.can_be_true
393
+ return super().can_be_true_default()
394
+
395
+ def can_be_false_default(self) -> bool:
396
+ if self.alias is not None:
397
+ return self.alias.target.can_be_false
398
+ return super().can_be_false_default()
399
+
400
+ def accept(self, visitor: TypeVisitor[T]) -> T:
401
+ return visitor.visit_type_alias_type(self)
402
+
403
+ def __hash__(self) -> int:
404
+ return hash((self.alias, tuple(self.args)))
405
+
406
+ def __eq__(self, other: object) -> bool:
407
+ # Note: never use this to determine subtype relationships, use is_subtype().
408
+ if not isinstance(other, TypeAliasType):
409
+ return NotImplemented
410
+ return self.alias == other.alias and self.args == other.args
411
+
412
+ def serialize(self) -> JsonDict:
413
+ assert self.alias is not None
414
+ data: JsonDict = {
415
+ ".class": "TypeAliasType",
416
+ "type_ref": self.alias.fullname,
417
+ "args": [arg.serialize() for arg in self.args],
418
+ }
419
+ return data
420
+
421
+ @classmethod
422
+ def deserialize(cls, data: JsonDict) -> TypeAliasType:
423
+ assert data[".class"] == "TypeAliasType"
424
+ args: list[Type] = []
425
+ if "args" in data:
426
+ args_list = data["args"]
427
+ assert isinstance(args_list, list)
428
+ args = [deserialize_type(arg) for arg in args_list]
429
+ alias = TypeAliasType(None, args)
430
+ alias.type_ref = data["type_ref"]
431
+ return alias
432
+
433
+ def copy_modified(self, *, args: list[Type] | None = None) -> TypeAliasType:
434
+ return TypeAliasType(
435
+ self.alias, args if args is not None else self.args.copy(), self.line, self.column
436
+ )
437
+
438
+
439
+ class TypeGuardedType(Type):
440
+ """Only used by find_isinstance_check() etc."""
441
+
442
+ __slots__ = ("type_guard",)
443
+
444
+ def __init__(self, type_guard: Type) -> None:
445
+ super().__init__(line=type_guard.line, column=type_guard.column)
446
+ self.type_guard = type_guard
447
+
448
+ def __repr__(self) -> str:
449
+ return f"TypeGuard({self.type_guard})"
450
+
451
+
452
+ class RequiredType(Type):
453
+ """Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition."""
454
+
455
+ def __init__(self, item: Type, *, required: bool) -> None:
456
+ super().__init__(line=item.line, column=item.column)
457
+ self.item = item
458
+ self.required = required
459
+
460
+ def __repr__(self) -> str:
461
+ if self.required:
462
+ return f"Required[{self.item}]"
463
+ else:
464
+ return f"NotRequired[{self.item}]"
465
+
466
+ def accept(self, visitor: TypeVisitor[T]) -> T:
467
+ return self.item.accept(visitor)
468
+
469
+
470
+ class ProperType(Type):
471
+ """Not a type alias.
472
+
473
+ Every type except TypeAliasType must inherit from this type.
474
+ """
475
+
476
+ __slots__ = ()
477
+
478
+
479
+ class TypeVarId:
480
+ # A type variable is uniquely identified by its raw id and meta level.
481
+
482
+ # For plain variables (type parameters of generic classes and
483
+ # functions) raw ids are allocated by semantic analysis, using
484
+ # positive ids 1, 2, ... for generic class parameters and negative
485
+ # ids -1, ... for generic function type arguments. A special value 0
486
+ # is reserved for Self type variable (autogenerated). This convention
487
+ # is only used to keep type variable ids distinct when allocating
488
+ # them; the type checker makes no distinction between class and
489
+ # function type variables.
490
+
491
+ # Metavariables are allocated unique ids starting from 1.
492
+ raw_id: int = 0
493
+
494
+ # Level of the variable in type inference. Currently either 0 for
495
+ # declared types, or 1 for type inference metavariables.
496
+ meta_level: int = 0
497
+
498
+ # Class variable used for allocating fresh ids for metavariables.
499
+ next_raw_id: ClassVar[int] = 1
500
+
501
+ # Fullname of class (or potentially function in the future) which
502
+ # declares this type variable (not the fullname of the TypeVar
503
+ # definition!), or ''
504
+ namespace: str
505
+
506
+ def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = "") -> None:
507
+ self.raw_id = raw_id
508
+ self.meta_level = meta_level
509
+ self.namespace = namespace
510
+
511
+ @staticmethod
512
+ def new(meta_level: int) -> TypeVarId:
513
+ raw_id = TypeVarId.next_raw_id
514
+ TypeVarId.next_raw_id += 1
515
+ return TypeVarId(raw_id, meta_level)
516
+
517
+ def __repr__(self) -> str:
518
+ return self.raw_id.__repr__()
519
+
520
+ def __eq__(self, other: object) -> bool:
521
+ return (
522
+ isinstance(other, TypeVarId)
523
+ and self.raw_id == other.raw_id
524
+ and self.meta_level == other.meta_level
525
+ and self.namespace == other.namespace
526
+ )
527
+
528
+ def __ne__(self, other: object) -> bool:
529
+ return not (self == other)
530
+
531
+ def __hash__(self) -> int:
532
+ return hash((self.raw_id, self.meta_level, self.namespace))
533
+
534
+ def is_meta_var(self) -> bool:
535
+ return self.meta_level > 0
536
+
537
+
538
+ class TypeVarLikeType(ProperType):
539
+ __slots__ = ("name", "fullname", "id", "upper_bound", "default")
540
+
541
+ name: str # Name (may be qualified)
542
+ fullname: str # Fully qualified name
543
+ id: TypeVarId
544
+ upper_bound: Type
545
+ default: Type
546
+
547
+ def __init__(
548
+ self,
549
+ name: str,
550
+ fullname: str,
551
+ id: TypeVarId | int,
552
+ upper_bound: Type,
553
+ default: Type,
554
+ line: int = -1,
555
+ column: int = -1,
556
+ ) -> None:
557
+ super().__init__(line, column)
558
+ self.name = name
559
+ self.fullname = fullname
560
+ if isinstance(id, int):
561
+ id = TypeVarId(id)
562
+ self.id = id
563
+ self.upper_bound = upper_bound
564
+ self.default = default
565
+
566
+ def serialize(self) -> JsonDict:
567
+ raise NotImplementedError
568
+
569
+ @classmethod
570
+ def deserialize(cls, data: JsonDict) -> TypeVarLikeType:
571
+ raise NotImplementedError
572
+
573
+ def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self:
574
+ raise NotImplementedError
575
+
576
+ @classmethod
577
+ def new_unification_variable(cls, old: Self) -> Self:
578
+ new_id = TypeVarId.new(meta_level=1)
579
+ return old.copy_modified(id=new_id)
580
+
581
+ def has_default(self) -> bool:
582
+ t = get_proper_type(self.default)
583
+ return not (isinstance(t, AnyType) and t.type_of_any == TypeOfAny.from_omitted_generics)
584
+
585
+
586
+ class TypeVarType(TypeVarLikeType):
587
+ """Type that refers to a type variable."""
588
+
589
+ __slots__ = ("values", "variance")
590
+
591
+ values: list[Type] # Value restriction, empty list if no restriction
592
+ variance: int
593
+
594
+ def __init__(
595
+ self,
596
+ name: str,
597
+ fullname: str,
598
+ id: TypeVarId | int,
599
+ values: list[Type],
600
+ upper_bound: Type,
601
+ default: Type,
602
+ variance: int = INVARIANT,
603
+ line: int = -1,
604
+ column: int = -1,
605
+ ) -> None:
606
+ super().__init__(name, fullname, id, upper_bound, default, line, column)
607
+ assert values is not None, "No restrictions must be represented by empty list"
608
+ self.values = values
609
+ self.variance = variance
610
+
611
+ def copy_modified(
612
+ self,
613
+ *,
614
+ values: Bogus[list[Type]] = _dummy,
615
+ upper_bound: Bogus[Type] = _dummy,
616
+ default: Bogus[Type] = _dummy,
617
+ id: Bogus[TypeVarId | int] = _dummy,
618
+ line: int = _dummy_int,
619
+ column: int = _dummy_int,
620
+ **kwargs: Any,
621
+ ) -> TypeVarType:
622
+ return TypeVarType(
623
+ name=self.name,
624
+ fullname=self.fullname,
625
+ id=self.id if id is _dummy else id,
626
+ values=self.values if values is _dummy else values,
627
+ upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,
628
+ default=self.default if default is _dummy else default,
629
+ variance=self.variance,
630
+ line=self.line if line == _dummy_int else line,
631
+ column=self.column if column == _dummy_int else column,
632
+ )
633
+
634
+ def accept(self, visitor: TypeVisitor[T]) -> T:
635
+ return visitor.visit_type_var(self)
636
+
637
+ def __hash__(self) -> int:
638
+ return hash((self.id, self.upper_bound, tuple(self.values)))
639
+
640
+ def __eq__(self, other: object) -> bool:
641
+ if not isinstance(other, TypeVarType):
642
+ return NotImplemented
643
+ return (
644
+ self.id == other.id
645
+ and self.upper_bound == other.upper_bound
646
+ and self.values == other.values
647
+ )
648
+
649
+ def serialize(self) -> JsonDict:
650
+ assert not self.id.is_meta_var()
651
+ return {
652
+ ".class": "TypeVarType",
653
+ "name": self.name,
654
+ "fullname": self.fullname,
655
+ "id": self.id.raw_id,
656
+ "namespace": self.id.namespace,
657
+ "values": [v.serialize() for v in self.values],
658
+ "upper_bound": self.upper_bound.serialize(),
659
+ "default": self.default.serialize(),
660
+ "variance": self.variance,
661
+ }
662
+
663
+ @classmethod
664
+ def deserialize(cls, data: JsonDict) -> TypeVarType:
665
+ assert data[".class"] == "TypeVarType"
666
+ return TypeVarType(
667
+ name=data["name"],
668
+ fullname=data["fullname"],
669
+ id=TypeVarId(data["id"], namespace=data["namespace"]),
670
+ values=[deserialize_type(v) for v in data["values"]],
671
+ upper_bound=deserialize_type(data["upper_bound"]),
672
+ default=deserialize_type(data["default"]),
673
+ variance=data["variance"],
674
+ )
675
+
676
+
677
+ class ParamSpecFlavor:
678
+ # Simple ParamSpec reference such as "P"
679
+ BARE: Final = 0
680
+ # P.args
681
+ ARGS: Final = 1
682
+ # P.kwargs
683
+ KWARGS: Final = 2
684
+
685
+
686
+ class ParamSpecType(TypeVarLikeType):
687
+ """Type that refers to a ParamSpec.
688
+
689
+ A ParamSpec is a type variable that represents the parameter
690
+ types, names and kinds of a callable (i.e., the signature without
691
+ the return type).
692
+
693
+ This can be one of these forms
694
+ * P (ParamSpecFlavor.BARE)
695
+ * P.args (ParamSpecFlavor.ARGS)
696
+ * P.kwargs (ParamSpecFLavor.KWARGS)
697
+
698
+ The upper_bound is really used as a fallback type -- it's shared
699
+ with TypeVarType for simplicity. It can't be specified by the user
700
+ and the value is directly derived from the flavor (currently
701
+ always just 'object').
702
+ """
703
+
704
+ __slots__ = ("flavor", "prefix")
705
+
706
+ flavor: int
707
+ prefix: Parameters
708
+
709
+ def __init__(
710
+ self,
711
+ name: str,
712
+ fullname: str,
713
+ id: TypeVarId | int,
714
+ flavor: int,
715
+ upper_bound: Type,
716
+ default: Type,
717
+ *,
718
+ line: int = -1,
719
+ column: int = -1,
720
+ prefix: Parameters | None = None,
721
+ ) -> None:
722
+ super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)
723
+ self.flavor = flavor
724
+ self.prefix = prefix or Parameters([], [], [])
725
+
726
+ def with_flavor(self, flavor: int) -> ParamSpecType:
727
+ return ParamSpecType(
728
+ self.name,
729
+ self.fullname,
730
+ self.id,
731
+ flavor,
732
+ upper_bound=self.upper_bound,
733
+ default=self.default,
734
+ prefix=self.prefix,
735
+ )
736
+
737
+ def copy_modified(
738
+ self,
739
+ *,
740
+ id: Bogus[TypeVarId | int] = _dummy,
741
+ flavor: int = _dummy_int,
742
+ prefix: Bogus[Parameters] = _dummy,
743
+ default: Bogus[Type] = _dummy,
744
+ **kwargs: Any,
745
+ ) -> ParamSpecType:
746
+ return ParamSpecType(
747
+ self.name,
748
+ self.fullname,
749
+ id if id is not _dummy else self.id,
750
+ flavor if flavor != _dummy_int else self.flavor,
751
+ self.upper_bound,
752
+ default=default if default is not _dummy else self.default,
753
+ line=self.line,
754
+ column=self.column,
755
+ prefix=prefix if prefix is not _dummy else self.prefix,
756
+ )
757
+
758
+ def accept(self, visitor: TypeVisitor[T]) -> T:
759
+ return visitor.visit_param_spec(self)
760
+
761
+ def name_with_suffix(self) -> str:
762
+ n = self.name
763
+ if self.flavor == ParamSpecFlavor.ARGS:
764
+ return f"{n}.args"
765
+ elif self.flavor == ParamSpecFlavor.KWARGS:
766
+ return f"{n}.kwargs"
767
+ return n
768
+
769
+ def __hash__(self) -> int:
770
+ return hash((self.id, self.flavor, self.prefix))
771
+
772
+ def __eq__(self, other: object) -> bool:
773
+ if not isinstance(other, ParamSpecType):
774
+ return NotImplemented
775
+ # Upper bound can be ignored, since it's determined by flavor.
776
+ return self.id == other.id and self.flavor == other.flavor and self.prefix == other.prefix
777
+
778
+ def serialize(self) -> JsonDict:
779
+ assert not self.id.is_meta_var()
780
+ return {
781
+ ".class": "ParamSpecType",
782
+ "name": self.name,
783
+ "fullname": self.fullname,
784
+ "id": self.id.raw_id,
785
+ "flavor": self.flavor,
786
+ "upper_bound": self.upper_bound.serialize(),
787
+ "default": self.default.serialize(),
788
+ "prefix": self.prefix.serialize(),
789
+ }
790
+
791
+ @classmethod
792
+ def deserialize(cls, data: JsonDict) -> ParamSpecType:
793
+ assert data[".class"] == "ParamSpecType"
794
+ return ParamSpecType(
795
+ data["name"],
796
+ data["fullname"],
797
+ data["id"],
798
+ data["flavor"],
799
+ deserialize_type(data["upper_bound"]),
800
+ deserialize_type(data["default"]),
801
+ prefix=Parameters.deserialize(data["prefix"]),
802
+ )
803
+
804
+
805
+ class TypeVarTupleType(TypeVarLikeType):
806
+ """Type that refers to a TypeVarTuple.
807
+
808
+ See PEP646 for more information.
809
+ """
810
+
811
+ __slots__ = ("tuple_fallback", "min_len")
812
+
813
+ def __init__(
814
+ self,
815
+ name: str,
816
+ fullname: str,
817
+ id: TypeVarId | int,
818
+ upper_bound: Type,
819
+ tuple_fallback: Instance,
820
+ default: Type,
821
+ *,
822
+ line: int = -1,
823
+ column: int = -1,
824
+ min_len: int = 0,
825
+ ) -> None:
826
+ super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)
827
+ self.tuple_fallback = tuple_fallback
828
+ # This value is not settable by a user. It is an internal-only thing to support
829
+ # len()-narrowing of variadic tuples.
830
+ self.min_len = min_len
831
+
832
+ def serialize(self) -> JsonDict:
833
+ assert not self.id.is_meta_var()
834
+ return {
835
+ ".class": "TypeVarTupleType",
836
+ "name": self.name,
837
+ "fullname": self.fullname,
838
+ "id": self.id.raw_id,
839
+ "upper_bound": self.upper_bound.serialize(),
840
+ "tuple_fallback": self.tuple_fallback.serialize(),
841
+ "default": self.default.serialize(),
842
+ "min_len": self.min_len,
843
+ }
844
+
845
+ @classmethod
846
+ def deserialize(cls, data: JsonDict) -> TypeVarTupleType:
847
+ assert data[".class"] == "TypeVarTupleType"
848
+ return TypeVarTupleType(
849
+ data["name"],
850
+ data["fullname"],
851
+ data["id"],
852
+ deserialize_type(data["upper_bound"]),
853
+ Instance.deserialize(data["tuple_fallback"]),
854
+ deserialize_type(data["default"]),
855
+ min_len=data["min_len"],
856
+ )
857
+
858
+ def accept(self, visitor: TypeVisitor[T]) -> T:
859
+ return visitor.visit_type_var_tuple(self)
860
+
861
+ def __hash__(self) -> int:
862
+ return hash((self.id, self.min_len))
863
+
864
+ def __eq__(self, other: object) -> bool:
865
+ if not isinstance(other, TypeVarTupleType):
866
+ return NotImplemented
867
+ return self.id == other.id and self.min_len == other.min_len
868
+
869
+ def copy_modified(
870
+ self,
871
+ *,
872
+ id: Bogus[TypeVarId | int] = _dummy,
873
+ upper_bound: Bogus[Type] = _dummy,
874
+ default: Bogus[Type] = _dummy,
875
+ min_len: Bogus[int] = _dummy,
876
+ **kwargs: Any,
877
+ ) -> TypeVarTupleType:
878
+ return TypeVarTupleType(
879
+ self.name,
880
+ self.fullname,
881
+ self.id if id is _dummy else id,
882
+ self.upper_bound if upper_bound is _dummy else upper_bound,
883
+ self.tuple_fallback,
884
+ self.default if default is _dummy else default,
885
+ line=self.line,
886
+ column=self.column,
887
+ min_len=self.min_len if min_len is _dummy else min_len,
888
+ )
889
+
890
+
891
+ class UnboundType(ProperType):
892
+ """Instance type that has not been bound during semantic analysis."""
893
+
894
+ __slots__ = (
895
+ "name",
896
+ "args",
897
+ "optional",
898
+ "empty_tuple_index",
899
+ "original_str_expr",
900
+ "original_str_fallback",
901
+ )
902
+
903
+ def __init__(
904
+ self,
905
+ name: str | None,
906
+ args: Sequence[Type] | None = None,
907
+ line: int = -1,
908
+ column: int = -1,
909
+ optional: bool = False,
910
+ empty_tuple_index: bool = False,
911
+ original_str_expr: str | None = None,
912
+ original_str_fallback: str | None = None,
913
+ ) -> None:
914
+ super().__init__(line, column)
915
+ if not args:
916
+ args = []
917
+ assert name is not None
918
+ self.name = name
919
+ self.args = tuple(args)
920
+ # Should this type be wrapped in an Optional?
921
+ self.optional = optional
922
+ # Special case for X[()]
923
+ self.empty_tuple_index = empty_tuple_index
924
+ # If this UnboundType was originally defined as a str or bytes, keep track of
925
+ # the original contents of that string-like thing. This way, if this UnboundExpr
926
+ # ever shows up inside of a LiteralType, we can determine whether that
927
+ # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid
928
+ # (unless 'foo' is an alias for another literal or something) and
929
+ # Literal["foo"] most likely is.
930
+ #
931
+ # We keep track of the entire string instead of just using a boolean flag
932
+ # so we can distinguish between things like Literal["foo"] vs
933
+ # Literal[" foo "].
934
+ #
935
+ # We also keep track of what the original base fallback type was supposed to be
936
+ # so we don't have to try and recompute it later
937
+ self.original_str_expr = original_str_expr
938
+ self.original_str_fallback = original_str_fallback
939
+
940
+ def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType:
941
+ if args is _dummy:
942
+ args = self.args
943
+ return UnboundType(
944
+ name=self.name,
945
+ args=args,
946
+ line=self.line,
947
+ column=self.column,
948
+ optional=self.optional,
949
+ empty_tuple_index=self.empty_tuple_index,
950
+ original_str_expr=self.original_str_expr,
951
+ original_str_fallback=self.original_str_fallback,
952
+ )
953
+
954
+ def accept(self, visitor: TypeVisitor[T]) -> T:
955
+ return visitor.visit_unbound_type(self)
956
+
957
+ def __hash__(self) -> int:
958
+ return hash((self.name, self.optional, tuple(self.args), self.original_str_expr))
959
+
960
+ def __eq__(self, other: object) -> bool:
961
+ if not isinstance(other, UnboundType):
962
+ return NotImplemented
963
+ return (
964
+ self.name == other.name
965
+ and self.optional == other.optional
966
+ and self.args == other.args
967
+ and self.original_str_expr == other.original_str_expr
968
+ and self.original_str_fallback == other.original_str_fallback
969
+ )
970
+
971
+ def serialize(self) -> JsonDict:
972
+ return {
973
+ ".class": "UnboundType",
974
+ "name": self.name,
975
+ "args": [a.serialize() for a in self.args],
976
+ "expr": self.original_str_expr,
977
+ "expr_fallback": self.original_str_fallback,
978
+ }
979
+
980
+ @classmethod
981
+ def deserialize(cls, data: JsonDict) -> UnboundType:
982
+ assert data[".class"] == "UnboundType"
983
+ return UnboundType(
984
+ data["name"],
985
+ [deserialize_type(a) for a in data["args"]],
986
+ original_str_expr=data["expr"],
987
+ original_str_fallback=data["expr_fallback"],
988
+ )
989
+
990
+
991
+ class CallableArgument(ProperType):
992
+ """Represents a Arg(type, 'name') inside a Callable's type list.
993
+
994
+ Note that this is a synthetic type for helping parse ASTs, not a real type.
995
+ """
996
+
997
+ __slots__ = ("typ", "name", "constructor")
998
+
999
+ typ: Type
1000
+ name: str | None
1001
+ constructor: str | None
1002
+
1003
+ def __init__(
1004
+ self,
1005
+ typ: Type,
1006
+ name: str | None,
1007
+ constructor: str | None,
1008
+ line: int = -1,
1009
+ column: int = -1,
1010
+ ) -> None:
1011
+ super().__init__(line, column)
1012
+ self.typ = typ
1013
+ self.name = name
1014
+ self.constructor = constructor
1015
+
1016
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1017
+ assert isinstance(visitor, SyntheticTypeVisitor)
1018
+ ret: T = visitor.visit_callable_argument(self)
1019
+ return ret
1020
+
1021
+ def serialize(self) -> JsonDict:
1022
+ assert False, "Synthetic types don't serialize"
1023
+
1024
+
1025
+ class TypeList(ProperType):
1026
+ """Information about argument types and names [...].
1027
+
1028
+ This is used for the arguments of a Callable type, i.e. for
1029
+ [arg, ...] in Callable[[arg, ...], ret]. This is not a real type
1030
+ but a syntactic AST construct. UnboundTypes can also have TypeList
1031
+ types before they are processed into Callable types.
1032
+ """
1033
+
1034
+ __slots__ = ("items",)
1035
+
1036
+ items: list[Type]
1037
+
1038
+ def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:
1039
+ super().__init__(line, column)
1040
+ self.items = items
1041
+
1042
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1043
+ assert isinstance(visitor, SyntheticTypeVisitor)
1044
+ ret: T = visitor.visit_type_list(self)
1045
+ return ret
1046
+
1047
+ def serialize(self) -> JsonDict:
1048
+ assert False, "Synthetic types don't serialize"
1049
+
1050
+ def __hash__(self) -> int:
1051
+ return hash(tuple(self.items))
1052
+
1053
+ def __eq__(self, other: object) -> bool:
1054
+ return isinstance(other, TypeList) and self.items == other.items
1055
+
1056
+
1057
+ class UnpackType(ProperType):
1058
+ """Type operator Unpack from PEP646. Can be either with Unpack[]
1059
+ or unpacking * syntax.
1060
+
1061
+ The inner type should be either a TypeVarTuple, or a variable length tuple.
1062
+ In an exceptional case of callable star argument it can be a fixed length tuple.
1063
+
1064
+ Note: the above restrictions are only guaranteed by normalizations after semantic
1065
+ analysis, if your code needs to handle UnpackType *during* semantic analysis, it is
1066
+ wild west, technically anything can be present in the wrapped type.
1067
+ """
1068
+
1069
+ __slots__ = ["type", "from_star_syntax"]
1070
+
1071
+ def __init__(
1072
+ self, typ: Type, line: int = -1, column: int = -1, from_star_syntax: bool = False
1073
+ ) -> None:
1074
+ super().__init__(line, column)
1075
+ self.type = typ
1076
+ self.from_star_syntax = from_star_syntax
1077
+
1078
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1079
+ return visitor.visit_unpack_type(self)
1080
+
1081
+ def serialize(self) -> JsonDict:
1082
+ return {".class": "UnpackType", "type": self.type.serialize()}
1083
+
1084
+ @classmethod
1085
+ def deserialize(cls, data: JsonDict) -> UnpackType:
1086
+ assert data[".class"] == "UnpackType"
1087
+ typ = data["type"]
1088
+ return UnpackType(deserialize_type(typ))
1089
+
1090
+ def __hash__(self) -> int:
1091
+ return hash(self.type)
1092
+
1093
+ def __eq__(self, other: object) -> bool:
1094
+ return isinstance(other, UnpackType) and self.type == other.type
1095
+
1096
+
1097
+ class AnyType(ProperType):
1098
+ """The type 'Any'."""
1099
+
1100
+ __slots__ = ("type_of_any", "source_any", "missing_import_name")
1101
+
1102
+ def __init__(
1103
+ self,
1104
+ type_of_any: int,
1105
+ source_any: AnyType | None = None,
1106
+ missing_import_name: str | None = None,
1107
+ line: int = -1,
1108
+ column: int = -1,
1109
+ ) -> None:
1110
+ super().__init__(line, column)
1111
+ self.type_of_any = type_of_any
1112
+ # If this Any was created as a result of interacting with another 'Any', record the source
1113
+ # and use it in reports.
1114
+ self.source_any = source_any
1115
+ if source_any and source_any.source_any:
1116
+ self.source_any = source_any.source_any
1117
+
1118
+ if source_any is None:
1119
+ self.missing_import_name = missing_import_name
1120
+ else:
1121
+ self.missing_import_name = source_any.missing_import_name
1122
+
1123
+ # Only unimported type anys and anys from other anys should have an import name
1124
+ assert missing_import_name is None or type_of_any in (
1125
+ TypeOfAny.from_unimported_type,
1126
+ TypeOfAny.from_another_any,
1127
+ )
1128
+ # Only Anys that come from another Any can have source_any.
1129
+ assert type_of_any != TypeOfAny.from_another_any or source_any is not None
1130
+ # We should not have chains of Anys.
1131
+ assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any
1132
+
1133
+ @property
1134
+ def is_from_error(self) -> bool:
1135
+ return self.type_of_any == TypeOfAny.from_error
1136
+
1137
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1138
+ return visitor.visit_any(self)
1139
+
1140
+ def copy_modified(
1141
+ self,
1142
+ # Mark with Bogus because _dummy is just an object (with type Any)
1143
+ type_of_any: int = _dummy_int,
1144
+ original_any: Bogus[AnyType | None] = _dummy,
1145
+ ) -> AnyType:
1146
+ if type_of_any == _dummy_int:
1147
+ type_of_any = self.type_of_any
1148
+ if original_any is _dummy:
1149
+ original_any = self.source_any
1150
+ return AnyType(
1151
+ type_of_any=type_of_any,
1152
+ source_any=original_any,
1153
+ missing_import_name=self.missing_import_name,
1154
+ line=self.line,
1155
+ column=self.column,
1156
+ )
1157
+
1158
+ def __hash__(self) -> int:
1159
+ return hash(AnyType)
1160
+
1161
+ def __eq__(self, other: object) -> bool:
1162
+ return isinstance(other, AnyType)
1163
+
1164
+ def serialize(self) -> JsonDict:
1165
+ return {
1166
+ ".class": "AnyType",
1167
+ "type_of_any": self.type_of_any,
1168
+ "source_any": self.source_any.serialize() if self.source_any is not None else None,
1169
+ "missing_import_name": self.missing_import_name,
1170
+ }
1171
+
1172
+ @classmethod
1173
+ def deserialize(cls, data: JsonDict) -> AnyType:
1174
+ assert data[".class"] == "AnyType"
1175
+ source = data["source_any"]
1176
+ return AnyType(
1177
+ data["type_of_any"],
1178
+ AnyType.deserialize(source) if source is not None else None,
1179
+ data["missing_import_name"],
1180
+ )
1181
+
1182
+
1183
+ class UninhabitedType(ProperType):
1184
+ """This type has no members.
1185
+
1186
+ This type is the bottom type.
1187
+ With strict Optional checking, it is the only common subtype between all
1188
+ other types, which allows `meet` to be well defined. Without strict
1189
+ Optional checking, NoneType fills this role.
1190
+
1191
+ In general, for any type T:
1192
+ join(UninhabitedType, T) = T
1193
+ meet(UninhabitedType, T) = UninhabitedType
1194
+ is_subtype(UninhabitedType, T) = True
1195
+ """
1196
+
1197
+ __slots__ = ("ambiguous", "is_noreturn")
1198
+
1199
+ is_noreturn: bool # Does this come from a NoReturn? Purely for error messages.
1200
+ # It is important to track whether this is an actual NoReturn type, or just a result
1201
+ # of ambiguous type inference, in the latter case we don't want to mark a branch as
1202
+ # unreachable in binder.
1203
+ ambiguous: bool # Is this a result of inference for a variable without constraints?
1204
+
1205
+ def __init__(self, is_noreturn: bool = False, line: int = -1, column: int = -1) -> None:
1206
+ super().__init__(line, column)
1207
+ self.is_noreturn = is_noreturn
1208
+ self.ambiguous = False
1209
+
1210
+ def can_be_true_default(self) -> bool:
1211
+ return False
1212
+
1213
+ def can_be_false_default(self) -> bool:
1214
+ return False
1215
+
1216
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1217
+ return visitor.visit_uninhabited_type(self)
1218
+
1219
+ def __hash__(self) -> int:
1220
+ return hash(UninhabitedType)
1221
+
1222
+ def __eq__(self, other: object) -> bool:
1223
+ return isinstance(other, UninhabitedType)
1224
+
1225
+ def serialize(self) -> JsonDict:
1226
+ return {".class": "UninhabitedType", "is_noreturn": self.is_noreturn}
1227
+
1228
+ @classmethod
1229
+ def deserialize(cls, data: JsonDict) -> UninhabitedType:
1230
+ assert data[".class"] == "UninhabitedType"
1231
+ return UninhabitedType(is_noreturn=data["is_noreturn"])
1232
+
1233
+
1234
+ class NoneType(ProperType):
1235
+ """The type of 'None'.
1236
+
1237
+ This type can be written by users as 'None'.
1238
+ """
1239
+
1240
+ __slots__ = ()
1241
+
1242
+ def __init__(self, line: int = -1, column: int = -1) -> None:
1243
+ super().__init__(line, column)
1244
+
1245
+ def can_be_true_default(self) -> bool:
1246
+ return False
1247
+
1248
+ def __hash__(self) -> int:
1249
+ return hash(NoneType)
1250
+
1251
+ def __eq__(self, other: object) -> bool:
1252
+ return isinstance(other, NoneType)
1253
+
1254
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1255
+ return visitor.visit_none_type(self)
1256
+
1257
+ def serialize(self) -> JsonDict:
1258
+ return {".class": "NoneType"}
1259
+
1260
+ @classmethod
1261
+ def deserialize(cls, data: JsonDict) -> NoneType:
1262
+ assert data[".class"] == "NoneType"
1263
+ return NoneType()
1264
+
1265
+ def is_singleton_type(self) -> bool:
1266
+ return True
1267
+
1268
+
1269
+ # NoneType used to be called NoneTyp so to avoid needlessly breaking
1270
+ # external plugins we keep that alias here.
1271
+ NoneTyp = NoneType
1272
+
1273
+
1274
+ class ErasedType(ProperType):
1275
+ """Placeholder for an erased type.
1276
+
1277
+ This is used during type inference. This has the special property that
1278
+ it is ignored during type inference.
1279
+ """
1280
+
1281
+ __slots__ = ()
1282
+
1283
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1284
+ return visitor.visit_erased_type(self)
1285
+
1286
+
1287
+ class DeletedType(ProperType):
1288
+ """Type of deleted variables.
1289
+
1290
+ These can be used as lvalues but not rvalues.
1291
+ """
1292
+
1293
+ __slots__ = ("source",)
1294
+
1295
+ source: str | None # May be None; name that generated this value
1296
+
1297
+ def __init__(self, source: str | None = None, line: int = -1, column: int = -1) -> None:
1298
+ super().__init__(line, column)
1299
+ self.source = source
1300
+
1301
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1302
+ return visitor.visit_deleted_type(self)
1303
+
1304
+ def serialize(self) -> JsonDict:
1305
+ return {".class": "DeletedType", "source": self.source}
1306
+
1307
+ @classmethod
1308
+ def deserialize(cls, data: JsonDict) -> DeletedType:
1309
+ assert data[".class"] == "DeletedType"
1310
+ return DeletedType(data["source"])
1311
+
1312
+
1313
+ # Fake TypeInfo to be used as a placeholder during Instance de-serialization.
1314
+ NOT_READY: Final = mypy.nodes.FakeInfo("De-serialization failure: TypeInfo not fixed")
1315
+
1316
+
1317
+ class ExtraAttrs:
1318
+ """Summary of module attributes and types.
1319
+
1320
+ This is used for instances of types.ModuleType, because they can have different
1321
+ attributes per instance, and for type narrowing with hasattr() checks.
1322
+ """
1323
+
1324
+ def __init__(
1325
+ self,
1326
+ attrs: dict[str, Type],
1327
+ immutable: set[str] | None = None,
1328
+ mod_name: str | None = None,
1329
+ ) -> None:
1330
+ self.attrs = attrs
1331
+ if immutable is None:
1332
+ immutable = set()
1333
+ self.immutable = immutable
1334
+ self.mod_name = mod_name
1335
+
1336
+ def __hash__(self) -> int:
1337
+ return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable))))
1338
+
1339
+ def __eq__(self, other: object) -> bool:
1340
+ if not isinstance(other, ExtraAttrs):
1341
+ return NotImplemented
1342
+ return self.attrs == other.attrs and self.immutable == other.immutable
1343
+
1344
+ def copy(self) -> ExtraAttrs:
1345
+ return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name)
1346
+
1347
+ def __repr__(self) -> str:
1348
+ return f"ExtraAttrs({self.attrs!r}, {self.immutable!r}, {self.mod_name!r})"
1349
+
1350
+
1351
+ class Instance(ProperType):
1352
+ """An instance type of form C[T1, ..., Tn].
1353
+
1354
+ The list of type variables may be empty.
1355
+
1356
+ Several types have fallbacks to `Instance`, because in Python everything is an object
1357
+ and this concept is impossible to express without intersection types. We therefore use
1358
+ fallbacks for all "non-special" (like UninhabitedType, ErasedType etc) types.
1359
+ """
1360
+
1361
+ __slots__ = ("type", "args", "invalid", "type_ref", "last_known_value", "_hash", "extra_attrs")
1362
+
1363
+ def __init__(
1364
+ self,
1365
+ typ: mypy.nodes.TypeInfo,
1366
+ args: Sequence[Type],
1367
+ line: int = -1,
1368
+ column: int = -1,
1369
+ *,
1370
+ last_known_value: LiteralType | None = None,
1371
+ extra_attrs: ExtraAttrs | None = None,
1372
+ ) -> None:
1373
+ super().__init__(line, column)
1374
+ self.type = typ
1375
+ self.args = tuple(args)
1376
+ self.type_ref: str | None = None
1377
+
1378
+ # True if recovered after incorrect number of type arguments error
1379
+ self.invalid = False
1380
+
1381
+ # This field keeps track of the underlying Literal[...] value associated with
1382
+ # this instance, if one is known.
1383
+ #
1384
+ # This field is set whenever possible within expressions, but is erased upon
1385
+ # variable assignment (see erasetype.remove_instance_last_known_values) unless
1386
+ # the variable is declared to be final.
1387
+ #
1388
+ # For example, consider the following program:
1389
+ #
1390
+ # a = 1
1391
+ # b: Final[int] = 2
1392
+ # c: Final = 3
1393
+ # print(a + b + c + 4)
1394
+ #
1395
+ # The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will
1396
+ # have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4]
1397
+ # respectively. However, the Instance object assigned to 'a' and 'b' will have their
1398
+ # last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be
1399
+ # specifically an int.
1400
+ #
1401
+ # Or more broadly, this field lets this Instance "remember" its original declaration
1402
+ # when applicable. We want this behavior because we want implicit Final declarations
1403
+ # to act pretty much identically with constants: we should be able to replace any
1404
+ # places where we use some Final variable with the original value and get the same
1405
+ # type-checking behavior. For example, we want this program:
1406
+ #
1407
+ # def expects_literal(x: Literal[3]) -> None: pass
1408
+ # var: Final = 3
1409
+ # expects_literal(var)
1410
+ #
1411
+ # ...to type-check in the exact same way as if we had written the program like this:
1412
+ #
1413
+ # def expects_literal(x: Literal[3]) -> None: pass
1414
+ # expects_literal(3)
1415
+ #
1416
+ # In order to make this work (especially with literal types), we need var's type
1417
+ # (an Instance) to remember the "original" value.
1418
+ #
1419
+ # Preserving this value within expressions is useful for similar reasons.
1420
+ #
1421
+ # Currently most of mypy will ignore this field and will continue to treat this type like
1422
+ # a regular Instance. We end up using this field only when we are explicitly within a
1423
+ # Literal context.
1424
+ self.last_known_value = last_known_value
1425
+
1426
+ # Cached hash value
1427
+ self._hash = -1
1428
+
1429
+ # Additional attributes defined per instance of this type. For example modules
1430
+ # have different attributes per instance of types.ModuleType. This is intended
1431
+ # to be "short-lived", we don't serialize it, and even don't store as variable type.
1432
+ self.extra_attrs = extra_attrs
1433
+
1434
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1435
+ return visitor.visit_instance(self)
1436
+
1437
+ def __hash__(self) -> int:
1438
+ if self._hash == -1:
1439
+ self._hash = hash((self.type, self.args, self.last_known_value, self.extra_attrs))
1440
+ return self._hash
1441
+
1442
+ def __eq__(self, other: object) -> bool:
1443
+ if not isinstance(other, Instance):
1444
+ return NotImplemented
1445
+ return (
1446
+ self.type == other.type
1447
+ and self.args == other.args
1448
+ and self.last_known_value == other.last_known_value
1449
+ and self.extra_attrs == other.extra_attrs
1450
+ )
1451
+
1452
+ def serialize(self) -> JsonDict | str:
1453
+ assert self.type is not None
1454
+ type_ref = self.type.fullname
1455
+ if not self.args and not self.last_known_value:
1456
+ return type_ref
1457
+ data: JsonDict = {".class": "Instance"}
1458
+ data["type_ref"] = type_ref
1459
+ data["args"] = [arg.serialize() for arg in self.args]
1460
+ if self.last_known_value is not None:
1461
+ data["last_known_value"] = self.last_known_value.serialize()
1462
+ return data
1463
+
1464
+ @classmethod
1465
+ def deserialize(cls, data: JsonDict | str) -> Instance:
1466
+ if isinstance(data, str):
1467
+ inst = Instance(NOT_READY, [])
1468
+ inst.type_ref = data
1469
+ return inst
1470
+ assert data[".class"] == "Instance"
1471
+ args: list[Type] = []
1472
+ if "args" in data:
1473
+ args_list = data["args"]
1474
+ assert isinstance(args_list, list)
1475
+ args = [deserialize_type(arg) for arg in args_list]
1476
+ inst = Instance(NOT_READY, args)
1477
+ inst.type_ref = data["type_ref"] # Will be fixed up by fixup.py later.
1478
+ if "last_known_value" in data:
1479
+ inst.last_known_value = LiteralType.deserialize(data["last_known_value"])
1480
+ return inst
1481
+
1482
+ def copy_modified(
1483
+ self,
1484
+ *,
1485
+ args: Bogus[list[Type]] = _dummy,
1486
+ last_known_value: Bogus[LiteralType | None] = _dummy,
1487
+ ) -> Instance:
1488
+ new = Instance(
1489
+ self.type,
1490
+ args if args is not _dummy else self.args,
1491
+ self.line,
1492
+ self.column,
1493
+ last_known_value=(
1494
+ last_known_value if last_known_value is not _dummy else self.last_known_value
1495
+ ),
1496
+ )
1497
+ # We intentionally don't copy the extra_attrs here, so they will be erased.
1498
+ new.can_be_true = self.can_be_true
1499
+ new.can_be_false = self.can_be_false
1500
+ return new
1501
+
1502
+ def copy_with_extra_attr(self, name: str, typ: Type) -> Instance:
1503
+ if self.extra_attrs:
1504
+ existing_attrs = self.extra_attrs.copy()
1505
+ else:
1506
+ existing_attrs = ExtraAttrs({}, set(), None)
1507
+ existing_attrs.attrs[name] = typ
1508
+ new = self.copy_modified()
1509
+ new.extra_attrs = existing_attrs
1510
+ return new
1511
+
1512
+ def is_singleton_type(self) -> bool:
1513
+ # TODO:
1514
+ # Also make this return True if the type corresponds to NotImplemented?
1515
+ return (
1516
+ self.type.is_enum
1517
+ and len(self.get_enum_values()) == 1
1518
+ or self.type.fullname == "builtins.ellipsis"
1519
+ )
1520
+
1521
+ def get_enum_values(self) -> list[str]:
1522
+ """Return the list of values for an Enum."""
1523
+ return [
1524
+ name for name, sym in self.type.names.items() if isinstance(sym.node, mypy.nodes.Var)
1525
+ ]
1526
+
1527
+
1528
+ class FunctionLike(ProperType):
1529
+ """Abstract base class for function types."""
1530
+
1531
+ __slots__ = ("fallback",)
1532
+
1533
+ fallback: Instance
1534
+
1535
+ def __init__(self, line: int = -1, column: int = -1) -> None:
1536
+ super().__init__(line, column)
1537
+ self._can_be_false = False
1538
+
1539
+ @abstractmethod
1540
+ def is_type_obj(self) -> bool:
1541
+ pass
1542
+
1543
+ @abstractmethod
1544
+ def type_object(self) -> mypy.nodes.TypeInfo:
1545
+ pass
1546
+
1547
+ @property
1548
+ @abstractmethod
1549
+ def items(self) -> list[CallableType]:
1550
+ pass
1551
+
1552
+ @abstractmethod
1553
+ def with_name(self, name: str) -> FunctionLike:
1554
+ pass
1555
+
1556
+ @abstractmethod
1557
+ def get_name(self) -> str | None:
1558
+ pass
1559
+
1560
+
1561
+ class FormalArgument(NamedTuple):
1562
+ name: str | None
1563
+ pos: int | None
1564
+ typ: Type
1565
+ required: bool
1566
+
1567
+
1568
+ class Parameters(ProperType):
1569
+ """Type that represents the parameters to a function.
1570
+
1571
+ Used for ParamSpec analysis. Note that by convention we handle this
1572
+ type as a Callable without return type, not as a "tuple with names",
1573
+ so that it behaves contravariantly, in particular [x: int] <: [int].
1574
+ """
1575
+
1576
+ __slots__ = (
1577
+ "arg_types",
1578
+ "arg_kinds",
1579
+ "arg_names",
1580
+ "min_args",
1581
+ "is_ellipsis_args",
1582
+ # TODO: variables don't really belong here, but they are used to allow hacky support
1583
+ # for forall . Foo[[x: T], T] by capturing generic callable with ParamSpec, see #15909
1584
+ "variables",
1585
+ "imprecise_arg_kinds",
1586
+ )
1587
+
1588
+ def __init__(
1589
+ self,
1590
+ arg_types: Sequence[Type],
1591
+ arg_kinds: list[ArgKind],
1592
+ arg_names: Sequence[str | None],
1593
+ *,
1594
+ variables: Sequence[TypeVarLikeType] | None = None,
1595
+ is_ellipsis_args: bool = False,
1596
+ imprecise_arg_kinds: bool = False,
1597
+ line: int = -1,
1598
+ column: int = -1,
1599
+ ) -> None:
1600
+ super().__init__(line, column)
1601
+ self.arg_types = list(arg_types)
1602
+ self.arg_kinds = arg_kinds
1603
+ self.arg_names = list(arg_names)
1604
+ assert len(arg_types) == len(arg_kinds) == len(arg_names)
1605
+ assert not any(isinstance(t, Parameters) for t in arg_types)
1606
+ self.min_args = arg_kinds.count(ARG_POS)
1607
+ self.is_ellipsis_args = is_ellipsis_args
1608
+ self.variables = variables or []
1609
+ self.imprecise_arg_kinds = imprecise_arg_kinds
1610
+
1611
+ def copy_modified(
1612
+ self,
1613
+ arg_types: Bogus[Sequence[Type]] = _dummy,
1614
+ arg_kinds: Bogus[list[ArgKind]] = _dummy,
1615
+ arg_names: Bogus[Sequence[str | None]] = _dummy,
1616
+ *,
1617
+ variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,
1618
+ is_ellipsis_args: Bogus[bool] = _dummy,
1619
+ imprecise_arg_kinds: Bogus[bool] = _dummy,
1620
+ ) -> Parameters:
1621
+ return Parameters(
1622
+ arg_types=arg_types if arg_types is not _dummy else self.arg_types,
1623
+ arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,
1624
+ arg_names=arg_names if arg_names is not _dummy else self.arg_names,
1625
+ is_ellipsis_args=(
1626
+ is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args
1627
+ ),
1628
+ variables=variables if variables is not _dummy else self.variables,
1629
+ imprecise_arg_kinds=(
1630
+ imprecise_arg_kinds
1631
+ if imprecise_arg_kinds is not _dummy
1632
+ else self.imprecise_arg_kinds
1633
+ ),
1634
+ )
1635
+
1636
+ # TODO: here is a lot of code duplication with Callable type, fix this.
1637
+ def var_arg(self) -> FormalArgument | None:
1638
+ """The formal argument for *args."""
1639
+ for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1640
+ if kind == ARG_STAR:
1641
+ return FormalArgument(None, position, type, False)
1642
+ return None
1643
+
1644
+ def kw_arg(self) -> FormalArgument | None:
1645
+ """The formal argument for **kwargs."""
1646
+ for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1647
+ if kind == ARG_STAR2:
1648
+ return FormalArgument(None, position, type, False)
1649
+ return None
1650
+
1651
+ def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:
1652
+ """Yields the formal arguments corresponding to this callable, ignoring *arg and **kwargs.
1653
+
1654
+ To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,
1655
+ if they are not None.
1656
+
1657
+ If you really want to include star args in the yielded output, set the
1658
+ 'include_star_args' parameter to 'True'."""
1659
+ args = []
1660
+ done_with_positional = False
1661
+ for i in range(len(self.arg_types)):
1662
+ kind = self.arg_kinds[i]
1663
+ if kind.is_named() or kind.is_star():
1664
+ done_with_positional = True
1665
+ if not include_star_args and kind.is_star():
1666
+ continue
1667
+
1668
+ required = kind.is_required()
1669
+ pos = None if done_with_positional else i
1670
+ arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)
1671
+ args.append(arg)
1672
+ return args
1673
+
1674
+ def argument_by_name(self, name: str | None) -> FormalArgument | None:
1675
+ if name is None:
1676
+ return None
1677
+ seen_star = False
1678
+ for i, (arg_name, kind, typ) in enumerate(
1679
+ zip(self.arg_names, self.arg_kinds, self.arg_types)
1680
+ ):
1681
+ # No more positional arguments after these.
1682
+ if kind.is_named() or kind.is_star():
1683
+ seen_star = True
1684
+ if kind.is_star():
1685
+ continue
1686
+ if arg_name == name:
1687
+ position = None if seen_star else i
1688
+ return FormalArgument(name, position, typ, kind.is_required())
1689
+ return self.try_synthesizing_arg_from_kwarg(name)
1690
+
1691
+ def argument_by_position(self, position: int | None) -> FormalArgument | None:
1692
+ if position is None:
1693
+ return None
1694
+ if position >= len(self.arg_names):
1695
+ return self.try_synthesizing_arg_from_vararg(position)
1696
+ name, kind, typ = (
1697
+ self.arg_names[position],
1698
+ self.arg_kinds[position],
1699
+ self.arg_types[position],
1700
+ )
1701
+ if kind.is_positional():
1702
+ return FormalArgument(name, position, typ, kind == ARG_POS)
1703
+ else:
1704
+ return self.try_synthesizing_arg_from_vararg(position)
1705
+
1706
+ def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:
1707
+ kw_arg = self.kw_arg()
1708
+ if kw_arg is not None:
1709
+ return FormalArgument(name, None, kw_arg.typ, False)
1710
+ else:
1711
+ return None
1712
+
1713
+ def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:
1714
+ var_arg = self.var_arg()
1715
+ if var_arg is not None:
1716
+ return FormalArgument(None, position, var_arg.typ, False)
1717
+ else:
1718
+ return None
1719
+
1720
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1721
+ return visitor.visit_parameters(self)
1722
+
1723
+ def serialize(self) -> JsonDict:
1724
+ return {
1725
+ ".class": "Parameters",
1726
+ "arg_types": [t.serialize() for t in self.arg_types],
1727
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
1728
+ "arg_names": self.arg_names,
1729
+ "variables": [tv.serialize() for tv in self.variables],
1730
+ "imprecise_arg_kinds": self.imprecise_arg_kinds,
1731
+ }
1732
+
1733
+ @classmethod
1734
+ def deserialize(cls, data: JsonDict) -> Parameters:
1735
+ assert data[".class"] == "Parameters"
1736
+ return Parameters(
1737
+ [deserialize_type(t) for t in data["arg_types"]],
1738
+ [ArgKind(x) for x in data["arg_kinds"]],
1739
+ data["arg_names"],
1740
+ variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]],
1741
+ imprecise_arg_kinds=data["imprecise_arg_kinds"],
1742
+ )
1743
+
1744
+ def __hash__(self) -> int:
1745
+ return hash(
1746
+ (
1747
+ self.is_ellipsis_args,
1748
+ tuple(self.arg_types),
1749
+ tuple(self.arg_names),
1750
+ tuple(self.arg_kinds),
1751
+ )
1752
+ )
1753
+
1754
+ def __eq__(self, other: object) -> bool:
1755
+ if isinstance(other, (Parameters, CallableType)):
1756
+ return (
1757
+ self.arg_types == other.arg_types
1758
+ and self.arg_names == other.arg_names
1759
+ and self.arg_kinds == other.arg_kinds
1760
+ and self.is_ellipsis_args == other.is_ellipsis_args
1761
+ )
1762
+ else:
1763
+ return NotImplemented
1764
+
1765
+
1766
+ CT = TypeVar("CT", bound="CallableType")
1767
+
1768
+
1769
+ class CallableType(FunctionLike):
1770
+ """Type of a non-overloaded callable object (such as function)."""
1771
+
1772
+ __slots__ = (
1773
+ "arg_types", # Types of function arguments
1774
+ "arg_kinds", # ARG_ constants
1775
+ "arg_names", # Argument names; None if not a keyword argument
1776
+ "min_args", # Minimum number of arguments; derived from arg_kinds
1777
+ "ret_type", # Return value type
1778
+ "name", # Name (may be None; for error messages and plugins)
1779
+ "definition", # For error messages. May be None.
1780
+ "variables", # Type variables for a generic function
1781
+ "is_ellipsis_args", # Is this Callable[..., t] (with literal '...')?
1782
+ "implicit", # Was this type implicitly generated instead of explicitly
1783
+ # specified by the user?
1784
+ "special_sig", # Non-None for signatures that require special handling
1785
+ # (currently only value is 'dict' for a signature similar to
1786
+ # 'dict')
1787
+ "from_type_type", # Was this callable generated by analyzing Type[...]
1788
+ # instantiation?
1789
+ "bound_args", # Bound type args, mostly unused but may be useful for
1790
+ # tools that consume mypy ASTs
1791
+ "def_extras", # Information about original definition we want to serialize.
1792
+ # This is used for more detailed error messages.
1793
+ "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case).
1794
+ "from_concatenate", # whether this callable is from a concatenate object
1795
+ # (this is used for error messages)
1796
+ "imprecise_arg_kinds",
1797
+ "unpack_kwargs", # Was an Unpack[...] with **kwargs used to define this callable?
1798
+ )
1799
+
1800
+ def __init__(
1801
+ self,
1802
+ # maybe this should be refactored to take a Parameters object
1803
+ arg_types: Sequence[Type],
1804
+ arg_kinds: list[ArgKind],
1805
+ arg_names: Sequence[str | None],
1806
+ ret_type: Type,
1807
+ fallback: Instance,
1808
+ name: str | None = None,
1809
+ definition: SymbolNode | None = None,
1810
+ variables: Sequence[TypeVarLikeType] | None = None,
1811
+ line: int = -1,
1812
+ column: int = -1,
1813
+ is_ellipsis_args: bool = False,
1814
+ implicit: bool = False,
1815
+ special_sig: str | None = None,
1816
+ from_type_type: bool = False,
1817
+ bound_args: Sequence[Type | None] = (),
1818
+ def_extras: dict[str, Any] | None = None,
1819
+ type_guard: Type | None = None,
1820
+ from_concatenate: bool = False,
1821
+ imprecise_arg_kinds: bool = False,
1822
+ unpack_kwargs: bool = False,
1823
+ ) -> None:
1824
+ super().__init__(line, column)
1825
+ assert len(arg_types) == len(arg_kinds) == len(arg_names)
1826
+ for t, k in zip(arg_types, arg_kinds):
1827
+ if isinstance(t, ParamSpecType):
1828
+ assert not t.prefix.arg_types
1829
+ # TODO: should we assert that only ARG_STAR contain ParamSpecType?
1830
+ # See testParamSpecJoin, that relies on passing e.g `P.args` as plain argument.
1831
+ if variables is None:
1832
+ variables = []
1833
+ self.arg_types = list(arg_types)
1834
+ self.arg_kinds = arg_kinds
1835
+ self.arg_names = list(arg_names)
1836
+ self.min_args = arg_kinds.count(ARG_POS)
1837
+ self.ret_type = ret_type
1838
+ self.fallback = fallback
1839
+ assert not name or "<bound method" not in name
1840
+ self.name = name
1841
+ self.definition = definition
1842
+ self.variables = variables
1843
+ self.is_ellipsis_args = is_ellipsis_args
1844
+ self.implicit = implicit
1845
+ self.special_sig = special_sig
1846
+ self.from_type_type = from_type_type
1847
+ self.from_concatenate = from_concatenate
1848
+ self.imprecise_arg_kinds = imprecise_arg_kinds
1849
+ if not bound_args:
1850
+ bound_args = ()
1851
+ self.bound_args = bound_args
1852
+ if def_extras:
1853
+ self.def_extras = def_extras
1854
+ elif isinstance(definition, FuncDef):
1855
+ # This information would be lost if we don't have definition
1856
+ # after serialization, but it is useful in error messages.
1857
+ # TODO: decide how to add more info here (file, line, column)
1858
+ # without changing interface hash.
1859
+ first_arg: str | None = None
1860
+ if definition.arg_names and definition.info and not definition.is_static:
1861
+ if getattr(definition, "arguments", None):
1862
+ first_arg = definition.arguments[0].variable.name
1863
+ else:
1864
+ first_arg = definition.arg_names[0]
1865
+ self.def_extras = {"first_arg": first_arg}
1866
+ else:
1867
+ self.def_extras = {}
1868
+ self.type_guard = type_guard
1869
+ self.unpack_kwargs = unpack_kwargs
1870
+
1871
+ def copy_modified(
1872
+ self: CT,
1873
+ arg_types: Bogus[Sequence[Type]] = _dummy,
1874
+ arg_kinds: Bogus[list[ArgKind]] = _dummy,
1875
+ arg_names: Bogus[Sequence[str | None]] = _dummy,
1876
+ ret_type: Bogus[Type] = _dummy,
1877
+ fallback: Bogus[Instance] = _dummy,
1878
+ name: Bogus[str | None] = _dummy,
1879
+ definition: Bogus[SymbolNode] = _dummy,
1880
+ variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,
1881
+ line: int = _dummy_int,
1882
+ column: int = _dummy_int,
1883
+ is_ellipsis_args: Bogus[bool] = _dummy,
1884
+ implicit: Bogus[bool] = _dummy,
1885
+ special_sig: Bogus[str | None] = _dummy,
1886
+ from_type_type: Bogus[bool] = _dummy,
1887
+ bound_args: Bogus[list[Type | None]] = _dummy,
1888
+ def_extras: Bogus[dict[str, Any]] = _dummy,
1889
+ type_guard: Bogus[Type | None] = _dummy,
1890
+ from_concatenate: Bogus[bool] = _dummy,
1891
+ imprecise_arg_kinds: Bogus[bool] = _dummy,
1892
+ unpack_kwargs: Bogus[bool] = _dummy,
1893
+ ) -> CT:
1894
+ modified = CallableType(
1895
+ arg_types=arg_types if arg_types is not _dummy else self.arg_types,
1896
+ arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,
1897
+ arg_names=arg_names if arg_names is not _dummy else self.arg_names,
1898
+ ret_type=ret_type if ret_type is not _dummy else self.ret_type,
1899
+ fallback=fallback if fallback is not _dummy else self.fallback,
1900
+ name=name if name is not _dummy else self.name,
1901
+ definition=definition if definition is not _dummy else self.definition,
1902
+ variables=variables if variables is not _dummy else self.variables,
1903
+ line=line if line != _dummy_int else self.line,
1904
+ column=column if column != _dummy_int else self.column,
1905
+ is_ellipsis_args=(
1906
+ is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args
1907
+ ),
1908
+ implicit=implicit if implicit is not _dummy else self.implicit,
1909
+ special_sig=special_sig if special_sig is not _dummy else self.special_sig,
1910
+ from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type,
1911
+ bound_args=bound_args if bound_args is not _dummy else self.bound_args,
1912
+ def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),
1913
+ type_guard=type_guard if type_guard is not _dummy else self.type_guard,
1914
+ from_concatenate=(
1915
+ from_concatenate if from_concatenate is not _dummy else self.from_concatenate
1916
+ ),
1917
+ imprecise_arg_kinds=(
1918
+ imprecise_arg_kinds
1919
+ if imprecise_arg_kinds is not _dummy
1920
+ else self.imprecise_arg_kinds
1921
+ ),
1922
+ unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs,
1923
+ )
1924
+ # Optimization: Only NewTypes are supported as subtypes since
1925
+ # the class is effectively final, so we can use a cast safely.
1926
+ return cast(CT, modified)
1927
+
1928
+ def var_arg(self) -> FormalArgument | None:
1929
+ """The formal argument for *args."""
1930
+ for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1931
+ if kind == ARG_STAR:
1932
+ return FormalArgument(None, position, type, False)
1933
+ return None
1934
+
1935
+ def kw_arg(self) -> FormalArgument | None:
1936
+ """The formal argument for **kwargs."""
1937
+ for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1938
+ if kind == ARG_STAR2:
1939
+ return FormalArgument(None, position, type, False)
1940
+ return None
1941
+
1942
+ @property
1943
+ def is_var_arg(self) -> bool:
1944
+ """Does this callable have a *args argument?"""
1945
+ return ARG_STAR in self.arg_kinds
1946
+
1947
+ @property
1948
+ def is_kw_arg(self) -> bool:
1949
+ """Does this callable have a **kwargs argument?"""
1950
+ return ARG_STAR2 in self.arg_kinds
1951
+
1952
+ def is_type_obj(self) -> bool:
1953
+ return self.fallback.type.is_metaclass() and not isinstance(
1954
+ get_proper_type(self.ret_type), UninhabitedType
1955
+ )
1956
+
1957
+ def type_object(self) -> mypy.nodes.TypeInfo:
1958
+ assert self.is_type_obj()
1959
+ ret = get_proper_type(self.ret_type)
1960
+ if isinstance(ret, TypeVarType):
1961
+ ret = get_proper_type(ret.upper_bound)
1962
+ if isinstance(ret, TupleType):
1963
+ ret = ret.partial_fallback
1964
+ if isinstance(ret, TypedDictType):
1965
+ ret = ret.fallback
1966
+ assert isinstance(ret, Instance)
1967
+ return ret.type
1968
+
1969
+ def accept(self, visitor: TypeVisitor[T]) -> T:
1970
+ return visitor.visit_callable_type(self)
1971
+
1972
+ def with_name(self, name: str) -> CallableType:
1973
+ """Return a copy of this type with the specified name."""
1974
+ return self.copy_modified(ret_type=self.ret_type, name=name)
1975
+
1976
+ def get_name(self) -> str | None:
1977
+ return self.name
1978
+
1979
+ def max_possible_positional_args(self) -> int:
1980
+ """Returns maximum number of positional arguments this method could possibly accept.
1981
+
1982
+ This takes into account *arg and **kwargs but excludes keyword-only args."""
1983
+ if self.is_var_arg or self.is_kw_arg:
1984
+ return sys.maxsize
1985
+ return sum(kind.is_positional() for kind in self.arg_kinds)
1986
+
1987
+ def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:
1988
+ """Return a list of the formal arguments of this callable, ignoring *arg and **kwargs.
1989
+
1990
+ To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,
1991
+ if they are not None.
1992
+
1993
+ If you really want to include star args in the yielded output, set the
1994
+ 'include_star_args' parameter to 'True'."""
1995
+ args = []
1996
+ done_with_positional = False
1997
+ for i in range(len(self.arg_types)):
1998
+ kind = self.arg_kinds[i]
1999
+ if kind.is_named() or kind.is_star():
2000
+ done_with_positional = True
2001
+ if not include_star_args and kind.is_star():
2002
+ continue
2003
+
2004
+ required = kind.is_required()
2005
+ pos = None if done_with_positional else i
2006
+ arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)
2007
+ args.append(arg)
2008
+ return args
2009
+
2010
+ def argument_by_name(self, name: str | None) -> FormalArgument | None:
2011
+ if name is None:
2012
+ return None
2013
+ seen_star = False
2014
+ for i, (arg_name, kind, typ) in enumerate(
2015
+ zip(self.arg_names, self.arg_kinds, self.arg_types)
2016
+ ):
2017
+ # No more positional arguments after these.
2018
+ if kind.is_named() or kind.is_star():
2019
+ seen_star = True
2020
+ if kind.is_star():
2021
+ continue
2022
+ if arg_name == name:
2023
+ position = None if seen_star else i
2024
+ return FormalArgument(name, position, typ, kind.is_required())
2025
+ return self.try_synthesizing_arg_from_kwarg(name)
2026
+
2027
+ def argument_by_position(self, position: int | None) -> FormalArgument | None:
2028
+ if position is None:
2029
+ return None
2030
+ if position >= len(self.arg_names):
2031
+ return self.try_synthesizing_arg_from_vararg(position)
2032
+ name, kind, typ = (
2033
+ self.arg_names[position],
2034
+ self.arg_kinds[position],
2035
+ self.arg_types[position],
2036
+ )
2037
+ if kind.is_positional():
2038
+ return FormalArgument(name, position, typ, kind == ARG_POS)
2039
+ else:
2040
+ return self.try_synthesizing_arg_from_vararg(position)
2041
+
2042
+ def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:
2043
+ kw_arg = self.kw_arg()
2044
+ if kw_arg is not None:
2045
+ return FormalArgument(name, None, kw_arg.typ, False)
2046
+ else:
2047
+ return None
2048
+
2049
+ def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:
2050
+ var_arg = self.var_arg()
2051
+ if var_arg is not None:
2052
+ return FormalArgument(None, position, var_arg.typ, False)
2053
+ else:
2054
+ return None
2055
+
2056
+ @property
2057
+ def items(self) -> list[CallableType]:
2058
+ return [self]
2059
+
2060
+ def is_generic(self) -> bool:
2061
+ return bool(self.variables)
2062
+
2063
+ def type_var_ids(self) -> list[TypeVarId]:
2064
+ a: list[TypeVarId] = []
2065
+ for tv in self.variables:
2066
+ a.append(tv.id)
2067
+ return a
2068
+
2069
+ def param_spec(self) -> ParamSpecType | None:
2070
+ """Return ParamSpec if callable can be called with one.
2071
+
2072
+ A Callable accepting ParamSpec P args (*args, **kwargs) must have the
2073
+ two final parameters like this: *args: P.args, **kwargs: P.kwargs.
2074
+ """
2075
+ if len(self.arg_types) < 2:
2076
+ return None
2077
+ if self.arg_kinds[-2] != ARG_STAR or self.arg_kinds[-1] != ARG_STAR2:
2078
+ return None
2079
+ arg_type = self.arg_types[-2]
2080
+ if not isinstance(arg_type, ParamSpecType):
2081
+ return None
2082
+
2083
+ # Prepend prefix for def f(prefix..., *args: P.args, **kwargs: P.kwargs) -> ...
2084
+ # TODO: confirm that all arg kinds are positional
2085
+ prefix = Parameters(self.arg_types[:-2], self.arg_kinds[:-2], self.arg_names[:-2])
2086
+ return arg_type.copy_modified(flavor=ParamSpecFlavor.BARE, prefix=prefix)
2087
+
2088
+ def with_unpacked_kwargs(self) -> NormalizedCallableType:
2089
+ if not self.unpack_kwargs:
2090
+ return cast(NormalizedCallableType, self)
2091
+ last_type = get_proper_type(self.arg_types[-1])
2092
+ assert isinstance(last_type, TypedDictType)
2093
+ extra_kinds = [
2094
+ ArgKind.ARG_NAMED if name in last_type.required_keys else ArgKind.ARG_NAMED_OPT
2095
+ for name in last_type.items
2096
+ ]
2097
+ new_arg_kinds = self.arg_kinds[:-1] + extra_kinds
2098
+ new_arg_names = self.arg_names[:-1] + list(last_type.items)
2099
+ new_arg_types = self.arg_types[:-1] + list(last_type.items.values())
2100
+ return NormalizedCallableType(
2101
+ self.copy_modified(
2102
+ arg_kinds=new_arg_kinds,
2103
+ arg_names=new_arg_names,
2104
+ arg_types=new_arg_types,
2105
+ unpack_kwargs=False,
2106
+ )
2107
+ )
2108
+
2109
+ def with_normalized_var_args(self) -> Self:
2110
+ var_arg = self.var_arg()
2111
+ if not var_arg or not isinstance(var_arg.typ, UnpackType):
2112
+ return self
2113
+ unpacked = get_proper_type(var_arg.typ.type)
2114
+ if not isinstance(unpacked, TupleType):
2115
+ # Note that we don't normalize *args: *tuple[X, ...] -> *args: X,
2116
+ # this should be done once in semanal_typeargs.py for user-defined types,
2117
+ # and we ourselves should never construct such type.
2118
+ return self
2119
+ unpack_index = find_unpack_in_list(unpacked.items)
2120
+ if unpack_index == 0 and len(unpacked.items) > 1:
2121
+ # Already normalized.
2122
+ return self
2123
+
2124
+ # Boilerplate:
2125
+ var_arg_index = self.arg_kinds.index(ARG_STAR)
2126
+ types_prefix = self.arg_types[:var_arg_index]
2127
+ kinds_prefix = self.arg_kinds[:var_arg_index]
2128
+ names_prefix = self.arg_names[:var_arg_index]
2129
+ types_suffix = self.arg_types[var_arg_index + 1 :]
2130
+ kinds_suffix = self.arg_kinds[var_arg_index + 1 :]
2131
+ names_suffix = self.arg_names[var_arg_index + 1 :]
2132
+ no_name: str | None = None # to silence mypy
2133
+
2134
+ # Now we have something non-trivial to do.
2135
+ if unpack_index is None:
2136
+ # Plain *Tuple[X, Y, Z] -> replace with ARG_POS completely
2137
+ types_middle = unpacked.items
2138
+ kinds_middle = [ARG_POS] * len(unpacked.items)
2139
+ names_middle = [no_name] * len(unpacked.items)
2140
+ else:
2141
+ # *Tuple[X, *Ts, Y, Z] or *Tuple[X, *tuple[T, ...], X, Z], here
2142
+ # we replace the prefix by ARG_POS (this is how some places expect
2143
+ # Callables to be represented)
2144
+ nested_unpack = unpacked.items[unpack_index]
2145
+ assert isinstance(nested_unpack, UnpackType)
2146
+ nested_unpacked = get_proper_type(nested_unpack.type)
2147
+ if unpack_index == len(unpacked.items) - 1:
2148
+ # Normalize also single item tuples like
2149
+ # *args: *Tuple[*tuple[X, ...]] -> *args: X
2150
+ # *args: *Tuple[*Ts] -> *args: *Ts
2151
+ # This may be not strictly necessary, but these are very verbose.
2152
+ if isinstance(nested_unpacked, Instance):
2153
+ assert nested_unpacked.type.fullname == "builtins.tuple"
2154
+ new_unpack = nested_unpacked.args[0]
2155
+ else:
2156
+ if not isinstance(nested_unpacked, TypeVarTupleType):
2157
+ # We found a non-nomralized tuple type, this means this method
2158
+ # is called during semantic analysis (e.g. from get_proper_type())
2159
+ # there is no point in normalizing callables at this stage.
2160
+ return self
2161
+ new_unpack = nested_unpack
2162
+ else:
2163
+ new_unpack = UnpackType(
2164
+ unpacked.copy_modified(items=unpacked.items[unpack_index:])
2165
+ )
2166
+ types_middle = unpacked.items[:unpack_index] + [new_unpack]
2167
+ kinds_middle = [ARG_POS] * unpack_index + [ARG_STAR]
2168
+ names_middle = [no_name] * unpack_index + [self.arg_names[var_arg_index]]
2169
+ return self.copy_modified(
2170
+ arg_types=types_prefix + types_middle + types_suffix,
2171
+ arg_kinds=kinds_prefix + kinds_middle + kinds_suffix,
2172
+ arg_names=names_prefix + names_middle + names_suffix,
2173
+ )
2174
+
2175
+ def __hash__(self) -> int:
2176
+ # self.is_type_obj() will fail if self.fallback.type is a FakeInfo
2177
+ if isinstance(self.fallback.type, FakeInfo):
2178
+ is_type_obj = 2
2179
+ else:
2180
+ is_type_obj = self.is_type_obj()
2181
+ return hash(
2182
+ (
2183
+ self.ret_type,
2184
+ is_type_obj,
2185
+ self.is_ellipsis_args,
2186
+ self.name,
2187
+ tuple(self.arg_types),
2188
+ tuple(self.arg_names),
2189
+ tuple(self.arg_kinds),
2190
+ self.fallback,
2191
+ )
2192
+ )
2193
+
2194
+ def __eq__(self, other: object) -> bool:
2195
+ if isinstance(other, CallableType):
2196
+ return (
2197
+ self.ret_type == other.ret_type
2198
+ and self.arg_types == other.arg_types
2199
+ and self.arg_names == other.arg_names
2200
+ and self.arg_kinds == other.arg_kinds
2201
+ and self.name == other.name
2202
+ and self.is_type_obj() == other.is_type_obj()
2203
+ and self.is_ellipsis_args == other.is_ellipsis_args
2204
+ and self.fallback == other.fallback
2205
+ )
2206
+ else:
2207
+ return NotImplemented
2208
+
2209
+ def serialize(self) -> JsonDict:
2210
+ # TODO: As an optimization, leave out everything related to
2211
+ # generic functions for non-generic functions.
2212
+ return {
2213
+ ".class": "CallableType",
2214
+ "arg_types": [t.serialize() for t in self.arg_types],
2215
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
2216
+ "arg_names": self.arg_names,
2217
+ "ret_type": self.ret_type.serialize(),
2218
+ "fallback": self.fallback.serialize(),
2219
+ "name": self.name,
2220
+ # We don't serialize the definition (only used for error messages).
2221
+ "variables": [v.serialize() for v in self.variables],
2222
+ "is_ellipsis_args": self.is_ellipsis_args,
2223
+ "implicit": self.implicit,
2224
+ "bound_args": [(None if t is None else t.serialize()) for t in self.bound_args],
2225
+ "def_extras": dict(self.def_extras),
2226
+ "type_guard": self.type_guard.serialize() if self.type_guard is not None else None,
2227
+ "from_concatenate": self.from_concatenate,
2228
+ "imprecise_arg_kinds": self.imprecise_arg_kinds,
2229
+ "unpack_kwargs": self.unpack_kwargs,
2230
+ }
2231
+
2232
+ @classmethod
2233
+ def deserialize(cls, data: JsonDict) -> CallableType:
2234
+ assert data[".class"] == "CallableType"
2235
+ # TODO: Set definition to the containing SymbolNode?
2236
+ return CallableType(
2237
+ [deserialize_type(t) for t in data["arg_types"]],
2238
+ [ArgKind(x) for x in data["arg_kinds"]],
2239
+ data["arg_names"],
2240
+ deserialize_type(data["ret_type"]),
2241
+ Instance.deserialize(data["fallback"]),
2242
+ name=data["name"],
2243
+ variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]],
2244
+ is_ellipsis_args=data["is_ellipsis_args"],
2245
+ implicit=data["implicit"],
2246
+ bound_args=[(None if t is None else deserialize_type(t)) for t in data["bound_args"]],
2247
+ def_extras=data["def_extras"],
2248
+ type_guard=(
2249
+ deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None
2250
+ ),
2251
+ from_concatenate=data["from_concatenate"],
2252
+ imprecise_arg_kinds=data["imprecise_arg_kinds"],
2253
+ unpack_kwargs=data["unpack_kwargs"],
2254
+ )
2255
+
2256
+
2257
+ # This is a little safety net to prevent reckless special-casing of callables
2258
+ # that can potentially break Unpack[...] with **kwargs.
2259
+ # TODO: use this in more places in checkexpr.py etc?
2260
+ NormalizedCallableType = NewType("NormalizedCallableType", CallableType)
2261
+
2262
+
2263
+ class Overloaded(FunctionLike):
2264
+ """Overloaded function type T1, ... Tn, where each Ti is CallableType.
2265
+
2266
+ The variant to call is chosen based on static argument
2267
+ types. Overloaded function types can only be defined in stub
2268
+ files, and thus there is no explicit runtime dispatch
2269
+ implementation.
2270
+ """
2271
+
2272
+ __slots__ = ("_items",)
2273
+
2274
+ _items: list[CallableType] # Must not be empty
2275
+
2276
+ def __init__(self, items: list[CallableType]) -> None:
2277
+ super().__init__(items[0].line, items[0].column)
2278
+ self._items = items
2279
+ self.fallback = items[0].fallback
2280
+
2281
+ @property
2282
+ def items(self) -> list[CallableType]:
2283
+ return self._items
2284
+
2285
+ def name(self) -> str | None:
2286
+ return self.get_name()
2287
+
2288
+ def is_type_obj(self) -> bool:
2289
+ # All the items must have the same type object status, so it's
2290
+ # sufficient to query only (any) one of them.
2291
+ return self._items[0].is_type_obj()
2292
+
2293
+ def type_object(self) -> mypy.nodes.TypeInfo:
2294
+ # All the items must have the same type object, so it's sufficient to
2295
+ # query only (any) one of them.
2296
+ return self._items[0].type_object()
2297
+
2298
+ def with_name(self, name: str) -> Overloaded:
2299
+ ni: list[CallableType] = []
2300
+ for it in self._items:
2301
+ ni.append(it.with_name(name))
2302
+ return Overloaded(ni)
2303
+
2304
+ def get_name(self) -> str | None:
2305
+ return self._items[0].name
2306
+
2307
+ def with_unpacked_kwargs(self) -> Overloaded:
2308
+ if any(i.unpack_kwargs for i in self.items):
2309
+ return Overloaded([i.with_unpacked_kwargs() for i in self.items])
2310
+ return self
2311
+
2312
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2313
+ return visitor.visit_overloaded(self)
2314
+
2315
+ def __hash__(self) -> int:
2316
+ return hash(tuple(self.items))
2317
+
2318
+ def __eq__(self, other: object) -> bool:
2319
+ if not isinstance(other, Overloaded):
2320
+ return NotImplemented
2321
+ return self.items == other.items
2322
+
2323
+ def serialize(self) -> JsonDict:
2324
+ return {".class": "Overloaded", "items": [t.serialize() for t in self.items]}
2325
+
2326
+ @classmethod
2327
+ def deserialize(cls, data: JsonDict) -> Overloaded:
2328
+ assert data[".class"] == "Overloaded"
2329
+ return Overloaded([CallableType.deserialize(t) for t in data["items"]])
2330
+
2331
+
2332
+ class TupleType(ProperType):
2333
+ """The tuple type Tuple[T1, ..., Tn] (at least one type argument).
2334
+
2335
+ Instance variables:
2336
+ items: Tuple item types
2337
+ partial_fallback: The (imprecise) underlying instance type that is used
2338
+ for non-tuple methods. This is generally builtins.tuple[Any, ...] for
2339
+ regular tuples, but it's different for named tuples and classes with
2340
+ a tuple base class. Use mypy.typeops.tuple_fallback to calculate the
2341
+ precise fallback type derived from item types.
2342
+ implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...]
2343
+ """
2344
+
2345
+ __slots__ = ("items", "partial_fallback", "implicit")
2346
+
2347
+ items: list[Type]
2348
+ partial_fallback: Instance
2349
+ implicit: bool
2350
+
2351
+ def __init__(
2352
+ self,
2353
+ items: list[Type],
2354
+ fallback: Instance,
2355
+ line: int = -1,
2356
+ column: int = -1,
2357
+ implicit: bool = False,
2358
+ ) -> None:
2359
+ super().__init__(line, column)
2360
+ self.partial_fallback = fallback
2361
+ self.items = items
2362
+ self.implicit = implicit
2363
+
2364
+ def can_be_true_default(self) -> bool:
2365
+ if self.can_be_any_bool():
2366
+ # Corner case: it is a `NamedTuple` with `__bool__` method defined.
2367
+ # It can be anything: both `True` and `False`.
2368
+ return True
2369
+ return self.length() > 0
2370
+
2371
+ def can_be_false_default(self) -> bool:
2372
+ if self.can_be_any_bool():
2373
+ # Corner case: it is a `NamedTuple` with `__bool__` method defined.
2374
+ # It can be anything: both `True` and `False`.
2375
+ return True
2376
+ if self.length() == 0:
2377
+ return True
2378
+ if self.length() > 1:
2379
+ return False
2380
+ # Special case tuple[*Ts] may or may not be false.
2381
+ item = self.items[0]
2382
+ if not isinstance(item, UnpackType):
2383
+ return False
2384
+ if not isinstance(item.type, TypeVarTupleType):
2385
+ # Non-normalized tuple[int, ...] can be false.
2386
+ return True
2387
+ return item.type.min_len == 0
2388
+
2389
+ def can_be_any_bool(self) -> bool:
2390
+ return bool(
2391
+ self.partial_fallback.type
2392
+ and self.partial_fallback.type.fullname != "builtins.tuple"
2393
+ and self.partial_fallback.type.names.get("__bool__")
2394
+ )
2395
+
2396
+ def length(self) -> int:
2397
+ return len(self.items)
2398
+
2399
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2400
+ return visitor.visit_tuple_type(self)
2401
+
2402
+ def __hash__(self) -> int:
2403
+ return hash((tuple(self.items), self.partial_fallback))
2404
+
2405
+ def __eq__(self, other: object) -> bool:
2406
+ if not isinstance(other, TupleType):
2407
+ return NotImplemented
2408
+ return self.items == other.items and self.partial_fallback == other.partial_fallback
2409
+
2410
+ def serialize(self) -> JsonDict:
2411
+ return {
2412
+ ".class": "TupleType",
2413
+ "items": [t.serialize() for t in self.items],
2414
+ "partial_fallback": self.partial_fallback.serialize(),
2415
+ "implicit": self.implicit,
2416
+ }
2417
+
2418
+ @classmethod
2419
+ def deserialize(cls, data: JsonDict) -> TupleType:
2420
+ assert data[".class"] == "TupleType"
2421
+ return TupleType(
2422
+ [deserialize_type(t) for t in data["items"]],
2423
+ Instance.deserialize(data["partial_fallback"]),
2424
+ implicit=data["implicit"],
2425
+ )
2426
+
2427
+ def copy_modified(
2428
+ self, *, fallback: Instance | None = None, items: list[Type] | None = None
2429
+ ) -> TupleType:
2430
+ if fallback is None:
2431
+ fallback = self.partial_fallback
2432
+ if items is None:
2433
+ items = self.items
2434
+ return TupleType(items, fallback, self.line, self.column)
2435
+
2436
+ def slice(
2437
+ self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None
2438
+ ) -> TupleType | None:
2439
+ if fallback is None:
2440
+ fallback = self.partial_fallback
2441
+
2442
+ if any(isinstance(t, UnpackType) for t in self.items):
2443
+ total = len(self.items)
2444
+ unpack_index = find_unpack_in_list(self.items)
2445
+ assert unpack_index is not None
2446
+ if begin is None and end is None:
2447
+ # We special-case this to support reversing variadic tuples.
2448
+ # General support for slicing is tricky, so we handle only simple cases.
2449
+ if stride == -1:
2450
+ slice_items = self.items[::-1]
2451
+ elif stride is None or stride == 1:
2452
+ slice_items = self.items
2453
+ else:
2454
+ return None
2455
+ elif (begin is None or unpack_index >= begin >= 0) and (
2456
+ end is not None and unpack_index >= end >= 0
2457
+ ):
2458
+ # Start and end are in the prefix, everything works in this case.
2459
+ slice_items = self.items[begin:end:stride]
2460
+ elif (begin is not None and unpack_index - total < begin < 0) and (
2461
+ end is None or unpack_index - total < end < 0
2462
+ ):
2463
+ # Start and end are in the suffix, everything works in this case.
2464
+ slice_items = self.items[begin:end:stride]
2465
+ elif (begin is None or unpack_index >= begin >= 0) and (
2466
+ end is None or unpack_index - total < end < 0
2467
+ ):
2468
+ # Start in the prefix, end in the suffix, we can support only trivial strides.
2469
+ if stride is None or stride == 1:
2470
+ slice_items = self.items[begin:end:stride]
2471
+ else:
2472
+ return None
2473
+ elif (begin is not None and unpack_index - total < begin < 0) and (
2474
+ end is not None and unpack_index >= end >= 0
2475
+ ):
2476
+ # Start in the suffix, end in the prefix, we can support only trivial strides.
2477
+ if stride is None or stride == -1:
2478
+ slice_items = self.items[begin:end:stride]
2479
+ else:
2480
+ return None
2481
+ else:
2482
+ # TODO: there some additional cases we can support for homogeneous variadic
2483
+ # items, we can "eat away" finite number of items.
2484
+ return None
2485
+ else:
2486
+ slice_items = self.items[begin:end:stride]
2487
+ return TupleType(slice_items, fallback, self.line, self.column, self.implicit)
2488
+
2489
+
2490
+ class TypedDictType(ProperType):
2491
+ """Type of TypedDict object {'k1': v1, ..., 'kn': vn}.
2492
+
2493
+ A TypedDict object is a dictionary with specific string (literal) keys. Each
2494
+ key has a value with a distinct type that depends on the key. TypedDict objects
2495
+ are normal dict objects at runtime.
2496
+
2497
+ A TypedDictType can be either named or anonymous. If it's anonymous, its
2498
+ fallback will be typing_extensions._TypedDict (Instance). _TypedDict is a subclass
2499
+ of Mapping[str, object] and defines all non-mapping dict methods that TypedDict
2500
+ supports. Some dict methods are unsafe and not supported. _TypedDict isn't defined
2501
+ at runtime.
2502
+
2503
+ If a TypedDict is named, its fallback will be an Instance of the named type
2504
+ (ex: "Point") whose TypeInfo has a typeddict_type that is anonymous. This
2505
+ is similar to how named tuples work.
2506
+
2507
+ TODO: The fallback structure is perhaps overly complicated.
2508
+ """
2509
+
2510
+ __slots__ = ("items", "required_keys", "fallback")
2511
+
2512
+ items: dict[str, Type] # item_name -> item_type
2513
+ required_keys: set[str]
2514
+ fallback: Instance
2515
+
2516
+ def __init__(
2517
+ self,
2518
+ items: dict[str, Type],
2519
+ required_keys: set[str],
2520
+ fallback: Instance,
2521
+ line: int = -1,
2522
+ column: int = -1,
2523
+ ) -> None:
2524
+ super().__init__(line, column)
2525
+ self.items = items
2526
+ self.required_keys = required_keys
2527
+ self.fallback = fallback
2528
+ self.can_be_true = len(self.items) > 0
2529
+ self.can_be_false = len(self.required_keys) == 0
2530
+
2531
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2532
+ return visitor.visit_typeddict_type(self)
2533
+
2534
+ def __hash__(self) -> int:
2535
+ return hash((frozenset(self.items.items()), self.fallback, frozenset(self.required_keys)))
2536
+
2537
+ def __eq__(self, other: object) -> bool:
2538
+ if not isinstance(other, TypedDictType):
2539
+ return NotImplemented
2540
+
2541
+ return (
2542
+ frozenset(self.items.keys()) == frozenset(other.items.keys())
2543
+ and all(
2544
+ left_item_type == right_item_type
2545
+ for (_, left_item_type, right_item_type) in self.zip(other)
2546
+ )
2547
+ and self.fallback == other.fallback
2548
+ and self.required_keys == other.required_keys
2549
+ )
2550
+
2551
+ def serialize(self) -> JsonDict:
2552
+ return {
2553
+ ".class": "TypedDictType",
2554
+ "items": [[n, t.serialize()] for (n, t) in self.items.items()],
2555
+ "required_keys": sorted(self.required_keys),
2556
+ "fallback": self.fallback.serialize(),
2557
+ }
2558
+
2559
+ @classmethod
2560
+ def deserialize(cls, data: JsonDict) -> TypedDictType:
2561
+ assert data[".class"] == "TypedDictType"
2562
+ return TypedDictType(
2563
+ {n: deserialize_type(t) for (n, t) in data["items"]},
2564
+ set(data["required_keys"]),
2565
+ Instance.deserialize(data["fallback"]),
2566
+ )
2567
+
2568
+ @property
2569
+ def is_final(self) -> bool:
2570
+ return self.fallback.type.is_final
2571
+
2572
+ def is_anonymous(self) -> bool:
2573
+ return self.fallback.type.fullname in TPDICT_FB_NAMES
2574
+
2575
+ def as_anonymous(self) -> TypedDictType:
2576
+ if self.is_anonymous():
2577
+ return self
2578
+ assert self.fallback.type.typeddict_type is not None
2579
+ return self.fallback.type.typeddict_type.as_anonymous()
2580
+
2581
+ def copy_modified(
2582
+ self,
2583
+ *,
2584
+ fallback: Instance | None = None,
2585
+ item_types: list[Type] | None = None,
2586
+ item_names: list[str] | None = None,
2587
+ required_keys: set[str] | None = None,
2588
+ ) -> TypedDictType:
2589
+ if fallback is None:
2590
+ fallback = self.fallback
2591
+ if item_types is None:
2592
+ items = self.items
2593
+ else:
2594
+ items = dict(zip(self.items, item_types))
2595
+ if required_keys is None:
2596
+ required_keys = self.required_keys
2597
+ if item_names is not None:
2598
+ items = {k: v for (k, v) in items.items() if k in item_names}
2599
+ required_keys &= set(item_names)
2600
+ return TypedDictType(items, required_keys, fallback, self.line, self.column)
2601
+
2602
+ def create_anonymous_fallback(self) -> Instance:
2603
+ anonymous = self.as_anonymous()
2604
+ return anonymous.fallback
2605
+
2606
+ def names_are_wider_than(self, other: TypedDictType) -> bool:
2607
+ return len(other.items.keys() - self.items.keys()) == 0
2608
+
2609
+ def zip(self, right: TypedDictType) -> Iterable[tuple[str, Type, Type]]:
2610
+ left = self
2611
+ for item_name, left_item_type in left.items.items():
2612
+ right_item_type = right.items.get(item_name)
2613
+ if right_item_type is not None:
2614
+ yield (item_name, left_item_type, right_item_type)
2615
+
2616
+ def zipall(self, right: TypedDictType) -> Iterable[tuple[str, Type | None, Type | None]]:
2617
+ left = self
2618
+ for item_name, left_item_type in left.items.items():
2619
+ right_item_type = right.items.get(item_name)
2620
+ yield (item_name, left_item_type, right_item_type)
2621
+ for item_name, right_item_type in right.items.items():
2622
+ if item_name in left.items:
2623
+ continue
2624
+ yield (item_name, None, right_item_type)
2625
+
2626
+
2627
+ class RawExpressionType(ProperType):
2628
+ """A synthetic type representing some arbitrary expression that does not cleanly
2629
+ translate into a type.
2630
+
2631
+ This synthetic type is only used at the beginning stages of semantic analysis
2632
+ and should be completely removing during the process for mapping UnboundTypes to
2633
+ actual types: we either turn it into a LiteralType or an AnyType.
2634
+
2635
+ For example, suppose `Foo[1]` is initially represented as the following:
2636
+
2637
+ UnboundType(
2638
+ name='Foo',
2639
+ args=[
2640
+ RawExpressionType(value=1, base_type_name='builtins.int'),
2641
+ ],
2642
+ )
2643
+
2644
+ As we perform semantic analysis, this type will transform into one of two
2645
+ possible forms.
2646
+
2647
+ If 'Foo' was an alias for 'Literal' all along, this type is transformed into:
2648
+
2649
+ LiteralType(value=1, fallback=int_instance_here)
2650
+
2651
+ Alternatively, if 'Foo' is an unrelated class, we report an error and instead
2652
+ produce something like this:
2653
+
2654
+ Instance(type=typeinfo_for_foo, args=[AnyType(TypeOfAny.from_error))
2655
+
2656
+ If the "note" field is not None, the provided note will be reported alongside the
2657
+ error at this point.
2658
+
2659
+ Note: if "literal_value" is None, that means this object is representing some
2660
+ expression that cannot possibly be a parameter of Literal[...]. For example,
2661
+ "Foo[3j]" would be represented as:
2662
+
2663
+ UnboundType(
2664
+ name='Foo',
2665
+ args=[
2666
+ RawExpressionType(value=None, base_type_name='builtins.complex'),
2667
+ ],
2668
+ )
2669
+ """
2670
+
2671
+ __slots__ = ("literal_value", "base_type_name", "note")
2672
+
2673
+ def __init__(
2674
+ self,
2675
+ literal_value: LiteralValue | None,
2676
+ base_type_name: str,
2677
+ line: int = -1,
2678
+ column: int = -1,
2679
+ note: str | None = None,
2680
+ ) -> None:
2681
+ super().__init__(line, column)
2682
+ self.literal_value = literal_value
2683
+ self.base_type_name = base_type_name
2684
+ self.note = note
2685
+
2686
+ def simple_name(self) -> str:
2687
+ return self.base_type_name.replace("builtins.", "")
2688
+
2689
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2690
+ assert isinstance(visitor, SyntheticTypeVisitor)
2691
+ ret: T = visitor.visit_raw_expression_type(self)
2692
+ return ret
2693
+
2694
+ def serialize(self) -> JsonDict:
2695
+ assert False, "Synthetic types don't serialize"
2696
+
2697
+ def __hash__(self) -> int:
2698
+ return hash((self.literal_value, self.base_type_name))
2699
+
2700
+ def __eq__(self, other: object) -> bool:
2701
+ if isinstance(other, RawExpressionType):
2702
+ return (
2703
+ self.base_type_name == other.base_type_name
2704
+ and self.literal_value == other.literal_value
2705
+ )
2706
+ else:
2707
+ return NotImplemented
2708
+
2709
+
2710
+ class LiteralType(ProperType):
2711
+ """The type of a Literal instance. Literal[Value]
2712
+
2713
+ A Literal always consists of:
2714
+
2715
+ 1. A native Python object corresponding to the contained inner value
2716
+ 2. A fallback for this Literal. The fallback also corresponds to the
2717
+ parent type this Literal subtypes.
2718
+
2719
+ For example, 'Literal[42]' is represented as
2720
+ 'LiteralType(value=42, fallback=instance_of_int)'
2721
+
2722
+ As another example, `Literal[Color.RED]` (where Color is an enum) is
2723
+ represented as `LiteralType(value="RED", fallback=instance_of_color)'.
2724
+ """
2725
+
2726
+ __slots__ = ("value", "fallback", "_hash")
2727
+
2728
+ def __init__(
2729
+ self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1
2730
+ ) -> None:
2731
+ super().__init__(line, column)
2732
+ self.value = value
2733
+ self.fallback = fallback
2734
+ self._hash = -1 # Cached hash value
2735
+
2736
+ def can_be_false_default(self) -> bool:
2737
+ return not self.value
2738
+
2739
+ def can_be_true_default(self) -> bool:
2740
+ return bool(self.value)
2741
+
2742
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2743
+ return visitor.visit_literal_type(self)
2744
+
2745
+ def __hash__(self) -> int:
2746
+ if self._hash == -1:
2747
+ self._hash = hash((self.value, self.fallback))
2748
+ return self._hash
2749
+
2750
+ def __eq__(self, other: object) -> bool:
2751
+ if isinstance(other, LiteralType):
2752
+ return self.fallback == other.fallback and self.value == other.value
2753
+ else:
2754
+ return NotImplemented
2755
+
2756
+ def is_enum_literal(self) -> bool:
2757
+ return self.fallback.type.is_enum
2758
+
2759
+ def value_repr(self) -> str:
2760
+ """Returns the string representation of the underlying type.
2761
+
2762
+ This function is almost equivalent to running `repr(self.value)`,
2763
+ except it includes some additional logic to correctly handle cases
2764
+ where the value is a string, byte string, a unicode string, or an enum.
2765
+ """
2766
+ raw = repr(self.value)
2767
+ fallback_name = self.fallback.type.fullname
2768
+
2769
+ # If this is backed by an enum,
2770
+ if self.is_enum_literal():
2771
+ return f"{fallback_name}.{self.value}"
2772
+
2773
+ if fallback_name == "builtins.bytes":
2774
+ # Note: 'builtins.bytes' only appears in Python 3, so we want to
2775
+ # explicitly prefix with a "b"
2776
+ return "b" + raw
2777
+ else:
2778
+ # 'builtins.str' could mean either depending on context, but either way
2779
+ # we don't prefix: it's the "native" string. And of course, if value is
2780
+ # some other type, we just return that string repr directly.
2781
+ return raw
2782
+
2783
+ def serialize(self) -> JsonDict | str:
2784
+ return {
2785
+ ".class": "LiteralType",
2786
+ "value": self.value,
2787
+ "fallback": self.fallback.serialize(),
2788
+ }
2789
+
2790
+ @classmethod
2791
+ def deserialize(cls, data: JsonDict) -> LiteralType:
2792
+ assert data[".class"] == "LiteralType"
2793
+ return LiteralType(value=data["value"], fallback=Instance.deserialize(data["fallback"]))
2794
+
2795
+ def is_singleton_type(self) -> bool:
2796
+ return self.is_enum_literal() or isinstance(self.value, bool)
2797
+
2798
+
2799
+ class UnionType(ProperType):
2800
+ """The union type Union[T1, ..., Tn] (at least one type argument)."""
2801
+
2802
+ __slots__ = ("items", "is_evaluated", "uses_pep604_syntax")
2803
+
2804
+ def __init__(
2805
+ self,
2806
+ items: Sequence[Type],
2807
+ line: int = -1,
2808
+ column: int = -1,
2809
+ is_evaluated: bool = True,
2810
+ uses_pep604_syntax: bool = False,
2811
+ ) -> None:
2812
+ super().__init__(line, column)
2813
+ # We must keep this false to avoid crashes during semantic analysis.
2814
+ # TODO: maybe switch this to True during type-checking pass?
2815
+ self.items = flatten_nested_unions(items, handle_type_alias_type=False)
2816
+ # is_evaluated should be set to false for type comments and string literals
2817
+ self.is_evaluated = is_evaluated
2818
+ # uses_pep604_syntax is True if Union uses OR syntax (X | Y)
2819
+ self.uses_pep604_syntax = uses_pep604_syntax
2820
+
2821
+ def can_be_true_default(self) -> bool:
2822
+ return any(item.can_be_true for item in self.items)
2823
+
2824
+ def can_be_false_default(self) -> bool:
2825
+ return any(item.can_be_false for item in self.items)
2826
+
2827
+ def __hash__(self) -> int:
2828
+ return hash(frozenset(self.items))
2829
+
2830
+ def __eq__(self, other: object) -> bool:
2831
+ if not isinstance(other, UnionType):
2832
+ return NotImplemented
2833
+ return frozenset(self.items) == frozenset(other.items)
2834
+
2835
+ @overload
2836
+ @staticmethod
2837
+ def make_union(
2838
+ items: Sequence[ProperType], line: int = -1, column: int = -1
2839
+ ) -> ProperType: ...
2840
+
2841
+ @overload
2842
+ @staticmethod
2843
+ def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: ...
2844
+
2845
+ @staticmethod
2846
+ def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type:
2847
+ if len(items) > 1:
2848
+ return UnionType(items, line, column)
2849
+ elif len(items) == 1:
2850
+ return items[0]
2851
+ else:
2852
+ return UninhabitedType()
2853
+
2854
+ def length(self) -> int:
2855
+ return len(self.items)
2856
+
2857
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2858
+ return visitor.visit_union_type(self)
2859
+
2860
+ def relevant_items(self) -> list[Type]:
2861
+ """Removes NoneTypes from Unions when strict Optional checking is off."""
2862
+ if state.strict_optional:
2863
+ return self.items
2864
+ else:
2865
+ return [i for i in self.items if not isinstance(get_proper_type(i), NoneType)]
2866
+
2867
+ def serialize(self) -> JsonDict:
2868
+ return {".class": "UnionType", "items": [t.serialize() for t in self.items]}
2869
+
2870
+ @classmethod
2871
+ def deserialize(cls, data: JsonDict) -> UnionType:
2872
+ assert data[".class"] == "UnionType"
2873
+ return UnionType([deserialize_type(t) for t in data["items"]])
2874
+
2875
+
2876
+ class PartialType(ProperType):
2877
+ """Type such as List[?] where type arguments are unknown, or partial None type.
2878
+
2879
+ These are used for inferring types in multiphase initialization such as this:
2880
+
2881
+ x = [] # x gets a partial type List[?], as item type is unknown
2882
+ x.append(1) # partial type gets replaced with normal type List[int]
2883
+
2884
+ Or with None:
2885
+
2886
+ x = None # x gets a partial type None
2887
+ if c:
2888
+ x = 1 # Infer actual type int for x
2889
+ """
2890
+
2891
+ __slots__ = ("type", "var", "value_type")
2892
+
2893
+ # None for the 'None' partial type; otherwise a generic class
2894
+ type: mypy.nodes.TypeInfo | None
2895
+ var: mypy.nodes.Var
2896
+ # For partial defaultdict[K, V], the type V (K is unknown). If V is generic,
2897
+ # the type argument is Any and will be replaced later.
2898
+ value_type: Instance | None
2899
+
2900
+ def __init__(
2901
+ self,
2902
+ type: mypy.nodes.TypeInfo | None,
2903
+ var: mypy.nodes.Var,
2904
+ value_type: Instance | None = None,
2905
+ ) -> None:
2906
+ super().__init__()
2907
+ self.type = type
2908
+ self.var = var
2909
+ self.value_type = value_type
2910
+
2911
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2912
+ return visitor.visit_partial_type(self)
2913
+
2914
+
2915
+ class EllipsisType(ProperType):
2916
+ """The type ... (ellipsis).
2917
+
2918
+ This is not a real type but a syntactic AST construct, used in Callable[..., T], for example.
2919
+
2920
+ A semantically analyzed type will never have ellipsis types.
2921
+ """
2922
+
2923
+ __slots__ = ()
2924
+
2925
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2926
+ assert isinstance(visitor, SyntheticTypeVisitor)
2927
+ ret: T = visitor.visit_ellipsis_type(self)
2928
+ return ret
2929
+
2930
+ def serialize(self) -> JsonDict:
2931
+ assert False, "Synthetic types don't serialize"
2932
+
2933
+
2934
+ class TypeType(ProperType):
2935
+ """For types like Type[User].
2936
+
2937
+ This annotates variables that are class objects, constrained by
2938
+ the type argument. See PEP 484 for more details.
2939
+
2940
+ We may encounter expressions whose values are specific classes;
2941
+ those are represented as callables (possibly overloaded)
2942
+ corresponding to the class's constructor's signature and returning
2943
+ an instance of that class. The difference with Type[C] is that
2944
+ those callables always represent the exact class given as the
2945
+ return type; Type[C] represents any class that's a subclass of C,
2946
+ and C may also be a type variable or a union (or Any).
2947
+
2948
+ Many questions around subtype relationships between Type[C1] and
2949
+ def(...) -> C2 are answered by looking at the subtype
2950
+ relationships between C1 and C2, since Type[] is considered
2951
+ covariant.
2952
+
2953
+ There's an unsolved problem with constructor signatures (also
2954
+ unsolved in PEP 484): calling a variable whose type is Type[C]
2955
+ assumes the constructor signature for C, even though a subclass of
2956
+ C might completely change the constructor signature. For now we
2957
+ just assume that users of Type[C] are careful not to do that (in
2958
+ the future we might detect when they are violating that
2959
+ assumption).
2960
+ """
2961
+
2962
+ __slots__ = ("item",)
2963
+
2964
+ # This can't be everything, but it can be a class reference,
2965
+ # a generic class instance, a union, Any, a type variable...
2966
+ item: ProperType
2967
+
2968
+ def __init__(
2969
+ self,
2970
+ item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType],
2971
+ *,
2972
+ line: int = -1,
2973
+ column: int = -1,
2974
+ ) -> None:
2975
+ """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of
2976
+ type UnionType must be handled through make_normalized static method.
2977
+ """
2978
+ super().__init__(line, column)
2979
+ self.item = item
2980
+
2981
+ @staticmethod
2982
+ def make_normalized(item: Type, *, line: int = -1, column: int = -1) -> ProperType:
2983
+ item = get_proper_type(item)
2984
+ if isinstance(item, UnionType):
2985
+ return UnionType.make_union(
2986
+ [TypeType.make_normalized(union_item) for union_item in item.items],
2987
+ line=line,
2988
+ column=column,
2989
+ )
2990
+ return TypeType(item, line=line, column=column) # type: ignore[arg-type]
2991
+
2992
+ def accept(self, visitor: TypeVisitor[T]) -> T:
2993
+ return visitor.visit_type_type(self)
2994
+
2995
+ def __hash__(self) -> int:
2996
+ return hash(self.item)
2997
+
2998
+ def __eq__(self, other: object) -> bool:
2999
+ if not isinstance(other, TypeType):
3000
+ return NotImplemented
3001
+ return self.item == other.item
3002
+
3003
+ def serialize(self) -> JsonDict:
3004
+ return {".class": "TypeType", "item": self.item.serialize()}
3005
+
3006
+ @classmethod
3007
+ def deserialize(cls, data: JsonDict) -> Type:
3008
+ assert data[".class"] == "TypeType"
3009
+ return TypeType.make_normalized(deserialize_type(data["item"]))
3010
+
3011
+
3012
+ class PlaceholderType(ProperType):
3013
+ """Temporary, yet-unknown type during semantic analysis.
3014
+
3015
+ This is needed when there's a reference to a type before the real symbol
3016
+ table entry of the target type is available (specifically, we use a
3017
+ temporary PlaceholderNode symbol node). Consider this example:
3018
+
3019
+ class str(Sequence[str]): ...
3020
+
3021
+ We use a PlaceholderType for the 'str' in 'Sequence[str]' since we can't create
3022
+ a TypeInfo for 'str' until all base classes have been resolved. We'll soon
3023
+ perform another analysis iteration which replaces the base class with a complete
3024
+ type without any placeholders. After semantic analysis, no placeholder types must
3025
+ exist.
3026
+ """
3027
+
3028
+ __slots__ = ("fullname", "args")
3029
+
3030
+ def __init__(self, fullname: str | None, args: list[Type], line: int) -> None:
3031
+ super().__init__(line)
3032
+ self.fullname = fullname # Must be a valid full name of an actual node (or None).
3033
+ self.args = args
3034
+
3035
+ def accept(self, visitor: TypeVisitor[T]) -> T:
3036
+ assert isinstance(visitor, SyntheticTypeVisitor)
3037
+ ret: T = visitor.visit_placeholder_type(self)
3038
+ return ret
3039
+
3040
+ def __hash__(self) -> int:
3041
+ return hash((self.fullname, tuple(self.args)))
3042
+
3043
+ def __eq__(self, other: object) -> bool:
3044
+ if not isinstance(other, PlaceholderType):
3045
+ return NotImplemented
3046
+ return self.fullname == other.fullname and self.args == other.args
3047
+
3048
+ def serialize(self) -> str:
3049
+ # We should never get here since all placeholders should be replaced
3050
+ # during semantic analysis.
3051
+ assert False, f"Internal error: unresolved placeholder type {self.fullname}"
3052
+
3053
+
3054
+ @overload
3055
+ def get_proper_type(typ: None) -> None: ...
3056
+
3057
+
3058
+ @overload
3059
+ def get_proper_type(typ: Type) -> ProperType: ...
3060
+
3061
+
3062
+ def get_proper_type(typ: Type | None) -> ProperType | None:
3063
+ """Get the expansion of a type alias type.
3064
+
3065
+ If the type is already a proper type, this is a no-op. Use this function
3066
+ wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...',
3067
+ because 'typ' in this case may be an alias to union. Note: if after making the decision
3068
+ on the isinstance() call you pass on the original type (and not one of its components)
3069
+ it is recommended to *always* pass on the unexpanded alias.
3070
+ """
3071
+ if typ is None:
3072
+ return None
3073
+ if isinstance(typ, TypeGuardedType): # type: ignore[misc]
3074
+ typ = typ.type_guard
3075
+ while isinstance(typ, TypeAliasType):
3076
+ typ = typ._expand_once()
3077
+ # TODO: store the name of original type alias on this type, so we can show it in errors.
3078
+ return cast(ProperType, typ)
3079
+
3080
+
3081
+ @overload
3082
+ def get_proper_types(types: list[Type] | tuple[Type, ...]) -> list[ProperType]: # type: ignore[overload-overlap]
3083
+ ...
3084
+
3085
+
3086
+ @overload
3087
+ def get_proper_types(
3088
+ types: list[Type | None] | tuple[Type | None, ...]
3089
+ ) -> list[ProperType | None]: ...
3090
+
3091
+
3092
+ def get_proper_types(
3093
+ types: list[Type] | list[Type | None] | tuple[Type | None, ...]
3094
+ ) -> list[ProperType] | list[ProperType | None]:
3095
+ if isinstance(types, list):
3096
+ typelist = types
3097
+ # Optimize for the common case so that we don't need to allocate anything
3098
+ if not any(
3099
+ isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist # type: ignore[misc]
3100
+ ):
3101
+ return cast("list[ProperType]", typelist)
3102
+ return [get_proper_type(t) for t in typelist]
3103
+ else:
3104
+ return [get_proper_type(t) for t in types]
3105
+
3106
+
3107
+ # We split off the type visitor base classes to another module
3108
+ # to make it easier to gradually get modules working with mypyc.
3109
+ # Import them here, after the types are defined.
3110
+ # This is intended as a re-export also.
3111
+ from mypy.type_visitor import (
3112
+ ALL_STRATEGY as ALL_STRATEGY,
3113
+ ANY_STRATEGY as ANY_STRATEGY,
3114
+ BoolTypeQuery as BoolTypeQuery,
3115
+ SyntheticTypeVisitor as SyntheticTypeVisitor,
3116
+ TypeQuery as TypeQuery,
3117
+ TypeTranslator as TypeTranslator,
3118
+ TypeVisitor as TypeVisitor,
3119
+ )
3120
+ from mypy.typetraverser import TypeTraverserVisitor
3121
+
3122
+
3123
+ class TypeStrVisitor(SyntheticTypeVisitor[str]):
3124
+ """Visitor for pretty-printing types into strings.
3125
+
3126
+ This is mostly for debugging/testing.
3127
+
3128
+ Do not preserve original formatting.
3129
+
3130
+ Notes:
3131
+ - Represent unbound types as Foo? or Foo?[...].
3132
+ - Represent the NoneType type as None.
3133
+ """
3134
+
3135
+ def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None:
3136
+ self.id_mapper = id_mapper
3137
+ self.any_as_dots = False
3138
+ self.options = options
3139
+
3140
+ def visit_unbound_type(self, t: UnboundType) -> str:
3141
+ s = t.name + "?"
3142
+ if t.args:
3143
+ s += f"[{self.list_str(t.args)}]"
3144
+ return s
3145
+
3146
+ def visit_type_list(self, t: TypeList) -> str:
3147
+ return f"<TypeList {self.list_str(t.items)}>"
3148
+
3149
+ def visit_callable_argument(self, t: CallableArgument) -> str:
3150
+ typ = t.typ.accept(self)
3151
+ if t.name is None:
3152
+ return f"{t.constructor}({typ})"
3153
+ else:
3154
+ return f"{t.constructor}({typ}, {t.name})"
3155
+
3156
+ def visit_any(self, t: AnyType) -> str:
3157
+ if self.any_as_dots and t.type_of_any == TypeOfAny.special_form:
3158
+ return "..."
3159
+ return "Any"
3160
+
3161
+ def visit_none_type(self, t: NoneType) -> str:
3162
+ return "None"
3163
+
3164
+ def visit_uninhabited_type(self, t: UninhabitedType) -> str:
3165
+ return "Never"
3166
+
3167
+ def visit_erased_type(self, t: ErasedType) -> str:
3168
+ return "<Erased>"
3169
+
3170
+ def visit_deleted_type(self, t: DeletedType) -> str:
3171
+ if t.source is None:
3172
+ return "<Deleted>"
3173
+ else:
3174
+ return f"<Deleted '{t.source}'>"
3175
+
3176
+ def visit_instance(self, t: Instance) -> str:
3177
+ if t.last_known_value and not t.args:
3178
+ # Instances with a literal fallback should never be generic. If they are,
3179
+ # something went wrong so we fall back to showing the full Instance repr.
3180
+ s = f"{t.last_known_value.accept(self)}?"
3181
+ else:
3182
+ s = t.type.fullname or t.type.name or "<???>"
3183
+
3184
+ if t.args:
3185
+ if t.type.fullname == "builtins.tuple":
3186
+ assert len(t.args) == 1
3187
+ s += f"[{self.list_str(t.args)}, ...]"
3188
+ else:
3189
+ s += f"[{self.list_str(t.args)}]"
3190
+ elif t.type.has_type_var_tuple_type and len(t.type.type_vars) == 1:
3191
+ s += "[()]"
3192
+ if self.id_mapper:
3193
+ s += f"<{self.id_mapper.id(t.type)}>"
3194
+ return s
3195
+
3196
+ def visit_type_var(self, t: TypeVarType) -> str:
3197
+ if t.name is None:
3198
+ # Anonymous type variable type (only numeric id).
3199
+ s = f"`{t.id}"
3200
+ else:
3201
+ # Named type variable type.
3202
+ s = f"{t.name}`{t.id}"
3203
+ if self.id_mapper and t.upper_bound:
3204
+ s += f"(upper_bound={t.upper_bound.accept(self)})"
3205
+ if t.has_default():
3206
+ s += f" = {t.default.accept(self)}"
3207
+ return s
3208
+
3209
+ def visit_param_spec(self, t: ParamSpecType) -> str:
3210
+ # prefixes are displayed as Concatenate
3211
+ s = ""
3212
+ if t.prefix.arg_types:
3213
+ s += f"[{self.list_str(t.prefix.arg_types)}, **"
3214
+ if t.name is None:
3215
+ # Anonymous type variable type (only numeric id).
3216
+ s += f"`{t.id}"
3217
+ else:
3218
+ # Named type variable type.
3219
+ s += f"{t.name_with_suffix()}`{t.id}"
3220
+ if t.prefix.arg_types:
3221
+ s += "]"
3222
+ if t.has_default():
3223
+ s += f" = {t.default.accept(self)}"
3224
+ return s
3225
+
3226
+ def visit_parameters(self, t: Parameters) -> str:
3227
+ # This is copied from visit_callable -- is there a way to decrease duplication?
3228
+ if t.is_ellipsis_args:
3229
+ return "..."
3230
+
3231
+ s = ""
3232
+ bare_asterisk = False
3233
+ for i in range(len(t.arg_types)):
3234
+ if s != "":
3235
+ s += ", "
3236
+ if t.arg_kinds[i].is_named() and not bare_asterisk:
3237
+ s += "*, "
3238
+ bare_asterisk = True
3239
+ if t.arg_kinds[i] == ARG_STAR:
3240
+ s += "*"
3241
+ if t.arg_kinds[i] == ARG_STAR2:
3242
+ s += "**"
3243
+ name = t.arg_names[i]
3244
+ if name:
3245
+ s += f"{name}: "
3246
+ r = t.arg_types[i].accept(self)
3247
+
3248
+ s += r
3249
+
3250
+ if t.arg_kinds[i].is_optional():
3251
+ s += " ="
3252
+
3253
+ return f"[{s}]"
3254
+
3255
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> str:
3256
+ if t.name is None:
3257
+ # Anonymous type variable type (only numeric id).
3258
+ s = f"`{t.id}"
3259
+ else:
3260
+ # Named type variable type.
3261
+ s = f"{t.name}`{t.id}"
3262
+ if t.has_default():
3263
+ s += f" = {t.default.accept(self)}"
3264
+ return s
3265
+
3266
+ def visit_callable_type(self, t: CallableType) -> str:
3267
+ param_spec = t.param_spec()
3268
+ if param_spec is not None:
3269
+ num_skip = 2
3270
+ else:
3271
+ num_skip = 0
3272
+
3273
+ s = ""
3274
+ asterisk = False
3275
+ for i in range(len(t.arg_types) - num_skip):
3276
+ if s != "":
3277
+ s += ", "
3278
+ if t.arg_kinds[i].is_named() and not asterisk:
3279
+ s += "*, "
3280
+ asterisk = True
3281
+ if t.arg_kinds[i] == ARG_STAR:
3282
+ s += "*"
3283
+ asterisk = True
3284
+ if t.arg_kinds[i] == ARG_STAR2:
3285
+ s += "**"
3286
+ name = t.arg_names[i]
3287
+ if name:
3288
+ s += name + ": "
3289
+ type_str = t.arg_types[i].accept(self)
3290
+ if t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs:
3291
+ type_str = f"Unpack[{type_str}]"
3292
+ s += type_str
3293
+ if t.arg_kinds[i].is_optional():
3294
+ s += " ="
3295
+
3296
+ if param_spec is not None:
3297
+ n = param_spec.name
3298
+ if s:
3299
+ s += ", "
3300
+ s += f"*{n}.args, **{n}.kwargs"
3301
+ if param_spec.has_default():
3302
+ s += f" = {param_spec.default.accept(self)}"
3303
+
3304
+ s = f"({s})"
3305
+
3306
+ if not isinstance(get_proper_type(t.ret_type), NoneType):
3307
+ if t.type_guard is not None:
3308
+ s += f" -> TypeGuard[{t.type_guard.accept(self)}]"
3309
+ else:
3310
+ s += f" -> {t.ret_type.accept(self)}"
3311
+
3312
+ if t.variables:
3313
+ vs = []
3314
+ for var in t.variables:
3315
+ if isinstance(var, TypeVarType):
3316
+ # We reimplement TypeVarType.__repr__ here in order to support id_mapper.
3317
+ if var.values:
3318
+ vals = f"({', '.join(val.accept(self) for val in var.values)})"
3319
+ vs.append(f"{var.name} in {vals}")
3320
+ elif not is_named_instance(var.upper_bound, "builtins.object"):
3321
+ vs.append(
3322
+ f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3323
+ )
3324
+ else:
3325
+ vs.append(
3326
+ f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3327
+ )
3328
+ else:
3329
+ # For other TypeVarLikeTypes, use the name and default
3330
+ vs.append(
3331
+ f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
3332
+ )
3333
+ s = f"[{', '.join(vs)}] {s}"
3334
+
3335
+ return f"def {s}"
3336
+
3337
+ def visit_overloaded(self, t: Overloaded) -> str:
3338
+ a = []
3339
+ for i in t.items:
3340
+ a.append(i.accept(self))
3341
+ return f"Overload({', '.join(a)})"
3342
+
3343
+ def visit_tuple_type(self, t: TupleType) -> str:
3344
+ s = self.list_str(t.items) or "()"
3345
+ tuple_name = "tuple" if self.options.use_lowercase_names() else "Tuple"
3346
+ if t.partial_fallback and t.partial_fallback.type:
3347
+ fallback_name = t.partial_fallback.type.fullname
3348
+ if fallback_name != "builtins.tuple":
3349
+ return f"{tuple_name}[{s}, fallback={t.partial_fallback.accept(self)}]"
3350
+ return f"{tuple_name}[{s}]"
3351
+
3352
+ def visit_typeddict_type(self, t: TypedDictType) -> str:
3353
+ def item_str(name: str, typ: str) -> str:
3354
+ if name in t.required_keys:
3355
+ return f"{name!r}: {typ}"
3356
+ else:
3357
+ return f"{name!r}?: {typ}"
3358
+
3359
+ s = (
3360
+ "{"
3361
+ + ", ".join(item_str(name, typ.accept(self)) for name, typ in t.items.items())
3362
+ + "}"
3363
+ )
3364
+ prefix = ""
3365
+ if t.fallback and t.fallback.type:
3366
+ if t.fallback.type.fullname not in TPDICT_FB_NAMES:
3367
+ prefix = repr(t.fallback.type.fullname) + ", "
3368
+ return f"TypedDict({prefix}{s})"
3369
+
3370
+ def visit_raw_expression_type(self, t: RawExpressionType) -> str:
3371
+ return repr(t.literal_value)
3372
+
3373
+ def visit_literal_type(self, t: LiteralType) -> str:
3374
+ return f"Literal[{t.value_repr()}]"
3375
+
3376
+ def visit_union_type(self, t: UnionType) -> str:
3377
+ s = self.list_str(t.items)
3378
+ return f"Union[{s}]"
3379
+
3380
+ def visit_partial_type(self, t: PartialType) -> str:
3381
+ if t.type is None:
3382
+ return "<partial None>"
3383
+ else:
3384
+ return "<partial {}[{}]>".format(t.type.name, ", ".join(["?"] * len(t.type.type_vars)))
3385
+
3386
+ def visit_ellipsis_type(self, t: EllipsisType) -> str:
3387
+ return "..."
3388
+
3389
+ def visit_type_type(self, t: TypeType) -> str:
3390
+ return f"Type[{t.item.accept(self)}]"
3391
+
3392
+ def visit_placeholder_type(self, t: PlaceholderType) -> str:
3393
+ return f"<placeholder {t.fullname}>"
3394
+
3395
+ def visit_type_alias_type(self, t: TypeAliasType) -> str:
3396
+ if t.alias is not None:
3397
+ unrolled, recursed = t._partial_expansion()
3398
+ self.any_as_dots = recursed
3399
+ type_str = unrolled.accept(self)
3400
+ self.any_as_dots = False
3401
+ return type_str
3402
+ return "<alias (unfixed)>"
3403
+
3404
+ def visit_unpack_type(self, t: UnpackType) -> str:
3405
+ return f"Unpack[{t.type.accept(self)}]"
3406
+
3407
+ def list_str(self, a: Iterable[Type]) -> str:
3408
+ """Convert items of an array to strings (pretty-print types)
3409
+ and join the results with commas.
3410
+ """
3411
+ res = []
3412
+ for t in a:
3413
+ res.append(t.accept(self))
3414
+ return ", ".join(res)
3415
+
3416
+
3417
+ class TrivialSyntheticTypeTranslator(TypeTranslator, SyntheticTypeVisitor[Type]):
3418
+ """A base class for type translators that need to be run during semantic analysis."""
3419
+
3420
+ def visit_placeholder_type(self, t: PlaceholderType) -> Type:
3421
+ return t
3422
+
3423
+ def visit_callable_argument(self, t: CallableArgument) -> Type:
3424
+ return t
3425
+
3426
+ def visit_ellipsis_type(self, t: EllipsisType) -> Type:
3427
+ return t
3428
+
3429
+ def visit_raw_expression_type(self, t: RawExpressionType) -> Type:
3430
+ return t
3431
+
3432
+ def visit_type_list(self, t: TypeList) -> Type:
3433
+ return t
3434
+
3435
+
3436
+ class UnrollAliasVisitor(TrivialSyntheticTypeTranslator):
3437
+ def __init__(self, initial_aliases: set[TypeAliasType]) -> None:
3438
+ self.recursed = False
3439
+ self.initial_aliases = initial_aliases
3440
+
3441
+ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
3442
+ if t in self.initial_aliases:
3443
+ self.recursed = True
3444
+ return AnyType(TypeOfAny.special_form)
3445
+ # Create a new visitor on encountering a new type alias, so that an alias like
3446
+ # A = Tuple[B, B]
3447
+ # B = int
3448
+ # will not be detected as recursive on the second encounter of B.
3449
+ subvisitor = UnrollAliasVisitor(self.initial_aliases | {t})
3450
+ result = get_proper_type(t).accept(subvisitor)
3451
+ if subvisitor.recursed:
3452
+ self.recursed = True
3453
+ return result
3454
+
3455
+
3456
+ def is_named_instance(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]:
3457
+ if not isinstance(fullnames, tuple):
3458
+ fullnames = (fullnames,)
3459
+
3460
+ t = get_proper_type(t)
3461
+ return isinstance(t, Instance) and t.type.fullname in fullnames
3462
+
3463
+
3464
+ class LocationSetter(TypeTraverserVisitor):
3465
+ # TODO: Should we update locations of other Type subclasses?
3466
+ def __init__(self, line: int, column: int) -> None:
3467
+ self.line = line
3468
+ self.column = column
3469
+
3470
+ def visit_instance(self, typ: Instance) -> None:
3471
+ typ.line = self.line
3472
+ typ.column = self.column
3473
+ super().visit_instance(typ)
3474
+
3475
+
3476
+ class HasTypeVars(BoolTypeQuery):
3477
+ def __init__(self) -> None:
3478
+ super().__init__(ANY_STRATEGY)
3479
+ self.skip_alias_target = True
3480
+
3481
+ def visit_type_var(self, t: TypeVarType) -> bool:
3482
+ return True
3483
+
3484
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:
3485
+ return True
3486
+
3487
+ def visit_param_spec(self, t: ParamSpecType) -> bool:
3488
+ return True
3489
+
3490
+
3491
+ def has_type_vars(typ: Type) -> bool:
3492
+ """Check if a type contains any type variables (recursively)."""
3493
+ return typ.accept(HasTypeVars())
3494
+
3495
+
3496
+ class HasRecursiveType(BoolTypeQuery):
3497
+ def __init__(self) -> None:
3498
+ super().__init__(ANY_STRATEGY)
3499
+
3500
+ def visit_type_alias_type(self, t: TypeAliasType) -> bool:
3501
+ return t.is_recursive or self.query_types(t.args)
3502
+
3503
+
3504
+ # Use singleton since this is hot (note: call reset() before using)
3505
+ _has_recursive_type: Final = HasRecursiveType()
3506
+
3507
+
3508
+ def has_recursive_types(typ: Type) -> bool:
3509
+ """Check if a type contains any recursive aliases (recursively)."""
3510
+ _has_recursive_type.reset()
3511
+ return typ.accept(_has_recursive_type)
3512
+
3513
+
3514
+ def split_with_prefix_and_suffix(
3515
+ types: tuple[Type, ...], prefix: int, suffix: int
3516
+ ) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]:
3517
+ if len(types) <= prefix + suffix:
3518
+ types = extend_args_for_prefix_and_suffix(types, prefix, suffix)
3519
+ if suffix:
3520
+ return types[:prefix], types[prefix:-suffix], types[-suffix:]
3521
+ else:
3522
+ return types[:prefix], types[prefix:], ()
3523
+
3524
+
3525
+ def extend_args_for_prefix_and_suffix(
3526
+ types: tuple[Type, ...], prefix: int, suffix: int
3527
+ ) -> tuple[Type, ...]:
3528
+ """Extend list of types by eating out from variadic tuple to satisfy prefix and suffix."""
3529
+ idx = None
3530
+ item = None
3531
+ for i, t in enumerate(types):
3532
+ if isinstance(t, UnpackType):
3533
+ p_type = get_proper_type(t.type)
3534
+ if isinstance(p_type, Instance) and p_type.type.fullname == "builtins.tuple":
3535
+ item = p_type.args[0]
3536
+ idx = i
3537
+ break
3538
+
3539
+ if idx is None:
3540
+ return types
3541
+ assert item is not None
3542
+ if idx < prefix:
3543
+ start = (item,) * (prefix - idx)
3544
+ else:
3545
+ start = ()
3546
+ if len(types) - idx - 1 < suffix:
3547
+ end = (item,) * (suffix - len(types) + idx + 1)
3548
+ else:
3549
+ end = ()
3550
+ return types[:idx] + start + (types[idx],) + end + types[idx + 1 :]
3551
+
3552
+
3553
+ def flatten_nested_unions(
3554
+ types: Sequence[Type], handle_type_alias_type: bool = True
3555
+ ) -> list[Type]:
3556
+ """Flatten nested unions in a type list."""
3557
+ if not isinstance(types, list):
3558
+ typelist = list(types)
3559
+ else:
3560
+ typelist = cast("list[Type]", types)
3561
+
3562
+ # Fast path: most of the time there is nothing to flatten
3563
+ if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc]
3564
+ return typelist
3565
+
3566
+ flat_items: list[Type] = []
3567
+ for t in typelist:
3568
+ tp = get_proper_type(t) if handle_type_alias_type else t
3569
+ if isinstance(tp, ProperType) and isinstance(tp, UnionType):
3570
+ flat_items.extend(
3571
+ flatten_nested_unions(tp.items, handle_type_alias_type=handle_type_alias_type)
3572
+ )
3573
+ else:
3574
+ # Must preserve original aliases when possible.
3575
+ flat_items.append(t)
3576
+ return flat_items
3577
+
3578
+
3579
+ def find_unpack_in_list(items: Sequence[Type]) -> int | None:
3580
+ unpack_index: int | None = None
3581
+ for i, item in enumerate(items):
3582
+ if isinstance(item, UnpackType):
3583
+ # We cannot fail here, so we must check this in an earlier
3584
+ # semanal phase.
3585
+ # Funky code here avoids mypyc narrowing the type of unpack_index.
3586
+ old_index = unpack_index
3587
+ assert old_index is None
3588
+ # Don't return so that we can also sanity check there is only one.
3589
+ unpack_index = i
3590
+ return unpack_index
3591
+
3592
+
3593
+ def flatten_nested_tuples(types: Sequence[Type]) -> list[Type]:
3594
+ """Recursively flatten TupleTypes nested with Unpack.
3595
+
3596
+ For example this will transform
3597
+ Tuple[A, Unpack[Tuple[B, Unpack[Tuple[C, D]]]]]
3598
+ into
3599
+ Tuple[A, B, C, D]
3600
+ """
3601
+ res = []
3602
+ for typ in types:
3603
+ if not isinstance(typ, UnpackType):
3604
+ res.append(typ)
3605
+ continue
3606
+ p_type = get_proper_type(typ.type)
3607
+ if not isinstance(p_type, TupleType):
3608
+ res.append(typ)
3609
+ continue
3610
+ res.extend(flatten_nested_tuples(p_type.items))
3611
+ return res
3612
+
3613
+
3614
+ def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue) -> bool:
3615
+ """Check if this type is a LiteralType with the given fallback type and value."""
3616
+ if isinstance(typ, Instance) and typ.last_known_value:
3617
+ typ = typ.last_known_value
3618
+ return (
3619
+ isinstance(typ, LiteralType)
3620
+ and typ.fallback.type.fullname == fallback_fullname
3621
+ and typ.value == value
3622
+ )
3623
+
3624
+
3625
+ names: Final = globals().copy()
3626
+ names.pop("NOT_READY", None)
3627
+ deserialize_map: Final = {
3628
+ key: obj.deserialize
3629
+ for key, obj in names.items()
3630
+ if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type
3631
+ }
3632
+
3633
+
3634
+ def callable_with_ellipsis(any_type: AnyType, ret_type: Type, fallback: Instance) -> CallableType:
3635
+ """Construct type Callable[..., ret_type]."""
3636
+ return CallableType(
3637
+ [any_type, any_type],
3638
+ [ARG_STAR, ARG_STAR2],
3639
+ [None, None],
3640
+ ret_type=ret_type,
3641
+ fallback=fallback,
3642
+ is_ellipsis_args=True,
3643
+ )
3644
+
3645
+
3646
+ def remove_dups(types: list[T]) -> list[T]:
3647
+ if len(types) <= 1:
3648
+ return types
3649
+ # Get unique elements in order of appearance
3650
+ all_types: set[T] = set()
3651
+ new_types: list[T] = []
3652
+ for t in types:
3653
+ if t not in all_types:
3654
+ new_types.append(t)
3655
+ all_types.add(t)
3656
+ return new_types
3657
+
3658
+
3659
+ def type_vars_as_args(type_vars: Sequence[TypeVarLikeType]) -> tuple[Type, ...]:
3660
+ """Represent type variables as they would appear in a type argument list."""
3661
+ args: list[Type] = []
3662
+ for tv in type_vars:
3663
+ if isinstance(tv, TypeVarTupleType):
3664
+ args.append(UnpackType(tv))
3665
+ else:
3666
+ args.append(tv)
3667
+ return tuple(args)
3668
+
3669
+
3670
+ # This cyclic import is unfortunate, but to avoid it we would need to move away all uses
3671
+ # of get_proper_type() from types.py. Majority of them have been removed, but few remaining
3672
+ # are quite tricky to get rid of, but ultimately we want to do it at some point.
3673
+ from mypy.expandtype import ExpandTypeVisitor
3674
+
3675
+
3676
+ class InstantiateAliasVisitor(ExpandTypeVisitor):
3677
+ def visit_union_type(self, t: UnionType) -> Type:
3678
+ # Unlike regular expand_type(), we don't do any simplification for unions,
3679
+ # not even removing strict duplicates. There are three reasons for this:
3680
+ # * get_proper_type() is a very hot function, even slightest slow down will
3681
+ # cause a perf regression
3682
+ # * We want to preserve this historical behaviour, to avoid possible
3683
+ # regressions
3684
+ # * Simplifying unions may (indirectly) call get_proper_type(), causing
3685
+ # infinite recursion.
3686
+ return TypeTranslator.visit_union_type(self, t)