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/typeanal.py ADDED
@@ -0,0 +1,2510 @@
1
+ """Semantic analysis of types"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ from contextlib import contextmanager
7
+ from typing import Callable, Final, Iterable, Iterator, List, Sequence, Tuple, TypeVar
8
+ from typing_extensions import Protocol
9
+
10
+ from mypy import errorcodes as codes, message_registry, nodes
11
+ from mypy.errorcodes import ErrorCode
12
+ from mypy.expandtype import expand_type
13
+ from mypy.messages import MessageBuilder, format_type_bare, quote_type_string, wrong_type_arg_count
14
+ from mypy.nodes import (
15
+ ARG_NAMED,
16
+ ARG_NAMED_OPT,
17
+ ARG_OPT,
18
+ ARG_POS,
19
+ ARG_STAR,
20
+ ARG_STAR2,
21
+ SYMBOL_FUNCBASE_TYPES,
22
+ ArgKind,
23
+ Context,
24
+ Decorator,
25
+ MypyFile,
26
+ ParamSpecExpr,
27
+ PlaceholderNode,
28
+ SymbolTableNode,
29
+ TypeAlias,
30
+ TypeInfo,
31
+ TypeVarExpr,
32
+ TypeVarLikeExpr,
33
+ TypeVarTupleExpr,
34
+ Var,
35
+ check_arg_kinds,
36
+ check_arg_names,
37
+ get_nongen_builtins,
38
+ )
39
+ from mypy.options import Options
40
+ from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface
41
+ from mypy.semanal_shared import SemanticAnalyzerCoreInterface, paramspec_args, paramspec_kwargs
42
+ from mypy.state import state
43
+ from mypy.tvar_scope import TypeVarLikeScope
44
+ from mypy.types import (
45
+ ANNOTATED_TYPE_NAMES,
46
+ ANY_STRATEGY,
47
+ FINAL_TYPE_NAMES,
48
+ LITERAL_TYPE_NAMES,
49
+ NEVER_NAMES,
50
+ TYPE_ALIAS_NAMES,
51
+ AnyType,
52
+ BoolTypeQuery,
53
+ CallableArgument,
54
+ CallableType,
55
+ DeletedType,
56
+ EllipsisType,
57
+ ErasedType,
58
+ Instance,
59
+ LiteralType,
60
+ NoneType,
61
+ Overloaded,
62
+ Parameters,
63
+ ParamSpecFlavor,
64
+ ParamSpecType,
65
+ PartialType,
66
+ PlaceholderType,
67
+ ProperType,
68
+ RawExpressionType,
69
+ RequiredType,
70
+ SyntheticTypeVisitor,
71
+ TrivialSyntheticTypeTranslator,
72
+ TupleType,
73
+ Type,
74
+ TypeAliasType,
75
+ TypedDictType,
76
+ TypeList,
77
+ TypeOfAny,
78
+ TypeQuery,
79
+ TypeType,
80
+ TypeVarId,
81
+ TypeVarLikeType,
82
+ TypeVarTupleType,
83
+ TypeVarType,
84
+ UnboundType,
85
+ UninhabitedType,
86
+ UnionType,
87
+ UnpackType,
88
+ callable_with_ellipsis,
89
+ find_unpack_in_list,
90
+ flatten_nested_tuples,
91
+ flatten_nested_unions,
92
+ get_proper_type,
93
+ has_type_vars,
94
+ )
95
+ from mypy.types_utils import is_bad_type_type_item
96
+ from mypy.typevars import fill_typevars
97
+
98
+ T = TypeVar("T")
99
+
100
+ type_constructors: Final = {
101
+ "typing.Callable",
102
+ "typing.Optional",
103
+ "typing.Tuple",
104
+ "typing.Type",
105
+ "typing.Union",
106
+ *LITERAL_TYPE_NAMES,
107
+ *ANNOTATED_TYPE_NAMES,
108
+ }
109
+
110
+ ARG_KINDS_BY_CONSTRUCTOR: Final = {
111
+ "mypy_extensions.Arg": ARG_POS,
112
+ "mypy_extensions.DefaultArg": ARG_OPT,
113
+ "mypy_extensions.NamedArg": ARG_NAMED,
114
+ "mypy_extensions.DefaultNamedArg": ARG_NAMED_OPT,
115
+ "mypy_extensions.VarArg": ARG_STAR,
116
+ "mypy_extensions.KwArg": ARG_STAR2,
117
+ }
118
+
119
+ GENERIC_STUB_NOT_AT_RUNTIME_TYPES: Final = {
120
+ "queue.Queue",
121
+ "builtins._PathLike",
122
+ "asyncio.futures.Future",
123
+ }
124
+
125
+ SELF_TYPE_NAMES: Final = {"typing.Self", "typing_extensions.Self"}
126
+
127
+
128
+ def analyze_type_alias(
129
+ type: Type,
130
+ api: SemanticAnalyzerCoreInterface,
131
+ tvar_scope: TypeVarLikeScope,
132
+ plugin: Plugin,
133
+ options: Options,
134
+ is_typeshed_stub: bool,
135
+ allow_placeholder: bool = False,
136
+ in_dynamic_func: bool = False,
137
+ global_scope: bool = True,
138
+ allowed_alias_tvars: list[TypeVarLikeType] | None = None,
139
+ ) -> tuple[Type, set[str]]:
140
+ """Analyze r.h.s. of a (potential) type alias definition.
141
+
142
+ If `node` is valid as a type alias rvalue, return the resulting type and a set of
143
+ full names of type aliases it depends on (directly or indirectly).
144
+ 'node' must have been semantically analyzed.
145
+ """
146
+ analyzer = TypeAnalyser(
147
+ api,
148
+ tvar_scope,
149
+ plugin,
150
+ options,
151
+ is_typeshed_stub,
152
+ defining_alias=True,
153
+ allow_placeholder=allow_placeholder,
154
+ prohibit_self_type="type alias target",
155
+ allowed_alias_tvars=allowed_alias_tvars,
156
+ )
157
+ analyzer.in_dynamic_func = in_dynamic_func
158
+ analyzer.global_scope = global_scope
159
+ res = type.accept(analyzer)
160
+ return res, analyzer.aliases_used
161
+
162
+
163
+ def no_subscript_builtin_alias(name: str, propose_alt: bool = True) -> str:
164
+ class_name = name.split(".")[-1]
165
+ msg = f'"{class_name}" is not subscriptable'
166
+ # This should never be called if the python_version is 3.9 or newer
167
+ nongen_builtins = get_nongen_builtins((3, 8))
168
+ replacement = nongen_builtins[name]
169
+ if replacement and propose_alt:
170
+ msg += f', use "{replacement}" instead'
171
+ return msg
172
+
173
+
174
+ class TypeAnalyser(SyntheticTypeVisitor[Type], TypeAnalyzerPluginInterface):
175
+ """Semantic analyzer for types.
176
+
177
+ Converts unbound types into bound types. This is a no-op for already
178
+ bound types.
179
+
180
+ If an incomplete reference is encountered, this does a defer. The
181
+ caller never needs to defer.
182
+ """
183
+
184
+ # Is this called from an untyped function definition?
185
+ in_dynamic_func: bool = False
186
+ # Is this called from global scope?
187
+ global_scope: bool = True
188
+
189
+ def __init__(
190
+ self,
191
+ api: SemanticAnalyzerCoreInterface,
192
+ tvar_scope: TypeVarLikeScope,
193
+ plugin: Plugin,
194
+ options: Options,
195
+ is_typeshed_stub: bool,
196
+ *,
197
+ defining_alias: bool = False,
198
+ allow_tuple_literal: bool = False,
199
+ allow_unbound_tvars: bool = False,
200
+ allow_placeholder: bool = False,
201
+ allow_required: bool = False,
202
+ allow_param_spec_literals: bool = False,
203
+ allow_unpack: bool = False,
204
+ report_invalid_types: bool = True,
205
+ prohibit_self_type: str | None = None,
206
+ allowed_alias_tvars: list[TypeVarLikeType] | None = None,
207
+ allow_type_any: bool = False,
208
+ ) -> None:
209
+ self.api = api
210
+ self.fail_func = api.fail
211
+ self.note_func = api.note
212
+ self.tvar_scope = tvar_scope
213
+ # Are we analysing a type alias definition rvalue?
214
+ self.defining_alias = defining_alias
215
+ self.allow_tuple_literal = allow_tuple_literal
216
+ # Positive if we are analyzing arguments of another (outer) type
217
+ self.nesting_level = 0
218
+ # Should we allow new type syntax when targeting older Python versions
219
+ # like 'list[int]' or 'X | Y' (allowed in stubs and with `__future__` import)?
220
+ self.always_allow_new_syntax = self.api.is_stub_file or self.api.is_future_flag_set(
221
+ "annotations"
222
+ )
223
+ # Should we accept unbound type variables? This is currently used for class bases,
224
+ # and alias right hand sides (before they are analyzed as type aliases).
225
+ self.allow_unbound_tvars = allow_unbound_tvars
226
+ if allowed_alias_tvars is None:
227
+ allowed_alias_tvars = []
228
+ self.allowed_alias_tvars = allowed_alias_tvars
229
+ # If false, record incomplete ref if we generate PlaceholderType.
230
+ self.allow_placeholder = allow_placeholder
231
+ # Are we in a context where Required[] is allowed?
232
+ self.allow_required = allow_required
233
+ # Are we in a context where ParamSpec literals are allowed?
234
+ self.allow_param_spec_literals = allow_param_spec_literals
235
+ # Are we in context where literal "..." specifically is allowed?
236
+ self.allow_ellipsis = False
237
+ # Should we report an error whenever we encounter a RawExpressionType outside
238
+ # of a Literal context: e.g. whenever we encounter an invalid type? Normally,
239
+ # we want to report an error, but the caller may want to do more specialized
240
+ # error handling.
241
+ self.report_invalid_types = report_invalid_types
242
+ self.plugin = plugin
243
+ self.options = options
244
+ self.is_typeshed_stub = is_typeshed_stub
245
+ # Names of type aliases encountered while analysing a type will be collected here.
246
+ self.aliases_used: set[str] = set()
247
+ self.prohibit_self_type = prohibit_self_type
248
+ # Allow variables typed as Type[Any] and type (useful for base classes).
249
+ self.allow_type_any = allow_type_any
250
+ self.allow_type_var_tuple = False
251
+ self.allow_unpack = allow_unpack
252
+
253
+ def lookup_qualified(
254
+ self, name: str, ctx: Context, suppress_errors: bool = False
255
+ ) -> SymbolTableNode | None:
256
+ return self.api.lookup_qualified(name, ctx, suppress_errors)
257
+
258
+ def lookup_fully_qualified(self, name: str) -> SymbolTableNode:
259
+ return self.api.lookup_fully_qualified(name)
260
+
261
+ def visit_unbound_type(self, t: UnboundType, defining_literal: bool = False) -> Type:
262
+ typ = self.visit_unbound_type_nonoptional(t, defining_literal)
263
+ if t.optional:
264
+ # We don't need to worry about double-wrapping Optionals or
265
+ # wrapping Anys: Union simplification will take care of that.
266
+ return make_optional_type(typ)
267
+ return typ
268
+
269
+ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type:
270
+ sym = self.lookup_qualified(t.name, t)
271
+ if sym is not None:
272
+ node = sym.node
273
+ if isinstance(node, PlaceholderNode):
274
+ if node.becomes_typeinfo:
275
+ # Reference to placeholder type.
276
+ if self.api.final_iteration:
277
+ self.cannot_resolve_type(t)
278
+ return AnyType(TypeOfAny.from_error)
279
+ elif self.allow_placeholder:
280
+ self.api.defer()
281
+ else:
282
+ self.api.record_incomplete_ref()
283
+ # Always allow ParamSpec for placeholders, if they are actually not valid,
284
+ # they will be reported later, after we resolve placeholders.
285
+ return PlaceholderType(
286
+ node.fullname,
287
+ self.anal_array(
288
+ t.args,
289
+ allow_param_spec=True,
290
+ allow_param_spec_literals=True,
291
+ allow_unpack=True,
292
+ ),
293
+ t.line,
294
+ )
295
+ else:
296
+ if self.api.final_iteration:
297
+ self.cannot_resolve_type(t)
298
+ return AnyType(TypeOfAny.from_error)
299
+ else:
300
+ # Reference to an unknown placeholder node.
301
+ self.api.record_incomplete_ref()
302
+ return AnyType(TypeOfAny.special_form)
303
+ if node is None:
304
+ self.fail(f"Internal error (node is None, kind={sym.kind})", t)
305
+ return AnyType(TypeOfAny.special_form)
306
+ fullname = node.fullname
307
+ hook = self.plugin.get_type_analyze_hook(fullname)
308
+ if hook is not None:
309
+ return hook(AnalyzeTypeContext(t, t, self))
310
+ if (
311
+ fullname in get_nongen_builtins(self.options.python_version)
312
+ and t.args
313
+ and not self.always_allow_new_syntax
314
+ ):
315
+ self.fail(
316
+ no_subscript_builtin_alias(fullname, propose_alt=not self.defining_alias), t
317
+ )
318
+ tvar_def = self.tvar_scope.get_binding(sym)
319
+ if isinstance(sym.node, ParamSpecExpr):
320
+ if tvar_def is None:
321
+ if self.allow_unbound_tvars:
322
+ return t
323
+ self.fail(f'ParamSpec "{t.name}" is unbound', t, code=codes.VALID_TYPE)
324
+ return AnyType(TypeOfAny.from_error)
325
+ assert isinstance(tvar_def, ParamSpecType)
326
+ if len(t.args) > 0:
327
+ self.fail(
328
+ f'ParamSpec "{t.name}" used with arguments', t, code=codes.VALID_TYPE
329
+ )
330
+ # Change the line number
331
+ return ParamSpecType(
332
+ tvar_def.name,
333
+ tvar_def.fullname,
334
+ tvar_def.id,
335
+ tvar_def.flavor,
336
+ tvar_def.upper_bound,
337
+ tvar_def.default,
338
+ line=t.line,
339
+ column=t.column,
340
+ )
341
+ if (
342
+ isinstance(sym.node, TypeVarExpr)
343
+ and self.defining_alias
344
+ and not defining_literal
345
+ and (tvar_def is None or tvar_def not in self.allowed_alias_tvars)
346
+ ):
347
+ self.fail(
348
+ f'Can\'t use bound type variable "{t.name}" to define generic alias',
349
+ t,
350
+ code=codes.VALID_TYPE,
351
+ )
352
+ return AnyType(TypeOfAny.from_error)
353
+ if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:
354
+ assert isinstance(tvar_def, TypeVarType)
355
+ if len(t.args) > 0:
356
+ self.fail(
357
+ f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE
358
+ )
359
+ # Change the line number
360
+ return tvar_def.copy_modified(line=t.line, column=t.column)
361
+ if isinstance(sym.node, TypeVarTupleExpr) and (
362
+ tvar_def is not None
363
+ and self.defining_alias
364
+ and tvar_def not in self.allowed_alias_tvars
365
+ ):
366
+ self.fail(
367
+ f'Can\'t use bound type variable "{t.name}" to define generic alias',
368
+ t,
369
+ code=codes.VALID_TYPE,
370
+ )
371
+ return AnyType(TypeOfAny.from_error)
372
+ if isinstance(sym.node, TypeVarTupleExpr):
373
+ if tvar_def is None:
374
+ if self.allow_unbound_tvars:
375
+ return t
376
+ self.fail(f'TypeVarTuple "{t.name}" is unbound', t, code=codes.VALID_TYPE)
377
+ return AnyType(TypeOfAny.from_error)
378
+ assert isinstance(tvar_def, TypeVarTupleType)
379
+ if not self.allow_type_var_tuple:
380
+ self.fail(
381
+ f'TypeVarTuple "{t.name}" is only valid with an unpack',
382
+ t,
383
+ code=codes.VALID_TYPE,
384
+ )
385
+ return AnyType(TypeOfAny.from_error)
386
+ if len(t.args) > 0:
387
+ self.fail(
388
+ f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE
389
+ )
390
+
391
+ # Change the line number
392
+ return TypeVarTupleType(
393
+ tvar_def.name,
394
+ tvar_def.fullname,
395
+ tvar_def.id,
396
+ tvar_def.upper_bound,
397
+ sym.node.tuple_fallback,
398
+ tvar_def.default,
399
+ line=t.line,
400
+ column=t.column,
401
+ )
402
+ special = self.try_analyze_special_unbound_type(t, fullname)
403
+ if special is not None:
404
+ return special
405
+ if isinstance(node, TypeAlias):
406
+ self.aliases_used.add(fullname)
407
+ an_args = self.anal_array(
408
+ t.args,
409
+ allow_param_spec=True,
410
+ allow_param_spec_literals=node.has_param_spec_type,
411
+ allow_unpack=True, # Fixed length unpacks can be used for non-variadic aliases.
412
+ )
413
+ if node.has_param_spec_type and len(node.alias_tvars) == 1:
414
+ an_args = self.pack_paramspec_args(an_args)
415
+
416
+ disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub
417
+ res = instantiate_type_alias(
418
+ node,
419
+ an_args,
420
+ self.fail,
421
+ node.no_args,
422
+ t,
423
+ self.options,
424
+ unexpanded_type=t,
425
+ disallow_any=disallow_any,
426
+ empty_tuple_index=t.empty_tuple_index,
427
+ )
428
+ # The only case where instantiate_type_alias() can return an incorrect instance is
429
+ # when it is top-level instance, so no need to recurse.
430
+ if (
431
+ isinstance(res, ProperType)
432
+ and isinstance(res, Instance)
433
+ and not (self.defining_alias and self.nesting_level == 0)
434
+ and not validate_instance(res, self.fail, t.empty_tuple_index)
435
+ ):
436
+ fix_instance(
437
+ res,
438
+ self.fail,
439
+ self.note,
440
+ disallow_any=disallow_any,
441
+ options=self.options,
442
+ use_generic_error=True,
443
+ unexpanded_type=t,
444
+ )
445
+ if node.eager:
446
+ res = get_proper_type(res)
447
+ return res
448
+ elif isinstance(node, TypeInfo):
449
+ return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index)
450
+ elif node.fullname in TYPE_ALIAS_NAMES:
451
+ return AnyType(TypeOfAny.special_form)
452
+ # Concatenate is an operator, no need for a proper type
453
+ elif node.fullname in ("typing_extensions.Concatenate", "typing.Concatenate"):
454
+ # We check the return type further up the stack for valid use locations
455
+ return self.apply_concatenate_operator(t)
456
+ else:
457
+ return self.analyze_unbound_type_without_type_info(t, sym, defining_literal)
458
+ else: # sym is None
459
+ return AnyType(TypeOfAny.special_form)
460
+
461
+ def pack_paramspec_args(self, an_args: Sequence[Type]) -> list[Type]:
462
+ # "Aesthetic" ParamSpec literals for single ParamSpec: C[int, str] -> C[[int, str]].
463
+ # These do not support mypy_extensions VarArgs, etc. as they were already analyzed
464
+ # TODO: should these be re-analyzed to get rid of this inconsistency?
465
+ count = len(an_args)
466
+ if count == 0:
467
+ return []
468
+ if count == 1 and isinstance(get_proper_type(an_args[0]), AnyType):
469
+ # Single Any is interpreted as ..., rather that a single argument with Any type.
470
+ # I didn't find this in the PEP, but it sounds reasonable.
471
+ return list(an_args)
472
+ if any(isinstance(a, (Parameters, ParamSpecType)) for a in an_args):
473
+ if len(an_args) > 1:
474
+ first_wrong = next(
475
+ arg for arg in an_args if isinstance(arg, (Parameters, ParamSpecType))
476
+ )
477
+ self.fail(
478
+ "Nested parameter specifications are not allowed",
479
+ first_wrong,
480
+ code=codes.VALID_TYPE,
481
+ )
482
+ return [AnyType(TypeOfAny.from_error)]
483
+ return list(an_args)
484
+ first = an_args[0]
485
+ return [
486
+ Parameters(
487
+ an_args, [ARG_POS] * count, [None] * count, line=first.line, column=first.column
488
+ )
489
+ ]
490
+
491
+ def cannot_resolve_type(self, t: UnboundType) -> None:
492
+ # TODO: Move error message generation to messages.py. We'd first
493
+ # need access to MessageBuilder here. Also move the similar
494
+ # message generation logic in semanal.py.
495
+ self.api.fail(f'Cannot resolve name "{t.name}" (possible cyclic definition)', t)
496
+ if self.api.is_func_scope():
497
+ self.note("Recursive types are not allowed at function scope", t)
498
+
499
+ def apply_concatenate_operator(self, t: UnboundType) -> Type:
500
+ if len(t.args) == 0:
501
+ self.api.fail("Concatenate needs type arguments", t, code=codes.VALID_TYPE)
502
+ return AnyType(TypeOfAny.from_error)
503
+
504
+ # Last argument has to be ParamSpec or Ellipsis.
505
+ ps = self.anal_type(t.args[-1], allow_param_spec=True, allow_ellipsis=True)
506
+ if not isinstance(ps, (ParamSpecType, Parameters)):
507
+ if isinstance(ps, UnboundType) and self.allow_unbound_tvars:
508
+ sym = self.lookup_qualified(ps.name, t)
509
+ if sym is not None and isinstance(sym.node, ParamSpecExpr):
510
+ return ps
511
+ self.api.fail(
512
+ "The last parameter to Concatenate needs to be a ParamSpec",
513
+ t,
514
+ code=codes.VALID_TYPE,
515
+ )
516
+ return AnyType(TypeOfAny.from_error)
517
+ elif isinstance(ps, ParamSpecType) and ps.prefix.arg_types:
518
+ self.api.fail("Nested Concatenates are invalid", t, code=codes.VALID_TYPE)
519
+
520
+ args = self.anal_array(t.args[:-1])
521
+ pre = ps.prefix if isinstance(ps, ParamSpecType) else ps
522
+
523
+ # mypy can't infer this :(
524
+ names: list[str | None] = [None] * len(args)
525
+
526
+ pre = Parameters(
527
+ args + pre.arg_types,
528
+ [ARG_POS] * len(args) + pre.arg_kinds,
529
+ names + pre.arg_names,
530
+ line=t.line,
531
+ column=t.column,
532
+ )
533
+ return ps.copy_modified(prefix=pre) if isinstance(ps, ParamSpecType) else pre
534
+
535
+ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Type | None:
536
+ """Bind special type that is recognized through magic name such as 'typing.Any'.
537
+
538
+ Return the bound type if successful, and return None if the type is a normal type.
539
+ """
540
+ if fullname == "builtins.None":
541
+ return NoneType()
542
+ elif fullname == "typing.Any" or fullname == "builtins.Any":
543
+ return AnyType(TypeOfAny.explicit, line=t.line, column=t.column)
544
+ elif fullname in FINAL_TYPE_NAMES:
545
+ self.fail(
546
+ "Final can be only used as an outermost qualifier in a variable annotation",
547
+ t,
548
+ code=codes.VALID_TYPE,
549
+ )
550
+ return AnyType(TypeOfAny.from_error)
551
+ elif fullname == "typing.Tuple" or (
552
+ fullname == "builtins.tuple"
553
+ and (self.always_allow_new_syntax or self.options.python_version >= (3, 9))
554
+ ):
555
+ # Tuple is special because it is involved in builtin import cycle
556
+ # and may be not ready when used.
557
+ sym = self.api.lookup_fully_qualified_or_none("builtins.tuple")
558
+ if not sym or isinstance(sym.node, PlaceholderNode):
559
+ if self.api.is_incomplete_namespace("builtins"):
560
+ self.api.record_incomplete_ref()
561
+ else:
562
+ self.fail('Name "tuple" is not defined', t)
563
+ return AnyType(TypeOfAny.special_form)
564
+ if len(t.args) == 0 and not t.empty_tuple_index:
565
+ # Bare 'Tuple' is same as 'tuple'
566
+ any_type = self.get_omitted_any(t)
567
+ return self.named_type("builtins.tuple", [any_type], line=t.line, column=t.column)
568
+ if len(t.args) == 2 and isinstance(t.args[1], EllipsisType):
569
+ # Tuple[T, ...] (uniform, variable-length tuple)
570
+ instance = self.named_type("builtins.tuple", [self.anal_type(t.args[0])])
571
+ instance.line = t.line
572
+ return instance
573
+ return self.tuple_type(
574
+ self.anal_array(t.args, allow_unpack=True), line=t.line, column=t.column
575
+ )
576
+ elif fullname == "typing.Union":
577
+ items = self.anal_array(t.args)
578
+ return UnionType.make_union(items)
579
+ elif fullname == "typing.Optional":
580
+ if len(t.args) != 1:
581
+ self.fail(
582
+ "Optional[...] must have exactly one type argument", t, code=codes.VALID_TYPE
583
+ )
584
+ return AnyType(TypeOfAny.from_error)
585
+ item = self.anal_type(t.args[0])
586
+ return make_optional_type(item)
587
+ elif fullname == "typing.Callable":
588
+ return self.analyze_callable_type(t)
589
+ elif fullname == "typing.Type" or (
590
+ fullname == "builtins.type"
591
+ and (self.always_allow_new_syntax or self.options.python_version >= (3, 9))
592
+ ):
593
+ if len(t.args) == 0:
594
+ if fullname == "typing.Type":
595
+ any_type = self.get_omitted_any(t)
596
+ return TypeType(any_type, line=t.line, column=t.column)
597
+ else:
598
+ # To prevent assignment of 'builtins.type' inferred as 'builtins.object'
599
+ # See https://github.com/python/mypy/issues/9476 for more information
600
+ return None
601
+ if len(t.args) != 1:
602
+ type_str = "Type[...]" if fullname == "typing.Type" else "type[...]"
603
+ self.fail(
604
+ type_str + " must have exactly one type argument", t, code=codes.VALID_TYPE
605
+ )
606
+ item = self.anal_type(t.args[0])
607
+ if is_bad_type_type_item(item):
608
+ self.fail("Type[...] can't contain another Type[...]", t, code=codes.VALID_TYPE)
609
+ item = AnyType(TypeOfAny.from_error)
610
+ return TypeType.make_normalized(item, line=t.line, column=t.column)
611
+ elif fullname == "typing.ClassVar":
612
+ if self.nesting_level > 0:
613
+ self.fail(
614
+ "Invalid type: ClassVar nested inside other type", t, code=codes.VALID_TYPE
615
+ )
616
+ if len(t.args) == 0:
617
+ return AnyType(TypeOfAny.from_omitted_generics, line=t.line, column=t.column)
618
+ if len(t.args) != 1:
619
+ self.fail(
620
+ "ClassVar[...] must have at most one type argument", t, code=codes.VALID_TYPE
621
+ )
622
+ return AnyType(TypeOfAny.from_error)
623
+ return self.anal_type(t.args[0])
624
+ elif fullname in NEVER_NAMES:
625
+ return UninhabitedType(is_noreturn=True)
626
+ elif fullname in LITERAL_TYPE_NAMES:
627
+ return self.analyze_literal_type(t)
628
+ elif fullname in ANNOTATED_TYPE_NAMES:
629
+ if len(t.args) < 2:
630
+ self.fail(
631
+ "Annotated[...] must have exactly one type argument"
632
+ " and at least one annotation",
633
+ t,
634
+ code=codes.VALID_TYPE,
635
+ )
636
+ return AnyType(TypeOfAny.from_error)
637
+ return self.anal_type(t.args[0])
638
+ elif fullname in ("typing_extensions.Required", "typing.Required"):
639
+ if not self.allow_required:
640
+ self.fail(
641
+ "Required[] can be only used in a TypedDict definition",
642
+ t,
643
+ code=codes.VALID_TYPE,
644
+ )
645
+ return AnyType(TypeOfAny.from_error)
646
+ if len(t.args) != 1:
647
+ self.fail(
648
+ "Required[] must have exactly one type argument", t, code=codes.VALID_TYPE
649
+ )
650
+ return AnyType(TypeOfAny.from_error)
651
+ return RequiredType(self.anal_type(t.args[0]), required=True)
652
+ elif fullname in ("typing_extensions.NotRequired", "typing.NotRequired"):
653
+ if not self.allow_required:
654
+ self.fail(
655
+ "NotRequired[] can be only used in a TypedDict definition",
656
+ t,
657
+ code=codes.VALID_TYPE,
658
+ )
659
+ return AnyType(TypeOfAny.from_error)
660
+ if len(t.args) != 1:
661
+ self.fail(
662
+ "NotRequired[] must have exactly one type argument", t, code=codes.VALID_TYPE
663
+ )
664
+ return AnyType(TypeOfAny.from_error)
665
+ return RequiredType(self.anal_type(t.args[0]), required=False)
666
+ elif self.anal_type_guard_arg(t, fullname) is not None:
667
+ # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args)
668
+ return self.named_type("builtins.bool")
669
+ elif fullname in ("typing.Unpack", "typing_extensions.Unpack"):
670
+ if len(t.args) != 1:
671
+ self.fail("Unpack[...] requires exactly one type argument", t)
672
+ return AnyType(TypeOfAny.from_error)
673
+ if not self.allow_unpack:
674
+ self.fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)
675
+ return AnyType(TypeOfAny.from_error)
676
+ self.allow_type_var_tuple = True
677
+ result = UnpackType(self.anal_type(t.args[0]), line=t.line, column=t.column)
678
+ self.allow_type_var_tuple = False
679
+ return result
680
+ elif fullname in SELF_TYPE_NAMES:
681
+ if t.args:
682
+ self.fail("Self type cannot have type arguments", t)
683
+ if self.prohibit_self_type is not None:
684
+ self.fail(f"Self type cannot be used in {self.prohibit_self_type}", t)
685
+ return AnyType(TypeOfAny.from_error)
686
+ if self.api.type is None:
687
+ self.fail("Self type is only allowed in annotations within class definition", t)
688
+ return AnyType(TypeOfAny.from_error)
689
+ if self.api.type.has_base("builtins.type"):
690
+ self.fail("Self type cannot be used in a metaclass", t)
691
+ if self.api.type.self_type is not None:
692
+ if self.api.type.is_final:
693
+ return fill_typevars(self.api.type)
694
+ return self.api.type.self_type.copy_modified(line=t.line, column=t.column)
695
+ # TODO: verify this is unreachable and replace with an assert?
696
+ self.fail("Unexpected Self type", t)
697
+ return AnyType(TypeOfAny.from_error)
698
+ return None
699
+
700
+ def get_omitted_any(self, typ: Type, fullname: str | None = None) -> AnyType:
701
+ disallow_any = not self.is_typeshed_stub and self.options.disallow_any_generics
702
+ return get_omitted_any(disallow_any, self.fail, self.note, typ, self.options, fullname)
703
+
704
+ def analyze_type_with_type_info(
705
+ self, info: TypeInfo, args: Sequence[Type], ctx: Context, empty_tuple_index: bool
706
+ ) -> Type:
707
+ """Bind unbound type when were able to find target TypeInfo.
708
+
709
+ This handles simple cases like 'int', 'modname.UserClass[str]', etc.
710
+ """
711
+
712
+ if len(args) > 0 and info.fullname == "builtins.tuple":
713
+ fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line)
714
+ return TupleType(self.anal_array(args, allow_unpack=True), fallback, ctx.line)
715
+
716
+ # Analyze arguments and (usually) construct Instance type. The
717
+ # number of type arguments and their values are
718
+ # checked only later, since we do not always know the
719
+ # valid count at this point. Thus we may construct an
720
+ # Instance with an invalid number of type arguments.
721
+ #
722
+ # We allow ParamSpec literals based on a heuristic: it will be
723
+ # checked later anyways but the error message may be worse.
724
+ instance = Instance(
725
+ info,
726
+ self.anal_array(
727
+ args,
728
+ allow_param_spec=True,
729
+ allow_param_spec_literals=info.has_param_spec_type,
730
+ allow_unpack=True, # Fixed length tuples can be used for non-variadic types.
731
+ ),
732
+ ctx.line,
733
+ ctx.column,
734
+ )
735
+ if len(info.type_vars) == 1 and info.has_param_spec_type:
736
+ instance.args = tuple(self.pack_paramspec_args(instance.args))
737
+
738
+ # Check type argument count.
739
+ instance.args = tuple(flatten_nested_tuples(instance.args))
740
+ if not (self.defining_alias and self.nesting_level == 0) and not validate_instance(
741
+ instance, self.fail, empty_tuple_index
742
+ ):
743
+ fix_instance(
744
+ instance,
745
+ self.fail,
746
+ self.note,
747
+ disallow_any=self.options.disallow_any_generics and not self.is_typeshed_stub,
748
+ options=self.options,
749
+ )
750
+
751
+ tup = info.tuple_type
752
+ if tup is not None:
753
+ # The class has a Tuple[...] base class so it will be
754
+ # represented as a tuple type.
755
+ if info.special_alias:
756
+ return instantiate_type_alias(
757
+ info.special_alias,
758
+ # TODO: should we allow NamedTuples generic in ParamSpec?
759
+ self.anal_array(args, allow_unpack=True),
760
+ self.fail,
761
+ False,
762
+ ctx,
763
+ self.options,
764
+ use_standard_error=True,
765
+ )
766
+ return tup.copy_modified(
767
+ items=self.anal_array(tup.items, allow_unpack=True), fallback=instance
768
+ )
769
+ td = info.typeddict_type
770
+ if td is not None:
771
+ # The class has a TypedDict[...] base class so it will be
772
+ # represented as a typeddict type.
773
+ if info.special_alias:
774
+ return instantiate_type_alias(
775
+ info.special_alias,
776
+ # TODO: should we allow TypedDicts generic in ParamSpec?
777
+ self.anal_array(args, allow_unpack=True),
778
+ self.fail,
779
+ False,
780
+ ctx,
781
+ self.options,
782
+ use_standard_error=True,
783
+ )
784
+ # Create a named TypedDictType
785
+ return td.copy_modified(
786
+ item_types=self.anal_array(list(td.items.values())), fallback=instance
787
+ )
788
+
789
+ if info.fullname == "types.NoneType":
790
+ self.fail(
791
+ "NoneType should not be used as a type, please use None instead",
792
+ ctx,
793
+ code=codes.VALID_TYPE,
794
+ )
795
+ return NoneType(ctx.line, ctx.column)
796
+
797
+ return instance
798
+
799
+ def analyze_unbound_type_without_type_info(
800
+ self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool
801
+ ) -> Type:
802
+ """Figure out what an unbound type that doesn't refer to a TypeInfo node means.
803
+
804
+ This is something unusual. We try our best to find out what it is.
805
+ """
806
+ name = sym.fullname
807
+ if name is None:
808
+ assert sym.node is not None
809
+ name = sym.node.name
810
+ # Option 1:
811
+ # Something with an Any type -- make it an alias for Any in a type
812
+ # context. This is slightly problematic as it allows using the type 'Any'
813
+ # as a base class -- however, this will fail soon at runtime so the problem
814
+ # is pretty minor.
815
+ if isinstance(sym.node, Var):
816
+ typ = get_proper_type(sym.node.type)
817
+ if isinstance(typ, AnyType):
818
+ return AnyType(
819
+ TypeOfAny.from_unimported_type, missing_import_name=typ.missing_import_name
820
+ )
821
+ elif self.allow_type_any:
822
+ if isinstance(typ, Instance) and typ.type.fullname == "builtins.type":
823
+ return AnyType(TypeOfAny.special_form)
824
+ if isinstance(typ, TypeType) and isinstance(typ.item, AnyType):
825
+ return AnyType(TypeOfAny.from_another_any, source_any=typ.item)
826
+ # Option 2:
827
+ # Unbound type variable. Currently these may be still valid,
828
+ # for example when defining a generic type alias.
829
+ unbound_tvar = (
830
+ isinstance(sym.node, (TypeVarExpr, TypeVarTupleExpr))
831
+ and self.tvar_scope.get_binding(sym) is None
832
+ )
833
+ if self.allow_unbound_tvars and unbound_tvar:
834
+ return t
835
+
836
+ # Option 3:
837
+ # Enum value. Note: we only want to return a LiteralType when
838
+ # we're using this enum value specifically within context of
839
+ # a "Literal[...]" type. So, if `defining_literal` is not set,
840
+ # we bail out early with an error.
841
+ #
842
+ # If, in the distant future, we decide to permit things like
843
+ # `def foo(x: Color.RED) -> None: ...`, we can remove that
844
+ # check entirely.
845
+ if isinstance(sym.node, Var) and sym.node.info and sym.node.info.is_enum:
846
+ value = sym.node.name
847
+ base_enum_short_name = sym.node.info.name
848
+ if not defining_literal:
849
+ msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(
850
+ base_enum_short_name, value
851
+ )
852
+ self.fail(msg.value, t, code=msg.code)
853
+ return AnyType(TypeOfAny.from_error)
854
+ return LiteralType(
855
+ value=value,
856
+ fallback=Instance(sym.node.info, [], line=t.line, column=t.column),
857
+ line=t.line,
858
+ column=t.column,
859
+ )
860
+
861
+ # None of the above options worked. We parse the args (if there are any)
862
+ # to make sure there are no remaining semanal-only types, then give up.
863
+ t = t.copy_modified(args=self.anal_array(t.args))
864
+ # TODO: Move this message building logic to messages.py.
865
+ notes: list[str] = []
866
+ if isinstance(sym.node, Var):
867
+ notes.append(
868
+ "See https://mypy.readthedocs.io/en/"
869
+ "stable/common_issues.html#variables-vs-type-aliases"
870
+ )
871
+ message = 'Variable "{}" is not valid as a type'
872
+ elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)):
873
+ message = 'Function "{}" is not valid as a type'
874
+ if name == "builtins.any":
875
+ notes.append('Perhaps you meant "typing.Any" instead of "any"?')
876
+ elif name == "builtins.callable":
877
+ notes.append('Perhaps you meant "typing.Callable" instead of "callable"?')
878
+ else:
879
+ notes.append('Perhaps you need "Callable[...]" or a callback protocol?')
880
+ elif isinstance(sym.node, MypyFile):
881
+ message = 'Module "{}" is not valid as a type'
882
+ notes.append("Perhaps you meant to use a protocol matching the module structure?")
883
+ elif unbound_tvar:
884
+ message = 'Type variable "{}" is unbound'
885
+ short = name.split(".")[-1]
886
+ notes.append(
887
+ (
888
+ '(Hint: Use "Generic[{}]" or "Protocol[{}]" base class'
889
+ ' to bind "{}" inside a class)'
890
+ ).format(short, short, short)
891
+ )
892
+ notes.append(
893
+ '(Hint: Use "{}" in function signature to bind "{}"'
894
+ " inside a function)".format(short, short)
895
+ )
896
+ else:
897
+ message = 'Cannot interpret reference "{}" as a type'
898
+ if not defining_literal:
899
+ # Literal check already gives a custom error. Avoid duplicating errors.
900
+ self.fail(message.format(name), t, code=codes.VALID_TYPE)
901
+ for note in notes:
902
+ self.note(note, t, code=codes.VALID_TYPE)
903
+
904
+ # TODO: Would it be better to always return Any instead of UnboundType
905
+ # in case of an error? On one hand, UnboundType has a name so error messages
906
+ # are more detailed, on the other hand, some of them may be bogus,
907
+ # see https://github.com/python/mypy/issues/4987.
908
+ return t
909
+
910
+ def visit_any(self, t: AnyType) -> Type:
911
+ return t
912
+
913
+ def visit_none_type(self, t: NoneType) -> Type:
914
+ return t
915
+
916
+ def visit_uninhabited_type(self, t: UninhabitedType) -> Type:
917
+ return t
918
+
919
+ def visit_erased_type(self, t: ErasedType) -> Type:
920
+ # This type should exist only temporarily during type inference
921
+ assert False, "Internal error: Unexpected erased type"
922
+
923
+ def visit_deleted_type(self, t: DeletedType) -> Type:
924
+ return t
925
+
926
+ def visit_type_list(self, t: TypeList) -> Type:
927
+ # Parameters literal (Z[[int, str, Whatever]])
928
+ if self.allow_param_spec_literals:
929
+ params = self.analyze_callable_args(t)
930
+ if params:
931
+ ts, kinds, names = params
932
+ # bind these types
933
+ return Parameters(self.anal_array(ts), kinds, names, line=t.line, column=t.column)
934
+ else:
935
+ return AnyType(TypeOfAny.from_error)
936
+ else:
937
+ self.fail(
938
+ 'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE
939
+ )
940
+ if len(t.items) == 1:
941
+ self.note('Did you mean "List[...]"?', t)
942
+ return AnyType(TypeOfAny.from_error)
943
+
944
+ def visit_callable_argument(self, t: CallableArgument) -> Type:
945
+ self.fail("Invalid type", t, code=codes.VALID_TYPE)
946
+ return AnyType(TypeOfAny.from_error)
947
+
948
+ def visit_instance(self, t: Instance) -> Type:
949
+ return t
950
+
951
+ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
952
+ # TODO: should we do something here?
953
+ return t
954
+
955
+ def visit_type_var(self, t: TypeVarType) -> Type:
956
+ return t
957
+
958
+ def visit_param_spec(self, t: ParamSpecType) -> Type:
959
+ return t
960
+
961
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:
962
+ return t
963
+
964
+ def visit_unpack_type(self, t: UnpackType) -> Type:
965
+ if not self.allow_unpack:
966
+ self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE)
967
+ return AnyType(TypeOfAny.from_error)
968
+ self.allow_type_var_tuple = True
969
+ result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax)
970
+ self.allow_type_var_tuple = False
971
+ return result
972
+
973
+ def visit_parameters(self, t: Parameters) -> Type:
974
+ raise NotImplementedError("ParamSpec literals cannot have unbound TypeVars")
975
+
976
+ def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type:
977
+ # Every Callable can bind its own type variables, if they're not in the outer scope
978
+ with self.tvar_scope_frame():
979
+ unpacked_kwargs = False
980
+ if self.defining_alias:
981
+ variables = t.variables
982
+ else:
983
+ variables, _ = self.bind_function_type_variables(t, t)
984
+ special = self.anal_type_guard(t.ret_type)
985
+ arg_kinds = t.arg_kinds
986
+ if len(arg_kinds) >= 2 and arg_kinds[-2] == ARG_STAR and arg_kinds[-1] == ARG_STAR2:
987
+ arg_types = self.anal_array(t.arg_types[:-2], nested=nested) + [
988
+ self.anal_star_arg_type(t.arg_types[-2], ARG_STAR, nested=nested),
989
+ self.anal_star_arg_type(t.arg_types[-1], ARG_STAR2, nested=nested),
990
+ ]
991
+ # If nested is True, it means we are analyzing a Callable[...] type, rather
992
+ # than a function definition type. We need to "unpack" ** TypedDict annotation
993
+ # here (for function definitions it is done in semanal).
994
+ if nested and isinstance(arg_types[-1], UnpackType):
995
+ # TODO: it would be better to avoid this get_proper_type() call.
996
+ unpacked = get_proper_type(arg_types[-1].type)
997
+ if isinstance(unpacked, TypedDictType):
998
+ arg_types[-1] = unpacked
999
+ unpacked_kwargs = True
1000
+ arg_types = self.check_unpacks_in_list(arg_types)
1001
+ else:
1002
+ star_index = None
1003
+ if ARG_STAR in arg_kinds:
1004
+ star_index = arg_kinds.index(ARG_STAR)
1005
+ star2_index = None
1006
+ if ARG_STAR2 in arg_kinds:
1007
+ star2_index = arg_kinds.index(ARG_STAR2)
1008
+ arg_types = []
1009
+ for i, ut in enumerate(t.arg_types):
1010
+ at = self.anal_type(
1011
+ ut, nested=nested, allow_unpack=i in (star_index, star2_index)
1012
+ )
1013
+ if nested and isinstance(at, UnpackType) and i == star_index:
1014
+ # TODO: it would be better to avoid this get_proper_type() call.
1015
+ p_at = get_proper_type(at.type)
1016
+ if isinstance(p_at, TypedDictType) and not at.from_star_syntax:
1017
+ # Automatically detect Unpack[Foo] in Callable as backwards
1018
+ # compatible syntax for **Foo, if Foo is a TypedDict.
1019
+ at = p_at
1020
+ arg_kinds[i] = ARG_STAR2
1021
+ unpacked_kwargs = True
1022
+ arg_types.append(at)
1023
+ if nested:
1024
+ arg_types = self.check_unpacks_in_list(arg_types)
1025
+ # If there were multiple (invalid) unpacks, the arg types list will become shorter,
1026
+ # we need to trim the kinds/names as well to avoid crashes.
1027
+ arg_kinds = t.arg_kinds[: len(arg_types)]
1028
+ arg_names = t.arg_names[: len(arg_types)]
1029
+
1030
+ ret = t.copy_modified(
1031
+ arg_types=arg_types,
1032
+ arg_kinds=arg_kinds,
1033
+ arg_names=arg_names,
1034
+ ret_type=self.anal_type(t.ret_type, nested=nested),
1035
+ # If the fallback isn't filled in yet,
1036
+ # its type will be the falsey FakeInfo
1037
+ fallback=(t.fallback if t.fallback.type else self.named_type("builtins.function")),
1038
+ variables=self.anal_var_defs(variables),
1039
+ type_guard=special,
1040
+ unpack_kwargs=unpacked_kwargs,
1041
+ )
1042
+ return ret
1043
+
1044
+ def anal_type_guard(self, t: Type) -> Type | None:
1045
+ if isinstance(t, UnboundType):
1046
+ sym = self.lookup_qualified(t.name, t)
1047
+ if sym is not None and sym.node is not None:
1048
+ return self.anal_type_guard_arg(t, sym.node.fullname)
1049
+ # TODO: What if it's an Instance? Then use t.type.fullname?
1050
+ return None
1051
+
1052
+ def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None:
1053
+ if fullname in ("typing_extensions.TypeGuard", "typing.TypeGuard"):
1054
+ if len(t.args) != 1:
1055
+ self.fail(
1056
+ "TypeGuard must have exactly one type argument", t, code=codes.VALID_TYPE
1057
+ )
1058
+ return AnyType(TypeOfAny.from_error)
1059
+ return self.anal_type(t.args[0])
1060
+ return None
1061
+
1062
+ def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> Type:
1063
+ """Analyze signature argument type for *args and **kwargs argument."""
1064
+ if isinstance(t, UnboundType) and t.name and "." in t.name and not t.args:
1065
+ components = t.name.split(".")
1066
+ tvar_name = ".".join(components[:-1])
1067
+ sym = self.lookup_qualified(tvar_name, t)
1068
+ if sym is not None and isinstance(sym.node, ParamSpecExpr):
1069
+ tvar_def = self.tvar_scope.get_binding(sym)
1070
+ if isinstance(tvar_def, ParamSpecType):
1071
+ if kind == ARG_STAR:
1072
+ make_paramspec = paramspec_args
1073
+ if components[-1] != "args":
1074
+ self.fail(
1075
+ f'Use "{tvar_name}.args" for variadic "*" parameter',
1076
+ t,
1077
+ code=codes.VALID_TYPE,
1078
+ )
1079
+ elif kind == ARG_STAR2:
1080
+ make_paramspec = paramspec_kwargs
1081
+ if components[-1] != "kwargs":
1082
+ self.fail(
1083
+ f'Use "{tvar_name}.kwargs" for variadic "**" parameter',
1084
+ t,
1085
+ code=codes.VALID_TYPE,
1086
+ )
1087
+ else:
1088
+ assert False, kind
1089
+ return make_paramspec(
1090
+ tvar_def.name,
1091
+ tvar_def.fullname,
1092
+ tvar_def.id,
1093
+ named_type_func=self.named_type,
1094
+ line=t.line,
1095
+ column=t.column,
1096
+ )
1097
+ return self.anal_type(t, nested=nested, allow_unpack=True)
1098
+
1099
+ def visit_overloaded(self, t: Overloaded) -> Type:
1100
+ # Overloaded types are manually constructed in semanal.py by analyzing the
1101
+ # AST and combining together the Callable types this visitor converts.
1102
+ #
1103
+ # So if we're ever asked to reanalyze an Overloaded type, we know it's
1104
+ # fine to just return it as-is.
1105
+ return t
1106
+
1107
+ def visit_tuple_type(self, t: TupleType) -> Type:
1108
+ # Types such as (t1, t2, ...) only allowed in assignment statements. They'll
1109
+ # generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead.
1110
+ if t.implicit and not self.allow_tuple_literal:
1111
+ self.fail("Syntax error in type annotation", t, code=codes.SYNTAX)
1112
+ if len(t.items) == 0:
1113
+ self.note(
1114
+ "Suggestion: Use Tuple[()] instead of () for an empty tuple, or "
1115
+ "None for a function without a return value",
1116
+ t,
1117
+ code=codes.SYNTAX,
1118
+ )
1119
+ elif len(t.items) == 1:
1120
+ self.note("Suggestion: Is there a spurious trailing comma?", t, code=codes.SYNTAX)
1121
+ else:
1122
+ self.note(
1123
+ "Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)",
1124
+ t,
1125
+ code=codes.SYNTAX,
1126
+ )
1127
+ return AnyType(TypeOfAny.from_error)
1128
+
1129
+ any_type = AnyType(TypeOfAny.special_form)
1130
+ # If the fallback isn't filled in yet, its type will be the falsey FakeInfo
1131
+ fallback = (
1132
+ t.partial_fallback
1133
+ if t.partial_fallback.type
1134
+ else self.named_type("builtins.tuple", [any_type])
1135
+ )
1136
+ return TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line)
1137
+
1138
+ def visit_typeddict_type(self, t: TypedDictType) -> Type:
1139
+ items = {
1140
+ item_name: self.anal_type(item_type) for (item_name, item_type) in t.items.items()
1141
+ }
1142
+ return TypedDictType(items, set(t.required_keys), t.fallback)
1143
+
1144
+ def visit_raw_expression_type(self, t: RawExpressionType) -> Type:
1145
+ # We should never see a bare Literal. We synthesize these raw literals
1146
+ # in the earlier stages of semantic analysis, but those
1147
+ # "fake literals" should always be wrapped in an UnboundType
1148
+ # corresponding to 'Literal'.
1149
+ #
1150
+ # Note: if at some point in the distant future, we decide to
1151
+ # make signatures like "foo(x: 20) -> None" legal, we can change
1152
+ # this method so it generates and returns an actual LiteralType
1153
+ # instead.
1154
+
1155
+ if self.report_invalid_types:
1156
+ if t.base_type_name in ("builtins.int", "builtins.bool"):
1157
+ # The only time it makes sense to use an int or bool is inside of
1158
+ # a literal type.
1159
+ msg = f"Invalid type: try using Literal[{repr(t.literal_value)}] instead?"
1160
+ elif t.base_type_name in ("builtins.float", "builtins.complex"):
1161
+ # We special-case warnings for floats and complex numbers.
1162
+ msg = f"Invalid type: {t.simple_name()} literals cannot be used as a type"
1163
+ else:
1164
+ # And in all other cases, we default to a generic error message.
1165
+ # Note: the reason why we use a generic error message for strings
1166
+ # but not ints or bools is because whenever we see an out-of-place
1167
+ # string, it's unclear if the user meant to construct a literal type
1168
+ # or just misspelled a regular type. So we avoid guessing.
1169
+ msg = "Invalid type comment or annotation"
1170
+
1171
+ self.fail(msg, t, code=codes.VALID_TYPE)
1172
+ if t.note is not None:
1173
+ self.note(t.note, t, code=codes.VALID_TYPE)
1174
+
1175
+ return AnyType(TypeOfAny.from_error, line=t.line, column=t.column)
1176
+
1177
+ def visit_literal_type(self, t: LiteralType) -> Type:
1178
+ return t
1179
+
1180
+ def visit_union_type(self, t: UnionType) -> Type:
1181
+ if (
1182
+ t.uses_pep604_syntax is True
1183
+ and t.is_evaluated is True
1184
+ and not self.always_allow_new_syntax
1185
+ and not self.options.python_version >= (3, 10)
1186
+ ):
1187
+ self.fail("X | Y syntax for unions requires Python 3.10", t, code=codes.SYNTAX)
1188
+ return UnionType(self.anal_array(t.items), t.line)
1189
+
1190
+ def visit_partial_type(self, t: PartialType) -> Type:
1191
+ assert False, "Internal error: Unexpected partial type"
1192
+
1193
+ def visit_ellipsis_type(self, t: EllipsisType) -> Type:
1194
+ if self.allow_ellipsis or self.allow_param_spec_literals:
1195
+ any_type = AnyType(TypeOfAny.explicit)
1196
+ return Parameters(
1197
+ [any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None], is_ellipsis_args=True
1198
+ )
1199
+ else:
1200
+ self.fail('Unexpected "..."', t)
1201
+ return AnyType(TypeOfAny.from_error)
1202
+
1203
+ def visit_type_type(self, t: TypeType) -> Type:
1204
+ return TypeType.make_normalized(self.anal_type(t.item), line=t.line)
1205
+
1206
+ def visit_placeholder_type(self, t: PlaceholderType) -> Type:
1207
+ n = (
1208
+ None
1209
+ # No dot in fullname indicates we are at function scope, and recursive
1210
+ # types are not supported there anyway, so we just give up.
1211
+ if not t.fullname or "." not in t.fullname
1212
+ else self.api.lookup_fully_qualified(t.fullname)
1213
+ )
1214
+ if not n or isinstance(n.node, PlaceholderNode):
1215
+ self.api.defer() # Still incomplete
1216
+ return t
1217
+ else:
1218
+ # TODO: Handle non-TypeInfo
1219
+ assert isinstance(n.node, TypeInfo)
1220
+ return self.analyze_type_with_type_info(n.node, t.args, t, False)
1221
+
1222
+ def analyze_callable_args_for_paramspec(
1223
+ self, callable_args: Type, ret_type: Type, fallback: Instance
1224
+ ) -> CallableType | None:
1225
+ """Construct a 'Callable[P, RET]', where P is ParamSpec, return None if we cannot."""
1226
+ if not isinstance(callable_args, UnboundType):
1227
+ return None
1228
+ sym = self.lookup_qualified(callable_args.name, callable_args)
1229
+ if sym is None:
1230
+ return None
1231
+ tvar_def = self.tvar_scope.get_binding(sym)
1232
+ if not isinstance(tvar_def, ParamSpecType):
1233
+ if (
1234
+ tvar_def is None
1235
+ and self.allow_unbound_tvars
1236
+ and isinstance(sym.node, ParamSpecExpr)
1237
+ ):
1238
+ # We are analyzing this type in runtime context (e.g. as type application).
1239
+ # If it is not valid as a type in this position an error will be given later.
1240
+ return callable_with_ellipsis(
1241
+ AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback
1242
+ )
1243
+ return None
1244
+
1245
+ return CallableType(
1246
+ [
1247
+ paramspec_args(
1248
+ tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type
1249
+ ),
1250
+ paramspec_kwargs(
1251
+ tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type
1252
+ ),
1253
+ ],
1254
+ [nodes.ARG_STAR, nodes.ARG_STAR2],
1255
+ [None, None],
1256
+ ret_type=ret_type,
1257
+ fallback=fallback,
1258
+ )
1259
+
1260
+ def analyze_callable_args_for_concatenate(
1261
+ self, callable_args: Type, ret_type: Type, fallback: Instance
1262
+ ) -> CallableType | AnyType | None:
1263
+ """Construct a 'Callable[C, RET]', where C is Concatenate[..., P], returning None if we
1264
+ cannot.
1265
+ """
1266
+ if not isinstance(callable_args, UnboundType):
1267
+ return None
1268
+ sym = self.lookup_qualified(callable_args.name, callable_args)
1269
+ if sym is None:
1270
+ return None
1271
+ if sym.node is None:
1272
+ return None
1273
+ if sym.node.fullname not in ("typing_extensions.Concatenate", "typing.Concatenate"):
1274
+ return None
1275
+
1276
+ tvar_def = self.anal_type(callable_args, allow_param_spec=True)
1277
+ if not isinstance(tvar_def, (ParamSpecType, Parameters)):
1278
+ if self.allow_unbound_tvars and isinstance(tvar_def, UnboundType):
1279
+ sym = self.lookup_qualified(tvar_def.name, callable_args)
1280
+ if sym is not None and isinstance(sym.node, ParamSpecExpr):
1281
+ # We are analyzing this type in runtime context (e.g. as type application).
1282
+ # If it is not valid as a type in this position an error will be given later.
1283
+ return callable_with_ellipsis(
1284
+ AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback
1285
+ )
1286
+ # Error was already given, so prevent further errors.
1287
+ return AnyType(TypeOfAny.from_error)
1288
+ if isinstance(tvar_def, Parameters):
1289
+ # This comes from Concatenate[int, ...]
1290
+ return CallableType(
1291
+ arg_types=tvar_def.arg_types,
1292
+ arg_names=tvar_def.arg_names,
1293
+ arg_kinds=tvar_def.arg_kinds,
1294
+ ret_type=ret_type,
1295
+ fallback=fallback,
1296
+ from_concatenate=True,
1297
+ )
1298
+
1299
+ # ick, CallableType should take ParamSpecType
1300
+ prefix = tvar_def.prefix
1301
+ # we don't set the prefix here as generic arguments will get updated at some point
1302
+ # in the future. CallableType.param_spec() accounts for this.
1303
+ return CallableType(
1304
+ [
1305
+ *prefix.arg_types,
1306
+ paramspec_args(
1307
+ tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type
1308
+ ),
1309
+ paramspec_kwargs(
1310
+ tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type
1311
+ ),
1312
+ ],
1313
+ [*prefix.arg_kinds, nodes.ARG_STAR, nodes.ARG_STAR2],
1314
+ [*prefix.arg_names, None, None],
1315
+ ret_type=ret_type,
1316
+ fallback=fallback,
1317
+ from_concatenate=True,
1318
+ )
1319
+
1320
+ def analyze_callable_type(self, t: UnboundType) -> Type:
1321
+ fallback = self.named_type("builtins.function")
1322
+ if len(t.args) == 0:
1323
+ # Callable (bare). Treat as Callable[..., Any].
1324
+ any_type = self.get_omitted_any(t)
1325
+ ret = callable_with_ellipsis(any_type, any_type, fallback)
1326
+ elif len(t.args) == 2:
1327
+ callable_args = t.args[0]
1328
+ ret_type = t.args[1]
1329
+ if isinstance(callable_args, TypeList):
1330
+ # Callable[[ARG, ...], RET] (ordinary callable type)
1331
+ analyzed_args = self.analyze_callable_args(callable_args)
1332
+ if analyzed_args is None:
1333
+ return AnyType(TypeOfAny.from_error)
1334
+ args, kinds, names = analyzed_args
1335
+ ret = CallableType(args, kinds, names, ret_type=ret_type, fallback=fallback)
1336
+ elif isinstance(callable_args, EllipsisType):
1337
+ # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments)
1338
+ ret = callable_with_ellipsis(
1339
+ AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback
1340
+ )
1341
+ else:
1342
+ # Callable[P, RET] (where P is ParamSpec)
1343
+ with self.tvar_scope_frame():
1344
+ # Temporarily bind ParamSpecs to allow code like this:
1345
+ # my_fun: Callable[Q, Foo[Q]]
1346
+ # We usually do this later in visit_callable_type(), but the analysis
1347
+ # below happens at very early stage.
1348
+ variables = []
1349
+ for name, tvar_expr in self.find_type_var_likes(callable_args):
1350
+ variables.append(self.tvar_scope.bind_new(name, tvar_expr))
1351
+ maybe_ret = self.analyze_callable_args_for_paramspec(
1352
+ callable_args, ret_type, fallback
1353
+ ) or self.analyze_callable_args_for_concatenate(
1354
+ callable_args, ret_type, fallback
1355
+ )
1356
+ if isinstance(maybe_ret, CallableType):
1357
+ maybe_ret = maybe_ret.copy_modified(variables=variables)
1358
+ if maybe_ret is None:
1359
+ # Callable[?, RET] (where ? is something invalid)
1360
+ self.fail(
1361
+ "The first argument to Callable must be a "
1362
+ 'list of types, parameter specification, or "..."',
1363
+ t,
1364
+ code=codes.VALID_TYPE,
1365
+ )
1366
+ self.note(
1367
+ "See https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas",
1368
+ t,
1369
+ )
1370
+ return AnyType(TypeOfAny.from_error)
1371
+ elif isinstance(maybe_ret, AnyType):
1372
+ return maybe_ret
1373
+ ret = maybe_ret
1374
+ else:
1375
+ if self.options.disallow_any_generics:
1376
+ self.fail('Please use "Callable[[<parameters>], <return type>]"', t)
1377
+ else:
1378
+ self.fail('Please use "Callable[[<parameters>], <return type>]" or "Callable"', t)
1379
+ return AnyType(TypeOfAny.from_error)
1380
+ assert isinstance(ret, CallableType)
1381
+ return ret.accept(self)
1382
+
1383
+ def refers_to_full_names(self, arg: UnboundType, names: Sequence[str]) -> bool:
1384
+ sym = self.lookup_qualified(arg.name, arg)
1385
+ if sym is not None:
1386
+ if sym.fullname in names:
1387
+ return True
1388
+ return False
1389
+
1390
+ def analyze_callable_args(
1391
+ self, arglist: TypeList
1392
+ ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None:
1393
+ args: list[Type] = []
1394
+ kinds: list[ArgKind] = []
1395
+ names: list[str | None] = []
1396
+ seen_unpack = False
1397
+ unpack_types: list[Type] = []
1398
+ invalid_unpacks: list[Type] = []
1399
+ second_unpack_last = False
1400
+ for i, arg in enumerate(arglist.items):
1401
+ if isinstance(arg, CallableArgument):
1402
+ args.append(arg.typ)
1403
+ names.append(arg.name)
1404
+ if arg.constructor is None:
1405
+ return None
1406
+ found = self.lookup_qualified(arg.constructor, arg)
1407
+ if found is None:
1408
+ # Looking it up already put an error message in
1409
+ return None
1410
+ elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR:
1411
+ self.fail(f'Invalid argument constructor "{found.fullname}"', arg)
1412
+ return None
1413
+ else:
1414
+ assert found.fullname is not None
1415
+ kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname]
1416
+ kinds.append(kind)
1417
+ if arg.name is not None and kind.is_star():
1418
+ self.fail(f"{arg.constructor} arguments should not have names", arg)
1419
+ return None
1420
+ elif (
1421
+ isinstance(arg, UnboundType)
1422
+ and self.refers_to_full_names(arg, ("typing_extensions.Unpack", "typing.Unpack"))
1423
+ or isinstance(arg, UnpackType)
1424
+ ):
1425
+ if seen_unpack:
1426
+ # Multiple unpacks, preserve them, so we can give an error later.
1427
+ if i == len(arglist.items) - 1 and not invalid_unpacks:
1428
+ # Special case: if there are just two unpacks, and the second one appears
1429
+ # as last type argument, it can be still valid, if the second unpacked type
1430
+ # is a TypedDict. This should be checked by the caller.
1431
+ second_unpack_last = True
1432
+ invalid_unpacks.append(arg)
1433
+ continue
1434
+ seen_unpack = True
1435
+ unpack_types.append(arg)
1436
+ else:
1437
+ if seen_unpack:
1438
+ unpack_types.append(arg)
1439
+ else:
1440
+ args.append(arg)
1441
+ kinds.append(ARG_POS)
1442
+ names.append(None)
1443
+ if seen_unpack:
1444
+ if len(unpack_types) == 1:
1445
+ args.append(unpack_types[0])
1446
+ else:
1447
+ first = unpack_types[0]
1448
+ if isinstance(first, UnpackType):
1449
+ # UnpackType doesn't have its own line/column numbers,
1450
+ # so use the unpacked type for error messages.
1451
+ first = first.type
1452
+ args.append(
1453
+ UnpackType(self.tuple_type(unpack_types, line=first.line, column=first.column))
1454
+ )
1455
+ kinds.append(ARG_STAR)
1456
+ names.append(None)
1457
+ for arg in invalid_unpacks:
1458
+ args.append(arg)
1459
+ kinds.append(ARG_STAR2 if second_unpack_last else ARG_STAR)
1460
+ names.append(None)
1461
+ # Note that arglist below is only used for error context.
1462
+ check_arg_names(names, [arglist] * len(args), self.fail, "Callable")
1463
+ check_arg_kinds(kinds, [arglist] * len(args), self.fail)
1464
+ return args, kinds, names
1465
+
1466
+ def analyze_literal_type(self, t: UnboundType) -> Type:
1467
+ if len(t.args) == 0:
1468
+ self.fail("Literal[...] must have at least one parameter", t, code=codes.VALID_TYPE)
1469
+ return AnyType(TypeOfAny.from_error)
1470
+
1471
+ output: list[Type] = []
1472
+ for i, arg in enumerate(t.args):
1473
+ analyzed_types = self.analyze_literal_param(i + 1, arg, t)
1474
+ if analyzed_types is None:
1475
+ return AnyType(TypeOfAny.from_error)
1476
+ else:
1477
+ output.extend(analyzed_types)
1478
+ return UnionType.make_union(output, line=t.line)
1479
+
1480
+ def analyze_literal_param(self, idx: int, arg: Type, ctx: Context) -> list[Type] | None:
1481
+ # This UnboundType was originally defined as a string.
1482
+ if isinstance(arg, UnboundType) and arg.original_str_expr is not None:
1483
+ assert arg.original_str_fallback is not None
1484
+ return [
1485
+ LiteralType(
1486
+ value=arg.original_str_expr,
1487
+ fallback=self.named_type(arg.original_str_fallback),
1488
+ line=arg.line,
1489
+ column=arg.column,
1490
+ )
1491
+ ]
1492
+
1493
+ # If arg is an UnboundType that was *not* originally defined as
1494
+ # a string, try expanding it in case it's a type alias or something.
1495
+ if isinstance(arg, UnboundType):
1496
+ self.nesting_level += 1
1497
+ try:
1498
+ arg = self.visit_unbound_type(arg, defining_literal=True)
1499
+ finally:
1500
+ self.nesting_level -= 1
1501
+
1502
+ # Literal[...] cannot contain Any. Give up and add an error message
1503
+ # (if we haven't already).
1504
+ arg = get_proper_type(arg)
1505
+ if isinstance(arg, AnyType):
1506
+ # Note: We can encounter Literals containing 'Any' under three circumstances:
1507
+ #
1508
+ # 1. If the user attempts use an explicit Any as a parameter
1509
+ # 2. If the user is trying to use an enum value imported from a module with
1510
+ # no type hints, giving it an implicit type of 'Any'
1511
+ # 3. If there's some other underlying problem with the parameter.
1512
+ #
1513
+ # We report an error in only the first two cases. In the third case, we assume
1514
+ # some other region of the code has already reported a more relevant error.
1515
+ #
1516
+ # TODO: Once we start adding support for enums, make sure we report a custom
1517
+ # error for case 2 as well.
1518
+ if arg.type_of_any not in (TypeOfAny.from_error, TypeOfAny.special_form):
1519
+ self.fail(
1520
+ f'Parameter {idx} of Literal[...] cannot be of type "Any"',
1521
+ ctx,
1522
+ code=codes.VALID_TYPE,
1523
+ )
1524
+ return None
1525
+ elif isinstance(arg, RawExpressionType):
1526
+ # A raw literal. Convert it directly into a literal if we can.
1527
+ if arg.literal_value is None:
1528
+ name = arg.simple_name()
1529
+ if name in ("float", "complex"):
1530
+ msg = f'Parameter {idx} of Literal[...] cannot be of type "{name}"'
1531
+ else:
1532
+ msg = "Invalid type: Literal[...] cannot contain arbitrary expressions"
1533
+ self.fail(msg, ctx, code=codes.VALID_TYPE)
1534
+ # Note: we deliberately ignore arg.note here: the extra info might normally be
1535
+ # helpful, but it generally won't make sense in the context of a Literal[...].
1536
+ return None
1537
+
1538
+ # Remap bytes and unicode into the appropriate type for the correct Python version
1539
+ fallback = self.named_type(arg.base_type_name)
1540
+ assert isinstance(fallback, Instance)
1541
+ return [LiteralType(arg.literal_value, fallback, line=arg.line, column=arg.column)]
1542
+ elif isinstance(arg, (NoneType, LiteralType)):
1543
+ # Types that we can just add directly to the literal/potential union of literals.
1544
+ return [arg]
1545
+ elif isinstance(arg, Instance) and arg.last_known_value is not None:
1546
+ # Types generated from declarations like "var: Final = 4".
1547
+ return [arg.last_known_value]
1548
+ elif isinstance(arg, UnionType):
1549
+ out = []
1550
+ for union_arg in arg.items:
1551
+ union_result = self.analyze_literal_param(idx, union_arg, ctx)
1552
+ if union_result is None:
1553
+ return None
1554
+ out.extend(union_result)
1555
+ return out
1556
+ else:
1557
+ self.fail(f"Parameter {idx} of Literal[...] is invalid", ctx, code=codes.VALID_TYPE)
1558
+ return None
1559
+
1560
+ def analyze_type(self, t: Type) -> Type:
1561
+ return t.accept(self)
1562
+
1563
+ def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:
1564
+ self.fail_func(msg, ctx, code=code)
1565
+
1566
+ def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:
1567
+ self.note_func(msg, ctx, code=code)
1568
+
1569
+ @contextmanager
1570
+ def tvar_scope_frame(self) -> Iterator[None]:
1571
+ old_scope = self.tvar_scope
1572
+ self.tvar_scope = self.tvar_scope.method_frame()
1573
+ yield
1574
+ self.tvar_scope = old_scope
1575
+
1576
+ def find_type_var_likes(self, t: Type) -> TypeVarLikeList:
1577
+ visitor = FindTypeVarVisitor(self.api, self.tvar_scope)
1578
+ t.accept(visitor)
1579
+ return visitor.type_var_likes
1580
+
1581
+ def infer_type_variables(
1582
+ self, type: CallableType
1583
+ ) -> tuple[list[tuple[str, TypeVarLikeExpr]], bool]:
1584
+ """Infer type variables from a callable.
1585
+
1586
+ Return tuple with these items:
1587
+ - list of unique type variables referred to in a callable
1588
+ - whether there is a reference to the Self type
1589
+ """
1590
+ visitor = FindTypeVarVisitor(self.api, self.tvar_scope)
1591
+ for arg in type.arg_types:
1592
+ arg.accept(visitor)
1593
+
1594
+ # When finding type variables in the return type of a function, don't
1595
+ # look inside Callable types. Type variables only appearing in
1596
+ # functions in the return type belong to those functions, not the
1597
+ # function we're currently analyzing.
1598
+ visitor.include_callables = False
1599
+ type.ret_type.accept(visitor)
1600
+
1601
+ return visitor.type_var_likes, visitor.has_self_type
1602
+
1603
+ def bind_function_type_variables(
1604
+ self, fun_type: CallableType, defn: Context
1605
+ ) -> tuple[Sequence[TypeVarLikeType], bool]:
1606
+ """Find the type variables of the function type and bind them in our tvar_scope"""
1607
+ has_self_type = False
1608
+ if fun_type.variables:
1609
+ defs = []
1610
+ for var in fun_type.variables:
1611
+ if self.api.type and self.api.type.self_type and var == self.api.type.self_type:
1612
+ has_self_type = True
1613
+ continue
1614
+ var_node = self.lookup_qualified(var.name, defn)
1615
+ assert var_node, "Binding for function type variable not found within function"
1616
+ var_expr = var_node.node
1617
+ assert isinstance(var_expr, TypeVarLikeExpr)
1618
+ binding = self.tvar_scope.bind_new(var.name, var_expr)
1619
+ defs.append(binding)
1620
+ return defs, has_self_type
1621
+ typevars, has_self_type = self.infer_type_variables(fun_type)
1622
+ # Do not define a new type variable if already defined in scope.
1623
+ typevars = [
1624
+ (name, tvar) for name, tvar in typevars if not self.is_defined_type_var(name, defn)
1625
+ ]
1626
+ defs = []
1627
+ for name, tvar in typevars:
1628
+ if not self.tvar_scope.allow_binding(tvar.fullname):
1629
+ self.fail(
1630
+ f'Type variable "{name}" is bound by an outer class',
1631
+ defn,
1632
+ code=codes.VALID_TYPE,
1633
+ )
1634
+ binding = self.tvar_scope.bind_new(name, tvar)
1635
+ defs.append(binding)
1636
+
1637
+ return defs, has_self_type
1638
+
1639
+ def is_defined_type_var(self, tvar: str, context: Context) -> bool:
1640
+ tvar_node = self.lookup_qualified(tvar, context)
1641
+ if not tvar_node:
1642
+ return False
1643
+ return self.tvar_scope.get_binding(tvar_node) is not None
1644
+
1645
+ def anal_array(
1646
+ self,
1647
+ a: Iterable[Type],
1648
+ nested: bool = True,
1649
+ *,
1650
+ allow_param_spec: bool = False,
1651
+ allow_param_spec_literals: bool = False,
1652
+ allow_unpack: bool = False,
1653
+ ) -> list[Type]:
1654
+ old_allow_param_spec_literals = self.allow_param_spec_literals
1655
+ self.allow_param_spec_literals = allow_param_spec_literals
1656
+ res: list[Type] = []
1657
+ for t in a:
1658
+ res.append(
1659
+ self.anal_type(
1660
+ t, nested, allow_param_spec=allow_param_spec, allow_unpack=allow_unpack
1661
+ )
1662
+ )
1663
+ self.allow_param_spec_literals = old_allow_param_spec_literals
1664
+ return self.check_unpacks_in_list(res)
1665
+
1666
+ def anal_type(
1667
+ self,
1668
+ t: Type,
1669
+ nested: bool = True,
1670
+ *,
1671
+ allow_param_spec: bool = False,
1672
+ allow_unpack: bool = False,
1673
+ allow_ellipsis: bool = False,
1674
+ ) -> Type:
1675
+ if nested:
1676
+ self.nesting_level += 1
1677
+ old_allow_required = self.allow_required
1678
+ self.allow_required = False
1679
+ old_allow_ellipsis = self.allow_ellipsis
1680
+ self.allow_ellipsis = allow_ellipsis
1681
+ old_allow_unpack = self.allow_unpack
1682
+ self.allow_unpack = allow_unpack
1683
+ try:
1684
+ analyzed = t.accept(self)
1685
+ finally:
1686
+ if nested:
1687
+ self.nesting_level -= 1
1688
+ self.allow_required = old_allow_required
1689
+ self.allow_ellipsis = old_allow_ellipsis
1690
+ self.allow_unpack = old_allow_unpack
1691
+ if (
1692
+ not allow_param_spec
1693
+ and isinstance(analyzed, ParamSpecType)
1694
+ and analyzed.flavor == ParamSpecFlavor.BARE
1695
+ ):
1696
+ if analyzed.prefix.arg_types:
1697
+ self.fail("Invalid location for Concatenate", t, code=codes.VALID_TYPE)
1698
+ self.note("You can use Concatenate as the first argument to Callable", t)
1699
+ analyzed = AnyType(TypeOfAny.from_error)
1700
+ else:
1701
+ self.fail(
1702
+ f'Invalid location for ParamSpec "{analyzed.name}"', t, code=codes.VALID_TYPE
1703
+ )
1704
+ self.note(
1705
+ "You can use ParamSpec as the first argument to Callable, e.g., "
1706
+ "'Callable[{}, int]'".format(analyzed.name),
1707
+ t,
1708
+ )
1709
+ analyzed = AnyType(TypeOfAny.from_error)
1710
+ return analyzed
1711
+
1712
+ def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType:
1713
+ if isinstance(var_def, TypeVarType):
1714
+ return TypeVarType(
1715
+ name=var_def.name,
1716
+ fullname=var_def.fullname,
1717
+ id=var_def.id.raw_id,
1718
+ values=self.anal_array(var_def.values),
1719
+ upper_bound=var_def.upper_bound.accept(self),
1720
+ default=var_def.default.accept(self),
1721
+ variance=var_def.variance,
1722
+ line=var_def.line,
1723
+ column=var_def.column,
1724
+ )
1725
+ else:
1726
+ return var_def
1727
+
1728
+ def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> list[TypeVarLikeType]:
1729
+ return [self.anal_var_def(vd) for vd in var_defs]
1730
+
1731
+ def named_type(
1732
+ self,
1733
+ fully_qualified_name: str,
1734
+ args: list[Type] | None = None,
1735
+ line: int = -1,
1736
+ column: int = -1,
1737
+ ) -> Instance:
1738
+ node = self.lookup_fully_qualified(fully_qualified_name)
1739
+ assert isinstance(node.node, TypeInfo)
1740
+ any_type = AnyType(TypeOfAny.special_form)
1741
+ if args is not None:
1742
+ args = self.check_unpacks_in_list(args)
1743
+ return Instance(
1744
+ node.node, args or [any_type] * len(node.node.defn.type_vars), line=line, column=column
1745
+ )
1746
+
1747
+ def check_unpacks_in_list(self, items: list[Type]) -> list[Type]:
1748
+ new_items: list[Type] = []
1749
+ num_unpacks = 0
1750
+ final_unpack = None
1751
+ for item in items:
1752
+ # TODO: handle forward references here, they appear as Unpack[Any].
1753
+ if isinstance(item, UnpackType) and not isinstance(
1754
+ get_proper_type(item.type), TupleType
1755
+ ):
1756
+ if not num_unpacks:
1757
+ new_items.append(item)
1758
+ num_unpacks += 1
1759
+ final_unpack = item
1760
+ else:
1761
+ new_items.append(item)
1762
+
1763
+ if num_unpacks > 1:
1764
+ assert final_unpack is not None
1765
+ self.fail("More than one Unpack in a type is not allowed", final_unpack)
1766
+ return new_items
1767
+
1768
+ def tuple_type(self, items: list[Type], line: int, column: int) -> TupleType:
1769
+ any_type = AnyType(TypeOfAny.special_form)
1770
+ return TupleType(
1771
+ items, fallback=self.named_type("builtins.tuple", [any_type]), line=line, column=column
1772
+ )
1773
+
1774
+
1775
+ TypeVarLikeList = List[Tuple[str, TypeVarLikeExpr]]
1776
+
1777
+
1778
+ class MsgCallback(Protocol):
1779
+ def __call__(self, __msg: str, __ctx: Context, *, code: ErrorCode | None = None) -> None: ...
1780
+
1781
+
1782
+ def get_omitted_any(
1783
+ disallow_any: bool,
1784
+ fail: MsgCallback,
1785
+ note: MsgCallback,
1786
+ orig_type: Type,
1787
+ options: Options,
1788
+ fullname: str | None = None,
1789
+ unexpanded_type: Type | None = None,
1790
+ ) -> AnyType:
1791
+ if disallow_any:
1792
+ nongen_builtins = get_nongen_builtins(options.python_version)
1793
+ if fullname in nongen_builtins:
1794
+ typ = orig_type
1795
+ # We use a dedicated error message for builtin generics (as the most common case).
1796
+ alternative = nongen_builtins[fullname]
1797
+ fail(
1798
+ message_registry.IMPLICIT_GENERIC_ANY_BUILTIN.format(alternative),
1799
+ typ,
1800
+ code=codes.TYPE_ARG,
1801
+ )
1802
+ else:
1803
+ typ = unexpanded_type or orig_type
1804
+ type_str = typ.name if isinstance(typ, UnboundType) else format_type_bare(typ, options)
1805
+
1806
+ fail(
1807
+ message_registry.BARE_GENERIC.format(quote_type_string(type_str)),
1808
+ typ,
1809
+ code=codes.TYPE_ARG,
1810
+ )
1811
+ base_type = get_proper_type(orig_type)
1812
+ base_fullname = (
1813
+ base_type.type.fullname if isinstance(base_type, Instance) else fullname
1814
+ )
1815
+ # Ideally, we'd check whether the type is quoted or `from __future__ annotations`
1816
+ # is set before issuing this note
1817
+ if (
1818
+ options.python_version < (3, 9)
1819
+ and base_fullname in GENERIC_STUB_NOT_AT_RUNTIME_TYPES
1820
+ ):
1821
+ # Recommend `from __future__ import annotations` or to put type in quotes
1822
+ # (string literal escaping) for classes not generic at runtime
1823
+ note(
1824
+ "Subscripting classes that are not generic at runtime may require "
1825
+ "escaping, see https://mypy.readthedocs.io/en/stable/runtime_troubles.html"
1826
+ "#not-generic-runtime",
1827
+ typ,
1828
+ code=codes.TYPE_ARG,
1829
+ )
1830
+
1831
+ any_type = AnyType(TypeOfAny.from_error, line=typ.line, column=typ.column)
1832
+ else:
1833
+ any_type = AnyType(
1834
+ TypeOfAny.from_omitted_generics, line=orig_type.line, column=orig_type.column
1835
+ )
1836
+ return any_type
1837
+
1838
+
1839
+ def fix_type_var_tuple_argument(t: Instance) -> None:
1840
+ if t.type.has_type_var_tuple_type:
1841
+ args = list(t.args)
1842
+ assert t.type.type_var_tuple_prefix is not None
1843
+ tvt = t.type.defn.type_vars[t.type.type_var_tuple_prefix]
1844
+ assert isinstance(tvt, TypeVarTupleType)
1845
+ args[t.type.type_var_tuple_prefix] = UnpackType(
1846
+ Instance(tvt.tuple_fallback.type, [args[t.type.type_var_tuple_prefix]])
1847
+ )
1848
+ t.args = tuple(args)
1849
+
1850
+
1851
+ def fix_instance(
1852
+ t: Instance,
1853
+ fail: MsgCallback,
1854
+ note: MsgCallback,
1855
+ disallow_any: bool,
1856
+ options: Options,
1857
+ use_generic_error: bool = False,
1858
+ unexpanded_type: Type | None = None,
1859
+ ) -> None:
1860
+ """Fix a malformed instance by replacing all type arguments with TypeVar default or Any.
1861
+
1862
+ Also emit a suitable error if this is not due to implicit Any's.
1863
+ """
1864
+ arg_count = len(t.args)
1865
+ min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)
1866
+ max_tv_count = len(t.type.type_vars)
1867
+ if arg_count < min_tv_count or arg_count > max_tv_count:
1868
+ # Don't use existing args if arg_count doesn't match
1869
+ if arg_count > max_tv_count:
1870
+ # Already wrong arg count error, don't emit missing type parameters error as well.
1871
+ disallow_any = False
1872
+ t.args = ()
1873
+ arg_count = 0
1874
+
1875
+ args: list[Type] = [*(t.args[:max_tv_count])]
1876
+ any_type: AnyType | None = None
1877
+ env: dict[TypeVarId, Type] = {}
1878
+
1879
+ for tv, arg in itertools.zip_longest(t.type.defn.type_vars, t.args, fillvalue=None):
1880
+ if tv is None:
1881
+ continue
1882
+ if arg is None:
1883
+ if tv.has_default():
1884
+ arg = tv.default
1885
+ else:
1886
+ if any_type is None:
1887
+ fullname = None if use_generic_error else t.type.fullname
1888
+ any_type = get_omitted_any(
1889
+ disallow_any, fail, note, t, options, fullname, unexpanded_type
1890
+ )
1891
+ arg = any_type
1892
+ args.append(arg)
1893
+ env[tv.id] = arg
1894
+ t.args = tuple(args)
1895
+ fix_type_var_tuple_argument(t)
1896
+ if not t.type.has_type_var_tuple_type:
1897
+ with state.strict_optional_set(options.strict_optional):
1898
+ fixed = expand_type(t, env)
1899
+ assert isinstance(fixed, Instance)
1900
+ t.args = fixed.args
1901
+
1902
+
1903
+ def instantiate_type_alias(
1904
+ node: TypeAlias,
1905
+ args: list[Type],
1906
+ fail: MsgCallback,
1907
+ no_args: bool,
1908
+ ctx: Context,
1909
+ options: Options,
1910
+ *,
1911
+ unexpanded_type: Type | None = None,
1912
+ disallow_any: bool = False,
1913
+ use_standard_error: bool = False,
1914
+ empty_tuple_index: bool = False,
1915
+ ) -> Type:
1916
+ """Create an instance of a (generic) type alias from alias node and type arguments.
1917
+
1918
+ We are following the rules outlined in TypeAlias docstring.
1919
+ Here:
1920
+ node: type alias node (definition)
1921
+ args: type arguments (types to be substituted in place of type variables
1922
+ when expanding the alias)
1923
+ fail: error reporter callback
1924
+ no_args: whether original definition used a bare generic `A = List`
1925
+ ctx: context where expansion happens
1926
+ unexpanded_type, disallow_any, use_standard_error: used to customize error messages
1927
+ """
1928
+ # Type aliases are special, since they can be expanded during semantic analysis,
1929
+ # so we need to normalize them as soon as possible.
1930
+ # TODO: can this cause an infinite recursion?
1931
+ args = flatten_nested_tuples(args)
1932
+ if any(unknown_unpack(a) for a in args):
1933
+ # This type is not ready to be validated, because of unknown total count.
1934
+ # Note that we keep the kind of Any for consistency.
1935
+ return set_any_tvars(node, [], ctx.line, ctx.column, options, special_form=True)
1936
+
1937
+ max_tv_count = len(node.alias_tvars)
1938
+ act_len = len(args)
1939
+ if (
1940
+ max_tv_count > 0
1941
+ and act_len == 0
1942
+ and not (empty_tuple_index and node.tvar_tuple_index is not None)
1943
+ ):
1944
+ # Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...]
1945
+ return set_any_tvars(
1946
+ node,
1947
+ args,
1948
+ ctx.line,
1949
+ ctx.column,
1950
+ options,
1951
+ disallow_any=disallow_any,
1952
+ fail=fail,
1953
+ unexpanded_type=unexpanded_type,
1954
+ )
1955
+ if max_tv_count == 0 and act_len == 0:
1956
+ if no_args:
1957
+ assert isinstance(node.target, Instance) # type: ignore[misc]
1958
+ # Note: this is the only case where we use an eager expansion. See more info about
1959
+ # no_args aliases like L = List in the docstring for TypeAlias class.
1960
+ return Instance(node.target.type, [], line=ctx.line, column=ctx.column)
1961
+ return TypeAliasType(node, [], line=ctx.line, column=ctx.column)
1962
+ if (
1963
+ max_tv_count == 0
1964
+ and act_len > 0
1965
+ and isinstance(node.target, Instance) # type: ignore[misc]
1966
+ and no_args
1967
+ ):
1968
+ tp = Instance(node.target.type, args)
1969
+ tp.line = ctx.line
1970
+ tp.column = ctx.column
1971
+ return tp
1972
+ if node.tvar_tuple_index is None:
1973
+ if any(isinstance(a, UnpackType) for a in args):
1974
+ # A variadic unpack in fixed size alias (fixed unpacks must be flattened by the caller)
1975
+ fail(message_registry.INVALID_UNPACK_POSITION, ctx, code=codes.VALID_TYPE)
1976
+ return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True)
1977
+ min_tv_count = sum(not tv.has_default() for tv in node.alias_tvars)
1978
+ fill_typevars = act_len != max_tv_count
1979
+ correct = min_tv_count <= act_len <= max_tv_count
1980
+ else:
1981
+ min_tv_count = sum(
1982
+ not tv.has_default() and not isinstance(tv, TypeVarTupleType)
1983
+ for tv in node.alias_tvars
1984
+ )
1985
+ correct = act_len >= min_tv_count
1986
+ for a in args:
1987
+ if isinstance(a, UnpackType):
1988
+ unpacked = get_proper_type(a.type)
1989
+ if isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple":
1990
+ # Variadic tuple is always correct.
1991
+ correct = True
1992
+ fill_typevars = not correct
1993
+ if fill_typevars:
1994
+ if not correct:
1995
+ if use_standard_error:
1996
+ # This is used if type alias is an internal representation of another type,
1997
+ # for example a generic TypedDict or NamedTuple.
1998
+ msg = wrong_type_arg_count(max_tv_count, max_tv_count, str(act_len), node.name)
1999
+ else:
2000
+ if node.tvar_tuple_index is not None:
2001
+ msg = (
2002
+ "Bad number of arguments for type alias,"
2003
+ f" expected at least {min_tv_count}, given {act_len}"
2004
+ )
2005
+ elif min_tv_count != max_tv_count:
2006
+ msg = (
2007
+ "Bad number of arguments for type alias,"
2008
+ f" expected between {min_tv_count} and {max_tv_count}, given {act_len}"
2009
+ )
2010
+ else:
2011
+ msg = (
2012
+ "Bad number of arguments for type alias,"
2013
+ f" expected {min_tv_count}, given {act_len}"
2014
+ )
2015
+ fail(msg, ctx, code=codes.TYPE_ARG)
2016
+ args = []
2017
+ return set_any_tvars(node, args, ctx.line, ctx.column, options, from_error=True)
2018
+ elif node.tvar_tuple_index is not None:
2019
+ # We also need to check if we are not performing a type variable tuple split.
2020
+ unpack = find_unpack_in_list(args)
2021
+ if unpack is not None:
2022
+ unpack_arg = args[unpack]
2023
+ assert isinstance(unpack_arg, UnpackType)
2024
+ if isinstance(unpack_arg.type, TypeVarTupleType):
2025
+ exp_prefix = node.tvar_tuple_index
2026
+ act_prefix = unpack
2027
+ exp_suffix = len(node.alias_tvars) - node.tvar_tuple_index - 1
2028
+ act_suffix = len(args) - unpack - 1
2029
+ if act_prefix < exp_prefix or act_suffix < exp_suffix:
2030
+ fail("TypeVarTuple cannot be split", ctx, code=codes.TYPE_ARG)
2031
+ return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True)
2032
+ # TODO: we need to check args validity w.r.t alias.alias_tvars.
2033
+ # Otherwise invalid instantiations will be allowed in runtime context.
2034
+ # Note: in type context, these will be still caught by semanal_typeargs.
2035
+ typ = TypeAliasType(node, args, ctx.line, ctx.column)
2036
+ assert typ.alias is not None
2037
+ # HACK: Implement FlexibleAlias[T, typ] by expanding it to typ here.
2038
+ if (
2039
+ isinstance(typ.alias.target, Instance) # type: ignore[misc]
2040
+ and typ.alias.target.type.fullname == "mypy_extensions.FlexibleAlias"
2041
+ ):
2042
+ exp = get_proper_type(typ)
2043
+ assert isinstance(exp, Instance)
2044
+ return exp.args[-1]
2045
+ return typ
2046
+
2047
+
2048
+ def set_any_tvars(
2049
+ node: TypeAlias,
2050
+ args: list[Type],
2051
+ newline: int,
2052
+ newcolumn: int,
2053
+ options: Options,
2054
+ *,
2055
+ from_error: bool = False,
2056
+ disallow_any: bool = False,
2057
+ special_form: bool = False,
2058
+ fail: MsgCallback | None = None,
2059
+ unexpanded_type: Type | None = None,
2060
+ ) -> TypeAliasType:
2061
+ if from_error or disallow_any:
2062
+ type_of_any = TypeOfAny.from_error
2063
+ elif special_form:
2064
+ type_of_any = TypeOfAny.special_form
2065
+ else:
2066
+ type_of_any = TypeOfAny.from_omitted_generics
2067
+ any_type = AnyType(type_of_any, line=newline, column=newcolumn)
2068
+
2069
+ env: dict[TypeVarId, Type] = {}
2070
+ used_any_type = False
2071
+ has_type_var_tuple_type = False
2072
+ for tv, arg in itertools.zip_longest(node.alias_tvars, args, fillvalue=None):
2073
+ if tv is None:
2074
+ continue
2075
+ if arg is None:
2076
+ if tv.has_default():
2077
+ arg = tv.default
2078
+ else:
2079
+ arg = any_type
2080
+ used_any_type = True
2081
+ if isinstance(tv, TypeVarTupleType):
2082
+ # TODO Handle TypeVarTuple defaults
2083
+ has_type_var_tuple_type = True
2084
+ arg = UnpackType(Instance(tv.tuple_fallback.type, [any_type]))
2085
+ args.append(arg)
2086
+ env[tv.id] = arg
2087
+ t = TypeAliasType(node, args, newline, newcolumn)
2088
+ if not has_type_var_tuple_type:
2089
+ fixed = expand_type(t, env)
2090
+ assert isinstance(fixed, TypeAliasType)
2091
+ t.args = fixed.args
2092
+
2093
+ if used_any_type and disallow_any and node.alias_tvars:
2094
+ assert fail is not None
2095
+ if unexpanded_type:
2096
+ type_str = (
2097
+ unexpanded_type.name
2098
+ if isinstance(unexpanded_type, UnboundType)
2099
+ else format_type_bare(unexpanded_type, options)
2100
+ )
2101
+ else:
2102
+ type_str = node.name
2103
+
2104
+ fail(
2105
+ message_registry.BARE_GENERIC.format(quote_type_string(type_str)),
2106
+ Context(newline, newcolumn),
2107
+ code=codes.TYPE_ARG,
2108
+ )
2109
+ return t
2110
+
2111
+
2112
+ def flatten_tvars(lists: list[list[T]]) -> list[T]:
2113
+ result: list[T] = []
2114
+ for lst in lists:
2115
+ for item in lst:
2116
+ if item not in result:
2117
+ result.append(item)
2118
+ return result
2119
+
2120
+
2121
+ class DivergingAliasDetector(TrivialSyntheticTypeTranslator):
2122
+ """See docstring of detect_diverging_alias() for details."""
2123
+
2124
+ # TODO: this doesn't really need to be a translator, but we don't have a trivial visitor.
2125
+ def __init__(
2126
+ self,
2127
+ seen_nodes: set[TypeAlias],
2128
+ lookup: Callable[[str, Context], SymbolTableNode | None],
2129
+ scope: TypeVarLikeScope,
2130
+ ) -> None:
2131
+ self.seen_nodes = seen_nodes
2132
+ self.lookup = lookup
2133
+ self.scope = scope
2134
+ self.diverging = False
2135
+
2136
+ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
2137
+ assert t.alias is not None, f"Unfixed type alias {t.type_ref}"
2138
+ if t.alias in self.seen_nodes:
2139
+ for arg in t.args:
2140
+ if not (
2141
+ isinstance(arg, TypeVarLikeType)
2142
+ or isinstance(arg, UnpackType)
2143
+ and isinstance(arg.type, TypeVarLikeType)
2144
+ ) and has_type_vars(arg):
2145
+ self.diverging = True
2146
+ return t
2147
+ # All clear for this expansion chain.
2148
+ return t
2149
+ new_nodes = self.seen_nodes | {t.alias}
2150
+ visitor = DivergingAliasDetector(new_nodes, self.lookup, self.scope)
2151
+ _ = get_proper_type(t).accept(visitor)
2152
+ if visitor.diverging:
2153
+ self.diverging = True
2154
+ return t
2155
+
2156
+
2157
+ def detect_diverging_alias(
2158
+ node: TypeAlias,
2159
+ target: Type,
2160
+ lookup: Callable[[str, Context], SymbolTableNode | None],
2161
+ scope: TypeVarLikeScope,
2162
+ ) -> bool:
2163
+ """This detects type aliases that will diverge during type checking.
2164
+
2165
+ For example F = Something[..., F[List[T]]]. At each expansion step this will produce
2166
+ *new* type aliases: e.g. F[List[int]], F[List[List[int]]], etc. So we can't detect
2167
+ recursion. It is a known problem in the literature, recursive aliases and generic types
2168
+ don't always go well together. It looks like there is no known systematic solution yet.
2169
+
2170
+ # TODO: should we handle such aliases using type_recursion counter and some large limit?
2171
+ They may be handy in rare cases, e.g. to express a union of non-mixed nested lists:
2172
+ Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...]
2173
+ """
2174
+ visitor = DivergingAliasDetector({node}, lookup, scope)
2175
+ _ = target.accept(visitor)
2176
+ return visitor.diverging
2177
+
2178
+
2179
+ def check_for_explicit_any(
2180
+ typ: Type | None,
2181
+ options: Options,
2182
+ is_typeshed_stub: bool,
2183
+ msg: MessageBuilder,
2184
+ context: Context,
2185
+ ) -> None:
2186
+ if options.disallow_any_explicit and not is_typeshed_stub and typ and has_explicit_any(typ):
2187
+ msg.explicit_any(context)
2188
+
2189
+
2190
+ def has_explicit_any(t: Type) -> bool:
2191
+ """
2192
+ Whether this type is or type it contains is an Any coming from explicit type annotation
2193
+ """
2194
+ return t.accept(HasExplicitAny())
2195
+
2196
+
2197
+ class HasExplicitAny(TypeQuery[bool]):
2198
+ def __init__(self) -> None:
2199
+ super().__init__(any)
2200
+
2201
+ def visit_any(self, t: AnyType) -> bool:
2202
+ return t.type_of_any == TypeOfAny.explicit
2203
+
2204
+ def visit_typeddict_type(self, t: TypedDictType) -> bool:
2205
+ # typeddict is checked during TypedDict declaration, so don't typecheck it here.
2206
+ return False
2207
+
2208
+
2209
+ def has_any_from_unimported_type(t: Type) -> bool:
2210
+ """Return true if this type is Any because an import was not followed.
2211
+
2212
+ If type t is such Any type or has type arguments that contain such Any type
2213
+ this function will return true.
2214
+ """
2215
+ return t.accept(HasAnyFromUnimportedType())
2216
+
2217
+
2218
+ class HasAnyFromUnimportedType(BoolTypeQuery):
2219
+ def __init__(self) -> None:
2220
+ super().__init__(ANY_STRATEGY)
2221
+
2222
+ def visit_any(self, t: AnyType) -> bool:
2223
+ return t.type_of_any == TypeOfAny.from_unimported_type
2224
+
2225
+ def visit_typeddict_type(self, t: TypedDictType) -> bool:
2226
+ # typeddict is checked during TypedDict declaration, so don't typecheck it here
2227
+ return False
2228
+
2229
+
2230
+ def collect_all_inner_types(t: Type) -> list[Type]:
2231
+ """
2232
+ Return all types that `t` contains
2233
+ """
2234
+ return t.accept(CollectAllInnerTypesQuery())
2235
+
2236
+
2237
+ class CollectAllInnerTypesQuery(TypeQuery[List[Type]]):
2238
+ def __init__(self) -> None:
2239
+ super().__init__(self.combine_lists_strategy)
2240
+
2241
+ def query_types(self, types: Iterable[Type]) -> list[Type]:
2242
+ return self.strategy([t.accept(self) for t in types]) + list(types)
2243
+
2244
+ @classmethod
2245
+ def combine_lists_strategy(cls, it: Iterable[list[Type]]) -> list[Type]:
2246
+ return list(itertools.chain.from_iterable(it))
2247
+
2248
+
2249
+ def make_optional_type(t: Type) -> Type:
2250
+ """Return the type corresponding to Optional[t].
2251
+
2252
+ Note that we can't use normal union simplification, since this function
2253
+ is called during semantic analysis and simplification only works during
2254
+ type checking.
2255
+ """
2256
+ p_t = get_proper_type(t)
2257
+ if isinstance(p_t, NoneType):
2258
+ return t
2259
+ elif isinstance(p_t, UnionType):
2260
+ # Eagerly expanding aliases is not safe during semantic analysis.
2261
+ items = [
2262
+ item
2263
+ for item in flatten_nested_unions(p_t.items, handle_type_alias_type=False)
2264
+ if not isinstance(get_proper_type(item), NoneType)
2265
+ ]
2266
+ return UnionType(items + [NoneType()], t.line, t.column)
2267
+ else:
2268
+ return UnionType([t, NoneType()], t.line, t.column)
2269
+
2270
+
2271
+ def validate_instance(t: Instance, fail: MsgCallback, empty_tuple_index: bool) -> bool:
2272
+ """Check if this is a well-formed instance with respect to argument count/positions."""
2273
+ # TODO: combine logic with instantiate_type_alias().
2274
+ if any(unknown_unpack(a) for a in t.args):
2275
+ # This type is not ready to be validated, because of unknown total count.
2276
+ # TODO: is it OK to fill with TypeOfAny.from_error instead of special form?
2277
+ return False
2278
+ if t.type.has_type_var_tuple_type:
2279
+ min_tv_count = sum(
2280
+ not tv.has_default() and not isinstance(tv, TypeVarTupleType)
2281
+ for tv in t.type.defn.type_vars
2282
+ )
2283
+ correct = len(t.args) >= min_tv_count
2284
+ if any(
2285
+ isinstance(a, UnpackType) and isinstance(get_proper_type(a.type), Instance)
2286
+ for a in t.args
2287
+ ):
2288
+ correct = True
2289
+ if not t.args:
2290
+ if not (empty_tuple_index and len(t.type.type_vars) == 1):
2291
+ # The Any arguments should be set by the caller.
2292
+ return False
2293
+ elif not correct:
2294
+ fail(
2295
+ f"Bad number of arguments, expected: at least {min_tv_count}, given: {len(t.args)}",
2296
+ t,
2297
+ code=codes.TYPE_ARG,
2298
+ )
2299
+ return False
2300
+ else:
2301
+ # We also need to check if we are not performing a type variable tuple split.
2302
+ unpack = find_unpack_in_list(t.args)
2303
+ if unpack is not None:
2304
+ unpack_arg = t.args[unpack]
2305
+ assert isinstance(unpack_arg, UnpackType)
2306
+ if isinstance(unpack_arg.type, TypeVarTupleType):
2307
+ assert t.type.type_var_tuple_prefix is not None
2308
+ assert t.type.type_var_tuple_suffix is not None
2309
+ exp_prefix = t.type.type_var_tuple_prefix
2310
+ act_prefix = unpack
2311
+ exp_suffix = t.type.type_var_tuple_suffix
2312
+ act_suffix = len(t.args) - unpack - 1
2313
+ if act_prefix < exp_prefix or act_suffix < exp_suffix:
2314
+ fail("TypeVarTuple cannot be split", t, code=codes.TYPE_ARG)
2315
+ return False
2316
+ elif any(isinstance(a, UnpackType) for a in t.args):
2317
+ # A variadic unpack in fixed size instance (fixed unpacks must be flattened by the caller)
2318
+ fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)
2319
+ t.args = ()
2320
+ return False
2321
+ elif len(t.args) != len(t.type.type_vars):
2322
+ # Invalid number of type parameters.
2323
+ arg_count = len(t.args)
2324
+ min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)
2325
+ max_tv_count = len(t.type.type_vars)
2326
+ if arg_count and (arg_count < min_tv_count or arg_count > max_tv_count):
2327
+ fail(
2328
+ wrong_type_arg_count(min_tv_count, max_tv_count, str(arg_count), t.type.name),
2329
+ t,
2330
+ code=codes.TYPE_ARG,
2331
+ )
2332
+ t.invalid = True
2333
+ return False
2334
+ return True
2335
+
2336
+
2337
+ def find_self_type(typ: Type, lookup: Callable[[str], SymbolTableNode | None]) -> bool:
2338
+ return typ.accept(HasSelfType(lookup))
2339
+
2340
+
2341
+ class HasSelfType(BoolTypeQuery):
2342
+ def __init__(self, lookup: Callable[[str], SymbolTableNode | None]) -> None:
2343
+ self.lookup = lookup
2344
+ super().__init__(ANY_STRATEGY)
2345
+
2346
+ def visit_unbound_type(self, t: UnboundType) -> bool:
2347
+ sym = self.lookup(t.name)
2348
+ if sym and sym.fullname in SELF_TYPE_NAMES:
2349
+ return True
2350
+ return super().visit_unbound_type(t)
2351
+
2352
+
2353
+ def unknown_unpack(t: Type) -> bool:
2354
+ """Check if a given type is an unpack of an unknown type.
2355
+
2356
+ Unfortunately, there is no robust way to distinguish forward references from
2357
+ genuine undefined names here. But this worked well so far, although it looks
2358
+ quite fragile.
2359
+ """
2360
+ if isinstance(t, UnpackType):
2361
+ unpacked = get_proper_type(t.type)
2362
+ if isinstance(unpacked, AnyType) and unpacked.type_of_any == TypeOfAny.special_form:
2363
+ return True
2364
+ return False
2365
+
2366
+
2367
+ class FindTypeVarVisitor(SyntheticTypeVisitor[None]):
2368
+ """Type visitor that looks for type variable types and self types."""
2369
+
2370
+ def __init__(self, api: SemanticAnalyzerCoreInterface, scope: TypeVarLikeScope) -> None:
2371
+ self.api = api
2372
+ self.scope = scope
2373
+ self.type_var_likes: list[tuple[str, TypeVarLikeExpr]] = []
2374
+ self.has_self_type = False
2375
+ self.seen_aliases: set[TypeAliasType] | None = None
2376
+ self.include_callables = True
2377
+
2378
+ def _seems_like_callable(self, type: UnboundType) -> bool:
2379
+ if not type.args:
2380
+ return False
2381
+ return isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType))
2382
+
2383
+ def visit_unbound_type(self, t: UnboundType) -> None:
2384
+ name = t.name
2385
+ node = None
2386
+
2387
+ # Special case P.args and P.kwargs for ParamSpecs only.
2388
+ if name.endswith("args"):
2389
+ if name.endswith((".args", ".kwargs")):
2390
+ base = ".".join(name.split(".")[:-1])
2391
+ n = self.api.lookup_qualified(base, t)
2392
+ if n is not None and isinstance(n.node, ParamSpecExpr):
2393
+ node = n
2394
+ name = base
2395
+ if node is None:
2396
+ node = self.api.lookup_qualified(name, t)
2397
+ if node and node.fullname in SELF_TYPE_NAMES:
2398
+ self.has_self_type = True
2399
+ if (
2400
+ node
2401
+ and isinstance(node.node, TypeVarLikeExpr)
2402
+ and self.scope.get_binding(node) is None
2403
+ ):
2404
+ if (name, node.node) not in self.type_var_likes:
2405
+ self.type_var_likes.append((name, node.node))
2406
+ elif not self.include_callables and self._seems_like_callable(t):
2407
+ if find_self_type(
2408
+ t, lambda name: self.api.lookup_qualified(name, t, suppress_errors=True)
2409
+ ):
2410
+ self.has_self_type = True
2411
+ return
2412
+ elif node and node.fullname in LITERAL_TYPE_NAMES:
2413
+ return
2414
+ elif node and node.fullname in ANNOTATED_TYPE_NAMES and t.args:
2415
+ # Don't query the second argument to Annotated for TypeVars
2416
+ self.process_types([t.args[0]])
2417
+ elif t.args:
2418
+ self.process_types(t.args)
2419
+
2420
+ def visit_type_list(self, t: TypeList) -> None:
2421
+ self.process_types(t.items)
2422
+
2423
+ def visit_callable_argument(self, t: CallableArgument) -> None:
2424
+ t.typ.accept(self)
2425
+
2426
+ def visit_any(self, t: AnyType) -> None:
2427
+ pass
2428
+
2429
+ def visit_uninhabited_type(self, t: UninhabitedType) -> None:
2430
+ pass
2431
+
2432
+ def visit_none_type(self, t: NoneType) -> None:
2433
+ pass
2434
+
2435
+ def visit_erased_type(self, t: ErasedType) -> None:
2436
+ pass
2437
+
2438
+ def visit_deleted_type(self, t: DeletedType) -> None:
2439
+ pass
2440
+
2441
+ def visit_type_var(self, t: TypeVarType) -> None:
2442
+ self.process_types([t.upper_bound, t.default] + t.values)
2443
+
2444
+ def visit_param_spec(self, t: ParamSpecType) -> None:
2445
+ self.process_types([t.upper_bound, t.default])
2446
+
2447
+ def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:
2448
+ self.process_types([t.upper_bound, t.default])
2449
+
2450
+ def visit_unpack_type(self, t: UnpackType) -> None:
2451
+ self.process_types([t.type])
2452
+
2453
+ def visit_parameters(self, t: Parameters) -> None:
2454
+ self.process_types(t.arg_types)
2455
+
2456
+ def visit_partial_type(self, t: PartialType) -> None:
2457
+ pass
2458
+
2459
+ def visit_instance(self, t: Instance) -> None:
2460
+ self.process_types(t.args)
2461
+
2462
+ def visit_callable_type(self, t: CallableType) -> None:
2463
+ # FIX generics
2464
+ self.process_types(t.arg_types)
2465
+ t.ret_type.accept(self)
2466
+
2467
+ def visit_tuple_type(self, t: TupleType) -> None:
2468
+ self.process_types(t.items)
2469
+
2470
+ def visit_typeddict_type(self, t: TypedDictType) -> None:
2471
+ self.process_types(list(t.items.values()))
2472
+
2473
+ def visit_raw_expression_type(self, t: RawExpressionType) -> None:
2474
+ pass
2475
+
2476
+ def visit_literal_type(self, t: LiteralType) -> None:
2477
+ pass
2478
+
2479
+ def visit_union_type(self, t: UnionType) -> None:
2480
+ self.process_types(t.items)
2481
+
2482
+ def visit_overloaded(self, t: Overloaded) -> None:
2483
+ self.process_types(t.items) # type: ignore[arg-type]
2484
+
2485
+ def visit_type_type(self, t: TypeType) -> None:
2486
+ t.item.accept(self)
2487
+
2488
+ def visit_ellipsis_type(self, t: EllipsisType) -> None:
2489
+ pass
2490
+
2491
+ def visit_placeholder_type(self, t: PlaceholderType) -> None:
2492
+ return self.process_types(t.args)
2493
+
2494
+ def visit_type_alias_type(self, t: TypeAliasType) -> None:
2495
+ # Skip type aliases in already visited types to avoid infinite recursion.
2496
+ if self.seen_aliases is None:
2497
+ self.seen_aliases = set()
2498
+ elif t in self.seen_aliases:
2499
+ return
2500
+ self.seen_aliases.add(t)
2501
+ self.process_types(t.args)
2502
+
2503
+ def process_types(self, types: list[Type] | tuple[Type, ...]) -> None:
2504
+ # Redundant type check helps mypyc.
2505
+ if isinstance(types, list):
2506
+ for t in types:
2507
+ t.accept(self)
2508
+ else:
2509
+ for t in types:
2510
+ t.accept(self)