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/nodes.py ADDED
@@ -0,0 +1,4112 @@
1
+ """Abstract syntax tree node classes (i.e. parse tree)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from abc import abstractmethod
7
+ from collections import defaultdict
8
+ from enum import Enum, unique
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Callable,
13
+ Dict,
14
+ Final,
15
+ Iterator,
16
+ List,
17
+ Optional,
18
+ Sequence,
19
+ Tuple,
20
+ TypeVar,
21
+ Union,
22
+ cast,
23
+ )
24
+ from typing_extensions import TypeAlias as _TypeAlias, TypeGuard
25
+
26
+ from mypy_extensions import trait
27
+
28
+ import mypy.strconv
29
+ from mypy.options import Options
30
+ from mypy.util import is_typeshed_file, short_type
31
+ from mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor
32
+
33
+ if TYPE_CHECKING:
34
+ from mypy.patterns import Pattern
35
+
36
+
37
+ class Context:
38
+ """Base type for objects that are valid as error message locations."""
39
+
40
+ __slots__ = ("line", "column", "end_line", "end_column")
41
+
42
+ def __init__(self, line: int = -1, column: int = -1) -> None:
43
+ self.line = line
44
+ self.column = column
45
+ self.end_line: int | None = None
46
+ self.end_column: int | None = None
47
+
48
+ def set_line(
49
+ self,
50
+ target: Context | int,
51
+ column: int | None = None,
52
+ end_line: int | None = None,
53
+ end_column: int | None = None,
54
+ ) -> None:
55
+ """If target is a node, pull line (and column) information
56
+ into this node. If column is specified, this will override any column
57
+ information coming from a node.
58
+ """
59
+ if isinstance(target, int):
60
+ self.line = target
61
+ else:
62
+ self.line = target.line
63
+ self.column = target.column
64
+ self.end_line = target.end_line
65
+ self.end_column = target.end_column
66
+
67
+ if column is not None:
68
+ self.column = column
69
+
70
+ if end_line is not None:
71
+ self.end_line = end_line
72
+
73
+ if end_column is not None:
74
+ self.end_column = end_column
75
+
76
+
77
+ if TYPE_CHECKING:
78
+ # break import cycle only needed for mypy
79
+ import mypy.types
80
+
81
+
82
+ T = TypeVar("T")
83
+
84
+ JsonDict: _TypeAlias = Dict[str, Any]
85
+
86
+
87
+ # Symbol table node kinds
88
+ #
89
+ # TODO rename to use more descriptive names
90
+
91
+ LDEF: Final = 0
92
+ GDEF: Final = 1
93
+ MDEF: Final = 2
94
+
95
+ # Placeholder for a name imported via 'from ... import'. Second phase of
96
+ # semantic will replace this the actual imported reference. This is
97
+ # needed so that we can detect whether a name has been imported during
98
+ # XXX what?
99
+ UNBOUND_IMPORTED: Final = 3
100
+
101
+ # RevealExpr node kinds
102
+ REVEAL_TYPE: Final = 0
103
+ REVEAL_LOCALS: Final = 1
104
+
105
+ LITERAL_YES: Final = 2
106
+ LITERAL_TYPE: Final = 1
107
+ LITERAL_NO: Final = 0
108
+
109
+ node_kinds: Final = {LDEF: "Ldef", GDEF: "Gdef", MDEF: "Mdef", UNBOUND_IMPORTED: "UnboundImported"}
110
+ inverse_node_kinds: Final = {_kind: _name for _name, _kind in node_kinds.items()}
111
+
112
+
113
+ implicit_module_attrs: Final = {
114
+ "__name__": "__builtins__.str",
115
+ "__doc__": None, # depends on Python version, see semanal.py
116
+ "__path__": None, # depends on if the module is a package
117
+ "__file__": "__builtins__.str",
118
+ "__package__": "__builtins__.str",
119
+ "__annotations__": None, # dict[str, Any] bounded in add_implicit_module_attrs()
120
+ }
121
+
122
+
123
+ # These aliases exist because built-in class objects are not subscriptable.
124
+ # For example `list[int]` fails at runtime. Instead List[int] should be used.
125
+ type_aliases: Final = {
126
+ "typing.List": "builtins.list",
127
+ "typing.Dict": "builtins.dict",
128
+ "typing.Set": "builtins.set",
129
+ "typing.FrozenSet": "builtins.frozenset",
130
+ "typing.ChainMap": "collections.ChainMap",
131
+ "typing.Counter": "collections.Counter",
132
+ "typing.DefaultDict": "collections.defaultdict",
133
+ "typing.Deque": "collections.deque",
134
+ "typing.OrderedDict": "collections.OrderedDict",
135
+ # HACK: a lie in lieu of actual support for PEP 675
136
+ "typing.LiteralString": "builtins.str",
137
+ }
138
+
139
+ # This keeps track of the oldest supported Python version where the corresponding
140
+ # alias source is available.
141
+ type_aliases_source_versions: Final = {"typing.LiteralString": (3, 11)}
142
+
143
+ # This keeps track of aliases in `typing_extensions`, which we treat specially.
144
+ typing_extensions_aliases: Final = {
145
+ # See: https://github.com/python/mypy/issues/11528
146
+ "typing_extensions.OrderedDict": "collections.OrderedDict",
147
+ # HACK: a lie in lieu of actual support for PEP 675
148
+ "typing_extensions.LiteralString": "builtins.str",
149
+ }
150
+
151
+ reverse_builtin_aliases: Final = {
152
+ "builtins.list": "typing.List",
153
+ "builtins.dict": "typing.Dict",
154
+ "builtins.set": "typing.Set",
155
+ "builtins.frozenset": "typing.FrozenSet",
156
+ }
157
+
158
+ _nongen_builtins: Final = {"builtins.tuple": "typing.Tuple", "builtins.enumerate": ""}
159
+ _nongen_builtins.update((name, alias) for alias, name in type_aliases.items())
160
+ # Drop OrderedDict from this for backward compatibility
161
+ del _nongen_builtins["collections.OrderedDict"]
162
+ # HACK: consequence of hackily treating LiteralString as an alias for str
163
+ del _nongen_builtins["builtins.str"]
164
+
165
+
166
+ def get_nongen_builtins(python_version: tuple[int, int]) -> dict[str, str]:
167
+ # After 3.9 with pep585 generic builtins are allowed
168
+ return _nongen_builtins if python_version < (3, 9) else {}
169
+
170
+
171
+ RUNTIME_PROTOCOL_DECOS: Final = (
172
+ "typing.runtime_checkable",
173
+ "typing_extensions.runtime",
174
+ "typing_extensions.runtime_checkable",
175
+ )
176
+
177
+
178
+ class Node(Context):
179
+ """Common base class for all non-type parse tree nodes."""
180
+
181
+ __slots__ = ()
182
+
183
+ def __str__(self) -> str:
184
+ ans = self.accept(mypy.strconv.StrConv(options=Options()))
185
+ if ans is None:
186
+ return repr(self)
187
+ return ans
188
+
189
+ def str_with_options(self, options: Options) -> str:
190
+ ans = self.accept(mypy.strconv.StrConv(options=options))
191
+ assert ans
192
+ return ans
193
+
194
+ def accept(self, visitor: NodeVisitor[T]) -> T:
195
+ raise RuntimeError("Not implemented", type(self))
196
+
197
+
198
+ @trait
199
+ class Statement(Node):
200
+ """A statement node."""
201
+
202
+ __slots__ = ()
203
+
204
+ def accept(self, visitor: StatementVisitor[T]) -> T:
205
+ raise RuntimeError("Not implemented", type(self))
206
+
207
+
208
+ @trait
209
+ class Expression(Node):
210
+ """An expression node."""
211
+
212
+ __slots__ = ()
213
+
214
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
215
+ raise RuntimeError("Not implemented", type(self))
216
+
217
+
218
+ class FakeExpression(Expression):
219
+ """A dummy expression.
220
+
221
+ We need a dummy expression in one place, and can't instantiate Expression
222
+ because it is a trait and mypyc barfs.
223
+ """
224
+
225
+ __slots__ = ()
226
+
227
+
228
+ # TODO:
229
+ # Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr'
230
+ # 'TupleExpr']; see #1783.
231
+ Lvalue: _TypeAlias = Expression
232
+
233
+
234
+ @trait
235
+ class SymbolNode(Node):
236
+ """Nodes that can be stored in a symbol table."""
237
+
238
+ __slots__ = ()
239
+
240
+ @property
241
+ @abstractmethod
242
+ def name(self) -> str:
243
+ pass
244
+
245
+ # Fully qualified name
246
+ @property
247
+ @abstractmethod
248
+ def fullname(self) -> str:
249
+ pass
250
+
251
+ @abstractmethod
252
+ def serialize(self) -> JsonDict:
253
+ pass
254
+
255
+ @classmethod
256
+ def deserialize(cls, data: JsonDict) -> SymbolNode:
257
+ classname = data[".class"]
258
+ method = deserialize_map.get(classname)
259
+ if method is not None:
260
+ return method(data)
261
+ raise NotImplementedError(f"unexpected .class {classname}")
262
+
263
+
264
+ # Items: fullname, related symbol table node, surrounding type (if any)
265
+ Definition: _TypeAlias = Tuple[str, "SymbolTableNode", Optional["TypeInfo"]]
266
+
267
+
268
+ class MypyFile(SymbolNode):
269
+ """The abstract syntax tree of a single source file."""
270
+
271
+ __slots__ = (
272
+ "_fullname",
273
+ "path",
274
+ "defs",
275
+ "alias_deps",
276
+ "is_bom",
277
+ "names",
278
+ "imports",
279
+ "ignored_lines",
280
+ "skipped_lines",
281
+ "is_stub",
282
+ "is_cache_skeleton",
283
+ "is_partial_stub_package",
284
+ "plugin_deps",
285
+ "future_import_flags",
286
+ "_is_typeshed_file",
287
+ )
288
+
289
+ __match_args__ = ("name", "path", "defs")
290
+
291
+ # Fully qualified module name
292
+ _fullname: str
293
+ # Path to the file (empty string if not known)
294
+ path: str
295
+ # Top-level definitions and statements
296
+ defs: list[Statement]
297
+ # Type alias dependencies as mapping from target to set of alias full names
298
+ alias_deps: defaultdict[str, set[str]]
299
+ # Is there a UTF-8 BOM at the start?
300
+ is_bom: bool
301
+ names: SymbolTable
302
+ # All import nodes within the file (also ones within functions etc.)
303
+ imports: list[ImportBase]
304
+ # Lines on which to ignore certain errors when checking.
305
+ # If the value is empty, ignore all errors; otherwise, the list contains all
306
+ # error codes to ignore.
307
+ ignored_lines: dict[int, list[str]]
308
+ # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE,
309
+ # or platform/version checks. Those lines would not be type-checked.
310
+ skipped_lines: set[int]
311
+ # Is this file represented by a stub file (.pyi)?
312
+ is_stub: bool
313
+ # Is this loaded from the cache and thus missing the actual body of the file?
314
+ is_cache_skeleton: bool
315
+ # Does this represent an __init__.pyi stub with a module __getattr__
316
+ # (i.e. a partial stub package), for such packages we suppress any missing
317
+ # module errors in addition to missing attribute errors.
318
+ is_partial_stub_package: bool
319
+ # Plugin-created dependencies
320
+ plugin_deps: dict[str, set[str]]
321
+ # Future imports defined in this file. Populated during semantic analysis.
322
+ future_import_flags: set[str]
323
+ _is_typeshed_file: bool | None
324
+
325
+ def __init__(
326
+ self,
327
+ defs: list[Statement],
328
+ imports: list[ImportBase],
329
+ is_bom: bool = False,
330
+ ignored_lines: dict[int, list[str]] | None = None,
331
+ ) -> None:
332
+ super().__init__()
333
+ self.defs = defs
334
+ self.line = 1 # Dummy line number
335
+ self.column = 0 # Dummy column
336
+ self.imports = imports
337
+ self.is_bom = is_bom
338
+ self.alias_deps = defaultdict(set)
339
+ self.plugin_deps = {}
340
+ if ignored_lines:
341
+ self.ignored_lines = ignored_lines
342
+ else:
343
+ self.ignored_lines = {}
344
+ self.skipped_lines = set()
345
+
346
+ self.path = ""
347
+ self.is_stub = False
348
+ self.is_cache_skeleton = False
349
+ self.is_partial_stub_package = False
350
+ self.future_import_flags = set()
351
+ self._is_typeshed_file = None
352
+
353
+ def local_definitions(self) -> Iterator[Definition]:
354
+ """Return all definitions within the module (including nested).
355
+
356
+ This doesn't include imported definitions.
357
+ """
358
+ return local_definitions(self.names, self.fullname)
359
+
360
+ @property
361
+ def name(self) -> str:
362
+ return "" if not self._fullname else self._fullname.split(".")[-1]
363
+
364
+ @property
365
+ def fullname(self) -> str:
366
+ return self._fullname
367
+
368
+ def accept(self, visitor: NodeVisitor[T]) -> T:
369
+ return visitor.visit_mypy_file(self)
370
+
371
+ def is_package_init_file(self) -> bool:
372
+ return len(self.path) != 0 and os.path.basename(self.path).startswith("__init__.")
373
+
374
+ def is_future_flag_set(self, flag: str) -> bool:
375
+ return flag in self.future_import_flags
376
+
377
+ def is_typeshed_file(self, options: Options) -> bool:
378
+ # Cache result since this is called a lot
379
+ if self._is_typeshed_file is None:
380
+ self._is_typeshed_file = is_typeshed_file(options.abs_custom_typeshed_dir, self.path)
381
+ return self._is_typeshed_file
382
+
383
+ def serialize(self) -> JsonDict:
384
+ return {
385
+ ".class": "MypyFile",
386
+ "_fullname": self._fullname,
387
+ "names": self.names.serialize(self._fullname),
388
+ "is_stub": self.is_stub,
389
+ "path": self.path,
390
+ "is_partial_stub_package": self.is_partial_stub_package,
391
+ "future_import_flags": list(self.future_import_flags),
392
+ }
393
+
394
+ @classmethod
395
+ def deserialize(cls, data: JsonDict) -> MypyFile:
396
+ assert data[".class"] == "MypyFile", data
397
+ tree = MypyFile([], [])
398
+ tree._fullname = data["_fullname"]
399
+ tree.names = SymbolTable.deserialize(data["names"])
400
+ tree.is_stub = data["is_stub"]
401
+ tree.path = data["path"]
402
+ tree.is_partial_stub_package = data["is_partial_stub_package"]
403
+ tree.is_cache_skeleton = True
404
+ tree.future_import_flags = set(data["future_import_flags"])
405
+ return tree
406
+
407
+
408
+ class ImportBase(Statement):
409
+ """Base class for all import statements."""
410
+
411
+ __slots__ = ("is_unreachable", "is_top_level", "is_mypy_only", "assignments")
412
+
413
+ is_unreachable: bool # Set by semanal.SemanticAnalyzerPass1 if inside `if False` etc.
414
+ is_top_level: bool # Ditto if outside any class or def
415
+ is_mypy_only: bool # Ditto if inside `if TYPE_CHECKING` or `if MYPY`
416
+
417
+ # If an import replaces existing definitions, we construct dummy assignment
418
+ # statements that assign the imported names to the names in the current scope,
419
+ # for type checking purposes. Example:
420
+ #
421
+ # x = 1
422
+ # from m import x <-- add assignment representing "x = m.x"
423
+ assignments: list[AssignmentStmt]
424
+
425
+ def __init__(self) -> None:
426
+ super().__init__()
427
+ self.assignments = []
428
+ self.is_unreachable = False
429
+ self.is_top_level = False
430
+ self.is_mypy_only = False
431
+
432
+
433
+ class Import(ImportBase):
434
+ """import m [as n]"""
435
+
436
+ __slots__ = ("ids",)
437
+
438
+ __match_args__ = ("ids",)
439
+
440
+ ids: list[tuple[str, str | None]] # (module id, as id)
441
+
442
+ def __init__(self, ids: list[tuple[str, str | None]]) -> None:
443
+ super().__init__()
444
+ self.ids = ids
445
+
446
+ def accept(self, visitor: StatementVisitor[T]) -> T:
447
+ return visitor.visit_import(self)
448
+
449
+
450
+ class ImportFrom(ImportBase):
451
+ """from m import x [as y], ..."""
452
+
453
+ __slots__ = ("id", "names", "relative")
454
+
455
+ __match_args__ = ("id", "names", "relative")
456
+
457
+ id: str
458
+ relative: int
459
+ names: list[tuple[str, str | None]] # Tuples (name, as name)
460
+
461
+ def __init__(self, id: str, relative: int, names: list[tuple[str, str | None]]) -> None:
462
+ super().__init__()
463
+ self.id = id
464
+ self.names = names
465
+ self.relative = relative
466
+
467
+ def accept(self, visitor: StatementVisitor[T]) -> T:
468
+ return visitor.visit_import_from(self)
469
+
470
+
471
+ class ImportAll(ImportBase):
472
+ """from m import *"""
473
+
474
+ __slots__ = ("id", "relative")
475
+
476
+ __match_args__ = ("id", "relative")
477
+
478
+ id: str
479
+ relative: int
480
+
481
+ def __init__(self, id: str, relative: int) -> None:
482
+ super().__init__()
483
+ self.id = id
484
+ self.relative = relative
485
+
486
+ def accept(self, visitor: StatementVisitor[T]) -> T:
487
+ return visitor.visit_import_all(self)
488
+
489
+
490
+ FUNCBASE_FLAGS: Final = ["is_property", "is_class", "is_static", "is_final"]
491
+
492
+
493
+ class FuncBase(Node):
494
+ """Abstract base class for function-like nodes.
495
+
496
+ N.B: Although this has SymbolNode subclasses (FuncDef,
497
+ OverloadedFuncDef), avoid calling isinstance(..., FuncBase) on
498
+ something that is typed as SymbolNode. This is to work around
499
+ mypy bug #3603, in which mypy doesn't understand multiple
500
+ inheritance very well, and will assume that a SymbolNode
501
+ cannot be a FuncBase.
502
+
503
+ Instead, test against SYMBOL_FUNCBASE_TYPES, which enumerates
504
+ SymbolNode subclasses that are also FuncBase subclasses.
505
+ """
506
+
507
+ __slots__ = (
508
+ "type",
509
+ "unanalyzed_type",
510
+ "info",
511
+ "is_property",
512
+ "is_class", # Uses "@classmethod" (explicit or implicit)
513
+ "is_static", # Uses "@staticmethod" (explicit or implicit)
514
+ "is_final", # Uses "@final"
515
+ "is_explicit_override", # Uses "@override"
516
+ "is_type_check_only", # Uses "@type_check_only"
517
+ "_fullname",
518
+ )
519
+
520
+ def __init__(self) -> None:
521
+ super().__init__()
522
+ # Type signature. This is usually CallableType or Overloaded, but it can be
523
+ # something else for decorated functions.
524
+ self.type: mypy.types.ProperType | None = None
525
+ # Original, not semantically analyzed type (used for reprocessing)
526
+ self.unanalyzed_type: mypy.types.ProperType | None = None
527
+ # If method, reference to TypeInfo
528
+ self.info = FUNC_NO_INFO
529
+ self.is_property = False
530
+ self.is_class = False
531
+ self.is_static = False
532
+ self.is_final = False
533
+ self.is_explicit_override = False
534
+ self.is_type_check_only = False
535
+ # Name with module prefix
536
+ self._fullname = ""
537
+
538
+ @property
539
+ @abstractmethod
540
+ def name(self) -> str:
541
+ pass
542
+
543
+ @property
544
+ def fullname(self) -> str:
545
+ return self._fullname
546
+
547
+
548
+ OverloadPart: _TypeAlias = Union["FuncDef", "Decorator"]
549
+
550
+
551
+ class OverloadedFuncDef(FuncBase, SymbolNode, Statement):
552
+ """A logical node representing all the variants of a multi-declaration function.
553
+
554
+ A multi-declaration function is often an @overload, but can also be a
555
+ @property with a setter and a/or a deleter.
556
+
557
+ This node has no explicit representation in the source program.
558
+ Overloaded variants must be consecutive in the source file.
559
+ """
560
+
561
+ __slots__ = ("items", "unanalyzed_items", "impl")
562
+
563
+ items: list[OverloadPart]
564
+ unanalyzed_items: list[OverloadPart]
565
+ impl: OverloadPart | None
566
+
567
+ def __init__(self, items: list[OverloadPart]) -> None:
568
+ super().__init__()
569
+ self.items = items
570
+ self.unanalyzed_items = items.copy()
571
+ self.impl = None
572
+ if items:
573
+ # TODO: figure out how to reliably set end position (we don't know the impl here).
574
+ self.set_line(items[0].line, items[0].column)
575
+
576
+ @property
577
+ def name(self) -> str:
578
+ if self.items:
579
+ return self.items[0].name
580
+ else:
581
+ # This may happen for malformed overload
582
+ assert self.impl is not None
583
+ return self.impl.name
584
+
585
+ def accept(self, visitor: StatementVisitor[T]) -> T:
586
+ return visitor.visit_overloaded_func_def(self)
587
+
588
+ def serialize(self) -> JsonDict:
589
+ return {
590
+ ".class": "OverloadedFuncDef",
591
+ "items": [i.serialize() for i in self.items],
592
+ "type": None if self.type is None else self.type.serialize(),
593
+ "fullname": self._fullname,
594
+ "impl": None if self.impl is None else self.impl.serialize(),
595
+ "flags": get_flags(self, FUNCBASE_FLAGS),
596
+ }
597
+
598
+ @classmethod
599
+ def deserialize(cls, data: JsonDict) -> OverloadedFuncDef:
600
+ assert data[".class"] == "OverloadedFuncDef"
601
+ res = OverloadedFuncDef(
602
+ [cast(OverloadPart, SymbolNode.deserialize(d)) for d in data["items"]]
603
+ )
604
+ if data.get("impl") is not None:
605
+ res.impl = cast(OverloadPart, SymbolNode.deserialize(data["impl"]))
606
+ # set line for empty overload items, as not set in __init__
607
+ if len(res.items) > 0:
608
+ res.set_line(res.impl.line)
609
+ if data.get("type") is not None:
610
+ typ = mypy.types.deserialize_type(data["type"])
611
+ assert isinstance(typ, mypy.types.ProperType)
612
+ res.type = typ
613
+ res._fullname = data["fullname"]
614
+ set_flags(res, data["flags"])
615
+ # NOTE: res.info will be set in the fixup phase.
616
+ return res
617
+
618
+
619
+ class Argument(Node):
620
+ """A single argument in a FuncItem."""
621
+
622
+ __slots__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
623
+
624
+ __match_args__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
625
+
626
+ def __init__(
627
+ self,
628
+ variable: Var,
629
+ type_annotation: mypy.types.Type | None,
630
+ initializer: Expression | None,
631
+ kind: ArgKind,
632
+ pos_only: bool = False,
633
+ ) -> None:
634
+ super().__init__()
635
+ self.variable = variable
636
+ self.type_annotation = type_annotation
637
+ self.initializer = initializer
638
+ self.kind = kind # must be an ARG_* constant
639
+ self.pos_only = pos_only
640
+
641
+ def set_line(
642
+ self,
643
+ target: Context | int,
644
+ column: int | None = None,
645
+ end_line: int | None = None,
646
+ end_column: int | None = None,
647
+ ) -> None:
648
+ super().set_line(target, column, end_line, end_column)
649
+
650
+ if self.initializer and self.initializer.line < 0:
651
+ self.initializer.set_line(self.line, self.column, self.end_line, self.end_column)
652
+
653
+ self.variable.set_line(self.line, self.column, self.end_line, self.end_column)
654
+
655
+
656
+ FUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [
657
+ "is_overload",
658
+ "is_generator",
659
+ "is_coroutine",
660
+ "is_async_generator",
661
+ "is_awaitable_coroutine",
662
+ ]
663
+
664
+
665
+ class FuncItem(FuncBase):
666
+ """Base class for nodes usable as overloaded function items."""
667
+
668
+ __slots__ = (
669
+ "arguments", # Note that can be unset if deserialized (type is a lie!)
670
+ "arg_names", # Names of arguments
671
+ "arg_kinds", # Kinds of arguments
672
+ "min_args", # Minimum number of arguments
673
+ "max_pos", # Maximum number of positional arguments, -1 if no explicit
674
+ # limit (*args not included)
675
+ "body", # Body of the function
676
+ "is_overload", # Is this an overload variant of function with more than
677
+ # one overload variant?
678
+ "is_generator", # Contains a yield statement?
679
+ "is_coroutine", # Defined using 'async def' syntax?
680
+ "is_async_generator", # Is an async def generator?
681
+ "is_awaitable_coroutine", # Decorated with '@{typing,asyncio}.coroutine'?
682
+ "expanded", # Variants of function with type variables with values expanded
683
+ )
684
+
685
+ __deletable__ = ("arguments", "max_pos", "min_args")
686
+
687
+ def __init__(
688
+ self,
689
+ arguments: list[Argument] | None = None,
690
+ body: Block | None = None,
691
+ typ: mypy.types.FunctionLike | None = None,
692
+ ) -> None:
693
+ super().__init__()
694
+ self.arguments = arguments or []
695
+ self.arg_names = [None if arg.pos_only else arg.variable.name for arg in self.arguments]
696
+ self.arg_kinds: list[ArgKind] = [arg.kind for arg in self.arguments]
697
+ self.max_pos: int = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT)
698
+ self.body: Block = body or Block([])
699
+ self.type = typ
700
+ self.unanalyzed_type = typ
701
+ self.is_overload: bool = False
702
+ self.is_generator: bool = False
703
+ self.is_coroutine: bool = False
704
+ self.is_async_generator: bool = False
705
+ self.is_awaitable_coroutine: bool = False
706
+ self.expanded: list[FuncItem] = []
707
+
708
+ self.min_args = 0
709
+ for i in range(len(self.arguments)):
710
+ if self.arguments[i] is None and i < self.max_fixed_argc():
711
+ self.min_args = i + 1
712
+
713
+ def max_fixed_argc(self) -> int:
714
+ return self.max_pos
715
+
716
+ def is_dynamic(self) -> bool:
717
+ return self.type is None
718
+
719
+
720
+ FUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [
721
+ "is_decorated",
722
+ "is_conditional",
723
+ "is_trivial_body",
724
+ "is_mypy_only",
725
+ ]
726
+
727
+ # Abstract status of a function
728
+ NOT_ABSTRACT: Final = 0
729
+ # Explicitly abstract (with @abstractmethod or overload without implementation)
730
+ IS_ABSTRACT: Final = 1
731
+ # Implicitly abstract: used for functions with trivial bodies defined in Protocols
732
+ IMPLICITLY_ABSTRACT: Final = 2
733
+
734
+
735
+ class FuncDef(FuncItem, SymbolNode, Statement):
736
+ """Function definition.
737
+
738
+ This is a non-lambda function defined using 'def'.
739
+ """
740
+
741
+ __slots__ = (
742
+ "_name",
743
+ "is_decorated",
744
+ "is_conditional",
745
+ "abstract_status",
746
+ "original_def",
747
+ "deco_line",
748
+ "is_trivial_body",
749
+ "is_mypy_only",
750
+ # Present only when a function is decorated with @typing.datasclass_transform or similar
751
+ "dataclass_transform_spec",
752
+ "docstring",
753
+ )
754
+
755
+ __match_args__ = ("name", "arguments", "type", "body")
756
+
757
+ # Note that all __init__ args must have default values
758
+ def __init__(
759
+ self,
760
+ name: str = "", # Function name
761
+ arguments: list[Argument] | None = None,
762
+ body: Block | None = None,
763
+ typ: mypy.types.FunctionLike | None = None,
764
+ ) -> None:
765
+ super().__init__(arguments, body, typ)
766
+ self._name = name
767
+ self.is_decorated = False
768
+ self.is_conditional = False # Defined conditionally (within block)?
769
+ self.abstract_status = NOT_ABSTRACT
770
+ # Is this an abstract method with trivial body?
771
+ # Such methods can't be called via super().
772
+ self.is_trivial_body = False
773
+ # Original conditional definition
774
+ self.original_def: None | FuncDef | Var | Decorator = None
775
+ # Used for error reporting (to keep backward compatibility with pre-3.8)
776
+ self.deco_line: int | None = None
777
+ # Definitions that appear in if TYPE_CHECKING are marked with this flag.
778
+ self.is_mypy_only = False
779
+ self.dataclass_transform_spec: DataclassTransformSpec | None = None
780
+ self.docstring: str | None = None
781
+
782
+ @property
783
+ def name(self) -> str:
784
+ return self._name
785
+
786
+ def accept(self, visitor: StatementVisitor[T]) -> T:
787
+ return visitor.visit_func_def(self)
788
+
789
+ def serialize(self) -> JsonDict:
790
+ # We're deliberating omitting arguments and storing only arg_names and
791
+ # arg_kinds for space-saving reasons (arguments is not used in later
792
+ # stages of mypy).
793
+ # TODO: After a FuncDef is deserialized, the only time we use `arg_names`
794
+ # and `arg_kinds` is when `type` is None and we need to infer a type. Can
795
+ # we store the inferred type ahead of time?
796
+ return {
797
+ ".class": "FuncDef",
798
+ "name": self._name,
799
+ "fullname": self._fullname,
800
+ "arg_names": self.arg_names,
801
+ "arg_kinds": [int(x.value) for x in self.arg_kinds],
802
+ "type": None if self.type is None else self.type.serialize(),
803
+ "flags": get_flags(self, FUNCDEF_FLAGS),
804
+ "abstract_status": self.abstract_status,
805
+ # TODO: Do we need expanded, original_def?
806
+ "dataclass_transform_spec": (
807
+ None
808
+ if self.dataclass_transform_spec is None
809
+ else self.dataclass_transform_spec.serialize()
810
+ ),
811
+ }
812
+
813
+ @classmethod
814
+ def deserialize(cls, data: JsonDict) -> FuncDef:
815
+ assert data[".class"] == "FuncDef"
816
+ body = Block([])
817
+ ret = FuncDef(
818
+ data["name"],
819
+ [],
820
+ body,
821
+ (
822
+ None
823
+ if data["type"] is None
824
+ else cast(mypy.types.FunctionLike, mypy.types.deserialize_type(data["type"]))
825
+ ),
826
+ )
827
+ ret._fullname = data["fullname"]
828
+ set_flags(ret, data["flags"])
829
+ # NOTE: ret.info is set in the fixup phase.
830
+ ret.arg_names = data["arg_names"]
831
+ ret.arg_kinds = [ArgKind(x) for x in data["arg_kinds"]]
832
+ ret.abstract_status = data["abstract_status"]
833
+ ret.dataclass_transform_spec = (
834
+ DataclassTransformSpec.deserialize(data["dataclass_transform_spec"])
835
+ if data["dataclass_transform_spec"] is not None
836
+ else None
837
+ )
838
+ # Leave these uninitialized so that future uses will trigger an error
839
+ del ret.arguments
840
+ del ret.max_pos
841
+ del ret.min_args
842
+ return ret
843
+
844
+
845
+ # All types that are both SymbolNodes and FuncBases. See the FuncBase
846
+ # docstring for the rationale.
847
+ SYMBOL_FUNCBASE_TYPES = (OverloadedFuncDef, FuncDef)
848
+
849
+
850
+ class Decorator(SymbolNode, Statement):
851
+ """A decorated function.
852
+
853
+ A single Decorator object can include any number of function decorators.
854
+ """
855
+
856
+ __slots__ = ("func", "decorators", "original_decorators", "var", "is_overload")
857
+
858
+ __match_args__ = ("decorators", "var", "func")
859
+
860
+ func: FuncDef # Decorated function
861
+ decorators: list[Expression] # Decorators (may be empty)
862
+ # Some decorators are removed by semanal, keep the original here.
863
+ original_decorators: list[Expression]
864
+ # TODO: This is mostly used for the type; consider replacing with a 'type' attribute
865
+ var: Var # Represents the decorated function obj
866
+ is_overload: bool
867
+
868
+ def __init__(self, func: FuncDef, decorators: list[Expression], var: Var) -> None:
869
+ super().__init__()
870
+ self.func = func
871
+ self.decorators = decorators
872
+ self.original_decorators = decorators.copy()
873
+ self.var = var
874
+ self.is_overload = False
875
+
876
+ @property
877
+ def name(self) -> str:
878
+ return self.func.name
879
+
880
+ @property
881
+ def fullname(self) -> str:
882
+ return self.func.fullname
883
+
884
+ @property
885
+ def is_final(self) -> bool:
886
+ return self.func.is_final
887
+
888
+ @property
889
+ def info(self) -> TypeInfo:
890
+ return self.func.info
891
+
892
+ @property
893
+ def type(self) -> mypy.types.Type | None:
894
+ return self.var.type
895
+
896
+ def accept(self, visitor: StatementVisitor[T]) -> T:
897
+ return visitor.visit_decorator(self)
898
+
899
+ def serialize(self) -> JsonDict:
900
+ return {
901
+ ".class": "Decorator",
902
+ "func": self.func.serialize(),
903
+ "var": self.var.serialize(),
904
+ "is_overload": self.is_overload,
905
+ }
906
+
907
+ @classmethod
908
+ def deserialize(cls, data: JsonDict) -> Decorator:
909
+ assert data[".class"] == "Decorator"
910
+ dec = Decorator(FuncDef.deserialize(data["func"]), [], Var.deserialize(data["var"]))
911
+ dec.is_overload = data["is_overload"]
912
+ return dec
913
+
914
+
915
+ VAR_FLAGS: Final = [
916
+ "is_self",
917
+ "is_cls",
918
+ "is_initialized_in_class",
919
+ "is_staticmethod",
920
+ "is_classmethod",
921
+ "is_property",
922
+ "is_settable_property",
923
+ "is_suppressed_import",
924
+ "is_classvar",
925
+ "is_abstract_var",
926
+ "is_final",
927
+ "final_unset_in_class",
928
+ "final_set_in_init",
929
+ "explicit_self_type",
930
+ "is_ready",
931
+ "is_inferred",
932
+ "invalid_partial_type",
933
+ "from_module_getattr",
934
+ "has_explicit_value",
935
+ "allow_incompatible_override",
936
+ ]
937
+
938
+
939
+ class Var(SymbolNode):
940
+ """A variable.
941
+
942
+ It can refer to global/local variable or a data attribute.
943
+ """
944
+
945
+ __slots__ = (
946
+ "_name",
947
+ "_fullname",
948
+ "info",
949
+ "type",
950
+ "final_value",
951
+ "is_self",
952
+ "is_cls",
953
+ "is_ready",
954
+ "is_inferred",
955
+ "is_initialized_in_class",
956
+ "is_staticmethod",
957
+ "is_classmethod",
958
+ "is_property",
959
+ "is_settable_property",
960
+ "is_classvar",
961
+ "is_abstract_var",
962
+ "is_final",
963
+ "final_unset_in_class",
964
+ "final_set_in_init",
965
+ "is_suppressed_import",
966
+ "explicit_self_type",
967
+ "from_module_getattr",
968
+ "has_explicit_value",
969
+ "allow_incompatible_override",
970
+ "invalid_partial_type",
971
+ )
972
+
973
+ __match_args__ = ("name", "type", "final_value")
974
+
975
+ def __init__(self, name: str, type: mypy.types.Type | None = None) -> None:
976
+ super().__init__()
977
+ self._name = name # Name without module prefix
978
+ # TODO: Should be Optional[str]
979
+ self._fullname = "" # Name with module prefix
980
+ # TODO: Should be Optional[TypeInfo]
981
+ self.info = VAR_NO_INFO
982
+ self.type: mypy.types.Type | None = type # Declared or inferred type, or None
983
+ # Is this the first argument to an ordinary method (usually "self")?
984
+ self.is_self = False
985
+ # Is this the first argument to a classmethod (typically "cls")?
986
+ self.is_cls = False
987
+ self.is_ready = True # If inferred, is the inferred type available?
988
+ self.is_inferred = self.type is None
989
+ # Is this initialized explicitly to a non-None value in class body?
990
+ self.is_initialized_in_class = False
991
+ self.is_staticmethod = False
992
+ self.is_classmethod = False
993
+ self.is_property = False
994
+ self.is_settable_property = False
995
+ self.is_classvar = False
996
+ self.is_abstract_var = False
997
+ # Set to true when this variable refers to a module we were unable to
998
+ # parse for some reason (eg a silenced module)
999
+ self.is_suppressed_import = False
1000
+ # Was this "variable" (rather a constant) defined as Final[...]?
1001
+ self.is_final = False
1002
+ # If constant value is a simple literal,
1003
+ # store the literal value (unboxed) for the benefit of
1004
+ # tools like mypyc.
1005
+ self.final_value: int | float | complex | bool | str | None = None
1006
+ # Where the value was set (only for class attributes)
1007
+ self.final_unset_in_class = False
1008
+ self.final_set_in_init = False
1009
+ # This is True for a variable that was declared on self with an explicit type:
1010
+ # class C:
1011
+ # def __init__(self) -> None:
1012
+ # self.x: int
1013
+ # This case is important because this defines a new Var, even if there is one
1014
+ # present in a superclass (without explicit type this doesn't create a new Var).
1015
+ # See SemanticAnalyzer.analyze_member_lvalue() for details.
1016
+ self.explicit_self_type = False
1017
+ # If True, this is an implicit Var created due to module-level __getattr__.
1018
+ self.from_module_getattr = False
1019
+ # Var can be created with an explicit value `a = 1` or without one `a: int`,
1020
+ # we need a way to tell which one is which.
1021
+ self.has_explicit_value = False
1022
+ # If True, subclasses can override this with an incompatible type.
1023
+ self.allow_incompatible_override = False
1024
+ # If True, this means we didn't manage to infer full type and fall back to
1025
+ # something like list[Any]. We may decide to not use such types as context.
1026
+ self.invalid_partial_type = False
1027
+
1028
+ @property
1029
+ def name(self) -> str:
1030
+ return self._name
1031
+
1032
+ @property
1033
+ def fullname(self) -> str:
1034
+ return self._fullname
1035
+
1036
+ def accept(self, visitor: NodeVisitor[T]) -> T:
1037
+ return visitor.visit_var(self)
1038
+
1039
+ def serialize(self) -> JsonDict:
1040
+ # TODO: Leave default values out?
1041
+ # NOTE: Sometimes self.is_ready is False here, but we don't care.
1042
+ data: JsonDict = {
1043
+ ".class": "Var",
1044
+ "name": self._name,
1045
+ "fullname": self._fullname,
1046
+ "type": None if self.type is None else self.type.serialize(),
1047
+ "flags": get_flags(self, VAR_FLAGS),
1048
+ }
1049
+ if self.final_value is not None:
1050
+ data["final_value"] = self.final_value
1051
+ return data
1052
+
1053
+ @classmethod
1054
+ def deserialize(cls, data: JsonDict) -> Var:
1055
+ assert data[".class"] == "Var"
1056
+ name = data["name"]
1057
+ type = None if data["type"] is None else mypy.types.deserialize_type(data["type"])
1058
+ v = Var(name, type)
1059
+ v.is_ready = False # Override True default set in __init__
1060
+ v._fullname = data["fullname"]
1061
+ set_flags(v, data["flags"])
1062
+ v.final_value = data.get("final_value")
1063
+ return v
1064
+
1065
+
1066
+ class ClassDef(Statement):
1067
+ """Class definition"""
1068
+
1069
+ __slots__ = (
1070
+ "name",
1071
+ "_fullname",
1072
+ "defs",
1073
+ "type_vars",
1074
+ "base_type_exprs",
1075
+ "removed_base_type_exprs",
1076
+ "info",
1077
+ "metaclass",
1078
+ "decorators",
1079
+ "keywords",
1080
+ "analyzed",
1081
+ "has_incompatible_baseclass",
1082
+ "deco_line",
1083
+ "docstring",
1084
+ "removed_statements",
1085
+ )
1086
+
1087
+ __match_args__ = ("name", "defs")
1088
+
1089
+ name: str # Name of the class without module prefix
1090
+ _fullname: str # Fully qualified name of the class
1091
+ defs: Block
1092
+ type_vars: list[mypy.types.TypeVarLikeType]
1093
+ # Base class expressions (not semantically analyzed -- can be arbitrary expressions)
1094
+ base_type_exprs: list[Expression]
1095
+ # Special base classes like Generic[...] get moved here during semantic analysis
1096
+ removed_base_type_exprs: list[Expression]
1097
+ info: TypeInfo # Related TypeInfo
1098
+ metaclass: Expression | None
1099
+ decorators: list[Expression]
1100
+ keywords: dict[str, Expression]
1101
+ analyzed: Expression | None
1102
+ has_incompatible_baseclass: bool
1103
+ # Used by special forms like NamedTuple and TypedDict to store invalid statements
1104
+ removed_statements: list[Statement]
1105
+
1106
+ def __init__(
1107
+ self,
1108
+ name: str,
1109
+ defs: Block,
1110
+ type_vars: list[mypy.types.TypeVarLikeType] | None = None,
1111
+ base_type_exprs: list[Expression] | None = None,
1112
+ metaclass: Expression | None = None,
1113
+ keywords: list[tuple[str, Expression]] | None = None,
1114
+ ) -> None:
1115
+ super().__init__()
1116
+ self.name = name
1117
+ self._fullname = ""
1118
+ self.defs = defs
1119
+ self.type_vars = type_vars or []
1120
+ self.base_type_exprs = base_type_exprs or []
1121
+ self.removed_base_type_exprs = []
1122
+ self.info = CLASSDEF_NO_INFO
1123
+ self.metaclass = metaclass
1124
+ self.decorators = []
1125
+ self.keywords = dict(keywords) if keywords else {}
1126
+ self.analyzed = None
1127
+ self.has_incompatible_baseclass = False
1128
+ # Used for error reporting (to keep backwad compatibility with pre-3.8)
1129
+ self.deco_line: int | None = None
1130
+ self.docstring: str | None = None
1131
+ self.removed_statements = []
1132
+
1133
+ @property
1134
+ def fullname(self) -> str:
1135
+ return self._fullname
1136
+
1137
+ @fullname.setter
1138
+ def fullname(self, v: str) -> None:
1139
+ self._fullname = v
1140
+
1141
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1142
+ return visitor.visit_class_def(self)
1143
+
1144
+ def is_generic(self) -> bool:
1145
+ return self.info.is_generic()
1146
+
1147
+ def serialize(self) -> JsonDict:
1148
+ # Not serialized: defs, base_type_exprs, metaclass, decorators,
1149
+ # analyzed (for named tuples etc.)
1150
+ return {
1151
+ ".class": "ClassDef",
1152
+ "name": self.name,
1153
+ "fullname": self.fullname,
1154
+ "type_vars": [v.serialize() for v in self.type_vars],
1155
+ }
1156
+
1157
+ @classmethod
1158
+ def deserialize(cls, data: JsonDict) -> ClassDef:
1159
+ assert data[".class"] == "ClassDef"
1160
+ res = ClassDef(
1161
+ data["name"],
1162
+ Block([]),
1163
+ # https://github.com/python/mypy/issues/12257
1164
+ [
1165
+ cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v))
1166
+ for v in data["type_vars"]
1167
+ ],
1168
+ )
1169
+ res.fullname = data["fullname"]
1170
+ return res
1171
+
1172
+
1173
+ class GlobalDecl(Statement):
1174
+ """Declaration global x, y, ..."""
1175
+
1176
+ __slots__ = ("names",)
1177
+
1178
+ __match_args__ = ("names",)
1179
+
1180
+ names: list[str]
1181
+
1182
+ def __init__(self, names: list[str]) -> None:
1183
+ super().__init__()
1184
+ self.names = names
1185
+
1186
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1187
+ return visitor.visit_global_decl(self)
1188
+
1189
+
1190
+ class NonlocalDecl(Statement):
1191
+ """Declaration nonlocal x, y, ..."""
1192
+
1193
+ __slots__ = ("names",)
1194
+
1195
+ __match_args__ = ("names",)
1196
+
1197
+ names: list[str]
1198
+
1199
+ def __init__(self, names: list[str]) -> None:
1200
+ super().__init__()
1201
+ self.names = names
1202
+
1203
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1204
+ return visitor.visit_nonlocal_decl(self)
1205
+
1206
+
1207
+ class Block(Statement):
1208
+ __slots__ = ("body", "is_unreachable")
1209
+
1210
+ __match_args__ = ("body", "is_unreachable")
1211
+
1212
+ def __init__(self, body: list[Statement]) -> None:
1213
+ super().__init__()
1214
+ self.body = body
1215
+ # True if we can determine that this block is not executed during semantic
1216
+ # analysis. For example, this applies to blocks that are protected by
1217
+ # something like "if PY3:" when using Python 2. However, some code is
1218
+ # only considered unreachable during type checking and this is not true
1219
+ # in those cases.
1220
+ self.is_unreachable = False
1221
+
1222
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1223
+ return visitor.visit_block(self)
1224
+
1225
+
1226
+ # Statements
1227
+
1228
+
1229
+ class ExpressionStmt(Statement):
1230
+ """An expression as a statement, such as print(s)."""
1231
+
1232
+ __slots__ = ("expr",)
1233
+
1234
+ __match_args__ = ("expr",)
1235
+
1236
+ expr: Expression
1237
+
1238
+ def __init__(self, expr: Expression) -> None:
1239
+ super().__init__()
1240
+ self.expr = expr
1241
+
1242
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1243
+ return visitor.visit_expression_stmt(self)
1244
+
1245
+
1246
+ class AssignmentStmt(Statement):
1247
+ """Assignment statement.
1248
+
1249
+ The same node class is used for single assignment, multiple assignment
1250
+ (e.g. x, y = z) and chained assignment (e.g. x = y = z), assignments
1251
+ that define new names, and assignments with explicit types ("# type: t"
1252
+ or "x: t [= ...]").
1253
+
1254
+ An lvalue can be NameExpr, TupleExpr, ListExpr, MemberExpr, or IndexExpr.
1255
+ """
1256
+
1257
+ __slots__ = (
1258
+ "lvalues",
1259
+ "rvalue",
1260
+ "type",
1261
+ "unanalyzed_type",
1262
+ "new_syntax",
1263
+ "is_alias_def",
1264
+ "is_final_def",
1265
+ "invalid_recursive_alias",
1266
+ )
1267
+
1268
+ __match_args__ = ("lvalues", "rvalues", "type")
1269
+
1270
+ lvalues: list[Lvalue]
1271
+ # This is a TempNode if and only if no rvalue (x: t).
1272
+ rvalue: Expression
1273
+ # Declared type in a comment, may be None.
1274
+ type: mypy.types.Type | None
1275
+ # Original, not semantically analyzed type in annotation (used for reprocessing)
1276
+ unanalyzed_type: mypy.types.Type | None
1277
+ # This indicates usage of PEP 526 type annotation syntax in assignment.
1278
+ new_syntax: bool
1279
+ # Does this assignment define a type alias?
1280
+ is_alias_def: bool
1281
+ # Is this a final definition?
1282
+ # Final attributes can't be re-assigned once set, and can't be overridden
1283
+ # in a subclass. This flag is not set if an attempted declaration was found to
1284
+ # be invalid during semantic analysis. It is still set to `True` if
1285
+ # a final declaration overrides another final declaration (this is checked
1286
+ # during type checking when MROs are known).
1287
+ is_final_def: bool
1288
+ # Stop further processing of this assignment, to prevent flipping back and forth
1289
+ # during semantic analysis passes.
1290
+ invalid_recursive_alias: bool
1291
+
1292
+ def __init__(
1293
+ self,
1294
+ lvalues: list[Lvalue],
1295
+ rvalue: Expression,
1296
+ type: mypy.types.Type | None = None,
1297
+ new_syntax: bool = False,
1298
+ ) -> None:
1299
+ super().__init__()
1300
+ self.lvalues = lvalues
1301
+ self.rvalue = rvalue
1302
+ self.type = type
1303
+ self.unanalyzed_type = type
1304
+ self.new_syntax = new_syntax
1305
+ self.is_alias_def = False
1306
+ self.is_final_def = False
1307
+ self.invalid_recursive_alias = False
1308
+
1309
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1310
+ return visitor.visit_assignment_stmt(self)
1311
+
1312
+
1313
+ class OperatorAssignmentStmt(Statement):
1314
+ """Operator assignment statement such as x += 1"""
1315
+
1316
+ __slots__ = ("op", "lvalue", "rvalue")
1317
+
1318
+ __match_args__ = ("lvalue", "op", "rvalue")
1319
+
1320
+ op: str # TODO: Enum?
1321
+ lvalue: Lvalue
1322
+ rvalue: Expression
1323
+
1324
+ def __init__(self, op: str, lvalue: Lvalue, rvalue: Expression) -> None:
1325
+ super().__init__()
1326
+ self.op = op
1327
+ self.lvalue = lvalue
1328
+ self.rvalue = rvalue
1329
+
1330
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1331
+ return visitor.visit_operator_assignment_stmt(self)
1332
+
1333
+
1334
+ class WhileStmt(Statement):
1335
+ __slots__ = ("expr", "body", "else_body")
1336
+
1337
+ __match_args__ = ("expr", "body", "else_body")
1338
+
1339
+ expr: Expression
1340
+ body: Block
1341
+ else_body: Block | None
1342
+
1343
+ def __init__(self, expr: Expression, body: Block, else_body: Block | None) -> None:
1344
+ super().__init__()
1345
+ self.expr = expr
1346
+ self.body = body
1347
+ self.else_body = else_body
1348
+
1349
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1350
+ return visitor.visit_while_stmt(self)
1351
+
1352
+
1353
+ class ForStmt(Statement):
1354
+ __slots__ = (
1355
+ "index",
1356
+ "index_type",
1357
+ "unanalyzed_index_type",
1358
+ "inferred_item_type",
1359
+ "inferred_iterator_type",
1360
+ "expr",
1361
+ "body",
1362
+ "else_body",
1363
+ "is_async",
1364
+ )
1365
+
1366
+ __match_args__ = ("index", "index_type", "expr", "body", "else_body")
1367
+
1368
+ # Index variables
1369
+ index: Lvalue
1370
+ # Type given by type comments for index, can be None
1371
+ index_type: mypy.types.Type | None
1372
+ # Original, not semantically analyzed type in annotation (used for reprocessing)
1373
+ unanalyzed_index_type: mypy.types.Type | None
1374
+ # Inferred iterable item type
1375
+ inferred_item_type: mypy.types.Type | None
1376
+ # Inferred iterator type
1377
+ inferred_iterator_type: mypy.types.Type | None
1378
+ # Expression to iterate
1379
+ expr: Expression
1380
+ body: Block
1381
+ else_body: Block | None
1382
+ is_async: bool # True if `async for ...` (PEP 492, Python 3.5)
1383
+
1384
+ def __init__(
1385
+ self,
1386
+ index: Lvalue,
1387
+ expr: Expression,
1388
+ body: Block,
1389
+ else_body: Block | None,
1390
+ index_type: mypy.types.Type | None = None,
1391
+ ) -> None:
1392
+ super().__init__()
1393
+ self.index = index
1394
+ self.index_type = index_type
1395
+ self.unanalyzed_index_type = index_type
1396
+ self.inferred_item_type = None
1397
+ self.inferred_iterator_type = None
1398
+ self.expr = expr
1399
+ self.body = body
1400
+ self.else_body = else_body
1401
+ self.is_async = False
1402
+
1403
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1404
+ return visitor.visit_for_stmt(self)
1405
+
1406
+
1407
+ class ReturnStmt(Statement):
1408
+ __slots__ = ("expr",)
1409
+
1410
+ __match_args__ = ("expr",)
1411
+
1412
+ expr: Expression | None
1413
+
1414
+ def __init__(self, expr: Expression | None) -> None:
1415
+ super().__init__()
1416
+ self.expr = expr
1417
+
1418
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1419
+ return visitor.visit_return_stmt(self)
1420
+
1421
+
1422
+ class AssertStmt(Statement):
1423
+ __slots__ = ("expr", "msg")
1424
+
1425
+ __match_args__ = ("expr", "msg")
1426
+
1427
+ expr: Expression
1428
+ msg: Expression | None
1429
+
1430
+ def __init__(self, expr: Expression, msg: Expression | None = None) -> None:
1431
+ super().__init__()
1432
+ self.expr = expr
1433
+ self.msg = msg
1434
+
1435
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1436
+ return visitor.visit_assert_stmt(self)
1437
+
1438
+
1439
+ class DelStmt(Statement):
1440
+ __slots__ = ("expr",)
1441
+
1442
+ __match_args__ = ("expr",)
1443
+
1444
+ expr: Lvalue
1445
+
1446
+ def __init__(self, expr: Lvalue) -> None:
1447
+ super().__init__()
1448
+ self.expr = expr
1449
+
1450
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1451
+ return visitor.visit_del_stmt(self)
1452
+
1453
+
1454
+ class BreakStmt(Statement):
1455
+ __slots__ = ()
1456
+
1457
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1458
+ return visitor.visit_break_stmt(self)
1459
+
1460
+
1461
+ class ContinueStmt(Statement):
1462
+ __slots__ = ()
1463
+
1464
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1465
+ return visitor.visit_continue_stmt(self)
1466
+
1467
+
1468
+ class PassStmt(Statement):
1469
+ __slots__ = ()
1470
+
1471
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1472
+ return visitor.visit_pass_stmt(self)
1473
+
1474
+
1475
+ class IfStmt(Statement):
1476
+ __slots__ = ("expr", "body", "else_body")
1477
+
1478
+ __match_args__ = ("expr", "body", "else_body")
1479
+
1480
+ expr: list[Expression]
1481
+ body: list[Block]
1482
+ else_body: Block | None
1483
+
1484
+ def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None:
1485
+ super().__init__()
1486
+ self.expr = expr
1487
+ self.body = body
1488
+ self.else_body = else_body
1489
+
1490
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1491
+ return visitor.visit_if_stmt(self)
1492
+
1493
+
1494
+ class RaiseStmt(Statement):
1495
+ __slots__ = ("expr", "from_expr")
1496
+
1497
+ __match_args__ = ("expr", "from_expr")
1498
+
1499
+ # Plain 'raise' is a valid statement.
1500
+ expr: Expression | None
1501
+ from_expr: Expression | None
1502
+
1503
+ def __init__(self, expr: Expression | None, from_expr: Expression | None) -> None:
1504
+ super().__init__()
1505
+ self.expr = expr
1506
+ self.from_expr = from_expr
1507
+
1508
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1509
+ return visitor.visit_raise_stmt(self)
1510
+
1511
+
1512
+ class TryStmt(Statement):
1513
+ __slots__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star")
1514
+
1515
+ __match_args__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star")
1516
+
1517
+ body: Block # Try body
1518
+ # Plain 'except:' also possible
1519
+ types: list[Expression | None] # Except type expressions
1520
+ vars: list[NameExpr | None] # Except variable names
1521
+ handlers: list[Block] # Except bodies
1522
+ else_body: Block | None
1523
+ finally_body: Block | None
1524
+ # Whether this is try ... except* (added in Python 3.11)
1525
+ is_star: bool
1526
+
1527
+ def __init__(
1528
+ self,
1529
+ body: Block,
1530
+ vars: list[NameExpr | None],
1531
+ types: list[Expression | None],
1532
+ handlers: list[Block],
1533
+ else_body: Block | None,
1534
+ finally_body: Block | None,
1535
+ ) -> None:
1536
+ super().__init__()
1537
+ self.body = body
1538
+ self.vars = vars
1539
+ self.types = types
1540
+ self.handlers = handlers
1541
+ self.else_body = else_body
1542
+ self.finally_body = finally_body
1543
+ self.is_star = False
1544
+
1545
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1546
+ return visitor.visit_try_stmt(self)
1547
+
1548
+
1549
+ class WithStmt(Statement):
1550
+ __slots__ = ("expr", "target", "unanalyzed_type", "analyzed_types", "body", "is_async")
1551
+
1552
+ __match_args__ = ("expr", "target", "body")
1553
+
1554
+ expr: list[Expression]
1555
+ target: list[Lvalue | None]
1556
+ # Type given by type comments for target, can be None
1557
+ unanalyzed_type: mypy.types.Type | None
1558
+ # Semantically analyzed types from type comment (TypeList type expanded)
1559
+ analyzed_types: list[mypy.types.Type]
1560
+ body: Block
1561
+ is_async: bool # True if `async with ...` (PEP 492, Python 3.5)
1562
+
1563
+ def __init__(
1564
+ self,
1565
+ expr: list[Expression],
1566
+ target: list[Lvalue | None],
1567
+ body: Block,
1568
+ target_type: mypy.types.Type | None = None,
1569
+ ) -> None:
1570
+ super().__init__()
1571
+ self.expr = expr
1572
+ self.target = target
1573
+ self.unanalyzed_type = target_type
1574
+ self.analyzed_types = []
1575
+ self.body = body
1576
+ self.is_async = False
1577
+
1578
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1579
+ return visitor.visit_with_stmt(self)
1580
+
1581
+
1582
+ class MatchStmt(Statement):
1583
+ __slots__ = ("subject", "patterns", "guards", "bodies")
1584
+
1585
+ __match_args__ = ("subject", "patterns", "guards", "bodies")
1586
+
1587
+ subject: Expression
1588
+ patterns: list[Pattern]
1589
+ guards: list[Expression | None]
1590
+ bodies: list[Block]
1591
+
1592
+ def __init__(
1593
+ self,
1594
+ subject: Expression,
1595
+ patterns: list[Pattern],
1596
+ guards: list[Expression | None],
1597
+ bodies: list[Block],
1598
+ ) -> None:
1599
+ super().__init__()
1600
+ assert len(patterns) == len(guards) == len(bodies)
1601
+ self.subject = subject
1602
+ self.patterns = patterns
1603
+ self.guards = guards
1604
+ self.bodies = bodies
1605
+
1606
+ def accept(self, visitor: StatementVisitor[T]) -> T:
1607
+ return visitor.visit_match_stmt(self)
1608
+
1609
+
1610
+ # Expressions
1611
+
1612
+
1613
+ class IntExpr(Expression):
1614
+ """Integer literal"""
1615
+
1616
+ __slots__ = ("value",)
1617
+
1618
+ __match_args__ = ("value",)
1619
+
1620
+ value: int # 0 by default
1621
+
1622
+ def __init__(self, value: int) -> None:
1623
+ super().__init__()
1624
+ self.value = value
1625
+
1626
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1627
+ return visitor.visit_int_expr(self)
1628
+
1629
+
1630
+ # How mypy uses StrExpr and BytesExpr:
1631
+ #
1632
+ # b'x' -> BytesExpr
1633
+ # 'x', u'x' -> StrExpr
1634
+
1635
+
1636
+ class StrExpr(Expression):
1637
+ """String literal"""
1638
+
1639
+ __slots__ = ("value",)
1640
+
1641
+ __match_args__ = ("value",)
1642
+
1643
+ value: str # '' by default
1644
+
1645
+ def __init__(self, value: str) -> None:
1646
+ super().__init__()
1647
+ self.value = value
1648
+
1649
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1650
+ return visitor.visit_str_expr(self)
1651
+
1652
+
1653
+ def is_StrExpr_list(seq: list[Expression]) -> TypeGuard[list[StrExpr]]:
1654
+ return all(isinstance(item, StrExpr) for item in seq)
1655
+
1656
+
1657
+ class BytesExpr(Expression):
1658
+ """Bytes literal"""
1659
+
1660
+ __slots__ = ("value",)
1661
+
1662
+ __match_args__ = ("value",)
1663
+
1664
+ # Note: we deliberately do NOT use bytes here because it ends up
1665
+ # unnecessarily complicating a lot of the result logic. For example,
1666
+ # we'd have to worry about converting the bytes into a format we can
1667
+ # easily serialize/deserialize to and from JSON, would have to worry
1668
+ # about turning the bytes into a human-readable representation in
1669
+ # error messages...
1670
+ #
1671
+ # It's more convenient to just store the human-readable representation
1672
+ # from the very start.
1673
+ value: str
1674
+
1675
+ def __init__(self, value: str) -> None:
1676
+ super().__init__()
1677
+ self.value = value
1678
+
1679
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1680
+ return visitor.visit_bytes_expr(self)
1681
+
1682
+
1683
+ class FloatExpr(Expression):
1684
+ """Float literal"""
1685
+
1686
+ __slots__ = ("value",)
1687
+
1688
+ __match_args__ = ("value",)
1689
+
1690
+ value: float # 0.0 by default
1691
+
1692
+ def __init__(self, value: float) -> None:
1693
+ super().__init__()
1694
+ self.value = value
1695
+
1696
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1697
+ return visitor.visit_float_expr(self)
1698
+
1699
+
1700
+ class ComplexExpr(Expression):
1701
+ """Complex literal"""
1702
+
1703
+ __slots__ = ("value",)
1704
+
1705
+ __match_args__ = ("value",)
1706
+
1707
+ value: complex
1708
+
1709
+ def __init__(self, value: complex) -> None:
1710
+ super().__init__()
1711
+ self.value = value
1712
+
1713
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1714
+ return visitor.visit_complex_expr(self)
1715
+
1716
+
1717
+ class EllipsisExpr(Expression):
1718
+ """Ellipsis (...)"""
1719
+
1720
+ __slots__ = ()
1721
+
1722
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1723
+ return visitor.visit_ellipsis(self)
1724
+
1725
+
1726
+ class StarExpr(Expression):
1727
+ """Star expression"""
1728
+
1729
+ __slots__ = ("expr", "valid")
1730
+
1731
+ __match_args__ = ("expr", "valid")
1732
+
1733
+ expr: Expression
1734
+ valid: bool
1735
+
1736
+ def __init__(self, expr: Expression) -> None:
1737
+ super().__init__()
1738
+ self.expr = expr
1739
+
1740
+ # Whether this starred expression is used in a tuple/list and as lvalue
1741
+ self.valid = False
1742
+
1743
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1744
+ return visitor.visit_star_expr(self)
1745
+
1746
+
1747
+ class RefExpr(Expression):
1748
+ """Abstract base class for name-like constructs"""
1749
+
1750
+ __slots__ = (
1751
+ "kind",
1752
+ "node",
1753
+ "_fullname",
1754
+ "is_new_def",
1755
+ "is_inferred_def",
1756
+ "is_alias_rvalue",
1757
+ "type_guard",
1758
+ )
1759
+
1760
+ def __init__(self) -> None:
1761
+ super().__init__()
1762
+ # LDEF/GDEF/MDEF/... (None if not available)
1763
+ self.kind: int | None = None
1764
+ # Var, FuncDef or TypeInfo that describes this
1765
+ self.node: SymbolNode | None = None
1766
+ # Fully qualified name (or name if not global)
1767
+ self._fullname = ""
1768
+ # Does this define a new name?
1769
+ self.is_new_def = False
1770
+ # Does this define a new name with inferred type?
1771
+ #
1772
+ # For members, after semantic analysis, this does not take base
1773
+ # classes into consideration at all; the type checker deals with these.
1774
+ self.is_inferred_def = False
1775
+ # Is this expression appears as an rvalue of a valid type alias definition?
1776
+ self.is_alias_rvalue = False
1777
+ # Cache type guard from callable_type.type_guard
1778
+ self.type_guard: mypy.types.Type | None = None
1779
+
1780
+ @property
1781
+ def fullname(self) -> str:
1782
+ return self._fullname
1783
+
1784
+ @fullname.setter
1785
+ def fullname(self, v: str) -> None:
1786
+ self._fullname = v
1787
+
1788
+
1789
+ class NameExpr(RefExpr):
1790
+ """Name expression
1791
+
1792
+ This refers to a local name, global name or a module.
1793
+ """
1794
+
1795
+ __slots__ = ("name", "is_special_form")
1796
+
1797
+ __match_args__ = ("name", "node")
1798
+
1799
+ def __init__(self, name: str) -> None:
1800
+ super().__init__()
1801
+ self.name = name # Name referred to
1802
+ # Is this a l.h.s. of a special form assignment like typed dict or type variable?
1803
+ self.is_special_form = False
1804
+
1805
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1806
+ return visitor.visit_name_expr(self)
1807
+
1808
+ def serialize(self) -> JsonDict:
1809
+ assert False, f"Serializing NameExpr: {self}"
1810
+
1811
+
1812
+ class MemberExpr(RefExpr):
1813
+ """Member access expression x.y"""
1814
+
1815
+ __slots__ = ("expr", "name", "def_var")
1816
+
1817
+ __match_args__ = ("expr", "name", "node")
1818
+
1819
+ def __init__(self, expr: Expression, name: str) -> None:
1820
+ super().__init__()
1821
+ self.expr = expr
1822
+ self.name = name
1823
+ # The variable node related to a definition through 'self.x = <initializer>'.
1824
+ # The nodes of other kinds of member expressions are resolved during type checking.
1825
+ self.def_var: Var | None = None
1826
+
1827
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1828
+ return visitor.visit_member_expr(self)
1829
+
1830
+
1831
+ # Kinds of arguments
1832
+ @unique
1833
+ class ArgKind(Enum):
1834
+ # Positional argument
1835
+ ARG_POS = 0
1836
+ # Positional, optional argument (functions only, not calls)
1837
+ ARG_OPT = 1
1838
+ # *arg argument
1839
+ ARG_STAR = 2
1840
+ # Keyword argument x=y in call, or keyword-only function arg
1841
+ ARG_NAMED = 3
1842
+ # **arg argument
1843
+ ARG_STAR2 = 4
1844
+ # In an argument list, keyword-only and also optional
1845
+ ARG_NAMED_OPT = 5
1846
+
1847
+ def is_positional(self, star: bool = False) -> bool:
1848
+ return self == ARG_POS or self == ARG_OPT or (star and self == ARG_STAR)
1849
+
1850
+ def is_named(self, star: bool = False) -> bool:
1851
+ return self == ARG_NAMED or self == ARG_NAMED_OPT or (star and self == ARG_STAR2)
1852
+
1853
+ def is_required(self) -> bool:
1854
+ return self == ARG_POS or self == ARG_NAMED
1855
+
1856
+ def is_optional(self) -> bool:
1857
+ return self == ARG_OPT or self == ARG_NAMED_OPT
1858
+
1859
+ def is_star(self) -> bool:
1860
+ return self == ARG_STAR or self == ARG_STAR2
1861
+
1862
+
1863
+ ARG_POS: Final = ArgKind.ARG_POS
1864
+ ARG_OPT: Final = ArgKind.ARG_OPT
1865
+ ARG_STAR: Final = ArgKind.ARG_STAR
1866
+ ARG_NAMED: Final = ArgKind.ARG_NAMED
1867
+ ARG_STAR2: Final = ArgKind.ARG_STAR2
1868
+ ARG_NAMED_OPT: Final = ArgKind.ARG_NAMED_OPT
1869
+
1870
+
1871
+ class CallExpr(Expression):
1872
+ """Call expression.
1873
+
1874
+ This can also represent several special forms that are syntactically calls
1875
+ such as cast(...) and None # type: ....
1876
+ """
1877
+
1878
+ __slots__ = ("callee", "args", "arg_kinds", "arg_names", "analyzed")
1879
+
1880
+ __match_args__ = ("callee", "args", "arg_kinds", "arg_names")
1881
+
1882
+ def __init__(
1883
+ self,
1884
+ callee: Expression,
1885
+ args: list[Expression],
1886
+ arg_kinds: list[ArgKind],
1887
+ arg_names: list[str | None],
1888
+ analyzed: Expression | None = None,
1889
+ ) -> None:
1890
+ super().__init__()
1891
+ if not arg_names:
1892
+ arg_names = [None] * len(args)
1893
+
1894
+ self.callee = callee
1895
+ self.args = args
1896
+ self.arg_kinds = arg_kinds # ARG_ constants
1897
+ # Each name can be None if not a keyword argument.
1898
+ self.arg_names: list[str | None] = arg_names
1899
+ # If not None, the node that represents the meaning of the CallExpr. For
1900
+ # cast(...) this is a CastExpr.
1901
+ self.analyzed = analyzed
1902
+
1903
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1904
+ return visitor.visit_call_expr(self)
1905
+
1906
+
1907
+ class YieldFromExpr(Expression):
1908
+ __slots__ = ("expr",)
1909
+
1910
+ __match_args__ = ("expr",)
1911
+
1912
+ expr: Expression
1913
+
1914
+ def __init__(self, expr: Expression) -> None:
1915
+ super().__init__()
1916
+ self.expr = expr
1917
+
1918
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1919
+ return visitor.visit_yield_from_expr(self)
1920
+
1921
+
1922
+ class YieldExpr(Expression):
1923
+ __slots__ = ("expr",)
1924
+
1925
+ __match_args__ = ("expr",)
1926
+
1927
+ expr: Expression | None
1928
+
1929
+ def __init__(self, expr: Expression | None) -> None:
1930
+ super().__init__()
1931
+ self.expr = expr
1932
+
1933
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1934
+ return visitor.visit_yield_expr(self)
1935
+
1936
+
1937
+ class IndexExpr(Expression):
1938
+ """Index expression x[y].
1939
+
1940
+ Also wraps type application such as List[int] as a special form.
1941
+ """
1942
+
1943
+ __slots__ = ("base", "index", "method_type", "analyzed")
1944
+
1945
+ __match_args__ = ("base", "index")
1946
+
1947
+ base: Expression
1948
+ index: Expression
1949
+ # Inferred __getitem__ method type
1950
+ method_type: mypy.types.Type | None
1951
+ # If not None, this is actually semantically a type application
1952
+ # Class[type, ...] or a type alias initializer.
1953
+ analyzed: TypeApplication | TypeAliasExpr | None
1954
+
1955
+ def __init__(self, base: Expression, index: Expression) -> None:
1956
+ super().__init__()
1957
+ self.base = base
1958
+ self.index = index
1959
+ self.method_type = None
1960
+ self.analyzed = None
1961
+
1962
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1963
+ return visitor.visit_index_expr(self)
1964
+
1965
+
1966
+ class UnaryExpr(Expression):
1967
+ """Unary operation"""
1968
+
1969
+ __slots__ = ("op", "expr", "method_type")
1970
+
1971
+ __match_args__ = ("op", "expr")
1972
+
1973
+ op: str # TODO: Enum?
1974
+ expr: Expression
1975
+ # Inferred operator method type
1976
+ method_type: mypy.types.Type | None
1977
+
1978
+ def __init__(self, op: str, expr: Expression) -> None:
1979
+ super().__init__()
1980
+ self.op = op
1981
+ self.expr = expr
1982
+ self.method_type = None
1983
+
1984
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
1985
+ return visitor.visit_unary_expr(self)
1986
+
1987
+
1988
+ class AssignmentExpr(Expression):
1989
+ """Assignment expressions in Python 3.8+, like "a := 2"."""
1990
+
1991
+ __slots__ = ("target", "value")
1992
+
1993
+ __match_args__ = ("target", "value")
1994
+
1995
+ def __init__(self, target: Expression, value: Expression) -> None:
1996
+ super().__init__()
1997
+ self.target = target
1998
+ self.value = value
1999
+
2000
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2001
+ return visitor.visit_assignment_expr(self)
2002
+
2003
+
2004
+ class OpExpr(Expression):
2005
+ """Binary operation.
2006
+
2007
+ The dot (.), [] and comparison operators have more specific nodes.
2008
+ """
2009
+
2010
+ __slots__ = (
2011
+ "op",
2012
+ "left",
2013
+ "right",
2014
+ "method_type",
2015
+ "right_always",
2016
+ "right_unreachable",
2017
+ "analyzed",
2018
+ )
2019
+
2020
+ __match_args__ = ("left", "op", "right")
2021
+
2022
+ op: str # TODO: Enum?
2023
+ left: Expression
2024
+ right: Expression
2025
+ # Inferred type for the operator method type (when relevant).
2026
+ method_type: mypy.types.Type | None
2027
+ # Per static analysis only: Is the right side going to be evaluated every time?
2028
+ right_always: bool
2029
+ # Per static analysis only: Is the right side unreachable?
2030
+ right_unreachable: bool
2031
+ # Used for expressions that represent a type "X | Y" in some contexts
2032
+ analyzed: TypeAliasExpr | None
2033
+
2034
+ def __init__(
2035
+ self, op: str, left: Expression, right: Expression, analyzed: TypeAliasExpr | None = None
2036
+ ) -> None:
2037
+ super().__init__()
2038
+ self.op = op
2039
+ self.left = left
2040
+ self.right = right
2041
+ self.method_type = None
2042
+ self.right_always = False
2043
+ self.right_unreachable = False
2044
+ self.analyzed = analyzed
2045
+
2046
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2047
+ return visitor.visit_op_expr(self)
2048
+
2049
+
2050
+ class ComparisonExpr(Expression):
2051
+ """Comparison expression (e.g. a < b > c < d)."""
2052
+
2053
+ __slots__ = ("operators", "operands", "method_types")
2054
+
2055
+ __match_args__ = ("operands", "operators")
2056
+
2057
+ operators: list[str]
2058
+ operands: list[Expression]
2059
+ # Inferred type for the operator methods (when relevant; None for 'is').
2060
+ method_types: list[mypy.types.Type | None]
2061
+
2062
+ def __init__(self, operators: list[str], operands: list[Expression]) -> None:
2063
+ super().__init__()
2064
+ self.operators = operators
2065
+ self.operands = operands
2066
+ self.method_types = []
2067
+
2068
+ def pairwise(self) -> Iterator[tuple[str, Expression, Expression]]:
2069
+ """If this comparison expr is "a < b is c == d", yields the sequence
2070
+ ("<", a, b), ("is", b, c), ("==", c, d)
2071
+ """
2072
+ for i, operator in enumerate(self.operators):
2073
+ yield operator, self.operands[i], self.operands[i + 1]
2074
+
2075
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2076
+ return visitor.visit_comparison_expr(self)
2077
+
2078
+
2079
+ class SliceExpr(Expression):
2080
+ """Slice expression (e.g. 'x:y', 'x:', '::2' or ':').
2081
+
2082
+ This is only valid as index in index expressions.
2083
+ """
2084
+
2085
+ __slots__ = ("begin_index", "end_index", "stride")
2086
+
2087
+ __match_args__ = ("begin_index", "end_index", "stride")
2088
+
2089
+ begin_index: Expression | None
2090
+ end_index: Expression | None
2091
+ stride: Expression | None
2092
+
2093
+ def __init__(
2094
+ self,
2095
+ begin_index: Expression | None,
2096
+ end_index: Expression | None,
2097
+ stride: Expression | None,
2098
+ ) -> None:
2099
+ super().__init__()
2100
+ self.begin_index = begin_index
2101
+ self.end_index = end_index
2102
+ self.stride = stride
2103
+
2104
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2105
+ return visitor.visit_slice_expr(self)
2106
+
2107
+
2108
+ class CastExpr(Expression):
2109
+ """Cast expression cast(type, expr)."""
2110
+
2111
+ __slots__ = ("expr", "type")
2112
+
2113
+ __match_args__ = ("expr", "type")
2114
+
2115
+ expr: Expression
2116
+ type: mypy.types.Type
2117
+
2118
+ def __init__(self, expr: Expression, typ: mypy.types.Type) -> None:
2119
+ super().__init__()
2120
+ self.expr = expr
2121
+ self.type = typ
2122
+
2123
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2124
+ return visitor.visit_cast_expr(self)
2125
+
2126
+
2127
+ class AssertTypeExpr(Expression):
2128
+ """Represents a typing.assert_type(expr, type) call."""
2129
+
2130
+ __slots__ = ("expr", "type")
2131
+
2132
+ __match_args__ = ("expr", "type")
2133
+
2134
+ expr: Expression
2135
+ type: mypy.types.Type
2136
+
2137
+ def __init__(self, expr: Expression, typ: mypy.types.Type) -> None:
2138
+ super().__init__()
2139
+ self.expr = expr
2140
+ self.type = typ
2141
+
2142
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2143
+ return visitor.visit_assert_type_expr(self)
2144
+
2145
+
2146
+ class RevealExpr(Expression):
2147
+ """Reveal type expression reveal_type(expr) or reveal_locals() expression."""
2148
+
2149
+ __slots__ = ("expr", "kind", "local_nodes", "is_imported")
2150
+
2151
+ __match_args__ = ("expr", "kind", "local_nodes", "is_imported")
2152
+
2153
+ expr: Expression | None
2154
+ kind: int
2155
+ local_nodes: list[Var] | None
2156
+
2157
+ def __init__(
2158
+ self,
2159
+ kind: int,
2160
+ expr: Expression | None = None,
2161
+ local_nodes: list[Var] | None = None,
2162
+ is_imported: bool = False,
2163
+ ) -> None:
2164
+ super().__init__()
2165
+ self.expr = expr
2166
+ self.kind = kind
2167
+ self.local_nodes = local_nodes
2168
+ self.is_imported = is_imported
2169
+
2170
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2171
+ return visitor.visit_reveal_expr(self)
2172
+
2173
+
2174
+ class SuperExpr(Expression):
2175
+ """Expression super().name"""
2176
+
2177
+ __slots__ = ("name", "info", "call")
2178
+
2179
+ __match_args__ = ("name", "call", "info")
2180
+
2181
+ name: str
2182
+ info: TypeInfo | None # Type that contains this super expression
2183
+ call: CallExpr # The expression super(...)
2184
+
2185
+ def __init__(self, name: str, call: CallExpr) -> None:
2186
+ super().__init__()
2187
+ self.name = name
2188
+ self.call = call
2189
+ self.info = None
2190
+
2191
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2192
+ return visitor.visit_super_expr(self)
2193
+
2194
+
2195
+ class LambdaExpr(FuncItem, Expression):
2196
+ """Lambda expression"""
2197
+
2198
+ __match_args__ = ("arguments", "arg_names", "arg_kinds", "body")
2199
+
2200
+ @property
2201
+ def name(self) -> str:
2202
+ return "<lambda>"
2203
+
2204
+ def expr(self) -> Expression:
2205
+ """Return the expression (the body) of the lambda."""
2206
+ ret = self.body.body[-1]
2207
+ assert isinstance(ret, ReturnStmt)
2208
+ expr = ret.expr
2209
+ assert expr is not None # lambda can't have empty body
2210
+ return expr
2211
+
2212
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2213
+ return visitor.visit_lambda_expr(self)
2214
+
2215
+ def is_dynamic(self) -> bool:
2216
+ return False
2217
+
2218
+
2219
+ class ListExpr(Expression):
2220
+ """List literal expression [...]."""
2221
+
2222
+ __slots__ = ("items",)
2223
+
2224
+ __match_args__ = ("items",)
2225
+
2226
+ items: list[Expression]
2227
+
2228
+ def __init__(self, items: list[Expression]) -> None:
2229
+ super().__init__()
2230
+ self.items = items
2231
+
2232
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2233
+ return visitor.visit_list_expr(self)
2234
+
2235
+
2236
+ class DictExpr(Expression):
2237
+ """Dictionary literal expression {key: value, ...}."""
2238
+
2239
+ __slots__ = ("items",)
2240
+
2241
+ __match_args__ = ("items",)
2242
+
2243
+ items: list[tuple[Expression | None, Expression]]
2244
+
2245
+ def __init__(self, items: list[tuple[Expression | None, Expression]]) -> None:
2246
+ super().__init__()
2247
+ self.items = items
2248
+
2249
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2250
+ return visitor.visit_dict_expr(self)
2251
+
2252
+
2253
+ class TupleExpr(Expression):
2254
+ """Tuple literal expression (..., ...)
2255
+
2256
+ Also lvalue sequences (..., ...) and [..., ...]"""
2257
+
2258
+ __slots__ = ("items",)
2259
+
2260
+ __match_args__ = ("items",)
2261
+
2262
+ items: list[Expression]
2263
+
2264
+ def __init__(self, items: list[Expression]) -> None:
2265
+ super().__init__()
2266
+ self.items = items
2267
+
2268
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2269
+ return visitor.visit_tuple_expr(self)
2270
+
2271
+
2272
+ class SetExpr(Expression):
2273
+ """Set literal expression {value, ...}."""
2274
+
2275
+ __slots__ = ("items",)
2276
+
2277
+ __match_args__ = ("items",)
2278
+
2279
+ items: list[Expression]
2280
+
2281
+ def __init__(self, items: list[Expression]) -> None:
2282
+ super().__init__()
2283
+ self.items = items
2284
+
2285
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2286
+ return visitor.visit_set_expr(self)
2287
+
2288
+
2289
+ class GeneratorExpr(Expression):
2290
+ """Generator expression ... for ... in ... [ for ... in ... ] [ if ... ]."""
2291
+
2292
+ __slots__ = ("left_expr", "sequences", "condlists", "is_async", "indices")
2293
+
2294
+ __match_args__ = ("left_expr", "indices", "sequences", "condlists")
2295
+
2296
+ left_expr: Expression
2297
+ sequences: list[Expression]
2298
+ condlists: list[list[Expression]]
2299
+ is_async: list[bool]
2300
+ indices: list[Lvalue]
2301
+
2302
+ def __init__(
2303
+ self,
2304
+ left_expr: Expression,
2305
+ indices: list[Lvalue],
2306
+ sequences: list[Expression],
2307
+ condlists: list[list[Expression]],
2308
+ is_async: list[bool],
2309
+ ) -> None:
2310
+ super().__init__()
2311
+ self.left_expr = left_expr
2312
+ self.sequences = sequences
2313
+ self.condlists = condlists
2314
+ self.indices = indices
2315
+ self.is_async = is_async
2316
+
2317
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2318
+ return visitor.visit_generator_expr(self)
2319
+
2320
+
2321
+ class ListComprehension(Expression):
2322
+ """List comprehension (e.g. [x + 1 for x in a])"""
2323
+
2324
+ __slots__ = ("generator",)
2325
+
2326
+ __match_args__ = ("generator",)
2327
+
2328
+ generator: GeneratorExpr
2329
+
2330
+ def __init__(self, generator: GeneratorExpr) -> None:
2331
+ super().__init__()
2332
+ self.generator = generator
2333
+
2334
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2335
+ return visitor.visit_list_comprehension(self)
2336
+
2337
+
2338
+ class SetComprehension(Expression):
2339
+ """Set comprehension (e.g. {x + 1 for x in a})"""
2340
+
2341
+ __slots__ = ("generator",)
2342
+
2343
+ __match_args__ = ("generator",)
2344
+
2345
+ generator: GeneratorExpr
2346
+
2347
+ def __init__(self, generator: GeneratorExpr) -> None:
2348
+ super().__init__()
2349
+ self.generator = generator
2350
+
2351
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2352
+ return visitor.visit_set_comprehension(self)
2353
+
2354
+
2355
+ class DictionaryComprehension(Expression):
2356
+ """Dictionary comprehension (e.g. {k: v for k, v in a}"""
2357
+
2358
+ __slots__ = ("key", "value", "sequences", "condlists", "is_async", "indices")
2359
+
2360
+ __match_args__ = ("key", "value", "indices", "sequences", "condlists")
2361
+
2362
+ key: Expression
2363
+ value: Expression
2364
+ sequences: list[Expression]
2365
+ condlists: list[list[Expression]]
2366
+ is_async: list[bool]
2367
+ indices: list[Lvalue]
2368
+
2369
+ def __init__(
2370
+ self,
2371
+ key: Expression,
2372
+ value: Expression,
2373
+ indices: list[Lvalue],
2374
+ sequences: list[Expression],
2375
+ condlists: list[list[Expression]],
2376
+ is_async: list[bool],
2377
+ ) -> None:
2378
+ super().__init__()
2379
+ self.key = key
2380
+ self.value = value
2381
+ self.sequences = sequences
2382
+ self.condlists = condlists
2383
+ self.indices = indices
2384
+ self.is_async = is_async
2385
+
2386
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2387
+ return visitor.visit_dictionary_comprehension(self)
2388
+
2389
+
2390
+ class ConditionalExpr(Expression):
2391
+ """Conditional expression (e.g. x if y else z)"""
2392
+
2393
+ __slots__ = ("cond", "if_expr", "else_expr")
2394
+
2395
+ __match_args__ = ("if_expr", "cond", "else_expr")
2396
+
2397
+ cond: Expression
2398
+ if_expr: Expression
2399
+ else_expr: Expression
2400
+
2401
+ def __init__(self, cond: Expression, if_expr: Expression, else_expr: Expression) -> None:
2402
+ super().__init__()
2403
+ self.cond = cond
2404
+ self.if_expr = if_expr
2405
+ self.else_expr = else_expr
2406
+
2407
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2408
+ return visitor.visit_conditional_expr(self)
2409
+
2410
+
2411
+ class TypeApplication(Expression):
2412
+ """Type application expr[type, ...]"""
2413
+
2414
+ __slots__ = ("expr", "types")
2415
+
2416
+ __match_args__ = ("expr", "types")
2417
+
2418
+ expr: Expression
2419
+ types: list[mypy.types.Type]
2420
+
2421
+ def __init__(self, expr: Expression, types: list[mypy.types.Type]) -> None:
2422
+ super().__init__()
2423
+ self.expr = expr
2424
+ self.types = types
2425
+
2426
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2427
+ return visitor.visit_type_application(self)
2428
+
2429
+
2430
+ # Variance of a type variable. For example, T in the definition of
2431
+ # List[T] is invariant, so List[int] is not a subtype of List[object],
2432
+ # and also List[object] is not a subtype of List[int].
2433
+ #
2434
+ # The T in Iterable[T] is covariant, so Iterable[int] is a subtype of
2435
+ # Iterable[object], but not vice versa.
2436
+ #
2437
+ # If T is contravariant in Foo[T], Foo[object] is a subtype of
2438
+ # Foo[int], but not vice versa.
2439
+ INVARIANT: Final = 0
2440
+ COVARIANT: Final = 1
2441
+ CONTRAVARIANT: Final = 2
2442
+
2443
+
2444
+ class TypeVarLikeExpr(SymbolNode, Expression):
2445
+ """Base class for TypeVarExpr, ParamSpecExpr and TypeVarTupleExpr.
2446
+
2447
+ Note that they are constructed by the semantic analyzer.
2448
+ """
2449
+
2450
+ __slots__ = ("_name", "_fullname", "upper_bound", "default", "variance")
2451
+
2452
+ _name: str
2453
+ _fullname: str
2454
+ # Upper bound: only subtypes of upper_bound are valid as values. By default
2455
+ # this is 'object', meaning no restriction.
2456
+ upper_bound: mypy.types.Type
2457
+ # Default: used to resolve the TypeVar if the default is not explicitly given.
2458
+ # By default this is 'AnyType(TypeOfAny.from_omitted_generics)'. See PEP 696.
2459
+ default: mypy.types.Type
2460
+ # Variance of the type variable. Invariant is the default.
2461
+ # TypeVar(..., covariant=True) defines a covariant type variable.
2462
+ # TypeVar(..., contravariant=True) defines a contravariant type
2463
+ # variable.
2464
+ variance: int
2465
+
2466
+ def __init__(
2467
+ self,
2468
+ name: str,
2469
+ fullname: str,
2470
+ upper_bound: mypy.types.Type,
2471
+ default: mypy.types.Type,
2472
+ variance: int = INVARIANT,
2473
+ ) -> None:
2474
+ super().__init__()
2475
+ self._name = name
2476
+ self._fullname = fullname
2477
+ self.upper_bound = upper_bound
2478
+ self.default = default
2479
+ self.variance = variance
2480
+
2481
+ @property
2482
+ def name(self) -> str:
2483
+ return self._name
2484
+
2485
+ @property
2486
+ def fullname(self) -> str:
2487
+ return self._fullname
2488
+
2489
+
2490
+ class TypeVarExpr(TypeVarLikeExpr):
2491
+ """Type variable expression TypeVar(...).
2492
+
2493
+ This is also used to represent type variables in symbol tables.
2494
+
2495
+ A type variable is not valid as a type unless bound in a TypeVarLikeScope.
2496
+ That happens within:
2497
+
2498
+ 1. a generic class that uses the type variable as a type argument or
2499
+ 2. a generic function that refers to the type variable in its signature.
2500
+ """
2501
+
2502
+ __slots__ = ("values",)
2503
+
2504
+ __match_args__ = ("name", "values", "upper_bound", "default")
2505
+
2506
+ # Value restriction: only types in the list are valid as values. If the
2507
+ # list is empty, there is no restriction.
2508
+ values: list[mypy.types.Type]
2509
+
2510
+ def __init__(
2511
+ self,
2512
+ name: str,
2513
+ fullname: str,
2514
+ values: list[mypy.types.Type],
2515
+ upper_bound: mypy.types.Type,
2516
+ default: mypy.types.Type,
2517
+ variance: int = INVARIANT,
2518
+ ) -> None:
2519
+ super().__init__(name, fullname, upper_bound, default, variance)
2520
+ self.values = values
2521
+
2522
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2523
+ return visitor.visit_type_var_expr(self)
2524
+
2525
+ def serialize(self) -> JsonDict:
2526
+ return {
2527
+ ".class": "TypeVarExpr",
2528
+ "name": self._name,
2529
+ "fullname": self._fullname,
2530
+ "values": [t.serialize() for t in self.values],
2531
+ "upper_bound": self.upper_bound.serialize(),
2532
+ "default": self.default.serialize(),
2533
+ "variance": self.variance,
2534
+ }
2535
+
2536
+ @classmethod
2537
+ def deserialize(cls, data: JsonDict) -> TypeVarExpr:
2538
+ assert data[".class"] == "TypeVarExpr"
2539
+ return TypeVarExpr(
2540
+ data["name"],
2541
+ data["fullname"],
2542
+ [mypy.types.deserialize_type(v) for v in data["values"]],
2543
+ mypy.types.deserialize_type(data["upper_bound"]),
2544
+ mypy.types.deserialize_type(data["default"]),
2545
+ data["variance"],
2546
+ )
2547
+
2548
+
2549
+ class ParamSpecExpr(TypeVarLikeExpr):
2550
+ __slots__ = ()
2551
+
2552
+ __match_args__ = ("name", "upper_bound", "default")
2553
+
2554
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2555
+ return visitor.visit_paramspec_expr(self)
2556
+
2557
+ def serialize(self) -> JsonDict:
2558
+ return {
2559
+ ".class": "ParamSpecExpr",
2560
+ "name": self._name,
2561
+ "fullname": self._fullname,
2562
+ "upper_bound": self.upper_bound.serialize(),
2563
+ "default": self.default.serialize(),
2564
+ "variance": self.variance,
2565
+ }
2566
+
2567
+ @classmethod
2568
+ def deserialize(cls, data: JsonDict) -> ParamSpecExpr:
2569
+ assert data[".class"] == "ParamSpecExpr"
2570
+ return ParamSpecExpr(
2571
+ data["name"],
2572
+ data["fullname"],
2573
+ mypy.types.deserialize_type(data["upper_bound"]),
2574
+ mypy.types.deserialize_type(data["default"]),
2575
+ data["variance"],
2576
+ )
2577
+
2578
+
2579
+ class TypeVarTupleExpr(TypeVarLikeExpr):
2580
+ """Type variable tuple expression TypeVarTuple(...)."""
2581
+
2582
+ __slots__ = "tuple_fallback"
2583
+
2584
+ tuple_fallback: mypy.types.Instance
2585
+
2586
+ __match_args__ = ("name", "upper_bound", "default")
2587
+
2588
+ def __init__(
2589
+ self,
2590
+ name: str,
2591
+ fullname: str,
2592
+ upper_bound: mypy.types.Type,
2593
+ tuple_fallback: mypy.types.Instance,
2594
+ default: mypy.types.Type,
2595
+ variance: int = INVARIANT,
2596
+ ) -> None:
2597
+ super().__init__(name, fullname, upper_bound, default, variance)
2598
+ self.tuple_fallback = tuple_fallback
2599
+
2600
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2601
+ return visitor.visit_type_var_tuple_expr(self)
2602
+
2603
+ def serialize(self) -> JsonDict:
2604
+ return {
2605
+ ".class": "TypeVarTupleExpr",
2606
+ "name": self._name,
2607
+ "fullname": self._fullname,
2608
+ "upper_bound": self.upper_bound.serialize(),
2609
+ "tuple_fallback": self.tuple_fallback.serialize(),
2610
+ "default": self.default.serialize(),
2611
+ "variance": self.variance,
2612
+ }
2613
+
2614
+ @classmethod
2615
+ def deserialize(cls, data: JsonDict) -> TypeVarTupleExpr:
2616
+ assert data[".class"] == "TypeVarTupleExpr"
2617
+ return TypeVarTupleExpr(
2618
+ data["name"],
2619
+ data["fullname"],
2620
+ mypy.types.deserialize_type(data["upper_bound"]),
2621
+ mypy.types.Instance.deserialize(data["tuple_fallback"]),
2622
+ mypy.types.deserialize_type(data["default"]),
2623
+ data["variance"],
2624
+ )
2625
+
2626
+
2627
+ class TypeAliasExpr(Expression):
2628
+ """Type alias expression (rvalue)."""
2629
+
2630
+ __slots__ = ("node",)
2631
+
2632
+ __match_args__ = ("node",)
2633
+
2634
+ node: TypeAlias
2635
+
2636
+ def __init__(self, node: TypeAlias) -> None:
2637
+ super().__init__()
2638
+ self.node = node
2639
+
2640
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2641
+ return visitor.visit_type_alias_expr(self)
2642
+
2643
+
2644
+ class NamedTupleExpr(Expression):
2645
+ """Named tuple expression namedtuple(...) or NamedTuple(...)."""
2646
+
2647
+ __slots__ = ("info", "is_typed")
2648
+
2649
+ __match_args__ = ("info",)
2650
+
2651
+ # The class representation of this named tuple (its tuple_type attribute contains
2652
+ # the tuple item types)
2653
+ info: TypeInfo
2654
+ is_typed: bool # whether this class was created with typing(_extensions).NamedTuple
2655
+
2656
+ def __init__(self, info: TypeInfo, is_typed: bool = False) -> None:
2657
+ super().__init__()
2658
+ self.info = info
2659
+ self.is_typed = is_typed
2660
+
2661
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2662
+ return visitor.visit_namedtuple_expr(self)
2663
+
2664
+
2665
+ class TypedDictExpr(Expression):
2666
+ """Typed dict expression TypedDict(...)."""
2667
+
2668
+ __slots__ = ("info",)
2669
+
2670
+ __match_args__ = ("info",)
2671
+
2672
+ # The class representation of this typed dict
2673
+ info: TypeInfo
2674
+
2675
+ def __init__(self, info: TypeInfo) -> None:
2676
+ super().__init__()
2677
+ self.info = info
2678
+
2679
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2680
+ return visitor.visit_typeddict_expr(self)
2681
+
2682
+
2683
+ class EnumCallExpr(Expression):
2684
+ """Named tuple expression Enum('name', 'val1 val2 ...')."""
2685
+
2686
+ __slots__ = ("info", "items", "values")
2687
+
2688
+ __match_args__ = ("info", "items", "values")
2689
+
2690
+ # The class representation of this enumerated type
2691
+ info: TypeInfo
2692
+ # The item names (for debugging)
2693
+ items: list[str]
2694
+ values: list[Expression | None]
2695
+
2696
+ def __init__(self, info: TypeInfo, items: list[str], values: list[Expression | None]) -> None:
2697
+ super().__init__()
2698
+ self.info = info
2699
+ self.items = items
2700
+ self.values = values
2701
+
2702
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2703
+ return visitor.visit_enum_call_expr(self)
2704
+
2705
+
2706
+ class PromoteExpr(Expression):
2707
+ """Ducktype class decorator expression _promote(...)."""
2708
+
2709
+ __slots__ = ("type",)
2710
+
2711
+ type: mypy.types.ProperType
2712
+
2713
+ def __init__(self, type: mypy.types.ProperType) -> None:
2714
+ super().__init__()
2715
+ self.type = type
2716
+
2717
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2718
+ return visitor.visit__promote_expr(self)
2719
+
2720
+
2721
+ class NewTypeExpr(Expression):
2722
+ """NewType expression NewType(...)."""
2723
+
2724
+ __slots__ = ("name", "old_type", "info")
2725
+
2726
+ __match_args__ = ("name", "old_type", "info")
2727
+
2728
+ name: str
2729
+ # The base type (the second argument to NewType)
2730
+ old_type: mypy.types.Type | None
2731
+ # The synthesized class representing the new type (inherits old_type)
2732
+ info: TypeInfo | None
2733
+
2734
+ def __init__(
2735
+ self, name: str, old_type: mypy.types.Type | None, line: int, column: int
2736
+ ) -> None:
2737
+ super().__init__(line=line, column=column)
2738
+ self.name = name
2739
+ self.old_type = old_type
2740
+ self.info = None
2741
+
2742
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2743
+ return visitor.visit_newtype_expr(self)
2744
+
2745
+
2746
+ class AwaitExpr(Expression):
2747
+ """Await expression (await ...)."""
2748
+
2749
+ __slots__ = ("expr",)
2750
+
2751
+ __match_args__ = ("expr",)
2752
+
2753
+ expr: Expression
2754
+
2755
+ def __init__(self, expr: Expression) -> None:
2756
+ super().__init__()
2757
+ self.expr = expr
2758
+
2759
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2760
+ return visitor.visit_await_expr(self)
2761
+
2762
+
2763
+ # Constants
2764
+
2765
+
2766
+ class TempNode(Expression):
2767
+ """Temporary dummy node used during type checking.
2768
+
2769
+ This node is not present in the original program; it is just an artifact
2770
+ of the type checker implementation. It only represents an opaque node with
2771
+ some fixed type.
2772
+ """
2773
+
2774
+ __slots__ = ("type", "no_rhs")
2775
+
2776
+ type: mypy.types.Type
2777
+ # Is this TempNode used to indicate absence of a right hand side in an annotated assignment?
2778
+ # (e.g. for 'x: int' the rvalue is TempNode(AnyType(TypeOfAny.special_form), no_rhs=True))
2779
+ no_rhs: bool
2780
+
2781
+ def __init__(
2782
+ self, typ: mypy.types.Type, no_rhs: bool = False, *, context: Context | None = None
2783
+ ) -> None:
2784
+ """Construct a dummy node; optionally borrow line/column from context object."""
2785
+ super().__init__()
2786
+ self.type = typ
2787
+ self.no_rhs = no_rhs
2788
+ if context is not None:
2789
+ self.line = context.line
2790
+ self.column = context.column
2791
+
2792
+ def __repr__(self) -> str:
2793
+ return "TempNode:%d(%s)" % (self.line, str(self.type))
2794
+
2795
+ def accept(self, visitor: ExpressionVisitor[T]) -> T:
2796
+ return visitor.visit_temp_node(self)
2797
+
2798
+
2799
+ # Special attributes not collected as protocol members by Python 3.12
2800
+ # See typing._SPECIAL_NAMES
2801
+ EXCLUDED_PROTOCOL_ATTRIBUTES: Final = frozenset(
2802
+ {
2803
+ "__abstractmethods__",
2804
+ "__annotations__",
2805
+ "__dict__",
2806
+ "__doc__",
2807
+ "__init__",
2808
+ "__module__",
2809
+ "__new__",
2810
+ "__slots__",
2811
+ "__subclasshook__",
2812
+ "__weakref__",
2813
+ "__class_getitem__", # Since Python 3.9
2814
+ }
2815
+ )
2816
+
2817
+
2818
+ class TypeInfo(SymbolNode):
2819
+ """The type structure of a single class.
2820
+
2821
+ Each TypeInfo corresponds one-to-one to a ClassDef, which
2822
+ represents the AST of the class.
2823
+
2824
+ In type-theory terms, this is a "type constructor", and if the
2825
+ class is generic then it will be a type constructor of higher kind.
2826
+ Where the class is used in an actual type, it's in the form of an
2827
+ Instance, which amounts to a type application of the tycon to
2828
+ the appropriate number of arguments.
2829
+ """
2830
+
2831
+ __slots__ = (
2832
+ "_fullname",
2833
+ "module_name",
2834
+ "defn",
2835
+ "mro",
2836
+ "_mro_refs",
2837
+ "bad_mro",
2838
+ "is_final",
2839
+ "declared_metaclass",
2840
+ "metaclass_type",
2841
+ "names",
2842
+ "is_abstract",
2843
+ "is_protocol",
2844
+ "runtime_protocol",
2845
+ "abstract_attributes",
2846
+ "deletable_attributes",
2847
+ "slots",
2848
+ "assuming",
2849
+ "assuming_proper",
2850
+ "inferring",
2851
+ "is_enum",
2852
+ "fallback_to_any",
2853
+ "meta_fallback_to_any",
2854
+ "type_vars",
2855
+ "has_param_spec_type",
2856
+ "bases",
2857
+ "_promote",
2858
+ "tuple_type",
2859
+ "special_alias",
2860
+ "is_named_tuple",
2861
+ "typeddict_type",
2862
+ "is_newtype",
2863
+ "is_intersection",
2864
+ "metadata",
2865
+ "alt_promote",
2866
+ "has_type_var_tuple_type",
2867
+ "type_var_tuple_prefix",
2868
+ "type_var_tuple_suffix",
2869
+ "self_type",
2870
+ "dataclass_transform_spec",
2871
+ "is_type_check_only",
2872
+ )
2873
+
2874
+ _fullname: str # Fully qualified name
2875
+ # Fully qualified name for the module this type was defined in. This
2876
+ # information is also in the fullname, but is harder to extract in the
2877
+ # case of nested class definitions.
2878
+ module_name: str
2879
+ defn: ClassDef # Corresponding ClassDef
2880
+ # Method Resolution Order: the order of looking up attributes. The first
2881
+ # value always to refers to this class.
2882
+ mro: list[TypeInfo]
2883
+ # Used to stash the names of the mro classes temporarily between
2884
+ # deserialization and fixup. See deserialize() for why.
2885
+ _mro_refs: list[str] | None
2886
+ bad_mro: bool # Could not construct full MRO
2887
+ is_final: bool
2888
+
2889
+ declared_metaclass: mypy.types.Instance | None
2890
+ metaclass_type: mypy.types.Instance | None
2891
+
2892
+ names: SymbolTable # Names defined directly in this type
2893
+ is_abstract: bool # Does the class have any abstract attributes?
2894
+ is_protocol: bool # Is this a protocol class?
2895
+ runtime_protocol: bool # Does this protocol support isinstance checks?
2896
+ # List of names of abstract attributes together with their abstract status.
2897
+ # The abstract status must be one of `NOT_ABSTRACT`, `IS_ABSTRACT`, `IMPLICITLY_ABSTRACT`.
2898
+ abstract_attributes: list[tuple[str, int]]
2899
+ deletable_attributes: list[str] # Used by mypyc only
2900
+ # Does this type have concrete `__slots__` defined?
2901
+ # If class does not have `__slots__` defined then it is `None`,
2902
+ # if it has empty `__slots__` then it is an empty set.
2903
+ slots: set[str] | None
2904
+
2905
+ # The attributes 'assuming' and 'assuming_proper' represent structural subtype matrices.
2906
+ #
2907
+ # In languages with structural subtyping, one can keep a global subtype matrix like this:
2908
+ # . A B C .
2909
+ # A 1 0 0
2910
+ # B 1 1 1
2911
+ # C 1 0 1
2912
+ # .
2913
+ # where 1 indicates that the type in corresponding row is a subtype of the type
2914
+ # in corresponding column. This matrix typically starts filled with all 1's and
2915
+ # a typechecker tries to "disprove" every subtyping relation using atomic (or nominal) types.
2916
+ # However, we don't want to keep this huge global state. Instead, we keep the subtype
2917
+ # information in the form of list of pairs (subtype, supertype) shared by all Instances
2918
+ # with given supertype's TypeInfo. When we enter a subtype check we push a pair in this list
2919
+ # thus assuming that we started with 1 in corresponding matrix element. Such algorithm allows
2920
+ # to treat recursive and mutually recursive protocols and other kinds of complex situations.
2921
+ #
2922
+ # If concurrent/parallel type checking will be added in future,
2923
+ # then there should be one matrix per thread/process to avoid false negatives
2924
+ # during the type checking phase.
2925
+ assuming: list[tuple[mypy.types.Instance, mypy.types.Instance]]
2926
+ assuming_proper: list[tuple[mypy.types.Instance, mypy.types.Instance]]
2927
+ # Ditto for temporary 'inferring' stack of recursive constraint inference.
2928
+ # It contains Instances of protocol types that appeared as an argument to
2929
+ # constraints.infer_constraints(). We need 'inferring' to avoid infinite recursion for
2930
+ # recursive and mutually recursive protocols.
2931
+ #
2932
+ # We make 'assuming' and 'inferring' attributes here instead of passing they as kwargs,
2933
+ # since this would require to pass them in many dozens of calls. In particular,
2934
+ # there is a dependency infer_constraint -> is_subtype -> is_callable_subtype ->
2935
+ # -> infer_constraints.
2936
+ inferring: list[mypy.types.Instance]
2937
+ # 'inferring' and 'assuming' can't be made sets, since we need to use
2938
+ # is_same_type to correctly treat unions.
2939
+
2940
+ # Classes inheriting from Enum shadow their true members with a __getattr__, so we
2941
+ # have to treat them as a special case.
2942
+ is_enum: bool
2943
+ # If true, any unknown attributes should have type 'Any' instead
2944
+ # of generating a type error. This would be true if there is a
2945
+ # base class with type 'Any', but other use cases may be
2946
+ # possible. This is similar to having __getattr__ that returns Any
2947
+ # (and __setattr__), but without the __getattr__ method.
2948
+ fallback_to_any: bool
2949
+
2950
+ # Same as above but for cases where metaclass has type Any. This will suppress
2951
+ # all attribute errors only for *class object* access.
2952
+ meta_fallback_to_any: bool
2953
+
2954
+ # Information related to type annotations.
2955
+
2956
+ # Generic type variable names (full names)
2957
+ type_vars: list[str]
2958
+
2959
+ # Whether this class has a ParamSpec type variable
2960
+ has_param_spec_type: bool
2961
+
2962
+ # Direct base classes.
2963
+ bases: list[mypy.types.Instance]
2964
+
2965
+ # Another type which this type will be treated as a subtype of,
2966
+ # even though it's not a subclass in Python. The non-standard
2967
+ # `@_promote` decorator introduces this, and there are also
2968
+ # several builtin examples, in particular `int` -> `float`.
2969
+ _promote: list[mypy.types.ProperType]
2970
+
2971
+ # This is used for promoting native integer types such as 'i64' to
2972
+ # 'int'. (_promote is used for the other direction.) This only
2973
+ # supports one-step promotions (e.g., i64 -> int, not
2974
+ # i64 -> int -> float, and this isn't used to promote in joins.
2975
+ #
2976
+ # This results in some unintuitive results, such as that even
2977
+ # though i64 is compatible with int and int is compatible with
2978
+ # float, i64 is *not* compatible with float.
2979
+ alt_promote: mypy.types.Instance | None
2980
+
2981
+ # Representation of a Tuple[...] base class, if the class has any
2982
+ # (e.g., for named tuples). If this is not None, the actual Type
2983
+ # object used for this class is not an Instance but a TupleType;
2984
+ # the corresponding Instance is set as the fallback type of the
2985
+ # tuple type.
2986
+ tuple_type: mypy.types.TupleType | None
2987
+
2988
+ # Is this a named tuple type?
2989
+ is_named_tuple: bool
2990
+
2991
+ # If this class is defined by the TypedDict type constructor,
2992
+ # then this is not None.
2993
+ typeddict_type: mypy.types.TypedDictType | None
2994
+
2995
+ # Is this a newtype type?
2996
+ is_newtype: bool
2997
+
2998
+ # Is this a synthesized intersection type?
2999
+ is_intersection: bool
3000
+
3001
+ # This is a dictionary that will be serialized and un-serialized as is.
3002
+ # It is useful for plugins to add their data to save in the cache.
3003
+ metadata: dict[str, JsonDict]
3004
+
3005
+ # Store type alias representing this type (for named tuples and TypedDicts).
3006
+ # Although definitions of these types are stored in symbol tables as TypeInfo,
3007
+ # when a type analyzer will find them, it should construct a TupleType, or
3008
+ # a TypedDict type. However, we can't use the plain types, since if the definition
3009
+ # is recursive, this will create an actual recursive structure of types (i.e. as
3010
+ # internal Python objects) causing infinite recursions everywhere during type checking.
3011
+ # To overcome this, we create a TypeAlias node, that will point to these types.
3012
+ # We store this node in the `special_alias` attribute, because it must be the same node
3013
+ # in case we are doing multiple semantic analysis passes.
3014
+ special_alias: TypeAlias | None
3015
+
3016
+ # Shared type variable for typing.Self in this class (if used, otherwise None).
3017
+ self_type: mypy.types.TypeVarType | None
3018
+
3019
+ # Added if the corresponding class is directly decorated with `typing.dataclass_transform`
3020
+ dataclass_transform_spec: DataclassTransformSpec | None
3021
+
3022
+ # Is set to `True` when class is decorated with `@typing.type_check_only`
3023
+ is_type_check_only: bool
3024
+
3025
+ FLAGS: Final = [
3026
+ "is_abstract",
3027
+ "is_enum",
3028
+ "fallback_to_any",
3029
+ "meta_fallback_to_any",
3030
+ "is_named_tuple",
3031
+ "is_newtype",
3032
+ "is_protocol",
3033
+ "runtime_protocol",
3034
+ "is_final",
3035
+ "is_intersection",
3036
+ ]
3037
+
3038
+ def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None:
3039
+ """Initialize a TypeInfo."""
3040
+ super().__init__()
3041
+ self._fullname = defn.fullname
3042
+ self.names = names
3043
+ self.defn = defn
3044
+ self.module_name = module_name
3045
+ self.type_vars = []
3046
+ self.has_param_spec_type = False
3047
+ self.has_type_var_tuple_type = False
3048
+ self.bases = []
3049
+ self.mro = []
3050
+ self._mro_refs = None
3051
+ self.bad_mro = False
3052
+ self.declared_metaclass = None
3053
+ self.metaclass_type = None
3054
+ self.is_abstract = False
3055
+ self.abstract_attributes = []
3056
+ self.deletable_attributes = []
3057
+ self.slots = None
3058
+ self.assuming = []
3059
+ self.assuming_proper = []
3060
+ self.inferring = []
3061
+ self.is_protocol = False
3062
+ self.runtime_protocol = False
3063
+ self.type_var_tuple_prefix: int | None = None
3064
+ self.type_var_tuple_suffix: int | None = None
3065
+ self.add_type_vars()
3066
+ self.is_final = False
3067
+ self.is_enum = False
3068
+ self.fallback_to_any = False
3069
+ self.meta_fallback_to_any = False
3070
+ self._promote = []
3071
+ self.alt_promote = None
3072
+ self.tuple_type = None
3073
+ self.special_alias = None
3074
+ self.is_named_tuple = False
3075
+ self.typeddict_type = None
3076
+ self.is_newtype = False
3077
+ self.is_intersection = False
3078
+ self.metadata = {}
3079
+ self.self_type = None
3080
+ self.dataclass_transform_spec = None
3081
+ self.is_type_check_only = False
3082
+
3083
+ def add_type_vars(self) -> None:
3084
+ self.has_type_var_tuple_type = False
3085
+ if self.defn.type_vars:
3086
+ for i, vd in enumerate(self.defn.type_vars):
3087
+ if isinstance(vd, mypy.types.ParamSpecType):
3088
+ self.has_param_spec_type = True
3089
+ if isinstance(vd, mypy.types.TypeVarTupleType):
3090
+ assert not self.has_type_var_tuple_type
3091
+ self.has_type_var_tuple_type = True
3092
+ self.type_var_tuple_prefix = i
3093
+ self.type_var_tuple_suffix = len(self.defn.type_vars) - i - 1
3094
+ self.type_vars.append(vd.name)
3095
+ assert not (
3096
+ self.has_param_spec_type and self.has_type_var_tuple_type
3097
+ ), "Mixing type var tuples and param specs not supported yet"
3098
+
3099
+ @property
3100
+ def name(self) -> str:
3101
+ """Short name."""
3102
+ return self.defn.name
3103
+
3104
+ @property
3105
+ def fullname(self) -> str:
3106
+ return self._fullname
3107
+
3108
+ def is_generic(self) -> bool:
3109
+ """Is the type generic (i.e. does it have type variables)?"""
3110
+ return len(self.type_vars) > 0
3111
+
3112
+ def get(self, name: str) -> SymbolTableNode | None:
3113
+ for cls in self.mro:
3114
+ n = cls.names.get(name)
3115
+ if n:
3116
+ return n
3117
+ return None
3118
+
3119
+ def get_containing_type_info(self, name: str) -> TypeInfo | None:
3120
+ for cls in self.mro:
3121
+ if name in cls.names:
3122
+ return cls
3123
+ return None
3124
+
3125
+ @property
3126
+ def protocol_members(self) -> list[str]:
3127
+ # Protocol members are names of all attributes/methods defined in a protocol
3128
+ # and in all its supertypes (except for 'object').
3129
+ members: set[str] = set()
3130
+ assert self.mro, "This property can be only accessed after MRO is (re-)calculated"
3131
+ for base in self.mro[:-1]: # we skip "object" since everyone implements it
3132
+ if base.is_protocol:
3133
+ for name, node in base.names.items():
3134
+ if isinstance(node.node, (TypeAlias, TypeVarExpr, MypyFile)):
3135
+ # These are auxiliary definitions (and type aliases are prohibited).
3136
+ continue
3137
+ if name in EXCLUDED_PROTOCOL_ATTRIBUTES:
3138
+ continue
3139
+ members.add(name)
3140
+ return sorted(members)
3141
+
3142
+ def __getitem__(self, name: str) -> SymbolTableNode:
3143
+ n = self.get(name)
3144
+ if n:
3145
+ return n
3146
+ else:
3147
+ raise KeyError(name)
3148
+
3149
+ def __repr__(self) -> str:
3150
+ return f"<TypeInfo {self.fullname}>"
3151
+
3152
+ def __bool__(self) -> bool:
3153
+ # We defined this here instead of just overriding it in
3154
+ # FakeInfo so that mypyc can generate a direct call instead of
3155
+ # using the generic bool handling.
3156
+ return not isinstance(self, FakeInfo)
3157
+
3158
+ def has_readable_member(self, name: str) -> bool:
3159
+ return self.get(name) is not None
3160
+
3161
+ def get_method(self, name: str) -> FuncBase | Decorator | None:
3162
+ for cls in self.mro:
3163
+ if name in cls.names:
3164
+ node = cls.names[name].node
3165
+ if isinstance(node, FuncBase):
3166
+ return node
3167
+ elif isinstance(node, Decorator): # Two `if`s make `mypyc` happy
3168
+ return node
3169
+ else:
3170
+ return None
3171
+ return None
3172
+
3173
+ def calculate_metaclass_type(self) -> mypy.types.Instance | None:
3174
+ declared = self.declared_metaclass
3175
+ if declared is not None and not declared.type.has_base("builtins.type"):
3176
+ return declared
3177
+ if self._fullname == "builtins.type":
3178
+ return mypy.types.Instance(self, [])
3179
+ candidates = [
3180
+ s.declared_metaclass
3181
+ for s in self.mro
3182
+ if s.declared_metaclass is not None and s.declared_metaclass.type is not None
3183
+ ]
3184
+ for c in candidates:
3185
+ if all(other.type in c.type.mro for other in candidates):
3186
+ return c
3187
+ return None
3188
+
3189
+ def is_metaclass(self) -> bool:
3190
+ return (
3191
+ self.has_base("builtins.type")
3192
+ or self.fullname == "abc.ABCMeta"
3193
+ or self.fallback_to_any
3194
+ )
3195
+
3196
+ def has_base(self, fullname: str) -> bool:
3197
+ """Return True if type has a base type with the specified name.
3198
+
3199
+ This can be either via extension or via implementation.
3200
+ """
3201
+ for cls in self.mro:
3202
+ if cls.fullname == fullname:
3203
+ return True
3204
+ return False
3205
+
3206
+ def direct_base_classes(self) -> list[TypeInfo]:
3207
+ """Return a direct base classes.
3208
+
3209
+ Omit base classes of other base classes.
3210
+ """
3211
+ return [base.type for base in self.bases]
3212
+
3213
+ def update_tuple_type(self, typ: mypy.types.TupleType) -> None:
3214
+ """Update tuple_type and special_alias as needed."""
3215
+ self.tuple_type = typ
3216
+ alias = TypeAlias.from_tuple_type(self)
3217
+ if not self.special_alias:
3218
+ self.special_alias = alias
3219
+ else:
3220
+ self.special_alias.target = alias.target
3221
+
3222
+ def update_typeddict_type(self, typ: mypy.types.TypedDictType) -> None:
3223
+ """Update typeddict_type and special_alias as needed."""
3224
+ self.typeddict_type = typ
3225
+ alias = TypeAlias.from_typeddict_type(self)
3226
+ if not self.special_alias:
3227
+ self.special_alias = alias
3228
+ else:
3229
+ self.special_alias.target = alias.target
3230
+
3231
+ def __str__(self) -> str:
3232
+ """Return a string representation of the type.
3233
+
3234
+ This includes the most important information about the type.
3235
+ """
3236
+ options = Options()
3237
+ return self.dump(
3238
+ str_conv=mypy.strconv.StrConv(options=options),
3239
+ type_str_conv=mypy.types.TypeStrVisitor(options=options),
3240
+ )
3241
+
3242
+ def dump(
3243
+ self, str_conv: mypy.strconv.StrConv, type_str_conv: mypy.types.TypeStrVisitor
3244
+ ) -> str:
3245
+ """Return a string dump of the contents of the TypeInfo."""
3246
+
3247
+ base: str = ""
3248
+
3249
+ def type_str(typ: mypy.types.Type) -> str:
3250
+ return typ.accept(type_str_conv)
3251
+
3252
+ head = "TypeInfo" + str_conv.format_id(self)
3253
+ if self.bases:
3254
+ base = f"Bases({', '.join(type_str(base) for base in self.bases)})"
3255
+ mro = "Mro({})".format(
3256
+ ", ".join(item.fullname + str_conv.format_id(item) for item in self.mro)
3257
+ )
3258
+ names = []
3259
+ for name in sorted(self.names):
3260
+ description = name + str_conv.format_id(self.names[name].node)
3261
+ node = self.names[name].node
3262
+ if isinstance(node, Var) and node.type:
3263
+ description += f" ({type_str(node.type)})"
3264
+ names.append(description)
3265
+ items = [f"Name({self.fullname})", base, mro, ("Names", names)]
3266
+ if self.declared_metaclass:
3267
+ items.append(f"DeclaredMetaclass({type_str(self.declared_metaclass)})")
3268
+ if self.metaclass_type:
3269
+ items.append(f"MetaclassType({type_str(self.metaclass_type)})")
3270
+ return mypy.strconv.dump_tagged(items, head, str_conv=str_conv)
3271
+
3272
+ def serialize(self) -> JsonDict:
3273
+ # NOTE: This is where all ClassDefs originate, so there shouldn't be duplicates.
3274
+ data = {
3275
+ ".class": "TypeInfo",
3276
+ "module_name": self.module_name,
3277
+ "fullname": self.fullname,
3278
+ "names": self.names.serialize(self.fullname),
3279
+ "defn": self.defn.serialize(),
3280
+ "abstract_attributes": self.abstract_attributes,
3281
+ "type_vars": self.type_vars,
3282
+ "has_param_spec_type": self.has_param_spec_type,
3283
+ "bases": [b.serialize() for b in self.bases],
3284
+ "mro": [c.fullname for c in self.mro],
3285
+ "_promote": [p.serialize() for p in self._promote],
3286
+ "alt_promote": None if self.alt_promote is None else self.alt_promote.serialize(),
3287
+ "declared_metaclass": (
3288
+ None if self.declared_metaclass is None else self.declared_metaclass.serialize()
3289
+ ),
3290
+ "metaclass_type": (
3291
+ None if self.metaclass_type is None else self.metaclass_type.serialize()
3292
+ ),
3293
+ "tuple_type": None if self.tuple_type is None else self.tuple_type.serialize(),
3294
+ "typeddict_type": (
3295
+ None if self.typeddict_type is None else self.typeddict_type.serialize()
3296
+ ),
3297
+ "flags": get_flags(self, TypeInfo.FLAGS),
3298
+ "metadata": self.metadata,
3299
+ "slots": sorted(self.slots) if self.slots is not None else None,
3300
+ "deletable_attributes": self.deletable_attributes,
3301
+ "self_type": self.self_type.serialize() if self.self_type is not None else None,
3302
+ "dataclass_transform_spec": (
3303
+ self.dataclass_transform_spec.serialize()
3304
+ if self.dataclass_transform_spec is not None
3305
+ else None
3306
+ ),
3307
+ }
3308
+ return data
3309
+
3310
+ @classmethod
3311
+ def deserialize(cls, data: JsonDict) -> TypeInfo:
3312
+ names = SymbolTable.deserialize(data["names"])
3313
+ defn = ClassDef.deserialize(data["defn"])
3314
+ module_name = data["module_name"]
3315
+ ti = TypeInfo(names, defn, module_name)
3316
+ ti._fullname = data["fullname"]
3317
+ # TODO: Is there a reason to reconstruct ti.subtypes?
3318
+ ti.abstract_attributes = [(attr[0], attr[1]) for attr in data["abstract_attributes"]]
3319
+ ti.type_vars = data["type_vars"]
3320
+ ti.has_param_spec_type = data["has_param_spec_type"]
3321
+ ti.bases = [mypy.types.Instance.deserialize(b) for b in data["bases"]]
3322
+ _promote = []
3323
+ for p in data["_promote"]:
3324
+ t = mypy.types.deserialize_type(p)
3325
+ assert isinstance(t, mypy.types.ProperType)
3326
+ _promote.append(t)
3327
+ ti._promote = _promote
3328
+ ti.alt_promote = (
3329
+ None
3330
+ if data["alt_promote"] is None
3331
+ else mypy.types.Instance.deserialize(data["alt_promote"])
3332
+ )
3333
+ ti.declared_metaclass = (
3334
+ None
3335
+ if data["declared_metaclass"] is None
3336
+ else mypy.types.Instance.deserialize(data["declared_metaclass"])
3337
+ )
3338
+ ti.metaclass_type = (
3339
+ None
3340
+ if data["metaclass_type"] is None
3341
+ else mypy.types.Instance.deserialize(data["metaclass_type"])
3342
+ )
3343
+ # NOTE: ti.mro will be set in the fixup phase based on these
3344
+ # names. The reason we need to store the mro instead of just
3345
+ # recomputing it from base classes has to do with a subtle
3346
+ # point about fine-grained incremental: the cache files might
3347
+ # not be loaded until after a class in the mro has changed its
3348
+ # bases, which causes the mro to change. If we recomputed our
3349
+ # mro, we would compute the *new* mro, which leaves us with no
3350
+ # way to detect that the mro has changed! Thus we need to make
3351
+ # sure to load the original mro so that once the class is
3352
+ # rechecked, it can tell that the mro has changed.
3353
+ ti._mro_refs = data["mro"]
3354
+ ti.tuple_type = (
3355
+ None
3356
+ if data["tuple_type"] is None
3357
+ else mypy.types.TupleType.deserialize(data["tuple_type"])
3358
+ )
3359
+ ti.typeddict_type = (
3360
+ None
3361
+ if data["typeddict_type"] is None
3362
+ else mypy.types.TypedDictType.deserialize(data["typeddict_type"])
3363
+ )
3364
+ ti.metadata = data["metadata"]
3365
+ ti.slots = set(data["slots"]) if data["slots"] is not None else None
3366
+ ti.deletable_attributes = data["deletable_attributes"]
3367
+ set_flags(ti, data["flags"])
3368
+ st = data["self_type"]
3369
+ ti.self_type = mypy.types.TypeVarType.deserialize(st) if st is not None else None
3370
+ if data.get("dataclass_transform_spec") is not None:
3371
+ ti.dataclass_transform_spec = DataclassTransformSpec.deserialize(
3372
+ data["dataclass_transform_spec"]
3373
+ )
3374
+ return ti
3375
+
3376
+
3377
+ class FakeInfo(TypeInfo):
3378
+ __slots__ = ("msg",)
3379
+
3380
+ # types.py defines a single instance of this class, called types.NOT_READY.
3381
+ # This instance is used as a temporary placeholder in the process of de-serialization
3382
+ # of 'Instance' types. The de-serialization happens in two steps: In the first step,
3383
+ # Instance.type is set to NOT_READY. In the second step (in fixup.py) it is replaced by
3384
+ # an actual TypeInfo. If you see the assertion error below, then most probably something
3385
+ # went wrong during the second step and an 'Instance' that raised this error was not fixed.
3386
+ # Note:
3387
+ # 'None' is not used as a dummy value for two reasons:
3388
+ # 1. This will require around 80-100 asserts to make 'mypy --strict-optional mypy'
3389
+ # pass cleanly.
3390
+ # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value
3391
+ # is from, whereas a 'None' value could come from anywhere.
3392
+ #
3393
+ # Additionally, this serves as a more general-purpose placeholder
3394
+ # for missing TypeInfos in a number of places where the excuses
3395
+ # for not being Optional are a little weaker.
3396
+ #
3397
+ # TypeInfo defines a __bool__ method that returns False for FakeInfo
3398
+ # so that it can be conveniently tested against in the same way that it
3399
+ # would be if things were properly optional.
3400
+ def __init__(self, msg: str) -> None:
3401
+ self.msg = msg
3402
+
3403
+ def __getattribute__(self, attr: str) -> type:
3404
+ # Handle __class__ so that isinstance still works...
3405
+ if attr == "__class__":
3406
+ return object.__getattribute__(self, attr) # type: ignore[no-any-return]
3407
+ raise AssertionError(object.__getattribute__(self, "msg"))
3408
+
3409
+
3410
+ VAR_NO_INFO: Final[TypeInfo] = FakeInfo("Var is lacking info")
3411
+ CLASSDEF_NO_INFO: Final[TypeInfo] = FakeInfo("ClassDef is lacking info")
3412
+ FUNC_NO_INFO: Final[TypeInfo] = FakeInfo("FuncBase for non-methods lack info")
3413
+
3414
+
3415
+ class TypeAlias(SymbolNode):
3416
+ """
3417
+ A symbol node representing a type alias.
3418
+
3419
+ Type alias is a static concept, in contrast to variables with types
3420
+ like Type[...]. Namely:
3421
+ * type aliases
3422
+ - can be used in type context (annotations)
3423
+ - cannot be re-assigned
3424
+ * variables with type Type[...]
3425
+ - cannot be used in type context
3426
+ - but can be re-assigned
3427
+
3428
+ An alias can be defined only by an assignment to a name (not any other lvalues).
3429
+
3430
+ Such assignment defines an alias by default. To define a variable,
3431
+ an explicit Type[...] annotation is required. As an exception,
3432
+ at non-global scope non-subscripted rvalue creates a variable even without
3433
+ an annotation. This exception exists to accommodate the common use case of
3434
+ class-valued attributes. See SemanticAnalyzerPass2.check_and_set_up_type_alias
3435
+ for details.
3436
+
3437
+ Aliases can be generic. We use bound type variables for generic aliases, similar
3438
+ to classes. Essentially, type aliases work as macros that expand textually.
3439
+ The definition and expansion rules are following:
3440
+
3441
+ 1. An alias targeting a generic class without explicit variables act as
3442
+ the given class (this doesn't apply to TypedDict, Tuple and Callable, which
3443
+ are not proper classes but special type constructors):
3444
+
3445
+ A = List
3446
+ AA = List[Any]
3447
+
3448
+ x: A # same as List[Any]
3449
+ x: A[int] # same as List[int]
3450
+
3451
+ x: AA # same as List[Any]
3452
+ x: AA[int] # Error!
3453
+
3454
+ C = Callable # Same as Callable[..., Any]
3455
+ T = Tuple # Same as Tuple[Any, ...]
3456
+
3457
+ 2. An alias using explicit type variables in its rvalue expects
3458
+ replacements (type arguments) for these variables. If missing, they
3459
+ are treated as Any, like for other generics:
3460
+
3461
+ B = List[Tuple[T, T]]
3462
+
3463
+ x: B # same as List[Tuple[Any, Any]]
3464
+ x: B[int] # same as List[Tuple[int, int]]
3465
+
3466
+ def f(x: B[T]) -> T: ... # without T, Any would be used here
3467
+
3468
+ 3. An alias can be defined using another aliases. In the definition
3469
+ rvalue the Any substitution doesn't happen for top level unsubscripted
3470
+ generic classes:
3471
+
3472
+ A = List
3473
+ B = A # here A is expanded to List, _not_ List[Any],
3474
+ # to match the Python runtime behaviour
3475
+ x: B[int] # same as List[int]
3476
+ C = List[A] # this expands to List[List[Any]]
3477
+
3478
+ AA = List[T]
3479
+ D = AA # here AA expands to List[Any]
3480
+ x: D[int] # Error!
3481
+
3482
+ Note: the fact that we support aliases like `A = List` means that the target
3483
+ type will be initially an instance type with wrong number of type arguments.
3484
+ Such instances are all fixed either during or after main semantic analysis passes.
3485
+ We therefore store the difference between `List` and `List[Any]` rvalues (targets)
3486
+ using the `no_args` flag. See also TypeAliasExpr.no_args.
3487
+
3488
+ Meaning of other fields:
3489
+
3490
+ target: The target type. For generic aliases contains bound type variables
3491
+ as nested types (currently TypeVar and ParamSpec are supported).
3492
+ _fullname: Qualified name of this type alias. This is used in particular
3493
+ to track fine grained dependencies from aliases.
3494
+ alias_tvars: Type variables used to define this alias.
3495
+ normalized: Used to distinguish between `A = List`, and `A = list`. Both
3496
+ are internally stored using `builtins.list` (because `typing.List` is
3497
+ itself an alias), while the second cannot be subscripted because of
3498
+ Python runtime limitation.
3499
+ line and column: Line and column on the original alias definition.
3500
+ eager: If True, immediately expand alias when referred to (useful for aliases
3501
+ within functions that can't be looked up from the symbol table)
3502
+ """
3503
+
3504
+ __slots__ = (
3505
+ "target",
3506
+ "_fullname",
3507
+ "alias_tvars",
3508
+ "no_args",
3509
+ "normalized",
3510
+ "_is_recursive",
3511
+ "eager",
3512
+ "tvar_tuple_index",
3513
+ )
3514
+
3515
+ __match_args__ = ("name", "target", "alias_tvars", "no_args")
3516
+
3517
+ def __init__(
3518
+ self,
3519
+ target: mypy.types.Type,
3520
+ fullname: str,
3521
+ line: int,
3522
+ column: int,
3523
+ *,
3524
+ alias_tvars: list[mypy.types.TypeVarLikeType] | None = None,
3525
+ no_args: bool = False,
3526
+ normalized: bool = False,
3527
+ eager: bool = False,
3528
+ ) -> None:
3529
+ self._fullname = fullname
3530
+ self.target = target
3531
+ if alias_tvars is None:
3532
+ alias_tvars = []
3533
+ self.alias_tvars = alias_tvars
3534
+ self.no_args = no_args
3535
+ self.normalized = normalized
3536
+ # This attribute is manipulated by TypeAliasType. If non-None,
3537
+ # it is the cached value.
3538
+ self._is_recursive: bool | None = None
3539
+ self.eager = eager
3540
+ self.tvar_tuple_index = None
3541
+ for i, t in enumerate(alias_tvars):
3542
+ if isinstance(t, mypy.types.TypeVarTupleType):
3543
+ self.tvar_tuple_index = i
3544
+ super().__init__(line, column)
3545
+
3546
+ @classmethod
3547
+ def from_tuple_type(cls, info: TypeInfo) -> TypeAlias:
3548
+ """Generate an alias to the tuple type described by a given TypeInfo.
3549
+
3550
+ NOTE: this doesn't set type alias type variables (for generic tuple types),
3551
+ they must be set by the caller (when fully analyzed).
3552
+ """
3553
+ assert info.tuple_type
3554
+ # TODO: is it possible to refactor this to set the correct type vars here?
3555
+ return TypeAlias(
3556
+ info.tuple_type.copy_modified(
3557
+ # Create an Instance similar to fill_typevars().
3558
+ fallback=mypy.types.Instance(
3559
+ info, mypy.types.type_vars_as_args(info.defn.type_vars)
3560
+ )
3561
+ ),
3562
+ info.fullname,
3563
+ info.line,
3564
+ info.column,
3565
+ )
3566
+
3567
+ @classmethod
3568
+ def from_typeddict_type(cls, info: TypeInfo) -> TypeAlias:
3569
+ """Generate an alias to the TypedDict type described by a given TypeInfo.
3570
+
3571
+ NOTE: this doesn't set type alias type variables (for generic TypedDicts),
3572
+ they must be set by the caller (when fully analyzed).
3573
+ """
3574
+ assert info.typeddict_type
3575
+ # TODO: is it possible to refactor this to set the correct type vars here?
3576
+ return TypeAlias(
3577
+ info.typeddict_type.copy_modified(
3578
+ # Create an Instance similar to fill_typevars().
3579
+ fallback=mypy.types.Instance(
3580
+ info, mypy.types.type_vars_as_args(info.defn.type_vars)
3581
+ )
3582
+ ),
3583
+ info.fullname,
3584
+ info.line,
3585
+ info.column,
3586
+ )
3587
+
3588
+ @property
3589
+ def name(self) -> str:
3590
+ return self._fullname.split(".")[-1]
3591
+
3592
+ @property
3593
+ def fullname(self) -> str:
3594
+ return self._fullname
3595
+
3596
+ @property
3597
+ def has_param_spec_type(self) -> bool:
3598
+ return any(isinstance(v, mypy.types.ParamSpecType) for v in self.alias_tvars)
3599
+
3600
+ def serialize(self) -> JsonDict:
3601
+ data: JsonDict = {
3602
+ ".class": "TypeAlias",
3603
+ "fullname": self._fullname,
3604
+ "target": self.target.serialize(),
3605
+ "alias_tvars": [v.serialize() for v in self.alias_tvars],
3606
+ "no_args": self.no_args,
3607
+ "normalized": self.normalized,
3608
+ "line": self.line,
3609
+ "column": self.column,
3610
+ }
3611
+ return data
3612
+
3613
+ def accept(self, visitor: NodeVisitor[T]) -> T:
3614
+ return visitor.visit_type_alias(self)
3615
+
3616
+ @classmethod
3617
+ def deserialize(cls, data: JsonDict) -> TypeAlias:
3618
+ assert data[".class"] == "TypeAlias"
3619
+ fullname = data["fullname"]
3620
+ alias_tvars = [mypy.types.deserialize_type(v) for v in data["alias_tvars"]]
3621
+ assert all(isinstance(t, mypy.types.TypeVarLikeType) for t in alias_tvars)
3622
+ target = mypy.types.deserialize_type(data["target"])
3623
+ no_args = data["no_args"]
3624
+ normalized = data["normalized"]
3625
+ line = data["line"]
3626
+ column = data["column"]
3627
+ return cls(
3628
+ target,
3629
+ fullname,
3630
+ line,
3631
+ column,
3632
+ alias_tvars=cast(List[mypy.types.TypeVarLikeType], alias_tvars),
3633
+ no_args=no_args,
3634
+ normalized=normalized,
3635
+ )
3636
+
3637
+
3638
+ class PlaceholderNode(SymbolNode):
3639
+ """Temporary symbol node that will later become a real SymbolNode.
3640
+
3641
+ These are only present during semantic analysis when using the new
3642
+ semantic analyzer. These are created if some essential dependencies
3643
+ of a definition are not yet complete.
3644
+
3645
+ A typical use is for names imported from a module which is still
3646
+ incomplete (within an import cycle):
3647
+
3648
+ from m import f # Initially may create PlaceholderNode
3649
+
3650
+ This is particularly important if the imported shadows a name from
3651
+ an enclosing scope or builtins:
3652
+
3653
+ from m import int # Placeholder avoids mixups with builtins.int
3654
+
3655
+ Another case where this is useful is when there is another definition
3656
+ or assignment:
3657
+
3658
+ from m import f
3659
+ def f() -> None: ...
3660
+
3661
+ In the above example, the presence of PlaceholderNode allows us to
3662
+ handle the second definition as a redefinition.
3663
+
3664
+ They are also used to create PlaceholderType instances for types
3665
+ that refer to incomplete types. Example:
3666
+
3667
+ class C(Sequence[C]): ...
3668
+
3669
+ We create a PlaceholderNode (with becomes_typeinfo=True) for C so
3670
+ that the type C in Sequence[C] can be bound.
3671
+
3672
+ Attributes:
3673
+
3674
+ fullname: Full name of the PlaceholderNode.
3675
+ node: AST node that contains the definition that caused this to
3676
+ be created. This is useful for tracking order of incomplete definitions
3677
+ and for debugging.
3678
+ becomes_typeinfo: If True, this refers something that could later
3679
+ become a TypeInfo. It can't be used with type variables, in
3680
+ particular, as this would cause issues with class type variable
3681
+ detection.
3682
+
3683
+ The long-term purpose of placeholder nodes/types is to evolve into
3684
+ something that can support general recursive types.
3685
+ """
3686
+
3687
+ __slots__ = ("_fullname", "node", "becomes_typeinfo")
3688
+
3689
+ def __init__(
3690
+ self, fullname: str, node: Node, line: int, *, becomes_typeinfo: bool = False
3691
+ ) -> None:
3692
+ self._fullname = fullname
3693
+ self.node = node
3694
+ self.becomes_typeinfo = becomes_typeinfo
3695
+ self.line = line
3696
+
3697
+ @property
3698
+ def name(self) -> str:
3699
+ return self._fullname.split(".")[-1]
3700
+
3701
+ @property
3702
+ def fullname(self) -> str:
3703
+ return self._fullname
3704
+
3705
+ def serialize(self) -> JsonDict:
3706
+ assert False, "PlaceholderNode can't be serialized"
3707
+
3708
+ def accept(self, visitor: NodeVisitor[T]) -> T:
3709
+ return visitor.visit_placeholder_node(self)
3710
+
3711
+
3712
+ class SymbolTableNode:
3713
+ """Description of a name binding in a symbol table.
3714
+
3715
+ These are only used as values in module (global), function (local)
3716
+ and class symbol tables (see SymbolTable). The name that is bound is
3717
+ the key in SymbolTable.
3718
+
3719
+ Symbol tables don't contain direct references to AST nodes primarily
3720
+ because there can be multiple symbol table references to a single
3721
+ AST node (due to imports and aliases), and different references can
3722
+ behave differently. This class describes the unique properties of
3723
+ each reference.
3724
+
3725
+ The most fundamental attribute is 'node', which is the AST node that
3726
+ the name refers to.
3727
+
3728
+ The kind is usually one of LDEF, GDEF or MDEF, depending on the scope
3729
+ of the definition. These three kinds can usually be used
3730
+ interchangeably and the difference between local, global and class
3731
+ scopes is mostly descriptive, with no semantic significance.
3732
+ However, some tools that consume mypy ASTs may care about these so
3733
+ they should be correct.
3734
+
3735
+ Attributes:
3736
+ node: AST node of definition. Among others, this can be one of
3737
+ FuncDef, Var, TypeInfo, TypeVarExpr or MypyFile -- or None
3738
+ for cross_ref that hasn't been fixed up yet.
3739
+ kind: Kind of node. Possible values:
3740
+ - LDEF: local definition
3741
+ - GDEF: global (module-level) definition
3742
+ - MDEF: class member definition
3743
+ - UNBOUND_IMPORTED: temporary kind for imported names (we
3744
+ don't know the final kind yet)
3745
+ module_public: If False, this name won't be imported via
3746
+ 'from <module> import *'. This has no effect on names within
3747
+ classes.
3748
+ module_hidden: If True, the name will be never exported (needed for
3749
+ stub files)
3750
+ cross_ref: For deserialized MypyFile nodes, the referenced module
3751
+ name; for other nodes, optionally the name of the referenced object.
3752
+ implicit: Was this defined by assignment to self attribute?
3753
+ plugin_generated: Was this symbol generated by a plugin?
3754
+ (And therefore needs to be removed in aststrip.)
3755
+ no_serialize: Do not serialize this node if True. This is used to prevent
3756
+ keys in the cache that refer to modules on which this file does not
3757
+ depend. Currently this can happen if there is a module not in build
3758
+ used e.g. like this:
3759
+ import a.b.c # type: ignore
3760
+ This will add a submodule symbol to parent module `a` symbol table,
3761
+ but `a.b` is _not_ added as its dependency. Therefore, we should
3762
+ not serialize these symbols as they may not be found during fixup
3763
+ phase, instead they will be re-added during subsequent patch parents
3764
+ phase.
3765
+ TODO: Refactor build.py to make dependency tracking more transparent
3766
+ and/or refactor look-up functions to not require parent patching.
3767
+
3768
+ NOTE: No other attributes should be added to this class unless they
3769
+ are shared by all node kinds.
3770
+ """
3771
+
3772
+ __slots__ = (
3773
+ "kind",
3774
+ "node",
3775
+ "module_public",
3776
+ "module_hidden",
3777
+ "cross_ref",
3778
+ "implicit",
3779
+ "plugin_generated",
3780
+ "no_serialize",
3781
+ )
3782
+
3783
+ def __init__(
3784
+ self,
3785
+ kind: int,
3786
+ node: SymbolNode | None,
3787
+ module_public: bool = True,
3788
+ implicit: bool = False,
3789
+ module_hidden: bool = False,
3790
+ *,
3791
+ plugin_generated: bool = False,
3792
+ no_serialize: bool = False,
3793
+ ) -> None:
3794
+ self.kind = kind
3795
+ self.node = node
3796
+ self.module_public = module_public
3797
+ self.implicit = implicit
3798
+ self.module_hidden = module_hidden
3799
+ self.cross_ref: str | None = None
3800
+ self.plugin_generated = plugin_generated
3801
+ self.no_serialize = no_serialize
3802
+
3803
+ @property
3804
+ def fullname(self) -> str | None:
3805
+ if self.node is not None:
3806
+ return self.node.fullname
3807
+ else:
3808
+ return None
3809
+
3810
+ @property
3811
+ def type(self) -> mypy.types.Type | None:
3812
+ node = self.node
3813
+ if isinstance(node, (Var, SYMBOL_FUNCBASE_TYPES)) and node.type is not None:
3814
+ return node.type
3815
+ elif isinstance(node, Decorator):
3816
+ return node.var.type
3817
+ else:
3818
+ return None
3819
+
3820
+ def copy(self) -> SymbolTableNode:
3821
+ new = SymbolTableNode(
3822
+ self.kind, self.node, self.module_public, self.implicit, self.module_hidden
3823
+ )
3824
+ new.cross_ref = self.cross_ref
3825
+ return new
3826
+
3827
+ def __str__(self) -> str:
3828
+ s = f"{node_kinds[self.kind]}/{short_type(self.node)}"
3829
+ if isinstance(self.node, SymbolNode):
3830
+ s += f" ({self.node.fullname})"
3831
+ # Include declared type of variables and functions.
3832
+ if self.type is not None:
3833
+ s += f" : {self.type}"
3834
+ if self.cross_ref:
3835
+ s += f" cross_ref:{self.cross_ref}"
3836
+ return s
3837
+
3838
+ def serialize(self, prefix: str, name: str) -> JsonDict:
3839
+ """Serialize a SymbolTableNode.
3840
+
3841
+ Args:
3842
+ prefix: full name of the containing module or class; or None
3843
+ name: name of this object relative to the containing object
3844
+ """
3845
+ data: JsonDict = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]}
3846
+ if self.module_hidden:
3847
+ data["module_hidden"] = True
3848
+ if not self.module_public:
3849
+ data["module_public"] = False
3850
+ if self.implicit:
3851
+ data["implicit"] = True
3852
+ if self.plugin_generated:
3853
+ data["plugin_generated"] = True
3854
+ if isinstance(self.node, MypyFile):
3855
+ data["cross_ref"] = self.node.fullname
3856
+ else:
3857
+ assert self.node is not None, f"{prefix}:{name}"
3858
+ if prefix is not None:
3859
+ fullname = self.node.fullname
3860
+ if (
3861
+ "." in fullname
3862
+ and fullname != prefix + "." + name
3863
+ and not (isinstance(self.node, Var) and self.node.from_module_getattr)
3864
+ ):
3865
+ assert not isinstance(
3866
+ self.node, PlaceholderNode
3867
+ ), f"Definition of {fullname} is unexpectedly incomplete"
3868
+ data["cross_ref"] = fullname
3869
+ return data
3870
+ data["node"] = self.node.serialize()
3871
+ return data
3872
+
3873
+ @classmethod
3874
+ def deserialize(cls, data: JsonDict) -> SymbolTableNode:
3875
+ assert data[".class"] == "SymbolTableNode"
3876
+ kind = inverse_node_kinds[data["kind"]]
3877
+ if "cross_ref" in data:
3878
+ # This will be fixed up later.
3879
+ stnode = SymbolTableNode(kind, None)
3880
+ stnode.cross_ref = data["cross_ref"]
3881
+ else:
3882
+ assert "node" in data, data
3883
+ node = SymbolNode.deserialize(data["node"])
3884
+ stnode = SymbolTableNode(kind, node)
3885
+ if "module_hidden" in data:
3886
+ stnode.module_hidden = data["module_hidden"]
3887
+ if "module_public" in data:
3888
+ stnode.module_public = data["module_public"]
3889
+ if "implicit" in data:
3890
+ stnode.implicit = data["implicit"]
3891
+ if "plugin_generated" in data:
3892
+ stnode.plugin_generated = data["plugin_generated"]
3893
+ return stnode
3894
+
3895
+
3896
+ class SymbolTable(Dict[str, SymbolTableNode]):
3897
+ """Static representation of a namespace dictionary.
3898
+
3899
+ This is used for module, class and function namespaces.
3900
+ """
3901
+
3902
+ __slots__ = ()
3903
+
3904
+ def __str__(self) -> str:
3905
+ a: list[str] = []
3906
+ for key, value in self.items():
3907
+ # Filter out the implicit import of builtins.
3908
+ if isinstance(value, SymbolTableNode):
3909
+ if (
3910
+ value.fullname != "builtins"
3911
+ and (value.fullname or "").split(".")[-1] not in implicit_module_attrs
3912
+ ):
3913
+ a.append(" " + str(key) + " : " + str(value))
3914
+ else:
3915
+ a.append(" <invalid item>")
3916
+ a = sorted(a)
3917
+ a.insert(0, "SymbolTable(")
3918
+ a[-1] += ")"
3919
+ return "\n".join(a)
3920
+
3921
+ def copy(self) -> SymbolTable:
3922
+ return SymbolTable([(key, node.copy()) for key, node in self.items()])
3923
+
3924
+ def serialize(self, fullname: str) -> JsonDict:
3925
+ data: JsonDict = {".class": "SymbolTable"}
3926
+ for key, value in self.items():
3927
+ # Skip __builtins__: it's a reference to the builtins
3928
+ # module that gets added to every module by
3929
+ # SemanticAnalyzerPass2.visit_file(), but it shouldn't be
3930
+ # accessed by users of the module.
3931
+ if key == "__builtins__" or value.no_serialize:
3932
+ continue
3933
+ data[key] = value.serialize(fullname, key)
3934
+ return data
3935
+
3936
+ @classmethod
3937
+ def deserialize(cls, data: JsonDict) -> SymbolTable:
3938
+ assert data[".class"] == "SymbolTable"
3939
+ st = SymbolTable()
3940
+ for key, value in data.items():
3941
+ if key != ".class":
3942
+ st[key] = SymbolTableNode.deserialize(value)
3943
+ return st
3944
+
3945
+
3946
+ class DataclassTransformSpec:
3947
+ """Specifies how a dataclass-like transform should be applied. The fields here are based on the
3948
+ parameters accepted by `typing.dataclass_transform`."""
3949
+
3950
+ __slots__ = (
3951
+ "eq_default",
3952
+ "order_default",
3953
+ "kw_only_default",
3954
+ "frozen_default",
3955
+ "field_specifiers",
3956
+ )
3957
+
3958
+ def __init__(
3959
+ self,
3960
+ *,
3961
+ eq_default: bool | None = None,
3962
+ order_default: bool | None = None,
3963
+ kw_only_default: bool | None = None,
3964
+ field_specifiers: tuple[str, ...] | None = None,
3965
+ # Specified outside of PEP 681:
3966
+ # frozen_default was added to CPythonin https://github.com/python/cpython/pull/99958 citing
3967
+ # positive discussion in typing-sig
3968
+ frozen_default: bool | None = None,
3969
+ ) -> None:
3970
+ self.eq_default = eq_default if eq_default is not None else True
3971
+ self.order_default = order_default if order_default is not None else False
3972
+ self.kw_only_default = kw_only_default if kw_only_default is not None else False
3973
+ self.frozen_default = frozen_default if frozen_default is not None else False
3974
+ self.field_specifiers = field_specifiers if field_specifiers is not None else ()
3975
+
3976
+ def serialize(self) -> JsonDict:
3977
+ return {
3978
+ "eq_default": self.eq_default,
3979
+ "order_default": self.order_default,
3980
+ "kw_only_default": self.kw_only_default,
3981
+ "frozen_default": self.frozen_default,
3982
+ "field_specifiers": list(self.field_specifiers),
3983
+ }
3984
+
3985
+ @classmethod
3986
+ def deserialize(cls, data: JsonDict) -> DataclassTransformSpec:
3987
+ return DataclassTransformSpec(
3988
+ eq_default=data.get("eq_default"),
3989
+ order_default=data.get("order_default"),
3990
+ kw_only_default=data.get("kw_only_default"),
3991
+ frozen_default=data.get("frozen_default"),
3992
+ field_specifiers=tuple(data.get("field_specifiers", [])),
3993
+ )
3994
+
3995
+
3996
+ def get_flags(node: Node, names: list[str]) -> list[str]:
3997
+ return [name for name in names if getattr(node, name)]
3998
+
3999
+
4000
+ def set_flags(node: Node, flags: list[str]) -> None:
4001
+ for name in flags:
4002
+ setattr(node, name, True)
4003
+
4004
+
4005
+ def get_member_expr_fullname(expr: MemberExpr) -> str | None:
4006
+ """Return the qualified name representation of a member expression.
4007
+
4008
+ Return a string of form foo.bar, foo.bar.baz, or similar, or None if the
4009
+ argument cannot be represented in this form.
4010
+ """
4011
+ initial: str | None = None
4012
+ if isinstance(expr.expr, NameExpr):
4013
+ initial = expr.expr.name
4014
+ elif isinstance(expr.expr, MemberExpr):
4015
+ initial = get_member_expr_fullname(expr.expr)
4016
+ else:
4017
+ return None
4018
+ return f"{initial}.{expr.name}"
4019
+
4020
+
4021
+ deserialize_map: Final = {
4022
+ key: obj.deserialize
4023
+ for key, obj in globals().items()
4024
+ if type(obj) is not FakeInfo
4025
+ and isinstance(obj, type)
4026
+ and issubclass(obj, SymbolNode)
4027
+ and obj is not SymbolNode
4028
+ }
4029
+
4030
+
4031
+ def check_arg_kinds(
4032
+ arg_kinds: list[ArgKind], nodes: list[T], fail: Callable[[str, T], None]
4033
+ ) -> None:
4034
+ is_var_arg = False
4035
+ is_kw_arg = False
4036
+ seen_named = False
4037
+ seen_opt = False
4038
+ for kind, node in zip(arg_kinds, nodes):
4039
+ if kind == ARG_POS:
4040
+ if is_var_arg or is_kw_arg or seen_named or seen_opt:
4041
+ fail(
4042
+ "Required positional args may not appear after default, named or var args",
4043
+ node,
4044
+ )
4045
+ break
4046
+ elif kind == ARG_OPT:
4047
+ if is_var_arg or is_kw_arg or seen_named:
4048
+ fail("Positional default args may not appear after named or var args", node)
4049
+ break
4050
+ seen_opt = True
4051
+ elif kind == ARG_STAR:
4052
+ if is_var_arg or is_kw_arg or seen_named:
4053
+ fail("Var args may not appear after named or var args", node)
4054
+ break
4055
+ is_var_arg = True
4056
+ elif kind == ARG_NAMED or kind == ARG_NAMED_OPT:
4057
+ seen_named = True
4058
+ if is_kw_arg:
4059
+ fail("A **kwargs argument must be the last argument", node)
4060
+ break
4061
+ elif kind == ARG_STAR2:
4062
+ if is_kw_arg:
4063
+ fail("You may only have one **kwargs argument", node)
4064
+ break
4065
+ is_kw_arg = True
4066
+
4067
+
4068
+ def check_arg_names(
4069
+ names: Sequence[str | None],
4070
+ nodes: list[T],
4071
+ fail: Callable[[str, T], None],
4072
+ description: str = "function definition",
4073
+ ) -> None:
4074
+ seen_names: set[str | None] = set()
4075
+ for name, node in zip(names, nodes):
4076
+ if name is not None and name in seen_names:
4077
+ fail(f'Duplicate argument "{name}" in {description}', node)
4078
+ break
4079
+ seen_names.add(name)
4080
+
4081
+
4082
+ def is_class_var(expr: NameExpr) -> bool:
4083
+ """Return whether the expression is ClassVar[...]"""
4084
+ if isinstance(expr.node, Var):
4085
+ return expr.node.is_classvar
4086
+ return False
4087
+
4088
+
4089
+ def is_final_node(node: SymbolNode | None) -> bool:
4090
+ """Check whether `node` corresponds to a final attribute."""
4091
+ return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final
4092
+
4093
+
4094
+ def local_definitions(
4095
+ names: SymbolTable, name_prefix: str, info: TypeInfo | None = None
4096
+ ) -> Iterator[Definition]:
4097
+ """Iterate over local definitions (not imported) in a symbol table.
4098
+
4099
+ Recursively iterate over class members and nested classes.
4100
+ """
4101
+ # TODO: What should the name be? Or maybe remove it?
4102
+ for name, symnode in names.items():
4103
+ shortname = name
4104
+ if "-redef" in name:
4105
+ # Restore original name from mangled name of multiply defined function
4106
+ shortname = name.split("-redef")[0]
4107
+ fullname = name_prefix + "." + shortname
4108
+ node = symnode.node
4109
+ if node and node.fullname == fullname:
4110
+ yield fullname, symnode, info
4111
+ if isinstance(node, TypeInfo):
4112
+ yield from local_definitions(node.names, fullname, node)